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