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