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