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