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