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