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