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