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