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