New silcconfig library and server parser. Merged silc-newconfig-final.patch.
[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_hash_table_list_reset(&htl);
665   silc_free(routed);
666   silc_free(packetdata.src_id);
667   silc_free(packetdata.dst_id);
668 }
669
670 /* This checks whether the relayed packet came from router. If it did
671    then we'll need to encrypt it with the channel key. This is called
672    from the silc_server_packet_relay_to_channel. */
673
674 static bool
675 silc_server_packet_relay_to_channel_encrypt(SilcServer server,
676                                             SilcSocketConnection sock,
677                                             SilcChannelEntry channel,
678                                             unsigned char *data,
679                                             unsigned int data_len)
680 {
681   /* If we are router and the packet came from router and private key
682      has not been set for the channel then we must encrypt the packet
683      as it was decrypted with the session key shared between us and the
684      router which sent it. This is so, because cells does not share the
685      same channel key. */
686   if (server->server_type == SILC_ROUTER &&
687       sock->type == SILC_SOCKET_TYPE_ROUTER &&
688       !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY) &&
689       channel->channel_key) {
690     SilcBuffer chp;
691     uint32 iv_len, i;
692     uint16 dlen, flags;
693
694     iv_len = silc_cipher_get_block_len(channel->channel_key);
695     if (channel->iv[0] == '\0')
696       for (i = 0; i < iv_len; i++) channel->iv[i] = 
697                                      silc_rng_get_byte(server->rng);
698     else
699       silc_hash_make(server->md5hash, channel->iv, iv_len, channel->iv);
700     
701     /* Encode new payload. This encrypts it also. */
702     SILC_GET16_MSB(flags, data);
703     SILC_GET16_MSB(dlen, data + 2);
704
705     if (dlen > data_len) {
706       SILC_LOG_WARNING(("Corrupted channel message, cannot relay it"));
707       return FALSE;
708     }
709
710     chp = silc_channel_message_payload_encode(flags, dlen, data + 4,
711                                               iv_len, channel->iv,
712                                               channel->channel_key,
713                                               channel->hmac);
714     memcpy(data, chp->data, chp->len);
715     silc_buffer_free(chp);
716   }
717
718   return TRUE;
719 }
720
721 /* This routine is explicitly used to relay messages to some channel.
722    Packets sent with this function we have received earlier and are
723    totally encrypted. This just sends the packet to all clients on
724    the channel. If the sender of the packet is someone on the channel 
725    the message will not be sent to that client. The SILC Packet header
726    is encrypted with the session key shared between us and the client.
727    MAC is also computed before encrypting the header. Rest of the
728    packet will be untouched. */
729
730 void silc_server_packet_relay_to_channel(SilcServer server,
731                                          SilcSocketConnection sender_sock,
732                                          SilcChannelEntry channel,
733                                          void *sender, 
734                                          SilcIdType sender_type,
735                                          void *sender_entry,
736                                          unsigned char *data,
737                                          uint32 data_len,
738                                          bool force_send)
739 {
740   bool found = FALSE;
741   SilcSocketConnection sock = NULL;
742   SilcPacketContext packetdata;
743   SilcClientEntry client = NULL;
744   SilcServerEntry *routed = NULL;
745   SilcChannelClientEntry chl;
746   uint32 routed_count = 0;
747   SilcIDListData idata;
748   SilcHashTableList htl;
749   bool gone = FALSE;
750   int k;
751
752   SILC_LOG_DEBUG(("Relaying packet to channel"));
753
754   /* This encrypts the packet, if needed. It will be encrypted if
755      it came from the router thus it needs to be encrypted with the
756      channel key. If the channel key does not exist, then we know we
757      don't have a single local user on the channel. */
758   if (!silc_server_packet_relay_to_channel_encrypt(server, sender_sock,
759                                                    channel, data,
760                                                    data_len))
761     return;
762
763   /* Set the packet context pointers. */
764   packetdata.flags = 0;
765   packetdata.type = SILC_PACKET_CHANNEL_MESSAGE;
766   packetdata.src_id = silc_id_id2str(sender, sender_type);
767   packetdata.src_id_len = silc_id_get_len(sender, sender_type);
768   packetdata.src_id_type = sender_type;
769   packetdata.dst_id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
770   packetdata.dst_id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
771   packetdata.dst_id_type = SILC_ID_CHANNEL;
772
773   /* If there are global users in the channel we will send the message
774      first to our router for further routing. */
775   if (server->server_type != SILC_ROUTER && !server->standalone &&
776       channel->global_users) {
777     SilcServerEntry router = server->router;
778
779     /* Check that the sender is not our router. */
780     if (sender_sock != (SilcSocketConnection)router->connection) {
781
782       /* Get data used in packet header encryption, keys and stuff. */
783       sock = (SilcSocketConnection)router->connection;
784       idata = (SilcIDListData)router;
785
786       SILC_LOG_DEBUG(("Sending channel message to router for routing"));
787
788       silc_server_packet_send_to_channel_real(server, sock, &packetdata,
789                                               idata->send_key, 
790                                               idata->hmac_send, 
791                                               idata->psn_send++, 
792                                               data, data_len, TRUE, 
793                                               force_send);
794     }
795   }
796
797   routed = silc_calloc(silc_hash_table_count(channel->user_list), 
798                        sizeof(*routed));
799
800   /* Mark that to the route the original sender if from is not routed */
801   if (sender_type == SILC_ID_CLIENT) {
802     client = (SilcClientEntry)sender_entry;
803     if (client->router) {
804       routed[routed_count++] = client->router;
805       SILC_LOG_DEBUG(("************* router %s", 
806                       silc_id_render(client->router->id, SILC_ID_SERVER)));
807     }
808   }
809
810   /* Send the message to clients on the channel's client list. */
811   silc_hash_table_list(channel->user_list, &htl);
812   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
813     client = chl->client;
814     if (!client)
815       continue;
816
817     /* Do not send to the sender */
818     if (!found && client == sender_entry) {
819       found = TRUE;
820       continue;
821     }
822
823     /* If the client has set router it means that it is not locally
824        connected client and we will route the packet further. */
825     if (server->server_type == SILC_ROUTER && client->router) {
826
827       /* Sender maybe server as well so we want to make sure that
828          we won't send the message to the server it came from. */
829       if (!found && SILC_ID_SERVER_COMPARE(client->router->id, sender)) {
830         found = TRUE;
831         routed[routed_count++] = client->router;
832         continue;
833       }
834
835       /* Check if we have sent the packet to this route already */
836       for (k = 0; k < routed_count; k++)
837         if (routed[k] == client->router)
838           break;
839       if (k < routed_count)
840         continue;
841         
842       /* Get data used in packet header encryption, keys and stuff. */
843       sock = (SilcSocketConnection)client->router->connection;
844       idata = (SilcIDListData)client->router;
845
846       /* Do not send to the sender. Check first whether the true
847          sender's router is same as this client's router. Also check
848          if the sender socket is the same as this client's router
849          socket. */
850       if (sender_entry &&
851           ((SilcClientEntry)sender_entry)->router == client->router)
852         continue;
853       if (sender_sock && sock == sender_sock)
854         continue;
855
856       SILC_LOG_DEBUG(("Relaying packet to client ID(%s) %s (%s)", 
857                       silc_id_render(client->id, SILC_ID_CLIENT),
858                       sock->hostname, sock->ip));
859
860       /* Mark this route routed already. */
861       routed[routed_count++] = client->router;
862         
863       /* If the remote connection is router then we'll decrypt the
864          channel message and re-encrypt it with the session key shared
865          between us and the remote router. This is done because the
866          channel keys are cell specific and we have different channel
867          key than the remote router has. */
868       if (sock->type == SILC_SOCKET_TYPE_ROUTER) {
869         if (gone)
870           continue;
871
872         SILC_LOG_DEBUG(("Remote is router, encrypt with session key"));
873         gone = TRUE;
874
875         /* If private key mode is not set then decrypt the packet
876            and re-encrypt it */
877         if (!(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
878           unsigned char *tmp = silc_calloc(data_len, sizeof(*data));
879           memcpy(tmp, data, data_len);
880
881           /* Decrypt the channel message (we don't check the MAC) */
882           if (channel->channel_key &&
883               !silc_channel_message_payload_decrypt(tmp, data_len, 
884                                                     channel->channel_key,
885                                                     NULL)) {
886             memset(tmp, 0, data_len);
887             silc_free(tmp);
888             continue;
889           }
890
891           /* Now re-encrypt and send it to the router */
892           silc_server_packet_send_srcdest(server, sock, 
893                                           SILC_PACKET_CHANNEL_MESSAGE, 0,
894                                           sender, sender_type,
895                                           channel->id, SILC_ID_CHANNEL,
896                                           tmp, data_len, force_send);
897
898           /* Free the copy of the channel message */
899           memset(tmp, 0, data_len);
900           silc_free(tmp);
901         } else {
902           /* Private key mode is set, we don't have the channel key, so
903              just re-encrypt the entire packet and send it to the router. */
904           silc_server_packet_send_srcdest(server, sock, 
905                                           SILC_PACKET_CHANNEL_MESSAGE, 0,
906                                           sender, sender_type,
907                                           channel->id, SILC_ID_CHANNEL,
908                                           data, data_len, force_send);
909         }
910         continue;
911       }
912
913       /* Send the packet (to normal server) */
914       silc_server_packet_send_to_channel_real(server, sock, &packetdata,
915                                               idata->send_key, 
916                                               idata->hmac_send, 
917                                               idata->psn_send++, 
918                                               data, data_len, TRUE, 
919                                               force_send);
920
921       continue;
922     }
923
924     if (client->router)
925       continue;
926
927     /* Get data used in packet header encryption, keys and stuff. */
928     sock = (SilcSocketConnection)client->connection;
929     idata = (SilcIDListData)client;
930
931     if (sender_sock && sock == sender_sock)
932       continue;
933
934     SILC_LOG_DEBUG(("Sending packet to client ID(%s) %s (%s)", 
935                     silc_id_render(client->id, SILC_ID_CLIENT),
936                     sock->hostname, sock->ip));
937
938     /* Send the packet */
939     silc_server_packet_send_to_channel_real(server, sock, &packetdata,
940                                             idata->send_key, 
941                                             idata->hmac_send, 
942                                             idata->psn_send++, 
943                                             data, data_len, TRUE, 
944                                             force_send);
945   }
946
947   silc_hash_table_list_reset(&htl);
948   silc_free(routed);
949   silc_free(packetdata.src_id);
950   silc_free(packetdata.dst_id);
951 }
952
953 /* This function is used to send packets strictly to all local clients
954    on a particular channel.  This is used for example to distribute new
955    channel key to all our locally connected clients on the channel. 
956    The packets are always encrypted with the session key shared between
957    the client, this means these are not _to the channel_ but _to the client_
958    on the channel. */
959
960 void silc_server_packet_send_local_channel(SilcServer server,
961                                            SilcChannelEntry channel,
962                                            SilcPacketType type,
963                                            SilcPacketFlags flags,
964                                            unsigned char *data,
965                                            uint32 data_len,
966                                            bool force_send)
967 {
968   SilcChannelClientEntry chl;
969   SilcHashTableList htl;
970   SilcSocketConnection sock = NULL;
971
972   SILC_LOG_DEBUG(("Start"));
973
974   /* Send the message to clients on the channel's client list. */
975   silc_hash_table_list(channel->user_list, &htl);
976   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
977     if (chl->client && !chl->client->router) {
978       sock = (SilcSocketConnection)chl->client->connection;
979
980       /* Send the packet to the client */
981       silc_server_packet_send_dest(server, sock, type, flags, chl->client->id,
982                                    SILC_ID_CLIENT, data, data_len,
983                                    force_send);
984     }
985   }
986   silc_hash_table_list_reset(&htl);
987 }
988
989 /* Routine used to send (relay, route) private messages to some destination.
990    If the private message key does not exist then the message is re-encrypted,
991    otherwise we just pass it along. This really is not used to send new
992    private messages (as server does not send them) but to relay received
993    private messages. */
994
995 void silc_server_send_private_message(SilcServer server,
996                                       SilcSocketConnection dst_sock,
997                                       SilcCipher cipher,
998                                       SilcHmac hmac,
999                                       uint32 sequence,
1000                                       SilcPacketContext *packet)
1001 {
1002   SilcBuffer buffer = packet->buffer;
1003
1004   /* Re-encrypt and send if private messge key does not exist */
1005   if (!(packet->flags & SILC_PACKET_FLAG_PRIVMSG_KEY)) {
1006
1007     silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
1008                      + packet->dst_id_len + packet->padlen);
1009     silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
1010     silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
1011
1012     /* Re-encrypt packet */
1013     silc_packet_encrypt(cipher, hmac, sequence, dst_sock->outbuf, buffer->len);
1014
1015     /* Send the packet */
1016     silc_server_packet_send_real(server, dst_sock, FALSE);
1017
1018   } else {
1019     /* Key exist so encrypt just header and send it */
1020     silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
1021                      + packet->dst_id_len + packet->padlen);
1022     silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
1023     silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
1024
1025     /* Encrypt header */
1026     silc_packet_encrypt(cipher, hmac, sequence, dst_sock->outbuf, 
1027                         SILC_PACKET_HEADER_LEN + packet->src_id_len + 
1028                         packet->dst_id_len + packet->padlen);
1029
1030     silc_server_packet_send_real(server, dst_sock, FALSE);
1031   }
1032 }
1033
1034 /* Sends current motd to client */
1035
1036 void silc_server_send_motd(SilcServer server,
1037                            SilcSocketConnection sock)
1038 {
1039   char *motd, *motd_file = NULL;
1040   uint32 motd_len;
1041
1042   if (server->config)
1043     motd_file = server->config->server_info->motd_file;
1044
1045   if (motd_file) {
1046     motd = silc_file_readfile(motd_file, &motd_len);
1047     if (!motd)
1048       return;
1049
1050     silc_server_send_notify(server, sock, FALSE, SILC_NOTIFY_TYPE_MOTD, 1,
1051                             motd, motd_len);
1052     silc_free(motd);
1053   }
1054 }
1055
1056 /* Sends error message. Error messages may or may not have any 
1057    implications. */
1058
1059 void silc_server_send_error(SilcServer server,
1060                             SilcSocketConnection sock,
1061                             const char *fmt, ...)
1062 {
1063   va_list ap;
1064   unsigned char buf[4096];
1065
1066   memset(buf, 0, sizeof(buf));
1067   va_start(ap, fmt);
1068   vsprintf(buf, fmt, ap);
1069   va_end(ap);
1070
1071   silc_server_packet_send(server, sock, SILC_PACKET_ERROR, 0, 
1072                           buf, strlen(buf), FALSE);
1073 }
1074
1075 /* Sends notify message. If format is TRUE the variable arguments are
1076    formatted and the formatted string is sent as argument payload. If it is
1077    FALSE then each argument is sent as separate argument and their format
1078    in the argument list must be { argument data, argument length }. */
1079
1080 void silc_server_send_notify(SilcServer server,
1081                              SilcSocketConnection sock,
1082                              bool broadcast,
1083                              SilcNotifyType type,
1084                              uint32 argc, ...)
1085 {
1086   va_list ap;
1087   SilcBuffer packet;
1088
1089   va_start(ap, argc);
1090
1091   packet = silc_notify_payload_encode(type, argc, ap);
1092   silc_server_packet_send(server, sock, SILC_PACKET_NOTIFY, 
1093                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
1094                           packet->data, packet->len, FALSE);
1095
1096   /* Send to backup routers if this is being broadcasted to primary
1097      router. */
1098   if (server->router && server->router->connection &&
1099       sock == server->router->connection && broadcast)
1100     silc_server_backup_send(server, NULL, SILC_PACKET_NOTIFY, 0,
1101                             packet->data, packet->len, FALSE, TRUE);
1102
1103   silc_buffer_free(packet);
1104   va_end(ap);
1105 }
1106
1107 /* Sends notify message and gets the arguments from the `args' Argument
1108    Payloads. */
1109
1110 void silc_server_send_notify_args(SilcServer server,
1111                                   SilcSocketConnection sock,
1112                                   bool broadcast,
1113                                   SilcNotifyType type,
1114                                   uint32 argc,
1115                                   SilcBuffer args)
1116 {
1117   SilcBuffer packet;
1118
1119   packet = silc_notify_payload_encode_args(type, argc, args);
1120   silc_server_packet_send(server, sock, SILC_PACKET_NOTIFY, 
1121                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
1122                           packet->data, packet->len, FALSE);
1123   silc_buffer_free(packet);
1124 }
1125
1126 /* Send CHANNEL_CHANGE notify type. This tells the receiver to replace the
1127    `old_id' with the `new_id'. */
1128
1129 void silc_server_send_notify_channel_change(SilcServer server,
1130                                             SilcSocketConnection sock,
1131                                             bool broadcast,
1132                                             SilcChannelID *old_id,
1133                                             SilcChannelID *new_id)
1134 {
1135   SilcBuffer idp1, idp2;
1136
1137   idp1 = silc_id_payload_encode((void *)old_id, SILC_ID_CHANNEL);
1138   idp2 = silc_id_payload_encode((void *)new_id, SILC_ID_CHANNEL);
1139
1140   silc_server_send_notify(server, sock, broadcast,
1141                           SILC_NOTIFY_TYPE_CHANNEL_CHANGE,
1142                           2, idp1->data, idp1->len, idp2->data, idp2->len);
1143   silc_buffer_free(idp1);
1144   silc_buffer_free(idp2);
1145 }
1146
1147 /* Send NICK_CHANGE notify type. This tells the receiver to replace the
1148    `old_id' with the `new_id'. */
1149
1150 void silc_server_send_notify_nick_change(SilcServer server,
1151                                          SilcSocketConnection sock,
1152                                          bool broadcast,
1153                                          SilcClientID *old_id,
1154                                          SilcClientID *new_id)
1155 {
1156   SilcBuffer idp1, idp2;
1157
1158   idp1 = silc_id_payload_encode((void *)old_id, SILC_ID_CLIENT);
1159   idp2 = silc_id_payload_encode((void *)new_id, SILC_ID_CLIENT);
1160
1161   silc_server_send_notify(server, sock, broadcast, 
1162                           SILC_NOTIFY_TYPE_NICK_CHANGE,
1163                           2, idp1->data, idp1->len, idp2->data, idp2->len);
1164   silc_buffer_free(idp1);
1165   silc_buffer_free(idp2);
1166 }
1167
1168 /* Sends JOIN notify type. This tells that new client by `client_id' ID
1169    has joined to the `channel'. */
1170
1171 void silc_server_send_notify_join(SilcServer server,
1172                                   SilcSocketConnection sock,
1173                                   bool broadcast,
1174                                   SilcChannelEntry channel,
1175                                   SilcClientID *client_id)
1176 {
1177   SilcBuffer idp1, idp2;
1178
1179   idp1 = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1180   idp2 = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
1181   silc_server_send_notify(server, sock, broadcast, SILC_NOTIFY_TYPE_JOIN,
1182                           2, idp1->data, idp1->len,
1183                           idp2->data, idp2->len);
1184   silc_buffer_free(idp1);
1185   silc_buffer_free(idp2);
1186 }
1187
1188 /* Sends LEAVE notify type. This tells that `client_id' has left the
1189    `channel'. The Notify packet is always destined to the channel. */
1190
1191 void silc_server_send_notify_leave(SilcServer server,
1192                                    SilcSocketConnection sock,
1193                                    bool broadcast,
1194                                    SilcChannelEntry channel,
1195                                    SilcClientID *client_id)
1196 {
1197   SilcBuffer idp;
1198
1199   idp = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1200   silc_server_send_notify_dest(server, sock, broadcast, (void *)channel->id,
1201                                SILC_ID_CHANNEL, SILC_NOTIFY_TYPE_LEAVE,
1202                                1, idp->data, idp->len);
1203   silc_buffer_free(idp);
1204 }
1205
1206 /* Sends CMODE_CHANGE notify type. This tells that `client_id' changed the
1207    `channel' mode to `mode. The Notify packet is always destined to
1208    the channel. */
1209
1210 void silc_server_send_notify_cmode(SilcServer server,
1211                                    SilcSocketConnection sock,
1212                                    bool broadcast,
1213                                    SilcChannelEntry channel,
1214                                    uint32 mode_mask,
1215                                    void *id, SilcIdType id_type,
1216                                    char *cipher, char *hmac,
1217                                    char *passphrase)
1218 {
1219   SilcBuffer idp;
1220   unsigned char mode[4];
1221
1222   idp = silc_id_payload_encode((void *)id, id_type);
1223   SILC_PUT32_MSB(mode_mask, mode);
1224
1225   silc_server_send_notify_dest(server, sock, broadcast, (void *)channel->id,
1226                                SILC_ID_CHANNEL, SILC_NOTIFY_TYPE_CMODE_CHANGE,
1227                                5, idp->data, idp->len,
1228                                mode, 4,
1229                                cipher, cipher ? strlen(cipher) : 0,
1230                                hmac, hmac ? strlen(hmac) : 0,
1231                                passphrase, passphrase ? 
1232                                strlen(passphrase) : 0);
1233   silc_buffer_free(idp);
1234 }
1235
1236 /* Sends CUMODE_CHANGE notify type. This tells that `client_id' changed the
1237    `target' client's mode on `channel'. The notify packet is always
1238    destined to the channel. */
1239
1240 void silc_server_send_notify_cumode(SilcServer server,
1241                                     SilcSocketConnection sock,
1242                                     bool broadcast,
1243                                     SilcChannelEntry channel,
1244                                     uint32 mode_mask,
1245                                     void *id, SilcIdType id_type,
1246                                     SilcClientID *target)
1247 {
1248   SilcBuffer idp1, idp2;
1249   unsigned char mode[4];
1250
1251   idp1 = silc_id_payload_encode((void *)id, id_type);
1252   idp2 = silc_id_payload_encode((void *)target, SILC_ID_CLIENT);
1253   SILC_PUT32_MSB(mode_mask, mode);
1254
1255   silc_server_send_notify_dest(server, sock, broadcast, (void *)channel->id,
1256                                SILC_ID_CHANNEL, 
1257                                SILC_NOTIFY_TYPE_CUMODE_CHANGE, 3, 
1258                                idp1->data, idp1->len,
1259                                mode, 4,
1260                                idp2->data, idp2->len);
1261   silc_buffer_free(idp1);
1262   silc_buffer_free(idp2);
1263 }
1264
1265 /* Sends SIGNOFF notify type. This tells that `client_id' client has
1266    left SILC network. This function is used only between server and router
1267    traffic. This is not used to send the notify to the channel for
1268    client. The `message may be NULL. */
1269
1270 void silc_server_send_notify_signoff(SilcServer server,
1271                                      SilcSocketConnection sock,
1272                                      bool broadcast,
1273                                      SilcClientID *client_id,
1274                                      const char *message)
1275 {
1276   SilcBuffer idp;
1277
1278   idp = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1279   silc_server_send_notify(server, sock, broadcast,
1280                           SILC_NOTIFY_TYPE_SIGNOFF,
1281                           message ? 2 : 1, idp->data, idp->len,
1282                           message, message ? strlen(message): 0);
1283   silc_buffer_free(idp);
1284 }
1285
1286 /* Sends TOPIC_SET notify type. This tells that `id' changed
1287    the `channel's topic to `topic'. The Notify packet is always destined
1288    to the channel. This function is used to send the topic set notifies
1289    between routers. */
1290
1291 void silc_server_send_notify_topic_set(SilcServer server,
1292                                        SilcSocketConnection sock,
1293                                        bool broadcast,
1294                                        SilcChannelEntry channel,
1295                                        void *id, SilcIdType id_type,
1296                                        char *topic)
1297 {
1298   SilcBuffer idp;
1299
1300   idp = silc_id_payload_encode(id, id_type);
1301   silc_server_send_notify_dest(server, sock, broadcast,
1302                                (void *)channel->id, SILC_ID_CHANNEL,
1303                                SILC_NOTIFY_TYPE_TOPIC_SET,
1304                                topic ? 2 : 1, 
1305                                idp->data, idp->len, 
1306                                topic, topic ? strlen(topic) : 0);
1307   silc_buffer_free(idp);
1308 }
1309
1310 /* Send KICKED notify type. This tells that the `client_id' on `channel'
1311    was kicked off the channel.  The `comment' may indicate the reason
1312    for the kicking. This function is used only between server and router
1313    traffic. */
1314
1315 void silc_server_send_notify_kicked(SilcServer server,
1316                                     SilcSocketConnection sock,
1317                                     bool broadcast,
1318                                     SilcChannelEntry channel,
1319                                     SilcClientID *client_id,
1320                                     SilcClientID *kicker,
1321                                     char *comment)
1322 {
1323   SilcBuffer idp1;
1324   SilcBuffer idp2;
1325
1326   idp1 = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1327   idp2 = silc_id_payload_encode((void *)kicker, SILC_ID_CLIENT);
1328   silc_server_send_notify_dest(server, sock, broadcast, (void *)channel->id,
1329                                SILC_ID_CHANNEL, SILC_NOTIFY_TYPE_KICKED, 3,
1330                                idp1->data, idp1->len,
1331                                comment, comment ? strlen(comment) : 0,
1332                                idp2->data, idp2->len);
1333   silc_buffer_free(idp1);
1334   silc_buffer_free(idp2);
1335 }
1336
1337 /* Send KILLED notify type. This tells that the `client_id' client was
1338    killed from the network.  The `comment' may indicate the reason
1339    for the killing. */
1340
1341 void silc_server_send_notify_killed(SilcServer server,
1342                                     SilcSocketConnection sock,
1343                                     bool broadcast,
1344                                     SilcClientID *client_id,
1345                                     char *comment)
1346 {
1347   SilcBuffer idp;
1348
1349   idp = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1350   silc_server_send_notify_dest(server, sock, broadcast, (void *)client_id,
1351                                SILC_ID_CLIENT, SILC_NOTIFY_TYPE_KILLED,
1352                                comment ? 2 : 1, idp->data, idp->len,
1353                                comment, comment ? strlen(comment) : 0);
1354   silc_buffer_free(idp);
1355 }
1356
1357 /* Sends UMODE_CHANGE notify type. This tells that `client_id' client's
1358    user mode in the SILC Network was changed. This function is used to
1359    send the packet between routers as broadcast packet. */
1360
1361 void silc_server_send_notify_umode(SilcServer server,
1362                                    SilcSocketConnection sock,
1363                                    bool broadcast,
1364                                    SilcClientID *client_id,
1365                                    uint32 mode_mask)
1366 {
1367   SilcBuffer idp;
1368   unsigned char mode[4];
1369
1370   idp = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1371   SILC_PUT32_MSB(mode_mask, mode);
1372
1373   silc_server_send_notify(server, sock, broadcast,
1374                           SILC_NOTIFY_TYPE_UMODE_CHANGE, 2,
1375                           idp->data, idp->len, 
1376                           mode, 4);
1377   silc_buffer_free(idp);
1378 }
1379
1380 /* Sends BAN notify type. This tells that ban has been either `add'ed
1381    or `del'eted on the `channel. This function is used to send the packet
1382    between routers as broadcast packet. */
1383
1384 void silc_server_send_notify_ban(SilcServer server,
1385                                  SilcSocketConnection sock,
1386                                  bool broadcast,
1387                                  SilcChannelEntry channel,
1388                                  char *add, char *del)
1389 {
1390   SilcBuffer idp;
1391
1392   idp = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
1393   silc_server_send_notify(server, sock, broadcast,
1394                           SILC_NOTIFY_TYPE_BAN, 3,
1395                           idp->data, idp->len,
1396                           add, add ? strlen(add) : 0,
1397                           del, del ? strlen(del) : 0);
1398   silc_buffer_free(idp);
1399 }
1400
1401 /* Sends INVITE notify type. This tells that invite has been either `add'ed
1402    or `del'eted on the `channel.  The sender of the invite is the `client_id'.
1403    This function is used to send the packet between routers as broadcast
1404    packet. */
1405
1406 void silc_server_send_notify_invite(SilcServer server,
1407                                     SilcSocketConnection sock,
1408                                     bool broadcast,
1409                                     SilcChannelEntry channel,
1410                                     SilcClientID *client_id,
1411                                     char *add, char *del)
1412 {
1413   SilcBuffer idp, idp2;
1414
1415   idp = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
1416   idp2 = silc_id_payload_encode((void *)client_id, SILC_ID_CLIENT);
1417   silc_server_send_notify(server, sock, broadcast,
1418                           SILC_NOTIFY_TYPE_INVITE, 5,
1419                           idp->data, idp->len,
1420                           channel->channel_name, strlen(channel->channel_name),
1421                           idp2->data, idp2->len,
1422                           add, add ? strlen(add) : 0,
1423                           del, del ? strlen(del) : 0);
1424   silc_buffer_free(idp);
1425   silc_buffer_free(idp2);
1426 }
1427
1428 /* Sends notify message destined to specific entity. */
1429
1430 void silc_server_send_notify_dest(SilcServer server,
1431                                   SilcSocketConnection sock,
1432                                   bool broadcast,
1433                                   void *dest_id,
1434                                   SilcIdType dest_id_type,
1435                                   SilcNotifyType type,
1436                                   uint32 argc, ...)
1437 {
1438   va_list ap;
1439   SilcBuffer packet;
1440
1441   va_start(ap, argc);
1442
1443   packet = silc_notify_payload_encode(type, argc, ap);
1444   silc_server_packet_send_dest(server, sock, SILC_PACKET_NOTIFY, 
1445                                broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
1446                                dest_id, dest_id_type,
1447                                packet->data, packet->len, FALSE);
1448   silc_buffer_free(packet);
1449   va_end(ap);
1450 }
1451
1452 /* Sends notify message to a channel. The notify message sent is 
1453    distributed to all clients on the channel. If `route_notify' is TRUE
1454    then the notify may be routed to primary route or to some other routers.
1455    If FALSE it is assured that the notify is sent only locally. If `sender'
1456    is provided then the packet is not sent to that connection since it
1457    originally came from it. */
1458
1459 void silc_server_send_notify_to_channel(SilcServer server,
1460                                         SilcSocketConnection sender,
1461                                         SilcChannelEntry channel,
1462                                         bool route_notify,
1463                                         SilcNotifyType type,
1464                                         uint32 argc, ...)
1465 {
1466   va_list ap;
1467   SilcBuffer packet;
1468
1469   va_start(ap, argc);
1470
1471   packet = silc_notify_payload_encode(type, argc, ap);
1472   silc_server_packet_send_to_channel(server, sender, channel, 
1473                                      SILC_PACKET_NOTIFY, route_notify,
1474                                      packet->data, packet->len, FALSE);
1475   silc_buffer_free(packet);
1476   va_end(ap);
1477 }
1478
1479 /* Send notify message to all channels the client has joined. It is quaranteed
1480    that the message is sent only once to a client (ie. if a client is joined
1481    on two same channel it will receive only one notify message). Also, this
1482    sends only to local clients (locally connected if we are server, and to
1483    local servers if we are router). If `sender' is provided the packet is
1484    not sent to that client at all. */
1485
1486 void silc_server_send_notify_on_channels(SilcServer server,
1487                                          SilcClientEntry sender,
1488                                          SilcClientEntry client,
1489                                          SilcNotifyType type,
1490                                          uint32 argc, ...)
1491 {
1492   int k;
1493   SilcSocketConnection sock = NULL;
1494   SilcPacketContext packetdata;
1495   SilcClientEntry c;
1496   SilcClientEntry *sent_clients = NULL;
1497   uint32 sent_clients_count = 0;
1498   SilcServerEntry *routed = NULL;
1499   uint32 routed_count = 0;
1500   SilcHashTableList htl, htl2;
1501   SilcChannelEntry channel;
1502   SilcChannelClientEntry chl, chl2;
1503   SilcIDListData idata;
1504   SilcBuffer packet;
1505   unsigned char *data;
1506   uint32 data_len;
1507   bool force_send = FALSE;
1508   va_list ap;
1509
1510   SILC_LOG_DEBUG(("Start"));
1511
1512   if (!silc_hash_table_count(client->channels))
1513     return;
1514
1515   va_start(ap, argc);
1516   packet = silc_notify_payload_encode(type, argc, ap);
1517   data = packet->data;
1518   data_len = packet->len;
1519
1520   /* Set the packet context pointers. */
1521   packetdata.flags = 0;
1522   packetdata.type = SILC_PACKET_NOTIFY;
1523   packetdata.src_id = silc_id_id2str(server->id, SILC_ID_SERVER);
1524   packetdata.src_id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1525   packetdata.src_id_type = SILC_ID_SERVER;
1526
1527   silc_hash_table_list(client->channels, &htl);
1528   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
1529     channel = chl->channel;
1530
1531     /* Send the message to all clients on the channel's client list. */
1532     silc_hash_table_list(channel->user_list, &htl2);
1533     while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
1534       c = chl2->client;
1535       
1536       if (sender && c == sender)
1537         continue;
1538
1539       /* Check if we have sent the packet to this client already */
1540       for (k = 0; k < sent_clients_count; k++)
1541         if (sent_clients[k] == c)
1542           break;
1543       if (k < sent_clients_count)
1544         continue;
1545
1546       /* If we are router and if this client has router set it is not
1547          locally connected client and we will route the message to the
1548          router set in the client. */
1549       if (c && c->router && server->server_type == SILC_ROUTER) {
1550         /* Check if we have sent the packet to this route already */
1551         for (k = 0; k < routed_count; k++)
1552           if (routed[k] == c->router)
1553             break;
1554         if (k < routed_count)
1555           continue;
1556         
1557         /* Get data used in packet header encryption, keys and stuff. */
1558         sock = (SilcSocketConnection)c->router->connection;
1559         idata = (SilcIDListData)c->router;
1560
1561         {
1562           SILC_LOG_DEBUG(("*****************"));
1563           SILC_LOG_DEBUG(("client->router->id %s",
1564                           silc_id_render(c->router->id, SILC_ID_SERVER)));
1565           SILC_LOG_DEBUG(("client->router->connection->user_data->id %s",
1566                           silc_id_render(((SilcServerEntry)sock->user_data)->id, SILC_ID_SERVER)));
1567         }
1568
1569         packetdata.dst_id = silc_id_id2str(c->router->id, SILC_ID_SERVER);
1570         packetdata.dst_id_len = silc_id_get_len(c->router->id, SILC_ID_SERVER);
1571         packetdata.dst_id_type = SILC_ID_SERVER;
1572
1573         /* Send the packet */
1574         silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1575                                                 idata->send_key, 
1576                                                 idata->hmac_send, 
1577                                                 idata->psn_send++, 
1578                                                 data, data_len, FALSE, 
1579                                                 force_send);
1580         
1581         silc_free(packetdata.dst_id);
1582
1583         /* We want to make sure that the packet is routed to same router
1584            only once. Mark this route as sent route. */
1585         routed = silc_realloc(routed, sizeof(*routed) * (routed_count + 1));
1586         routed[routed_count++] = c->router;
1587         continue;
1588       }
1589
1590       if (c && c->router)
1591         continue;
1592
1593       /* Send to locally connected client */
1594       if (c) {
1595         
1596         /* Get data used in packet header encryption, keys and stuff. */
1597         sock = (SilcSocketConnection)c->connection;
1598         idata = (SilcIDListData)c;
1599         
1600         packetdata.dst_id = silc_id_id2str(c->id, SILC_ID_CLIENT);
1601         packetdata.dst_id_len = silc_id_get_len(c->id, SILC_ID_CLIENT);
1602         packetdata.dst_id_type = SILC_ID_CLIENT;
1603
1604         /* Send the packet */
1605         silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1606                                                 idata->send_key, 
1607                                                 idata->hmac_send, 
1608                                                 idata->psn_send++, 
1609                                                 data, data_len, FALSE, 
1610                                                 force_send);
1611
1612         silc_free(packetdata.dst_id);
1613
1614         /* Make sure that we send the notify only once per client. */
1615         sent_clients = silc_realloc(sent_clients, sizeof(*sent_clients) * 
1616                                     (sent_clients_count + 1));
1617         sent_clients[sent_clients_count++] = c;
1618       }
1619     }
1620     silc_hash_table_list_reset(&htl2);
1621   }
1622
1623   silc_hash_table_list_reset(&htl);
1624   silc_free(routed);
1625   silc_free(sent_clients);
1626   silc_free(packetdata.src_id);
1627   silc_buffer_free(packet);
1628   va_end(ap);
1629 }
1630
1631 /* Sends New ID Payload to remote end. The packet is used to distribute
1632    information about new registered clients, servers, channel etc. usually
1633    to routers so that they can keep these information up to date. 
1634    If the argument `broadcast' is TRUE then the packet is sent as
1635    broadcast packet. */
1636
1637 void silc_server_send_new_id(SilcServer server,
1638                              SilcSocketConnection sock,
1639                              bool broadcast,
1640                              void *id, SilcIdType id_type, 
1641                              uint32 id_len)
1642 {
1643   SilcBuffer idp;
1644
1645   SILC_LOG_DEBUG(("Start"));
1646
1647   idp = silc_id_payload_encode(id, id_type);
1648   silc_server_packet_send(server, sock, SILC_PACKET_NEW_ID, 
1649                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0, 
1650                           idp->data, idp->len, FALSE);
1651
1652   /* Send to backup routers if this is being broadcasted to primary
1653      router. */
1654   if (server->router && server->router->connection &&
1655       sock == server->router->connection && broadcast)
1656     silc_server_backup_send(server, NULL, SILC_PACKET_NEW_ID, 0,
1657                             idp->data, idp->len, FALSE, TRUE);
1658
1659   silc_buffer_free(idp);
1660 }
1661
1662 /* Send New Channel Payload to notify about newly created channel in the
1663    SILC network. Router uses this to notify other routers in the network 
1664    about new channel. This packet is broadcasted by router. */
1665
1666 void silc_server_send_new_channel(SilcServer server,
1667                                   SilcSocketConnection sock,
1668                                   bool broadcast,
1669                                   char *channel_name,
1670                                   void *channel_id, 
1671                                   uint32 channel_id_len,
1672                                   uint32 mode)
1673 {
1674   SilcBuffer packet;
1675   unsigned char *cid;
1676   uint32 name_len = strlen(channel_name);
1677
1678   SILC_LOG_DEBUG(("Start"));
1679
1680   cid = silc_id_id2str(channel_id, SILC_ID_CHANNEL);
1681   if (!cid)
1682     return;
1683
1684   /* Encode the channel payload */
1685   packet = silc_channel_payload_encode(channel_name, name_len,
1686                                        cid, channel_id_len, mode);
1687
1688   silc_server_packet_send(server, sock, SILC_PACKET_NEW_CHANNEL, 
1689                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0, 
1690                           packet->data, packet->len, FALSE);
1691
1692   /* Send to backup routers if this is being broadcasted to primary
1693      router. */
1694   if (server->server_type == SILC_ROUTER &&
1695       server->router && server->router->connection &&
1696       sock == server->router->connection && broadcast)
1697     silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
1698                             packet->data, packet->len, FALSE, TRUE);
1699
1700   silc_free(cid);
1701   silc_buffer_free(packet);
1702 }
1703
1704 /* Send Channel Key payload to distribute the new channel key. Normal server
1705    sends this to router when new client joins to existing channel. Router
1706    sends this to the local server who sent the join command in case where
1707    the channel did not exist yet. Both normal and router servers uses this
1708    also to send this to locally connected clients on the channel. This
1709    must not be broadcasted packet. Routers do not send this to each other. 
1710    If `sender is provided then the packet is not sent to that connection since
1711    it originally came from it. */
1712
1713 void silc_server_send_channel_key(SilcServer server,
1714                                   SilcSocketConnection sender,
1715                                   SilcChannelEntry channel,
1716                                   unsigned char route)
1717 {
1718   SilcBuffer packet;
1719   unsigned char *chid;
1720   uint32 tmp_len;
1721  
1722   SILC_LOG_DEBUG(("Sending key to channel %s", channel->channel_name));
1723  
1724   chid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
1725   if (!chid)
1726     return;
1727  
1728   /* Encode channel key packet */
1729   tmp_len = strlen(channel->channel_key->cipher->name);
1730   packet = silc_channel_key_payload_encode(silc_id_get_len(channel->id,
1731                                                            SILC_ID_CHANNEL),
1732                                            chid, tmp_len,
1733                                            channel->channel_key->cipher->name,
1734                                            channel->key_len / 8, channel->key);
1735   silc_server_packet_send_to_channel(server, sender, channel, 
1736                                      SILC_PACKET_CHANNEL_KEY,
1737                                      route, packet->data, packet->len, 
1738                                      FALSE);
1739   silc_buffer_free(packet);
1740   silc_free(chid);
1741 }
1742
1743 /* Generic function to send any command. The arguments must be sent already
1744    encoded into correct form in correct order. */
1745
1746 void silc_server_send_command(SilcServer server, 
1747                               SilcSocketConnection sock,
1748                               SilcCommand command, 
1749                               uint16 ident,
1750                               uint32 argc, ...)
1751 {
1752   SilcBuffer packet;
1753   va_list ap;
1754
1755   va_start(ap, argc);
1756
1757   packet = silc_command_payload_encode_vap(command, ident, argc, ap);
1758   silc_server_packet_send(server, sock, SILC_PACKET_COMMAND, 0,
1759                           packet->data, packet->len, TRUE);
1760   silc_buffer_free(packet);
1761   va_end(ap);
1762 }
1763
1764 /* Generic function to send any command reply. The arguments must be sent
1765    already encoded into correct form in correct order. */
1766
1767 void silc_server_send_command_reply(SilcServer server, 
1768                                     SilcSocketConnection sock,
1769                                     SilcCommand command, 
1770                                     SilcCommandStatus status,
1771                                     uint16 ident,
1772                                     uint32 argc, ...)
1773 {
1774   SilcBuffer packet;
1775   va_list ap;
1776
1777   va_start(ap, argc);
1778
1779   packet = silc_command_reply_payload_encode_vap(command, status, ident, 
1780                                                  argc, ap);
1781   silc_server_packet_send(server, sock, SILC_PACKET_COMMAND_REPLY, 0,
1782                           packet->data, packet->len, TRUE);
1783   silc_buffer_free(packet);
1784   va_end(ap);
1785 }
1786
1787 /* Generic function to send any command reply. The arguments must be sent
1788    already encoded into correct form in correct order. */
1789
1790 void silc_server_send_dest_command_reply(SilcServer server, 
1791                                          SilcSocketConnection sock,
1792                                          void *dst_id,
1793                                          SilcIdType dst_id_type,
1794                                          SilcCommand command, 
1795                                          SilcCommandStatus status,
1796                                          uint16 ident,
1797                                          uint32 argc, ...)
1798 {
1799   SilcBuffer packet;
1800   va_list ap;
1801
1802   va_start(ap, argc);
1803
1804   packet = silc_command_reply_payload_encode_vap(command, status, ident, 
1805                                                  argc, ap);
1806   silc_server_packet_send_dest(server, sock, SILC_PACKET_COMMAND_REPLY, 0,
1807                                dst_id, dst_id_type, packet->data, 
1808                                packet->len, TRUE);
1809   silc_buffer_free(packet);
1810   va_end(ap);
1811 }
1812
1813 /* Send the heartbeat packet. */
1814
1815 void silc_server_send_heartbeat(SilcServer server,
1816                                 SilcSocketConnection sock)
1817 {
1818   silc_server_packet_send(server, sock, SILC_PACKET_HEARTBEAT, 0,
1819                           NULL, 0, FALSE);
1820 }
1821
1822 /* Generic function to relay packet we've received. This is used to relay
1823    packets to a client but generally can be used to other purposes as well. */
1824
1825 void silc_server_relay_packet(SilcServer server,
1826                               SilcSocketConnection dst_sock,
1827                               SilcCipher cipher,
1828                               SilcHmac hmac,
1829                               uint32 sequence,
1830                               SilcPacketContext *packet,
1831                               bool force_send)
1832 {
1833   silc_buffer_push(packet->buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
1834                    + packet->dst_id_len + packet->padlen);
1835
1836   silc_packet_send_prepare(dst_sock, 0, 0, packet->buffer->len);
1837   silc_buffer_put(dst_sock->outbuf, packet->buffer->data, packet->buffer->len);
1838   
1839   /* Re-encrypt packet */
1840   silc_packet_encrypt(cipher, hmac, sequence, dst_sock->outbuf, 
1841                       packet->buffer->len);
1842   
1843   /* Send the packet */
1844   silc_server_packet_send_real(server, dst_sock, force_send);
1845
1846   silc_buffer_pull(packet->buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
1847                    + packet->dst_id_len + packet->padlen);
1848 }
1849
1850 /* Routine used to send the connection authentication packet. */
1851
1852 void silc_server_send_connection_auth_request(SilcServer server,
1853                                               SilcSocketConnection sock,
1854                                               uint16 conn_type,
1855                                               SilcAuthMethod auth_meth)
1856 {
1857   SilcBuffer packet;
1858
1859   packet = silc_buffer_alloc(4);
1860   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1861   silc_buffer_format(packet,
1862                      SILC_STR_UI_SHORT(conn_type),
1863                      SILC_STR_UI_SHORT(auth_meth),
1864                      SILC_STR_END);
1865
1866   silc_server_packet_send(server, sock, SILC_PACKET_CONNECTION_AUTH_REQUEST,
1867                           0, packet->data, packet->len, FALSE);
1868   silc_buffer_free(packet);
1869 }
1870
1871 /* Purge the outgoing packet queue to the network if there is data. This
1872    function can be used to empty the packet queue. It is guaranteed that
1873    after this function returns the outgoing data queue is empty. */
1874
1875 void silc_server_packet_queue_purge(SilcServer server,
1876                                     SilcSocketConnection sock)
1877 {
1878   if (sock && SILC_IS_OUTBUF_PENDING(sock) && 
1879       (SILC_IS_DISCONNECTED(sock) == FALSE)) {
1880     server->stat.packets_sent++;
1881
1882     if (sock->outbuf->data - sock->outbuf->head)
1883       silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1884
1885     silc_packet_send(sock, TRUE);
1886
1887     SILC_SET_CONNECTION_FOR_INPUT(server->schedule, sock->sock);
1888     SILC_UNSET_OUTBUF_PENDING(sock);
1889     silc_buffer_clear(sock->outbuf);
1890   }
1891 }