1c5972b688e6e741c07be4161c85dcf8289a9656
[umurmur.git] / src / client.c
1 /* Copyright (C) 2009-2014, Martin Johansson <martin@fatbob.nu>
2    Copyright (C) 2005-2014, Thorvald Natvig <thorvald@natvig.com>
3
4    All rights reserved.
5
6    Redistribution and use in source and binary forms, with or without
7    modification, are permitted provided that the following conditions
8    are met:
9
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.
18
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.
30    */
31 #include <sys/poll.h>
32 #include <sys/socket.h>
33 #include <fcntl.h>
34 #include <errno.h>
35 #include <limits.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include "log.h"
39 #include "list.h"
40 #include "client.h"
41 #include "ssl.h"
42 #include "messages.h"
43 #include "messagehandler.h"
44 #include "conf.h"
45 #include "channel.h"
46 #include "version.h"
47 #include "voicetarget.h"
48 #include "ban.h"
49 #include "util.h"
50
51 extern char system_string[], version_string[];
52
53 static int Client_read(client_t *client);
54 static int Client_write(client_t *client);
55 static int Client_send_udp(client_t *client, uint8_t *data, int len);
56 void Client_free(client_t *client);
57
58 declare_list(clients);
59 static int clientcount; /* = 0 */
60 static int maxBandwidth;
61 bool_t bOpus = true;
62
63 int iCodecAlpha, iCodecBeta;
64 bool_t bPreferAlpha;
65
66 extern int* udpsocks;
67 extern bool_t hasv4;
68
69 void Client_init()
70 {
71         maxBandwidth = getIntConf(MAX_BANDWIDTH) / 8; /* From bits/s -> bytes/s */
72 }
73
74 int Client_count()
75 {
76         return clientcount;
77 }
78
79 int Client_getfds(struct pollfd *pollfds)
80 {
81         struct dlist *itr;
82         int i = 0;
83         list_iterate(itr, &clients) {
84                 client_t *c;
85                 c = list_get_entry(itr, client_t, node);
86                 pollfds[i].fd = c->tcpfd;
87                 pollfds[i].events = POLLIN | POLLHUP | POLLERR;
88                 if (c->txsize > 0 || c->readBlockedOnWrite) /* Data waiting to be sent? */
89                         pollfds[i].events |= POLLOUT;
90                 i++;
91         }
92         return i;
93 }
94
95 void Client_janitor()
96 {
97         struct dlist *itr, *save;
98         int bwTop = maxBandwidth + maxBandwidth / 4;
99         list_iterate_safe(itr, save, &clients) {
100                 client_t *c;
101                 c = list_get_entry(itr, client_t, node);
102                 Log_debug("Client %s BW available %d", c->username, c->availableBandwidth);
103                 c->availableBandwidth += maxBandwidth;
104                 if (c->availableBandwidth > bwTop)
105                         c->availableBandwidth = bwTop;
106
107                 if (Timer_isElapsed(&c->lastActivity, 1000000LL * INACTIVITY_TIMEOUT)) {
108                         /* No activity from client - assume it is lost and close. */
109                         Log_info_client(c, "Timeout, closing.");
110                         Client_free(c);
111                 }
112         }
113         Ban_pruneBanned();
114 }
115
116 void Client_codec_add(client_t *client, int codec)
117 {
118         codec_t *cd = malloc(sizeof(codec_t));
119         if (cd == NULL)
120                 Log_fatal("Out of memory");
121         init_list_entry(&cd->node);
122         cd->codec = codec;
123         list_add_tail(&cd->node, &client->codecs);
124 }
125
126 void Client_codec_free(client_t *client)
127 {
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));
132         }
133 }
134
135 codec_t *Client_codec_iterate(client_t *client, codec_t **codec_itr)
136 {
137         codec_t *cd = *codec_itr;
138
139         if (list_empty(&client->codecs))
140                 return NULL;
141
142         if (cd == NULL) {
143                 cd = list_get_entry(list_get_first(&client->codecs), codec_t, node);
144         } else {
145                 if (list_get_next(&cd->node) == &client->codecs)
146                         cd = NULL;
147                 else
148                         cd = list_get_entry(list_get_next(&cd->node), codec_t, node);
149         }
150         *codec_itr = cd;
151         return cd;
152 }
153
154 void Client_token_add(client_t *client, char *token_string)
155 {
156         token_t *token;
157
158         if (client->tokencount >= MAX_TOKENS)
159                 return;
160         token = malloc(sizeof(token_t));
161         if (token == NULL)
162                 Log_fatal("Out of memory");
163         init_list_entry(&token->node);
164         token->token = strdup(token_string);
165         if (token->token == NULL)
166                 Log_fatal("Out of memory");
167         list_add_tail(&token->node, &client->tokens);
168         client->tokencount++;
169 }
170
171 bool_t Client_token_match(client_t *client, char const *str)
172 {
173         token_t *token;
174         struct dlist *itr;
175
176         if (list_empty(&client->tokens))
177                 return false;
178         list_iterate(itr, &client->tokens) {
179                 token = list_get_entry(itr, token_t, node);
180                 if (strncasecmp(token->token, str, MAX_TOKENSIZE) == 0)
181                         return true;
182         }
183         return false;
184 }
185
186 void Client_token_free(client_t *client)
187 {
188         struct dlist *itr, *save;
189         token_t *token;
190
191         list_iterate_safe(itr, save, &client->tokens) {
192                 token = list_get_entry(itr, token_t, node);
193                 list_del(&token->node);
194                 free(token->token);
195                 free(token);
196         }
197         client->tokencount = 0;
198 }
199
200
201 #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."
202 #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."
203 void recheckCodecVersions(client_t *connectingClient)
204 {
205         client_t *client_itr = NULL;
206         int max = 0, version, current_version;
207         int users = 0, opus = 0;
208         message_t *sendmsg;
209         struct dlist codec_list, *itr, *save;
210         codec_t *codec_itr, *cd;
211         bool_t found;
212         bool_t enableOpus;
213
214         init_list_entry(&codec_list);
215
216         while (Client_iterate(&client_itr) != NULL) {
217                 codec_itr = NULL;
218                 if (client_itr->codec_count == 0 && !client_itr->bOpus)
219                         continue;
220                 while (Client_codec_iterate(client_itr, &codec_itr) != NULL) {
221                         found = false;
222                         list_iterate(itr, &codec_list) {
223                                 cd = list_get_entry(itr, codec_t, node);
224                                 if (cd->codec == codec_itr->codec) {
225                                         cd->count++;
226                                         found = true;
227                                 }
228                         }
229                         if (!found) {
230                                 cd = malloc(sizeof(codec_t));
231                                 if (!cd)
232                                         Log_fatal("Out of memory");
233                                 memset(cd, 0, sizeof(codec_t));
234                                 init_list_entry(&cd->node);
235                                 cd->codec = codec_itr->codec;
236                                 cd->count = 1;
237                                 list_add_tail(&cd->node, &codec_list);
238                         }
239                 }
240                 users++;
241                 if (client_itr->bOpus)
242                         opus++;
243         }
244         if (users == 0)
245                 return;
246
247         enableOpus = ((opus * 100 / users) >= getIntConf(OPUS_THRESHOLD));
248
249         list_iterate(itr, &codec_list) {
250                 cd = list_get_entry(itr, codec_t, node);
251                 if (cd->count > max) {
252                         max = cd->count;
253                         version = cd->codec;
254                 }
255         }
256         list_iterate_safe(itr, save, &codec_list) {
257                 list_del(&list_get_entry(itr, codec_t, node)->node);
258                 free(list_get_entry(itr, codec_t, node));
259         }
260
261         current_version = bPreferAlpha ? iCodecAlpha : iCodecBeta;
262         if (current_version != version) {
263                 // If we don't already use the compat bitstream version set
264                 // it as alpha and announce it. If another codec now got the
265                 // majority set it as the opposite of the currently valid bPreferAlpha
266                 // and announce it.
267                 if (version == (uint32_t)0x8000000b)
268                         bPreferAlpha = true;
269                 else
270                         bPreferAlpha = !bPreferAlpha;
271
272                 if (bPreferAlpha)
273                         iCodecAlpha = version;
274                 else
275                         iCodecBeta = version;
276         } else if (bOpus && enableOpus) {
277                 if (connectingClient && !connectingClient->bOpus)
278                         Client_textmessage(connectingClient, OPUS_WARN_USING);
279                 return;
280         }
281
282         sendmsg = Msg_create(CodecVersion);
283         sendmsg->payload.codecVersion->alpha = iCodecAlpha;
284         sendmsg->payload.codecVersion->beta = iCodecBeta;
285         sendmsg->payload.codecVersion->prefer_alpha = bPreferAlpha;
286         sendmsg->payload.codecVersion->has_opus = true;
287         sendmsg->payload.codecVersion->opus = enableOpus;
288
289         Client_send_message_except(NULL, sendmsg);
290
291         if (enableOpus && !bOpus) {
292                 client_itr = NULL;
293                 while (Client_iterate(&client_itr) != NULL) {
294                         if ((client_itr->authenticated || client_itr == connectingClient) &&
295                                 !client_itr->bOpus) {
296                                 Client_textmessage(client_itr, OPUS_WARN_SWITCHING);
297                         }
298                 }
299                 Log_info("OPUS codec %s", bOpus ? "enabled" : "disabled");
300         }
301
302         bOpus = enableOpus;
303 }
304
305 static int findFreeSessionId()
306 {
307         int id;
308         client_t *itr = NULL;
309
310         for (id = 1; id < INT_MAX; id++) {
311                 itr = NULL;
312                 while ((itr = Client_iterate(&itr)) != NULL) {
313                         if (itr->sessionId == id)
314                                 break;
315                 }
316                 if (itr == NULL) /* Found free id */
317                         return id;
318         }
319         return -1;
320 }
321
322 int Client_add(int fd, struct sockaddr_storage *remote)
323 {
324         client_t* newclient;
325         message_t *sendmsg;
326         char* addressString = NULL;
327
328         if (Ban_isBannedAddr(remote)) {
329                 addressString = Util_addressToString(remote);
330                 Log_info("Address %s banned. Disconnecting", addressString);
331                 free(addressString);
332                 return -1;
333         }
334
335         if ((newclient = calloc(1, sizeof(client_t))) == NULL)
336                 Log_fatal("(%s:%s): Out of memory while allocating %d bytes.", __FILE__, __LINE__, sizeof(client_t));
337
338         newclient->tcpfd = fd;
339         memcpy(&newclient->remote_tcp, remote, sizeof(struct sockaddr_storage));
340         newclient->ssl = SSLi_newconnection(&newclient->tcpfd, &newclient->SSLready);
341         if (newclient->ssl == NULL) {
342                 addressString = Util_addressToString(remote);
343                 Log_warn("SSL negotiation failed with %s on port %d", addressString, Util_addressToPort(remote));
344                 free(addressString);
345                 free(newclient);
346                 return -1;
347         }
348         newclient->availableBandwidth = maxBandwidth;
349         Timer_init(&newclient->lastActivity);
350         Timer_init(&newclient->connectTime);
351         Timer_init(&newclient->idleTime);
352         newclient->sessionId = findFreeSessionId();
353         if (newclient->sessionId < 0)
354                 Log_fatal("Could not find a free session ID");
355
356         init_list_entry(&newclient->txMsgQueue);
357         init_list_entry(&newclient->chan_node);
358         init_list_entry(&newclient->node);
359         init_list_entry(&newclient->voicetargets);
360         init_list_entry(&newclient->codecs);
361         init_list_entry(&newclient->tokens);
362
363         list_add_tail(&newclient->node, &clients);
364         clientcount++;
365
366         /* Send version message to client */
367         sendmsg = Msg_create(Version);
368         sendmsg->payload.version->has_version = true;
369         sendmsg->payload.version->version = PROTOCOL_VERSION;
370         sendmsg->payload.version->release = strdup(UMURMUR_VERSION);
371         sendmsg->payload.version->os = strdup(system_string);
372         sendmsg->payload.version->os_version = strdup(version_string);
373         Client_send_message(newclient, sendmsg);
374
375         return 0;
376 }
377
378 void Client_free(client_t *client)
379 {
380         struct dlist *itr, *save;
381         message_t *sendmsg;
382         bool_t authenticatedLeft = client->authenticated;
383
384         if (client->authenticated) {
385                 int leave_id;
386                 leave_id = Chan_userLeave(client);
387                 if (leave_id > 0) { /* Remove temp channel */
388                         sendmsg = Msg_create(ChannelRemove);
389                         sendmsg->payload.channelRemove->channel_id = leave_id;
390                         Client_send_message_except(client, sendmsg);
391                 }
392                 sendmsg = Msg_create(UserRemove);
393                 sendmsg->payload.userRemove->session = client->sessionId;
394                 Client_send_message_except(client, sendmsg);
395         }
396         list_iterate_safe(itr, save, &client->txMsgQueue) {
397                 list_del(&list_get_entry(itr, message_t, node)->node);
398                 Msg_free(list_get_entry(itr, message_t, node));
399         }
400         Client_codec_free(client);
401         Voicetarget_free_all(client);
402         Client_token_free(client);
403
404         list_del(&client->node);
405         if (client->ssl)
406                 SSLi_free(client->ssl);
407         close(client->tcpfd);
408         clientcount--;
409         if (client->release)
410                 free(client->release);
411         if (client->os)
412                 free(client->os);
413         if (client->os_version)
414                 free(client->os_version);
415         if (client->username)
416                 free(client->username);
417         if (client->context)
418                 free(client->context);
419         free(client);
420
421         if (authenticatedLeft)
422                 recheckCodecVersions(NULL); /* Can use better codec now? */
423 }
424
425 void Client_close(client_t *client)
426 {
427         SSLi_shutdown(client->ssl);
428         client->shutdown_wait = true;
429 }
430
431 void Client_disconnect_all()
432 {
433         struct dlist *itr, *save;
434
435         list_iterate_safe(itr, save, &clients) {
436                 Client_free(list_get_entry(itr, client_t, node));
437         }
438 }
439
440 int Client_read_fd(int fd)
441 {
442         struct dlist *itr;
443         client_t *client = NULL;
444
445         list_iterate(itr, &clients) {
446                 if (fd == list_get_entry(itr, client_t, node)->tcpfd) {
447                         client = list_get_entry(itr, client_t, node);
448                         break;
449                 }
450         }
451         if (client != NULL)
452                 return Client_read(client);
453         else
454                 return -1;
455 }
456
457 int Client_read(client_t *client)
458 {
459         int rc;
460
461         Timer_restart(&client->lastActivity);
462
463         if (client->writeBlockedOnRead) {
464                 client->writeBlockedOnRead = false;
465                 Log_debug("Client_read: writeBlockedOnRead == true");
466                 return Client_write(client);
467         }
468
469         if (client->shutdown_wait) {
470                 Client_free(client);
471                 return 0;
472         }
473         if (!client->SSLready) {
474                 int rc;
475                 rc = SSLi_nonblockaccept(client->ssl, &client->SSLready);
476                 if (rc < 0) {
477                         Client_free(client);
478                         return -1;
479                 }
480         }
481
482         do {
483                 errno = 0;
484                 if (!client->msgsize)
485                         rc = SSLi_read(client->ssl, &client->rxbuf[client->rxcount], 6 - client->rxcount);
486                 else
487                         rc = SSLi_read(client->ssl, &client->rxbuf[client->rxcount], client->msgsize);
488                 if (rc > 0) {
489                         message_t *msg;
490                         client->rxcount += rc;
491                         if (!client->msgsize && client->rxcount >= 6) {
492                                 uint32_t msgLen;
493                                 memcpy(&msgLen, &client->rxbuf[2], sizeof(uint32_t));
494                                 client->msgsize = ntohl(msgLen);
495                         }
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
500                                  */
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));
503                                 Client_free(client);
504                                 return -1;
505                                 /* client->rxcount = client->msgsize = 0; */
506                         }
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 */
510                                 if (msg)
511                                         Mh_handle_message(client, msg);
512                                 client->rxcount = client->msgsize = 0;
513                         }
514                 } else /* rc <= 0 */ {
515                         if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_WANT_READ) {
516                                 return 0;
517                         }
518                         else if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_WANT_WRITE) {
519                                 client->readBlockedOnWrite = true;
520                                 return 0;
521                         }
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);
526                         }
527                         else {
528                                 if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_SYSCALL) {
529                                         if (errno == 0)
530                                                 Log_info_client(client, "Connection closed by peer");
531                                         else
532                                                 Log_info_client(client,"Error: %s  - Closing connection (code %d)",
533                                                         strerror(errno));
534                                 }
535                                 else if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_CONNRESET) {
536                                         Log_info_client(client, "Connection reset by peer");
537                                 }
538                                 else {
539                                         Log_info_client(client, "SSL error: %d - Closing connection", SSLi_get_error(client->ssl, rc));
540                                 }
541                                 Client_free(client);
542                                 return -1;
543                         }
544                 }
545         } while (SSLi_data_pending(client->ssl));
546
547         return 0;
548 }
549
550 int Client_write_fd(int fd)
551 {
552         struct dlist *itr;
553         client_t *client = NULL;
554
555         list_iterate(itr, &clients) {
556                 if(fd == list_get_entry(itr, client_t, node)->tcpfd) {
557                         client = list_get_entry(itr, client_t, node);
558                         break;
559                 }
560         }
561         if (client != NULL)
562                 return Client_write(client);
563         else
564                 return -1;
565 }
566
567 int Client_write(client_t *client)
568 {
569         int rc;
570
571         if (client->readBlockedOnWrite) {
572                 client->readBlockedOnWrite = false;
573                 Log_debug("Client_write: readBlockedOnWrite == true");
574                 return Client_read(client);
575         }
576         rc = SSLi_write(client->ssl, &client->txbuf[client->txcount], client->txsize - client->txcount);
577         if (rc > 0) {
578                 client->txcount += rc;
579                 if (client->txcount == client->txsize)
580                         client->txsize = client->txcount = 0;
581         }
582         else if (rc < 0) {
583                 if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_WANT_READ) {
584                         client->writeBlockedOnRead = true;
585                         return 0;
586                 }
587                 else if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_WANT_WRITE) {
588                         return 0;
589                 }
590                 else {
591                         if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_SYSCALL) {
592                                 Log_info_client(client, "Error: %s      - Closing connection", strerror(errno));
593                         }
594                         else if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_CONNRESET) {
595                                 Log_info_client(client, "Connection reset by peer");
596                         }
597                         else {
598                                 Log_info_client(client, "SSL error: %d - Closing connection.", SSLi_get_error(client->ssl, rc));
599                         }
600                         Client_free(client);
601                         return -1;
602                 }
603         }
604         if (client->txsize == 0 && !list_empty(&client->txMsgQueue)) {
605                 message_t *msg;
606                 msg = list_get_entry(list_get_first(&client->txMsgQueue), message_t, node);
607                 list_del(list_get_first(&client->txMsgQueue));
608                 client->txQueueCount--;
609                 Client_send_message(client, msg);
610         }
611         return 0;
612 }
613
614 int Client_send_message_ver(client_t *client, message_t *msg, uint32_t version)
615 {
616         if ((version == 0) || (client->version >= version) ||
617                 ((version & 0x80000000) && (client->version < (~version))))
618                 return Client_send_message(client, msg);
619         else
620                 Msg_free(msg);
621         return -1;
622 }
623
624 int Client_send_message(client_t *client, message_t *msg)
625 {
626         if (!client->authenticated && msg->messageType != Version) {
627                 Msg_free(msg);
628                 return 0;
629         }
630         if (client->txsize != 0 || !client->SSLready) {
631                 /* Queue message */
632                 if ((client->txQueueCount > 5 &&  msg->messageType == UDPTunnel) ||
633                         client->txQueueCount > 30) {
634                         Msg_free(msg);
635                         return -1;
636                 }
637                 client->txQueueCount++;
638                 list_add_tail(&msg->node, &client->txMsgQueue);
639                 Log_debug("Queueing message");
640         } else {
641                 int len;
642                 len = Msg_messageToNetwork(msg, client->txbuf);
643                 doAssert(len < BUFSIZE);
644
645                 client->txsize = len;
646                 client->txcount = 0;
647                 Client_write(client);
648                 Msg_free(msg);
649         }
650         return 0;
651 }
652
653 client_t *Client_iterate(client_t **client_itr)
654 {
655         client_t *c = *client_itr;
656
657         if (list_empty(&clients))
658                 return NULL;
659
660         if (c == NULL) {
661                 c = list_get_entry(list_get_first(&clients), client_t, node);
662         } else {
663                 if (list_get_next(&c->node) == &clients)
664                         c = NULL;
665                 else
666                         c = list_get_entry(list_get_next(&c->node), client_t, node);
667         }
668         *client_itr = c;
669         return c;
670 }
671
672 void Client_textmessage(client_t *client, char *text)
673 {
674         char *message;
675         uint32_t *tree_id;
676         message_t *sendmsg = NULL;
677
678         message = malloc(strlen(text) + 1);
679         if (!message)
680                 Log_fatal("Out of memory");
681         tree_id = malloc(sizeof(uint32_t));
682         if (!tree_id)
683                 Log_fatal("Out of memory");
684         *tree_id = 0;
685         sendmsg = Msg_create(TextMessage);
686         sendmsg->payload.textMessage->message = message;
687         sendmsg->payload.textMessage->n_tree_id = 1;
688         sendmsg->payload.textMessage->tree_id = tree_id;
689         strcpy(message, text);
690         Client_send_message(client, sendmsg);
691 }
692
693
694 int Client_send_message_except(client_t *client, message_t *msg)
695 {
696         client_t *itr = NULL;
697         int count = 0;
698
699         Msg_inc_ref(msg); /* Make sure a reference is held during the whole iteration. */
700         while (Client_iterate(&itr) != NULL) {
701                 if (itr != client) {
702                         if (count++ > 0)
703                                 Msg_inc_ref(msg); /* One extra reference for each new copy */
704                         Log_debug("Msg %d to %s refcount %d",  msg->messageType, itr->username, msg->refcount);
705                         Client_send_message(itr, msg);
706                 }
707         }
708         Msg_free(msg); /* Free our reference to the message */
709
710         if (count == 0)
711                 Msg_free(msg); /* If only 1 client is connected then no message is passed
712                                                 * to Client_send_message(). Free it here. */
713
714         return 0;
715 }
716
717 int Client_send_message_except_ver(client_t *client, message_t *msg, uint32_t version)
718 {
719         client_t *itr = NULL;
720         int count = 0;
721
722         Msg_inc_ref(msg); /* Make sure a reference is held during the whole iteration. */
723         while (Client_iterate(&itr) != NULL) {
724                 if (itr != client) {
725                         if (count++ > 0)
726                                 Msg_inc_ref(msg); /* One extra reference for each new copy */
727                         Log_debug("Msg %d to %s refcount %d",  msg->messageType, itr->username, msg->refcount);
728                         Client_send_message_ver(itr, msg, version);
729                 }
730         }
731         Msg_free(msg); /* Free our reference to the message */
732
733         if (count == 0)
734                 Msg_free(msg); /* If only 1 client is connected then no message is passed
735                                                 * to Client_send_message(). Free it here. */
736
737         return 0;
738 }
739
740 static bool_t checkDecrypt(client_t *client, const uint8_t *encrypted, uint8_t *plain, unsigned int len)
741 {
742         if (CryptState_isValid(&client->cryptState) &&
743                 CryptState_decrypt(&client->cryptState, encrypted, plain, len))
744                 return true;
745
746         if (Timer_elapsed(&client->cryptState.tLastGood) > 5000000ULL) {
747                 if (Timer_elapsed(&client->cryptState.tLastRequest) > 5000000ULL) {
748                         message_t *sendmsg;
749                         Timer_restart(&client->cryptState.tLastRequest);
750
751                         sendmsg = Msg_create(CryptSetup);
752                         Log_info_client(client, "Requesting voice channel crypt resync");
753                         Client_send_message(client, sendmsg);
754                 }
755         }
756         return false;
757 }
758
759 #define UDP_PACKET_SIZE 1024
760 int Client_read_udp(int udpsock)
761 {
762         int len;
763         struct sockaddr_storage from;
764         socklen_t fromlen = sizeof(struct sockaddr_storage);
765         uint8_t key[KEY_LENGTH];
766         client_t *itr;
767         UDPMessageType_t msgType;
768         uint8_t fromaddress[4 * sizeof(in_addr_t)];
769         uint16_t fromport;
770
771 #if defined(__LP64__)
772         uint8_t encbuff[UDP_PACKET_SIZE + 8];
773         uint8_t *encrypted = encbuff + 4;
774 #else
775         uint8_t encrypted[UDP_PACKET_SIZE];
776 #endif
777         uint8_t buffer[UDP_PACKET_SIZE];
778
779         len = recvfrom(udpsock, encrypted, UDP_PACKET_SIZE, MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
780
781         memset(key, 0, KEY_LENGTH);
782
783         fromport = Util_addressToPort(&from);
784
785         if(from.ss_family == AF_INET) {
786                 memcpy(fromaddress, &((struct sockaddr_in*)&from)->sin_addr, sizeof(in_addr_t));
787                 memcpy(&key[0], &fromport, 2);
788                 memcpy(&key[2], fromaddress, sizeof(in_addr_t));
789         } else {
790                 memcpy(fromaddress, &((struct sockaddr_in6*)&from)->sin6_addr, 4 * sizeof(in_addr_t));
791                 memcpy(&key[0], &fromport, 2);
792                 memcpy(&key[2], fromaddress, 4 * sizeof(in_addr_t));
793         }
794
795         if (len <= 0)
796                 return -1;
797         else if (len < 5 || len > UDP_PACKET_SIZE) /* 4 bytes crypt header + type + session */
798                 return 0;
799
800         /*
801          * Reply to ping packet
802          * The second and third uint32_t are the timestamp, which will be returned unmodified
803          */
804         if (len == 12 && *encrypted == 0) {
805                 uint32_t *ping = (uint32_t *)encrypted;
806                 ping[0] = htonl((uint32_t)PROTOCOL_VERSION);
807                 ping[3] = htonl((uint32_t)clientcount);
808                 ping[4] = htonl((uint32_t)getIntConf(MAX_CLIENTS));
809                 ping[5] = htonl((uint32_t)getIntConf(MAX_BANDWIDTH));
810
811                 sendto(udpsock, encrypted, 6 * sizeof(uint32_t), 0, (struct sockaddr *)&from, fromlen);
812                 return 0;
813         }
814
815         itr = NULL;
816
817         while (Client_iterate(&itr) != NULL) {
818                 if (memcmp(itr->key, key, KEY_LENGTH) == 0) {
819                         if (!checkDecrypt(itr, encrypted, buffer, len))
820                                 goto out;
821                         break;
822                 }
823         }
824         if (itr == NULL) { /* Unknown peer */
825                 struct sockaddr_storage itraddressstorage;
826                 uint8_t itraddress[4 * sizeof(in_addr_t)];
827                 int addresslength;
828
829                 while (Client_iterate(&itr) != NULL) {
830                         itraddressstorage = itr->remote_tcp;
831                         if(itraddressstorage.ss_family == AF_INET) {
832                                 memcpy(itraddress, &((struct sockaddr_in*)&from)->sin_addr, sizeof(in_addr_t));
833                                 addresslength = sizeof(in_addr_t);
834                         } else {
835                                 memcpy(itraddress, &((struct sockaddr_in6*)&from)->sin6_addr, 4 * sizeof(in_addr_t));
836                                 addresslength = 4 * sizeof(in_addr_t);
837                         }
838
839                         if (memcmp(itraddress, fromaddress, addresslength) == 0) {
840                                 if (checkDecrypt(itr, encrypted, buffer, len)) {
841                                         memcpy(itr->key, key, KEY_LENGTH);
842                                         char* clientAddressString = Util_clientAddressToString(itr);
843                                         Log_info_client(itr, "New UDP connection from %s on port %d", clientAddressString, fromport);
844                                         free(clientAddressString);
845                                         memcpy(&itr->remote_udp, &from, sizeof(struct sockaddr_storage));
846                                         break;
847                                 }
848                         }
849                 } /* while */
850         }
851         if (itr == NULL) { /* Couldn't find this peer among connected clients */
852                 goto out;
853         }
854
855         itr->bUDP = true;
856         len -= 4; /* Adjust for crypt header */
857         msgType = (UDPMessageType_t)((buffer[0] >> 5) & 0x7);
858
859         char *clientAddressString = NULL;
860
861         switch (msgType) {
862                 case UDPVoiceSpeex:
863                 case UDPVoiceCELTAlpha:
864                 case UDPVoiceCELTBeta:
865                         if (bOpus)
866                                 break;
867                 case UDPVoiceOpus:
868                         Client_voiceMsg(itr, buffer, len);
869                         break;
870                 case UDPPing:
871                         Log_debug("UDP Ping reply len %d", len);
872                         Client_send_udp(itr, buffer, len);
873                         break;
874                 default:
875                         clientAddressString = Util_clientAddressToString(itr);
876                         Log_debug("Unknown UDP message type from %s port %d", clientAddressString, fromport);
877                         free(clientAddressString);
878                         break;
879         }
880
881 out:
882         return 0;
883 }
884
885 static inline void Client_send_voice(client_t *src, client_t *dst, uint8_t *data, int len, int poslen)
886 {
887         if (IS_AUTH(dst) && dst != src && !dst->deaf && !dst->self_deaf) {
888                 if (poslen > 0 && /* Has positional data */
889                         src->context != NULL && dst->context != NULL && /* ...both source and destination has context */
890                         strcmp(src->context, dst->context) == 0) /* ...and the contexts match */
891                         Client_send_udp(dst, data, len);
892                 else
893                         Client_send_udp(dst, data, len - poslen);
894         }
895 }
896
897 /* Handle decrypted voice message */
898 int Client_voiceMsg(client_t *client, uint8_t *data, int len)
899 {
900         uint8_t buffer[UDP_PACKET_SIZE];
901         pds_t *pdi = Pds_create(data + 1, len - 1);
902         pds_t *pds = Pds_create(buffer + 1, UDP_PACKET_SIZE - 1);
903         unsigned int type = data[0] & 0xe0;
904         unsigned int target = data[0] & 0x1f;
905         unsigned int poslen, counter, size;
906         int offset, packetsize;
907         voicetarget_t *vt;
908
909         channel_t *ch = (channel_t *)client->channel;
910         struct dlist *itr;
911
912         if (!client->authenticated || client->mute || client->self_mute || ch->silent)
913                 goto out;
914
915         packetsize = 20 + 8 + 4 + len;
916         if (client->availableBandwidth - packetsize < 0)
917                 goto out; /* Discard */
918         client->availableBandwidth -= packetsize;
919
920         Timer_restart(&client->idleTime);
921         Timer_restart(&client->lastActivity);
922
923         counter = Pds_get_numval(pdi); /* step past session id */
924         if ((type >> 5) != UDPVoiceOpus) {
925                 do {
926                         counter = Pds_next8(pdi);
927                         offset = Pds_skip(pdi, counter & 0x7f);
928                 } while ((counter & 0x80) && offset > 0);
929         } else {
930                 size = Pds_get_numval(pdi);
931                 Pds_skip(pdi, size & 0x1fff);
932         }
933
934         poslen = pdi->maxsize - pdi->offset; /* For stripping of positional info */
935
936         Pds_add_numval(pds, client->sessionId);
937         Pds_append_data_nosize(pds, data + 1, len - 1);
938
939         if (target == 0x1f) { /* Loopback */
940                 buffer[0] = (uint8_t) type;
941                 Client_send_udp(client, buffer, pds->offset + 1);
942         }
943         else if (target == 0) { /* regular channel speech */
944                 buffer[0] = (uint8_t) type;
945
946                 if (ch == NULL)
947                         goto out;
948
949                 list_iterate(itr, &ch->clients) {
950                         client_t *c;
951                         c = list_get_entry(itr, client_t, chan_node);
952                         Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
953                 }
954         } else if ((vt = Voicetarget_get_id(client, target)) != NULL) { /* Targeted whisper */
955                 int i;
956                 channel_t *ch;
957                 /* Channels */
958                 for (i = 0; i < TARGET_MAX_CHANNELS && vt->channels[i].channel != -1; i++) {
959                         buffer[0] = (uint8_t) (type | 1);
960                         Log_debug("Whisper channel %d", vt->channels[i]);
961                         ch = Chan_fromId(vt->channels[i].channel);
962                         if (ch == NULL)
963                                 continue;
964                         list_iterate(itr, &ch->clients) {
965                                 client_t *c;
966                                 c = list_get_entry(itr, client_t, chan_node);
967                                 Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
968                         }
969                         /* Channel links */
970                         if (vt->channels[i].linked && !list_empty(&ch->channel_links)) {
971                                 struct dlist *ch_itr;
972                                 list_iterate(ch_itr, &ch->channel_links) {
973                                         channellist_t *chl;
974                                         channel_t *ch_link;
975                                         chl = list_get_entry(ch_itr, channellist_t, node);
976                                         ch_link = chl->chan;
977                                         list_iterate(itr, &ch_link->clients) {
978                                                 client_t *c;
979                                                 c = list_get_entry(itr, client_t, chan_node);
980                                                 Log_debug("Linked voice from %s -> %s", ch->name, ch_link->name);
981                                                 Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
982                                         }
983                                 }
984                         }
985                         /* children */
986                         if (vt->channels[i].children) {
987                                 struct dlist chanlist, *ch_itr;
988                                 init_list_entry(&chanlist);
989                                 Chan_buildTreeList(ch, &chanlist);
990                                 list_iterate(ch_itr, &chanlist) {
991                                         channel_t *sub;
992                                         sub = list_get_entry(ch_itr, channellist_t, node)->chan;
993                                         list_iterate(itr, &sub->clients) {
994                                                 client_t *c;
995                                                 c = list_get_entry(itr, client_t, chan_node);
996                                                 Log_debug("Child voice from %s -> %s", ch->name, sub->name);
997                                                 Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
998                                         }
999                                 }
1000                                 Chan_freeTreeList(&chanlist);
1001                         }
1002                 }
1003                 /* Sessions */
1004                 for (i = 0; i < TARGET_MAX_SESSIONS && vt->sessions[i] != -1; i++) {
1005                         client_t *c;
1006                         buffer[0] = (uint8_t) (type | 2);
1007                         Log_debug("Whisper session %d", vt->sessions[i]);
1008                         while (Client_iterate(&c) != NULL) {
1009                                 if (c->sessionId == vt->sessions[i]) {
1010                                         Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
1011                                         break;
1012                                 }
1013                         }
1014                 }
1015         }
1016 out:
1017         Pds_free(pds);
1018         Pds_free(pdi);
1019
1020         return 0;
1021 }
1022
1023 static int Client_send_udp(client_t *client, uint8_t *data, int len)
1024 {
1025         uint8_t *buf, *mbuf;
1026
1027         int udpsock = (client->remote_udp.ss_family == AF_INET) ? udpsocks[0] : udpsocks[(hasv4) ? 1 : 0];
1028
1029         if (Util_clientAddressToPortUDP(client) != 0 && CryptState_isValid(&client->cryptState) &&
1030                 client->bUDP) {
1031 #if defined(__LP64__)
1032                 buf = mbuf = malloc(len + 4 + 16);
1033                 buf += 4;
1034 #else
1035                 mbuf = buf = malloc(len + 4);
1036 #endif
1037                 if (mbuf == NULL)
1038                         Log_fatal("Out of memory");
1039
1040                 CryptState_encrypt(&client->cryptState, data, buf, len);
1041
1042 #if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__APPLE__)
1043                         sendto(udpsock, buf, len + 4, 0, (struct sockaddr *)&client->remote_udp, client->remote_tcp.ss_len);
1044 #else
1045                         sendto(udpsock, buf, len + 4, 0, (struct sockaddr *)&client->remote_udp, sizeof(struct sockaddr_storage));
1046 #endif
1047
1048                 free(mbuf);
1049         } else {
1050                 message_t *msg;
1051                 msg = Msg_CreateVoiceMsg(data, len);
1052                 Client_send_message(client, msg);
1053         }
1054         return 0;
1055 }