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