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. */
529
530 void silc_server_packet_send_to_channel(SilcServer server,
531                                         SilcSocketConnection sender,
532                                         SilcChannelEntry channel,
533                                         SilcPacketType type,
534                                         bool route,
535                                         unsigned char *data,
536                                         uint32 data_len,
537                                         bool force_send)
538 {
539   SilcSocketConnection sock = NULL;
540   SilcPacketContext packetdata;
541   SilcClientEntry client = NULL;
542   SilcServerEntry *routed = NULL;
543   SilcChannelClientEntry chl;
544   SilcHashTableList htl;
545   SilcIDListData idata;
546   uint32 routed_count = 0;
547   bool gone = FALSE;
548   int k;
549
550   /* This doesn't send channel message packets */
551   assert(type != SILC_PACKET_CHANNEL_MESSAGE);
552   
553   SILC_LOG_DEBUG(("Sending packet to channel"));
554
555   /* Set the packet context pointers. */
556   packetdata.flags = 0;
557   packetdata.type = type;
558   packetdata.src_id = silc_id_id2str(server->id, SILC_ID_SERVER);
559   packetdata.src_id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
560   packetdata.src_id_type = SILC_ID_SERVER;
561   packetdata.dst_id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
562   packetdata.dst_id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
563   packetdata.dst_id_type = SILC_ID_CHANNEL;
564
565   /* If there are global users in the channel we will send the message
566      first to our router for further routing. */
567   if (route && server->server_type != SILC_ROUTER && !server->standalone &&
568       channel->global_users) {
569     SilcServerEntry router;
570
571     /* Get data used in packet header encryption, keys and stuff. */
572     router = server->router;
573     sock = (SilcSocketConnection)router->connection;
574     idata = (SilcIDListData)router;
575     
576     if (sock != sender) {
577       SILC_LOG_DEBUG(("Sending channel message to router for routing"));
578       
579       silc_server_packet_send_to_channel_real(server, sock, &packetdata,
580                                               idata->send_key, 
581                                               idata->hmac_send, 
582                                               idata->psn_send++,
583                                               data, data_len, FALSE, 
584                                               force_send);
585     }
586   }
587
588   routed = silc_calloc(silc_hash_table_count(channel->user_list), 
589                        sizeof(*routed));
590
591   /* Send the message to clients on the channel's client list. */
592   silc_hash_table_list(channel->user_list, &htl);
593   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
594     client = chl->client;
595     if (!client)
596       continue;
597
598     /* If client has router set it is not locally connected client and
599        we will route the message to the router set in the client. Though,
600        send locally connected server in all cases. */
601     if (server->server_type == SILC_ROUTER && client->router && 
602         ((!route && client->router->router == server->id_entry) || route)) {
603
604       /* Check if we have sent the packet to this route already */
605       for (k = 0; k < routed_count; k++)
606         if (routed[k] == client->router)
607           break;
608       if (k < routed_count)
609         continue;
610
611       /* Get data used in packet header encryption, keys and stuff. */
612       sock = (SilcSocketConnection)client->router->connection;
613       idata = (SilcIDListData)client->router;
614
615       if (sender && sock == sender)
616         continue;
617
618       /* Route only once to router */
619       if (sock->type == SILC_SOCKET_TYPE_ROUTER) {
620         if (gone)
621           continue;
622         gone = TRUE;
623       }
624
625       /* Send the packet */
626       silc_server_packet_send_to_channel_real(server, sock, &packetdata,
627                                               idata->send_key, 
628                                               idata->hmac_send, 
629                                               idata->psn_send++,
630                                               data, data_len, FALSE, 
631                                               force_send);
632
633       /* Mark this route routed already */
634       routed[routed_count++] = client->router;
635       continue;
636     }
637
638     if (client->router)
639       continue;
640
641     /* Send to locally connected client */
642
643     /* Get data used in packet header encryption, keys and stuff. */
644     sock = (SilcSocketConnection)client->connection;
645     idata = (SilcIDListData)client;
646     
647     if (sender && sock == sender)
648       continue;
649
650     /* Send the packet */
651     silc_server_packet_send_to_channel_real(server, sock, &packetdata,
652                                             idata->send_key, 
653                                             idata->hmac_send, 
654                                             idata->psn_send++, 
655                                             data, data_len, FALSE, 
656                                             force_send);
657   }
658
659   silc_free(routed);
660   silc_free(packetdata.src_id);
661   silc_free(packetdata.dst_id);
662 }
663
664 /* This checks whether the relayed packet came from router. If it did
665    then we'll need to encrypt it with the channel key. This is called
666    from the silc_server_packet_relay_to_channel. */
667
668 static bool
669 silc_server_packet_relay_to_channel_encrypt(SilcServer server,
670                                             SilcSocketConnection sock,
671                                             SilcChannelEntry channel,
672                                             unsigned char *data,
673                                             unsigned int data_len)
674 {
675   /* If we are router and the packet came from router and private key
676      has not been set for the channel then we must encrypt the packet
677      as it was decrypted with the session key shared between us and the
678      router which sent it. This is so, because cells does not share the
679      same channel key. */
680   if (server->server_type == SILC_ROUTER &&
681       sock->type == SILC_SOCKET_TYPE_ROUTER &&
682       !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY) &&
683       channel->channel_key) {
684     SilcBuffer chp;
685     uint32 iv_len, i;
686     uint16 dlen, flags;
687
688     iv_len = silc_cipher_get_block_len(channel->channel_key);
689     if (channel->iv[0] == '\0')
690       for (i = 0; i < iv_len; i++) channel->iv[i] = 
691                                      silc_rng_get_byte(server->rng);
692     else
693       silc_hash_make(server->md5hash, channel->iv, iv_len, channel->iv);
694     
695     /* Encode new payload. This encrypts it also. */
696     SILC_GET16_MSB(flags, data);
697     SILC_GET16_MSB(dlen, data + 2);
698
699     if (dlen > data_len) {
700       SILC_LOG_WARNING(("Corrupted channel message, cannot relay it"));
701       return FALSE;
702     }
703
704     chp = silc_channel_message_payload_encode(flags, dlen, data + 4,
705                                               iv_len, channel->iv,
706                                               channel->channel_key,
707                                               channel->hmac);
708     memcpy(data, chp->data, chp->len);
709     silc_buffer_free(chp);
710   }
711
712   return TRUE;
713 }
714
715 /* This routine is explicitly used to relay messages to some channel.
716    Packets sent with this function we have received earlier and are
717    totally encrypted. This just sends the packet to all clients on
718    the channel. If the sender of the packet is someone on the channel 
719    the message will not be sent to that client. The SILC Packet header
720    is encrypted with the session key shared between us and the client.
721    MAC is also computed before encrypting the header. Rest of the
722    packet will be untouched. */
723
724 void silc_server_packet_relay_to_channel(SilcServer server,
725                                          SilcSocketConnection sender_sock,
726                                          SilcChannelEntry channel,
727                                          void *sender, 
728                                          SilcIdType sender_type,
729                                          void *sender_entry,
730                                          unsigned char *data,
731                                          uint32 data_len,
732                                          bool force_send)
733 {
734   bool found = FALSE;
735   SilcSocketConnection sock = NULL;
736   SilcPacketContext packetdata;
737   SilcClientEntry client = NULL;
738   SilcServerEntry *routed = NULL;
739   SilcChannelClientEntry chl;
740   uint32 routed_count = 0;
741   SilcIDListData idata;
742   SilcHashTableList htl;
743   bool gone = FALSE;
744   int k;
745
746   SILC_LOG_DEBUG(("Relaying packet to channel"));
747
748   /* This encrypts the packet, if needed. It will be encrypted if
749      it came from the router thus it needs to be encrypted with the
750      channel key. If the channel key does not exist, then we know we
751      don't have a single local user on the channel. */
752   if (!silc_server_packet_relay_to_channel_encrypt(server, sender_sock,
753                                                    channel, data,
754                                                    data_len))
755     return;
756
757   /* Set the packet context pointers. */
758   packetdata.flags = 0;
759   packetdata.type = SILC_PACKET_CHANNEL_MESSAGE;
760   packetdata.src_id = silc_id_id2str(sender, sender_type);
761   packetdata.src_id_len = silc_id_get_len(sender, sender_type);
762   packetdata.src_id_type = sender_type;
763   packetdata.dst_id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
764   packetdata.dst_id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
765   packetdata.dst_id_type = SILC_ID_CHANNEL;
766
767   /* If there are global users in the channel we will send the message
768      first to our router for further routing. */
769   if (server->server_type != SILC_ROUTER && !server->standalone &&
770       channel->global_users) {
771     SilcServerEntry router = server->router;
772
773     /* Check that the sender is not our router. */
774     if (sender_sock != (SilcSocketConnection)router->connection) {
775
776       /* Get data used in packet header encryption, keys and stuff. */
777       sock = (SilcSocketConnection)router->connection;
778       idata = (SilcIDListData)router;
779
780       SILC_LOG_DEBUG(("Sending channel message to router for routing"));
781
782       silc_server_packet_send_to_channel_real(server, sock, &packetdata,
783                                               idata->send_key, 
784                                               idata->hmac_send, 
785                                               idata->psn_send++, 
786                                               data, data_len, TRUE, 
787                                               force_send);
788     }
789   }
790
791   routed = silc_calloc(silc_hash_table_count(channel->user_list), 
792                        sizeof(*routed));
793
794   /* Mark that to the route the original sender if from is not routed */
795   if (sender_type == SILC_ID_CLIENT) {
796     client = (SilcClientEntry)sender_entry;
797     if (client->router) {
798       routed[routed_count++] = client->router;
799       SILC_LOG_DEBUG(("************* router %s", 
800                       silc_id_render(client->router->id, SILC_ID_SERVER)));
801     }
802   }
803
804   /* Send the message to clients on the channel's client list. */
805   silc_hash_table_list(channel->user_list, &htl);
806   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
807     client = chl->client;
808     if (!client)
809       continue;
810
811     /* Do not send to the sender */
812     if (!found && client == sender_entry) {
813       found = TRUE;
814       continue;
815     }
816
817     /* If the client has set router it means that it is not locally
818        connected client and we will route the packet further. */
819     if (server->server_type == SILC_ROUTER && client->router) {
820
821       /* Sender maybe server as well so we want to make sure that
822          we won't send the message to the server it came from. */
823       if (!found && SILC_ID_SERVER_COMPARE(client->router->id, sender)) {
824         found = TRUE;
825         routed[routed_count++] = client->router;
826         continue;
827       }
828
829       /* Check if we have sent the packet to this route already */
830       for (k = 0; k < routed_count; k++)
831         if (routed[k] == client->router)
832           break;
833       if (k < routed_count)
834         continue;
835         
836       /* Get data used in packet header encryption, keys and stuff. */
837       sock = (SilcSocketConnection)client->router->connection;
838       idata = (SilcIDListData)client->router;
839
840       /* Do not send to the sender. Check first whether the true
841          sender's router is same as this client's router. Also check
842          if the sender socket is the same as this client's router
843          socket. */
844       if (sender_entry &&
845           ((SilcClientEntry)sender_entry)->router == client->router)
846         continue;
847       if (sender_sock && sock == sender_sock)
848         continue;
849
850       SILC_LOG_DEBUG(("Relaying packet to client ID(%s) %s (%s)", 
851                       silc_id_render(client->id, SILC_ID_CLIENT),
852                       sock->hostname, sock->ip));
853
854       /* Mark this route routed already. */
855       routed[routed_count++] = client->router;
856         
857       /* If the remote connection is router then we'll decrypt the
858          channel message and re-encrypt it with the session key shared
859          between us and the remote router. This is done because the
860          channel keys are cell specific and we have different channel
861          key than the remote router has. */
862       if (sock->type == SILC_SOCKET_TYPE_ROUTER) {
863         if (gone)
864           continue;
865
866         SILC_LOG_DEBUG(("Remote is router, encrypt with session key"));
867         gone = TRUE;
868
869         /* If private key mode is not set then decrypt the packet
870            and re-encrypt it */
871         if (!(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
872           unsigned char *tmp = silc_calloc(data_len, sizeof(*data));
873           memcpy(tmp, data, data_len);
874
875           /* Decrypt the channel message (we don't check the MAC) */
876           if (channel->channel_key &&
877               !silc_channel_message_payload_decrypt(tmp, data_len, 
878                                                     channel->channel_key,
879                                                     NULL)) {
880             memset(tmp, 0, data_len);
881             silc_free(tmp);
882             continue;
883           }
884
885           /* Now re-encrypt and send it to the router */
886           silc_server_packet_send_srcdest(server, sock, 
887                                           SILC_PACKET_CHANNEL_MESSAGE, 0,
888                                           sender, sender_type,
889                                           channel->id, SILC_ID_CHANNEL,
890                                           tmp, data_len, force_send);
891
892           /* Free the copy of the channel message */
893           memset(tmp, 0, data_len);
894           silc_free(tmp);
895         } else {
896           /* Private key mode is set, we don't have the channel key, so
897              just re-encrypt the entire packet and send it to the router. */
898           silc_server_packet_send_srcdest(server, sock, 
899                                           SILC_PACKET_CHANNEL_MESSAGE, 0,
900                                           sender, sender_type,
901                                           channel->id, SILC_ID_CHANNEL,
902                                           data, data_len, force_send);
903         }
904         continue;
905       }
906
907       /* Send the packet (to normal server) */
908       silc_server_packet_send_to_channel_real(server, sock, &packetdata,
909                                               idata->send_key, 
910                                               idata->hmac_send, 
911                                               idata->psn_send++, 
912                                               data, data_len, TRUE, 
913                                               force_send);
914
915       continue;
916     }
917
918     if (client->router)
919       continue;
920
921     /* Get data used in packet header encryption, keys and stuff. */
922     sock = (SilcSocketConnection)client->connection;
923     idata = (SilcIDListData)client;
924
925     if (sender_sock && sock == sender_sock)
926       continue;
927
928     SILC_LOG_DEBUG(("Sending packet to client ID(%s) %s (%s)", 
929                     silc_id_render(client->id, SILC_ID_CLIENT),
930                     sock->hostname, sock->ip));
931
932     /* Send the packet */
933     silc_server_packet_send_to_channel_real(server, sock, &packetdata,
934                                             idata->send_key, 
935                                             idata->hmac_send, 
936                                             idata->psn_send++, 
937                                             data, data_len, TRUE, 
938                                             force_send);
939   }
940
941   silc_free(routed);
942   silc_free(packetdata.src_id);
943   silc_free(packetdata.dst_id);
944 }
945
946 /* This function is used to send packets strictly to all local clients
947    on a particular channel.  This is used for example to distribute new
948    channel key to all our locally connected clients on the channel. 
949    The packets are always encrypted with the session key shared between
950    the client, this means these are not _to the channel_ but _to the client_
951    on the channel. */
952
953 void silc_server_packet_send_local_channel(SilcServer server,
954                                            SilcChannelEntry channel,
955                                            SilcPacketType type,
956                                            SilcPacketFlags flags,
957                                            unsigned char *data,
958                                            uint32 data_len,
959                                            bool force_send)
960 {
961   SilcChannelClientEntry chl;
962   SilcHashTableList htl;
963   SilcSocketConnection sock = NULL;
964
965   SILC_LOG_DEBUG(("Start"));
966
967   /* Send the message to clients on the channel's client list. */
968   silc_hash_table_list(channel->user_list, &htl);
969   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
970     if (chl->client && !chl->client->router) {
971       sock = (SilcSocketConnection)chl->client->connection;
972
973       /* Send the packet to the client */
974       silc_server_packet_send_dest(server, sock, type, flags, chl->client->id,
975                                    SILC_ID_CLIENT, data, data_len,
976                                    force_send);
977     }
978   }
979 }
980
981 /* Routine used to send (relay, route) private messages to some destination.
982    If the private message key does not exist then the message is re-encrypted,
983    otherwise we just pass it along. This really is not used to send new
984    private messages (as server does not send them) but to relay received
985    private messages. */
986
987 void silc_server_send_private_message(SilcServer server,
988                                       SilcSocketConnection dst_sock,
989                                       SilcCipher cipher,
990                                       SilcHmac hmac,
991                                       uint32 sequence,
992                                       SilcPacketContext *packet)
993 {
994   SilcBuffer buffer = packet->buffer;
995
996   /* Re-encrypt and send if private messge key does not exist */
997   if (!(packet->flags & SILC_PACKET_FLAG_PRIVMSG_KEY)) {
998
999     silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
1000                      + packet->dst_id_len + packet->padlen);
1001     silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
1002     silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
1003
1004     /* Re-encrypt packet */
1005     silc_packet_encrypt(cipher, hmac, sequence, dst_sock->outbuf, buffer->len);
1006
1007     /* Send the packet */
1008     silc_server_packet_send_real(server, dst_sock, FALSE);
1009
1010   } else {
1011     /* Key exist so encrypt just header and send it */
1012     silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
1013                      + packet->dst_id_len + packet->padlen);
1014     silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
1015     silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
1016
1017     /* Encrypt header */
1018     silc_packet_encrypt(cipher, hmac, sequence, dst_sock->outbuf, 
1019                         SILC_PACKET_HEADER_LEN + packet->src_id_len + 
1020                         packet->dst_id_len + packet->padlen);
1021
1022     silc_server_packet_send_real(server, dst_sock, FALSE);
1023   }
1024 }
1025
1026 /* Sends current motd to client */
1027
1028 void silc_server_send_motd(SilcServer server,
1029                            SilcSocketConnection sock)
1030 {
1031   char *motd;
1032   uint32 motd_len;
1033
1034   if (server->config && server->config->motd && 
1035       server->config->motd->motd_file) {
1036
1037     motd = silc_file_readfile(server->config->motd->motd_file, &motd_len);
1038     if (!motd)
1039       return;
1040
1041     silc_server_send_notify(server, sock, FALSE, SILC_NOTIFY_TYPE_MOTD, 1,
1042                             motd, motd_len);
1043     silc_free(motd);
1044   }
1045 }
1046
1047 /* Sends error message. Error messages may or may not have any 
1048    implications. */
1049
1050 void silc_server_send_error(SilcServer server,
1051                             SilcSocketConnection sock,
1052                             const char *fmt, ...)
1053 {
1054   va_list ap;
1055   unsigned char buf[4096];
1056
1057   memset(buf, 0, sizeof(buf));
1058   va_start(ap, fmt);
1059   vsprintf(buf, fmt, ap);
1060   va_end(ap);
1061
1062   silc_server_packet_send(server, sock, SILC_PACKET_ERROR, 0, 
1063                           buf, strlen(buf), FALSE);
1064 }
1065
1066 /* Sends notify message. If format is TRUE the variable arguments are
1067    formatted and the formatted string is sent as argument payload. If it is
1068    FALSE then each argument is sent as separate argument and their format
1069    in the argument list must be { argument data, argument length }. */
1070
1071 void silc_server_send_notify(SilcServer server,
1072                              SilcSocketConnection sock,
1073                              bool broadcast,
1074                              SilcNotifyType type,
1075                              uint32 argc, ...)
1076 {
1077   va_list ap;
1078   SilcBuffer packet;
1079
1080   va_start(ap, argc);
1081
1082   packet = silc_notify_payload_encode(type, argc, ap);
1083   silc_server_packet_send(server, sock, SILC_PACKET_NOTIFY, 
1084                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
1085                           packet->data, packet->len, FALSE);
1086
1087   /* Send to backup routers if this is being broadcasted to primary
1088      router. */
1089   if (server->router && server->router->connection &&
1090       sock == server->router->connection && broadcast)
1091     silc_server_backup_send(server, NULL, SILC_PACKET_NOTIFY, 0,
1092                             packet->data, packet->len, FALSE, TRUE);
1093
1094   silc_buffer_free(packet);
1095   va_end(ap);
1096 }
1097
1098 /* Sends notify message and gets the arguments from the `args' Argument
1099    Payloads. */
1100
1101 void silc_server_send_notify_args(SilcServer server,
1102                                   SilcSocketConnection sock,
1103                                   bool broadcast,
1104                                   SilcNotifyType type,
1105                                   uint32 argc,
1106                                   SilcBuffer args)
1107 {
1108   SilcBuffer packet;
1109
1110   packet = silc_notify_payload_encode_args(type, argc, args);
1111   silc_server_packet_send(server, sock, SILC_PACKET_NOTIFY, 
1112                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
1113                           packet->data, packet->len, FALSE);
1114   silc_buffer_free(packet);
1115 }
1116
1117 /* Send CHANNEL_CHANGE notify type. This tells the receiver to replace the
1118    `old_id' with the `new_id'. */
1119
1120 void silc_server_send_notify_channel_change(SilcServer server,
1121                                             SilcSocketConnection sock,
1122                                             bool broadcast,
1123                                             SilcChannelID *old_id,
1124                                             SilcChannelID *new_id)
1125 {
1126   SilcBuffer idp1, idp2;
1127
1128   idp1 = silc_id_payload_encode((void *)old_id, SILC_ID_CHANNEL);
1129   idp2 = silc_id_payload_encode((void *)new_id, SILC_ID_CHANNEL);
1130
1131   silc_server_send_notify(server, sock, broadcast,
1132                           SILC_NOTIFY_TYPE_CHANNEL_CHANGE,
1133                           2, idp1->data, idp1->len, idp2->data, idp2->len);
1134   silc_buffer_free(idp1);
1135   silc_buffer_free(idp2);
1136 }
1137
1138 /* Send NICK_CHANGE notify type. This tells the receiver to replace the
1139    `old_id' with the `new_id'. */
1140
1141 void silc_server_send_notify_nick_change(SilcServer server,
1142                                          SilcSocketConnection sock,
1143                                          bool broadcast,
1144                                          SilcClientID *old_id,
1145                                          SilcClientID *new_id)
1146 {
1147   SilcBuffer idp1, idp2;
1148
1149   idp1 = silc_id_payload_encode((void *)old_id, SILC_ID_CLIENT);
1150   idp2 = silc_id_payload_encode((void *)new_id, SILC_ID_CLIENT);
1151
1152   silc_server_send_notify(server, sock, broadcast, 
1153                           SILC_NOTIFY_TYPE_NICK_CHANGE,
1154                           2, idp1->data, idp1->len, idp2->data, idp2->len);
1155   silc_buffer_free(idp1);
1156   silc_buffer_free(idp2);
1157 }
1158
1159 /* Sends JOIN notify type. This tells that new client by `client_id' ID
1160    has joined to the `channel'. */
1161
1162 void silc_server_send_notify_join(SilcServer server,
1163                                   SilcSocketConnection sock,
1164                                   bool broadcast,
1165                                   SilcChannelEntry channel,
1166                                   SilcClientID *client_id)
1167 {
1168   SilcBuffer idp1, idp2;
1169
1170   idp1 = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1171   idp2 = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
1172   silc_server_send_notify(server, sock, broadcast, SILC_NOTIFY_TYPE_JOIN,
1173                           2, idp1->data, idp1->len,
1174                           idp2->data, idp2->len);
1175   silc_buffer_free(idp1);
1176   silc_buffer_free(idp2);
1177 }
1178
1179 /* Sends LEAVE notify type. This tells that `client_id' has left the
1180    `channel'. The Notify packet is always destined to the channel. */
1181
1182 void silc_server_send_notify_leave(SilcServer server,
1183                                    SilcSocketConnection sock,
1184                                    bool broadcast,
1185                                    SilcChannelEntry channel,
1186                                    SilcClientID *client_id)
1187 {
1188   SilcBuffer idp;
1189
1190   idp = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1191   silc_server_send_notify_dest(server, sock, broadcast, (void *)channel->id,
1192                                SILC_ID_CHANNEL, SILC_NOTIFY_TYPE_LEAVE,
1193                                1, idp->data, idp->len);
1194   silc_buffer_free(idp);
1195 }
1196
1197 /* Sends CMODE_CHANGE notify type. This tells that `client_id' changed the
1198    `channel' mode to `mode. The Notify packet is always destined to
1199    the channel. */
1200
1201 void silc_server_send_notify_cmode(SilcServer server,
1202                                    SilcSocketConnection sock,
1203                                    bool broadcast,
1204                                    SilcChannelEntry channel,
1205                                    uint32 mode_mask,
1206                                    void *id, SilcIdType id_type,
1207                                    char *cipher, char *hmac)
1208 {
1209   SilcBuffer idp;
1210   unsigned char mode[4];
1211
1212   idp = silc_id_payload_encode((void *)id, id_type);
1213   SILC_PUT32_MSB(mode_mask, mode);
1214
1215   silc_server_send_notify_dest(server, sock, broadcast, (void *)channel->id,
1216                                SILC_ID_CHANNEL, SILC_NOTIFY_TYPE_CMODE_CHANGE,
1217                                4, idp->data, idp->len,
1218                                mode, 4,
1219                                cipher, cipher ? strlen(cipher) : 0,
1220                                hmac, hmac ? strlen(hmac) : 0);
1221   silc_buffer_free(idp);
1222 }
1223
1224 /* Sends CUMODE_CHANGE notify type. This tells that `client_id' changed the
1225    `target' client's mode on `channel'. The Notify packet is always
1226    destined to the channel. */
1227
1228 void silc_server_send_notify_cumode(SilcServer server,
1229                                     SilcSocketConnection sock,
1230                                     bool broadcast,
1231                                     SilcChannelEntry channel,
1232                                     uint32 mode_mask,
1233                                     void *id, SilcIdType id_type,
1234                                     SilcClientID *target)
1235 {
1236   SilcBuffer idp1, idp2;
1237   unsigned char mode[4];
1238
1239   idp1 = silc_id_payload_encode((void *)id, id_type);
1240   idp2 = silc_id_payload_encode((void *)target, SILC_ID_CLIENT);
1241   SILC_PUT32_MSB(mode_mask, mode);
1242
1243   silc_server_send_notify_dest(server, sock, broadcast, (void *)channel->id,
1244                                SILC_ID_CHANNEL, 
1245                                SILC_NOTIFY_TYPE_CUMODE_CHANGE, 3, 
1246                                idp1->data, idp1->len,
1247                                mode, 4,
1248                                idp2->data, idp2->len);
1249   silc_buffer_free(idp1);
1250   silc_buffer_free(idp2);
1251 }
1252
1253 /* Sends SIGNOFF notify type. This tells that `client_id' client has
1254    left SILC network. This function is used only between server and router
1255    traffic. This is not used to send the notify to the channel for
1256    client. The `message may be NULL. */
1257
1258 void silc_server_send_notify_signoff(SilcServer server,
1259                                      SilcSocketConnection sock,
1260                                      bool broadcast,
1261                                      SilcClientID *client_id,
1262                                      char *message)
1263 {
1264   SilcBuffer idp;
1265
1266   idp = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1267   silc_server_send_notify(server, sock, broadcast,
1268                           SILC_NOTIFY_TYPE_SIGNOFF,
1269                           message ? 2 : 1, idp->data, idp->len,
1270                           message, message ? strlen(message): 0);
1271   silc_buffer_free(idp);
1272 }
1273
1274 /* Sends TOPIC_SET notify type. This tells that `client_id' changed
1275    the `channel's topic to `topic'. The Notify packet is always destined
1276    to the channel. This function is used to send the topic set notifies
1277    between routers. */
1278
1279 void silc_server_send_notify_topic_set(SilcServer server,
1280                                        SilcSocketConnection sock,
1281                                        bool broadcast,
1282                                        SilcChannelEntry channel,
1283                                        SilcClientID *client_id,
1284                                        char *topic)
1285 {
1286   SilcBuffer idp;
1287
1288   idp = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1289   silc_server_send_notify(server, sock, broadcast,
1290                           SILC_NOTIFY_TYPE_TOPIC_SET,
1291                           topic ? 2 : 1, 
1292                           idp->data, idp->len, 
1293                           topic, topic ? strlen(topic) : 0);
1294   silc_buffer_free(idp);
1295 }
1296
1297 /* Send KICKED notify type. This tells that the `client_id' on `channel'
1298    was kicked off the channel.  The `comment' may indicate the reason
1299    for the kicking. This function is used only between server and router
1300    traffic. */
1301
1302 void silc_server_send_notify_kicked(SilcServer server,
1303                                     SilcSocketConnection sock,
1304                                     bool broadcast,
1305                                     SilcChannelEntry channel,
1306                                     SilcClientID *client_id,
1307                                     char *comment)
1308 {
1309   SilcBuffer idp;
1310
1311   idp = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1312   silc_server_send_notify_dest(server, sock, broadcast, (void *)channel->id,
1313                                SILC_ID_CHANNEL, SILC_NOTIFY_TYPE_KICKED,
1314                                comment ? 2 : 1, idp->data, idp->len,
1315                                comment, comment ? strlen(comment) : 0);
1316   silc_buffer_free(idp);
1317 }
1318
1319 /* Send KILLED notify type. This tells that the `client_id' client was
1320    killed from the network.  The `comment' may indicate the reason
1321    for the killing. */
1322
1323 void silc_server_send_notify_killed(SilcServer server,
1324                                     SilcSocketConnection sock,
1325                                     bool broadcast,
1326                                     SilcClientID *client_id,
1327                                     char *comment)
1328 {
1329   SilcBuffer idp;
1330
1331   idp = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1332   silc_server_send_notify_dest(server, sock, broadcast, (void *)client_id,
1333                                SILC_ID_CLIENT, SILC_NOTIFY_TYPE_KILLED,
1334                                comment ? 2 : 1, idp->data, idp->len,
1335                                comment, comment ? strlen(comment) : 0);
1336   silc_buffer_free(idp);
1337 }
1338
1339 /* Sends UMODE_CHANGE notify type. This tells that `client_id' client's
1340    user mode in the SILC Network was changed. This function is used to
1341    send the packet between routers as broadcast packet. */
1342
1343 void silc_server_send_notify_umode(SilcServer server,
1344                                    SilcSocketConnection sock,
1345                                    bool broadcast,
1346                                    SilcClientID *client_id,
1347                                    uint32 mode_mask)
1348 {
1349   SilcBuffer idp;
1350   unsigned char mode[4];
1351
1352   idp = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1353   SILC_PUT32_MSB(mode_mask, mode);
1354
1355   silc_server_send_notify(server, sock, broadcast,
1356                           SILC_NOTIFY_TYPE_UMODE_CHANGE, 2,
1357                           idp->data, idp->len, 
1358                           mode, 4);
1359   silc_buffer_free(idp);
1360 }
1361
1362 /* Sends BAN notify type. This tells that ban has been either `add'ed
1363    or `del'eted on the `channel. This function is used to send the packet
1364    between routers as broadcast packet. */
1365
1366 void silc_server_send_notify_ban(SilcServer server,
1367                                  SilcSocketConnection sock,
1368                                  bool broadcast,
1369                                  SilcChannelEntry channel,
1370                                  char *add, char *del)
1371 {
1372   SilcBuffer idp;
1373
1374   idp = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
1375   silc_server_send_notify(server, sock, broadcast,
1376                           SILC_NOTIFY_TYPE_BAN, 3,
1377                           idp->data, idp->len,
1378                           add, add ? strlen(add) : 0,
1379                           del, del ? strlen(del) : 0);
1380   silc_buffer_free(idp);
1381 }
1382
1383 /* Sends INVITE notify type. This tells that invite has been either `add'ed
1384    or `del'eted on the `channel.  The sender of the invite is the `client_id'.
1385    This function is used to send the packet between routers as broadcast
1386    packet. */
1387
1388 void silc_server_send_notify_invite(SilcServer server,
1389                                     SilcSocketConnection sock,
1390                                     bool broadcast,
1391                                     SilcChannelEntry channel,
1392                                     SilcClientID *client_id,
1393                                     char *add, char *del)
1394 {
1395   SilcBuffer idp, idp2;
1396
1397   idp = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
1398   idp2 = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1399   silc_server_send_notify(server, sock, broadcast,
1400                           SILC_NOTIFY_TYPE_INVITE, 5,
1401                           idp->data, idp->len,
1402                           channel->channel_name, strlen(channel->channel_name),
1403                           idp2->data, idp2->len,
1404                           add, add ? strlen(add) : 0,
1405                           del, del ? strlen(del) : 0);
1406   silc_buffer_free(idp);
1407   silc_buffer_free(idp2);
1408 }
1409
1410 /* Sends notify message destined to specific entity. */
1411
1412 void silc_server_send_notify_dest(SilcServer server,
1413                                   SilcSocketConnection sock,
1414                                   bool broadcast,
1415                                   void *dest_id,
1416                                   SilcIdType dest_id_type,
1417                                   SilcNotifyType type,
1418                                   uint32 argc, ...)
1419 {
1420   va_list ap;
1421   SilcBuffer packet;
1422
1423   va_start(ap, argc);
1424
1425   packet = silc_notify_payload_encode(type, argc, ap);
1426   silc_server_packet_send_dest(server, sock, SILC_PACKET_NOTIFY, 
1427                                broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
1428                                dest_id, dest_id_type,
1429                                packet->data, packet->len, FALSE);
1430   silc_buffer_free(packet);
1431   va_end(ap);
1432 }
1433
1434 /* Sends notify message to a channel. The notify message sent is 
1435    distributed to all clients on the channel. If `route_notify' is TRUE
1436    then the notify may be routed to primary route or to some other routers.
1437    If FALSE it is assured that the notify is sent only locally. If `sender'
1438    is provided then the packet is not sent to that connection since it
1439    originally came from it. */
1440
1441 void silc_server_send_notify_to_channel(SilcServer server,
1442                                         SilcSocketConnection sender,
1443                                         SilcChannelEntry channel,
1444                                         unsigned char route_notify,
1445                                         SilcNotifyType type,
1446                                         uint32 argc, ...)
1447 {
1448   va_list ap;
1449   SilcBuffer packet;
1450
1451   va_start(ap, argc);
1452
1453   packet = silc_notify_payload_encode(type, argc, ap);
1454   silc_server_packet_send_to_channel(server, sender, channel, 
1455                                      SILC_PACKET_NOTIFY, route_notify,
1456                                      packet->data, packet->len, FALSE);
1457   silc_buffer_free(packet);
1458   va_end(ap);
1459 }
1460
1461 /* Send notify message to all channels the client has joined. It is quaranteed
1462    that the message is sent only once to a client (ie. if a client is joined
1463    on two same channel it will receive only one notify message). Also, this
1464    sends only to local clients (locally connected if we are server, and to
1465    local servers if we are router). If `sender' is provided the packet is
1466    not sent to that client at all. */
1467
1468 void silc_server_send_notify_on_channels(SilcServer server,
1469                                          SilcClientEntry sender,
1470                                          SilcClientEntry client,
1471                                          SilcNotifyType type,
1472                                          uint32 argc, ...)
1473 {
1474   int k;
1475   SilcSocketConnection sock = NULL;
1476   SilcPacketContext packetdata;
1477   SilcClientEntry c;
1478   SilcClientEntry *sent_clients = NULL;
1479   uint32 sent_clients_count = 0;
1480   SilcServerEntry *routed = NULL;
1481   uint32 routed_count = 0;
1482   SilcHashTableList htl, htl2;
1483   SilcChannelEntry channel;
1484   SilcChannelClientEntry chl, chl2;
1485   SilcIDListData idata;
1486   SilcBuffer packet;
1487   unsigned char *data;
1488   uint32 data_len;
1489   bool force_send = FALSE;
1490   va_list ap;
1491
1492   SILC_LOG_DEBUG(("Start"));
1493
1494   if (!silc_hash_table_count(client->channels))
1495     return;
1496
1497   va_start(ap, argc);
1498   packet = silc_notify_payload_encode(type, argc, ap);
1499   data = packet->data;
1500   data_len = packet->len;
1501
1502   /* Set the packet context pointers. */
1503   packetdata.flags = 0;
1504   packetdata.type = SILC_PACKET_NOTIFY;
1505   packetdata.src_id = silc_id_id2str(server->id, SILC_ID_SERVER);
1506   packetdata.src_id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1507   packetdata.src_id_type = SILC_ID_SERVER;
1508
1509   silc_hash_table_list(client->channels, &htl);
1510   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
1511     channel = chl->channel;
1512
1513     /* Send the message to all clients on the channel's client list. */
1514     silc_hash_table_list(channel->user_list, &htl2);
1515     while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
1516       c = chl2->client;
1517       
1518       if (sender && c == sender)
1519         continue;
1520
1521       /* Check if we have sent the packet to this client already */
1522       for (k = 0; k < sent_clients_count; k++)
1523         if (sent_clients[k] == c)
1524           break;
1525       if (k < sent_clients_count)
1526         continue;
1527
1528       /* If we are router and if this client has router set it is not
1529          locally connected client and we will route the message to the
1530          router set in the client. */
1531       if (c && c->router && server->server_type == SILC_ROUTER) {
1532         /* Check if we have sent the packet to this route already */
1533         for (k = 0; k < routed_count; k++)
1534           if (routed[k] == c->router)
1535             break;
1536         if (k < routed_count)
1537           continue;
1538         
1539         /* Get data used in packet header encryption, keys and stuff. */
1540         sock = (SilcSocketConnection)c->router->connection;
1541         idata = (SilcIDListData)c->router;
1542
1543         {
1544           SILC_LOG_DEBUG(("*****************"));
1545           SILC_LOG_DEBUG(("client->router->id %s",
1546                           silc_id_render(c->router->id, SILC_ID_SERVER)));
1547           SILC_LOG_DEBUG(("client->router->connection->user_data->id %s",
1548                           silc_id_render(((SilcServerEntry)sock->user_data)->id, SILC_ID_SERVER)));
1549         }
1550
1551         packetdata.dst_id = silc_id_id2str(c->router->id, SILC_ID_SERVER);
1552         packetdata.dst_id_len = silc_id_get_len(c->router->id, SILC_ID_SERVER);
1553         packetdata.dst_id_type = SILC_ID_SERVER;
1554
1555         /* Send the packet */
1556         silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1557                                                 idata->send_key, 
1558                                                 idata->hmac_send, 
1559                                                 idata->psn_send++, 
1560                                                 data, data_len, FALSE, 
1561                                                 force_send);
1562         
1563         silc_free(packetdata.dst_id);
1564
1565         /* We want to make sure that the packet is routed to same router
1566            only once. Mark this route as sent route. */
1567         routed = silc_realloc(routed, sizeof(*routed) * (routed_count + 1));
1568         routed[routed_count++] = c->router;
1569         continue;
1570       }
1571
1572       if (c && c->router)
1573         continue;
1574
1575       /* Send to locally connected client */
1576       if (c) {
1577         
1578         /* Get data used in packet header encryption, keys and stuff. */
1579         sock = (SilcSocketConnection)c->connection;
1580         idata = (SilcIDListData)c;
1581         
1582         packetdata.dst_id = silc_id_id2str(c->id, SILC_ID_CLIENT);
1583         packetdata.dst_id_len = silc_id_get_len(c->id, SILC_ID_CLIENT);
1584         packetdata.dst_id_type = SILC_ID_CLIENT;
1585
1586         /* Send the packet */
1587         silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1588                                                 idata->send_key, 
1589                                                 idata->hmac_send, 
1590                                                 idata->psn_send++, 
1591                                                 data, data_len, FALSE, 
1592                                                 force_send);
1593
1594         silc_free(packetdata.dst_id);
1595
1596         /* Make sure that we send the notify only once per client. */
1597         sent_clients = silc_realloc(sent_clients, sizeof(*sent_clients) * 
1598                                     (sent_clients_count + 1));
1599         sent_clients[sent_clients_count++] = c;
1600       }
1601     }
1602   }
1603
1604   silc_free(routed);
1605   silc_free(sent_clients);
1606   silc_free(packetdata.src_id);
1607   silc_buffer_free(packet);
1608   va_end(ap);
1609 }
1610
1611 /* Sends New ID Payload to remote end. The packet is used to distribute
1612    information about new registered clients, servers, channel etc. usually
1613    to routers so that they can keep these information up to date. 
1614    If the argument `broadcast' is TRUE then the packet is sent as
1615    broadcast packet. */
1616
1617 void silc_server_send_new_id(SilcServer server,
1618                              SilcSocketConnection sock,
1619                              bool broadcast,
1620                              void *id, SilcIdType id_type, 
1621                              uint32 id_len)
1622 {
1623   SilcBuffer idp;
1624
1625   SILC_LOG_DEBUG(("Start"));
1626
1627   idp = silc_id_payload_encode(id, id_type);
1628   silc_server_packet_send(server, sock, SILC_PACKET_NEW_ID, 
1629                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0, 
1630                           idp->data, idp->len, FALSE);
1631
1632   /* Send to backup routers if this is being broadcasted to primary
1633      router. */
1634   if (server->router && server->router->connection &&
1635       sock == server->router->connection && broadcast)
1636     silc_server_backup_send(server, NULL, SILC_PACKET_NEW_ID, 0,
1637                             idp->data, idp->len, FALSE, TRUE);
1638
1639   silc_buffer_free(idp);
1640 }
1641
1642 /* Send New Channel Payload to notify about newly created channel in the
1643    SILC network. Normal server nevers sends this packet. Router uses this
1644    to notify other routers in the network about new channel. This packet
1645    is broadcasted. */
1646
1647 void silc_server_send_new_channel(SilcServer server,
1648                                   SilcSocketConnection sock,
1649                                   bool broadcast,
1650                                   char *channel_name,
1651                                   void *channel_id, 
1652                                   uint32 channel_id_len,
1653                                   uint32 mode)
1654 {
1655   SilcBuffer packet;
1656   unsigned char *cid;
1657   uint32 name_len = strlen(channel_name);
1658
1659   SILC_LOG_DEBUG(("Start"));
1660
1661   cid = silc_id_id2str(channel_id, SILC_ID_CHANNEL);
1662   if (!cid)
1663     return;
1664
1665   /* Encode the channel payload */
1666   packet = silc_channel_payload_encode(channel_name, name_len,
1667                                        cid, channel_id_len, mode);
1668
1669   silc_server_packet_send(server, sock, SILC_PACKET_NEW_CHANNEL, 
1670                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0, 
1671                           packet->data, packet->len, FALSE);
1672
1673   /* Send to backup routers if this is being broadcasted to primary
1674      router. */
1675   if (server->router && server->router->connection &&
1676       sock == server->router->connection && broadcast)
1677     silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
1678                             packet->data, packet->len, FALSE, TRUE);
1679
1680   silc_free(cid);
1681   silc_buffer_free(packet);
1682 }
1683
1684 /* Send Channel Key payload to distribute the new channel key. Normal server
1685    sends this to router when new client joins to existing channel. Router
1686    sends this to the local server who sent the join command in case where
1687    the channel did not exist yet. Both normal and router servers uses this
1688    also to send this to locally connected clients on the channel. This
1689    must not be broadcasted packet. Routers do not send this to each other. 
1690    If `sender is provided then the packet is not sent to that connection since
1691    it originally came from it. */
1692
1693 void silc_server_send_channel_key(SilcServer server,
1694                                   SilcSocketConnection sender,
1695                                   SilcChannelEntry channel,
1696                                   unsigned char route)
1697 {
1698   SilcBuffer packet;
1699   unsigned char *chid;
1700   uint32 tmp_len;
1701  
1702   SILC_LOG_DEBUG(("Start"));
1703  
1704   chid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
1705   if (!chid)
1706     return;
1707  
1708   /* Encode channel key packet */
1709   tmp_len = strlen(channel->channel_key->cipher->name);
1710   packet = silc_channel_key_payload_encode(silc_id_get_len(channel->id,
1711                                                            SILC_ID_CHANNEL),
1712                                            chid, tmp_len,
1713                                            channel->channel_key->cipher->name,
1714                                            channel->key_len / 8, channel->key);
1715   silc_server_packet_send_to_channel(server, sender, channel, 
1716                                      SILC_PACKET_CHANNEL_KEY,
1717                                      route, packet->data, packet->len, FALSE);
1718   silc_buffer_free(packet);
1719   silc_free(chid);
1720 }
1721
1722 /* Generic function to send any command. The arguments must be sent already
1723    encoded into correct form in correct order. */
1724
1725 void silc_server_send_command(SilcServer server, 
1726                               SilcSocketConnection sock,
1727                               SilcCommand command, 
1728                               uint16 ident,
1729                               uint32 argc, ...)
1730 {
1731   SilcBuffer packet;
1732   va_list ap;
1733
1734   va_start(ap, argc);
1735
1736   packet = silc_command_payload_encode_vap(command, ident, argc, ap);
1737   silc_server_packet_send(server, sock, SILC_PACKET_COMMAND, 0,
1738                           packet->data, packet->len, TRUE);
1739   silc_buffer_free(packet);
1740   va_end(ap);
1741 }
1742
1743 /* Generic function to send any command reply. The arguments must be sent
1744    already encoded into correct form in correct order. */
1745
1746 void silc_server_send_command_reply(SilcServer server, 
1747                                     SilcSocketConnection sock,
1748                                     SilcCommand command, 
1749                                     SilcCommandStatus status,
1750                                     uint16 ident,
1751                                     uint32 argc, ...)
1752 {
1753   SilcBuffer packet;
1754   va_list ap;
1755
1756   va_start(ap, argc);
1757
1758   packet = silc_command_reply_payload_encode_vap(command, status, ident, 
1759                                                  argc, ap);
1760   silc_server_packet_send(server, sock, SILC_PACKET_COMMAND_REPLY, 0,
1761                           packet->data, packet->len, TRUE);
1762   silc_buffer_free(packet);
1763   va_end(ap);
1764 }
1765
1766 /* Send the heartbeat packet. */
1767
1768 void silc_server_send_heartbeat(SilcServer server,
1769                                 SilcSocketConnection sock)
1770 {
1771   silc_server_packet_send(server, sock, SILC_PACKET_HEARTBEAT, 0,
1772                           NULL, 0, FALSE);
1773 }
1774
1775 /* Generic function to relay packet we've received. This is used to relay
1776    packets to a client but generally can be used to other purposes as well. */
1777
1778 void silc_server_relay_packet(SilcServer server,
1779                               SilcSocketConnection dst_sock,
1780                               SilcCipher cipher,
1781                               SilcHmac hmac,
1782                               uint32 sequence,
1783                               SilcPacketContext *packet,
1784                               bool force_send)
1785 {
1786   silc_buffer_push(packet->buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
1787                    + packet->dst_id_len + packet->padlen);
1788
1789   silc_packet_send_prepare(dst_sock, 0, 0, packet->buffer->len);
1790   silc_buffer_put(dst_sock->outbuf, packet->buffer->data, packet->buffer->len);
1791   
1792   /* Re-encrypt packet */
1793   silc_packet_encrypt(cipher, hmac, sequence, dst_sock->outbuf, 
1794                       packet->buffer->len);
1795   
1796   /* Send the packet */
1797   silc_server_packet_send_real(server, dst_sock, force_send);
1798
1799   silc_buffer_pull(packet->buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
1800                    + packet->dst_id_len + packet->padlen);
1801 }
1802
1803 /* Routine used to send the connection authentication packet. */
1804
1805 void silc_server_send_connection_auth_request(SilcServer server,
1806                                               SilcSocketConnection sock,
1807                                               uint16 conn_type,
1808                                               SilcAuthMethod auth_meth)
1809 {
1810   SilcBuffer packet;
1811
1812   packet = silc_buffer_alloc(4);
1813   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1814   silc_buffer_format(packet,
1815                      SILC_STR_UI_SHORT(conn_type),
1816                      SILC_STR_UI_SHORT(auth_meth),
1817                      SILC_STR_END);
1818
1819   silc_server_packet_send(server, sock, SILC_PACKET_CONNECTION_AUTH_REQUEST,
1820                           0, packet->data, packet->len, FALSE);
1821   silc_buffer_free(packet);
1822 }
1823
1824 /* Purge the outgoing packet queue to the network if there is data. This
1825    function can be used to empty the packet queue. It is guaranteed that
1826    after this function returns the outgoing data queue is empty. */
1827
1828 void silc_server_packet_queue_purge(SilcServer server,
1829                                     SilcSocketConnection sock)
1830 {
1831   if (sock && SILC_IS_OUTBUF_PENDING(sock) && 
1832       (SILC_IS_DISCONNECTED(sock) == FALSE)) {
1833     server->stat.packets_sent++;
1834
1835     if (sock->outbuf->data - sock->outbuf->head)
1836       silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1837
1838     silc_packet_send(sock, TRUE);
1839
1840     SILC_SET_CONNECTION_FOR_INPUT(server->schedule, sock->sock);
1841     SILC_UNSET_OUTBUF_PENDING(sock);
1842     silc_buffer_clear(sock->outbuf);
1843   }
1844 }