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