Add silent channel option
[umurmur.git] / src / client.c
1 /* Copyright (C) 2009-2013, Martin Johansson <martin@fatbob.nu>
2    Copyright (C) 2005-2013, 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 udpsock;
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_in *remote)
321 {
322         client_t *newclient;
323         message_t *sendmsg;
324
325         if (Ban_isBannedAddr((in_addr_t *)&remote->sin_addr)) {
326                 Log_info("Address %s banned. Disconnecting", inet_ntoa(remote->sin_addr));
327                 return -1;
328         }
329         newclient = malloc(sizeof(client_t));
330         if (newclient == NULL)
331                 Log_fatal("Out of memory");
332         memset(newclient, 0, sizeof(client_t));
333
334         newclient->tcpfd = fd;
335         memcpy(&newclient->remote_tcp, remote, sizeof(struct sockaddr_in));
336         newclient->ssl = SSLi_newconnection(&newclient->tcpfd, &newclient->SSLready);
337         if (newclient->ssl == NULL) {
338                 Log_warn("SSL negotiation failed with %s:%d", inet_ntoa(remote->sin_addr),
339                                  ntohs(remote->sin_port));
340                 free(newclient);
341                 return -1;
342         }
343         newclient->availableBandwidth = maxBandwidth;
344         Timer_init(&newclient->lastActivity);
345         Timer_init(&newclient->connectTime);
346         Timer_init(&newclient->idleTime);
347         newclient->sessionId = findFreeSessionId();
348         if (newclient->sessionId < 0)
349                 Log_fatal("Could not find a free session ID");
350         
351         init_list_entry(&newclient->txMsgQueue);
352         init_list_entry(&newclient->chan_node);
353         init_list_entry(&newclient->node);
354         init_list_entry(&newclient->voicetargets);
355         init_list_entry(&newclient->codecs);
356         init_list_entry(&newclient->tokens);
357         
358         list_add_tail(&newclient->node, &clients);
359         clientcount++;
360         
361         /* Send version message to client */
362         sendmsg = Msg_create(Version);
363         sendmsg->payload.version->has_version = true;
364         sendmsg->payload.version->version = PROTOCOL_VERSION;
365         sendmsg->payload.version->release = strdup(UMURMUR_VERSION);
366         sendmsg->payload.version->os = strdup(system_string);
367         sendmsg->payload.version->os_version = strdup(version_string);
368         Client_send_message(newclient, sendmsg);
369
370         return 0;
371 }
372
373 void Client_free(client_t *client)
374 {
375         struct dlist *itr, *save;
376         message_t *sendmsg;
377         bool_t authenticatedLeft = client->authenticated;
378
379         if (client->authenticated) {
380                 int leave_id;
381                 leave_id = Chan_userLeave(client);
382                 if (leave_id > 0) { /* Remove temp channel */
383                         sendmsg = Msg_create(ChannelRemove);
384                         sendmsg->payload.channelRemove->channel_id = leave_id;
385                         Client_send_message_except(client, sendmsg);
386                 }
387                 sendmsg = Msg_create(UserRemove);
388                 sendmsg->payload.userRemove->session = client->sessionId;
389                 Client_send_message_except(client, sendmsg);
390         }
391         list_iterate_safe(itr, save, &client->txMsgQueue) {
392                 list_del(&list_get_entry(itr, message_t, node)->node);
393                 Msg_free(list_get_entry(itr, message_t, node));
394         }
395         Client_codec_free(client);
396         Voicetarget_free_all(client);
397         Client_token_free(client);
398         
399         list_del(&client->node);
400         if (client->ssl)
401                 SSLi_free(client->ssl);
402         close(client->tcpfd);
403         clientcount--;
404         if (client->release)
405                 free(client->release);
406         if (client->os)
407                 free(client->os);                       
408         if (client->os_version)
409                 free(client->os_version);                       
410         if (client->username)
411                 free(client->username);
412         if (client->context)
413                 free(client->context);
414         free(client);
415
416         if (authenticatedLeft)
417                 recheckCodecVersions(NULL); /* Can use better codec now? */
418 }
419
420 void Client_close(client_t *client)
421 {
422         SSLi_shutdown(client->ssl);
423         client->shutdown_wait = true;
424 }
425
426 void Client_disconnect_all()
427 {
428         struct dlist *itr, *save;
429         
430         list_iterate_safe(itr, save, &clients) {
431                 Client_free(list_get_entry(itr, client_t, node));
432         }
433 }
434
435 int Client_read_fd(int fd)
436 {
437         struct dlist *itr;
438         client_t *client = NULL;
439         
440         list_iterate(itr, &clients) {
441                 if (fd == list_get_entry(itr, client_t, node)->tcpfd) {
442                         client = list_get_entry(itr, client_t, node);
443                         break;
444                 }
445         }
446         if (client != NULL)
447                 return Client_read(client);
448         else
449                 return -1;
450 }
451
452 int Client_read(client_t *client)
453 {
454         int rc;
455
456         Timer_restart(&client->lastActivity);
457         
458         if (client->writeBlockedOnRead) {
459                 client->writeBlockedOnRead = false;
460                 Log_debug("Client_read: writeBlockedOnRead == true");
461                 return Client_write(client);
462         }
463         
464         if (client->shutdown_wait) {
465                 Client_free(client);
466                 return 0;
467         }
468         if (!client->SSLready) {
469                 int rc;
470                 rc = SSLi_nonblockaccept(client->ssl, &client->SSLready);
471                 if (rc < 0) {
472                         Client_free(client);
473                         return -1;
474                 }
475         }
476
477         do {
478                 errno = 0;
479                 if (!client->msgsize) 
480                         rc = SSLi_read(client->ssl, &client->rxbuf[client->rxcount], 6 - client->rxcount);
481                 else
482                         rc = SSLi_read(client->ssl, &client->rxbuf[client->rxcount], client->msgsize);
483                 if (rc > 0) {
484                         message_t *msg;
485                         client->rxcount += rc;
486                         if (!client->msgsize && client->rxcount >= 6) {
487                                 uint32_t msgLen;
488                                 memcpy(&msgLen, &client->rxbuf[2], sizeof(uint32_t));
489                                 client->msgsize = ntohl(msgLen);
490                         }
491                         if (client->msgsize > BUFSIZE - 6) {
492                                 /* XXX - figure out how to handle this. A large size here can represent two cases:
493                                  * 1. A valid size. The only message that is this big is UserState message with a big texture
494                                  * 2. An invalid size = protocol error, e.g. connecting with a 1.1.x client
495                                  */
496                                 Log_warn("Too big message received (%d bytes). Playing safe and disconnecting client %s:%d",
497                                                  client->msgsize, inet_ntoa(client->remote_tcp.sin_addr), ntohs(client->remote_tcp.sin_port));
498                                 Client_free(client);
499                                 return -1;
500                                 /* client->rxcount = client->msgsize = 0; */
501                         }
502                         else if (client->rxcount == client->msgsize + 6) { /* Got all of the message */
503                                 msg = Msg_networkToMessage(client->rxbuf, client->msgsize + 6);
504                                 /* pass messsage to handler */
505                                 if (msg)
506                                         Mh_handle_message(client, msg);
507                                 client->rxcount = client->msgsize = 0;
508                         }
509                 } else /* rc <= 0 */ {
510                         if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_WANT_READ) {
511                                 return 0;
512                         }
513                         else if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_WANT_WRITE) {
514                                 client->readBlockedOnWrite = true;
515                                 return 0;
516                         }
517                         else if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_ZERO_RETURN || 
518                                  SSLi_get_error(client->ssl, rc) == 0) {
519                                 Log_info_client(client, "Connection closed by peer");
520                                 Client_close(client);
521                         }
522                         else {
523                                 if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_SYSCALL) {
524                                         if (errno == 0)
525                                                 Log_info_client(client, "Connection closed by peer");
526                                         else
527                                                 Log_info_client(client,"Error: %s  - Closing connection (code %d)", 
528                                                                 strerror(errno));
529                                 }
530                                 else if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_CONNRESET) {
531                                         Log_info_client(client, "Connection reset by peer");
532                                 }
533                                 else {
534                                         Log_info_client(client, "SSL error: %d - Closing connection", SSLi_get_error(client->ssl, rc));
535                                 }
536                                 Client_free(client);
537                                 return -1;
538                         }
539                 }
540         } while (SSLi_data_pending(client->ssl));
541         
542         return 0;
543 }
544
545 int Client_write_fd(int fd)
546 {
547         struct dlist *itr;
548         client_t *client = NULL;
549         
550         list_iterate(itr, &clients) {
551                 if(fd == list_get_entry(itr, client_t, node)->tcpfd) {
552                         client = list_get_entry(itr, client_t, node);
553                         break;
554                 }
555         }
556         if (client != NULL)
557                 return Client_write(client);
558         else
559                 return -1;
560 }
561
562 int Client_write(client_t *client)
563 {
564         int rc;
565         
566         if (client->readBlockedOnWrite) {
567                 client->readBlockedOnWrite = false;
568                 Log_debug("Client_write: readBlockedOnWrite == true");
569                 return Client_read(client);
570         }
571         rc = SSLi_write(client->ssl, &client->txbuf[client->txcount], client->txsize - client->txcount);
572         if (rc > 0) {
573                 client->txcount += rc;
574                 if (client->txcount == client->txsize)
575                         client->txsize = client->txcount = 0;
576         }
577         else if (rc < 0) {
578                 if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_WANT_READ) {
579                         client->writeBlockedOnRead = true;
580                         return 0;
581                 }
582                 else if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_WANT_WRITE) {
583                         return 0;
584                 }
585                 else {
586                         if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_SYSCALL) {
587                                 Log_info_client(client, "Error: %s  - Closing connection", strerror(errno));
588                         }
589                         else if (SSLi_get_error(client->ssl, rc) == SSLI_ERROR_CONNRESET) {
590                                 Log_info_client(client, "Connection reset by peer");
591                         }
592                         else {
593                                 Log_info_client(client, "SSL error: %d - Closing connection.", SSLi_get_error(client->ssl, rc));
594                         }
595                         Client_free(client);
596                         return -1;
597                 }
598         }
599         if (client->txsize == 0 && !list_empty(&client->txMsgQueue)) {
600                 message_t *msg;
601                 msg = list_get_entry(list_get_first(&client->txMsgQueue), message_t, node);
602                 list_del(list_get_first(&client->txMsgQueue));
603                 client->txQueueCount--;
604                 Client_send_message(client, msg);
605         }
606         return 0;
607 }
608
609 int Client_send_message_ver(client_t *client, message_t *msg, uint32_t version)
610 {
611         if ((version == 0) || (client->version >= version) ||
612                 ((version & 0x80000000) && (client->version < (~version))))
613                 return Client_send_message(client, msg);
614         else
615                 Msg_free(msg);
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()
755 {
756         int len;
757         struct sockaddr_in from;
758         socklen_t fromlen = sizeof(struct sockaddr_in);
759         uint64_t key;
760         client_t *itr;
761         UDPMessageType_t msgType;
762         
763 #if defined(__LP64__)
764         uint8_t encbuff[UDP_PACKET_SIZE + 8];
765         uint8_t *encrypted = encbuff + 4;
766 #else
767         uint8_t encrypted[UDP_PACKET_SIZE];
768 #endif
769         uint8_t buffer[UDP_PACKET_SIZE];
770         
771         len = recvfrom(udpsock, encrypted, UDP_PACKET_SIZE, MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
772         if (len == 0) {
773                 return -1;
774         } else if (len < 0) {
775                 return -1;
776         } else if (len < 5) {
777                 // 4 bytes crypt header + type + session
778                 return 0;
779         } else if (len > UDP_PACKET_SIZE) {
780                 return 0;
781         }
782
783         /* Ping packet */
784         if (len == 12 && *encrypted == 0) {
785                 uint32_t *ping = (uint32_t *)encrypted;
786                 ping[0] = htonl((uint32_t)PROTOCOL_VERSION);
787                 // 1 and 2 will be the timestamp, which we return unmodified.
788                 ping[3] = htonl((uint32_t)clientcount);
789                 ping[4] = htonl((uint32_t)getIntConf(MAX_CLIENTS));
790                 ping[5] = htonl((uint32_t)getIntConf(MAX_BANDWIDTH));
791                 
792                 sendto(udpsock, encrypted, 6 * sizeof(uint32_t), 0, (struct sockaddr *)&from, fromlen);
793                 return 0;
794         }
795         
796         key = (((uint64_t)from.sin_addr.s_addr) << 16) ^ from.sin_port;
797         itr = NULL;
798         
799         while (Client_iterate(&itr) != NULL) {
800                 if (itr->key == key) {
801                         if (!checkDecrypt(itr, encrypted, buffer, len))
802                                 goto out;
803                         break;
804                 }
805         }       
806         if (itr == NULL) { /* Unknown peer */
807                 while (Client_iterate(&itr) != NULL) {
808                         if (itr->remote_tcp.sin_addr.s_addr == from.sin_addr.s_addr) {
809                                 if (checkDecrypt(itr, encrypted, buffer, len)) {
810                                         itr->key = key;
811                                         Log_info_client(itr, "New UDP connection port %d", ntohs(from.sin_port));
812                                         memcpy(&itr->remote_udp, &from, sizeof(struct sockaddr_in));
813                                         break;
814                                 }
815                         }
816                 } /* while */
817         }
818         if (itr == NULL) { /* Couldn't find this peer among connected clients */
819                 goto out;
820         }
821         
822         itr->bUDP = true;
823         len -= 4; /* Adjust for crypt header */
824         msgType = (UDPMessageType_t)((buffer[0] >> 5) & 0x7);
825         switch (msgType) {
826         case UDPVoiceSpeex:
827         case UDPVoiceCELTAlpha:
828         case UDPVoiceCELTBeta:
829                 if (bOpus)
830                         break;
831         case UDPVoiceOpus:
832                 Client_voiceMsg(itr, buffer, len);
833                 break;
834         case UDPPing:
835                 Log_debug("UDP Ping reply len %d", len);
836                 Client_send_udp(itr, buffer, len);
837                 break;
838         default:
839                 Log_debug("Unknown UDP message type from %s port %d", inet_ntoa(from.sin_addr), ntohs(from.sin_port));
840                 break;
841         }
842         
843 out:
844         return 0;
845 }
846
847 static inline void Client_send_voice(client_t *src, client_t *dst, uint8_t *data, int len, int poslen)
848 {
849         if (IS_AUTH(dst) && dst != src && !dst->deaf && !dst->self_deaf) {
850                 if (poslen > 0 && /* Has positional data */
851                         src->context != NULL && dst->context != NULL && /* ...both source and destination has context */
852                         strcmp(src->context, dst->context) == 0) /* ...and the contexts match */
853                         Client_send_udp(dst, data, len);
854                 else 
855                         Client_send_udp(dst, data, len - poslen);
856         }
857 }
858
859 /* Handle decrypted voice message */
860 int Client_voiceMsg(client_t *client, uint8_t *data, int len)
861 {
862         uint8_t buffer[UDP_PACKET_SIZE];
863         pds_t *pdi = Pds_create(data + 1, len - 1);
864         pds_t *pds = Pds_create(buffer + 1, UDP_PACKET_SIZE - 1);
865         unsigned int type = data[0] & 0xe0;
866         unsigned int target = data[0] & 0x1f;
867         unsigned int poslen, counter, size;
868         int offset, packetsize;
869         voicetarget_t *vt;
870         
871         channel_t *ch = (channel_t *)client->channel;
872         struct dlist *itr;
873         
874         if (!client->authenticated || client->mute || client->self_mute || ch->silent)
875                 goto out;
876         
877         packetsize = 20 + 8 + 4 + len;
878         if (client->availableBandwidth - packetsize < 0)
879                 goto out; /* Discard */
880         client->availableBandwidth -= packetsize;
881         
882         Timer_restart(&client->idleTime);
883         Timer_restart(&client->lastActivity);
884         
885         counter = Pds_get_numval(pdi); /* step past session id */
886         if ((type >> 5) != UDPVoiceOpus) {
887                 do {
888                         counter = Pds_next8(pdi);
889                         offset = Pds_skip(pdi, counter & 0x7f);
890                 } while ((counter & 0x80) && offset > 0);
891         } else {
892                 size = Pds_get_numval(pdi);
893                 Pds_skip(pdi, size & 0x1fff);
894         }
895                 
896         poslen = pdi->maxsize - pdi->offset; /* For stripping of positional info */
897         
898         Pds_add_numval(pds, client->sessionId);
899         Pds_append_data_nosize(pds, data + 1, len - 1);
900         
901         if (target == 0x1f) { /* Loopback */
902                 buffer[0] = (uint8_t) type;
903                 Client_send_udp(client, buffer, pds->offset + 1);
904         }
905         else if (target == 0) { /* regular channel speech */
906                 buffer[0] = (uint8_t) type;
907                 
908                 if (ch == NULL)
909                         goto out;
910                 
911                 list_iterate(itr, &ch->clients) {
912                         client_t *c;
913                         c = list_get_entry(itr, client_t, chan_node);
914                         Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
915                 }
916         } else if ((vt = Voicetarget_get_id(client, target)) != NULL) { /* Targeted whisper */
917                 int i;
918                 channel_t *ch;
919                 /* Channels */
920                 for (i = 0; i < TARGET_MAX_CHANNELS && vt->channels[i].channel != -1; i++) {
921                         buffer[0] = (uint8_t) (type | 1);
922                         Log_debug("Whisper channel %d", vt->channels[i]);
923                         ch = Chan_fromId(vt->channels[i].channel);
924                         if (ch == NULL)
925                                 continue;
926                         list_iterate(itr, &ch->clients) {
927                                 client_t *c;
928                                 c = list_get_entry(itr, client_t, chan_node);
929                                 Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
930                         }
931                         /* Channel links */
932                         if (vt->channels[i].linked && !list_empty(&ch->channel_links)) {
933                                 struct dlist *ch_itr;
934                                 list_iterate(ch_itr, &ch->channel_links) {
935                                         channel_t *ch_link;
936                                         ch_link = list_get_entry(ch_itr, channel_t, link_node);
937                                         list_iterate(itr, &ch_link->clients) {
938                                                 client_t *c;
939                                                 c = list_get_entry(itr, client_t, chan_node);
940                                                 Log_debug("Linked voice from %s -> %s", ch->name, ch_link->name);
941                                                 Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
942                                         }
943                                 }
944                         }
945                         /* children */
946                         if (vt->channels[i].children) {
947                                 struct dlist chanlist, *ch_itr;
948                                 init_list_entry(&chanlist);
949                                 Chan_buildTreeList(ch, &chanlist);
950                                 list_iterate(ch_itr, &chanlist) {
951                                         channel_t *sub;
952                                         sub = list_get_entry(ch_itr, channellist_t, node)->chan;
953                                         list_iterate(itr, &sub->clients) {
954                                                 client_t *c;
955                                                 c = list_get_entry(itr, client_t, chan_node);
956                                                 Log_debug("Child voice from %s -> %s", ch->name, sub->name);
957                                                 Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
958                                         }
959                                 }
960                                 Chan_freeTreeList(&chanlist);
961                         }
962                 }                       
963                 /* Sessions */
964                 for (i = 0; i < TARGET_MAX_SESSIONS && vt->sessions[i] != -1; i++) {
965                         client_t *c;
966                         buffer[0] = (uint8_t) (type | 2);
967                         Log_debug("Whisper session %d", vt->sessions[i]);
968                         while (Client_iterate(&c) != NULL) {
969                                 if (c->sessionId == vt->sessions[i]) {
970                                         Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
971                                         break;
972                                 }
973                         }
974                 }
975         }
976 out:
977         Pds_free(pds);
978         Pds_free(pdi);
979         
980         return 0;
981 }
982
983
984 static int Client_send_udp(client_t *client, uint8_t *data, int len)
985 {
986         uint8_t *buf, *mbuf;
987
988         if (client->remote_udp.sin_port != 0 && CryptState_isValid(&client->cryptState) &&
989                 client->bUDP) {
990 #if defined(__LP64__)
991                 buf = mbuf = malloc(len + 4 + 16);
992                 buf += 4;
993 #else
994                 mbuf = buf = malloc(len + 4);
995 #endif
996                 if (mbuf == NULL)
997                         Log_fatal("Out of memory");
998                 
999                 CryptState_encrypt(&client->cryptState, data, buf, len);
1000                 
1001                 sendto(udpsock, buf, len + 4, 0, (struct sockaddr *)&client->remote_udp, sizeof(struct sockaddr_in));
1002                 
1003                 free(mbuf);
1004         } else {
1005                 message_t *msg;
1006                 msg = Msg_CreateVoiceMsg(data, len);
1007                 Client_send_message(client, msg);
1008         }
1009         return 0;
1010 }