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
42 /* Allocates a new SILC server object. This has to be done before the server
43    can be used. After allocation one must call silc_server_init to initialize
44    the server. The new allocated server object is returned to the new_server
45    argument. */
46
47 int silc_server_alloc(SilcServer *new_server)
48 {
49   SilcServer server;
50
51   SILC_LOG_DEBUG(("Allocating new server object"));
52
53   server = silc_calloc(1, sizeof(*server));
54   server->server_type = SILC_SERVER;
55   server->standalone = TRUE;
56   server->local_list = silc_calloc(1, sizeof(*server->local_list));
57   server->global_list = silc_calloc(1, sizeof(*server->global_list));
58   server->pending_commands = silc_dlist_init();
59 #ifdef SILC_SIM
60   server->sim = silc_dlist_init();
61 #endif
62
63   *new_server = server;
64
65   return TRUE;
66 }
67
68 /* Free's the SILC server object. This is called at the very end before
69    the program ends. */
70
71 void silc_server_free(SilcServer server)
72 {
73   if (server) {
74 #ifdef SILC_SIM
75     SilcSimContext *sim;
76 #endif
77
78     if (server->local_list)
79       silc_free(server->local_list);
80     if (server->global_list)
81       silc_free(server->global_list);
82     if (server->rng)
83       silc_rng_free(server->rng);
84
85 #ifdef SILC_SIM
86     while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
87       silc_dlist_del(server->sim, sim);
88       silc_sim_free(sim);
89     }
90     silc_dlist_uninit(server->sim);
91 #endif
92
93     if (server->params)
94       silc_free(server->params);
95
96     if (server->pending_commands)
97       silc_dlist_uninit(server->pending_commands);
98
99     silc_math_primegen_uninit(); /* XXX */
100     silc_free(server);
101   }
102 }
103
104 /* Initializes the entire SILC server. This is called always before running
105    the server. This is called only once at the initialization of the program.
106    This binds the server to its listenning port. After this function returns 
107    one should call silc_server_run to start the server. This returns TRUE 
108    when everything is ok to run the server. Configuration file must be
109    read and parsed before calling this. */
110
111 int silc_server_init(SilcServer server)
112 {
113   int *sock = NULL, sock_count = 0, i;
114   SilcServerID *id;
115   SilcServerEntry id_entry;
116
117   SILC_LOG_DEBUG(("Initializing server"));
118   assert(server);
119   assert(server->config);
120
121   /* XXX After server is made as Silc Server Library this can be given
122      as argument, for now this is hard coded */
123   server->params = silc_calloc(1, sizeof(*server->params));
124   server->params->retry_count = SILC_SERVER_RETRY_COUNT;
125   server->params->retry_interval_min = SILC_SERVER_RETRY_INTERVAL_MIN;
126   server->params->retry_interval_max = SILC_SERVER_RETRY_INTERVAL_MAX;
127   server->params->retry_keep_trying = FALSE;
128   server->params->protocol_timeout = 60;
129   server->params->require_reverse_mapping = FALSE;
130
131   /* Set log files where log message should be saved. */
132   server->config->server = server;
133   silc_config_server_setlogfiles(server->config);
134  
135   /* Register all configured ciphers, PKCS and hash functions. */
136   silc_config_server_register_ciphers(server->config);
137   silc_config_server_register_pkcs(server->config);
138   silc_config_server_register_hashfuncs(server->config);
139
140   /* Initialize random number generator for the server. */
141   server->rng = silc_rng_alloc();
142   silc_rng_init(server->rng);
143   silc_math_primegen_init(); /* XXX */
144
145   /* Initialize hash functions for server to use */
146   silc_hash_alloc("md5", &server->md5hash);
147   silc_hash_alloc("sha1", &server->sha1hash);
148
149   /* Initialize none cipher */
150   silc_cipher_alloc("none", &server->none_cipher);
151
152   /* XXXXX Generate RSA key pair */
153   {
154     unsigned char *public_key;
155     unsigned char *private_key;
156     unsigned int pk_len, prv_len;
157     struct stat st;
158
159     if (stat("pubkey.pub", &st) < 0 && stat("privkey.prv", &st) < 0) {
160
161       if (silc_pkcs_alloc("rsa", &server->pkcs) == FALSE) {
162         SILC_LOG_ERROR(("Could not create RSA key pair"));
163         goto err0;
164       }
165       
166       if (server->pkcs->pkcs->init(server->pkcs->context, 
167                                    1024, server->rng) == FALSE) {
168         SILC_LOG_ERROR(("Could not generate RSA key pair"));
169         goto err0;
170       }
171       
172       public_key = server->pkcs->pkcs->get_public_key(server->pkcs->context,
173                                                       &pk_len);
174       private_key = server->pkcs->pkcs->get_private_key(server->pkcs->context,
175                                                         &prv_len);
176       
177       SILC_LOG_HEXDUMP(("public key"), public_key, pk_len);
178       SILC_LOG_HEXDUMP(("private key"), private_key, prv_len);
179       
180       server->public_key = 
181         silc_pkcs_public_key_alloc("rsa", "UN=root, HN=dummy",
182                                    public_key, pk_len);
183       server->private_key = 
184         silc_pkcs_private_key_alloc("rsa", private_key, prv_len);
185       
186       /* XXX Save keys */
187       silc_pkcs_save_public_key("pubkey.pub", server->public_key,
188                                 SILC_PKCS_FILE_PEM);
189       silc_pkcs_save_private_key("privkey.prv", server->private_key, NULL,
190                                  SILC_PKCS_FILE_BIN);
191
192       memset(public_key, 0, pk_len);
193       memset(private_key, 0, prv_len);
194       silc_free(public_key);
195       silc_free(private_key);
196     } else {
197       silc_pkcs_load_public_key("pubkey.pub", &server->public_key,
198                                 SILC_PKCS_FILE_PEM);
199       silc_pkcs_load_private_key("privkey.prv", &server->private_key,
200                                  SILC_PKCS_FILE_BIN);
201     }
202   }
203
204   /* Create a listening server. Note that our server can listen on
205      multiple ports. All listeners are created here and now. */
206   /* XXX Still check this whether to use server_info or listen_port. */
207   sock_count = 0;
208   while(server->config->listen_port) {
209     int tmp;
210
211     tmp = silc_net_create_server(server->config->listen_port->port,
212                                  server->config->listen_port->host);
213     if (tmp < 0)
214       goto err0;
215
216     sock = silc_realloc(sock, (sizeof(int *) * (sock_count + 1)));
217     sock[sock_count] = tmp;
218     server->config->listen_port = server->config->listen_port->next;
219     sock_count++;
220   }
221
222   /* Initialize ID caches */
223   server->local_list->clients = silc_idcache_alloc(0);
224   server->local_list->servers = silc_idcache_alloc(0);
225   server->local_list->channels = silc_idcache_alloc(0);
226
227   /* These are allocated for normal server as well as these hold some 
228      global information that the server has fetched from its router. For 
229      router these are used as they are supposed to be used on router. */
230   server->global_list->clients = silc_idcache_alloc(0);
231   server->global_list->servers = silc_idcache_alloc(0);
232   server->global_list->channels = silc_idcache_alloc(0);
233
234   /* Allocate the entire socket list that is used in server. Eventually 
235      all connections will have entry in this table (it is a table of 
236      pointers to the actual object that is allocated individually 
237      later). */
238   server->sockets = silc_calloc(SILC_SERVER_MAX_CONNECTIONS,
239                                 sizeof(*server->sockets));
240
241   for (i = 0; i < sock_count; i++) {
242     SilcSocketConnection newsocket = NULL;
243
244     /* Set socket to non-blocking mode */
245     silc_net_set_socket_nonblock(sock[i]);
246     server->sock = sock[i];
247     
248     /* Create a Server ID for the server. */
249     silc_id_create_server_id(sock[i], server->rng, &id);
250     if (!id) {
251       goto err0;
252     }
253     
254     server->id = id;
255     server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
256     server->id_string_len = silc_id_get_len(SILC_ID_SERVER);
257     server->id_type = SILC_ID_SERVER;
258     server->server_name = server->config->server_info->server_name;
259
260     /* Add ourselves to the server list. We don't have a router yet 
261        beacuse we haven't established a route yet. It will be done later. 
262        For now, NULL is sent as router. This allocates new entry to
263        the ID list. */
264     id_entry = 
265       silc_idlist_add_server(server->local_list,
266                              server->config->server_info->server_name,
267                              server->server_type, server->id, NULL, NULL);
268     if (!id_entry) {
269       SILC_LOG_ERROR(("Could not add ourselves to cache"));
270       goto err0;
271     }
272     
273     /* Add ourselves also to the socket table. The entry allocated above
274        is sent as argument for fast referencing in the future. */
275     silc_socket_alloc(sock[i], SILC_SOCKET_TYPE_SERVER, id_entry, 
276                       &newsocket);
277     if (!newsocket)
278       goto err0;
279
280     server->sockets[sock[i]] = newsocket;
281
282     /* Put the allocated socket pointer also to the entry allocated above 
283        for fast back-referencing to the socket list. */
284     id_entry->connection = (void *)server->sockets[sock[i]];
285     server->id_entry = id_entry;
286   }
287
288   /* Register the task queues. In SILC we have by default three task queues. 
289      One task queue for non-timeout tasks which perform different kind of 
290      I/O on file descriptors, timeout task queue for timeout tasks, and,
291      generic non-timeout task queue whose tasks apply to all connections. */
292   silc_task_queue_alloc(&server->io_queue, TRUE);
293   if (!server->io_queue) {
294     goto err0;
295   }
296   silc_task_queue_alloc(&server->timeout_queue, TRUE);
297   if (!server->timeout_queue) {
298     goto err1;
299   }
300   silc_task_queue_alloc(&server->generic_queue, TRUE);
301   if (!server->generic_queue) {
302     goto err1;
303   }
304
305   /* Register protocols */
306   silc_server_protocols_register();
307
308   /* Initialize the scheduler */
309   silc_schedule_init(&server->io_queue, &server->timeout_queue, 
310                      &server->generic_queue, 
311                      SILC_SERVER_MAX_CONNECTIONS);
312   
313   /* Add the first task to the queue. This is task that is executed by
314      timeout. It expires as soon as the caller calls silc_server_run. This
315      task performs authentication protocol and key exchange with our
316      primary router. */
317   silc_task_register(server->timeout_queue, sock[0], 
318                      silc_server_connect_to_router,
319                      (void *)server, 0, 1,
320                      SILC_TASK_TIMEOUT,
321                      SILC_TASK_PRI_NORMAL);
322
323   /* Add listener task to the queue. This task receives new connections to the 
324      server. This task remains on the queue until the end of the program. */
325   silc_task_register(server->io_queue, sock[0],
326                      silc_server_accept_new_connection,
327                      (void *)server, 0, 0, 
328                      SILC_TASK_FD,
329                      SILC_TASK_PRI_NORMAL);
330   server->listenning = TRUE;
331
332   /* If server connections has been configured then we must be router as
333      normal server cannot have server connections, only router connections. */
334   if (server->config->servers)
335     server->server_type = SILC_ROUTER;
336
337   SILC_LOG_DEBUG(("Server initialized"));
338
339   /* We are done here, return succesfully */
340   return TRUE;
341
342   silc_task_queue_free(server->timeout_queue);
343  err1:
344   silc_task_queue_free(server->io_queue);
345  err0:
346   for (i = 0; i < sock_count; i++)
347     silc_net_close_server(sock[i]);
348
349   return FALSE;
350 }
351
352 /* Fork server to background and set gid+uid to non-root.
353    Silcd will not run as root, so trying to set either user or group to
354    root will cause silcd to exit. */
355
356 void silc_server_daemonise(SilcServer server)
357 {
358   /* Are we executing silcd as root or a regular user? */
359   if (geteuid()==0) {
360     
361     struct passwd *pw;
362     struct group *gr;
363     char *user, *group;
364     
365     if (!server->config->identity || !server->config->identity->user || 
366         !server->config->identity->group) {
367       fprintf(stderr, "Error:"
368        "\tSILC server must not be run as root.  For the security of your\n"
369        "\tsystem it is strongly suggested that you run SILC under dedicated\n"
370        "\tuser account.  Modify the [Identity] configuration section to run\n"
371        "\tthe server as non-root user.\n");
372       exit(1);
373     }
374     
375     /* Get the values given for user and group in configuration file */
376     user=server->config->identity->user;
377     group=server->config->identity->group;
378     
379     /* Check whether the user/group information is text */ 
380     if (atoi(user)!=0 || atoi(group)!=0) {
381       SILC_LOG_DEBUG(("Invalid user and/or group information"));
382       SILC_LOG_DEBUG(("User and/or group given as number"));
383       fprintf(stderr, "Invalid user and/or group information\n");
384       fprintf(stderr, "Please assign them as names, not numbers\n");
385       exit(1);
386     }
387     
388     /* Catch the nasty incident of string "0" returning 0 from atoi */
389     if (strcmp("0", user)==0 || strcmp("0", group)==0) {
390       SILC_LOG_DEBUG(("User and/or group configured to 0. Unacceptable"));
391       fprintf(stderr, "User and/or group configured to 0. Exiting\n");
392       exit(1);
393     }
394     
395     pw=getpwnam(user);
396     gr=getgrnam(group);
397
398     if (!pw) {
399       fprintf(stderr, "No such user %s found\n", user);
400       exit(1);
401     }
402
403     if (!gr) {
404       fprintf(stderr, "No such group %s found\n", group);
405       exit(1);
406     }
407     
408     /* Check whether user and/or group is set to root. If yes, exit
409        immediately. Otherwise, setgid and setuid server to user.group */
410     if (gr->gr_gid==0 || pw->pw_uid==0) {
411       fprintf(stderr, "Error:"
412        "\tSILC server must not be run as root.  For the security of your\n"
413        "\tsystem it is strongly suggested that you run SILC under dedicated\n"
414        "\tuser account.  Modify the [Identity] configuration section to run\n"
415        "\tthe server as non-root user.\n");
416       exit(1);
417     } else {
418       /* Fork server to background, making it a daemon */
419       if (fork()) {
420         SILC_LOG_DEBUG(("Server started as root. Dropping privileges."));
421         SILC_LOG_DEBUG(("Forking SILC server to background"));
422         exit(0);
423       } 
424       setsid();
425       
426       SILC_LOG_DEBUG(("Changing to group %s", group));
427       if(setgid(gr->gr_gid)==0) {
428         SILC_LOG_DEBUG(("Setgid to %s", group));
429       } else {
430         SILC_LOG_DEBUG(("Setgid to %s failed", group));
431         fprintf(stderr, "Tried to setgid %s but no such group. Exiting\n",
432                 group);
433         exit(1);
434       }
435       SILC_LOG_DEBUG(("Changing to user nobody"));
436       if(setuid(pw->pw_uid)==0) {
437         SILC_LOG_DEBUG(("Setuid to %s", user));
438       } else {
439         SILC_LOG_DEBUG(("Setuid to %s failed", user));
440         fprintf(stderr, "Tried to setuid %s but no such user. Exiting\n",
441                 user);
442         exit(1);
443       }
444     }
445   } else {
446     /* Fork server to background, making it a daemon */
447     if (fork()) {
448       SILC_LOG_DEBUG(("Server started as user")); 
449       SILC_LOG_DEBUG(("Forking SILC server to background"));
450       exit(0);
451     }
452     setsid();
453   }
454 }
455
456 /* Stops the SILC server. This function is used to shutdown the server. 
457    This is usually called after the scheduler has returned. After stopping 
458    the server one should call silc_server_free. */
459
460 void silc_server_stop(SilcServer server)
461 {
462   SILC_LOG_DEBUG(("Stopping server"));
463
464   /* Stop the scheduler, although it might be already stopped. This
465      doesn't hurt anyone. This removes all the tasks and task queues,
466      as well. */
467   silc_schedule_stop();
468   silc_schedule_uninit();
469
470   silc_server_protocols_unregister();
471
472   SILC_LOG_DEBUG(("Server stopped"));
473 }
474
475 /* The heart of the server. This runs the scheduler thus runs the server. 
476    When this returns the server has been stopped and the program will
477    be terminated. */
478
479 void silc_server_run(SilcServer server)
480 {
481   SILC_LOG_DEBUG(("Running server"));
482
483   /* Start the scheduler, the heart of the SILC server. When this returns
484      the program will be terminated. */
485   silc_schedule();
486 }
487
488 /* Timeout callback that will be called to retry connecting to remote
489    router. This is used by both normal and router server. This will wait
490    before retrying the connecting. The timeout is generated by exponential
491    backoff algorithm. */
492
493 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
494 {
495   SilcServerConnection sconn = (SilcServerConnection)context;
496   SilcServer server = sconn->server;
497
498   SILC_LOG_INFO(("Retrying connecting to a router"));
499
500   /* Calculate next timeout */
501   if (sconn->retry_count >= 1) {
502     sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
503     if (sconn->retry_timeout > SILC_SERVER_RETRY_INTERVAL_MAX)
504       sconn->retry_timeout = SILC_SERVER_RETRY_INTERVAL_MAX;
505   } else {
506     sconn->retry_timeout = server->params->retry_interval_min;
507   }
508   sconn->retry_count++;
509   sconn->retry_timeout = sconn->retry_timeout +
510     silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
511
512   /* If we've reached max retry count, give up. */
513   if (sconn->retry_count > server->params->retry_count && 
514       server->params->retry_keep_trying == FALSE) {
515     SILC_LOG_ERROR(("Could not connect to router, giving up"));
516     return;
517   }
518
519   /* Wait one before retrying */
520   silc_task_register(server->timeout_queue, fd, silc_server_connect_router,
521                      context, sconn->retry_timeout, 
522                      server->params->retry_interval_min_usec,
523                      SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
524 }
525
526 /* Generic routine to use connect to a router. */
527
528 SILC_TASK_CALLBACK(silc_server_connect_router)
529 {    
530   SilcServerConnection sconn = (SilcServerConnection)context;
531   SilcServer server = sconn->server;
532   SilcSocketConnection newsocket;
533   SilcProtocol protocol;
534   SilcServerKEInternalContext *proto_ctx;
535   int sock;
536
537   /* Connect to remote host */
538   sock = silc_net_create_connection(sconn->remote_port, 
539                                     sconn->remote_host);
540   if (sock < 0) {
541     SILC_LOG_ERROR(("Could not connect to router"));
542     silc_task_register(server->timeout_queue, fd, 
543                        silc_server_connect_to_router_retry,
544                        context, 0, 1, SILC_TASK_TIMEOUT, 
545                        SILC_TASK_PRI_NORMAL);
546     return;
547   }
548
549   /* Set socket options */
550   silc_net_set_socket_nonblock(sock);
551   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
552
553   /* Create socket connection for the connection. Even though we
554      know that we are connecting to a router we will mark the socket
555      to be unknown connection until we have executed authentication
556      protocol. */
557   silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
558   server->sockets[sock] = newsocket;
559   newsocket->hostname = strdup(sconn->remote_host);
560   newsocket->ip = strdup(sconn->remote_host);
561   newsocket->port = sconn->remote_port;
562   sconn->sock = newsocket;
563
564   /* Allocate internal protocol context. This is sent as context
565      to the protocol. */
566   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
567   proto_ctx->server = (void *)server;
568   proto_ctx->context = (void *)sconn;
569   proto_ctx->sock = newsocket;
570   proto_ctx->rng = server->rng;
571   proto_ctx->responder = FALSE;
572       
573   /* Perform key exchange protocol. silc_server_connect_to_router_second
574      will be called after the protocol is finished. */
575   silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE, 
576                       &protocol, proto_ctx,
577                       silc_server_connect_to_router_second);
578   newsocket->protocol = protocol;
579       
580   /* Register a timeout task that will be executed if the protocol
581      is not executed within set limit. */
582   proto_ctx->timeout_task = 
583     silc_task_register(server->timeout_queue, sock, 
584                        silc_server_timeout_remote,
585                        server, server->params->protocol_timeout,
586                        server->params->protocol_timeout_usec,
587                        SILC_TASK_TIMEOUT,
588                        SILC_TASK_PRI_LOW);
589
590   /* Register the connection for network input and output. This sets
591      that scheduler will listen for incoming packets for this connection 
592      and sets that outgoing packets may be sent to this connection as 
593      well. However, this doesn't set the scheduler for outgoing traffic,
594      it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
595      later when outgoing data is available. */
596   context = (void *)server;
597   SILC_REGISTER_CONNECTION_FOR_IO(sock);
598   
599   /* Run the protocol */
600   protocol->execute(server->timeout_queue, 0, protocol, sock, 0, 0);
601 }
602   
603 /* This function connects to our primary router or if we are a router this
604    establishes all our primary routes. This is called at the start of the
605    server to do authentication and key exchange with our router - called
606    from schedule. */
607
608 SILC_TASK_CALLBACK(silc_server_connect_to_router)
609 {
610   SilcServer server = (SilcServer)context;
611   SilcServerConnection sconn;
612
613   SILC_LOG_DEBUG(("Connecting to router(s)"));
614
615   /* If we are normal SILC server we need to connect to our cell's
616      router. */
617   if (server->server_type == SILC_SERVER) {
618     SILC_LOG_DEBUG(("We are normal server"));
619
620     /* Create connection to the router, if configured. */
621     if (server->config->routers) {
622
623       /* Allocate connection object for hold connection specific stuff. */
624       sconn = silc_calloc(1, sizeof(*sconn));
625       sconn->server = server;
626       sconn->remote_host = server->config->routers->host;
627       sconn->remote_port = server->config->routers->port;
628
629       silc_task_register(server->timeout_queue, fd, 
630                          silc_server_connect_router,
631                          (void *)sconn, 0, 1, SILC_TASK_TIMEOUT, 
632                          SILC_TASK_PRI_NORMAL);
633       return;
634     }
635   }
636
637   /* If we are a SILC router we need to establish all of our primary
638      routes. */
639   if (server->server_type == SILC_ROUTER) {
640     SilcConfigServerSectionServerConnection *ptr;
641
642     SILC_LOG_DEBUG(("We are router"));
643
644     /* Create the connections to all our routes */
645     ptr = server->config->routers;
646     while (ptr) {
647
648       SILC_LOG_DEBUG(("Router connection [%s] %s:%d",
649                       ptr->initiator ? "Initiator" : "Responder",
650                       ptr->host, ptr->port));
651
652       if (ptr->initiator) {
653         /* Allocate connection object for hold connection specific stuff. */
654         sconn = silc_calloc(1, sizeof(*sconn));
655         sconn->server = server;
656         sconn->remote_host = ptr->host;
657         sconn->remote_port = ptr->port;
658
659         silc_task_register(server->timeout_queue, fd, 
660                            silc_server_connect_router,
661                            (void *)sconn, 0, 1, SILC_TASK_TIMEOUT, 
662                            SILC_TASK_PRI_NORMAL);
663       }
664
665       if (!ptr->next)
666         return;
667
668       ptr = ptr->next;
669     }
670   }
671
672   SILC_LOG_DEBUG(("No router(s), server will be standalone"));
673   
674   /* There wasn't a configured router, we will continue but we don't
675      have a connection to outside world.  We will be standalone server. */
676   server->standalone = TRUE;
677 }
678
679 /* Second part of connecting to router(s). Key exchange protocol has been
680    executed and now we will execute authentication protocol. */
681
682 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
683 {
684   SilcProtocol protocol = (SilcProtocol)context;
685   SilcServerKEInternalContext *ctx = 
686     (SilcServerKEInternalContext *)protocol->context;
687   SilcServer server = (SilcServer)ctx->server;
688   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
689   SilcSocketConnection sock = NULL;
690   SilcServerConnAuthInternalContext *proto_ctx;
691
692   SILC_LOG_DEBUG(("Start"));
693
694   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
695     /* Error occured during protocol */
696     silc_protocol_free(protocol);
697     if (ctx->packet)
698       silc_packet_context_free(ctx->packet);
699     if (ctx->ske)
700       silc_ske_free(ctx->ske);
701     if (ctx->dest_id)
702       silc_free(ctx->dest_id);
703     silc_free(ctx);
704     sock->protocol = NULL;
705     silc_server_disconnect_remote(server, sock, "Server closed connection: "
706                                   "Key exchange failed");
707     return;
708   }
709   
710   /* Allocate internal context for the authentication protocol. This
711      is sent as context for the protocol. */
712   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
713   proto_ctx->server = (void *)server;
714   proto_ctx->context = (void *)sconn;
715   proto_ctx->sock = sock = server->sockets[fd];
716   proto_ctx->ske = ctx->ske;       /* Save SKE object from previous protocol */
717   proto_ctx->dest_id_type = ctx->dest_id_type;
718   proto_ctx->dest_id = ctx->dest_id;
719
720   /* Resolve the authentication method used in this connection */
721   proto_ctx->auth_meth = SILC_PROTOCOL_CONN_AUTH_PASSWORD;
722   if (server->config->routers) {
723     SilcConfigServerSectionServerConnection *conn = NULL;
724
725     /* Check if we find a match from user configured connections */
726     conn = silc_config_server_find_router_conn(server->config,
727                                                sock->hostname,
728                                                sock->port);
729     if (conn) {
730       /* Match found. Use the configured authentication method */
731       proto_ctx->auth_meth = conn->auth_meth;
732       if (conn->auth_data) {
733         proto_ctx->auth_data = strdup(conn->auth_data);
734         proto_ctx->auth_data_len = strlen(conn->auth_data);
735       }
736     } else {
737       /* No match found. */
738       /* XXX */
739     }
740   } else {
741     /* XXX */
742   }
743
744   /* Free old protocol as it is finished now */
745   silc_protocol_free(protocol);
746   if (ctx->packet)
747     silc_packet_context_free(ctx->packet);
748   silc_free(ctx);
749   sock->protocol = NULL;
750
751   /* Allocate the authentication protocol. This is allocated here
752      but we won't start it yet. We will be receiving party of this
753      protocol thus we will wait that connecting party will make
754      their first move. */
755   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH, 
756                       &sock->protocol, proto_ctx, 
757                       silc_server_connect_to_router_final);
758
759   /* Register timeout task. If the protocol is not executed inside
760      this timelimit the connection will be terminated. Currently
761      this is 15 seconds and is hard coded limit (XXX). */
762   proto_ctx->timeout_task = 
763     silc_task_register(server->timeout_queue, sock->sock, 
764                        silc_server_timeout_remote,
765                        (void *)server, 15, 0,
766                        SILC_TASK_TIMEOUT,
767                        SILC_TASK_PRI_LOW);
768
769   /* Run the protocol */
770   sock->protocol->execute(server->timeout_queue, 0, 
771                           sock->protocol, sock->sock, 0, 0);
772 }
773
774 /* Finalizes the connection to router. Registers a server task to the
775    queue so that we can accept new connections. */
776
777 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
778 {
779   SilcProtocol protocol = (SilcProtocol)context;
780   SilcServerConnAuthInternalContext *ctx = 
781     (SilcServerConnAuthInternalContext *)protocol->context;
782   SilcServer server = (SilcServer)ctx->server;
783   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
784   SilcSocketConnection sock = ctx->sock;
785   SilcServerEntry id_entry;
786   SilcBuffer packet;
787   SilcServerHBContext hb_context;
788   unsigned char *id_string;
789
790   SILC_LOG_DEBUG(("Start"));
791
792   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
793     /* Error occured during protocol */
794     if (ctx->dest_id)
795       silc_free(ctx->dest_id);
796     silc_server_disconnect_remote(server, sock, "Server closed connection: "
797                                   "Authentication failed");
798     goto out;
799   }
800
801   /* Add a task to the queue. This task receives new connections to the 
802      server. This task remains on the queue until the end of the program. */
803   if (!server->listenning) {
804     silc_task_register(server->io_queue, server->sock, 
805                        silc_server_accept_new_connection,
806                        (void *)server, 0, 0, 
807                        SILC_TASK_FD,
808                        SILC_TASK_PRI_NORMAL);
809     server->listenning = TRUE;
810   }
811
812   /* Send NEW_SERVER packet to the router. We will become registered
813      to the SILC network after sending this packet. */
814   id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
815   packet = silc_buffer_alloc(2 + 2 + SILC_ID_SERVER_LEN + 
816                              strlen(server->server_name));
817   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
818   silc_buffer_format(packet,
819                      SILC_STR_UI_SHORT(SILC_ID_SERVER_LEN),
820                      SILC_STR_UI_XNSTRING(id_string, SILC_ID_SERVER_LEN),
821                      SILC_STR_UI_SHORT(strlen(server->server_name)),
822                      SILC_STR_UI_XNSTRING(server->server_name,
823                                           strlen(server->server_name)),
824                      SILC_STR_END);
825
826   /* Send the packet */
827   silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
828                           packet->data, packet->len, TRUE);
829   silc_buffer_free(packet);
830   silc_free(id_string);
831
832   SILC_LOG_DEBUG(("Connected to router %s", sock->hostname));
833
834   /* Add the connected router to local server list */
835   server->standalone = FALSE;
836   id_entry = silc_idlist_add_server(server->local_list, sock->hostname,
837                                     SILC_ROUTER, ctx->dest_id, NULL, sock);
838   if (!id_entry) {
839     if (ctx->dest_id)
840       silc_free(ctx->dest_id);
841     silc_server_disconnect_remote(server, sock, "Server closed connection: "
842                                   "Authentication failed");
843     goto out;
844   }
845
846   silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
847   silc_free(sock->user_data);
848   sock->user_data = (void *)id_entry;
849   sock->type = SILC_SOCKET_TYPE_ROUTER;
850   server->id_entry->router = id_entry;
851   server->router = id_entry;
852   server->router->data.registered = TRUE;
853
854   /* Perform keepalive. The `hb_context' will be freed automatically
855      when finally calling the silc_socket_free function. XXX hardcoded 
856      timeout!! */
857   hb_context = silc_calloc(1, sizeof(*hb_context));
858   hb_context->server = server;
859   silc_socket_set_heartbeat(sock, 600, hb_context,
860                             silc_server_perform_heartbeat,
861                             server->timeout_queue);
862
863   /* If we are router then announce our possible servers. */
864   if (server->server_type == SILC_ROUTER)
865     silc_server_announce_servers(server);
866
867   /* Announce our clients and channels to the router */
868   silc_server_announce_clients(server);
869   silc_server_announce_channels(server);
870
871  out:
872   /* Free the temporary connection data context */
873   if (sconn)
874     silc_free(sconn);
875
876   /* Free the protocol object */
877   silc_protocol_free(protocol);
878   if (ctx->packet)
879     silc_packet_context_free(ctx->packet);
880   if (ctx->ske)
881     silc_ske_free(ctx->ske);
882   silc_free(ctx);
883   sock->protocol = NULL;
884 }
885
886 /* Accepts new connections to the server. Accepting new connections are
887    done in three parts to make it async. */
888
889 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
890 {
891   SilcServer server = (SilcServer)context;
892   SilcSocketConnection newsocket;
893   SilcServerKEInternalContext *proto_ctx;
894   int sock;
895
896   SILC_LOG_DEBUG(("Accepting new connection"));
897
898   server->stat.conn_attempts++;
899
900   sock = silc_net_accept_connection(server->sock);
901   if (sock < 0) {
902     SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
903     server->stat.conn_failures++;
904     return;
905   }
906
907   /* Check max connections */
908   if (sock > SILC_SERVER_MAX_CONNECTIONS) {
909     if (server->config->redirect) {
910       /* XXX Redirecting connection to somewhere else now?? */
911       /*silc_server_send_notify("Server is full, trying to redirect..."); */
912     } else {
913       SILC_LOG_ERROR(("Refusing connection, server is full"));
914       server->stat.conn_failures++;
915     }
916     return;
917   }
918
919   /* Set socket options */
920   silc_net_set_socket_nonblock(sock);
921   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
922
923   /* We don't create a ID yet, since we don't know what type of connection
924      this is yet. But, we do add the connection to the socket table. */
925   silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
926   server->sockets[sock] = newsocket;
927
928   /* XXX This MUST be done async as this will block the entire server
929      process. Either we have to do our own resolver stuff or in the future
930      we can use threads. */
931   /* Perform name and address lookups for the remote host. */
932   silc_net_check_host_by_sock(sock, &newsocket->hostname, &newsocket->ip);
933   if ((server->params->require_reverse_mapping && !newsocket->hostname) ||
934       !newsocket->ip) {
935     SILC_LOG_ERROR(("IP/DNS lookup failed"));
936     server->stat.conn_failures++;
937     return;
938   }
939   if (!newsocket->hostname)
940     newsocket->hostname = strdup(newsocket->ip);
941
942   SILC_LOG_INFO(("Incoming connection from %s (%s)", newsocket->hostname,
943                  newsocket->ip));
944
945   /* Allocate internal context for key exchange protocol. This is
946      sent as context for the protocol. */
947   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
948   proto_ctx->server = context;
949   proto_ctx->sock = newsocket;
950   proto_ctx->rng = server->rng;
951   proto_ctx->responder = TRUE;
952
953   /* Prepare the connection for key exchange protocol. We allocate the
954      protocol but will not start it yet. The connector will be the
955      initiator of the protocol thus we will wait for initiation from 
956      there before we start the protocol. */
957   server->stat.auth_attempts++;
958   silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE, 
959                       &newsocket->protocol, proto_ctx, 
960                       silc_server_accept_new_connection_second);
961
962   /* Register a timeout task that will be executed if the connector
963      will not start the key exchange protocol within 60 seconds. For
964      now, this is a hard coded limit. After 60 secs the connection will
965      be closed if the key exchange protocol has not been started. */
966   proto_ctx->timeout_task = 
967     silc_task_register(server->timeout_queue, newsocket->sock, 
968                        silc_server_timeout_remote,
969                        context, 60, 0,
970                        SILC_TASK_TIMEOUT,
971                        SILC_TASK_PRI_LOW);
972
973   /* Register the connection for network input and output. This sets
974      that scheduler will listen for incoming packets for this connection 
975      and sets that outgoing packets may be sent to this connection as well.
976      However, this doesn't set the scheduler for outgoing traffic, it
977      will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
978      later when outgoing data is available. */
979   SILC_REGISTER_CONNECTION_FOR_IO(sock);
980 }
981
982 /* Second part of accepting new connection. Key exchange protocol has been
983    performed and now it is time to do little connection authentication
984    protocol to figure out whether this connection is client or server
985    and whether it has right to access this server (especially server
986    connections needs to be authenticated). */
987
988 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
989 {
990   SilcProtocol protocol = (SilcProtocol)context;
991   SilcServerKEInternalContext *ctx = 
992     (SilcServerKEInternalContext *)protocol->context;
993   SilcServer server = (SilcServer)ctx->server;
994   SilcSocketConnection sock = NULL;
995   SilcServerConnAuthInternalContext *proto_ctx;
996
997   SILC_LOG_DEBUG(("Start"));
998
999   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
1000     /* Error occured during protocol */
1001     silc_protocol_free(protocol);
1002     if (ctx->packet)
1003       silc_packet_context_free(ctx->packet);
1004     if (ctx->ske)
1005       silc_ske_free(ctx->ske);
1006     if (ctx->dest_id)
1007       silc_free(ctx->dest_id);
1008     silc_free(ctx);
1009     if (sock)
1010       sock->protocol = NULL;
1011     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1012                                   "Key exchange failed");
1013     server->stat.auth_failures++;
1014     return;
1015   }
1016
1017   /* Allocate internal context for the authentication protocol. This
1018      is sent as context for the protocol. */
1019   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1020   proto_ctx->server = (void *)server;
1021   proto_ctx->sock = sock = server->sockets[fd];
1022   proto_ctx->ske = ctx->ske;    /* Save SKE object from previous protocol */
1023   proto_ctx->responder = TRUE;
1024   proto_ctx->dest_id_type = ctx->dest_id_type;
1025   proto_ctx->dest_id = ctx->dest_id;
1026
1027   /* Free old protocol as it is finished now */
1028   silc_protocol_free(protocol);
1029   if (ctx->packet)
1030     silc_packet_context_free(ctx->packet);
1031   silc_free(ctx);
1032   sock->protocol = NULL;
1033
1034   /* Allocate the authentication protocol. This is allocated here
1035      but we won't start it yet. We will be receiving party of this
1036      protocol thus we will wait that connecting party will make
1037      their first move. */
1038   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH, 
1039                       &sock->protocol, proto_ctx, 
1040                       silc_server_accept_new_connection_final);
1041
1042   /* Register timeout task. If the protocol is not executed inside
1043      this timelimit the connection will be terminated. Currently
1044      this is 60 seconds and is hard coded limit (XXX). */
1045   proto_ctx->timeout_task = 
1046     silc_task_register(server->timeout_queue, sock->sock, 
1047                        silc_server_timeout_remote,
1048                        (void *)server, 60, 0,
1049                        SILC_TASK_TIMEOUT,
1050                        SILC_TASK_PRI_LOW);
1051 }
1052
1053 /* Final part of accepting new connection. The connection has now
1054    been authenticated and keys has been exchanged. We also know whether
1055    this is client or server connection. */
1056
1057 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1058 {
1059   SilcProtocol protocol = (SilcProtocol)context;
1060   SilcServerConnAuthInternalContext *ctx = 
1061     (SilcServerConnAuthInternalContext *)protocol->context;
1062   SilcServer server = (SilcServer)ctx->server;
1063   SilcSocketConnection sock = ctx->sock;
1064   SilcServerHBContext hb_context;
1065   void *id_entry = NULL;
1066
1067   SILC_LOG_DEBUG(("Start"));
1068
1069   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
1070     /* Error occured during protocol */
1071     silc_protocol_free(protocol);
1072     if (ctx->packet)
1073       silc_packet_context_free(ctx->packet);
1074     if (ctx->ske)
1075       silc_ske_free(ctx->ske);
1076     if (ctx->dest_id)
1077       silc_free(ctx->dest_id);
1078     silc_free(ctx);
1079     if (sock)
1080       sock->protocol = NULL;
1081     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1082                                   "Authentication failed");
1083     server->stat.auth_failures++;
1084     return;
1085   }
1086
1087   sock->type = ctx->conn_type;
1088   switch(sock->type) {
1089   case SILC_SOCKET_TYPE_CLIENT:
1090     {
1091       SilcClientEntry client;
1092
1093       SILC_LOG_DEBUG(("Remote host is client"));
1094       SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
1095                      sock->ip));
1096
1097       /* Add the client to the client ID cache. The nickname and Client ID
1098          and other information is created after we have received NEW_CLIENT
1099          packet from client. */
1100       client = silc_idlist_add_client(server->local_list, 
1101                                       NULL, NULL, NULL, NULL, NULL, sock);
1102       if (!client) {
1103         SILC_LOG_ERROR(("Could not add new client to cache"));
1104         silc_free(sock->user_data);
1105         break;
1106       }
1107
1108       /* Statistics */
1109       server->stat.my_clients++;
1110       server->stat.clients++;
1111       if (server->server_type == SILC_ROUTER)
1112         server->stat.cell_clients++;
1113
1114       id_entry = (void *)client;
1115       break;
1116     }
1117   case SILC_SOCKET_TYPE_SERVER:
1118   case SILC_SOCKET_TYPE_ROUTER:
1119     {
1120       SilcServerEntry new_server;
1121
1122       SILC_LOG_DEBUG(("Remote host is %s", 
1123                       sock->type == SILC_SOCKET_TYPE_SERVER ? 
1124                       "server" : "router"));
1125       SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
1126                      sock->ip, sock->type == SILC_SOCKET_TYPE_SERVER ? 
1127                      "server" : "router"));
1128
1129       /* Add the server into server cache. The server name and Server ID
1130          is updated after we have received NEW_SERVER packet from the
1131          server. We mark ourselves as router for this server if we really
1132          are router. */
1133       new_server = 
1134         silc_idlist_add_server(server->local_list, NULL,
1135                                sock->type == SILC_SOCKET_TYPE_SERVER ?
1136                                SILC_SERVER : SILC_ROUTER, NULL, 
1137                                sock->type == SILC_SOCKET_TYPE_SERVER ?
1138                                server->id_entry : NULL, sock);
1139       if (!new_server) {
1140         SILC_LOG_ERROR(("Could not add new server to cache"));
1141         silc_free(sock->user_data);
1142         break;
1143       }
1144
1145       /* Statistics */
1146       if (sock->type == SILC_SOCKET_TYPE_SERVER)
1147         server->stat.my_servers++;
1148       else
1149         server->stat.my_routers++;
1150       server->stat.servers++;
1151
1152       id_entry = (void *)new_server;
1153       
1154       /* There is connection to other server now, if it is router then
1155          we will have connection to outside world.  If we are router but
1156          normal server connected to us then we will remain standalone,
1157          if we are standlone. */
1158       if (server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER) {
1159         SILC_LOG_DEBUG(("We are not standalone server anymore"));
1160         server->standalone = FALSE;
1161         if (!server->id_entry->router) {
1162           server->id_entry->router = id_entry;
1163           server->router = id_entry;
1164         }
1165       }
1166       break;
1167     }
1168   default:
1169     break;
1170   }
1171
1172   /* Add the common data structure to the ID entry. */
1173   if (id_entry)
1174     silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1175       
1176   /* Add to sockets internal pointer for fast referencing */
1177   silc_free(sock->user_data);
1178   sock->user_data = id_entry;
1179
1180   /* Connection has been fully established now. Everything is ok. */
1181   SILC_LOG_DEBUG(("New connection authenticated"));
1182
1183   /* Perform keepalive. The `hb_context' will be freed automatically
1184      when finally calling the silc_socket_free function. XXX hardcoded 
1185      timeout!! */
1186   hb_context = silc_calloc(1, sizeof(*hb_context));
1187   hb_context->server = server;
1188   silc_socket_set_heartbeat(sock, 600, hb_context,
1189                             silc_server_perform_heartbeat,
1190                             server->timeout_queue);
1191
1192   silc_protocol_free(protocol);
1193   if (ctx->packet)
1194     silc_packet_context_free(ctx->packet);
1195   if (ctx->ske)
1196     silc_ske_free(ctx->ske);
1197   if (ctx->dest_id)
1198     silc_free(ctx->dest_id);
1199   silc_free(ctx);
1200   sock->protocol = NULL;
1201 }
1202
1203 /* This function is used to read packets from network and send packets to
1204    network. This is usually a generic task. */
1205
1206 SILC_TASK_CALLBACK(silc_server_packet_process)
1207 {
1208   SilcServer server = (SilcServer)context;
1209   SilcSocketConnection sock = server->sockets[fd];
1210   SilcIDListData idata;
1211   SilcCipher cipher = NULL;
1212   SilcHmac hmac = NULL;
1213   int ret;
1214
1215   if (!sock)
1216     return;
1217
1218   SILC_LOG_DEBUG(("Processing packet"));
1219
1220   /* Packet sending */
1221
1222   if (type == SILC_TASK_WRITE) {
1223     server->stat.packets_sent++;
1224
1225     if (sock->outbuf->data - sock->outbuf->head)
1226       silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1227
1228     ret = silc_server_packet_send_real(server, sock, TRUE);
1229
1230     /* If returned -2 could not write to connection now, will do
1231        it later. */
1232     if (ret == -2)
1233       return;
1234
1235     if (ret == -1)
1236       return;
1237     
1238     /* The packet has been sent and now it is time to set the connection
1239        back to only for input. When there is again some outgoing data 
1240        available for this connection it will be set for output as well. 
1241        This call clears the output setting and sets it only for input. */
1242     SILC_SET_CONNECTION_FOR_INPUT(fd);
1243     SILC_UNSET_OUTBUF_PENDING(sock);
1244
1245     silc_buffer_clear(sock->outbuf);
1246     return;
1247   }
1248
1249   /* Packet receiving */
1250
1251   /* Read some data from connection */
1252   ret = silc_packet_receive(sock);
1253   if (ret < 0)
1254     return;
1255     
1256   /* EOF */
1257   if (ret == 0) {
1258     SILC_LOG_DEBUG(("Read EOF"));
1259       
1260     /* If connection is disconnecting already we will finally
1261        close the connection */
1262     if (SILC_IS_DISCONNECTING(sock)) {
1263       if (sock->user_data)
1264         silc_server_free_sock_user_data(server, sock);
1265       silc_server_close_connection(server, sock);
1266       return;
1267     }
1268       
1269     SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1270
1271     /* If the closed connection was our primary router connection the
1272        start re-connecting phase. */
1273     if (!server->standalone && server->server_type == SILC_SERVER && 
1274         sock == server->router->connection)
1275       silc_task_register(server->timeout_queue, 0, 
1276                          silc_server_connect_to_router,
1277                          context, 0, 500000,
1278                          SILC_TASK_TIMEOUT,
1279                          SILC_TASK_PRI_NORMAL);
1280
1281     if (sock->user_data)
1282       silc_server_free_sock_user_data(server, sock);
1283     silc_server_close_connection(server, sock);
1284     return;
1285   }
1286
1287   /* If connection is disconnecting or disconnected we will ignore
1288      what we read. */
1289   if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1290     SILC_LOG_DEBUG(("Ignoring read data from invalid connection"));
1291     return;
1292   }
1293
1294   server->stat.packets_received++;
1295
1296   /* Get keys and stuff from ID entry */
1297   idata = (SilcIDListData)sock->user_data;
1298   if (idata) {
1299     idata->last_receive = time(NULL);
1300     cipher = idata->receive_key;
1301     hmac = idata->hmac;
1302   }
1303  
1304   /* Process the packet. This will call the parser that will then
1305      decrypt and parse the packet. */
1306   silc_packet_receive_process(sock, cipher, hmac, silc_server_packet_parse, 
1307                               server);
1308 }
1309
1310 /* Parses whole packet, received earlier. */
1311
1312 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1313 {
1314   SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1315   SilcServer server = (SilcServer)parse_ctx->context;
1316   SilcSocketConnection sock = parse_ctx->sock;
1317   SilcPacketContext *packet = parse_ctx->packet;
1318   int ret;
1319
1320   SILC_LOG_DEBUG(("Start"));
1321
1322   /* Decrypt the received packet */
1323   ret = silc_packet_decrypt(parse_ctx->cipher, parse_ctx->hmac, 
1324                             packet->buffer, packet);
1325   if (ret < 0)
1326     goto out;
1327
1328   if (ret == 0) {
1329     /* Parse the packet. Packet type is returned. */
1330     ret = silc_packet_parse(packet);
1331   } else {
1332     /* Parse the packet header in special way as this is "special"
1333        packet type. */
1334     ret = silc_packet_parse_special(packet);
1335   }
1336
1337   if (ret == SILC_PACKET_NONE)
1338     goto out;
1339
1340   if (server->server_type == SILC_ROUTER) {
1341     /* Route the packet if it is not destined to us. Other ID types but
1342        server are handled separately after processing them. */
1343     if (packet->dst_id_type == SILC_ID_SERVER && 
1344         sock->type != SILC_SOCKET_TYPE_CLIENT &&
1345         SILC_ID_SERVER_COMPARE(packet->dst_id, server->id_string)) {
1346       
1347       /* Route the packet to fastest route for the destination ID */
1348       void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len, 
1349                                 packet->dst_id_type);
1350       if (!id)
1351         goto out;
1352       silc_server_packet_route(server,
1353                                silc_server_route_get(server, id,
1354                                                      packet->dst_id_type),
1355                                packet);
1356       silc_free(id);
1357       goto out;
1358     }
1359     
1360     /* Broadcast packet if it is marked as broadcast packet and it is
1361        originated from router and we are router. */
1362     if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1363         packet->flags & SILC_PACKET_FLAG_BROADCAST) {
1364       silc_server_packet_broadcast(server, server->router->connection, packet);
1365     }
1366   }
1367
1368   /* Parse the incoming packet type */
1369   silc_server_packet_parse_type(server, sock, packet);
1370
1371  out:
1372   silc_buffer_clear(sock->inbuf);
1373   silc_packet_context_free(packet);
1374   silc_free(parse_ctx);
1375 }
1376
1377 /* Parser callback called by silc_packet_receive_process. This merely
1378    registers timeout that will handle the actual parsing when appropriate. */
1379
1380 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1381 {
1382   SilcServer server = (SilcServer)parser_context->context;
1383   SilcSocketConnection sock = parser_context->sock;
1384
1385   switch (sock->type) {
1386   case SILC_SOCKET_TYPE_CLIENT:
1387   case SILC_SOCKET_TYPE_UNKNOWN:
1388     /* Parse the packet with timeout */
1389     silc_task_register(server->timeout_queue, sock->sock,
1390                        silc_server_packet_parse_real,
1391                        (void *)parser_context, 0, 100000,
1392                        SILC_TASK_TIMEOUT,
1393                        SILC_TASK_PRI_NORMAL);
1394     break;
1395   case SILC_SOCKET_TYPE_SERVER:
1396   case SILC_SOCKET_TYPE_ROUTER:
1397     /* Packets from servers are parsed as soon as possible */
1398     silc_task_register(server->timeout_queue, sock->sock,
1399                        silc_server_packet_parse_real,
1400                        (void *)parser_context, 0, 1,
1401                        SILC_TASK_TIMEOUT,
1402                        SILC_TASK_PRI_NORMAL);
1403     break;
1404   default:
1405     return;
1406   }
1407 }
1408
1409 /* Parses the packet type and calls what ever routines the packet type
1410    requires. This is done for all incoming packets. */
1411
1412 void silc_server_packet_parse_type(SilcServer server, 
1413                                    SilcSocketConnection sock,
1414                                    SilcPacketContext *packet)
1415 {
1416   SilcPacketType type = packet->type;
1417
1418   SILC_LOG_DEBUG(("Parsing packet type %d", type));
1419
1420   /* Parse the packet type */
1421   switch(type) {
1422   case SILC_PACKET_DISCONNECT:
1423     SILC_LOG_DEBUG(("Disconnect packet"));
1424     break;
1425
1426   case SILC_PACKET_SUCCESS:
1427     /*
1428      * Success received for something. For now we can have only
1429      * one protocol for connection executing at once hence this
1430      * success message is for whatever protocol is executing currently.
1431      */
1432     SILC_LOG_DEBUG(("Success packet"));
1433     if (sock->protocol) {
1434       sock->protocol->execute(server->timeout_queue, 0,
1435                               sock->protocol, sock->sock, 0, 0);
1436     }
1437     break;
1438
1439   case SILC_PACKET_FAILURE:
1440     /*
1441      * Failure received for something. For now we can have only
1442      * one protocol for connection executing at once hence this
1443      * failure message is for whatever protocol is executing currently.
1444      */
1445     SILC_LOG_DEBUG(("Failure packet"));
1446     if (sock->protocol) {
1447       /* XXX Audit the failure type */
1448       sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
1449       sock->protocol->execute(server->timeout_queue, 0,
1450                               sock->protocol, sock->sock, 0, 0);
1451     }
1452     break;
1453
1454   case SILC_PACKET_REJECT:
1455     SILC_LOG_DEBUG(("Reject packet"));
1456     return;
1457     break;
1458
1459   case SILC_PACKET_NOTIFY:
1460     /*
1461      * Received notify packet. Server can receive notify packets from
1462      * router. Server then relays the notify messages to clients if needed.
1463      */
1464     SILC_LOG_DEBUG(("Notify packet"));
1465     silc_server_notify(server, sock, packet);
1466     break;
1467
1468     /* 
1469      * Channel packets
1470      */
1471   case SILC_PACKET_CHANNEL_MESSAGE:
1472     /*
1473      * Received channel message. Channel messages are special packets
1474      * (although probably most common ones) thus they are handled
1475      * specially.
1476      */
1477     SILC_LOG_DEBUG(("Channel Message packet"));
1478     silc_server_channel_message(server, sock, packet);
1479     break;
1480
1481   case SILC_PACKET_CHANNEL_KEY:
1482     /*
1483      * Received key for channel. As channels are created by the router
1484      * the keys are as well. We will distribute the key to all of our
1485      * locally connected clients on the particular channel. Router
1486      * never receives this channel and thus is ignored.
1487      */
1488     SILC_LOG_DEBUG(("Channel Key packet"));
1489     silc_server_channel_key(server, sock, packet);
1490     break;
1491
1492     /*
1493      * Command packets
1494      */
1495   case SILC_PACKET_COMMAND:
1496     /*
1497      * Recived command. Processes the command request and allocates the
1498      * command context and calls the command.
1499      */
1500     SILC_LOG_DEBUG(("Command packet"));
1501     silc_server_command_process(server, sock, packet);
1502     break;
1503
1504   case SILC_PACKET_COMMAND_REPLY:
1505     /*
1506      * Received command reply packet. Received command reply to command. It
1507      * may be reply to command sent by us or reply to command sent by client
1508      * that we've routed further.
1509      */
1510     SILC_LOG_DEBUG(("Command Reply packet"));
1511     silc_server_command_reply(server, sock, packet);
1512     break;
1513
1514     /*
1515      * Private Message packets
1516      */
1517   case SILC_PACKET_PRIVATE_MESSAGE:
1518     /*
1519      * Received private message packet. The packet is coming from either
1520      * client or server.
1521      */
1522     SILC_LOG_DEBUG(("Private Message packet"));
1523     silc_server_private_message(server, sock, packet);
1524     break;
1525
1526   case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1527     /*
1528      * Private message key packet.
1529      */
1530     break;
1531
1532     /*
1533      * Key Exchange protocol packets
1534      */
1535   case SILC_PACKET_KEY_EXCHANGE:
1536     SILC_LOG_DEBUG(("KE packet"));
1537     if (sock->protocol && sock->protocol->protocol->type 
1538         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1539
1540       SilcServerKEInternalContext *proto_ctx = 
1541         (SilcServerKEInternalContext *)sock->protocol->context;
1542
1543       proto_ctx->packet = silc_packet_context_dup(packet);
1544
1545       /* Let the protocol handle the packet */
1546       sock->protocol->execute(server->timeout_queue, 0, 
1547                               sock->protocol, sock->sock, 0, 100000);
1548     } else {
1549       SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1550                       "protocol active, packet dropped."));
1551
1552       /* XXX Trigger KE protocol?? Rekey actually, maybe. */
1553     }
1554     break;
1555
1556   case SILC_PACKET_KEY_EXCHANGE_1:
1557     SILC_LOG_DEBUG(("KE 1 packet"));
1558     if (sock->protocol && sock->protocol->protocol->type 
1559         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1560
1561       SilcServerKEInternalContext *proto_ctx = 
1562         (SilcServerKEInternalContext *)sock->protocol->context;
1563
1564       if (proto_ctx->packet)
1565         silc_packet_context_free(proto_ctx->packet);
1566
1567       proto_ctx->packet = silc_packet_context_dup(packet);
1568       proto_ctx->dest_id_type = packet->src_id_type;
1569       proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1570                                           packet->src_id_type);
1571       if (!proto_ctx->dest_id)
1572         break;
1573
1574       /* Let the protocol handle the packet */
1575       sock->protocol->execute(server->timeout_queue, 0, 
1576                               sock->protocol, sock->sock,
1577                               0, 100000);
1578     } else {
1579       SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1580                       "protocol active, packet dropped."));
1581     }
1582     break;
1583
1584   case SILC_PACKET_KEY_EXCHANGE_2:
1585     SILC_LOG_DEBUG(("KE 2 packet"));
1586     if (sock->protocol && sock->protocol->protocol->type 
1587         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1588
1589       SilcServerKEInternalContext *proto_ctx = 
1590         (SilcServerKEInternalContext *)sock->protocol->context;
1591
1592       if (proto_ctx->packet)
1593         silc_packet_context_free(proto_ctx->packet);
1594
1595       proto_ctx->packet = silc_packet_context_dup(packet);
1596       proto_ctx->dest_id_type = packet->src_id_type;
1597       proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1598                                           packet->src_id_type);
1599       if (!proto_ctx->dest_id)
1600         break;
1601
1602       /* Let the protocol handle the packet */
1603       sock->protocol->execute(server->timeout_queue, 0, 
1604                               sock->protocol, sock->sock,
1605                               0, 100000);
1606     } else {
1607       SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1608                       "protocol active, packet dropped."));
1609     }
1610     break;
1611
1612   case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1613     /*
1614      * Connection authentication request packet. When we receive this packet
1615      * we will send to the other end information about our mandatory
1616      * authentication method for the connection. This packet maybe received
1617      * at any time. 
1618      */
1619     SILC_LOG_DEBUG(("Connection authentication request packet"));
1620     break;
1621
1622     /*
1623      * Connection Authentication protocol packets
1624      */
1625   case SILC_PACKET_CONNECTION_AUTH:
1626     /* Start of the authentication protocol. We receive here the 
1627        authentication data and will verify it. */
1628     SILC_LOG_DEBUG(("Connection auth packet"));
1629     if (sock->protocol && sock->protocol->protocol->type 
1630         == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1631
1632       SilcServerConnAuthInternalContext *proto_ctx = 
1633         (SilcServerConnAuthInternalContext *)sock->protocol->context;
1634
1635       proto_ctx->packet = silc_packet_context_dup(packet);
1636
1637       /* Let the protocol handle the packet */
1638       sock->protocol->execute(server->timeout_queue, 0, 
1639                               sock->protocol, sock->sock, 0, 0);
1640     } else {
1641       SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1642                       "protocol active, packet dropped."));
1643     }
1644     break;
1645
1646   case SILC_PACKET_NEW_ID:
1647     /*
1648      * Received New ID packet. This includes some new ID that has been
1649      * created. It may be for client, server or channel. This is the way
1650      * to distribute information about new registered entities in the
1651      * SILC network.
1652      */
1653     SILC_LOG_DEBUG(("New ID packet"));
1654     silc_server_new_id(server, sock, packet);
1655     break;
1656
1657   case SILC_PACKET_NEW_ID_LIST:
1658     /*
1659      * Received list of ID's. This packet is used by servers and routers
1660      * to notify their primary router about clients and servers they have.
1661      */
1662     SILC_LOG_DEBUG(("New ID List packet"));
1663     silc_server_new_id_list(server, sock, packet);
1664     break;
1665
1666   case SILC_PACKET_NEW_CLIENT:
1667     /*
1668      * Received new client packet. This includes client information that
1669      * we will use to create initial client ID. After creating new
1670      * ID we will send it to the client.
1671      */
1672     SILC_LOG_DEBUG(("New Client packet"));
1673     silc_server_new_client(server, sock, packet);
1674     break;
1675
1676   case SILC_PACKET_NEW_SERVER:
1677     /*
1678      * Received new server packet. This includes Server ID and some other
1679      * information that we may save. This is received after server has 
1680      * connected to us.
1681      */
1682     SILC_LOG_DEBUG(("New Server packet"));
1683     silc_server_new_server(server, sock, packet);
1684     break;
1685
1686   case SILC_PACKET_NEW_CHANNEL:
1687     /*
1688      * Received new channel packet. Information about new channel in the
1689      * network are distributed using this packet.
1690      */
1691     SILC_LOG_DEBUG(("New Channel packet"));
1692     silc_server_new_channel(server, sock, packet);
1693     break;
1694
1695   case SILC_PACKET_NEW_CHANNEL_USER:
1696     /*
1697      * Received new channel user packet. Information about new users on a
1698      * channel are distributed between routers using this packet.  The
1699      * router receiving this will redistribute it and also sent JOIN notify
1700      * to local clients on the same channel. Normal server sends JOIN notify
1701      * to its local clients on the channel.
1702      */
1703     SILC_LOG_DEBUG(("New Channel User packet"));
1704     silc_server_new_channel_user(server, sock, packet);
1705     break;
1706
1707   case SILC_PACKET_NEW_CHANNEL_LIST:
1708     /*
1709      * List of new channel packets received. This is usually received when
1710      * existing server or router connects to us and distributes information
1711      * of all channels it has.
1712      */
1713     SILC_LOG_DEBUG(("New Channel List packet"));
1714     silc_server_new_channel_list(server, sock, packet);
1715     break;
1716
1717   case SILC_PACKET_NEW_CHANNEL_USER_LIST:
1718     /*
1719      * List of new channel user packets received. This is usually received
1720      * when existing server or router connects to us and distributes 
1721      * information of all channel users it has.
1722      */
1723     SILC_LOG_DEBUG(("New Channel User List packet"));
1724     silc_server_new_channel_user_list(server, sock, packet);
1725     break;
1726
1727   case SILC_PACKET_REPLACE_ID:
1728     /*
1729      * Received replace ID packet. This sends the old ID that is to be
1730      * replaced with the new one included into the packet. Client must not
1731      * send this packet.
1732      */
1733     SILC_LOG_DEBUG(("Replace ID packet"));
1734     silc_server_replace_id(server, sock, packet);
1735     break;
1736
1737   case SILC_PACKET_REMOVE_ID:
1738     /*
1739      * Received remove ID Packet. 
1740      */
1741     SILC_LOG_DEBUG(("Remove ID packet"));
1742     silc_server_remove_id(server, sock, packet);
1743     break;
1744
1745   case SILC_PACKET_REMOVE_CHANNEL_USER:
1746     /*
1747      * Received packet to remove user from a channel. Routers notify other
1748      * routers about a user leaving a channel.
1749      */
1750     SILC_LOG_DEBUG(("Remove Channel User packet"));
1751     silc_server_remove_channel_user(server, sock, packet);
1752     break;
1753
1754   case SILC_PACKET_SET_MODE:
1755     /*
1756      * Received packet to set the mode of channel or client's channel mode.
1757      */
1758     SILC_LOG_DEBUG(("Set Mode packet"));
1759     silc_server_set_mode(server, sock, packet);
1760     break;
1761
1762   case SILC_PACKET_HEARTBEAT:
1763     /*
1764      * Received heartbeat.
1765      */
1766     SILC_LOG_DEBUG(("Heartbeat packet"));
1767     break;
1768
1769   default:
1770     SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
1771     break;
1772   }
1773   
1774 }
1775
1776 /* Closes connection to socket connection */
1777
1778 void silc_server_close_connection(SilcServer server,
1779                                   SilcSocketConnection sock)
1780 {
1781   SILC_LOG_DEBUG(("Closing connection %d", sock->sock));
1782
1783   /* We won't listen for this connection anymore */
1784   silc_schedule_unset_listen_fd(sock->sock);
1785
1786   /* Unregister all tasks */
1787   silc_task_unregister_by_fd(server->io_queue, sock->sock);
1788   silc_task_unregister_by_fd(server->timeout_queue, sock->sock);
1789
1790   /* Close the actual connection */
1791   silc_net_close_connection(sock->sock);
1792   server->sockets[sock->sock] = NULL;
1793   silc_socket_free(sock);
1794 }
1795
1796 /* Sends disconnect message to remote connection and disconnects the 
1797    connection. */
1798
1799 void silc_server_disconnect_remote(SilcServer server,
1800                                    SilcSocketConnection sock,
1801                                    const char *fmt, ...)
1802 {
1803   va_list ap;
1804   unsigned char buf[4096];
1805
1806   if (!sock)
1807     return;
1808
1809   memset(buf, 0, sizeof(buf));
1810   va_start(ap, fmt);
1811   vsprintf(buf, fmt, ap);
1812   va_end(ap);
1813
1814   SILC_LOG_DEBUG(("Disconnecting remote host"));
1815
1816   /* Notify remote end that the conversation is over. The notify message
1817      is tried to be sent immediately. */
1818   silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,  
1819                           buf, strlen(buf), TRUE);
1820
1821   /* Mark the connection to be disconnected */
1822   SILC_SET_DISCONNECTED(sock);
1823   silc_server_close_connection(server, sock);
1824 }
1825
1826 /* Free's user_data pointer from socket connection object. This also sends
1827    appropriate notify packets to the network to inform about leaving
1828    entities. */
1829
1830 void silc_server_free_sock_user_data(SilcServer server, 
1831                                      SilcSocketConnection sock)
1832 {
1833   SILC_LOG_DEBUG(("Start"));
1834
1835   switch(sock->type) {
1836   case SILC_SOCKET_TYPE_CLIENT:
1837     {
1838       SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
1839
1840       /* Remove client from all channels */
1841       silc_server_remove_from_channels(server, sock, user_data);
1842
1843       /* XXX must take some info to history before freeing */
1844
1845       /* Send REMOVE_ID packet to routers. */
1846       if (!server->standalone && server->router)
1847         silc_server_send_remove_id(server, server->router->connection,
1848                                    server->server_type == SILC_SERVER ?
1849                                    FALSE : TRUE, user_data->id, 
1850                                    SILC_ID_CLIENT_LEN, SILC_ID_CLIENT);
1851
1852       /* Free the client entry and everything in it */
1853       silc_idlist_del_data(user_data);
1854       silc_idlist_del_client(server->local_list, user_data);
1855       server->stat.my_clients--;
1856       server->stat.clients--;
1857       if (server->server_type == SILC_ROUTER)
1858         server->stat.cell_clients--;
1859       break;
1860     }
1861   case SILC_SOCKET_TYPE_SERVER:
1862   case SILC_SOCKET_TYPE_ROUTER:
1863     {
1864       SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
1865
1866       /* Send REMOVE_ID packet to routers. */
1867       if (!server->standalone && server->router)
1868         silc_server_send_remove_id(server, server->router->connection,
1869                                    server->server_type == SILC_SERVER ?
1870                                    FALSE : TRUE, user_data->id, 
1871                                    SILC_ID_CLIENT_LEN, SILC_ID_CLIENT);
1872
1873       /* Then also free all client entries that this server owns as
1874          they will become invalid now as well. */
1875       silc_server_remove_clients_by_server(server, user_data);
1876
1877       /* If this was our primary router connection then we're lost to
1878          the outside world. */
1879       if (server->server_type == SILC_SERVER && server->router == user_data) {
1880         server->id_entry->router = NULL;
1881         server->router = NULL;
1882         server->standalone = TRUE;
1883       }
1884
1885       /* Free the server entry */
1886       silc_idlist_del_data(user_data);
1887       silc_idlist_del_server(server->local_list, user_data);
1888       server->stat.my_servers--;
1889       server->stat.servers--;
1890       if (server->server_type == SILC_ROUTER)
1891         server->stat.cell_servers--;
1892       break;
1893     }
1894   default:
1895     {
1896       SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
1897
1898       silc_idlist_del_data(user_data);
1899       silc_free(user_data);
1900       break;
1901     }
1902   }
1903
1904   sock->user_data = NULL;
1905 }
1906
1907 /* This function is used to remove all client entries by the server `entry'.
1908    This is called when the connection is lost to the server. In this case
1909    we must invalidate all the client entries owned by the server `entry'. */
1910
1911 int silc_server_remove_clients_by_server(SilcServer server, 
1912                                          SilcServerEntry entry)
1913 {
1914   SilcIDCacheList list = NULL;
1915   SilcIDCacheEntry id_cache = NULL;
1916   SilcClientEntry client = NULL;
1917
1918   if (silc_idcache_find_by_id(server->local_list->clients, 
1919                               SILC_ID_CACHE_ANY, SILC_ID_CLIENT, &list)) {
1920
1921     if (silc_idcache_list_first(list, &id_cache)) {
1922       while (id_cache) {
1923         client = (SilcClientEntry)id_cache->context;
1924         
1925         if (client->router != entry) {
1926           if (!silc_idcache_list_next(list, &id_cache))
1927             break;
1928           else
1929             continue;
1930         }
1931
1932         /* Remove the client entry */
1933         silc_server_remove_from_channels(server, NULL, client);
1934         silc_idlist_del_client(server->local_list, client);
1935
1936         if (!silc_idcache_list_next(list, &id_cache))
1937           break;
1938       }
1939     }
1940     silc_idcache_list_free(list);
1941   }
1942   
1943   if (silc_idcache_find_by_id(server->global_list->clients, 
1944                               SILC_ID_CACHE_ANY, SILC_ID_CLIENT, &list)) {
1945
1946     if (silc_idcache_list_first(list, &id_cache)) {
1947       while (id_cache) {
1948         client = (SilcClientEntry)id_cache->context;
1949         
1950         if (client->router != entry) {
1951           if (!silc_idcache_list_next(list, &id_cache))
1952             break;
1953           else
1954             continue;
1955         }
1956
1957         /* Remove the client entry */
1958         silc_server_remove_from_channels(server, NULL, client);
1959         silc_idlist_del_client(server->global_list, client);
1960
1961         if (!silc_idcache_list_next(list, &id_cache))
1962           break;
1963       }
1964     }
1965     silc_idcache_list_free(list);
1966   }
1967   
1968   return TRUE;
1969 }
1970
1971 /* Checks whether given channel has global users.  If it does this returns
1972    TRUE and FALSE if there is only locally connected clients on the channel. */
1973
1974 int silc_server_channel_has_global(SilcChannelEntry channel)
1975 {
1976   SilcChannelClientEntry chl;
1977
1978   silc_list_start(channel->user_list);
1979   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
1980     if (chl->client->router)
1981       return TRUE;
1982   }
1983
1984   return FALSE;
1985 }
1986
1987 /* Checks whether given channel has locally connected users.  If it does this
1988    returns TRUE and FALSE if there is not one locally connected client. */
1989
1990 int silc_server_channel_has_local(SilcChannelEntry channel)
1991 {
1992   SilcChannelClientEntry chl;
1993
1994   silc_list_start(channel->user_list);
1995   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
1996     if (!chl->client->router)
1997       return TRUE;
1998   }
1999
2000   return FALSE;
2001 }
2002
2003 /* Removes client from all channels it has joined. This is used when client
2004    connection is disconnected. If the client on a channel is last, the
2005    channel is removed as well. This sends the SIGNOFF notify types. */
2006
2007 void silc_server_remove_from_channels(SilcServer server, 
2008                                       SilcSocketConnection sock,
2009                                       SilcClientEntry client)
2010 {
2011   SilcChannelEntry channel;
2012   SilcChannelClientEntry chl;
2013   SilcBuffer clidp;
2014
2015   SILC_LOG_DEBUG(("Start"));
2016
2017   if (!client || !client->id)
2018     return;
2019
2020   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2021
2022   /* Remove the client from all channels. The client is removed from
2023      the channels' user list. */
2024   silc_list_start(client->channels);
2025   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2026     channel = chl->channel;
2027
2028     /* Remove channel from client's channel list */
2029     silc_list_del(client->channels, chl);
2030
2031     /* Remove channel if there is no users anymore */
2032     if (server->server_type == SILC_ROUTER &&
2033         silc_list_count(channel->user_list) < 2) {
2034       if (!silc_idlist_del_channel(server->local_list, channel))
2035         silc_idlist_del_channel(server->global_list, channel);
2036       server->stat.my_channels--;
2037       continue;
2038     }
2039
2040     /* Remove client from channel's client list */
2041     silc_list_del(channel->user_list, chl);
2042     silc_free(chl);
2043     server->stat.my_chanclients--;
2044
2045     /* If there is not at least one local user on the channel then we don't
2046        need the channel entry anymore, we can remove it safely. */
2047     if (server->server_type == SILC_SERVER &&
2048         !silc_server_channel_has_local(channel)) {
2049       /* Notify about leaving client if this channel has global users. */
2050       if (channel->global_users)
2051         silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2052                                            SILC_NOTIFY_TYPE_SIGNOFF, 1,
2053                                            clidp->data, clidp->len);
2054
2055       if (!silc_idlist_del_channel(server->local_list, channel))
2056         silc_idlist_del_channel(server->global_list, channel);
2057       server->stat.my_channels--;
2058       continue;
2059     }
2060
2061     /* Send notify to channel about client leaving SILC and thus
2062        the entire channel. */
2063     silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2064                                        SILC_NOTIFY_TYPE_SIGNOFF, 1,
2065                                        clidp->data, clidp->len);
2066   }
2067
2068   silc_buffer_free(clidp);
2069 }
2070
2071 /* Removes client from one channel. This is used for example when client
2072    calls LEAVE command to remove itself from the channel. Returns TRUE
2073    if channel still exists and FALSE if the channel is removed when
2074    last client leaves the channel. If `notify' is FALSE notify messages
2075    are not sent. */
2076
2077 int silc_server_remove_from_one_channel(SilcServer server, 
2078                                         SilcSocketConnection sock,
2079                                         SilcChannelEntry channel,
2080                                         SilcClientEntry client,
2081                                         int notify)
2082 {
2083   SilcChannelEntry ch;
2084   SilcChannelClientEntry chl;
2085   SilcBuffer clidp;
2086
2087   SILC_LOG_DEBUG(("Start"));
2088
2089   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2090
2091   /* Remove the client from the channel. The client is removed from
2092      the channel's user list. */
2093   silc_list_start(client->channels);
2094   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2095     if (chl->channel != channel)
2096       continue;
2097
2098     ch = chl->channel;
2099
2100     /* Remove channel from client's channel list */
2101     silc_list_del(client->channels, chl);
2102
2103     /* Remove channel if there is no users anymore */
2104     if (server->server_type == SILC_ROUTER &&
2105         silc_list_count(channel->user_list) < 2) {
2106       if (!silc_idlist_del_channel(server->local_list, channel))
2107         silc_idlist_del_channel(server->global_list, channel);
2108       silc_buffer_free(clidp);
2109       server->stat.my_channels--;
2110       return FALSE;
2111     }
2112
2113     /* Remove client from channel's client list */
2114     silc_list_del(channel->user_list, chl);
2115     silc_free(chl);
2116     server->stat.my_chanclients--;
2117
2118     /* If there is no global users on the channel anymore mark the channel
2119        as local channel. */
2120     if (server->server_type == SILC_SERVER &&
2121         !silc_server_channel_has_global(channel))
2122       channel->global_users = FALSE;
2123
2124     /* If there is not at least one local user on the channel then we don't
2125        need the channel entry anymore, we can remove it safely. */
2126     if (server->server_type == SILC_SERVER &&
2127         !silc_server_channel_has_local(channel)) {
2128       /* Notify about leaving client if this channel has global users. */
2129       if (notify && channel->global_users)
2130         silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2131                                            SILC_NOTIFY_TYPE_LEAVE, 1,
2132                                            clidp->data, clidp->len);
2133
2134       if (!silc_idlist_del_channel(server->local_list, channel))
2135         silc_idlist_del_channel(server->global_list, channel);
2136       silc_buffer_free(clidp);
2137       server->stat.my_channels--;
2138       return FALSE;
2139     }
2140
2141     /* Send notify to channel about client leaving the channel */
2142     if (notify)
2143       silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2144                                          SILC_NOTIFY_TYPE_LEAVE, 1,
2145                                          clidp->data, clidp->len);
2146     break;
2147   }
2148
2149   silc_buffer_free(clidp);
2150   return TRUE;
2151 }
2152
2153 /* Returns TRUE if the given client is on the channel.  FALSE if not. 
2154    This works because we assure that the user list on the channel is
2155    always in up to date thus we can only check the channel list from 
2156    `client' which is faster than checking the user list from `channel'. */
2157
2158 int silc_server_client_on_channel(SilcClientEntry client,
2159                                   SilcChannelEntry channel)
2160 {
2161   SilcChannelClientEntry chl;
2162
2163   if (!client || !channel)
2164     return FALSE;
2165
2166   silc_list_start(client->channels);
2167   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END)
2168     if (chl->channel == channel)
2169       return TRUE;
2170
2171   return FALSE;
2172 }
2173
2174 /* Timeout callback. This is called if connection is idle or for some
2175    other reason is not responding within some period of time. This 
2176    disconnects the remote end. */
2177
2178 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2179 {
2180   SilcServer server = (SilcServer)context;
2181   SilcSocketConnection sock = server->sockets[fd];
2182
2183   if (!sock)
2184     return;
2185
2186   if (sock->user_data)
2187     silc_server_free_sock_user_data(server, sock);
2188
2189   silc_server_disconnect_remote(server, sock, 
2190                                 "Server closed connection: "
2191                                 "Connection timeout");
2192 }
2193
2194 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2195    function may be used only by router. In real SILC network all channels
2196    are created by routers thus this function is never used by normal
2197    server. */
2198
2199 SilcChannelEntry silc_server_create_new_channel(SilcServer server, 
2200                                                 SilcServerID *router_id,
2201                                                 char *cipher, 
2202                                                 char *channel_name)
2203 {
2204   SilcChannelID *channel_id;
2205   SilcChannelEntry entry;
2206   SilcCipher key;
2207
2208   SILC_LOG_DEBUG(("Creating new channel"));
2209
2210   if (!cipher)
2211     cipher = "twofish";
2212
2213   /* Allocate cipher */
2214   silc_cipher_alloc(cipher, &key);
2215
2216   channel_name = strdup(channel_name);
2217
2218   /* Create the channel */
2219   silc_id_create_channel_id(router_id, server->rng, &channel_id);
2220   entry = silc_idlist_add_channel(server->local_list, channel_name, 
2221                                   SILC_CHANNEL_MODE_NONE, channel_id, 
2222                                   NULL, key);
2223   if (!entry) {
2224     silc_free(channel_name);
2225     return NULL;
2226   }
2227
2228   /* Now create the actual key material */
2229   silc_server_create_channel_key(server, entry, 16);
2230
2231   /* Notify other routers about the new channel. We send the packet
2232      to our primary route. */
2233   if (server->standalone == FALSE) {
2234     silc_server_send_new_channel(server, server->router->connection, TRUE, 
2235                                  channel_name, entry->id, SILC_ID_CHANNEL_LEN);
2236   }
2237
2238   server->stat.my_channels++;
2239
2240   return entry;
2241 }
2242
2243 /* Same as above but creates the channel with Channel ID `channel_id. */
2244
2245 SilcChannelEntry 
2246 silc_server_create_new_channel_with_id(SilcServer server, 
2247                                        char *cipher, 
2248                                        char *channel_name,
2249                                        SilcChannelID *channel_id)
2250 {
2251   SilcChannelEntry entry;
2252   SilcCipher key;
2253
2254   SILC_LOG_DEBUG(("Creating new channel"));
2255
2256   if (!cipher)
2257     cipher = "twofish";
2258
2259   /* Allocate cipher */
2260   silc_cipher_alloc(cipher, &key);
2261
2262   channel_name = strdup(channel_name);
2263
2264   /* Create the channel */
2265   entry = silc_idlist_add_channel(server->local_list, channel_name, 
2266                                   SILC_CHANNEL_MODE_NONE, channel_id, 
2267                                   NULL, key);
2268   if (!entry) {
2269     silc_free(channel_name);
2270     return NULL;
2271   }
2272
2273   /* Now create the actual key material */
2274   silc_server_create_channel_key(server, entry, 16);
2275
2276   /* Notify other routers about the new channel. We send the packet
2277      to our primary route. */
2278   if (server->standalone == FALSE) {
2279     silc_server_send_new_channel(server, server->router->connection, TRUE, 
2280                                  channel_name, entry->id, SILC_ID_CHANNEL_LEN);
2281   }
2282
2283   server->stat.my_channels++;
2284
2285   return entry;
2286 }
2287
2288 /* Generates new channel key. This is used to create the initial channel key
2289    but also to re-generate new key for channel. If `key_len' is provided
2290    it is the bytes of the key length. */
2291
2292 void silc_server_create_channel_key(SilcServer server, 
2293                                     SilcChannelEntry channel,
2294                                     unsigned int key_len)
2295 {
2296   int i;
2297   unsigned char channel_key[32];
2298   unsigned int len;
2299
2300   if (!channel->channel_key)
2301     silc_cipher_alloc("twofish", &channel->channel_key);
2302
2303   if (key_len)
2304     len = key_len;
2305   else if (channel->key_len)
2306     len = channel->key_len / 8;
2307   else
2308     len = sizeof(channel_key);
2309
2310   /* Create channel key */
2311   for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
2312   
2313   /* Set the key */
2314   channel->channel_key->cipher->set_key(channel->channel_key->context, 
2315                                         channel_key, len);
2316
2317   /* Remove old key if exists */
2318   if (channel->key) {
2319     memset(channel->key, 0, channel->key_len / 8);
2320     silc_free(channel->key);
2321   }
2322
2323   /* Save the key */
2324   channel->key_len = len * 8;
2325   channel->key = silc_calloc(len, sizeof(*channel->key));
2326   memcpy(channel->key, channel_key, len);
2327   memset(channel_key, 0, sizeof(channel_key));
2328 }
2329
2330 /* Saves the channel key found in the encoded `key_payload' buffer. This 
2331    function is used when we receive Channel Key Payload and also when we're
2332    processing JOIN command reply. Returns entry to the channel. */
2333
2334 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
2335                                               SilcBuffer key_payload,
2336                                               SilcChannelEntry channel)
2337 {
2338   SilcChannelKeyPayload payload = NULL;
2339   SilcChannelID *id = NULL;
2340   unsigned char *tmp;
2341   unsigned int tmp_len;
2342   char *cipher;
2343
2344   /* Decode channel key payload */
2345   payload = silc_channel_key_payload_parse(key_payload);
2346   if (!payload) {
2347     SILC_LOG_ERROR(("Bad channel key payload, dropped"));
2348     channel = NULL;
2349     goto out;
2350   }
2351
2352   /* Get the channel entry */
2353   if (!channel) {
2354
2355     /* Get channel ID */
2356     tmp = silc_channel_key_get_id(payload, &tmp_len);
2357     id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
2358     if (!id) {
2359       channel = NULL;
2360       goto out;
2361     }
2362
2363     channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
2364     if (!channel) {
2365       channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
2366       if (!channel) {
2367         SILC_LOG_ERROR(("Received key for non-existent channel"));
2368         goto out;
2369       }
2370     }
2371   }
2372
2373   tmp = silc_channel_key_get_key(payload, &tmp_len);
2374   if (!tmp) {
2375     channel = NULL;
2376     goto out;
2377   }
2378
2379   cipher = silc_channel_key_get_cipher(payload, NULL);;
2380   if (!cipher) {
2381     channel = NULL;
2382     goto out;
2383   }
2384
2385   /* Remove old key if exists */
2386   if (channel->key) {
2387     memset(channel->key, 0, channel->key_len / 8);
2388     silc_free(channel->key);
2389     silc_cipher_free(channel->channel_key);
2390   }
2391
2392   /* Create new cipher */
2393   if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
2394     channel = NULL;
2395     goto out;
2396   }
2397
2398   /* Save the key */
2399   channel->key_len = tmp_len * 8;
2400   channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
2401   memcpy(channel->key, tmp, tmp_len);
2402   channel->channel_key->cipher->set_key(channel->channel_key->context, 
2403                                         tmp, tmp_len);
2404
2405  out:
2406   if (id)
2407     silc_free(id);
2408   if (payload)
2409     silc_channel_key_payload_free(payload);
2410
2411   return channel;
2412 }
2413
2414 /* Heartbeat callback. This function is set as argument for the
2415    silc_socket_set_heartbeat function. The library will call this function
2416    at the set time interval. */
2417
2418 void silc_server_perform_heartbeat(SilcSocketConnection sock,
2419                                    void *hb_context)
2420 {
2421   SilcServerHBContext hb = (SilcServerHBContext)hb_context;
2422
2423   SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname,
2424                   sock->ip));
2425
2426   /* Send the heartbeat */
2427   silc_server_send_heartbeat(hb->server, sock);
2428 }
2429
2430 /* Returns assembled of all servers in the given ID list. The packet's
2431    form is dictated by the New ID payload. */
2432
2433 static void silc_server_announce_get_servers(SilcServer server,
2434                                              SilcIDList id_list,
2435                                              SilcBuffer *servers)
2436 {
2437   SilcIDCacheList list;
2438   SilcIDCacheEntry id_cache;
2439   SilcServerEntry entry;
2440   SilcBuffer idp;
2441
2442   /* Go through all clients in the list */
2443   if (silc_idcache_find_by_id(id_list->clients, SILC_ID_CACHE_ANY, 
2444                               SILC_ID_SERVER, &list)) {
2445     if (silc_idcache_list_first(list, &id_cache)) {
2446       while (id_cache) {
2447         entry = (SilcServerEntry)id_cache->context;
2448
2449         idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
2450
2451         *servers = silc_buffer_realloc(*servers, 
2452                                        (*servers ? 
2453                                         (*servers)->truelen + idp->len : 
2454                                         idp->len));
2455         silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
2456         silc_buffer_put(*servers, idp->data, idp->len);
2457         silc_buffer_pull(*servers, idp->len);
2458         silc_buffer_free(idp);
2459
2460         if (!silc_idcache_list_next(list, &id_cache))
2461           break;
2462       }
2463     }
2464
2465     silc_idcache_list_free(list);
2466   }
2467 }
2468
2469 /* This function is used by router to announce existing servers to our
2470    primary router when we've connected to it. */
2471
2472 void silc_server_announce_servers(SilcServer server)
2473 {
2474   SilcBuffer servers = NULL;
2475
2476   SILC_LOG_DEBUG(("Announcing servers"));
2477
2478   /* Get servers in local list */
2479   silc_server_announce_get_servers(server, server->local_list, &servers);
2480
2481   /* Get servers in global list */
2482   silc_server_announce_get_servers(server, server->global_list, &servers);
2483
2484   if (servers) {
2485     silc_buffer_push(servers, servers->data - servers->head);
2486     SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
2487
2488     /* Send the packet */
2489     silc_server_packet_send(server, server->router->connection,
2490                             SILC_PACKET_NEW_ID_LIST, 0,
2491                             servers->data, servers->len, TRUE);
2492
2493     silc_buffer_free(servers);
2494   }
2495 }
2496
2497 /* Returns assembled packet of all clients in the given ID list. The
2498    packet's form is dictated by the New ID Payload. */
2499
2500 static void silc_server_announce_get_clients(SilcServer server,
2501                                              SilcIDList id_list,
2502                                              SilcBuffer *clients)
2503 {
2504   SilcIDCacheList list;
2505   SilcIDCacheEntry id_cache;
2506   SilcClientEntry client;
2507   SilcBuffer idp;
2508
2509   /* Go through all clients in the list */
2510   if (silc_idcache_find_by_id(id_list->clients, SILC_ID_CACHE_ANY, 
2511                               SILC_ID_CLIENT, &list)) {
2512     if (silc_idcache_list_first(list, &id_cache)) {
2513       while (id_cache) {
2514         client = (SilcClientEntry)id_cache->context;
2515
2516         idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2517
2518         *clients = silc_buffer_realloc(*clients, 
2519                                        (*clients ? 
2520                                         (*clients)->truelen + idp->len : 
2521                                         idp->len));
2522         silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
2523         silc_buffer_put(*clients, idp->data, idp->len);
2524         silc_buffer_pull(*clients, idp->len);
2525         silc_buffer_free(idp);
2526
2527         if (!silc_idcache_list_next(list, &id_cache))
2528           break;
2529       }
2530     }
2531
2532     silc_idcache_list_free(list);
2533   }
2534 }
2535
2536 /* This function is used to announce our existing clients to our router
2537    when we've connected to it. */
2538
2539 void silc_server_announce_clients(SilcServer server)
2540 {
2541   SilcBuffer clients = NULL;
2542
2543   SILC_LOG_DEBUG(("Announcing clients"));
2544
2545   /* Get clients in local list */
2546   silc_server_announce_get_clients(server, server->local_list,
2547                                    &clients);
2548
2549   /* As router we announce our global list as well */
2550   if (server->server_type == SILC_ROUTER)
2551     silc_server_announce_get_clients(server, server->global_list,
2552                                      &clients);
2553
2554   if (clients) {
2555     silc_buffer_push(clients, clients->data - clients->head);
2556     SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
2557
2558     /* Send the packet */
2559     silc_server_packet_send(server, server->router->connection,
2560                             SILC_PACKET_NEW_ID_LIST, 0,
2561                             clients->data, clients->len, TRUE);
2562
2563     silc_buffer_free(clients);
2564   }
2565 }
2566
2567 /* Returns assembled packets for all channels and users on those channels
2568    from the given ID List. The packets are in the form dictated by the
2569    New Channel and New Channel User payloads. */
2570
2571 static void silc_server_announce_get_channels(SilcServer server,
2572                                               SilcIDList id_list,
2573                                               SilcBuffer *channels,
2574                                               SilcBuffer *channel_users)
2575 {
2576   SilcIDCacheList list;
2577   SilcIDCacheEntry id_cache;
2578   SilcChannelEntry channel;
2579   SilcChannelClientEntry chl;
2580   unsigned char *cid;
2581   unsigned short name_len;
2582   int len;
2583
2584   /* Go through all channels in the list */
2585   if (silc_idcache_find_by_id(id_list->channels, SILC_ID_CACHE_ANY, 
2586                               SILC_ID_CHANNEL, &list)) {
2587     if (silc_idcache_list_first(list, &id_cache)) {
2588       while (id_cache) {
2589         channel = (SilcChannelEntry)id_cache->context;
2590         
2591         cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
2592         name_len = strlen(channel->channel_name);
2593
2594         len = 4 + name_len + SILC_ID_CHANNEL_LEN;
2595         *channels = 
2596           silc_buffer_realloc(*channels, 
2597                               (*channels ? (*channels)->truelen + len : len));
2598         silc_buffer_pull_tail(*channels, 
2599                               ((*channels)->end - (*channels)->data));
2600         silc_buffer_format(*channels,
2601                            SILC_STR_UI_SHORT(name_len),
2602                            SILC_STR_UI_XNSTRING(channel->channel_name, 
2603                                                 name_len),
2604                            SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
2605                            SILC_STR_UI_XNSTRING(cid, SILC_ID_CHANNEL_LEN),
2606                            SILC_STR_END);
2607         silc_buffer_pull(*channels, len);
2608
2609         /* Now find all users on the channel */
2610         silc_list_start(channel->user_list);
2611         while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2612           unsigned char *clid;
2613
2614           clid = silc_id_id2str(chl->client->id, SILC_ID_CLIENT);
2615           
2616           len = 4 + SILC_ID_CHANNEL_LEN + SILC_ID_CLIENT_LEN;
2617           *channel_users = 
2618             silc_buffer_realloc(*channel_users, 
2619                                 (*channel_users ? 
2620                                  (*channel_users)->truelen + len : len));
2621           silc_buffer_pull_tail(*channel_users, 
2622                                 ((*channel_users)->end - 
2623                                  (*channel_users)->data));
2624           silc_buffer_format(*channel_users,
2625                              SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
2626                              SILC_STR_UI_XNSTRING(cid, SILC_ID_CHANNEL_LEN),
2627                              SILC_STR_UI_SHORT(SILC_ID_CLIENT_LEN),
2628                              SILC_STR_UI_XNSTRING(clid, SILC_ID_CLIENT_LEN),
2629                              SILC_STR_END);
2630           silc_buffer_pull(*channel_users, len);
2631           silc_free(clid);
2632         }
2633
2634         silc_free(cid);
2635
2636         if (!silc_idcache_list_next(list, &id_cache))
2637           break;
2638       }
2639     }
2640
2641     silc_idcache_list_free(list);
2642   }
2643 }
2644
2645 /* This function is used to announce our existing channels to our router
2646    when we've connected to it. This also announces the users on the
2647    channels to the router. */
2648
2649 void silc_server_announce_channels(SilcServer server)
2650 {
2651   SilcBuffer channels = NULL, channel_users = NULL;
2652
2653   SILC_LOG_DEBUG(("Announcing channels and channel users"));
2654
2655   /* Get channels and channel users in local list */
2656   silc_server_announce_get_channels(server, server->local_list,
2657                                     &channels, &channel_users);
2658
2659   /* Get channels and channel users in global list */
2660   silc_server_announce_get_channels(server, server->global_list,
2661                                     &channels, &channel_users);
2662
2663   if (channels) {
2664     silc_buffer_push(channels, channels->data - channels->head);
2665     SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
2666
2667     /* Send the packet */
2668     silc_server_packet_send(server, server->router->connection,
2669                             SILC_PACKET_NEW_CHANNEL_LIST, 0,
2670                             channels->data, channels->len,
2671                             FALSE);
2672
2673     silc_buffer_free(channels);
2674   }
2675
2676   if (channel_users) {
2677     silc_buffer_push(channel_users, channel_users->data - channel_users->head);
2678     SILC_LOG_HEXDUMP(("channel users"), channel_users->data, 
2679                      channel_users->len);
2680
2681     /* Send the packet */
2682     silc_server_packet_send(server, server->router->connection,
2683                             SILC_PACKET_NEW_CHANNEL_USER_LIST, 0,
2684                             channel_users->data, channel_users->len,
2685                             FALSE);
2686
2687     silc_buffer_free(channel_users);
2688   }
2689 }