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