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