Assure that channel key is set before sending it.
[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 && !chl->client->router) {
984       sock = (SilcSocketConnection)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     silc_server_send_notify(server, sock, FALSE, SILC_NOTIFY_TYPE_MOTD, 1,
1052                             motd, motd_len);
1053     silc_free(motd);
1054   }
1055 }
1056
1057 /* Sends error message. Error messages may or may not have any 
1058    implications. */
1059
1060 void silc_server_send_error(SilcServer server,
1061                             SilcSocketConnection sock,
1062                             const char *fmt, ...)
1063 {
1064   va_list ap;
1065   unsigned char buf[4096];
1066
1067   memset(buf, 0, sizeof(buf));
1068   va_start(ap, fmt);
1069   vsprintf(buf, fmt, ap);
1070   va_end(ap);
1071
1072   silc_server_packet_send(server, sock, SILC_PACKET_ERROR, 0, 
1073                           buf, strlen(buf), FALSE);
1074 }
1075
1076 /* Sends notify message. If format is TRUE the variable arguments are
1077    formatted and the formatted string is sent as argument payload. If it is
1078    FALSE then each argument is sent as separate argument and their format
1079    in the argument list must be { argument data, argument length }. */
1080
1081 void silc_server_send_notify(SilcServer server,
1082                              SilcSocketConnection sock,
1083                              bool broadcast,
1084                              SilcNotifyType type,
1085                              SilcUInt32 argc, ...)
1086 {
1087   va_list ap;
1088   SilcBuffer packet;
1089
1090   va_start(ap, argc);
1091
1092   packet = silc_notify_payload_encode(type, argc, ap);
1093   silc_server_packet_send(server, sock, SILC_PACKET_NOTIFY, 
1094                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
1095                           packet->data, packet->len, FALSE);
1096
1097   /* Send to backup routers if this is being broadcasted to primary
1098      router.  The silc_server_backup_send checks further whether to
1099      actually send it or not. */
1100   if ((broadcast && sock && sock == SILC_PRIMARY_ROUTE(server)) ||
1101       (broadcast && !sock && !SILC_PRIMARY_ROUTE(server)))
1102     silc_server_backup_send(server, NULL, SILC_PACKET_NOTIFY, 0,
1103                             packet->data, packet->len, FALSE, TRUE);
1104
1105   silc_buffer_free(packet);
1106   va_end(ap);
1107 }
1108
1109 /* Sends notify message and gets the arguments from the `args' Argument
1110    Payloads. */
1111
1112 void silc_server_send_notify_args(SilcServer server,
1113                                   SilcSocketConnection sock,
1114                                   bool broadcast,
1115                                   SilcNotifyType type,
1116                                   SilcUInt32 argc,
1117                                   SilcBuffer args)
1118 {
1119   SilcBuffer packet;
1120
1121   packet = silc_notify_payload_encode_args(type, argc, args);
1122   silc_server_packet_send(server, sock, SILC_PACKET_NOTIFY, 
1123                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
1124                           packet->data, packet->len, FALSE);
1125   silc_buffer_free(packet);
1126 }
1127
1128 /* Send CHANNEL_CHANGE notify type. This tells the receiver to replace the
1129    `old_id' with the `new_id'. */
1130
1131 void silc_server_send_notify_channel_change(SilcServer server,
1132                                             SilcSocketConnection sock,
1133                                             bool broadcast,
1134                                             SilcChannelID *old_id,
1135                                             SilcChannelID *new_id)
1136 {
1137   SilcBuffer idp1, idp2;
1138
1139   idp1 = silc_id_payload_encode((void *)old_id, SILC_ID_CHANNEL);
1140   idp2 = silc_id_payload_encode((void *)new_id, SILC_ID_CHANNEL);
1141
1142   silc_server_send_notify(server, sock, broadcast,
1143                           SILC_NOTIFY_TYPE_CHANNEL_CHANGE,
1144                           2, idp1->data, idp1->len, idp2->data, idp2->len);
1145   silc_buffer_free(idp1);
1146   silc_buffer_free(idp2);
1147 }
1148
1149 /* Send NICK_CHANGE notify type. This tells the receiver to replace the
1150    `old_id' with the `new_id'. */
1151
1152 void silc_server_send_notify_nick_change(SilcServer server,
1153                                          SilcSocketConnection sock,
1154                                          bool broadcast,
1155                                          SilcClientID *old_id,
1156                                          SilcClientID *new_id,
1157                                          const char *nickname)
1158 {
1159   SilcBuffer idp1, idp2;
1160
1161   idp1 = silc_id_payload_encode((void *)old_id, SILC_ID_CLIENT);
1162   idp2 = silc_id_payload_encode((void *)new_id, SILC_ID_CLIENT);
1163
1164   silc_server_send_notify(server, sock, broadcast, 
1165                           SILC_NOTIFY_TYPE_NICK_CHANGE,
1166                           3, idp1->data, idp1->len, idp2->data, idp2->len,
1167                           nickname, nickname ? strlen(nickname) : 0);
1168   silc_buffer_free(idp1);
1169   silc_buffer_free(idp2);
1170 }
1171
1172 /* Sends JOIN notify type. This tells that new client by `client_id' ID
1173    has joined to the `channel'. */
1174
1175 void silc_server_send_notify_join(SilcServer server,
1176                                   SilcSocketConnection sock,
1177                                   bool broadcast,
1178                                   SilcChannelEntry channel,
1179                                   SilcClientID *client_id)
1180 {
1181   SilcBuffer idp1, idp2;
1182
1183   idp1 = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1184   idp2 = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
1185   silc_server_send_notify(server, sock, broadcast, SILC_NOTIFY_TYPE_JOIN,
1186                           2, idp1->data, idp1->len,
1187                           idp2->data, idp2->len);
1188   silc_buffer_free(idp1);
1189   silc_buffer_free(idp2);
1190 }
1191
1192 /* Sends LEAVE notify type. This tells that `client_id' has left the
1193    `channel'. The Notify packet is always destined to the channel. */
1194
1195 void silc_server_send_notify_leave(SilcServer server,
1196                                    SilcSocketConnection sock,
1197                                    bool broadcast,
1198                                    SilcChannelEntry channel,
1199                                    SilcClientID *client_id)
1200 {
1201   SilcBuffer idp;
1202
1203   idp = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1204   silc_server_send_notify_dest(server, sock, broadcast, (void *)channel->id,
1205                                SILC_ID_CHANNEL, SILC_NOTIFY_TYPE_LEAVE,
1206                                1, idp->data, idp->len);
1207   silc_buffer_free(idp);
1208 }
1209
1210 /* Sends CMODE_CHANGE notify type. This tells that `client_id' changed the
1211    `channel' mode to `mode. The Notify packet is always destined to
1212    the channel. */
1213
1214 void silc_server_send_notify_cmode(SilcServer server,
1215                                    SilcSocketConnection sock,
1216                                    bool broadcast,
1217                                    SilcChannelEntry channel,
1218                                    SilcUInt32 mode_mask,
1219                                    void *id, SilcIdType id_type,
1220                                    const char *cipher, const char *hmac,
1221                                    const char *passphrase,
1222                                    SilcPublicKey founder_key)
1223 {
1224   SilcBuffer idp;
1225   unsigned char mode[4], *key = NULL;
1226   SilcUInt32 key_len = 0;
1227
1228   idp = silc_id_payload_encode((void *)id, id_type);
1229   SILC_PUT32_MSB(mode_mask, mode);
1230   if (founder_key)
1231     key = silc_pkcs_public_key_encode(founder_key, &key_len);
1232
1233   silc_server_send_notify_dest(server, sock, broadcast, (void *)channel->id,
1234                                SILC_ID_CHANNEL, SILC_NOTIFY_TYPE_CMODE_CHANGE,
1235                                6, idp->data, idp->len,
1236                                mode, 4,
1237                                cipher, cipher ? strlen(cipher) : 0,
1238                                hmac, hmac ? strlen(hmac) : 0,
1239                                passphrase, passphrase ? 
1240                                strlen(passphrase) : 0,
1241                                key, key_len);
1242   silc_free(key);
1243   silc_buffer_free(idp);
1244 }
1245
1246 /* Sends CUMODE_CHANGE notify type. This tells that `id' changed the
1247    `target' client's mode on `channel'. The notify packet is always
1248    destined to the channel. */
1249
1250 void silc_server_send_notify_cumode(SilcServer server,
1251                                     SilcSocketConnection sock,
1252                                     bool broadcast,
1253                                     SilcChannelEntry channel,
1254                                     SilcUInt32 mode_mask,
1255                                     void *id, SilcIdType id_type,
1256                                     SilcClientID *target,
1257                                     SilcPublicKey founder_key)
1258 {
1259   SilcBuffer idp1, idp2;
1260   unsigned char mode[4], *key = NULL;
1261   SilcUInt32 key_len = 0;
1262
1263   idp1 = silc_id_payload_encode((void *)id, id_type);
1264   idp2 = silc_id_payload_encode((void *)target, SILC_ID_CLIENT);
1265   SILC_PUT32_MSB(mode_mask, mode);
1266   if (founder_key)
1267     key = silc_pkcs_public_key_encode(founder_key, &key_len);
1268
1269   silc_server_send_notify_dest(server, sock, broadcast, (void *)channel->id,
1270                                SILC_ID_CHANNEL, 
1271                                SILC_NOTIFY_TYPE_CUMODE_CHANGE, 4, 
1272                                idp1->data, idp1->len,
1273                                mode, 4,
1274                                idp2->data, idp2->len,
1275                                key, key_len);
1276   silc_free(key);
1277   silc_buffer_free(idp1);
1278   silc_buffer_free(idp2);
1279 }
1280
1281 /* Sends SIGNOFF notify type. This tells that `client_id' client has
1282    left SILC network. This function is used only between server and router
1283    traffic. This is not used to send the notify to the channel for
1284    client. The `message may be NULL. */
1285
1286 void silc_server_send_notify_signoff(SilcServer server,
1287                                      SilcSocketConnection sock,
1288                                      bool broadcast,
1289                                      SilcClientID *client_id,
1290                                      const char *message)
1291 {
1292   SilcBuffer idp;
1293
1294   idp = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1295   silc_server_send_notify(server, sock, broadcast,
1296                           SILC_NOTIFY_TYPE_SIGNOFF,
1297                           message ? 2 : 1, idp->data, idp->len,
1298                           message, message ? strlen(message): 0);
1299   silc_buffer_free(idp);
1300 }
1301
1302 /* Sends TOPIC_SET notify type. This tells that `id' changed
1303    the `channel's topic to `topic'. The Notify packet is always destined
1304    to the channel. This function is used to send the topic set notifies
1305    between routers. */
1306
1307 void silc_server_send_notify_topic_set(SilcServer server,
1308                                        SilcSocketConnection sock,
1309                                        bool broadcast,
1310                                        SilcChannelEntry channel,
1311                                        void *id, SilcIdType id_type,
1312                                        char *topic)
1313 {
1314   SilcBuffer idp;
1315
1316   idp = silc_id_payload_encode(id, id_type);
1317   silc_server_send_notify_dest(server, sock, broadcast,
1318                                (void *)channel->id, SILC_ID_CHANNEL,
1319                                SILC_NOTIFY_TYPE_TOPIC_SET,
1320                                topic ? 2 : 1, 
1321                                idp->data, idp->len, 
1322                                topic, topic ? strlen(topic) : 0);
1323   silc_buffer_free(idp);
1324 }
1325
1326 /* Send KICKED notify type. This tells that the `client_id' on `channel'
1327    was kicked off the channel.  The `comment' may indicate the reason
1328    for the kicking. This function is used only between server and router
1329    traffic. */
1330
1331 void silc_server_send_notify_kicked(SilcServer server,
1332                                     SilcSocketConnection sock,
1333                                     bool broadcast,
1334                                     SilcChannelEntry channel,
1335                                     SilcClientID *client_id,
1336                                     SilcClientID *kicker,
1337                                     char *comment)
1338 {
1339   SilcBuffer idp1;
1340   SilcBuffer idp2;
1341
1342   idp1 = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1343   idp2 = silc_id_payload_encode((void *)kicker, SILC_ID_CLIENT);
1344   silc_server_send_notify_dest(server, sock, broadcast, (void *)channel->id,
1345                                SILC_ID_CHANNEL, SILC_NOTIFY_TYPE_KICKED, 3,
1346                                idp1->data, idp1->len,
1347                                comment, comment ? strlen(comment) : 0,
1348                                idp2->data, idp2->len);
1349   silc_buffer_free(idp1);
1350   silc_buffer_free(idp2);
1351 }
1352
1353 /* Send KILLED notify type. This tells that the `client_id' client was
1354    killed from the network.  The `comment' may indicate the reason
1355    for the killing. */
1356
1357 void silc_server_send_notify_killed(SilcServer server,
1358                                     SilcSocketConnection sock,
1359                                     bool broadcast,
1360                                     SilcClientID *client_id,
1361                                     const char *comment,
1362                                     void *killer, SilcIdType killer_type)
1363 {
1364   SilcBuffer idp1;
1365   SilcBuffer idp2;
1366
1367   idp1 = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
1368   idp2 = silc_id_payload_encode(killer, killer_type);
1369   silc_server_send_notify_dest(server, sock, broadcast, (void *)client_id,
1370                                SILC_ID_CLIENT, SILC_NOTIFY_TYPE_KILLED,
1371                                3, idp1->data, idp1->len,
1372                                comment, comment ? strlen(comment) : 0,
1373                                idp2->data, idp2->len);
1374   silc_buffer_free(idp1);
1375   silc_buffer_free(idp2);
1376 }
1377
1378 /* Sends UMODE_CHANGE notify type. This tells that `client_id' client's
1379    user mode in the SILC Network was changed. This function is used to
1380    send the packet between routers as broadcast packet. */
1381
1382 void silc_server_send_notify_umode(SilcServer server,
1383                                    SilcSocketConnection sock,
1384                                    bool broadcast,
1385                                    SilcClientID *client_id,
1386                                    SilcUInt32 mode_mask)
1387 {
1388   SilcBuffer idp;
1389   unsigned char mode[4];
1390
1391   idp = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1392   SILC_PUT32_MSB(mode_mask, mode);
1393
1394   silc_server_send_notify(server, sock, broadcast,
1395                           SILC_NOTIFY_TYPE_UMODE_CHANGE, 2,
1396                           idp->data, idp->len, 
1397                           mode, 4);
1398   silc_buffer_free(idp);
1399 }
1400
1401 /* Sends BAN notify type. This tells that ban has been either `add'ed
1402    or `del'eted on the `channel. This function is used to send the packet
1403    between routers as broadcast packet. */
1404
1405 void silc_server_send_notify_ban(SilcServer server,
1406                                  SilcSocketConnection sock,
1407                                  bool broadcast,
1408                                  SilcChannelEntry channel,
1409                                  char *add, char *del)
1410 {
1411   SilcBuffer idp;
1412
1413   idp = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
1414   silc_server_send_notify(server, sock, broadcast,
1415                           SILC_NOTIFY_TYPE_BAN, 3,
1416                           idp->data, idp->len,
1417                           add, add ? strlen(add) : 0,
1418                           del, del ? strlen(del) : 0);
1419   silc_buffer_free(idp);
1420 }
1421
1422 /* Sends INVITE notify type. This tells that invite has been either `add'ed
1423    or `del'eted on the `channel.  The sender of the invite is the `client_id'.
1424    This function is used to send the packet between routers as broadcast
1425    packet. */
1426
1427 void silc_server_send_notify_invite(SilcServer server,
1428                                     SilcSocketConnection sock,
1429                                     bool broadcast,
1430                                     SilcChannelEntry channel,
1431                                     SilcClientID *client_id,
1432                                     char *add, char *del)
1433 {
1434   SilcBuffer idp, idp2;
1435
1436   idp = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
1437   idp2 = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1438   silc_server_send_notify(server, sock, broadcast,
1439                           SILC_NOTIFY_TYPE_INVITE, 5,
1440                           idp->data, idp->len,
1441                           channel->channel_name, strlen(channel->channel_name),
1442                           idp2->data, idp2->len,
1443                           add, add ? strlen(add) : 0,
1444                           del, del ? strlen(del) : 0);
1445   silc_buffer_free(idp);
1446   silc_buffer_free(idp2);
1447 }
1448
1449 /* Sends WATCH notify type. This tells that the `client' was watched and
1450    its status in the network has changed. */
1451
1452 void silc_server_send_notify_watch(SilcServer server,
1453                                    SilcSocketConnection sock,
1454                                    SilcClientEntry watcher,
1455                                    SilcClientEntry client,
1456                                    const char *nickname,
1457                                    SilcNotifyType type)
1458 {
1459   SilcBuffer idp;
1460   unsigned char mode[4], n[2];
1461
1462   idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
1463   SILC_PUT16_MSB(type, n);
1464   SILC_PUT32_MSB(client->mode, mode);
1465   silc_server_send_notify_dest(server, sock, FALSE, watcher->id,
1466                                SILC_ID_CLIENT, SILC_NOTIFY_TYPE_WATCH,
1467                                4, idp->data, idp->len,
1468                                nickname, nickname ? strlen(nickname) : 0,
1469                                mode, sizeof(mode), 
1470                                type != SILC_NOTIFY_TYPE_NONE ?
1471                                n : NULL, sizeof(n));
1472   silc_buffer_free(idp);
1473 }
1474
1475 /* Sends notify message destined to specific entity. */
1476
1477 void silc_server_send_notify_dest(SilcServer server,
1478                                   SilcSocketConnection sock,
1479                                   bool broadcast,
1480                                   void *dest_id,
1481                                   SilcIdType dest_id_type,
1482                                   SilcNotifyType type,
1483                                   SilcUInt32 argc, ...)
1484 {
1485   va_list ap;
1486   SilcBuffer packet;
1487
1488   va_start(ap, argc);
1489
1490   packet = silc_notify_payload_encode(type, argc, ap);
1491   silc_server_packet_send_dest(server, sock, SILC_PACKET_NOTIFY, 
1492                                broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
1493                                dest_id, dest_id_type,
1494                                packet->data, packet->len, FALSE);
1495
1496   /* Send to backup routers if this is being broadcasted to primary
1497      router.  The silc_server_backup_send checks further whether to
1498      actually send it or not. */
1499   if ((broadcast && sock && sock == SILC_PRIMARY_ROUTE(server)) ||
1500       (broadcast && !sock && !SILC_PRIMARY_ROUTE(server)))
1501     silc_server_backup_send_dest(server, NULL, SILC_PACKET_NOTIFY, 0,
1502                                  dest_id, dest_id_type,
1503                                  packet->data, packet->len, FALSE, TRUE);
1504
1505   silc_buffer_free(packet);
1506   va_end(ap);
1507 }
1508
1509 /* Sends notify message to a channel. The notify message sent is 
1510    distributed to all clients on the channel. If `route_notify' is TRUE
1511    then the notify may be routed to primary route or to some other routers.
1512    If FALSE it is assured that the notify is sent only locally. If `sender'
1513    is provided then the packet is not sent to that connection since it
1514    originally came from it. */
1515
1516 void silc_server_send_notify_to_channel(SilcServer server,
1517                                         SilcSocketConnection sender,
1518                                         SilcChannelEntry channel,
1519                                         bool route_notify,
1520                                         SilcNotifyType type,
1521                                         SilcUInt32 argc, ...)
1522 {
1523   va_list ap;
1524   SilcBuffer packet;
1525
1526   va_start(ap, argc);
1527
1528   packet = silc_notify_payload_encode(type, argc, ap);
1529   silc_server_packet_send_to_channel(server, sender, channel, 
1530                                      SILC_PACKET_NOTIFY, route_notify,
1531                                      packet->data, packet->len, FALSE);
1532   silc_buffer_free(packet);
1533   va_end(ap);
1534 }
1535
1536 /* Send notify message to all channels the client has joined. It is quaranteed
1537    that the message is sent only once to a client (ie. if a client is joined
1538    on two same channel it will receive only one notify message). Also, this
1539    sends only to local clients (locally connected if we are server, and to
1540    local servers if we are router). If `sender' is provided the packet is
1541    not sent to that client at all. */
1542
1543 void silc_server_send_notify_on_channels(SilcServer server,
1544                                          SilcClientEntry sender,
1545                                          SilcClientEntry client,
1546                                          SilcNotifyType type,
1547                                          SilcUInt32 argc, ...)
1548 {
1549   int k;
1550   SilcSocketConnection sock = NULL;
1551   SilcPacketContext packetdata;
1552   SilcClientEntry c;
1553   SilcClientEntry *sent_clients = NULL;
1554   SilcUInt32 sent_clients_count = 0;
1555   SilcServerEntry *routed = NULL;
1556   SilcUInt32 routed_count = 0;
1557   SilcHashTableList htl, htl2;
1558   SilcChannelEntry channel;
1559   SilcChannelClientEntry chl, chl2;
1560   SilcIDListData idata;
1561   SilcBuffer packet;
1562   unsigned char *data;
1563   SilcUInt32 data_len;
1564   bool force_send = FALSE;
1565   va_list ap;
1566
1567   if (!silc_hash_table_count(client->channels)) {
1568     SILC_LOG_DEBUG(("Client is not joined to any channels"));
1569     return;
1570   }
1571
1572   SILC_LOG_DEBUG(("Sending notify to joined channels"));
1573
1574   va_start(ap, argc);
1575   packet = silc_notify_payload_encode(type, argc, ap);
1576   data = packet->data;
1577   data_len = packet->len;
1578
1579   /* Set the packet context pointers. */
1580   packetdata.flags = 0;
1581   packetdata.type = SILC_PACKET_NOTIFY;
1582   packetdata.src_id = silc_id_id2str(server->id, SILC_ID_SERVER);
1583   packetdata.src_id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1584   packetdata.src_id_type = SILC_ID_SERVER;
1585
1586   silc_hash_table_list(client->channels, &htl);
1587   while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
1588     channel = chl->channel;
1589
1590     /* Send the message to all clients on the channel's client list. */
1591     silc_hash_table_list(channel->user_list, &htl2);
1592     while (silc_hash_table_get(&htl2, NULL, (void **)&chl2)) {
1593       c = chl2->client;
1594       
1595       if (sender && c == sender)
1596         continue;
1597
1598       /* Check if we have sent the packet to this client already */
1599       for (k = 0; k < sent_clients_count; k++)
1600         if (sent_clients[k] == c)
1601           break;
1602       if (k < sent_clients_count)
1603         continue;
1604
1605       /* If we are router and if this client has router set it is not
1606          locally connected client and we will route the message to the
1607          router set in the client. */
1608       if (c && c->router && server->server_type == SILC_ROUTER) {
1609         /* Check if we have sent the packet to this route already */
1610         for (k = 0; k < routed_count; k++)
1611           if (routed[k] == c->router)
1612             break;
1613         if (k < routed_count)
1614           continue;
1615         
1616         /* Get data used in packet header encryption, keys and stuff. */
1617         sock = (SilcSocketConnection)c->router->connection;
1618         idata = (SilcIDListData)c->router;
1619
1620         {
1621           SILC_LOG_DEBUG(("*****************"));
1622           SILC_LOG_DEBUG(("client->router->id %s",
1623                           silc_id_render(c->router->id, SILC_ID_SERVER)));
1624           SILC_LOG_DEBUG(("client->router->connection->user_data->id %s",
1625                           silc_id_render(((SilcServerEntry)sock->user_data)->id, SILC_ID_SERVER)));
1626         }
1627
1628         packetdata.dst_id = silc_id_id2str(c->router->id, SILC_ID_SERVER);
1629         packetdata.dst_id_len = silc_id_get_len(c->router->id, SILC_ID_SERVER);
1630         packetdata.dst_id_type = SILC_ID_SERVER;
1631
1632         /* Send the packet */
1633         silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1634                                                 idata->send_key, 
1635                                                 idata->hmac_send, 
1636                                                 idata->psn_send++, 
1637                                                 data, data_len, FALSE, 
1638                                                 force_send);
1639         
1640         silc_free(packetdata.dst_id);
1641
1642         /* We want to make sure that the packet is routed to same router
1643            only once. Mark this route as sent route. */
1644         routed = silc_realloc(routed, sizeof(*routed) * (routed_count + 1));
1645         routed[routed_count++] = c->router;
1646         continue;
1647       }
1648
1649       if (c && c->router)
1650         continue;
1651
1652       /* Send to locally connected client */
1653       if (c) {
1654         
1655         /* Get data used in packet header encryption, keys and stuff. */
1656         sock = (SilcSocketConnection)c->connection;
1657         idata = (SilcIDListData)c;
1658         
1659         if (!sock)
1660           continue;
1661
1662         packetdata.dst_id = silc_id_id2str(c->id, SILC_ID_CLIENT);
1663         packetdata.dst_id_len = silc_id_get_len(c->id, SILC_ID_CLIENT);
1664         packetdata.dst_id_type = SILC_ID_CLIENT;
1665
1666         /* Send the packet */
1667         silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1668                                                 idata->send_key, 
1669                                                 idata->hmac_send, 
1670                                                 idata->psn_send++, 
1671                                                 data, data_len, FALSE, 
1672                                                 force_send);
1673
1674         silc_free(packetdata.dst_id);
1675
1676         /* Make sure that we send the notify only once per client. */
1677         sent_clients = silc_realloc(sent_clients, sizeof(*sent_clients) * 
1678                                     (sent_clients_count + 1));
1679         sent_clients[sent_clients_count++] = c;
1680       }
1681     }
1682     silc_hash_table_list_reset(&htl2);
1683   }
1684
1685   silc_hash_table_list_reset(&htl);
1686   silc_free(routed);
1687   silc_free(sent_clients);
1688   silc_free(packetdata.src_id);
1689   silc_buffer_free(packet);
1690   va_end(ap);
1691 }
1692
1693 /* Sends New ID Payload to remote end. The packet is used to distribute
1694    information about new registered clients, servers, channel etc. usually
1695    to routers so that they can keep these information up to date. 
1696    If the argument `broadcast' is TRUE then the packet is sent as
1697    broadcast packet. */
1698
1699 void silc_server_send_new_id(SilcServer server,
1700                              SilcSocketConnection sock,
1701                              bool broadcast,
1702                              void *id, SilcIdType id_type, 
1703                              SilcUInt32 id_len)
1704 {
1705   SilcBuffer idp;
1706
1707   SILC_LOG_DEBUG(("Sending new ID"));
1708
1709   idp = silc_id_payload_encode(id, id_type);
1710   silc_server_packet_send(server, sock, SILC_PACKET_NEW_ID, 
1711                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0, 
1712                           idp->data, idp->len, FALSE);
1713   silc_buffer_free(idp);
1714 }
1715
1716 /* Send New Channel Payload to notify about newly created channel in the
1717    SILC network. Router uses this to notify other routers in the network 
1718    about new channel. This packet is broadcasted by router. */
1719
1720 void silc_server_send_new_channel(SilcServer server,
1721                                   SilcSocketConnection sock,
1722                                   bool broadcast,
1723                                   char *channel_name,
1724                                   void *channel_id, 
1725                                   SilcUInt32 channel_id_len,
1726                                   SilcUInt32 mode)
1727 {
1728   SilcBuffer packet;
1729   unsigned char *cid;
1730   SilcUInt32 name_len = strlen(channel_name);
1731
1732   SILC_LOG_DEBUG(("Sending new channel"));
1733
1734   cid = silc_id_id2str(channel_id, SILC_ID_CHANNEL);
1735   if (!cid)
1736     return;
1737
1738   /* Encode the channel payload */
1739   packet = silc_channel_payload_encode(channel_name, name_len,
1740                                        cid, channel_id_len, mode);
1741
1742   silc_server_packet_send(server, sock, SILC_PACKET_NEW_CHANNEL, 
1743                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0, 
1744                           packet->data, packet->len, FALSE);
1745
1746   silc_free(cid);
1747   silc_buffer_free(packet);
1748 }
1749
1750 /* Send Channel Key payload to distribute the new channel key. Normal server
1751    sends this to router when new client joins to existing channel. Router
1752    sends this to the local server who sent the join command in case where
1753    the channel did not exist yet. Both normal and router servers uses this
1754    also to send this to locally connected clients on the channel. This
1755    must not be broadcasted packet. Routers do not send this to each other. 
1756    If `sender is provided then the packet is not sent to that connection since
1757    it originally came from it. */
1758
1759 void silc_server_send_channel_key(SilcServer server,
1760                                   SilcSocketConnection sender,
1761                                   SilcChannelEntry channel,
1762                                   unsigned char route)
1763 {
1764   SilcBuffer packet;
1765   unsigned char *chid;
1766   SilcUInt32 tmp_len;
1767  
1768   SILC_LOG_DEBUG(("Sending key to channel %s", channel->channel_name));
1769  
1770   chid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
1771   if (!chid)
1772     return;
1773
1774   if (!channel->channel_key)
1775     return;
1776  
1777   /* Encode channel key packet */
1778   tmp_len = strlen(channel->channel_key->cipher->name);
1779   packet = silc_channel_key_payload_encode(silc_id_get_len(channel->id,
1780                                                            SILC_ID_CHANNEL),
1781                                            chid, tmp_len,
1782                                            channel->channel_key->cipher->name,
1783                                            channel->key_len / 8, channel->key);
1784   silc_server_packet_send_to_channel(server, sender, channel, 
1785                                      SILC_PACKET_CHANNEL_KEY,
1786                                      route, packet->data, packet->len, 
1787                                      FALSE);
1788   silc_buffer_free(packet);
1789   silc_free(chid);
1790 }
1791
1792 /* Generic function to send any command. The arguments must be sent already
1793    encoded into correct form in correct order. */
1794
1795 void silc_server_send_command(SilcServer server, 
1796                               SilcSocketConnection sock,
1797                               SilcCommand command, 
1798                               SilcUInt16 ident,
1799                               SilcUInt32 argc, ...)
1800 {
1801   SilcBuffer packet;
1802   va_list ap;
1803
1804   va_start(ap, argc);
1805
1806   packet = silc_command_payload_encode_vap(command, ident, argc, ap);
1807   silc_server_packet_send(server, sock, SILC_PACKET_COMMAND, 0,
1808                           packet->data, packet->len, TRUE);
1809   silc_buffer_free(packet);
1810   va_end(ap);
1811 }
1812
1813 /* Generic function to send any command reply. The arguments must be sent
1814    already encoded into correct form in correct order. */
1815
1816 void silc_server_send_command_reply(SilcServer server, 
1817                                     SilcSocketConnection sock,
1818                                     SilcCommand command, 
1819                                     SilcStatus status,
1820                                     SilcStatus error,
1821                                     SilcUInt16 ident,
1822                                     SilcUInt32 argc, ...)
1823 {
1824   SilcBuffer packet;
1825   va_list ap;
1826
1827   va_start(ap, argc);
1828
1829   packet = silc_command_reply_payload_encode_vap(command, status, error,
1830                                                  ident, argc, ap);
1831   silc_server_packet_send(server, sock, SILC_PACKET_COMMAND_REPLY, 0,
1832                           packet->data, packet->len, TRUE);
1833   silc_buffer_free(packet);
1834   va_end(ap);
1835 }
1836
1837 /* Generic function to send any command reply. The arguments must be sent
1838    already encoded into correct form in correct order. */
1839
1840 void silc_server_send_dest_command_reply(SilcServer server, 
1841                                          SilcSocketConnection sock,
1842                                          void *dst_id,
1843                                          SilcIdType dst_id_type,
1844                                          SilcCommand command, 
1845                                          SilcStatus status,
1846                                          SilcStatus error,
1847                                          SilcUInt16 ident,
1848                                          SilcUInt32 argc, ...)
1849 {
1850   SilcBuffer packet;
1851   va_list ap;
1852
1853   va_start(ap, argc);
1854
1855   packet = silc_command_reply_payload_encode_vap(command, status, error,
1856                                                  ident, argc, ap);
1857   silc_server_packet_send_dest(server, sock, SILC_PACKET_COMMAND_REPLY, 0,
1858                                dst_id, dst_id_type, packet->data, 
1859                                packet->len, TRUE);
1860   silc_buffer_free(packet);
1861   va_end(ap);
1862 }
1863
1864 /* Send the heartbeat packet. */
1865
1866 void silc_server_send_heartbeat(SilcServer server,
1867                                 SilcSocketConnection sock)
1868 {
1869   silc_server_packet_send(server, sock, SILC_PACKET_HEARTBEAT, 0,
1870                           NULL, 0, FALSE);
1871 }
1872
1873 /* Generic function to relay packet we've received. This is used to relay
1874    packets to a client but generally can be used to other purposes as well. */
1875
1876 void silc_server_relay_packet(SilcServer server,
1877                               SilcSocketConnection dst_sock,
1878                               SilcCipher cipher,
1879                               SilcHmac hmac,
1880                               SilcUInt32 sequence,
1881                               SilcPacketContext *packet,
1882                               bool force_send)
1883 {
1884   const SilcBufferStruct p;
1885
1886   silc_buffer_push(packet->buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
1887                    + packet->dst_id_len + packet->padlen);
1888   if (!silc_packet_send_prepare(dst_sock, 0, 0, packet->buffer->len, hmac,
1889                                 (const SilcBuffer)&p)) {
1890     SILC_LOG_ERROR(("Cannot send packet"));
1891     return;
1892   }
1893   silc_buffer_put((SilcBuffer)&p, packet->buffer->data, packet->buffer->len);
1894
1895   /* Re-encrypt packet */
1896   silc_packet_encrypt(cipher, hmac, sequence, (SilcBuffer)&p, p.len);
1897   
1898   /* Send the packet */
1899   silc_server_packet_send_real(server, dst_sock, force_send);
1900
1901   silc_buffer_pull(packet->buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
1902                    + packet->dst_id_len + packet->padlen);
1903 }
1904
1905 /* Routine used to send the connection authentication packet. */
1906
1907 void silc_server_send_connection_auth_request(SilcServer server,
1908                                               SilcSocketConnection sock,
1909                                               SilcUInt16 conn_type,
1910                                               SilcAuthMethod auth_meth)
1911 {
1912   SilcBuffer packet;
1913
1914   packet = silc_buffer_alloc(4);
1915   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1916   silc_buffer_format(packet,
1917                      SILC_STR_UI_SHORT(conn_type),
1918                      SILC_STR_UI_SHORT(auth_meth),
1919                      SILC_STR_END);
1920
1921   silc_server_packet_send(server, sock, SILC_PACKET_CONNECTION_AUTH_REQUEST,
1922                           0, packet->data, packet->len, FALSE);
1923   silc_buffer_free(packet);
1924 }
1925
1926 /* Purge the outgoing packet queue to the network if there is data. This
1927    function can be used to empty the packet queue. It is guaranteed that
1928    after this function returns the outgoing data queue is empty. */
1929
1930 void silc_server_packet_queue_purge(SilcServer server,
1931                                     SilcSocketConnection sock)
1932 {
1933   if (sock && SILC_IS_OUTBUF_PENDING(sock) && 
1934       (SILC_IS_DISCONNECTED(sock) == FALSE)) {
1935     server->stat.packets_sent++;
1936     silc_packet_send(sock, TRUE);
1937     SILC_SET_CONNECTION_FOR_INPUT(server->schedule, sock->sock);
1938     SILC_UNSET_OUTBUF_PENDING(sock);
1939     silc_buffer_clear(sock->outbuf);
1940   }
1941 }
1942
1943 /* Send packet to clients that are known to be operators.  If server
1944    is router and `route' is TRUE then the packet would go to all operators
1945    in the SILC network.  If `route' is FALSE then only local operators
1946    (local for server and cell wide for router).  If `local' is TRUE then
1947    only locally connected operators receive the packet.  If `local' is
1948    TRUE then `route' is ignored.  If server is normal server and `route'
1949    is FALSE it is equivalent to `local' being TRUE. */
1950
1951 void silc_server_send_opers(SilcServer server,
1952                             SilcPacketType type,
1953                             SilcPacketFlags flags,
1954                             bool route, bool local,
1955                             unsigned char *data, 
1956                             SilcUInt32 data_len,
1957                             bool force_send)
1958 {
1959   SilcIDCacheList list = NULL;
1960   SilcIDCacheEntry id_cache = NULL;
1961   SilcClientEntry client = NULL;
1962   SilcSocketConnection sock;
1963   SilcServerEntry *routed = NULL;
1964   SilcUInt32 routed_count = 0;
1965   bool gone = FALSE;
1966   int k;
1967
1968   SILC_LOG_DEBUG(("Sending %s packet to operators",
1969                   silc_get_packet_name(type)));
1970
1971   /* If local was requested send only locally connected operators. */
1972   if (local || (server->server_type == SILC_SERVER && !route)) {
1973     if (!silc_idcache_get_all(server->local_list->clients, &list) ||
1974         !silc_idcache_list_first(list, &id_cache))
1975       return;
1976     while (id_cache) {
1977       client = (SilcClientEntry)id_cache->context;
1978       if (!client->router && SILC_IS_LOCAL(client) &&
1979           (client->mode & SILC_UMODE_SERVER_OPERATOR ||
1980            client->mode & SILC_UMODE_ROUTER_OPERATOR)) {
1981
1982         /* Send the packet to locally connected operator */
1983         silc_server_packet_send_dest(server, client->connection, type, flags,
1984                                      client->id, SILC_ID_CLIENT,
1985                                      data, data_len, force_send);
1986       }
1987
1988       if (!silc_idcache_list_next(list, &id_cache))
1989         break;
1990     }
1991     silc_idcache_list_free(list);
1992     return;
1993   }
1994
1995   if (!silc_idcache_get_all(server->local_list->clients, &list) ||
1996       !silc_idcache_list_first(list, &id_cache))
1997     return;
1998   while (id_cache) {
1999     client = (SilcClientEntry)id_cache->context;
2000     if (!(client->mode & SILC_UMODE_SERVER_OPERATOR) &&
2001         !(client->mode & SILC_UMODE_ROUTER_OPERATOR))
2002       goto next;
2003
2004     if (server->server_type != SILC_SERVER && client->router && 
2005         ((!route && client->router->router == server->id_entry) || route)) {
2006
2007       /* Check if we have sent the packet to this route already */
2008       for (k = 0; k < routed_count; k++)
2009         if (routed[k] == client->router)
2010           break;
2011       if (k < routed_count)
2012         goto next;
2013
2014       /* Route only once to router */
2015       sock = (SilcSocketConnection)client->router->connection;
2016       if (sock->type == SILC_SOCKET_TYPE_ROUTER) {
2017         if (gone)
2018           goto next;
2019         gone = TRUE;
2020       }
2021
2022       /* Send the packet */
2023       silc_server_packet_send_dest(server, sock, type, flags,
2024                                    client->id, SILC_ID_CLIENT,
2025                                    data, data_len, force_send);
2026
2027       /* Mark this route routed already */
2028       routed = silc_realloc(routed, sizeof(*routed) * (routed_count + 1));
2029       routed[routed_count++] = client->router;
2030       goto next;
2031     }
2032
2033     if (client->router || !client->connection)
2034       goto next;
2035
2036     /* Send to locally connected client */
2037     sock = (SilcSocketConnection)client->connection;
2038     silc_server_packet_send_dest(server, sock, type, flags,
2039                                  client->id, SILC_ID_CLIENT,
2040                                  data, data_len, force_send);
2041
2042   next:
2043     if (!silc_idcache_list_next(list, &id_cache))
2044       break;
2045   }
2046   silc_idcache_list_free(list);
2047
2048   if (!silc_idcache_get_all(server->global_list->clients, &list) ||
2049       !silc_idcache_list_first(list, &id_cache))
2050     return;
2051   while (id_cache) {
2052     client = (SilcClientEntry)id_cache->context;
2053     if (!(client->mode & SILC_UMODE_SERVER_OPERATOR) &&
2054         !(client->mode & SILC_UMODE_ROUTER_OPERATOR))
2055       goto nextg;
2056
2057     if (server->server_type != SILC_SERVER && client->router && 
2058         ((!route && client->router->router == server->id_entry) || route)) {
2059
2060       /* Check if we have sent the packet to this route already */
2061       for (k = 0; k < routed_count; k++)
2062         if (routed[k] == client->router)
2063           break;
2064       if (k < routed_count)
2065         goto nextg;
2066
2067       /* Route only once to router */
2068       sock = (SilcSocketConnection)client->router->connection;
2069       if (sock->type == SILC_SOCKET_TYPE_ROUTER) {
2070         if (gone)
2071           goto nextg;
2072         gone = TRUE;
2073       }
2074
2075       /* Send the packet */
2076       silc_server_packet_send_dest(server, sock, type, flags,
2077                                    client->id, SILC_ID_CLIENT,
2078                                    data, data_len, force_send);
2079
2080       /* Mark this route routed already */
2081       routed = silc_realloc(routed, sizeof(*routed) * (routed_count + 1));
2082       routed[routed_count++] = client->router;
2083       goto nextg;
2084     }
2085
2086     if (client->router || !client->connection)
2087       goto nextg;
2088
2089     /* Send to locally connected client */
2090     sock = (SilcSocketConnection)client->connection;
2091     silc_server_packet_send_dest(server, sock, type, flags,
2092                                  client->id, SILC_ID_CLIENT,
2093                                  data, data_len, force_send);
2094
2095   nextg:
2096     if (!silc_idcache_list_next(list, &id_cache))
2097       break;
2098   }
2099   silc_idcache_list_free(list);
2100   silc_free(routed);
2101 }
2102
2103 /* Send a notify packet to operators */
2104
2105 void silc_server_send_opers_notify(SilcServer server,
2106                                    bool route,
2107                                    bool local,
2108                                    SilcNotifyType type,
2109                                    SilcUInt32 argc, ...)
2110 {
2111   va_list ap;
2112   SilcBuffer packet;
2113
2114   va_start(ap, argc);
2115   packet = silc_notify_payload_encode(type, argc, ap);
2116   silc_server_send_opers(server, SILC_PACKET_NOTIFY, 0,
2117                          route, local, packet->data, packet->len,
2118                          FALSE);
2119   silc_buffer_free(packet);
2120   va_end(ap);
2121 }