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