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