0860b68e1ea6c357acca50d1f72e7eac19cf2742
[silc.git] / apps / silcd / packet_send.c
1 /*
2
3   packet_send.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 1997 - 2001 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; either version 2 of the License, or
12   (at your option) any later version.
13   
14   This program is distributed in the hope that it will be useful,
15   but WITHOUT ANY WARRANTY; without even the implied warranty of
16   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   GNU General Public License for more details.
18
19 */
20 /*
21  * Server packet routines to send packets. 
22  */
23 /* $Id$ */
24
25 #include "serverincludes.h"
26 #include "server_internal.h"
27
28 /* Routine that sends packet or marks packet to be sent. This is used
29    directly only in special cases. Normal cases should use
30    silc_server_packet_send. Returns < 0 error. */
31
32 int silc_server_packet_send_real(SilcServer server,
33                                  SilcSocketConnection sock,
34                                  bool force_send)
35 {
36   int ret;
37
38   /* If disconnecting, ignore the data */
39   if (SILC_IS_DISCONNECTING(sock))
40     return -1;
41
42   /* If rekey protocol is active we must assure that all packets are
43      sent through packet queue. */
44   if (SILC_SERVER_IS_REKEY(sock))
45     force_send = FALSE;
46
47   /* If outbound data is already pending do not force send */
48   if (SILC_IS_OUTBUF_PENDING(sock))
49     force_send = FALSE;
50
51   /* Send the packet */
52   ret = silc_packet_send(sock, force_send);
53   if (ret != -2)
54     return ret;
55
56   /* Mark that there is some outgoing data available for this connection. 
57      This call sets the connection both for input and output (the input
58      is set always and this call keeps the input setting, actually). 
59      Actual data sending is performed by silc_server_packet_process. */
60   SILC_SET_CONNECTION_FOR_OUTPUT(server->schedule, sock->sock);
61
62   /* Mark to socket that data is pending in outgoing buffer. This flag
63      is needed if new data is added to the buffer before the earlier
64      put data is sent to the network. */
65   SILC_SET_OUTBUF_PENDING(sock);
66
67   return 0;
68 }
69
70 /* Assembles a new packet to be sent out to network. This doesn't actually
71    send the packet but creates the packet and fills the outgoing data
72    buffer and marks the packet ready to be sent to network. However, If 
73    argument force_send is TRUE the packet is sent immediately and not put 
74    to queue. Normal case is that the packet is not sent immediately. */
75
76 void silc_server_packet_send(SilcServer server,
77                              SilcSocketConnection sock, 
78                              SilcPacketType type, 
79                              SilcPacketFlags flags,
80                              unsigned char *data, 
81                              uint32 data_len,
82                              bool force_send)
83 {
84   void *dst_id = NULL;
85   SilcIdType dst_id_type = SILC_ID_NONE;
86   SilcIDListData idata = (SilcIDListData)sock->user_data;
87
88   if (!sock)
89     return;
90
91   /* If disconnecting, ignore the data */
92   if (SILC_IS_DISCONNECTING(sock))
93     return;
94
95   /* If entry is disabled do not sent anything. */
96   if (idata && idata->status & SILC_IDLIST_STATUS_DISABLED)
97     return;
98
99   /* Get data used in the packet sending, keys and stuff */
100   switch(sock->type) {
101   case SILC_SOCKET_TYPE_CLIENT:
102     if (sock->user_data) {
103       dst_id = ((SilcClientEntry)sock->user_data)->id;
104       dst_id_type = SILC_ID_CLIENT;
105     }
106     break;
107   case SILC_SOCKET_TYPE_SERVER:
108   case SILC_SOCKET_TYPE_ROUTER:
109     if (sock->user_data) {
110       dst_id = ((SilcServerEntry)sock->user_data)->id;
111       dst_id_type = SILC_ID_SERVER;
112     }
113     break;
114   default:
115     break;
116   }
117
118   silc_server_packet_send_dest(server, sock, type, flags, dst_id,
119                                dst_id_type, data, data_len, force_send);
120 }
121
122 /* Assembles a new packet to be sent out to network. This doesn't actually
123    send the packet but creates the packet and fills the outgoing data
124    buffer and marks the packet ready to be sent to network. However, If 
125    argument force_send is TRUE the packet is sent immediately and not put 
126    to queue. Normal case is that the packet is not sent immediately. 
127    Destination information is sent as argument for this function. */
128
129 void silc_server_packet_send_dest(SilcServer server,
130                                   SilcSocketConnection sock, 
131                                   SilcPacketType type, 
132                                   SilcPacketFlags flags,
133                                   void *dst_id,
134                                   SilcIdType dst_id_type,
135                                   unsigned char *data, 
136                                   uint32 data_len,
137                                   bool force_send)
138 {
139   SilcPacketContext packetdata;
140   SilcIDListData idata = (SilcIDListData)sock->user_data;
141   SilcCipher cipher = NULL;
142   SilcHmac hmac = NULL;
143   uint32 sequence = 0;
144   unsigned char *dst_id_data = NULL;
145   uint32 dst_id_len = 0;
146   int block_len = 0;
147
148   /* If disconnecting, ignore the data */
149   if (SILC_IS_DISCONNECTING(sock))
150     return;
151
152   /* If entry is disabled do not sent anything. */
153   if (idata && idata->status & SILC_IDLIST_STATUS_DISABLED)
154     return;
155
156   SILC_LOG_DEBUG(("Sending packet, type %d", type));
157
158   if (dst_id) {
159     dst_id_data = silc_id_id2str(dst_id, dst_id_type);
160     dst_id_len = silc_id_get_len(dst_id, dst_id_type);
161   }
162
163   if (idata) {
164     cipher = idata->send_key;
165     hmac = idata->hmac_send;
166     sequence = idata->psn_send++;
167     block_len = silc_cipher_get_block_len(cipher);
168   }
169
170   /* Set the packet context pointers */
171   packetdata.type = type;
172   packetdata.flags = flags;
173   packetdata.src_id = silc_id_id2str(server->id, server->id_type);
174   packetdata.src_id_len = silc_id_get_len(server->id, server->id_type);
175   packetdata.src_id_type = server->id_type;
176   packetdata.dst_id = dst_id_data;
177   packetdata.dst_id_len = dst_id_len;
178   packetdata.dst_id_type = dst_id_type;
179   packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN + 
180     packetdata.src_id_len + dst_id_len;
181   packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen, block_len);
182
183   /* Prepare outgoing data buffer for packet sending */
184   silc_packet_send_prepare(sock, 
185                            SILC_PACKET_HEADER_LEN +
186                            packetdata.src_id_len + 
187                            packetdata.dst_id_len,
188                            packetdata.padlen,
189                            data_len);
190
191   SILC_LOG_DEBUG(("Putting data to outgoing buffer, len %d", data_len));
192
193   packetdata.buffer = sock->outbuf;
194
195   /* Put the data to the buffer */
196   if (data && data_len)
197     silc_buffer_put(sock->outbuf, data, data_len);
198
199   /* Create the outgoing packet */
200   silc_packet_assemble(&packetdata, cipher);
201
202   /* Encrypt the packet */
203   silc_packet_encrypt(cipher, hmac, sequence, sock->outbuf, sock->outbuf->len);
204
205   SILC_LOG_HEXDUMP(("Outgoing packet (%d), len %d", sequence, 
206                     sock->outbuf->len),
207                    sock->outbuf->data, sock->outbuf->len);
208
209   /* Now actually send the packet */
210   silc_server_packet_send_real(server, sock, force_send);
211
212   if (packetdata.src_id)
213     silc_free(packetdata.src_id);
214   if (packetdata.dst_id)
215     silc_free(packetdata.dst_id);
216 }
217
218 /* Assembles a new packet to be sent out to network. This doesn't actually
219    send the packet but creates the packet and fills the outgoing data
220    buffer and marks the packet ready to be sent to network. However, If 
221    argument force_send is TRUE the packet is sent immediately and not put 
222    to queue. Normal case is that the packet is not sent immediately. 
223    The source and destination information is sent as argument for this
224    function. */
225
226 void silc_server_packet_send_srcdest(SilcServer server,
227                                      SilcSocketConnection sock, 
228                                      SilcPacketType type, 
229                                      SilcPacketFlags flags,
230                                      void *src_id,
231                                      SilcIdType src_id_type,
232                                      void *dst_id,
233                                      SilcIdType dst_id_type,
234                                      unsigned char *data, 
235                                      uint32 data_len,
236                                      bool force_send)
237 {
238   SilcPacketContext packetdata;
239   SilcIDListData idata;
240   SilcCipher cipher = NULL;
241   SilcHmac hmac = NULL;
242   uint32 sequence = 0;
243   unsigned char *dst_id_data = NULL;
244   uint32 dst_id_len = 0;
245   unsigned char *src_id_data = NULL;
246   uint32 src_id_len = 0;
247   int block_len = 0;
248
249   SILC_LOG_DEBUG(("Sending packet, type %d", type));
250
251   /* Get data used in the packet sending, keys and stuff */
252   idata = (SilcIDListData)sock->user_data;
253
254   if (dst_id) {
255     dst_id_data = silc_id_id2str(dst_id, dst_id_type);
256     dst_id_len = silc_id_get_len(dst_id, dst_id_type);
257   }
258
259   if (src_id) {
260     src_id_data = silc_id_id2str(src_id, src_id_type);
261     src_id_len = silc_id_get_len(src_id, src_id_type);
262   }
263
264   if (idata) {
265     cipher = idata->send_key;
266     hmac = idata->hmac_send;
267     sequence = idata->psn_send++;
268     block_len = silc_cipher_get_block_len(cipher);
269   }
270
271   /* Set the packet context pointers */
272   packetdata.type = type;
273   packetdata.flags = flags;
274   packetdata.src_id = src_id_data;
275   packetdata.src_id_len = src_id_len;
276   packetdata.src_id_type = src_id_type;
277   packetdata.dst_id = dst_id_data;
278   packetdata.dst_id_len = dst_id_len;
279   packetdata.dst_id_type = dst_id_type;
280   packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN + 
281     packetdata.src_id_len + dst_id_len;
282   packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen, block_len);
283
284   /* Prepare outgoing data buffer for packet sending */
285   silc_packet_send_prepare(sock, 
286                            SILC_PACKET_HEADER_LEN +
287                            packetdata.src_id_len + 
288                            packetdata.dst_id_len,
289                            packetdata.padlen,
290                            data_len);
291
292   SILC_LOG_DEBUG(("Putting data to outgoing buffer, len %d", data_len));
293
294   packetdata.buffer = sock->outbuf;
295
296   /* Put the data to the buffer */
297   if (data && data_len)
298     silc_buffer_put(sock->outbuf, data, data_len);
299
300   /* Create the outgoing packet */
301   silc_packet_assemble(&packetdata, cipher);
302
303   /* Encrypt the packet */
304   silc_packet_encrypt(cipher, hmac, sequence, sock->outbuf, sock->outbuf->len);
305
306   SILC_LOG_HEXDUMP(("Outgoing packet (%d), len %d", sequence, 
307                     sock->outbuf->len),
308                    sock->outbuf->data, sock->outbuf->len);
309
310   /* Now actually send the packet */
311   silc_server_packet_send_real(server, sock, force_send);
312
313   if (packetdata.src_id)
314     silc_free(packetdata.src_id);
315   if (packetdata.dst_id)
316     silc_free(packetdata.dst_id);
317 }
318
319 /* Broadcast received packet to our primary route. This function is used
320    by router to further route received broadcast packet. It is expected
321    that the broadcast flag from the packet is checked before calling this
322    function. This does not test or set the broadcast flag. */
323
324 void silc_server_packet_broadcast(SilcServer server,
325                                   SilcSocketConnection sock,
326                                   SilcPacketContext *packet)
327 {
328   SilcBuffer buffer = packet->buffer;
329   SilcIDListData idata;
330   void *id;
331
332   SILC_LOG_DEBUG(("Broadcasting received broadcast packet"));
333
334   /* If the packet is originated from our primary route we are
335      not allowed to send the packet. */
336   id = silc_id_str2id(packet->src_id, packet->src_id_len, packet->src_id_type);
337   if (id && !SILC_ID_SERVER_COMPARE(id, server->router->id)) {
338     idata = (SilcIDListData)sock->user_data;
339
340     silc_buffer_push(buffer, buffer->data - buffer->head);
341     silc_packet_send_prepare(sock, 0, 0, buffer->len); 
342     silc_buffer_put(sock->outbuf, buffer->data, buffer->len);
343     silc_packet_encrypt(idata->send_key, idata->hmac_send, idata->psn_send++,
344                         sock->outbuf, sock->outbuf->len);
345
346     SILC_LOG_HEXDUMP(("Broadcasted packet (%d), len %d", idata->psn_send - 1,
347                       sock->outbuf->len),
348                      sock->outbuf->data, sock->outbuf->len);
349
350     /* Now actually send the packet */
351     silc_server_packet_send_real(server, sock, TRUE);
352     silc_free(id);
353     return;
354   }
355
356   SILC_LOG_DEBUG(("Will not broadcast to primary route since it is the "
357                   "original sender of this packet"));
358   silc_free(id);
359 }
360
361 /* Routes received packet to `sock'. This is used to route the packets that
362    router receives but are not destined to it. */
363
364 void silc_server_packet_route(SilcServer server,
365                               SilcSocketConnection sock,
366                               SilcPacketContext *packet)
367 {
368   SilcBuffer buffer = packet->buffer;
369   SilcIDListData idata;
370
371   SILC_LOG_DEBUG(("Routing received packet"));
372
373   idata = (SilcIDListData)sock->user_data;
374
375   silc_buffer_push(buffer, buffer->data - buffer->head);
376   silc_packet_send_prepare(sock, 0, 0, buffer->len); 
377   silc_buffer_put(sock->outbuf, buffer->data, buffer->len);
378   silc_packet_encrypt(idata->send_key, idata->hmac_send, idata->psn_send++,
379                       sock->outbuf, sock->outbuf->len);
380
381   SILC_LOG_HEXDUMP(("Routed packet (%d), len %d", idata->psn_send - 1, 
382                     sock->outbuf->len),
383                    sock->outbuf->data, sock->outbuf->len);
384
385   /* Now actually send the packet */
386   silc_server_packet_send_real(server, sock, TRUE);
387 }
388
389 /* This routine can be used to send a packet to table of clients provided
390    in `clients'. If `route' is FALSE the packet is routed only to local
391    clients (for server locally connected, and for router local cell). */
392
393 void silc_server_packet_send_clients(SilcServer server,
394                                      SilcClientEntry *clients,
395                                      uint32 clients_count,
396                                      SilcPacketType type, 
397                                      SilcPacketFlags flags,
398                                      bool route,
399                                      unsigned char *data, 
400                                      uint32 data_len,
401                                      bool force_send)
402 {
403   SilcSocketConnection sock = NULL;
404   SilcClientEntry client = NULL;
405   SilcServerEntry *routed = NULL;
406   uint32 routed_count = 0;
407   bool gone = FALSE;
408   int i, k;
409
410   SILC_LOG_DEBUG(("Sending packet to list of clients"));
411
412   /* Send to all clients in table */
413   for (i = 0; i < clients_count; i++) {
414     client = clients[i];
415
416     /* If client has router set it is not locally connected client and
417        we will route the message to the router set in the client. Though,
418        send locally connected server in all cases. */
419     if (server->server_type == SILC_ROUTER && client->router && 
420         ((!route && client->router->router == server->id_entry) || route)) {
421
422       /* Check if we have sent the packet to this route already */
423       for (k = 0; k < routed_count; k++)
424         if (routed[k] == client->router)
425           break;
426       if (k < routed_count)
427         continue;
428
429       /* Route only once to router */
430       sock = (SilcSocketConnection)client->router->connection;
431       if (sock->type == SILC_SOCKET_TYPE_ROUTER) {
432         if (gone)
433           continue;
434         gone = TRUE;
435       }
436
437       /* Send the packet */
438       silc_server_packet_send_dest(server, sock, type, flags,
439                                    client->router->id, SILC_ID_SERVER,
440                                    data, data_len, force_send);
441
442       /* Mark this route routed already */
443       routed = silc_realloc(routed, sizeof(*routed) * (routed_count + 1));
444       routed[routed_count++] = client->router;
445       continue;
446     }
447
448     if (client->router)
449       continue;
450
451     /* Send to locally connected client */
452     sock = (SilcSocketConnection)client->connection;
453     silc_server_packet_send_dest(server, sock, type, flags,
454                                  client->id, SILC_ID_CLIENT,
455                                  data, data_len, force_send);
456   }
457
458   silc_free(routed);
459 }
460
461 /* Internal routine to actually create the channel packet and send it
462    to network. This is common function in channel message sending. If
463    `channel_message' is TRUE this encrypts the message as it is strictly
464    a channel message. If FALSE normal encryption process is used. */
465
466 static void
467 silc_server_packet_send_to_channel_real(SilcServer server,
468                                         SilcSocketConnection sock,
469                                         SilcPacketContext *packet,
470                                         SilcCipher cipher,
471                                         SilcHmac hmac,
472                                         uint32 sequence,
473                                         unsigned char *data,
474                                         uint32 data_len,
475                                         bool channel_message,
476                                         bool force_send)
477 {
478   int block_len;
479
480   if (!sock)
481     return;
482
483   packet->truelen = data_len + SILC_PACKET_HEADER_LEN + 
484     packet->src_id_len + packet->dst_id_len;
485
486   block_len = cipher ? silc_cipher_get_block_len(cipher) : 0;
487   if (channel_message)
488     packet->padlen = SILC_PACKET_PADLEN((SILC_PACKET_HEADER_LEN +
489                                          packet->src_id_len +
490                                          packet->dst_id_len), block_len);
491   else
492     packet->padlen = SILC_PACKET_PADLEN(packet->truelen, block_len);
493
494   /* Prepare outgoing data buffer for packet sending */
495   silc_packet_send_prepare(sock, 
496                            SILC_PACKET_HEADER_LEN +
497                            packet->src_id_len + 
498                            packet->dst_id_len,
499                            packet->padlen,
500                            data_len);
501
502   packet->buffer = sock->outbuf;
503
504   /* Put the data to buffer, assemble and encrypt the packet. The packet
505      is encrypted with normal session key shared with the client, unless
506      the `channel_message' is TRUE. */
507   silc_buffer_put(sock->outbuf, data, data_len);
508   silc_packet_assemble(packet, cipher);
509   if (channel_message)
510     silc_packet_encrypt(cipher, hmac, sequence, sock->outbuf, 
511                         SILC_PACKET_HEADER_LEN + packet->src_id_len + 
512                         packet->dst_id_len + packet->padlen);
513   else
514     silc_packet_encrypt(cipher, hmac, sequence, sock->outbuf, 
515                         sock->outbuf->len);
516     
517   SILC_LOG_HEXDUMP(("Channel packet (%d), len %d", sequence, 
518                     sock->outbuf->len),
519                    sock->outbuf->data, sock->outbuf->len);
520
521   /* Now actually send the packet */
522   silc_server_packet_send_real(server, sock, force_send);
523 }
524
525 /* This routine is used by the server to send packets to channel. The 
526    packet sent with this function is distributed to all clients on
527    the channel. Usually this is used to send notify messages to the
528    channel, things like notify about new user joining to the channel. 
529    If `route' is FALSE then the packet is sent only locally and will not
530    be routed anywhere (for router locally means cell wide). If `sender'
531    is provided then the packet is not sent to that connection since it
532    originally came from it. If `send_to_clients' is FALSE then the
533    packet is not sent clients, only servers. */
534
535 void silc_server_packet_send_to_channel(SilcServer server,
536                                         SilcSocketConnection sender,
537                                         SilcChannelEntry channel,
538                                         SilcPacketType type,
539                                         bool route,
540                                         unsigned char *data,
541                                         uint32 data_len,
542                                         bool force_send)
543 {
544   SilcSocketConnection sock = NULL;
545   SilcPacketContext packetdata;
546   SilcClientEntry client = NULL;
547   SilcServerEntry *routed = NULL;
548   SilcChannelClientEntry chl;
549   SilcHashTableList htl;
550   SilcIDListData idata;
551   uint32 routed_count = 0;
552   bool gone = FALSE;
553   int k;
554
555   /* This doesn't send channel message packets */
556   assert(type != SILC_PACKET_CHANNEL_MESSAGE);
557   
558   SILC_LOG_DEBUG(("Sending packet to channel"));
559
560   /* Set the packet context pointers. */
561   packetdata.flags = 0;
562   packetdata.type = type;
563   packetdata.src_id = silc_id_id2str(server->id, SILC_ID_SERVER);
564   packetdata.src_id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
565   packetdata.src_id_type = SILC_ID_SERVER;
566   packetdata.dst_id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
567   packetdata.dst_id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
568   packetdata.dst_id_type = SILC_ID_CHANNEL;
569
570   /* If there are global users in the channel we will send the message
571      first to our router for further routing. */
572   if (route && server->server_type != SILC_ROUTER && !server->standalone &&
573       channel->global_users) {
574     SilcServerEntry router;
575
576     /* Get data used in packet header encryption, keys and stuff. */
577     router = server->router;
578     sock = (SilcSocketConnection)router->connection;
579     idata = (SilcIDListData)router;
580     
581     if (sock != sender) {
582       SILC_LOG_DEBUG(("Sending packet to router for routing"));
583       
584       silc_server_packet_send_to_channel_real(server, sock, &packetdata,
585                                               idata->send_key, 
586                                               idata->hmac_send, 
587                                               idata->psn_send++,
588                                               data, data_len, FALSE, 
589                                               force_send);
590     }
591   }
592
593   routed = silc_calloc(silc_hash_table_count(channel->user_list), 
594                        sizeof(*routed));
595
596   /* Send the message to clients on the channel's client list. */
597   silc_hash_table_list(channel->user_list, &htl);
598   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
599     client = chl->client;
600     if (!client)
601       continue;
602
603     /* If client has router set it is not locally connected client and
604        we will route the message to the router set in the client. Though,
605        send locally connected server in all cases. */
606     if (server->server_type == SILC_ROUTER && client->router && 
607         ((!route && client->router->router == server->id_entry) || route)) {
608
609       /* Check if we have sent the packet to this route already */
610       for (k = 0; k < routed_count; k++)
611         if (routed[k] == client->router)
612           break;
613       if (k < routed_count)
614         continue;
615
616       /* Get data used in packet header encryption, keys and stuff. */
617       sock = (SilcSocketConnection)client->router->connection;
618       idata = (SilcIDListData)client->router;
619
620       if (sender && sock == sender)
621         continue;
622
623       /* Route only once to router */
624       if (sock->type == SILC_SOCKET_TYPE_ROUTER) {
625         if (gone)
626           continue;
627         gone = TRUE;
628       }
629
630       /* Send the packet */
631       silc_server_packet_send_to_channel_real(server, sock, &packetdata,
632                                               idata->send_key, 
633                                               idata->hmac_send, 
634                                               idata->psn_send++,
635                                               data, data_len, FALSE, 
636                                               force_send);
637
638       /* Mark this route routed already */
639       routed[routed_count++] = client->router;
640       continue;
641     }
642
643     if (client->router)
644       continue;
645
646     /* Send to locally connected client */
647
648     /* Get data used in packet header encryption, keys and stuff. */
649     sock = (SilcSocketConnection)client->connection;
650     idata = (SilcIDListData)client;
651     
652     if (sender && sock == sender)
653       continue;
654
655     /* Send the packet */
656     silc_server_packet_send_to_channel_real(server, sock, &packetdata,
657                                             idata->send_key, 
658                                             idata->hmac_send, 
659                                             idata->psn_send++, 
660                                             data, data_len, FALSE, 
661                                             force_send);
662   }
663
664   silc_free(routed);
665   silc_free(packetdata.src_id);
666   silc_free(packetdata.dst_id);
667 }
668
669 /* This checks whether the relayed packet came from router. If it did
670    then we'll need to encrypt it with the channel key. This is called
671    from the silc_server_packet_relay_to_channel. */
672
673 static bool
674 silc_server_packet_relay_to_channel_encrypt(SilcServer server,
675                                             SilcSocketConnection sock,
676                                             SilcChannelEntry channel,
677                                             unsigned char *data,
678                                             unsigned int data_len)
679 {
680   /* If we are router and the packet came from router and private key
681      has not been set for the channel then we must encrypt the packet
682      as it was decrypted with the session key shared between us and the
683      router which sent it. This is so, because cells does not share the
684      same channel key. */
685   if (server->server_type == SILC_ROUTER &&
686       sock->type == SILC_SOCKET_TYPE_ROUTER &&
687       !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY) &&
688       channel->channel_key) {
689     SilcBuffer chp;
690     uint32 iv_len, i;
691     uint16 dlen, flags;
692
693     iv_len = silc_cipher_get_block_len(channel->channel_key);
694     if (channel->iv[0] == '\0')
695       for (i = 0; i < iv_len; i++) channel->iv[i] = 
696                                      silc_rng_get_byte(server->rng);
697     else
698       silc_hash_make(server->md5hash, channel->iv, iv_len, channel->iv);
699     
700     /* Encode new payload. This encrypts it also. */
701     SILC_GET16_MSB(flags, data);
702     SILC_GET16_MSB(dlen, data + 2);
703
704     if (dlen > data_len) {
705       SILC_LOG_WARNING(("Corrupted channel message, cannot relay it"));
706       return FALSE;
707     }
708
709     chp = silc_channel_message_payload_encode(flags, dlen, data + 4,
710                                               iv_len, channel->iv,
711                                               channel->channel_key,
712                                               channel->hmac);
713     memcpy(data, chp->data, chp->len);
714     silc_buffer_free(chp);
715   }
716
717   return TRUE;
718 }
719
720 /* This routine is explicitly used to relay messages to some channel.
721    Packets sent with this function we have received earlier and are
722    totally encrypted. This just sends the packet to all clients on
723    the channel. If the sender of the packet is someone on the channel 
724    the message will not be sent to that client. The SILC Packet header
725    is encrypted with the session key shared between us and the client.
726    MAC is also computed before encrypting the header. Rest of the
727    packet will be untouched. */
728
729 void silc_server_packet_relay_to_channel(SilcServer server,
730                                          SilcSocketConnection sender_sock,
731                                          SilcChannelEntry channel,
732                                          void *sender, 
733                                          SilcIdType sender_type,
734                                          void *sender_entry,
735                                          unsigned char *data,
736                                          uint32 data_len,
737                                          bool force_send)
738 {
739   bool found = FALSE;
740   SilcSocketConnection sock = NULL;
741   SilcPacketContext packetdata;
742   SilcClientEntry client = NULL;
743   SilcServerEntry *routed = NULL;
744   SilcChannelClientEntry chl;
745   uint32 routed_count = 0;
746   SilcIDListData idata;
747   SilcHashTableList htl;
748   bool gone = FALSE;
749   int k;
750
751   SILC_LOG_DEBUG(("Relaying packet to channel"));
752
753   /* This encrypts the packet, if needed. It will be encrypted if
754      it came from the router thus it needs to be encrypted with the
755      channel key. If the channel key does not exist, then we know we
756      don't have a single local user on the channel. */
757   if (!silc_server_packet_relay_to_channel_encrypt(server, sender_sock,
758                                                    channel, data,
759                                                    data_len))
760     return;
761
762   /* Set the packet context pointers. */
763   packetdata.flags = 0;
764   packetdata.type = SILC_PACKET_CHANNEL_MESSAGE;
765   packetdata.src_id = silc_id_id2str(sender, sender_type);
766   packetdata.src_id_len = silc_id_get_len(sender, sender_type);
767   packetdata.src_id_type = sender_type;
768   packetdata.dst_id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
769   packetdata.dst_id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
770   packetdata.dst_id_type = SILC_ID_CHANNEL;
771
772   /* If there are global users in the channel we will send the message
773      first to our router for further routing. */
774   if (server->server_type != SILC_ROUTER && !server->standalone &&
775       channel->global_users) {
776     SilcServerEntry router = server->router;
777
778     /* Check that the sender is not our router. */
779     if (sender_sock != (SilcSocketConnection)router->connection) {
780
781       /* Get data used in packet header encryption, keys and stuff. */
782       sock = (SilcSocketConnection)router->connection;
783       idata = (SilcIDListData)router;
784
785       SILC_LOG_DEBUG(("Sending channel message to router for routing"));
786
787       silc_server_packet_send_to_channel_real(server, sock, &packetdata,
788                                               idata->send_key, 
789                                               idata->hmac_send, 
790                                               idata->psn_send++, 
791                                               data, data_len, TRUE, 
792                                               force_send);
793     }
794   }
795
796   routed = silc_calloc(silc_hash_table_count(channel->user_list), 
797                        sizeof(*routed));
798
799   /* Mark that to the route the original sender if from is not routed */
800   if (sender_type == SILC_ID_CLIENT) {
801     client = (SilcClientEntry)sender_entry;
802     if (client->router) {
803       routed[routed_count++] = client->router;
804       SILC_LOG_DEBUG(("************* router %s", 
805                       silc_id_render(client->router->id, SILC_ID_SERVER)));
806     }
807   }
808
809   /* Send the message to clients on the channel's client list. */
810   silc_hash_table_list(channel->user_list, &htl);
811   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
812     client = chl->client;
813     if (!client)
814       continue;
815
816     /* Do not send to the sender */
817     if (!found && client == sender_entry) {
818       found = TRUE;
819       continue;
820     }
821
822     /* If the client has set router it means that it is not locally
823        connected client and we will route the packet further. */
824     if (server->server_type == SILC_ROUTER && client->router) {
825
826       /* Sender maybe server as well so we want to make sure that
827          we won't send the message to the server it came from. */
828       if (!found && SILC_ID_SERVER_COMPARE(client->router->id, sender)) {
829         found = TRUE;
830         routed[routed_count++] = client->router;
831         continue;
832       }
833
834       /* Check if we have sent the packet to this route already */
835       for (k = 0; k < routed_count; k++)
836         if (routed[k] == client->router)
837           break;
838       if (k < routed_count)
839         continue;
840         
841       /* Get data used in packet header encryption, keys and stuff. */
842       sock = (SilcSocketConnection)client->router->connection;
843       idata = (SilcIDListData)client->router;
844
845       /* Do not send to the sender. Check first whether the true
846          sender's router is same as this client's router. Also check
847          if the sender socket is the same as this client's router
848          socket. */
849       if (sender_entry &&
850           ((SilcClientEntry)sender_entry)->router == client->router)
851         continue;
852       if (sender_sock && sock == sender_sock)
853         continue;
854
855       SILC_LOG_DEBUG(("Relaying packet to client ID(%s) %s (%s)", 
856                       silc_id_render(client->id, SILC_ID_CLIENT),
857                       sock->hostname, sock->ip));
858
859       /* Mark this route routed already. */
860       routed[routed_count++] = client->router;
861         
862       /* If the remote connection is router then we'll decrypt the
863          channel message and re-encrypt it with the session key shared
864          between us and the remote router. This is done because the
865          channel keys are cell specific and we have different channel
866          key than the remote router has. */
867       if (sock->type == SILC_SOCKET_TYPE_ROUTER) {
868         if (gone)
869           continue;
870
871         SILC_LOG_DEBUG(("Remote is router, encrypt with session key"));
872         gone = TRUE;
873
874         /* If private key mode is not set then decrypt the packet
875            and re-encrypt it */
876         if (!(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
877           unsigned char *tmp = silc_calloc(data_len, sizeof(*data));
878           memcpy(tmp, data, data_len);
879
880           /* Decrypt the channel message (we don't check the MAC) */
881           if (channel->channel_key &&
882               !silc_channel_message_payload_decrypt(tmp, data_len, 
883                                                     channel->channel_key,
884                                                     NULL)) {
885             memset(tmp, 0, data_len);
886             silc_free(tmp);
887             continue;
888           }
889
890           /* Now re-encrypt and send it to the router */
891           silc_server_packet_send_srcdest(server, sock, 
892                                           SILC_PACKET_CHANNEL_MESSAGE, 0,
893                                           sender, sender_type,
894                                           channel->id, SILC_ID_CHANNEL,
895                                           tmp, data_len, force_send);
896
897           /* Free the copy of the channel message */
898           memset(tmp, 0, data_len);
899           silc_free(tmp);
900         } else {
901           /* Private key mode is set, we don't have the channel key, so
902              just re-encrypt the entire packet and send it to the router. */
903           silc_server_packet_send_srcdest(server, sock, 
904                                           SILC_PACKET_CHANNEL_MESSAGE, 0,
905                                           sender, sender_type,
906                                           channel->id, SILC_ID_CHANNEL,
907                                           data, data_len, force_send);
908         }
909         continue;
910       }
911
912       /* Send the packet (to normal server) */
913       silc_server_packet_send_to_channel_real(server, sock, &packetdata,
914                                               idata->send_key, 
915                                               idata->hmac_send, 
916                                               idata->psn_send++, 
917                                               data, data_len, TRUE, 
918                                               force_send);
919
920       continue;
921     }
922
923     if (client->router)
924       continue;
925
926     /* Get data used in packet header encryption, keys and stuff. */
927     sock = (SilcSocketConnection)client->connection;
928     idata = (SilcIDListData)client;
929
930     if (sender_sock && sock == sender_sock)
931       continue;
932
933     SILC_LOG_DEBUG(("Sending packet to client ID(%s) %s (%s)", 
934                     silc_id_render(client->id, SILC_ID_CLIENT),
935                     sock->hostname, sock->ip));
936
937     /* Send the packet */
938     silc_server_packet_send_to_channel_real(server, sock, &packetdata,
939                                             idata->send_key, 
940                                             idata->hmac_send, 
941                                             idata->psn_send++, 
942                                             data, data_len, TRUE, 
943                                             force_send);
944   }
945
946   silc_free(routed);
947   silc_free(packetdata.src_id);
948   silc_free(packetdata.dst_id);
949 }
950
951 /* This function is used to send packets strictly to all local clients
952    on a particular channel.  This is used for example to distribute new
953    channel key to all our locally connected clients on the channel. 
954    The packets are always encrypted with the session key shared between
955    the client, this means these are not _to the channel_ but _to the client_
956    on the channel. */
957
958 void silc_server_packet_send_local_channel(SilcServer server,
959                                            SilcChannelEntry channel,
960                                            SilcPacketType type,
961                                            SilcPacketFlags flags,
962                                            unsigned char *data,
963                                            uint32 data_len,
964                                            bool force_send)
965 {
966   SilcChannelClientEntry chl;
967   SilcHashTableList htl;
968   SilcSocketConnection sock = NULL;
969
970   SILC_LOG_DEBUG(("Start"));
971
972   /* Send the message to clients on the channel's client list. */
973   silc_hash_table_list(channel->user_list, &htl);
974   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
975     if (chl->client && !chl->client->router) {
976       sock = (SilcSocketConnection)chl->client->connection;
977
978       /* Send the packet to the client */
979       silc_server_packet_send_dest(server, sock, type, flags, chl->client->id,
980                                    SILC_ID_CLIENT, data, data_len,
981                                    force_send);
982     }
983   }
984 }
985
986 /* Routine used to send (relay, route) private messages to some destination.
987    If the private message key does not exist then the message is re-encrypted,
988    otherwise we just pass it along. This really is not used to send new
989    private messages (as server does not send them) but to relay received
990    private messages. */
991
992 void silc_server_send_private_message(SilcServer server,
993                                       SilcSocketConnection dst_sock,
994                                       SilcCipher cipher,
995                                       SilcHmac hmac,
996                                       uint32 sequence,
997                                       SilcPacketContext *packet)
998 {
999   SilcBuffer buffer = packet->buffer;
1000
1001   /* Re-encrypt and send if private messge key does not exist */
1002   if (!(packet->flags & SILC_PACKET_FLAG_PRIVMSG_KEY)) {
1003
1004     silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
1005                      + packet->dst_id_len + packet->padlen);
1006     silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
1007     silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
1008
1009     /* Re-encrypt packet */
1010     silc_packet_encrypt(cipher, hmac, sequence, dst_sock->outbuf, buffer->len);
1011
1012     /* Send the packet */
1013     silc_server_packet_send_real(server, dst_sock, FALSE);
1014
1015   } else {
1016     /* Key exist so encrypt just header and send it */
1017     silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
1018                      + packet->dst_id_len + packet->padlen);
1019     silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
1020     silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
1021
1022     /* Encrypt header */
1023     silc_packet_encrypt(cipher, hmac, sequence, dst_sock->outbuf, 
1024                         SILC_PACKET_HEADER_LEN + packet->src_id_len + 
1025                         packet->dst_id_len + packet->padlen);
1026
1027     silc_server_packet_send_real(server, dst_sock, FALSE);
1028   }
1029 }
1030
1031 /* Sends current motd to client */
1032
1033 void silc_server_send_motd(SilcServer server,
1034                            SilcSocketConnection sock)
1035 {
1036   char *motd;
1037   uint32 motd_len;
1038
1039   if (server->config && server->config->motd && 
1040       server->config->motd->motd_file) {
1041
1042     motd = silc_file_readfile(server->config->motd->motd_file, &motd_len);
1043     if (!motd)
1044       return;
1045
1046     silc_server_send_notify(server, sock, FALSE, SILC_NOTIFY_TYPE_MOTD, 1,
1047                             motd, motd_len);
1048     silc_free(motd);
1049   }
1050 }
1051
1052 /* Sends error message. Error messages may or may not have any 
1053    implications. */
1054
1055 void silc_server_send_error(SilcServer server,
1056                             SilcSocketConnection sock,
1057                             const char *fmt, ...)
1058 {
1059   va_list ap;
1060   unsigned char buf[4096];
1061
1062   memset(buf, 0, sizeof(buf));
1063   va_start(ap, fmt);
1064   vsprintf(buf, fmt, ap);
1065   va_end(ap);
1066
1067   silc_server_packet_send(server, sock, SILC_PACKET_ERROR, 0, 
1068                           buf, strlen(buf), FALSE);
1069 }
1070
1071 /* Sends notify message. If format is TRUE the variable arguments are
1072    formatted and the formatted string is sent as argument payload. If it is
1073    FALSE then each argument is sent as separate argument and their format
1074    in the argument list must be { argument data, argument length }. */
1075
1076 void silc_server_send_notify(SilcServer server,
1077                              SilcSocketConnection sock,
1078                              bool broadcast,
1079                              SilcNotifyType type,
1080                              uint32 argc, ...)
1081 {
1082   va_list ap;
1083   SilcBuffer packet;
1084
1085   va_start(ap, argc);
1086
1087   packet = silc_notify_payload_encode(type, argc, ap);
1088   silc_server_packet_send(server, sock, SILC_PACKET_NOTIFY, 
1089                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
1090                           packet->data, packet->len, FALSE);
1091
1092   /* Send to backup routers if this is being broadcasted to primary
1093      router. */
1094   if (server->router && server->router->connection &&
1095       sock == server->router->connection && broadcast)
1096     silc_server_backup_send(server, NULL, SILC_PACKET_NOTIFY, 0,
1097                             packet->data, packet->len, FALSE, TRUE);
1098
1099   silc_buffer_free(packet);
1100   va_end(ap);
1101 }
1102
1103 /* Sends notify message and gets the arguments from the `args' Argument
1104    Payloads. */
1105
1106 void silc_server_send_notify_args(SilcServer server,
1107                                   SilcSocketConnection sock,
1108                                   bool broadcast,
1109                                   SilcNotifyType type,
1110                                   uint32 argc,
1111                                   SilcBuffer args)
1112 {
1113   SilcBuffer packet;
1114
1115   packet = silc_notify_payload_encode_args(type, argc, args);
1116   silc_server_packet_send(server, sock, SILC_PACKET_NOTIFY, 
1117                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
1118                           packet->data, packet->len, FALSE);
1119   silc_buffer_free(packet);
1120 }
1121
1122 /* Send CHANNEL_CHANGE notify type. This tells the receiver to replace the
1123    `old_id' with the `new_id'. */
1124
1125 void silc_server_send_notify_channel_change(SilcServer server,
1126                                             SilcSocketConnection sock,
1127                                             bool broadcast,
1128                                             SilcChannelID *old_id,
1129                                             SilcChannelID *new_id)
1130 {
1131   SilcBuffer idp1, idp2;
1132
1133   idp1 = silc_id_payload_encode((void *)old_id, SILC_ID_CHANNEL);
1134   idp2 = silc_id_payload_encode((void *)new_id, SILC_ID_CHANNEL);
1135
1136   silc_server_send_notify(server, sock, broadcast,
1137                           SILC_NOTIFY_TYPE_CHANNEL_CHANGE,
1138                           2, idp1->data, idp1->len, idp2->data, idp2->len);
1139   silc_buffer_free(idp1);
1140   silc_buffer_free(idp2);
1141 }
1142
1143 /* Send NICK_CHANGE notify type. This tells the receiver to replace the
1144    `old_id' with the `new_id'. */
1145
1146 void silc_server_send_notify_nick_change(SilcServer server,
1147                                          SilcSocketConnection sock,
1148                                          bool broadcast,
1149                                          SilcClientID *old_id,
1150                                          SilcClientID *new_id)
1151 {
1152   SilcBuffer idp1, idp2;
1153
1154   idp1 = silc_id_payload_encode((void *)old_id, SILC_ID_CLIENT);
1155   idp2 = silc_id_payload_encode((void *)new_id, SILC_ID_CLIENT);
1156
1157   silc_server_send_notify(server, sock, broadcast, 
1158                           SILC_NOTIFY_TYPE_NICK_CHANGE,
1159                           2, idp1->data, idp1->len, idp2->data, idp2->len);
1160   silc_buffer_free(idp1);
1161   silc_buffer_free(idp2);
1162 }
1163
1164 /* Sends JOIN notify type. This tells that new client by `client_id' ID
1165    has joined to the `channel'. */
1166
1167 void silc_server_send_notify_join(SilcServer server,
1168                                   SilcSocketConnection sock,
1169                                   bool broadcast,
1170                                   SilcChannelEntry channel,
1171                                   SilcClientID *client_id)
1172 {
1173   SilcBuffer idp1, idp2;
1174
1175   idp1 = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1176   idp2 = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
1177   silc_server_send_notify(server, sock, broadcast, SILC_NOTIFY_TYPE_JOIN,
1178                           2, idp1->data, idp1->len,
1179                           idp2->data, idp2->len);
1180   silc_buffer_free(idp1);
1181   silc_buffer_free(idp2);
1182 }
1183
1184 /* Sends LEAVE notify type. This tells that `client_id' has left the
1185    `channel'. The Notify packet is always destined to the channel. */
1186
1187 void silc_server_send_notify_leave(SilcServer server,
1188                                    SilcSocketConnection sock,
1189                                    bool broadcast,
1190                                    SilcChannelEntry channel,
1191                                    SilcClientID *client_id)
1192 {
1193   SilcBuffer idp;
1194
1195   idp = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1196   silc_server_send_notify_dest(server, sock, broadcast, (void *)channel->id,
1197                                SILC_ID_CHANNEL, SILC_NOTIFY_TYPE_LEAVE,
1198                                1, idp->data, idp->len);
1199   silc_buffer_free(idp);
1200 }
1201
1202 /* Sends CMODE_CHANGE notify type. This tells that `client_id' changed the
1203    `channel' mode to `mode. The Notify packet is always destined to
1204    the channel. */
1205
1206 void silc_server_send_notify_cmode(SilcServer server,
1207                                    SilcSocketConnection sock,
1208                                    bool broadcast,
1209                                    SilcChannelEntry channel,
1210                                    uint32 mode_mask,
1211                                    void *id, SilcIdType id_type,
1212                                    char *cipher, char *hmac,
1213                                    char *passphrase)
1214 {
1215   SilcBuffer idp;
1216   unsigned char mode[4];
1217
1218   idp = silc_id_payload_encode((void *)id, id_type);
1219   SILC_PUT32_MSB(mode_mask, mode);
1220
1221   silc_server_send_notify_dest(server, sock, broadcast, (void *)channel->id,
1222                                SILC_ID_CHANNEL, SILC_NOTIFY_TYPE_CMODE_CHANGE,
1223                                5, idp->data, idp->len,
1224                                mode, 4,
1225                                cipher, cipher ? strlen(cipher) : 0,
1226                                hmac, hmac ? strlen(hmac) : 0,
1227                                passphrase, passphrase ? 
1228                                strlen(passphrase) : 0);
1229   silc_buffer_free(idp);
1230 }
1231
1232 /* Sends CUMODE_CHANGE notify type. This tells that `client_id' changed the
1233    `target' client's mode on `channel'. The notify packet is always
1234    destined to the channel. */
1235
1236 void silc_server_send_notify_cumode(SilcServer server,
1237                                     SilcSocketConnection sock,
1238                                     bool broadcast,
1239                                     SilcChannelEntry channel,
1240                                     uint32 mode_mask,
1241                                     void *id, SilcIdType id_type,
1242                                     SilcClientID *target)
1243 {
1244   SilcBuffer idp1, idp2;
1245   unsigned char mode[4];
1246
1247   idp1 = silc_id_payload_encode((void *)id, id_type);
1248   idp2 = silc_id_payload_encode((void *)target, SILC_ID_CLIENT);
1249   SILC_PUT32_MSB(mode_mask, mode);
1250
1251   silc_server_send_notify_dest(server, sock, broadcast, (void *)channel->id,
1252                                SILC_ID_CHANNEL, 
1253                                SILC_NOTIFY_TYPE_CUMODE_CHANGE, 3, 
1254                                idp1->data, idp1->len,
1255                                mode, 4,
1256                                idp2->data, idp2->len);
1257   silc_buffer_free(idp1);
1258   silc_buffer_free(idp2);
1259 }
1260
1261 /* Sends SIGNOFF notify type. This tells that `client_id' client has
1262    left SILC network. This function is used only between server and router
1263    traffic. This is not used to send the notify to the channel for
1264    client. The `message may be NULL. */
1265
1266 void silc_server_send_notify_signoff(SilcServer server,
1267                                      SilcSocketConnection sock,
1268                                      bool broadcast,
1269                                      SilcClientID *client_id,
1270                                      const char *message)
1271 {
1272   SilcBuffer idp;
1273
1274   idp = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1275   silc_server_send_notify(server, sock, broadcast,
1276                           SILC_NOTIFY_TYPE_SIGNOFF,
1277                           message ? 2 : 1, idp->data, idp->len,
1278                           message, message ? strlen(message): 0);
1279   silc_buffer_free(idp);
1280 }
1281
1282 /* Sends TOPIC_SET notify type. This tells that `id' changed
1283    the `channel's topic to `topic'. The Notify packet is always destined
1284    to the channel. This function is used to send the topic set notifies
1285    between routers. */
1286
1287 void silc_server_send_notify_topic_set(SilcServer server,
1288                                        SilcSocketConnection sock,
1289                                        bool broadcast,
1290                                        SilcChannelEntry channel,
1291                                        void *id, SilcIdType id_type,
1292                                        char *topic)
1293 {
1294   SilcBuffer idp;
1295
1296   idp = silc_id_payload_encode(id, id_type);
1297   silc_server_send_notify_dest(server, sock, broadcast,
1298                                (void *)channel->id, SILC_ID_CHANNEL,
1299                                SILC_NOTIFY_TYPE_TOPIC_SET,
1300                                topic ? 2 : 1, 
1301                                idp->data, idp->len, 
1302                                topic, topic ? strlen(topic) : 0);
1303   silc_buffer_free(idp);
1304 }
1305
1306 /* Send KICKED notify type. This tells that the `client_id' on `channel'
1307    was kicked off the channel.  The `comment' may indicate the reason
1308    for the kicking. This function is used only between server and router
1309    traffic. */
1310
1311 void silc_server_send_notify_kicked(SilcServer server,
1312                                     SilcSocketConnection sock,
1313                                     bool broadcast,
1314                                     SilcChannelEntry channel,
1315                                     SilcClientID *client_id,
1316                                     SilcClientID *kicker,
1317                                     char *comment)
1318 {
1319   SilcBuffer idp1;
1320   SilcBuffer idp2;
1321
1322   idp1 = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1323   idp2 = silc_id_payload_encode((void *)kicker, SILC_ID_CLIENT);
1324   silc_server_send_notify_dest(server, sock, broadcast, (void *)channel->id,
1325                                SILC_ID_CHANNEL, SILC_NOTIFY_TYPE_KICKED, 3,
1326                                idp1->data, idp1->len,
1327                                comment, comment ? strlen(comment) : 0,
1328                                idp2->data, idp2->len);
1329   silc_buffer_free(idp1);
1330   silc_buffer_free(idp2);
1331 }
1332
1333 /* Send KILLED notify type. This tells that the `client_id' client was
1334    killed from the network.  The `comment' may indicate the reason
1335    for the killing. */
1336
1337 void silc_server_send_notify_killed(SilcServer server,
1338                                     SilcSocketConnection sock,
1339                                     bool broadcast,
1340                                     SilcClientID *client_id,
1341                                     char *comment)
1342 {
1343   SilcBuffer idp;
1344
1345   idp = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1346   silc_server_send_notify_dest(server, sock, broadcast, (void *)client_id,
1347                                SILC_ID_CLIENT, SILC_NOTIFY_TYPE_KILLED,
1348                                comment ? 2 : 1, idp->data, idp->len,
1349                                comment, comment ? strlen(comment) : 0);
1350   silc_buffer_free(idp);
1351 }
1352
1353 /* Sends UMODE_CHANGE notify type. This tells that `client_id' client's
1354    user mode in the SILC Network was changed. This function is used to
1355    send the packet between routers as broadcast packet. */
1356
1357 void silc_server_send_notify_umode(SilcServer server,
1358                                    SilcSocketConnection sock,
1359                                    bool broadcast,
1360                                    SilcClientID *client_id,
1361                                    uint32 mode_mask)
1362 {
1363   SilcBuffer idp;
1364   unsigned char mode[4];
1365
1366   idp = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1367   SILC_PUT32_MSB(mode_mask, mode);
1368
1369   silc_server_send_notify(server, sock, broadcast,
1370                           SILC_NOTIFY_TYPE_UMODE_CHANGE, 2,
1371                           idp->data, idp->len, 
1372                           mode, 4);
1373   silc_buffer_free(idp);
1374 }
1375
1376 /* Sends BAN notify type. This tells that ban has been either `add'ed
1377    or `del'eted on the `channel. This function is used to send the packet
1378    between routers as broadcast packet. */
1379
1380 void silc_server_send_notify_ban(SilcServer server,
1381                                  SilcSocketConnection sock,
1382                                  bool broadcast,
1383                                  SilcChannelEntry channel,
1384                                  char *add, char *del)
1385 {
1386   SilcBuffer idp;
1387
1388   idp = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
1389   silc_server_send_notify(server, sock, broadcast,
1390                           SILC_NOTIFY_TYPE_BAN, 3,
1391                           idp->data, idp->len,
1392                           add, add ? strlen(add) : 0,
1393                           del, del ? strlen(del) : 0);
1394   silc_buffer_free(idp);
1395 }
1396
1397 /* Sends INVITE notify type. This tells that invite has been either `add'ed
1398    or `del'eted on the `channel.  The sender of the invite is the `client_id'.
1399    This function is used to send the packet between routers as broadcast
1400    packet. */
1401
1402 void silc_server_send_notify_invite(SilcServer server,
1403                                     SilcSocketConnection sock,
1404                                     bool broadcast,
1405                                     SilcChannelEntry channel,
1406                                     SilcClientID *client_id,
1407                                     char *add, char *del)
1408 {
1409   SilcBuffer idp, idp2;
1410
1411   idp = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
1412   idp2 = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1413   silc_server_send_notify(server, sock, broadcast,
1414                           SILC_NOTIFY_TYPE_INVITE, 5,
1415                           idp->data, idp->len,
1416                           channel->channel_name, strlen(channel->channel_name),
1417                           idp2->data, idp2->len,
1418                           add, add ? strlen(add) : 0,
1419                           del, del ? strlen(del) : 0);
1420   silc_buffer_free(idp);
1421   silc_buffer_free(idp2);
1422 }
1423
1424 /* Sends notify message destined to specific entity. */
1425
1426 void silc_server_send_notify_dest(SilcServer server,
1427                                   SilcSocketConnection sock,
1428                                   bool broadcast,
1429                                   void *dest_id,
1430                                   SilcIdType dest_id_type,
1431                                   SilcNotifyType type,
1432                                   uint32 argc, ...)
1433 {
1434   va_list ap;
1435   SilcBuffer packet;
1436
1437   va_start(ap, argc);
1438
1439   packet = silc_notify_payload_encode(type, argc, ap);
1440   silc_server_packet_send_dest(server, sock, SILC_PACKET_NOTIFY, 
1441                                broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
1442                                dest_id, dest_id_type,
1443                                packet->data, packet->len, FALSE);
1444   silc_buffer_free(packet);
1445   va_end(ap);
1446 }
1447
1448 /* Sends notify message to a channel. The notify message sent is 
1449    distributed to all clients on the channel. If `route_notify' is TRUE
1450    then the notify may be routed to primary route or to some other routers.
1451    If FALSE it is assured that the notify is sent only locally. If `sender'
1452    is provided then the packet is not sent to that connection since it
1453    originally came from it. */
1454
1455 void silc_server_send_notify_to_channel(SilcServer server,
1456                                         SilcSocketConnection sender,
1457                                         SilcChannelEntry channel,
1458                                         bool route_notify,
1459                                         SilcNotifyType type,
1460                                         uint32 argc, ...)
1461 {
1462   va_list ap;
1463   SilcBuffer packet;
1464
1465   va_start(ap, argc);
1466
1467   packet = silc_notify_payload_encode(type, argc, ap);
1468   silc_server_packet_send_to_channel(server, sender, channel, 
1469                                      SILC_PACKET_NOTIFY, route_notify,
1470                                      packet->data, packet->len, FALSE);
1471   silc_buffer_free(packet);
1472   va_end(ap);
1473 }
1474
1475 /* Send notify message to all channels the client has joined. It is quaranteed
1476    that the message is sent only once to a client (ie. if a client is joined
1477    on two same channel it will receive only one notify message). Also, this
1478    sends only to local clients (locally connected if we are server, and to
1479    local servers if we are router). If `sender' is provided the packet is
1480    not sent to that client at all. */
1481
1482 void silc_server_send_notify_on_channels(SilcServer server,
1483                                          SilcClientEntry sender,
1484                                          SilcClientEntry client,
1485                                          SilcNotifyType type,
1486                                          uint32 argc, ...)
1487 {
1488   int k;
1489   SilcSocketConnection sock = NULL;
1490   SilcPacketContext packetdata;
1491   SilcClientEntry c;
1492   SilcClientEntry *sent_clients = NULL;
1493   uint32 sent_clients_count = 0;
1494   SilcServerEntry *routed = NULL;
1495   uint32 routed_count = 0;
1496   SilcHashTableList htl, htl2;
1497   SilcChannelEntry channel;
1498   SilcChannelClientEntry chl, chl2;
1499   SilcIDListData idata;
1500   SilcBuffer packet;
1501   unsigned char *data;
1502   uint32 data_len;
1503   bool force_send = FALSE;
1504   va_list ap;
1505
1506   SILC_LOG_DEBUG(("Start"));
1507
1508   if (!silc_hash_table_count(client->channels))
1509     return;
1510
1511   va_start(ap, argc);
1512   packet = silc_notify_payload_encode(type, argc, ap);
1513   data = packet->data;
1514   data_len = packet->len;
1515
1516   /* Set the packet context pointers. */
1517   packetdata.flags = 0;
1518   packetdata.type = SILC_PACKET_NOTIFY;
1519   packetdata.src_id = silc_id_id2str(server->id, SILC_ID_SERVER);
1520   packetdata.src_id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1521   packetdata.src_id_type = SILC_ID_SERVER;
1522
1523   silc_hash_table_list(client->channels, &htl);
1524   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
1525     channel = chl->channel;
1526
1527     /* Send the message to all clients on the channel's client list. */
1528     silc_hash_table_list(channel->user_list, &htl2);
1529     while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
1530       c = chl2->client;
1531       
1532       if (sender && c == sender)
1533         continue;
1534
1535       /* Check if we have sent the packet to this client already */
1536       for (k = 0; k < sent_clients_count; k++)
1537         if (sent_clients[k] == c)
1538           break;
1539       if (k < sent_clients_count)
1540         continue;
1541
1542       /* If we are router and if this client has router set it is not
1543          locally connected client and we will route the message to the
1544          router set in the client. */
1545       if (c && c->router && server->server_type == SILC_ROUTER) {
1546         /* Check if we have sent the packet to this route already */
1547         for (k = 0; k < routed_count; k++)
1548           if (routed[k] == c->router)
1549             break;
1550         if (k < routed_count)
1551           continue;
1552         
1553         /* Get data used in packet header encryption, keys and stuff. */
1554         sock = (SilcSocketConnection)c->router->connection;
1555         idata = (SilcIDListData)c->router;
1556
1557         {
1558           SILC_LOG_DEBUG(("*****************"));
1559           SILC_LOG_DEBUG(("client->router->id %s",
1560                           silc_id_render(c->router->id, SILC_ID_SERVER)));
1561           SILC_LOG_DEBUG(("client->router->connection->user_data->id %s",
1562                           silc_id_render(((SilcServerEntry)sock->user_data)->id, SILC_ID_SERVER)));
1563         }
1564
1565         packetdata.dst_id = silc_id_id2str(c->router->id, SILC_ID_SERVER);
1566         packetdata.dst_id_len = silc_id_get_len(c->router->id, SILC_ID_SERVER);
1567         packetdata.dst_id_type = SILC_ID_SERVER;
1568
1569         /* Send the packet */
1570         silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1571                                                 idata->send_key, 
1572                                                 idata->hmac_send, 
1573                                                 idata->psn_send++, 
1574                                                 data, data_len, FALSE, 
1575                                                 force_send);
1576         
1577         silc_free(packetdata.dst_id);
1578
1579         /* We want to make sure that the packet is routed to same router
1580            only once. Mark this route as sent route. */
1581         routed = silc_realloc(routed, sizeof(*routed) * (routed_count + 1));
1582         routed[routed_count++] = c->router;
1583         continue;
1584       }
1585
1586       if (c && c->router)
1587         continue;
1588
1589       /* Send to locally connected client */
1590       if (c) {
1591         
1592         /* Get data used in packet header encryption, keys and stuff. */
1593         sock = (SilcSocketConnection)c->connection;
1594         idata = (SilcIDListData)c;
1595         
1596         packetdata.dst_id = silc_id_id2str(c->id, SILC_ID_CLIENT);
1597         packetdata.dst_id_len = silc_id_get_len(c->id, SILC_ID_CLIENT);
1598         packetdata.dst_id_type = SILC_ID_CLIENT;
1599
1600         /* Send the packet */
1601         silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1602                                                 idata->send_key, 
1603                                                 idata->hmac_send, 
1604                                                 idata->psn_send++, 
1605                                                 data, data_len, FALSE, 
1606                                                 force_send);
1607
1608         silc_free(packetdata.dst_id);
1609
1610         /* Make sure that we send the notify only once per client. */
1611         sent_clients = silc_realloc(sent_clients, sizeof(*sent_clients) * 
1612                                     (sent_clients_count + 1));
1613         sent_clients[sent_clients_count++] = c;
1614       }
1615     }
1616   }
1617
1618   silc_free(routed);
1619   silc_free(sent_clients);
1620   silc_free(packetdata.src_id);
1621   silc_buffer_free(packet);
1622   va_end(ap);
1623 }
1624
1625 /* Sends New ID Payload to remote end. The packet is used to distribute
1626    information about new registered clients, servers, channel etc. usually
1627    to routers so that they can keep these information up to date. 
1628    If the argument `broadcast' is TRUE then the packet is sent as
1629    broadcast packet. */
1630
1631 void silc_server_send_new_id(SilcServer server,
1632                              SilcSocketConnection sock,
1633                              bool broadcast,
1634                              void *id, SilcIdType id_type, 
1635                              uint32 id_len)
1636 {
1637   SilcBuffer idp;
1638
1639   SILC_LOG_DEBUG(("Start"));
1640
1641   idp = silc_id_payload_encode(id, id_type);
1642   silc_server_packet_send(server, sock, SILC_PACKET_NEW_ID, 
1643                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0, 
1644                           idp->data, idp->len, FALSE);
1645
1646   /* Send to backup routers if this is being broadcasted to primary
1647      router. */
1648   if (server->router && server->router->connection &&
1649       sock == server->router->connection && broadcast)
1650     silc_server_backup_send(server, NULL, SILC_PACKET_NEW_ID, 0,
1651                             idp->data, idp->len, FALSE, TRUE);
1652
1653   silc_buffer_free(idp);
1654 }
1655
1656 /* Send New Channel Payload to notify about newly created channel in the
1657    SILC network. Router uses this to notify other routers in the network 
1658    about new channel. This packet is broadcasted by router. */
1659
1660 void silc_server_send_new_channel(SilcServer server,
1661                                   SilcSocketConnection sock,
1662                                   bool broadcast,
1663                                   char *channel_name,
1664                                   void *channel_id, 
1665                                   uint32 channel_id_len,
1666                                   uint32 mode)
1667 {
1668   SilcBuffer packet;
1669   unsigned char *cid;
1670   uint32 name_len = strlen(channel_name);
1671
1672   SILC_LOG_DEBUG(("Start"));
1673
1674   cid = silc_id_id2str(channel_id, SILC_ID_CHANNEL);
1675   if (!cid)
1676     return;
1677
1678   /* Encode the channel payload */
1679   packet = silc_channel_payload_encode(channel_name, name_len,
1680                                        cid, channel_id_len, mode);
1681
1682   silc_server_packet_send(server, sock, SILC_PACKET_NEW_CHANNEL, 
1683                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0, 
1684                           packet->data, packet->len, FALSE);
1685
1686   /* Send to backup routers if this is being broadcasted to primary
1687      router. */
1688   if (server->server_type == SILC_ROUTER &&
1689       server->router && server->router->connection &&
1690       sock == server->router->connection && broadcast)
1691     silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
1692                             packet->data, packet->len, FALSE, TRUE);
1693
1694   silc_free(cid);
1695   silc_buffer_free(packet);
1696 }
1697
1698 /* Send Channel Key payload to distribute the new channel key. Normal server
1699    sends this to router when new client joins to existing channel. Router
1700    sends this to the local server who sent the join command in case where
1701    the channel did not exist yet. Both normal and router servers uses this
1702    also to send this to locally connected clients on the channel. This
1703    must not be broadcasted packet. Routers do not send this to each other. 
1704    If `sender is provided then the packet is not sent to that connection since
1705    it originally came from it. */
1706
1707 void silc_server_send_channel_key(SilcServer server,
1708                                   SilcSocketConnection sender,
1709                                   SilcChannelEntry channel,
1710                                   unsigned char route)
1711 {
1712   SilcBuffer packet;
1713   unsigned char *chid;
1714   uint32 tmp_len;
1715  
1716   SILC_LOG_DEBUG(("Sending key to channel %s", channel->channel_name));
1717  
1718   chid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
1719   if (!chid)
1720     return;
1721  
1722   /* Encode channel key packet */
1723   tmp_len = strlen(channel->channel_key->cipher->name);
1724   packet = silc_channel_key_payload_encode(silc_id_get_len(channel->id,
1725                                                            SILC_ID_CHANNEL),
1726                                            chid, tmp_len,
1727                                            channel->channel_key->cipher->name,
1728                                            channel->key_len / 8, channel->key);
1729   silc_server_packet_send_to_channel(server, sender, channel, 
1730                                      SILC_PACKET_CHANNEL_KEY,
1731                                      route, packet->data, packet->len, 
1732                                      FALSE);
1733   silc_buffer_free(packet);
1734   silc_free(chid);
1735 }
1736
1737 /* Generic function to send any command. The arguments must be sent already
1738    encoded into correct form in correct order. */
1739
1740 void silc_server_send_command(SilcServer server, 
1741                               SilcSocketConnection sock,
1742                               SilcCommand command, 
1743                               uint16 ident,
1744                               uint32 argc, ...)
1745 {
1746   SilcBuffer packet;
1747   va_list ap;
1748
1749   va_start(ap, argc);
1750
1751   packet = silc_command_payload_encode_vap(command, ident, argc, ap);
1752   silc_server_packet_send(server, sock, SILC_PACKET_COMMAND, 0,
1753                           packet->data, packet->len, TRUE);
1754   silc_buffer_free(packet);
1755   va_end(ap);
1756 }
1757
1758 /* Generic function to send any command reply. The arguments must be sent
1759    already encoded into correct form in correct order. */
1760
1761 void silc_server_send_command_reply(SilcServer server, 
1762                                     SilcSocketConnection sock,
1763                                     SilcCommand command, 
1764                                     SilcCommandStatus status,
1765                                     uint16 ident,
1766                                     uint32 argc, ...)
1767 {
1768   SilcBuffer packet;
1769   va_list ap;
1770
1771   va_start(ap, argc);
1772
1773   packet = silc_command_reply_payload_encode_vap(command, status, ident, 
1774                                                  argc, ap);
1775   silc_server_packet_send(server, sock, SILC_PACKET_COMMAND_REPLY, 0,
1776                           packet->data, packet->len, TRUE);
1777   silc_buffer_free(packet);
1778   va_end(ap);
1779 }
1780
1781 /* Generic function to send any command reply. The arguments must be sent
1782    already encoded into correct form in correct order. */
1783
1784 void silc_server_send_dest_command_reply(SilcServer server, 
1785                                          SilcSocketConnection sock,
1786                                          void *dst_id,
1787                                          SilcIdType dst_id_type,
1788                                          SilcCommand command, 
1789                                          SilcCommandStatus status,
1790                                          uint16 ident,
1791                                          uint32 argc, ...)
1792 {
1793   SilcBuffer packet;
1794   va_list ap;
1795
1796   va_start(ap, argc);
1797
1798   packet = silc_command_reply_payload_encode_vap(command, status, ident, 
1799                                                  argc, ap);
1800   silc_server_packet_send_dest(server, sock, SILC_PACKET_COMMAND_REPLY, 0,
1801                                dst_id, dst_id_type, packet->data, 
1802                                packet->len, TRUE);
1803   silc_buffer_free(packet);
1804   va_end(ap);
1805 }
1806
1807 /* Send the heartbeat packet. */
1808
1809 void silc_server_send_heartbeat(SilcServer server,
1810                                 SilcSocketConnection sock)
1811 {
1812   silc_server_packet_send(server, sock, SILC_PACKET_HEARTBEAT, 0,
1813                           NULL, 0, FALSE);
1814 }
1815
1816 /* Generic function to relay packet we've received. This is used to relay
1817    packets to a client but generally can be used to other purposes as well. */
1818
1819 void silc_server_relay_packet(SilcServer server,
1820                               SilcSocketConnection dst_sock,
1821                               SilcCipher cipher,
1822                               SilcHmac hmac,
1823                               uint32 sequence,
1824                               SilcPacketContext *packet,
1825                               bool force_send)
1826 {
1827   silc_buffer_push(packet->buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
1828                    + packet->dst_id_len + packet->padlen);
1829
1830   silc_packet_send_prepare(dst_sock, 0, 0, packet->buffer->len);
1831   silc_buffer_put(dst_sock->outbuf, packet->buffer->data, packet->buffer->len);
1832   
1833   /* Re-encrypt packet */
1834   silc_packet_encrypt(cipher, hmac, sequence, dst_sock->outbuf, 
1835                       packet->buffer->len);
1836   
1837   /* Send the packet */
1838   silc_server_packet_send_real(server, dst_sock, force_send);
1839
1840   silc_buffer_pull(packet->buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
1841                    + packet->dst_id_len + packet->padlen);
1842 }
1843
1844 /* Routine used to send the connection authentication packet. */
1845
1846 void silc_server_send_connection_auth_request(SilcServer server,
1847                                               SilcSocketConnection sock,
1848                                               uint16 conn_type,
1849                                               SilcAuthMethod auth_meth)
1850 {
1851   SilcBuffer packet;
1852
1853   packet = silc_buffer_alloc(4);
1854   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1855   silc_buffer_format(packet,
1856                      SILC_STR_UI_SHORT(conn_type),
1857                      SILC_STR_UI_SHORT(auth_meth),
1858                      SILC_STR_END);
1859
1860   silc_server_packet_send(server, sock, SILC_PACKET_CONNECTION_AUTH_REQUEST,
1861                           0, packet->data, packet->len, FALSE);
1862   silc_buffer_free(packet);
1863 }
1864
1865 /* Purge the outgoing packet queue to the network if there is data. This
1866    function can be used to empty the packet queue. It is guaranteed that
1867    after this function returns the outgoing data queue is empty. */
1868
1869 void silc_server_packet_queue_purge(SilcServer server,
1870                                     SilcSocketConnection sock)
1871 {
1872   if (sock && SILC_IS_OUTBUF_PENDING(sock) && 
1873       (SILC_IS_DISCONNECTED(sock) == FALSE)) {
1874     server->stat.packets_sent++;
1875
1876     if (sock->outbuf->data - sock->outbuf->head)
1877       silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1878
1879     silc_packet_send(sock, TRUE);
1880
1881     SILC_SET_CONNECTION_FOR_INPUT(server->schedule, sock->sock);
1882     SILC_UNSET_OUTBUF_PENDING(sock);
1883     silc_buffer_clear(sock->outbuf);
1884   }
1885 }