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