1 /* Copyright (C) 2009-2010, Martin Johansson <martin@fatbob.nu>
2 Copyright (C) 2005-2010, Thorvald Natvig <thorvald@natvig.com>
6 Redistribution and use in source and binary forms, with or without
7 modification, are permitted provided that the following conditions
10 - Redistributions of source code must retain the above copyright notice,
11 this list of conditions and the following disclaimer.
12 - Redistributions in binary form must reproduce the above copyright notice,
13 this list of conditions and the following disclaimer in the documentation
14 and/or other materials provided with the distribution.
15 - Neither the name of the Developers nor the names of its contributors may
16 be used to endorse or promote products derived from this software without
17 specific prior written permission.
19 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
23 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include <sys/socket.h>
43 #include "messagehandler.h"
47 #include "voicetarget.h"
49 extern char system_string[], version_string[];
51 static int Client_read(client_t *client);
52 static int Client_write(client_t *client);
53 static int Client_send_udp(client_t *client, uint8_t *data, int len);
54 void Client_free(client_t *client);
56 declare_list(clients);
57 static int clientcount; /* = 0 */
58 static int maxBandwidth;
60 int iCodecAlpha, iCodecBeta;
67 maxBandwidth = getIntConf(MAX_BANDWIDTH) / 8; /* From bits/s -> bytes/s */
75 int Client_getfds(struct pollfd *pollfds)
79 list_iterate(itr, &clients) {
81 c = list_get_entry(itr, client_t, node);
82 pollfds[i].fd = c->tcpfd;
83 pollfds[i].events = POLLIN | POLLHUP | POLLERR;
84 if (c->txsize > 0 || c->readBlockedOnWrite) /* Data waiting to be sent? */
85 pollfds[i].events |= POLLOUT;
94 int bwTop = maxBandwidth + maxBandwidth / 4;
95 list_iterate(itr, &clients) {
97 c = list_get_entry(itr, client_t, node);
98 Log_debug("Client %s BW available %d", c->username, c->availableBandwidth);
99 c->availableBandwidth += maxBandwidth;
100 if (c->availableBandwidth > bwTop)
101 c->availableBandwidth = bwTop;
103 if (Timer_isElapsed(&c->lastActivity, 1000000LL * INACTICITY_TIMEOUT)) {
104 /* No activity from client - assume it is lost and close. */
105 Log_info_client(c, "Timeout, closing.");
111 void Client_codec_add(client_t *client, int codec)
113 codec_t *cd = malloc(sizeof(codec_t));
115 Log_fatal("Out of memory");
116 init_list_entry(&cd->node);
118 list_add_tail(&cd->node, &client->codecs);
121 void Client_codec_free(client_t *client)
123 struct dlist *itr, *save;
124 list_iterate_safe(itr, save, &client->codecs) {
125 list_del(&list_get_entry(itr, codec_t, node)->node);
126 free(list_get_entry(itr, codec_t, node));
130 codec_t *Client_codec_iterate(client_t *client, codec_t **codec_itr)
132 codec_t *cd = *codec_itr;
134 if (list_empty(&client->codecs))
138 cd = list_get_entry(list_get_first(&client->codecs), codec_t, node);
140 if (list_get_next(&cd->node) == &client->codecs)
143 cd = list_get_entry(list_get_next(&cd->node), codec_t, node);
149 void recheckCodecVersions()
151 client_t *client_itr = NULL;
152 int max = 0, version, current_version;
154 struct dlist codec_list, *itr, *save;
155 codec_t *codec_itr, *cd;
158 init_list_entry(&codec_list);
160 while (Client_iterate(&client_itr) != NULL) {
162 while (Client_codec_iterate(client_itr, &codec_itr) != NULL) {
164 list_iterate(itr, &codec_list) {
165 cd = list_get_entry(itr, codec_t, node);
166 if (cd->codec == codec_itr->codec) {
172 cd = malloc(sizeof(codec_t));
174 Log_fatal("Out of memory");
175 memset(cd, 0, sizeof(codec_t));
176 init_list_entry(&cd->node);
177 cd->codec = codec_itr->codec;
179 list_add_tail(&cd->node, &codec_list);
184 list_iterate(itr, &codec_list) {
185 cd = list_get_entry(itr, codec_t, node);
186 if (cd->count > max) {
191 list_iterate_safe(itr, save, &codec_list) {
192 list_del(&list_get_entry(itr, codec_t, node)->node);
193 free(list_get_entry(itr, codec_t, node));
196 current_version = bPreferAlpha ? iCodecAlpha : iCodecBeta;
197 if (current_version == version)
199 // If we don't already use the compat bitstream version set
200 // it as alpha and announce it. If another codec now got the
201 // majority set it as the opposite of the currently valid bPreferAlpha
203 if (version == (uint32_t)0x8000000a)
206 bPreferAlpha = ! bPreferAlpha;
209 iCodecAlpha = version;
211 iCodecBeta = version;
213 sendmsg = Msg_create(CodecVersion);
214 sendmsg->payload.codecVersion->alpha = version;
215 sendmsg->payload.codecVersion->beta = version;
216 sendmsg->payload.codecVersion->prefer_alpha = bPreferAlpha;
217 Client_send_message_except(NULL, sendmsg);
219 Log_info("CELT codec switch 0x%x 0x%x (prefer 0x%x)", iCodecAlpha, iCodecBeta,
220 bPreferAlpha ? iCodecAlpha : iCodecBeta);
224 static int findFreeSessionId()
227 client_t *itr = NULL;
229 for (id = 1; id < INT_MAX; id++) {
231 while ((itr = Client_iterate(&itr)) != NULL) {
232 if (itr->sessionId == id)
235 if (itr == NULL) /* Found free id */
241 int Client_add(int fd, struct sockaddr_in *remote)
246 newclient = malloc(sizeof(client_t));
247 if (newclient == NULL)
248 Log_fatal("Out of memory");
249 memset(newclient, 0, sizeof(client_t));
251 newclient->tcpfd = fd;
252 memcpy(&newclient->remote_tcp, remote, sizeof(struct sockaddr_in));
253 newclient->ssl = SSLi_newconnection(&newclient->tcpfd, &newclient->SSLready);
254 if (newclient->ssl == NULL) {
255 Log_warn("SSL negotiation failed with %s:%d", inet_ntoa(remote->sin_addr),
256 ntohs(remote->sin_port));
260 newclient->availableBandwidth = maxBandwidth;
261 Timer_init(&newclient->lastActivity);
262 newclient->sessionId = findFreeSessionId();
263 if (newclient->sessionId < 0)
264 Log_fatal("Could not find a free session ID");
266 init_list_entry(&newclient->txMsgQueue);
267 init_list_entry(&newclient->chan_node);
268 init_list_entry(&newclient->node);
269 init_list_entry(&newclient->voicetargets);
270 init_list_entry(&newclient->codecs);
272 list_add_tail(&newclient->node, &clients);
275 /* Send version message to client */
276 sendmsg = Msg_create(Version);
277 sendmsg->payload.version->has_version = true;
278 sendmsg->payload.version->version = PROTOCOL_VERSION;
279 sendmsg->payload.version->release = strdup(UMURMUR_VERSION);
280 sendmsg->payload.version->os = strdup(system_string);
281 sendmsg->payload.version->os_version = strdup(version_string);
282 Client_send_message(newclient, sendmsg);
287 void Client_free(client_t *client)
289 struct dlist *itr, *save;
292 if (client->authenticated) {
294 leave_id = Chan_userLeave(client);
295 if (leave_id > 0) { /* Remove temp channel */
296 sendmsg = Msg_create(ChannelRemove);
297 sendmsg->payload.channelRemove->channel_id = leave_id;
298 Client_send_message_except(client, sendmsg);
300 sendmsg = Msg_create(UserRemove);
301 sendmsg->payload.userRemove->session = client->sessionId;
302 Client_send_message_except(client, sendmsg);
304 list_iterate_safe(itr, save, &client->txMsgQueue) {
305 list_del(&list_get_entry(itr, message_t, node)->node);
306 Msg_free(list_get_entry(itr, message_t, node));
308 Client_codec_free(client);
309 Voicetarget_free_all(client);
311 list_del(&client->node);
313 SSLi_free(client->ssl);
314 close(client->tcpfd);
317 free(client->release);
320 if (client->username)
321 free(client->username);
323 free(client->context);
327 void Client_close(client_t *client)
329 SSLi_shutdown(client->ssl);
330 client->shutdown_wait = true;
333 void Client_disconnect_all()
335 struct dlist *itr, *save;
337 list_iterate_safe(itr, save, &clients) {
338 Client_free(list_get_entry(itr, client_t, node));
342 int Client_read_fd(int fd)
345 client_t *client = NULL;
347 list_iterate(itr, &clients) {
348 if (fd == list_get_entry(itr, client_t, node)->tcpfd) {
349 client = list_get_entry(itr, client_t, node);
354 Log_fatal("No client found for fd %d", fd);
356 return Client_read(client);
359 int Client_read(client_t *client)
363 Timer_restart(&client->lastActivity);
365 if (client->writeBlockedOnRead) {
366 client->writeBlockedOnRead = false;
367 Log_debug("Client_read: writeBlockedOnRead == true");
368 return Client_write(client);
371 if (client->shutdown_wait) {
375 if (!client->SSLready) {
377 rc = SSLi_nonblockaccept(client->ssl, &client->SSLready);
386 if (!client->msgsize)
387 rc = SSLi_read(client->ssl, &client->rxbuf[client->rxcount], 6 - client->rxcount);
389 rc = SSLi_read(client->ssl, &client->rxbuf[client->rxcount], client->msgsize);
392 client->rxcount += rc;
393 if (!client->msgsize && client->rxcount >= 6) {
395 memcpy(&msgLen, &client->rxbuf[2], sizeof(uint32_t));
396 client->msgsize = ntohl(msgLen);
398 if (client->msgsize > BUFSIZE - 6) {
399 /* XXX - figure out how to handle this. A large size here can represent two cases:
400 * 1. A valid size. The only message that is this big is UserState message with a big texture
401 * 2. An invalid size = protocol error, e.g. connecting with a 1.1.x client
403 Log_warn("Too big message received (%d bytes). Playing safe and disconnecting client %s:%d",
404 client->msgsize, inet_ntoa(client->remote_tcp.sin_addr), ntohs(client->remote_tcp.sin_port));
407 /* client->rxcount = client->msgsize = 0; */
409 else if (client->rxcount == client->msgsize + 6) { /* Got all of the message */
410 msg = Msg_networkToMessage(client->rxbuf, client->msgsize + 6);
411 /* pass messsage to handler */
413 Mh_handle_message(client, msg);
414 client->rxcount = client->msgsize = 0;
416 } else /* rc <= 0 */ {
417 if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_WANT_READ) {
420 else if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_WANT_WRITE) {
421 client->readBlockedOnWrite = true;
424 else if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_ZERO_RETURN) {
425 Log_info_client(client, "Connection closed by peer");
426 if (!client->shutdown_wait)
427 Client_close(client);
430 if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_SYSCALL) {
431 Log_info_client(client, "Connection closed by peer");
434 Log_info_client(client, "SSL error: %d - Closing connection", SSLi_get_error(client->ssl, rc));
440 } while (SSLi_data_pending(client->ssl));
445 int Client_write_fd(int fd)
448 client_t *client = NULL;
450 list_iterate(itr, &clients) {
451 if(fd == list_get_entry(itr, client_t, node)->tcpfd) {
452 client = list_get_entry(itr, client_t, node);
457 Log_fatal("No client found for fd %d", fd);
458 Client_write(client);
462 int Client_write(client_t *client)
466 if (client->readBlockedOnWrite) {
467 client->readBlockedOnWrite = false;
468 Log_debug("Client_write: readBlockedOnWrite == true");
469 return Client_read(client);
471 rc = SSLi_write(client->ssl, &client->txbuf[client->txcount], client->txsize - client->txcount);
473 client->txcount += rc;
474 if (client->txcount == client->txsize)
475 client->txsize = client->txcount = 0;
478 if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_WANT_READ) {
479 client->writeBlockedOnRead = true;
482 else if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_WANT_WRITE) {
486 if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_SYSCALL)
487 Log_warn("Client_write: Error: %s - Closing connection", strerror(errno));
489 Log_warn("Client_write: SSL error: %d - Closing connection.", SSLi_get_error(client->ssl, rc));
494 if (client->txsize == 0 && !list_empty(&client->txMsgQueue)) {
496 msg = list_get_entry(list_get_first(&client->txMsgQueue), message_t, node);
497 list_del(list_get_first(&client->txMsgQueue));
498 client->txQueueCount--;
499 Client_send_message(client, msg);
504 int Client_send_message(client_t *client, message_t *msg)
506 if (!client->authenticated && msg->messageType != Version) {
510 if (client->txsize != 0 || !client->SSLready) {
512 if ((client->txQueueCount > 5 && msg->messageType == UDPTunnel) ||
513 client->txQueueCount > 30) {
517 client->txQueueCount++;
518 list_add_tail(&msg->node, &client->txMsgQueue);
519 Log_debug("Queueing message");
522 len = Msg_messageToNetwork(msg, client->txbuf);
523 doAssert(len < BUFSIZE);
525 client->txsize = len;
527 Client_write(client);
533 client_t *Client_iterate(client_t **client_itr)
535 client_t *c = *client_itr;
537 if (list_empty(&clients))
541 c = list_get_entry(list_get_first(&clients), client_t, node);
543 if (list_get_next(&c->node) == &clients)
546 c = list_get_entry(list_get_next(&c->node), client_t, node);
553 int Client_send_message_except(client_t *client, message_t *msg)
555 client_t *itr = NULL;
558 Msg_inc_ref(msg); /* Make sure a reference is held during the whole iteration. */
559 while (Client_iterate(&itr) != NULL) {
562 Msg_inc_ref(msg); /* One extra reference for each new copy */
563 Log_debug("Msg %d to %s refcount %d", msg->messageType, itr->username, msg->refcount);
564 Client_send_message(itr, msg);
567 Msg_free(msg); /* Free our reference to the message */
570 Msg_free(msg); /* If only 1 client is connected then no message is passed
571 * to Client_send_message(). Free it here. */
576 static bool_t checkDecrypt(client_t *client, const uint8_t *encrypted, uint8_t *plain, unsigned int len)
578 if (CryptState_isValid(&client->cryptState) &&
579 CryptState_decrypt(&client->cryptState, encrypted, plain, len))
582 if (Timer_elapsed(&client->cryptState.tLastGood) > 5000000ULL) {
583 if (Timer_elapsed(&client->cryptState.tLastRequest) > 5000000ULL) {
585 Timer_restart(&client->cryptState.tLastRequest);
587 sendmsg = Msg_create(CryptSetup);
588 Log_info_client(client, "Requesting voice channel crypt resync");
589 Client_send_message(client, sendmsg);
595 #define UDP_PACKET_SIZE 1024
596 int Client_read_udp()
599 struct sockaddr_in from;
600 socklen_t fromlen = sizeof(struct sockaddr_in);
603 UDPMessageType_t msgType;
605 #if defined(__LP64__)
606 uint8_t encbuff[UDP_PACKET_SIZE + 8];
607 uint8_t *encrypted = encbuff + 4;
609 uint8_t encrypted[UDP_PACKET_SIZE];
611 uint8_t buffer[UDP_PACKET_SIZE];
613 len = recvfrom(udpsock, encrypted, UDP_PACKET_SIZE, MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
616 } else if (len < 0) {
618 } else if (len < 5) {
619 // 4 bytes crypt header + type + session
621 } else if (len > UDP_PACKET_SIZE) {
626 if (len == 12 && *encrypted == 0) {
627 uint32_t *ping = (uint32_t *)encrypted;
628 ping[0] = htonl((uint32_t)PROTOCOL_VERSION);
629 // 1 and 2 will be the timestamp, which we return unmodified.
630 ping[3] = htonl((uint32_t)clientcount);
631 ping[4] = htonl((uint32_t)getIntConf(MAX_CLIENTS));
632 ping[5] = htonl((uint32_t)getIntConf(MAX_BANDWIDTH));
634 sendto(udpsock, encrypted, 6 * sizeof(uint32_t), 0, (struct sockaddr *)&from, fromlen);
638 key = (((uint64_t)from.sin_addr.s_addr) << 16) ^ from.sin_port;
641 while (Client_iterate(&itr) != NULL) {
642 if (itr->key == key) {
643 if (!checkDecrypt(itr, encrypted, buffer, len))
648 if (itr == NULL) { /* Unknown peer */
649 while (Client_iterate(&itr) != NULL) {
650 if (itr->remote_tcp.sin_addr.s_addr == from.sin_addr.s_addr) {
651 if (checkDecrypt(itr, encrypted, buffer, len)) {
653 Log_info_client(itr, "New UDP connection port %d", ntohs(from.sin_port));
654 memcpy(&itr->remote_udp, &from, sizeof(struct sockaddr_in));
657 else Log_warn("Bad cryptstate from peer");
661 if (itr == NULL) { /* Couldn't find this peer among connected clients */
666 len -= 4; /* Adjust for crypt header */
667 msgType = (UDPMessageType_t)((buffer[0] >> 5) & 0x7);
670 case UDPVoiceCELTAlpha:
671 case UDPVoiceCELTBeta:
672 Client_voiceMsg(itr, buffer, len);
675 Log_debug("UDP Ping reply len %d", len);
676 Client_send_udp(itr, buffer, len);
679 Log_debug("Unknown UDP message type from %s port %d", inet_ntoa(from.sin_addr), ntohs(from.sin_port));
687 static inline void Client_send_voice(client_t *src, client_t *dst, uint8_t *data, int len, int poslen)
689 if (IS_AUTH(dst) && dst != src && !dst->deaf) {
690 if (poslen > 0 && /* Has positional data */
691 src->context != NULL && dst->context != NULL && /* ...both source and destination has context */
692 strcmp(src->context, dst->context) == 0) /* ...and the contexts match */
693 Client_send_udp(dst, data, len);
695 Client_send_udp(dst, data, len - poslen);
699 /* Handle decrypted voice message */
700 int Client_voiceMsg(client_t *client, uint8_t *data, int len)
702 uint8_t buffer[UDP_PACKET_SIZE];
703 pds_t *pdi = Pds_create(data + 1, len - 1);
704 pds_t *pds = Pds_create(buffer + 1, UDP_PACKET_SIZE - 1);
705 unsigned int type = data[0] & 0xe0;
706 unsigned int target = data[0] & 0x1f;
707 unsigned int poslen, counter;
708 int offset, packetsize;
711 channel_t *ch = (channel_t *)client->channel;
714 if (!client->authenticated || client->mute)
717 packetsize = 20 + 8 + 4 + len;
718 if (client->availableBandwidth - packetsize < 0)
719 goto out; /* Discard */
720 client->availableBandwidth -= packetsize;
722 counter = Pds_get_numval(pdi); /* step past session id */
724 counter = Pds_next8(pdi);
725 offset = Pds_skip(pdi, counter & 0x7f);
726 } while ((counter & 0x80) && offset > 0);
728 poslen = pdi->maxsize - pdi->offset; /* For stripping of positional info */
730 Pds_add_numval(pds, client->sessionId);
731 Pds_append_data_nosize(pds, data + 1, len - 1);
733 if (target == 0x1f) { /* Loopback */
734 buffer[0] = (uint8_t) type;
735 Client_send_udp(client, buffer, pds->offset + 1);
737 else if (target == 0) { /* regular channel speech */
738 buffer[0] = (uint8_t) type;
743 list_iterate(itr, &ch->clients) {
745 c = list_get_entry(itr, client_t, chan_node);
746 Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
748 } else if ((vt = Voicetarget_get_id(client, target)) != NULL) { /* Targeted whisper */
752 for (i = 0; i < TARGET_MAX_CHANNELS && vt->channels[i].channel != -1; i++) {
753 buffer[0] = (uint8_t) (type | 1);
754 Log_debug("Whisper channel %d", vt->channels[i]);
755 ch = Chan_fromId(vt->channels[i].channel);
758 list_iterate(itr, &ch->clients) {
760 c = list_get_entry(itr, client_t, chan_node);
761 Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
764 if (vt->channels[i].linked && !list_empty(&ch->channel_links)) {
765 struct dlist *ch_itr;
766 list_iterate(ch_itr, &ch->channel_links) {
768 ch_link = list_get_entry(ch_itr, channel_t, link_node);
769 list_iterate(itr, &ch_link->clients) {
771 c = list_get_entry(itr, client_t, chan_node);
772 Log_debug("Linked voice from %s -> %s", ch->name, ch_link->name);
773 Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
778 if (vt->channels[i].children) {
779 struct dlist chanlist, *ch_itr;
780 init_list_entry(&chanlist);
781 Chan_buildTreeList(ch, &chanlist);
782 list_iterate(ch_itr, &chanlist) {
784 sub = list_get_entry(ch_itr, channellist_t, node)->chan;
785 list_iterate(itr, &sub->clients) {
787 c = list_get_entry(itr, client_t, chan_node);
788 Log_debug("Child voice from %s -> %s", ch->name, sub->name);
789 Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
792 Chan_freeTreeList(&chanlist);
796 for (i = 0; i < TARGET_MAX_SESSIONS && vt->sessions[i] != -1; i++) {
798 buffer[0] = (uint8_t) (type | 2);
799 Log_debug("Whisper session %d", vt->sessions[i]);
800 while (Client_iterate(&c) != NULL) {
801 if (c->sessionId == vt->sessions[i]) {
802 Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
816 static int Client_send_udp(client_t *client, uint8_t *data, int len)
820 if (client->remote_udp.sin_port != 0 && CryptState_isValid(&client->cryptState) &&
822 #if defined(__LP64__)
823 buf = mbuf = malloc(len + 4 + 16);
826 mbuf = buf = malloc(len + 4);
829 Log_fatal("Out of memory");
831 CryptState_encrypt(&client->cryptState, data, buf, len);
833 sendto(udpsock, buf, len + 4, 0, (struct sockaddr *)&client->remote_udp, sizeof(struct sockaddr_in));
838 msg = Msg_CreateVoiceMsg(data, len);
839 Client_send_message(client, msg);