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->ske->prop->group,
748                                         ctx->responder)) {
749     silc_protocol_free(protocol);
750     sock->protocol = NULL;
751     silc_ske_free_key_material(ctx->keymat);
752     if (ctx->packet)
753       silc_packet_context_free(ctx->packet);
754     if (ctx->ske)
755       silc_ske_free(ctx->ske);
756     if (ctx->dest_id)
757       silc_free(ctx->dest_id);
758     silc_free(ctx);
759     silc_task_unregister_by_callback(server->timeout_queue,
760                                      silc_server_failure_callback);
761     silc_server_disconnect_remote(server, sock, "Server closed connection: "
762                                   "Key exchange failed");
763     return;
764   }    
765   silc_ske_free_key_material(ctx->keymat);
766
767   /* Allocate internal context for the authentication protocol. This
768      is sent as context for the protocol. */
769   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
770   proto_ctx->server = (void *)server;
771   proto_ctx->context = (void *)sconn;
772   proto_ctx->sock = sock;
773   proto_ctx->ske = ctx->ske;       /* Save SKE object from previous protocol */
774   proto_ctx->dest_id_type = ctx->dest_id_type;
775   proto_ctx->dest_id = ctx->dest_id;
776
777   /* Resolve the authentication method used in this connection. Check if 
778      we find a match from user configured connections */
779   conn = silc_server_config_find_router_conn(server->config,
780                                              sock->hostname,
781                                              sock->port);
782   if (conn) {
783     /* Match found. Use the configured authentication method */
784     proto_ctx->auth_meth = conn->auth_meth;
785     if (conn->auth_data) {
786       proto_ctx->auth_data = strdup(conn->auth_data);
787       proto_ctx->auth_data_len = strlen(conn->auth_data);
788     }
789   } else {
790     SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
791                     sock->hostname, sock->ip, sock->port));
792     silc_protocol_free(protocol);
793     sock->protocol = NULL;
794     if (ctx->packet)
795       silc_packet_context_free(ctx->packet);
796     if (ctx->ske)
797       silc_ske_free(ctx->ske);
798     if (ctx->dest_id)
799       silc_free(ctx->dest_id);
800     silc_free(ctx);
801     silc_task_unregister_by_callback(server->timeout_queue,
802                                      silc_server_failure_callback);
803     silc_server_disconnect_remote(server, sock, "Server closed connection: "
804                                   "Key exchange failed");
805     return;
806   }
807
808   /* Free old protocol as it is finished now */
809   silc_protocol_free(protocol);
810   if (ctx->packet)
811     silc_packet_context_free(ctx->packet);
812   silc_free(ctx);
813   sock->protocol = NULL;
814
815   /* Allocate the authentication protocol. This is allocated here
816      but we won't start it yet. We will be receiving party of this
817      protocol thus we will wait that connecting party will make
818      their first move. */
819   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH, 
820                       &sock->protocol, proto_ctx, 
821                       silc_server_connect_to_router_final);
822
823   /* Register timeout task. If the protocol is not executed inside
824      this timelimit the connection will be terminated. Currently
825      this is 15 seconds and is hard coded limit (XXX). */
826   proto_ctx->timeout_task = 
827     silc_task_register(server->timeout_queue, sock->sock, 
828                        silc_server_timeout_remote,
829                        (void *)server, 15, 0,
830                        SILC_TASK_TIMEOUT,
831                        SILC_TASK_PRI_LOW);
832
833   /* Run the protocol */
834   sock->protocol->execute(server->timeout_queue, 0, 
835                           sock->protocol, sock->sock, 0, 0);
836 }
837
838 /* Finalizes the connection to router. Registers a server task to the
839    queue so that we can accept new connections. */
840
841 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
842 {
843   SilcProtocol protocol = (SilcProtocol)context;
844   SilcServerConnAuthInternalContext *ctx = 
845     (SilcServerConnAuthInternalContext *)protocol->context;
846   SilcServer server = (SilcServer)ctx->server;
847   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
848   SilcSocketConnection sock = ctx->sock;
849   SilcServerEntry id_entry;
850   SilcBuffer packet;
851   SilcServerHBContext hb_context;
852   unsigned char *id_string;
853   SilcIDListData idata;
854
855   SILC_LOG_DEBUG(("Start"));
856
857   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
858       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
859     /* Error occured during protocol */
860     if (ctx->dest_id)
861       silc_free(ctx->dest_id);
862     silc_server_disconnect_remote(server, sock, "Server closed connection: "
863                                   "Authentication failed");
864     goto out;
865   }
866
867   /* Add a task to the queue. This task receives new connections to the 
868      server. This task remains on the queue until the end of the program. */
869   if (!server->listenning) {
870     silc_task_register(server->io_queue, server->sock, 
871                        silc_server_accept_new_connection,
872                        (void *)server, 0, 0, 
873                        SILC_TASK_FD,
874                        SILC_TASK_PRI_NORMAL);
875     server->listenning = TRUE;
876   }
877
878   /* Send NEW_SERVER packet to the router. We will become registered
879      to the SILC network after sending this packet. */
880   id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
881   packet = silc_buffer_alloc(2 + 2 + SILC_ID_SERVER_LEN + 
882                              strlen(server->server_name));
883   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
884   silc_buffer_format(packet,
885                      SILC_STR_UI_SHORT(SILC_ID_SERVER_LEN),
886                      SILC_STR_UI_XNSTRING(id_string, SILC_ID_SERVER_LEN),
887                      SILC_STR_UI_SHORT(strlen(server->server_name)),
888                      SILC_STR_UI_XNSTRING(server->server_name,
889                                           strlen(server->server_name)),
890                      SILC_STR_END);
891
892   /* Send the packet */
893   silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
894                           packet->data, packet->len, TRUE);
895   silc_buffer_free(packet);
896   silc_free(id_string);
897
898   SILC_LOG_DEBUG(("Connected to router %s", sock->hostname));
899
900   /* Add the connected router to local server list */
901   server->standalone = FALSE;
902   id_entry = silc_idlist_add_server(server->local_list, sock->hostname,
903                                     SILC_ROUTER, ctx->dest_id, NULL, sock);
904   if (!id_entry) {
905     if (ctx->dest_id)
906       silc_free(ctx->dest_id);
907     silc_server_disconnect_remote(server, sock, "Server closed connection: "
908                                   "Authentication failed");
909     goto out;
910   }
911
912   silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
913   silc_free(sock->user_data);
914   sock->user_data = (void *)id_entry;
915   sock->type = SILC_SOCKET_TYPE_ROUTER;
916   server->id_entry->router = id_entry;
917   server->router = id_entry;
918   idata = (SilcIDListData)sock->user_data;
919   idata->registered = TRUE;
920
921   /* Perform keepalive. The `hb_context' will be freed automatically
922      when finally calling the silc_socket_free function. XXX hardcoded 
923      timeout!! */
924   hb_context = silc_calloc(1, sizeof(*hb_context));
925   hb_context->server = server;
926   silc_socket_set_heartbeat(sock, 600, hb_context,
927                             silc_server_perform_heartbeat,
928                             server->timeout_queue);
929
930   /* Register re-key timeout */
931   idata->rekey->timeout = 3600; /* XXX hardcoded */
932   idata->rekey->context = (void *)server;
933   silc_task_register(server->timeout_queue, sock->sock, 
934                      silc_server_rekey_callback,
935                      (void *)sock, idata->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->ske->prop->group,
1102                                         ctx->responder)) {
1103     silc_protocol_free(protocol);
1104     sock->protocol = NULL;
1105     silc_ske_free_key_material(ctx->keymat);
1106     if (ctx->packet)
1107       silc_packet_context_free(ctx->packet);
1108     if (ctx->ske)
1109       silc_ske_free(ctx->ske);
1110     if (ctx->dest_id)
1111       silc_free(ctx->dest_id);
1112     silc_free(ctx);
1113     silc_task_unregister_by_callback(server->timeout_queue,
1114                                      silc_server_failure_callback);
1115     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1116                                   "Key exchange failed");
1117     server->stat.auth_failures++;
1118     return;
1119   }    
1120   silc_ske_free_key_material(ctx->keymat);
1121
1122   /* Allocate internal context for the authentication protocol. This
1123      is sent as context for the protocol. */
1124   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1125   proto_ctx->server = (void *)server;
1126   proto_ctx->sock = sock;
1127   proto_ctx->ske = ctx->ske;    /* Save SKE object from previous protocol */
1128   proto_ctx->responder = TRUE;
1129   proto_ctx->dest_id_type = ctx->dest_id_type;
1130   proto_ctx->dest_id = ctx->dest_id;
1131
1132   /* Free old protocol as it is finished now */
1133   silc_protocol_free(protocol);
1134   if (ctx->packet)
1135     silc_packet_context_free(ctx->packet);
1136   silc_free(ctx);
1137   sock->protocol = NULL;
1138
1139   /* Allocate the authentication protocol. This is allocated here
1140      but we won't start it yet. We will be receiving party of this
1141      protocol thus we will wait that connecting party will make
1142      their first move. */
1143   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH, 
1144                       &sock->protocol, proto_ctx, 
1145                       silc_server_accept_new_connection_final);
1146
1147   /* Register timeout task. If the protocol is not executed inside
1148      this timelimit the connection will be terminated. Currently
1149      this is 60 seconds and is hard coded limit (XXX). */
1150   proto_ctx->timeout_task = 
1151     silc_task_register(server->timeout_queue, sock->sock, 
1152                        silc_server_timeout_remote,
1153                        (void *)server, 60, 0,
1154                        SILC_TASK_TIMEOUT,
1155                        SILC_TASK_PRI_LOW);
1156 }
1157
1158 /* Final part of accepting new connection. The connection has now
1159    been authenticated and keys has been exchanged. We also know whether
1160    this is client or server connection. */
1161
1162 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1163 {
1164   SilcProtocol protocol = (SilcProtocol)context;
1165   SilcServerConnAuthInternalContext *ctx = 
1166     (SilcServerConnAuthInternalContext *)protocol->context;
1167   SilcServer server = (SilcServer)ctx->server;
1168   SilcSocketConnection sock = ctx->sock;
1169   SilcServerHBContext hb_context;
1170   void *id_entry = NULL;
1171
1172   SILC_LOG_DEBUG(("Start"));
1173
1174   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1175       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1176     /* Error occured during protocol */
1177     silc_protocol_free(protocol);
1178     sock->protocol = NULL;
1179     if (ctx->packet)
1180       silc_packet_context_free(ctx->packet);
1181     if (ctx->ske)
1182       silc_ske_free(ctx->ske);
1183     if (ctx->dest_id)
1184       silc_free(ctx->dest_id);
1185     silc_free(ctx);
1186     if (sock)
1187       sock->protocol = NULL;
1188     silc_task_unregister_by_callback(server->timeout_queue,
1189                                      silc_server_failure_callback);
1190     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1191                                   "Authentication failed");
1192     server->stat.auth_failures++;
1193     return;
1194   }
1195
1196   sock->type = ctx->conn_type;
1197   switch(sock->type) {
1198   case SILC_SOCKET_TYPE_CLIENT:
1199     {
1200       SilcClientEntry client;
1201
1202       SILC_LOG_DEBUG(("Remote host is client"));
1203       SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
1204                      sock->ip));
1205
1206       /* Add the client to the client ID cache. The nickname and Client ID
1207          and other information is created after we have received NEW_CLIENT
1208          packet from client. */
1209       client = silc_idlist_add_client(server->local_list, 
1210                                       NULL, 0, NULL, NULL, NULL, NULL, sock);
1211       if (!client) {
1212         SILC_LOG_ERROR(("Could not add new client to cache"));
1213         silc_free(sock->user_data);
1214         break;
1215       }
1216
1217       /* Statistics */
1218       server->stat.my_clients++;
1219       server->stat.clients++;
1220       if (server->server_type == SILC_ROUTER)
1221         server->stat.cell_clients++;
1222
1223       id_entry = (void *)client;
1224       break;
1225     }
1226   case SILC_SOCKET_TYPE_SERVER:
1227   case SILC_SOCKET_TYPE_ROUTER:
1228     {
1229       SilcServerEntry new_server;
1230
1231       SILC_LOG_DEBUG(("Remote host is %s", 
1232                       sock->type == SILC_SOCKET_TYPE_SERVER ? 
1233                       "server" : "router"));
1234       SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
1235                      sock->ip, sock->type == SILC_SOCKET_TYPE_SERVER ? 
1236                      "server" : "router"));
1237
1238       /* Add the server into server cache. The server name and Server ID
1239          is updated after we have received NEW_SERVER packet from the
1240          server. We mark ourselves as router for this server if we really
1241          are router. */
1242       new_server = 
1243         silc_idlist_add_server(server->local_list, NULL,
1244                                sock->type == SILC_SOCKET_TYPE_SERVER ?
1245                                SILC_SERVER : SILC_ROUTER, NULL, 
1246                                sock->type == SILC_SOCKET_TYPE_SERVER ?
1247                                server->id_entry : NULL, sock);
1248       if (!new_server) {
1249         SILC_LOG_ERROR(("Could not add new server to cache"));
1250         silc_free(sock->user_data);
1251         break;
1252       }
1253
1254       /* Statistics */
1255       if (sock->type == SILC_SOCKET_TYPE_SERVER)
1256         server->stat.my_servers++;
1257       else
1258         server->stat.my_routers++;
1259       server->stat.servers++;
1260
1261       id_entry = (void *)new_server;
1262       
1263       /* There is connection to other server now, if it is router then
1264          we will have connection to outside world.  If we are router but
1265          normal server connected to us then we will remain standalone,
1266          if we are standlone. */
1267       if (server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER) {
1268         SILC_LOG_DEBUG(("We are not standalone server anymore"));
1269         server->standalone = FALSE;
1270         if (!server->id_entry->router) {
1271           server->id_entry->router = id_entry;
1272           server->router = id_entry;
1273         }
1274       }
1275       break;
1276     }
1277   default:
1278     break;
1279   }
1280
1281   /* Add the common data structure to the ID entry. */
1282   if (id_entry)
1283     silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1284       
1285   /* Add to sockets internal pointer for fast referencing */
1286   silc_free(sock->user_data);
1287   sock->user_data = id_entry;
1288
1289   /* Connection has been fully established now. Everything is ok. */
1290   SILC_LOG_DEBUG(("New connection authenticated"));
1291
1292   /* Perform keepalive. The `hb_context' will be freed automatically
1293      when finally calling the silc_socket_free function. XXX hardcoded 
1294      timeout!! */
1295   hb_context = silc_calloc(1, sizeof(*hb_context));
1296   hb_context->server = server;
1297   silc_socket_set_heartbeat(sock, 600, hb_context,
1298                             silc_server_perform_heartbeat,
1299                             server->timeout_queue);
1300
1301   silc_task_unregister_by_callback(server->timeout_queue,
1302                                    silc_server_failure_callback);
1303   silc_protocol_free(protocol);
1304   if (ctx->packet)
1305     silc_packet_context_free(ctx->packet);
1306   if (ctx->ske)
1307     silc_ske_free(ctx->ske);
1308   if (ctx->dest_id)
1309     silc_free(ctx->dest_id);
1310   silc_free(ctx);
1311   sock->protocol = NULL;
1312 }
1313
1314 /* This function is used to read packets from network and send packets to
1315    network. This is usually a generic task. */
1316
1317 SILC_TASK_CALLBACK(silc_server_packet_process)
1318 {
1319   SilcServer server = (SilcServer)context;
1320   SilcSocketConnection sock = server->sockets[fd];
1321   SilcIDListData idata;
1322   SilcCipher cipher = NULL;
1323   SilcHmac hmac = NULL;
1324   int ret;
1325
1326   if (!sock)
1327     return;
1328
1329   SILC_LOG_DEBUG(("Processing packet"));
1330
1331   /* Packet sending */
1332
1333   if (type == SILC_TASK_WRITE) {
1334     /* Do not send data to disconnected connection */
1335     if (SILC_IS_DISCONNECTED(sock))
1336       return;
1337
1338     server->stat.packets_sent++;
1339
1340     if (sock->outbuf->data - sock->outbuf->head)
1341      silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1342
1343     ret = silc_server_packet_send_real(server, sock, TRUE);
1344
1345     /* If returned -2 could not write to connection now, will do
1346        it later. */
1347     if (ret == -2)
1348       return;
1349
1350     if (ret == -1)
1351       return;
1352     
1353     /* The packet has been sent and now it is time to set the connection
1354        back to only for input. When there is again some outgoing data 
1355        available for this connection it will be set for output as well. 
1356        This call clears the output setting and sets it only for input. */
1357     SILC_SET_CONNECTION_FOR_INPUT(fd);
1358     SILC_UNSET_OUTBUF_PENDING(sock);
1359
1360     silc_buffer_clear(sock->outbuf);
1361     return;
1362   }
1363
1364   /* Packet receiving */
1365
1366   /* Read some data from connection */
1367   ret = silc_packet_receive(sock);
1368   if (ret < 0)
1369     return;
1370     
1371   /* EOF */
1372   if (ret == 0) {
1373     SILC_LOG_DEBUG(("Read EOF"));
1374       
1375     /* If connection is disconnecting already we will finally
1376        close the connection */
1377     if (SILC_IS_DISCONNECTING(sock)) {
1378       if (sock->user_data)
1379         silc_server_free_sock_user_data(server, sock);
1380       silc_server_close_connection(server, sock);
1381       return;
1382     }
1383       
1384     SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1385     SILC_SET_DISCONNECTING(sock);
1386
1387     /* If the closed connection was our primary router connection the
1388        start re-connecting phase. */
1389     if (!server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER && 
1390         sock == server->router->connection)
1391       silc_task_register(server->timeout_queue, 0, 
1392                          silc_server_connect_to_router,
1393                          context, 1, 0,
1394                          SILC_TASK_TIMEOUT,
1395                          SILC_TASK_PRI_NORMAL);
1396
1397     if (sock->user_data)
1398       silc_server_free_sock_user_data(server, sock);
1399     silc_server_close_connection(server, sock);
1400     return;
1401   }
1402
1403   /* If connection is disconnecting or disconnected we will ignore
1404      what we read. */
1405   if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1406     SILC_LOG_DEBUG(("Ignoring read data from disonnected connection"));
1407     return;
1408   }
1409
1410   server->stat.packets_received++;
1411
1412   /* Get keys and stuff from ID entry */
1413   idata = (SilcIDListData)sock->user_data;
1414   if (idata) {
1415     idata->last_receive = time(NULL);
1416     cipher = idata->receive_key;
1417     hmac = idata->hmac;
1418   }
1419  
1420   /* Process the packet. This will call the parser that will then
1421      decrypt and parse the packet. */
1422   silc_packet_receive_process(sock, cipher, hmac, silc_server_packet_parse, 
1423                               server);
1424 }
1425
1426 /* Callback function that the silc_packet_decrypt will call to make the
1427    decision whether the packet is normal or special packet. We will 
1428    return TRUE if it is normal and FALSE if it is special */
1429
1430 static int silc_server_packet_decrypt_check(SilcPacketType packet_type,
1431                                             SilcBuffer buffer,
1432                                             SilcPacketContext *packet,
1433                                             void *context)
1434 {
1435   SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1436   SilcServer server = (SilcServer)parse_ctx->context;
1437
1438   /* Packet is normal packet, if: 
1439
1440      1) packet is private message packet and does not have private key set
1441      2) is other packet than channel message packet
1442      3) is channel message packet and remote is router and we are router 
1443
1444      all other packets are special packets 
1445   */
1446
1447   if (packet_type == SILC_PACKET_PRIVATE_MESSAGE &&
1448       (buffer->data[2] & SILC_PACKET_FLAG_PRIVMSG_KEY))
1449     return FALSE;
1450
1451   if (packet_type != SILC_PACKET_CHANNEL_MESSAGE || 
1452       (packet_type == SILC_PACKET_CHANNEL_MESSAGE &&
1453        parse_ctx->sock->type == SILC_SOCKET_TYPE_ROUTER &&
1454        server->server_type == SILC_ROUTER))
1455     return TRUE;
1456
1457   return FALSE;
1458 }
1459
1460 /* Parses whole packet, received earlier. */
1461
1462 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1463 {
1464   SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1465   SilcServer server = (SilcServer)parse_ctx->context;
1466   SilcSocketConnection sock = parse_ctx->sock;
1467   SilcPacketContext *packet = parse_ctx->packet;
1468   int ret;
1469
1470   SILC_LOG_DEBUG(("Start"));
1471
1472   /* Decrypt the received packet */
1473   ret = silc_packet_decrypt(parse_ctx->cipher, parse_ctx->hmac, 
1474                             packet->buffer, packet,
1475                             silc_server_packet_decrypt_check, parse_ctx);
1476   if (ret < 0)
1477     goto out;
1478
1479   if (ret == 0) {
1480     /* Parse the packet. Packet type is returned. */
1481     ret = silc_packet_parse(packet);
1482   } else {
1483     /* Parse the packet header in special way as this is "special"
1484        packet type. */
1485     ret = silc_packet_parse_special(packet);
1486   }
1487
1488   if (ret == SILC_PACKET_NONE)
1489     goto out;
1490
1491   /* Check that the the current client ID is same as in the client's packet. */
1492   if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1493     SilcClientEntry client = (SilcClientEntry)sock->user_data;
1494     if (client && client->id) {
1495       void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1496                                 packet->src_id_type);
1497       if (SILC_ID_CLIENT_COMPARE(client->id, id)) {
1498         silc_free(id);
1499         goto out;
1500       }
1501       silc_free(id);
1502     }
1503   }
1504
1505   if (server->server_type == SILC_ROUTER) {
1506     /* Route the packet if it is not destined to us. Other ID types but
1507        server are handled separately after processing them. */
1508     if (packet->dst_id_type == SILC_ID_SERVER && 
1509         sock->type != SILC_SOCKET_TYPE_CLIENT &&
1510         SILC_ID_SERVER_COMPARE(packet->dst_id, server->id_string)) {
1511       
1512       /* Route the packet to fastest route for the destination ID */
1513       void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len, 
1514                                 packet->dst_id_type);
1515       if (!id)
1516         goto out;
1517       silc_server_packet_route(server,
1518                                silc_server_route_get(server, id,
1519                                                      packet->dst_id_type),
1520                                packet);
1521       silc_free(id);
1522       goto out;
1523     }
1524     
1525     /* Broadcast packet if it is marked as broadcast packet and it is
1526        originated from router and we are router. */
1527     if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1528         packet->flags & SILC_PACKET_FLAG_BROADCAST) {
1529       silc_server_packet_broadcast(server, server->router->connection, packet);
1530     }
1531   }
1532
1533   /* Parse the incoming packet type */
1534   silc_server_packet_parse_type(server, sock, packet);
1535
1536  out:
1537   /*  silc_buffer_clear(sock->inbuf); */
1538   silc_packet_context_free(packet);
1539   silc_free(parse_ctx);
1540 }
1541
1542 /* Parser callback called by silc_packet_receive_process. This merely
1543    registers timeout that will handle the actual parsing when appropriate. */
1544
1545 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1546 {
1547   SilcServer server = (SilcServer)parser_context->context;
1548   SilcSocketConnection sock = parser_context->sock;
1549
1550   switch (sock->type) {
1551   case SILC_SOCKET_TYPE_CLIENT:
1552   case SILC_SOCKET_TYPE_UNKNOWN:
1553     /* Parse the packet with timeout */
1554     silc_task_register(server->timeout_queue, sock->sock,
1555                        silc_server_packet_parse_real,
1556                        (void *)parser_context, 0, 100000,
1557                        SILC_TASK_TIMEOUT,
1558                        SILC_TASK_PRI_NORMAL);
1559     break;
1560   case SILC_SOCKET_TYPE_SERVER:
1561   case SILC_SOCKET_TYPE_ROUTER:
1562     /* Packets from servers are parsed as soon as possible */
1563     silc_task_register(server->timeout_queue, sock->sock,
1564                        silc_server_packet_parse_real,
1565                        (void *)parser_context, 0, 1,
1566                        SILC_TASK_TIMEOUT,
1567                        SILC_TASK_PRI_NORMAL);
1568     break;
1569   default:
1570     return;
1571   }
1572 }
1573
1574 /* Parses the packet type and calls what ever routines the packet type
1575    requires. This is done for all incoming packets. */
1576
1577 void silc_server_packet_parse_type(SilcServer server, 
1578                                    SilcSocketConnection sock,
1579                                    SilcPacketContext *packet)
1580 {
1581   SilcPacketType type = packet->type;
1582
1583   SILC_LOG_DEBUG(("Parsing packet type %d", type));
1584
1585   /* Parse the packet type */
1586   switch(type) {
1587   case SILC_PACKET_DISCONNECT:
1588     SILC_LOG_DEBUG(("Disconnect packet"));
1589     if (packet->flags & SILC_PACKET_FLAG_LIST)
1590       break;
1591     break;
1592
1593   case SILC_PACKET_SUCCESS:
1594     /*
1595      * Success received for something. For now we can have only
1596      * one protocol for connection executing at once hence this
1597      * success message is for whatever protocol is executing currently.
1598      */
1599     SILC_LOG_DEBUG(("Success packet"));
1600     if (packet->flags & SILC_PACKET_FLAG_LIST)
1601       break;
1602     if (sock->protocol) {
1603       sock->protocol->execute(server->timeout_queue, 0,
1604                               sock->protocol, sock->sock, 0, 0);
1605     }
1606     break;
1607
1608   case SILC_PACKET_FAILURE:
1609     /*
1610      * Failure received for something. For now we can have only
1611      * one protocol for connection executing at once hence this
1612      * failure message is for whatever protocol is executing currently.
1613      */
1614     SILC_LOG_DEBUG(("Failure packet"));
1615     if (packet->flags & SILC_PACKET_FLAG_LIST)
1616       break;
1617     if (sock->protocol) {
1618       SilcServerFailureContext f;
1619       f = silc_calloc(1, sizeof(*f));
1620       f->server = server;
1621       f->sock = sock;
1622       
1623       /* We will wait 5 seconds to process this failure packet */
1624       silc_task_register(server->timeout_queue, sock->sock,
1625                          silc_server_failure_callback, (void *)f, 5, 0,
1626                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1627     }
1628     break;
1629
1630   case SILC_PACKET_REJECT:
1631     SILC_LOG_DEBUG(("Reject packet"));
1632     if (packet->flags & SILC_PACKET_FLAG_LIST)
1633       break;
1634     return;
1635     break;
1636
1637   case SILC_PACKET_NOTIFY:
1638     /*
1639      * Received notify packet. Server can receive notify packets from
1640      * router. Server then relays the notify messages to clients if needed.
1641      */
1642     SILC_LOG_DEBUG(("Notify packet"));
1643     if (packet->flags & SILC_PACKET_FLAG_LIST)
1644       silc_server_notify_list(server, sock, packet);
1645     else
1646       silc_server_notify(server, sock, packet);
1647     break;
1648
1649     /* 
1650      * Channel packets
1651      */
1652   case SILC_PACKET_CHANNEL_MESSAGE:
1653     /*
1654      * Received channel message. Channel messages are special packets
1655      * (although probably most common ones) thus they are handled
1656      * specially.
1657      */
1658     SILC_LOG_DEBUG(("Channel Message packet"));
1659     if (packet->flags & SILC_PACKET_FLAG_LIST)
1660       break;
1661     silc_server_channel_message(server, sock, packet);
1662     break;
1663
1664   case SILC_PACKET_CHANNEL_KEY:
1665     /*
1666      * Received key for channel. As channels are created by the router
1667      * the keys are as well. We will distribute the key to all of our
1668      * locally connected clients on the particular channel. Router
1669      * never receives this channel and thus is ignored.
1670      */
1671     SILC_LOG_DEBUG(("Channel Key packet"));
1672     if (packet->flags & SILC_PACKET_FLAG_LIST)
1673       break;
1674     silc_server_channel_key(server, sock, packet);
1675     break;
1676
1677     /*
1678      * Command packets
1679      */
1680   case SILC_PACKET_COMMAND:
1681     /*
1682      * Recived command. Processes the command request and allocates the
1683      * command context and calls the command.
1684      */
1685     SILC_LOG_DEBUG(("Command packet"));
1686     if (packet->flags & SILC_PACKET_FLAG_LIST)
1687       break;
1688     silc_server_command_process(server, sock, packet);
1689     break;
1690
1691   case SILC_PACKET_COMMAND_REPLY:
1692     /*
1693      * Received command reply packet. Received command reply to command. It
1694      * may be reply to command sent by us or reply to command sent by client
1695      * that we've routed further.
1696      */
1697     SILC_LOG_DEBUG(("Command Reply packet"));
1698     if (packet->flags & SILC_PACKET_FLAG_LIST)
1699       break;
1700     silc_server_command_reply(server, sock, packet);
1701     break;
1702
1703     /*
1704      * Private Message packets
1705      */
1706   case SILC_PACKET_PRIVATE_MESSAGE:
1707     /*
1708      * Received private message packet. The packet is coming from either
1709      * client or server.
1710      */
1711     SILC_LOG_DEBUG(("Private Message packet"));
1712     if (packet->flags & SILC_PACKET_FLAG_LIST)
1713       break;
1714     silc_server_private_message(server, sock, packet);
1715     break;
1716
1717   case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1718     /*
1719      * Private message key packet.
1720      */
1721     if (packet->flags & SILC_PACKET_FLAG_LIST)
1722       break;
1723     silc_server_private_message_key(server, sock, packet);
1724     break;
1725
1726     /*
1727      * Key Exchange protocol packets
1728      */
1729   case SILC_PACKET_KEY_EXCHANGE:
1730     SILC_LOG_DEBUG(("KE packet"));
1731     if (packet->flags & SILC_PACKET_FLAG_LIST)
1732       break;
1733
1734     if (sock->protocol && sock->protocol->protocol &&
1735         sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1736
1737       SilcServerKEInternalContext *proto_ctx = 
1738         (SilcServerKEInternalContext *)sock->protocol->context;
1739
1740       proto_ctx->packet = silc_packet_context_dup(packet);
1741
1742       /* Let the protocol handle the packet */
1743       sock->protocol->execute(server->timeout_queue, 0, 
1744                               sock->protocol, sock->sock, 0, 100000);
1745     } else {
1746       SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1747                       "protocol active, packet dropped."));
1748
1749       /* XXX Trigger KE protocol?? Rekey actually, maybe. */
1750     }
1751     break;
1752
1753   case SILC_PACKET_KEY_EXCHANGE_1:
1754     SILC_LOG_DEBUG(("KE 1 packet"));
1755     if (packet->flags & SILC_PACKET_FLAG_LIST)
1756       break;
1757
1758     if (sock->protocol && sock->protocol->protocol &&
1759         (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1760          sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
1761
1762       if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
1763         SilcServerRekeyInternalContext *proto_ctx = 
1764           (SilcServerRekeyInternalContext *)sock->protocol->context;
1765         
1766         if (proto_ctx->packet)
1767           silc_packet_context_free(proto_ctx->packet);
1768         
1769         proto_ctx->packet = silc_packet_context_dup(packet);
1770
1771         /* Let the protocol handle the packet */
1772         sock->protocol->execute(server->timeout_queue, 0, 
1773                                 sock->protocol, sock->sock, 0, 0);
1774       } else {
1775         SilcServerKEInternalContext *proto_ctx = 
1776           (SilcServerKEInternalContext *)sock->protocol->context;
1777         
1778         if (proto_ctx->packet)
1779           silc_packet_context_free(proto_ctx->packet);
1780         
1781         proto_ctx->packet = silc_packet_context_dup(packet);
1782         proto_ctx->dest_id_type = packet->src_id_type;
1783         proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1784                                             packet->src_id_type);
1785         if (!proto_ctx->dest_id)
1786           break;
1787
1788         /* Let the protocol handle the packet */
1789         sock->protocol->execute(server->timeout_queue, 0, 
1790                                 sock->protocol, sock->sock,
1791                                 0, 100000);
1792       }
1793     } else {
1794       SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1795                       "protocol active, packet dropped."));
1796     }
1797     break;
1798
1799   case SILC_PACKET_KEY_EXCHANGE_2:
1800     SILC_LOG_DEBUG(("KE 2 packet"));
1801     if (packet->flags & SILC_PACKET_FLAG_LIST)
1802       break;
1803
1804     if (sock->protocol && sock->protocol->protocol &&
1805         (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1806          sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
1807
1808       if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
1809         SilcServerRekeyInternalContext *proto_ctx = 
1810           (SilcServerRekeyInternalContext *)sock->protocol->context;
1811         
1812         if (proto_ctx->packet)
1813           silc_packet_context_free(proto_ctx->packet);
1814         
1815         proto_ctx->packet = silc_packet_context_dup(packet);
1816
1817         /* Let the protocol handle the packet */
1818         sock->protocol->execute(server->timeout_queue, 0, 
1819                                 sock->protocol, sock->sock, 0, 0);
1820       } else {
1821         SilcServerKEInternalContext *proto_ctx = 
1822           (SilcServerKEInternalContext *)sock->protocol->context;
1823         
1824         if (proto_ctx->packet)
1825           silc_packet_context_free(proto_ctx->packet);
1826         
1827         proto_ctx->packet = silc_packet_context_dup(packet);
1828         proto_ctx->dest_id_type = packet->src_id_type;
1829         proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1830                                             packet->src_id_type);
1831         if (!proto_ctx->dest_id)
1832           break;
1833
1834         /* Let the protocol handle the packet */
1835         sock->protocol->execute(server->timeout_queue, 0, 
1836                                 sock->protocol, sock->sock,
1837                                 0, 100000);
1838       }
1839     } else {
1840       SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1841                       "protocol active, packet dropped."));
1842     }
1843     break;
1844
1845   case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1846     /*
1847      * Connection authentication request packet. When we receive this packet
1848      * we will send to the other end information about our mandatory
1849      * authentication method for the connection. This packet maybe received
1850      * at any time. 
1851      */
1852     SILC_LOG_DEBUG(("Connection authentication request packet"));
1853     if (packet->flags & SILC_PACKET_FLAG_LIST)
1854       break;
1855     silc_server_connection_auth_request(server, sock, packet);
1856     break;
1857
1858     /*
1859      * Connection Authentication protocol packets
1860      */
1861   case SILC_PACKET_CONNECTION_AUTH:
1862     /* Start of the authentication protocol. We receive here the 
1863        authentication data and will verify it. */
1864     SILC_LOG_DEBUG(("Connection auth packet"));
1865     if (packet->flags & SILC_PACKET_FLAG_LIST)
1866       break;
1867
1868     if (sock->protocol && sock->protocol->protocol->type 
1869         == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1870
1871       SilcServerConnAuthInternalContext *proto_ctx = 
1872         (SilcServerConnAuthInternalContext *)sock->protocol->context;
1873
1874       proto_ctx->packet = silc_packet_context_dup(packet);
1875
1876       /* Let the protocol handle the packet */
1877       sock->protocol->execute(server->timeout_queue, 0, 
1878                               sock->protocol, sock->sock, 0, 0);
1879     } else {
1880       SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1881                       "protocol active, packet dropped."));
1882     }
1883     break;
1884
1885   case SILC_PACKET_NEW_ID:
1886     /*
1887      * Received New ID packet. This includes some new ID that has been
1888      * created. It may be for client, server or channel. This is the way
1889      * to distribute information about new registered entities in the
1890      * SILC network.
1891      */
1892     SILC_LOG_DEBUG(("New ID packet"));
1893     if (packet->flags & SILC_PACKET_FLAG_LIST)
1894       silc_server_new_id_list(server, sock, packet);
1895     else
1896       silc_server_new_id(server, sock, packet);
1897     break;
1898
1899   case SILC_PACKET_NEW_CLIENT:
1900     /*
1901      * Received new client packet. This includes client information that
1902      * we will use to create initial client ID. After creating new
1903      * ID we will send it to the client.
1904      */
1905     SILC_LOG_DEBUG(("New Client packet"));
1906     if (packet->flags & SILC_PACKET_FLAG_LIST)
1907       break;
1908     silc_server_new_client(server, sock, packet);
1909     break;
1910
1911   case SILC_PACKET_NEW_SERVER:
1912     /*
1913      * Received new server packet. This includes Server ID and some other
1914      * information that we may save. This is received after server has 
1915      * connected to us.
1916      */
1917     SILC_LOG_DEBUG(("New Server packet"));
1918     if (packet->flags & SILC_PACKET_FLAG_LIST)
1919       break;
1920     silc_server_new_server(server, sock, packet);
1921     break;
1922
1923   case SILC_PACKET_NEW_CHANNEL:
1924     /*
1925      * Received new channel packet. Information about new channel in the
1926      * network are distributed using this packet.
1927      */
1928     SILC_LOG_DEBUG(("New Channel packet"));
1929     if (packet->flags & SILC_PACKET_FLAG_LIST)
1930       silc_server_new_channel_list(server, sock, packet);
1931     else
1932       silc_server_new_channel(server, sock, packet);
1933     break;
1934
1935   case SILC_PACKET_HEARTBEAT:
1936     /*
1937      * Received heartbeat.
1938      */
1939     SILC_LOG_DEBUG(("Heartbeat packet"));
1940     if (packet->flags & SILC_PACKET_FLAG_LIST)
1941       break;
1942     break;
1943
1944   case SILC_PACKET_KEY_AGREEMENT:
1945     /*
1946      * Received heartbeat.
1947      */
1948     SILC_LOG_DEBUG(("Key agreement packet"));
1949     if (packet->flags & SILC_PACKET_FLAG_LIST)
1950       break;
1951     silc_server_key_agreement(server, sock, packet);
1952     break;
1953
1954   case SILC_PACKET_REKEY:
1955     /*
1956      * Received re-key packet. The sender wants to regenerate the session
1957      * keys.
1958      */
1959     SILC_LOG_DEBUG(("Re-key packet"));
1960     if (packet->flags & SILC_PACKET_FLAG_LIST)
1961       break;
1962     silc_server_rekey(server, sock, packet);
1963     break;
1964
1965   case SILC_PACKET_REKEY_DONE:
1966     /*
1967      * The re-key is done.
1968      */
1969     SILC_LOG_DEBUG(("Re-key done packet"));
1970     if (packet->flags & SILC_PACKET_FLAG_LIST)
1971       break;
1972
1973     if (sock->protocol && sock->protocol->protocol &&
1974         sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
1975
1976       SilcServerRekeyInternalContext *proto_ctx = 
1977         (SilcServerRekeyInternalContext *)sock->protocol->context;
1978
1979       if (proto_ctx->packet)
1980         silc_packet_context_free(proto_ctx->packet);
1981
1982       proto_ctx->packet = silc_packet_context_dup(packet);
1983
1984       /* Let the protocol handle the packet */
1985       sock->protocol->execute(server->timeout_queue, 0, 
1986                               sock->protocol, sock->sock,
1987                               0, 100000);
1988     } else {
1989       SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
1990                       "protocol active, packet dropped."));
1991     }
1992     break;
1993
1994   default:
1995     SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
1996     break;
1997   }
1998   
1999 }
2000
2001 /* Creates connection to a remote router. */
2002
2003 void silc_server_create_connection(SilcServer server,
2004                                    char *remote_host, uint32 port)
2005 {
2006   SilcServerConnection sconn;
2007
2008   /* Allocate connection object for hold connection specific stuff. */
2009   sconn = silc_calloc(1, sizeof(*sconn));
2010   sconn->server = server;
2011   sconn->remote_host = strdup(remote_host);
2012   sconn->remote_port = port;
2013
2014   silc_task_register(server->timeout_queue, 0, 
2015                      silc_server_connect_router,
2016                      (void *)sconn, 0, 1, SILC_TASK_TIMEOUT, 
2017                      SILC_TASK_PRI_NORMAL);
2018 }
2019
2020 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2021 {
2022   silc_socket_free((SilcSocketConnection)context);
2023 }
2024
2025 /* Closes connection to socket connection */
2026
2027 void silc_server_close_connection(SilcServer server,
2028                                   SilcSocketConnection sock)
2029 {
2030   SILC_LOG_DEBUG(("Closing connection %d", sock->sock));
2031
2032   /* We won't listen for this connection anymore */
2033   silc_schedule_unset_listen_fd(sock->sock);
2034
2035   /* Unregister all tasks */
2036   silc_task_unregister_by_fd(server->io_queue, sock->sock);
2037   silc_task_unregister_by_fd(server->timeout_queue, sock->sock);
2038
2039   /* Close the actual connection */
2040   silc_net_close_connection(sock->sock);
2041   server->sockets[sock->sock] = NULL;
2042
2043   silc_task_register(server->timeout_queue, 0, 
2044                      silc_server_close_connection_final,
2045                      (void *)sock, 0, 1, SILC_TASK_TIMEOUT, 
2046                      SILC_TASK_PRI_NORMAL);
2047 }
2048
2049 /* Sends disconnect message to remote connection and disconnects the 
2050    connection. */
2051
2052 void silc_server_disconnect_remote(SilcServer server,
2053                                    SilcSocketConnection sock,
2054                                    const char *fmt, ...)
2055 {
2056   va_list ap;
2057   unsigned char buf[4096];
2058
2059   if (!sock)
2060     return;
2061
2062   memset(buf, 0, sizeof(buf));
2063   va_start(ap, fmt);
2064   vsprintf(buf, fmt, ap);
2065   va_end(ap);
2066
2067   SILC_LOG_DEBUG(("Disconnecting remote host"));
2068
2069   SILC_LOG_INFO(("Disconnecting %s:%d [%s]", sock->hostname,
2070                   sock->port,
2071                   (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2072                    sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2073                    sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2074                    "Router")));
2075
2076   /* Notify remote end that the conversation is over. The notify message
2077      is tried to be sent immediately. */
2078   silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,  
2079                           buf, strlen(buf), TRUE);
2080
2081   /* Mark the connection to be disconnected */
2082   SILC_SET_DISCONNECTED(sock);
2083   silc_server_close_connection(server, sock);
2084 }
2085
2086 typedef struct {
2087   SilcServer server;
2088   SilcClientEntry client;
2089 } *FreeClientInternal;
2090
2091 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2092 {
2093   FreeClientInternal i = (FreeClientInternal)context;
2094
2095   silc_idlist_del_data(i->client);
2096   silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2097   silc_free(i);
2098 }
2099
2100 /* Frees client data and notifies about client's signoff. */
2101
2102 void silc_server_free_client_data(SilcServer server, 
2103                                   SilcSocketConnection sock,
2104                                   SilcClientEntry client, 
2105                                   int notify,
2106                                   char *signoff)
2107 {
2108   FreeClientInternal i = silc_calloc(1, sizeof(*i));
2109
2110   /* If there is pending outgoing data for the client then purge it
2111      to the network before removing the client entry. */
2112   if (sock && SILC_IS_OUTBUF_PENDING(sock) && 
2113       (SILC_IS_DISCONNECTED(sock) == FALSE)) {
2114     server->stat.packets_sent++;
2115
2116     if (sock->outbuf->data - sock->outbuf->head)
2117      silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
2118
2119     silc_server_packet_send_real(server, sock, TRUE);
2120
2121     SILC_SET_CONNECTION_FOR_INPUT(sock->sock);
2122     SILC_UNSET_OUTBUF_PENDING(sock);
2123     silc_buffer_clear(sock->outbuf);
2124   }
2125
2126   /* Send SIGNOFF notify to routers. */
2127   if (notify && !server->standalone && server->router)
2128     silc_server_send_notify_signoff(server, server->router->connection,
2129                                     server->server_type == SILC_SERVER ?
2130                                     FALSE : TRUE, client->id, 
2131                                     SILC_ID_CLIENT_LEN, signoff);
2132
2133   /* Remove client from all channels */
2134   if (notify)
2135     silc_server_remove_from_channels(server, NULL, client, 
2136                                      TRUE, signoff, TRUE);
2137   else
2138     silc_server_remove_from_channels(server, NULL, client, 
2139                                      FALSE, NULL, FALSE);
2140
2141   /* We will not delete the client entry right away. We will take it
2142      into history (for WHOWAS command) for 5 minutes */
2143   i->server = server;
2144   i->client = client;
2145   silc_task_register(server->timeout_queue, 0, 
2146                      silc_server_free_client_data_timeout,
2147                      (void *)i, 300, 0,
2148                      SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2149   client->data.registered = FALSE;
2150
2151   /* Free the client entry and everything in it */
2152   server->stat.my_clients--;
2153   server->stat.clients--;
2154   if (server->server_type == SILC_ROUTER)
2155     server->stat.cell_clients--;
2156 }
2157
2158 /* Frees user_data pointer from socket connection object. This also sends
2159    appropriate notify packets to the network to inform about leaving
2160    entities. */
2161
2162 void silc_server_free_sock_user_data(SilcServer server, 
2163                                      SilcSocketConnection sock)
2164 {
2165   SILC_LOG_DEBUG(("Start"));
2166
2167   switch(sock->type) {
2168   case SILC_SOCKET_TYPE_CLIENT:
2169     {
2170       SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2171       silc_server_free_client_data(server, sock, user_data, TRUE, NULL);
2172       break;
2173     }
2174   case SILC_SOCKET_TYPE_SERVER:
2175   case SILC_SOCKET_TYPE_ROUTER:
2176     {
2177       SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2178
2179       /* Free all client entries that this server owns as they will
2180          become invalid now as well. */
2181       silc_server_remove_clients_by_server(server, user_data, TRUE);
2182
2183       /* If this was our primary router connection then we're lost to
2184          the outside world. */
2185       if (server->router == user_data) {
2186         server->id_entry->router = NULL;
2187         server->router = NULL;
2188         server->standalone = TRUE;
2189       }
2190
2191       /* Free the server entry */
2192       silc_idlist_del_data(user_data);
2193       silc_idlist_del_server(server->local_list, user_data);
2194       server->stat.my_servers--;
2195       server->stat.servers--;
2196       if (server->server_type == SILC_ROUTER)
2197         server->stat.cell_servers--;
2198       break;
2199     }
2200   default:
2201     {
2202       SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2203
2204       silc_idlist_del_data(user_data);
2205       silc_free(user_data);
2206       break;
2207     }
2208   }
2209
2210   sock->user_data = NULL;
2211 }
2212
2213 /* This function is used to remove all client entries by the server `entry'.
2214    This is called when the connection is lost to the server. In this case
2215    we must invalidate all the client entries owned by the server `entry'. 
2216    If the `server_signoff' is TRUE then the SERVER_SIGNOFF notify is
2217    distributed to our local clients. */
2218
2219 int silc_server_remove_clients_by_server(SilcServer server, 
2220                                          SilcServerEntry entry,
2221                                          int server_signoff)
2222 {
2223   SilcIDCacheList list = NULL;
2224   SilcIDCacheEntry id_cache = NULL;
2225   SilcClientEntry client = NULL;
2226   SilcBuffer idp;
2227   SilcClientEntry *clients = NULL;
2228   uint32 clients_c = 0;
2229   unsigned char **argv = NULL;
2230   uint32 *argv_lens = NULL, *argv_types = NULL, argc = 0;
2231   int i;
2232
2233   SILC_LOG_DEBUG(("Start"));
2234
2235   if (server_signoff) {
2236     idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
2237     argv = silc_realloc(argv, sizeof(*argv) * (argc + 1));
2238     argv_lens = silc_realloc(argv_lens,  sizeof(*argv_lens) * (argc + 1));
2239     argv_types = silc_realloc(argv_types, sizeof(*argv_types) * (argc + 1));
2240     argv[argc] = idp->data;
2241     argv_lens[argc] = idp->len;
2242     argv_types[argc] = argc + 1;
2243     argc++;
2244     silc_buffer_free(idp);
2245   }
2246
2247   if (silc_idcache_find_by_id(server->local_list->clients, 
2248                               SILC_ID_CACHE_ANY, SILC_ID_CLIENT, &list)) {
2249
2250     if (silc_idcache_list_first(list, &id_cache)) {
2251       while (id_cache) {
2252         client = (SilcClientEntry)id_cache->context;
2253         if (client->data.registered == FALSE) {
2254           if (!silc_idcache_list_next(list, &id_cache))
2255             break;
2256           else
2257             continue;
2258         }
2259
2260         if (client->router != entry) {
2261           if (server_signoff && client->connection) {
2262             clients = silc_realloc(clients, 
2263                                    sizeof(*clients) * (clients_c + 1));
2264             clients[clients_c] = client;
2265             clients_c++;
2266           }
2267
2268           if (!silc_idcache_list_next(list, &id_cache))
2269             break;
2270           else
2271             continue;
2272         }
2273
2274         if (server_signoff) {
2275           idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2276           argv = silc_realloc(argv, sizeof(*argv) * (argc + 1));
2277           argv_lens = silc_realloc(argv_lens, sizeof(*argv_lens) *
2278                                    (argc + 1));
2279           argv_types = silc_realloc(argv_types, sizeof(*argv_types) *
2280                                     (argc + 1));
2281           argv[argc] = silc_calloc(idp->len, sizeof(*argv[0]));
2282           memcpy(argv[argc], idp->data, idp->len);
2283           argv_lens[argc] = idp->len;
2284           argv_types[argc] = argc + 1;
2285           argc++;
2286           silc_buffer_free(idp);
2287         }
2288
2289         /* Remove the client entry */
2290         silc_server_remove_from_channels(server, NULL, client, FALSE, 
2291                                          NULL, FALSE);
2292         silc_idlist_del_client(server->local_list, client);
2293
2294         if (!silc_idcache_list_next(list, &id_cache))
2295           break;
2296       }
2297     }
2298     silc_idcache_list_free(list);
2299   }
2300   
2301   if (silc_idcache_find_by_id(server->global_list->clients, 
2302                               SILC_ID_CACHE_ANY, SILC_ID_CLIENT, &list)) {
2303
2304     if (silc_idcache_list_first(list, &id_cache)) {
2305       while (id_cache) {
2306         client = (SilcClientEntry)id_cache->context;
2307         if (client->data.registered == FALSE) {
2308           if (!silc_idcache_list_next(list, &id_cache))
2309             break;
2310           else
2311             continue;
2312         }
2313         
2314         if (client->router != entry) {
2315           if (server_signoff && client->connection) {
2316             clients = silc_realloc(clients, 
2317                                    sizeof(*clients) * (clients_c + 1));
2318             clients[clients_c] = client;
2319             clients_c++;
2320           }
2321
2322           if (!silc_idcache_list_next(list, &id_cache))
2323             break;
2324           else
2325             continue;
2326         }
2327
2328         if (server_signoff) {
2329           idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2330           argv = silc_realloc(argv, sizeof(*argv) * (argc + 1));
2331           argv_lens = silc_realloc(argv_lens, sizeof(*argv_lens) *
2332                                    (argc + 1));
2333           argv_types = silc_realloc(argv_types, sizeof(*argv_types) *
2334                                     (argc + 1));
2335           argv[argc] = silc_calloc(idp->len, sizeof(*argv[0]));
2336           memcpy(argv[argc], idp->data, idp->len);
2337           argv_lens[argc] = idp->len;
2338           argv_types[argc] = argc + 1;
2339           argc++;
2340           silc_buffer_free(idp);
2341         }
2342
2343         /* Remove the client entry */
2344         silc_server_remove_from_channels(server, NULL, client, FALSE,
2345                                          NULL, FALSE);
2346         silc_idlist_del_client(server->global_list, client);
2347
2348         if (!silc_idcache_list_next(list, &id_cache))
2349           break;
2350       }
2351     }
2352     silc_idcache_list_free(list);
2353   }
2354
2355   /* Send the SERVER_SIGNOFF notify */
2356   if (server_signoff) {
2357     SilcBuffer args;
2358
2359     /* Send SERVER_SIGNOFF notify to our primary router */
2360     if (!server->standalone && server->router) {
2361       args = silc_argument_payload_encode(1, argv, argv_lens,
2362                                           argv_types);
2363       silc_server_send_notify_args(server, 
2364                                    server->router->connection,
2365                                    server->server_type == 
2366                                    SILC_SERVER ? FALSE : TRUE, 
2367                                    SILC_NOTIFY_TYPE_SERVER_SIGNOFF,
2368                                    argc, args);
2369       silc_buffer_free(args);
2370     }
2371
2372     args = silc_argument_payload_encode(argc, argv, argv_lens,
2373                                         argv_types);
2374     /* Send to local clients */
2375     for (i = 0; i < clients_c; i++) {
2376       silc_server_send_notify_args(server, clients[i]->connection,
2377                                    FALSE, SILC_NOTIFY_TYPE_SERVER_SIGNOFF,
2378                                    argc, args);
2379     }
2380
2381     silc_free(clients);
2382     silc_buffer_free(args);
2383     silc_free(argv);
2384     silc_free(argv_lens);
2385     silc_free(argv_types);
2386   }
2387
2388   return TRUE;
2389 }
2390
2391 /* Checks whether given channel has global users.  If it does this returns
2392    TRUE and FALSE if there is only locally connected clients on the channel. */
2393
2394 int silc_server_channel_has_global(SilcChannelEntry channel)
2395 {
2396   SilcChannelClientEntry chl;
2397
2398   silc_list_start(channel->user_list);
2399   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2400     if (chl->client->router)
2401       return TRUE;
2402   }
2403
2404   return FALSE;
2405 }
2406
2407 /* Checks whether given channel has locally connected users.  If it does this
2408    returns TRUE and FALSE if there is not one locally connected client. */
2409
2410 int silc_server_channel_has_local(SilcChannelEntry channel)
2411 {
2412   SilcChannelClientEntry chl;
2413
2414   silc_list_start(channel->user_list);
2415   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2416     if (!chl->client->router)
2417       return TRUE;
2418   }
2419
2420   return FALSE;
2421 }
2422
2423 /* Removes client from all channels it has joined. This is used when client
2424    connection is disconnected. If the client on a channel is last, the
2425    channel is removed as well. This sends the SIGNOFF notify types. */
2426
2427 void silc_server_remove_from_channels(SilcServer server, 
2428                                       SilcSocketConnection sock,
2429                                       SilcClientEntry client,
2430                                       int notify,
2431                                       char *signoff_message,
2432                                       int keygen)
2433 {
2434   SilcChannelEntry channel;
2435   SilcChannelClientEntry chl;
2436   SilcBuffer clidp;
2437
2438   SILC_LOG_DEBUG(("Start"));
2439
2440   if (!client || !client->id)
2441     return;
2442
2443   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2444
2445   /* Remove the client from all channels. The client is removed from
2446      the channels' user list. */
2447   silc_list_start(client->channels);
2448   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2449     channel = chl->channel;
2450
2451     /* Remove channel from client's channel list */
2452     silc_list_del(client->channels, chl);
2453
2454     /* Remove channel if there is no users anymore */
2455     if (server->server_type == SILC_ROUTER &&
2456         silc_list_count(channel->user_list) < 2) {
2457       server->stat.my_channels--;
2458
2459       if (channel->rekey)
2460         silc_task_unregister_by_context(server->timeout_queue, channel->rekey);
2461
2462       if (channel->founder_key) {
2463         /* The founder auth data exists, do not remove the channel entry */
2464         SilcChannelClientEntry chl2;
2465
2466         channel->id = NULL;
2467
2468         silc_list_start(channel->user_list);
2469         while ((chl2 = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2470           silc_list_del(chl2->client->channels, chl2);
2471           silc_list_del(channel->user_list, chl2);
2472           silc_free(chl2);
2473         }
2474         continue;
2475       }
2476
2477       if (!silc_idlist_del_channel(server->local_list, channel))
2478         silc_idlist_del_channel(server->global_list, channel);
2479       continue;
2480     }
2481
2482     /* Remove client from channel's client list */
2483     silc_list_del(channel->user_list, chl);
2484     silc_free(chl);
2485     server->stat.my_chanclients--;
2486
2487     /* If there is no global users on the channel anymore mark the channel
2488        as local channel. */
2489     if (server->server_type == SILC_SERVER &&
2490         !silc_server_channel_has_global(channel))
2491       channel->global_users = FALSE;
2492
2493     /* If there is not at least one local user on the channel then we don't
2494        need the channel entry anymore, we can remove it safely. */
2495     if (server->server_type == SILC_SERVER &&
2496         !silc_server_channel_has_local(channel)) {
2497       /* Notify about leaving client if this channel has global users. */
2498       if (notify && channel->global_users)
2499         silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2500                                            SILC_NOTIFY_TYPE_SIGNOFF, 
2501                                            signoff_message ? 2 : 1,
2502                                            clidp->data, clidp->len,
2503                                            signoff_message, signoff_message ?
2504                                            strlen(signoff_message) : 0);
2505
2506       server->stat.my_channels--;
2507
2508       if (channel->rekey)
2509         silc_task_unregister_by_context(server->timeout_queue, channel->rekey);
2510
2511       if (channel->founder_key) {
2512         /* The founder auth data exists, do not remove the channel entry */
2513         SilcChannelClientEntry chl2;
2514
2515         channel->id = NULL;
2516
2517         silc_list_start(channel->user_list);
2518         while ((chl2 = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2519           silc_list_del(chl2->client->channels, chl2);
2520           silc_list_del(channel->user_list, chl2);
2521           silc_free(chl2);
2522         }
2523         continue;
2524       }
2525
2526       if (!silc_idlist_del_channel(server->local_list, channel))
2527         silc_idlist_del_channel(server->global_list, channel);
2528       continue;
2529     }
2530
2531     /* Send notify to channel about client leaving SILC and thus
2532        the entire channel. */
2533     if (notify)
2534       silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2535                                          SILC_NOTIFY_TYPE_SIGNOFF, 
2536                                          signoff_message ? 2 : 1,
2537                                          clidp->data, clidp->len,
2538                                          signoff_message, signoff_message ?
2539                                          strlen(signoff_message) : 0);
2540
2541     if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2542       /* Re-generate channel key */
2543       silc_server_create_channel_key(server, channel, 0);
2544       
2545       /* Send the channel key to the channel. The key of course is not sent
2546          to the client who was removed from the channel. */
2547       silc_server_send_channel_key(server, client->connection, channel, 
2548                                    server->server_type == SILC_ROUTER ? 
2549                                    FALSE : !server->standalone);
2550     }
2551   }
2552
2553   silc_buffer_free(clidp);
2554 }
2555
2556 /* Removes client from one channel. This is used for example when client
2557    calls LEAVE command to remove itself from the channel. Returns TRUE
2558    if channel still exists and FALSE if the channel is removed when
2559    last client leaves the channel. If `notify' is FALSE notify messages
2560    are not sent. */
2561
2562 int silc_server_remove_from_one_channel(SilcServer server, 
2563                                         SilcSocketConnection sock,
2564                                         SilcChannelEntry channel,
2565                                         SilcClientEntry client,
2566                                         int notify)
2567 {
2568   SilcChannelEntry ch;
2569   SilcChannelClientEntry chl;
2570   SilcBuffer clidp;
2571
2572   SILC_LOG_DEBUG(("Start"));
2573
2574   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2575
2576   /* Remove the client from the channel. The client is removed from
2577      the channel's user list. */
2578   silc_list_start(client->channels);
2579   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2580     if (chl->channel != channel)
2581       continue;
2582
2583     ch = chl->channel;
2584
2585     /* Remove channel from client's channel list */
2586     silc_list_del(client->channels, chl);
2587
2588     /* Remove channel if there is no users anymore */
2589     if (server->server_type == SILC_ROUTER &&
2590         silc_list_count(channel->user_list) < 2) {
2591       if (channel->rekey)
2592         silc_task_unregister_by_context(server->timeout_queue, channel->rekey);
2593       if (!silc_idlist_del_channel(server->local_list, channel))
2594         silc_idlist_del_channel(server->global_list, channel);
2595       silc_buffer_free(clidp);
2596       server->stat.my_channels--;
2597       return FALSE;
2598     }
2599
2600     /* Remove client from channel's client list */
2601     silc_list_del(channel->user_list, chl);
2602     silc_free(chl);
2603     server->stat.my_chanclients--;
2604
2605     /* If there is no global users on the channel anymore mark the channel
2606        as local channel. */
2607     if (server->server_type == SILC_SERVER &&
2608         !silc_server_channel_has_global(channel))
2609       channel->global_users = FALSE;
2610
2611     /* If there is not at least one local user on the channel then we don't
2612        need the channel entry anymore, we can remove it safely. */
2613     if (server->server_type == SILC_SERVER &&
2614         !silc_server_channel_has_local(channel)) {
2615       /* Notify about leaving client if this channel has global users. */
2616       if (notify && channel->global_users)
2617         silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2618                                            SILC_NOTIFY_TYPE_LEAVE, 1,
2619                                            clidp->data, clidp->len);
2620
2621       server->stat.my_channels--;
2622       silc_buffer_free(clidp);
2623
2624       if (channel->rekey)
2625         silc_task_unregister_by_context(server->timeout_queue, channel->rekey);
2626
2627       if (channel->founder_key) {
2628         /* The founder auth data exists, do not remove the channel entry */
2629         SilcChannelClientEntry chl2;
2630
2631         channel->id = NULL;
2632
2633         silc_list_start(channel->user_list);
2634         while ((chl2 = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2635           silc_list_del(chl2->client->channels, chl2);
2636           silc_list_del(channel->user_list, chl2);
2637           silc_free(chl2);
2638         }
2639         return FALSE;
2640       }
2641
2642       if (!silc_idlist_del_channel(server->local_list, channel))
2643         silc_idlist_del_channel(server->global_list, channel);
2644       return FALSE;
2645     }
2646
2647     /* Send notify to channel about client leaving the channel */
2648     if (notify)
2649       silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2650                                          SILC_NOTIFY_TYPE_LEAVE, 1,
2651                                          clidp->data, clidp->len);
2652     break;
2653   }
2654
2655   silc_buffer_free(clidp);
2656   return TRUE;
2657 }
2658
2659 /* Returns TRUE if the given client is on the channel.  FALSE if not. 
2660    This works because we assure that the user list on the channel is
2661    always in up to date thus we can only check the channel list from 
2662    `client' which is faster than checking the user list from `channel'. */
2663
2664 int silc_server_client_on_channel(SilcClientEntry client,
2665                                   SilcChannelEntry channel)
2666 {
2667   SilcChannelClientEntry chl;
2668
2669   if (!client || !channel)
2670     return FALSE;
2671
2672   silc_list_start(client->channels);
2673   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END)
2674     if (chl->channel == channel)
2675       return TRUE;
2676
2677   return FALSE;
2678 }
2679
2680 /* Timeout callback. This is called if connection is idle or for some
2681    other reason is not responding within some period of time. This 
2682    disconnects the remote end. */
2683
2684 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2685 {
2686   SilcServer server = (SilcServer)context;
2687   SilcSocketConnection sock = server->sockets[fd];
2688
2689   if (!sock)
2690     return;
2691
2692   if (sock->user_data)
2693     silc_server_free_sock_user_data(server, sock);
2694
2695   silc_server_disconnect_remote(server, sock, 
2696                                 "Server closed connection: "
2697                                 "Connection timeout");
2698 }
2699
2700 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2701    function may be used only by router. In real SILC network all channels
2702    are created by routers thus this function is never used by normal
2703    server. */
2704
2705 SilcChannelEntry silc_server_create_new_channel(SilcServer server, 
2706                                                 SilcServerID *router_id,
2707                                                 char *cipher, 
2708                                                 char *hmac,
2709                                                 char *channel_name,
2710                                                 int broadcast)
2711 {
2712   SilcChannelID *channel_id;
2713   SilcChannelEntry entry;
2714   SilcCipher key;
2715   SilcHmac newhmac;
2716
2717   SILC_LOG_DEBUG(("Creating new channel"));
2718
2719   if (!cipher)
2720     cipher = "aes-256-cbc";
2721   if (!hmac)
2722     hmac = "hmac-sha1-96";
2723
2724   /* Allocate cipher */
2725   if (!silc_cipher_alloc(cipher, &key))
2726     return NULL;
2727
2728   /* Allocate hmac */
2729   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2730     silc_cipher_free(key);
2731     return NULL;
2732   }
2733
2734   channel_name = strdup(channel_name);
2735
2736   /* Create the channel */
2737   silc_id_create_channel_id(router_id, server->rng, &channel_id);
2738   entry = silc_idlist_add_channel(server->local_list, channel_name, 
2739                                   SILC_CHANNEL_MODE_NONE, channel_id, 
2740                                   NULL, key, newhmac);
2741   if (!entry) {
2742     silc_free(channel_name);
2743     return NULL;
2744   }
2745
2746   entry->cipher = strdup(cipher);
2747   entry->hmac_name = strdup(hmac);
2748
2749   /* Now create the actual key material */
2750   silc_server_create_channel_key(server, entry, 
2751                                  silc_cipher_get_key_len(key) / 8);
2752
2753   /* Notify other routers about the new channel. We send the packet
2754      to our primary route. */
2755   if (broadcast && server->standalone == FALSE)
2756     silc_server_send_new_channel(server, server->router->connection, TRUE, 
2757                                  channel_name, entry->id, SILC_ID_CHANNEL_LEN,
2758                                  entry->mode);
2759
2760   server->stat.my_channels++;
2761
2762   return entry;
2763 }
2764
2765 /* Same as above but creates the channel with Channel ID `channel_id. */
2766
2767 SilcChannelEntry 
2768 silc_server_create_new_channel_with_id(SilcServer server, 
2769                                        char *cipher, 
2770                                        char *hmac,
2771                                        char *channel_name,
2772                                        SilcChannelID *channel_id,
2773                                        int broadcast)
2774 {
2775   SilcChannelEntry entry;
2776   SilcCipher key;
2777   SilcHmac newhmac;
2778
2779   SILC_LOG_DEBUG(("Creating new channel"));
2780
2781   if (!cipher)
2782     cipher = "aes-256-cbc";
2783   if (!hmac)
2784     hmac = "hmac-sha1-96";
2785
2786   /* Allocate cipher */
2787   if (!silc_cipher_alloc(cipher, &key))
2788     return NULL;
2789
2790   /* Allocate hmac */
2791   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2792     silc_cipher_free(key);
2793     return NULL;
2794   }
2795
2796   channel_name = strdup(channel_name);
2797
2798   /* Create the channel */
2799   entry = silc_idlist_add_channel(server->local_list, channel_name, 
2800                                   SILC_CHANNEL_MODE_NONE, channel_id, 
2801                                   NULL, key, newhmac);
2802   if (!entry) {
2803     silc_free(channel_name);
2804     return NULL;
2805   }
2806
2807   /* Now create the actual key material */
2808   silc_server_create_channel_key(server, entry, 
2809                                  silc_cipher_get_key_len(key) / 8);
2810
2811   /* Notify other routers about the new channel. We send the packet
2812      to our primary route. */
2813   if (broadcast && server->standalone == FALSE)
2814     silc_server_send_new_channel(server, server->router->connection, TRUE, 
2815                                  channel_name, entry->id, SILC_ID_CHANNEL_LEN,
2816                                  entry->mode);
2817
2818   server->stat.my_channels++;
2819
2820   return entry;
2821 }
2822
2823 /* Channel's key re-key timeout callback. */
2824
2825 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
2826 {
2827   SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
2828   SilcServer server = (SilcServer)rekey->context;
2829
2830   silc_server_create_channel_key(server, rekey->channel, rekey->key_len);
2831   silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
2832
2833   silc_task_register(server->timeout_queue, 0, 
2834                      silc_server_channel_key_rekey,
2835                      (void *)rekey, 3600, 0,
2836                      SILC_TASK_TIMEOUT,
2837                      SILC_TASK_PRI_NORMAL);
2838 }
2839
2840 /* Generates new channel key. This is used to create the initial channel key
2841    but also to re-generate new key for channel. If `key_len' is provided
2842    it is the bytes of the key length. */
2843
2844 void silc_server_create_channel_key(SilcServer server, 
2845                                     SilcChannelEntry channel,
2846                                     uint32 key_len)
2847 {
2848   int i;
2849   unsigned char channel_key[32], hash[32];
2850   uint32 len;
2851
2852   SILC_LOG_DEBUG(("Generating channel key"));
2853
2854   if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
2855     SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
2856     return;
2857   }
2858
2859   if (!channel->channel_key)
2860     if (!silc_cipher_alloc("aes-256-cbc", &channel->channel_key))
2861       return;
2862
2863   if (key_len)
2864     len = key_len;
2865   else if (channel->key_len)
2866     len = channel->key_len / 8;
2867   else
2868     len = silc_cipher_get_key_len(channel->channel_key) / 8;
2869
2870   /* Create channel key */
2871   for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
2872   
2873   /* Set the key */
2874   silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
2875
2876   /* Remove old key if exists */
2877   if (channel->key) {
2878     memset(channel->key, 0, channel->key_len / 8);
2879     silc_free(channel->key);
2880   }
2881
2882   /* Save the key */
2883   channel->key_len = len * 8;
2884   channel->key = silc_calloc(len, sizeof(*channel->key));
2885   memcpy(channel->key, channel_key, len);
2886   memset(channel_key, 0, sizeof(channel_key));
2887
2888   /* Generate HMAC key from the channel key data and set it */
2889   if (!channel->hmac)
2890     silc_hmac_alloc("hmac-sha1-96", NULL, &channel->hmac);
2891   silc_hash_make(channel->hmac->hash, channel->key, len, hash);
2892   silc_hmac_set_key(channel->hmac, hash, silc_hash_len(channel->hmac->hash));
2893   memset(hash, 0, sizeof(hash));
2894
2895   if (server->server_type == SILC_ROUTER) {
2896     if (!channel->rekey)
2897       channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
2898     channel->rekey->context = (void *)server;
2899     channel->rekey->channel = channel;
2900     channel->rekey->key_len = key_len;
2901
2902     silc_task_unregister_by_callback(server->timeout_queue,
2903                                      silc_server_channel_key_rekey);
2904     silc_task_register(server->timeout_queue, 0, 
2905                        silc_server_channel_key_rekey,
2906                        (void *)channel->rekey, 3600, 0,
2907                        SILC_TASK_TIMEOUT,
2908                        SILC_TASK_PRI_NORMAL);
2909   }
2910 }
2911
2912 /* Saves the channel key found in the encoded `key_payload' buffer. This 
2913    function is used when we receive Channel Key Payload and also when we're
2914    processing JOIN command reply. Returns entry to the channel. */
2915
2916 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
2917                                               SilcBuffer key_payload,
2918                                               SilcChannelEntry channel)
2919 {
2920   SilcChannelKeyPayload payload = NULL;
2921   SilcChannelID *id = NULL;
2922   unsigned char *tmp, hash[32];
2923   uint32 tmp_len;
2924   char *cipher;
2925
2926   SILC_LOG_DEBUG(("Start"));
2927
2928   /* Decode channel key payload */
2929   payload = silc_channel_key_payload_parse(key_payload);
2930   if (!payload) {
2931     SILC_LOG_ERROR(("Bad channel key payload, dropped"));
2932     channel = NULL;
2933     goto out;
2934   }
2935
2936   /* Get the channel entry */
2937   if (!channel) {
2938
2939     /* Get channel ID */
2940     tmp = silc_channel_key_get_id(payload, &tmp_len);
2941     id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
2942     if (!id) {
2943       channel = NULL;
2944       goto out;
2945     }
2946
2947     channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
2948     if (!channel) {
2949       channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
2950       if (!channel) {
2951         SILC_LOG_ERROR(("Received key for non-existent channel"));
2952         goto out;
2953       }
2954     }
2955   }
2956
2957   tmp = silc_channel_key_get_key(payload, &tmp_len);
2958   if (!tmp) {
2959     channel = NULL;
2960     goto out;
2961   }
2962
2963   cipher = silc_channel_key_get_cipher(payload, NULL);
2964   if (!cipher) {
2965     channel = NULL;
2966     goto out;
2967   }
2968
2969   /* Remove old key if exists */
2970   if (channel->key) {
2971     memset(channel->key, 0, channel->key_len / 8);
2972     silc_free(channel->key);
2973     silc_cipher_free(channel->channel_key);
2974   }
2975
2976   /* Create new cipher */
2977   if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
2978     channel = NULL;
2979     goto out;
2980   }
2981
2982   if (channel->cipher)
2983     silc_free(channel->cipher);
2984   channel->cipher = strdup(cipher);
2985
2986   /* Save the key */
2987   channel->key_len = tmp_len * 8;
2988   channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
2989   memcpy(channel->key, tmp, tmp_len);
2990   silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
2991
2992   /* Generate HMAC key from the channel key data and set it */
2993   if (!channel->hmac)
2994     silc_hmac_alloc("hmac-sha1-96", NULL, &channel->hmac);
2995   silc_hash_make(channel->hmac->hash, tmp, tmp_len, hash);
2996   silc_hmac_set_key(channel->hmac, hash, silc_hash_len(channel->hmac->hash));
2997
2998   memset(hash, 0, sizeof(hash));
2999   memset(tmp, 0, tmp_len);
3000
3001   if (server->server_type == SILC_ROUTER) {
3002     if (!channel->rekey)
3003       channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3004     channel->rekey->context = (void *)server;
3005     channel->rekey->channel = channel;
3006
3007     silc_task_unregister_by_callback(server->timeout_queue,
3008                                      silc_server_channel_key_rekey);
3009     silc_task_register(server->timeout_queue, 0, 
3010                        silc_server_channel_key_rekey,
3011                        (void *)channel->rekey, 3600, 0,
3012                        SILC_TASK_TIMEOUT,
3013                        SILC_TASK_PRI_NORMAL);
3014   }
3015
3016  out:
3017   if (id)
3018     silc_free(id);
3019   if (payload)
3020     silc_channel_key_payload_free(payload);
3021
3022   return channel;
3023 }
3024
3025 /* Heartbeat callback. This function is set as argument for the
3026    silc_socket_set_heartbeat function. The library will call this function
3027    at the set time interval. */
3028
3029 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3030                                    void *hb_context)
3031 {
3032   SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3033
3034   SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname,
3035                   sock->ip));
3036
3037   /* Send the heartbeat */
3038   silc_server_send_heartbeat(hb->server, sock);
3039 }
3040
3041 /* Returns assembled of all servers in the given ID list. The packet's
3042    form is dictated by the New ID payload. */
3043
3044 static void silc_server_announce_get_servers(SilcServer server,
3045                                              SilcIDList id_list,
3046                                              SilcBuffer *servers)
3047 {
3048   SilcIDCacheList list;
3049   SilcIDCacheEntry id_cache;
3050   SilcServerEntry entry;
3051   SilcBuffer idp;
3052
3053   /* Go through all clients in the list */
3054   if (silc_idcache_find_by_id(id_list->clients, SILC_ID_CACHE_ANY, 
3055                               SILC_ID_SERVER, &list)) {
3056     if (silc_idcache_list_first(list, &id_cache)) {
3057       while (id_cache) {
3058         entry = (SilcServerEntry)id_cache->context;
3059
3060         idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3061
3062         *servers = silc_buffer_realloc(*servers, 
3063                                        (*servers ? 
3064                                         (*servers)->truelen + idp->len : 
3065                                         idp->len));
3066         silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3067         silc_buffer_put(*servers, idp->data, idp->len);
3068         silc_buffer_pull(*servers, idp->len);
3069         silc_buffer_free(idp);
3070
3071         if (!silc_idcache_list_next(list, &id_cache))
3072           break;
3073       }
3074     }
3075
3076     silc_idcache_list_free(list);
3077   }
3078 }
3079
3080 /* This function is used by router to announce existing servers to our
3081    primary router when we've connected to it. */
3082
3083 void silc_server_announce_servers(SilcServer server)
3084 {
3085   SilcBuffer servers = NULL;
3086
3087   SILC_LOG_DEBUG(("Announcing servers"));
3088
3089   /* Get servers in local list */
3090   silc_server_announce_get_servers(server, server->local_list, &servers);
3091
3092   /* Get servers in global list */
3093   silc_server_announce_get_servers(server, server->global_list, &servers);
3094
3095   if (servers) {
3096     silc_buffer_push(servers, servers->data - servers->head);
3097     SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3098
3099     /* Send the packet */
3100     silc_server_packet_send(server, server->router->connection,
3101                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3102                             servers->data, servers->len, TRUE);
3103
3104     silc_buffer_free(servers);
3105   }
3106 }
3107
3108 /* Returns assembled packet of all clients in the given ID list. The
3109    packet's form is dictated by the New ID Payload. */
3110
3111 static void silc_server_announce_get_clients(SilcServer server,
3112                                              SilcIDList id_list,
3113                                              SilcBuffer *clients)
3114 {
3115   SilcIDCacheList list;
3116   SilcIDCacheEntry id_cache;
3117   SilcClientEntry client;
3118   SilcBuffer idp;
3119
3120   /* Go through all clients in the list */
3121   if (silc_idcache_find_by_id(id_list->clients, SILC_ID_CACHE_ANY, 
3122                               SILC_ID_CLIENT, &list)) {
3123     if (silc_idcache_list_first(list, &id_cache)) {
3124       while (id_cache) {
3125         client = (SilcClientEntry)id_cache->context;
3126
3127         idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3128
3129         *clients = silc_buffer_realloc(*clients, 
3130                                        (*clients ? 
3131                                         (*clients)->truelen + idp->len : 
3132                                         idp->len));
3133         silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3134         silc_buffer_put(*clients, idp->data, idp->len);
3135         silc_buffer_pull(*clients, idp->len);
3136         silc_buffer_free(idp);
3137
3138         if (!silc_idcache_list_next(list, &id_cache))
3139           break;
3140       }
3141     }
3142
3143     silc_idcache_list_free(list);
3144   }
3145 }
3146
3147 /* This function is used to announce our existing clients to our router
3148    when we've connected to it. */
3149
3150 void silc_server_announce_clients(SilcServer server)
3151 {
3152   SilcBuffer clients = NULL;
3153
3154   SILC_LOG_DEBUG(("Announcing clients"));
3155
3156   /* Get clients in local list */
3157   silc_server_announce_get_clients(server, server->local_list,
3158                                    &clients);
3159
3160   /* As router we announce our global list as well */
3161   if (server->server_type == SILC_ROUTER)
3162     silc_server_announce_get_clients(server, server->global_list,
3163                                      &clients);
3164
3165   if (clients) {
3166     silc_buffer_push(clients, clients->data - clients->head);
3167     SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3168
3169     /* Send the packet */
3170     silc_server_packet_send(server, server->router->connection,
3171                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3172                             clients->data, clients->len, TRUE);
3173
3174     silc_buffer_free(clients);
3175   }
3176 }
3177
3178 static SilcBuffer 
3179 silc_server_announce_encode_join(uint32 argc, ...)
3180 {
3181   va_list ap;
3182
3183   va_start(ap, argc);
3184   return silc_notify_payload_encode(SILC_NOTIFY_TYPE_JOIN, argc, ap);
3185 }
3186
3187 /* Returns assembled packets for channel users of the `channel'. */
3188
3189 void silc_server_announce_get_channel_users(SilcServer server,
3190                                             SilcChannelEntry channel,
3191                                             SilcBuffer *channel_users)
3192 {
3193   SilcChannelClientEntry chl;
3194   SilcBuffer chidp, clidp;
3195   SilcBuffer tmp;
3196   int len;
3197
3198   SILC_LOG_DEBUG(("Start"));
3199
3200   /* Now find all users on the channel */
3201   chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3202   silc_list_start(channel->user_list);
3203   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
3204     clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3205     tmp = silc_server_announce_encode_join(2, clidp->data, clidp->len,
3206                                            chidp->data, chidp->len);
3207     len = tmp->len;
3208     *channel_users = 
3209       silc_buffer_realloc(*channel_users, 
3210                           (*channel_users ? 
3211                            (*channel_users)->truelen + len : len));
3212     silc_buffer_pull_tail(*channel_users, 
3213                           ((*channel_users)->end - 
3214                            (*channel_users)->data));
3215     
3216     silc_buffer_put(*channel_users, tmp->data, tmp->len);
3217     silc_buffer_pull(*channel_users, len);
3218     silc_buffer_free(clidp);
3219     silc_buffer_free(tmp);
3220   }
3221   silc_buffer_free(chidp);
3222 }
3223
3224 /* Returns assembled packets for all channels and users on those channels
3225    from the given ID List. The packets are in the form dictated by the
3226    New Channel and New Channel User payloads. */
3227
3228 void silc_server_announce_get_channels(SilcServer server,
3229                                        SilcIDList id_list,
3230                                        SilcBuffer *channels,
3231                                        SilcBuffer *channel_users)
3232 {
3233   SilcIDCacheList list;
3234   SilcIDCacheEntry id_cache;
3235   SilcChannelEntry channel;
3236   unsigned char *cid;
3237   uint16 name_len;
3238   int len;
3239
3240   SILC_LOG_DEBUG(("Start"));
3241
3242   /* Go through all channels in the list */
3243   if (silc_idcache_find_by_id(id_list->channels, SILC_ID_CACHE_ANY, 
3244                               SILC_ID_CHANNEL, &list)) {
3245     if (silc_idcache_list_first(list, &id_cache)) {
3246       while (id_cache) {
3247         channel = (SilcChannelEntry)id_cache->context;
3248         
3249         cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3250         name_len = strlen(channel->channel_name);
3251
3252         len = 4 + name_len + SILC_ID_CHANNEL_LEN + 4;
3253         *channels = 
3254           silc_buffer_realloc(*channels, 
3255                               (*channels ? (*channels)->truelen + len : len));
3256         silc_buffer_pull_tail(*channels, 
3257                               ((*channels)->end - (*channels)->data));
3258         silc_buffer_format(*channels,
3259                            SILC_STR_UI_SHORT(name_len),
3260                            SILC_STR_UI_XNSTRING(channel->channel_name, 
3261                                                 name_len),
3262                            SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
3263                            SILC_STR_UI_XNSTRING(cid, SILC_ID_CHANNEL_LEN),
3264                            SILC_STR_UI_INT(channel->mode),
3265                            SILC_STR_END);
3266         silc_buffer_pull(*channels, len);
3267
3268         silc_server_announce_get_channel_users(server, channel,
3269                                                channel_users);
3270
3271         silc_free(cid);
3272
3273         if (!silc_idcache_list_next(list, &id_cache))
3274           break;
3275       }
3276     }
3277
3278     silc_idcache_list_free(list);
3279   }
3280 }
3281
3282 /* This function is used to announce our existing channels to our router
3283    when we've connected to it. This also announces the users on the
3284    channels to the router. */
3285
3286 void silc_server_announce_channels(SilcServer server)
3287 {
3288   SilcBuffer channels = NULL, channel_users = NULL;
3289
3290   SILC_LOG_DEBUG(("Announcing channels and channel users"));
3291
3292   /* Get channels and channel users in local list */
3293   silc_server_announce_get_channels(server, server->local_list,
3294                                     &channels, &channel_users);
3295
3296   /* Get channels and channel users in global list */
3297   silc_server_announce_get_channels(server, server->global_list,
3298                                     &channels, &channel_users);
3299
3300   if (channels) {
3301     silc_buffer_push(channels, channels->data - channels->head);
3302     SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3303
3304     /* Send the packet */
3305     silc_server_packet_send(server, server->router->connection,
3306                             SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3307                             channels->data, channels->len,
3308                             FALSE);
3309
3310     silc_buffer_free(channels);
3311   }
3312
3313   if (channel_users) {
3314     silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3315     SILC_LOG_HEXDUMP(("channel users"), channel_users->data, 
3316                      channel_users->len);
3317
3318     /* Send the packet */
3319     silc_server_packet_send(server, server->router->connection,
3320                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3321                             channel_users->data, channel_users->len,
3322                             FALSE);
3323
3324     silc_buffer_free(channel_users);
3325   }
3326 }
3327
3328 /* Failure timeout callback. If this is called then we will immediately
3329    process the received failure. We always process the failure with timeout
3330    since we do not want to blindly trust to received failure packets. 
3331    This won't be called (the timeout is cancelled) if the failure was
3332    bogus (it is bogus if remote does not close the connection after sending
3333    the failure). */
3334
3335 SILC_TASK_CALLBACK(silc_server_failure_callback)
3336 {
3337   SilcServerFailureContext f = (SilcServerFailureContext)context;
3338
3339   if (f->sock->protocol) {
3340     f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3341     f->sock->protocol->execute(f->server->timeout_queue, 0,
3342                                f->sock->protocol, f->sock->sock, 0, 0);
3343   }
3344
3345   silc_free(f);
3346 }
3347
3348 /* Assembles user list and users mode list from the `channel'. */
3349
3350 void silc_server_get_users_on_channel(SilcServer server,
3351                                       SilcChannelEntry channel,
3352                                       SilcBuffer *user_list,
3353                                       SilcBuffer *mode_list,
3354                                       uint32 *user_count)
3355 {
3356   SilcChannelClientEntry chl;
3357   SilcBuffer client_id_list;
3358   SilcBuffer client_mode_list;
3359   SilcBuffer idp;
3360   uint32 list_count = 0;
3361
3362   client_id_list = silc_buffer_alloc((SILC_ID_CLIENT_LEN + 4) * 
3363                                      silc_list_count(channel->user_list));
3364   client_mode_list = silc_buffer_alloc(4 * 
3365                                        silc_list_count(channel->user_list));
3366   silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3367   silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3368   silc_list_start(channel->user_list);
3369   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
3370     /* Client ID */
3371     idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3372     silc_buffer_put(client_id_list, idp->data, idp->len);
3373     silc_buffer_pull(client_id_list, idp->len);
3374     silc_buffer_free(idp);
3375
3376     /* Client's mode on channel */
3377     SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3378     silc_buffer_pull(client_mode_list, 4);
3379
3380     list_count++;
3381   }
3382   silc_buffer_push(client_id_list, 
3383                    client_id_list->data - client_id_list->head);
3384   silc_buffer_push(client_mode_list, 
3385                    client_mode_list->data - client_mode_list->head);
3386
3387   *user_list = client_id_list;
3388   *mode_list = client_mode_list;
3389   *user_count = list_count;
3390 }
3391
3392 /* Saves users and their modes to the `channel'. */
3393
3394 void silc_server_save_users_on_channel(SilcServer server,
3395                                        SilcSocketConnection sock,
3396                                        SilcChannelEntry channel,
3397                                        SilcClientID *noadd,
3398                                        SilcBuffer user_list,
3399                                        SilcBuffer mode_list,
3400                                        uint32 user_count)
3401 {
3402   int i;
3403
3404   /* Cache the received Client ID's and modes. This cache expires
3405      whenever server sends notify message to channel. It means two things;
3406      some user has joined or leaved the channel. XXX TODO! */
3407   for (i = 0; i < user_count; i++) {
3408     uint16 idp_len;
3409     uint32 mode;
3410     SilcClientID *client_id;
3411     SilcClientEntry client;
3412
3413     /* Client ID */
3414     SILC_GET16_MSB(idp_len, user_list->data + 2);
3415     idp_len += 4;
3416     client_id = silc_id_payload_parse_id(user_list->data, idp_len);
3417     silc_buffer_pull(user_list, idp_len);
3418     if (!client_id)
3419       continue;
3420
3421     /* Mode */
3422     SILC_GET32_MSB(mode, mode_list->data);
3423     silc_buffer_pull(mode_list, 4);
3424
3425     if (noadd && !SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3426       silc_free(client_id);
3427       continue;
3428     }
3429     
3430     /* Check if we have this client cached already. */
3431     client = silc_idlist_find_client_by_id(server->local_list, client_id,
3432                                            NULL);
3433     if (!client)
3434       client = silc_idlist_find_client_by_id(server->global_list, 
3435                                              client_id, NULL);
3436     if (!client) {
3437       /* If router did not find such Client ID in its lists then this must
3438          be bogus client or some router in the net is buggy. */
3439       if (server->server_type == SILC_ROUTER) {
3440         silc_free(client_id);
3441         continue;
3442       }
3443
3444       /* We don't have that client anywhere, add it. The client is added
3445          to global list since server didn't have it in the lists so it must be 
3446          global. */
3447       client = silc_idlist_add_client(server->global_list, NULL, 0, NULL, 
3448                                       NULL, 
3449                                       silc_id_dup(client_id, SILC_ID_CLIENT), 
3450                                       sock->user_data, NULL);
3451       if (!client) {
3452         silc_free(client_id);
3453         continue;
3454       }
3455
3456       client->data.registered = TRUE;
3457     }
3458
3459     silc_free(client_id);
3460
3461     if (!silc_server_client_on_channel(client, channel)) {
3462       /* Client was not on the channel, add it. */
3463       SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3464       chl->client = client;
3465       chl->mode = mode;
3466       chl->channel = channel;
3467       silc_list_add(channel->user_list, chl);
3468       silc_list_add(client->channels, chl);
3469     }
3470   }
3471 }
3472
3473 /* Lookups route to the client indicated by `id' client ID. The connection
3474    object and internal data object is returned. Returns NULL if route
3475    could not be found to the client. If the `client_id' is specified then
3476    it is used and the `id_data' is ignored. */
3477
3478 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3479                                                   unsigned char *id_data,
3480                                                   uint32 id_len,
3481                                                   SilcClientID *client_id,
3482                                                   SilcIDListData *idata)
3483 {
3484   SilcClientID *id;
3485   SilcClientEntry client;
3486
3487   SILC_LOG_DEBUG(("Start"));
3488
3489   /* Decode destination Client ID */
3490   if (!client_id) {
3491     id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3492     if (!id) {
3493       SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3494       return NULL;
3495     }
3496   } else {
3497     id = silc_id_dup(client_id, SILC_ID_CLIENT);
3498   }
3499
3500   /* If the destination belongs to our server we don't have to route
3501      the packet anywhere but to send it to the local destination. */
3502   client = silc_idlist_find_client_by_id(server->local_list, id, NULL);
3503   if (client) {
3504     silc_free(id);
3505
3506     if (client && client->data.registered == FALSE)
3507       return NULL;
3508
3509     /* If we are router and the client has router then the client is in
3510        our cell but not directly connected to us. */
3511     if (server->server_type == SILC_ROUTER && client->router) {
3512       /* We are of course in this case the client's router thus the real
3513          "router" of the client is the server who owns the client. Thus
3514          we will send the packet to that server. */
3515       *idata = (SilcIDListData)client->router;
3516       return client->router->connection;
3517     }
3518
3519     /* Seems that client really is directly connected to us */
3520     *idata = (SilcIDListData)client;
3521     return client->connection;
3522   }
3523
3524   /* Destination belongs to someone not in this server. If we are normal
3525      server our action is to send the packet to our router. */
3526   if (server->server_type == SILC_SERVER && !server->standalone) {
3527     silc_free(id);
3528     *idata = (SilcIDListData)server->router;
3529     return server->router->connection;
3530   }
3531
3532   /* We are router and we will perform route lookup for the destination 
3533      and send the packet to fastest route. */
3534   if (server->server_type == SILC_ROUTER && !server->standalone) {
3535     /* Check first that the ID is valid */
3536     client = silc_idlist_find_client_by_id(server->global_list, id, NULL);
3537     if (client) {
3538       SilcSocketConnection dst_sock;
3539
3540       dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
3541
3542       silc_free(id);
3543       *idata = (SilcIDListData)dst_sock->user_data;
3544       return dst_sock;
3545     }
3546   }
3547
3548   silc_free(id);
3549   return NULL;
3550 }
3551
3552 /* Encodes and returns channel list of channels the `client' has joined.
3553    Secret channels are not put to the list. */
3554
3555 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
3556                                                SilcClientEntry client)
3557 {
3558   SilcBuffer buffer = NULL;
3559   SilcChannelEntry channel;
3560   SilcChannelClientEntry chl;
3561   unsigned char *cid;
3562   uint16 name_len;
3563   int len;
3564
3565   silc_list_start(client->channels);
3566   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
3567     channel = chl->channel;
3568
3569     if (channel->mode & SILC_CHANNEL_MODE_SECRET)
3570       continue;
3571
3572     cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3573     name_len = strlen(channel->channel_name);
3574     
3575     len = 4 + name_len + SILC_ID_CHANNEL_LEN + 4;
3576     buffer = silc_buffer_realloc(buffer, 
3577                                  (buffer ? (buffer)->truelen + len : len));
3578     silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
3579     silc_buffer_format(buffer,
3580                        SILC_STR_UI_SHORT(name_len),
3581                        SILC_STR_UI_XNSTRING(channel->channel_name, 
3582                                             name_len),
3583                        SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
3584                        SILC_STR_UI_XNSTRING(cid, SILC_ID_CHANNEL_LEN),
3585                        SILC_STR_UI_INT(chl->mode), /* Client's mode */
3586                        SILC_STR_END);
3587     silc_buffer_pull(buffer, len);
3588     silc_free(cid);
3589   }
3590
3591   if (buffer)
3592     silc_buffer_push(buffer, buffer->data - buffer->head);
3593
3594   return buffer;
3595 }
3596
3597 /* Finds client entry by Client ID and if it is not found then resolves
3598    it using WHOIS command. */
3599
3600 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
3601                                                SilcClientID *client_id)
3602 {
3603   SilcClientEntry client;
3604
3605   client = silc_idlist_find_client_by_id(server->local_list, client_id, NULL);
3606   if (!client) {
3607     client = silc_idlist_find_client_by_id(server->global_list, 
3608                                            client_id, NULL);
3609     if (!client && server->server_type == SILC_ROUTER)
3610       return NULL;
3611   }
3612
3613   if (!client && server->standalone)
3614     return NULL;
3615
3616   if (!client || !client->nickname || !client->username) {
3617     SilcBuffer buffer, idp;
3618
3619     idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3620     buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
3621                                             ++server->cmd_ident, 1,
3622                                             3, idp->data, idp->len);
3623     silc_server_packet_send(server, client ? client->router->connection :
3624                             server->router->connection,
3625                             SILC_PACKET_COMMAND, 0,
3626                             buffer->data, buffer->len, FALSE);
3627     silc_buffer_free(idp);
3628     silc_buffer_free(buffer);
3629   }
3630
3631   return client;
3632 }
3633
3634 /* A timeout callback for the re-key. We will be the initiator of the
3635    re-key protocol. */
3636
3637 SILC_TASK_CALLBACK(silc_server_rekey_callback)
3638 {
3639   SilcSocketConnection sock = (SilcSocketConnection)context;
3640   SilcIDListData idata = (SilcIDListData)sock->user_data;
3641   SilcServer server = (SilcServer)idata->rekey->context;
3642   SilcProtocol protocol;
3643   SilcServerRekeyInternalContext *proto_ctx;
3644
3645   SILC_LOG_DEBUG(("Start"));
3646
3647   /* Allocate internal protocol context. This is sent as context
3648      to the protocol. */
3649   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
3650   proto_ctx->server = (void *)server;
3651   proto_ctx->sock = sock;
3652   proto_ctx->responder = FALSE;
3653   proto_ctx->pfs = idata->rekey->pfs;
3654       
3655   /* Perform rekey protocol. Will call the final callback after the
3656      protocol is over. */
3657   silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY, 
3658                       &protocol, proto_ctx, silc_server_rekey_final);
3659   sock->protocol = protocol;
3660       
3661   /* Run the protocol */
3662   protocol->execute(server->timeout_queue, 0, protocol, 
3663                     sock->sock, 0, 0);
3664
3665   /* Re-register re-key timeout */
3666   silc_task_register(server->timeout_queue, sock->sock, 
3667                      silc_server_rekey_callback,
3668                      context, idata->rekey->timeout, 0,
3669                      SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
3670 }
3671
3672 /* The final callback for the REKEY protocol. This will actually take the
3673    new key material into use. */
3674
3675 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
3676 {
3677   SilcProtocol protocol = (SilcProtocol)context;
3678   SilcServerRekeyInternalContext *ctx =
3679     (SilcServerRekeyInternalContext *)protocol->context;
3680   SilcServer server = (SilcServer)ctx->server;
3681   SilcSocketConnection sock = ctx->sock;
3682
3683   SILC_LOG_DEBUG(("Start"));
3684
3685   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
3686       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
3687     /* Error occured during protocol */
3688     silc_protocol_cancel(server->timeout_queue, protocol);
3689     silc_protocol_free(protocol);
3690     sock->protocol = NULL;
3691     if (ctx->keymat)
3692       silc_ske_free_key_material(ctx->keymat);
3693     if (ctx->packet)
3694       silc_packet_context_free(ctx->packet);
3695     if (ctx->ske)
3696       silc_ske_free(ctx->ske);
3697     silc_free(ctx);
3698     return;
3699   }
3700
3701   /* Take the keys into use */
3702   if (ctx->pfs == TRUE)
3703     silc_server_protocol_rekey_generate_pfs(server, ctx);
3704   else
3705     silc_server_protocol_rekey_generate(server, ctx);
3706
3707   /* Cleanup */
3708   silc_protocol_free(protocol);
3709   sock->protocol = NULL;
3710   if (ctx->keymat)
3711     silc_ske_free_key_material(ctx->keymat);
3712   if (ctx->packet)
3713     silc_packet_context_free(ctx->packet);
3714   if (ctx->ske)
3715     silc_ske_free(ctx->ske);
3716   silc_free(ctx);
3717 }