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