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