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