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