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