Use a function to find a free Session ID instead of just incrementing a counter.
[umurmur.git] / src / client.c
1 /* Copyright (C) 2009-2010, Martin Johansson <martin@fatbob.nu>
2    Copyright (C) 2005-2010, 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 <errno.h>
34 #include "log.h"
35 #include "list.h"
36 #include "client.h"
37 #include "ssl.h"
38 #include "messages.h"
39 #include "messagehandler.h"
40 #include "conf.h"
41 #include "channel.h"
42 #include "version.h"
43 #include "voicetarget.h"
44
45 extern char system_string[], version_string[];
46
47 static int Client_read(client_t *client);
48 static int Client_write(client_t *client);
49 static int Client_send_udp(client_t *client, uint8_t *data, int len);
50 void Client_free(client_t *client);
51
52 declare_list(clients);
53 static int clientcount; /* = 0 */
54 static int maxBandwidth;
55
56 int iCodecAlpha, iCodecBeta;
57 bool_t bPreferAlpha;
58
59 extern int udpsock;
60
61 void Client_init()
62 {
63         maxBandwidth = getIntConf(MAX_BANDWIDTH) / 8; /* From bits/s -> bytes/s */
64 }
65
66 int Client_count()
67 {
68         return clientcount;
69 }
70
71 int Client_getfds(struct pollfd *pollfds)
72 {
73         struct dlist *itr;
74         int i = 0;
75         list_iterate(itr, &clients) {
76                 client_t *c;
77                 c = list_get_entry(itr, client_t, node);
78                 pollfds[i].fd = c->tcpfd;
79                 pollfds[i].events = POLLIN | POLLHUP | POLLERR;
80                 if (c->txsize > 0 || c->readBlockedOnWrite) /* Data waiting to be sent? */
81                         pollfds[i].events |= POLLOUT;
82                 i++;
83         }
84         return i;
85 }
86
87 void Client_janitor()
88 {
89         struct dlist *itr;
90         int bwTop = maxBandwidth + maxBandwidth / 4;
91         list_iterate(itr, &clients) {
92                 client_t *c;
93                 c = list_get_entry(itr, client_t, node);
94                 Log_debug("Client %s BW available %d", c->playerName, c->availableBandwidth);
95                 c->availableBandwidth += maxBandwidth;
96                 if (c->availableBandwidth > bwTop)
97                         c->availableBandwidth = bwTop;
98                 
99                 if (Timer_isElapsed(&c->lastActivity, 1000000LL * INACTICITY_TIMEOUT)) {
100                         /* No activity from client - assume it is lost and close. */
101                         Log_info_client(c, "Timeout, closing.");
102                         Client_free(c);
103                 }
104         }
105 }
106
107 void recheckCodecVersions()
108 {
109         int codec_map[MAX_CODECS][2];
110         client_t *itr = NULL;
111         int i, codecindex, max = 0, version, current_version;
112         message_t *sendmsg;
113         
114         memset(codec_map, 0, MAX_CODECS * 2 * sizeof(int));
115         while (Client_iterate(&itr) != NULL) {
116                 for (i = 0; i < itr->codec_count; i++) {
117                         for (codecindex = 0; codecindex < MAX_CODECS; codecindex++) {
118                                 if (codec_map[codecindex][0] == 0) {
119                                         codec_map[codecindex][0] = itr->codecs[i];
120                                         codec_map[codecindex][1] = 1;
121                                         break;
122                                 }
123                                 if (itr->codecs[i] == codec_map[codecindex][0])
124                                         codec_map[codecindex][1]++;
125                         }
126                 }
127         }
128         for (codecindex = 0; codecindex < MAX_CODECS; codecindex++) {
129                 if (codec_map[codecindex][0] == 0)
130                         break;
131                 if (codec_map[codecindex][1] > max) {
132                         max = codec_map[codecindex][1];
133                         version = codec_map[codecindex][0];
134                 }
135         }
136         current_version = bPreferAlpha ? iCodecAlpha : iCodecBeta;
137         if (current_version == version)
138                 return;
139         // If we don't already use the compat bitstream version set
140         // it as alpha and announce it. If another codec now got the
141         // majority set it as the opposite of the currently valid bPreferAlpha
142         // and announce it.
143         if (version == (uint32_t)0x8000000a)
144                 bPreferAlpha = true;
145         else
146                 bPreferAlpha = ! bPreferAlpha;
147
148         if (bPreferAlpha)
149                 iCodecAlpha = version;
150         else
151                 iCodecBeta = version;
152         
153         sendmsg = Msg_create(CodecVersion);
154         sendmsg->payload.codecVersion->alpha = version;
155         sendmsg->payload.codecVersion->beta = version;
156         sendmsg->payload.codecVersion->prefer_alpha = bPreferAlpha;
157         Client_send_message_except(NULL, sendmsg);
158         
159         Log_info("CELT codec switch 0x%x 0x%x (prefer 0x%x)", iCodecAlpha, iCodecBeta,
160                          bPreferAlpha ? iCodecAlpha : iCodecBeta);
161         
162 }
163
164 static int findFreeSessionId()
165 {
166         int id;
167         client_t *itr = NULL;
168
169         for (id = 1; id < INT_MAX; id++) {
170                 itr = NULL;
171                 while ((itr = Client_iterate(&itr)) != NULL) {
172                         if (itr->sessionId == id)
173                                 break;
174                 }
175                 if (itr == NULL) /* Found free id */
176                         return id;
177         }
178         return -1;
179 }
180
181 int Client_add(int fd, struct sockaddr_in *remote)
182 {
183         client_t *newclient;
184         message_t *sendmsg;
185         
186         newclient = malloc(sizeof(client_t));
187         if (newclient == NULL)
188                 Log_fatal("Out of memory");
189         memset(newclient, 0, sizeof(client_t));
190
191         newclient->tcpfd = fd;
192         memcpy(&newclient->remote_tcp, remote, sizeof(struct sockaddr_in));
193         newclient->ssl = SSL_newconnection(newclient->tcpfd, &newclient->SSLready);
194         if (newclient->ssl == NULL) {
195                 Log_warn("SSL negotiation failed with %s:%d", inet_ntoa(remote->sin_addr),
196                                  ntohs(remote->sin_port));
197                 free(newclient);
198                 return -1;
199         }
200         newclient->availableBandwidth = maxBandwidth;
201         Timer_init(&newclient->lastActivity);
202         newclient->sessionId = findFreeSessionId();
203         if (newclient->sessionId < 0)
204                 Log_fatal("Could not find a free session ID");
205         
206         init_list_entry(&newclient->txMsgQueue);
207         init_list_entry(&newclient->chan_node);
208         init_list_entry(&newclient->node);
209         init_list_entry(&newclient->voicetargets);
210         
211         list_add_tail(&newclient->node, &clients);
212         clientcount++;
213         
214         /* Send version message to client */
215         sendmsg = Msg_create(Version);
216         sendmsg->payload.version->has_version = true;
217         sendmsg->payload.version->version = PROTOCOL_VERSION;
218         sendmsg->payload.version->release = strdup(UMURMUR_VERSION);
219         sendmsg->payload.version->os = strdup(system_string);
220         sendmsg->payload.version->os_version = strdup(version_string);
221         Client_send_message(newclient, sendmsg);
222
223         return 0;
224 }
225
226 void Client_free(client_t *client)
227 {
228         struct dlist *itr, *save;
229         message_t *sendmsg;
230
231         if (client->authenticated) {
232                 int leave_id;
233                 leave_id = Chan_playerLeave(client);
234                 if (leave_id > 0) { /* Remove temp channel */
235                         sendmsg = Msg_create(ChannelRemove);
236                         sendmsg->payload.channelRemove->channel_id = leave_id;
237                         Client_send_message_except(client, sendmsg);
238                 }
239                 sendmsg = Msg_create(UserRemove);
240                 sendmsg->payload.userRemove->session = client->sessionId;
241                 Client_send_message_except(client, sendmsg);
242         }
243         list_iterate_safe(itr, save, &client->txMsgQueue) {
244                 list_del(&list_get_entry(itr, message_t, node)->node);
245                 Msg_free(list_get_entry(itr, message_t, node));
246         }
247         Voicetarget_free_all(client);
248         
249         list_del(&client->node);
250         if (client->ssl)
251                 SSL_free(client->ssl);
252         close(client->tcpfd);
253         clientcount--;
254         if (client->release)
255                 free(client->release);
256         if (client->os)
257                 free(client->os);                       
258         if (client->playerName)
259                 free(client->playerName);
260         if (client->context)
261                 free(client->context);
262         free(client);
263 }
264
265 void Client_close(client_t *client)
266 {
267         SSL_shutdown(client->ssl);
268         client->shutdown_wait = true;
269 }
270
271 void Client_disconnect_all()
272 {
273         struct dlist *itr, *save;
274         
275         list_iterate_safe(itr, save, &clients) {
276                 Client_free(list_get_entry(itr, client_t, node));
277         }
278 }
279
280 int Client_read_fd(int fd)
281 {
282         struct dlist *itr;
283         client_t *client = NULL;
284         
285         list_iterate(itr, &clients) {
286                 if (fd == list_get_entry(itr, client_t, node)->tcpfd) {
287                         client = list_get_entry(itr, client_t, node);
288                         break;
289                 }
290         }
291         if (client == NULL)
292                 Log_fatal("No client found for fd %d", fd);
293         
294         return Client_read(client);
295 }
296
297 int Client_read(client_t *client)
298 {
299         int rc;
300
301         Timer_restart(&client->lastActivity);
302         
303         if (client->writeBlockedOnRead) {
304                 client->writeBlockedOnRead = false;
305                 Log_debug("Client_read: writeBlockedOnRead == true");
306                 return Client_write(client);
307         }
308         
309         if (client->shutdown_wait) {
310                 Client_free(client);
311                 return 0;
312         }
313         if (!client->SSLready) {
314                 int rc;
315                 rc = SSL_nonblockaccept(client->ssl, &client->SSLready);
316                 if (rc < 0) {
317                         Client_free(client);
318                         return -1;
319                 }
320         }
321
322         do {
323                 errno = 0;
324                 if (!client->msgsize) 
325                         rc = SSL_read(client->ssl, &client->rxbuf[client->rxcount], 6 - client->rxcount);
326                 else if (client->drainleft > 0)
327                         rc = SSL_read(client->ssl, client->rxbuf, client->drainleft > BUFSIZE ? BUFSIZE : client->drainleft);
328                 else
329                         rc = SSL_read(client->ssl, &client->rxbuf[client->rxcount], client->msgsize);
330                 if (rc > 0) {
331                         message_t *msg;
332                         if (client->drainleft > 0)
333                                 client->drainleft -= rc;
334                         else {
335                                 client->rxcount += rc;
336                                 if (!client->msgsize && client->rxcount >= 6) {
337                                         uint32_t msgLen;
338                                         memcpy(&msgLen, &client->rxbuf[2], sizeof(uint32_t));
339                                         client->msgsize = ntohl(msgLen);
340                                 }
341                                 if (client->msgsize > BUFSIZE - 6 && client->drainleft == 0) {
342                                         Log_info_client(client, "Too big message received (%d bytes). Discarding.", client->msgsize);
343                                         client->rxcount = client->msgsize = 0;
344                                         client->drainleft = client->msgsize;
345                                 }
346                                 else if (client->rxcount == client->msgsize + 6) { /* Got all of the message */
347                                         msg = Msg_networkToMessage(client->rxbuf, client->msgsize + 6);
348                                         /* pass messsage to handler */
349                                         if (msg)
350                                                         Mh_handle_message(client, msg);
351                                         client->rxcount = client->msgsize = 0;
352                                 }
353                         }
354                 } else /* rc <= 0 */ {
355                         if (SSL_get_error(client->ssl, rc) == SSL_ERROR_WANT_READ) {
356                                 return 0;
357                         }
358                         else if (SSL_get_error(client->ssl, rc) == SSL_ERROR_WANT_WRITE) {
359                                 client->readBlockedOnWrite = true;
360                                 return 0;
361                         }
362                         else if (SSL_get_error(client->ssl, rc) == SSL_ERROR_ZERO_RETURN) {
363                                 Log_info_client(client, "Connection closed by peer");
364                                 if (!client->shutdown_wait)
365                                         Client_close(client);
366                         }
367                         else {
368                                 if (SSL_get_error(client->ssl, rc) == SSL_ERROR_SYSCALL) {
369                                         /* Hmm. This is where we end up when the client closes its connection.
370                                          * Kind of strange...
371                                          */
372                                         Log_info_client(client, "Connection closed by peer");
373                                 }
374                                 else {
375                                         Log_info_client(client, "SSL error: %d - Closing connection", SSL_get_error(client->ssl, rc));
376                                 }
377                                 Client_free(client);
378                                 return -1;
379                         }
380                 }
381         } while (SSL_pending(client->ssl));
382         return 0;       
383 }
384
385 int Client_write_fd(int fd)
386 {
387         struct dlist *itr;
388         client_t *client = NULL;
389         
390         list_iterate(itr, &clients) {
391                 if(fd == list_get_entry(itr, client_t, node)->tcpfd) {
392                         client = list_get_entry(itr, client_t, node);
393                         break;
394                 }
395         }
396         if (client == NULL)
397                 Log_fatal("No client found for fd %d", fd);
398         Client_write(client);
399         return 0;
400 }
401
402 int Client_write(client_t *client)
403 {
404         int rc;
405         
406         if (client->readBlockedOnWrite) {
407                 client->readBlockedOnWrite = false;
408                 Log_debug("Client_write: readBlockedOnWrite == true");
409                 return Client_read(client);
410         }
411         rc = SSL_write(client->ssl, &client->txbuf[client->txcount], client->txsize - client->txcount);
412         if (rc > 0) {
413                 client->txcount += rc;
414                 if (client->txcount == client->txsize)
415                         client->txsize = client->txcount = 0;
416         }
417         else if (rc < 0) {
418                 if (SSL_get_error(client->ssl, rc) == SSL_ERROR_WANT_READ) {
419                         client->writeBlockedOnRead = true;
420                         return 0;
421                 }
422                 else if (SSL_get_error(client->ssl, rc) == SSL_ERROR_WANT_WRITE) {
423                         return 0;
424                 }
425                 else {
426                         if (SSL_get_error(client->ssl, rc) == SSL_ERROR_SYSCALL)
427                                 Log_warn("Client_write: Error: %s  - Closing connection", strerror(errno));
428                         else
429                                 Log_warn("Client_write: SSL error: %d - Closing connection.", SSL_get_error(client->ssl, rc));
430                         Client_free(client);
431                         return -1;
432                 }
433         }
434         if (client->txsize == 0 && !list_empty(&client->txMsgQueue)) {
435                 message_t *msg;
436                 msg = list_get_entry(list_get_first(&client->txMsgQueue), message_t, node);
437                 list_del(list_get_first(&client->txMsgQueue));
438                 client->txQueueCount--;
439                 Client_send_message(client, msg);
440         }
441         return 0;
442 }
443
444 int Client_send_message(client_t *client, message_t *msg)
445 {
446         if (!client->authenticated && msg->messageType != Version) {
447                 Msg_free(msg);
448                 return 0;
449         }
450         if (client->txsize != 0 || !client->SSLready) {
451                 /* Queue message */
452                 if ((client->txQueueCount > 5 &&  msg->messageType == UDPTunnel) ||
453                         client->txQueueCount > 30) {
454                         Msg_free(msg);
455                         return -1;
456                 }
457                 client->txQueueCount++;
458                 list_add_tail(&msg->node, &client->txMsgQueue);
459                 Log_debug("Queueing message");
460         } else {
461                 int len;
462                 memset(client->txbuf, 0, BUFSIZE);
463                 len = Msg_messageToNetwork(msg, client->txbuf);
464                 doAssert(len < BUFSIZE);
465
466                 client->txsize = len;
467                 client->txcount = 0;
468                 Client_write(client);
469                 Msg_free(msg);
470         }
471         return 0;
472 }
473
474 client_t *Client_iterate(client_t **client_itr)
475 {
476         client_t *c = *client_itr;
477
478         if (list_empty(&clients))
479                 return NULL;
480         
481         if (c == NULL) {
482                 c = list_get_entry(list_get_first(&clients), client_t, node);
483         } else {
484                 if (list_get_next(&c->node) == &clients)
485                         c = NULL;
486                 else
487                         c = list_get_entry(list_get_next(&c->node), client_t, node);
488         }
489         *client_itr = c;
490         return c;
491 }
492
493
494 int Client_send_message_except(client_t *client, message_t *msg)
495 {
496         client_t *itr = NULL;
497         int count = 0;
498         
499         Msg_inc_ref(msg); /* Make sure a reference is held during the whole iteration. */
500         while (Client_iterate(&itr) != NULL) {
501                 if (itr != client) {
502                         if (count++ > 0)
503                                 Msg_inc_ref(msg); /* One extra reference for each new copy */
504                         Log_debug("Msg %d to %s refcount %d",  msg->messageType, itr->playerName, msg->refcount);
505                         Client_send_message(itr, msg);
506                 }
507         }
508         Msg_free(msg); /* Free our reference to the message */
509         
510         if (count == 0)
511                 Msg_free(msg); /* If only 1 client is connected then no message is passed
512                                                 * to Client_send_message(). Free it here. */
513                 
514         return 0;
515 }
516
517 static bool_t checkDecrypt(client_t *client, const uint8_t *encrypted, uint8_t *plain, unsigned int len)
518 {
519         if (CryptState_isValid(&client->cryptState) &&
520                 CryptState_decrypt(&client->cryptState, encrypted, plain, len))
521                 return true;
522
523         if (Timer_elapsed(&client->cryptState.tLastGood) > 5000000ULL) {
524                 if (Timer_elapsed(&client->cryptState.tLastRequest) > 5000000ULL) {
525                         message_t *sendmsg;
526                         Timer_restart(&client->cryptState.tLastRequest);
527                         
528                         sendmsg = Msg_create(CryptSetup);
529                         Log_info_client(client, "Requesting voice channel crypt resync");               
530                         Client_send_message(client, sendmsg);
531                 }
532         }
533         return false;
534 }
535
536 #define UDP_PACKET_SIZE 1024
537 int Client_read_udp()
538 {
539         int len;
540         struct sockaddr_in from;
541         socklen_t fromlen = sizeof(struct sockaddr_in);
542         uint64_t key;
543         client_t *itr;
544         UDPMessageType_t msgType;
545         
546 #if defined(__LP64__)
547         uint8_t encbuff[UDP_PACKET_SIZE + 8];
548         uint8_t *encrypted = encbuff + 4;
549 #else
550         uint8_t encrypted[UDP_PACKET_SIZE];
551 #endif
552         uint8_t buffer[UDP_PACKET_SIZE];
553         
554         len = recvfrom(udpsock, encrypted, UDP_PACKET_SIZE, MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
555         if (len == 0) {
556                 return -1;
557         } else if (len < 0) {
558                 return -1;
559         } else if (len < 5) {
560                 // 4 bytes crypt header + type + session
561                 return 0;
562         } else if (len > UDP_PACKET_SIZE) {
563                 return 0;
564         }
565
566         /* Ping packet */
567         if (len == 12 && *encrypted == 0) {
568                 uint32_t *ping = (uint32_t *)encrypted;
569                 ping[0] = htonl((uint32_t)PROTOCOL_VERSION);
570                 // 1 and 2 will be the timestamp, which we return unmodified.
571                 ping[3] = htonl((uint32_t)clientcount);
572                 ping[4] = htonl((uint32_t)getIntConf(MAX_CLIENTS));
573                 ping[5] = htonl((uint32_t)getIntConf(MAX_BANDWIDTH));
574                 
575                 sendto(udpsock, encrypted, 6 * sizeof(uint32_t), 0, (struct sockaddr *)&from, fromlen);
576                 return 0;
577         }
578         
579         key = (((uint64_t)from.sin_addr.s_addr) << 16) ^ from.sin_port;
580         itr = NULL;
581         
582         while (Client_iterate(&itr) != NULL) {
583                 if (itr->key == key) {
584                         if (!checkDecrypt(itr, encrypted, buffer, len))
585                                 goto out;
586                         break;
587                 }
588         }       
589         if (itr == NULL) { /* Unknown peer */
590                 while (Client_iterate(&itr) != NULL) {
591                         if (itr->remote_tcp.sin_addr.s_addr == from.sin_addr.s_addr) {
592                                 if (checkDecrypt(itr, encrypted, buffer, len)) {
593                                         itr->key = key;
594                                         Log_info_client(itr, "New UDP connection port %d", ntohs(from.sin_port));
595                                         memcpy(&itr->remote_udp, &from, sizeof(struct sockaddr_in));
596                                         break;
597                                 }
598                                 else Log_warn("Bad cryptstate from peer");
599                         }
600                 } /* while */
601         }
602         if (itr == NULL) {
603                 goto out;
604         }
605         
606         msgType = (UDPMessageType_t)((buffer[0] >> 5) & 0x7);
607         switch (msgType) {
608         case UDPVoiceSpeex:
609         case UDPVoiceCELTAlpha:
610         case UDPVoiceCELTBeta:
611                 // u->bUdp = true;
612                 Client_voiceMsg(itr, buffer, len);
613                 break;
614         case UDPPing:
615                 Log_debug("UDP Ping reply len %d", len);
616                 Client_send_udp(itr, buffer, len);
617                 break;
618         default:
619                 Log_debug("Unknown UDP message type from %s port %d", inet_ntoa(from.sin_addr), ntohs(from.sin_port));
620                 break;
621         }
622 out:
623         return 0;
624 }
625
626 static inline void Client_send_voice(client_t *src, client_t *dst, uint8_t *data, int len, int poslen)
627 {
628         if (IS_AUTH(dst) && dst != src && !dst->deaf) {
629                 if (poslen > 0 && /* Has positional data */
630                         src->context != NULL && dst->context != NULL && /* ...both source and destination has context */
631                         strcmp(src->context, dst->context) == 0) /* ...and the contexts match */
632                         Client_send_udp(dst, data, len);
633                 else
634                         Client_send_udp(dst, data, len - poslen);
635         }
636 }
637
638 /* Handle decrypted voice message */
639 int Client_voiceMsg(client_t *client, uint8_t *data, int len)
640 {
641         uint8_t buffer[UDP_PACKET_SIZE];
642         pds_t *pdi = Pds_create(data + 1, len - 1);
643         pds_t *pds = Pds_create(buffer + 1, UDP_PACKET_SIZE - 1);
644         unsigned int type = data[0] & 0xe0;
645         unsigned int target = data[0] & 0x1f;
646         unsigned int poslen, counter;
647         int offset, packetsize;
648         voicetarget_t *vt;
649         
650         channel_t *ch = (channel_t *)client->channel;
651         struct dlist *itr;
652         
653         if (!client->authenticated || client->mute)
654                 goto out;
655         
656         packetsize = 20 + 8 + 4 + len;
657         if (client->availableBandwidth - packetsize < 0)
658                 goto out; /* Discard */
659         client->availableBandwidth -= packetsize;
660         
661         counter = Pds_get_numval(pdi); /* step past session id */
662         do {
663                 counter = Pds_next8(pdi);
664                 offset = Pds_skip(pdi, counter & 0x7f);
665         } while ((counter & 0x80) && offset > 0);
666
667         poslen = pdi->maxsize - pdi->offset; /* For stripping of positional info */
668         
669         Pds_add_numval(pds, client->sessionId);
670         Pds_append_data_nosize(pds, data + 1, len - 1);
671         
672         if (target == 0x1f) { /* Loopback */
673                 buffer[0] = (uint8_t) type;
674                 Client_send_udp(client, buffer, pds->offset + 1);
675         }
676         else if (target == 0) { /* regular channel speech */
677                 buffer[0] = (uint8_t) type;
678                 
679                 if (ch == NULL)
680                         goto out;
681                 
682                 list_iterate(itr, &ch->clients) {
683                         client_t *c;
684                         c = list_get_entry(itr, client_t, chan_node);
685                         Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
686                 }
687                 /* Channel links */
688                 if (!list_empty(&ch->channel_links)) {
689                         struct dlist *ch_itr;
690                         list_iterate(ch_itr, &ch->channel_links) {
691                                 channel_t *ch_link;
692                                 ch_link = list_get_entry(ch_itr, channel_t, link_node);
693                                 list_iterate(itr, &ch_link->clients) {
694                                         client_t *c;
695                                         c = list_get_entry(itr, client_t, chan_node);
696                                         Log_debug("Linked voice from %s -> %s", ch->name, ch_link->name);
697                                         Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
698                                 }
699                         }
700                 }
701         } else if ((vt = Voicetarget_get_id(client, target)) != NULL) { /* Targeted whisper */
702                 int i;
703                 channel_t *ch;
704                 /* Channels */
705                 for (i = 0; i < TARGET_MAX_CHANNELS && vt->channels[i] != -1; i++) {
706                         Log_debug("Whisper channel %d", vt->channels[i]);
707                         ch = Chan_fromId(vt->channels[i]);
708                         if (ch == NULL)
709                                 continue;
710                         list_iterate(itr, &ch->clients) {
711                                 client_t *c;
712                                 c = list_get_entry(itr, client_t, chan_node);
713                                 Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
714                         }
715                 }                       
716                 /* Sessions */
717                 for (i = 0; i < TARGET_MAX_SESSIONS && vt->sessions[i] != -1; i++) {
718                         client_t *c;
719                         Log_debug("Whisper session %d", vt->sessions[i]);
720                         while (Client_iterate(&c) != NULL) {
721                                 if (c->sessionId == vt->sessions[i]) {
722                                         Client_send_voice(client, c, buffer, pds->offset + 1, poslen);
723                                         break;
724                                 }
725                         }
726                 }
727         }
728 out:
729         Pds_free(pds);
730         Pds_free(pdi);
731         
732         return 0;
733 }
734
735
736 static int Client_send_udp(client_t *client, uint8_t *data, int len)
737 {
738         uint8_t *buf, *mbuf;
739
740         if (client->remote_udp.sin_port != 0 && CryptState_isValid(&client->cryptState)) {
741 #if defined(__LP64__)
742                 buf = mbuf = malloc(len + 4 + 16);
743                 buf += 4;
744 #else
745                 mbuf = buf = malloc(len + 4);
746 #endif
747                 if (mbuf == NULL)
748                         Log_fatal("Out of memory");
749                 
750                 CryptState_encrypt(&client->cryptState, data, buf, len);
751                 
752                 sendto(udpsock, buf, len + 4, 0, (struct sockaddr *)&client->remote_udp, sizeof(struct sockaddr_in));
753                 
754                 free(mbuf);
755         } else {
756                 message_t *msg;
757                 buf = malloc(len);
758                 memcpy(buf, data, len);
759                 msg = Msg_create(UDPTunnel);
760                 
761                 msg->payload.UDPTunnel->packet.data = buf;
762                 msg->payload.UDPTunnel->packet.len = len;
763                 Client_send_message(client, msg);
764         }
765         return 0;
766 }