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