updates.
[silc.git] / apps / silcd / packet_send.c
1 /*
2
3   packet_send.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 1997 - 2001 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; either version 2 of the License, or
12   (at your option) any later version.
13   
14   This program is distributed in the hope that it will be useful,
15   but WITHOUT ANY WARRANTY; without even the implied warranty of
16   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   GNU General Public License for more details.
18
19 */
20 /*
21  * Server packet routines to send packets. 
22  */
23 /* $Id$ */
24
25 #include "serverincludes.h"
26 #include "server_internal.h"
27
28 /* Routine that sends packet or marks packet to be sent. This is used
29    directly only in special cases. Normal cases should use
30    silc_server_packet_send. Returns < 0 error. */
31
32 int silc_server_packet_send_real(SilcServer server,
33                                  SilcSocketConnection sock,
34                                  bool force_send)
35 {
36   int ret;
37
38   /* If disconnecting, ignore the data */
39   if (SILC_IS_DISCONNECTING(sock))
40     return -1;
41
42   /* If rekey protocol is active we must assure that all packets are
43      sent through packet queue. */
44   if (SILC_SERVER_IS_REKEY(sock))
45     force_send = FALSE;
46
47   /* If outbound data is already pending do not force send */
48   if (SILC_IS_OUTBUF_PENDING(sock))
49     force_send = FALSE;
50
51   /* Send the packet */
52   ret = silc_packet_send(sock, force_send);
53   if (ret != -2)
54     return ret;
55
56   /* Mark that there is some outgoing data available for this connection. 
57      This call sets the connection both for input and output (the input
58      is set always and this call keeps the input setting, actually). 
59      Actual data sending is performed by silc_server_packet_process. */
60   SILC_SET_CONNECTION_FOR_OUTPUT(server->schedule, sock->sock);
61
62   /* Mark to socket that data is pending in outgoing buffer. This flag
63      is needed if new data is added to the buffer before the earlier
64      put data is sent to the network. */
65   SILC_SET_OUTBUF_PENDING(sock);
66
67   return 0;
68 }
69
70 /* Assembles a new packet to be sent out to network. This doesn't actually
71    send the packet but creates the packet and fills the outgoing data
72    buffer and marks the packet ready to be sent to network. However, If 
73    argument force_send is TRUE the packet is sent immediately and not put 
74    to queue. Normal case is that the packet is not sent immediately. */
75
76 void silc_server_packet_send(SilcServer server,
77                              SilcSocketConnection sock, 
78                              SilcPacketType type, 
79                              SilcPacketFlags flags,
80                              unsigned char *data, 
81                              uint32 data_len,
82                              bool force_send)
83 {
84   void *dst_id = NULL;
85   SilcIdType dst_id_type = SILC_ID_NONE;
86   SilcIDListData idata = (SilcIDListData)sock->user_data;
87
88   if (!sock)
89     return;
90
91   /* If disconnecting, ignore the data */
92   if (SILC_IS_DISCONNECTING(sock))
93     return;
94
95   /* If entry is disabled do not sent anything. */
96   if (idata && idata->status & SILC_IDLIST_STATUS_DISABLED)
97     return;
98
99   /* Get data used in the packet sending, keys and stuff */
100   switch(sock->type) {
101   case SILC_SOCKET_TYPE_CLIENT:
102     if (sock->user_data) {
103       dst_id = ((SilcClientEntry)sock->user_data)->id;
104       dst_id_type = SILC_ID_CLIENT;
105     }
106     break;
107   case SILC_SOCKET_TYPE_SERVER:
108   case SILC_SOCKET_TYPE_ROUTER:
109     if (sock->user_data) {
110       dst_id = ((SilcServerEntry)sock->user_data)->id;
111       dst_id_type = SILC_ID_SERVER;
112     }
113     break;
114   default:
115     break;
116   }
117
118   silc_server_packet_send_dest(server, sock, type, flags, dst_id,
119                                dst_id_type, data, data_len, force_send);
120 }
121
122 /* Assembles a new packet to be sent out to network. This doesn't actually
123    send the packet but creates the packet and fills the outgoing data
124    buffer and marks the packet ready to be sent to network. However, If 
125    argument force_send is TRUE the packet is sent immediately and not put 
126    to queue. Normal case is that the packet is not sent immediately. 
127    Destination information is sent as argument for this function. */
128
129 void silc_server_packet_send_dest(SilcServer server,
130                                   SilcSocketConnection sock, 
131                                   SilcPacketType type, 
132                                   SilcPacketFlags flags,
133                                   void *dst_id,
134                                   SilcIdType dst_id_type,
135                                   unsigned char *data, 
136                                   uint32 data_len,
137                                   bool force_send)
138 {
139   SilcPacketContext packetdata;
140   SilcIDListData idata = (SilcIDListData)sock->user_data;
141   SilcCipher cipher = NULL;
142   SilcHmac hmac = NULL;
143   uint32 sequence = 0;
144   unsigned char *dst_id_data = NULL;
145   uint32 dst_id_len = 0;
146   int block_len = 0;
147
148   /* If disconnecting, ignore the data */
149   if (SILC_IS_DISCONNECTING(sock))
150     return;
151
152   /* If entry is disabled do not sent anything. */
153   if (idata && idata->status & SILC_IDLIST_STATUS_DISABLED)
154     return;
155
156   SILC_LOG_DEBUG(("Sending packet, type %d", type));
157
158   if (dst_id) {
159     dst_id_data = silc_id_id2str(dst_id, dst_id_type);
160     dst_id_len = silc_id_get_len(dst_id, dst_id_type);
161   }
162
163   if (idata) {
164     cipher = idata->send_key;
165     hmac = idata->hmac_send;
166     sequence = idata->psn_send++;
167     block_len = silc_cipher_get_block_len(cipher);
168   }
169
170   /* Set the packet context pointers */
171   packetdata.type = type;
172   packetdata.flags = flags;
173   packetdata.src_id = silc_id_id2str(server->id, server->id_type);
174   packetdata.src_id_len = silc_id_get_len(server->id, server->id_type);
175   packetdata.src_id_type = server->id_type;
176   packetdata.dst_id = dst_id_data;
177   packetdata.dst_id_len = dst_id_len;
178   packetdata.dst_id_type = dst_id_type;
179   packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN + 
180     packetdata.src_id_len + dst_id_len;
181   packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen, block_len);
182
183   /* Prepare outgoing data buffer for packet sending */
184   silc_packet_send_prepare(sock, 
185                            SILC_PACKET_HEADER_LEN +
186                            packetdata.src_id_len + 
187                            packetdata.dst_id_len,
188                            packetdata.padlen,
189                            data_len);
190
191   SILC_LOG_DEBUG(("Putting data to outgoing buffer, len %d", data_len));
192
193   packetdata.buffer = sock->outbuf;
194
195   /* Put the data to the buffer */
196   if (data && data_len)
197     silc_buffer_put(sock->outbuf, data, data_len);
198
199   /* Create the outgoing packet */
200   silc_packet_assemble(&packetdata, cipher);
201
202   /* Encrypt the packet */
203   silc_packet_encrypt(cipher, hmac, sequence, sock->outbuf, sock->outbuf->len);
204
205   SILC_LOG_HEXDUMP(("Outgoing packet (%d), len %d", sequence, 
206                     sock->outbuf->len),
207                    sock->outbuf->data, sock->outbuf->len);
208
209   /* Now actually send the packet */
210   silc_server_packet_send_real(server, sock, force_send);
211
212   if (packetdata.src_id)
213     silc_free(packetdata.src_id);
214   if (packetdata.dst_id)
215     silc_free(packetdata.dst_id);
216 }
217
218 /* Assembles a new packet to be sent out to network. This doesn't actually
219    send the packet but creates the packet and fills the outgoing data
220    buffer and marks the packet ready to be sent to network. However, If 
221    argument force_send is TRUE the packet is sent immediately and not put 
222    to queue. Normal case is that the packet is not sent immediately. 
223    The source and destination information is sent as argument for this
224    function. */
225
226 void silc_server_packet_send_srcdest(SilcServer server,
227                                      SilcSocketConnection sock, 
228                                      SilcPacketType type, 
229                                      SilcPacketFlags flags,
230                                      void *src_id,
231                                      SilcIdType src_id_type,
232                                      void *dst_id,
233                                      SilcIdType dst_id_type,
234                                      unsigned char *data, 
235                                      uint32 data_len,
236                                      bool force_send)
237 {
238   SilcPacketContext packetdata;
239   SilcIDListData idata;
240   SilcCipher cipher = NULL;
241   SilcHmac hmac = NULL;
242   uint32 sequence = 0;
243   unsigned char *dst_id_data = NULL;
244   uint32 dst_id_len = 0;
245   unsigned char *src_id_data = NULL;
246   uint32 src_id_len = 0;
247   int block_len = 0;
248
249   SILC_LOG_DEBUG(("Sending packet, type %d", type));
250
251   /* Get data used in the packet sending, keys and stuff */
252   idata = (SilcIDListData)sock->user_data;
253
254   if (dst_id) {
255     dst_id_data = silc_id_id2str(dst_id, dst_id_type);
256     dst_id_len = silc_id_get_len(dst_id, dst_id_type);
257   }
258
259   if (src_id) {
260     src_id_data = silc_id_id2str(src_id, src_id_type);
261     src_id_len = silc_id_get_len(src_id, src_id_type);
262   }
263
264   if (idata) {
265     cipher = idata->send_key;
266     hmac = idata->hmac_send;
267     sequence = idata->psn_send++;
268     block_len = silc_cipher_get_block_len(cipher);
269   }
270
271   /* Set the packet context pointers */
272   packetdata.type = type;
273   packetdata.flags = flags;
274   packetdata.src_id = src_id_data;
275   packetdata.src_id_len = src_id_len;
276   packetdata.src_id_type = src_id_type;
277   packetdata.dst_id = dst_id_data;
278   packetdata.dst_id_len = dst_id_len;
279   packetdata.dst_id_type = dst_id_type;
280   packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN + 
281     packetdata.src_id_len + dst_id_len;
282   packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen, block_len);
283
284   /* Prepare outgoing data buffer for packet sending */
285   silc_packet_send_prepare(sock, 
286                            SILC_PACKET_HEADER_LEN +
287                            packetdata.src_id_len + 
288                            packetdata.dst_id_len,
289                            packetdata.padlen,
290                            data_len);
291
292   SILC_LOG_DEBUG(("Putting data to outgoing buffer, len %d", data_len));
293
294   packetdata.buffer = sock->outbuf;
295
296   /* Put the data to the buffer */
297   if (data && data_len)
298     silc_buffer_put(sock->outbuf, data, data_len);
299
300   /* Create the outgoing packet */
301   silc_packet_assemble(&packetdata, cipher);
302
303   /* Encrypt the packet */
304   silc_packet_encrypt(cipher, hmac, sequence, sock->outbuf, sock->outbuf->len);
305
306   SILC_LOG_HEXDUMP(("Outgoing packet (%d), len %d", sequence, 
307                     sock->outbuf->len),
308                    sock->outbuf->data, sock->outbuf->len);
309
310   /* Now actually send the packet */
311   silc_server_packet_send_real(server, sock, force_send);
312
313   if (packetdata.src_id)
314     silc_free(packetdata.src_id);
315   if (packetdata.dst_id)
316     silc_free(packetdata.dst_id);
317 }
318
319 /* Broadcast received packet to our primary route. This function is used
320    by router to further route received broadcast packet. It is expected
321    that the broadcast flag from the packet is checked before calling this
322    function. This does not test or set the broadcast flag. */
323
324 void silc_server_packet_broadcast(SilcServer server,
325                                   SilcSocketConnection sock,
326                                   SilcPacketContext *packet)
327 {
328   SilcBuffer buffer = packet->buffer;
329   SilcIDListData idata;
330   void *id;
331
332   SILC_LOG_DEBUG(("Broadcasting received broadcast packet"));
333
334   /* If the packet is originated from our primary route we are
335      not allowed to send the packet. */
336   id = silc_id_str2id(packet->src_id, packet->src_id_len, packet->src_id_type);
337   if (id && !SILC_ID_SERVER_COMPARE(id, server->router->id)) {
338     idata = (SilcIDListData)sock->user_data;
339
340     silc_buffer_push(buffer, buffer->data - buffer->head);
341     silc_packet_send_prepare(sock, 0, 0, buffer->len); 
342     silc_buffer_put(sock->outbuf, buffer->data, buffer->len);
343     silc_packet_encrypt(idata->send_key, idata->hmac_send, idata->psn_send++,
344                         sock->outbuf, sock->outbuf->len);
345
346     SILC_LOG_HEXDUMP(("Broadcasted packet (%d), len %d", idata->psn_send - 1,
347                       sock->outbuf->len),
348                      sock->outbuf->data, sock->outbuf->len);
349
350     /* Now actually send the packet */
351     silc_server_packet_send_real(server, sock, TRUE);
352     silc_free(id);
353     return;
354   }
355
356   SILC_LOG_DEBUG(("Will not broadcast to primary route since it is the "
357                   "original sender of this packet"));
358   silc_free(id);
359 }
360
361 /* Routes received packet to `sock'. This is used to route the packets that
362    router receives but are not destined to it. */
363
364 void silc_server_packet_route(SilcServer server,
365                               SilcSocketConnection sock,
366                               SilcPacketContext *packet)
367 {
368   SilcBuffer buffer = packet->buffer;
369   SilcIDListData idata;
370
371   SILC_LOG_DEBUG(("Routing received packet"));
372
373   idata = (SilcIDListData)sock->user_data;
374
375   silc_buffer_push(buffer, buffer->data - buffer->head);
376   silc_packet_send_prepare(sock, 0, 0, buffer->len); 
377   silc_buffer_put(sock->outbuf, buffer->data, buffer->len);
378   silc_packet_encrypt(idata->send_key, idata->hmac_send, idata->psn_send++,
379                       sock->outbuf, sock->outbuf->len);
380
381   SILC_LOG_HEXDUMP(("Routed packet (%d), len %d", idata->psn_send - 1, 
382                     sock->outbuf->len),
383                    sock->outbuf->data, sock->outbuf->len);
384
385   /* Now actually send the packet */
386   silc_server_packet_send_real(server, sock, TRUE);
387 }
388
389 /* Internal routine to actually create the channel packet and send it
390    to network. This is common function in channel message sending. If
391    `channel_message' is TRUE this encrypts the message as it is strictly
392    a channel message. If FALSE normal encryption process is used. */
393
394 static void
395 silc_server_packet_send_to_channel_real(SilcServer server,
396                                         SilcSocketConnection sock,
397                                         SilcPacketContext *packet,
398                                         SilcCipher cipher,
399                                         SilcHmac hmac,
400                                         uint32 sequence,
401                                         unsigned char *data,
402                                         uint32 data_len,
403                                         bool channel_message,
404                                         bool force_send)
405 {
406   int block_len = 0;
407   packet->truelen = data_len + SILC_PACKET_HEADER_LEN + 
408     packet->src_id_len + packet->dst_id_len;
409
410   if (cipher) {
411     block_len = silc_cipher_get_block_len(cipher);
412
413     if (channel_message)
414       packet->padlen = SILC_PACKET_PADLEN((SILC_PACKET_HEADER_LEN +
415                                            packet->src_id_len +
416                                            packet->dst_id_len), block_len);
417     else
418       packet->padlen = SILC_PACKET_PADLEN(packet->truelen, block_len);
419   }
420
421   /* Prepare outgoing data buffer for packet sending */
422   silc_packet_send_prepare(sock, 
423                            SILC_PACKET_HEADER_LEN +
424                            packet->src_id_len + 
425                            packet->dst_id_len,
426                            packet->padlen,
427                            data_len);
428
429   packet->buffer = sock->outbuf;
430
431   /* Put the data to buffer, assemble and encrypt the packet. The packet
432      is encrypted with normal session key shared with the client, unless
433      the `channel_message' is TRUE. */
434   silc_buffer_put(sock->outbuf, data, data_len);
435   silc_packet_assemble(packet, cipher);
436   if (channel_message)
437     silc_packet_encrypt(cipher, hmac, sequence, sock->outbuf, 
438                         SILC_PACKET_HEADER_LEN + packet->src_id_len + 
439                         packet->dst_id_len + packet->padlen);
440   else
441     silc_packet_encrypt(cipher, hmac, sequence, sock->outbuf, 
442                         sock->outbuf->len);
443     
444   SILC_LOG_HEXDUMP(("Channel packet (%d), len %d", sequence, 
445                     sock->outbuf->len),
446                    sock->outbuf->data, sock->outbuf->len);
447
448   /* Now actually send the packet */
449   silc_server_packet_send_real(server, sock, force_send);
450 }
451
452 /* This routine is used by the server to send packets to channel. The 
453    packet sent with this function is distributed to all clients on
454    the channel. Usually this is used to send notify messages to the
455    channel, things like notify about new user joining to the channel. 
456    If `route' is FALSE then the packet is sent only locally and will not
457    be routed anywhere (for router locally means cell wide). If `sender'
458    is provided then the packet is not sent to that connection since it
459    originally came from it. */
460
461 void silc_server_packet_send_to_channel(SilcServer server,
462                                         SilcSocketConnection sender,
463                                         SilcChannelEntry channel,
464                                         SilcPacketType type,
465                                         bool route,
466                                         unsigned char *data,
467                                         uint32 data_len,
468                                         bool force_send)
469 {
470   SilcSocketConnection sock = NULL;
471   SilcPacketContext packetdata;
472   SilcClientEntry client = NULL;
473   SilcServerEntry *routed = NULL;
474   SilcChannelClientEntry chl;
475   SilcHashTableList htl;
476   SilcIDListData idata;
477   uint32 routed_count = 0;
478   bool gone = FALSE;
479   int k;
480
481   /* This doesn't send channel message packets */
482   assert(type != SILC_PACKET_CHANNEL_MESSAGE);
483   
484   SILC_LOG_DEBUG(("Sending packet to channel"));
485
486   /* Set the packet context pointers. */
487   packetdata.flags = 0;
488   packetdata.type = type;
489   packetdata.src_id = silc_id_id2str(server->id, SILC_ID_SERVER);
490   packetdata.src_id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
491   packetdata.src_id_type = SILC_ID_SERVER;
492   packetdata.dst_id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
493   packetdata.dst_id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
494   packetdata.dst_id_type = SILC_ID_CHANNEL;
495
496   /* If there are global users in the channel we will send the message
497      first to our router for further routing. */
498   if (route && server->server_type != SILC_ROUTER && !server->standalone &&
499       channel->global_users) {
500     SilcServerEntry router;
501
502     /* Get data used in packet header encryption, keys and stuff. */
503     router = server->router;
504     sock = (SilcSocketConnection)router->connection;
505     idata = (SilcIDListData)router;
506     
507     if (sock != sender) {
508       SILC_LOG_DEBUG(("Sending channel message to router for routing"));
509       
510       silc_server_packet_send_to_channel_real(server, sock, &packetdata,
511                                               idata->send_key, 
512                                               idata->hmac_send, 
513                                               idata->psn_send++,
514                                               data, data_len, FALSE, 
515                                               force_send);
516     }
517   }
518
519   routed = silc_calloc(silc_hash_table_count(channel->user_list), 
520                        sizeof(*routed));
521
522   /* Send the message to clients on the channel's client list. */
523   silc_hash_table_list(channel->user_list, &htl);
524   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
525     client = chl->client;
526     if (!client)
527       continue;
528
529     /* If client has router set it is not locally connected client and
530        we will route the message to the router set in the client. Though,
531        send locally connected server in all cases. */
532     if (server->server_type == SILC_ROUTER && client->router && 
533         ((!route && client->router->router == server->id_entry) || route)) {
534
535       /* Check if we have sent the packet to this route already */
536       for (k = 0; k < routed_count; k++)
537         if (routed[k] == client->router)
538           break;
539       if (k < routed_count)
540         continue;
541
542       /* Get data used in packet header encryption, keys and stuff. */
543       sock = (SilcSocketConnection)client->router->connection;
544       idata = (SilcIDListData)client->router;
545
546       if (sender && sock == sender)
547         continue;
548
549       /* Route only once to router */
550       if (sock->type == SILC_SOCKET_TYPE_ROUTER) {
551         if (gone)
552           continue;
553         gone = TRUE;
554       }
555
556       /* Send the packet */
557       silc_server_packet_send_to_channel_real(server, sock, &packetdata,
558                                               idata->send_key, 
559                                               idata->hmac_send, 
560                                               idata->psn_send++,
561                                               data, data_len, FALSE, 
562                                               force_send);
563
564       /* Mark this route routed already */
565       routed[routed_count++] = client->router;
566       continue;
567     }
568
569     if (client->router)
570       continue;
571
572     /* Send to locally connected client */
573
574     /* Get data used in packet header encryption, keys and stuff. */
575     sock = (SilcSocketConnection)client->connection;
576     idata = (SilcIDListData)client;
577     
578     if (sender && sock == sender)
579       continue;
580
581       /* Send the packet */
582     silc_server_packet_send_to_channel_real(server, sock, &packetdata,
583                                             idata->send_key, 
584                                             idata->hmac_send, 
585                                             idata->psn_send++, 
586                                             data, data_len, FALSE, 
587                                             force_send);
588   }
589
590   silc_free(routed);
591   silc_free(packetdata.src_id);
592   silc_free(packetdata.dst_id);
593 }
594
595 /* This checks whether the relayed packet came from router. If it did
596    then we'll need to encrypt it with the channel key. This is called
597    from the silc_server_packet_relay_to_channel. */
598
599 static bool
600 silc_server_packet_relay_to_channel_encrypt(SilcServer server,
601                                             SilcSocketConnection sock,
602                                             SilcChannelEntry channel,
603                                             unsigned char *data,
604                                             unsigned int data_len)
605 {
606   /* If we are router and the packet came from router and private key
607      has not been set for the channel then we must encrypt the packet
608      as it was decrypted with the session key shared between us and the
609      router which sent it. This is so, because cells does not share the
610      same channel key. */
611   if (server->server_type == SILC_ROUTER &&
612       sock->type == SILC_SOCKET_TYPE_ROUTER &&
613       !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY) &&
614       channel->channel_key) {
615     SilcBuffer chp;
616     uint32 iv_len, i;
617     uint16 dlen, flags;
618
619     iv_len = silc_cipher_get_block_len(channel->channel_key);
620     if (channel->iv[0] == '\0')
621       for (i = 0; i < iv_len; i++) channel->iv[i] = 
622                                      silc_rng_get_byte(server->rng);
623     else
624       silc_hash_make(server->md5hash, channel->iv, iv_len, channel->iv);
625     
626     /* Encode new payload. This encrypts it also. */
627     SILC_GET16_MSB(flags, data);
628     SILC_GET16_MSB(dlen, data + 2);
629
630     if (dlen > data_len) {
631       SILC_LOG_WARNING(("Corrupted channel message, cannot relay it"));
632       return FALSE;
633     }
634
635     chp = silc_channel_message_payload_encode(flags, dlen, data + 4,
636                                               iv_len, channel->iv,
637                                               channel->channel_key,
638                                               channel->hmac);
639     memcpy(data, chp->data, chp->len);
640     silc_buffer_free(chp);
641   }
642
643   return TRUE;
644 }
645
646 /* This routine is explicitly used to relay messages to some channel.
647    Packets sent with this function we have received earlier and are
648    totally encrypted. This just sends the packet to all clients on
649    the channel. If the sender of the packet is someone on the channel 
650    the message will not be sent to that client. The SILC Packet header
651    is encrypted with the session key shared between us and the client.
652    MAC is also computed before encrypting the header. Rest of the
653    packet will be untouched. */
654
655 void silc_server_packet_relay_to_channel(SilcServer server,
656                                          SilcSocketConnection sender_sock,
657                                          SilcChannelEntry channel,
658                                          void *sender, 
659                                          SilcIdType sender_type,
660                                          void *sender_entry,
661                                          unsigned char *data,
662                                          uint32 data_len,
663                                          bool force_send)
664 {
665   bool found = FALSE;
666   SilcSocketConnection sock = NULL;
667   SilcPacketContext packetdata;
668   SilcClientEntry client = NULL;
669   SilcServerEntry *routed = NULL;
670   SilcChannelClientEntry chl;
671   uint32 routed_count = 0;
672   SilcIDListData idata;
673   SilcHashTableList htl;
674   bool gone = FALSE;
675   int k;
676
677   SILC_LOG_DEBUG(("Relaying packet to channel"));
678
679   /* This encrypts the packet, if needed. It will be encrypted if
680      it came from the router thus it needs to be encrypted with the
681      channel key. If the channel key does not exist, then we know we
682      don't have a single local user on the channel. */
683   if (!silc_server_packet_relay_to_channel_encrypt(server, sender_sock,
684                                                    channel, data,
685                                                    data_len))
686     return;
687
688   /* Set the packet context pointers. */
689   packetdata.flags = 0;
690   packetdata.type = SILC_PACKET_CHANNEL_MESSAGE;
691   packetdata.src_id = silc_id_id2str(sender, sender_type);
692   packetdata.src_id_len = silc_id_get_len(sender, sender_type);
693   packetdata.src_id_type = sender_type;
694   packetdata.dst_id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
695   packetdata.dst_id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
696   packetdata.dst_id_type = SILC_ID_CHANNEL;
697
698   /* If there are global users in the channel we will send the message
699      first to our router for further routing. */
700   if (server->server_type != SILC_ROUTER && !server->standalone &&
701       channel->global_users) {
702     SilcServerEntry router = server->router;
703
704     /* Check that the sender is not our router. */
705     if (sender_sock != (SilcSocketConnection)router->connection) {
706
707       /* Get data used in packet header encryption, keys and stuff. */
708       sock = (SilcSocketConnection)router->connection;
709       idata = (SilcIDListData)router;
710
711       SILC_LOG_DEBUG(("Sending channel message to router for routing"));
712
713       silc_server_packet_send_to_channel_real(server, sock, &packetdata,
714                                               idata->send_key, 
715                                               idata->hmac_send, 
716                                               idata->psn_send++, 
717                                               data, data_len, TRUE, 
718                                               force_send);
719     }
720   }
721
722   routed = silc_calloc(silc_hash_table_count(channel->user_list), 
723                        sizeof(*routed));
724
725   /* Mark that to the route the original sender if from is not routed */
726   if (sender_type == SILC_ID_CLIENT) {
727     client = (SilcClientEntry)sender_entry;
728     if (client->router) {
729       routed[routed_count++] = client->router;
730       SILC_LOG_DEBUG(("************* router %s", 
731                       silc_id_render(client->router->id, SILC_ID_SERVER)));
732     }
733   }
734
735   /* Send the message to clients on the channel's client list. */
736   silc_hash_table_list(channel->user_list, &htl);
737   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
738     client = chl->client;
739     if (!client)
740       continue;
741
742     /* Do not send to the sender */
743     if (!found && client == sender_entry) {
744       found = TRUE;
745       continue;
746     }
747
748     /* If the client has set router it means that it is not locally
749        connected client and we will route the packet further. */
750     if (server->server_type == SILC_ROUTER && client->router) {
751
752       /* Sender maybe server as well so we want to make sure that
753          we won't send the message to the server it came from. */
754       if (!found && SILC_ID_SERVER_COMPARE(client->router->id, sender)) {
755         found = TRUE;
756         routed[routed_count++] = client->router;
757         continue;
758       }
759
760       /* Check if we have sent the packet to this route already */
761       for (k = 0; k < routed_count; k++)
762         if (routed[k] == client->router)
763           break;
764       if (k < routed_count)
765         continue;
766         
767       /* Get data used in packet header encryption, keys and stuff. */
768       sock = (SilcSocketConnection)client->router->connection;
769       idata = (SilcIDListData)client->router;
770
771       /* Do not send to the sender. Check first whether the true
772          sender's router is same as this client's router. Also check
773          if the sender socket is the same as this client's router
774          socket. */
775       if (sender_entry &&
776           ((SilcClientEntry)sender_entry)->router == client->router)
777         continue;
778       if (sender_sock && sock == sender_sock)
779         continue;
780
781       SILC_LOG_DEBUG(("Relaying packet to client ID(%s) %s (%s)", 
782                       silc_id_render(client->id, SILC_ID_CLIENT),
783                       sock->hostname, sock->ip));
784
785       /* Mark this route routed already. */
786       routed[routed_count++] = client->router;
787         
788       /* If the remote connection is router then we'll decrypt the
789          channel message and re-encrypt it with the session key shared
790          between us and the remote router. This is done because the
791          channel keys are cell specific and we have different channel
792          key than the remote router has. */
793       if (sock->type == SILC_SOCKET_TYPE_ROUTER) {
794         if (gone)
795           continue;
796
797         SILC_LOG_DEBUG(("Remote is router, encrypt with session key"));
798         gone = TRUE;
799
800         /* If private key mode is not set then decrypt the packet
801            and re-encrypt it */
802         if (!(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
803           unsigned char *tmp = silc_calloc(data_len, sizeof(*data));
804           memcpy(tmp, data, data_len);
805
806           /* Decrypt the channel message (we don't check the MAC) */
807           if (channel->channel_key &&
808               !silc_channel_message_payload_decrypt(tmp, data_len, 
809                                                     channel->channel_key,
810                                                     NULL)) {
811             memset(tmp, 0, data_len);
812             silc_free(tmp);
813             continue;
814           }
815
816           /* Now re-encrypt and send it to the router */
817           silc_server_packet_send_srcdest(server, sock, 
818                                           SILC_PACKET_CHANNEL_MESSAGE, 0,
819                                           sender, sender_type,
820                                           channel->id, SILC_ID_CHANNEL,
821                                           tmp, data_len, force_send);
822
823           /* Free the copy of the channel message */
824           memset(tmp, 0, data_len);
825           silc_free(tmp);
826         } else {
827           /* Private key mode is set, we don't have the channel key, so
828              just re-encrypt the entire packet and send it to the router. */
829           silc_server_packet_send_srcdest(server, sock, 
830                                           SILC_PACKET_CHANNEL_MESSAGE, 0,
831                                           sender, sender_type,
832                                           channel->id, SILC_ID_CHANNEL,
833                                           data, data_len, force_send);
834         }
835         continue;
836       }
837
838       /* Send the packet (to normal server) */
839       silc_server_packet_send_to_channel_real(server, sock, &packetdata,
840                                               idata->send_key, 
841                                               idata->hmac_send, 
842                                               idata->psn_send++, 
843                                               data, data_len, TRUE, 
844                                               force_send);
845
846       continue;
847     }
848
849     if (client->router)
850       continue;
851
852     /* Get data used in packet header encryption, keys and stuff. */
853     sock = (SilcSocketConnection)client->connection;
854     idata = (SilcIDListData)client;
855
856     if (sender_sock && sock == sender_sock)
857       continue;
858
859     SILC_LOG_DEBUG(("Sending packet to client ID(%s) %s (%s)", 
860                     silc_id_render(client->id, SILC_ID_CLIENT),
861                     sock->hostname, sock->ip));
862
863     /* Send the packet */
864     silc_server_packet_send_to_channel_real(server, sock, &packetdata,
865                                             idata->send_key, 
866                                             idata->hmac_send, 
867                                             idata->psn_send++, 
868                                             data, data_len, TRUE, 
869                                             force_send);
870   }
871
872   silc_free(routed);
873   silc_free(packetdata.src_id);
874   silc_free(packetdata.dst_id);
875 }
876
877 /* This function is used to send packets strictly to all local clients
878    on a particular channel.  This is used for example to distribute new
879    channel key to all our locally connected clients on the channel. 
880    The packets are always encrypted with the session key shared between
881    the client, this means these are not _to the channel_ but _to the client_
882    on the channel. */
883
884 void silc_server_packet_send_local_channel(SilcServer server,
885                                            SilcChannelEntry channel,
886                                            SilcPacketType type,
887                                            SilcPacketFlags flags,
888                                            unsigned char *data,
889                                            uint32 data_len,
890                                            bool force_send)
891 {
892   SilcChannelClientEntry chl;
893   SilcHashTableList htl;
894   SilcSocketConnection sock = NULL;
895
896   SILC_LOG_DEBUG(("Start"));
897
898   /* Send the message to clients on the channel's client list. */
899   silc_hash_table_list(channel->user_list, &htl);
900   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
901     if (chl->client && !chl->client->router) {
902       sock = (SilcSocketConnection)chl->client->connection;
903
904       /* Send the packet to the client */
905       silc_server_packet_send_dest(server, sock, type, flags, chl->client->id,
906                                    SILC_ID_CLIENT, data, data_len,
907                                    force_send);
908     }
909   }
910 }
911
912 /* Routine used to send (relay, route) private messages to some destination.
913    If the private message key does not exist then the message is re-encrypted,
914    otherwise we just pass it along. This really is not used to send new
915    private messages (as server does not send them) but to relay received
916    private messages. */
917
918 void silc_server_send_private_message(SilcServer server,
919                                       SilcSocketConnection dst_sock,
920                                       SilcCipher cipher,
921                                       SilcHmac hmac,
922                                       uint32 sequence,
923                                       SilcPacketContext *packet)
924 {
925   SilcBuffer buffer = packet->buffer;
926
927   /* Re-encrypt and send if private messge key does not exist */
928   if (!(packet->flags & SILC_PACKET_FLAG_PRIVMSG_KEY)) {
929
930     silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
931                      + packet->dst_id_len + packet->padlen);
932     silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
933     silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
934
935     /* Re-encrypt packet */
936     silc_packet_encrypt(cipher, hmac, sequence, dst_sock->outbuf, buffer->len);
937
938     /* Send the packet */
939     silc_server_packet_send_real(server, dst_sock, FALSE);
940
941   } else {
942     /* Key exist so encrypt just header and send it */
943     silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
944                      + packet->dst_id_len + packet->padlen);
945     silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
946     silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
947
948     /* Encrypt header */
949     silc_packet_encrypt(cipher, hmac, sequence, dst_sock->outbuf, 
950                         SILC_PACKET_HEADER_LEN + packet->src_id_len + 
951                         packet->dst_id_len + packet->padlen);
952
953     silc_server_packet_send_real(server, dst_sock, FALSE);
954   }
955 }
956
957 /* Sends current motd to client */
958
959 void silc_server_send_motd(SilcServer server,
960                            SilcSocketConnection sock)
961 {
962   char *motd;
963   uint32 motd_len;
964
965   if (server->config && server->config->motd && 
966       server->config->motd->motd_file) {
967
968     motd = silc_file_read(server->config->motd->motd_file, &motd_len);
969     if (!motd)
970       return;
971
972     silc_server_send_notify(server, sock, FALSE, SILC_NOTIFY_TYPE_MOTD, 1,
973                             motd, motd_len);
974     silc_free(motd);
975   }
976 }
977
978 /* Sends error message. Error messages may or may not have any 
979    implications. */
980
981 void silc_server_send_error(SilcServer server,
982                             SilcSocketConnection sock,
983                             const char *fmt, ...)
984 {
985   va_list ap;
986   unsigned char buf[4096];
987
988   memset(buf, 0, sizeof(buf));
989   va_start(ap, fmt);
990   vsprintf(buf, fmt, ap);
991   va_end(ap);
992
993   silc_server_packet_send(server, sock, SILC_PACKET_ERROR, 0, 
994                           buf, strlen(buf), FALSE);
995 }
996
997 /* Sends notify message. If format is TRUE the variable arguments are
998    formatted and the formatted string is sent as argument payload. If it is
999    FALSE then each argument is sent as separate argument and their format
1000    in the argument list must be { argument data, argument length }. */
1001
1002 void silc_server_send_notify(SilcServer server,
1003                              SilcSocketConnection sock,
1004                              bool broadcast,
1005                              SilcNotifyType type,
1006                              uint32 argc, ...)
1007 {
1008   va_list ap;
1009   SilcBuffer packet;
1010
1011   va_start(ap, argc);
1012
1013   packet = silc_notify_payload_encode(type, argc, ap);
1014   silc_server_packet_send(server, sock, SILC_PACKET_NOTIFY, 
1015                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
1016                           packet->data, packet->len, FALSE);
1017
1018   /* Send to backup routers if this is being broadcasted to primary
1019      router. */
1020   if (server->router && server->router->connection &&
1021       sock == server->router->connection && broadcast)
1022     silc_server_backup_send(server, NULL, SILC_PACKET_NOTIFY, 0,
1023                             packet->data, packet->len, FALSE, TRUE);
1024
1025   silc_buffer_free(packet);
1026   va_end(ap);
1027 }
1028
1029 /* Sends notify message and gets the arguments from the `args' Argument
1030    Payloads. */
1031
1032 void silc_server_send_notify_args(SilcServer server,
1033                                   SilcSocketConnection sock,
1034                                   bool broadcast,
1035                                   SilcNotifyType type,
1036                                   uint32 argc,
1037                                   SilcBuffer args)
1038 {
1039   SilcBuffer packet;
1040
1041   packet = silc_notify_payload_encode_args(type, argc, args);
1042   silc_server_packet_send(server, sock, SILC_PACKET_NOTIFY, 
1043                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
1044                           packet->data, packet->len, FALSE);
1045   silc_buffer_free(packet);
1046 }
1047
1048 /* Send CHANNEL_CHANGE notify type. This tells the receiver to replace the
1049    `old_id' with the `new_id'. */
1050
1051 void silc_server_send_notify_channel_change(SilcServer server,
1052                                             SilcSocketConnection sock,
1053                                             bool broadcast,
1054                                             SilcChannelID *old_id,
1055                                             SilcChannelID *new_id)
1056 {
1057   SilcBuffer idp1, idp2;
1058
1059   idp1 = silc_id_payload_encode((void *)old_id, SILC_ID_CHANNEL);
1060   idp2 = silc_id_payload_encode((void *)new_id, SILC_ID_CHANNEL);
1061
1062   silc_server_send_notify(server, sock, broadcast,
1063                           SILC_NOTIFY_TYPE_CHANNEL_CHANGE,
1064                           2, idp1->data, idp1->len, idp2->data, idp2->len);
1065   silc_buffer_free(idp1);
1066   silc_buffer_free(idp2);
1067 }
1068
1069 /* Send NICK_CHANGE notify type. This tells the receiver to replace the
1070    `old_id' with the `new_id'. */
1071
1072 void silc_server_send_notify_nick_change(SilcServer server,
1073                                          SilcSocketConnection sock,
1074                                          bool broadcast,
1075                                          SilcClientID *old_id,
1076                                          SilcClientID *new_id)
1077 {
1078   SilcBuffer idp1, idp2;
1079
1080   idp1 = silc_id_payload_encode((void *)old_id, SILC_ID_CLIENT);
1081   idp2 = silc_id_payload_encode((void *)new_id, SILC_ID_CLIENT);
1082
1083   silc_server_send_notify(server, sock, broadcast, 
1084                           SILC_NOTIFY_TYPE_NICK_CHANGE,
1085                           2, idp1->data, idp1->len, idp2->data, idp2->len);
1086   silc_buffer_free(idp1);
1087   silc_buffer_free(idp2);
1088 }
1089
1090 /* Sends JOIN notify type. This tells that new client by `client_id' ID
1091    has joined to the `channel'. */
1092
1093 void silc_server_send_notify_join(SilcServer server,
1094                                   SilcSocketConnection sock,
1095                                   bool broadcast,
1096                                   SilcChannelEntry channel,
1097                                   SilcClientID *client_id)
1098 {
1099   SilcBuffer idp1, idp2;
1100
1101   idp1 = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1102   idp2 = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
1103   silc_server_send_notify(server, sock, broadcast, SILC_NOTIFY_TYPE_JOIN,
1104                           2, idp1->data, idp1->len,
1105                           idp2->data, idp2->len);
1106   silc_buffer_free(idp1);
1107   silc_buffer_free(idp2);
1108 }
1109
1110 /* Sends LEAVE notify type. This tells that `client_id' has left the
1111    `channel'. The Notify packet is always destined to the channel. */
1112
1113 void silc_server_send_notify_leave(SilcServer server,
1114                                    SilcSocketConnection sock,
1115                                    bool broadcast,
1116                                    SilcChannelEntry channel,
1117                                    SilcClientID *client_id)
1118 {
1119   SilcBuffer idp;
1120
1121   idp = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1122   silc_server_send_notify_dest(server, sock, broadcast, (void *)channel->id,
1123                                SILC_ID_CHANNEL, SILC_NOTIFY_TYPE_LEAVE,
1124                                1, idp->data, idp->len);
1125   silc_buffer_free(idp);
1126 }
1127
1128 /* Sends CMODE_CHANGE notify type. This tells that `client_id' changed the
1129    `channel' mode to `mode. The Notify packet is always destined to
1130    the channel. */
1131
1132 void silc_server_send_notify_cmode(SilcServer server,
1133                                    SilcSocketConnection sock,
1134                                    bool broadcast,
1135                                    SilcChannelEntry channel,
1136                                    uint32 mode_mask,
1137                                    void *id, SilcIdType id_type,
1138                                    char *cipher, char *hmac)
1139 {
1140   SilcBuffer idp;
1141   unsigned char mode[4];
1142
1143   idp = silc_id_payload_encode((void *)id, id_type);
1144   SILC_PUT32_MSB(mode_mask, mode);
1145
1146   silc_server_send_notify_dest(server, sock, broadcast, (void *)channel->id,
1147                                SILC_ID_CHANNEL, SILC_NOTIFY_TYPE_CMODE_CHANGE,
1148                                4, idp->data, idp->len,
1149                                mode, 4,
1150                                cipher, cipher ? strlen(cipher) : 0,
1151                                hmac, hmac ? strlen(hmac) : 0);
1152   silc_buffer_free(idp);
1153 }
1154
1155 /* Sends CUMODE_CHANGE notify type. This tells that `client_id' changed the
1156    `target' client's mode on `channel'. The Notify packet is always
1157    destined to the channel. */
1158
1159 void silc_server_send_notify_cumode(SilcServer server,
1160                                     SilcSocketConnection sock,
1161                                     bool broadcast,
1162                                     SilcChannelEntry channel,
1163                                     uint32 mode_mask,
1164                                     void *id, SilcIdType id_type,
1165                                     SilcClientID *target)
1166 {
1167   SilcBuffer idp1, idp2;
1168   unsigned char mode[4];
1169
1170   idp1 = silc_id_payload_encode((void *)id, id_type);
1171   idp2 = silc_id_payload_encode((void *)target, SILC_ID_CLIENT);
1172   SILC_PUT32_MSB(mode_mask, mode);
1173
1174   silc_server_send_notify_dest(server, sock, broadcast, (void *)channel->id,
1175                                SILC_ID_CHANNEL, 
1176                                SILC_NOTIFY_TYPE_CUMODE_CHANGE, 3, 
1177                                idp1->data, idp1->len,
1178                                mode, 4,
1179                                idp2->data, idp2->len);
1180   silc_buffer_free(idp1);
1181   silc_buffer_free(idp2);
1182 }
1183
1184 /* Sends SIGNOFF notify type. This tells that `client_id' client has
1185    left SILC network. This function is used only between server and router
1186    traffic. This is not used to send the notify to the channel for
1187    client. The `message may be NULL. */
1188
1189 void silc_server_send_notify_signoff(SilcServer server,
1190                                      SilcSocketConnection sock,
1191                                      bool broadcast,
1192                                      SilcClientID *client_id,
1193                                      char *message)
1194 {
1195   SilcBuffer idp;
1196
1197   idp = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1198   silc_server_send_notify(server, sock, broadcast,
1199                           SILC_NOTIFY_TYPE_SIGNOFF,
1200                           message ? 2 : 1, idp->data, idp->len,
1201                           message, message ? strlen(message): 0);
1202   silc_buffer_free(idp);
1203 }
1204
1205 /* Sends TOPIC_SET notify type. This tells that `client_id' changed
1206    the `channel's topic to `topic'. The Notify packet is always destined
1207    to the channel. This function is used to send the topic set notifies
1208    between routers. */
1209
1210 void silc_server_send_notify_topic_set(SilcServer server,
1211                                        SilcSocketConnection sock,
1212                                        bool broadcast,
1213                                        SilcChannelEntry channel,
1214                                        SilcClientID *client_id,
1215                                        char *topic)
1216 {
1217   SilcBuffer idp;
1218
1219   idp = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1220   silc_server_send_notify(server, sock, broadcast,
1221                           SILC_NOTIFY_TYPE_TOPIC_SET,
1222                           topic ? 2 : 1, 
1223                           idp->data, idp->len, 
1224                           topic, topic ? strlen(topic) : 0);
1225   silc_buffer_free(idp);
1226 }
1227
1228 /* Send KICKED notify type. This tells that the `client_id' on `channel'
1229    was kicked off the channel.  The `comment' may indicate the reason
1230    for the kicking. This function is used only between server and router
1231    traffic. */
1232
1233 void silc_server_send_notify_kicked(SilcServer server,
1234                                     SilcSocketConnection sock,
1235                                     bool broadcast,
1236                                     SilcChannelEntry channel,
1237                                     SilcClientID *client_id,
1238                                     char *comment)
1239 {
1240   SilcBuffer idp;
1241
1242   idp = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1243   silc_server_send_notify_dest(server, sock, broadcast, (void *)channel->id,
1244                                SILC_ID_CHANNEL, SILC_NOTIFY_TYPE_KICKED,
1245                                comment ? 2 : 1, idp->data, idp->len,
1246                                comment, comment ? strlen(comment) : 0);
1247   silc_buffer_free(idp);
1248 }
1249
1250 /* Send KILLED notify type. This tells that the `client_id' client was
1251    killed from the network.  The `comment' may indicate the reason
1252    for the killing. */
1253
1254 void silc_server_send_notify_killed(SilcServer server,
1255                                     SilcSocketConnection sock,
1256                                     bool broadcast,
1257                                     SilcClientID *client_id,
1258                                     char *comment)
1259 {
1260   SilcBuffer idp;
1261
1262   idp = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1263   silc_server_send_notify_dest(server, sock, broadcast, (void *)client_id,
1264                                SILC_ID_CLIENT, SILC_NOTIFY_TYPE_KILLED,
1265                                comment ? 2 : 1, idp->data, idp->len,
1266                                comment, comment ? strlen(comment) : 0);
1267   silc_buffer_free(idp);
1268 }
1269
1270 /* Sends UMODE_CHANGE notify type. This tells that `client_id' client's
1271    user mode in the SILC Network was changed. This function is used to
1272    send the packet between routers as broadcast packet. */
1273
1274 void silc_server_send_notify_umode(SilcServer server,
1275                                    SilcSocketConnection sock,
1276                                    bool broadcast,
1277                                    SilcClientID *client_id,
1278                                    uint32 mode_mask)
1279 {
1280   SilcBuffer idp;
1281   unsigned char mode[4];
1282
1283   idp = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1284   SILC_PUT32_MSB(mode_mask, mode);
1285
1286   silc_server_send_notify(server, sock, broadcast,
1287                           SILC_NOTIFY_TYPE_UMODE_CHANGE, 2,
1288                           idp->data, idp->len, 
1289                           mode, 4);
1290   silc_buffer_free(idp);
1291 }
1292
1293 /* Sends BAN notify type. This tells that ban has been either `add'ed
1294    or `del'eted on the `channel. This function is used to send the packet
1295    between routers as broadcast packet. */
1296
1297 void silc_server_send_notify_ban(SilcServer server,
1298                                  SilcSocketConnection sock,
1299                                  bool broadcast,
1300                                  SilcChannelEntry channel,
1301                                  char *add, char *del)
1302 {
1303   SilcBuffer idp;
1304
1305   idp = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
1306   silc_server_send_notify(server, sock, broadcast,
1307                           SILC_NOTIFY_TYPE_BAN, 3,
1308                           idp->data, idp->len,
1309                           add, add ? strlen(add) : 0,
1310                           del, del ? strlen(del) : 0);
1311   silc_buffer_free(idp);
1312 }
1313
1314 /* Sends INVITE notify type. This tells that invite has been either `add'ed
1315    or `del'eted on the `channel.  The sender of the invite is the `client_id'.
1316    This function is used to send the packet between routers as broadcast
1317    packet. */
1318
1319 void silc_server_send_notify_invite(SilcServer server,
1320                                     SilcSocketConnection sock,
1321                                     bool broadcast,
1322                                     SilcChannelEntry channel,
1323                                     SilcClientID *client_id,
1324                                     char *add, char *del)
1325 {
1326   SilcBuffer idp, idp2;
1327
1328   idp = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
1329   idp2 = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1330   silc_server_send_notify(server, sock, broadcast,
1331                           SILC_NOTIFY_TYPE_INVITE, 5,
1332                           idp->data, idp->len,
1333                           channel->channel_name, strlen(channel->channel_name),
1334                           idp2->data, idp2->len,
1335                           add, add ? strlen(add) : 0,
1336                           del, del ? strlen(del) : 0);
1337   silc_buffer_free(idp);
1338   silc_buffer_free(idp2);
1339 }
1340
1341 /* Sends notify message destined to specific entity. */
1342
1343 void silc_server_send_notify_dest(SilcServer server,
1344                                   SilcSocketConnection sock,
1345                                   bool broadcast,
1346                                   void *dest_id,
1347                                   SilcIdType dest_id_type,
1348                                   SilcNotifyType type,
1349                                   uint32 argc, ...)
1350 {
1351   va_list ap;
1352   SilcBuffer packet;
1353
1354   va_start(ap, argc);
1355
1356   packet = silc_notify_payload_encode(type, argc, ap);
1357   silc_server_packet_send_dest(server, sock, SILC_PACKET_NOTIFY, 
1358                                broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
1359                                dest_id, dest_id_type,
1360                                packet->data, packet->len, FALSE);
1361   silc_buffer_free(packet);
1362   va_end(ap);
1363 }
1364
1365 /* Sends notify message to a channel. The notify message sent is 
1366    distributed to all clients on the channel. If `route_notify' is TRUE
1367    then the notify may be routed to primary route or to some other routers.
1368    If FALSE it is assured that the notify is sent only locally. If `sender'
1369    is provided then the packet is not sent to that connection since it
1370    originally came from it. */
1371
1372 void silc_server_send_notify_to_channel(SilcServer server,
1373                                         SilcSocketConnection sender,
1374                                         SilcChannelEntry channel,
1375                                         unsigned char route_notify,
1376                                         SilcNotifyType type,
1377                                         uint32 argc, ...)
1378 {
1379   va_list ap;
1380   SilcBuffer packet;
1381
1382   va_start(ap, argc);
1383
1384   packet = silc_notify_payload_encode(type, argc, ap);
1385   silc_server_packet_send_to_channel(server, sender, channel, 
1386                                      SILC_PACKET_NOTIFY, route_notify,
1387                                      packet->data, packet->len, FALSE);
1388   silc_buffer_free(packet);
1389   va_end(ap);
1390 }
1391
1392 /* Send notify message to all channels the client has joined. It is quaranteed
1393    that the message is sent only once to a client (ie. if a client is joined
1394    on two same channel it will receive only one notify message). Also, this
1395    sends only to local clients (locally connected if we are server, and to
1396    local servers if we are router). If `sender' is provided the packet is
1397    not sent to that client at all. */
1398
1399 void silc_server_send_notify_on_channels(SilcServer server,
1400                                          SilcClientEntry sender,
1401                                          SilcClientEntry client,
1402                                          SilcNotifyType type,
1403                                          uint32 argc, ...)
1404 {
1405   int k;
1406   SilcSocketConnection sock = NULL;
1407   SilcPacketContext packetdata;
1408   SilcClientEntry c;
1409   SilcClientEntry *sent_clients = NULL;
1410   uint32 sent_clients_count = 0;
1411   SilcServerEntry *routed = NULL;
1412   uint32 routed_count = 0;
1413   SilcHashTableList htl, htl2;
1414   SilcChannelEntry channel;
1415   SilcChannelClientEntry chl, chl2;
1416   SilcIDListData idata;
1417   SilcBuffer packet;
1418   unsigned char *data;
1419   uint32 data_len;
1420   bool force_send = FALSE;
1421   va_list ap;
1422   int block_len;
1423
1424   SILC_LOG_DEBUG(("Start"));
1425
1426   if (!silc_hash_table_count(client->channels))
1427     return;
1428
1429   va_start(ap, argc);
1430   packet = silc_notify_payload_encode(type, argc, ap);
1431   data = packet->data;
1432   data_len = packet->len;
1433
1434   /* Set the packet context pointers. */
1435   packetdata.flags = 0;
1436   packetdata.type = SILC_PACKET_NOTIFY;
1437   packetdata.src_id = silc_id_id2str(server->id, SILC_ID_SERVER);
1438   packetdata.src_id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1439   packetdata.src_id_type = SILC_ID_SERVER;
1440
1441   silc_hash_table_list(client->channels, &htl);
1442   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
1443     channel = chl->channel;
1444
1445     /* Send the message to all clients on the channel's client list. */
1446     silc_hash_table_list(channel->user_list, &htl2);
1447     while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
1448       c = chl2->client;
1449       
1450       if (sender && c == sender)
1451         continue;
1452
1453       /* Check if we have sent the packet to this client already */
1454       for (k = 0; k < sent_clients_count; k++)
1455         if (sent_clients[k] == c)
1456           break;
1457       if (k < sent_clients_count)
1458         continue;
1459
1460       /* If we are router and if this client has router set it is not
1461          locally connected client and we will route the message to the
1462          router set in the client. */
1463       if (c && c->router && server->server_type == SILC_ROUTER) {
1464         /* Check if we have sent the packet to this route already */
1465         for (k = 0; k < routed_count; k++)
1466           if (routed[k] == c->router)
1467             break;
1468         if (k < routed_count)
1469           continue;
1470         
1471         /* Get data used in packet header encryption, keys and stuff. */
1472         sock = (SilcSocketConnection)c->router->connection;
1473         idata = (SilcIDListData)c->router;
1474         block_len = idata->send_key ? 
1475           silc_cipher_get_block_len(idata->send_key) : 0;
1476
1477         packetdata.dst_id = silc_id_id2str(c->router->id, SILC_ID_SERVER);
1478         packetdata.dst_id_len = silc_id_get_len(c->router->id, SILC_ID_SERVER);
1479         packetdata.dst_id_type = SILC_ID_SERVER;
1480         packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN + 
1481           packetdata.src_id_len + packetdata.dst_id_len;
1482         packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen, block_len);
1483
1484         /* Send the packet */
1485         silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1486                                                 idata->send_key, 
1487                                                 idata->hmac_send, 
1488                                                 idata->psn_send++, 
1489                                                 data, data_len, FALSE, 
1490                                                 force_send);
1491         
1492         silc_free(packetdata.dst_id);
1493
1494         /* We want to make sure that the packet is routed to same router
1495            only once. Mark this route as sent route. */
1496         routed = silc_realloc(routed, sizeof(*routed) * (routed_count + 1));
1497         routed[routed_count++] = c->router;
1498         continue;
1499       }
1500
1501       if (c && c->router)
1502         continue;
1503
1504       /* Send to locally connected client */
1505       if (c) {
1506         
1507         /* Get data used in packet header encryption, keys and stuff. */
1508         sock = (SilcSocketConnection)c->connection;
1509         idata = (SilcIDListData)c;
1510         block_len = idata->send_key ? 
1511           silc_cipher_get_block_len(idata->send_key) : 0;
1512         
1513         packetdata.dst_id = silc_id_id2str(c->id, SILC_ID_CLIENT);
1514         packetdata.dst_id_len = silc_id_get_len(c->id, SILC_ID_CLIENT);
1515         packetdata.dst_id_type = SILC_ID_CLIENT;
1516         packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN + 
1517           packetdata.src_id_len + packetdata.dst_id_len;
1518         packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen, block_len);
1519
1520         /* Send the packet */
1521         silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1522                                                 idata->send_key, 
1523                                                 idata->hmac_send, 
1524                                                 idata->psn_send++, 
1525                                                 data, data_len, FALSE, 
1526                                                 force_send);
1527
1528         silc_free(packetdata.dst_id);
1529
1530         /* Make sure that we send the notify only once per client. */
1531         sent_clients = silc_realloc(sent_clients, sizeof(*sent_clients) * 
1532                                     (sent_clients_count + 1));
1533         sent_clients[sent_clients_count++] = c;
1534       }
1535     }
1536   }
1537
1538   silc_free(routed);
1539   silc_free(sent_clients);
1540   silc_free(packetdata.src_id);
1541   va_end(ap);
1542 }
1543
1544 /* Sends New ID Payload to remote end. The packet is used to distribute
1545    information about new registered clients, servers, channel etc. usually
1546    to routers so that they can keep these information up to date. 
1547    If the argument `broadcast' is TRUE then the packet is sent as
1548    broadcast packet. */
1549
1550 void silc_server_send_new_id(SilcServer server,
1551                              SilcSocketConnection sock,
1552                              bool broadcast,
1553                              void *id, SilcIdType id_type, 
1554                              uint32 id_len)
1555 {
1556   SilcBuffer idp;
1557
1558   SILC_LOG_DEBUG(("Start"));
1559
1560   idp = silc_id_payload_encode(id, id_type);
1561   silc_server_packet_send(server, sock, SILC_PACKET_NEW_ID, 
1562                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0, 
1563                           idp->data, idp->len, FALSE);
1564
1565   /* Send to backup routers if this is being broadcasted to primary
1566      router. */
1567   if (server->router && server->router->connection &&
1568       sock == server->router->connection && broadcast)
1569     silc_server_backup_send(server, NULL, SILC_PACKET_NEW_ID, 0,
1570                             idp->data, idp->len, FALSE, TRUE);
1571
1572   silc_buffer_free(idp);
1573 }
1574
1575 /* Send New Channel Payload to notify about newly created channel in the
1576    SILC network. Normal server nevers sends this packet. Router uses this
1577    to notify other routers in the network about new channel. This packet
1578    is broadcasted. */
1579
1580 void silc_server_send_new_channel(SilcServer server,
1581                                   SilcSocketConnection sock,
1582                                   bool broadcast,
1583                                   char *channel_name,
1584                                   void *channel_id, 
1585                                   uint32 channel_id_len,
1586                                   uint32 mode)
1587 {
1588   SilcBuffer packet;
1589   unsigned char *cid;
1590   uint32 name_len = strlen(channel_name);
1591
1592   SILC_LOG_DEBUG(("Start"));
1593
1594   cid = silc_id_id2str(channel_id, SILC_ID_CHANNEL);
1595   if (!cid)
1596     return;
1597
1598   /* Encode the channel payload */
1599   packet = silc_channel_payload_encode(channel_name, name_len,
1600                                        cid, channel_id_len, mode);
1601
1602   silc_server_packet_send(server, sock, SILC_PACKET_NEW_CHANNEL, 
1603                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0, 
1604                           packet->data, packet->len, FALSE);
1605
1606   /* Send to backup routers if this is being broadcasted to primary
1607      router. */
1608   if (server->router && server->router->connection &&
1609       sock == server->router->connection && broadcast)
1610     silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
1611                             packet->data, packet->len, FALSE, TRUE);
1612
1613   silc_free(cid);
1614   silc_buffer_free(packet);
1615 }
1616
1617 /* Send Channel Key payload to distribute the new channel key. Normal server
1618    sends this to router when new client joins to existing channel. Router
1619    sends this to the local server who sent the join command in case where
1620    the channel did not exist yet. Both normal and router servers uses this
1621    also to send this to locally connected clients on the channel. This
1622    must not be broadcasted packet. Routers do not send this to each other. 
1623    If `sender is provided then the packet is not sent to that connection since
1624    it originally came from it. */
1625
1626 void silc_server_send_channel_key(SilcServer server,
1627                                   SilcSocketConnection sender,
1628                                   SilcChannelEntry channel,
1629                                   unsigned char route)
1630 {
1631   SilcBuffer packet;
1632   unsigned char *chid;
1633   uint32 tmp_len;
1634  
1635   SILC_LOG_DEBUG(("Start"));
1636  
1637   chid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
1638   if (!chid)
1639     return;
1640  
1641   /* Encode channel key packet */
1642   tmp_len = strlen(channel->channel_key->cipher->name);
1643   packet = silc_channel_key_payload_encode(silc_id_get_len(channel->id,
1644                                                            SILC_ID_CHANNEL),
1645                                            chid, tmp_len,
1646                                            channel->channel_key->cipher->name,
1647                                            channel->key_len / 8, channel->key);
1648   silc_server_packet_send_to_channel(server, sender, channel, 
1649                                      SILC_PACKET_CHANNEL_KEY,
1650                                      route, packet->data, packet->len, FALSE);
1651   silc_buffer_free(packet);
1652   silc_free(chid);
1653 }
1654
1655 /* Generic function to send any command. The arguments must be sent already
1656    encoded into correct form in correct order. */
1657
1658 void silc_server_send_command(SilcServer server, 
1659                               SilcSocketConnection sock,
1660                               SilcCommand command, 
1661                               uint16 ident,
1662                               uint32 argc, ...)
1663 {
1664   SilcBuffer packet;
1665   va_list ap;
1666
1667   va_start(ap, argc);
1668
1669   packet = silc_command_payload_encode_vap(command, ident, argc, ap);
1670   silc_server_packet_send(server, sock, SILC_PACKET_COMMAND, 0,
1671                           packet->data, packet->len, TRUE);
1672   silc_buffer_free(packet);
1673   va_end(ap);
1674 }
1675
1676 /* Send the heartbeat packet. */
1677
1678 void silc_server_send_heartbeat(SilcServer server,
1679                                 SilcSocketConnection sock)
1680 {
1681   silc_server_packet_send(server, sock, SILC_PACKET_HEARTBEAT, 0,
1682                           NULL, 0, FALSE);
1683 }
1684
1685 /* Generic function to relay packet we've received. This is used to relay
1686    packets to a client but generally can be used to other purposes as well. */
1687
1688 void silc_server_relay_packet(SilcServer server,
1689                               SilcSocketConnection dst_sock,
1690                               SilcCipher cipher,
1691                               SilcHmac hmac,
1692                               uint32 sequence,
1693                               SilcPacketContext *packet,
1694                               bool force_send)
1695 {
1696   silc_buffer_push(packet->buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
1697                    + packet->dst_id_len + packet->padlen);
1698
1699   silc_packet_send_prepare(dst_sock, 0, 0, packet->buffer->len);
1700   silc_buffer_put(dst_sock->outbuf, packet->buffer->data, packet->buffer->len);
1701   
1702   /* Re-encrypt packet */
1703   silc_packet_encrypt(cipher, hmac, sequence, dst_sock->outbuf, 
1704                       packet->buffer->len);
1705   
1706   /* Send the packet */
1707   silc_server_packet_send_real(server, dst_sock, force_send);
1708
1709   silc_buffer_pull(packet->buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
1710                    + packet->dst_id_len + packet->padlen);
1711 }
1712
1713 /* Routine used to send the connection authentication packet. */
1714
1715 void silc_server_send_connection_auth_request(SilcServer server,
1716                                               SilcSocketConnection sock,
1717                                               uint16 conn_type,
1718                                               SilcAuthMethod auth_meth)
1719 {
1720   SilcBuffer packet;
1721
1722   packet = silc_buffer_alloc(4);
1723   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1724   silc_buffer_format(packet,
1725                      SILC_STR_UI_SHORT(conn_type),
1726                      SILC_STR_UI_SHORT(auth_meth),
1727                      SILC_STR_END);
1728
1729   silc_server_packet_send(server, sock, SILC_PACKET_CONNECTION_AUTH_REQUEST,
1730                           0, packet->data, packet->len, FALSE);
1731   silc_buffer_free(packet);
1732 }
1733
1734 /* Purge the outgoing packet queue to the network if there is data. This
1735    function can be used to empty the packet queue. It is guaranteed that
1736    after this function returns the outgoing data queue is empty. */
1737
1738 void silc_server_packet_queue_purge(SilcServer server,
1739                                     SilcSocketConnection sock)
1740 {
1741   if (sock && SILC_IS_OUTBUF_PENDING(sock) && 
1742       (SILC_IS_DISCONNECTED(sock) == FALSE)) {
1743     server->stat.packets_sent++;
1744
1745     if (sock->outbuf->data - sock->outbuf->head)
1746       silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1747
1748     silc_packet_send(sock, TRUE);
1749
1750     SILC_SET_CONNECTION_FOR_INPUT(server->schedule, sock->sock);
1751     SILC_UNSET_OUTBUF_PENDING(sock);
1752     silc_buffer_clear(sock->outbuf);
1753   }
1754 }