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