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