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