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>
44 #include "messagehandler.h"
48 #include "voicetarget.h"
52 extern char system_string[], version_string[];
54 static int Client_read(client_t *client);
55 static int Client_write(client_t *client);
56 static int Client_send_udp(client_t *client, uint8_t *data, int len);
57 static client_t *Client_find_by_fd(int fd);
58 void Client_free(client_t *client);
60 declare_list(clients);
61 static int clientcount; /* = 0 */
62 static int maxBandwidth;
65 int iCodecAlpha, iCodecBeta;
73 maxBandwidth = getIntConf(MAX_BANDWIDTH) / 8; /* From bits/s -> bytes/s */
81 int Client_getfds(struct pollfd *pollfds)
85 list_iterate(itr, &clients) {
87 c = list_get_entry(itr, client_t, node);
88 pollfds[i].fd = c->tcpfd;
89 pollfds[i].events = POLLIN | POLLHUP | POLLERR;
90 if (c->txsize > 0 || c->readBlockedOnWrite) /* Data waiting to be sent? */
91 pollfds[i].events |= POLLOUT;
99 struct dlist *itr, *save;
100 int bwTop = maxBandwidth + maxBandwidth / 4;
101 list_iterate_safe(itr, save, &clients) {
103 c = list_get_entry(itr, client_t, node);
104 Log_debug("Client %s BW available %d", c->username, c->availableBandwidth);
105 c->availableBandwidth += maxBandwidth;
106 if (c->availableBandwidth > bwTop)
107 c->availableBandwidth = bwTop;
109 if (Timer_isElapsed(&c->lastActivity, 1000000LL * INACTIVITY_TIMEOUT)) {
110 /* No activity from client - assume it is lost and close. */
111 Log_info_client(c, "Timeout, closing.");
118 void Client_codec_add(client_t *client, int codec)
120 codec_t *cd = Memory_safeMalloc(1, sizeof(codec_t));
121 init_list_entry(&cd->node);
123 list_add_tail(&cd->node, &client->codecs);
126 void Client_codec_free(client_t *client)
128 struct dlist *itr, *save;
129 list_iterate_safe(itr, save, &client->codecs) {
130 list_del(&list_get_entry(itr, codec_t, node)->node);
131 free(list_get_entry(itr, codec_t, node));
135 codec_t *Client_codec_iterate(client_t *client, codec_t **codec_itr)
137 codec_t *cd = *codec_itr;
139 if (list_empty(&client->codecs))
143 cd = list_get_entry(list_get_first(&client->codecs), codec_t, node);
145 if (list_get_next(&cd->node) == &client->codecs)
148 cd = list_get_entry(list_get_next(&cd->node), codec_t, node);
154 void Client_token_add(client_t *client, char *token_string)
158 if (client->tokencount >= MAX_TOKENS)
160 token = Memory_safeMalloc(1, sizeof(token_t));
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 const *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 = Memory_safeCalloc(1, sizeof(codec_t));
229 init_list_entry(&cd->node);
230 cd->codec = codec_itr->codec;
232 list_add_tail(&cd->node, &codec_list);
236 if (client_itr->bOpus)
242 enableOpus = ((opus * 100 / users) >= getIntConf(OPUS_THRESHOLD));
244 list_iterate(itr, &codec_list) {
245 cd = list_get_entry(itr, codec_t, node);
246 if (cd->count > max) {
251 list_iterate_safe(itr, save, &codec_list) {
252 list_del(&list_get_entry(itr, codec_t, node)->node);
253 free(list_get_entry(itr, codec_t, node));
256 current_version = bPreferAlpha ? iCodecAlpha : iCodecBeta;
257 if (current_version != version) {
258 // If we don't already use the compat bitstream version set
259 // it as alpha and announce it. If another codec now got the
260 // majority set it as the opposite of the currently valid bPreferAlpha
262 if (version == (uint32_t)0x8000000b)
265 bPreferAlpha = !bPreferAlpha;
268 iCodecAlpha = version;
270 iCodecBeta = version;
271 } else if (bOpus && enableOpus) {
272 if (connectingClient && !connectingClient->bOpus)
273 Client_textmessage(connectingClient, OPUS_WARN_USING);
277 sendmsg = Msg_create(CodecVersion);
278 sendmsg->payload.codecVersion->alpha = iCodecAlpha;
279 sendmsg->payload.codecVersion->beta = iCodecBeta;
280 sendmsg->payload.codecVersion->prefer_alpha = bPreferAlpha;
281 sendmsg->payload.codecVersion->has_opus = true;
282 sendmsg->payload.codecVersion->opus = enableOpus;
284 Client_send_message_except(NULL, sendmsg);
286 if (enableOpus && !bOpus) {
288 while (Client_iterate(&client_itr) != NULL) {
289 if ((client_itr->authenticated || client_itr == connectingClient) &&
290 !client_itr->bOpus) {
291 Client_textmessage(client_itr, OPUS_WARN_SWITCHING);
294 Log_info("OPUS codec %s", bOpus ? "enabled" : "disabled");
300 static int findFreeSessionId()
303 client_t *itr = NULL;
305 for (id = 1; id < INT_MAX; id++) {
307 while ((itr = Client_iterate(&itr)) != NULL) {
308 if (itr->sessionId == id)
311 if (itr == NULL) /* Found free id */
317 int Client_add(int fd, struct sockaddr_storage *remote)
321 char* addressString = NULL;
323 if (Ban_isBannedAddr(remote)) {
324 addressString = Util_addressToString(remote);
325 Log_info("Address %s banned. Disconnecting", addressString);
330 newclient = Memory_safeCalloc(1, sizeof(client_t));
332 newclient->tcpfd = fd;
333 memcpy(&newclient->remote_tcp, remote, sizeof(struct sockaddr_storage));
334 newclient->ssl = SSLi_newconnection(&newclient->tcpfd, &newclient->SSLready);
335 if (newclient->ssl == NULL) {
336 addressString = Util_addressToString(remote);
337 Log_warn("SSL negotiation failed with %s on port %d", addressString, Util_addressToPort(remote));
342 newclient->availableBandwidth = maxBandwidth;
343 Timer_init(&newclient->lastActivity);
344 Timer_init(&newclient->connectTime);
345 Timer_init(&newclient->idleTime);
346 newclient->sessionId = findFreeSessionId();
347 if (newclient->sessionId < 0)
348 Log_fatal("Could not find a free session ID");
350 init_list_entry(&newclient->txMsgQueue);
351 init_list_entry(&newclient->chan_node);
352 init_list_entry(&newclient->node);
353 init_list_entry(&newclient->voicetargets);
354 init_list_entry(&newclient->codecs);
355 init_list_entry(&newclient->tokens);
357 list_add_tail(&newclient->node, &clients);
360 /* Send version message to client */
361 sendmsg = Msg_create(Version);
362 sendmsg->payload.version->has_version = true;
363 sendmsg->payload.version->version = PROTOCOL_VERSION;
364 sendmsg->payload.version->release = strdup(UMURMUR_VERSION);
365 sendmsg->payload.version->os = strdup(system_string);
366 sendmsg->payload.version->os_version = strdup(version_string);
367 Client_send_message(newclient, sendmsg);
372 void Client_free(client_t *client)
374 struct dlist *itr, *save;
376 bool_t authenticatedLeft = client->authenticated;
378 if (client->authenticated) {
380 leave_id = Chan_userLeave(client);
381 if (leave_id > 0) { /* Remove temp channel */
382 sendmsg = Msg_create(ChannelRemove);
383 sendmsg->payload.channelRemove->channel_id = leave_id;
384 Client_send_message_except(client, sendmsg);
386 sendmsg = Msg_create(UserRemove);
387 sendmsg->payload.userRemove->session = client->sessionId;
388 Client_send_message_except(client, sendmsg);
390 list_iterate_safe(itr, save, &client->txMsgQueue) {
391 list_del(&list_get_entry(itr, message_t, node)->node);
392 Msg_free(list_get_entry(itr, message_t, node));
394 Client_codec_free(client);
395 Voicetarget_free_all(client);
396 Client_token_free(client);
398 list_del(&client->node);
400 SSLi_free(client->ssl);
401 close(client->tcpfd);
404 free(client->release);
406 free(client->os_version);
407 free(client->username);
408 free(client->context);
411 if (authenticatedLeft)
412 recheckCodecVersions(NULL); /* Can use better codec now? */
415 void Client_close(client_t *client)
417 SSLi_shutdown(client->ssl);
418 client->shutdown_wait = true;
421 void Client_disconnect_all()
423 struct dlist *itr, *save;
425 list_iterate_safe(itr, save, &clients) {
426 Client_free(list_get_entry(itr, client_t, node));
430 client_t *Client_find_by_fd(int fd)
434 list_iterate(itr, &clients) {
435 client_t *client = list_get_entry(itr, client_t, node);
437 if (client->tcpfd == fd) {
445 int Client_read_fd(int fd)
449 client = Client_find_by_fd(fd);
452 return Client_read(client);
457 int Client_read(client_t *client)
461 Timer_restart(&client->lastActivity);
463 if (client->writeBlockedOnRead) {
464 client->writeBlockedOnRead = false;
465 Log_debug("Client_read: writeBlockedOnRead == true");
466 return Client_write(client);
469 if (client->shutdown_wait) {
473 if (!client->SSLready) {
475 rc = SSLi_nonblockaccept(client->ssl, &client->SSLready);
484 if (!client->msgsize)
485 rc = SSLi_read(client->ssl, &client->rxbuf[client->rxcount], 6 - client->rxcount);
487 rc = SSLi_read(client->ssl, &client->rxbuf[client->rxcount], client->msgsize);
490 client->rxcount += rc;
491 if (!client->msgsize && client->rxcount >= 6) {
493 memcpy(&msgLen, &client->rxbuf[2], sizeof(uint32_t));
494 client->msgsize = ntohl(msgLen);
496 if (client->msgsize > BUFSIZE - 6) {
497 /* XXX - figure out how to handle this. A large size here can represent two cases:
498 * 1. A valid size. The only message that is this big is UserState message with a big texture
499 * 2. An invalid size = protocol error, e.g. connecting with a 1.1.x client
501 // Log_warn("Too big message received (%d bytes). Playing safe and disconnecting client %s:%d",
502 // client->msgsize, inet_ntoa(client->remote_tcp.sin_addr), ntohs(client->remote_tcp.sin_port));
505 /* client->rxcount = client->msgsize = 0; */
507 else if (client->rxcount == client->msgsize + 6) { /* Got all of the message */
508 msg = Msg_networkToMessage(client->rxbuf, client->msgsize + 6);
509 /* pass messsage to handler */
511 Mh_handle_message(client, msg);
512 client->rxcount = client->msgsize = 0;
514 } else /* rc <= 0 */ {
515 if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_WANT_READ) {
518 else if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_WANT_WRITE) {
519 client->readBlockedOnWrite = true;
522 else if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_ZERO_RETURN ||
523 SSLi_get_error(client->ssl, rc) == 0) {
524 Log_info_client(client, "Connection closed by peer");
525 Client_close(client);
528 if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_SYSCALL) {
530 Log_info_client(client, "Connection closed by peer");
532 Log_info_client(client,"Error: %s - Closing connection (code %d)",
535 else if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_CONNRESET) {
536 Log_info_client(client, "Connection reset by peer");
539 Log_info_client(client, "SSL error: %d - Closing connection", SSLi_get_error(client->ssl, rc));
545 } while (SSLi_data_pending(client->ssl));
550 int Client_write_fd(int fd)
554 client = Client_find_by_fd(fd);
557 return Client_write(client);
562 int Client_write(client_t *client)
566 if (client->readBlockedOnWrite) {
567 client->readBlockedOnWrite = false;
568 Log_debug("Client_write: readBlockedOnWrite == true");
569 return Client_read(client);
571 rc = SSLi_write(client->ssl, &client->txbuf[client->txcount], client->txsize - client->txcount);
573 client->txcount += rc;
574 if (client->txcount == client->txsize)
575 client->txsize = client->txcount = 0;
578 if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_WANT_READ) {
579 client->writeBlockedOnRead = true;
582 else if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_WANT_WRITE) {
586 if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_SYSCALL) {
587 Log_info_client(client, "Error: %s - Closing connection", strerror(errno));
589 else if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_CONNRESET) {
590 Log_info_client(client, "Connection reset by peer");
593 Log_info_client(client, "SSL error: %d - Closing connection.", SSLi_get_error(client->ssl, rc));
599 if (client->txsize == 0 && !list_empty(&client->txMsgQueue)) {
601 msg = list_get_entry(list_get_first(&client->txMsgQueue), message_t, node);
602 list_del(list_get_first(&client->txMsgQueue));
603 client->txQueueCount--;
604 Client_send_message(client, msg);
609 int Client_send_message_ver(client_t *client, message_t *msg, uint32_t version)
611 if ((version == 0) || (client->version >= version) ||
612 ((version & 0x80000000) && (client->version < (~version))))
613 return Client_send_message(client, msg);
619 int Client_send_message(client_t *client, message_t *msg)
621 if (!client->authenticated && msg->messageType != Version) {
625 if (client->txsize != 0 || !client->SSLready) {
627 if ((client->txQueueCount > 5 && msg->messageType == UDPTunnel) ||
628 client->txQueueCount > 30) {
632 client->txQueueCount++;
633 list_add_tail(&msg->node, &client->txMsgQueue);
634 Log_debug("Queueing message");
637 len = Msg_messageToNetwork(msg, client->txbuf);
638 doAssert(len < BUFSIZE);
640 client->txsize = len;
642 Client_write(client);
648 client_t *Client_iterate(client_t **client_itr)
650 client_t *c = *client_itr;
652 if (list_empty(&clients))
656 c = list_get_entry(list_get_first(&clients), client_t, node);
658 if (list_get_next(&c->node) == &clients)
661 c = list_get_entry(list_get_next(&c->node), client_t, node);
667 void Client_textmessage(client_t *client, char *text)
671 message_t *sendmsg = NULL;
673 message = Memory_safeMalloc(1, strlen(text) + 1);
674 tree_id = Memory_safeMalloc(1, sizeof(uint32_t));
676 sendmsg = Msg_create(TextMessage);
677 sendmsg->payload.textMessage->message = message;
678 sendmsg->payload.textMessage->n_tree_id = 1;
679 sendmsg->payload.textMessage->tree_id = tree_id;
680 strcpy(message, text);
681 Client_send_message(client, sendmsg);
685 int Client_send_message_except(client_t *client, message_t *msg)
687 client_t *itr = NULL;
689 while (Client_iterate(&itr) != NULL) {
691 Msg_inc_ref(msg); /* One extra reference for each new copy */
692 Log_debug("Msg %d to %s refcount %d", msg->messageType, itr->username, msg->refcount);
693 Client_send_message(itr, msg);
696 Msg_free(msg); /* Consume caller's reference. */
701 int Client_send_message_except_ver(client_t *client, message_t *msg, uint32_t version)
703 client_t *itr = NULL;
705 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_ver(itr, msg, version);
712 Msg_free(msg); /* Consume caller's reference. */
717 static bool_t checkDecrypt(client_t *client, const uint8_t *encrypted, uint8_t *plain, unsigned int len)
719 if (CryptState_isValid(&client->cryptState) &&
720 CryptState_decrypt(&client->cryptState, encrypted, plain, len))
723 if (Timer_elapsed(&client->cryptState.tLastGood) > 5000000ULL) {
724 if (Timer_elapsed(&client->cryptState.tLastRequest) > 5000000ULL) {
726 Timer_restart(&client->cryptState.tLastRequest);
728 sendmsg = Msg_create(CryptSetup);
729 Log_info_client(client, "Requesting voice channel crypt resync");
730 Client_send_message(client, sendmsg);
736 #define UDP_PACKET_SIZE 1024
737 int Client_read_udp(int udpsock)
740 struct sockaddr_storage from;
741 socklen_t fromlen = sizeof(struct sockaddr_storage);
742 uint8_t key[KEY_LENGTH];
744 UDPMessageType_t msgType;
745 uint8_t fromaddress[4 * sizeof(in_addr_t)];
748 #if defined(__LP64__)
749 uint8_t encbuff[UDP_PACKET_SIZE + 8];
750 uint8_t *encrypted = encbuff + 4;
752 uint8_t encrypted[UDP_PACKET_SIZE];
754 uint8_t buffer[UDP_PACKET_SIZE];
756 len = recvfrom(udpsock, encrypted, UDP_PACKET_SIZE, MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
758 memset(key, 0, KEY_LENGTH);
760 fromport = Util_addressToPort(&from);
762 if(from.ss_family == AF_INET) {
763 memcpy(fromaddress, &((struct sockaddr_in*)&from)->sin_addr, sizeof(in_addr_t));
764 memcpy(&key[0], &fromport, 2);
765 memcpy(&key[2], fromaddress, sizeof(in_addr_t));
767 memcpy(fromaddress, &((struct sockaddr_in6*)&from)->sin6_addr, 4 * sizeof(in_addr_t));
768 memcpy(&key[0], &fromport, 2);
769 memcpy(&key[2], fromaddress, 4 * sizeof(in_addr_t));
774 else if (len < 5 || len > UDP_PACKET_SIZE) /* 4 bytes crypt header + type + session */
778 * Reply to ping packet
779 * The second and third uint32_t are the timestamp, which will be returned unmodified
781 if (len == 12 && *encrypted == 0) {
782 uint32_t *ping = (uint32_t *)encrypted;
783 ping[0] = htonl((uint32_t)PROTOCOL_VERSION);
784 ping[3] = htonl((uint32_t)clientcount);
785 ping[4] = htonl((uint32_t)getIntConf(MAX_CLIENTS));
786 ping[5] = htonl((uint32_t)getIntConf(MAX_BANDWIDTH));
788 sendto(udpsock, encrypted, 6 * sizeof(uint32_t), 0, (struct sockaddr *)&from, fromlen);
794 while (Client_iterate(&itr) != NULL) {
795 if (memcmp(itr->key, key, KEY_LENGTH) == 0) {
796 if (!checkDecrypt(itr, encrypted, buffer, len))
801 if (itr == NULL) { /* Unknown peer */
802 struct sockaddr_storage itraddressstorage;
803 uint8_t itraddress[4 * sizeof(in_addr_t)];
806 while (Client_iterate(&itr) != NULL) {
807 itraddressstorage = itr->remote_tcp;
808 if(itraddressstorage.ss_family == AF_INET) {
809 memcpy(itraddress, &((struct sockaddr_in*)&from)->sin_addr, sizeof(in_addr_t));
810 addresslength = sizeof(in_addr_t);
812 memcpy(itraddress, &((struct sockaddr_in6*)&from)->sin6_addr, 4 * sizeof(in_addr_t));
813 addresslength = 4 * sizeof(in_addr_t);
816 if (memcmp(itraddress, fromaddress, addresslength) == 0) {
817 if (checkDecrypt(itr, encrypted, buffer, len)) {
818 memcpy(itr->key, key, KEY_LENGTH);
819 char* clientAddressString = Util_clientAddressToString(itr);
820 Log_info_client(itr, "New UDP connection from %s on port %d", clientAddressString, fromport);
821 free(clientAddressString);
822 memcpy(&itr->remote_udp, &from, sizeof(struct sockaddr_storage));
828 if (itr == NULL) { /* Couldn't find this peer among connected clients */
833 len -= 4; /* Adjust for crypt header */
834 msgType = (UDPMessageType_t)((buffer[0] >> 5) & 0x7);
836 char *clientAddressString = NULL;
840 case UDPVoiceCELTAlpha:
841 case UDPVoiceCELTBeta:
845 Client_voiceMsg(itr, buffer, len);
848 Log_debug("UDP Ping reply len %d", len);
849 Client_send_udp(itr, buffer, len);
852 clientAddressString = Util_clientAddressToString(itr);
853 Log_debug("Unknown UDP message type from %s port %d", clientAddressString, fromport);
854 free(clientAddressString);
862 static inline void Client_send_voice(client_t *src, client_t *dst, uint8_t *data, int len, int poslen)
864 if (IS_AUTH(dst) && dst != src && !dst->deaf && !dst->self_deaf) {
865 if (poslen > 0 && /* Has positional data */
866 src->context != NULL && dst->context != NULL && /* ...both source and destination has context */
867 strcmp(src->context, dst->context) == 0) /* ...and the contexts match */
868 Client_send_udp(dst, data, len);
870 Client_send_udp(dst, data, len - poslen);
874 /* Handle decrypted voice message */
875 int Client_voiceMsg(client_t *client, uint8_t *data, int len)
877 uint8_t buffer[UDP_PACKET_SIZE];
878 pds_t *pdi = Pds_create(data + 1, len - 1);
879 pds_t *pds = Pds_create(buffer + 1, UDP_PACKET_SIZE - 1);
880 unsigned int type = data[0] & 0xe0;
881 unsigned int target = data[0] & 0x1f;
882 unsigned int poslen, counter, size;
883 int offset, packetsize;
886 channel_t *ch = client->channel;
889 if (!client->authenticated || client->mute || client->self_mute || ch->silent)
892 packetsize = 20 + 8 + 4 + len;
893 if (client->availableBandwidth - packetsize < 0)
894 goto out; /* Discard */
895 client->availableBandwidth -= packetsize;
897 Timer_restart(&client->idleTime);
898 Timer_restart(&client->lastActivity);
900 counter = Pds_get_numval(pdi); /* step past session id */
901 if ((type >> 5) != UDPVoiceOpus) {
903 counter = Pds_next8(pdi);
904 offset = Pds_skip(pdi, counter & 0x7f);
905 } while ((counter & 0x80) && offset > 0);
907 size = Pds_get_numval(pdi);
908 Pds_skip(pdi, size & 0x1fff);
911 poslen = pdi->maxsize - pdi->offset; /* For stripping of positional info */
913 Pds_add_numval(pds, client->sessionId);
914 Pds_append_data_nosize(pds, data + 1, len - 1);
916 if (target == 0x1f) { /* Loopback */
917 buffer[0] = (uint8_t) type;
918 Client_send_udp(client, buffer, pds->offset + 1);
920 else if (target == 0) { /* regular channel speech */
921 buffer[0] = (uint8_t) type;
926 list_iterate(itr, &ch->clients) {
928 c = list_get_entry(itr, client_t, chan_node);
929 Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
931 } else if ((vt = Voicetarget_get_id(client, target)) != NULL) { /* Targeted whisper */
935 for (i = 0; i < TARGET_MAX_CHANNELS && vt->channels[i].channel != -1; i++) {
936 buffer[0] = (uint8_t) (type | 1);
937 Log_debug("Whisper channel %d", vt->channels[i]);
938 ch = Chan_fromId(vt->channels[i].channel);
941 list_iterate(itr, &ch->clients) {
943 c = list_get_entry(itr, client_t, chan_node);
944 Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
947 if (vt->channels[i].linked && !list_empty(&ch->channel_links)) {
948 struct dlist *ch_itr;
949 list_iterate(ch_itr, &ch->channel_links) {
952 chl = list_get_entry(ch_itr, channellist_t, node);
954 list_iterate(itr, &ch_link->clients) {
956 c = list_get_entry(itr, client_t, chan_node);
957 Log_debug("Linked voice from %s -> %s", ch->name, ch_link->name);
958 Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
963 if (vt->channels[i].children) {
964 struct dlist chanlist, *ch_itr;
965 init_list_entry(&chanlist);
966 Chan_buildTreeList(ch, &chanlist);
967 list_iterate(ch_itr, &chanlist) {
969 sub = list_get_entry(ch_itr, channellist_t, node)->chan;
970 list_iterate(itr, &sub->clients) {
972 c = list_get_entry(itr, client_t, chan_node);
973 Log_debug("Child voice from %s -> %s", ch->name, sub->name);
974 Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
977 Chan_freeTreeList(&chanlist);
981 for (i = 0; i < TARGET_MAX_SESSIONS && vt->sessions[i] != -1; i++) {
983 buffer[0] = (uint8_t) (type | 2);
984 Log_debug("Whisper session %d", vt->sessions[i]);
985 while (Client_iterate(&c) != NULL) {
986 if (c->sessionId == vt->sessions[i]) {
987 Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
1000 static int Client_send_udp(client_t *client, uint8_t *data, int len)
1002 uint8_t *buf, *mbuf;
1004 int udpsock = (client->remote_udp.ss_family == AF_INET) ? udpsocks[0] : udpsocks[(hasv4) ? 1 : 0];
1006 if (Util_clientAddressToPortUDP(client) != 0 && CryptState_isValid(&client->cryptState) &&
1008 #if defined(__LP64__)
1009 buf = mbuf = Memory_safeMalloc(1, len + 4 + 16);
1012 mbuf = buf = Memory_safeMalloc(1, len + 4);
1014 CryptState_encrypt(&client->cryptState, data, buf, len);
1016 #if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__APPLE__)
1017 sendto(udpsock, buf, len + 4, 0, (struct sockaddr *)&client->remote_udp, client->remote_tcp.ss_len);
1019 sendto(udpsock, buf, len + 4, 0, (struct sockaddr *)&client->remote_udp, sizeof(struct sockaddr_storage));
1025 msg = Msg_CreateVoiceMsg(data, len);
1026 Client_send_message(client, msg);