1 /* Copyright (C) 2009-2014, Martin Johansson <martin@fatbob.nu>
2 Copyright (C) 2005-2014, 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"
50 extern char system_string[], version_string[];
52 static int Client_read(client_t *client);
53 static int Client_write(client_t *client);
54 static int Client_send_udp(client_t *client, uint8_t *data, int len);
55 void Client_free(client_t *client);
57 declare_list(clients);
58 static int clientcount; /* = 0 */
59 static int maxBandwidth;
62 int iCodecAlpha, iCodecBeta;
69 maxBandwidth = getIntConf(MAX_BANDWIDTH) / 8; /* From bits/s -> bytes/s */
77 int Client_getfds(struct pollfd *pollfds)
81 list_iterate(itr, &clients) {
83 c = list_get_entry(itr, client_t, node);
84 pollfds[i].fd = c->tcpfd;
85 pollfds[i].events = POLLIN | POLLHUP | POLLERR;
86 if (c->txsize > 0 || c->readBlockedOnWrite) /* Data waiting to be sent? */
87 pollfds[i].events |= POLLOUT;
95 struct dlist *itr, *save;
96 int bwTop = maxBandwidth + maxBandwidth / 4;
97 list_iterate_safe(itr, save, &clients) {
99 c = list_get_entry(itr, client_t, node);
100 Log_debug("Client %s BW available %d", c->username, c->availableBandwidth);
101 c->availableBandwidth += maxBandwidth;
102 if (c->availableBandwidth > bwTop)
103 c->availableBandwidth = bwTop;
105 if (Timer_isElapsed(&c->lastActivity, 1000000LL * INACTIVITY_TIMEOUT)) {
106 /* No activity from client - assume it is lost and close. */
107 Log_info_client(c, "Timeout, closing.");
114 void Client_codec_add(client_t *client, int codec)
116 codec_t *cd = malloc(sizeof(codec_t));
118 Log_fatal("Out of memory");
119 init_list_entry(&cd->node);
121 list_add_tail(&cd->node, &client->codecs);
124 void Client_codec_free(client_t *client)
126 struct dlist *itr, *save;
127 list_iterate_safe(itr, save, &client->codecs) {
128 list_del(&list_get_entry(itr, codec_t, node)->node);
129 free(list_get_entry(itr, codec_t, node));
133 codec_t *Client_codec_iterate(client_t *client, codec_t **codec_itr)
135 codec_t *cd = *codec_itr;
137 if (list_empty(&client->codecs))
141 cd = list_get_entry(list_get_first(&client->codecs), codec_t, node);
143 if (list_get_next(&cd->node) == &client->codecs)
146 cd = list_get_entry(list_get_next(&cd->node), codec_t, node);
152 void Client_token_add(client_t *client, char *token_string)
156 if (client->tokencount >= MAX_TOKENS)
158 token = malloc(sizeof(token_t));
160 Log_fatal("Out of memory");
161 init_list_entry(&token->node);
162 token->token = strdup(token_string);
163 if (token->token == NULL)
164 Log_fatal("Out of memory");
165 list_add_tail(&token->node, &client->tokens);
166 client->tokencount++;
169 bool_t Client_token_match(client_t *client, char *str)
174 if (list_empty(&client->tokens))
176 list_iterate(itr, &client->tokens) {
177 token = list_get_entry(itr, token_t, node);
178 if (strncasecmp(token->token, str, MAX_TOKENSIZE) == 0)
184 void Client_token_free(client_t *client)
186 struct dlist *itr, *save;
189 list_iterate_safe(itr, save, &client->tokens) {
190 token = list_get_entry(itr, token_t, node);
191 list_del(&token->node);
195 client->tokencount = 0;
199 #define OPUS_WARN_USING "<strong>WARNING:</strong> Your client doesn't support the Opus codec the server is using, you won't be able to talk or hear anyone. Please upgrade your Mumble client."
200 #define OPUS_WARN_SWITCHING "<strong>WARNING:</strong> Your client doesn't support the Opus codec the server is switching to, you won't be able to talk or hear anyone. Please upgrade your Mumble client."
201 void recheckCodecVersions(client_t *connectingClient)
203 client_t *client_itr = NULL;
204 int max = 0, version, current_version;
205 int users = 0, opus = 0;
207 struct dlist codec_list, *itr, *save;
208 codec_t *codec_itr, *cd;
212 init_list_entry(&codec_list);
214 while (Client_iterate(&client_itr) != NULL) {
216 if (client_itr->codec_count == 0 && !client_itr->bOpus)
218 while (Client_codec_iterate(client_itr, &codec_itr) != NULL) {
220 list_iterate(itr, &codec_list) {
221 cd = list_get_entry(itr, codec_t, node);
222 if (cd->codec == codec_itr->codec) {
228 cd = malloc(sizeof(codec_t));
230 Log_fatal("Out of memory");
231 memset(cd, 0, sizeof(codec_t));
232 init_list_entry(&cd->node);
233 cd->codec = codec_itr->codec;
235 list_add_tail(&cd->node, &codec_list);
239 if (client_itr->bOpus)
245 enableOpus = ((opus * 100 / users) >= getIntConf(OPUS_THRESHOLD));
247 list_iterate(itr, &codec_list) {
248 cd = list_get_entry(itr, codec_t, node);
249 if (cd->count > max) {
254 list_iterate_safe(itr, save, &codec_list) {
255 list_del(&list_get_entry(itr, codec_t, node)->node);
256 free(list_get_entry(itr, codec_t, node));
259 current_version = bPreferAlpha ? iCodecAlpha : iCodecBeta;
260 if (current_version != version) {
261 // If we don't already use the compat bitstream version set
262 // it as alpha and announce it. If another codec now got the
263 // majority set it as the opposite of the currently valid bPreferAlpha
265 if (version == (uint32_t)0x8000000b)
268 bPreferAlpha = !bPreferAlpha;
271 iCodecAlpha = version;
273 iCodecBeta = version;
274 } else if (bOpus && enableOpus) {
275 if (connectingClient && !connectingClient->bOpus)
276 Client_textmessage(connectingClient, OPUS_WARN_USING);
280 sendmsg = Msg_create(CodecVersion);
281 sendmsg->payload.codecVersion->alpha = iCodecAlpha;
282 sendmsg->payload.codecVersion->beta = iCodecBeta;
283 sendmsg->payload.codecVersion->prefer_alpha = bPreferAlpha;
284 sendmsg->payload.codecVersion->has_opus = true;
285 sendmsg->payload.codecVersion->opus = enableOpus;
287 Client_send_message_except(NULL, sendmsg);
289 if (enableOpus && !bOpus) {
291 while (Client_iterate(&client_itr) != NULL) {
292 if ((client_itr->authenticated || client_itr == connectingClient) &&
293 !client_itr->bOpus) {
294 Client_textmessage(client_itr, OPUS_WARN_SWITCHING);
297 Log_info("OPUS codec %s", bOpus ? "enabled" : "disabled");
303 static int findFreeSessionId()
306 client_t *itr = NULL;
308 for (id = 1; id < INT_MAX; id++) {
310 while ((itr = Client_iterate(&itr)) != NULL) {
311 if (itr->sessionId == id)
314 if (itr == NULL) /* Found free id */
320 int Client_add(int fd, struct sockaddr_storage *remote)
324 char addressPresentation[INET6_ADDRSTRLEN];
327 if(remote->ss_family == AF_INET) {
328 inet_ntop(AF_INET, &((struct sockaddr_in*)remote)->sin_addr, addressPresentation, INET6_ADDRSTRLEN);
329 port = ntohs(((struct sockaddr_in*)remote)->sin_port);
331 inet_ntop(AF_INET6, &((struct sockaddr_in6*)remote)->sin6_addr, addressPresentation, INET6_ADDRSTRLEN);
332 port = ntohs(((struct sockaddr_in6*)remote)->sin6_port);
335 if (Ban_isBannedAddr(remote)) {
336 Log_info("Address %s banned. Disconnecting", addressPresentation);
340 if ((newclient = calloc(1, sizeof(client_t))) == NULL)
341 Log_fatal("Out of memory (%s:%s)", __FILE__, __LINE__);
343 memcpy(newclient->addressString, addressPresentation, INET6_ADDRSTRLEN);
345 newclient->tcpfd = fd;
346 memcpy(&newclient->remote_tcp, remote, sizeof(struct sockaddr_storage));
347 newclient->ssl = SSLi_newconnection(&newclient->tcpfd, &newclient->SSLready);
348 if (newclient->ssl == NULL) {
349 Log_warn("SSL negotiation failed with %s on port %d", addressPresentation, port);
353 newclient->availableBandwidth = maxBandwidth;
354 Timer_init(&newclient->lastActivity);
355 Timer_init(&newclient->connectTime);
356 Timer_init(&newclient->idleTime);
357 newclient->sessionId = findFreeSessionId();
358 if (newclient->sessionId < 0)
359 Log_fatal("Could not find a free session ID");
361 init_list_entry(&newclient->txMsgQueue);
362 init_list_entry(&newclient->chan_node);
363 init_list_entry(&newclient->node);
364 init_list_entry(&newclient->voicetargets);
365 init_list_entry(&newclient->codecs);
366 init_list_entry(&newclient->tokens);
368 list_add_tail(&newclient->node, &clients);
371 /* Send version message to client */
372 sendmsg = Msg_create(Version);
373 sendmsg->payload.version->has_version = true;
374 sendmsg->payload.version->version = PROTOCOL_VERSION;
375 sendmsg->payload.version->release = strdup(UMURMUR_VERSION);
376 sendmsg->payload.version->os = strdup(system_string);
377 sendmsg->payload.version->os_version = strdup(version_string);
378 Client_send_message(newclient, sendmsg);
383 void Client_free(client_t *client)
385 struct dlist *itr, *save;
387 bool_t authenticatedLeft = client->authenticated;
389 if (client->authenticated) {
391 leave_id = Chan_userLeave(client);
392 if (leave_id > 0) { /* Remove temp channel */
393 sendmsg = Msg_create(ChannelRemove);
394 sendmsg->payload.channelRemove->channel_id = leave_id;
395 Client_send_message_except(client, sendmsg);
397 sendmsg = Msg_create(UserRemove);
398 sendmsg->payload.userRemove->session = client->sessionId;
399 Client_send_message_except(client, sendmsg);
401 list_iterate_safe(itr, save, &client->txMsgQueue) {
402 list_del(&list_get_entry(itr, message_t, node)->node);
403 Msg_free(list_get_entry(itr, message_t, node));
405 Client_codec_free(client);
406 Voicetarget_free_all(client);
407 Client_token_free(client);
409 list_del(&client->node);
411 SSLi_free(client->ssl);
412 close(client->tcpfd);
415 free(client->release);
418 if (client->os_version)
419 free(client->os_version);
420 if (client->username)
421 free(client->username);
423 free(client->context);
426 if (authenticatedLeft)
427 recheckCodecVersions(NULL); /* Can use better codec now? */
430 void Client_close(client_t *client)
432 SSLi_shutdown(client->ssl);
433 client->shutdown_wait = true;
436 void Client_disconnect_all()
438 struct dlist *itr, *save;
440 list_iterate_safe(itr, save, &clients) {
441 Client_free(list_get_entry(itr, client_t, node));
445 int Client_read_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 return Client_read(client);
462 int Client_read(client_t *client)
466 Timer_restart(&client->lastActivity);
468 if (client->writeBlockedOnRead) {
469 client->writeBlockedOnRead = false;
470 Log_debug("Client_read: writeBlockedOnRead == true");
471 return Client_write(client);
474 if (client->shutdown_wait) {
478 if (!client->SSLready) {
480 rc = SSLi_nonblockaccept(client->ssl, &client->SSLready);
489 if (!client->msgsize)
490 rc = SSLi_read(client->ssl, &client->rxbuf[client->rxcount], 6 - client->rxcount);
492 rc = SSLi_read(client->ssl, &client->rxbuf[client->rxcount], client->msgsize);
495 client->rxcount += rc;
496 if (!client->msgsize && client->rxcount >= 6) {
498 memcpy(&msgLen, &client->rxbuf[2], sizeof(uint32_t));
499 client->msgsize = ntohl(msgLen);
501 if (client->msgsize > BUFSIZE - 6) {
502 /* XXX - figure out how to handle this. A large size here can represent two cases:
503 * 1. A valid size. The only message that is this big is UserState message with a big texture
504 * 2. An invalid size = protocol error, e.g. connecting with a 1.1.x client
506 // Log_warn("Too big message received (%d bytes). Playing safe and disconnecting client %s:%d",
507 // client->msgsize, inet_ntoa(client->remote_tcp.sin_addr), ntohs(client->remote_tcp.sin_port));
510 /* client->rxcount = client->msgsize = 0; */
512 else if (client->rxcount == client->msgsize + 6) { /* Got all of the message */
513 msg = Msg_networkToMessage(client->rxbuf, client->msgsize + 6);
514 /* pass messsage to handler */
516 Mh_handle_message(client, msg);
517 client->rxcount = client->msgsize = 0;
519 } else /* rc <= 0 */ {
520 if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_WANT_READ) {
523 else if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_WANT_WRITE) {
524 client->readBlockedOnWrite = true;
527 else if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_ZERO_RETURN ||
528 SSLi_get_error(client->ssl, rc) == 0) {
529 Log_info_client(client, "Connection closed by peer");
530 Client_close(client);
533 if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_SYSCALL) {
535 Log_info_client(client, "Connection closed by peer");
537 Log_info_client(client,"Error: %s - Closing connection (code %d)",
540 else if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_CONNRESET) {
541 Log_info_client(client, "Connection reset by peer");
544 Log_info_client(client, "SSL error: %d - Closing connection", SSLi_get_error(client->ssl, rc));
550 } while (SSLi_data_pending(client->ssl));
555 int Client_write_fd(int fd)
558 client_t *client = NULL;
560 list_iterate(itr, &clients) {
561 if(fd == list_get_entry(itr, client_t, node)->tcpfd) {
562 client = list_get_entry(itr, client_t, node);
567 return Client_write(client);
572 int Client_write(client_t *client)
576 if (client->readBlockedOnWrite) {
577 client->readBlockedOnWrite = false;
578 Log_debug("Client_write: readBlockedOnWrite == true");
579 return Client_read(client);
581 rc = SSLi_write(client->ssl, &client->txbuf[client->txcount], client->txsize - client->txcount);
583 client->txcount += rc;
584 if (client->txcount == client->txsize)
585 client->txsize = client->txcount = 0;
588 if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_WANT_READ) {
589 client->writeBlockedOnRead = true;
592 else if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_WANT_WRITE) {
596 if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_SYSCALL) {
597 Log_info_client(client, "Error: %s - Closing connection", strerror(errno));
599 else if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_CONNRESET) {
600 Log_info_client(client, "Connection reset by peer");
603 Log_info_client(client, "SSL error: %d - Closing connection.", SSLi_get_error(client->ssl, rc));
609 if (client->txsize == 0 && !list_empty(&client->txMsgQueue)) {
611 msg = list_get_entry(list_get_first(&client->txMsgQueue), message_t, node);
612 list_del(list_get_first(&client->txMsgQueue));
613 client->txQueueCount--;
614 Client_send_message(client, msg);
619 int Client_send_message_ver(client_t *client, message_t *msg, uint32_t version)
621 if ((version == 0) || (client->version >= version) ||
622 ((version & 0x80000000) && (client->version < (~version))))
623 return Client_send_message(client, msg);
628 int Client_send_message(client_t *client, message_t *msg)
630 if (!client->authenticated && msg->messageType != Version) {
634 if (client->txsize != 0 || !client->SSLready) {
636 if ((client->txQueueCount > 5 && msg->messageType == UDPTunnel) ||
637 client->txQueueCount > 30) {
641 client->txQueueCount++;
642 list_add_tail(&msg->node, &client->txMsgQueue);
643 Log_debug("Queueing message");
646 len = Msg_messageToNetwork(msg, client->txbuf);
647 doAssert(len < BUFSIZE);
649 client->txsize = len;
651 Client_write(client);
657 client_t *Client_iterate(client_t **client_itr)
659 client_t *c = *client_itr;
661 if (list_empty(&clients))
665 c = list_get_entry(list_get_first(&clients), client_t, node);
667 if (list_get_next(&c->node) == &clients)
670 c = list_get_entry(list_get_next(&c->node), client_t, node);
676 void Client_textmessage(client_t *client, char *text)
680 message_t *sendmsg = NULL;
682 message = malloc(strlen(text) + 1);
684 Log_fatal("Out of memory");
685 tree_id = malloc(sizeof(uint32_t));
687 Log_fatal("Out of memory");
689 sendmsg = Msg_create(TextMessage);
690 sendmsg->payload.textMessage->message = message;
691 sendmsg->payload.textMessage->n_tree_id = 1;
692 sendmsg->payload.textMessage->tree_id = tree_id;
693 strcpy(message, text);
694 Client_send_message(client, sendmsg);
698 int Client_send_message_except(client_t *client, message_t *msg)
700 client_t *itr = NULL;
703 Msg_inc_ref(msg); /* Make sure a reference is held during the whole iteration. */
704 while (Client_iterate(&itr) != NULL) {
707 Msg_inc_ref(msg); /* One extra reference for each new copy */
708 Log_debug("Msg %d to %s refcount %d", msg->messageType, itr->username, msg->refcount);
709 Client_send_message(itr, msg);
712 Msg_free(msg); /* Free our reference to the message */
715 Msg_free(msg); /* If only 1 client is connected then no message is passed
716 * to Client_send_message(). Free it here. */
721 int Client_send_message_except_ver(client_t *client, message_t *msg, uint32_t version)
723 client_t *itr = NULL;
726 Msg_inc_ref(msg); /* Make sure a reference is held during the whole iteration. */
727 while (Client_iterate(&itr) != NULL) {
730 Msg_inc_ref(msg); /* One extra reference for each new copy */
731 Log_debug("Msg %d to %s refcount %d", msg->messageType, itr->username, msg->refcount);
732 Client_send_message_ver(itr, msg, version);
735 Msg_free(msg); /* Free our reference to the message */
738 Msg_free(msg); /* If only 1 client is connected then no message is passed
739 * to Client_send_message(). Free it here. */
744 static bool_t checkDecrypt(client_t *client, const uint8_t *encrypted, uint8_t *plain, unsigned int len)
746 if (CryptState_isValid(&client->cryptState) &&
747 CryptState_decrypt(&client->cryptState, encrypted, plain, len))
750 if (Timer_elapsed(&client->cryptState.tLastGood) > 5000000ULL) {
751 if (Timer_elapsed(&client->cryptState.tLastRequest) > 5000000ULL) {
753 Timer_restart(&client->cryptState.tLastRequest);
755 sendmsg = Msg_create(CryptSetup);
756 Log_info_client(client, "Requesting voice channel crypt resync");
757 Client_send_message(client, sendmsg);
763 #define UDP_PACKET_SIZE 1024
764 int Client_read_udp(int udpsock)
767 struct sockaddr_storage from;
768 socklen_t fromlen = sizeof(struct sockaddr_storage);
769 uint8_t key[KEY_LENGTH];
771 UDPMessageType_t msgType;
772 uint8_t fromaddress[4 * sizeof(in_addr_t)];
775 #if defined(__LP64__)
776 uint8_t encbuff[UDP_PACKET_SIZE + 8];
777 uint8_t *encrypted = encbuff + 4;
779 uint8_t encrypted[UDP_PACKET_SIZE];
781 uint8_t buffer[UDP_PACKET_SIZE];
783 len = recvfrom(udpsock, encrypted, UDP_PACKET_SIZE, MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
785 memset(key, 0, KEY_LENGTH);
787 if(from.ss_family == AF_INET) {
788 memcpy(fromaddress, &((struct sockaddr_in*)&from)->sin_addr, sizeof(in_addr_t));
789 fromport = ntohs(((struct sockaddr_in*)&from)->sin_port);
790 memcpy(&key[0], &fromport, 2);
791 memcpy(&key[2], fromaddress, sizeof(in_addr_t));
793 memcpy(fromaddress, &((struct sockaddr_in6*)&from)->sin6_addr, 4 * sizeof(in_addr_t));
794 fromport = ntohs(((struct sockaddr_in6*)&from)->sin6_port);
795 memcpy(&key[0], &fromport, 2);
796 memcpy(&key[2], fromaddress, 4 * sizeof(in_addr_t));
801 } else if (len < 0) {
803 } else if (len < 5) {
804 // 4 bytes crypt header + type + session
806 } else if (len > UDP_PACKET_SIZE) {
811 if (len == 12 && *encrypted == 0) {
812 uint32_t *ping = (uint32_t *)encrypted;
813 ping[0] = htonl((uint32_t)PROTOCOL_VERSION);
814 // 1 and 2 will be the timestamp, which we return unmodified.
815 ping[3] = htonl((uint32_t)clientcount);
816 ping[4] = htonl((uint32_t)getIntConf(MAX_CLIENTS));
817 ping[5] = htonl((uint32_t)getIntConf(MAX_BANDWIDTH));
819 sendto(udpsock, encrypted, 6 * sizeof(uint32_t), 0, (struct sockaddr *)&from, fromlen);
825 while (Client_iterate(&itr) != NULL) {
826 if (memcmp(itr->key, key, KEY_LENGTH) == 0) {
827 if (!checkDecrypt(itr, encrypted, buffer, len))
832 if (itr == NULL) { /* Unknown peer */
833 struct sockaddr_storage itraddressstorage;
834 uint8_t itraddress[4 * sizeof(in_addr_t)];
837 while (Client_iterate(&itr) != NULL) {
838 itraddressstorage = itr->remote_tcp;
839 if(itraddressstorage.ss_family == AF_INET) {
840 memcpy(itraddress, &((struct sockaddr_in*)&from)->sin_addr, sizeof(in_addr_t));
841 addresslength = sizeof(in_addr_t);
843 memcpy(itraddress, &((struct sockaddr_in6*)&from)->sin6_addr, 4 * sizeof(in_addr_t));
844 addresslength = 4 * sizeof(in_addr_t);
847 if (memcmp(itraddress, fromaddress, addresslength) == 0) {
848 if (checkDecrypt(itr, encrypted, buffer, len)) {
849 memcpy(itr->key, key, KEY_LENGTH);
850 Log_info_client(itr, "New UDP connection from %s on port %d", itr->addressString, fromport);
851 memcpy(&itr->remote_udp, &from, sizeof(struct sockaddr_storage));
857 if (itr == NULL) { /* Couldn't find this peer among connected clients */
862 len -= 4; /* Adjust for crypt header */
863 msgType = (UDPMessageType_t)((buffer[0] >> 5) & 0x7);
866 case UDPVoiceCELTAlpha:
867 case UDPVoiceCELTBeta:
871 Client_voiceMsg(itr, buffer, len);
874 Log_debug("UDP Ping reply len %d", len);
875 Client_send_udp(itr, buffer, len);
878 Log_debug("Unknown UDP message type from %s port %d", itr->addressString, fromport);
886 static inline void Client_send_voice(client_t *src, client_t *dst, uint8_t *data, int len, int poslen)
888 if (IS_AUTH(dst) && dst != src && !dst->deaf && !dst->self_deaf) {
889 if (poslen > 0 && /* Has positional data */
890 src->context != NULL && dst->context != NULL && /* ...both source and destination has context */
891 strcmp(src->context, dst->context) == 0) /* ...and the contexts match */
892 Client_send_udp(dst, data, len);
894 Client_send_udp(dst, data, len - poslen);
898 /* Handle decrypted voice message */
899 int Client_voiceMsg(client_t *client, uint8_t *data, int len)
901 uint8_t buffer[UDP_PACKET_SIZE];
902 pds_t *pdi = Pds_create(data + 1, len - 1);
903 pds_t *pds = Pds_create(buffer + 1, UDP_PACKET_SIZE - 1);
904 unsigned int type = data[0] & 0xe0;
905 unsigned int target = data[0] & 0x1f;
906 unsigned int poslen, counter, size;
907 int offset, packetsize;
910 channel_t *ch = (channel_t *)client->channel;
913 if (!client->authenticated || client->mute || client->self_mute || ch->silent)
916 packetsize = 20 + 8 + 4 + len;
917 if (client->availableBandwidth - packetsize < 0)
918 goto out; /* Discard */
919 client->availableBandwidth -= packetsize;
921 Timer_restart(&client->idleTime);
922 Timer_restart(&client->lastActivity);
924 counter = Pds_get_numval(pdi); /* step past session id */
925 if ((type >> 5) != UDPVoiceOpus) {
927 counter = Pds_next8(pdi);
928 offset = Pds_skip(pdi, counter & 0x7f);
929 } while ((counter & 0x80) && offset > 0);
931 size = Pds_get_numval(pdi);
932 Pds_skip(pdi, size & 0x1fff);
935 poslen = pdi->maxsize - pdi->offset; /* For stripping of positional info */
937 Pds_add_numval(pds, client->sessionId);
938 Pds_append_data_nosize(pds, data + 1, len - 1);
940 if (target == 0x1f) { /* Loopback */
941 buffer[0] = (uint8_t) type;
942 Client_send_udp(client, buffer, pds->offset + 1);
944 else if (target == 0) { /* regular channel speech */
945 buffer[0] = (uint8_t) type;
950 list_iterate(itr, &ch->clients) {
952 c = list_get_entry(itr, client_t, chan_node);
953 Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
955 } else if ((vt = Voicetarget_get_id(client, target)) != NULL) { /* Targeted whisper */
959 for (i = 0; i < TARGET_MAX_CHANNELS && vt->channels[i].channel != -1; i++) {
960 buffer[0] = (uint8_t) (type | 1);
961 Log_debug("Whisper channel %d", vt->channels[i]);
962 ch = Chan_fromId(vt->channels[i].channel);
965 list_iterate(itr, &ch->clients) {
967 c = list_get_entry(itr, client_t, chan_node);
968 Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
971 if (vt->channels[i].linked && !list_empty(&ch->channel_links)) {
972 struct dlist *ch_itr;
973 list_iterate(ch_itr, &ch->channel_links) {
975 ch_link = list_get_entry(ch_itr, channel_t, link_node);
976 list_iterate(itr, &ch_link->clients) {
978 c = list_get_entry(itr, client_t, chan_node);
979 Log_debug("Linked voice from %s -> %s", ch->name, ch_link->name);
980 Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
985 if (vt->channels[i].children) {
986 struct dlist chanlist, *ch_itr;
987 init_list_entry(&chanlist);
988 Chan_buildTreeList(ch, &chanlist);
989 list_iterate(ch_itr, &chanlist) {
991 sub = list_get_entry(ch_itr, channellist_t, node)->chan;
992 list_iterate(itr, &sub->clients) {
994 c = list_get_entry(itr, client_t, chan_node);
995 Log_debug("Child voice from %s -> %s", ch->name, sub->name);
996 Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
999 Chan_freeTreeList(&chanlist);
1003 for (i = 0; i < TARGET_MAX_SESSIONS && vt->sessions[i] != -1; i++) {
1005 buffer[0] = (uint8_t) (type | 2);
1006 Log_debug("Whisper session %d", vt->sessions[i]);
1007 while (Client_iterate(&c) != NULL) {
1008 if (c->sessionId == vt->sessions[i]) {
1009 Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
1022 static int Client_send_udp(client_t *client, uint8_t *data, int len)
1024 uint8_t *buf, *mbuf;
1025 uint16_t clientport;
1026 int udpsock = (client->remote_udp.ss_family == AF_INET) ? udpsocks[0] : udpsocks[1];
1028 if (client->remote_udp.ss_family == AF_INET)
1029 clientport = ntohs(((struct sockaddr_in*)&client->remote_udp)->sin_port);
1031 clientport = ntohs(((struct sockaddr_in6*)&client->remote_udp)->sin6_port);
1033 if (clientport != 0 && CryptState_isValid(&client->cryptState) &&
1035 #if defined(__LP64__)
1036 buf = mbuf = malloc(len + 4 + 16);
1039 mbuf = buf = malloc(len + 4);
1042 Log_fatal("Out of memory");
1044 CryptState_encrypt(&client->cryptState, data, buf, len);
1046 #if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__APPLE__)
1047 sendto(udpsock, buf, len + 4, 0, (struct sockaddr *)&client->remote_udp, client->remote_tcp.ss_len);
1049 sendto(udpsock, buf, len + 4, 0, (struct sockaddr *)&client->remote_udp, sizeof(struct sockaddr_storage));
1055 msg = Msg_CreateVoiceMsg(data, len);
1056 Client_send_message(client, msg);