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