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