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