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