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