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