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