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