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