More SILC Server 1.1 porting. Added HTTP statistics access.
[silc.git] / apps / silcd / server.c
1 /*
2
3   server.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 1997 - 2005, 2007 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 #include "serverincludes.h"
21 #include "server_internal.h"
22
23 /************************* Types and definitions ****************************/
24
25 SILC_TASK_CALLBACK(silc_server_get_stats);
26 SILC_TASK_CALLBACK(silc_server_connect_router);
27 SILC_TASK_CALLBACK(silc_server_do_rekey);
28 SILC_TASK_CALLBACK(silc_server_purge_expired_clients);
29 static void silc_server_accept_new_connection(SilcNetStatus status,
30                                               SilcStream stream,
31                                               void *context);
32 static void silc_server_packet_parse_type(SilcServer server,
33                                           SilcPacketStream sock,
34                                           SilcPacket packet);
35 static void silc_server_rekey(SilcServer server, SilcPacketStream sock,
36                               SilcPacket packet);
37
38
39 /************************ Static utility functions **************************/
40
41 /* SKE public key verification callback */
42
43 static void
44 silc_server_verify_key(SilcSKE ske,
45                        SilcPublicKey public_key,
46                        void *context,
47                        SilcSKEVerifyCbCompletion completion,
48                        void *completion_context)
49 {
50   SilcPacketStream sock = context;
51   SilcUnknownEntry entry = silc_packet_get_context(sock);
52
53   SILC_LOG_DEBUG(("Verifying public key"));
54
55   if (silc_pkcs_get_type(public_key) != SILC_SKE_PK_TYPE_SILC) {
56     SILC_LOG_WARNING(("We don't support %s (%s) port %d public key type %d",
57                       entry->hostname, entry->ip, entry->port,
58                       silc_pkcs_get_type(public_key)));
59     completion(ske, SILC_SKE_STATUS_UNSUPPORTED_PUBLIC_KEY,
60                completion_context);
61     return;
62   }
63
64   /* We accept all keys without explicit verification */
65   completion(ske, SILC_SKE_STATUS_OK, completion_context);
66 }
67
68
69 /************************ Packet engine callbacks ***************************/
70
71 /* Packet engine callback to receive a packet */
72
73 static SilcBool silc_server_packet_receive(SilcPacketEngine engine,
74                                            SilcPacketStream stream,
75                                            SilcPacket packet,
76                                            void *callback_context,
77                                            void *stream_context)
78 {
79   SilcServer server = callback_context;
80   SilcIDListData idata = stream_context;
81
82   /* Packets we do not handle */
83   switch (packet->type) {
84   case SILC_PACKET_HEARTBEAT:
85   case SILC_PACKET_SUCCESS:
86   case SILC_PACKET_FAILURE:
87   case SILC_PACKET_REJECT:
88   case SILC_PACKET_KEY_EXCHANGE:
89   case SILC_PACKET_KEY_EXCHANGE_1:
90   case SILC_PACKET_KEY_EXCHANGE_2:
91   case SILC_PACKET_REKEY_DONE:
92   case SILC_PACKET_CONNECTION_AUTH:
93     return FALSE;
94     break;
95   }
96
97   /* Only specific packets can come without source ID present. */
98   if ((!packet->src_id ||
99        !(idata->status & SILC_IDLIST_STATUS_REGISTERED)) &&
100       packet->type != SILC_PACKET_NEW_CLIENT &&
101       packet->type != SILC_PACKET_NEW_SERVER &&
102       packet->type != SILC_PACKET_CONNECTION_AUTH_REQUEST &&
103       packet->type != SILC_PACKET_DISCONNECT)
104     return FALSE;
105
106   /* NEW_CLIENT and NEW_SERVER are accepted only without source ID
107      and for unregistered connection. */
108   if (packet->src_id && (packet->type == SILC_PACKET_NEW_CLIENT ||
109                          packet->type == SILC_PACKET_NEW_SERVER) &&
110       (idata->status & SILC_IDLIST_STATUS_REGISTERED))
111     return FALSE;
112
113   /* Ignore packets from disabled connection */
114   if (idata->status & SILC_IDLIST_STATUS_DISABLED &&
115       packet->type != SILC_PACKET_HEARTBEAT &&
116       packet->type != SILC_PACKET_RESUME_ROUTER &&
117       packet->type != SILC_PACKET_REKEY)
118     return FALSE;
119
120   /* Check that the the current client ID is same as in the client's packet. */
121   if (idata->conn_type == SILC_CONN_CLIENT) {
122     SilcClientEntry client = (SilcClientEntry)silc_packet_get_context(stream);
123     SilcClientID client_id;
124
125     if (client->id && packet->src_id &&
126         silc_id_str2id(packet->src_id, packet->src_id_len,
127                        packet->src_id_type, &client_id, sizeof(client_id))) {
128       if (!SILC_ID_CLIENT_COMPARE(client->id, &client_id)) {
129         SILC_LOG_DEBUG(("Packet source is not same as sender"));
130         return FALSE;
131       }
132     }
133   }
134
135   if (server->server_type == SILC_ROUTER) {
136     /* Route the packet if it is not destined to us. Other ID types but
137        server are handled separately after processing them. */
138     if (packet->dst_id &&
139         !(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
140         packet->dst_id_type == SILC_ID_SERVER &&
141         idata->conn_type != SILC_CONN_CLIENT &&
142         memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
143       SilcPacketStream conn;
144       SilcServerID server_id;
145
146       silc_id_str2id(packet->dst_id, packet->dst_id_len, packet->dst_id_type,
147                      &server_id, sizeof(server_id));
148
149       conn = silc_server_route_get(server, &server_id, SILC_ID_SERVER);
150       if (!conn) {
151         SILC_LOG_WARNING(("Packet to unknown server ID %s, dropped (no route)",
152                           silc_id_render(&server_id, SILC_ID_SERVER)));
153         return FALSE;
154       }
155
156       silc_server_packet_route(server, conn, packet);
157       silc_packet_free(packet);
158       return TRUE;
159     }
160   }
161
162   /* Broadcast packet if it is marked as broadcast packet and it is
163      originated from router and we are router. */
164   if (server->server_type == SILC_ROUTER &&
165       idata->conn_type == SILC_CONN_ROUTER &&
166       packet->flags & SILC_PACKET_FLAG_BROADCAST) {
167     /* Broadcast to our primary route */
168     silc_server_packet_broadcast(server, SILC_PRIMARY_ROUTE(server), packet);
169
170     /* If we have backup routers then we need to feed all broadcast
171        data to those servers. */
172     silc_server_backup_broadcast(server, stream, packet);
173   }
174
175   /* Process packet */
176   silc_server_packet_parse_type(server, stream, packet);
177
178   return TRUE;
179 }
180
181 /* Packet engine callback to indicate end of stream */
182
183 static void silc_server_packet_eos(SilcPacketEngine engine,
184                                    SilcPacketStream stream,
185                                    void *callback_context,
186                                    void *stream_context)
187 {
188   SilcServer server = callback_context;
189   SilcIDListData idata = silc_packet_get_context(stream);
190
191   SILC_LOG_DEBUG(("End of stream received"));
192
193   if (!idata)
194     return;
195
196   if (server->router_conn && server->router_conn->sock == stream &&
197       !server->router && server->standalone) {
198     silc_server_create_connections(server);
199   } else {
200     /* If backup disconnected then mark that resuming will not be allowed */
201      if (server->server_type == SILC_ROUTER && !server->backup_router &&
202          idata->conn_type == SILC_CONN_SERVER) {
203       SilcServerEntry server_entry = (SilcServerEntry)idata;
204       if (server_entry->server_type == SILC_BACKUP_ROUTER)
205         server->backup_closed = TRUE;
206     }
207
208     silc_server_free_sock_user_data(server, stream, NULL);
209   }
210
211   silc_server_close_connection(server, stream);
212 }
213
214 /* Packet engine callback to indicate error */
215
216 static void silc_server_packet_error(SilcPacketEngine engine,
217                                      SilcPacketStream stream,
218                                      SilcPacketError error,
219                                      void *callback_context,
220                                      void *stream_context)
221 {
222   SilcIDListData idata = silc_packet_get_context(stream);
223   SilcStream sock = silc_packet_stream_get_stream(stream);
224   const char *ip;
225   SilcUInt16 port;
226
227   if (!idata || !sock)
228     return;
229
230   if (!silc_socket_stream_get_info(sock, NULL, NULL, &ip, &port))
231     return;
232
233   SILC_LOG_ERROR(("Connection %s:%d [%s]: %s",
234                   SILC_CONNTYPE_STRING(idata->conn_type), ip, port,
235                   silc_packet_error_string(error)));
236 }
237
238 /* Packet stream callbacks */
239 static SilcPacketCallbacks silc_server_stream_cbs =
240 {
241   silc_server_packet_receive,
242   silc_server_packet_eos,
243   silc_server_packet_error
244 };
245
246 /* Parses the packet type and calls what ever routines the packet type
247    requires. This is done for all incoming packets. */
248
249 static void silc_server_packet_parse_type(SilcServer server,
250                                           SilcPacketStream sock,
251                                           SilcPacket packet)
252 {
253   SilcPacketType type = packet->type;
254   SilcIDListData idata = silc_packet_get_context(sock);
255
256   SILC_LOG_DEBUG(("Received %s packet [flags %d]",
257                   silc_get_packet_name(type), packet->flags));
258
259   /* Parse the packet type */
260   switch (type) {
261   case SILC_PACKET_NOTIFY:
262     /*
263      * Received notify packet. Server can receive notify packets from
264      * router. Server then relays the notify messages to clients if needed.
265      */
266     if (packet->flags & SILC_PACKET_FLAG_LIST)
267       silc_server_notify_list(server, sock, packet);
268     else
269       silc_server_notify(server, sock, packet);
270     break;
271
272     /*
273      * Private Message packets
274      */
275   case SILC_PACKET_PRIVATE_MESSAGE:
276     /*
277      * Received private message packet. The packet is coming from either
278      * client or server.
279      */
280     if (packet->flags & SILC_PACKET_FLAG_LIST)
281       break;
282     idata->last_receive = time(NULL);
283     silc_server_private_message(server, sock, packet);
284     break;
285
286     /*
287      * Channel packets
288      */
289   case SILC_PACKET_CHANNEL_MESSAGE:
290     /*
291      * Received channel message. Channel messages are special packets
292      * (although probably most common ones) thus they are handled
293      * specially.
294      */
295     if (packet->flags & SILC_PACKET_FLAG_LIST)
296       break;
297     idata->last_receive = time(NULL);
298     silc_server_channel_message(server, sock, packet);
299     break;
300
301     /*
302      * Command packets
303      */
304   case SILC_PACKET_COMMAND:
305     /*
306      * Recived command. Processes the command request and allocates the
307      * command context and calls the command.
308      */
309     if (packet->flags & SILC_PACKET_FLAG_LIST)
310       break;
311     server->stat.commands_received++;
312     silc_server_command_process(server, sock, packet);
313     break;
314
315   case SILC_PACKET_COMMAND_REPLY:
316     /*
317      * Received command reply packet. Received command reply to command. It
318      * may be reply to command sent by us or reply to command sent by client
319      * that we've routed further.
320      */
321     if (packet->flags & SILC_PACKET_FLAG_LIST)
322       break;
323     server->stat.commands_received++;
324     silc_server_command_reply(server, sock, packet);
325     break;
326
327   case SILC_PACKET_DISCONNECT:
328     {
329       SilcStatus status;
330       char *message = NULL;
331       const char *hostname, *ip;
332
333       if (packet->flags & SILC_PACKET_FLAG_LIST)
334         break;
335       if (silc_buffer_len(&packet->buffer) < 1)
336         break;
337
338       status = (SilcStatus)packet->buffer.data[0];
339       if (silc_buffer_len(&packet->buffer) > 1 &&
340           silc_utf8_valid(packet->buffer.data + 1, silc_buffer_len(&packet->buffer) - 1))
341         message = silc_memdup(packet->buffer.data + 1,
342                               silc_buffer_len(&packet->buffer) - 1);
343
344       if (!silc_socket_stream_get_info(sock, NULL, &hostname, &ip, NULL))
345         break;
346
347       SILC_LOG_INFO(("Disconnected by %s (%s): %s (%d) %s", ip, hostname,
348                      silc_get_status_message(status), status,
349                      message ? message : ""));
350
351       silc_free(message);
352
353       /* Do not switch to backup in case of error */
354       server->backup_noswitch = (status == SILC_STATUS_OK ? FALSE : TRUE);
355
356       /* If backup disconnected then mark that resuming will not be allowed */
357 #if 0
358       if (server->server_type == SILC_ROUTER && !server->backup_router &&
359           sock->type == SILC_CONN_SERVER && sock->user_data) {
360         SilcServerEntry server_entry = sock->user_data;
361         if (server_entry->server_type == SILC_BACKUP_ROUTER)
362           server->backup_closed = TRUE;
363       }
364
365       /* Handle the disconnection from our end too */
366       if (sock->user_data && SILC_IS_LOCAL(sock->user_data))
367         silc_server_free_sock_user_data(server, sock, NULL);
368       SILC_SET_DISCONNECTING(sock);
369       silc_server_close_connection(server, sock);
370       server->backup_noswitch = FALSE;
371 #endif
372     }
373     break;
374
375   case SILC_PACKET_CHANNEL_KEY:
376     /*
377      * Received key for channel. As channels are created by the router
378      * the keys are as well. We will distribute the key to all of our
379      * locally connected clients on the particular channel. Router
380      * never receives this channel and thus is ignored.
381      */
382     if (packet->flags & SILC_PACKET_FLAG_LIST)
383       break;
384     silc_server_channel_key(server, sock, packet);
385     break;
386
387   case SILC_PACKET_PRIVATE_MESSAGE_KEY:
388     /*
389      * Private message key packet.
390      */
391     if (packet->flags & SILC_PACKET_FLAG_LIST)
392       break;
393     silc_server_private_message_key(server, sock, packet);
394     break;
395
396   case SILC_PACKET_CONNECTION_AUTH_REQUEST:
397     /*
398      * Connection authentication request packet. When we receive this packet
399      * we will send to the other end information about our mandatory
400      * authentication method for the connection. This packet maybe received
401      * at any time.
402      */
403     if (packet->flags & SILC_PACKET_FLAG_LIST)
404       break;
405     silc_server_connection_auth_request(server, sock, packet);
406     break;
407
408   case SILC_PACKET_NEW_ID:
409     /*
410      * Received New ID packet. This includes some new ID that has been
411      * created. It may be for client, server or channel. This is the way
412      * to distribute information about new registered entities in the
413      * SILC network.
414      */
415     if (packet->flags & SILC_PACKET_FLAG_LIST)
416       silc_server_new_id_list(server, sock, packet);
417     else
418       silc_server_new_id(server, sock, packet);
419     break;
420
421   case SILC_PACKET_NEW_CLIENT:
422     /*
423      * Received new client packet. This includes client information that
424      * we will use to create initial client ID. After creating new
425      * ID we will send it to the client.
426      */
427     if (packet->flags & SILC_PACKET_FLAG_LIST)
428       break;
429     silc_server_new_client(server, sock, packet);
430     break;
431
432   case SILC_PACKET_NEW_SERVER:
433     /*
434      * Received new server packet. This includes Server ID and some other
435      * information that we may save. This is received after server has
436      * connected to us.
437      */
438     if (packet->flags & SILC_PACKET_FLAG_LIST)
439       break;
440     silc_server_new_server(server, sock, packet);
441     break;
442
443   case SILC_PACKET_NEW_CHANNEL:
444     /*
445      * Received new channel packet. Information about new channel in the
446      * network are distributed using this packet.
447      */
448     if (packet->flags & SILC_PACKET_FLAG_LIST)
449       silc_server_new_channel_list(server, sock, packet);
450     else
451       silc_server_new_channel(server, sock, packet);
452     break;
453
454   case SILC_PACKET_HEARTBEAT:
455     /*
456      * Received heartbeat.
457      */
458     if (packet->flags & SILC_PACKET_FLAG_LIST)
459       break;
460     break;
461
462   case SILC_PACKET_KEY_AGREEMENT:
463     /*
464      * Received heartbeat.
465      */
466     if (packet->flags & SILC_PACKET_FLAG_LIST)
467       break;
468     silc_server_key_agreement(server, sock, packet);
469     break;
470
471   case SILC_PACKET_REKEY:
472     /*
473      * Received re-key packet. The sender wants to regenerate the session
474      * keys.
475      */
476     if (packet->flags & SILC_PACKET_FLAG_LIST)
477       break;
478     silc_server_rekey(server, sock, packet);
479     break;
480
481   case SILC_PACKET_FTP:
482     /* FTP packet */
483     if (packet->flags & SILC_PACKET_FLAG_LIST)
484       break;
485     silc_server_ftp(server, sock, packet);
486     break;
487
488   case SILC_PACKET_RESUME_CLIENT:
489     /* Resume client */
490     if (packet->flags & SILC_PACKET_FLAG_LIST)
491       break;
492     silc_server_resume_client(server, sock, packet);
493     break;
494
495   case SILC_PACKET_RESUME_ROUTER:
496     /* Resume router packet received. This packet is received for backup
497        router resuming protocol. */
498     if (packet->flags & SILC_PACKET_FLAG_LIST)
499       break;
500 #if 0
501     silc_server_backup_resume_router(server, sock, packet);
502 #endif
503     break;
504
505   default:
506     SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
507     break;
508   }
509 }
510
511 /****************************** Server API **********************************/
512
513 /* Allocates a new SILC server object. This has to be done before the server
514    can be used. After allocation one must call silc_server_init to initialize
515    the server. The new allocated server object is returned to the new_server
516    argument. */
517
518 SilcBool silc_server_alloc(SilcServer *new_server)
519 {
520   SilcServer server;
521
522   SILC_LOG_DEBUG(("Allocating new server object"));
523
524   server = silc_calloc(1, sizeof(*server));
525   if (!server)
526     return FALSE;
527   server->server_type = SILC_SERVER;
528   server->standalone = TRUE;
529   server->local_list = silc_calloc(1, sizeof(*server->local_list));
530   if (!server->local_list)
531     return FALSE;
532   server->global_list = silc_calloc(1, sizeof(*server->global_list));
533   if (!server->global_list)
534     return FALSE;
535   server->pending_commands = silc_dlist_init();
536   if (!server->pending_commands)
537     return FALSE;
538   server->listeners = silc_dlist_init();
539   if (!server->listeners)
540     return FALSE;
541   server->repository = silc_skr_alloc();
542   if (!server->repository)
543     return FALSE;
544   server->conns = silc_dlist_init();
545   if (!server->conns)
546     return FALSE;
547   server->expired_clients = silc_dlist_init();
548   if (!server->expired_clients)
549     return FALSE;
550
551   *new_server = server;
552
553   return TRUE;
554 }
555
556 /* Free's the SILC server object. This is called at the very end before
557    the program ends. */
558
559 void silc_server_free(SilcServer server)
560 {
561   SilcList list;
562   SilcIDCacheEntry cache;
563
564   if (!server)
565     return;
566
567   silc_server_backup_free(server);
568   silc_server_config_unref(&server->config_ref);
569   if (server->rng)
570     silc_rng_free(server->rng);
571   if (server->public_key)
572     silc_pkcs_public_key_free(server->public_key);
573   if (server->private_key)
574     silc_pkcs_private_key_free(server->private_key);
575   if (server->pending_commands)
576     silc_dlist_uninit(server->pending_commands);
577   if (server->id_entry)
578     silc_idlist_del_server(server->local_list, server->id_entry);
579
580   /* Delete all channels */
581   if (silc_idcache_get_all(server->local_list->channels, &list)) {
582     silc_list_start(list);
583     while ((cache = silc_list_get(list)))
584       silc_idlist_del_channel(server->local_list, cache->context);
585   }
586   if (silc_idcache_get_all(server->global_list->channels, &list)) {
587     silc_list_start(list);
588     while ((cache = silc_list_get(list)))
589       silc_idlist_del_channel(server->global_list, cache->context);
590   }
591
592   /* Delete all clients */
593   if (silc_idcache_get_all(server->local_list->clients, &list)) {
594     silc_list_start(list);
595     while ((cache = silc_list_get(list)))
596       silc_idlist_del_client(server->local_list, cache->context);
597   }
598   if (silc_idcache_get_all(server->global_list->clients, &list)) {
599     silc_list_start(list);
600     while ((cache = silc_list_get(list)))
601       silc_idlist_del_client(server->global_list, cache->context);
602   }
603
604   /* Delete all servers */
605   if (silc_idcache_get_all(server->local_list->servers, &list)) {
606     silc_list_start(list);
607     while ((cache = silc_list_get(list)))
608       silc_idlist_del_server(server->local_list, cache->context);
609   }
610   if (silc_idcache_get_all(server->global_list->servers, &list)) {
611     while ((cache = silc_list_get(list)))
612       silc_idlist_del_server(server->global_list, cache->context);
613   }
614
615   silc_idcache_free(server->local_list->clients);
616   silc_idcache_free(server->local_list->servers);
617   silc_idcache_free(server->local_list->channels);
618   silc_idcache_free(server->global_list->clients);
619   silc_idcache_free(server->global_list->servers);
620   silc_idcache_free(server->global_list->channels);
621   silc_hash_table_free(server->watcher_list);
622   silc_hash_table_free(server->watcher_list_pk);
623   silc_hash_free(server->md5hash);
624   silc_hash_free(server->sha1hash);
625
626   silc_dlist_uninit(server->listeners);
627   silc_dlist_uninit(server->conns);
628   silc_dlist_uninit(server->expired_clients);
629   silc_skr_free(server->repository);
630   silc_packet_engine_stop(server->packet_engine);
631
632   silc_free(server->local_list);
633   silc_free(server->global_list);
634   silc_free(server->server_name);
635   silc_free(server->purge_i);
636   silc_free(server->purge_g);
637   silc_free(server);
638
639   silc_hmac_unregister_all();
640   silc_hash_unregister_all();
641   silc_cipher_unregister_all();
642   silc_pkcs_unregister_all();
643 }
644
645 /* Creates a new server listener. */
646
647 static SilcNetListener
648 silc_server_listen(SilcServer server, const char *server_ip, SilcUInt16 port)
649 {
650   SilcNetListener listener;
651
652   listener =
653     silc_net_tcp_create_listener(&server_ip, 1, port, TRUE,
654                                  server->config->require_reverse_lookup,
655                                  server->schedule,
656                                  silc_server_accept_new_connection, server);
657   if (!listener) {
658     SILC_SERVER_LOG_ERROR(("Could not create server listener: %s on %hu",
659                            server_ip, port));
660     return NULL;
661   }
662
663   return listener;
664 }
665
666 /* Adds a secondary listener. */
667
668 SilcBool silc_server_init_secondary(SilcServer server)
669 {
670   return TRUE;
671 #if 0
672   int sock = 0;
673   SilcPacketStream newsocket = NULL;
674   SilcServerConfigServerInfoInterface *interface;
675
676   for (interface = server->config->server_info->secondary; interface;
677        interface = interface->next, sock++) {
678
679     if (!silc_server_listen(server,
680         interface->server_ip, interface->port, &sock_list[sock]))
681       goto err;
682
683     /* Set socket to non-blocking mode */
684     silc_net_set_socket_nonblock(sock_list[sock]);
685
686     /* Add ourselves also to the socket table. The entry allocated above
687        is sent as argument for fast referencing in the future. */
688     silc_socket_alloc(sock_list[sock],
689                       SILC_CONN_SERVER, NULL, &newsocket);
690     server->sockets[sock_list[sock]] = newsocket;
691     SILC_SET_LISTENER(newsocket);
692
693     /* Perform name and address lookups to resolve the listenning address
694        and port. */
695     if (!silc_net_check_local_by_sock(sock_list[sock], &newsocket->hostname,
696                             &newsocket->ip)) {
697       if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
698         !newsocket->ip) {
699         SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
700                       newsocket->hostname ? newsocket->hostname :
701                       newsocket->ip ? newsocket->ip : ""));
702         server->stat.conn_failures++;
703         goto err;
704       }
705       if (!newsocket->hostname)
706         newsocket->hostname = strdup(newsocket->ip);
707     }
708     newsocket->port = silc_net_get_local_port(sock);
709
710     newsocket->user_data = (void *)server->id_entry;
711     silc_schedule_task_add(server->schedule, sock_list[sock],
712                            silc_server_accept_new_connection,
713                            (void *)server, 0, 0,
714                            SILC_TASK_FD,
715                            SILC_TASK_PRI_NORMAL);
716   }
717
718   return TRUE;
719
720  err:
721   do silc_net_close_server(sock_list[sock--]); while (sock >= 0);
722 #endif /* 0 */
723   return FALSE;
724 }
725
726 /* Initializes the entire SILC server. This is called always before running
727    the server. This is called only once at the initialization of the program.
728    This binds the server to its listenning port. After this function returns
729    one should call silc_server_run to start the server. This returns TRUE
730    when everything is ok to run the server. Configuration file must be
731    read and parsed before calling this. */
732
733 SilcBool silc_server_init(SilcServer server)
734 {
735   SilcServerID *id;
736   SilcServerEntry id_entry;
737   SilcIDListPurge purge;
738   SilcNetListener listener;
739   SilcUInt16 *port;
740   char **ip;
741
742   SILC_LOG_DEBUG(("Initializing server"));
743
744   server->starttime = time(NULL);
745
746   /* Take config object for us */
747   silc_server_config_ref(&server->config_ref, server->config,
748                          server->config);
749
750 #ifdef SILC_DEBUG
751   /* Set debugging on if configured */
752   if (server->config->debug_string) {
753     silc_log_debug(TRUE);
754     silc_log_set_debug_string(server->config->debug_string);
755   }
756 #endif /* SILC_DEBUG */
757
758   /* Steal public and private key from the config object */
759   server->public_key = server->config->server_info->public_key;
760   server->private_key = server->config->server_info->private_key;
761   server->config->server_info->public_key = NULL;
762   server->config->server_info->private_key = NULL;
763
764   /* Register all configured ciphers, PKCS and hash functions. */
765   if (!silc_server_config_register_ciphers(server))
766     silc_cipher_register_default();
767   if (!silc_server_config_register_pkcs(server))
768     silc_pkcs_register_default();
769   if (!silc_server_config_register_hashfuncs(server))
770     silc_hash_register_default();
771   if (!silc_server_config_register_hmacs(server))
772     silc_hmac_register_default();
773
774   /* Initialize random number generator for the server. */
775   server->rng = silc_rng_alloc();
776   silc_rng_init(server->rng);
777   silc_rng_global_init(server->rng);
778
779   /* Initialize hash functions for server to use */
780   silc_hash_alloc("md5", &server->md5hash);
781   silc_hash_alloc("sha1", &server->sha1hash);
782
783   /* Initialize the scheduler */
784   server->schedule = silc_schedule_init(server->config->param.connections_max,
785                                         server);
786   if (!server->schedule)
787     goto err;
788
789   /* First, register log files configuration for error output */
790   silc_server_config_setlogfiles(server);
791
792   /* Initialize ID caches */
793   server->local_list->clients =
794     silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor,
795                        server);
796   server->local_list->servers =
797     silc_idcache_alloc(0, SILC_ID_SERVER, silc_idlist_server_destructor,
798                        server);
799   server->local_list->channels =
800     silc_idcache_alloc(0, SILC_ID_CHANNEL, silc_idlist_channel_destructor,
801                        NULL);
802
803   /* These are allocated for normal server as well as these hold some
804      global information that the server has fetched from its router. For
805      router these are used as they are supposed to be used on router. */
806   server->global_list->clients =
807     silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor,
808                        server);
809   server->global_list->servers =
810     silc_idcache_alloc(0, SILC_ID_SERVER, silc_idlist_server_destructor,
811                        server);
812   server->global_list->channels =
813     silc_idcache_alloc(0, SILC_ID_CHANNEL, silc_idlist_channel_destructor,
814                        NULL);
815
816   /* Init watcher lists */
817   server->watcher_list =
818     silc_hash_table_alloc(1, silc_hash_client_id_hash, NULL,
819                           silc_hash_data_compare, (void *)CLIENTID_HASH_LEN,
820                           NULL, NULL, TRUE);
821   if (!server->watcher_list)
822     goto err;
823   server->watcher_list_pk =
824     silc_hash_table_alloc(1, silc_hash_public_key, NULL,
825                           silc_hash_public_key_compare, NULL,
826                           NULL, NULL, TRUE);
827   if (!server->watcher_list_pk)
828     goto err;
829
830   /* Create TCP listener */
831   listener = silc_server_listen(
832                    server,
833                    server->config->server_info->primary == NULL ? NULL :
834                    server->config->server_info->primary->server_ip,
835                    server->config->server_info->primary == NULL ? 0 :
836                    server->config->server_info->primary->port);
837   if (!listener)
838     goto err;
839
840   silc_dlist_add(server->listeners, listener);
841
842   /* Create a Server ID for the server. */
843   port = silc_net_listener_get_port(listener, NULL);
844   ip = silc_net_listener_get_ip(listener, NULL);
845   silc_id_create_server_id(ip[0], port[0], server->rng, &id);
846   if (!id)
847     goto err;
848
849   silc_free(port);
850   silc_free(ip[0]);
851   silc_free(ip);
852
853   server->id = id;
854   server->server_name = server->config->server_info->server_name;
855   server->config->server_info->server_name = NULL;
856   silc_id_id2str(server->id, SILC_ID_SERVER, server->id_string,
857                  sizeof(server->id_string), &server->id_string_len);
858
859   /* Add ourselves to the server list. We don't have a router yet
860      beacuse we haven't established a route yet. It will be done later.
861      For now, NULL is sent as router. This allocates new entry to
862      the ID list. */
863   id_entry =
864     silc_idlist_add_server(server->local_list, strdup(server->server_name),
865                            server->server_type, server->id, NULL, NULL);
866   if (!id_entry) {
867     SILC_LOG_ERROR(("Could not add local server to cache"));
868     goto err;
869   }
870   id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
871   server->id_entry = id_entry;
872
873   /* Create secondary TCP listeners */
874   if (silc_server_init_secondary(server) == FALSE)
875     goto err;
876
877   server->listenning = TRUE;
878
879   /* Create connections to configured routers. */
880   silc_server_create_connections(server);
881
882   /* If server connections has been configured then we must be router as
883      normal server cannot have server connections, only router connections. */
884   if (server->config->servers) {
885     SilcServerConfigServer *ptr = server->config->servers;
886
887     server->server_type = SILC_ROUTER;
888     while (ptr) {
889       if (ptr->backup_router) {
890         server->server_type = SILC_BACKUP_ROUTER;
891         server->backup_router = TRUE;
892         server->id_entry->server_type = SILC_BACKUP_ROUTER;
893         break;
894       }
895       ptr = ptr->next;
896     }
897   }
898
899   /* Register the ID Cache purge task. This periodically purges the ID cache
900      and removes the expired cache entries. */
901
902   /* Clients local list */
903   server->purge_i = purge = silc_calloc(1, sizeof(*purge));
904   purge->cache = server->local_list->clients;
905   purge->timeout = 600;
906   silc_schedule_task_add_timeout(server->schedule, silc_idlist_purge,
907                                  (void *)purge, purge->timeout, 0);
908
909   /* Clients global list */
910   server->purge_g = purge = silc_calloc(1, sizeof(*purge));
911   purge->cache = server->global_list->clients;
912   purge->timeout = 300;
913   silc_schedule_task_add_timeout(server->schedule, silc_idlist_purge,
914                                  (void *)purge, purge->timeout, 0);
915
916   /* If we are normal server we'll retrieve network statisticial information
917      once in a while from the router. */
918   if (server->server_type != SILC_ROUTER)
919     silc_schedule_task_add_timeout(server->schedule, silc_server_get_stats,
920                                    server, 10, 0);
921
922   if (server->server_type == SILC_ROUTER)
923     server->stat.routers++;
924
925   /* Start packet engine */
926   server->packet_engine =
927     silc_packet_engine_start(server->rng, server->server_type == SILC_ROUTER,
928                              &silc_server_stream_cbs, server);
929   if (!server->packet_engine)
930     goto err;
931
932   /* Register client entry expiration timeout */
933   silc_schedule_task_add_timeout(server->schedule,
934                                  silc_server_purge_expired_clients, server,
935                                  600, 0);
936
937   /* Initialize HTTP server */
938   silc_server_http_init(server);
939
940   SILC_LOG_DEBUG(("Server initialized"));
941
942   /* We are done here, return succesfully */
943   return TRUE;
944
945  err:
946   silc_server_config_unref(&server->config_ref);
947   return FALSE;
948 }
949
950 #if 0
951 /* Task callback to close a socket connection after rehash */
952
953 SILC_TASK_CALLBACK(silc_server_rehash_close_connection)
954 {
955   SilcServer server = context;
956   SilcPacketStream sock = server->sockets[fd];
957
958   if (!sock)
959     return;
960
961   SILC_LOG_INFO(("Connection %s:%d [%s] is unconfigured",
962                  sock->hostname, sock->port,
963                  (sock->type == SILC_CONN_UNKNOWN ? "Unknown" :
964                   sock->type == SILC_CONN_CLIENT ? "Client" :
965                   sock->type == SILC_CONN_SERVER ? "Server" :
966                   "Router")));
967   silc_schedule_task_del_by_context(server->schedule, sock);
968   silc_server_disconnect_remote(server, sock,
969                                 SILC_STATUS_ERR_BANNED_FROM_SERVER,
970                                 "This connection is removed from "
971                                 "configuration");
972   if (sock->user_data)
973     silc_server_free_sock_user_data(server, sock, NULL);
974 }
975 #endif /* 0 */
976
977 /* This function basically reads the config file again and switches the config
978    object pointed by the server object. After that, we have to fix various
979    things such as the server_name and the listening ports.
980    Keep in mind that we no longer have the root privileges at this point. */
981
982 SilcBool silc_server_rehash(SilcServer server)
983 {
984 #if 0
985   SilcServerConfig newconfig;
986
987   SILC_LOG_INFO(("Rehashing server"));
988
989   /* Reset the logging system */
990   silc_log_quick(TRUE);
991   silc_log_flush_all();
992
993   /* Start the main rehash phase (read again the config file) */
994   newconfig = silc_server_config_alloc(server->config_file, server);
995   if (!newconfig) {
996     SILC_LOG_ERROR(("Rehash FAILED."));
997     return FALSE;
998   }
999
1000   /* Reinit scheduler if necessary */
1001   if (newconfig->param.connections_max > server->config->param.connections_max)
1002     if (!silc_schedule_reinit(server->schedule,
1003                               newconfig->param.connections_max))
1004       return FALSE;
1005
1006   /* Fix the server_name field */
1007   if (strcmp(server->server_name, newconfig->server_info->server_name)) {
1008     silc_free(server->server_name);
1009
1010     /* Check server name */
1011     server->server_name =
1012       silc_identifier_check(newconfig->server_info->server_name,
1013                             strlen(newconfig->server_info->server_name),
1014                             SILC_STRING_LOCALE, 256, NULL);
1015     if (!server->server_name) {
1016       SILC_LOG_ERROR(("Malformed server name string '%s'",
1017                       server->config->server_info->server_name));
1018       return FALSE;
1019     }
1020
1021     /* Update the idcache list with a fresh pointer */
1022     silc_free(server->id_entry->server_name);
1023     server->id_entry->server_name = strdup(server->server_name);
1024     if (!silc_idcache_del_by_context(server->local_list->servers,
1025                                      server->id_entry))
1026       return FALSE;
1027     if (!silc_idcache_add(server->local_list->servers,
1028                           strdup(server->id_entry->server_name),
1029                           server->id_entry->id, server->id_entry, 0, NULL))
1030       return FALSE;
1031   }
1032
1033   /* Set logging */
1034   silc_server_config_setlogfiles(server);
1035
1036   /* Change new key pair if necessary */
1037   if (newconfig->server_info->public_key &&
1038       !silc_pkcs_public_key_compare(server->public_key,
1039                                     newconfig->server_info->public_key)) {
1040     silc_pkcs_public_key_free(server->public_key);
1041     silc_pkcs_private_key_free(server->private_key);
1042     server->public_key = newconfig->server_info->public_key;
1043     server->private_key = newconfig->server_info->private_key;
1044     newconfig->server_info->public_key = NULL;
1045     newconfig->server_info->private_key = NULL;
1046
1047     /* Allocate PKCS context for local public and private keys */
1048     silc_pkcs_free(server->pkcs);
1049     if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
1050       return FALSE;
1051     silc_pkcs_public_key_set(server->pkcs, server->public_key);
1052     silc_pkcs_private_key_set(server->pkcs, server->private_key);
1053   }
1054
1055   /* Check for unconfigured server and router connections and close
1056      connections that were unconfigured. */
1057
1058   if (server->config->routers) {
1059     SilcServerConfigRouter *ptr;
1060     SilcServerConfigRouter *newptr;
1061     SilcBool found;
1062
1063     for (ptr = server->config->routers; ptr; ptr = ptr->next) {
1064       found = FALSE;
1065
1066       /* Check whether new config has this one too */
1067       for (newptr = newconfig->routers; newptr; newptr = newptr->next) {
1068         if (silc_string_compare(newptr->host, ptr->host) &&
1069             newptr->port == ptr->port &&
1070             newptr->initiator == ptr->initiator) {
1071           found = TRUE;
1072           break;
1073         }
1074       }
1075
1076       if (!found && ptr->host) {
1077         /* Remove this connection */
1078         SilcPacketStream sock;
1079         sock = silc_server_find_socket_by_host(server, SILC_CONN_ROUTER,
1080                                                ptr->host, ptr->port);
1081         if (sock && !SILC_IS_LISTENER(sock))
1082           silc_schedule_task_add(server->schedule, sock->sock,
1083                                  silc_server_rehash_close_connection,
1084                                  server, 0, 1, SILC_TASK_TIMEOUT,
1085                                  SILC_TASK_PRI_NORMAL);
1086       }
1087     }
1088   }
1089
1090   if (server->config->servers) {
1091     SilcServerConfigServer *ptr;
1092     SilcServerConfigServer *newptr;
1093     SilcBool found;
1094
1095     for (ptr = server->config->servers; ptr; ptr = ptr->next) {
1096       found = FALSE;
1097
1098       /* Check whether new config has this one too */
1099       for (newptr = newconfig->servers; newptr; newptr = newptr->next) {
1100         if (silc_string_compare(newptr->host, ptr->host)) {
1101           found = TRUE;
1102           break;
1103         }
1104       }
1105
1106       if (!found && ptr->host) {
1107         /* Remove this connection */
1108         SilcPacketStream sock;
1109         sock = silc_server_find_socket_by_host(server, SILC_CONN_SERVER,
1110                                                ptr->host, 0);
1111         if (sock && !SILC_IS_LISTENER(sock))
1112           silc_schedule_task_add(server->schedule, sock->sock,
1113                                  silc_server_rehash_close_connection,
1114                                  server, 0, 1, SILC_TASK_TIMEOUT,
1115                                  SILC_TASK_PRI_NORMAL);
1116       }
1117     }
1118   }
1119
1120   if (server->config->clients) {
1121     SilcServerConfigClient *ptr;
1122     SilcServerConfigClient *newptr;
1123     SilcBool found;
1124
1125     for (ptr = server->config->clients; ptr; ptr = ptr->next) {
1126       found = FALSE;
1127
1128       /* Check whether new config has this one too */
1129       for (newptr = newconfig->clients; newptr; newptr = newptr->next) {
1130         if (silc_string_compare(newptr->host, ptr->host)) {
1131           found = TRUE;
1132           break;
1133         }
1134       }
1135
1136       if (!found && ptr->host) {
1137         /* Remove this connection */
1138         SilcPacketStream sock;
1139         sock = silc_server_find_socket_by_host(server, SILC_CONN_CLIENT,
1140                                                ptr->host, 0);
1141         if (sock)
1142           silc_schedule_task_add(server->schedule, sock->sock,
1143                                  silc_server_rehash_close_connection,
1144                                  server, 0, 1, SILC_TASK_TIMEOUT,
1145                                  SILC_TASK_PRI_NORMAL);
1146       }
1147     }
1148   }
1149
1150   /* Create connections after rehash */
1151   silc_server_create_connections(server);
1152
1153   /* Check whether our router status has changed */
1154   if (newconfig->servers) {
1155     SilcServerConfigServer *ptr = newconfig->servers;
1156
1157     server->server_type = SILC_ROUTER;
1158     while (ptr) {
1159       if (ptr->backup_router) {
1160         server->server_type = SILC_BACKUP_ROUTER;
1161         server->backup_router = TRUE;
1162         server->id_entry->server_type = SILC_BACKUP_ROUTER;
1163         break;
1164       }
1165       ptr = ptr->next;
1166     }
1167   }
1168
1169   /* Our old config is gone now. We'll unreference our reference made in
1170      silc_server_init and then destroy it since we are destroying it
1171      underneath the application (layer which called silc_server_init). */
1172   silc_server_config_unref(&server->config_ref);
1173   silc_server_config_destroy(server->config);
1174
1175   /* Take new config context */
1176   server->config = newconfig;
1177   silc_server_config_ref(&server->config_ref, server->config, server->config);
1178
1179 #ifdef SILC_DEBUG
1180   /* Set debugging on if configured */
1181   if (server->config->debug_string) {
1182     silc_log_debug(TRUE);
1183     silc_log_set_debug_string(server->config->debug_string);
1184   }
1185 #endif /* SILC_DEBUG */
1186
1187   SILC_LOG_DEBUG(("Server rehashed"));
1188 #endif /* 0 */
1189
1190   return TRUE;
1191 }
1192
1193 /* The heart of the server. This runs the scheduler thus runs the server.
1194    When this returns the server has been stopped and the program will
1195    be terminated. */
1196
1197 void silc_server_run(SilcServer server)
1198 {
1199   SILC_LOG_INFO(("SILC Server started"));
1200
1201   /* Start the scheduler, the heart of the SILC server. When this returns
1202      the program will be terminated. */
1203   silc_schedule(server->schedule);
1204 }
1205
1206 /* Stops the SILC server. This function is used to shutdown the server.
1207    This is usually called after the scheduler has returned. After stopping
1208    the server one should call silc_server_free. */
1209
1210 void silc_server_stop(SilcServer server)
1211 {
1212   SilcDList list;
1213   SilcPacketStream ps;
1214   SilcNetListener listener;
1215
1216   SILC_LOG_INFO(("SILC Server shutting down"));
1217
1218   server->server_shutdown = TRUE;
1219
1220   /* Close all connections */
1221   if (server->packet_engine) {
1222     list = silc_packet_engine_get_streams(server->packet_engine);
1223
1224     silc_dlist_start(list);
1225     while ((ps = silc_dlist_get(list))) {
1226       SilcIDListData idata = silc_packet_get_context(ps);
1227
1228       if (idata)
1229         idata->status &= ~SILC_IDLIST_STATUS_DISABLED;
1230
1231       silc_server_disconnect_remote(server, ps, SILC_STATUS_OK,
1232                                     "Server is shutting down");
1233       silc_server_free_sock_user_data(server, ps,
1234                                       "Server is shutting down");
1235     }
1236     silc_dlist_uninit(list);
1237   }
1238
1239   /* We are not connected to network anymore */
1240   server->standalone = TRUE;
1241
1242   silc_dlist_start(server->listeners);
1243   while ((listener = silc_dlist_get(server->listeners)))
1244     silc_net_close_listener(listener);
1245
1246   silc_server_http_uninit(server);
1247
1248   silc_schedule_stop(server->schedule);
1249   silc_schedule_uninit(server->schedule);
1250   server->schedule = NULL;
1251
1252   SILC_LOG_DEBUG(("Server stopped"));
1253 }
1254
1255 /* Purge expired client entries from the server */
1256
1257 SILC_TASK_CALLBACK(silc_server_purge_expired_clients)
1258 {
1259   SilcServer server = context;
1260   SilcClientEntry client;
1261   SilcIDList id_list;
1262
1263   SILC_LOG_DEBUG(("Expire timeout"));
1264
1265   silc_dlist_start(server->expired_clients);
1266   while ((client = silc_dlist_get(server->expired_clients))) {
1267     if (client->data.status & SILC_IDLIST_STATUS_REGISTERED)
1268       continue;
1269
1270     id_list = (client->data.status & SILC_IDLIST_STATUS_LOCAL ?
1271                server->local_list : server->global_list);
1272
1273     silc_idlist_del_data(client);
1274     silc_idlist_del_client(id_list, client);
1275     silc_dlist_del(server->expired_clients, client);
1276   }
1277
1278   silc_schedule_task_add_timeout(server->schedule,
1279                                  silc_server_purge_expired_clients, server,
1280                                  600, 0);
1281 }
1282
1283
1284 /******************************* Connecting *********************************/
1285
1286 /* Free connection context */
1287
1288 static void silc_server_connection_free(SilcServerConnection sconn)
1289 {
1290   silc_dlist_del(sconn->server->conns, sconn);
1291   silc_server_config_unref(&sconn->conn);
1292   silc_free(sconn->remote_host);
1293   silc_free(sconn->backup_replace_ip);
1294   silc_free(sconn);
1295 }
1296
1297 /* Creates connection to a remote router. */
1298
1299 void silc_server_create_connection(SilcServer server,
1300                                    SilcBool reconnect,
1301                                    const char *remote_host, SilcUInt32 port,
1302                                    SilcServerConnectCallback callback,
1303                                    void *context)
1304 {
1305   SilcServerConnection sconn;
1306
1307   /* Allocate connection object for hold connection specific stuff. */
1308   sconn = silc_calloc(1, sizeof(*sconn));
1309   if (!sconn)
1310     return;
1311   sconn->remote_host = strdup(remote_host);
1312   sconn->remote_port = port;
1313   sconn->no_reconnect = reconnect == FALSE;
1314   sconn->callback = callback;
1315   sconn->callback_context = context;
1316
1317   silc_schedule_task_add_timeout(server->schedule, silc_server_connect_router,
1318                                  sconn, 0, 0);
1319 }
1320
1321 /* Connection authentication completion callback */
1322
1323 static void
1324 silc_server_ke_auth_compl(SilcConnAuth connauth, SilcBool success,
1325                           void *context)
1326 {
1327   SilcServerConnection sconn = context;
1328   SilcUnknownEntry entry = silc_packet_get_context(sconn->sock);
1329   SilcServer server = entry->server;
1330   SilcServerConfigServer *conn;
1331   SilcServerConfigConnParams *param;
1332   SilcIDListData idata;
1333   SilcServerEntry id_entry;
1334   unsigned char id[32];
1335   SilcUInt32 id_len;
1336   SilcID remote_id;
1337
1338   SILC_LOG_DEBUG(("Connection authentication completed"));
1339
1340   if (success == FALSE) {
1341     /* Authentication failed */
1342     /* XXX retry connecting */
1343
1344     silc_server_disconnect_remote(server, sconn->sock,
1345                                   SILC_STATUS_ERR_AUTH_FAILED, NULL);
1346     return;
1347   }
1348
1349   SILC_LOG_INFO(("Connected to %s %s",
1350                  SILC_CONNTYPE_STRING(entry->data.conn_type),
1351                  sconn->remote_host));
1352
1353   /* Create the actual entry for remote entity */
1354   switch (entry->data.conn_type) {
1355   case SILC_CONN_SERVER:
1356     SILC_LOG_DEBUG(("Remote is SILC server"));
1357
1358     /* Add new server.  The server must register itself to us before it
1359        becomes registered to SILC network. */
1360     id_entry = silc_idlist_add_server(server->local_list,
1361                                       strdup(sconn->remote_host),
1362                                       SILC_SERVER, NULL, NULL, sconn->sock);
1363     if (!id_entry) {
1364       silc_server_disconnect_remote(server, sconn->sock,
1365                                     SILC_STATUS_ERR_RESOURCE_LIMIT, NULL);
1366       silc_server_connection_free(sconn);
1367       silc_free(entry);
1368       return;
1369     }
1370
1371     silc_idlist_add_data(id_entry, (SilcIDListData)entry);
1372     break;
1373
1374   case SILC_CONN_ROUTER:
1375     SILC_LOG_DEBUG(("Remote is SILC router"));
1376
1377     /* Register to network */
1378     silc_id_id2str(server->id, SILC_ID_SERVER, id, sizeof(id), &id_len);
1379     if (!silc_packet_send_va(sconn->sock, SILC_PACKET_NEW_SERVER, 0,
1380                              SILC_STR_UI_SHORT(id_len),
1381                              SILC_STR_DATA(id, id_len),
1382                              SILC_STR_UI_SHORT(strlen(server->server_name)),
1383                              SILC_STR_DATA(server->server_name,
1384                                            strlen(server->server_name)),
1385                              SILC_STR_END)) {
1386       silc_server_disconnect_remote(server, sconn->sock,
1387                                     SILC_STATUS_ERR_RESOURCE_LIMIT, NULL);
1388       silc_server_connection_free(sconn);
1389       silc_free(entry);
1390       return;
1391     }
1392
1393     /* Get remote ID */
1394     silc_packet_get_ids(sconn->sock, NULL, NULL, NULL, &remote_id);
1395
1396     /* Check that we do not have this ID already */
1397     id_entry = silc_idlist_find_server_by_id(server->local_list,
1398                                              &remote_id.u.server_id,
1399                                              TRUE, NULL);
1400     if (id_entry) {
1401       silc_idcache_del_by_context(server->local_list->servers, id_entry, NULL);
1402     } else {
1403       id_entry = silc_idlist_find_server_by_id(server->global_list,
1404                                                &remote_id.u.server_id,
1405                                                TRUE, NULL);
1406       if (id_entry)
1407         silc_idcache_del_by_context(server->global_list->servers, id_entry,
1408                                     NULL);
1409     }
1410
1411     SILC_LOG_DEBUG(("New server id(%s)",
1412                     silc_id_render(&remote_id.u.server_id, SILC_ID_SERVER)));
1413
1414     /* Add the connected router to global server list.  Router is sent
1415        as NULL since it's local to us. */
1416     id_entry = silc_idlist_add_server(server->global_list,
1417                                       strdup(sconn->remote_host),
1418                                       SILC_ROUTER, &remote_id.u.server_id,
1419                                       NULL, sconn->sock);
1420     if (!id_entry) {
1421       silc_server_disconnect_remote(server, sconn->sock,
1422                                     SILC_STATUS_ERR_RESOURCE_LIMIT, NULL);
1423       silc_server_connection_free(sconn);
1424       silc_free(entry);
1425       return;
1426     }
1427
1428     /* Registered */
1429     silc_idlist_add_data(id_entry, (SilcIDListData)entry);
1430     idata = (SilcIDListData)entry;
1431     idata->status |= (SILC_IDLIST_STATUS_REGISTERED |
1432                       SILC_IDLIST_STATUS_LOCAL);
1433
1434     if (!sconn->backup) {
1435       /* Mark this router our primary router if we're still standalone */
1436       if (server->standalone) {
1437         SILC_LOG_DEBUG(("This connection is our primary router"));
1438         server->id_entry->router = id_entry;
1439         server->router = id_entry;
1440         server->router->server_type = SILC_ROUTER;
1441         server->standalone = FALSE;
1442         server->backup_primary = FALSE;
1443
1444         /* Announce data if we are not backup router (unless not as primary
1445            currently).  Backup router announces later at the end of
1446            resuming protocol. */
1447         if (server->backup_router && server->server_type == SILC_ROUTER) {
1448           SILC_LOG_DEBUG(("Announce data after resume protocol"));
1449         } else {
1450           /* If we are router then announce our possible servers.  Backup
1451              router announces also global servers. */
1452           if (server->server_type == SILC_ROUTER)
1453             silc_server_announce_servers(server,
1454                                          server->backup_router ? TRUE : FALSE,
1455                                          0, SILC_PRIMARY_ROUTE(server));
1456
1457           /* Announce our clients and channels to the router */
1458           silc_server_announce_clients(server, 0, SILC_PRIMARY_ROUTE(server));
1459           silc_server_announce_channels(server, 0, SILC_PRIMARY_ROUTE(server));
1460         }
1461
1462 #if 0
1463         /* If we are backup router then this primary router is whom we are
1464            backing up. */
1465         if (server->server_type == SILC_BACKUP_ROUTER)
1466           silc_server_backup_add(server, server->id_entry, sock->ip,
1467                                  sconn->remote_port, TRUE);
1468 #endif /* 0 */
1469       }
1470     } else {
1471       /* Add this server to be our backup router */
1472       id_entry->server_type = SILC_BACKUP_ROUTER;
1473       silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1474                              sconn->backup_replace_port, FALSE);
1475     }
1476
1477     break;
1478
1479   default:
1480     silc_server_disconnect_remote(server, sconn->sock,
1481                                   SILC_STATUS_ERR_AUTH_FAILED, NULL);
1482     silc_server_connection_free(sconn);
1483     silc_free(entry);
1484     return;
1485   }
1486
1487   conn = sconn->conn.ref_ptr;
1488   param = &server->config->param;
1489   if (conn && conn->param)
1490     param = conn->param;
1491
1492   /* Register rekey timeout */
1493   sconn->rekey_timeout = param->key_exchange_rekey;
1494   silc_schedule_task_add_timeout(server->schedule, silc_server_do_rekey,
1495                                  sconn->sock, sconn->rekey_timeout, 0);
1496
1497 #if 0
1498   /* Perform keepalive. */
1499   silc_socket_set_heartbeat(sock, param->keepalive_secs, server,
1500                             silc_server_perform_heartbeat,
1501                             server->schedule);
1502
1503  out:
1504   /* Call the completion callback to indicate that we've connected to
1505      the router */
1506   if (sconn && sconn->callback)
1507     (*sconn->callback)(server, id_entry, sconn->callback_context);
1508
1509   /* Free the temporary connection data context */
1510   if (sconn) {
1511     silc_server_config_unref(&sconn->conn);
1512     silc_free(sconn->remote_host);
1513     silc_free(sconn->backup_replace_ip);
1514     silc_free(sconn);
1515   }
1516   if (sconn == server->router_conn)
1517     server->router_conn = NULL;
1518 #endif /* 0 */
1519
1520   silc_free(entry);
1521 }
1522
1523 /* SKE completion callback */
1524
1525 static void silc_server_ke_completed(SilcSKE ske, SilcSKEStatus status,
1526                                      SilcSKESecurityProperties prop,
1527                                      SilcSKEKeyMaterial keymat,
1528                                      SilcSKERekeyMaterial rekey,
1529                                      void *context)
1530 {
1531   SilcServerConnection sconn = context;
1532   SilcUnknownEntry entry = silc_packet_get_context(sconn->sock);
1533   SilcServer server = entry->server;
1534   SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
1535   SilcAuthMethod auth_meth = SILC_AUTH_NONE;
1536   void *auth_data = NULL;
1537   SilcUInt32 auth_data_len = 0;
1538   SilcConnAuth connauth;
1539   SilcCipher send_key, receive_key;
1540   SilcHmac hmac_send, hmac_receive;
1541   SilcHash hash;
1542
1543   if (status != SILC_SKE_STATUS_OK) {
1544     /* SKE failed */
1545     SILC_LOG_ERROR(("Error (%s) during Key Exchange protocol with %s (%s)",
1546                     silc_ske_map_status(status), entry->hostname, entry->ip));
1547
1548     /* XXX retry connecting */
1549     silc_ske_free(ske);
1550     silc_server_disconnect_remote(server, sconn->sock,
1551                                   SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1552     silc_server_connection_free(sconn);
1553     return;
1554   }
1555
1556   SILC_LOG_DEBUG(("Setting keys into use"));
1557
1558   /* Set the keys into use.  The data will be encrypted after this. */
1559   if (!silc_ske_set_keys(ske, keymat, prop, &send_key, &receive_key,
1560                          &hmac_send, &hmac_receive, &hash)) {
1561
1562     /* XXX retry connecting */
1563
1564     /* Error setting keys */
1565     silc_ske_free(ske);
1566     silc_server_disconnect_remote(server, sconn->sock,
1567                                   SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1568     silc_server_connection_free(sconn);
1569     return;
1570   }
1571   silc_packet_set_keys(sconn->sock, send_key, receive_key, hmac_send,
1572                        hmac_receive, FALSE);
1573
1574   SILC_LOG_DEBUG(("Starting connection authentication"));
1575
1576   connauth = silc_connauth_alloc(server->schedule, ske,
1577                                  server->config->conn_auth_timeout);
1578   if (!connauth) {
1579     /* XXX retry connecting */
1580
1581     /** Error allocating auth protocol */
1582     silc_ske_free(ske);
1583     silc_server_disconnect_remote(server, sconn->sock,
1584                                   SILC_STATUS_ERR_RESOURCE_LIMIT, NULL);
1585     silc_server_connection_free(sconn);
1586     return;
1587   }
1588
1589   /* Get authentication method */
1590   if (conn) {
1591     if (conn->passphrase) {
1592       if (conn->publickeys && !server->config->prefer_passphrase_auth) {
1593         auth_meth = SILC_AUTH_PUBLIC_KEY;
1594         auth_data = server->private_key;
1595       } else {
1596         auth_meth = SILC_AUTH_PASSWORD;
1597         auth_data = conn->passphrase;
1598         auth_data_len = conn->passphrase_len;
1599       }
1600     } else {
1601       auth_meth = SILC_AUTH_PUBLIC_KEY;
1602       auth_data = server->private_key;
1603     }
1604   }
1605
1606   /* Start connection authentication */
1607   silc_connauth_initiator(connauth, server->server_type == SILC_ROUTER ?
1608                           SILC_CONN_ROUTER : SILC_CONN_SERVER, auth_meth,
1609                           auth_data, auth_data_len,
1610                           silc_server_ke_auth_compl, sconn);
1611 }
1612
1613 /* Function that is called when the network connection to a router has
1614    been established.  This will continue with the key exchange protocol
1615    with the remote router. */
1616
1617 void silc_server_start_key_exchange(SilcServerConnection sconn)
1618 {
1619   SilcServer server = sconn->server;
1620   SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
1621   SilcUnknownEntry entry;
1622   SilcSKEParamsStruct params;
1623   SilcSKE ske;
1624
1625   /* Cancel any possible retry timeouts */
1626   silc_schedule_task_del_by_context(server->schedule, sconn);
1627
1628   /* Create packet stream */
1629   sconn->sock = silc_packet_stream_create(server->packet_engine,
1630                                           server->schedule, sconn->stream);
1631   if (!sconn->sock) {
1632     SILC_LOG_ERROR(("Cannot connect: cannot create packet stream"));
1633     silc_stream_destroy(sconn->stream);
1634     silc_server_connection_free(sconn);
1635     return;
1636   }
1637   server->stat.conn_num++;
1638
1639   /* Set source ID to packet stream */
1640   if (!silc_packet_set_ids(sconn->sock, SILC_ID_SERVER, server->id,
1641                            0, NULL)) {
1642     silc_packet_stream_destroy(sconn->sock);
1643     silc_server_connection_free(sconn);
1644     return;
1645   }
1646
1647   /* Create entry for remote entity */
1648   entry = silc_calloc(1, sizeof(*entry));
1649   if (!entry) {
1650     silc_packet_stream_destroy(sconn->sock);
1651     silc_server_connection_free(sconn);
1652     return;
1653   }
1654   entry->server = server;
1655   silc_packet_set_context(sconn->sock, entry);
1656
1657   /* Set Key Exchange flags from configuration, but fall back to global
1658      settings too. */
1659   memset(&params, 0, sizeof(params));
1660   SILC_GET_SKE_FLAGS(conn, params.flags);
1661   if (server->config->param.key_exchange_pfs)
1662     params.flags |= SILC_SKE_SP_FLAG_PFS;
1663
1664   /* Start SILC Key Exchange protocol */
1665   SILC_LOG_DEBUG(("Starting key exchange protocol"));
1666   ske = silc_ske_alloc(server->rng, server->schedule, server->repository,
1667                        server->public_key, server->private_key, sconn->sock);
1668   if (!ske) {
1669     silc_free(entry);
1670     silc_packet_stream_destroy(sconn->sock);
1671     silc_server_connection_free(sconn);
1672     return;
1673   }
1674   silc_ske_set_callbacks(ske, silc_server_verify_key,
1675                          silc_server_ke_completed, sconn->sock);
1676
1677   /* Start key exchange protocol */
1678   params.version = silc_version_string;
1679   params.timeout_secs = server->config->key_exchange_timeout;
1680   silc_ske_initiator(ske, sconn->sock, &params, NULL);
1681 }
1682
1683 /* Timeout callback that will be called to retry connecting to remote
1684    router. This is used by both normal and router server. This will wait
1685    before retrying the connecting. The timeout is generated by exponential
1686    backoff algorithm. */
1687
1688 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
1689 {
1690   SilcServerConnection sconn = context;
1691   SilcServer server = sconn->server;
1692   SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
1693   SilcServerConfigConnParams *param =
1694                 (conn->param ? conn->param : &server->config->param);
1695
1696   SILC_LOG_INFO(("Retrying connecting to %s:%d", sconn->remote_host,
1697                  sconn->remote_port));
1698
1699   /* Calculate next timeout */
1700   if (sconn->retry_count >= 1) {
1701     sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
1702     if (sconn->retry_timeout > param->reconnect_interval_max)
1703       sconn->retry_timeout = param->reconnect_interval_max;
1704   } else {
1705     sconn->retry_timeout = param->reconnect_interval;
1706   }
1707   sconn->retry_count++;
1708   sconn->retry_timeout = sconn->retry_timeout +
1709     (silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER);
1710
1711   /* If we've reached max retry count, give up. */
1712   if ((sconn->retry_count > param->reconnect_count) &&
1713       !param->reconnect_keep_trying) {
1714     SILC_LOG_ERROR(("Could not connect, giving up"));
1715     silc_server_connection_free(sconn);
1716     return;
1717   }
1718
1719   SILC_LOG_DEBUG(("Retrying connecting %d seconds", sconn->retry_timeout));
1720
1721   /* We will lookup a fresh pointer later */
1722   silc_server_config_unref(&sconn->conn);
1723
1724   /* Wait before retrying */
1725   silc_schedule_task_del_by_context(server->schedule, sconn);
1726   silc_schedule_task_add_timeout(server->schedule, silc_server_connect_router,
1727                                  sconn, sconn->retry_timeout, 0);
1728 }
1729
1730 /* Callback for async connection to remote router */
1731
1732 static void silc_server_connection_established(SilcNetStatus status,
1733                                                SilcStream stream,
1734                                                void *context)
1735 {
1736   SilcServerConnection sconn = context;
1737   SilcServer server = sconn->server;
1738
1739   silc_schedule_task_del_by_context(server->schedule, sconn);
1740   sconn->op = NULL;
1741
1742   switch (status) {
1743   case SILC_NET_OK:
1744     SILC_LOG_DEBUG(("Connection to %s:%d established",
1745                     sconn->remote_host, sconn->remote_port));
1746
1747     /* Continue with key exchange protocol */
1748     sconn->stream = stream;
1749     silc_server_start_key_exchange(sconn);
1750     break;
1751
1752   case SILC_NET_UNKNOWN_IP:
1753   case SILC_NET_UNKNOWN_HOST:
1754     SILC_LOG_ERROR(("Could not connect to %s:%d: %s",
1755                     sconn->remote_host, sconn->remote_port,
1756                     silc_net_get_error_string(status)));
1757     silc_server_connection_free(sconn);
1758     break;
1759
1760   default:
1761     SILC_LOG_ERROR(("Could not connect to %s:%d: %s",
1762                     sconn->remote_host, sconn->remote_port,
1763                     silc_net_get_error_string(status)));
1764     if (!sconn->no_reconnect) {
1765       silc_schedule_task_add_timeout(sconn->server->schedule,
1766                                      silc_server_connect_to_router_retry,
1767                                      sconn, 1, 0);
1768     } else {
1769       silc_server_connection_free(sconn);
1770     }
1771     break;
1772   }
1773 }
1774
1775 /* Generic routine to use connect to a router. */
1776
1777 SILC_TASK_CALLBACK(silc_server_connect_router)
1778 {
1779   SilcServerConnection sconn = context;
1780   SilcServer server = sconn->server;
1781   SilcServerConfigRouter *rconn;
1782
1783   silc_schedule_task_del_by_context(server->schedule, sconn);
1784
1785   /* Don't connect if we are shutting down. */
1786   if (server->server_shutdown) {
1787     silc_server_connection_free(sconn);
1788     return;
1789   }
1790
1791   SILC_LOG_INFO(("Connecting to the %s %s on port %d",
1792                  (sconn->backup ? "backup router" : "router"),
1793                  sconn->remote_host, sconn->remote_port));
1794
1795   if (!server->no_conf) {
1796     /* Find connection configuration */
1797     rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
1798                                                 sconn->remote_port);
1799     if (!rconn) {
1800       SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
1801                      (sconn->backup ? "backup router" : "router"),
1802                      sconn->remote_host, sconn->remote_port));
1803       silc_server_connection_free(sconn);
1804       return;
1805     }
1806     silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
1807   }
1808
1809   /* Connect to remote host */
1810   sconn->op =
1811     silc_net_tcp_connect((!server->config->server_info->primary ? NULL :
1812                           server->config->server_info->primary->server_ip),
1813                          sconn->remote_host, sconn->remote_port,
1814                          server->schedule, silc_server_connection_established,
1815                          sconn);
1816   if (!sconn->op) {
1817     SILC_LOG_ERROR(("Could not connect to router %s:%d",
1818                     sconn->remote_host, sconn->remote_port));
1819     silc_server_connection_free(sconn);
1820     return;
1821   }
1822
1823   /* Add to connection list */
1824   silc_dlist_add(server->conns, sconn);
1825 }
1826
1827 /* This function connects to our primary router or if we are a router this
1828    establishes all our primary routes. This is called at the start of the
1829    server to do authentication and key exchange with our router - called
1830    from schedule. */
1831
1832 SILC_TASK_CALLBACK(silc_server_connect_to_router)
1833 {
1834   SilcServer server = context;
1835   SilcServerConnection sconn;
1836   SilcServerConfigRouter *ptr;
1837
1838   /* Don't connect if we are shutting down. */
1839   if (server->server_shutdown)
1840     return;
1841
1842   SILC_LOG_DEBUG(("We are %s",
1843                   (server->server_type == SILC_SERVER ?
1844                    "normal server" : server->server_type == SILC_ROUTER ?
1845                    "router" : "backup router/normal server")));
1846
1847   /* XXX */
1848   if (!server->config->routers) {
1849     /* There wasn't a configured router, we will continue but we don't
1850        have a connection to outside world.  We will be standalone server. */
1851     SILC_LOG_DEBUG(("No router(s), we are standalone"));
1852     server->standalone = TRUE;
1853     return;
1854   }
1855
1856   /* Create the connections to all our routes */
1857   for (ptr = server->config->routers; ptr; ptr = ptr->next) {
1858
1859     SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
1860                     ptr->backup_router ? "Backup router" : "Router",
1861                     ptr->initiator ? "Initiator" : "Responder",
1862                     ptr->host, ptr->port));
1863
1864     if (server->server_type == SILC_ROUTER && ptr->backup_router &&
1865         ptr->initiator == FALSE && !server->backup_router &&
1866         !silc_server_config_get_backup_router(server))
1867       server->wait_backup = TRUE;
1868
1869     if (!ptr->initiator)
1870       continue;
1871
1872     /* Check whether we are connecting or connected to this host already */
1873     if (silc_server_num_sockets_by_remote(server,
1874                                           silc_net_is_ip(ptr->host) ?
1875                                           ptr->host : NULL,
1876                                           silc_net_is_ip(ptr->host) ?
1877                                           NULL : ptr->host, ptr->port)) {
1878       SILC_LOG_DEBUG(("We are already connected to %s:%d",
1879                       ptr->host, ptr->port));
1880
1881       /* If we don't have primary router and this connection is our
1882          primary router we are in desync.  Reconnect to the primary. */
1883       if (server->standalone && !server->router) {
1884         /* XXX */
1885         SilcPacketStream sock;
1886         SilcServerConfigRouter *primary =
1887           silc_server_config_get_primary_router(server);
1888         if (primary != ptr)
1889           continue;
1890         sock = silc_server_find_socket_by_host(server, SILC_CONN_ROUTER,
1891                                                ptr->host, ptr->port);
1892         if (!sock)
1893           continue;
1894         server->backup_noswitch = TRUE;
1895 #if 0
1896         if (sock->user_data)
1897           silc_server_free_sock_user_data(server, sock, NULL);
1898         silc_server_disconnect_remote(server, sock, 0, NULL);
1899 #endif /* 0 */
1900         server->backup_noswitch = FALSE;
1901         SILC_LOG_DEBUG(("Reconnecting to primary router"));
1902       } else {
1903         continue;
1904       }
1905     }
1906
1907     /* Allocate connection object for hold connection specific stuff. */
1908     sconn = silc_calloc(1, sizeof(*sconn));
1909     if (!sconn)
1910       continue;
1911     sconn->remote_host = strdup(ptr->host);
1912     sconn->remote_port = ptr->port;
1913     sconn->backup = ptr->backup_router;
1914     if (sconn->backup) {
1915       sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
1916       sconn->backup_replace_port = ptr->backup_replace_port;
1917     }
1918
1919     /* XXX */
1920     if (!server->router_conn && !sconn->backup)
1921       server->router_conn = sconn;
1922
1923     /* Connect */
1924     silc_server_connect_router(server->schedule, server, SILC_TASK_EXPIRE,
1925                                0, sconn);
1926   }
1927 }
1928
1929
1930 /************************ Accepting new connection **************************/
1931
1932 /* After this is called, server don't wait for backup router anymore.
1933    This gets called automatically even after we have backup router
1934    connection established. */
1935
1936 SILC_TASK_CALLBACK(silc_server_backup_router_wait)
1937 {
1938   SilcServer server = context;
1939   server->wait_backup = FALSE;
1940 }
1941
1942 /* Authentication data callback */
1943
1944 static SilcBool
1945 silc_server_accept_get_auth(SilcConnAuth connauth,
1946                             SilcConnectionType conn_type,
1947                             unsigned char **passphrase,
1948                             SilcUInt32 *passphrase_len,
1949                             SilcSKR *repository,
1950                             void *context)
1951 {
1952   SilcPacketStream sock = context;
1953   SilcUnknownEntry entry = silc_packet_get_context(sock);
1954   SilcServer server = entry->server;
1955
1956   SILC_LOG_DEBUG(("Remote connection type %d", conn_type));
1957
1958   /* Remote end is client */
1959   if (conn_type == SILC_CONN_CLIENT) {
1960     SilcServerConfigClient *cconfig = entry->cconfig.ref_ptr;
1961     if (!cconfig)
1962       return FALSE;
1963
1964     *passphrase = cconfig->passphrase;
1965     *passphrase_len = cconfig->passphrase_len;
1966     if (cconfig->publickeys)
1967       *repository = server->repository;
1968
1969     entry->data.conn_type = conn_type;
1970     return TRUE;
1971   }
1972
1973   /* Remote end is server */
1974   if (conn_type == SILC_CONN_SERVER) {
1975     SilcServerConfigServer *sconfig = entry->sconfig.ref_ptr;
1976     if (!sconfig)
1977       return FALSE;
1978
1979     *passphrase = sconfig->passphrase;
1980     *passphrase_len = sconfig->passphrase_len;
1981     if (sconfig->publickeys)
1982       *repository = server->repository;
1983
1984     entry->data.conn_type = conn_type;
1985     return TRUE;
1986   }
1987
1988   /* Remote end is router */
1989   if (conn_type == SILC_CONN_ROUTER) {
1990     SilcServerConfigRouter *rconfig = entry->rconfig.ref_ptr;
1991     if (!rconfig)
1992       return FALSE;
1993
1994     *passphrase = rconfig->passphrase;
1995     *passphrase_len = rconfig->passphrase_len;
1996     if (rconfig->publickeys)
1997       *repository = server->repository;
1998
1999     entry->data.conn_type = conn_type;
2000     return TRUE;
2001   }
2002
2003   return FALSE;
2004 }
2005
2006 /* Authentication completion callback. */
2007
2008 static void
2009 silc_server_accept_auth_compl(SilcConnAuth connauth, SilcBool success,
2010                               void *context)
2011 {
2012   SilcPacketStream sock = context;
2013   SilcUnknownEntry entry = silc_packet_get_context(sock);
2014   SilcIDListData idata = (SilcIDListData)entry;
2015   SilcServer server = entry->server;
2016   SilcServerConfigConnParams *param = &server->config->param;
2017   SilcServerConnection sconn;
2018   void *id_entry;
2019   const char *hostname;
2020   SilcUInt16 port;
2021
2022   silc_socket_stream_get_info(silc_packet_stream_get_stream(sock),
2023                               NULL, &hostname, NULL, &port);
2024
2025   if (success == FALSE) {
2026     /* Authentication failed */
2027     SILC_LOG_INFO(("Authentication failed for %s (%s) [%s]", entry->hostname,
2028                    entry->ip, SILC_CONNTYPE_STRING(entry->data.conn_type)));
2029     server->stat.auth_failures++;
2030     silc_server_disconnect_remote(server, sock,
2031                                   SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
2032     goto out;
2033   }
2034
2035   SILC_LOG_DEBUG(("Checking whether connection is allowed"));
2036
2037   switch (entry->data.conn_type) {
2038   case SILC_CONN_CLIENT:
2039     {
2040       SilcClientEntry client;
2041       SilcServerConfigClient *conn = entry->cconfig.ref_ptr;
2042
2043       /* Verify whether this connection is after all allowed to connect */
2044       if (!silc_server_connection_allowed(server, sock, entry->data.conn_type,
2045                                           &server->config->param,
2046                                           conn->param,
2047                                           silc_connauth_get_ske(connauth))) {
2048         server->stat.auth_failures++;
2049         goto out;
2050       }
2051
2052       /* If we are primary router and we have backup router configured
2053          but it has not connected to use yet, do not accept any other
2054          connection. */
2055       if (server->wait_backup && server->server_type == SILC_ROUTER &&
2056           !server->backup_router) {
2057         SilcServerConfigRouter *router;
2058         router = silc_server_config_get_backup_router(server);
2059         if (router && strcmp(server->config->server_info->primary->server_ip,
2060                              entry->ip) &&
2061             silc_server_find_socket_by_host(server,
2062                                             SILC_CONN_SERVER,
2063                                             router->backup_replace_ip, 0)) {
2064           SILC_LOG_INFO(("Will not accept connections because we do "
2065                          "not have backup router connection established"));
2066           silc_server_disconnect_remote(server, sock,
2067                                         SILC_STATUS_ERR_PERM_DENIED,
2068                                         "We do not have connection to backup "
2069                                         "router established, try later");
2070           server->stat.auth_failures++;
2071
2072           /* From here on, wait 20 seconds for the backup router to appear. */
2073           silc_schedule_task_add_timeout(server->schedule,
2074                                          silc_server_backup_router_wait,
2075                                          (void *)server, 20, 0);
2076           goto out;
2077         }
2078       }
2079
2080       SILC_LOG_DEBUG(("Remote host is client"));
2081       SILC_LOG_INFO(("Connection %s (%s) is client", entry->hostname,
2082                      entry->ip));
2083
2084       /* Add the client to the client ID cache. The nickname and Client ID
2085          and other information is created after we have received NEW_CLIENT
2086          packet from client. */
2087       client = silc_idlist_add_client(server->local_list,
2088                                       NULL, NULL, NULL, NULL, NULL, sock);
2089       if (!client) {
2090         SILC_LOG_ERROR(("Could not add new client to cache"));
2091         server->stat.auth_failures++;
2092         silc_server_disconnect_remote(server, sock,
2093                                       SILC_STATUS_ERR_AUTH_FAILED, NULL);
2094         goto out;
2095       }
2096       entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
2097
2098       /* Statistics */
2099       server->stat.my_clients++;
2100       server->stat.clients++;
2101       server->stat.cell_clients++;
2102
2103       /* Get connection parameters */
2104       if (conn->param) {
2105         param = conn->param;
2106
2107         if (!param->keepalive_secs)
2108           param->keepalive_secs = server->config->param.keepalive_secs;
2109
2110         if (!param->qos && server->config->param.qos) {
2111           param->qos = server->config->param.qos;
2112           param->qos_rate_limit = server->config->param.qos_rate_limit;
2113           param->qos_bytes_limit = server->config->param.qos_bytes_limit;
2114           param->qos_limit_sec = server->config->param.qos_limit_sec;
2115           param->qos_limit_usec = server->config->param.qos_limit_usec;
2116         }
2117
2118         /* Check if to be anonymous connection */
2119         if (param->anonymous)
2120           client->mode |= SILC_UMODE_ANONYMOUS;
2121       }
2122
2123       /* Add public key to repository */
2124       if (!silc_server_get_public_key_by_client(server, client, NULL))
2125         silc_skr_add_public_key_simple(server->repository,
2126                                        entry->data.public_key,
2127                                        SILC_SKR_USAGE_IDENTIFICATION, client,
2128                                        NULL);
2129
2130       id_entry = (void *)client;
2131       break;
2132     }
2133
2134   case SILC_CONN_SERVER:
2135   case SILC_CONN_ROUTER:
2136     {
2137       SilcServerEntry new_server;
2138       SilcBool initiator = FALSE;
2139       SilcBool backup_local = FALSE;
2140       SilcBool backup_router = FALSE;
2141       char *backup_replace_ip = NULL;
2142       SilcUInt16 backup_replace_port = 0;
2143       SilcServerConfigServer *sconn = entry->sconfig.ref_ptr;
2144       SilcServerConfigRouter *rconn = entry->rconfig.ref_ptr;
2145
2146       /* If we are backup router and this is incoming server connection
2147          and we do not have connection to primary router, do not allow
2148          the connection. */
2149       if (server->server_type == SILC_BACKUP_ROUTER &&
2150           entry->data.conn_type == SILC_CONN_SERVER &&
2151           !SILC_PRIMARY_ROUTE(server)) {
2152         SILC_LOG_INFO(("Will not accept server connection because we do "
2153                        "not have primary router connection established"));
2154         silc_server_disconnect_remote(server, sock,
2155                                       SILC_STATUS_ERR_PERM_DENIED,
2156                                       "We do not have connection to primary "
2157                                       "router established, try later");
2158         server->stat.auth_failures++;
2159         goto out;
2160       }
2161
2162       if (entry->data.conn_type == SILC_CONN_ROUTER) {
2163         /* Verify whether this connection is after all allowed to connect */
2164         if (!silc_server_connection_allowed(server, sock,
2165                                             entry->data.conn_type,
2166                                             &server->config->param,
2167                                             rconn ? rconn->param : NULL,
2168                                             silc_connauth_get_ske(connauth))) {
2169           server->stat.auth_failures++;
2170           goto out;
2171         }
2172
2173         if (rconn) {
2174           if (rconn->param) {
2175             param = rconn->param;
2176
2177             if (!param->keepalive_secs)
2178               param->keepalive_secs = server->config->param.keepalive_secs;
2179
2180             if (!param->qos && server->config->param.qos) {
2181               param->qos = server->config->param.qos;
2182               param->qos_rate_limit = server->config->param.qos_rate_limit;
2183               param->qos_bytes_limit = server->config->param.qos_bytes_limit;
2184               param->qos_limit_sec = server->config->param.qos_limit_sec;
2185               param->qos_limit_usec = server->config->param.qos_limit_usec;
2186             }
2187           }
2188
2189           initiator = rconn->initiator;
2190           backup_local = rconn->backup_local;
2191           backup_router = rconn->backup_router;
2192           backup_replace_ip = rconn->backup_replace_ip;
2193           backup_replace_port = rconn->backup_replace_port;
2194         }
2195       }
2196
2197       if (entry->data.conn_type == SILC_CONN_SERVER) {
2198         /* Verify whether this connection is after all allowed to connect */
2199         if (!silc_server_connection_allowed(server, sock,
2200                                             entry->data.conn_type,
2201                                             &server->config->param,
2202                                             sconn ? sconn->param : NULL,
2203                                             silc_connauth_get_ske(connauth))) {
2204           server->stat.auth_failures++;
2205           goto out;
2206         }
2207         if (sconn) {
2208           if (sconn->param) {
2209             param = sconn->param;
2210
2211             if (!param->keepalive_secs)
2212               param->keepalive_secs = server->config->param.keepalive_secs;
2213
2214             if (!param->qos && server->config->param.qos) {
2215               param->qos = server->config->param.qos;
2216               param->qos_rate_limit = server->config->param.qos_rate_limit;
2217               param->qos_bytes_limit = server->config->param.qos_bytes_limit;
2218               param->qos_limit_sec = server->config->param.qos_limit_sec;
2219               param->qos_limit_usec = server->config->param.qos_limit_usec;
2220             }
2221           }
2222
2223           backup_router = sconn->backup_router;
2224         }
2225       }
2226
2227       /* If we are primary router and we have backup router configured
2228          but it has not connected to use yet, do not accept any other
2229          connection. */
2230 #if 0
2231       if (server->wait_backup && server->server_type == SILC_ROUTER &&
2232           !server->backup_router && !backup_router) {
2233         SilcServerConfigRouter *router;
2234         router = silc_server_config_get_backup_router(server);
2235         if (router && strcmp(server->config->server_info->primary->server_ip,
2236                              ip) &&
2237             silc_server_find_socket_by_host(server,
2238                                             SILC_CONN_SERVER,
2239                                             router->backup_replace_ip, 0)) {
2240           SILC_LOG_INFO(("Will not accept connections because we do "
2241                          "not have backup router connection established"));
2242           silc_server_disconnect_remote(server, sock,
2243                                         SILC_STATUS_ERR_PERM_DENIED,
2244                                         "We do not have connection to backup "
2245                                         "router established, try later");
2246           server->stat.auth_failures++;
2247
2248           /* From here on, wait 20 seconds for the backup router to appear. */
2249           silc_schedule_task_add_timeout(server->schedule,
2250                                          silc_server_backup_router_wait,
2251                                          (void *)server, 20, 0);
2252           goto out;
2253         }
2254       }
2255 #endif /* 0 */
2256
2257       SILC_LOG_DEBUG(("Remote host is %s",
2258                       entry->data.conn_type == SILC_CONN_SERVER ?
2259                       "server" : (backup_router ?
2260                                   "backup router" : "router")));
2261       SILC_LOG_INFO(("Connection %s (%s) is %s", entry->hostname,
2262                      entry->ip, entry->data.conn_type == SILC_CONN_SERVER ?
2263                      "server" : (backup_router ?
2264                                  "backup router" : "router")));
2265
2266       /* Add the server into server cache. The server name and Server ID
2267          is updated after we have received NEW_SERVER packet from the
2268          server. We mark ourselves as router for this server if we really
2269          are router. */
2270       new_server =
2271         silc_idlist_add_server((entry->data.conn_type == SILC_CONN_SERVER ?
2272                                 server->local_list : (backup_router ?
2273                                                       server->local_list :
2274                                                       server->global_list)),
2275                                NULL,
2276                                (entry->data.conn_type == SILC_CONN_SERVER ?
2277                                 SILC_SERVER : SILC_ROUTER),
2278                                NULL,
2279                                (entry->data.conn_type == SILC_CONN_SERVER ?
2280                                 server->id_entry : (backup_router ?
2281                                                     server->id_entry : NULL)),
2282                                sock);
2283       if (!new_server) {
2284         SILC_LOG_ERROR(("Could not add new server to cache"));
2285         silc_server_disconnect_remote(server, sock,
2286                                       SILC_STATUS_ERR_AUTH_FAILED, NULL);
2287         server->stat.auth_failures++;
2288         goto out;
2289       }
2290       entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
2291
2292       id_entry = (void *)new_server;
2293
2294       /* If the incoming connection is router and marked as backup router
2295          then add it to be one of our backups */
2296       if (entry->data.conn_type == SILC_CONN_ROUTER && backup_router) {
2297         /* Change it back to SERVER type since that's what it really is. */
2298         if (backup_local)
2299           entry->data.conn_type = SILC_CONN_SERVER;
2300         new_server->server_type = SILC_BACKUP_ROUTER;
2301
2302         SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
2303                                ("Backup router %s is now online",
2304                                 entry->hostname));
2305
2306         /* Remove the backup waiting with timeout */
2307         silc_schedule_task_add_timeout(server->schedule,
2308                                        silc_server_backup_router_wait,
2309                                        (void *)server, 10, 0);
2310       }
2311
2312       /* Statistics */
2313       if (entry->data.conn_type == SILC_CONN_SERVER) {
2314         server->stat.my_servers++;
2315         server->stat.servers++;
2316       } else {
2317         server->stat.my_routers++;
2318         server->stat.routers++;
2319       }
2320
2321       /* Check whether this connection is to be our primary router connection
2322          if we do not already have the primary route. */
2323       if (!backup_router &&
2324           server->standalone && entry->data.conn_type == SILC_CONN_ROUTER) {
2325         if (silc_server_config_is_primary_route(server) && !initiator)
2326           break;
2327
2328         SILC_LOG_DEBUG(("We are not standalone server anymore"));
2329         server->standalone = FALSE;
2330         if (!server->id_entry->router) {
2331           server->id_entry->router = id_entry;
2332           server->router = id_entry;
2333         }
2334       }
2335
2336       break;
2337     }
2338
2339   default:
2340     goto out;
2341     break;
2342   }
2343
2344   /* Add connection to server->conns so that we know we have connection
2345      to this peer. */
2346   sconn = silc_calloc(1, sizeof(*sconn));
2347   sconn->server = server;
2348   sconn->sock = sock;
2349   sconn->remote_host = strdup(hostname);
2350   sconn->remote_port = port;
2351   silc_dlist_add(server->conns, sconn);
2352   idata->sconn = sconn;
2353   idata->last_receive = time(NULL);
2354
2355   /* Add the common data structure to the ID entry. */
2356   silc_idlist_add_data(id_entry, (SilcIDListData)entry);
2357   silc_packet_set_context(sock, id_entry);
2358
2359   /* Connection has been fully established now. Everything is ok. */
2360   SILC_LOG_DEBUG(("New connection authenticated"));
2361
2362 #if 0
2363   /* Perform keepalive. */
2364   if (param->keepalive_secs)
2365     silc_socket_set_heartbeat(sock, param->keepalive_secs, server,
2366                               silc_server_perform_heartbeat,
2367                               server->schedule);
2368 #endif
2369
2370   /* Perform Quality of Service */
2371   if (param->qos)
2372     silc_socket_stream_set_qos(silc_packet_stream_get_stream(sock),
2373                                param->qos_rate_limit, param->qos_bytes_limit,
2374                                param->qos_limit_sec, param->qos_limit_usec);
2375
2376   silc_server_config_unref(&entry->cconfig);
2377   silc_server_config_unref(&entry->sconfig);
2378   silc_server_config_unref(&entry->rconfig);
2379   silc_free(entry);
2380
2381  out:
2382   silc_ske_free(silc_connauth_get_ske(connauth));
2383   silc_connauth_free(connauth);
2384 }
2385
2386 /* SKE completion callback.  We set the new keys into use here. */
2387
2388 static void
2389 silc_server_accept_completed(SilcSKE ske, SilcSKEStatus status,
2390                              SilcSKESecurityProperties prop,
2391                              SilcSKEKeyMaterial keymat,
2392                              SilcSKERekeyMaterial rekey,
2393                              void *context)
2394 {
2395   SilcPacketStream sock = context;
2396   SilcUnknownEntry entry = silc_packet_get_context(sock);
2397   SilcIDListData idata = (SilcIDListData)entry;
2398   SilcServer server = entry->server;
2399   SilcConnAuth connauth;
2400   SilcCipher send_key, receive_key;
2401   SilcHmac hmac_send, hmac_receive;
2402   SilcHash hash;
2403
2404   if (status != SILC_SKE_STATUS_OK) {
2405     /* SKE failed */
2406     SILC_LOG_ERROR(("Error (%s) during Key Exchange protocol with %s (%s)",
2407                     silc_ske_map_status(status), entry->hostname, entry->ip));
2408     silc_ske_free(ske);
2409     silc_server_disconnect_remote(server, sock,
2410                                   SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
2411     return;
2412   }
2413
2414   SILC_LOG_DEBUG(("Setting keys into use"));
2415
2416   /* Set the keys into use.  The data will be encrypted after this. */
2417   if (!silc_ske_set_keys(ske, keymat, prop, &send_key, &receive_key,
2418                          &hmac_send, &hmac_receive, &hash)) {
2419     /* Error setting keys */
2420     silc_ske_free(ske);
2421     silc_server_disconnect_remote(server, sock,
2422                                   SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
2423     return;
2424   }
2425   silc_packet_set_keys(sock, send_key, receive_key, hmac_send,
2426                        hmac_receive, FALSE);
2427
2428   idata->rekey = rekey;
2429   idata->public_key = silc_pkcs_public_key_copy(prop->public_key);
2430
2431   SILC_LOG_DEBUG(("Starting connection authentication"));
2432   server->stat.auth_attempts++;
2433
2434   connauth = silc_connauth_alloc(server->schedule, ske,
2435                                  server->config->conn_auth_timeout);
2436   if (!connauth) {
2437     /** Error allocating auth protocol */
2438     silc_ske_free(ske);
2439     silc_server_disconnect_remote(server, sock,
2440                                   SILC_STATUS_ERR_RESOURCE_LIMIT, NULL);
2441     return;
2442   }
2443
2444   /* Start connection authentication */
2445   silc_connauth_responder(connauth, silc_server_accept_get_auth,
2446                           silc_server_accept_auth_compl, sock);
2447 }
2448
2449 /* Accept new TCP connection */
2450
2451 static void silc_server_accept_new_connection(SilcNetStatus status,
2452                                               SilcStream stream,
2453                                               void *context)
2454 {
2455   SilcServer server = context;
2456   SilcPacketStream packet_stream;
2457   SilcServerConfigClient *cconfig = NULL;
2458   SilcServerConfigServer *sconfig = NULL;
2459   SilcServerConfigRouter *rconfig = NULL;
2460   SilcServerConfigDeny *deny;
2461   SilcUnknownEntry entry;
2462   SilcSKE ske;
2463   SilcSKEParamsStruct params;
2464   char *hostname, *ip;
2465   SilcUInt16 port;
2466
2467   SILC_LOG_DEBUG(("Accepting new connection"));
2468
2469   /* Check for maximum allowed connections */
2470   server->stat.conn_attempts++;
2471   if (silc_dlist_count(server->conns) >
2472       server->config->param.connections_max) {
2473     SILC_LOG_ERROR(("Refusing connection, server is full"));
2474     server->stat.conn_failures++;
2475     silc_stream_destroy(stream);
2476     return;
2477   }
2478
2479   /* Get hostname, IP and port */
2480   if (!silc_socket_stream_get_info(stream, NULL, (const char **)&hostname,
2481                                    (const char **)&ip, &port)) {
2482     /* Bad socket stream */
2483     server->stat.conn_failures++;
2484     silc_stream_destroy(stream);
2485     return;
2486   }
2487
2488   /* Create packet stream */
2489   packet_stream = silc_packet_stream_create(server->packet_engine,
2490                                             server->schedule, stream);
2491   if (!packet_stream) {
2492     SILC_LOG_ERROR(("Refusing connection, cannot create packet stream"));
2493     server->stat.conn_failures++;
2494     silc_stream_destroy(stream);
2495     return;
2496   }
2497   server->stat.conn_num++;
2498
2499   /* Set source ID to packet stream */
2500   if (!silc_packet_set_ids(packet_stream, SILC_ID_SERVER, server->id,
2501                            0, NULL)) {
2502     /* Out of memory */
2503     server->stat.conn_failures++;
2504     silc_packet_stream_destroy(packet_stream);
2505     return;
2506   }
2507
2508   /* Check whether this connection is denied to connect to us. */
2509   deny = silc_server_config_find_denied(server, ip);
2510   if (!deny)
2511     deny = silc_server_config_find_denied(server, hostname);
2512   if (deny) {
2513     /* The connection is denied */
2514     SILC_LOG_INFO(("Connection %s (%s) is denied", hostname, ip));
2515     silc_server_disconnect_remote(server, packet_stream,
2516                                   SILC_STATUS_ERR_BANNED_FROM_SERVER,
2517                                   deny->reason);
2518     return;
2519   }
2520
2521   /* Check whether we have configured this sort of connection at all. We
2522      have to check all configurations since we don't know what type of
2523      connection this is. */
2524   if (!(cconfig = silc_server_config_find_client(server, ip)))
2525     cconfig = silc_server_config_find_client(server, hostname);
2526   if (!(sconfig = silc_server_config_find_server_conn(server, ip)))
2527     sconfig = silc_server_config_find_server_conn(server, hostname);
2528   if (server->server_type == SILC_ROUTER)
2529     if (!(rconfig = silc_server_config_find_router_conn(server, ip, port)))
2530       rconfig = silc_server_config_find_router_conn(server, hostname, port);
2531   if (!cconfig && !sconfig && !rconfig) {
2532     SILC_LOG_INFO(("Connection %s (%s) is not allowed", hostname, ip));
2533     server->stat.conn_failures++;
2534     silc_server_disconnect_remote(server, packet_stream,
2535                                   SILC_STATUS_ERR_BANNED_FROM_SERVER, NULL);
2536     return;
2537   }
2538
2539   /* The connection is allowed */
2540   entry = silc_calloc(1, sizeof(*entry));
2541   if (!entry) {
2542     server->stat.conn_failures++;
2543     silc_server_disconnect_remote(server, packet_stream,
2544                                   SILC_STATUS_ERR_RESOURCE_LIMIT, NULL);
2545     return;
2546   }
2547   entry->hostname = hostname;
2548   entry->ip = ip;
2549   entry->port = port;
2550   entry->server = server;
2551   silc_packet_set_context(packet_stream, entry);
2552
2553   silc_server_config_ref(&entry->cconfig, server->config, cconfig);
2554   silc_server_config_ref(&entry->sconfig, server->config, sconfig);
2555   silc_server_config_ref(&entry->rconfig, server->config, rconfig);
2556
2557   /* Take flags for key exchange. Since we do not know what type of connection
2558      this is, we go through all found configurations and use the global ones
2559      as well. This will result always into strictest key exchange flags. */
2560   memset(&params, 0, sizeof(params));
2561   SILC_GET_SKE_FLAGS(cconfig, params.flags);
2562   SILC_GET_SKE_FLAGS(sconfig, params.flags);
2563   SILC_GET_SKE_FLAGS(rconfig, params.flags);
2564   if (server->config->param.key_exchange_pfs)
2565     params.flags |= SILC_SKE_SP_FLAG_PFS;
2566
2567   SILC_LOG_INFO(("Incoming connection %s (%s)", hostname, ip));
2568   server->stat.conn_attempts++;
2569
2570   /* Start SILC Key Exchange protocol */
2571   SILC_LOG_DEBUG(("Starting key exchange protocol"));
2572   ske = silc_ske_alloc(server->rng, server->schedule, server->repository,
2573                        server->public_key, server->private_key,
2574                        packet_stream);
2575   if (!ske) {
2576     server->stat.conn_failures++;
2577     silc_server_disconnect_remote(server, packet_stream,
2578                                   SILC_STATUS_ERR_RESOURCE_LIMIT, NULL);
2579     return;
2580   }
2581   silc_ske_set_callbacks(ske, silc_server_verify_key,
2582                          silc_server_accept_completed, packet_stream);
2583
2584   /* Start key exchange protocol */
2585   params.version = silc_version_string;
2586   params.timeout_secs = server->config->key_exchange_timeout;
2587   silc_ske_responder(ske, packet_stream, &params);
2588 }
2589
2590
2591 /********************************** Rekey ***********************************/
2592
2593 /* Initiator rekey completion callback */
2594
2595 static void silc_server_rekey_completion(SilcSKE ske,
2596                                          SilcSKEStatus status,
2597                                          const SilcSKESecurityProperties prop,
2598                                          const SilcSKEKeyMaterial keymat,
2599                                          SilcSKERekeyMaterial rekey,
2600                                          void *context)
2601 {
2602   SilcPacketStream sock = context;
2603   SilcIDListData idata = silc_packet_get_context(sock);
2604   SilcServer server = idata->sconn->server;
2605
2606   idata->sconn->op = NULL;
2607   if (status != SILC_SKE_STATUS_OK) {
2608     SILC_LOG_ERROR(("Error during rekey protocol with %s",
2609                     idata->sconn->remote_host));
2610     return;
2611   }
2612
2613   SILC_LOG_DEBUG(("Rekey protocol completed with %s:%d [%s]",
2614                   idata->sconn->remote_host, idata->sconn->remote_port,
2615                   SILC_CONNTYPE_STRING(idata->conn_type)));
2616
2617   /* Save rekey data for next rekey */
2618   idata->rekey = rekey;
2619
2620   /* Register new rekey timeout */
2621   silc_schedule_task_add_timeout(server->schedule, silc_server_do_rekey,
2622                                  sock, idata->sconn->rekey_timeout, 0);
2623 }
2624
2625 /* Rekey callback.  Start rekey as initiator */
2626
2627 SILC_TASK_CALLBACK(silc_server_do_rekey)
2628 {
2629   SilcServer server = app_context;
2630   SilcPacketStream sock = context;
2631   SilcIDListData idata = silc_packet_get_context(sock);
2632   SilcSKE ske;
2633
2634   /* Do not execute rekey with disabled connections */
2635   if (idata->status & SILC_IDLIST_STATUS_DISABLED)
2636     return;
2637
2638   /* If another protocol is active do not start rekey */
2639   if (idata->sconn->op) {
2640     SILC_LOG_DEBUG(("Waiting for other protocol to finish before rekeying"));
2641     silc_schedule_task_add_timeout(server->schedule, silc_server_do_rekey,
2642                                    sock, 60, 0);
2643     return;
2644   }
2645
2646   SILC_LOG_DEBUG(("Executing rekey protocol with %s:%d [%s]",
2647                   idata->sconn->remote_host, idata->sconn->remote_port,
2648                   SILC_CONNTYPE_STRING(idata->conn_type)));
2649
2650   /* Allocate SKE */
2651   ske = silc_ske_alloc(server->rng, server->schedule, server->repository,
2652                        server->public_key, server->private_key, sock);
2653   if (!ske)
2654     return;
2655
2656   /* Set SKE callbacks */
2657   silc_ske_set_callbacks(ske, NULL, silc_server_rekey_completion, sock);
2658
2659   /* Perform rekey */
2660   idata->sconn->op = silc_ske_rekey_initiator(ske, sock, idata->rekey);
2661 }
2662
2663 /* Responder rekey completion callback */
2664
2665 static void
2666 silc_server_rekey_resp_completion(SilcSKE ske,
2667                                   SilcSKEStatus status,
2668                                   const SilcSKESecurityProperties prop,
2669                                   const SilcSKEKeyMaterial keymat,
2670                                   SilcSKERekeyMaterial rekey,
2671                                   void *context)
2672 {
2673   SilcPacketStream sock = context;
2674   SilcIDListData idata = silc_packet_get_context(sock);
2675
2676   idata->sconn->op = NULL;
2677   if (status != SILC_SKE_STATUS_OK) {
2678     SILC_LOG_ERROR(("Error during rekey protocol with %s",
2679                     idata->sconn->remote_host));
2680     return;
2681   }
2682
2683   SILC_LOG_DEBUG(("Rekey protocol completed with %s:%d [%s]",
2684                   idata->sconn->remote_host, idata->sconn->remote_port,
2685                   SILC_CONNTYPE_STRING(idata->conn_type)));
2686
2687   /* Save rekey data for next rekey */
2688   idata->rekey = rekey;
2689 }
2690
2691 /* Start rekey as responder */
2692
2693 static void silc_server_rekey(SilcServer server, SilcPacketStream sock,
2694                               SilcPacket packet)
2695 {
2696   SilcIDListData idata = silc_packet_get_context(sock);
2697   SilcSKE ske;
2698
2699   SILC_LOG_DEBUG(("Executing rekey protocol with %s:%d [%s]",
2700                   idata->sconn->remote_host, idata->sconn->remote_port,
2701                   SILC_CONNTYPE_STRING(idata->conn_type)));
2702
2703   /* Allocate SKE */
2704   ske = silc_ske_alloc(server->rng, server->schedule, server->repository,
2705                        server->public_key, server->private_key, sock);
2706   if (!ske) {
2707     silc_packet_free(packet);
2708     return;
2709   }
2710
2711   /* Set SKE callbacks */
2712   silc_ske_set_callbacks(ske, NULL, silc_server_rekey_resp_completion, sock);
2713
2714   /* Perform rekey */
2715   idata->sconn->op = silc_ske_rekey_responder(ske, sock, idata->rekey,
2716                                               packet);
2717 }
2718
2719
2720 /****************************** Disconnection *******************************/
2721
2722 /* Destroys packet stream. */
2723
2724 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2725 {
2726   silc_packet_stream_destroy(context);
2727 }
2728
2729 /* Closes connection to socket connection */
2730
2731 void silc_server_close_connection(SilcServer server,
2732                                   SilcPacketStream sock)
2733 {
2734   SilcIDListData idata = silc_packet_get_context(sock);
2735   char tmp[128];
2736   const char *hostname;
2737   SilcUInt16 port;
2738
2739 #if 0
2740   /* If any protocol is active cancel its execution. It will call
2741      the final callback which will finalize the disconnection. */
2742   if (sock->protocol && sock->protocol->protocol &&
2743       sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
2744     SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
2745     silc_protocol_cancel(sock->protocol, server->schedule);
2746     sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2747     silc_protocol_execute_final(sock->protocol, server->schedule);
2748     sock->protocol = NULL;
2749     return;
2750   }
2751 #endif
2752
2753   memset(tmp, 0, sizeof(tmp));
2754   //  silc_socket_get_error(sock, tmp, sizeof(tmp));
2755   silc_socket_stream_get_info(silc_packet_stream_get_stream(sock),
2756                               NULL, &hostname, NULL, &port);
2757   SILC_LOG_INFO(("Closing connection %s:%d [%s] %s", hostname, port,
2758                  idata ? SILC_CONNTYPE_STRING(idata->conn_type) : "",
2759                  tmp[0] ? tmp : ""));
2760
2761   //  silc_socket_set_qos(sock, 0, 0, 0, 0, NULL);
2762
2763   /* Close connection with timeout */
2764   server->stat.conn_num--;
2765   silc_schedule_task_add_timeout(server->schedule,
2766                                  silc_server_close_connection_final,
2767                                  sock, 0, 1);
2768 }
2769
2770 /* Sends disconnect message to remote connection and disconnects the
2771    connection. */
2772
2773 void silc_server_disconnect_remote(SilcServer server,
2774                                    SilcPacketStream sock,
2775                                    SilcStatus status, ...)
2776 {
2777   unsigned char buf[512];
2778   va_list ap;
2779   char *cp;
2780
2781   if (!sock)
2782     return;
2783
2784   SILC_LOG_DEBUG(("Disconnecting remote host"));
2785
2786   va_start(ap, status);
2787   cp = va_arg(ap, char *);
2788   if (cp)
2789     silc_vsnprintf(buf, sizeof(buf), cp, ap);
2790   va_end(ap);
2791
2792   /* Send SILC_PACKET_DISCONNECT */
2793   silc_packet_send_va(sock, SILC_PACKET_DISCONNECT, 0,
2794                       SILC_STR_UI_CHAR(status),
2795                       SILC_STR_UI8_STRING(cp ? buf : NULL),
2796                       SILC_STR_END);
2797
2798   /* Close connection */
2799   silc_server_close_connection(server, sock);
2800 }
2801
2802 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2803 {
2804   SilcClientEntry client = context;
2805
2806   assert(!silc_hash_table_count(client->channels));
2807
2808   silc_idlist_del_data(client);
2809   //  silc_idcache_purge_by_context(server->local_list->clients, client);
2810 }
2811
2812 /* Frees client data and notifies about client's signoff. */
2813
2814 void silc_server_free_client_data(SilcServer server,
2815                                   SilcPacketStream sock,
2816                                   SilcClientEntry client,
2817                                   int notify,
2818                                   const char *signoff)
2819 {
2820   SILC_LOG_DEBUG(("Freeing client data"));
2821
2822   if (client->id) {
2823     /* Check if anyone is watching this nickname */
2824     if (server->server_type == SILC_ROUTER)
2825       silc_server_check_watcher_list(server, client, NULL,
2826                                      SILC_NOTIFY_TYPE_SIGNOFF);
2827
2828     /* Send SIGNOFF notify to routers. */
2829     if (notify)
2830       silc_server_send_notify_signoff(server, SILC_PRIMARY_ROUTE(server),
2831                                       SILC_BROADCAST(server), client->id,
2832                                       signoff);
2833   }
2834
2835   /* Remove client from all channels */
2836   if (notify)
2837     silc_server_remove_from_channels(server, NULL, client,
2838                                      TRUE, (char *)signoff, TRUE, FALSE);
2839   else
2840     silc_server_remove_from_channels(server, NULL, client,
2841                                      FALSE, NULL, FALSE, FALSE);
2842
2843   /* Remove this client from watcher list if it is */
2844   silc_server_del_from_watcher_list(server, client);
2845
2846   /* Remove client's public key from repository, this will free it too. */
2847   if (client->data.public_key) {
2848     silc_skr_del_public_key(server->repository, client->data.public_key,
2849                             client);
2850     client->data.public_key = NULL;
2851   }
2852
2853   /* Update statistics */
2854   server->stat.my_clients--;
2855   server->stat.clients--;
2856   if (server->stat.cell_clients)
2857     server->stat.cell_clients--;
2858   SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2859   SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2860   silc_schedule_task_del_by_context(server->schedule, client);
2861
2862   /* We will not delete the client entry right away. We will take it
2863      into history (for WHOWAS command) for 5 minutes, unless we're
2864      shutting down server. */
2865   if (!server->server_shutdown) {
2866     silc_schedule_task_add_timeout(server->schedule,
2867                                    silc_server_free_client_data_timeout,
2868                                    client, 600, 0);
2869     client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2870     client->data.status &= ~SILC_IDLIST_STATUS_LOCAL;
2871     client->mode = 0;
2872     client->router = NULL;
2873     client->connection = NULL;
2874   } else {
2875     /* Delete directly since we're shutting down server */
2876     silc_idlist_del_data(client);
2877     silc_idlist_del_client(server->local_list, client);
2878   }
2879 }
2880
2881 /* Frees user_data pointer from socket connection object. This also sends
2882    appropriate notify packets to the network to inform about leaving
2883    entities. */
2884
2885 void silc_server_free_sock_user_data(SilcServer server,
2886                                      SilcPacketStream sock,
2887                                      const char *signoff_message)
2888 {
2889   SilcIDListData idata = silc_packet_get_context(sock);
2890
2891   if (!idata)
2892     return;
2893
2894   switch (idata->conn_type) {
2895   case SILC_CONN_CLIENT:
2896     {
2897       SilcClientEntry client_entry = (SilcClientEntry)idata;
2898       silc_server_free_client_data(server, sock, client_entry, TRUE,
2899                                    signoff_message);
2900       silc_packet_set_context(sock, NULL);
2901       break;
2902     }
2903
2904   case SILC_CONN_SERVER:
2905   case SILC_CONN_ROUTER:
2906     {
2907       SilcServerEntry user_data = (SilcServerEntry)idata;
2908       SilcServerEntry backup_router = NULL;
2909
2910       SILC_LOG_DEBUG(("Freeing server data"));
2911
2912       if (user_data->id)
2913         backup_router = silc_server_backup_get(server, user_data->id);
2914
2915       if (!server->backup_router && server->server_type == SILC_ROUTER &&
2916           backup_router == server->id_entry &&
2917           idata->conn_type != SILC_CONN_ROUTER)
2918         backup_router = NULL;
2919
2920       if (server->server_shutdown || server->backup_noswitch)
2921         backup_router = NULL;
2922
2923       /* If this was our primary router connection then we're lost to
2924          the outside world. */
2925       if (server->router == user_data) {
2926         /* Check whether we have a backup router connection */
2927         if (!backup_router || backup_router == user_data) {
2928           if (!server->no_reconnect)
2929             silc_server_create_connections(server);
2930           server->id_entry->router = NULL;
2931           server->router = NULL;
2932           server->standalone = TRUE;
2933           server->backup_primary = FALSE;
2934           backup_router = NULL;
2935         } else {
2936           if (server->id_entry != backup_router) {
2937             SILC_LOG_INFO(("New primary router is backup router %s",
2938                            backup_router->server_name));
2939             server->id_entry->router = backup_router;
2940             server->router = backup_router;
2941             server->router_connect = time(0);
2942             server->backup_primary = TRUE;
2943             backup_router->data.status &= ~SILC_IDLIST_STATUS_DISABLED;
2944
2945             /* Send START_USE to backup router to indicate we have switched */
2946             silc_server_backup_send_start_use(server,
2947                                               backup_router->connection,
2948                                               FALSE);
2949           } else {
2950             SILC_LOG_INFO(("We are now new primary router in this cell"));
2951             server->id_entry->router = NULL;
2952             server->router = NULL;
2953             server->standalone = TRUE;
2954           }
2955
2956           /* We stop here to take a breath */
2957           sleep(2);
2958
2959 #if 0
2960           if (server->backup_router) {
2961             server->server_type = SILC_ROUTER;
2962
2963             /* We'll need to constantly try to reconnect to the primary
2964                router so that we'll see when it comes back online. */
2965             silc_server_backup_reconnect(server, sock->ip, sock->port,
2966                                          silc_server_backup_connected,
2967                                          NULL);
2968           }
2969 #endif /* 0 */
2970
2971           /* Mark this connection as replaced */
2972           silc_server_backup_replaced_add(server, user_data->id,
2973                                           backup_router);
2974         }
2975       } else if (backup_router) {
2976         SILC_LOG_INFO(("Enabling the use of backup router %s",
2977                        backup_router->server_name));
2978
2979         /* Mark this connection as replaced */
2980         silc_server_backup_replaced_add(server, user_data->id,
2981                                         backup_router);
2982       } else if (server->server_type == SILC_SERVER &&
2983                  idata->conn_type == SILC_CONN_ROUTER) {
2984         /* Reconnect to the router (backup) */
2985         if (!server->no_reconnect)
2986           silc_server_create_connections(server);
2987       }
2988
2989       if (user_data->server_name)
2990         SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
2991                                ("Server %s signoff", user_data->server_name));
2992
2993       if (!backup_router) {
2994         /* Remove all servers that are originated from this server, and
2995            remove the clients of those servers too. */
2996         silc_server_remove_servers_by_server(server, user_data, TRUE);
2997
2998 #if 0
2999         /* Remove the clients that this server owns as they will become
3000            invalid now too.  For backup router the server is actually
3001            coming from the primary router, so mark that as the owner
3002            of this entry. */
3003         if (server->server_type == SILC_BACKUP_ROUTER &&
3004             sock->type == SILC_CONN_SERVER)
3005           silc_server_remove_clients_by_server(server, server->router,
3006                                                user_data, TRUE);
3007         else
3008 #endif
3009           silc_server_remove_clients_by_server(server, user_data,
3010                                                user_data, TRUE);
3011
3012         /* Remove channels owned by this server */
3013         if (server->server_type == SILC_SERVER)
3014           silc_server_remove_channels_by_server(server, user_data);
3015       } else {
3016         /* Enable local server connections that may be disabled */
3017         silc_server_local_servers_toggle_enabled(server, TRUE);
3018
3019         /* Update the client entries of this server to the new backup
3020            router.  If we are the backup router we also resolve the real
3021            servers for the clients.  After updating is over this also
3022            removes the clients that this server explicitly owns. */
3023         silc_server_update_clients_by_server(server, user_data,
3024                                              backup_router, TRUE);
3025
3026         /* If we are router and just lost our primary router (now standlaone)
3027            we remove everything that was behind it, since we don't know
3028            any better. */
3029         if (server->server_type == SILC_ROUTER && server->standalone)
3030           /* Remove all servers that are originated from this server, and
3031              remove the clients of those servers too. */
3032           silc_server_remove_servers_by_server(server, user_data, TRUE);
3033
3034         /* Finally remove the clients that are explicitly owned by this
3035            server.  They go down with the server. */
3036         silc_server_remove_clients_by_server(server, user_data,
3037                                              user_data, TRUE);
3038
3039         /* Update our server cache to use the new backup router too. */
3040         silc_server_update_servers_by_server(server, user_data, backup_router);
3041         if (server->server_type == SILC_SERVER)
3042           silc_server_update_channels_by_server(server, user_data,
3043                                                 backup_router);
3044
3045         /* Send notify about primary router going down to local operators */
3046         if (server->backup_router)
3047           SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3048                                  SILC_NOTIFY_TYPE_NONE,
3049                                  ("%s switched to backup router %s "
3050                                   "(we are primary router now)",
3051                                   server->server_name, server->server_name));
3052         else if (server->router)
3053           SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3054                                  SILC_NOTIFY_TYPE_NONE,
3055                                  ("%s switched to backup router %s",
3056                                   server->server_name,
3057                                   server->router->server_name));
3058       }
3059       server->backup_noswitch = FALSE;
3060
3061       /* Free the server entry */
3062       silc_server_backup_del(server, user_data);
3063       silc_server_backup_replaced_del(server, user_data);
3064       silc_idlist_del_data(user_data);
3065       if (!silc_idlist_del_server(server->local_list, user_data))
3066         silc_idlist_del_server(server->global_list, user_data);
3067       if (idata->conn_type == SILC_CONN_SERVER) {
3068         server->stat.my_servers--;
3069         server->stat.servers--;
3070       } else {
3071         server->stat.my_routers--;
3072         server->stat.routers--;
3073       }
3074       if (server->server_type == SILC_ROUTER)
3075         server->stat.cell_servers--;
3076
3077       if (backup_router && backup_router != server->id_entry) {
3078         /* Announce all of our stuff that was created about 5 minutes ago.
3079            The backup router knows all the other stuff already. */
3080         if (server->server_type == SILC_ROUTER)
3081           silc_server_announce_servers(server, FALSE, time(0) - 300,
3082                                        backup_router->connection);
3083
3084         /* Announce our clients and channels to the router */
3085         silc_server_announce_clients(server, time(0) - 300,
3086                                      backup_router->connection);
3087         silc_server_announce_channels(server, time(0) - 300,
3088                                       backup_router->connection);
3089       }
3090
3091       silc_packet_set_context(sock, NULL);
3092       break;
3093     }
3094
3095   default:
3096     {
3097       SilcUnknownEntry entry = (SilcUnknownEntry)idata;
3098
3099       SILC_LOG_DEBUG(("Freeing unknown connection data"));
3100
3101       silc_idlist_del_data(idata);
3102       silc_free(entry);
3103       silc_packet_set_context(sock, NULL);
3104       break;
3105     }
3106   }
3107 }
3108
3109 /* Removes client from all channels it has joined. This is used when client
3110    connection is disconnected. If the client on a channel is last, the
3111    channel is removed as well. This sends the SIGNOFF notify types. */
3112
3113 void silc_server_remove_from_channels(SilcServer server,
3114                                       SilcPacketStream sock,
3115                                       SilcClientEntry client,
3116                                       SilcBool notify,
3117                                       const char *signoff_message,
3118                                       SilcBool keygen,
3119                                       SilcBool killed)
3120 {
3121   SilcChannelEntry channel;
3122   SilcChannelClientEntry chl;
3123   SilcHashTableList htl;
3124   SilcBuffer clidp = NULL;
3125
3126   if (!client)
3127     return;
3128
3129   if (notify && !client->id)
3130     notify = FALSE;
3131
3132   SILC_LOG_DEBUG(("Removing client %s from joined channels",
3133                   notify ? silc_id_render(client->id, SILC_ID_CLIENT) : ""));
3134
3135   if (notify) {
3136     clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3137     if (!clidp)
3138       notify = FALSE;
3139   }
3140
3141   /* Remove the client from all channels. The client is removed from
3142      the channels' user list. */
3143   silc_hash_table_list(client->channels, &htl);
3144   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3145     channel = chl->channel;
3146
3147     /* Remove channel if this is last client leaving the channel, unless
3148        the channel is permanent. */
3149     if (server->server_type != SILC_SERVER &&
3150         silc_hash_table_count(channel->user_list) < 2) {
3151       silc_server_channel_delete(server, channel);
3152       continue;
3153     }
3154
3155     silc_hash_table_del(client->channels, channel);
3156     silc_hash_table_del(channel->user_list, client);
3157     channel->user_count--;
3158
3159     /* If there is no global users on the channel anymore mark the channel
3160        as local channel. Do not check if the removed client is local client. */
3161     if (server->server_type == SILC_SERVER && channel->global_users &&
3162         chl->client->router && !silc_server_channel_has_global(channel))
3163       channel->global_users = FALSE;
3164
3165     memset(chl, 'A', sizeof(*chl));
3166     silc_free(chl);
3167
3168     /* Update statistics */
3169     if (SILC_IS_LOCAL(client))
3170       server->stat.my_chanclients--;
3171     if (server->server_type == SILC_ROUTER) {
3172       server->stat.cell_chanclients--;
3173       server->stat.chanclients--;
3174     }
3175
3176     /* If there is not at least one local user on the channel then we don't
3177        need the channel entry anymore, we can remove it safely, unless the
3178        channel is permanent channel */
3179     if (server->server_type == SILC_SERVER &&
3180         !silc_server_channel_has_local(channel)) {
3181       /* Notify about leaving client if this channel has global users. */
3182       if (notify && channel->global_users)
3183         silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3184                                            SILC_NOTIFY_TYPE_SIGNOFF,
3185                                            signoff_message ? 2 : 1,
3186                                            clidp->data, silc_buffer_len(clidp),
3187                                            signoff_message, signoff_message ?
3188                                            strlen(signoff_message) : 0);
3189
3190       silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3191       silc_server_channel_delete(server, channel);
3192       continue;
3193     }
3194
3195     /* Send notify to channel about client leaving SILC and channel too */
3196     if (notify)
3197       silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3198                                          SILC_NOTIFY_TYPE_SIGNOFF,
3199                                          signoff_message ? 2 : 1,
3200                                          clidp->data, silc_buffer_len(clidp),
3201                                          signoff_message, signoff_message ?
3202                                          strlen(signoff_message) : 0);
3203
3204     if (killed && clidp) {
3205       /* Remove the client from channel's invite list */
3206       if (channel->invite_list &&
3207           silc_hash_table_count(channel->invite_list)) {
3208         SilcBuffer ab;
3209         SilcArgumentPayload iargs;
3210         ab = silc_argument_payload_encode_one(NULL, clidp->data,
3211                                               silc_buffer_len(clidp), 3);
3212         iargs = silc_argument_payload_parse(ab->data, silc_buffer_len(ab), 1);
3213         silc_server_inviteban_process(server, channel->invite_list, 1, iargs);
3214         silc_buffer_free(ab);
3215         silc_argument_payload_free(iargs);
3216       }
3217     }
3218
3219     /* Don't create keys if we are shutting down */
3220     if (server->server_shutdown)
3221       continue;
3222
3223     /* Re-generate channel key if needed */
3224     if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3225       if (!silc_server_create_channel_key(server, channel, 0))
3226         continue;
3227
3228       /* Send the channel key to the channel. The key of course is not sent
3229          to the client who was removed from the channel. */
3230       silc_server_send_channel_key(server, client->connection, channel,
3231                                    server->server_type == SILC_ROUTER ?
3232                                    FALSE : !server->standalone);
3233     }
3234   }
3235
3236   silc_hash_table_list_reset(&htl);
3237   if (clidp)
3238     silc_buffer_free(clidp);
3239 }
3240
3241 /* Removes client from one channel. This is used for example when client
3242    calls LEAVE command to remove itself from the channel. Returns TRUE
3243    if channel still exists and FALSE if the channel is removed when
3244    last client leaves the channel. If `notify' is FALSE notify messages
3245    are not sent. */
3246
3247 SilcBool silc_server_remove_from_one_channel(SilcServer server,
3248                                          SilcPacketStream sock,
3249                                          SilcChannelEntry channel,
3250                                          SilcClientEntry client,
3251                                          SilcBool notify)
3252 {
3253   SilcChannelClientEntry chl;
3254   SilcBuffer clidp;
3255
3256   SILC_LOG_DEBUG(("Removing %s from channel %s",
3257                   silc_id_render(client->id, SILC_ID_CLIENT),
3258                   channel->channel_name));
3259
3260   /* Get the entry to the channel, if this client is not on the channel
3261      then return Ok. */
3262   if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
3263     return TRUE;
3264
3265   /* Remove channel if this is last client leaving the channel, unless
3266      the channel is permanent. */
3267   if (server->server_type != SILC_SERVER &&
3268       silc_hash_table_count(channel->user_list) < 2) {
3269     silc_server_channel_delete(server, channel);
3270     return FALSE;
3271   }
3272
3273   silc_hash_table_del(client->channels, channel);
3274   silc_hash_table_del(channel->user_list, client);
3275   channel->user_count--;
3276
3277   /* If there is no global users on the channel anymore mark the channel
3278      as local channel. Do not check if the client is local client. */
3279   if (server->server_type == SILC_SERVER && channel->global_users &&
3280       chl->client->router && !silc_server_channel_has_global(channel))
3281     channel->global_users = FALSE;
3282
3283   memset(chl, 'O', sizeof(*chl));
3284   silc_free(chl);
3285
3286   /* Update statistics */
3287   if (SILC_IS_LOCAL(client))
3288     server->stat.my_chanclients--;
3289   if (server->server_type == SILC_ROUTER) {
3290     server->stat.cell_chanclients--;
3291     server->stat.chanclients--;
3292   }
3293
3294   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3295   if (!clidp)
3296     notify = FALSE;
3297
3298   /* If there is not at least one local user on the channel then we don't
3299      need the channel entry anymore, we can remove it safely, unless the
3300      channel is permanent channel */
3301   if (server->server_type == SILC_SERVER &&
3302       !silc_server_channel_has_local(channel)) {
3303     /* Notify about leaving client if this channel has global users. */
3304     if (notify && channel->global_users)
3305       silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3306                                          SILC_NOTIFY_TYPE_LEAVE, 1,
3307                                          clidp->data, silc_buffer_len(clidp));
3308
3309     silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3310     silc_server_channel_delete(server, channel);
3311     silc_buffer_free(clidp);
3312     return FALSE;
3313   }
3314
3315   /* Send notify to channel about client leaving the channel */
3316   if (notify)
3317     silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3318                                        SILC_NOTIFY_TYPE_LEAVE, 1,
3319                                        clidp->data, silc_buffer_len(clidp));
3320
3321   silc_buffer_free(clidp);
3322   return TRUE;
3323 }
3324
3325 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
3326    function may be used only by router. In real SILC network all channels
3327    are created by routers thus this function is never used by normal
3328    server. */
3329
3330 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3331                                                 SilcServerID *router_id,
3332                                                 char *cipher,
3333                                                 char *hmac,
3334                                                 char *channel_name,
3335                                                 int broadcast)
3336 {
3337   SilcChannelID *channel_id;
3338   SilcChannelEntry entry;
3339   SilcCipher send_key, receive_key;
3340   SilcHmac newhmac;
3341
3342   SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3343
3344   if (!cipher)
3345     cipher = SILC_DEFAULT_CIPHER;
3346   if (!hmac)
3347     hmac = SILC_DEFAULT_HMAC;
3348
3349   /* Allocate cipher */
3350   if (!silc_cipher_alloc(cipher, &send_key))
3351     return NULL;
3352   if (!silc_cipher_alloc(cipher, &receive_key)) {
3353     silc_cipher_free(send_key);
3354     return NULL;
3355   }
3356
3357   /* Allocate hmac */
3358   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3359     silc_cipher_free(send_key);
3360     silc_cipher_free(receive_key);
3361     return NULL;
3362   }
3363
3364   channel_name = strdup(channel_name);
3365
3366   /* Create the channel ID */
3367   if (!silc_id_create_channel_id(server, router_id, server->rng,
3368                                  &channel_id)) {
3369     silc_free(channel_name);
3370     silc_cipher_free(send_key);
3371     silc_cipher_free(receive_key);
3372     silc_hmac_free(newhmac);
3373     return NULL;
3374   }
3375
3376   /* Create the channel */
3377   entry = silc_idlist_add_channel(server->local_list, channel_name,
3378                                   SILC_CHANNEL_MODE_NONE, channel_id,
3379                                   NULL, send_key, receive_key, newhmac);
3380   if (!entry) {
3381     silc_free(channel_name);
3382     silc_cipher_free(send_key);
3383     silc_cipher_free(receive_key);
3384     silc_hmac_free(newhmac);
3385     silc_free(channel_id);
3386     return NULL;
3387   }
3388
3389   entry->cipher = strdup(cipher);
3390   entry->hmac_name = strdup(hmac);
3391
3392   /* Now create the actual key material */
3393   if (!silc_server_create_channel_key(server, entry,
3394                                       silc_cipher_get_key_len(send_key) / 8)) {
3395     silc_idlist_del_channel(server->local_list, entry);
3396     return NULL;
3397   }
3398
3399   /* Notify other routers about the new channel. We send the packet
3400      to our primary route. */
3401   if (broadcast)
3402     silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3403                                  channel_name, entry->id,
3404                                  silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3405                                  entry->mode);
3406
3407   /* Distribute to backup routers */
3408   if (broadcast && server->server_type == SILC_ROUTER) {
3409     SilcBuffer packet;
3410     unsigned char cid[32];
3411     SilcUInt32 name_len = strlen(channel_name);
3412     SilcUInt32 id_len;
3413
3414     silc_id_id2str(entry->id, SILC_ID_CHANNEL, cid, sizeof(cid), &id_len);
3415     packet = silc_channel_payload_encode(channel_name, name_len,
3416                                          cid, id_len, entry->mode);
3417     silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3418                             packet->data, silc_buffer_len(packet), FALSE,
3419                             TRUE);
3420     silc_buffer_free(packet);
3421   }
3422
3423   server->stat.my_channels++;
3424   if (server->server_type == SILC_ROUTER) {
3425     server->stat.channels++;
3426     server->stat.cell_channels++;
3427     entry->users_resolved = TRUE;
3428   }
3429
3430   return entry;
3431 }
3432
3433 /* Same as above but creates the channel with Channel ID `channel_id. */
3434
3435 SilcChannelEntry
3436 silc_server_create_new_channel_with_id(SilcServer server,
3437                                        char *cipher,
3438                                        char *hmac,
3439                                        char *channel_name,
3440                                        SilcChannelID *channel_id,
3441                                        int broadcast)
3442 {
3443   SilcChannelEntry entry;
3444   SilcCipher send_key, receive_key;
3445   SilcHmac newhmac;
3446
3447   SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3448
3449   if (!cipher)
3450     cipher = SILC_DEFAULT_CIPHER;
3451   if (!hmac)
3452     hmac = SILC_DEFAULT_HMAC;
3453
3454   /* Allocate cipher */
3455   if (!silc_cipher_alloc(cipher, &send_key))
3456     return NULL;
3457   if (!silc_cipher_alloc(cipher, &receive_key)) {
3458     silc_cipher_free(send_key);
3459     return NULL;
3460   }
3461
3462   /* Allocate hmac */
3463   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3464     silc_cipher_free(send_key);
3465     silc_cipher_free(receive_key);
3466     return NULL;
3467   }
3468
3469   channel_name = strdup(channel_name);
3470
3471   /* Create the channel */
3472   entry = silc_idlist_add_channel(server->local_list, channel_name,
3473                                   SILC_CHANNEL_MODE_NONE, channel_id,
3474                                   NULL, send_key, receive_key, newhmac);
3475   if (!entry) {
3476     silc_cipher_free(send_key);
3477     silc_cipher_free(receive_key);
3478     silc_hmac_free(newhmac);
3479     silc_free(channel_name);
3480     return NULL;
3481   }
3482
3483   /* Now create the actual key material */
3484   if (!silc_server_create_channel_key(server, entry,
3485                                       silc_cipher_get_key_len(send_key) / 8)) {
3486     silc_idlist_del_channel(server->local_list, entry);
3487     return NULL;
3488   }
3489
3490   /* Notify other routers about the new channel. We send the packet
3491      to our primary route. */
3492   if (broadcast)
3493     silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3494                                  channel_name, entry->id,
3495                                  silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3496                                  entry->mode);
3497
3498   /* Distribute to backup routers */
3499   if (broadcast && server->server_type == SILC_ROUTER) {
3500     SilcBuffer packet;
3501     unsigned char cid[32];
3502     SilcUInt32 name_len = strlen(channel_name);
3503     SilcUInt32 id_len;
3504
3505     silc_id_id2str(entry->id, SILC_ID_CHANNEL, cid, sizeof(cid), &id_len);
3506     packet = silc_channel_payload_encode(channel_name, name_len,
3507                                          cid, id_len, entry->mode);
3508     silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3509                             packet->data, silc_buffer_len(packet), FALSE,
3510                             TRUE);
3511     silc_buffer_free(packet);
3512   }
3513
3514   server->stat.my_channels++;
3515   if (server->server_type == SILC_ROUTER) {
3516     server->stat.channels++;
3517     server->stat.cell_channels++;
3518     entry->users_resolved = TRUE;
3519   }
3520
3521   return entry;
3522 }
3523
3524 /* Channel's key re-key timeout callback. */
3525
3526 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3527 {
3528   SilcServer server = app_context;
3529   SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3530
3531   rekey->task = NULL;
3532
3533   /* Return now if we are shutting down */
3534   if (server->server_shutdown)
3535     return;
3536
3537   if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3538     return;
3539
3540   silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3541 }
3542
3543 /* Generates new channel key. This is used to create the initial channel key
3544    but also to re-generate new key for channel. If `key_len' is provided
3545    it is the bytes of the key length. */
3546
3547 SilcBool silc_server_create_channel_key(SilcServer server,
3548                                         SilcChannelEntry channel,
3549                                         SilcUInt32 key_len)
3550 {
3551   int i;
3552   unsigned char channel_key[32], hash[SILC_HASH_MAXLEN];
3553   SilcUInt32 len;
3554
3555   if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3556     SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3557     return TRUE;
3558   }
3559
3560   SILC_LOG_DEBUG(("Generating channel %s key", channel->channel_name));
3561
3562   if (!channel->send_key)
3563     if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->send_key)) {
3564       channel->send_key = NULL;
3565       return FALSE;
3566     }
3567   if (!channel->receive_key)
3568     if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->receive_key)) {
3569       silc_cipher_free(channel->send_key);
3570       channel->send_key = channel->receive_key = NULL;
3571       return FALSE;
3572     }
3573
3574   if (key_len)
3575     len = key_len;
3576   else if (channel->key_len)
3577     len = channel->key_len / 8;
3578   else
3579     len = silc_cipher_get_key_len(channel->send_key) / 8;
3580
3581   /* Create channel key */
3582   for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3583
3584   /* Set the key */
3585   silc_cipher_set_key(channel->send_key, channel_key, len * 8, TRUE);
3586   silc_cipher_set_key(channel->receive_key, channel_key, len * 8, FALSE);
3587
3588   /* Remove old key if exists */
3589   if (channel->key) {
3590     memset(channel->key, 0, channel->key_len / 8);
3591     silc_free(channel->key);
3592   }
3593
3594   /* Save the key */
3595   channel->key_len = len * 8;
3596   channel->key = silc_memdup(channel_key, len);
3597   memset(channel_key, 0, sizeof(channel_key));
3598
3599   /* Generate HMAC key from the channel key data and set it */
3600   if (!channel->hmac)
3601     if (!silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac)) {
3602       memset(channel->key, 0, channel->key_len / 8);
3603       silc_free(channel->key);
3604       silc_cipher_free(channel->send_key);
3605       silc_cipher_free(channel->receive_key);
3606       channel->send_key = channel->receive_key = NULL;
3607       return FALSE;
3608     }
3609   silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3610   silc_hmac_set_key(channel->hmac, hash,
3611                     silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3612   memset(hash, 0, sizeof(hash));
3613
3614   if (server->server_type == SILC_ROUTER) {
3615     if (!channel->rekey)
3616       channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3617     channel->rekey->channel = channel;
3618     channel->rekey->key_len = key_len;
3619     if (channel->rekey->task)
3620       silc_schedule_task_del(server->schedule, channel->rekey->task);
3621
3622     channel->rekey->task =
3623       silc_schedule_task_add_timeout(server->schedule,
3624                                      silc_server_channel_key_rekey,
3625                                      (void *)channel->rekey,
3626                                      server->config->channel_rekey_secs, 0);
3627   }
3628
3629   return TRUE;
3630 }
3631
3632 /* Saves the channel key found in the encoded `key_payload' buffer. This
3633    function is used when we receive Channel Key Payload and also when we're
3634    processing JOIN command reply. Returns entry to the channel. */
3635
3636 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3637                                               SilcBuffer key_payload,
3638                                               SilcChannelEntry channel)
3639 {
3640   SilcChannelKeyPayload payload = NULL;
3641   SilcChannelID id;
3642   unsigned char *tmp, hash[SILC_HASH_MAXLEN];
3643   SilcUInt32 tmp_len;
3644   char *cipher;
3645
3646   /* Decode channel key payload */
3647   payload = silc_channel_key_payload_parse(key_payload->data,
3648                                            silc_buffer_len(key_payload));
3649   if (!payload) {
3650     SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3651     channel = NULL;
3652     goto out;
3653   }
3654
3655   /* Get the channel entry */
3656   if (!channel) {
3657
3658     /* Get channel ID */
3659     tmp = silc_channel_key_get_id(payload, &tmp_len);
3660     if (!silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL, &id, sizeof(id))) {
3661       channel = NULL;
3662       goto out;
3663     }
3664
3665     channel = silc_idlist_find_channel_by_id(server->local_list, &id, NULL);
3666     if (!channel) {
3667       channel = silc_idlist_find_channel_by_id(server->global_list, &id, NULL);
3668       if (!channel) {
3669         if (server->server_type == SILC_ROUTER)
3670           SILC_LOG_ERROR(("Received key for non-existent channel %s",
3671                           silc_id_render(&id, SILC_ID_CHANNEL)));
3672         goto out;
3673       }
3674     }
3675   }
3676
3677   SILC_LOG_DEBUG(("Saving new channel %s key", channel->channel_name));
3678
3679   tmp = silc_channel_key_get_key(payload, &tmp_len);
3680   if (!tmp) {
3681     channel = NULL;
3682     goto out;
3683   }
3684
3685   cipher = silc_channel_key_get_cipher(payload, NULL);
3686   if (!cipher) {
3687     channel = NULL;
3688     goto out;
3689   }
3690
3691   /* Remove old key if exists */
3692   if (channel->key) {
3693     memset(channel->key, 0, channel->key_len / 8);
3694     silc_free(channel->key);
3695     silc_cipher_free(channel->send_key);
3696     silc_cipher_free(channel->receive_key);
3697   }
3698
3699   /* Create new cipher */
3700   if (!silc_cipher_alloc(cipher, &channel->send_key)) {
3701     channel->send_key = NULL;
3702     channel = NULL;
3703     goto out;
3704   }
3705   if (!silc_cipher_alloc(cipher, &channel->receive_key)) {
3706     silc_cipher_free(channel->send_key);
3707     channel->send_key = channel->receive_key = NULL;
3708     channel = NULL;
3709     goto out;
3710   }
3711
3712   if (channel->cipher)
3713     silc_free(channel->cipher);
3714   channel->cipher = strdup(cipher);
3715
3716   /* Save the key */
3717   channel->key_len = tmp_len * 8;
3718   channel->key = silc_memdup(tmp, tmp_len);
3719   silc_cipher_set_key(channel->send_key, tmp, channel->key_len, TRUE);
3720   silc_cipher_set_key(channel->receive_key, tmp, channel->key_len, FALSE);
3721
3722   /* Generate HMAC key from the channel key data and set it */
3723   if (!channel->hmac)
3724     if (!silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac)) {
3725       memset(channel->key, 0, channel->key_len / 8);
3726       silc_free(channel->key);
3727       silc_cipher_free(channel->send_key);
3728       silc_cipher_free(channel->receive_key);
3729       channel->send_key = channel->receive_key = NULL;
3730       return FALSE;
3731     }
3732   silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3733   silc_hmac_set_key(channel->hmac, hash,
3734                     silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3735
3736   memset(hash, 0, sizeof(hash));
3737   memset(tmp, 0, tmp_len);
3738
3739   if (server->server_type == SILC_ROUTER) {
3740     if (!channel->rekey)
3741       channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3742     channel->rekey->channel = channel;
3743     if (channel->rekey->task)
3744       silc_schedule_task_del(server->schedule, channel->rekey->task);
3745
3746     channel->rekey->task =
3747       silc_schedule_task_add_timeout(server->schedule,
3748                                      silc_server_channel_key_rekey,
3749                                      (void *)channel->rekey,
3750                                      server->config->channel_rekey_secs, 0);
3751   }
3752
3753  out:
3754   if (payload)
3755     silc_channel_key_payload_free(payload);
3756
3757   return channel;
3758 }
3759
3760 /* Returns assembled of all servers in the given ID list. The packet's
3761    form is dictated by the New ID payload. */
3762
3763 static void silc_server_announce_get_servers(SilcServer server,
3764                                              SilcServerEntry remote,
3765                                              SilcIDList id_list,
3766                                              SilcBuffer *servers,
3767                                              unsigned long creation_time)
3768 {
3769   SilcList list;
3770   SilcIDCacheEntry id_cache;
3771   SilcServerEntry entry;
3772   SilcBuffer idp;
3773
3774   /* Go through all clients in the list */
3775   if (silc_idcache_get_all(id_list->servers, &list)) {
3776     silc_list_start(list);
3777     while ((id_cache = silc_list_get(list))) {
3778       entry = (SilcServerEntry)id_cache->context;
3779
3780       /* Do not announce the one we've sending our announcements and
3781          do not announce ourself. Also check the creation time if it's
3782          provided. */
3783       if ((entry == remote) || (entry == server->id_entry) ||
3784           (creation_time && entry->data.created < creation_time))
3785         continue;
3786
3787       idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3788
3789       *servers = silc_buffer_realloc(*servers,
3790                                      (*servers ?
3791                                       silc_buffer_truelen((*servers)) +
3792                                       silc_buffer_len(idp) :
3793                                       silc_buffer_len(idp)));
3794       silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3795       silc_buffer_put(*servers, idp->data, silc_buffer_len(idp));
3796       silc_buffer_pull(*servers, silc_buffer_len(idp));
3797       silc_buffer_free(idp);
3798     }
3799   }
3800 }
3801
3802 static SilcBuffer
3803 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3804 {
3805   va_list ap;
3806   SilcBuffer p;
3807
3808   va_start(ap, argc);
3809   p = silc_notify_payload_encode(notify, argc, ap);
3810   va_end(ap);
3811
3812   return p;
3813 }
3814
3815 /* This function is used by router to announce existing servers to our
3816    primary router when we've connected to it. If `creation_time' is non-zero
3817    then only the servers that has been created after the `creation_time'
3818    will be announced. */
3819
3820 void silc_server_announce_servers(SilcServer server, SilcBool global,
3821                                   unsigned long creation_time,
3822                                   SilcPacketStream remote)
3823 {
3824   SilcBuffer servers = NULL;
3825
3826   SILC_LOG_DEBUG(("Announcing servers"));
3827
3828   /* Get servers in local list */
3829   silc_server_announce_get_servers(server, silc_packet_get_context(remote),
3830                                    server->local_list, &servers,
3831                                    creation_time);
3832
3833   if (global)
3834     /* Get servers in global list */
3835     silc_server_announce_get_servers(server, silc_packet_get_context(remote),
3836                                      server->global_list, &servers,
3837                                      creation_time);
3838
3839   if (servers) {
3840     silc_buffer_push(servers, servers->data - servers->head);
3841     SILC_LOG_HEXDUMP(("servers"), servers->data, silc_buffer_len(servers));
3842
3843     /* Send the packet */
3844     silc_server_packet_send(server, remote,
3845                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3846                             servers->data, silc_buffer_len(servers));
3847
3848     silc_buffer_free(servers);
3849   }
3850 }
3851
3852 /* Returns assembled packet of all clients in the given ID list. The
3853    packet's form is dictated by the New ID Payload. */
3854
3855 static void silc_server_announce_get_clients(SilcServer server,
3856                                              SilcIDList id_list,
3857                                              SilcBuffer *clients,
3858                                              SilcBuffer *umodes,
3859                                              unsigned long creation_time)
3860 {
3861   SilcList list;
3862   SilcIDCacheEntry id_cache;
3863   SilcClientEntry client;
3864   SilcBuffer idp;
3865   SilcBuffer tmp;
3866   unsigned char mode[4];
3867
3868   /* Go through all clients in the list */
3869   if (silc_idcache_get_all(id_list->clients, &list)) {
3870     silc_list_start(list);
3871     while ((id_cache = silc_list_get(list))) {
3872       client = (SilcClientEntry)id_cache->context;
3873
3874       if (creation_time && client->data.created < creation_time)
3875         continue;
3876       if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED))
3877         continue;
3878       if (!client->connection && !client->router)
3879         continue;
3880
3881       idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3882
3883       *clients = silc_buffer_realloc(*clients,
3884                                      (*clients ?
3885                                       silc_buffer_truelen((*clients)) +
3886                                       silc_buffer_len(idp) :
3887                                       silc_buffer_len(idp)));
3888       silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3889       silc_buffer_put(*clients, idp->data, silc_buffer_len(idp));
3890       silc_buffer_pull(*clients, silc_buffer_len(idp));
3891
3892       SILC_PUT32_MSB(client->mode, mode);
3893       tmp =
3894         silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3895                                            2, idp->data, silc_buffer_len(idp),
3896                                            mode, 4);
3897       *umodes = silc_buffer_realloc(*umodes,
3898                                     (*umodes ?
3899                                      silc_buffer_truelen((*umodes)) +
3900                                      silc_buffer_len(tmp) :
3901                                      silc_buffer_len(tmp)));
3902       silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3903       silc_buffer_put(*umodes, tmp->data, silc_buffer_len(tmp));
3904       silc_buffer_pull(*umodes, silc_buffer_len(tmp));
3905       silc_buffer_free(tmp);
3906
3907       silc_buffer_free(idp);
3908     }
3909   }
3910 }
3911
3912 /* This function is used to announce our existing clients to our router
3913    when we've connected to it. If `creation_time' is non-zero then only
3914    the clients that has been created after the `creation_time' will be
3915    announced. */
3916
3917 void silc_server_announce_clients(SilcServer server,
3918                                   unsigned long creation_time,
3919                                   SilcPacketStream remote)
3920 {
3921   SilcBuffer clients = NULL;
3922   SilcBuffer umodes = NULL;
3923
3924   SILC_LOG_DEBUG(("Announcing clients"));
3925
3926   /* Get clients in local list */
3927   silc_server_announce_get_clients(server, server->local_list,
3928                                    &clients, &umodes, creation_time);
3929
3930   /* As router we announce our global list as well */
3931   if (server->server_type == SILC_ROUTER)
3932     silc_server_announce_get_clients(server, server->global_list,
3933                                      &clients, &umodes, creation_time);
3934
3935   if (clients) {
3936     silc_buffer_push(clients, clients->data - clients->head);
3937     SILC_LOG_HEXDUMP(("clients"), clients->data, silc_buffer_len(clients));
3938
3939     /* Send the packet */
3940     silc_server_packet_send(server, remote,
3941                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3942                             clients->data, silc_buffer_len(clients));
3943
3944     silc_buffer_free(clients);
3945   }
3946
3947   if (umodes) {
3948     silc_buffer_push(umodes, umodes->data - umodes->head);
3949     SILC_LOG_HEXDUMP(("umodes"), umodes->data, silc_buffer_len(umodes));
3950
3951     /* Send the packet */
3952     silc_server_packet_send(server, remote,
3953                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3954                             umodes->data, silc_buffer_len(umodes));
3955
3956     silc_buffer_free(umodes);
3957   }
3958 }
3959
3960 /* Returns channel's topic for announcing it */
3961
3962 void silc_server_announce_get_channel_topic(SilcServer server,
3963                                             SilcChannelEntry channel,
3964                                             SilcBuffer *topic)
3965 {
3966   SilcBuffer chidp;
3967
3968   if (channel->topic) {
3969     chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3970     *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3971                                                 chidp->data,
3972                                                 silc_buffer_len(chidp),
3973                                                 channel->topic,
3974                                                 strlen(channel->topic));
3975     silc_buffer_free(chidp);
3976   }
3977 }
3978
3979 /* Returns channel's invite and ban lists */
3980
3981 void silc_server_announce_get_inviteban(SilcServer server,
3982                                         SilcChannelEntry channel,
3983                                         SilcBuffer *invite,
3984                                         SilcBuffer *ban)
3985 {
3986   SilcBuffer list, idp, idp2, tmp2;
3987   SilcUInt32 type;
3988   SilcHashTableList htl;
3989   const unsigned char a[1] = { 0x03 };
3990
3991   idp = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
3992
3993   /* Encode invite list */
3994   if (channel->invite_list && silc_hash_table_count(channel->invite_list)) {
3995     list = silc_buffer_alloc_size(2);
3996     type = silc_hash_table_count(channel->invite_list);
3997     SILC_PUT16_MSB(type, list->data);
3998     silc_hash_table_list(channel->invite_list, &htl);
3999     while (silc_hash_table_get(&htl, (void *)&type, (void *)&tmp2))
4000       list = silc_argument_payload_encode_one(list, tmp2->data, silc_buffer_len(tmp2),
4001                                               type);
4002     silc_hash_table_list_reset(&htl);
4003
4004     idp2 = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4005     *invite =
4006       silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_INVITE, 5,
4007                                          idp->data, silc_buffer_len(idp),
4008                                          channel->channel_name,
4009                                          strlen(channel->channel_name),
4010                                          idp2->data, silc_buffer_len(idp2),
4011                                          a, 1,
4012                                          list->data, silc_buffer_len(list));
4013     silc_buffer_free(idp2);
4014     silc_buffer_free(list);
4015   }
4016
4017   /* Encode ban list */
4018   if (channel->ban_list && silc_hash_table_count(channel->ban_list)) {
4019     list = silc_buffer_alloc_size(2);
4020     type = silc_hash_table_count(channel->ban_list);
4021     SILC_PUT16_MSB(type, list->data);
4022     silc_hash_table_list(channel->ban_list, &htl);
4023     while (silc_hash_table_get(&htl, (void *)&type, (void *)&tmp2))
4024       list = silc_argument_payload_encode_one(list, tmp2->data, silc_buffer_len(tmp2),
4025                                               type);
4026     silc_hash_table_list_reset(&htl);
4027
4028     *ban =
4029       silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_BAN, 3,
4030                                          idp->data, silc_buffer_len(idp),
4031                                          a, 1,
4032                                          list->data, silc_buffer_len(list));
4033     silc_buffer_free(list);
4034   }
4035
4036   silc_buffer_free(idp);
4037 }
4038
4039 /* Returns assembled packets for channel users of the `channel'. */
4040
4041 void silc_server_announce_get_channel_users(SilcServer server,
4042                                             SilcChannelEntry channel,
4043                                             SilcBuffer *channel_modes,
4044                                             SilcBuffer *channel_users,
4045                                             SilcBuffer *channel_users_modes)
4046 {
4047   SilcChannelClientEntry chl;
4048   SilcHashTableList htl;
4049   SilcBuffer chidp, clidp, csidp;
4050   SilcBuffer tmp, fkey = NULL, chpklist;
4051   int len;
4052   unsigned char mode[4], ulimit[4];
4053   char *hmac;
4054
4055   SILC_LOG_DEBUG(("Start"));
4056
4057   chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4058   csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4059   chpklist = silc_server_get_channel_pk_list(server, channel, TRUE, FALSE);
4060
4061   /* CMODE notify */
4062   SILC_PUT32_MSB(channel->mode, mode);
4063   if (channel->mode & SILC_CHANNEL_MODE_ULIMIT)
4064     SILC_PUT32_MSB(channel->user_limit, ulimit);
4065   hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
4066   if (channel->founder_key)
4067     fkey = silc_public_key_payload_encode(channel->founder_key);
4068   tmp =
4069     silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
4070                                        8, csidp->data,
4071                                        silc_buffer_len(csidp),
4072                                        mode, sizeof(mode),
4073                                        NULL, 0,
4074                                        hmac, hmac ? strlen(hmac) : 0,
4075                                        channel->passphrase,
4076                                        channel->passphrase ?
4077                                        strlen(channel->passphrase) : 0,
4078                                        fkey ? fkey->data : NULL,
4079                                        fkey ? silc_buffer_len(fkey) : 0,
4080                                        chpklist ? chpklist->data : NULL,
4081                                        chpklist ?
4082                                        silc_buffer_len(chpklist) : 0,
4083                                        (channel->mode &
4084                                         SILC_CHANNEL_MODE_ULIMIT ?
4085                                         ulimit : NULL),
4086                                        (channel->mode &
4087                                         SILC_CHANNEL_MODE_ULIMIT ?
4088                                         sizeof(ulimit) : 0));
4089   len = silc_buffer_len(tmp);
4090   *channel_modes =
4091     silc_buffer_realloc(*channel_modes,
4092                         (*channel_modes ?
4093                          silc_buffer_truelen((*channel_modes)) + len : len));
4094   silc_buffer_pull_tail(*channel_modes,
4095                         ((*channel_modes)->end -
4096                          (*channel_modes)->data));
4097   silc_buffer_put(*channel_modes, tmp->data, silc_buffer_len(tmp));
4098   silc_buffer_pull(*channel_modes, len);
4099   silc_buffer_free(tmp);
4100   silc_buffer_free(fkey);
4101   fkey = NULL;
4102
4103   /* Now find all users on the channel */
4104   silc_hash_table_list(channel->user_list, &htl);
4105   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4106     clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4107
4108     /* JOIN Notify */
4109     tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
4110                                              clidp->data,
4111                                              silc_buffer_len(clidp),
4112                                              chidp->data,
4113                                              silc_buffer_len(chidp));
4114     len = silc_buffer_len(tmp);
4115     *channel_users =
4116       silc_buffer_realloc(*channel_users,
4117                           (*channel_users ?
4118                            silc_buffer_truelen((*channel_users)) + len : len));
4119     silc_buffer_pull_tail(*channel_users,
4120                           ((*channel_users)->end -
4121                            (*channel_users)->data));
4122
4123     silc_buffer_put(*channel_users, tmp->data, silc_buffer_len(tmp));
4124     silc_buffer_pull(*channel_users, len);
4125     silc_buffer_free(tmp);
4126
4127     /* CUMODE notify for mode change on the channel */
4128     SILC_PUT32_MSB(chl->mode, mode);
4129     if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
4130       fkey = silc_public_key_payload_encode(channel->founder_key);
4131     tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
4132                                              4, csidp->data,
4133                                              silc_buffer_len(csidp),
4134                                              mode, sizeof(mode),
4135                                              clidp->data,
4136                                              silc_buffer_len(clidp),
4137                                              fkey ? fkey->data : NULL,
4138                                              fkey ? silc_buffer_len(fkey) : 0);
4139     len = silc_buffer_len(tmp);
4140     *channel_users_modes =
4141       silc_buffer_realloc(*channel_users_modes,
4142                           (*channel_users_modes ?
4143                            silc_buffer_truelen((*channel_users_modes)) +
4144                            len : len));
4145     silc_buffer_pull_tail(*channel_users_modes,
4146                           ((*channel_users_modes)->end -
4147                            (*channel_users_modes)->data));
4148
4149     silc_buffer_put(*channel_users_modes, tmp->data, silc_buffer_len(tmp));
4150     silc_buffer_pull(*channel_users_modes, len);
4151     silc_buffer_free(tmp);
4152     silc_buffer_free(fkey);
4153     fkey = NULL;
4154     silc_buffer_free(clidp);
4155   }
4156   silc_hash_table_list_reset(&htl);
4157   silc_buffer_free(chidp);
4158   silc_buffer_free(csidp);
4159 }
4160
4161 /* Returns assembled packets for all channels and users on those channels
4162    from the given ID List. The packets are in the form dictated by the
4163    New Channel and New Channel User payloads. */
4164
4165 void silc_server_announce_get_channels(SilcServer server,
4166                                        SilcIDList id_list,
4167                                        SilcBuffer *channels,
4168                                        SilcBuffer **channel_modes,
4169                                        SilcBuffer *channel_users,
4170                                        SilcBuffer **channel_users_modes,
4171                                        SilcUInt32 *channel_users_modes_c,
4172                                        SilcBuffer **channel_topics,
4173                                        SilcBuffer **channel_invites,
4174                                        SilcBuffer **channel_bans,
4175                                        SilcChannelID ***channel_ids,
4176                                        unsigned long creation_time)
4177 {
4178   SilcList list;
4179   SilcIDCacheEntry id_cache;
4180   SilcChannelEntry channel;
4181   unsigned char cid[32];
4182   SilcUInt32 id_len;
4183   SilcUInt16 name_len;
4184   int len;
4185   int i = *channel_users_modes_c;
4186   SilcBool announce;
4187
4188   SILC_LOG_DEBUG(("Start"));
4189
4190   /* Go through all channels in the list */
4191   if (silc_idcache_get_all(id_list->channels, &list)) {
4192     silc_list_start(list);
4193     while ((id_cache = silc_list_get(list))) {
4194       channel = (SilcChannelEntry)id_cache->context;
4195
4196       if (creation_time && channel->created < creation_time)
4197         announce = FALSE;
4198       else
4199         announce = TRUE;
4200
4201       silc_id_id2str(channel->id, SILC_ID_CHANNEL, cid, sizeof(cid), &id_len);
4202       name_len = strlen(channel->channel_name);
4203
4204       if (announce) {
4205         len = 4 + name_len + id_len + 4;
4206         *channels =
4207           silc_buffer_realloc(*channels,
4208                               (*channels ?
4209                                silc_buffer_truelen((*channels)) +
4210                                len : len));
4211         silc_buffer_pull_tail(*channels,
4212                               ((*channels)->end - (*channels)->data));
4213         silc_buffer_format(*channels,
4214                            SILC_STR_UI_SHORT(name_len),
4215                            SILC_STR_UI_XNSTRING(channel->channel_name,
4216                                                 name_len),
4217                            SILC_STR_UI_SHORT(id_len),
4218                              SILC_STR_UI_XNSTRING(cid, id_len),
4219                            SILC_STR_UI_INT(channel->mode),
4220                            SILC_STR_END);
4221         silc_buffer_pull(*channels, len);
4222       }
4223
4224       if (creation_time && channel->updated < creation_time)
4225         announce = FALSE;
4226       else
4227         announce = TRUE;
4228
4229       if (announce) {
4230         /* Channel user modes */
4231         *channel_users_modes = silc_realloc(*channel_users_modes,
4232                                             sizeof(**channel_users_modes) *
4233                                             (i + 1));
4234         (*channel_users_modes)[i] = NULL;
4235         *channel_modes = silc_realloc(*channel_modes,
4236                                       sizeof(**channel_modes) * (i + 1));
4237         (*channel_modes)[i] = NULL;
4238         *channel_ids = silc_realloc(*channel_ids,
4239                                       sizeof(**channel_ids) * (i + 1));
4240         (*channel_ids)[i] = NULL;
4241         silc_server_announce_get_channel_users(server, channel,
4242                                                &(*channel_modes)[i],
4243                                                channel_users,
4244                                                &(*channel_users_modes)[i]);
4245         (*channel_ids)[i] = channel->id;
4246
4247         /* Channel's topic */
4248         *channel_topics = silc_realloc(*channel_topics,
4249                                        sizeof(**channel_topics) * (i + 1));
4250         (*channel_topics)[i] = NULL;
4251         silc_server_announce_get_channel_topic(server, channel,
4252                                                &(*channel_topics)[i]);
4253
4254         /* Channel's invite and ban list */
4255         *channel_invites = silc_realloc(*channel_invites,
4256                                         sizeof(**channel_invites) * (i + 1));
4257         (*channel_invites)[i] = NULL;
4258         *channel_bans = silc_realloc(*channel_bans,
4259                                      sizeof(**channel_bans) * (i + 1));
4260         (*channel_bans)[i] = NULL;
4261         silc_server_announce_get_inviteban(server, channel,
4262                                            &(*channel_invites)[i],
4263                                            &(*channel_bans)[i]);
4264
4265         (*channel_users_modes_c)++;
4266
4267         i++;
4268       }
4269     }
4270   }
4271 }
4272
4273 /* This function is used to announce our existing channels to our router
4274    when we've connected to it. This also announces the users on the
4275    channels to the router. If the `creation_time' is non-zero only the
4276    channels that was created after the `creation_time' are announced.
4277    Note that the channel users are still announced even if the `creation_time'
4278    was provided. */
4279
4280 void silc_server_announce_channels(SilcServer server,
4281                                    unsigned long creation_time,
4282                                    SilcPacketStream remote)
4283 {
4284   SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
4285   SilcBuffer *channel_users_modes = NULL;
4286   SilcBuffer *channel_topics = NULL;
4287   SilcBuffer *channel_invites = NULL;
4288   SilcBuffer *channel_bans = NULL;
4289   SilcUInt32 channel_users_modes_c = 0;
4290   SilcChannelID **channel_ids = NULL;
4291
4292   SILC_LOG_DEBUG(("Announcing channels and channel users"));
4293
4294   /* Get channels and channel users in local list */
4295   silc_server_announce_get_channels(server, server->local_list,
4296                                     &channels, &channel_modes,
4297                                     &channel_users,
4298                                     &channel_users_modes,
4299                                     &channel_users_modes_c,
4300                                     &channel_topics,
4301                                     &channel_invites,
4302                                     &channel_bans,
4303                                     &channel_ids, creation_time);
4304
4305   /* Get channels and channel users in global list */
4306   if (server->server_type != SILC_SERVER)
4307     silc_server_announce_get_channels(server, server->global_list,
4308                                       &channels, &channel_modes,
4309                                       &channel_users,
4310                                       &channel_users_modes,
4311                                       &channel_users_modes_c,
4312                                       &channel_topics,
4313                                       &channel_invites,
4314                                       &channel_bans,
4315                                       &channel_ids, creation_time);
4316
4317   if (channels) {
4318     silc_buffer_push(channels, channels->data - channels->head);
4319     SILC_LOG_HEXDUMP(("channels"), channels->data, silc_buffer_len(channels));
4320
4321     /* Send the packet */
4322     silc_server_packet_send(server, remote,
4323                             SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
4324                             channels->data, silc_buffer_len(channels));
4325
4326     silc_buffer_free(channels);
4327   }
4328
4329   if (channel_users) {
4330     silc_buffer_push(channel_users, channel_users->data - channel_users->head);
4331     SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
4332                      silc_buffer_len(channel_users));
4333
4334     /* Send the packet */
4335     silc_server_packet_send(server, remote,
4336                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4337                             channel_users->data, silc_buffer_len(channel_users));
4338
4339     silc_buffer_free(channel_users);
4340   }
4341
4342   if (channel_modes) {
4343     int i;
4344
4345     for (i = 0; i < channel_users_modes_c; i++) {
4346       if (!channel_modes[i])
4347         continue;
4348       silc_buffer_push(channel_modes[i],
4349                        channel_modes[i]->data -
4350                        channel_modes[i]->head);
4351       SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
4352                        silc_buffer_len(channel_modes[i]));
4353       silc_server_packet_send_dest(server, remote,
4354                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4355                                    channel_ids[i], SILC_ID_CHANNEL,
4356                                    channel_modes[i]->data,
4357                                    silc_buffer_len(channel_modes[i]));
4358       silc_buffer_free(channel_modes[i]);
4359     }
4360     silc_free(channel_modes);
4361   }
4362
4363   if (channel_users_modes) {
4364     int i;
4365
4366     for (i = 0; i < channel_users_modes_c; i++) {
4367       if (!channel_users_modes[i])
4368         continue;
4369       silc_buffer_push(channel_users_modes[i],
4370                        channel_users_modes[i]->data -
4371                        channel_users_modes[i]->head);
4372       SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
4373                        silc_buffer_len(channel_users_modes[i]));
4374       silc_server_packet_send_dest(server, remote,
4375                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4376                                    channel_ids[i], SILC_ID_CHANNEL,
4377                                    channel_users_modes[i]->data,
4378                                    silc_buffer_len(channel_users_modes[i]));
4379       silc_buffer_free(channel_users_modes[i]);
4380     }
4381     silc_free(channel_users_modes);
4382   }
4383
4384   if (channel_topics) {
4385     int i;
4386
4387     for (i = 0; i < channel_users_modes_c; i++) {
4388       if (!channel_topics[i])
4389         continue;
4390
4391       silc_buffer_push(channel_topics[i],
4392                        channel_topics[i]->data -
4393                        channel_topics[i]->head);
4394       SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
4395                        silc_buffer_len(channel_topics[i]));
4396       silc_server_packet_send_dest(server, remote,
4397                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4398                                    channel_ids[i], SILC_ID_CHANNEL,
4399                                    channel_topics[i]->data,
4400                                    silc_buffer_len(channel_topics[i]));
4401       silc_buffer_free(channel_topics[i]);
4402     }
4403     silc_free(channel_topics);
4404   }
4405
4406   if (channel_invites) {
4407     int i;
4408
4409     for (i = 0; i < channel_users_modes_c; i++) {
4410       if (!channel_invites[i])
4411         continue;
4412
4413       silc_buffer_push(channel_invites[i],
4414                        channel_invites[i]->data -
4415                        channel_invites[i]->head);
4416       SILC_LOG_HEXDUMP(("channel invite list"), channel_invites[i]->data,
4417                        silc_buffer_len(channel_invites[i]));
4418       silc_server_packet_send_dest(server, remote,
4419                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4420                                    channel_ids[i], SILC_ID_CHANNEL,
4421                                    channel_invites[i]->data,
4422                                    silc_buffer_len(channel_invites[i]));
4423       silc_buffer_free(channel_invites[i]);
4424     }
4425     silc_free(channel_invites);
4426   }
4427
4428   if (channel_bans) {
4429     int i;
4430
4431     for (i = 0; i < channel_users_modes_c; i++) {
4432       if (!channel_bans[i])
4433         continue;
4434
4435       silc_buffer_push(channel_bans[i],
4436                        channel_bans[i]->data -
4437                        channel_bans[i]->head);
4438       SILC_LOG_HEXDUMP(("channel ban list"), channel_bans[i]->data,
4439                        silc_buffer_len(channel_bans[i]));
4440       silc_server_packet_send_dest(server, remote,
4441                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4442                                    channel_ids[i], SILC_ID_CHANNEL,
4443                                    channel_bans[i]->data,
4444                                    silc_buffer_len(channel_bans[i]));
4445       silc_buffer_free(channel_bans[i]);
4446     }
4447     silc_free(channel_bans);
4448   }
4449
4450   silc_free(channel_ids);
4451 }
4452
4453 /* Announces WATCH list. */
4454
4455 void silc_server_announce_watches(SilcServer server,
4456                                   SilcPacketStream remote)
4457 {
4458   SilcHashTableList htl;
4459   SilcBuffer buffer, idp, args, pkp;
4460   SilcClientEntry client;
4461   void *key;
4462
4463   SILC_LOG_DEBUG(("Announcing watch list"));
4464
4465   /* XXX because way we save the nicks (hash) we cannot announce them. */
4466
4467   /* XXX we should send all public keys in one command if client is
4468      watching more than one key */
4469   silc_hash_table_list(server->watcher_list_pk, &htl);
4470   while (silc_hash_table_get(&htl, &key, (void *)&client)) {
4471     if (!client || !client->id)
4472       continue;
4473
4474     server->stat.commands_sent++;
4475
4476     idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
4477     args = silc_buffer_alloc_size(2);
4478     silc_buffer_format(args,
4479                        SILC_STR_UI_SHORT(1),
4480                        SILC_STR_END);
4481     pkp = silc_public_key_payload_encode(key);
4482     args = silc_argument_payload_encode_one(args, pkp->data,
4483                                             silc_buffer_len(pkp), 0x00);
4484     buffer = silc_command_payload_encode_va(SILC_COMMAND_WATCH,
4485                                             ++server->cmd_ident, 2,
4486                                             1, idp->data, silc_buffer_len(idp),
4487                                             4, args->data,
4488                                             silc_buffer_len(args));
4489
4490     /* Send command */
4491     silc_server_packet_send(server, remote, SILC_PACKET_COMMAND, 0,
4492                             buffer->data, silc_buffer_len(buffer));
4493
4494     silc_buffer_free(pkp);
4495     silc_buffer_free(args);
4496     silc_buffer_free(idp);
4497     silc_buffer_free(buffer);
4498   }
4499   silc_hash_table_list_reset(&htl);
4500 }
4501
4502 /* Assembles user list and users mode list from the `channel'. */
4503
4504 SilcBool silc_server_get_users_on_channel(SilcServer server,
4505                                       SilcChannelEntry channel,
4506                                       SilcBuffer *user_list,
4507                                       SilcBuffer *mode_list,
4508                                       SilcUInt32 *user_count)
4509 {
4510   SilcChannelClientEntry chl;
4511   SilcHashTableList htl;
4512   SilcBuffer client_id_list;
4513   SilcBuffer client_mode_list;
4514   SilcBuffer idp;
4515   SilcUInt32 list_count = 0, len = 0;
4516
4517   if (!silc_hash_table_count(channel->user_list))
4518     return FALSE;
4519
4520   silc_hash_table_list(channel->user_list, &htl);
4521   while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4522     len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
4523   silc_hash_table_list_reset(&htl);
4524
4525   client_id_list = silc_buffer_alloc(len);
4526   client_mode_list =
4527     silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
4528   silc_buffer_pull_tail(client_id_list, silc_buffer_truelen(client_id_list));
4529   silc_buffer_pull_tail(client_mode_list,
4530                         silc_buffer_truelen(client_mode_list));
4531
4532   silc_hash_table_list(channel->user_list, &htl);
4533   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4534     /* Client ID */
4535     idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4536     silc_buffer_put(client_id_list, idp->data, silc_buffer_len(idp));
4537     silc_buffer_pull(client_id_list, silc_buffer_len(idp));
4538     silc_buffer_free(idp);
4539
4540     /* Client's mode on channel */
4541     SILC_PUT32_MSB(chl->mode, client_mode_list->data);
4542     silc_buffer_pull(client_mode_list, 4);
4543
4544     list_count++;
4545   }
4546   silc_hash_table_list_reset(&htl);
4547   silc_buffer_push(client_id_list,
4548                    client_id_list->data - client_id_list->head);
4549   silc_buffer_push(client_mode_list,
4550                    client_mode_list->data - client_mode_list->head);
4551
4552   *user_list = client_id_list;
4553   *mode_list = client_mode_list;
4554   *user_count = list_count;
4555   return TRUE;
4556 }
4557
4558 /* Saves users and their modes to the `channel'. */
4559
4560 void silc_server_save_users_on_channel(SilcServer server,
4561                                        SilcPacketStream sock,
4562                                        SilcChannelEntry channel,
4563                                        SilcClientID *noadd,
4564                                        SilcBuffer user_list,
4565                                        SilcBuffer mode_list,
4566                                        SilcUInt32 user_count)
4567 {
4568   int i;
4569   SilcUInt16 idp_len;
4570   SilcUInt32 mode;
4571   SilcID id;
4572   SilcClientEntry client;
4573   SilcIDCacheEntry cache;
4574   SilcChannelClientEntry chl;
4575
4576   SILC_LOG_DEBUG(("Saving %d users on %s channel", user_count,
4577                   channel->channel_name));
4578
4579   for (i = 0; i < user_count; i++) {
4580     /* Client ID */
4581     SILC_GET16_MSB(idp_len, user_list->data + 2);
4582     idp_len += 4;
4583     if (!silc_id_payload_parse_id(user_list->data, idp_len, &id))
4584       continue;
4585     silc_buffer_pull(user_list, idp_len);
4586
4587     /* Mode */
4588     SILC_GET32_MSB(mode, mode_list->data);
4589     silc_buffer_pull(mode_list, 4);
4590
4591     if (noadd && SILC_ID_CLIENT_COMPARE(&id.u.client_id, noadd))
4592       continue;
4593
4594     cache = NULL;
4595
4596     /* Check if we have this client cached already. */
4597     client = silc_idlist_find_client_by_id(server->local_list,
4598                                            &id.u.client_id,
4599                                            server->server_type, &cache);
4600     if (!client)
4601       client = silc_idlist_find_client_by_id(server->global_list,
4602                                              &id.u.client_id,
4603                                              server->server_type, &cache);
4604     if (!client) {
4605       /* If router did not find such Client ID in its lists then this must
4606          be bogus client or some router in the net is buggy. */
4607       if (server->server_type != SILC_SERVER)
4608         continue;
4609
4610       /* We don't have that client anywhere, add it. The client is added
4611          to global list since server didn't have it in the lists so it must be
4612          global. */
4613       client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
4614                                       silc_id_dup(&id.u.client_id,
4615                                                   SILC_ID_CLIENT),
4616                                       silc_packet_get_context(sock),
4617                                       NULL);
4618       if (!client) {
4619         SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
4620         continue;
4621       }
4622
4623       client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
4624     }
4625
4626     if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
4627       SILC_LOG_ERROR(("Attempting to add unregistered client to channel ",
4628                       "%s", channel->channel_name));
4629       continue;
4630     }
4631
4632     if (!silc_server_client_on_channel(client, channel, &chl)) {
4633       /* Client was not on the channel, add it. */
4634       chl = silc_calloc(1, sizeof(*chl));
4635       chl->client = client;
4636       chl->mode = mode;
4637       chl->channel = channel;
4638       silc_hash_table_add(channel->user_list, chl->client, chl);
4639       silc_hash_table_add(client->channels, chl->channel, chl);
4640       channel->user_count++;
4641     } else {
4642       /* Update mode */
4643       chl->mode = mode;
4644     }
4645   }
4646 }
4647
4648 /* Saves channels and channels user modes to the `client'.  Removes
4649    the client from those channels that are not sent in the list but
4650    it has joined. */
4651
4652 void silc_server_save_user_channels(SilcServer server,
4653                                     SilcPacketStream sock,
4654                                     SilcClientEntry client,
4655                                     SilcBuffer channels,
4656                                     SilcBuffer channels_user_modes)
4657 {
4658   SilcDList ch;
4659   SilcUInt32 *chumodes;
4660   SilcChannelPayload entry;
4661   SilcChannelEntry channel;
4662   SilcChannelID channel_id;
4663   SilcChannelClientEntry chl;
4664   SilcHashTable ht = NULL;
4665   SilcHashTableList htl;
4666   char *name;
4667   int i = 0;
4668
4669   if (!channels || !channels_user_modes ||
4670       !(client->data.status & SILC_IDLIST_STATUS_REGISTERED))
4671     goto out;
4672
4673   ch = silc_channel_payload_parse_list(channels->data,
4674                                        silc_buffer_len(channels));
4675   if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
4676                                &chumodes)) {
4677     ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL,
4678                                NULL, NULL, NULL, TRUE);
4679     silc_dlist_start(ch);
4680     while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
4681       /* Check if we have this channel, and add it if we don't have it.
4682          Also add the client on the channel unless it is there already. */
4683       if (!silc_channel_get_id_parse(entry, &channel_id))
4684         continue;
4685       channel = silc_idlist_find_channel_by_id(server->local_list,
4686                                                &channel_id, NULL);
4687       if (!channel)
4688         channel = silc_idlist_find_channel_by_id(server->global_list,
4689                                                  &channel_id, NULL);
4690       if (!channel) {
4691         if (server->server_type != SILC_SERVER) {
4692           i++;
4693           continue;
4694         }
4695
4696         /* We don't have that channel anywhere, add it. */
4697         name = silc_channel_get_name(entry, NULL);
4698         channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
4699                                           silc_id_dup(&channel_id,
4700                                                       SILC_ID_CHANNEL),
4701                                           server->router, NULL, NULL, 0);
4702         if (!channel) {
4703           i++;
4704           continue;
4705         }
4706       }
4707
4708       channel->mode = silc_channel_get_mode(entry);
4709
4710       /* Add the client on the channel */
4711       if (!silc_server_client_on_channel(client, channel, &chl)) {
4712         chl = silc_calloc(1, sizeof(*chl));
4713         chl->client = client;
4714         chl->mode = chumodes[i++];
4715         chl->channel = channel;
4716         silc_hash_table_add(channel->user_list, chl->client, chl);
4717         silc_hash_table_add(client->channels, chl->channel, chl);
4718         channel->user_count++;
4719       } else {
4720         /* Update mode */
4721         chl->mode = chumodes[i++];
4722       }
4723
4724       silc_hash_table_add(ht, channel, channel);
4725     }
4726     silc_channel_payload_list_free(ch);
4727     silc_free(chumodes);
4728   }
4729
4730  out:
4731   /* Go through the list again and remove client from channels that
4732      are no part of the list. */
4733   if (ht) {
4734     silc_hash_table_list(client->channels, &htl);
4735     while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4736       if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
4737         silc_hash_table_del(chl->channel->user_list, chl->client);
4738         silc_hash_table_del(chl->client->channels, chl->channel);
4739         silc_free(chl);
4740       }
4741     }
4742     silc_hash_table_list_reset(&htl);
4743     silc_hash_table_free(ht);
4744   } else {
4745     silc_hash_table_list(client->channels, &htl);
4746     while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4747       silc_hash_table_del(chl->channel->user_list, chl->client);
4748       silc_hash_table_del(chl->client->channels, chl->channel);
4749       silc_free(chl);
4750     }
4751     silc_hash_table_list_reset(&htl);
4752   }
4753 }
4754
4755 /* Lookups route to the client indicated by the `id_data'. The connection
4756    object and internal data object is returned. Returns NULL if route
4757    could not be found to the client. If the `client_id' is specified then
4758    it is used and the `id_data' is ignored. */
4759
4760 SilcPacketStream
4761 silc_server_get_client_route(SilcServer server,
4762                              unsigned char *id_data,
4763                              SilcUInt32 id_len,
4764                              SilcClientID *client_id,
4765                              SilcIDListData *idata,
4766                              SilcClientEntry *client_entry)
4767 {
4768   SilcClientID *id, clid;
4769   SilcClientEntry client;
4770
4771   SILC_LOG_DEBUG(("Start"));
4772
4773   if (client_entry)
4774     *client_entry = NULL;
4775
4776   /* Decode destination Client ID */
4777   if (!client_id) {
4778     if (!silc_id_str2id(id_data, id_len, SILC_ID_CLIENT, &clid, sizeof(clid)))
4779       return NULL;
4780     id = silc_id_dup(&clid, SILC_ID_CLIENT);
4781   } else {
4782     id = silc_id_dup(client_id, SILC_ID_CLIENT);
4783   }
4784
4785   /* If the destination belongs to our server we don't have to route
4786      the packet anywhere but to send it to the local destination. */
4787   client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
4788   if (client) {
4789     silc_free(id);
4790
4791     /* If we are router and the client has router then the client is in
4792        our cell but not directly connected to us. */
4793     if (server->server_type == SILC_ROUTER && client->router) {
4794       /* We are of course in this case the client's router thus the route
4795          to the client is the server who owns the client. So, we will send
4796          the packet to that server. */
4797       if (idata)
4798         *idata = (SilcIDListData)client->router;
4799       return client->router->connection;
4800     }
4801
4802     /* Seems that client really is directly connected to us */
4803     if (idata)
4804       *idata = (SilcIDListData)client;
4805     if (client_entry)
4806       *client_entry = client;
4807     return client->connection;
4808   }
4809
4810   /* Destination belongs to someone not in this server. If we are normal
4811      server our action is to send the packet to our router. */
4812   if (server->server_type != SILC_ROUTER && !server->standalone) {
4813     silc_free(id);
4814     if (idata)
4815       *idata = (SilcIDListData)server->router;
4816     return SILC_PRIMARY_ROUTE(server);
4817   }
4818
4819   /* We are router and we will perform route lookup for the destination
4820      and send the packet to fastest route. */
4821   if (server->server_type == SILC_ROUTER && !server->standalone) {
4822     /* Check first that the ID is valid */
4823     client = silc_idlist_find_client_by_id(server->global_list, id,
4824                                            TRUE, NULL);
4825     if (client) {
4826       SilcPacketStream dst_sock;
4827
4828       dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
4829
4830       silc_free(id);
4831       if (idata && dst_sock)
4832         *idata = silc_packet_get_context(dst_sock);
4833       return dst_sock;
4834     }
4835   }
4836
4837   silc_free(id);
4838   return NULL;
4839 }
4840
4841 /* Encodes and returns channel list of channels the `client' has joined.
4842    Secret channels are not put to the list. */
4843
4844 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
4845                                                SilcClientEntry client,
4846                                                SilcBool get_private,
4847                                                SilcBool get_secret,
4848                                                SilcBuffer *user_mode_list)
4849 {
4850   SilcBuffer buffer = NULL;
4851   SilcChannelEntry channel;
4852   SilcChannelClientEntry chl;
4853   SilcHashTableList htl;
4854   unsigned char cid[32];
4855   SilcUInt32 id_len;
4856   SilcUInt16 name_len;
4857   int len;
4858
4859   if (user_mode_list)
4860     *user_mode_list = NULL;
4861
4862   silc_hash_table_list(client->channels, &htl);
4863   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4864     channel = chl->channel;
4865
4866     if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
4867       continue;
4868     if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
4869       continue;
4870
4871     silc_id_id2str(channel->id, SILC_ID_CHANNEL, cid, sizeof(cid), &id_len);
4872     name_len = strlen(channel->channel_name);
4873
4874     len = 4 + name_len + id_len + 4;
4875     buffer = silc_buffer_realloc(buffer,
4876                                  (buffer ?
4877                                   silc_buffer_truelen(buffer) + len : len));
4878     silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
4879     silc_buffer_format(buffer,
4880                        SILC_STR_UI_SHORT(name_len),
4881                        SILC_STR_DATA(channel->channel_name, name_len),
4882                        SILC_STR_UI_SHORT(id_len),
4883                        SILC_STR_DATA(cid, id_len),
4884                        SILC_STR_UI_INT(chl->channel->mode),
4885                        SILC_STR_END);
4886     silc_buffer_pull(buffer, len);
4887
4888     if (user_mode_list) {
4889       *user_mode_list =
4890         silc_buffer_realloc(*user_mode_list,
4891                             (*user_mode_list ?
4892                              silc_buffer_truelen((*user_mode_list)) + 4 : 4));
4893       silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
4894                                               (*user_mode_list)->data));
4895       SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
4896       silc_buffer_pull(*user_mode_list, 4);
4897     }
4898   }
4899   silc_hash_table_list_reset(&htl);
4900
4901   if (buffer)
4902     silc_buffer_push(buffer, buffer->data - buffer->head);
4903   if (user_mode_list && *user_mode_list)
4904     silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
4905                                        (*user_mode_list)->head));
4906
4907   return buffer;
4908 }
4909
4910 /* Task callback used to retrieve network statistical information from
4911    router server once in a while. */
4912
4913 SILC_TASK_CALLBACK(silc_server_get_stats)
4914 {
4915   SilcServer server = (SilcServer)context;
4916   SilcBuffer idp, packet;
4917
4918   if (!server->standalone) {
4919     SILC_LOG_DEBUG(("Retrieving stats from router"));
4920     server->stat.commands_sent++;
4921     idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
4922     packet = silc_command_payload_encode_va(SILC_COMMAND_STATS,
4923                                             ++server->cmd_ident, 1,
4924                                             1, idp->data,
4925                                             silc_buffer_len(idp));
4926     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
4927                             SILC_PACKET_COMMAND, 0, packet->data,
4928                             silc_buffer_len(packet));
4929     silc_buffer_free(packet);
4930     silc_buffer_free(idp);
4931   }
4932
4933   silc_schedule_task_add_timeout(server->schedule, silc_server_get_stats,
4934                                  server, 120, 0);
4935 }