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