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