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