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