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