Router environment. WHOIS/IDENTIFY/JOIN/channel message sending
[silc.git] / apps / silcd / packet_send.c
1 /*
2
3   packet_send.c
4
5   Author: Pekka Riikonen <priikone@poseidon.pspt.fi>
6
7   Copyright (C) 1997 - 2000 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                                  int force_send)
35 {
36   int ret;
37
38   /* Send the packet */
39   ret = silc_packet_send(sock, force_send);
40   if (ret != -2)
41     return ret;
42
43   /* Mark that there is some outgoing data available for this connection. 
44      This call sets the connection both for input and output (the input
45      is set always and this call keeps the input setting, actually). 
46      Actual data sending is performed by silc_server_packet_process. */
47   SILC_SET_CONNECTION_FOR_OUTPUT(sock->sock);
48
49   /* Mark to socket that data is pending in outgoing buffer. This flag
50      is needed if new data is added to the buffer before the earlier
51      put data is sent to the network. */
52   SILC_SET_OUTBUF_PENDING(sock);
53
54   return 0;
55 }
56
57 /* Assembles a new packet to be sent out to network. This doesn't actually
58    send the packet but creates the packet and fills the outgoing data
59    buffer and marks the packet ready to be sent to network. However, If 
60    argument force_send is TRUE the packet is sent immediately and not put 
61    to queue. Normal case is that the packet is not sent immediately. */
62
63 void silc_server_packet_send(SilcServer server,
64                              SilcSocketConnection sock, 
65                              SilcPacketType type, 
66                              SilcPacketFlags flags,
67                              unsigned char *data, 
68                              unsigned int data_len,
69                              int force_send)
70 {
71   void *dst_id = NULL;
72   SilcIdType dst_id_type = SILC_ID_NONE;
73
74   if (!sock)
75     return;
76
77   /* Get data used in the packet sending, keys and stuff */
78   switch(sock->type) {
79   case SILC_SOCKET_TYPE_CLIENT:
80     dst_id = ((SilcClientEntry)sock->user_data)->id;
81     dst_id_type = SILC_ID_CLIENT;
82     break;
83   case SILC_SOCKET_TYPE_SERVER:
84   case SILC_SOCKET_TYPE_ROUTER:
85     dst_id = ((SilcServerEntry)sock->user_data)->id;
86     dst_id_type = SILC_ID_SERVER;
87     break;
88   default:
89     break;
90   }
91
92   silc_server_packet_send_dest(server, sock, type, flags, dst_id,
93                                dst_id_type, data, data_len, force_send);
94 }
95
96 /* Assembles a new packet to be sent out to network. This doesn't actually
97    send the packet but creates the packet and fills the outgoing data
98    buffer and marks the packet ready to be sent to network. However, If 
99    argument force_send is TRUE the packet is sent immediately and not put 
100    to queue. Normal case is that the packet is not sent immediately. 
101    Destination information is sent as argument for this function. */
102
103 void silc_server_packet_send_dest(SilcServer server,
104                                   SilcSocketConnection sock, 
105                                   SilcPacketType type, 
106                                   SilcPacketFlags flags,
107                                   void *dst_id,
108                                   SilcIdType dst_id_type,
109                                   unsigned char *data, 
110                                   unsigned int data_len,
111                                   int force_send)
112 {
113   SilcPacketContext packetdata;
114   SilcIDListData idata;
115   SilcCipher cipher = NULL;
116   SilcHmac hmac = NULL;
117   unsigned char *dst_id_data = NULL;
118   unsigned int dst_id_len = 0;
119
120   SILC_LOG_DEBUG(("Sending packet, type %d", type));
121
122   /* Get data used in the packet sending, keys and stuff */
123   idata = (SilcIDListData)sock->user_data;
124
125   if (dst_id) {
126     dst_id_data = silc_id_id2str(dst_id, dst_id_type);
127     dst_id_len = silc_id_get_len(dst_id_type);
128   }
129
130   /* Set the packet context pointers */
131   packetdata.type = type;
132   packetdata.flags = flags;
133   packetdata.src_id = silc_id_id2str(server->id, server->id_type);
134   packetdata.src_id_len = SILC_ID_SERVER_LEN;
135   packetdata.src_id_type = server->id_type;
136   packetdata.dst_id = dst_id_data;
137   packetdata.dst_id_len = dst_id_len;
138   packetdata.dst_id_type = dst_id_type;
139   packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN + 
140     packetdata.src_id_len + dst_id_len;
141   packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
142   packetdata.rng = server->rng;
143
144   /* Prepare outgoing data buffer for packet sending */
145   silc_packet_send_prepare(sock, 
146                            SILC_PACKET_HEADER_LEN +
147                            packetdata.src_id_len + 
148                            packetdata.dst_id_len,
149                            packetdata.padlen,
150                            data_len);
151
152   SILC_LOG_DEBUG(("Putting data to outgoing buffer, len %d", data_len));
153
154   packetdata.buffer = sock->outbuf;
155
156   /* Put the data to the buffer */
157   if (data && data_len)
158     silc_buffer_put(sock->outbuf, data, data_len);
159
160   /* Create the outgoing packet */
161   silc_packet_assemble(&packetdata);
162
163   if (idata) {
164     cipher = idata->send_key;
165     hmac = idata->hmac;
166   }
167
168   /* Encrypt the packet */
169   silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
170
171   SILC_LOG_HEXDUMP(("Outgoing packet, len %d", sock->outbuf->len),
172                    sock->outbuf->data, sock->outbuf->len);
173
174   /* Now actually send the packet */
175   silc_server_packet_send_real(server, sock, force_send);
176
177   if (packetdata.src_id)
178     silc_free(packetdata.src_id);
179   if (packetdata.dst_id)
180     silc_free(packetdata.dst_id);
181 }
182
183 /* Forwards packet. Packets sent with this function will be marked as
184    forwarded (in the SILC header flags) so that the receiver knows that
185    we have forwarded the packet to it. Forwarded packets are handled
186    specially by the receiver as they are not destined to the receiver
187    originally. However, the receiver knows this because the forwarded
188    flag has been set (and the flag is authenticated). */
189
190 void silc_server_packet_forward(SilcServer server,
191                                 SilcSocketConnection sock,
192                                 unsigned char *data, unsigned int data_len,
193                                 int force_send)
194 {
195   SilcIDListData idata;
196   SilcCipher cipher = NULL;
197   SilcHmac hmac = NULL;
198
199   SILC_LOG_DEBUG(("Forwarding packet"));
200
201   /* Get data used in the packet sending, keys and stuff */
202   idata = (SilcIDListData)sock->user_data;
203
204   /* Prepare outgoing data buffer for packet sending */
205   silc_packet_send_prepare(sock, 0, 0, data_len);
206
207   /* Put the data to the buffer */
208   if (data && data_len)
209     silc_buffer_put(sock->outbuf, data, data_len);
210
211   /* Add the FORWARDED flag to packet flags */
212   sock->outbuf->data[2] |= (unsigned char)SILC_PACKET_FLAG_FORWARDED;
213
214   if (idata) {
215     cipher = idata->send_key;
216     hmac = idata->hmac;
217   }
218
219   /* Encrypt the packet */
220   silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
221
222   SILC_LOG_HEXDUMP(("Forwarded packet, len %d", sock->outbuf->len),
223                    sock->outbuf->data, sock->outbuf->len);
224
225   /* Now actually send the packet */
226   silc_server_packet_send_real(server, sock, force_send);
227 }
228
229 /* Broadcast received packet to our primary route. This function is used
230    by router to further route received broadcast packet. It is expected
231    that the broadcast flag from the packet is checked before calling this
232    function. This does not test or set the broadcast flag. */
233
234 void silc_server_packet_broadcast(SilcServer server,
235                                   SilcSocketConnection sock,
236                                   SilcPacketContext *packet)
237 {
238   SilcBuffer buffer = packet->buffer;
239   SilcIDListData idata;
240   void *id;
241
242   SILC_LOG_DEBUG(("Broadcasting received broadcast packet"));
243
244   /* If the packet is originated from our primary route we are
245      not allowed to send the packet. */
246   id = silc_id_str2id(packet->src_id, packet->src_id_type);
247   if (id && SILC_ID_SERVER_COMPARE(id, server->router->id)) {
248     idata = (SilcIDListData)sock->user_data;
249
250     silc_buffer_push(buffer, buffer->data - buffer->head);
251     silc_packet_send_prepare(sock, 0, 0, buffer->len); 
252     silc_buffer_put(sock->outbuf, buffer->data, buffer->len);
253     silc_packet_encrypt(idata->send_key, idata->hmac, 
254                         sock->outbuf, sock->outbuf->len);
255
256     SILC_LOG_HEXDUMP(("Broadcasted packet, len %d", sock->outbuf->len),
257                      sock->outbuf->data, sock->outbuf->len);
258
259     /* Now actually send the packet */
260     silc_server_packet_send_real(server, sock, TRUE);
261     silc_free(id);
262     return;
263   }
264
265   SILC_LOG_DEBUG(("Will not broadcast to primary route since it is the "
266                   "original sender of this packet"));
267   silc_free(id);
268 }
269
270 /* Routes received packet to `sock'. This is used to route the packets that
271    router receives but are not destined to it. */
272
273 void silc_server_packet_route(SilcServer server,
274                               SilcSocketConnection sock,
275                               SilcPacketContext *packet)
276 {
277   SilcBuffer buffer = packet->buffer;
278   SilcIDListData idata;
279
280   SILC_LOG_DEBUG(("Routing received packet"));
281
282   idata = (SilcIDListData)sock->user_data;
283
284   silc_buffer_push(buffer, buffer->data - buffer->head);
285   silc_packet_send_prepare(sock, 0, 0, buffer->len); 
286   silc_buffer_put(sock->outbuf, buffer->data, buffer->len);
287   silc_packet_encrypt(idata->send_key, idata->hmac, 
288                       sock->outbuf, sock->outbuf->len);
289
290   SILC_LOG_HEXDUMP(("Routed packet, len %d", sock->outbuf->len),
291                    sock->outbuf->data, sock->outbuf->len);
292
293   /* Now actually send the packet */
294   silc_server_packet_send_real(server, sock, TRUE);
295 }
296
297 /* Internal routine to actually create the channel packet and send it
298    to network. This is common function in channel message sending. If
299    `channel_message' is TRUE this encrypts the message as it is strictly
300    a channel message. If FALSE normal encryption process is used. */
301
302 static void
303 silc_server_packet_send_to_channel_real(SilcServer server,
304                                         SilcSocketConnection sock,
305                                         SilcPacketContext *packet,
306                                         SilcCipher cipher,
307                                         SilcHmac hmac,
308                                         unsigned char *data,
309                                         unsigned int data_len,
310                                         int channel_message,
311                                         int force_send)
312 {
313   packet->truelen = data_len + SILC_PACKET_HEADER_LEN + 
314     packet->src_id_len + packet->dst_id_len;
315
316   /* Prepare outgoing data buffer for packet sending */
317   silc_packet_send_prepare(sock, 
318                            SILC_PACKET_HEADER_LEN +
319                            packet->src_id_len + 
320                            packet->dst_id_len,
321                            packet->padlen,
322                            data_len);
323
324   packet->buffer = sock->outbuf;
325
326   /* Put the data to buffer, assemble and encrypt the packet. The packet
327      is encrypted with normal session key shared with the client. */
328   silc_buffer_put(sock->outbuf, data, data_len);
329   silc_packet_assemble(packet);
330   if (channel_message)
331     silc_packet_encrypt(cipher, hmac, sock->outbuf, SILC_PACKET_HEADER_LEN + 
332                         packet->src_id_len + packet->dst_id_len +
333                         packet->padlen);
334   else
335     silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
336     
337   SILC_LOG_HEXDUMP(("Channel packet, len %d", sock->outbuf->len),
338                    sock->outbuf->data, sock->outbuf->len);
339
340   /* Now actually send the packet */
341   silc_server_packet_send_real(server, sock, force_send);
342 }
343
344 /* This routine is used by the server to send packets to channel. The 
345    packet sent with this function is distributed to all clients on
346    the channel. Usually this is used to send notify messages to the
347    channel, things like notify about new user joining to the channel. 
348    If `route' is FALSE then the packet is sent only locally and will not
349    be routed anywhere (for router locally means cell wide). */
350
351 void silc_server_packet_send_to_channel(SilcServer server,
352                                         SilcChannelEntry channel,
353                                         SilcPacketType type,
354                                         unsigned char route,
355                                         unsigned char *data,
356                                         unsigned int data_len,
357                                         int force_send)
358 {
359   SilcSocketConnection sock = NULL;
360   SilcPacketContext packetdata;
361   SilcClientEntry client = NULL;
362   SilcServerEntry *routed = NULL;
363   SilcChannelClientEntry chl;
364   SilcIDListData idata;
365   unsigned int routed_count = 0;
366
367   /* This doesn't send channel message packets */
368   if (type == SILC_PACKET_CHANNEL_MESSAGE)
369     return;
370   
371   SILC_LOG_DEBUG(("Sending packet to channel"));
372
373   /* Set the packet context pointers. */
374   packetdata.flags = 0;
375   packetdata.type = type;
376   packetdata.src_id = silc_id_id2str(server->id, SILC_ID_SERVER);
377   packetdata.src_id_len = SILC_ID_SERVER_LEN;
378   packetdata.src_id_type = SILC_ID_SERVER;
379   packetdata.dst_id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
380   packetdata.dst_id_len = SILC_ID_CHANNEL_LEN;
381   packetdata.dst_id_type = SILC_ID_CHANNEL;
382   packetdata.rng = server->rng;
383   packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN + 
384     packetdata.src_id_len + packetdata.dst_id_len;
385   packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
386
387   /* If there are global users in the channel we will send the message
388      first to our router for further routing. */
389   if (route && server->server_type == SILC_SERVER && !server->standalone &&
390       channel->global_users) {
391     SilcServerEntry router;
392
393     /* Get data used in packet header encryption, keys and stuff. */
394     router = server->router;
395     sock = (SilcSocketConnection)router->connection;
396     idata = (SilcIDListData)router;
397     
398     SILC_LOG_DEBUG(("Sending channel message to router for routing"));
399
400     silc_server_packet_send_to_channel_real(server, sock, &packetdata,
401                                             idata->send_key, idata->hmac, 
402                                             data, data_len, FALSE, force_send);
403   }
404
405   /* Send the message to clients on the channel's client list. */
406   silc_list_start(channel->user_list);
407   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
408     client = chl->client;
409
410     /* If client has router set it is not locally connected client and
411        we will route the message to the router set in the client. Though,
412        send locally connected server in all cases. */
413     if (server->server_type == SILC_ROUTER && client && client->router && 
414         ((!route && client->router->router == server->id_entry) || route)) {
415       int k;
416
417       /* Check if we have sent the packet to this route already */
418       for (k = 0; k < routed_count; k++)
419         if (routed[k] == client->router)
420           break;
421       if (k < routed_count)
422         continue;
423
424       /* Get data used in packet header encryption, keys and stuff. */
425       sock = (SilcSocketConnection)client->router->connection;
426       idata = (SilcIDListData)client->router;
427
428       /* Send the packet */
429       silc_server_packet_send_to_channel_real(server, sock, &packetdata,
430                                               idata->send_key, idata->hmac, 
431                                               data, data_len, FALSE, 
432                                               force_send);
433
434       /* We want to make sure that the packet is routed to same router
435          only once. Mark this route as sent route. */
436       k = routed_count;
437       routed = silc_realloc(routed, sizeof(*routed) * (k + 1));
438       routed[k] = client->router;
439       routed_count++;
440
441       continue;
442     }
443
444     if (server->server_type == SILC_ROUTER && !route)
445       continue;
446
447     /* Send to locally connected client */
448     if (client) {
449
450       /* Get data used in packet header encryption, keys and stuff. */
451       sock = (SilcSocketConnection)client->connection;
452       idata = (SilcIDListData)client;
453
454       /* Send the packet */
455       silc_server_packet_send_to_channel_real(server, sock, &packetdata,
456                                               idata->send_key, idata->hmac, 
457                                               data, data_len, FALSE, 
458                                               force_send);
459     }
460   }
461
462   if (routed_count)
463     silc_free(routed);
464   silc_free(packetdata.src_id);
465   silc_free(packetdata.dst_id);
466 }
467
468 /* This routine is explicitly used to relay messages to some channel.
469    Packets sent with this function we have received earlier and are
470    totally encrypted. This just sends the packet to all clients on
471    the channel. If the sender of the packet is someone on the channel 
472    the message will not be sent to that client. The SILC Packet header
473    is encrypted with the session key shared between us and the client.
474    MAC is also computed before encrypting the header. Rest of the
475    packet will be untouched. */
476
477 void silc_server_packet_relay_to_channel(SilcServer server,
478                                          SilcSocketConnection sender_sock,
479                                          SilcChannelEntry channel,
480                                          void *sender, 
481                                          SilcIdType sender_type,
482                                          unsigned char *data,
483                                          unsigned int data_len,
484                                          int force_send)
485 {
486   int found = FALSE;
487   SilcSocketConnection sock = NULL;
488   SilcPacketContext packetdata;
489   SilcClientEntry client = NULL;
490   SilcServerEntry *routed = NULL;
491   SilcChannelClientEntry chl;
492   unsigned int routed_count = 0;
493   SilcIDListData idata;
494
495   SILC_LOG_DEBUG(("Relaying packet to channel"));
496
497   /* Set the packet context pointers. */
498   packetdata.flags = 0;
499   packetdata.type = SILC_PACKET_CHANNEL_MESSAGE;
500   packetdata.src_id = silc_id_id2str(sender, sender_type);
501   packetdata.src_id_len = silc_id_get_len(sender_type);
502   packetdata.src_id_type = sender_type;
503   packetdata.dst_id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
504   packetdata.dst_id_len = SILC_ID_CHANNEL_LEN;
505   packetdata.dst_id_type = SILC_ID_CHANNEL;
506   packetdata.rng = server->rng;
507   packetdata.padlen = SILC_PACKET_PADLEN((SILC_PACKET_HEADER_LEN +
508                                           packetdata.src_id_len +
509                                           packetdata.dst_id_len));
510
511   /* If there are global users in the channel we will send the message
512      first to our router for further routing. */
513   if (server->server_type == SILC_SERVER && !server->standalone &&
514       channel->global_users) {
515     SilcServerEntry router;
516
517     router = server->router;
518
519     /* Check that the sender is not our router. */
520     if (sender_sock != (SilcSocketConnection)router->connection) {
521
522       /* Get data used in packet header encryption, keys and stuff. */
523       sock = (SilcSocketConnection)router->connection;
524       idata = (SilcIDListData)router;
525
526       SILC_LOG_DEBUG(("Sending channel message to router for routing"));
527
528       silc_server_packet_send_to_channel_real(server, sock, &packetdata,
529                                               idata->send_key, idata->hmac, 
530                                               data, data_len, TRUE, 
531                                               force_send);
532     }
533   }
534
535   /* Send the message to clients on the channel's client list. */
536   silc_list_start(channel->user_list);
537   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
538     client = chl->client;
539
540     if (client) {
541
542       /* If sender is one on the channel do not send it the packet. */
543       if (!found && !SILC_ID_CLIENT_COMPARE(client->id, sender)) {
544         found = TRUE;
545         continue;
546       }
547
548       /* If the client has set router it means that it is not locally
549          connected client and we will route the packet further. */
550       if (server->server_type == SILC_ROUTER && client->router) {
551         int k;
552
553         /* Sender maybe server as well so we want to make sure that
554            we won't send the message to the server it came from. */
555         if (!found && !SILC_ID_SERVER_COMPARE(client->router->id, sender)) {
556           found = TRUE;
557           continue;
558         }
559
560         /* Check if we have sent the packet to this route already */
561         for (k = 0; k < routed_count; k++)
562           if (routed[k] == client->router)
563             break;
564         if (k < routed_count)
565           continue;
566         
567         /* Get data used in packet header encryption, keys and stuff. */
568         sock = (SilcSocketConnection)client->router->connection;
569         idata = (SilcIDListData)client->router;
570
571         /* Send the packet */
572         silc_server_packet_send_to_channel_real(server, sock, &packetdata,
573                                                 idata->send_key, idata->hmac, 
574                                                 data, data_len, TRUE, 
575                                                 force_send);
576         
577         /* We want to make sure that the packet is routed to same router
578            only once. Mark this route as sent route. */
579         k = routed_count;
580         routed = silc_realloc(routed, sizeof(*routed) * (k + 1));
581         routed[k] = client->router;
582         routed_count++;
583         
584         continue;
585       }
586
587       /* XXX Check client's mode on the channel. */
588
589       /* Get data used in packet header encryption, keys and stuff. */
590       sock = (SilcSocketConnection)client->connection;
591       idata = (SilcIDListData)client;
592
593       SILC_LOG_DEBUG(("Sending packet to client %s (%s)", 
594                       sock->hostname, sock->ip));
595
596       /* Send the packet */
597       silc_server_packet_send_to_channel_real(server, sock, &packetdata,
598                                               idata->send_key, idata->hmac, 
599                                               data, data_len, TRUE, 
600                                               force_send);
601     }
602   }
603
604   silc_free(packetdata.src_id);
605   silc_free(packetdata.dst_id);
606 }
607
608 /* This function is used to send packets strictly to all local clients
609    on a particular channel.  This is used for example to distribute new
610    channel key to all our locally connected clients on the channel. 
611    The packets are always encrypted with the session key shared between
612    the client, this means these are not _to the channel_ but _to the client_
613    on the channel. */
614
615 void silc_server_packet_send_local_channel(SilcServer server,
616                                            SilcChannelEntry channel,
617                                            SilcPacketType type,
618                                            SilcPacketFlags flags,
619                                            unsigned char *data,
620                                            unsigned int data_len,
621                                            int force_send)
622 {
623   SilcChannelClientEntry chl;
624   SilcSocketConnection sock = NULL;
625
626   SILC_LOG_DEBUG(("Start"));
627
628   /* Send the message to clients on the channel's client list. */
629   silc_list_start(channel->user_list);
630   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
631     if (chl->client) {
632       sock = (SilcSocketConnection)chl->client->connection;
633
634       /* Send the packet to the client */
635       silc_server_packet_send_dest(server, sock, type, flags, chl->client->id,
636                                    SILC_ID_CLIENT, data, data_len,
637                                    force_send);
638     }
639   }
640 }
641
642 /* Routine used to send (relay, route) private messages to some destination.
643    If the private message key does not exist then the message is re-encrypted,
644    otherwise we just pass it along. This really is not used to send new
645    private messages (as server does not send them) but to relay received
646    private messages. */
647
648 void silc_server_send_private_message(SilcServer server,
649                                       SilcSocketConnection dst_sock,
650                                       SilcCipher cipher,
651                                       SilcHmac hmac,
652                                       SilcPacketContext *packet)
653 {
654   SilcBuffer buffer = packet->buffer;
655
656   /* Send and re-encrypt if private messge key does not exist */
657   if ((packet->flags & SILC_PACKET_FLAG_PRIVMSG_KEY) == FALSE) {
658
659     silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
660                      + packet->dst_id_len + packet->padlen);
661     silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
662     silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
663     
664     /* Re-encrypt packet */
665     silc_packet_encrypt(cipher, hmac, dst_sock->outbuf, buffer->len);
666     
667     /* Send the packet */
668     silc_server_packet_send_real(server, dst_sock, FALSE);
669
670   } else {
671     /* Key exist so just send it */
672     silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
673                      + packet->dst_id_len + packet->padlen);
674     silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
675     silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
676     silc_server_packet_send_real(server, dst_sock, FALSE);
677   }
678 }
679
680 /* Sends current motd to client */
681
682 void silc_server_send_motd(SilcServer server,
683                            SilcSocketConnection sock)
684 {
685   char *motd;
686   int motd_len;
687
688   if (server->config && server->config->motd && 
689       server->config->motd->motd_file) {
690
691     motd = silc_file_read(server->config->motd->motd_file, &motd_len);
692     if (!motd)
693       return;
694
695     silc_server_send_notify(server, sock, SILC_NOTIFY_TYPE_MOTD, 1,
696                             motd, motd_len);
697     silc_free(motd);
698   }
699 }
700
701 /* Sends error message. Error messages may or may not have any 
702    implications. */
703
704 void silc_server_send_error(SilcServer server,
705                             SilcSocketConnection sock,
706                             const char *fmt, ...)
707 {
708   va_list ap;
709   unsigned char buf[4096];
710
711   memset(buf, 0, sizeof(buf));
712   va_start(ap, fmt);
713   vsprintf(buf, fmt, ap);
714   va_end(ap);
715
716   silc_server_packet_send(server, sock, SILC_PACKET_ERROR, 0, 
717                           buf, strlen(buf), FALSE);
718 }
719
720 /* Sends notify message. If format is TRUE the variable arguments are
721    formatted and the formatted string is sent as argument payload. If it is
722    FALSE then each argument is sent as separate argument and their format
723    in the argument list must be { argument data, argument length }. */
724
725 void silc_server_send_notify(SilcServer server,
726                              SilcSocketConnection sock,
727                              SilcNotifyType type,
728                              unsigned int argc, ...)
729 {
730   va_list ap;
731   SilcBuffer packet;
732
733   va_start(ap, argc);
734
735   packet = silc_notify_payload_encode(type, argc, ap);
736   silc_server_packet_send(server, sock, SILC_PACKET_NOTIFY, 0, 
737                           packet->data, packet->len, FALSE);
738   silc_buffer_free(packet);
739 }
740
741 /* Sends notify message destined to specific entity. */
742
743 void silc_server_send_notify_dest(SilcServer server,
744                                   SilcSocketConnection sock,
745                                   void *dest_id,
746                                   SilcIdType dest_id_type,
747                                   SilcNotifyType type,
748                                   unsigned int argc, ...)
749 {
750   va_list ap;
751   SilcBuffer packet;
752
753   va_start(ap, argc);
754
755   packet = silc_notify_payload_encode(type, argc, ap);
756   silc_server_packet_send_dest(server, sock, SILC_PACKET_NOTIFY, 0, 
757                                dest_id, dest_id_type,
758                                packet->data, packet->len, FALSE);
759   silc_buffer_free(packet);
760 }
761
762 /* Sends notify message to a channel. The notify message sent is 
763    distributed to all clients on the channel. If `router_notify' is TRUE
764    then the notify may be routed to primary route or to some other routers.
765    If FALSE it is assured that the notify is sent only locally. */
766
767 void silc_server_send_notify_to_channel(SilcServer server,
768                                         SilcChannelEntry channel,
769                                         unsigned char route_notify,
770                                         SilcNotifyType type,
771                                         unsigned int argc, ...)
772 {
773   va_list ap;
774   SilcBuffer packet;
775
776   va_start(ap, argc);
777
778   packet = silc_notify_payload_encode(type, argc, ap);
779   silc_server_packet_send_to_channel(server, channel, 
780                                      SILC_PACKET_NOTIFY, route_notify,
781                                      packet->data, packet->len, FALSE);
782   silc_buffer_free(packet);
783 }
784
785 /* Send notify message to all clients the client has joined. It is quaranteed
786    that the message is sent only once to a client (ie. if a client is joined
787    on two same channel it will receive only one notify message). Also, this
788    sends only to local clients (locally connected if we are server, and to
789    local servers if we are router). */
790
791 void silc_server_send_notify_on_channels(SilcServer server,
792                                          SilcClientEntry client,
793                                          SilcNotifyType type,
794                                          unsigned int argc, ...)
795 {
796   int k;
797   SilcSocketConnection sock = NULL;
798   SilcPacketContext packetdata;
799   SilcClientEntry c;
800   SilcClientEntry *sent_clients = NULL;
801   unsigned int sent_clients_count = 0;
802   SilcServerEntry *routed = NULL;
803   unsigned int routed_count = 0;
804   SilcChannelEntry channel;
805   SilcChannelClientEntry chl, chl2;
806   SilcIDListData idata;
807   SilcBuffer packet;
808   unsigned char *data;
809   unsigned int data_len;
810   int force_send = FALSE;
811   va_list ap;
812
813   SILC_LOG_DEBUG(("Start"));
814
815   if (!silc_list_count(client->channels))
816     return;
817
818   va_start(ap, argc);
819   packet = silc_notify_payload_encode(type, argc, ap);
820   data = packet->data;
821   data_len = packet->len;
822
823   /* Set the packet context pointers. */
824   packetdata.flags = 0;
825   packetdata.type = SILC_PACKET_NOTIFY;
826   packetdata.src_id = silc_id_id2str(server->id, SILC_ID_SERVER);
827   packetdata.src_id_len = SILC_ID_SERVER_LEN;
828   packetdata.src_id_type = SILC_ID_SERVER;
829   packetdata.rng = server->rng;
830
831   silc_list_start(client->channels);
832   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
833     channel = chl->channel;
834
835     /* Send the message to all clients on the channel's client list. */
836     silc_list_start(channel->user_list);
837     while ((chl2 = silc_list_get(channel->user_list)) != SILC_LIST_END) {
838       c = chl2->client;
839       
840       /* Check if we have sent the packet to this client already */
841       for (k = 0; k < sent_clients_count; k++)
842         if (sent_clients[k] == c)
843           break;
844       if (k < sent_clients_count)
845         continue;
846
847       /* If we are router and if this client has router set it is not
848          locally connected client and we will route the message to the
849          router set in the client. */
850       if (c && c->router && server->server_type == SILC_ROUTER) {
851         /* Check if we have sent the packet to this route already */
852         for (k = 0; k < routed_count; k++)
853           if (routed[k] == c->router)
854             break;
855         if (k < routed_count)
856           continue;
857         
858         /* Get data used in packet header encryption, keys and stuff. */
859         sock = (SilcSocketConnection)c->router->connection;
860         idata = (SilcIDListData)c->router;
861         
862         packetdata.dst_id = silc_id_id2str(c->router->id, SILC_ID_SERVER);
863         packetdata.dst_id_len = SILC_ID_SERVER_LEN;
864         packetdata.dst_id_type = SILC_ID_SERVER;
865         packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN + 
866           packetdata.src_id_len + packetdata.dst_id_len;
867         packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
868
869         /* Send the packet */
870         silc_server_packet_send_to_channel_real(server, sock, &packetdata,
871                                                 idata->send_key, idata->hmac, 
872                                                 data, data_len, FALSE, 
873                                                 force_send);
874         
875         silc_free(packetdata.dst_id);
876
877         /* We want to make sure that the packet is routed to same router
878            only once. Mark this route as sent route. */
879         k = routed_count;
880         routed = silc_realloc(routed, sizeof(*routed) * (k + 1));
881         routed[k] = c->router;
882         routed_count++;
883
884         continue;
885       }
886
887       /* Send to locally connected client */
888       if (c) {
889         
890         /* Get data used in packet header encryption, keys and stuff. */
891         sock = (SilcSocketConnection)c->connection;
892         idata = (SilcIDListData)c;
893         
894         packetdata.dst_id = silc_id_id2str(c->id, SILC_ID_CLIENT);
895         packetdata.dst_id_len = SILC_ID_CLIENT_LEN;
896         packetdata.dst_id_type = SILC_ID_CLIENT;
897         packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN + 
898           packetdata.src_id_len + packetdata.dst_id_len;
899         packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
900
901         /* Send the packet */
902         silc_server_packet_send_to_channel_real(server, sock, &packetdata,
903                                                 idata->send_key, idata->hmac, 
904                                                 data, data_len, FALSE, 
905                                                 force_send);
906
907         silc_free(packetdata.dst_id);
908
909         /* Make sure that we send the notify only once per client. */
910         sent_clients = silc_realloc(sent_clients, sizeof(*sent_clients) * 
911                                     (sent_clients_count + 1));
912         sent_clients[sent_clients_count] = c;
913         sent_clients_count++;
914       }
915     }
916   }
917
918   if (routed_count)
919     silc_free(routed);
920   if (sent_clients_count)
921     silc_free(sent_clients);
922   silc_free(packetdata.src_id);
923 }
924
925 /* Sends New ID Payload to remote end. The packet is used to distribute
926    information about new registered clients, servers, channel etc. usually
927    to routers so that they can keep these information up to date. 
928    If the argument `broadcast' is TRUE then the packet is sent as
929    broadcast packet. */
930
931 void silc_server_send_new_id(SilcServer server,
932                              SilcSocketConnection sock,
933                              int broadcast,
934                              void *id, SilcIdType id_type, 
935                              unsigned int id_len)
936 {
937   SilcBuffer idp;
938
939   SILC_LOG_DEBUG(("Start"));
940
941   idp = silc_id_payload_encode(id, id_type);
942   silc_server_packet_send(server, sock, SILC_PACKET_NEW_ID, 
943                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0, 
944                           idp->data, idp->len, FALSE);
945   silc_buffer_free(idp);
946 }
947
948 /* Sends Replace ID payload to remote end. This is used to replace old
949    ID with new ID sent in the packet.  This is called for example when
950    user changes nickname and we create new ID for the user.  If the 
951    argument `broadcast' is TRUE then the packet is sent as
952    broadcast packet. */
953 /* XXX It would be expected that the new id is same type as the old
954    ID. :) */
955
956 void silc_server_send_replace_id(SilcServer server,
957                                  SilcSocketConnection sock,
958                                  int broadcast,
959                                  void *old_id, SilcIdType old_id_type,
960                                  unsigned int old_id_len,
961                                  void *new_id, SilcIdType new_id_type,
962                                  unsigned int new_id_len)
963 {
964   SilcBuffer packet;
965   unsigned char *oid;
966   unsigned char *nid;
967
968   SILC_LOG_DEBUG(("Start"));
969
970   oid = silc_id_id2str(old_id, old_id_type);
971   if (!oid)
972     return;
973
974   nid = silc_id_id2str(new_id, new_id_type);
975   if (!nid)
976     return;
977
978   packet = silc_buffer_alloc(2 + 2 + 2 + 2 + old_id_len + new_id_len);
979   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
980   silc_buffer_format(packet,
981                      SILC_STR_UI_SHORT(old_id_type),
982                      SILC_STR_UI_SHORT(old_id_len),
983                      SILC_STR_UI_XNSTRING(oid, old_id_len),
984                      SILC_STR_UI_SHORT(new_id_type),
985                      SILC_STR_UI_SHORT(new_id_len),
986                      SILC_STR_UI_XNSTRING(nid, new_id_len),
987                      SILC_STR_END);
988
989   silc_server_packet_send(server, sock, SILC_PACKET_REPLACE_ID, 
990                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0, 
991                           packet->data, packet->len, FALSE);
992   silc_free(oid);
993   silc_free(nid);
994   silc_buffer_free(packet);
995 }
996
997 /* This function is used to send Remove Channel User payload. This may sent
998    by server but is usually used only by router to notify other routers that
999    user has left a channel. Normal server sends this packet to its router
1000    to notify that the router should not hold a record about this client
1001    on a channel anymore. Router distributes it further to other routers. */
1002
1003 void silc_server_send_remove_channel_user(SilcServer server,
1004                                           SilcSocketConnection sock,
1005                                           int broadcast,
1006                                           void *client_id, void *channel_id)
1007 {
1008   SilcBuffer packet;
1009   unsigned char *clid, *chid;
1010
1011   SILC_LOG_DEBUG(("Start"));
1012
1013   clid = silc_id_id2str(client_id, SILC_ID_CLIENT);
1014   if (!clid)
1015     return;
1016
1017   chid = silc_id_id2str(channel_id, SILC_ID_CHANNEL);
1018   if (!chid)
1019     return;
1020
1021   packet = silc_buffer_alloc(2 + 2 + SILC_ID_CLIENT_LEN + SILC_ID_CHANNEL_LEN);
1022   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1023   silc_buffer_format(packet,
1024                      SILC_STR_UI_SHORT(SILC_ID_CLIENT_LEN),
1025                      SILC_STR_UI_XNSTRING(clid, SILC_ID_CLIENT_LEN),
1026                      SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
1027                      SILC_STR_UI_XNSTRING(chid, SILC_ID_CHANNEL_LEN),
1028                      SILC_STR_END);
1029
1030   silc_server_packet_send(server, sock, SILC_PACKET_REMOVE_CHANNEL_USER, 
1031                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0, 
1032                           packet->data, packet->len, FALSE);
1033   silc_free(clid);
1034   silc_free(chid);
1035   silc_buffer_free(packet);
1036 }
1037
1038 /* Send New Channel Payload to notify about newly created channel in the
1039    SILC network. Normal server nevers sends this packet. Router uses this
1040    to notify other routers in the network about new channel. This packet
1041    is broadcasted. */
1042
1043 void silc_server_send_new_channel(SilcServer server,
1044                                   SilcSocketConnection sock,
1045                                   int broadcast,
1046                                   char *channel_name,
1047                                   void *channel_id, 
1048                                   unsigned int channel_id_len)
1049 {
1050   SilcBuffer packet;
1051   unsigned char *cid;
1052   unsigned int name_len = strlen(channel_name);
1053
1054   SILC_LOG_DEBUG(("Start"));
1055
1056   cid = silc_id_id2str(channel_id, SILC_ID_CHANNEL);
1057   if (!cid)
1058     return;
1059
1060   packet = silc_buffer_alloc(2 + 2 + name_len + channel_id_len);
1061   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1062   silc_buffer_format(packet,
1063                      SILC_STR_UI_SHORT(name_len),
1064                      SILC_STR_UI_XNSTRING(channel_name, name_len),
1065                      SILC_STR_UI_SHORT(channel_id_len),
1066                      SILC_STR_UI_XNSTRING(cid, channel_id_len),
1067                      SILC_STR_END);
1068
1069   silc_server_packet_send(server, sock, SILC_PACKET_NEW_CHANNEL, 
1070                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0, 
1071                           packet->data, packet->len, FALSE);
1072
1073   silc_free(cid);
1074   silc_buffer_free(packet);
1075 }
1076
1077 /* Send New Channel User payload to notify routers in the network about new
1078    user on the channel. The packet is may be broadcasted. Normal server
1079    can send this but must not receive. Router can send and receive it. */
1080
1081 void silc_server_send_new_channel_user(SilcServer server,
1082                                        SilcSocketConnection sock,
1083                                        int broadcast,
1084                                        void *channel_id, 
1085                                        unsigned int channel_id_len,
1086                                        void *client_id,
1087                                        unsigned int client_id_len)
1088 {
1089   SilcBuffer packet;
1090   unsigned char *clid, *chid;
1091
1092   SILC_LOG_DEBUG(("Start"));
1093
1094   chid = silc_id_id2str(channel_id, SILC_ID_CHANNEL);
1095   if (!chid)
1096     return;
1097
1098   clid = silc_id_id2str(client_id, SILC_ID_CLIENT);
1099   if (!clid)
1100     return;
1101
1102   packet = silc_buffer_alloc(2 + 2 + channel_id_len + client_id_len);
1103   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1104   silc_buffer_format(packet,
1105                      SILC_STR_UI_SHORT(channel_id_len),
1106                      SILC_STR_UI_XNSTRING(chid, channel_id_len),
1107                      SILC_STR_UI_SHORT(client_id_len),
1108                      SILC_STR_UI_XNSTRING(clid, client_id_len),
1109                      SILC_STR_END);
1110
1111   silc_server_packet_send(server, sock, SILC_PACKET_NEW_CHANNEL_USER, 
1112                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0, 
1113                           packet->data, packet->len, FALSE);
1114   silc_free(clid);
1115   silc_free(chid);
1116   silc_buffer_free(packet);
1117 }
1118
1119 /* Send Channel Key payload to distribute the new channel key. Normal server
1120    sends this to router when new client joins to existing channel. Router
1121    sends this to the local server who sent the join command in case where
1122    the channel did not exist yet. Both normal and router servers uses this
1123    also to send this to locally connected clients on the channel. This
1124    must not be broadcasted packet. Routers do not send this to each other. */
1125
1126 void silc_server_send_channel_key(SilcServer server,
1127                                   SilcChannelEntry channel,
1128                                   unsigned char route)
1129 {
1130   SilcBuffer packet;
1131   unsigned char *chid;
1132   unsigned int tmp_len;
1133  
1134   SILC_LOG_DEBUG(("Start"));
1135  
1136   chid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
1137   if (!chid)
1138     return;
1139  
1140   /* Encode channel key packet */
1141   tmp_len = strlen(channel->channel_key->cipher->name);
1142   packet = silc_channel_key_payload_encode(SILC_ID_CHANNEL_LEN, chid, tmp_len,
1143                                            channel->channel_key->cipher->name,
1144                                            channel->key_len / 8, channel->key);
1145  
1146   silc_server_packet_send_to_channel(server, channel, SILC_PACKET_CHANNEL_KEY,
1147                                      route, packet->data, packet->len, FALSE);
1148   silc_buffer_free(packet);
1149   silc_free(chid);
1150 }
1151
1152 /* Generic function to send any command. The arguments must be sent already
1153    encoded into correct form in correct order. */
1154
1155 void silc_server_send_command(SilcServer server, 
1156                               SilcSocketConnection sock,
1157                               SilcCommand command, 
1158                               unsigned int argc, ...)
1159 {
1160   SilcBuffer packet;
1161   va_list ap;
1162
1163   va_start(ap, argc);
1164
1165   packet = silc_command_payload_encode_vap(command, 0, argc, ap);
1166   silc_server_packet_send(server, sock, SILC_PACKET_COMMAND, 0,
1167                           packet->data, packet->len, TRUE);
1168   silc_buffer_free(packet);
1169 }
1170
1171 /* Function used to send REMOVE_ID packet. The packet is used to notify
1172    routers that certain ID should be removed. After that the ID will become
1173    invalid.  If the argument `broadcast' is TRUE then the packet is sent as
1174    broadcast packet. */
1175
1176 void silc_server_send_remove_id(SilcServer server,
1177                                 SilcSocketConnection sock,
1178                                 int broadcast,
1179                                 void *id, unsigned int id_len,
1180                                 SilcIdType id_type)
1181 {
1182   SilcBuffer idp;
1183
1184   SILC_LOG_DEBUG(("Start"));
1185
1186   idp = silc_id_payload_encode(id, id_type);
1187   silc_server_packet_send(server, sock, SILC_PACKET_REMOVE_ID, 
1188                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0, 
1189                           idp->data, idp->len, FALSE);
1190   silc_buffer_free(idp);
1191 }