give a better looking to silc_server_connect_to_route()
[silc.git] / apps / silcd / server.c
1 /*
2
3   server.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 1997 - 2002 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; either version 2 of the License, or
12   (at your option) any later version.
13
14   This program is distributed in the hope that it will be useful,
15   but WITHOUT ANY WARRANTY; without even the implied warranty of
16   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   GNU General Public License for more details.
18
19 */
20 /*
21  * This is the actual SILC server than handles everything relating to
22  * servicing the SILC connections. This is also a SILC router as a router
23  * is also normal server.
24  */
25 /* $Id$ */
26
27 #include "serverincludes.h"
28 #include "server_internal.h"
29
30 /* Static prototypes */
31 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry);
32 SILC_TASK_CALLBACK(silc_server_connect_router);
33 SILC_TASK_CALLBACK(silc_server_connect_to_router);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
35 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
38 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
39 SILC_TASK_CALLBACK(silc_server_packet_process);
40 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
41 SILC_TASK_CALLBACK(silc_server_close_connection_final);
42 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout);
43 SILC_TASK_CALLBACK(silc_server_timeout_remote);
44 SILC_TASK_CALLBACK(silc_server_channel_key_rekey);
45 SILC_TASK_CALLBACK(silc_server_failure_callback);
46 SILC_TASK_CALLBACK(silc_server_rekey_callback);
47
48 /* Allocates a new SILC server object. This has to be done before the server
49    can be used. After allocation one must call silc_server_init to initialize
50    the server. The new allocated server object is returned to the new_server
51    argument. */
52
53 int silc_server_alloc(SilcServer *new_server)
54 {
55   SilcServer server;
56
57   SILC_LOG_DEBUG(("Allocating new server object"));
58
59   server = silc_calloc(1, sizeof(*server));
60   server->server_type = SILC_SERVER;
61   server->standalone = TRUE;
62   server->local_list = silc_calloc(1, sizeof(*server->local_list));
63   server->global_list = silc_calloc(1, sizeof(*server->global_list));
64   server->pending_commands = silc_dlist_init();
65 #ifdef SILC_SIM
66   server->sim = silc_dlist_init();
67 #endif
68
69   *new_server = server;
70
71   return TRUE;
72 }
73
74 /* Free's the SILC server object. This is called at the very end before
75    the program ends. */
76
77 void silc_server_free(SilcServer server)
78 {
79   if (server) {
80 #ifdef SILC_SIM
81     SilcSim sim;
82
83     while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
84       silc_dlist_del(server->sim, sim);
85       silc_sim_free(sim);
86     }
87     silc_dlist_uninit(server->sim);
88 #endif
89
90     if (server->rng)
91       silc_rng_free(server->rng);
92     if (server->pkcs)
93       silc_pkcs_free(server->pkcs);
94     if (server->pending_commands)
95       silc_dlist_uninit(server->pending_commands);
96     if (server->id_entry)
97       silc_idlist_del_server(server->local_list, server->id_entry);
98
99     silc_idcache_free(server->local_list->clients);
100     silc_idcache_free(server->local_list->servers);
101     silc_idcache_free(server->local_list->channels);
102     silc_idcache_free(server->global_list->clients);
103     silc_idcache_free(server->global_list->servers);
104     silc_idcache_free(server->global_list->channels);
105
106     silc_free(server->sockets);
107     silc_free(server);
108   }
109 }
110
111 /* Opens a listening port.
112    XXX This function will become more general and will support multiple
113    listening ports */
114
115 static bool silc_server_listen(SilcServer server, int *sock)
116 {
117
118   *sock = silc_net_create_server(server->config->server_info->port,
119                                 server->config->server_info->server_ip);
120   if (*sock < 0) {
121     SILC_LOG_ERROR(("Could not create server listener: %s on %hu",
122                     server->config->server_info->server_ip,
123                     server->config->server_info->port));
124     return FALSE;
125   }
126   return TRUE;
127 }
128
129 /* Initializes the entire SILC server. This is called always before running
130    the server. This is called only once at the initialization of the program.
131    This binds the server to its listenning port. After this function returns
132    one should call silc_server_run to start the server. This returns TRUE
133    when everything is ok to run the server. Configuration file must be
134    read and parsed before calling this. */
135
136 bool silc_server_init(SilcServer server)
137 {
138   int sock;
139   SilcServerID *id;
140   SilcServerEntry id_entry;
141   SilcIDListPurge purge;
142
143   SILC_LOG_DEBUG(("Initializing server"));
144   assert(server);
145   assert(server->config);
146
147   /* Set public and private keys */
148   if (!server->config->server_info ||
149       !server->config->server_info->public_key ||
150       !server->config->server_info->private_key) {
151     SILC_LOG_ERROR(("Server public key and/or private key does not exist"));
152     return FALSE;
153   }
154
155   /* Steal public and private key from the config object */
156   server->public_key = server->config->server_info->public_key;
157   server->private_key = server->config->server_info->private_key;
158   server->config->server_info->public_key = NULL;
159   server->config->server_info->private_key = NULL;
160
161   /* Register all configured ciphers, PKCS and hash functions. */
162   if (!silc_server_config_register_ciphers(server))
163     silc_cipher_register_default();
164   if (!silc_server_config_register_pkcs(server))
165     silc_pkcs_register_default();
166   if (!silc_server_config_register_hashfuncs(server))
167     silc_hash_register_default();
168   if (!silc_server_config_register_hmacs(server))
169     silc_hmac_register_default();
170
171   /* Initialize random number generator for the server. */
172   server->rng = silc_rng_alloc();
173   silc_rng_init(server->rng);
174   silc_rng_global_init(server->rng);
175
176   /* Initialize hash functions for server to use */
177   silc_hash_alloc("md5", &server->md5hash);
178   silc_hash_alloc("sha1", &server->sha1hash);
179
180   /* Allocate PKCS context for local public and private keys */
181   silc_pkcs_alloc(server->public_key->name, &server->pkcs);
182   silc_pkcs_public_key_set(server->pkcs, server->public_key);
183   silc_pkcs_private_key_set(server->pkcs, server->private_key);
184
185   /* Initialize the scheduler */
186   server->schedule = silc_schedule_init(server->config->param.connections_max);
187   if (!server->schedule)
188     goto err;
189
190   /* First, register log files configuration for error output */
191   silc_server_config_setlogfiles(server);
192
193   /* Initialize ID caches */
194   server->local_list->clients =
195     silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
196   server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
197   server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
198
199   /* These are allocated for normal server as well as these hold some
200      global information that the server has fetched from its router. For
201      router these are used as they are supposed to be used on router. */
202   server->global_list->clients =
203     silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
204   server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
205   server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
206
207   /* Create a listening server */
208   if (!silc_server_listen(server, &sock))
209     goto err;
210
211   /* Allocate the entire socket list that is used in server. Eventually
212      all connections will have entry in this table (it is a table of
213      pointers to the actual object that is allocated individually
214      later). */
215   server->sockets = silc_calloc(server->config->param.connections_max,
216                                 sizeof(*server->sockets));
217
218   do {
219     SilcSocketConnection newsocket = NULL;
220
221     /* Set socket to non-blocking mode */
222     silc_net_set_socket_nonblock(sock);
223     server->sock = sock;
224
225     /* Add ourselves also to the socket table. The entry allocated above
226        is sent as argument for fast referencing in the future. */
227     silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
228     server->sockets[sock] = newsocket;
229
230     /* Perform name and address lookups to resolve the listenning address
231        and port. */
232     if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
233                                       &newsocket->ip)) {
234       if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
235           !newsocket->ip) {
236         SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
237                         newsocket->hostname ? newsocket->hostname :
238                         newsocket->ip ? newsocket->ip : ""));
239         server->stat.conn_failures++;
240         goto err;
241       }
242       if (!newsocket->hostname)
243         newsocket->hostname = strdup(newsocket->ip);
244     }
245     newsocket->port = silc_net_get_local_port(sock);
246
247     /* Create a Server ID for the server. */
248     silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
249     if (!id)
250       goto err;
251
252     server->id = id;
253     server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
254     server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
255     server->id_type = SILC_ID_SERVER;
256     server->server_name = server->config->server_info->server_name;
257     server->config->server_info->server_name = NULL;
258
259     /* Add ourselves to the server list. We don't have a router yet
260        beacuse we haven't established a route yet. It will be done later.
261        For now, NULL is sent as router. This allocates new entry to
262        the ID list. */
263     id_entry =
264       silc_idlist_add_server(server->local_list, strdup(server->server_name),
265                              server->server_type, server->id, NULL, NULL);
266     if (!id_entry) {
267       SILC_LOG_ERROR(("Could not add ourselves to cache"));
268       goto err;
269     }
270     id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
271
272     /* Put the allocated socket pointer also to the entry allocated above
273        for fast back-referencing to the socket list. */
274     newsocket->user_data = (void *)id_entry;
275     id_entry->connection = (void *)newsocket;
276     server->id_entry = id_entry;
277   } while (0);
278
279   /* Register protocols */
280   silc_server_protocols_register();
281
282   /* Add the first task to the scheduler. This is task that is executed by
283      timeout. It expires as soon as the caller calls silc_server_run. This
284      task performs authentication protocol and key exchange with our
285      primary router. */
286   silc_schedule_task_add(server->schedule, sock,
287                          silc_server_connect_to_router,
288                          (void *)server, 0, 1,
289                          SILC_TASK_TIMEOUT,
290                          SILC_TASK_PRI_NORMAL);
291
292   /* Add listener task to the scheduler. This task receives new connections
293      to the server. This task remains on the queue until the end of the
294      program. */
295   silc_schedule_task_add(server->schedule, sock,
296                          silc_server_accept_new_connection,
297                          (void *)server, 0, 0,
298                          SILC_TASK_FD,
299                          SILC_TASK_PRI_NORMAL);
300   server->listenning = TRUE;
301
302   /* If server connections has been configured then we must be router as
303      normal server cannot have server connections, only router connections. */
304   if (server->config->servers) {
305     SilcServerConfigServer *ptr = server->config->servers;
306
307     server->server_type = SILC_ROUTER;
308     while (ptr) {
309       if (ptr->backup_router) {
310         server->server_type = SILC_BACKUP_ROUTER;
311         server->backup_router = TRUE;
312         server->id_entry->server_type = SILC_BACKUP_ROUTER;
313         break;
314       }
315       ptr = ptr->next;
316     }
317   }
318
319   /* Register the ID Cache purge task. This periodically purges the ID cache
320      and removes the expired cache entries. */
321
322   /* Clients local list */
323   purge = silc_calloc(1, sizeof(*purge));
324   purge->cache = server->local_list->clients;
325   purge->schedule = server->schedule;
326   purge->timeout = 600;
327   silc_schedule_task_add(purge->schedule, 0,
328                          silc_idlist_purge,
329                          (void *)purge, purge->timeout, 0,
330                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
331
332   /* Clients global list */
333   purge = silc_calloc(1, sizeof(*purge));
334   purge->cache = server->global_list->clients;
335   purge->schedule = server->schedule;
336   purge->timeout = 300;
337   silc_schedule_task_add(purge->schedule, 0,
338                          silc_idlist_purge,
339                          (void *)purge, purge->timeout, 0,
340                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
341
342   SILC_LOG_DEBUG(("Server initialized"));
343
344   /* We are done here, return succesfully */
345   return TRUE;
346
347  err:
348   silc_net_close_server(sock);
349   return FALSE;
350 }
351
352 /* This function basically reads the config file again and switches the config
353    object pointed by the server object. After that, we have to fix various
354    things such as the server_name and the listening ports.
355    Keep in mind that we no longer have the root privileges at this point. */
356
357 bool silc_server_rehash(SilcServer server)
358 {
359   SilcServerConfig newconfig;
360
361   /* Reset the logging system */
362   silc_log_quick = TRUE;
363   silc_log_flush_all();
364
365   /* Start the main rehash phase (read again the config file) */
366   SILC_LOG_INFO(("Rehashing server"));
367   newconfig = silc_server_config_alloc(server->config_file);
368
369   if (!newconfig) {
370     SILC_LOG_ERROR(("Rehash FAILED."));
371     return FALSE;
372   }
373   silc_server_config_unref(&server->config_ref);
374   server->config = newconfig;
375   silc_server_config_ref(&server->config_ref, newconfig, (void *) newconfig);
376
377   /* Fix the server_name field */
378   if (!strcmp(server->server_name, newconfig->server_info->server_name)) {
379     /* We don't need any update */
380     silc_free(newconfig->server_info->server_name);
381     newconfig->server_info->server_name = NULL;
382   } else {
383     silc_free(server->server_name);
384     server->server_name = newconfig->server_info->server_name;
385     newconfig->server_info->server_name = NULL;
386
387     /* Update the idcache list with a fresh pointer */
388     silc_free(server->id_entry->server_name);
389     server->id_entry->server_name = strdup(server->server_name);
390     silc_idcache_del_by_context(server->local_list->servers, server->id_entry);
391     silc_idcache_add(server->local_list->servers, server->id_entry->server_name,
392                      server->id_entry->id, server->id_entry, 0, NULL);
393   }
394
395   silc_server_config_setlogfiles(server);
396
397   /* XXX There is still to implement the publickey change and modules
398      adding (we can't allow modules removing since we can't know which
399      one are actually in use */
400
401   return TRUE;
402 }
403
404 /* Drop root privileges. If some system call fails, die. */
405
406 void silc_server_drop(SilcServer server)
407 {
408   /* Are we executing silcd as root or a regular user? */
409   if (geteuid()) {
410     SILC_LOG_DEBUG(("Server started as user"));
411   }
412   else {
413     struct passwd *pw;
414     struct group *gr;
415     char *user, *group;
416
417     SILC_LOG_DEBUG(("Server started as root. Dropping privileges."));
418
419     /* Get the values given for user and group in configuration file */
420     user = server->config->server_info->user;
421     group = server->config->server_info->group;
422
423     if (!user || !group) {
424       fprintf(stderr, "Error:"
425        "\tSILC server must not be run as root.  For the security of your\n"
426        "\tsystem it is strongly suggested that you run SILC under dedicated\n"
427        "\tuser account.  Modify the ServerInfo configuration section to run\n"
428        "\tthe server as non-root user.\n");
429       exit(1);
430     }
431
432     /* Check whether the user/group does not begin with a number */
433     if (isdigit(user[0]) || isdigit(group[0])) {
434       SILC_LOG_DEBUG(("User and/or group starts with a number"));
435       fprintf(stderr, "Invalid user and/or group information\n");
436       fprintf(stderr, "Please assign them as names, not numbers\n");
437       exit(1);
438     }
439
440     if (!(pw = getpwnam(user))) {
441       fprintf(stderr, "Error: No such user %s found.\n", user);
442       exit(1);
443     }
444     if (!(gr = getgrnam(group))) {
445       fprintf(stderr, "Error: No such group %s found.\n", group);
446       exit(1);
447     }
448
449     /* Check whether user and/or group is set to root. If yes, exit
450        immediately. Otherwise, setgid and setuid server to user.group */
451     if ((gr->gr_gid == 0) || (pw->pw_uid == 0)) {
452       fprintf(stderr, "Error:"
453        "\tSILC server must not be run as root.  For the security of your\n"
454        "\tsystem it is strongly suggested that you run SILC under dedicated\n"
455        "\tuser account.  Modify the ServerInfo configuration section to run\n"
456        "\tthe server as non-root user.\n");
457       exit(1);
458     }
459
460     SILC_LOG_DEBUG(("Changing to group %s (gid=%u)", group, gr->gr_gid));
461     if (setgid(gr->gr_gid) != 0) {
462       fprintf(stderr, "Error: Failed setgid() to %s (gid=%u). Exiting.\n",
463               group, gr->gr_gid);
464       exit(1);
465     }
466 #if defined HAVE_SETGROUPS && defined HAVE_INITGROUPS
467     SILC_LOG_DEBUG(("Removing supplementary groups"));
468     if (setgroups(0, NULL) != 0) {
469       fprintf(stderr, "Error: Failed setgroups() to NULL. Exiting.\n");
470       exit(1);
471     }
472     SILC_LOG_DEBUG(("Setting supplementary groups for user %s", user));
473     if (initgroups(user, gr->gr_gid) != 0) {
474       fprintf(stderr, "Error: Failed initgroups() for user %s (gid=%u). "
475               "Exiting.\n", user, gr->gr_gid);
476       exit(1);
477     }
478 #endif
479     SILC_LOG_DEBUG(("Changing to user %s (uid=%u)", user, pw->pw_uid));
480     if (setuid(pw->pw_uid) != 0) {
481       fprintf(stderr, "Error: Failed to setuid() to %s (gid=%u). Exiting.\n",
482               user, pw->pw_uid);
483       exit(1);
484     }
485   }
486 }
487
488 /* Fork server to background */
489
490 void silc_server_daemonise(SilcServer server)
491 {
492   int i;
493
494   SILC_LOG_DEBUG(("Forking SILC server to background"));
495
496   if ((i = fork()) < 0) {
497     fprintf(stderr, "Error: fork() failed: %s\n", strerror(errno));
498     exit(1);
499   }
500
501   if (i) /* Kill the parent */
502     exit(0);
503
504   server->background = TRUE;
505   setsid();
506
507   /* XXX close stdin, stdout, stderr -- before this, check that all writes
508      to stderr are changed to SILC_SERVER_LOG_ERROR() */
509 }
510
511 /* The heart of the server. This runs the scheduler thus runs the server.
512    When this returns the server has been stopped and the program will
513    be terminated. */
514
515 void silc_server_run(SilcServer server)
516 {
517   SILC_LOG_INFO(("SILC Server started"));
518
519   /* Start the scheduler, the heart of the SILC server. When this returns
520      the program will be terminated. */
521   silc_schedule(server->schedule);
522 }
523
524 /* Stops the SILC server. This function is used to shutdown the server.
525    This is usually called after the scheduler has returned. After stopping
526    the server one should call silc_server_free. */
527
528 void silc_server_stop(SilcServer server)
529 {
530   SILC_LOG_DEBUG(("Stopping server"));
531
532   if (server->schedule) {
533     silc_schedule_stop(server->schedule);
534     silc_schedule_uninit(server->schedule);
535     server->schedule = NULL;
536   }
537
538   silc_server_protocols_unregister();
539
540   SILC_LOG_DEBUG(("Server stopped"));
541 }
542
543 /* Function that is called when the network connection to a router has
544    been established.  This will continue with the key exchange protocol
545    with the remote router. */
546
547 void silc_server_start_key_exchange(SilcServer server,
548                                     SilcServerConnection sconn,
549                                     int sock)
550 {
551   SilcSocketConnection newsocket;
552   SilcProtocol protocol;
553   SilcServerKEInternalContext *proto_ctx;
554   SilcServerConfigRouter *conn =
555     (SilcServerConfigRouter *) sconn->conn.ref_ptr;
556   void *context;
557
558   /* Cancel any possible retry timeouts */
559   silc_schedule_task_del_by_callback(server->schedule,
560                                      silc_server_connect_router);
561
562   /* Set socket options */
563   silc_net_set_socket_nonblock(sock);
564   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
565
566   /* Create socket connection for the connection. Even though we
567      know that we are connecting to a router we will mark the socket
568      to be unknown connection until we have executed authentication
569      protocol. */
570   silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
571   server->sockets[sock] = newsocket;
572   newsocket->hostname = strdup(sconn->remote_host);
573   newsocket->ip = strdup(sconn->remote_host);
574   newsocket->port = sconn->remote_port;
575   sconn->sock = newsocket;
576
577   /* Allocate internal protocol context. This is sent as context
578      to the protocol. */
579   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
580   proto_ctx->server = (void *)server;
581   proto_ctx->context = (void *)sconn;
582   proto_ctx->sock = newsocket;
583   proto_ctx->rng = server->rng;
584   proto_ctx->responder = FALSE;
585
586   /* Set Key Exchange flags from configuration, but fall back to global
587      settings too. */
588   SILC_GET_SKE_FLAGS(conn, proto_ctx);
589   if (server->config->param.key_exchange_pfs)
590     proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
591
592   /* Perform key exchange protocol. silc_server_connect_to_router_second
593      will be called after the protocol is finished. */
594   silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
595                       &protocol, proto_ctx,
596                       silc_server_connect_to_router_second);
597   newsocket->protocol = protocol;
598
599   /* Register a timeout task that will be executed if the protocol
600      is not executed within set limit. */
601   proto_ctx->timeout_task =
602     silc_schedule_task_add(server->schedule, sock,
603                            silc_server_timeout_remote,
604                            server, server->config->key_exchange_timeout, 0,
605                            SILC_TASK_TIMEOUT,
606                            SILC_TASK_PRI_LOW);
607
608   /* Register the connection for network input and output. This sets
609      that scheduler will listen for incoming packets for this connection
610      and sets that outgoing packets may be sent to this connection as
611      well. However, this doesn't set the scheduler for outgoing traffic,
612      it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
613      later when outgoing data is available. */
614   context = (void *)server;
615   SILC_REGISTER_CONNECTION_FOR_IO(sock);
616
617   /* Run the protocol */
618   silc_protocol_execute(protocol, server->schedule, 0, 0);
619 }
620
621 /* Timeout callback that will be called to retry connecting to remote
622    router. This is used by both normal and router server. This will wait
623    before retrying the connecting. The timeout is generated by exponential
624    backoff algorithm. */
625
626 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
627 {
628   SilcServerConnection sconn = (SilcServerConnection)context;
629   SilcServer server = sconn->server;
630   SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
631   SilcServerConfigConnParams *param =
632                 (conn->param ? conn->param : &server->config->param);
633
634   SILC_LOG_INFO(("Retrying connecting to a router"));
635
636   /* Calculate next timeout */
637   if (sconn->retry_count >= 1) {
638     sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
639     if (sconn->retry_timeout > param->reconnect_interval_max)
640       sconn->retry_timeout = param->reconnect_interval_max;
641   } else {
642     sconn->retry_timeout = param->reconnect_interval;
643   }
644   sconn->retry_count++;
645   sconn->retry_timeout = sconn->retry_timeout +
646     silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
647
648   /* If we've reached max retry count, give up. */
649   if ((sconn->retry_count > param->reconnect_count) &&
650       !param->reconnect_keep_trying) {
651     SILC_LOG_ERROR(("Could not connect to router, giving up"));
652     silc_server_config_unref(&sconn->conn);
653     silc_free(sconn->remote_host);
654     silc_free(sconn->backup_replace_ip);
655     silc_free(sconn);
656     return;
657   }
658
659   /* we will lookup a fresh pointer later */
660   silc_server_config_unref(&sconn->conn);
661
662   /* Wait one before retrying */
663   silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
664                          context, sconn->retry_timeout, 0,
665                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
666 }
667
668 /* Generic routine to use connect to a router. */
669
670 SILC_TASK_CALLBACK(silc_server_connect_router)
671 {
672   SilcServerConnection sconn = (SilcServerConnection)context;
673   SilcServer server = sconn->server;
674   SilcServerConfigRouter *rconn;
675   int sock;
676
677   SILC_LOG_INFO(("Connecting to the %s %s on port %d",
678                  (sconn->backup ? "backup router" : "router"),
679                  sconn->remote_host, sconn->remote_port));
680
681   server->router_connect = time(NULL);
682   rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
683                                               sconn->remote_port);
684   if (!rconn) {
685     SILC_LOG_INFO(("Unconfigured server, giving up"));
686     silc_free(sconn->remote_host);
687     silc_free(sconn->backup_replace_ip);
688     silc_free(sconn);
689     return;
690   }
691   silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
692
693   /* Connect to remote host */
694   sock = silc_net_create_connection(server->config->server_info->server_ip,
695                                     sconn->remote_port,
696                                     sconn->remote_host);
697   if (sock < 0) {
698     SILC_LOG_ERROR(("Could not connect to router %s:%d",
699                     sconn->remote_host, sconn->remote_port));
700     if (!sconn->no_reconnect)
701       silc_schedule_task_add(server->schedule, 0,
702                              silc_server_connect_to_router_retry,
703                              context, 0, 1, SILC_TASK_TIMEOUT,
704                              SILC_TASK_PRI_NORMAL);
705     else
706       silc_server_config_unref(&sconn->conn);
707     return;
708   }
709
710   /* Continue with key exchange protocol */
711   silc_server_start_key_exchange(server, sconn, sock);
712 }
713
714 /* This function connects to our primary router or if we are a router this
715    establishes all our primary routes. This is called at the start of the
716    server to do authentication and key exchange with our router - called
717    from schedule. */
718
719 SILC_TASK_CALLBACK(silc_server_connect_to_router)
720 {
721   SilcServer server = (SilcServer)context;
722   SilcServerConnection sconn;
723   SilcServerConfigRouter *ptr;
724
725   SILC_LOG_DEBUG(("Connecting to router(s)"));
726
727   if (server->server_type == SILC_SERVER) {
728     SILC_LOG_DEBUG(("We are normal server"));
729   } else if (server->server_type == SILC_ROUTER) {
730     SILC_LOG_DEBUG(("We are router"));
731   } else {
732     SILC_LOG_DEBUG(("We are backup router/normal server"));
733   }
734
735   if (!server->config->routers) {
736     /* There wasn't a configured router, we will continue but we don't
737        have a connection to outside world.  We will be standalone server. */
738     SILC_LOG_DEBUG(("No router(s), server will be standalone"));
739     server->standalone = TRUE;
740     return;
741   }
742
743   /* Create the connections to all our routes */
744   for (ptr = server->config->routers; ptr; ptr = ptr->next) {
745
746     SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
747                     ptr->backup_router ? "Backup router" : "Router",
748                     ptr->initiator ? "Initiator" : "Responder",
749                     ptr->host, ptr->port));
750
751     if (ptr->initiator) {
752       /* Allocate connection object for hold connection specific stuff. */
753       sconn = silc_calloc(1, sizeof(*sconn));
754       sconn->server = server;
755       sconn->remote_host = strdup(ptr->host);
756       sconn->remote_port = ptr->port;
757       sconn->backup = ptr->backup_router;
758       if (sconn->backup) {
759         sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
760         sconn->backup_replace_port = ptr->backup_replace_port;
761       }
762
763       if (!server->router_conn && !sconn->backup)
764         server->router_conn = sconn;
765
766       silc_schedule_task_add(server->schedule, fd,
767                              silc_server_connect_router,
768                              (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
769                              SILC_TASK_PRI_NORMAL);
770     }
771   }
772 }
773
774 /* Second part of connecting to router(s). Key exchange protocol has been
775    executed and now we will execute authentication protocol. */
776
777 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
778 {
779   SilcProtocol protocol = (SilcProtocol)context;
780   SilcServerKEInternalContext *ctx =
781     (SilcServerKEInternalContext *)protocol->context;
782   SilcServer server = (SilcServer)ctx->server;
783   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
784   SilcSocketConnection sock = ctx->sock;
785   SilcServerConnAuthInternalContext *proto_ctx;
786   SilcServerConfigRouter *conn = NULL;
787
788   SILC_LOG_DEBUG(("Start"));
789
790   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
791       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
792     /* Error occured during protocol */
793     silc_protocol_free(protocol);
794     sock->protocol = NULL;
795     silc_ske_free_key_material(ctx->keymat);
796     if (ctx->packet)
797       silc_packet_context_free(ctx->packet);
798     if (ctx->ske)
799       silc_ske_free(ctx->ske);
800     silc_free(ctx->dest_id);
801     silc_server_config_unref(&ctx->cconfig);
802     silc_server_config_unref(&ctx->sconfig);
803     silc_server_config_unref(&ctx->rconfig);
804     silc_free(ctx);
805     silc_server_config_unref(&sconn->conn);
806     silc_free(sconn->remote_host);
807     silc_free(sconn->backup_replace_ip);
808     silc_free(sconn);
809     silc_schedule_task_del_by_callback(server->schedule,
810                                        silc_server_failure_callback);
811     silc_server_disconnect_remote(server, sock, "Server closed connection: "
812                                   "Key exchange failed");
813     return;
814   }
815
816   /* We now have the key material as the result of the key exchange
817      protocol. Take the key material into use. Free the raw key material
818      as soon as we've set them into use. */
819   if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
820                                         ctx->sock, ctx->keymat,
821                                         ctx->ske->prop->cipher,
822                                         ctx->ske->prop->pkcs,
823                                         ctx->ske->prop->hash,
824                                         ctx->ske->prop->hmac,
825                                         ctx->ske->prop->group,
826                                         ctx->responder)) {
827     silc_protocol_free(protocol);
828     sock->protocol = NULL;
829     silc_ske_free_key_material(ctx->keymat);
830     if (ctx->packet)
831       silc_packet_context_free(ctx->packet);
832     if (ctx->ske)
833       silc_ske_free(ctx->ske);
834     silc_free(ctx->dest_id);
835     silc_free(ctx);
836     silc_server_config_unref(&sconn->conn);
837     silc_free(sconn->remote_host);
838     silc_free(sconn->backup_replace_ip);
839     silc_free(sconn);
840     silc_schedule_task_del_by_callback(server->schedule,
841                                        silc_server_failure_callback);
842     silc_server_disconnect_remote(server, sock, "Server closed connection: "
843                                   "Key exchange failed");
844     return;
845   }
846   silc_ske_free_key_material(ctx->keymat);
847
848   /* Allocate internal context for the authentication protocol. This
849      is sent as context for the protocol. */
850   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
851   proto_ctx->server = (void *)server;
852   proto_ctx->context = (void *)sconn;
853   proto_ctx->sock = sock;
854   proto_ctx->ske = ctx->ske;       /* Save SKE object from previous protocol */
855   proto_ctx->dest_id_type = ctx->dest_id_type;
856   proto_ctx->dest_id = ctx->dest_id;
857
858   /* Resolve the authentication method used in this connection. Check if
859      we find a match from user configured connections */
860   if (!sconn->conn.ref_ptr)
861     conn = silc_server_config_find_router_conn(server, sock->hostname,
862                                                sock->port);
863   else
864     conn = sconn->conn.ref_ptr;
865
866   if (conn) {
867     /* Match found. Use the configured authentication method. Take only
868        the passphrase, since for public key auth we automatically use
869        our local key pair. */
870     if (conn->passphrase) {
871       if (conn->publickeys && !server->config->prefer_passphrase_auth) {
872         proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
873       } else {
874         proto_ctx->auth_data = strdup(conn->passphrase);
875         proto_ctx->auth_data_len = strlen(conn->passphrase);
876         proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
877       }
878     } else if (conn->publickeys) {
879       proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
880     } else {
881       proto_ctx->auth_meth = SILC_AUTH_NONE;
882     }
883   } else {
884     SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
885                     sock->hostname, sock->ip, sock->port));
886     silc_protocol_free(protocol);
887     sock->protocol = NULL;
888     if (ctx->packet)
889       silc_packet_context_free(ctx->packet);
890     if (ctx->ske)
891       silc_ske_free(ctx->ske);
892     silc_free(ctx->dest_id);
893     silc_free(ctx);
894     silc_schedule_task_del_by_callback(server->schedule,
895                                        silc_server_failure_callback);
896     silc_server_disconnect_remote(server, sock, "Server closed connection: "
897                                   "Key exchange failed");
898     return;
899   }
900
901   /* Free old protocol as it is finished now */
902   silc_protocol_free(protocol);
903   if (ctx->packet)
904     silc_packet_context_free(ctx->packet);
905   silc_free(ctx);
906   sock->protocol = NULL;
907
908   /* Allocate the authentication protocol. This is allocated here
909      but we won't start it yet. We will be receiving party of this
910      protocol thus we will wait that connecting party will make
911      their first move. */
912   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
913                       &sock->protocol, proto_ctx,
914                       silc_server_connect_to_router_final);
915
916   /* Register timeout task. If the protocol is not executed inside
917      this timelimit the connection will be terminated. */
918   proto_ctx->timeout_task =
919     silc_schedule_task_add(server->schedule, sock->sock,
920                            silc_server_timeout_remote,
921                            (void *)server,
922                            server->config->conn_auth_timeout, 0,
923                            SILC_TASK_TIMEOUT,
924                            SILC_TASK_PRI_LOW);
925
926   /* Run the protocol */
927   silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
928 }
929
930 /* Finalizes the connection to router. Registers a server task to the
931    queue so that we can accept new connections. */
932
933 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
934 {
935   SilcProtocol protocol = (SilcProtocol)context;
936   SilcServerConnAuthInternalContext *ctx =
937     (SilcServerConnAuthInternalContext *)protocol->context;
938   SilcServer server = (SilcServer)ctx->server;
939   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
940   SilcSocketConnection sock = ctx->sock;
941   SilcServerEntry id_entry;
942   SilcBuffer packet;
943   SilcServerHBContext hb_context;
944   unsigned char *id_string;
945   SilcUInt32 id_len;
946   SilcIDListData idata;
947   SilcServerConfigRouter *conn = NULL;
948   SilcServerConfigConnParams *param = NULL;
949
950   SILC_LOG_DEBUG(("Start"));
951
952   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
953       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
954     /* Error occured during protocol */
955     silc_free(ctx->dest_id);
956     silc_server_disconnect_remote(server, sock, "Server closed connection: "
957                                   "Authentication failed");
958     goto out;
959   }
960
961   /* Add a task to the queue. This task receives new connections to the
962      server. This task remains on the queue until the end of the program. */
963   if (!server->listenning && !sconn->backup) {
964     silc_schedule_task_add(server->schedule, server->sock,
965                            silc_server_accept_new_connection,
966                            (void *)server, 0, 0,
967                            SILC_TASK_FD,
968                            SILC_TASK_PRI_NORMAL);
969     server->listenning = TRUE;
970   }
971
972   /* Send NEW_SERVER packet to the router. We will become registered
973      to the SILC network after sending this packet. */
974   id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
975   id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
976   packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
977   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
978   silc_buffer_format(packet,
979                      SILC_STR_UI_SHORT(id_len),
980                      SILC_STR_UI_XNSTRING(id_string, id_len),
981                      SILC_STR_UI_SHORT(strlen(server->server_name)),
982                      SILC_STR_UI_XNSTRING(server->server_name,
983                                           strlen(server->server_name)),
984                      SILC_STR_END);
985
986   /* Send the packet */
987   silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
988                           packet->data, packet->len, TRUE);
989   silc_buffer_free(packet);
990   silc_free(id_string);
991
992   SILC_LOG_INFO(("Connected to router %s", sock->hostname));
993
994   /* Check that we do not have this ID already */
995   id_entry = silc_idlist_find_server_by_id(server->local_list,
996                                            ctx->dest_id, TRUE, NULL);
997   if (id_entry) {
998     silc_idcache_del_by_context(server->local_list->servers, id_entry);
999   } else {
1000     id_entry = silc_idlist_find_server_by_id(server->global_list,
1001                                              ctx->dest_id, TRUE, NULL);
1002     if (id_entry)
1003       silc_idcache_del_by_context(server->global_list->servers, id_entry);
1004   }
1005
1006   SILC_LOG_DEBUG(("New server id(%s)",
1007                   silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1008
1009   /* Add the connected router to global server list */
1010   id_entry = silc_idlist_add_server(server->global_list,
1011                                     strdup(sock->hostname),
1012                                     SILC_ROUTER, ctx->dest_id, NULL, sock);
1013   if (!id_entry) {
1014     silc_free(ctx->dest_id);
1015     SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1016     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1017                                   "Authentication failed");
1018     goto out;
1019   }
1020
1021   silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1022   silc_free(sock->user_data);
1023   sock->user_data = (void *)id_entry;
1024   sock->type = SILC_SOCKET_TYPE_ROUTER;
1025   idata = (SilcIDListData)sock->user_data;
1026   idata->status |= SILC_IDLIST_STATUS_REGISTERED;
1027
1028   conn = sconn->conn.ref_ptr;
1029   param = &server->config->param;
1030   if (conn && conn->param)
1031     param = conn->param;
1032
1033   /* Perform keepalive. The `hb_context' will be freed automatically
1034      when finally calling the silc_socket_free function. */
1035   hb_context = silc_calloc(1, sizeof(*hb_context));
1036   hb_context->server = server;
1037   silc_socket_set_heartbeat(sock, param->keepalive_secs, hb_context,
1038                             silc_server_perform_heartbeat,
1039                             server->schedule);
1040
1041   /* Register re-key timeout */
1042   idata->rekey->timeout = param->key_exchange_rekey;
1043   idata->rekey->context = (void *)server;
1044   silc_schedule_task_add(server->schedule, sock->sock,
1045                          silc_server_rekey_callback,
1046                          (void *)sock, idata->rekey->timeout, 0,
1047                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1048
1049   if (!sconn->backup) {
1050     /* Mark this router our primary router if we're still standalone */
1051     if (server->standalone) {
1052       server->id_entry->router = id_entry;
1053       server->router = id_entry;
1054       server->standalone = FALSE;
1055
1056       /* If we are router then announce our possible servers. */
1057       if (server->server_type == SILC_ROUTER)
1058         silc_server_announce_servers(server, FALSE, 0,
1059                                      server->router->connection);
1060
1061       /* Announce our clients and channels to the router */
1062       silc_server_announce_clients(server, 0, server->router->connection);
1063       silc_server_announce_channels(server, 0, server->router->connection);
1064     }
1065   } else {
1066     /* Add this server to be our backup router */
1067     silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1068                            sconn->backup_replace_port, FALSE);
1069   }
1070
1071   sock->protocol = NULL;
1072
1073   /* Call the completion callback to indicate that we've connected to
1074      the router */
1075   if (sconn->callback)
1076     (*sconn->callback)(server, id_entry, sconn->callback_context);
1077
1078  out:
1079   /* Free the temporary connection data context */
1080   if (sconn) {
1081     silc_server_config_unref(&sconn->conn);
1082     silc_free(sconn->remote_host);
1083     silc_free(sconn->backup_replace_ip);
1084     silc_free(sconn);
1085   }
1086   if (sconn == server->router_conn)
1087     server->router_conn = NULL;
1088
1089   /* Free the protocol object */
1090   if (sock->protocol == protocol)
1091     sock->protocol = NULL;
1092   silc_protocol_free(protocol);
1093   if (ctx->packet)
1094     silc_packet_context_free(ctx->packet);
1095   if (ctx->ske)
1096     silc_ske_free(ctx->ske);
1097   if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1098     silc_free(ctx->auth_data);
1099   silc_free(ctx);
1100 }
1101
1102 /* Host lookup callback that is called after the incoming connection's
1103    IP and FQDN lookup is performed. This will actually check the acceptance
1104    of the incoming connection and will register the key exchange protocol
1105    for this connection. */
1106
1107 static void
1108 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1109                                          void *context)
1110 {
1111   SilcServer server = (SilcServer)context;
1112   SilcServerKEInternalContext *proto_ctx;
1113   SilcServerConfigClient *cconfig = NULL;
1114   SilcServerConfigServer *sconfig = NULL;
1115   SilcServerConfigRouter *rconfig = NULL;
1116   SilcServerConfigDeny *deny;
1117   int port;
1118
1119   SILC_LOG_DEBUG(("Start"));
1120
1121   /* Check whether we could resolve both IP and FQDN. */
1122   if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1123                     server->config->require_reverse_lookup)) {
1124     SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1125                     sock->hostname ? sock->hostname :
1126                     sock->ip ? sock->ip : ""));
1127     server->stat.conn_failures++;
1128     silc_server_disconnect_remote(server, sock,
1129                                   "Server closed connection: Unknown host");
1130     return;
1131   }
1132
1133   /* Register the connection for network input and output. This sets
1134      that scheduler will listen for incoming packets for this connection
1135      and sets that outgoing packets may be sent to this connection as well.
1136      However, this doesn't set the scheduler for outgoing traffic, it
1137      will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1138      later when outgoing data is available. */
1139   SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1140
1141   SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1142                  sock->ip));
1143
1144   port = server->sockets[server->sock]->port; /* Listenning port */
1145
1146   /* Check whether this connection is denied to connect to us. */
1147   deny = silc_server_config_find_denied(server, sock->ip);
1148   if (!deny)
1149     deny = silc_server_config_find_denied(server, sock->hostname);
1150   if (deny) {
1151     /* The connection is denied */
1152     SILC_LOG_INFO(("Connection %s (%s) is denied",
1153                    sock->hostname, sock->ip));
1154     silc_server_disconnect_remote(server, sock, deny->reason ?
1155                                   deny->reason :
1156                                   "Server closed connection: "
1157                                   "Connection refused");
1158     server->stat.conn_failures++;
1159     return;
1160   }
1161
1162   /* Check whether we have configured this sort of connection at all. We
1163      have to check all configurations since we don't know what type of
1164      connection this is. */
1165   if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1166     cconfig = silc_server_config_find_client(server, sock->hostname);
1167   if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1168     sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1169   if (server->server_type == SILC_ROUTER) {
1170     if (!(rconfig = silc_server_config_find_router_conn(server,
1171                                                         sock->ip, port)))
1172       rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1173                                                     sock->port);
1174   }
1175   if (!cconfig && !sconfig && !rconfig) {
1176     SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1177                    sock->ip));
1178     silc_server_disconnect_remote(server, sock,
1179                                   "Server closed connection: "
1180                                   "Connection refused");
1181     server->stat.conn_failures++;
1182     return;
1183   }
1184
1185   /* The connection is allowed */
1186
1187   /* Allocate internal context for key exchange protocol. This is
1188      sent as context for the protocol. */
1189   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1190   proto_ctx->server = context;
1191   proto_ctx->sock = sock;
1192   proto_ctx->rng = server->rng;
1193   proto_ctx->responder = TRUE;
1194   silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1195   silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1196   silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1197
1198   /* Take flags for key exchange. Since we do not know what type of connection
1199      this is, we go through all found configurations and use the global ones
1200      as well. This will result always into strictest key exchange flags. */
1201   SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1202   SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1203   SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1204   if (server->config->param.key_exchange_pfs)
1205     proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1206
1207   /* Prepare the connection for key exchange protocol. We allocate the
1208      protocol but will not start it yet. The connector will be the
1209      initiator of the protocol thus we will wait for initiation from
1210      there before we start the protocol. */
1211   server->stat.auth_attempts++;
1212   silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1213                       &sock->protocol, proto_ctx,
1214                       silc_server_accept_new_connection_second);
1215
1216   /* Register a timeout task that will be executed if the connector
1217      will not start the key exchange protocol within specified timeout
1218      and the connection will be closed. */
1219   proto_ctx->timeout_task =
1220     silc_schedule_task_add(server->schedule, sock->sock,
1221                            silc_server_timeout_remote,
1222                            context, server->config->key_exchange_timeout, 0,
1223                            SILC_TASK_TIMEOUT,
1224                            SILC_TASK_PRI_LOW);
1225 }
1226
1227 /* Accepts new connections to the server. Accepting new connections are
1228    done in three parts to make it async. */
1229
1230 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1231 {
1232   SilcServer server = (SilcServer)context;
1233   SilcSocketConnection newsocket;
1234   int sock;
1235
1236   SILC_LOG_DEBUG(("Accepting new connection"));
1237
1238   server->stat.conn_attempts++;
1239
1240   sock = silc_net_accept_connection(server->sock);
1241   if (sock < 0) {
1242     SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1243     server->stat.conn_failures++;
1244     return;
1245   }
1246
1247   /* Check for maximum allowed connections */
1248   if (sock > server->config->param.connections_max) {
1249     SILC_LOG_ERROR(("Refusing connection, server is full, try again later"));
1250     server->stat.conn_failures++;
1251     silc_net_close_connection(sock);
1252     return;
1253   }
1254
1255   /* Set socket options */
1256   silc_net_set_socket_nonblock(sock);
1257   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1258
1259   /* We don't create a ID yet, since we don't know what type of connection
1260      this is yet. But, we do add the connection to the socket table. */
1261   silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1262   server->sockets[sock] = newsocket;
1263
1264   /* Perform asynchronous host lookup. This will lookup the IP and the
1265      FQDN of the remote connection. After the lookup is done the connection
1266      is accepted further. */
1267   silc_socket_host_lookup(newsocket, TRUE,
1268                           silc_server_accept_new_connection_lookup, context,
1269                           server->schedule);
1270 }
1271
1272 /* Second part of accepting new connection. Key exchange protocol has been
1273    performed and now it is time to do little connection authentication
1274    protocol to figure out whether this connection is client or server
1275    and whether it has right to access this server (especially server
1276    connections needs to be authenticated). */
1277
1278 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1279 {
1280   SilcProtocol protocol = (SilcProtocol)context;
1281   SilcServerKEInternalContext *ctx =
1282     (SilcServerKEInternalContext *)protocol->context;
1283   SilcServer server = (SilcServer)ctx->server;
1284   SilcSocketConnection sock = ctx->sock;
1285   SilcServerConnAuthInternalContext *proto_ctx;
1286
1287   SILC_LOG_DEBUG(("Start"));
1288
1289   if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1290       (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1291     /* Error occured during protocol */
1292     silc_protocol_free(protocol);
1293     sock->protocol = NULL;
1294     silc_ske_free_key_material(ctx->keymat);
1295     if (ctx->packet)
1296       silc_packet_context_free(ctx->packet);
1297     if (ctx->ske)
1298       silc_ske_free(ctx->ske);
1299     silc_free(ctx->dest_id);
1300     silc_server_config_unref(&ctx->cconfig);
1301     silc_server_config_unref(&ctx->sconfig);
1302     silc_server_config_unref(&ctx->rconfig);
1303     silc_free(ctx);
1304     silc_schedule_task_del_by_callback(server->schedule,
1305                                        silc_server_failure_callback);
1306     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1307                                   "Key exchange failed");
1308     server->stat.auth_failures++;
1309     return;
1310   }
1311
1312   /* We now have the key material as the result of the key exchange
1313      protocol. Take the key material into use. Free the raw key material
1314      as soon as we've set them into use. */
1315   if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1316                                         ctx->sock, ctx->keymat,
1317                                         ctx->ske->prop->cipher,
1318                                         ctx->ske->prop->pkcs,
1319                                         ctx->ske->prop->hash,
1320                                         ctx->ske->prop->hmac,
1321                                         ctx->ske->prop->group,
1322                                         ctx->responder)) {
1323     silc_protocol_free(protocol);
1324     sock->protocol = NULL;
1325     silc_ske_free_key_material(ctx->keymat);
1326     if (ctx->packet)
1327       silc_packet_context_free(ctx->packet);
1328     if (ctx->ske)
1329       silc_ske_free(ctx->ske);
1330     silc_free(ctx->dest_id);
1331     silc_server_config_unref(&ctx->cconfig);
1332     silc_server_config_unref(&ctx->sconfig);
1333     silc_server_config_unref(&ctx->rconfig);
1334     silc_free(ctx);
1335     silc_schedule_task_del_by_callback(server->schedule,
1336                                        silc_server_failure_callback);
1337     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1338                                   "Key exchange failed");
1339     server->stat.auth_failures++;
1340     return;
1341   }
1342   silc_ske_free_key_material(ctx->keymat);
1343
1344   /* Allocate internal context for the authentication protocol. This
1345      is sent as context for the protocol. */
1346   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1347   proto_ctx->server = (void *)server;
1348   proto_ctx->sock = sock;
1349   proto_ctx->ske = ctx->ske;    /* Save SKE object from previous protocol */
1350   proto_ctx->responder = TRUE;
1351   proto_ctx->dest_id_type = ctx->dest_id_type;
1352   proto_ctx->dest_id = ctx->dest_id;
1353   proto_ctx->cconfig = ctx->cconfig;
1354   proto_ctx->sconfig = ctx->sconfig;
1355   proto_ctx->rconfig = ctx->rconfig;
1356
1357   /* Free old protocol as it is finished now */
1358   silc_protocol_free(protocol);
1359   if (ctx->packet)
1360     silc_packet_context_free(ctx->packet);
1361   silc_free(ctx);
1362   sock->protocol = NULL;
1363
1364   /* Allocate the authentication protocol. This is allocated here
1365      but we won't start it yet. We will be receiving party of this
1366      protocol thus we will wait that connecting party will make
1367      their first move. */
1368   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1369                       &sock->protocol, proto_ctx,
1370                       silc_server_accept_new_connection_final);
1371
1372   /* Register timeout task. If the protocol is not executed inside
1373      this timelimit the connection will be terminated. */
1374   proto_ctx->timeout_task =
1375     silc_schedule_task_add(server->schedule, sock->sock,
1376                            silc_server_timeout_remote,
1377                            (void *)server,
1378                            server->config->conn_auth_timeout, 0,
1379                            SILC_TASK_TIMEOUT,
1380                            SILC_TASK_PRI_LOW);
1381 }
1382
1383 /* Final part of accepting new connection. The connection has now
1384    been authenticated and keys has been exchanged. We also know whether
1385    this is client or server connection. */
1386
1387 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1388 {
1389   SilcProtocol protocol = (SilcProtocol)context;
1390   SilcServerConnAuthInternalContext *ctx =
1391     (SilcServerConnAuthInternalContext *)protocol->context;
1392   SilcServer server = (SilcServer)ctx->server;
1393   SilcSocketConnection sock = ctx->sock;
1394   SilcServerHBContext hb_context;
1395   SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1396   void *id_entry;
1397   SilcUInt32 hearbeat_timeout = server->config->param.keepalive_secs;
1398
1399   SILC_LOG_DEBUG(("Start"));
1400
1401   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1402       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1403     /* Error occured during protocol */
1404     silc_protocol_free(protocol);
1405     sock->protocol = NULL;
1406     if (ctx->packet)
1407       silc_packet_context_free(ctx->packet);
1408     if (ctx->ske)
1409       silc_ske_free(ctx->ske);
1410     silc_free(ctx->dest_id);
1411     silc_server_config_unref(&ctx->cconfig);
1412     silc_server_config_unref(&ctx->sconfig);
1413     silc_server_config_unref(&ctx->rconfig);
1414     silc_free(ctx);
1415     silc_schedule_task_del_by_callback(server->schedule,
1416                                        silc_server_failure_callback);
1417     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1418                                   "Authentication failed");
1419     server->stat.auth_failures++;
1420     return;
1421   }
1422
1423   entry->data.last_receive = time(NULL);
1424
1425   switch (ctx->conn_type) {
1426   case SILC_SOCKET_TYPE_CLIENT:
1427     {
1428       SilcClientEntry client;
1429       SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1430
1431       /* Verify whether this connection is after all allowed to connect */
1432       if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1433                                           &server->config->param,
1434                                           conn->param, ctx->ske)) {
1435         server->stat.auth_failures++;
1436         goto out;
1437       }
1438
1439       SILC_LOG_DEBUG(("Remote host is client"));
1440       SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1441                      sock->ip));
1442
1443       /* Add the client to the client ID cache. The nickname and Client ID
1444          and other information is created after we have received NEW_CLIENT
1445          packet from client. */
1446       client = silc_idlist_add_client(server->local_list,
1447                                       NULL, NULL, NULL, NULL, NULL, sock, 0);
1448       if (!client) {
1449         SILC_LOG_ERROR(("Could not add new client to cache"));
1450         silc_free(sock->user_data);
1451         silc_server_disconnect_remote(server, sock,
1452                                       "Server closed connection: "
1453                                       "Authentication failed");
1454         server->stat.auth_failures++;
1455         goto out;
1456       }
1457
1458       /* Statistics */
1459       server->stat.my_clients++;
1460       server->stat.clients++;
1461       if (server->server_type == SILC_ROUTER)
1462         server->stat.cell_clients++;
1463
1464       /* Get connection parameters */
1465       if (conn->param) {
1466         if (conn->param->keepalive_secs)
1467           hearbeat_timeout = conn->param->keepalive_secs;
1468       }
1469
1470       id_entry = (void *)client;
1471       break;
1472     }
1473   case SILC_SOCKET_TYPE_SERVER:
1474   case SILC_SOCKET_TYPE_ROUTER:
1475     {
1476       SilcServerEntry new_server;
1477       bool initiator = FALSE;
1478       bool backup_local = FALSE;
1479       bool backup_router = FALSE;
1480       char *backup_replace_ip = NULL;
1481       SilcUInt16 backup_replace_port = 0;
1482       SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1483       SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1484
1485       if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1486         /* Verify whether this connection is after all allowed to connect */
1487         if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1488                                             &server->config->param,
1489                                             rconn ? rconn->param : NULL,
1490                                             ctx->ske)) {
1491           server->stat.auth_failures++;
1492           goto out;
1493         }
1494
1495         if (rconn) {
1496           if (rconn->param) {
1497             if (rconn->param->keepalive_secs)
1498               hearbeat_timeout = rconn->param->keepalive_secs;
1499           }
1500
1501           initiator = rconn->initiator;
1502           backup_local = rconn->backup_local;
1503           backup_router = rconn->backup_router;
1504           backup_replace_ip = rconn->backup_replace_ip;
1505           backup_replace_port = rconn->backup_replace_port;
1506         }
1507       }
1508
1509       if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1510         /* Verify whether this connection is after all allowed to connect */
1511         if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1512                                             &server->config->param,
1513                                             sconn ? sconn->param : NULL,
1514                                             ctx->ske)) {
1515           server->stat.auth_failures++;
1516           goto out;
1517         }
1518         if (sconn) {
1519           if (sconn->param) {
1520             if (sconn->param->keepalive_secs)
1521               hearbeat_timeout = sconn->param->keepalive_secs;
1522           }
1523
1524           backup_router = sconn->backup_router;
1525         }
1526       }
1527
1528       SILC_LOG_DEBUG(("Remote host is %s",
1529                       ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1530                       "server" : (backup_router ?
1531                                   "backup router" : "router")));
1532       SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
1533                      sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1534                      "server" : (backup_router ?
1535                                  "backup router" : "router")));
1536
1537       /* Add the server into server cache. The server name and Server ID
1538          is updated after we have received NEW_SERVER packet from the
1539          server. We mark ourselves as router for this server if we really
1540          are router. */
1541       new_server =
1542         silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1543                                 server->local_list : (backup_router ?
1544                                                       server->local_list :
1545                                                       server->global_list)),
1546                                NULL,
1547                                (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1548                                 SILC_SERVER : SILC_ROUTER),
1549                                NULL,
1550                                (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1551                                 server->id_entry : (backup_router ?
1552                                                     server->id_entry : NULL)),
1553                                sock);
1554       if (!new_server) {
1555         SILC_LOG_ERROR(("Could not add new server to cache"));
1556         silc_free(sock->user_data);
1557         silc_server_disconnect_remote(server, sock,
1558                                       "Server closed connection: "
1559                                       "Authentication failed");
1560         server->stat.auth_failures++;
1561         goto out;
1562       }
1563
1564       /* Statistics */
1565       if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1566         server->stat.my_servers++;
1567       else
1568         server->stat.my_routers++;
1569       server->stat.servers++;
1570
1571       id_entry = (void *)new_server;
1572
1573       /* If the incoming connection is router and marked as backup router
1574          then add it to be one of our backups */
1575       if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
1576         silc_server_backup_add(server, new_server, backup_replace_ip,
1577                                backup_replace_port, backup_local);
1578
1579         /* Change it back to SERVER type since that's what it really is. */
1580         if (backup_local)
1581           ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1582
1583         new_server->server_type = SILC_BACKUP_ROUTER;
1584       }
1585
1586       /* Check whether this connection is to be our primary router connection
1587          if we do not already have the primary route. */
1588       if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1589         if (silc_server_config_is_primary_route(server) && !initiator)
1590           break;
1591
1592         SILC_LOG_DEBUG(("We are not standalone server anymore"));
1593         server->standalone = FALSE;
1594         if (!server->id_entry->router) {
1595           server->id_entry->router = id_entry;
1596           server->router = id_entry;
1597         }
1598       }
1599
1600       break;
1601     }
1602   default:
1603     goto out;
1604     break;
1605   }
1606
1607   sock->type = ctx->conn_type;
1608
1609   /* Add the common data structure to the ID entry. */
1610   silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1611
1612   /* Add to sockets internal pointer for fast referencing */
1613   silc_free(sock->user_data);
1614   sock->user_data = id_entry;
1615
1616   /* Connection has been fully established now. Everything is ok. */
1617   SILC_LOG_DEBUG(("New connection authenticated"));
1618
1619   /* Perform keepalive. The `hb_context' will be freed automatically
1620      when finally calling the silc_socket_free function. */
1621   hb_context = silc_calloc(1, sizeof(*hb_context));
1622   hb_context->server = server;
1623   silc_socket_set_heartbeat(sock, hearbeat_timeout, hb_context,
1624                             silc_server_perform_heartbeat,
1625                             server->schedule);
1626
1627  out:
1628   silc_schedule_task_del_by_callback(server->schedule,
1629                                      silc_server_failure_callback);
1630   silc_protocol_free(protocol);
1631   if (ctx->packet)
1632     silc_packet_context_free(ctx->packet);
1633   if (ctx->ske)
1634     silc_ske_free(ctx->ske);
1635   silc_free(ctx->dest_id);
1636   silc_server_config_unref(&ctx->cconfig);
1637   silc_server_config_unref(&ctx->sconfig);
1638   silc_server_config_unref(&ctx->rconfig);
1639   silc_free(ctx);
1640   sock->protocol = NULL;
1641 }
1642
1643 /* This function is used to read packets from network and send packets to
1644    network. This is usually a generic task. */
1645
1646 SILC_TASK_CALLBACK(silc_server_packet_process)
1647 {
1648   SilcServer server = (SilcServer)context;
1649   SilcSocketConnection sock = server->sockets[fd];
1650   SilcIDListData idata;
1651   SilcCipher cipher = NULL;
1652   SilcHmac hmac = NULL;
1653   SilcUInt32 sequence = 0;
1654   int ret;
1655
1656   if (!sock)
1657     return;
1658
1659   SILC_LOG_DEBUG(("Processing packet"));
1660
1661   /* Packet sending */
1662
1663   if (type == SILC_TASK_WRITE) {
1664     /* Do not send data to disconnected connection */
1665     if (SILC_IS_DISCONNECTED(sock))
1666       return;
1667
1668     server->stat.packets_sent++;
1669
1670     /* Send the packet */
1671     ret = silc_packet_send(sock, TRUE);
1672
1673     /* If returned -2 could not write to connection now, will do
1674        it later. */
1675     if (ret == -2)
1676       return;
1677
1678     if (ret == -1) {
1679       SILC_LOG_ERROR(("Error sending packet to connection "
1680                       "%s:%d [%s]", sock->hostname, sock->port,
1681                       (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1682                        sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1683                        sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1684                        "Router")));
1685       return;
1686     }
1687
1688     /* The packet has been sent and now it is time to set the connection
1689        back to only for input. When there is again some outgoing data
1690        available for this connection it will be set for output as well.
1691        This call clears the output setting and sets it only for input. */
1692     SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1693     SILC_UNSET_OUTBUF_PENDING(sock);
1694
1695     silc_buffer_clear(sock->outbuf);
1696     return;
1697   }
1698
1699   /* Packet receiving */
1700
1701   /* Read some data from connection */
1702   ret = silc_packet_receive(sock);
1703   if (ret < 0) {
1704
1705     if (ret == -1)
1706       SILC_LOG_ERROR(("Error receiving packet from connection "
1707                       "%s:%d [%s] %s", sock->hostname, sock->port,
1708                       (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1709                        sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1710                        sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1711                        "Router"), strerror(errno)));
1712     return;
1713   }
1714
1715   /* EOF */
1716   if (ret == 0) {
1717     SILC_LOG_DEBUG(("Read EOF"));
1718
1719     /* If connection is disconnecting already we will finally
1720        close the connection */
1721     if (SILC_IS_DISCONNECTING(sock)) {
1722       if (sock->user_data)
1723         silc_server_free_sock_user_data(server, sock, NULL);
1724       silc_server_close_connection(server, sock);
1725       return;
1726     }
1727
1728     SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1729     SILC_SET_DISCONNECTING(sock);
1730
1731     if (sock->user_data) {
1732       char tmp[128];
1733       if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
1734         silc_server_free_sock_user_data(server, sock, tmp);
1735       else
1736         silc_server_free_sock_user_data(server, sock, NULL);
1737     } else if (server->router_conn && server->router_conn->sock == sock &&
1738              !server->router && server->standalone)
1739       silc_schedule_task_add(server->schedule, 0,
1740                              silc_server_connect_to_router,
1741                              server, 1, 0,
1742                              SILC_TASK_TIMEOUT,
1743                              SILC_TASK_PRI_NORMAL);
1744
1745     silc_server_close_connection(server, sock);
1746     return;
1747   }
1748
1749   /* If connection is disconnecting or disconnected we will ignore
1750      what we read. */
1751   if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1752     SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
1753     return;
1754   }
1755
1756   server->stat.packets_received++;
1757
1758   /* Get keys and stuff from ID entry */
1759   idata = (SilcIDListData)sock->user_data;
1760   if (idata) {
1761     cipher = idata->receive_key;
1762     hmac = idata->hmac_receive;
1763     sequence = idata->psn_receive;
1764   }
1765
1766   /* Process the packet. This will call the parser that will then
1767      decrypt and parse the packet. */
1768   ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1769                                     TRUE : FALSE, cipher, hmac, sequence,
1770                                     silc_server_packet_parse, server);
1771
1772   /* If this socket connection is not authenticated yet and the packet
1773      processing failed we will drop the connection since it can be
1774      a malicious flooder. */
1775   if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
1776       (!sock->protocol || sock->protocol->protocol->type ==
1777        SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
1778     SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
1779     SILC_SET_DISCONNECTING(sock);
1780
1781     if (sock->user_data)
1782       silc_server_free_sock_user_data(server, sock, NULL);
1783     silc_server_close_connection(server, sock);
1784   }
1785 }
1786
1787 /* Parses whole packet, received earlier. */
1788
1789 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1790 {
1791   SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1792   SilcServer server = (SilcServer)parse_ctx->context;
1793   SilcSocketConnection sock = parse_ctx->sock;
1794   SilcPacketContext *packet = parse_ctx->packet;
1795   SilcIDListData idata = (SilcIDListData)sock->user_data;
1796   int ret;
1797
1798   SILC_LOG_DEBUG(("Start"));
1799
1800   /* Parse the packet */
1801   if (parse_ctx->normal)
1802     ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
1803   else
1804     ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
1805
1806   /* If entry is disabled ignore what we got. */
1807   if (ret != SILC_PACKET_RESUME_ROUTER &&
1808       idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1809     SILC_LOG_DEBUG(("Connection is disabled"));
1810     goto out;
1811   }
1812
1813   if (ret == SILC_PACKET_NONE)
1814     goto out;
1815
1816   /* Check that the the current client ID is same as in the client's packet. */
1817   if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1818     SilcClientEntry client = (SilcClientEntry)sock->user_data;
1819     if (client && client->id) {
1820       void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1821                                 packet->src_id_type);
1822       if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1823         silc_free(id);
1824         goto out;
1825       }
1826       silc_free(id);
1827     }
1828   }
1829
1830   if (server->server_type == SILC_ROUTER) {
1831     /* Route the packet if it is not destined to us. Other ID types but
1832        server are handled separately after processing them. */
1833     if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1834         packet->dst_id_type == SILC_ID_SERVER &&
1835         sock->type != SILC_SOCKET_TYPE_CLIENT &&
1836         memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1837
1838       /* Route the packet to fastest route for the destination ID */
1839       void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1840                                 packet->dst_id_type);
1841       if (!id)
1842         goto out;
1843       silc_server_packet_route(server,
1844                                silc_server_route_get(server, id,
1845                                                      packet->dst_id_type),
1846                                packet);
1847       silc_free(id);
1848       goto out;
1849     }
1850   }
1851
1852   /* Parse the incoming packet type */
1853   silc_server_packet_parse_type(server, sock, packet);
1854
1855   if (server->server_type == SILC_ROUTER) {
1856     /* Broadcast packet if it is marked as broadcast packet and it is
1857        originated from router and we are router. */
1858     if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1859         packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1860         !server->standalone) {
1861       /* Broadcast to our primary route */
1862       silc_server_packet_broadcast(server, server->router->connection, packet);
1863
1864       /* If we have backup routers then we need to feed all broadcast
1865          data to those servers. */
1866       silc_server_backup_broadcast(server, sock, packet);
1867     }
1868   }
1869
1870  out:
1871   silc_packet_context_free(packet);
1872   silc_free(parse_ctx);
1873 }
1874
1875 /* Parser callback called by silc_packet_receive_process. This merely
1876    registers timeout that will handle the actual parsing when appropriate. */
1877
1878 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
1879                               void *context)
1880 {
1881   SilcServer server = (SilcServer)context;
1882   SilcSocketConnection sock = parser_context->sock;
1883   SilcIDListData idata = (SilcIDListData)sock->user_data;
1884
1885   if (idata)
1886     idata->psn_receive = parser_context->packet->sequence + 1;
1887
1888   /* If protocol for this connection is key exchange or rekey then we'll
1889      process all packets synchronously, since there might be packets in
1890      queue that we are not able to decrypt without first processing the
1891      packets before them. */
1892   if ((parser_context->packet->type == SILC_PACKET_REKEY ||
1893        parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
1894       (sock->protocol && sock->protocol->protocol &&
1895        (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1896         sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
1897     silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1898                                   parser_context);
1899
1900     /* Reprocess data since we'll return FALSE here.  This is because
1901        the idata->receive_key might have become valid in the last packet
1902        and we want to call this processor with valid cipher. */
1903     if (idata)
1904       silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1905                                   TRUE : FALSE, idata->receive_key,
1906                                   idata->hmac_receive, idata->psn_receive,
1907                                   silc_server_packet_parse, server);
1908     else
1909       silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1910                                   TRUE : FALSE, NULL, NULL, 0,
1911                                   silc_server_packet_parse, server);
1912     return FALSE;
1913   }
1914
1915   switch (sock->type) {
1916   case SILC_SOCKET_TYPE_UNKNOWN:
1917   case SILC_SOCKET_TYPE_CLIENT:
1918     /* Parse the packet with timeout */
1919     silc_schedule_task_add(server->schedule, sock->sock,
1920                            silc_server_packet_parse_real,
1921                            (void *)parser_context, 0, 100000,
1922                            SILC_TASK_TIMEOUT,
1923                            SILC_TASK_PRI_NORMAL);
1924     break;
1925   case SILC_SOCKET_TYPE_SERVER:
1926   case SILC_SOCKET_TYPE_ROUTER:
1927     /* Packets from servers are parsed immediately */
1928     silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1929                                   parser_context);
1930     break;
1931   default:
1932     return TRUE;
1933   }
1934
1935   return TRUE;
1936 }
1937
1938 /* Parses the packet type and calls what ever routines the packet type
1939    requires. This is done for all incoming packets. */
1940
1941 void silc_server_packet_parse_type(SilcServer server,
1942                                    SilcSocketConnection sock,
1943                                    SilcPacketContext *packet)
1944 {
1945   SilcPacketType type = packet->type;
1946   SilcIDListData idata = (SilcIDListData)sock->user_data;
1947
1948   SILC_LOG_DEBUG(("Parsing packet type %d", type));
1949
1950   /* Parse the packet type */
1951   switch (type) {
1952   case SILC_PACKET_DISCONNECT:
1953     SILC_LOG_DEBUG(("Disconnect packet"));
1954     if (packet->flags & SILC_PACKET_FLAG_LIST)
1955       break;
1956     if (silc_string_is_ascii(packet->buffer->data, packet->buffer->len)) {
1957       /* Duplicate to null terminate the string. */
1958       char *message = silc_memdup(packet->buffer->data, packet->buffer->len);
1959       SILC_LOG_ERROR(("%s", message));
1960       silc_free(message);
1961     }
1962     break;
1963
1964   case SILC_PACKET_SUCCESS:
1965     /*
1966      * Success received for something. For now we can have only
1967      * one protocol for connection executing at once hence this
1968      * success message is for whatever protocol is executing currently.
1969      */
1970     SILC_LOG_DEBUG(("Success packet"));
1971     if (packet->flags & SILC_PACKET_FLAG_LIST)
1972       break;
1973     if (sock->protocol)
1974       silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1975     break;
1976
1977   case SILC_PACKET_FAILURE:
1978     /*
1979      * Failure received for something. For now we can have only
1980      * one protocol for connection executing at once hence this
1981      * failure message is for whatever protocol is executing currently.
1982      */
1983     SILC_LOG_DEBUG(("Failure packet"));
1984     if (packet->flags & SILC_PACKET_FLAG_LIST)
1985       break;
1986     if (sock->protocol) {
1987       SilcServerFailureContext f;
1988       f = silc_calloc(1, sizeof(*f));
1989       f->server = server;
1990       f->sock = sock;
1991
1992       /* We will wait 5 seconds to process this failure packet */
1993       silc_schedule_task_add(server->schedule, sock->sock,
1994                          silc_server_failure_callback, (void *)f, 5, 0,
1995                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1996     }
1997     break;
1998
1999   case SILC_PACKET_REJECT:
2000     SILC_LOG_DEBUG(("Reject packet"));
2001     if (packet->flags & SILC_PACKET_FLAG_LIST)
2002       break;
2003     return;
2004     break;
2005
2006   case SILC_PACKET_NOTIFY:
2007     /*
2008      * Received notify packet. Server can receive notify packets from
2009      * router. Server then relays the notify messages to clients if needed.
2010      */
2011     SILC_LOG_DEBUG(("Notify packet"));
2012     if (packet->flags & SILC_PACKET_FLAG_LIST)
2013       silc_server_notify_list(server, sock, packet);
2014     else
2015       silc_server_notify(server, sock, packet);
2016     break;
2017
2018     /*
2019      * Channel packets
2020      */
2021   case SILC_PACKET_CHANNEL_MESSAGE:
2022     /*
2023      * Received channel message. Channel messages are special packets
2024      * (although probably most common ones) thus they are handled
2025      * specially.
2026      */
2027     SILC_LOG_DEBUG(("Channel Message packet"));
2028     if (packet->flags & SILC_PACKET_FLAG_LIST)
2029       break;
2030     idata->last_receive = time(NULL);
2031     silc_server_channel_message(server, sock, packet);
2032     break;
2033
2034   case SILC_PACKET_CHANNEL_KEY:
2035     /*
2036      * Received key for channel. As channels are created by the router
2037      * the keys are as well. We will distribute the key to all of our
2038      * locally connected clients on the particular channel. Router
2039      * never receives this channel and thus is ignored.
2040      */
2041     SILC_LOG_DEBUG(("Channel Key packet"));
2042     if (packet->flags & SILC_PACKET_FLAG_LIST)
2043       break;
2044     silc_server_channel_key(server, sock, packet);
2045     break;
2046
2047     /*
2048      * Command packets
2049      */
2050   case SILC_PACKET_COMMAND:
2051     /*
2052      * Recived command. Processes the command request and allocates the
2053      * command context and calls the command.
2054      */
2055     SILC_LOG_DEBUG(("Command packet"));
2056     if (packet->flags & SILC_PACKET_FLAG_LIST)
2057       break;
2058     silc_server_command_process(server, sock, packet);
2059     break;
2060
2061   case SILC_PACKET_COMMAND_REPLY:
2062     /*
2063      * Received command reply packet. Received command reply to command. It
2064      * may be reply to command sent by us or reply to command sent by client
2065      * that we've routed further.
2066      */
2067     SILC_LOG_DEBUG(("Command Reply packet"));
2068     if (packet->flags & SILC_PACKET_FLAG_LIST)
2069       break;
2070     silc_server_command_reply(server, sock, packet);
2071     break;
2072
2073     /*
2074      * Private Message packets
2075      */
2076   case SILC_PACKET_PRIVATE_MESSAGE:
2077     /*
2078      * Received private message packet. The packet is coming from either
2079      * client or server.
2080      */
2081     SILC_LOG_DEBUG(("Private Message packet"));
2082     if (packet->flags & SILC_PACKET_FLAG_LIST)
2083       break;
2084     idata->last_receive = time(NULL);
2085     silc_server_private_message(server, sock, packet);
2086     break;
2087
2088   case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2089     /*
2090      * Private message key packet.
2091      */
2092     if (packet->flags & SILC_PACKET_FLAG_LIST)
2093       break;
2094     silc_server_private_message_key(server, sock, packet);
2095     break;
2096
2097     /*
2098      * Key Exchange protocol packets
2099      */
2100   case SILC_PACKET_KEY_EXCHANGE:
2101     SILC_LOG_DEBUG(("KE packet"));
2102     if (packet->flags & SILC_PACKET_FLAG_LIST)
2103       break;
2104
2105     if (sock->protocol && sock->protocol->protocol &&
2106         sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2107       SilcServerKEInternalContext *proto_ctx =
2108         (SilcServerKEInternalContext *)sock->protocol->context;
2109
2110       proto_ctx->packet = silc_packet_context_dup(packet);
2111
2112       /* Let the protocol handle the packet */
2113       silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2114     } else {
2115       SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2116                       "protocol active, packet dropped."));
2117     }
2118     break;
2119
2120   case SILC_PACKET_KEY_EXCHANGE_1:
2121     SILC_LOG_DEBUG(("KE 1 packet"));
2122     if (packet->flags & SILC_PACKET_FLAG_LIST)
2123       break;
2124
2125     if (sock->protocol && sock->protocol->protocol &&
2126         (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2127          sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2128
2129       if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2130         SilcServerRekeyInternalContext *proto_ctx =
2131           (SilcServerRekeyInternalContext *)sock->protocol->context;
2132
2133         if (proto_ctx->packet)
2134           silc_packet_context_free(proto_ctx->packet);
2135
2136         proto_ctx->packet = silc_packet_context_dup(packet);
2137
2138         /* Let the protocol handle the packet */
2139         silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2140       } else {
2141         SilcServerKEInternalContext *proto_ctx =
2142           (SilcServerKEInternalContext *)sock->protocol->context;
2143
2144         if (proto_ctx->packet)
2145           silc_packet_context_free(proto_ctx->packet);
2146
2147         proto_ctx->packet = silc_packet_context_dup(packet);
2148         proto_ctx->dest_id_type = packet->src_id_type;
2149         proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2150                                             packet->src_id_type);
2151         if (!proto_ctx->dest_id)
2152           break;
2153
2154         /* Let the protocol handle the packet */
2155         silc_protocol_execute(sock->protocol, server->schedule,
2156                               0, 100000);
2157       }
2158     } else {
2159       SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2160                       "protocol active, packet dropped."));
2161     }
2162     break;
2163
2164   case SILC_PACKET_KEY_EXCHANGE_2:
2165     SILC_LOG_DEBUG(("KE 2 packet"));
2166     if (packet->flags & SILC_PACKET_FLAG_LIST)
2167       break;
2168
2169     if (sock->protocol && sock->protocol->protocol &&
2170         (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2171          sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2172
2173       if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2174         SilcServerRekeyInternalContext *proto_ctx =
2175           (SilcServerRekeyInternalContext *)sock->protocol->context;
2176
2177         if (proto_ctx->packet)
2178           silc_packet_context_free(proto_ctx->packet);
2179
2180         proto_ctx->packet = silc_packet_context_dup(packet);
2181
2182         /* Let the protocol handle the packet */
2183         silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2184       } else {
2185         SilcServerKEInternalContext *proto_ctx =
2186           (SilcServerKEInternalContext *)sock->protocol->context;
2187
2188         if (proto_ctx->packet)
2189           silc_packet_context_free(proto_ctx->packet);
2190
2191         proto_ctx->packet = silc_packet_context_dup(packet);
2192         proto_ctx->dest_id_type = packet->src_id_type;
2193         proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2194                                             packet->src_id_type);
2195         if (!proto_ctx->dest_id)
2196           break;
2197
2198         /* Let the protocol handle the packet */
2199         silc_protocol_execute(sock->protocol, server->schedule,
2200                               0, 100000);
2201       }
2202     } else {
2203       SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2204                       "protocol active, packet dropped."));
2205     }
2206     break;
2207
2208   case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2209     /*
2210      * Connection authentication request packet. When we receive this packet
2211      * we will send to the other end information about our mandatory
2212      * authentication method for the connection. This packet maybe received
2213      * at any time.
2214      */
2215     SILC_LOG_DEBUG(("Connection authentication request packet"));
2216     if (packet->flags & SILC_PACKET_FLAG_LIST)
2217       break;
2218     silc_server_connection_auth_request(server, sock, packet);
2219     break;
2220
2221     /*
2222      * Connection Authentication protocol packets
2223      */
2224   case SILC_PACKET_CONNECTION_AUTH:
2225     /* Start of the authentication protocol. We receive here the
2226        authentication data and will verify it. */
2227     SILC_LOG_DEBUG(("Connection auth packet"));
2228     if (packet->flags & SILC_PACKET_FLAG_LIST)
2229       break;
2230
2231     if (sock->protocol && sock->protocol->protocol->type
2232         == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2233
2234       SilcServerConnAuthInternalContext *proto_ctx =
2235         (SilcServerConnAuthInternalContext *)sock->protocol->context;
2236
2237       proto_ctx->packet = silc_packet_context_dup(packet);
2238
2239       /* Let the protocol handle the packet */
2240       silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2241     } else {
2242       SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2243                       "protocol active, packet dropped."));
2244     }
2245     break;
2246
2247   case SILC_PACKET_NEW_ID:
2248     /*
2249      * Received New ID packet. This includes some new ID that has been
2250      * created. It may be for client, server or channel. This is the way
2251      * to distribute information about new registered entities in the
2252      * SILC network.
2253      */
2254     SILC_LOG_DEBUG(("New ID packet"));
2255     if (packet->flags & SILC_PACKET_FLAG_LIST)
2256       silc_server_new_id_list(server, sock, packet);
2257     else
2258       silc_server_new_id(server, sock, packet);
2259     break;
2260
2261   case SILC_PACKET_NEW_CLIENT:
2262     /*
2263      * Received new client packet. This includes client information that
2264      * we will use to create initial client ID. After creating new
2265      * ID we will send it to the client.
2266      */
2267     SILC_LOG_DEBUG(("New Client packet"));
2268     if (packet->flags & SILC_PACKET_FLAG_LIST)
2269       break;
2270     silc_server_new_client(server, sock, packet);
2271     break;
2272
2273   case SILC_PACKET_NEW_SERVER:
2274     /*
2275      * Received new server packet. This includes Server ID and some other
2276      * information that we may save. This is received after server has
2277      * connected to us.
2278      */
2279     SILC_LOG_DEBUG(("New Server packet"));
2280     if (packet->flags & SILC_PACKET_FLAG_LIST)
2281       break;
2282     silc_server_new_server(server, sock, packet);
2283     break;
2284
2285   case SILC_PACKET_NEW_CHANNEL:
2286     /*
2287      * Received new channel packet. Information about new channel in the
2288      * network are distributed using this packet.
2289      */
2290     SILC_LOG_DEBUG(("New Channel packet"));
2291     if (packet->flags & SILC_PACKET_FLAG_LIST)
2292       silc_server_new_channel_list(server, sock, packet);
2293     else
2294       silc_server_new_channel(server, sock, packet);
2295     break;
2296
2297   case SILC_PACKET_HEARTBEAT:
2298     /*
2299      * Received heartbeat.
2300      */
2301     SILC_LOG_DEBUG(("Heartbeat packet"));
2302     if (packet->flags & SILC_PACKET_FLAG_LIST)
2303       break;
2304     break;
2305
2306   case SILC_PACKET_KEY_AGREEMENT:
2307     /*
2308      * Received heartbeat.
2309      */
2310     SILC_LOG_DEBUG(("Key agreement packet"));
2311     if (packet->flags & SILC_PACKET_FLAG_LIST)
2312       break;
2313     silc_server_key_agreement(server, sock, packet);
2314     break;
2315
2316   case SILC_PACKET_REKEY:
2317     /*
2318      * Received re-key packet. The sender wants to regenerate the session
2319      * keys.
2320      */
2321     SILC_LOG_DEBUG(("Re-key packet"));
2322     if (packet->flags & SILC_PACKET_FLAG_LIST)
2323       break;
2324     silc_server_rekey(server, sock, packet);
2325     break;
2326
2327   case SILC_PACKET_REKEY_DONE:
2328     /*
2329      * The re-key is done.
2330      */
2331     SILC_LOG_DEBUG(("Re-key done packet"));
2332     if (packet->flags & SILC_PACKET_FLAG_LIST)
2333       break;
2334
2335     if (sock->protocol && sock->protocol->protocol &&
2336         sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2337
2338       SilcServerRekeyInternalContext *proto_ctx =
2339         (SilcServerRekeyInternalContext *)sock->protocol->context;
2340
2341       if (proto_ctx->packet)
2342         silc_packet_context_free(proto_ctx->packet);
2343
2344       proto_ctx->packet = silc_packet_context_dup(packet);
2345
2346       /* Let the protocol handle the packet */
2347       silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2348     } else {
2349       SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2350                       "protocol active, packet dropped."));
2351     }
2352     break;
2353
2354   case SILC_PACKET_FTP:
2355     /* FTP packet */
2356     SILC_LOG_DEBUG(("FTP packet"));
2357     if (packet->flags & SILC_PACKET_FLAG_LIST)
2358       break;
2359     silc_server_ftp(server, sock, packet);
2360     break;
2361
2362   case SILC_PACKET_RESUME_ROUTER:
2363     /* Resume router packet received. This packet is received for backup
2364        router resuming protocol. */
2365     SILC_LOG_DEBUG(("Resume router packet"));
2366     if (packet->flags & SILC_PACKET_FLAG_LIST)
2367       break;
2368     silc_server_backup_resume_router(server, sock, packet);
2369     break;
2370
2371   default:
2372     SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2373     break;
2374   }
2375
2376 }
2377
2378 /* Creates connection to a remote router. */
2379
2380 void silc_server_create_connection(SilcServer server,
2381                                    const char *remote_host, SilcUInt32 port)
2382 {
2383   SilcServerConnection sconn;
2384
2385   /* Allocate connection object for hold connection specific stuff. */
2386   sconn = silc_calloc(1, sizeof(*sconn));
2387   sconn->server = server;
2388   sconn->remote_host = strdup(remote_host);
2389   sconn->remote_port = port;
2390   sconn->no_reconnect = TRUE;
2391
2392   silc_schedule_task_add(server->schedule, 0,
2393                          silc_server_connect_router,
2394                          (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2395                          SILC_TASK_PRI_NORMAL);
2396 }
2397
2398 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2399 {
2400   silc_socket_free((SilcSocketConnection)context);
2401 }
2402
2403 /* Closes connection to socket connection */
2404
2405 void silc_server_close_connection(SilcServer server,
2406                                   SilcSocketConnection sock)
2407 {
2408   if (!server->sockets[sock->sock])
2409     return;
2410
2411   SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2412                   sock->port,
2413                   (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2414                    sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2415                    sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2416                    "Router")));
2417
2418   /* We won't listen for this connection anymore */
2419   silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2420
2421   /* Unregister all tasks */
2422   silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2423
2424   /* Close the actual connection */
2425   silc_net_close_connection(sock->sock);
2426   server->sockets[sock->sock] = NULL;
2427
2428   /* If sock->user_data is NULL then we'll check for active protocols
2429      here since the silc_server_free_sock_user_data has not been called
2430      for this connection. */
2431   if (!sock->user_data) {
2432     /* If any protocol is active cancel its execution. It will call
2433        the final callback which will finalize the disconnection. */
2434     if (sock->protocol) {
2435       silc_protocol_cancel(sock->protocol, server->schedule);
2436       sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2437       silc_protocol_execute_final(sock->protocol, server->schedule);
2438       sock->protocol = NULL;
2439       return;
2440     }
2441   }
2442
2443   silc_schedule_task_add(server->schedule, 0,
2444                          silc_server_close_connection_final,
2445                          (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2446                          SILC_TASK_PRI_NORMAL);
2447 }
2448
2449 /* Sends disconnect message to remote connection and disconnects the
2450    connection. */
2451
2452 void silc_server_disconnect_remote(SilcServer server,
2453                                    SilcSocketConnection sock,
2454                                    const char *fmt, ...)
2455 {
2456   va_list ap;
2457   unsigned char buf[4096];
2458
2459   if (!sock)
2460     return;
2461
2462   memset(buf, 0, sizeof(buf));
2463   va_start(ap, fmt);
2464   vsprintf(buf, fmt, ap);
2465   va_end(ap);
2466
2467   SILC_LOG_DEBUG(("Disconnecting remote host"));
2468
2469   /* Notify remote end that the conversation is over. The notify message
2470      is tried to be sent immediately. */
2471   silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2472                           buf, strlen(buf), TRUE);
2473   silc_server_packet_queue_purge(server, sock);
2474
2475   /* Mark the connection to be disconnected */
2476   SILC_SET_DISCONNECTED(sock);
2477   silc_server_close_connection(server, sock);
2478 }
2479
2480 typedef struct {
2481   SilcServer server;
2482   SilcClientEntry client;
2483 } *FreeClientInternal;
2484
2485 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2486 {
2487   FreeClientInternal i = (FreeClientInternal)context;
2488
2489   silc_idlist_del_data(i->client);
2490   silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2491   silc_free(i);
2492 }
2493
2494 /* Frees client data and notifies about client's signoff. */
2495
2496 void silc_server_free_client_data(SilcServer server,
2497                                   SilcSocketConnection sock,
2498                                   SilcClientEntry client,
2499                                   int notify,
2500                                   const char *signoff)
2501 {
2502   FreeClientInternal i = silc_calloc(1, sizeof(*i));
2503
2504   /* If there is pending outgoing data for the client then purge it
2505      to the network before removing the client entry. */
2506   silc_server_packet_queue_purge(server, sock);
2507
2508   if (!client->id)
2509     return;
2510
2511   /* Send SIGNOFF notify to routers. */
2512   if (notify && !server->standalone && server->router)
2513     silc_server_send_notify_signoff(server, server->router->connection,
2514                                     server->server_type == SILC_SERVER ?
2515                                     FALSE : TRUE, client->id, signoff);
2516
2517   /* Remove client from all channels */
2518   if (notify)
2519     silc_server_remove_from_channels(server, NULL, client,
2520                                      TRUE, (char *)signoff, TRUE);
2521   else
2522     silc_server_remove_from_channels(server, NULL, client,
2523                                      FALSE, NULL, FALSE);
2524
2525   /* Update statistics */
2526   server->stat.my_clients--;
2527   server->stat.clients--;
2528   if (server->server_type == SILC_ROUTER)
2529     server->stat.cell_clients--;
2530   SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2531   SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2532
2533   /* We will not delete the client entry right away. We will take it
2534      into history (for WHOWAS command) for 5 minutes */
2535   i->server = server;
2536   i->client = client;
2537   silc_schedule_task_add(server->schedule, 0,
2538                          silc_server_free_client_data_timeout,
2539                          (void *)i, 300, 0,
2540                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2541   client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2542   client->router = NULL;
2543   client->connection = NULL;
2544   client->mode = 0;
2545 }
2546
2547 /* Frees user_data pointer from socket connection object. This also sends
2548    appropriate notify packets to the network to inform about leaving
2549    entities. */
2550
2551 void silc_server_free_sock_user_data(SilcServer server,
2552                                      SilcSocketConnection sock,
2553                                      const char *signoff_message)
2554 {
2555   SILC_LOG_DEBUG(("Start"));
2556
2557   switch (sock->type) {
2558   case SILC_SOCKET_TYPE_CLIENT:
2559     {
2560       SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2561       silc_server_free_client_data(server, sock, user_data, TRUE,
2562                                    signoff_message);
2563       break;
2564     }
2565   case SILC_SOCKET_TYPE_SERVER:
2566   case SILC_SOCKET_TYPE_ROUTER:
2567     {
2568       SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2569       SilcServerEntry backup_router = NULL;
2570
2571       if (user_data->id)
2572         backup_router = silc_server_backup_get(server, user_data->id);
2573
2574       /* If this was our primary router connection then we're lost to
2575          the outside world. */
2576       if (server->router == user_data) {
2577         /* Check whether we have a backup router connection */
2578         if (!backup_router || backup_router == user_data) {
2579           silc_schedule_task_add(server->schedule, 0,
2580                                  silc_server_connect_to_router,
2581                                  server, 1, 0,
2582                                  SILC_TASK_TIMEOUT,
2583                                  SILC_TASK_PRI_NORMAL);
2584
2585           server->id_entry->router = NULL;
2586           server->router = NULL;
2587           server->standalone = TRUE;
2588           backup_router = NULL;
2589         } else {
2590           SILC_LOG_INFO(("New primary router is backup router %s",
2591                          backup_router->server_name));
2592           SILC_LOG_DEBUG(("New primary router is backup router %s",
2593                           backup_router->server_name));
2594           server->id_entry->router = backup_router;
2595           server->router = backup_router;
2596           server->router_connect = time(0);
2597           server->backup_primary = TRUE;
2598           if (server->server_type == SILC_BACKUP_ROUTER) {
2599             server->server_type = SILC_ROUTER;
2600
2601             /* We'll need to constantly try to reconnect to the primary
2602                router so that we'll see when it comes back online. */
2603             silc_server_backup_reconnect(server, sock->ip, sock->port,
2604                                          silc_server_backup_connected,
2605                                          NULL);
2606           }
2607
2608           /* Mark this connection as replaced */
2609           silc_server_backup_replaced_add(server, user_data->id,
2610                                           backup_router);
2611         }
2612       } else if (backup_router) {
2613         SILC_LOG_INFO(("Enabling the use of backup router %s",
2614                        backup_router->server_name));
2615         SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2616                         backup_router->server_name));
2617
2618         /* Mark this connection as replaced */
2619         silc_server_backup_replaced_add(server, user_data->id,
2620                                         backup_router);
2621       }
2622
2623       if (!backup_router) {
2624         /* Free all client entries that this server owns as they will
2625            become invalid now as well. */
2626         if (user_data->id)
2627           silc_server_remove_clients_by_server(server, user_data, TRUE);
2628         if (server->server_type == SILC_SERVER)
2629           silc_server_remove_channels_by_server(server, user_data);
2630       } else {
2631         /* Update the client entries of this server to the new backup
2632            router. This also removes the clients that *really* was owned
2633            by the primary router and went down with the router.  */
2634         silc_server_update_clients_by_server(server, user_data, backup_router,
2635                                              TRUE, TRUE);
2636         silc_server_update_servers_by_server(server, user_data, backup_router);
2637         if (server->server_type == SILC_SERVER)
2638           silc_server_update_channels_by_server(server, user_data,
2639                                                 backup_router);
2640       }
2641
2642       /* Free the server entry */
2643       silc_server_backup_del(server, user_data);
2644       silc_server_backup_replaced_del(server, user_data);
2645       silc_idlist_del_data(user_data);
2646       if (!silc_idlist_del_server(server->local_list, user_data))
2647         silc_idlist_del_server(server->global_list, user_data);
2648       server->stat.my_servers--;
2649       server->stat.servers--;
2650       if (server->server_type == SILC_ROUTER)
2651         server->stat.cell_servers--;
2652
2653       if (backup_router) {
2654         /* Announce all of our stuff that was created about 5 minutes ago.
2655            The backup router knows all the other stuff already. */
2656         if (server->server_type == SILC_ROUTER)
2657           silc_server_announce_servers(server, FALSE, time(0) - 300,
2658                                        backup_router->connection);
2659
2660         /* Announce our clients and channels to the router */
2661         silc_server_announce_clients(server, time(0) - 300,
2662                                      backup_router->connection);
2663         silc_server_announce_channels(server, time(0) - 300,
2664                                       backup_router->connection);
2665       }
2666       break;
2667     }
2668   default:
2669     {
2670       SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2671
2672       silc_idlist_del_data(user_data);
2673       silc_free(user_data);
2674       break;
2675     }
2676   }
2677
2678   /* If any protocol is active cancel its execution */
2679   if (sock->protocol) {
2680     silc_protocol_cancel(sock->protocol, server->schedule);
2681     sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2682     silc_protocol_execute_final(sock->protocol, server->schedule);
2683     sock->protocol = NULL;
2684   }
2685
2686   sock->user_data = NULL;
2687 }
2688
2689 /* Removes client from all channels it has joined. This is used when client
2690    connection is disconnected. If the client on a channel is last, the
2691    channel is removed as well. This sends the SIGNOFF notify types. */
2692
2693 void silc_server_remove_from_channels(SilcServer server,
2694                                       SilcSocketConnection sock,
2695                                       SilcClientEntry client,
2696                                       int notify,
2697                                       char *signoff_message,
2698                                       int keygen)
2699 {
2700   SilcChannelEntry channel;
2701   SilcChannelClientEntry chl;
2702   SilcHashTableList htl;
2703   SilcBuffer clidp;
2704
2705   SILC_LOG_DEBUG(("Start"));
2706
2707   if (!client || !client->id)
2708     return;
2709
2710   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2711
2712   /* Remove the client from all channels. The client is removed from
2713      the channels' user list. */
2714   silc_hash_table_list(client->channels, &htl);
2715   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2716     channel = chl->channel;
2717
2718     /* Remove channel from client's channel list */
2719     silc_hash_table_del(client->channels, channel);
2720
2721     /* Remove channel if there is no users anymore */
2722     if (server->server_type == SILC_ROUTER &&
2723         silc_hash_table_count(channel->user_list) < 2) {
2724       if (channel->rekey)
2725         silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2726       if (silc_idlist_del_channel(server->local_list, channel))
2727         server->stat.my_channels--;
2728       else
2729         silc_idlist_del_channel(server->global_list, channel);
2730       continue;
2731     }
2732
2733     /* Remove client from channel's client list */
2734     silc_hash_table_del(channel->user_list, chl->client);
2735     channel->user_count--;
2736
2737     /* If there is no global users on the channel anymore mark the channel
2738        as local channel. Do not check if the removed client is local client. */
2739     if (server->server_type != SILC_ROUTER && channel->global_users &&
2740         chl->client->router && !silc_server_channel_has_global(channel))
2741       channel->global_users = FALSE;
2742
2743     silc_free(chl);
2744     server->stat.my_chanclients--;
2745
2746     /* If there is not at least one local user on the channel then we don't
2747        need the channel entry anymore, we can remove it safely. */
2748     if (server->server_type != SILC_ROUTER &&
2749         !silc_server_channel_has_local(channel)) {
2750       /* Notify about leaving client if this channel has global users. */
2751       if (notify && channel->global_users)
2752         silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2753                                            SILC_NOTIFY_TYPE_SIGNOFF,
2754                                            signoff_message ? 2 : 1,
2755                                            clidp->data, clidp->len,
2756                                            signoff_message, signoff_message ?
2757                                            strlen(signoff_message) : 0);
2758
2759       if (channel->rekey)
2760         silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2761
2762       if (channel->founder_key) {
2763         /* The founder auth data exists, do not remove the channel entry */
2764         SilcChannelClientEntry chl2;
2765         SilcHashTableList htl2;
2766
2767         channel->disabled = TRUE;
2768
2769         silc_hash_table_list(channel->user_list, &htl2);
2770         while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2771           silc_hash_table_del(chl2->client->channels, channel);
2772           silc_hash_table_del(channel->user_list, chl2->client);
2773           channel->user_count--;
2774           silc_free(chl2);
2775         }
2776         silc_hash_table_list_reset(&htl2);
2777         continue;
2778       }
2779
2780       /* Remove the channel entry */
2781       if (silc_idlist_del_channel(server->local_list, channel))
2782         server->stat.my_channels--;
2783       else
2784         silc_idlist_del_channel(server->global_list, channel);
2785       continue;
2786     }
2787
2788     /* Send notify to channel about client leaving SILC and thus
2789        the entire channel. */
2790     if (notify)
2791       silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2792                                          SILC_NOTIFY_TYPE_SIGNOFF,
2793                                          signoff_message ? 2 : 1,
2794                                          clidp->data, clidp->len,
2795                                          signoff_message, signoff_message ?
2796                                          strlen(signoff_message) : 0);
2797
2798     if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2799       /* Re-generate channel key */
2800       if (!silc_server_create_channel_key(server, channel, 0))
2801         goto out;
2802
2803       /* Send the channel key to the channel. The key of course is not sent
2804          to the client who was removed from the channel. */
2805       silc_server_send_channel_key(server, client->connection, channel,
2806                                    server->server_type == SILC_ROUTER ?
2807                                    FALSE : !server->standalone);
2808     }
2809   }
2810
2811  out:
2812   silc_hash_table_list_reset(&htl);
2813   silc_buffer_free(clidp);
2814 }
2815
2816 /* Removes client from one channel. This is used for example when client
2817    calls LEAVE command to remove itself from the channel. Returns TRUE
2818    if channel still exists and FALSE if the channel is removed when
2819    last client leaves the channel. If `notify' is FALSE notify messages
2820    are not sent. */
2821
2822 int silc_server_remove_from_one_channel(SilcServer server,
2823                                         SilcSocketConnection sock,
2824                                         SilcChannelEntry channel,
2825                                         SilcClientEntry client,
2826                                         int notify)
2827 {
2828   SilcChannelClientEntry chl;
2829   SilcBuffer clidp;
2830
2831   SILC_LOG_DEBUG(("Start"));
2832
2833   /* Get the entry to the channel, if this client is not on the channel
2834      then return Ok. */
2835   if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2836     return TRUE;
2837
2838   /* Remove the client from the channel. The client is removed from
2839      the channel's user list. */
2840
2841   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2842
2843   /* Remove channel from client's channel list */
2844   silc_hash_table_del(client->channels, chl->channel);
2845
2846   /* Remove channel if there is no users anymore */
2847   if (server->server_type == SILC_ROUTER &&
2848       silc_hash_table_count(channel->user_list) < 2) {
2849     if (channel->rekey)
2850       silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2851     if (silc_idlist_del_channel(server->local_list, channel))
2852       server->stat.my_channels--;
2853     else
2854       silc_idlist_del_channel(server->global_list, channel);
2855     silc_buffer_free(clidp);
2856     return FALSE;
2857   }
2858
2859   /* Remove client from channel's client list */
2860   silc_hash_table_del(channel->user_list, chl->client);
2861   channel->user_count--;
2862
2863   /* If there is no global users on the channel anymore mark the channel
2864      as local channel. Do not check if the client is local client. */
2865   if (server->server_type != SILC_ROUTER && channel->global_users &&
2866       chl->client->router && !silc_server_channel_has_global(channel))
2867     channel->global_users = FALSE;
2868
2869   silc_free(chl);
2870   server->stat.my_chanclients--;
2871
2872   /* If there is not at least one local user on the channel then we don't
2873      need the channel entry anymore, we can remove it safely. */
2874   if (server->server_type != SILC_ROUTER &&
2875       !silc_server_channel_has_local(channel)) {
2876     /* Notify about leaving client if this channel has global users. */
2877     if (notify && channel->global_users)
2878       silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2879                                          SILC_NOTIFY_TYPE_LEAVE, 1,
2880                                          clidp->data, clidp->len);
2881
2882     silc_buffer_free(clidp);
2883
2884     if (channel->rekey)
2885       silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2886
2887     if (channel->founder_key) {
2888       /* The founder auth data exists, do not remove the channel entry */
2889       SilcChannelClientEntry chl2;
2890       SilcHashTableList htl2;
2891
2892       channel->disabled = TRUE;
2893
2894       silc_hash_table_list(channel->user_list, &htl2);
2895       while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2896         silc_hash_table_del(chl2->client->channels, channel);
2897         silc_hash_table_del(channel->user_list, chl2->client);
2898         channel->user_count--;
2899         silc_free(chl2);
2900       }
2901       silc_hash_table_list_reset(&htl2);
2902       return FALSE;
2903     }
2904
2905     /* Remove the channel entry */
2906     if (silc_idlist_del_channel(server->local_list, channel))
2907       server->stat.my_channels--;
2908     else
2909       silc_idlist_del_channel(server->global_list, channel);
2910     return FALSE;
2911   }
2912
2913   /* Send notify to channel about client leaving the channel */
2914   if (notify)
2915     silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2916                                        SILC_NOTIFY_TYPE_LEAVE, 1,
2917                                        clidp->data, clidp->len);
2918
2919   silc_buffer_free(clidp);
2920   return TRUE;
2921 }
2922
2923 /* Timeout callback. This is called if connection is idle or for some
2924    other reason is not responding within some period of time. This
2925    disconnects the remote end. */
2926
2927 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2928 {
2929   SilcServer server = (SilcServer)context;
2930   SilcSocketConnection sock = server->sockets[fd];
2931
2932   SILC_LOG_DEBUG(("Start"));
2933
2934   if (!sock)
2935     return;
2936
2937   SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
2938                   sock->hostname, sock->ip));
2939
2940   /* If we have protocol active we must assure that we call the protocol's
2941      final callback so that all the memory is freed. */
2942   if (sock->protocol) {
2943     silc_protocol_cancel(sock->protocol, server->schedule);
2944     sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2945     silc_protocol_execute_final(sock->protocol, server->schedule);
2946     sock->protocol = NULL;
2947     return;
2948   }
2949
2950   if (sock->user_data)
2951     silc_server_free_sock_user_data(server, sock, NULL);
2952
2953   silc_server_disconnect_remote(server, sock, "Server closed connection: "
2954                                 "Connection timeout");
2955 }
2956
2957 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2958    function may be used only by router. In real SILC network all channels
2959    are created by routers thus this function is never used by normal
2960    server. */
2961
2962 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2963                                                 SilcServerID *router_id,
2964                                                 char *cipher,
2965                                                 char *hmac,
2966                                                 char *channel_name,
2967                                                 int broadcast)
2968 {
2969   SilcChannelID *channel_id;
2970   SilcChannelEntry entry;
2971   SilcCipher key;
2972   SilcHmac newhmac;
2973
2974   SILC_LOG_DEBUG(("Creating new channel"));
2975
2976   if (!cipher)
2977     cipher = SILC_DEFAULT_CIPHER;
2978   if (!hmac)
2979     hmac = SILC_DEFAULT_HMAC;
2980
2981   /* Allocate cipher */
2982   if (!silc_cipher_alloc(cipher, &key))
2983     return NULL;
2984
2985   /* Allocate hmac */
2986   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2987     silc_cipher_free(key);
2988     return NULL;
2989   }
2990
2991   channel_name = strdup(channel_name);
2992
2993   /* Create the channel ID */
2994   if (!silc_id_create_channel_id(server, router_id, server->rng,
2995                                  &channel_id)) {
2996     silc_free(channel_name);
2997     silc_cipher_free(key);
2998     silc_hmac_free(newhmac);
2999     return NULL;
3000   }
3001
3002   /* Create the channel */
3003   entry = silc_idlist_add_channel(server->local_list, channel_name,
3004                                   SILC_CHANNEL_MODE_NONE, channel_id,
3005                                   NULL, key, newhmac, 0);
3006   if (!entry) {
3007     silc_free(channel_name);
3008     silc_cipher_free(key);
3009     silc_hmac_free(newhmac);
3010     silc_free(channel_id);
3011     return NULL;
3012   }
3013
3014   entry->cipher = strdup(cipher);
3015   entry->hmac_name = strdup(hmac);
3016
3017   /* Now create the actual key material */
3018   if (!silc_server_create_channel_key(server, entry,
3019                                       silc_cipher_get_key_len(key) / 8)) {
3020     silc_idlist_del_channel(server->local_list, entry);
3021     return NULL;
3022   }
3023
3024   /* Notify other routers about the new channel. We send the packet
3025      to our primary route. */
3026   if (broadcast && server->standalone == FALSE)
3027     silc_server_send_new_channel(server, server->router->connection, TRUE,
3028                                  channel_name, entry->id,
3029                                  silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3030                                  entry->mode);
3031
3032   server->stat.my_channels++;
3033
3034   return entry;
3035 }
3036
3037 /* Same as above but creates the channel with Channel ID `channel_id. */
3038
3039 SilcChannelEntry
3040 silc_server_create_new_channel_with_id(SilcServer server,
3041                                        char *cipher,
3042                                        char *hmac,
3043                                        char *channel_name,
3044                                        SilcChannelID *channel_id,
3045                                        int broadcast)
3046 {
3047   SilcChannelEntry entry;
3048   SilcCipher key;
3049   SilcHmac newhmac;
3050
3051   SILC_LOG_DEBUG(("Creating new channel"));
3052
3053   if (!cipher)
3054     cipher = SILC_DEFAULT_CIPHER;
3055   if (!hmac)
3056     hmac = SILC_DEFAULT_HMAC;
3057
3058   /* Allocate cipher */
3059   if (!silc_cipher_alloc(cipher, &key))
3060     return NULL;
3061
3062   /* Allocate hmac */
3063   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3064     silc_cipher_free(key);
3065     return NULL;
3066   }
3067
3068   channel_name = strdup(channel_name);
3069
3070   /* Create the channel */
3071   entry = silc_idlist_add_channel(server->local_list, channel_name,
3072                                   SILC_CHANNEL_MODE_NONE, channel_id,
3073                                   NULL, key, newhmac, 0);
3074   if (!entry) {
3075     silc_cipher_free(key);
3076     silc_hmac_free(newhmac);
3077     silc_free(channel_name);
3078     return NULL;
3079   }
3080
3081   /* Now create the actual key material */
3082   if (!silc_server_create_channel_key(server, entry,
3083                                       silc_cipher_get_key_len(key) / 8)) {
3084     silc_idlist_del_channel(server->local_list, entry);
3085     return NULL;
3086   }
3087
3088   /* Notify other routers about the new channel. We send the packet
3089      to our primary route. */
3090   if (broadcast && server->standalone == FALSE)
3091     silc_server_send_new_channel(server, server->router->connection, TRUE,
3092                                  channel_name, entry->id,
3093                                  silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3094                                  entry->mode);
3095
3096   server->stat.my_channels++;
3097
3098   return entry;
3099 }
3100
3101 /* Channel's key re-key timeout callback. */
3102
3103 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3104 {
3105   SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3106   SilcServer server = (SilcServer)rekey->context;
3107
3108   rekey->task = NULL;
3109
3110   if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3111     return;
3112
3113   silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3114 }
3115
3116 /* Generates new channel key. This is used to create the initial channel key
3117    but also to re-generate new key for channel. If `key_len' is provided
3118    it is the bytes of the key length. */
3119
3120 bool silc_server_create_channel_key(SilcServer server,
3121                                     SilcChannelEntry channel,
3122                                     SilcUInt32 key_len)
3123 {
3124   int i;
3125   unsigned char channel_key[32], hash[32];
3126   SilcUInt32 len;
3127
3128   SILC_LOG_DEBUG(("Generating channel key"));
3129
3130   if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3131     SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3132     return TRUE;
3133   }
3134
3135   if (!channel->channel_key)
3136     if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3137       channel->channel_key = NULL;
3138       return FALSE;
3139     }
3140
3141   if (key_len)
3142     len = key_len;
3143   else if (channel->key_len)
3144     len = channel->key_len / 8;
3145   else
3146     len = silc_cipher_get_key_len(channel->channel_key) / 8;
3147
3148   /* Create channel key */
3149   for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3150
3151   /* Set the key */
3152   silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3153
3154   /* Remove old key if exists */
3155   if (channel->key) {
3156     memset(channel->key, 0, channel->key_len / 8);
3157     silc_free(channel->key);
3158   }
3159
3160   /* Save the key */
3161   channel->key_len = len * 8;
3162   channel->key = silc_memdup(channel_key, len);
3163   memset(channel_key, 0, sizeof(channel_key));
3164
3165   /* Generate HMAC key from the channel key data and set it */
3166   if (!channel->hmac)
3167     silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3168   silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3169   silc_hmac_set_key(channel->hmac, hash,
3170                     silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3171   memset(hash, 0, sizeof(hash));
3172
3173   if (server->server_type == SILC_ROUTER) {
3174     if (!channel->rekey)
3175       channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3176     channel->rekey->context = (void *)server;
3177     channel->rekey->channel = channel;
3178     channel->rekey->key_len = key_len;
3179     if (channel->rekey->task)
3180       silc_schedule_task_del(server->schedule, channel->rekey->task);
3181
3182     channel->rekey->task =
3183       silc_schedule_task_add(server->schedule, 0,
3184                              silc_server_channel_key_rekey,
3185                              (void *)channel->rekey,
3186                              server->config->channel_rekey_secs, 0,
3187                              SILC_TASK_TIMEOUT,
3188                              SILC_TASK_PRI_NORMAL);
3189   }
3190
3191   return TRUE;
3192 }
3193
3194 /* Saves the channel key found in the encoded `key_payload' buffer. This
3195    function is used when we receive Channel Key Payload and also when we're
3196    processing JOIN command reply. Returns entry to the channel. */
3197
3198 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3199                                               SilcBuffer key_payload,
3200                                               SilcChannelEntry channel)
3201 {
3202   SilcChannelKeyPayload payload = NULL;
3203   SilcChannelID *id = NULL;
3204   unsigned char *tmp, hash[32];
3205   SilcUInt32 tmp_len;
3206   char *cipher;
3207
3208   SILC_LOG_DEBUG(("Start"));
3209
3210   /* Decode channel key payload */
3211   payload = silc_channel_key_payload_parse(key_payload->data,
3212                                            key_payload->len);
3213   if (!payload) {
3214     SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3215     channel = NULL;
3216     goto out;
3217   }
3218
3219   /* Get the channel entry */
3220   if (!channel) {
3221
3222     /* Get channel ID */
3223     tmp = silc_channel_key_get_id(payload, &tmp_len);
3224     id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3225     if (!id) {
3226       channel = NULL;
3227       goto out;
3228     }
3229
3230     channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3231     if (!channel) {
3232       channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3233       if (!channel) {
3234         SILC_LOG_ERROR(("Received key for non-existent channel %s",
3235                         silc_id_render(id, SILC_ID_CHANNEL)));
3236         goto out;
3237       }
3238     }
3239   }
3240
3241   tmp = silc_channel_key_get_key(payload, &tmp_len);
3242   if (!tmp) {
3243     channel = NULL;
3244     goto out;
3245   }
3246
3247   cipher = silc_channel_key_get_cipher(payload, NULL);
3248   if (!cipher) {
3249     channel = NULL;
3250     goto out;
3251   }
3252
3253   /* Remove old key if exists */
3254   if (channel->key) {
3255     memset(channel->key, 0, channel->key_len / 8);
3256     silc_free(channel->key);
3257     silc_cipher_free(channel->channel_key);
3258   }
3259
3260   /* Create new cipher */
3261   if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3262     channel->channel_key = NULL;
3263     channel = NULL;
3264     goto out;
3265   }
3266
3267   if (channel->cipher)
3268     silc_free(channel->cipher);
3269   channel->cipher = strdup(cipher);
3270
3271   /* Save the key */
3272   channel->key_len = tmp_len * 8;
3273   channel->key = silc_memdup(tmp, tmp_len);
3274   silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3275
3276   /* Generate HMAC key from the channel key data and set it */
3277   if (!channel->hmac)
3278     silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3279   silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3280   silc_hmac_set_key(channel->hmac, hash,
3281                     silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3282
3283   memset(hash, 0, sizeof(hash));
3284   memset(tmp, 0, tmp_len);
3285
3286   if (server->server_type == SILC_ROUTER) {
3287     if (!channel->rekey)
3288       channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3289     channel->rekey->context = (void *)server;
3290     channel->rekey->channel = channel;
3291     if (channel->rekey->task)
3292       silc_schedule_task_del(server->schedule, channel->rekey->task);
3293
3294     channel->rekey->task =
3295       silc_schedule_task_add(server->schedule, 0,
3296                              silc_server_channel_key_rekey,
3297                              (void *)channel->rekey,
3298                              server->config->channel_rekey_secs, 0,
3299                              SILC_TASK_TIMEOUT,
3300                              SILC_TASK_PRI_NORMAL);
3301   }
3302
3303  out:
3304   silc_free(id);
3305   if (payload)
3306     silc_channel_key_payload_free(payload);
3307
3308   return channel;
3309 }
3310
3311 /* Heartbeat callback. This function is set as argument for the
3312    silc_socket_set_heartbeat function. The library will call this function
3313    at the set time interval. */
3314
3315 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3316                                    void *hb_context)
3317 {
3318   SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3319
3320   SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3321
3322   /* Send the heartbeat */
3323   silc_server_send_heartbeat(hb->server, sock);
3324 }
3325
3326 /* Returns assembled of all servers in the given ID list. The packet's
3327    form is dictated by the New ID payload. */
3328
3329 static void silc_server_announce_get_servers(SilcServer server,
3330                                              SilcServerEntry remote,
3331                                              SilcIDList id_list,
3332                                              SilcBuffer *servers,
3333                                              unsigned long creation_time)
3334 {
3335   SilcIDCacheList list;
3336   SilcIDCacheEntry id_cache;
3337   SilcServerEntry entry;
3338   SilcBuffer idp;
3339
3340   /* Go through all clients in the list */
3341   if (silc_idcache_get_all(id_list->servers, &list)) {
3342     if (silc_idcache_list_first(list, &id_cache)) {
3343       while (id_cache) {
3344         entry = (SilcServerEntry)id_cache->context;
3345
3346         /* Do not announce the one we've sending our announcements and
3347            do not announce ourself. Also check the creation time if it's
3348            provided. */
3349         if ((entry == remote) || (entry == server->id_entry) ||
3350             (creation_time && entry->data.created < creation_time)) {
3351           if (!silc_idcache_list_next(list, &id_cache))
3352             break;
3353           continue;
3354         }
3355
3356         idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3357
3358         *servers = silc_buffer_realloc(*servers,
3359                                        (*servers ?
3360                                         (*servers)->truelen + idp->len :
3361                                         idp->len));
3362         silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3363         silc_buffer_put(*servers, idp->data, idp->len);
3364         silc_buffer_pull(*servers, idp->len);
3365         silc_buffer_free(idp);
3366
3367         if (!silc_idcache_list_next(list, &id_cache))
3368           break;
3369       }
3370     }
3371
3372     silc_idcache_list_free(list);
3373   }
3374 }
3375
3376 static SilcBuffer
3377 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3378 {
3379   va_list ap;
3380   SilcBuffer p;
3381
3382   va_start(ap, argc);
3383   p = silc_notify_payload_encode(notify, argc, ap);
3384   va_end(ap);
3385
3386   return p;
3387 }
3388
3389 /* This function is used by router to announce existing servers to our
3390    primary router when we've connected to it. If `creation_time' is non-zero
3391    then only the servers that has been created after the `creation_time'
3392    will be announced. */
3393
3394 void silc_server_announce_servers(SilcServer server, bool global,
3395                                   unsigned long creation_time,
3396                                   SilcSocketConnection remote)
3397 {
3398   SilcBuffer servers = NULL;
3399
3400   SILC_LOG_DEBUG(("Announcing servers"));
3401
3402   /* Get servers in local list */
3403   silc_server_announce_get_servers(server, remote->user_data,
3404                                    server->local_list, &servers,
3405                                    creation_time);
3406
3407   if (global)
3408     /* Get servers in global list */
3409     silc_server_announce_get_servers(server, remote->user_data,
3410                                      server->global_list, &servers,
3411                                      creation_time);
3412
3413   if (servers) {
3414     silc_buffer_push(servers, servers->data - servers->head);
3415     SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3416
3417     /* Send the packet */
3418     silc_server_packet_send(server, remote,
3419                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3420                             servers->data, servers->len, TRUE);
3421
3422     silc_buffer_free(servers);
3423   }
3424 }
3425
3426 /* Returns assembled packet of all clients in the given ID list. The
3427    packet's form is dictated by the New ID Payload. */
3428
3429 static void silc_server_announce_get_clients(SilcServer server,
3430                                              SilcIDList id_list,
3431                                              SilcBuffer *clients,
3432                                              SilcBuffer *umodes,
3433                                              unsigned long creation_time)
3434 {
3435   SilcIDCacheList list;
3436   SilcIDCacheEntry id_cache;
3437   SilcClientEntry client;
3438   SilcBuffer idp;
3439   SilcBuffer tmp;
3440   unsigned char mode[4];
3441
3442   /* Go through all clients in the list */
3443   if (silc_idcache_get_all(id_list->clients, &list)) {
3444     if (silc_idcache_list_first(list, &id_cache)) {
3445       while (id_cache) {
3446         client = (SilcClientEntry)id_cache->context;
3447
3448         if (creation_time && client->data.created < creation_time) {
3449           if (!silc_idcache_list_next(list, &id_cache))
3450             break;
3451           continue;
3452         }
3453
3454         idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3455
3456         *clients = silc_buffer_realloc(*clients,
3457                                        (*clients ?
3458                                         (*clients)->truelen + idp->len :
3459                                         idp->len));
3460         silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3461         silc_buffer_put(*clients, idp->data, idp->len);
3462         silc_buffer_pull(*clients, idp->len);
3463
3464         SILC_PUT32_MSB(client->mode, mode);
3465         tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3466                                                  2, idp->data, idp->len,
3467                                                  mode, 4);
3468         *umodes = silc_buffer_realloc(*umodes,
3469                                       (*umodes ?
3470                                        (*umodes)->truelen + tmp->len :
3471                                        tmp->len));
3472         silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3473         silc_buffer_put(*umodes, tmp->data, tmp->len);
3474         silc_buffer_pull(*umodes, tmp->len);
3475         silc_buffer_free(tmp);
3476
3477         silc_buffer_free(idp);
3478
3479         if (!silc_idcache_list_next(list, &id_cache))
3480           break;
3481       }
3482     }
3483
3484     silc_idcache_list_free(list);
3485   }
3486 }
3487
3488 /* This function is used to announce our existing clients to our router
3489    when we've connected to it. If `creation_time' is non-zero then only
3490    the clients that has been created after the `creation_time' will be
3491    announced. */
3492
3493 void silc_server_announce_clients(SilcServer server,
3494                                   unsigned long creation_time,
3495                                   SilcSocketConnection remote)
3496 {
3497   SilcBuffer clients = NULL;
3498   SilcBuffer umodes = NULL;
3499
3500   SILC_LOG_DEBUG(("Announcing clients"));
3501
3502   /* Get clients in local list */
3503   silc_server_announce_get_clients(server, server->local_list,
3504                                    &clients, &umodes, creation_time);
3505
3506   /* As router we announce our global list as well */
3507   if (server->server_type == SILC_ROUTER)
3508     silc_server_announce_get_clients(server, server->global_list,
3509                                      &clients, &umodes, creation_time);
3510
3511   if (clients) {
3512     silc_buffer_push(clients, clients->data - clients->head);
3513     SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3514
3515     /* Send the packet */
3516     silc_server_packet_send(server, remote,
3517                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3518                             clients->data, clients->len, TRUE);
3519
3520     silc_buffer_free(clients);
3521   }
3522
3523   if (umodes) {
3524     silc_buffer_push(umodes, umodes->data - umodes->head);
3525     SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3526
3527     /* Send the packet */
3528     silc_server_packet_send(server, remote,
3529                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3530                             umodes->data, umodes->len, TRUE);
3531
3532     silc_buffer_free(umodes);
3533   }
3534 }
3535
3536 /* Returns channel's topic for announcing it */
3537
3538 void silc_server_announce_get_channel_topic(SilcServer server,
3539                                             SilcChannelEntry channel,
3540                                             SilcBuffer *topic)
3541 {
3542   SilcBuffer chidp;
3543
3544   if (channel->topic) {
3545     chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3546     *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3547                                                 chidp->data, chidp->len,
3548                                                 channel->topic,
3549                                                 strlen(channel->topic));
3550     silc_buffer_free(chidp);
3551   }
3552 }
3553
3554 /* Returns assembled packets for channel users of the `channel'. */
3555
3556 void silc_server_announce_get_channel_users(SilcServer server,
3557                                             SilcChannelEntry channel,
3558                                             SilcBuffer *channel_users,
3559                                             SilcBuffer *channel_users_modes)
3560 {
3561   SilcChannelClientEntry chl;
3562   SilcHashTableList htl;
3563   SilcBuffer chidp, clidp;
3564   SilcBuffer tmp;
3565   int len;
3566   unsigned char mode[4];
3567
3568   SILC_LOG_DEBUG(("Start"));
3569
3570   /* Now find all users on the channel */
3571   chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3572   silc_hash_table_list(channel->user_list, &htl);
3573   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3574     clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3575
3576     /* JOIN Notify */
3577     tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3578                                              clidp->data, clidp->len,
3579                                              chidp->data, chidp->len);
3580     len = tmp->len;
3581     *channel_users =
3582       silc_buffer_realloc(*channel_users,
3583                           (*channel_users ?
3584                            (*channel_users)->truelen + len : len));
3585     silc_buffer_pull_tail(*channel_users,
3586                           ((*channel_users)->end -
3587                            (*channel_users)->data));
3588
3589     silc_buffer_put(*channel_users, tmp->data, tmp->len);
3590     silc_buffer_pull(*channel_users, len);
3591     silc_buffer_free(tmp);
3592
3593     /* CUMODE notify for mode change on the channel */
3594     SILC_PUT32_MSB(chl->mode, mode);
3595     tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3596                                              3, clidp->data, clidp->len,
3597                                              mode, 4,
3598                                              clidp->data, clidp->len);
3599     len = tmp->len;
3600     *channel_users_modes =
3601       silc_buffer_realloc(*channel_users_modes,
3602                           (*channel_users_modes ?
3603                            (*channel_users_modes)->truelen + len : len));
3604     silc_buffer_pull_tail(*channel_users_modes,
3605                           ((*channel_users_modes)->end -
3606                            (*channel_users_modes)->data));
3607
3608     silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3609     silc_buffer_pull(*channel_users_modes, len);
3610     silc_buffer_free(tmp);
3611
3612     silc_buffer_free(clidp);
3613   }
3614   silc_hash_table_list_reset(&htl);
3615   silc_buffer_free(chidp);
3616 }
3617
3618 /* Returns assembled packets for all channels and users on those channels
3619    from the given ID List. The packets are in the form dictated by the
3620    New Channel and New Channel User payloads. */
3621
3622 void silc_server_announce_get_channels(SilcServer server,
3623                                        SilcIDList id_list,
3624                                        SilcBuffer *channels,
3625                                        SilcBuffer *channel_users,
3626                                        SilcBuffer **channel_users_modes,
3627                                        SilcUInt32 *channel_users_modes_c,
3628                                        SilcBuffer **channel_topics,
3629                                        SilcChannelID ***channel_ids,
3630                                        unsigned long creation_time)
3631 {
3632   SilcIDCacheList list;
3633   SilcIDCacheEntry id_cache;
3634   SilcChannelEntry channel;
3635   unsigned char *cid;
3636   SilcUInt32 id_len;
3637   SilcUInt16 name_len;
3638   int len;
3639   int i = *channel_users_modes_c;
3640   bool announce;
3641
3642   SILC_LOG_DEBUG(("Start"));
3643
3644   /* Go through all channels in the list */
3645   if (silc_idcache_get_all(id_list->channels, &list)) {
3646     if (silc_idcache_list_first(list, &id_cache)) {
3647       while (id_cache) {
3648         channel = (SilcChannelEntry)id_cache->context;
3649
3650         if (creation_time && channel->created < creation_time)
3651           announce = FALSE;
3652         else
3653           announce = TRUE;
3654
3655         cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3656         id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3657         name_len = strlen(channel->channel_name);
3658
3659         if (announce) {
3660           len = 4 + name_len + id_len + 4;
3661           *channels =
3662             silc_buffer_realloc(*channels,
3663                                 (*channels ? (*channels)->truelen +
3664                                  len : len));
3665           silc_buffer_pull_tail(*channels,
3666                                 ((*channels)->end - (*channels)->data));
3667           silc_buffer_format(*channels,
3668                              SILC_STR_UI_SHORT(name_len),
3669                              SILC_STR_UI_XNSTRING(channel->channel_name,
3670                                                   name_len),
3671                              SILC_STR_UI_SHORT(id_len),
3672                              SILC_STR_UI_XNSTRING(cid, id_len),
3673                              SILC_STR_UI_INT(channel->mode),
3674                              SILC_STR_END);
3675           silc_buffer_pull(*channels, len);
3676         }
3677
3678         /* Channel user modes */
3679         *channel_users_modes = silc_realloc(*channel_users_modes,
3680                                             sizeof(**channel_users_modes) *
3681                                             (i + 1));
3682         (*channel_users_modes)[i] = NULL;
3683         *channel_ids = silc_realloc(*channel_ids,
3684                                     sizeof(**channel_ids) * (i + 1));
3685         (*channel_ids)[i] = NULL;
3686         silc_server_announce_get_channel_users(server, channel,
3687                                                channel_users,
3688                                                &(*channel_users_modes)[i]);
3689         (*channel_ids)[i] = channel->id;
3690
3691         /* Channel's topic */
3692         *channel_topics = silc_realloc(*channel_topics,
3693                                        sizeof(**channel_topics) * (i + 1));
3694         (*channel_topics)[i] = NULL;
3695         silc_server_announce_get_channel_topic(server, channel,
3696                                                &(*channel_topics)[i]);
3697         i++;
3698
3699         if (!silc_idcache_list_next(list, &id_cache))
3700           break;
3701       }
3702
3703       *channel_users_modes_c += i;
3704     }
3705
3706     silc_idcache_list_free(list);
3707   }
3708 }
3709
3710 /* This function is used to announce our existing channels to our router
3711    when we've connected to it. This also announces the users on the
3712    channels to the router. If the `creation_time' is non-zero only the
3713    channels that was created after the `creation_time' are announced.
3714    Note that the channel users are still announced even if the `creation_time'
3715    was provided. */
3716
3717 void silc_server_announce_channels(SilcServer server,
3718                                    unsigned long creation_time,
3719                                    SilcSocketConnection remote)
3720 {
3721   SilcBuffer channels = NULL, channel_users = NULL;
3722   SilcBuffer *channel_users_modes = NULL;
3723   SilcBuffer *channel_topics = NULL;
3724   SilcUInt32 channel_users_modes_c = 0;
3725   SilcChannelID **channel_ids = NULL;
3726
3727   SILC_LOG_DEBUG(("Announcing channels and channel users"));
3728
3729   /* Get channels and channel users in local list */
3730   silc_server_announce_get_channels(server, server->local_list,
3731                                     &channels, &channel_users,
3732                                     &channel_users_modes,
3733                                     &channel_users_modes_c,
3734                                     &channel_topics,
3735                                     &channel_ids, creation_time);
3736
3737   /* Get channels and channel users in global list */
3738   if (server->server_type != SILC_SERVER)
3739     silc_server_announce_get_channels(server, server->global_list,
3740                                       &channels, &channel_users,
3741                                       &channel_users_modes,
3742                                       &channel_users_modes_c,
3743                                       &channel_topics,
3744                                       &channel_ids, creation_time);
3745
3746   if (channels) {
3747     silc_buffer_push(channels, channels->data - channels->head);
3748     SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3749
3750     /* Send the packet */
3751     silc_server_packet_send(server, remote,
3752                             SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3753                             channels->data, channels->len,
3754                             FALSE);
3755
3756     silc_buffer_free(channels);
3757   }
3758
3759   if (channel_users) {
3760     silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3761     SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3762                      channel_users->len);
3763
3764     /* Send the packet */
3765     silc_server_packet_send(server, remote,
3766                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3767                             channel_users->data, channel_users->len,
3768                             FALSE);
3769
3770     silc_buffer_free(channel_users);
3771   }
3772
3773   if (channel_users_modes) {
3774     int i;
3775
3776     for (i = 0; i < channel_users_modes_c; i++) {
3777       if (!channel_users_modes[i])
3778         continue;
3779       silc_buffer_push(channel_users_modes[i],
3780                        channel_users_modes[i]->data -
3781                        channel_users_modes[i]->head);
3782       SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3783                        channel_users_modes[i]->len);
3784       silc_server_packet_send_dest(server, remote,
3785                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3786                                    channel_ids[i], SILC_ID_CHANNEL,
3787                                    channel_users_modes[i]->data,
3788                                    channel_users_modes[i]->len,
3789                                    FALSE);
3790       silc_buffer_free(channel_users_modes[i]);
3791     }
3792     silc_free(channel_users_modes);
3793   }
3794
3795   if (channel_topics) {
3796     int i;
3797
3798     for (i = 0; i < channel_users_modes_c; i++) {
3799       if (!channel_topics[i])
3800         continue;
3801
3802       silc_buffer_push(channel_topics[i],
3803                        channel_topics[i]->data -
3804                        channel_topics[i]->head);
3805       SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
3806                        channel_topics[i]->len);
3807       silc_server_packet_send_dest(server, remote,
3808                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3809                                    channel_ids[i], SILC_ID_CHANNEL,
3810                                    channel_topics[i]->data,
3811                                    channel_topics[i]->len,
3812                                    FALSE);
3813       silc_buffer_free(channel_topics[i]);
3814     }
3815     silc_free(channel_topics);
3816   }
3817
3818   silc_free(channel_ids);
3819 }
3820
3821 /* Failure timeout callback. If this is called then we will immediately
3822    process the received failure. We always process the failure with timeout
3823    since we do not want to blindly trust to received failure packets.
3824    This won't be called (the timeout is cancelled) if the failure was
3825    bogus (it is bogus if remote does not close the connection after sending
3826    the failure). */
3827
3828 SILC_TASK_CALLBACK(silc_server_failure_callback)
3829 {
3830   SilcServerFailureContext f = (SilcServerFailureContext)context;
3831
3832   if (f->sock->protocol) {
3833     f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3834     silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3835   }
3836
3837   silc_free(f);
3838 }
3839
3840 /* Assembles user list and users mode list from the `channel'. */
3841
3842 void silc_server_get_users_on_channel(SilcServer server,
3843                                       SilcChannelEntry channel,
3844                                       SilcBuffer *user_list,
3845                                       SilcBuffer *mode_list,
3846                                       SilcUInt32 *user_count)
3847 {
3848   SilcChannelClientEntry chl;
3849   SilcHashTableList htl;
3850   SilcBuffer client_id_list;
3851   SilcBuffer client_mode_list;
3852   SilcBuffer idp;
3853   SilcUInt32 list_count = 0, len = 0;
3854
3855   silc_hash_table_list(channel->user_list, &htl);
3856   while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3857     len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3858   silc_hash_table_list_reset(&htl);
3859
3860   client_id_list = silc_buffer_alloc(len);
3861   client_mode_list =
3862     silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3863   silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3864   silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3865
3866   silc_hash_table_list(channel->user_list, &htl);
3867   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3868     /* Client ID */
3869     idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3870     silc_buffer_put(client_id_list, idp->data, idp->len);
3871     silc_buffer_pull(client_id_list, idp->len);
3872     silc_buffer_free(idp);
3873
3874     /* Client's mode on channel */
3875     SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3876     silc_buffer_pull(client_mode_list, 4);
3877
3878     list_count++;
3879   }
3880   silc_hash_table_list_reset(&htl);
3881   silc_buffer_push(client_id_list,
3882                    client_id_list->data - client_id_list->head);
3883   silc_buffer_push(client_mode_list,
3884                    client_mode_list->data - client_mode_list->head);
3885
3886   *user_list = client_id_list;
3887   *mode_list = client_mode_list;
3888   *user_count = list_count;
3889 }
3890
3891 /* Saves users and their modes to the `channel'. */
3892
3893 void silc_server_save_users_on_channel(SilcServer server,
3894                                        SilcSocketConnection sock,
3895                                        SilcChannelEntry channel,
3896                                        SilcClientID *noadd,
3897                                        SilcBuffer user_list,
3898                                        SilcBuffer mode_list,
3899                                        SilcUInt32 user_count)
3900 {
3901   int i;
3902   SilcUInt16 idp_len;
3903   SilcUInt32 mode;
3904   SilcClientID *client_id;
3905   SilcClientEntry client;
3906   SilcIDCacheEntry cache;
3907   bool global;
3908
3909   SILC_LOG_DEBUG(("Start"));
3910
3911   for (i = 0; i < user_count; i++) {
3912     /* Client ID */
3913     SILC_GET16_MSB(idp_len, user_list->data + 2);
3914     idp_len += 4;
3915     client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
3916     silc_buffer_pull(user_list, idp_len);
3917     if (!client_id)
3918       continue;
3919
3920     /* Mode */
3921     SILC_GET32_MSB(mode, mode_list->data);
3922     silc_buffer_pull(mode_list, 4);
3923
3924     if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3925       silc_free(client_id);
3926       continue;
3927     }
3928
3929     global = FALSE;
3930
3931     /* Check if we have this client cached already. */
3932     client = silc_idlist_find_client_by_id(server->local_list, client_id,
3933                                            server->server_type, &cache);
3934     if (!client) {
3935       client = silc_idlist_find_client_by_id(server->global_list,
3936                                              client_id, server->server_type,
3937                                              &cache);
3938       global = TRUE;
3939     }
3940     if (!client) {
3941       /* If router did not find such Client ID in its lists then this must
3942          be bogus client or some router in the net is buggy. */
3943       if (server->server_type == SILC_ROUTER) {
3944         silc_free(client_id);
3945         continue;
3946       }
3947
3948       /* We don't have that client anywhere, add it. The client is added
3949          to global list since server didn't have it in the lists so it must be
3950          global. */
3951       client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3952                                       silc_id_dup(client_id, SILC_ID_CLIENT),
3953                                       sock->user_data, NULL, 0);
3954       if (!client) {
3955         SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3956         silc_free(client_id);
3957         continue;
3958       }
3959
3960       client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3961     } else {
3962       /* Found, if it is from global list we'll assure that we won't
3963          expire it now that the entry is on channel. */
3964       if (global)
3965         cache->expire = 0;
3966     }
3967
3968     silc_free(client_id);
3969
3970     if (!silc_server_client_on_channel(client, channel, NULL)) {
3971       /* Client was not on the channel, add it. */
3972       SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3973       chl->client = client;
3974       chl->mode = mode;
3975       chl->channel = channel;
3976       silc_hash_table_add(channel->user_list, chl->client, chl);
3977       silc_hash_table_add(client->channels, chl->channel, chl);
3978       channel->user_count++;
3979     }
3980   }
3981 }
3982
3983 /* Lookups route to the client indicated by the `id_data'. The connection
3984    object and internal data object is returned. Returns NULL if route
3985    could not be found to the client. If the `client_id' is specified then
3986    it is used and the `id_data' is ignored. */
3987
3988 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3989                                                   unsigned char *id_data,
3990                                                   SilcUInt32 id_len,
3991                                                   SilcClientID *client_id,
3992                                                   SilcIDListData *idata)
3993 {
3994   SilcClientID *id;
3995   SilcClientEntry client;
3996
3997   SILC_LOG_DEBUG(("Start"));
3998
3999   /* Decode destination Client ID */
4000   if (!client_id) {
4001     id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
4002     if (!id) {
4003       SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
4004       return NULL;
4005     }
4006   } else {
4007     id = silc_id_dup(client_id, SILC_ID_CLIENT);
4008   }
4009
4010   /* If the destination belongs to our server we don't have to route
4011      the packet anywhere but to send it to the local destination. */
4012   client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
4013   if (client) {
4014     silc_free(id);
4015
4016     /* If we are router and the client has router then the client is in
4017        our cell but not directly connected to us. */
4018     if (server->server_type == SILC_ROUTER && client->router) {
4019       /* We are of course in this case the client's router thus the route
4020          to the client is the server who owns the client. So, we will send
4021          the packet to that server. */
4022       if (idata)
4023         *idata = (SilcIDListData)client->router;
4024       return client->router->connection;
4025     }
4026
4027     /* Seems that client really is directly connected to us */
4028     if (idata)
4029       *idata = (SilcIDListData)client;
4030     return client->connection;
4031   }
4032
4033   /* Destination belongs to someone not in this server. If we are normal
4034      server our action is to send the packet to our router. */
4035   if (server->server_type != SILC_ROUTER && !server->standalone) {
4036     silc_free(id);
4037     if (idata)
4038       *idata = (SilcIDListData)server->router;
4039     return server->router->connection;
4040   }
4041
4042   /* We are router and we will perform route lookup for the destination
4043      and send the packet to fastest route. */
4044   if (server->server_type == SILC_ROUTER && !server->standalone) {
4045     /* Check first that the ID is valid */
4046     client = silc_idlist_find_client_by_id(server->global_list, id,
4047                                            TRUE, NULL);
4048     if (client) {
4049       SilcSocketConnection dst_sock;
4050
4051       dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
4052
4053       silc_free(id);
4054       if (idata)
4055         *idata = (SilcIDListData)dst_sock->user_data;
4056       return dst_sock;
4057     }
4058   }
4059
4060   silc_free(id);
4061   return NULL;
4062 }
4063
4064 /* Encodes and returns channel list of channels the `client' has joined.
4065    Secret channels are not put to the list. */
4066
4067 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
4068                                                SilcClientEntry client)
4069 {
4070   SilcBuffer buffer = NULL;
4071   SilcChannelEntry channel;
4072   SilcChannelClientEntry chl;
4073   SilcHashTableList htl;
4074   unsigned char *cid;
4075   SilcUInt32 id_len;
4076   SilcUInt16 name_len;
4077   int len;
4078
4079   silc_hash_table_list(client->channels, &htl);
4080   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4081     channel = chl->channel;
4082
4083     if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
4084         channel->mode & SILC_CHANNEL_MODE_PRIVATE)
4085       continue;
4086
4087     cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4088     id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4089     name_len = strlen(channel->channel_name);
4090
4091     len = 4 + name_len + id_len + 4;
4092     buffer = silc_buffer_realloc(buffer,
4093                                  (buffer ? (buffer)->truelen + len : len));
4094     silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
4095     silc_buffer_format(buffer,
4096                        SILC_STR_UI_SHORT(name_len),
4097                        SILC_STR_UI_XNSTRING(channel->channel_name,
4098                                             name_len),
4099                        SILC_STR_UI_SHORT(id_len),
4100                        SILC_STR_UI_XNSTRING(cid, id_len),
4101                        SILC_STR_UI_INT(chl->mode), /* Client's mode */
4102                        SILC_STR_END);
4103     silc_buffer_pull(buffer, len);
4104     silc_free(cid);
4105   }
4106   silc_hash_table_list_reset(&htl);
4107
4108   if (buffer)
4109     silc_buffer_push(buffer, buffer->data - buffer->head);
4110
4111   return buffer;
4112 }
4113
4114 /* Finds client entry by Client ID and if it is not found then resolves
4115    it using WHOIS command. */
4116
4117 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4118                                                SilcClientID *client_id,
4119                                                bool *resolved)
4120 {
4121   SilcClientEntry client;
4122
4123   if (resolved)
4124     *resolved = FALSE;
4125
4126   client = silc_idlist_find_client_by_id(server->local_list, client_id,
4127                                          TRUE, NULL);
4128   if (!client) {
4129     client = silc_idlist_find_client_by_id(server->global_list,
4130                                            client_id, TRUE, NULL);
4131     if (!client && server->server_type == SILC_ROUTER)
4132       return NULL;
4133   }
4134
4135   if (!client && server->standalone)
4136     return NULL;
4137
4138   if (!client || !client->nickname || !client->username) {
4139     SilcBuffer buffer, idp;
4140
4141     client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4142     client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4143     client->resolve_cmd_ident = ++server->cmd_ident;
4144
4145     idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4146     buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4147                                             server->cmd_ident, 1,
4148                                             3, idp->data, idp->len);
4149     silc_server_packet_send(server, client ? client->router->connection :
4150                             server->router->connection,
4151                             SILC_PACKET_COMMAND, 0,
4152                             buffer->data, buffer->len, FALSE);
4153     silc_buffer_free(idp);
4154     silc_buffer_free(buffer);
4155
4156     if (resolved)
4157       *resolved = TRUE;
4158
4159     return NULL;
4160   }
4161
4162   return client;
4163 }
4164
4165 /* A timeout callback for the re-key. We will be the initiator of the
4166    re-key protocol. */
4167
4168 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4169 {
4170   SilcSocketConnection sock = (SilcSocketConnection)context;
4171   SilcIDListData idata = (SilcIDListData)sock->user_data;
4172   SilcServer server = (SilcServer)idata->rekey->context;
4173   SilcProtocol protocol;
4174   SilcServerRekeyInternalContext *proto_ctx;
4175
4176   SILC_LOG_DEBUG(("Start"));
4177
4178   /* Allocate internal protocol context. This is sent as context
4179      to the protocol. */
4180   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4181   proto_ctx->server = (void *)server;
4182   proto_ctx->sock = sock;
4183   proto_ctx->responder = FALSE;
4184   proto_ctx->pfs = idata->rekey->pfs;
4185
4186   /* Perform rekey protocol. Will call the final callback after the
4187      protocol is over. */
4188   silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4189                       &protocol, proto_ctx, silc_server_rekey_final);
4190   sock->protocol = protocol;
4191
4192   /* Run the protocol */
4193   silc_protocol_execute(protocol, server->schedule, 0, 0);
4194
4195   /* Re-register re-key timeout */
4196   silc_schedule_task_add(server->schedule, sock->sock,
4197                          silc_server_rekey_callback,
4198                          context, idata->rekey->timeout, 0,
4199                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4200 }
4201
4202 /* The final callback for the REKEY protocol. This will actually take the
4203    new key material into use. */
4204
4205 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4206 {
4207   SilcProtocol protocol = (SilcProtocol)context;
4208   SilcServerRekeyInternalContext *ctx =
4209     (SilcServerRekeyInternalContext *)protocol->context;
4210   SilcServer server = (SilcServer)ctx->server;
4211   SilcSocketConnection sock = ctx->sock;
4212
4213   SILC_LOG_DEBUG(("Start"));
4214
4215   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4216       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4217     /* Error occured during protocol */
4218     SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4219     silc_protocol_cancel(protocol, server->schedule);
4220     silc_protocol_free(protocol);
4221     sock->protocol = NULL;
4222     if (ctx->packet)
4223       silc_packet_context_free(ctx->packet);
4224     if (ctx->ske)
4225       silc_ske_free(ctx->ske);
4226     silc_free(ctx);
4227     return;
4228   }
4229
4230   /* Purge the outgoing data queue to assure that all rekey packets really
4231      go to the network before we quit the protocol. */
4232   silc_server_packet_queue_purge(server, sock);
4233
4234   /* Cleanup */
4235   silc_protocol_free(protocol);
4236   sock->protocol = NULL;
4237   if (ctx->packet)
4238     silc_packet_context_free(ctx->packet);
4239   if (ctx->ske)
4240     silc_ske_free(ctx->ske);
4241   silc_free(ctx);
4242 }