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