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