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