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         continue;
2608       }
2609
2610       /* Remove the channel entry */
2611       if (silc_idlist_del_channel(server->local_list, channel))
2612         server->stat.my_channels--;
2613       else 
2614         silc_idlist_del_channel(server->global_list, channel);
2615       continue;
2616     }
2617
2618     /* Send notify to channel about client leaving SILC and thus
2619        the entire channel. */
2620     if (notify)
2621       silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2622                                          SILC_NOTIFY_TYPE_SIGNOFF, 
2623                                          signoff_message ? 2 : 1,
2624                                          clidp->data, clidp->len,
2625                                          signoff_message, signoff_message ?
2626                                          strlen(signoff_message) : 0);
2627
2628     if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2629       /* Re-generate channel key */
2630       if (!silc_server_create_channel_key(server, channel, 0))
2631         return;
2632       
2633       /* Send the channel key to the channel. The key of course is not sent
2634          to the client who was removed from the channel. */
2635       silc_server_send_channel_key(server, client->connection, channel, 
2636                                    server->server_type == SILC_ROUTER ? 
2637                                    FALSE : !server->standalone);
2638     }
2639   }
2640
2641   silc_buffer_free(clidp);
2642 }
2643
2644 /* Removes client from one channel. This is used for example when client
2645    calls LEAVE command to remove itself from the channel. Returns TRUE
2646    if channel still exists and FALSE if the channel is removed when
2647    last client leaves the channel. If `notify' is FALSE notify messages
2648    are not sent. */
2649
2650 int silc_server_remove_from_one_channel(SilcServer server, 
2651                                         SilcSocketConnection sock,
2652                                         SilcChannelEntry channel,
2653                                         SilcClientEntry client,
2654                                         int notify)
2655 {
2656   SilcChannelClientEntry chl;
2657   SilcBuffer clidp;
2658
2659   SILC_LOG_DEBUG(("Start"));
2660
2661   /* Get the entry to the channel, if this client is not on the channel
2662      then return Ok. */
2663   if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2664     return TRUE;
2665
2666   /* Remove the client from the channel. The client is removed from
2667      the channel's user list. */
2668
2669   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2670
2671   /* Remove channel from client's channel list */
2672   silc_hash_table_del(client->channels, chl->channel);
2673
2674   /* Remove channel if there is no users anymore */
2675   if (server->server_type == SILC_ROUTER &&
2676       silc_hash_table_count(channel->user_list) < 2) {
2677     if (channel->rekey)
2678       silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2679     if (silc_idlist_del_channel(server->local_list, channel))
2680       server->stat.my_channels--;
2681     else 
2682       silc_idlist_del_channel(server->global_list, channel);
2683     silc_buffer_free(clidp);
2684     return FALSE;
2685   }
2686
2687   /* Remove client from channel's client list */
2688   silc_hash_table_del(channel->user_list, chl->client);
2689   
2690   /* If there is no global users on the channel anymore mark the channel
2691      as local channel. Do not check if the client is local client. */
2692   if (server->server_type != SILC_ROUTER && channel->global_users &&
2693       chl->client->router && !silc_server_channel_has_global(channel))
2694     channel->global_users = FALSE;
2695
2696   silc_free(chl);
2697   server->stat.my_chanclients--;
2698
2699   /* If there is not at least one local user on the channel then we don't
2700      need the channel entry anymore, we can remove it safely. */
2701   if (server->server_type != SILC_ROUTER &&
2702       !silc_server_channel_has_local(channel)) {
2703     /* Notify about leaving client if this channel has global users. */
2704     if (notify && channel->global_users)
2705       silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2706                                          SILC_NOTIFY_TYPE_LEAVE, 1,
2707                                          clidp->data, clidp->len);
2708     
2709     silc_buffer_free(clidp);
2710     
2711     if (channel->rekey)
2712       silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2713
2714     if (channel->founder_key) {
2715       /* The founder auth data exists, do not remove the channel entry */
2716       SilcChannelClientEntry chl2;
2717       SilcHashTableList htl2;
2718       
2719       channel->disabled = TRUE;
2720       
2721       silc_hash_table_list(channel->user_list, &htl2);
2722       while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2723         silc_hash_table_del(chl2->client->channels, channel);
2724         silc_hash_table_del(channel->user_list, chl2->client);
2725         silc_free(chl2);
2726       }
2727       return FALSE;
2728     }
2729
2730     /* Remove the channel entry */
2731     if (silc_idlist_del_channel(server->local_list, channel))
2732       server->stat.my_channels--;
2733     else 
2734       silc_idlist_del_channel(server->global_list, channel);
2735     return FALSE;
2736   }
2737
2738   /* Send notify to channel about client leaving the channel */
2739   if (notify)
2740     silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2741                                        SILC_NOTIFY_TYPE_LEAVE, 1,
2742                                        clidp->data, clidp->len);
2743
2744   silc_buffer_free(clidp);
2745   return TRUE;
2746 }
2747
2748 /* Timeout callback. This is called if connection is idle or for some
2749    other reason is not responding within some period of time. This 
2750    disconnects the remote end. */
2751
2752 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2753 {
2754   SilcServer server = (SilcServer)context;
2755   SilcSocketConnection sock = server->sockets[fd];
2756
2757   SILC_LOG_DEBUG(("Start"));
2758
2759   if (!sock)
2760     return;
2761
2762   /* If we have protocol active we must assure that we call the protocol's
2763      final callback so that all the memory is freed. */
2764   if (sock->protocol) {
2765     silc_protocol_cancel(sock->protocol, server->schedule);
2766     sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2767     silc_protocol_execute_final(sock->protocol, server->schedule);
2768     sock->protocol = NULL;
2769     return;
2770   }
2771
2772   if (sock->user_data)
2773     silc_server_free_sock_user_data(server, sock, NULL);
2774
2775   silc_server_disconnect_remote(server, sock, "Server closed connection: "
2776                                 "Connection timeout");
2777 }
2778
2779 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2780    function may be used only by router. In real SILC network all channels
2781    are created by routers thus this function is never used by normal
2782    server. */
2783
2784 SilcChannelEntry silc_server_create_new_channel(SilcServer server, 
2785                                                 SilcServerID *router_id,
2786                                                 char *cipher, 
2787                                                 char *hmac,
2788                                                 char *channel_name,
2789                                                 int broadcast)
2790 {
2791   SilcChannelID *channel_id;
2792   SilcChannelEntry entry;
2793   SilcCipher key;
2794   SilcHmac newhmac;
2795
2796   SILC_LOG_DEBUG(("Creating new channel"));
2797
2798   if (!cipher)
2799     cipher = SILC_DEFAULT_CIPHER;
2800   if (!hmac)
2801     hmac = SILC_DEFAULT_HMAC;
2802
2803   /* Allocate cipher */
2804   if (!silc_cipher_alloc(cipher, &key))
2805     return NULL;
2806
2807   /* Allocate hmac */
2808   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2809     silc_cipher_free(key);
2810     return NULL;
2811   }
2812
2813   channel_name = strdup(channel_name);
2814
2815   /* Create the channel ID */
2816   if (!silc_id_create_channel_id(server, router_id, server->rng, 
2817                                  &channel_id)) {
2818     silc_free(channel_name);
2819     silc_cipher_free(key);
2820     silc_hmac_free(newhmac);
2821     return NULL;
2822   }
2823
2824   /* Create the channel */
2825   entry = silc_idlist_add_channel(server->local_list, channel_name, 
2826                                   SILC_CHANNEL_MODE_NONE, channel_id, 
2827                                   NULL, key, newhmac, 0);
2828   if (!entry) {
2829     silc_free(channel_name);
2830     silc_cipher_free(key);
2831     silc_hmac_free(newhmac);
2832     silc_free(channel_id);
2833     return NULL;
2834   }
2835
2836   entry->cipher = strdup(cipher);
2837   entry->hmac_name = strdup(hmac);
2838
2839   /* Now create the actual key material */
2840   if (!silc_server_create_channel_key(server, entry, 
2841                                       silc_cipher_get_key_len(key) / 8)) {
2842     silc_idlist_del_channel(server->local_list, entry);
2843     return NULL;
2844   }
2845
2846   /* Notify other routers about the new channel. We send the packet
2847      to our primary route. */
2848   if (broadcast && server->standalone == FALSE)
2849     silc_server_send_new_channel(server, server->router->connection, TRUE, 
2850                                  channel_name, entry->id, 
2851                                  silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2852                                  entry->mode);
2853
2854   server->stat.my_channels++;
2855
2856   return entry;
2857 }
2858
2859 /* Same as above but creates the channel with Channel ID `channel_id. */
2860
2861 SilcChannelEntry 
2862 silc_server_create_new_channel_with_id(SilcServer server, 
2863                                        char *cipher, 
2864                                        char *hmac,
2865                                        char *channel_name,
2866                                        SilcChannelID *channel_id,
2867                                        int broadcast)
2868 {
2869   SilcChannelEntry entry;
2870   SilcCipher key;
2871   SilcHmac newhmac;
2872
2873   SILC_LOG_DEBUG(("Creating new channel"));
2874
2875   if (!cipher)
2876     cipher = SILC_DEFAULT_CIPHER;
2877   if (!hmac)
2878     hmac = SILC_DEFAULT_HMAC;
2879
2880   /* Allocate cipher */
2881   if (!silc_cipher_alloc(cipher, &key))
2882     return NULL;
2883
2884   /* Allocate hmac */
2885   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2886     silc_cipher_free(key);
2887     return NULL;
2888   }
2889
2890   channel_name = strdup(channel_name);
2891
2892   /* Create the channel */
2893   entry = silc_idlist_add_channel(server->local_list, channel_name, 
2894                                   SILC_CHANNEL_MODE_NONE, channel_id, 
2895                                   NULL, key, newhmac, 0);
2896   if (!entry) {
2897     silc_cipher_free(key);
2898     silc_hmac_free(newhmac);
2899     silc_free(channel_name);
2900     return NULL;
2901   }
2902
2903   /* Now create the actual key material */
2904   if (!silc_server_create_channel_key(server, entry, 
2905                                       silc_cipher_get_key_len(key) / 8)) {
2906     silc_idlist_del_channel(server->local_list, entry);
2907     return NULL;
2908   }
2909
2910   /* Notify other routers about the new channel. We send the packet
2911      to our primary route. */
2912   if (broadcast && server->standalone == FALSE)
2913     silc_server_send_new_channel(server, server->router->connection, TRUE, 
2914                                  channel_name, entry->id, 
2915                                  silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2916                                  entry->mode);
2917
2918   server->stat.my_channels++;
2919
2920   return entry;
2921 }
2922
2923 /* Channel's key re-key timeout callback. */
2924
2925 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
2926 {
2927   SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
2928   SilcServer server = (SilcServer)rekey->context;
2929
2930   rekey->task = NULL;
2931
2932   if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
2933     return;
2934
2935   silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
2936 }
2937
2938 /* Generates new channel key. This is used to create the initial channel key
2939    but also to re-generate new key for channel. If `key_len' is provided
2940    it is the bytes of the key length. */
2941
2942 bool silc_server_create_channel_key(SilcServer server, 
2943                                     SilcChannelEntry channel,
2944                                     uint32 key_len)
2945 {
2946   int i;
2947   unsigned char channel_key[32], hash[32];
2948   uint32 len;
2949
2950   SILC_LOG_DEBUG(("Generating channel key"));
2951
2952   if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
2953     SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
2954     return TRUE;
2955   }
2956
2957   if (!channel->channel_key)
2958     if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
2959       channel->channel_key = NULL;
2960       return FALSE;
2961     }
2962
2963   if (key_len)
2964     len = key_len;
2965   else if (channel->key_len)
2966     len = channel->key_len / 8;
2967   else
2968     len = silc_cipher_get_key_len(channel->channel_key) / 8;
2969
2970   /* Create channel key */
2971   for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
2972   
2973   /* Set the key */
2974   silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
2975
2976   /* Remove old key if exists */
2977   if (channel->key) {
2978     memset(channel->key, 0, channel->key_len / 8);
2979     silc_free(channel->key);
2980   }
2981
2982   /* Save the key */
2983   channel->key_len = len * 8;
2984   channel->key = silc_calloc(len, sizeof(*channel->key));
2985   memcpy(channel->key, channel_key, len);
2986   memset(channel_key, 0, sizeof(channel_key));
2987
2988   /* Generate HMAC key from the channel key data and set it */
2989   if (!channel->hmac)
2990     silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
2991   silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
2992   silc_hmac_set_key(channel->hmac, hash, 
2993                     silc_hash_len(silc_hmac_get_hash(channel->hmac)));
2994   memset(hash, 0, sizeof(hash));
2995
2996   if (server->server_type == SILC_ROUTER) {
2997     if (!channel->rekey)
2998       channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
2999     channel->rekey->context = (void *)server;
3000     channel->rekey->channel = channel;
3001     channel->rekey->key_len = key_len;
3002     if (channel->rekey->task)
3003       silc_schedule_task_del(server->schedule, channel->rekey->task);
3004
3005     channel->rekey->task = 
3006       silc_schedule_task_add(server->schedule, 0, 
3007                              silc_server_channel_key_rekey,
3008                              (void *)channel->rekey, 3600, 0,
3009                              SILC_TASK_TIMEOUT,
3010                              SILC_TASK_PRI_NORMAL);
3011   }
3012
3013   return TRUE;
3014 }
3015
3016 /* Saves the channel key found in the encoded `key_payload' buffer. This 
3017    function is used when we receive Channel Key Payload and also when we're
3018    processing JOIN command reply. Returns entry to the channel. */
3019
3020 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3021                                               SilcBuffer key_payload,
3022                                               SilcChannelEntry channel)
3023 {
3024   SilcChannelKeyPayload payload = NULL;
3025   SilcChannelID *id = NULL;
3026   unsigned char *tmp, hash[32];
3027   uint32 tmp_len;
3028   char *cipher;
3029
3030   SILC_LOG_DEBUG(("Start"));
3031
3032   /* Decode channel key payload */
3033   payload = silc_channel_key_payload_parse(key_payload->data, 
3034                                            key_payload->len);
3035   if (!payload) {
3036     SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3037     channel = NULL;
3038     goto out;
3039   }
3040
3041   /* Get the channel entry */
3042   if (!channel) {
3043
3044     /* Get channel ID */
3045     tmp = silc_channel_key_get_id(payload, &tmp_len);
3046     id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3047     if (!id) {
3048       channel = NULL;
3049       goto out;
3050     }
3051
3052     channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3053     if (!channel) {
3054       channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3055       if (!channel) {
3056         SILC_LOG_ERROR(("Received key for non-existent channel %s",
3057                         silc_id_render(id, SILC_ID_CHANNEL)));
3058         goto out;
3059       }
3060     }
3061   }
3062
3063   tmp = silc_channel_key_get_key(payload, &tmp_len);
3064   if (!tmp) {
3065     channel = NULL;
3066     goto out;
3067   }
3068
3069   cipher = silc_channel_key_get_cipher(payload, NULL);
3070   if (!cipher) {
3071     channel = NULL;
3072     goto out;
3073   }
3074
3075   /* Remove old key if exists */
3076   if (channel->key) {
3077     memset(channel->key, 0, channel->key_len / 8);
3078     silc_free(channel->key);
3079     silc_cipher_free(channel->channel_key);
3080   }
3081
3082   /* Create new cipher */
3083   if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3084     channel->channel_key = NULL;
3085     channel = NULL;
3086     goto out;
3087   }
3088
3089   if (channel->cipher)
3090     silc_free(channel->cipher);
3091   channel->cipher = strdup(cipher);
3092
3093   /* Save the key */
3094   channel->key_len = tmp_len * 8;
3095   channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
3096   memcpy(channel->key, tmp, tmp_len);
3097   silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3098
3099   /* Generate HMAC key from the channel key data and set it */
3100   if (!channel->hmac)
3101     silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3102   silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3103   silc_hmac_set_key(channel->hmac, hash, 
3104                     silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3105
3106   memset(hash, 0, sizeof(hash));
3107   memset(tmp, 0, tmp_len);
3108
3109   if (server->server_type == SILC_ROUTER) {
3110     if (!channel->rekey)
3111       channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3112     channel->rekey->context = (void *)server;
3113     channel->rekey->channel = channel;
3114     if (channel->rekey->task)
3115       silc_schedule_task_del(server->schedule, channel->rekey->task);
3116
3117     channel->rekey->task = 
3118       silc_schedule_task_add(server->schedule, 0, 
3119                              silc_server_channel_key_rekey,
3120                              (void *)channel->rekey, 3600, 0,
3121                              SILC_TASK_TIMEOUT,
3122                              SILC_TASK_PRI_NORMAL);
3123   }
3124
3125  out:
3126   silc_free(id);
3127   if (payload)
3128     silc_channel_key_payload_free(payload);
3129
3130   return channel;
3131 }
3132
3133 /* Heartbeat callback. This function is set as argument for the
3134    silc_socket_set_heartbeat function. The library will call this function
3135    at the set time interval. */
3136
3137 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3138                                    void *hb_context)
3139 {
3140   SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3141
3142   SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3143
3144   /* Send the heartbeat */
3145   silc_server_send_heartbeat(hb->server, sock);
3146 }
3147
3148 /* Returns assembled of all servers in the given ID list. The packet's
3149    form is dictated by the New ID payload. */
3150
3151 static void silc_server_announce_get_servers(SilcServer server,
3152                                              SilcServerEntry remote,
3153                                              SilcIDList id_list,
3154                                              SilcBuffer *servers,
3155                                              unsigned long creation_time)
3156 {
3157   SilcIDCacheList list;
3158   SilcIDCacheEntry id_cache;
3159   SilcServerEntry entry;
3160   SilcBuffer idp;
3161
3162   /* Go through all clients in the list */
3163   if (silc_idcache_get_all(id_list->servers, &list)) {
3164     if (silc_idcache_list_first(list, &id_cache)) {
3165       while (id_cache) {
3166         entry = (SilcServerEntry)id_cache->context;
3167
3168         /* Do not announce the one we've sending our announcements and
3169            do not announce ourself. Also check the creation time if it's
3170            provided. */
3171         if ((entry == remote) || (entry == server->id_entry) ||
3172             (creation_time && entry->data.created < creation_time)) {
3173           if (!silc_idcache_list_next(list, &id_cache))
3174             break;
3175           continue;
3176         }
3177
3178         idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3179
3180         *servers = silc_buffer_realloc(*servers, 
3181                                        (*servers ? 
3182                                         (*servers)->truelen + idp->len : 
3183                                         idp->len));
3184         silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3185         silc_buffer_put(*servers, idp->data, idp->len);
3186         silc_buffer_pull(*servers, idp->len);
3187         silc_buffer_free(idp);
3188
3189         if (!silc_idcache_list_next(list, &id_cache))
3190           break;
3191       }
3192     }
3193
3194     silc_idcache_list_free(list);
3195   }
3196 }
3197
3198 static SilcBuffer 
3199 silc_server_announce_encode_notify(SilcNotifyType notify, uint32 argc, ...)
3200 {
3201   va_list ap;
3202   SilcBuffer p;
3203
3204   va_start(ap, argc);
3205   p = silc_notify_payload_encode(notify, argc, ap);
3206   va_end(ap);
3207  
3208   return p;
3209 }
3210
3211 /* This function is used by router to announce existing servers to our
3212    primary router when we've connected to it. If `creation_time' is non-zero
3213    then only the servers that has been created after the `creation_time'
3214    will be announced. */
3215
3216 void silc_server_announce_servers(SilcServer server, bool global,
3217                                   unsigned long creation_time,
3218                                   SilcSocketConnection remote)
3219 {
3220   SilcBuffer servers = NULL;
3221
3222   SILC_LOG_DEBUG(("Announcing servers"));
3223
3224   /* Get servers in local list */
3225   silc_server_announce_get_servers(server, remote->user_data,
3226                                    server->local_list, &servers,
3227                                    creation_time);
3228
3229   if (global)
3230     /* Get servers in global list */
3231     silc_server_announce_get_servers(server, remote->user_data,
3232                                      server->global_list, &servers,
3233                                      creation_time);
3234
3235   if (servers) {
3236     silc_buffer_push(servers, servers->data - servers->head);
3237     SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3238
3239     /* Send the packet */
3240     silc_server_packet_send(server, remote,
3241                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3242                             servers->data, servers->len, TRUE);
3243
3244     silc_buffer_free(servers);
3245   }
3246 }
3247
3248 /* Returns assembled packet of all clients in the given ID list. The
3249    packet's form is dictated by the New ID Payload. */
3250
3251 static void silc_server_announce_get_clients(SilcServer server,
3252                                              SilcIDList id_list,
3253                                              SilcBuffer *clients,
3254                                              SilcBuffer *umodes,
3255                                              unsigned long creation_time)
3256 {
3257   SilcIDCacheList list;
3258   SilcIDCacheEntry id_cache;
3259   SilcClientEntry client;
3260   SilcBuffer idp;
3261   SilcBuffer tmp;
3262   unsigned char mode[4];
3263
3264   /* Go through all clients in the list */
3265   if (silc_idcache_get_all(id_list->clients, &list)) {
3266     if (silc_idcache_list_first(list, &id_cache)) {
3267       while (id_cache) {
3268         client = (SilcClientEntry)id_cache->context;
3269
3270         if (creation_time && client->data.created < creation_time) {
3271           if (!silc_idcache_list_next(list, &id_cache))
3272             break;
3273           continue;
3274         }
3275
3276         idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3277
3278         *clients = silc_buffer_realloc(*clients, 
3279                                        (*clients ? 
3280                                         (*clients)->truelen + idp->len : 
3281                                         idp->len));
3282         silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3283         silc_buffer_put(*clients, idp->data, idp->len);
3284         silc_buffer_pull(*clients, idp->len);
3285
3286         SILC_PUT32_MSB(client->mode, mode);
3287         tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3288                                                  2, idp->data, idp->len,
3289                                                  mode, 4);
3290         *umodes = silc_buffer_realloc(*umodes, 
3291                                       (*umodes ? 
3292                                        (*umodes)->truelen + tmp->len :  
3293                                        tmp->len));
3294         silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3295         silc_buffer_put(*umodes, tmp->data, tmp->len);
3296         silc_buffer_pull(*umodes, tmp->len);
3297         silc_buffer_free(tmp);
3298
3299         silc_buffer_free(idp);
3300
3301         if (!silc_idcache_list_next(list, &id_cache))
3302           break;
3303       }
3304     }
3305
3306     silc_idcache_list_free(list);
3307   }
3308 }
3309
3310 /* This function is used to announce our existing clients to our router
3311    when we've connected to it. If `creation_time' is non-zero then only
3312    the clients that has been created after the `creation_time' will be
3313    announced. */
3314
3315 void silc_server_announce_clients(SilcServer server,
3316                                   unsigned long creation_time,
3317                                   SilcSocketConnection remote)
3318 {
3319   SilcBuffer clients = NULL;
3320   SilcBuffer umodes = NULL;
3321
3322   SILC_LOG_DEBUG(("Announcing clients"));
3323
3324   /* Get clients in local list */
3325   silc_server_announce_get_clients(server, server->local_list,
3326                                    &clients, &umodes, creation_time);
3327
3328   /* As router we announce our global list as well */
3329   if (server->server_type == SILC_ROUTER)
3330     silc_server_announce_get_clients(server, server->global_list,
3331                                      &clients, &umodes, creation_time);
3332
3333   if (clients) {
3334     silc_buffer_push(clients, clients->data - clients->head);
3335     SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3336
3337     /* Send the packet */
3338     silc_server_packet_send(server, remote,
3339                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3340                             clients->data, clients->len, TRUE);
3341
3342     silc_buffer_free(clients);
3343   }
3344
3345   if (umodes) {
3346     silc_buffer_push(umodes, umodes->data - umodes->head);
3347     SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3348
3349     /* Send the packet */
3350     silc_server_packet_send(server, remote,
3351                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3352                             umodes->data, umodes->len, TRUE);
3353
3354     silc_buffer_free(umodes);
3355   }
3356 }
3357
3358 /* Returns channel's topic for announcing it */
3359
3360 void silc_server_announce_get_channel_topic(SilcServer server,
3361                                             SilcChannelEntry channel,
3362                                             SilcBuffer *topic)
3363 {
3364   SilcBuffer chidp;
3365
3366   if (channel->topic) {
3367     chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3368     *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3369                                                 chidp->data, chidp->len,
3370                                                 channel->topic, 
3371                                                 strlen(channel->topic));
3372     silc_buffer_free(chidp);
3373   }
3374 }
3375
3376 /* Returns assembled packets for channel users of the `channel'. */
3377
3378 void silc_server_announce_get_channel_users(SilcServer server,
3379                                             SilcChannelEntry channel,
3380                                             SilcBuffer *channel_users,
3381                                             SilcBuffer *channel_users_modes)
3382 {
3383   SilcChannelClientEntry chl;
3384   SilcHashTableList htl;
3385   SilcBuffer chidp, clidp;
3386   SilcBuffer tmp;
3387   int len;
3388   unsigned char mode[4];
3389
3390   SILC_LOG_DEBUG(("Start"));
3391
3392   /* Now find all users on the channel */
3393   chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3394   silc_hash_table_list(channel->user_list, &htl);
3395   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3396     clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3397
3398     /* JOIN Notify */
3399     tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2, 
3400                                              clidp->data, clidp->len,
3401                                              chidp->data, chidp->len);
3402     len = tmp->len;
3403     *channel_users = 
3404       silc_buffer_realloc(*channel_users, 
3405                           (*channel_users ? 
3406                            (*channel_users)->truelen + len : len));
3407     silc_buffer_pull_tail(*channel_users, 
3408                           ((*channel_users)->end - 
3409                            (*channel_users)->data));
3410     
3411     silc_buffer_put(*channel_users, tmp->data, tmp->len);
3412     silc_buffer_pull(*channel_users, len);
3413     silc_buffer_free(tmp);
3414
3415     /* CUMODE notify for mode change on the channel */
3416     SILC_PUT32_MSB(chl->mode, mode);
3417     tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE, 
3418                                              3, clidp->data, clidp->len,
3419                                              mode, 4,
3420                                              clidp->data, clidp->len);
3421     len = tmp->len;
3422     *channel_users_modes = 
3423       silc_buffer_realloc(*channel_users_modes, 
3424                           (*channel_users_modes ? 
3425                            (*channel_users_modes)->truelen + len : len));
3426     silc_buffer_pull_tail(*channel_users_modes, 
3427                           ((*channel_users_modes)->end - 
3428                            (*channel_users_modes)->data));
3429     
3430     silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3431     silc_buffer_pull(*channel_users_modes, len);
3432     silc_buffer_free(tmp);
3433
3434     silc_buffer_free(clidp);
3435   }
3436   silc_buffer_free(chidp);
3437 }
3438
3439 /* Returns assembled packets for all channels and users on those channels
3440    from the given ID List. The packets are in the form dictated by the
3441    New Channel and New Channel User payloads. */
3442
3443 void silc_server_announce_get_channels(SilcServer server,
3444                                        SilcIDList id_list,
3445                                        SilcBuffer *channels,
3446                                        SilcBuffer *channel_users,
3447                                        SilcBuffer **channel_users_modes,
3448                                        uint32 *channel_users_modes_c,
3449                                        SilcBuffer **channel_topics,
3450                                        SilcChannelID ***channel_ids,
3451                                        unsigned long creation_time)
3452 {
3453   SilcIDCacheList list;
3454   SilcIDCacheEntry id_cache;
3455   SilcChannelEntry channel;
3456   unsigned char *cid;
3457   uint32 id_len;
3458   uint16 name_len;
3459   int len;
3460   int i = *channel_users_modes_c;
3461   bool announce;
3462
3463   SILC_LOG_DEBUG(("Start"));
3464
3465   /* Go through all channels in the list */
3466   if (silc_idcache_get_all(id_list->channels, &list)) {
3467     if (silc_idcache_list_first(list, &id_cache)) {
3468       while (id_cache) {
3469         channel = (SilcChannelEntry)id_cache->context;
3470
3471         if (creation_time && channel->created < creation_time)
3472           announce = FALSE;
3473         else
3474           announce = TRUE;
3475
3476         cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3477         id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3478         name_len = strlen(channel->channel_name);
3479
3480         if (announce) {
3481           len = 4 + name_len + id_len + 4;
3482           *channels = 
3483             silc_buffer_realloc(*channels, 
3484                                 (*channels ? (*channels)->truelen + 
3485                                  len : len));
3486           silc_buffer_pull_tail(*channels, 
3487                                 ((*channels)->end - (*channels)->data));
3488           silc_buffer_format(*channels,
3489                              SILC_STR_UI_SHORT(name_len),
3490                              SILC_STR_UI_XNSTRING(channel->channel_name, 
3491                                                   name_len),
3492                              SILC_STR_UI_SHORT(id_len),
3493                              SILC_STR_UI_XNSTRING(cid, id_len),
3494                              SILC_STR_UI_INT(channel->mode),
3495                              SILC_STR_END);
3496           silc_buffer_pull(*channels, len);
3497         }
3498
3499         /* Channel user modes */
3500         *channel_users_modes = silc_realloc(*channel_users_modes,
3501                                             sizeof(**channel_users_modes) * 
3502                                             (i + 1));
3503         (*channel_users_modes)[i] = NULL;
3504         *channel_ids = silc_realloc(*channel_ids, 
3505                                     sizeof(**channel_ids) * (i + 1));
3506         (*channel_ids)[i] = NULL;
3507         silc_server_announce_get_channel_users(server, channel,
3508                                                channel_users,
3509                                                &(*channel_users_modes)[i]);
3510         (*channel_ids)[i] = channel->id;
3511
3512         /* Channel's topic */
3513         *channel_topics = silc_realloc(*channel_topics,
3514                                        sizeof(**channel_topics) * (i + 1));
3515         (*channel_topics)[i] = NULL;
3516         silc_server_announce_get_channel_topic(server, channel,
3517                                                &(*channel_topics)[i]);
3518         i++;
3519
3520         if (!silc_idcache_list_next(list, &id_cache))
3521           break;
3522       }
3523
3524       *channel_users_modes_c += i;
3525     }
3526
3527     silc_idcache_list_free(list);
3528   }
3529 }
3530
3531 /* This function is used to announce our existing channels to our router
3532    when we've connected to it. This also announces the users on the
3533    channels to the router. If the `creation_time' is non-zero only the
3534    channels that was created after the `creation_time' are announced.
3535    Note that the channel users are still announced even if the `creation_time'
3536    was provided. */
3537
3538 void silc_server_announce_channels(SilcServer server,
3539                                    unsigned long creation_time,
3540                                    SilcSocketConnection remote)
3541 {
3542   SilcBuffer channels = NULL, channel_users = NULL;
3543   SilcBuffer *channel_users_modes = NULL;
3544   SilcBuffer *channel_topics = NULL;
3545   uint32 channel_users_modes_c = 0;
3546   SilcChannelID **channel_ids = NULL;
3547
3548   SILC_LOG_DEBUG(("Announcing channels and channel users"));
3549
3550   /* Get channels and channel users in local list */
3551   silc_server_announce_get_channels(server, server->local_list,
3552                                     &channels, &channel_users,
3553                                     &channel_users_modes,
3554                                     &channel_users_modes_c,
3555                                     &channel_topics,
3556                                     &channel_ids, creation_time);
3557
3558   /* Get channels and channel users in global list */
3559   if (server->server_type != SILC_SERVER)
3560     silc_server_announce_get_channels(server, server->global_list,
3561                                       &channels, &channel_users,
3562                                       &channel_users_modes,
3563                                       &channel_users_modes_c,
3564                                       &channel_topics,
3565                                       &channel_ids, creation_time);
3566
3567   if (channels) {
3568     silc_buffer_push(channels, channels->data - channels->head);
3569     SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3570
3571     /* Send the packet */
3572     silc_server_packet_send(server, remote,
3573                             SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3574                             channels->data, channels->len,
3575                             FALSE);
3576
3577     silc_buffer_free(channels);
3578   }
3579
3580   if (channel_users) {
3581     silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3582     SILC_LOG_HEXDUMP(("channel users"), channel_users->data, 
3583                      channel_users->len);
3584
3585     /* Send the packet */
3586     silc_server_packet_send(server, remote,
3587                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3588                             channel_users->data, channel_users->len,
3589                             FALSE);
3590
3591     silc_buffer_free(channel_users);
3592   }
3593
3594   if (channel_users_modes) {
3595     int i;
3596
3597     for (i = 0; i < channel_users_modes_c; i++) {
3598       if (!channel_users_modes[i])
3599         continue;
3600       silc_buffer_push(channel_users_modes[i], 
3601                        channel_users_modes[i]->data - 
3602                        channel_users_modes[i]->head);
3603       SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data, 
3604                        channel_users_modes[i]->len);
3605       silc_server_packet_send_dest(server, remote,
3606                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3607                                    channel_ids[i], SILC_ID_CHANNEL,
3608                                    channel_users_modes[i]->data, 
3609                                    channel_users_modes[i]->len,
3610                                    FALSE);
3611       silc_buffer_free(channel_users_modes[i]);
3612     }
3613     silc_free(channel_users_modes);
3614   }
3615
3616   if (channel_topics) {
3617     int i;
3618
3619     for (i = 0; i < channel_users_modes_c; i++) {
3620       if (!channel_topics[i])
3621         continue;
3622
3623       silc_buffer_push(channel_topics[i], 
3624                        channel_topics[i]->data - 
3625                        channel_topics[i]->head);
3626       SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data, 
3627                        channel_topics[i]->len);
3628       silc_server_packet_send_dest(server, remote,
3629                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3630                                    channel_ids[i], SILC_ID_CHANNEL,
3631                                    channel_topics[i]->data, 
3632                                    channel_topics[i]->len,
3633                                    FALSE);
3634       silc_buffer_free(channel_topics[i]);
3635     }
3636     silc_free(channel_topics);
3637   }
3638
3639   silc_free(channel_ids);
3640 }
3641
3642 /* Failure timeout callback. If this is called then we will immediately
3643    process the received failure. We always process the failure with timeout
3644    since we do not want to blindly trust to received failure packets. 
3645    This won't be called (the timeout is cancelled) if the failure was
3646    bogus (it is bogus if remote does not close the connection after sending
3647    the failure). */
3648
3649 SILC_TASK_CALLBACK(silc_server_failure_callback)
3650 {
3651   SilcServerFailureContext f = (SilcServerFailureContext)context;
3652
3653   if (f->sock->protocol) {
3654     f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3655     silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3656   }
3657
3658   silc_free(f);
3659 }
3660
3661 /* Assembles user list and users mode list from the `channel'. */
3662
3663 void silc_server_get_users_on_channel(SilcServer server,
3664                                       SilcChannelEntry channel,
3665                                       SilcBuffer *user_list,
3666                                       SilcBuffer *mode_list,
3667                                       uint32 *user_count)
3668 {
3669   SilcChannelClientEntry chl;
3670   SilcHashTableList htl;
3671   SilcBuffer client_id_list;
3672   SilcBuffer client_mode_list;
3673   SilcBuffer idp;
3674   uint32 list_count = 0, len = 0;
3675
3676   silc_hash_table_list(channel->user_list, &htl);
3677   while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3678     len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3679
3680   client_id_list = silc_buffer_alloc(len);
3681   client_mode_list = 
3682     silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3683   silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3684   silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3685
3686   silc_hash_table_list(channel->user_list, &htl);
3687   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3688     /* Client ID */
3689     idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3690     silc_buffer_put(client_id_list, idp->data, idp->len);
3691     silc_buffer_pull(client_id_list, idp->len);
3692     silc_buffer_free(idp);
3693
3694     /* Client's mode on channel */
3695     SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3696     silc_buffer_pull(client_mode_list, 4);
3697
3698     list_count++;
3699   }
3700   silc_buffer_push(client_id_list, 
3701                    client_id_list->data - client_id_list->head);
3702   silc_buffer_push(client_mode_list, 
3703                    client_mode_list->data - client_mode_list->head);
3704
3705   *user_list = client_id_list;
3706   *mode_list = client_mode_list;
3707   *user_count = list_count;
3708 }
3709
3710 /* Saves users and their modes to the `channel'. */
3711
3712 void silc_server_save_users_on_channel(SilcServer server,
3713                                        SilcSocketConnection sock,
3714                                        SilcChannelEntry channel,
3715                                        SilcClientID *noadd,
3716                                        SilcBuffer user_list,
3717                                        SilcBuffer mode_list,
3718                                        uint32 user_count)
3719 {
3720   int i;
3721   uint16 idp_len;
3722   uint32 mode;
3723   SilcClientID *client_id;
3724   SilcClientEntry client;
3725   SilcIDCacheEntry cache;
3726   bool global;
3727
3728   SILC_LOG_DEBUG(("Start"));
3729
3730   for (i = 0; i < user_count; i++) {
3731     /* Client ID */
3732     SILC_GET16_MSB(idp_len, user_list->data + 2);
3733     idp_len += 4;
3734     client_id = silc_id_payload_parse_id(user_list->data, idp_len);
3735     silc_buffer_pull(user_list, idp_len);
3736     if (!client_id)
3737       continue;
3738
3739     /* Mode */
3740     SILC_GET32_MSB(mode, mode_list->data);
3741     silc_buffer_pull(mode_list, 4);
3742
3743     if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3744       silc_free(client_id);
3745       continue;
3746     }
3747
3748     global = FALSE;
3749     
3750     /* Check if we have this client cached already. */
3751     client = silc_idlist_find_client_by_id(server->local_list, client_id,
3752                                            server->server_type, &cache);
3753     if (!client) {
3754       client = silc_idlist_find_client_by_id(server->global_list, 
3755                                              client_id, server->server_type,
3756                                              &cache);
3757       global = TRUE;
3758     }
3759     if (!client) {
3760       /* If router did not find such Client ID in its lists then this must
3761          be bogus client or some router in the net is buggy. */
3762       if (server->server_type == SILC_ROUTER) {
3763         silc_free(client_id);
3764         continue;
3765       }
3766
3767       /* We don't have that client anywhere, add it. The client is added
3768          to global list since server didn't have it in the lists so it must be 
3769          global. */
3770       client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3771                                       silc_id_dup(client_id, SILC_ID_CLIENT), 
3772                                       sock->user_data, NULL, 0);
3773       if (!client) {
3774         SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3775         silc_free(client_id);
3776         continue;
3777       }
3778
3779       client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3780     } else {
3781       /* Found, if it is from global list we'll assure that we won't
3782          expire it now that the entry is on channel. */
3783       if (global)
3784         cache->expire = 0;
3785     }
3786
3787     silc_free(client_id);
3788
3789     if (!silc_server_client_on_channel(client, channel)) {
3790       /* Client was not on the channel, add it. */
3791       SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3792       chl->client = client;
3793       chl->mode = mode;
3794       chl->channel = channel;
3795       silc_hash_table_add(channel->user_list, chl->client, chl);
3796       silc_hash_table_add(client->channels, chl->channel, chl);
3797     }
3798   }
3799 }
3800
3801 /* Lookups route to the client indicated by the `id_data'. The connection
3802    object and internal data object is returned. Returns NULL if route
3803    could not be found to the client. If the `client_id' is specified then
3804    it is used and the `id_data' is ignored. */
3805
3806 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3807                                                   unsigned char *id_data,
3808                                                   uint32 id_len,
3809                                                   SilcClientID *client_id,
3810                                                   SilcIDListData *idata)
3811 {
3812   SilcClientID *id;
3813   SilcClientEntry client;
3814
3815   SILC_LOG_DEBUG(("Start"));
3816
3817   /* Decode destination Client ID */
3818   if (!client_id) {
3819     id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3820     if (!id) {
3821       SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3822       return NULL;
3823     }
3824   } else {
3825     id = silc_id_dup(client_id, SILC_ID_CLIENT);
3826   }
3827
3828   /* If the destination belongs to our server we don't have to route
3829      the packet anywhere but to send it to the local destination. */
3830   client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
3831   if (client) {
3832     silc_free(id);
3833
3834     /* If we are router and the client has router then the client is in
3835        our cell but not directly connected to us. */
3836     if (server->server_type == SILC_ROUTER && client->router) {
3837       /* We are of course in this case the client's router thus the route
3838          to the client is the server who owns the client. So, we will send
3839          the packet to that server. */
3840       if (idata)
3841         *idata = (SilcIDListData)client->router;
3842       return client->router->connection;
3843     }
3844
3845     /* Seems that client really is directly connected to us */
3846     if (idata)
3847       *idata = (SilcIDListData)client;
3848     return client->connection;
3849   }
3850
3851   /* Destination belongs to someone not in this server. If we are normal
3852      server our action is to send the packet to our router. */
3853   if (server->server_type != SILC_ROUTER && !server->standalone) {
3854     silc_free(id);
3855     if (idata)
3856       *idata = (SilcIDListData)server->router;
3857     return server->router->connection;
3858   }
3859
3860   /* We are router and we will perform route lookup for the destination 
3861      and send the packet to fastest route. */
3862   if (server->server_type == SILC_ROUTER && !server->standalone) {
3863     /* Check first that the ID is valid */
3864     client = silc_idlist_find_client_by_id(server->global_list, id, 
3865                                            TRUE, NULL);
3866     if (client) {
3867       SilcSocketConnection dst_sock;
3868
3869       dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
3870
3871       silc_free(id);
3872       if (idata)
3873         *idata = (SilcIDListData)dst_sock->user_data;
3874       return dst_sock;
3875     }
3876   }
3877
3878   silc_free(id);
3879   return NULL;
3880 }
3881
3882 /* Encodes and returns channel list of channels the `client' has joined.
3883    Secret channels are not put to the list. */
3884
3885 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
3886                                                SilcClientEntry client)
3887 {
3888   SilcBuffer buffer = NULL;
3889   SilcChannelEntry channel;
3890   SilcChannelClientEntry chl;
3891   SilcHashTableList htl;
3892   unsigned char *cid;
3893   uint32 id_len;
3894   uint16 name_len;
3895   int len;
3896
3897   silc_hash_table_list(client->channels, &htl);
3898   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3899     channel = chl->channel;
3900
3901     if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
3902         channel->mode & SILC_CHANNEL_MODE_PRIVATE)
3903       continue;
3904
3905     cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3906     id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3907     name_len = strlen(channel->channel_name);
3908     
3909     len = 4 + name_len + id_len + 4;
3910     buffer = silc_buffer_realloc(buffer, 
3911                                  (buffer ? (buffer)->truelen + len : len));
3912     silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
3913     silc_buffer_format(buffer,
3914                        SILC_STR_UI_SHORT(name_len),
3915                        SILC_STR_UI_XNSTRING(channel->channel_name, 
3916                                             name_len),
3917                        SILC_STR_UI_SHORT(id_len),
3918                        SILC_STR_UI_XNSTRING(cid, id_len),
3919                        SILC_STR_UI_INT(chl->mode), /* Client's mode */
3920                        SILC_STR_END);
3921     silc_buffer_pull(buffer, len);
3922     silc_free(cid);
3923   }
3924
3925   if (buffer)
3926     silc_buffer_push(buffer, buffer->data - buffer->head);
3927
3928   return buffer;
3929 }
3930
3931 /* Finds client entry by Client ID and if it is not found then resolves
3932    it using WHOIS command. */
3933
3934 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
3935                                                SilcClientID *client_id,
3936                                                bool *resolved)
3937 {
3938   SilcClientEntry client;
3939
3940   if (resolved)
3941     *resolved = FALSE;
3942
3943   client = silc_idlist_find_client_by_id(server->local_list, client_id,
3944                                          TRUE, NULL);
3945   if (!client) {
3946     client = silc_idlist_find_client_by_id(server->global_list, 
3947                                            client_id, TRUE, NULL);
3948     if (!client && server->server_type == SILC_ROUTER)
3949       return NULL;
3950   }
3951
3952   if (!client && server->standalone)
3953     return NULL;
3954
3955   if (!client || !client->nickname || !client->username) {
3956     SilcBuffer buffer, idp;
3957
3958     client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
3959     client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
3960     client->resolve_cmd_ident = ++server->cmd_ident;
3961
3962     idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3963     buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
3964                                             server->cmd_ident, 1,
3965                                             3, idp->data, idp->len);
3966     silc_server_packet_send(server, client ? client->router->connection :
3967                             server->router->connection,
3968                             SILC_PACKET_COMMAND, 0,
3969                             buffer->data, buffer->len, FALSE);
3970     silc_buffer_free(idp);
3971     silc_buffer_free(buffer);
3972
3973     if (resolved)
3974       *resolved = TRUE;
3975
3976     return NULL;
3977   }
3978
3979   return client;
3980 }
3981
3982 /* A timeout callback for the re-key. We will be the initiator of the
3983    re-key protocol. */
3984
3985 SILC_TASK_CALLBACK(silc_server_rekey_callback)
3986 {
3987   SilcSocketConnection sock = (SilcSocketConnection)context;
3988   SilcIDListData idata = (SilcIDListData)sock->user_data;
3989   SilcServer server = (SilcServer)idata->rekey->context;
3990   SilcProtocol protocol;
3991   SilcServerRekeyInternalContext *proto_ctx;
3992
3993   SILC_LOG_DEBUG(("Start"));
3994
3995   /* Allocate internal protocol context. This is sent as context
3996      to the protocol. */
3997   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
3998   proto_ctx->server = (void *)server;
3999   proto_ctx->sock = sock;
4000   proto_ctx->responder = FALSE;
4001   proto_ctx->pfs = idata->rekey->pfs;
4002       
4003   /* Perform rekey protocol. Will call the final callback after the
4004      protocol is over. */
4005   silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY, 
4006                       &protocol, proto_ctx, silc_server_rekey_final);
4007   sock->protocol = protocol;
4008       
4009   /* Run the protocol */
4010   silc_protocol_execute(protocol, server->schedule, 0, 0);
4011
4012   /* Re-register re-key timeout */
4013   silc_schedule_task_add(server->schedule, sock->sock, 
4014                          silc_server_rekey_callback,
4015                          context, idata->rekey->timeout, 0,
4016                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4017 }
4018
4019 /* The final callback for the REKEY protocol. This will actually take the
4020    new key material into use. */
4021
4022 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4023 {
4024   SilcProtocol protocol = (SilcProtocol)context;
4025   SilcServerRekeyInternalContext *ctx =
4026     (SilcServerRekeyInternalContext *)protocol->context;
4027   SilcServer server = (SilcServer)ctx->server;
4028   SilcSocketConnection sock = ctx->sock;
4029
4030   SILC_LOG_DEBUG(("Start"));
4031
4032   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4033       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4034     /* Error occured during protocol */
4035     SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4036     silc_protocol_cancel(protocol, server->schedule);
4037     silc_protocol_free(protocol);
4038     sock->protocol = NULL;
4039     if (ctx->packet)
4040       silc_packet_context_free(ctx->packet);
4041     if (ctx->ske)
4042       silc_ske_free(ctx->ske);
4043     silc_free(ctx);
4044     return;
4045   }
4046
4047   /* Purge the outgoing data queue to assure that all rekey packets really
4048      go to the network before we quit the protocol. */
4049   silc_server_packet_queue_purge(server, sock);
4050
4051   /* Cleanup */
4052   silc_protocol_free(protocol);
4053   sock->protocol = NULL;
4054   if (ctx->packet)
4055     silc_packet_context_free(ctx->packet);
4056   if (ctx->ske)
4057     silc_ske_free(ctx->ske);
4058   silc_free(ctx);
4059 }