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