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