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