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