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