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