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