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
715   SILC_LOG_DEBUG(("Start"));
716
717   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
718     /* Error occured during protocol */
719     silc_protocol_free(protocol);
720     silc_ske_free_key_material(ctx->keymat);
721     if (ctx->packet)
722       silc_packet_context_free(ctx->packet);
723     if (ctx->ske)
724       silc_ske_free(ctx->ske);
725     if (ctx->dest_id)
726       silc_free(ctx->dest_id);
727     silc_free(ctx);
728     silc_task_unregister_by_callback(server->timeout_queue,
729                                      silc_server_failure_callback);
730     silc_server_disconnect_remote(server, sock, "Server closed connection: "
731                                   "Key exchange failed");
732     return;
733   }
734   
735   /* We now have the key material as the result of the key exchange
736      protocol. Take the key material into use. Free the raw key material
737      as soon as we've set them into use. */
738   if (!silc_server_protocol_ke_set_keys(ctx->ske, ctx->sock, ctx->keymat,
739                                         ctx->ske->prop->cipher,
740                                         ctx->ske->prop->pkcs,
741                                         ctx->ske->prop->hash,
742                                         ctx->ske->prop->hmac,
743                                         ctx->responder)) {
744     silc_protocol_free(protocol);
745     silc_ske_free_key_material(ctx->keymat);
746     if (ctx->packet)
747       silc_packet_context_free(ctx->packet);
748     if (ctx->ske)
749       silc_ske_free(ctx->ske);
750     if (ctx->dest_id)
751       silc_free(ctx->dest_id);
752     silc_free(ctx);
753     silc_task_unregister_by_callback(server->timeout_queue,
754                                      silc_server_failure_callback);
755     silc_server_disconnect_remote(server, sock, "Server closed connection: "
756                                   "Key exchange failed");
757     return;
758   }    
759   silc_ske_free_key_material(ctx->keymat);
760
761   /* Allocate internal context for the authentication protocol. This
762      is sent as context for the protocol. */
763   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
764   proto_ctx->server = (void *)server;
765   proto_ctx->context = (void *)sconn;
766   proto_ctx->sock = sock = server->sockets[fd];
767   proto_ctx->ske = ctx->ske;       /* Save SKE object from previous protocol */
768   proto_ctx->dest_id_type = ctx->dest_id_type;
769   proto_ctx->dest_id = ctx->dest_id;
770
771   /* Resolve the authentication method used in this connection */
772   proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
773   if (server->config->routers) {
774     SilcServerConfigSectionServerConnection *conn = NULL;
775
776     /* Check if we find a match from user configured connections */
777     conn = silc_server_config_find_router_conn(server->config,
778                                                sock->hostname,
779                                                sock->port);
780     if (conn) {
781       /* Match found. Use the configured authentication method */
782       proto_ctx->auth_meth = conn->auth_meth;
783       if (conn->auth_data) {
784         proto_ctx->auth_data = strdup(conn->auth_data);
785         proto_ctx->auth_data_len = strlen(conn->auth_data);
786       }
787     } else {
788       /* No match found. */
789       /* XXX */
790     }
791   } else {
792     /* XXX */
793   }
794
795   /* Free old protocol as it is finished now */
796   silc_protocol_free(protocol);
797   if (ctx->packet)
798     silc_packet_context_free(ctx->packet);
799   silc_free(ctx);
800   sock->protocol = NULL;
801
802   /* Allocate the authentication protocol. This is allocated here
803      but we won't start it yet. We will be receiving party of this
804      protocol thus we will wait that connecting party will make
805      their first move. */
806   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH, 
807                       &sock->protocol, proto_ctx, 
808                       silc_server_connect_to_router_final);
809
810   /* Register timeout task. If the protocol is not executed inside
811      this timelimit the connection will be terminated. Currently
812      this is 15 seconds and is hard coded limit (XXX). */
813   proto_ctx->timeout_task = 
814     silc_task_register(server->timeout_queue, sock->sock, 
815                        silc_server_timeout_remote,
816                        (void *)server, 15, 0,
817                        SILC_TASK_TIMEOUT,
818                        SILC_TASK_PRI_LOW);
819
820   /* Run the protocol */
821   sock->protocol->execute(server->timeout_queue, 0, 
822                           sock->protocol, sock->sock, 0, 0);
823 }
824
825 /* Finalizes the connection to router. Registers a server task to the
826    queue so that we can accept new connections. */
827
828 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
829 {
830   SilcProtocol protocol = (SilcProtocol)context;
831   SilcServerConnAuthInternalContext *ctx = 
832     (SilcServerConnAuthInternalContext *)protocol->context;
833   SilcServer server = (SilcServer)ctx->server;
834   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
835   SilcSocketConnection sock = ctx->sock;
836   SilcServerEntry id_entry;
837   SilcBuffer packet;
838   SilcServerHBContext hb_context;
839   unsigned char *id_string;
840
841   SILC_LOG_DEBUG(("Start"));
842
843   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
844     /* Error occured during protocol */
845     if (ctx->dest_id)
846       silc_free(ctx->dest_id);
847     silc_server_disconnect_remote(server, sock, "Server closed connection: "
848                                   "Authentication failed");
849     goto out;
850   }
851
852   /* Add a task to the queue. This task receives new connections to the 
853      server. This task remains on the queue until the end of the program. */
854   if (!server->listenning) {
855     silc_task_register(server->io_queue, server->sock, 
856                        silc_server_accept_new_connection,
857                        (void *)server, 0, 0, 
858                        SILC_TASK_FD,
859                        SILC_TASK_PRI_NORMAL);
860     server->listenning = TRUE;
861   }
862
863   /* Send NEW_SERVER packet to the router. We will become registered
864      to the SILC network after sending this packet. */
865   id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
866   packet = silc_buffer_alloc(2 + 2 + SILC_ID_SERVER_LEN + 
867                              strlen(server->server_name));
868   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
869   silc_buffer_format(packet,
870                      SILC_STR_UI_SHORT(SILC_ID_SERVER_LEN),
871                      SILC_STR_UI_XNSTRING(id_string, SILC_ID_SERVER_LEN),
872                      SILC_STR_UI_SHORT(strlen(server->server_name)),
873                      SILC_STR_UI_XNSTRING(server->server_name,
874                                           strlen(server->server_name)),
875                      SILC_STR_END);
876
877   /* Send the packet */
878   silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
879                           packet->data, packet->len, TRUE);
880   silc_buffer_free(packet);
881   silc_free(id_string);
882
883   SILC_LOG_DEBUG(("Connected to router %s", sock->hostname));
884
885   /* Add the connected router to local server list */
886   server->standalone = FALSE;
887   id_entry = silc_idlist_add_server(server->local_list, sock->hostname,
888                                     SILC_ROUTER, ctx->dest_id, NULL, sock);
889   if (!id_entry) {
890     if (ctx->dest_id)
891       silc_free(ctx->dest_id);
892     silc_server_disconnect_remote(server, sock, "Server closed connection: "
893                                   "Authentication failed");
894     goto out;
895   }
896
897   silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
898   silc_free(sock->user_data);
899   sock->user_data = (void *)id_entry;
900   sock->type = SILC_SOCKET_TYPE_ROUTER;
901   server->id_entry->router = id_entry;
902   server->router = id_entry;
903   server->router->data.registered = TRUE;
904
905   /* Perform keepalive. The `hb_context' will be freed automatically
906      when finally calling the silc_socket_free function. XXX hardcoded 
907      timeout!! */
908   hb_context = silc_calloc(1, sizeof(*hb_context));
909   hb_context->server = server;
910   silc_socket_set_heartbeat(sock, 600, hb_context,
911                             silc_server_perform_heartbeat,
912                             server->timeout_queue);
913
914   /* If we are router then announce our possible servers. */
915   if (server->server_type == SILC_ROUTER)
916     silc_server_announce_servers(server);
917
918   /* Announce our clients and channels to the router */
919   silc_server_announce_clients(server);
920   silc_server_announce_channels(server);
921
922  out:
923   /* Free the temporary connection data context */
924   if (sconn) {
925     silc_free(sconn->remote_host);
926     silc_free(sconn);
927   }
928
929   /* Free the protocol object */
930   silc_protocol_free(protocol);
931   if (ctx->packet)
932     silc_packet_context_free(ctx->packet);
933   if (ctx->ske)
934     silc_ske_free(ctx->ske);
935   silc_free(ctx);
936   sock->protocol = NULL;
937 }
938
939 /* Accepts new connections to the server. Accepting new connections are
940    done in three parts to make it async. */
941
942 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
943 {
944   SilcServer server = (SilcServer)context;
945   SilcSocketConnection newsocket;
946   SilcServerKEInternalContext *proto_ctx;
947   int sock;
948
949   SILC_LOG_DEBUG(("Accepting new connection"));
950
951   server->stat.conn_attempts++;
952
953   sock = silc_net_accept_connection(server->sock);
954   if (sock < 0) {
955     SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
956     server->stat.conn_failures++;
957     return;
958   }
959
960   /* Check max connections */
961   if (sock > SILC_SERVER_MAX_CONNECTIONS) {
962     if (server->config->redirect) {
963       /* XXX Redirecting connection to somewhere else now?? */
964       /*silc_server_send_notify("Server is full, trying to redirect..."); */
965     } else {
966       SILC_LOG_ERROR(("Refusing connection, server is full"));
967       server->stat.conn_failures++;
968     }
969     return;
970   }
971
972   /* Set socket options */
973   silc_net_set_socket_nonblock(sock);
974   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
975
976   /* We don't create a ID yet, since we don't know what type of connection
977      this is yet. But, we do add the connection to the socket table. */
978   silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
979   server->sockets[sock] = newsocket;
980
981   /* XXX This MUST be done async as this will block the entire server
982      process. Either we have to do our own resolver stuff or in the future
983      we can use threads. */
984   /* Perform name and address lookups for the remote host. */
985   silc_net_check_host_by_sock(sock, &newsocket->hostname, &newsocket->ip);
986   if ((server->params->require_reverse_mapping && !newsocket->hostname) ||
987       !newsocket->ip) {
988     SILC_LOG_ERROR(("IP/DNS lookup failed"));
989     server->stat.conn_failures++;
990     return;
991   }
992   if (!newsocket->hostname)
993     newsocket->hostname = strdup(newsocket->ip);
994   newsocket->port = silc_net_get_remote_port(sock);
995
996   SILC_LOG_INFO(("Incoming connection from %s (%s)", newsocket->hostname,
997                  newsocket->ip));
998
999   /* Allocate internal context for key exchange protocol. This is
1000      sent as context for the protocol. */
1001   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1002   proto_ctx->server = context;
1003   proto_ctx->sock = newsocket;
1004   proto_ctx->rng = server->rng;
1005   proto_ctx->responder = TRUE;
1006
1007   /* Prepare the connection for key exchange protocol. We allocate the
1008      protocol but will not start it yet. The connector will be the
1009      initiator of the protocol thus we will wait for initiation from 
1010      there before we start the protocol. */
1011   server->stat.auth_attempts++;
1012   silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE, 
1013                       &newsocket->protocol, proto_ctx, 
1014                       silc_server_accept_new_connection_second);
1015
1016   /* Register a timeout task that will be executed if the connector
1017      will not start the key exchange protocol within 60 seconds. For
1018      now, this is a hard coded limit. After 60 secs the connection will
1019      be closed if the key exchange protocol has not been started. */
1020   proto_ctx->timeout_task = 
1021     silc_task_register(server->timeout_queue, newsocket->sock, 
1022                        silc_server_timeout_remote,
1023                        context, 60, 0,
1024                        SILC_TASK_TIMEOUT,
1025                        SILC_TASK_PRI_LOW);
1026
1027   /* Register the connection for network input and output. This sets
1028      that scheduler will listen for incoming packets for this connection 
1029      and sets that outgoing packets may be sent to this connection as well.
1030      However, this doesn't set the scheduler for outgoing traffic, it
1031      will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1032      later when outgoing data is available. */
1033   SILC_REGISTER_CONNECTION_FOR_IO(sock);
1034 }
1035
1036 /* Second part of accepting new connection. Key exchange protocol has been
1037    performed and now it is time to do little connection authentication
1038    protocol to figure out whether this connection is client or server
1039    and whether it has right to access this server (especially server
1040    connections needs to be authenticated). */
1041
1042 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1043 {
1044   SilcProtocol protocol = (SilcProtocol)context;
1045   SilcServerKEInternalContext *ctx = 
1046     (SilcServerKEInternalContext *)protocol->context;
1047   SilcServer server = (SilcServer)ctx->server;
1048   SilcSocketConnection sock = NULL;
1049   SilcServerConnAuthInternalContext *proto_ctx;
1050
1051   SILC_LOG_DEBUG(("Start"));
1052
1053   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1054       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1055     /* Error occured during protocol */
1056     silc_protocol_free(protocol);
1057     silc_ske_free_key_material(ctx->keymat);
1058     if (ctx->packet)
1059       silc_packet_context_free(ctx->packet);
1060     if (ctx->ske)
1061       silc_ske_free(ctx->ske);
1062     if (ctx->dest_id)
1063       silc_free(ctx->dest_id);
1064     silc_free(ctx);
1065     silc_task_unregister_by_callback(server->timeout_queue,
1066                                      silc_server_failure_callback);
1067     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1068                                   "Key exchange failed");
1069     server->stat.auth_failures++;
1070     return;
1071   }
1072
1073   /* We now have the key material as the result of the key exchange
1074      protocol. Take the key material into use. Free the raw key material
1075      as soon as we've set them into use. */
1076   if (!silc_server_protocol_ke_set_keys(ctx->ske, ctx->sock, ctx->keymat,
1077                                         ctx->ske->prop->cipher,
1078                                         ctx->ske->prop->pkcs,
1079                                         ctx->ske->prop->hash,
1080                                         ctx->ske->prop->hmac,
1081                                         ctx->responder)) {
1082     silc_protocol_free(protocol);
1083     silc_ske_free_key_material(ctx->keymat);
1084     if (ctx->packet)
1085       silc_packet_context_free(ctx->packet);
1086     if (ctx->ske)
1087       silc_ske_free(ctx->ske);
1088     if (ctx->dest_id)
1089       silc_free(ctx->dest_id);
1090     silc_free(ctx);
1091     silc_task_unregister_by_callback(server->timeout_queue,
1092                                      silc_server_failure_callback);
1093     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1094                                   "Key exchange failed");
1095     server->stat.auth_failures++;
1096     return;
1097   }    
1098   silc_ske_free_key_material(ctx->keymat);
1099
1100   /* Allocate internal context for the authentication protocol. This
1101      is sent as context for the protocol. */
1102   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1103   proto_ctx->server = (void *)server;
1104   proto_ctx->sock = sock = server->sockets[fd];
1105   proto_ctx->ske = ctx->ske;    /* Save SKE object from previous protocol */
1106   proto_ctx->responder = TRUE;
1107   proto_ctx->dest_id_type = ctx->dest_id_type;
1108   proto_ctx->dest_id = ctx->dest_id;
1109
1110   /* Free old protocol as it is finished now */
1111   silc_protocol_free(protocol);
1112   if (ctx->packet)
1113     silc_packet_context_free(ctx->packet);
1114   silc_free(ctx);
1115   sock->protocol = NULL;
1116
1117   /* Allocate the authentication protocol. This is allocated here
1118      but we won't start it yet. We will be receiving party of this
1119      protocol thus we will wait that connecting party will make
1120      their first move. */
1121   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH, 
1122                       &sock->protocol, proto_ctx, 
1123                       silc_server_accept_new_connection_final);
1124
1125   /* Register timeout task. If the protocol is not executed inside
1126      this timelimit the connection will be terminated. Currently
1127      this is 60 seconds and is hard coded limit (XXX). */
1128   proto_ctx->timeout_task = 
1129     silc_task_register(server->timeout_queue, sock->sock, 
1130                        silc_server_timeout_remote,
1131                        (void *)server, 60, 0,
1132                        SILC_TASK_TIMEOUT,
1133                        SILC_TASK_PRI_LOW);
1134 }
1135
1136 /* Final part of accepting new connection. The connection has now
1137    been authenticated and keys has been exchanged. We also know whether
1138    this is client or server connection. */
1139
1140 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1141 {
1142   SilcProtocol protocol = (SilcProtocol)context;
1143   SilcServerConnAuthInternalContext *ctx = 
1144     (SilcServerConnAuthInternalContext *)protocol->context;
1145   SilcServer server = (SilcServer)ctx->server;
1146   SilcSocketConnection sock = ctx->sock;
1147   SilcServerHBContext hb_context;
1148   void *id_entry = NULL;
1149
1150   SILC_LOG_DEBUG(("Start"));
1151
1152   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1153       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1154     /* Error occured during protocol */
1155     silc_protocol_free(protocol);
1156     if (ctx->packet)
1157       silc_packet_context_free(ctx->packet);
1158     if (ctx->ske)
1159       silc_ske_free(ctx->ske);
1160     if (ctx->dest_id)
1161       silc_free(ctx->dest_id);
1162     silc_free(ctx);
1163     if (sock)
1164       sock->protocol = NULL;
1165     silc_task_unregister_by_callback(server->timeout_queue,
1166                                      silc_server_failure_callback);
1167     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1168                                   "Authentication failed");
1169     server->stat.auth_failures++;
1170     return;
1171   }
1172
1173   sock->type = ctx->conn_type;
1174   switch(sock->type) {
1175   case SILC_SOCKET_TYPE_CLIENT:
1176     {
1177       SilcClientEntry client;
1178
1179       SILC_LOG_DEBUG(("Remote host is client"));
1180       SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
1181                      sock->ip));
1182
1183       /* Add the client to the client ID cache. The nickname and Client ID
1184          and other information is created after we have received NEW_CLIENT
1185          packet from client. */
1186       client = silc_idlist_add_client(server->local_list, 
1187                                       NULL, 0, NULL, NULL, NULL, NULL, sock);
1188       if (!client) {
1189         SILC_LOG_ERROR(("Could not add new client to cache"));
1190         silc_free(sock->user_data);
1191         break;
1192       }
1193
1194       /* Statistics */
1195       server->stat.my_clients++;
1196       server->stat.clients++;
1197       if (server->server_type == SILC_ROUTER)
1198         server->stat.cell_clients++;
1199
1200       id_entry = (void *)client;
1201       break;
1202     }
1203   case SILC_SOCKET_TYPE_SERVER:
1204   case SILC_SOCKET_TYPE_ROUTER:
1205     {
1206       SilcServerEntry new_server;
1207
1208       SILC_LOG_DEBUG(("Remote host is %s", 
1209                       sock->type == SILC_SOCKET_TYPE_SERVER ? 
1210                       "server" : "router"));
1211       SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
1212                      sock->ip, sock->type == SILC_SOCKET_TYPE_SERVER ? 
1213                      "server" : "router"));
1214
1215       /* Add the server into server cache. The server name and Server ID
1216          is updated after we have received NEW_SERVER packet from the
1217          server. We mark ourselves as router for this server if we really
1218          are router. */
1219       new_server = 
1220         silc_idlist_add_server(server->local_list, NULL,
1221                                sock->type == SILC_SOCKET_TYPE_SERVER ?
1222                                SILC_SERVER : SILC_ROUTER, NULL, 
1223                                sock->type == SILC_SOCKET_TYPE_SERVER ?
1224                                server->id_entry : NULL, sock);
1225       if (!new_server) {
1226         SILC_LOG_ERROR(("Could not add new server to cache"));
1227         silc_free(sock->user_data);
1228         break;
1229       }
1230
1231       /* Statistics */
1232       if (sock->type == SILC_SOCKET_TYPE_SERVER)
1233         server->stat.my_servers++;
1234       else
1235         server->stat.my_routers++;
1236       server->stat.servers++;
1237
1238       id_entry = (void *)new_server;
1239       
1240       /* There is connection to other server now, if it is router then
1241          we will have connection to outside world.  If we are router but
1242          normal server connected to us then we will remain standalone,
1243          if we are standlone. */
1244       if (server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER) {
1245         SILC_LOG_DEBUG(("We are not standalone server anymore"));
1246         server->standalone = FALSE;
1247         if (!server->id_entry->router) {
1248           server->id_entry->router = id_entry;
1249           server->router = id_entry;
1250         }
1251       }
1252       break;
1253     }
1254   default:
1255     break;
1256   }
1257
1258   /* Add the common data structure to the ID entry. */
1259   if (id_entry)
1260     silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1261       
1262   /* Add to sockets internal pointer for fast referencing */
1263   silc_free(sock->user_data);
1264   sock->user_data = id_entry;
1265
1266   /* Connection has been fully established now. Everything is ok. */
1267   SILC_LOG_DEBUG(("New connection authenticated"));
1268
1269   /* Perform keepalive. The `hb_context' will be freed automatically
1270      when finally calling the silc_socket_free function. XXX hardcoded 
1271      timeout!! */
1272   hb_context = silc_calloc(1, sizeof(*hb_context));
1273   hb_context->server = server;
1274   silc_socket_set_heartbeat(sock, 600, hb_context,
1275                             silc_server_perform_heartbeat,
1276                             server->timeout_queue);
1277
1278   silc_task_unregister_by_callback(server->timeout_queue,
1279                                    silc_server_failure_callback);
1280   silc_protocol_free(protocol);
1281   if (ctx->packet)
1282     silc_packet_context_free(ctx->packet);
1283   if (ctx->ske)
1284     silc_ske_free(ctx->ske);
1285   if (ctx->dest_id)
1286     silc_free(ctx->dest_id);
1287   silc_free(ctx);
1288   sock->protocol = NULL;
1289 }
1290
1291 /* This function is used to read packets from network and send packets to
1292    network. This is usually a generic task. */
1293
1294 SILC_TASK_CALLBACK(silc_server_packet_process)
1295 {
1296   SilcServer server = (SilcServer)context;
1297   SilcSocketConnection sock = server->sockets[fd];
1298   SilcIDListData idata;
1299   SilcCipher cipher = NULL;
1300   SilcHmac hmac = NULL;
1301   int ret;
1302
1303   if (!sock)
1304     return;
1305
1306   SILC_LOG_DEBUG(("Processing packet"));
1307
1308   /* Packet sending */
1309
1310   if (type == SILC_TASK_WRITE) {
1311     /* Do not send data to disconnected connection */
1312     if (SILC_IS_DISCONNECTED(sock))
1313       return;
1314
1315     server->stat.packets_sent++;
1316
1317     if (sock->outbuf->data - sock->outbuf->head)
1318      silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1319
1320     ret = silc_server_packet_send_real(server, sock, TRUE);
1321
1322     /* If returned -2 could not write to connection now, will do
1323        it later. */
1324     if (ret == -2)
1325       return;
1326
1327     if (ret == -1)
1328       return;
1329     
1330     /* The packet has been sent and now it is time to set the connection
1331        back to only for input. When there is again some outgoing data 
1332        available for this connection it will be set for output as well. 
1333        This call clears the output setting and sets it only for input. */
1334     SILC_SET_CONNECTION_FOR_INPUT(fd);
1335     SILC_UNSET_OUTBUF_PENDING(sock);
1336
1337     silc_buffer_clear(sock->outbuf);
1338     return;
1339   }
1340
1341   /* Packet receiving */
1342
1343   /* Read some data from connection */
1344   ret = silc_packet_receive(sock);
1345   if (ret < 0)
1346     return;
1347     
1348   /* EOF */
1349   if (ret == 0) {
1350     SILC_LOG_DEBUG(("Read EOF"));
1351       
1352     /* If connection is disconnecting already we will finally
1353        close the connection */
1354     if (SILC_IS_DISCONNECTING(sock)) {
1355       if (sock->user_data)
1356         silc_server_free_sock_user_data(server, sock);
1357       silc_server_close_connection(server, sock);
1358       return;
1359     }
1360       
1361     SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1362     SILC_SET_DISCONNECTING(sock);
1363
1364     /* If the closed connection was our primary router connection the
1365        start re-connecting phase. */
1366     if (!server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER && 
1367         sock == server->router->connection)
1368       silc_task_register(server->timeout_queue, 0, 
1369                          silc_server_connect_to_router,
1370                          context, 1, 0,
1371                          SILC_TASK_TIMEOUT,
1372                          SILC_TASK_PRI_NORMAL);
1373
1374     if (sock->user_data)
1375       silc_server_free_sock_user_data(server, sock);
1376     silc_server_close_connection(server, sock);
1377     return;
1378   }
1379
1380   /* If connection is disconnecting or disconnected we will ignore
1381      what we read. */
1382   if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1383     SILC_LOG_DEBUG(("Ignoring read data from disonnected connection"));
1384     return;
1385   }
1386
1387   server->stat.packets_received++;
1388
1389   /* Get keys and stuff from ID entry */
1390   idata = (SilcIDListData)sock->user_data;
1391   if (idata) {
1392     idata->last_receive = time(NULL);
1393     cipher = idata->receive_key;
1394     hmac = idata->hmac;
1395   }
1396  
1397   /* Process the packet. This will call the parser that will then
1398      decrypt and parse the packet. */
1399   silc_packet_receive_process(sock, cipher, hmac, silc_server_packet_parse, 
1400                               server);
1401 }
1402
1403 /* Callback function that the silc_packet_decrypt will call to make the
1404    decision whether the packet is normal or special packet. We will 
1405    return TRUE if it is normal and FALSE if it is special */
1406
1407 static int silc_server_packet_decrypt_check(SilcPacketType packet_type,
1408                                             SilcBuffer buffer,
1409                                             SilcPacketContext *packet,
1410                                             void *context)
1411 {
1412   SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1413   SilcServer server = (SilcServer)parse_ctx->context;
1414
1415   /* Packet is normal packet, if: 
1416
1417      1) packet is private message packet and does not have private key set
1418      2) is other packet than channel message packet
1419      3) is channel message packet and remote is router and we are router 
1420
1421      all other packets are special packets 
1422   */
1423   if ((packet_type == SILC_PACKET_PRIVATE_MESSAGE &&
1424        !(buffer->data[2] & SILC_PACKET_FLAG_PRIVMSG_KEY)) ||
1425       packet_type != SILC_PACKET_CHANNEL_MESSAGE || 
1426       (packet_type == SILC_PACKET_CHANNEL_MESSAGE &&
1427        parse_ctx->sock->type == SILC_SOCKET_TYPE_ROUTER &&
1428        server->server_type == SILC_ROUTER))
1429     return TRUE;
1430
1431   return FALSE;
1432 }
1433
1434 /* Parses whole packet, received earlier. */
1435
1436 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1437 {
1438   SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1439   SilcServer server = (SilcServer)parse_ctx->context;
1440   SilcSocketConnection sock = parse_ctx->sock;
1441   SilcPacketContext *packet = parse_ctx->packet;
1442   int ret;
1443
1444   SILC_LOG_DEBUG(("Start"));
1445
1446   /* Decrypt the received packet */
1447   ret = silc_packet_decrypt(parse_ctx->cipher, parse_ctx->hmac, 
1448                             packet->buffer, packet,
1449                             silc_server_packet_decrypt_check, parse_ctx);
1450   if (ret < 0)
1451     goto out;
1452
1453   if (ret == 0) {
1454     /* Parse the packet. Packet type is returned. */
1455     ret = silc_packet_parse(packet);
1456   } else {
1457     /* Parse the packet header in special way as this is "special"
1458        packet type. */
1459     ret = silc_packet_parse_special(packet);
1460   }
1461
1462   if (ret == SILC_PACKET_NONE)
1463     goto out;
1464
1465   /* Check that the the current client ID is same as in the client's packet. */
1466   if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1467     SilcClientEntry client = (SilcClientEntry)sock->user_data;
1468     if (client && client->id) {
1469       void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1470                                 packet->src_id_type);
1471       if (SILC_ID_CLIENT_COMPARE(client->id, id)) {
1472         silc_free(id);
1473         goto out;
1474       }
1475       silc_free(id);
1476     }
1477   }
1478
1479   if (server->server_type == SILC_ROUTER) {
1480     /* Route the packet if it is not destined to us. Other ID types but
1481        server are handled separately after processing them. */
1482     if (packet->dst_id_type == SILC_ID_SERVER && 
1483         sock->type != SILC_SOCKET_TYPE_CLIENT &&
1484         SILC_ID_SERVER_COMPARE(packet->dst_id, server->id_string)) {
1485       
1486       /* Route the packet to fastest route for the destination ID */
1487       void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len, 
1488                                 packet->dst_id_type);
1489       if (!id)
1490         goto out;
1491       silc_server_packet_route(server,
1492                                silc_server_route_get(server, id,
1493                                                      packet->dst_id_type),
1494                                packet);
1495       silc_free(id);
1496       goto out;
1497     }
1498     
1499     /* Broadcast packet if it is marked as broadcast packet and it is
1500        originated from router and we are router. */
1501     if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1502         packet->flags & SILC_PACKET_FLAG_BROADCAST) {
1503       silc_server_packet_broadcast(server, server->router->connection, packet);
1504     }
1505   }
1506
1507   /* Parse the incoming packet type */
1508   silc_server_packet_parse_type(server, sock, packet);
1509
1510  out:
1511   silc_buffer_clear(sock->inbuf);
1512   silc_packet_context_free(packet);
1513   silc_free(parse_ctx);
1514 }
1515
1516 /* Parser callback called by silc_packet_receive_process. This merely
1517    registers timeout that will handle the actual parsing when appropriate. */
1518
1519 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1520 {
1521   SilcServer server = (SilcServer)parser_context->context;
1522   SilcSocketConnection sock = parser_context->sock;
1523
1524   switch (sock->type) {
1525   case SILC_SOCKET_TYPE_CLIENT:
1526   case SILC_SOCKET_TYPE_UNKNOWN:
1527     /* Parse the packet with timeout */
1528     silc_task_register(server->timeout_queue, sock->sock,
1529                        silc_server_packet_parse_real,
1530                        (void *)parser_context, 0, 100000,
1531                        SILC_TASK_TIMEOUT,
1532                        SILC_TASK_PRI_NORMAL);
1533     break;
1534   case SILC_SOCKET_TYPE_SERVER:
1535   case SILC_SOCKET_TYPE_ROUTER:
1536     /* Packets from servers are parsed as soon as possible */
1537     silc_task_register(server->timeout_queue, sock->sock,
1538                        silc_server_packet_parse_real,
1539                        (void *)parser_context, 0, 1,
1540                        SILC_TASK_TIMEOUT,
1541                        SILC_TASK_PRI_NORMAL);
1542     break;
1543   default:
1544     return;
1545   }
1546 }
1547
1548 /* Parses the packet type and calls what ever routines the packet type
1549    requires. This is done for all incoming packets. */
1550
1551 void silc_server_packet_parse_type(SilcServer server, 
1552                                    SilcSocketConnection sock,
1553                                    SilcPacketContext *packet)
1554 {
1555   SilcPacketType type = packet->type;
1556
1557   SILC_LOG_DEBUG(("Parsing packet type %d", type));
1558
1559   /* Parse the packet type */
1560   switch(type) {
1561   case SILC_PACKET_DISCONNECT:
1562     SILC_LOG_DEBUG(("Disconnect packet"));
1563     if (packet->flags & SILC_PACKET_FLAG_LIST)
1564       break;
1565     break;
1566
1567   case SILC_PACKET_SUCCESS:
1568     /*
1569      * Success received for something. For now we can have only
1570      * one protocol for connection executing at once hence this
1571      * success message is for whatever protocol is executing currently.
1572      */
1573     SILC_LOG_DEBUG(("Success packet"));
1574     if (packet->flags & SILC_PACKET_FLAG_LIST)
1575       break;
1576     if (sock->protocol) {
1577       sock->protocol->execute(server->timeout_queue, 0,
1578                               sock->protocol, sock->sock, 0, 0);
1579     }
1580     break;
1581
1582   case SILC_PACKET_FAILURE:
1583     /*
1584      * Failure received for something. For now we can have only
1585      * one protocol for connection executing at once hence this
1586      * failure message is for whatever protocol is executing currently.
1587      */
1588     SILC_LOG_DEBUG(("Failure packet"));
1589     if (packet->flags & SILC_PACKET_FLAG_LIST)
1590       break;
1591     if (sock->protocol) {
1592       SilcServerFailureContext f;
1593       f = silc_calloc(1, sizeof(*f));
1594       f->server = server;
1595       f->sock = sock;
1596       
1597       /* We will wait 5 seconds to process this failure packet */
1598       silc_task_register(server->timeout_queue, sock->sock,
1599                          silc_server_failure_callback, (void *)f, 5, 0,
1600                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1601     }
1602     break;
1603
1604   case SILC_PACKET_REJECT:
1605     SILC_LOG_DEBUG(("Reject packet"));
1606     if (packet->flags & SILC_PACKET_FLAG_LIST)
1607       break;
1608     return;
1609     break;
1610
1611   case SILC_PACKET_NOTIFY:
1612     /*
1613      * Received notify packet. Server can receive notify packets from
1614      * router. Server then relays the notify messages to clients if needed.
1615      */
1616     SILC_LOG_DEBUG(("Notify packet"));
1617     if (packet->flags & SILC_PACKET_FLAG_LIST)
1618       silc_server_notify_list(server, sock, packet);
1619     else
1620       silc_server_notify(server, sock, packet);
1621     break;
1622
1623     /* 
1624      * Channel packets
1625      */
1626   case SILC_PACKET_CHANNEL_MESSAGE:
1627     /*
1628      * Received channel message. Channel messages are special packets
1629      * (although probably most common ones) thus they are handled
1630      * specially.
1631      */
1632     SILC_LOG_DEBUG(("Channel Message packet"));
1633     if (packet->flags & SILC_PACKET_FLAG_LIST)
1634       break;
1635     silc_server_channel_message(server, sock, packet);
1636     break;
1637
1638   case SILC_PACKET_CHANNEL_KEY:
1639     /*
1640      * Received key for channel. As channels are created by the router
1641      * the keys are as well. We will distribute the key to all of our
1642      * locally connected clients on the particular channel. Router
1643      * never receives this channel and thus is ignored.
1644      */
1645     SILC_LOG_DEBUG(("Channel Key packet"));
1646     if (packet->flags & SILC_PACKET_FLAG_LIST)
1647       break;
1648     silc_server_channel_key(server, sock, packet);
1649     break;
1650
1651     /*
1652      * Command packets
1653      */
1654   case SILC_PACKET_COMMAND:
1655     /*
1656      * Recived command. Processes the command request and allocates the
1657      * command context and calls the command.
1658      */
1659     SILC_LOG_DEBUG(("Command packet"));
1660     if (packet->flags & SILC_PACKET_FLAG_LIST)
1661       break;
1662     silc_server_command_process(server, sock, packet);
1663     break;
1664
1665   case SILC_PACKET_COMMAND_REPLY:
1666     /*
1667      * Received command reply packet. Received command reply to command. It
1668      * may be reply to command sent by us or reply to command sent by client
1669      * that we've routed further.
1670      */
1671     SILC_LOG_DEBUG(("Command Reply packet"));
1672     if (packet->flags & SILC_PACKET_FLAG_LIST)
1673       break;
1674     silc_server_command_reply(server, sock, packet);
1675     break;
1676
1677     /*
1678      * Private Message packets
1679      */
1680   case SILC_PACKET_PRIVATE_MESSAGE:
1681     /*
1682      * Received private message packet. The packet is coming from either
1683      * client or server.
1684      */
1685     SILC_LOG_DEBUG(("Private Message packet"));
1686     if (packet->flags & SILC_PACKET_FLAG_LIST)
1687       break;
1688     silc_server_private_message(server, sock, packet);
1689     break;
1690
1691   case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1692     /*
1693      * Private message key packet.
1694      */
1695     if (packet->flags & SILC_PACKET_FLAG_LIST)
1696       break;
1697     silc_server_private_message_key(server, sock, packet);
1698     break;
1699
1700     /*
1701      * Key Exchange protocol packets
1702      */
1703   case SILC_PACKET_KEY_EXCHANGE:
1704     SILC_LOG_DEBUG(("KE packet"));
1705     if (packet->flags & SILC_PACKET_FLAG_LIST)
1706       break;
1707
1708     if (sock->protocol && sock->protocol->protocol->type 
1709         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1710
1711       SilcServerKEInternalContext *proto_ctx = 
1712         (SilcServerKEInternalContext *)sock->protocol->context;
1713
1714       proto_ctx->packet = silc_packet_context_dup(packet);
1715
1716       /* Let the protocol handle the packet */
1717       sock->protocol->execute(server->timeout_queue, 0, 
1718                               sock->protocol, sock->sock, 0, 100000);
1719     } else {
1720       SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1721                       "protocol active, packet dropped."));
1722
1723       /* XXX Trigger KE protocol?? Rekey actually, maybe. */
1724     }
1725     break;
1726
1727   case SILC_PACKET_KEY_EXCHANGE_1:
1728     SILC_LOG_DEBUG(("KE 1 packet"));
1729     if (packet->flags & SILC_PACKET_FLAG_LIST)
1730       break;
1731
1732     if (sock->protocol && sock->protocol->protocol->type 
1733         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1734
1735       SilcServerKEInternalContext *proto_ctx = 
1736         (SilcServerKEInternalContext *)sock->protocol->context;
1737
1738       if (proto_ctx->packet)
1739         silc_packet_context_free(proto_ctx->packet);
1740
1741       proto_ctx->packet = silc_packet_context_dup(packet);
1742       proto_ctx->dest_id_type = packet->src_id_type;
1743       proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1744                                           packet->src_id_type);
1745       if (!proto_ctx->dest_id)
1746         break;
1747
1748       /* Let the protocol handle the packet */
1749       sock->protocol->execute(server->timeout_queue, 0, 
1750                               sock->protocol, sock->sock,
1751                               0, 100000);
1752     } else {
1753       SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1754                       "protocol active, packet dropped."));
1755     }
1756     break;
1757
1758   case SILC_PACKET_KEY_EXCHANGE_2:
1759     SILC_LOG_DEBUG(("KE 2 packet"));
1760     if (packet->flags & SILC_PACKET_FLAG_LIST)
1761       break;
1762
1763     if (sock->protocol && sock->protocol->protocol->type 
1764         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1765
1766       SilcServerKEInternalContext *proto_ctx = 
1767         (SilcServerKEInternalContext *)sock->protocol->context;
1768
1769       if (proto_ctx->packet)
1770         silc_packet_context_free(proto_ctx->packet);
1771
1772       proto_ctx->packet = silc_packet_context_dup(packet);
1773       proto_ctx->dest_id_type = packet->src_id_type;
1774       proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1775                                           packet->src_id_type);
1776       if (!proto_ctx->dest_id)
1777         break;
1778
1779       /* Let the protocol handle the packet */
1780       sock->protocol->execute(server->timeout_queue, 0, 
1781                               sock->protocol, sock->sock,
1782                               0, 100000);
1783     } else {
1784       SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1785                       "protocol active, packet dropped."));
1786     }
1787     break;
1788
1789   case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1790     /*
1791      * Connection authentication request packet. When we receive this packet
1792      * we will send to the other end information about our mandatory
1793      * authentication method for the connection. This packet maybe received
1794      * at any time. 
1795      */
1796     SILC_LOG_DEBUG(("Connection authentication request packet"));
1797     if (packet->flags & SILC_PACKET_FLAG_LIST)
1798       break;
1799     break;
1800
1801     /*
1802      * Connection Authentication protocol packets
1803      */
1804   case SILC_PACKET_CONNECTION_AUTH:
1805     /* Start of the authentication protocol. We receive here the 
1806        authentication data and will verify it. */
1807     SILC_LOG_DEBUG(("Connection auth packet"));
1808     if (packet->flags & SILC_PACKET_FLAG_LIST)
1809       break;
1810
1811     if (sock->protocol && sock->protocol->protocol->type 
1812         == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1813
1814       SilcServerConnAuthInternalContext *proto_ctx = 
1815         (SilcServerConnAuthInternalContext *)sock->protocol->context;
1816
1817       proto_ctx->packet = silc_packet_context_dup(packet);
1818
1819       /* Let the protocol handle the packet */
1820       sock->protocol->execute(server->timeout_queue, 0, 
1821                               sock->protocol, sock->sock, 0, 0);
1822     } else {
1823       SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1824                       "protocol active, packet dropped."));
1825     }
1826     break;
1827
1828   case SILC_PACKET_NEW_ID:
1829     /*
1830      * Received New ID packet. This includes some new ID that has been
1831      * created. It may be for client, server or channel. This is the way
1832      * to distribute information about new registered entities in the
1833      * SILC network.
1834      */
1835     SILC_LOG_DEBUG(("New ID packet"));
1836     if (packet->flags & SILC_PACKET_FLAG_LIST)
1837       silc_server_new_id_list(server, sock, packet);
1838     else
1839       silc_server_new_id(server, sock, packet);
1840     break;
1841
1842   case SILC_PACKET_NEW_CLIENT:
1843     /*
1844      * Received new client packet. This includes client information that
1845      * we will use to create initial client ID. After creating new
1846      * ID we will send it to the client.
1847      */
1848     SILC_LOG_DEBUG(("New Client packet"));
1849     if (packet->flags & SILC_PACKET_FLAG_LIST)
1850       break;
1851     silc_server_new_client(server, sock, packet);
1852     break;
1853
1854   case SILC_PACKET_NEW_SERVER:
1855     /*
1856      * Received new server packet. This includes Server ID and some other
1857      * information that we may save. This is received after server has 
1858      * connected to us.
1859      */
1860     SILC_LOG_DEBUG(("New Server packet"));
1861     if (packet->flags & SILC_PACKET_FLAG_LIST)
1862       break;
1863     silc_server_new_server(server, sock, packet);
1864     break;
1865
1866   case SILC_PACKET_NEW_CHANNEL:
1867     /*
1868      * Received new channel packet. Information about new channel in the
1869      * network are distributed using this packet.
1870      */
1871     SILC_LOG_DEBUG(("New Channel packet"));
1872     if (packet->flags & SILC_PACKET_FLAG_LIST)
1873       silc_server_new_channel_list(server, sock, packet);
1874     else
1875       silc_server_new_channel(server, sock, packet);
1876     break;
1877
1878   case SILC_PACKET_HEARTBEAT:
1879     /*
1880      * Received heartbeat.
1881      */
1882     SILC_LOG_DEBUG(("Heartbeat packet"));
1883     if (packet->flags & SILC_PACKET_FLAG_LIST)
1884       break;
1885     break;
1886
1887   case SILC_PACKET_KEY_AGREEMENT:
1888     /*
1889      * Received heartbeat.
1890      */
1891     SILC_LOG_DEBUG(("Key agreement packet"));
1892     if (packet->flags & SILC_PACKET_FLAG_LIST)
1893       break;
1894     silc_server_key_agreement(server, sock, packet);
1895     break;
1896
1897   default:
1898     SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
1899     break;
1900   }
1901   
1902 }
1903
1904 /* Creates connection to a remote router. */
1905
1906 void silc_server_create_connection(SilcServer server,
1907                                    char *remote_host, unsigned int port)
1908 {
1909   SilcServerConnection sconn;
1910
1911   /* Allocate connection object for hold connection specific stuff. */
1912   sconn = silc_calloc(1, sizeof(*sconn));
1913   sconn->server = server;
1914   sconn->remote_host = strdup(remote_host);
1915   sconn->remote_port = port;
1916
1917   silc_task_register(server->timeout_queue, 0, 
1918                      silc_server_connect_router,
1919                      (void *)sconn, 0, 1, SILC_TASK_TIMEOUT, 
1920                      SILC_TASK_PRI_NORMAL);
1921 }
1922
1923 /* Closes connection to socket connection */
1924
1925 void silc_server_close_connection(SilcServer server,
1926                                   SilcSocketConnection sock)
1927 {
1928   SILC_LOG_DEBUG(("Closing connection %d", sock->sock));
1929
1930   /* We won't listen for this connection anymore */
1931   silc_schedule_unset_listen_fd(sock->sock);
1932
1933   /* Unregister all tasks */
1934   silc_task_unregister_by_fd(server->io_queue, sock->sock);
1935   silc_task_unregister_by_fd(server->timeout_queue, sock->sock);
1936
1937   /* Close the actual connection */
1938   silc_net_close_connection(sock->sock);
1939   server->sockets[sock->sock] = NULL;
1940   silc_socket_free(sock);
1941 }
1942
1943 /* Sends disconnect message to remote connection and disconnects the 
1944    connection. */
1945
1946 void silc_server_disconnect_remote(SilcServer server,
1947                                    SilcSocketConnection sock,
1948                                    const char *fmt, ...)
1949 {
1950   va_list ap;
1951   unsigned char buf[4096];
1952
1953   if (!sock)
1954     return;
1955
1956   memset(buf, 0, sizeof(buf));
1957   va_start(ap, fmt);
1958   vsprintf(buf, fmt, ap);
1959   va_end(ap);
1960
1961   SILC_LOG_DEBUG(("Disconnecting remote host"));
1962
1963   SILC_LOG_INFO(("Disconnecting %s:%d [%s]", sock->hostname,
1964                   sock->port,
1965                   (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1966                    sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1967                    sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1968                    "Router")));
1969
1970   /* Notify remote end that the conversation is over. The notify message
1971      is tried to be sent immediately. */
1972   silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,  
1973                           buf, strlen(buf), TRUE);
1974
1975   /* Mark the connection to be disconnected */
1976   SILC_SET_DISCONNECTED(sock);
1977   silc_server_close_connection(server, sock);
1978 }
1979
1980 typedef struct {
1981   SilcServer server;
1982   SilcClientEntry client;
1983 } *FreeClientInternal;
1984
1985 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
1986 {
1987   FreeClientInternal i = (FreeClientInternal)context;
1988
1989   silc_idlist_del_data(i->client);
1990   silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
1991   silc_free(i);
1992 }
1993
1994 /* Frees client data and notifies about client's signoff. */
1995
1996 void silc_server_free_client_data(SilcServer server, 
1997                                   SilcSocketConnection sock,
1998                                   SilcClientEntry client, 
1999                                   int notify,
2000                                   char *signoff)
2001 {
2002   FreeClientInternal i = silc_calloc(1, sizeof(*i));
2003
2004   /* If there is pending outgoing data for the client then purge it
2005      to the network before removing the client entry. */
2006   if (sock && SILC_IS_OUTBUF_PENDING(sock) && 
2007       (SILC_IS_DISCONNECTED(sock) == FALSE)) {
2008     server->stat.packets_sent++;
2009
2010     if (sock->outbuf->data - sock->outbuf->head)
2011      silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
2012
2013     silc_server_packet_send_real(server, sock, TRUE);
2014
2015     SILC_SET_CONNECTION_FOR_INPUT(sock->sock);
2016     SILC_UNSET_OUTBUF_PENDING(sock);
2017     silc_buffer_clear(sock->outbuf);
2018   }
2019
2020   /* Send SIGNOFF notify to routers. */
2021   if (notify && !server->standalone && server->router)
2022     silc_server_send_notify_signoff(server, server->router->connection,
2023                                     server->server_type == SILC_SERVER ?
2024                                     FALSE : TRUE, client->id, 
2025                                     SILC_ID_CLIENT_LEN, signoff);
2026
2027   /* Remove client from all channels */
2028   if (notify)
2029     silc_server_remove_from_channels(server, NULL, client, 
2030                                      TRUE, signoff, TRUE);
2031   else
2032     silc_server_remove_from_channels(server, NULL, client, 
2033                                      FALSE, NULL, FALSE);
2034
2035   /* We will not delete the client entry right away. We will take it
2036      into history (for WHOWAS command) for 5 minutes */
2037   i->server = server;
2038   i->client = client;
2039   silc_task_register(server->timeout_queue, 0, 
2040                      silc_server_free_client_data_timeout,
2041                      (void *)i, 300, 0,
2042                      SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2043   client->data.registered = FALSE;
2044
2045   /* Free the client entry and everything in it */
2046   server->stat.my_clients--;
2047   server->stat.clients--;
2048   if (server->server_type == SILC_ROUTER)
2049     server->stat.cell_clients--;
2050 }
2051
2052 /* Frees user_data pointer from socket connection object. This also sends
2053    appropriate notify packets to the network to inform about leaving
2054    entities. */
2055
2056 void silc_server_free_sock_user_data(SilcServer server, 
2057                                      SilcSocketConnection sock)
2058 {
2059   SILC_LOG_DEBUG(("Start"));
2060
2061   switch(sock->type) {
2062   case SILC_SOCKET_TYPE_CLIENT:
2063     {
2064       SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2065       silc_server_free_client_data(server, sock, user_data, TRUE, NULL);
2066       break;
2067     }
2068   case SILC_SOCKET_TYPE_SERVER:
2069   case SILC_SOCKET_TYPE_ROUTER:
2070     {
2071       SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2072
2073       /* Send REMOVE_ID packet to routers. */
2074       if (!server->standalone && server->router)
2075         silc_server_send_notify_server_signoff(server, 
2076                                                server->router->connection,
2077                                                server->server_type == 
2078                                                SILC_SERVER ?
2079                                                FALSE : TRUE, user_data->id, 
2080                                                SILC_ID_SERVER_LEN);
2081
2082       /* Then also free all client entries that this server owns as
2083          they will become invalid now as well. */
2084       silc_server_remove_clients_by_server(server, user_data);
2085
2086       /* If this was our primary router connection then we're lost to
2087          the outside world. */
2088       if (server->router == user_data) {
2089         server->id_entry->router = NULL;
2090         server->router = NULL;
2091         server->standalone = TRUE;
2092       }
2093
2094       /* Free the server entry */
2095       silc_idlist_del_data(user_data);
2096       silc_idlist_del_server(server->local_list, user_data);
2097       server->stat.my_servers--;
2098       server->stat.servers--;
2099       if (server->server_type == SILC_ROUTER)
2100         server->stat.cell_servers--;
2101       break;
2102     }
2103   default:
2104     {
2105       SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2106
2107       silc_idlist_del_data(user_data);
2108       silc_free(user_data);
2109       break;
2110     }
2111   }
2112
2113   sock->user_data = NULL;
2114 }
2115
2116 /* This function is used to remove all client entries by the server `entry'.
2117    This is called when the connection is lost to the server. In this case
2118    we must invalidate all the client entries owned by the server `entry'. */
2119
2120 int silc_server_remove_clients_by_server(SilcServer server, 
2121                                          SilcServerEntry entry)
2122 {
2123   SilcIDCacheList list = NULL;
2124   SilcIDCacheEntry id_cache = NULL;
2125   SilcClientEntry client = NULL;
2126
2127   SILC_LOG_DEBUG(("Start"));
2128
2129   if (silc_idcache_find_by_id(server->local_list->clients, 
2130                               SILC_ID_CACHE_ANY, SILC_ID_CLIENT, &list)) {
2131
2132     if (silc_idcache_list_first(list, &id_cache)) {
2133       while (id_cache) {
2134         client = (SilcClientEntry)id_cache->context;
2135         
2136         if (client->router != entry) {
2137           if (!silc_idcache_list_next(list, &id_cache))
2138             break;
2139           else
2140             continue;
2141         }
2142
2143         /* Remove the client entry */
2144         silc_server_remove_from_channels(server, NULL, client, TRUE, 
2145                                          NULL, TRUE);
2146         silc_idlist_del_client(server->local_list, client);
2147
2148         if (!silc_idcache_list_next(list, &id_cache))
2149           break;
2150       }
2151     }
2152     silc_idcache_list_free(list);
2153   }
2154   
2155   if (silc_idcache_find_by_id(server->global_list->clients, 
2156                               SILC_ID_CACHE_ANY, SILC_ID_CLIENT, &list)) {
2157
2158     if (silc_idcache_list_first(list, &id_cache)) {
2159       while (id_cache) {
2160         client = (SilcClientEntry)id_cache->context;
2161         
2162         if (client->router != entry) {
2163           if (!silc_idcache_list_next(list, &id_cache))
2164             break;
2165           else
2166             continue;
2167         }
2168
2169         /* Remove the client entry */
2170         silc_server_remove_from_channels(server, NULL, client, TRUE,
2171                                          NULL, TRUE);
2172         silc_idlist_del_client(server->global_list, client);
2173
2174         if (!silc_idcache_list_next(list, &id_cache))
2175           break;
2176       }
2177     }
2178     silc_idcache_list_free(list);
2179   }
2180   
2181   return TRUE;
2182 }
2183
2184 /* Checks whether given channel has global users.  If it does this returns
2185    TRUE and FALSE if there is only locally connected clients on the channel. */
2186
2187 int silc_server_channel_has_global(SilcChannelEntry channel)
2188 {
2189   SilcChannelClientEntry chl;
2190
2191   silc_list_start(channel->user_list);
2192   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2193     if (chl->client->router)
2194       return TRUE;
2195   }
2196
2197   return FALSE;
2198 }
2199
2200 /* Checks whether given channel has locally connected users.  If it does this
2201    returns TRUE and FALSE if there is not one locally connected client. */
2202
2203 int silc_server_channel_has_local(SilcChannelEntry channel)
2204 {
2205   SilcChannelClientEntry chl;
2206
2207   silc_list_start(channel->user_list);
2208   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2209     if (!chl->client->router)
2210       return TRUE;
2211   }
2212
2213   return FALSE;
2214 }
2215
2216 /* Removes client from all channels it has joined. This is used when client
2217    connection is disconnected. If the client on a channel is last, the
2218    channel is removed as well. This sends the SIGNOFF notify types. */
2219
2220 void silc_server_remove_from_channels(SilcServer server, 
2221                                       SilcSocketConnection sock,
2222                                       SilcClientEntry client,
2223                                       int notify,
2224                                       char *signoff_message,
2225                                       int keygen)
2226 {
2227   SilcChannelEntry channel;
2228   SilcChannelClientEntry chl;
2229   SilcBuffer clidp;
2230
2231   SILC_LOG_DEBUG(("Start"));
2232
2233   if (!client || !client->id)
2234     return;
2235
2236   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2237
2238   /* Remove the client from all channels. The client is removed from
2239      the channels' user list. */
2240   silc_list_start(client->channels);
2241   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2242     channel = chl->channel;
2243
2244     /* Remove channel from client's channel list */
2245     silc_list_del(client->channels, chl);
2246
2247     /* Remove channel if there is no users anymore */
2248     if (server->server_type == SILC_ROUTER &&
2249         silc_list_count(channel->user_list) < 2) {
2250       if (!silc_idlist_del_channel(server->local_list, channel))
2251         silc_idlist_del_channel(server->global_list, channel);
2252       server->stat.my_channels--;
2253       continue;
2254     }
2255
2256     /* Remove client from channel's client list */
2257     silc_list_del(channel->user_list, chl);
2258     silc_free(chl);
2259     server->stat.my_chanclients--;
2260
2261     /* If there is no global users on the channel anymore mark the channel
2262        as local channel. */
2263     if (server->server_type == SILC_SERVER &&
2264         !silc_server_channel_has_global(channel))
2265       channel->global_users = FALSE;
2266
2267     /* If there is not at least one local user on the channel then we don't
2268        need the channel entry anymore, we can remove it safely. */
2269     if (server->server_type == SILC_SERVER &&
2270         !silc_server_channel_has_local(channel)) {
2271       /* Notify about leaving client if this channel has global users. */
2272       if (notify && channel->global_users)
2273         silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2274                                            SILC_NOTIFY_TYPE_SIGNOFF, 
2275                                            signoff_message ? 2 : 1,
2276                                            clidp->data, clidp->len,
2277                                            signoff_message, signoff_message ?
2278                                            strlen(signoff_message) : 0);
2279
2280       if (!silc_idlist_del_channel(server->local_list, channel))
2281         silc_idlist_del_channel(server->global_list, channel);
2282       server->stat.my_channels--;
2283       continue;
2284     }
2285
2286     /* Send notify to channel about client leaving SILC and thus
2287        the entire channel. */
2288     if (notify)
2289       silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2290                                          SILC_NOTIFY_TYPE_SIGNOFF, 
2291                                          signoff_message ? 2 : 1,
2292                                          clidp->data, clidp->len,
2293                                          signoff_message, signoff_message ?
2294                                          strlen(signoff_message) : 0);
2295
2296     if (keygen) {
2297       /* Re-generate channel key */
2298       silc_server_create_channel_key(server, channel, 0);
2299       
2300       /* Send the channel key to the channel. The key of course is not sent
2301          to the client who was removed f rom the channel. */
2302       silc_server_send_channel_key(server, client->connection, channel, 
2303                                    server->server_type == SILC_ROUTER ? 
2304                                    FALSE : !server->standalone);
2305     }
2306   }
2307
2308   silc_buffer_free(clidp);
2309 }
2310
2311 /* Removes client from one channel. This is used for example when client
2312    calls LEAVE command to remove itself from the channel. Returns TRUE
2313    if channel still exists and FALSE if the channel is removed when
2314    last client leaves the channel. If `notify' is FALSE notify messages
2315    are not sent. */
2316
2317 int silc_server_remove_from_one_channel(SilcServer server, 
2318                                         SilcSocketConnection sock,
2319                                         SilcChannelEntry channel,
2320                                         SilcClientEntry client,
2321                                         int notify)
2322 {
2323   SilcChannelEntry ch;
2324   SilcChannelClientEntry chl;
2325   SilcBuffer clidp;
2326
2327   SILC_LOG_DEBUG(("Start"));
2328
2329   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2330
2331   /* Remove the client from the channel. The client is removed from
2332      the channel's user list. */
2333   silc_list_start(client->channels);
2334   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2335     if (chl->channel != channel)
2336       continue;
2337
2338     ch = chl->channel;
2339
2340     /* Remove channel from client's channel list */
2341     silc_list_del(client->channels, chl);
2342
2343     /* Remove channel if there is no users anymore */
2344     if (server->server_type == SILC_ROUTER &&
2345         silc_list_count(channel->user_list) < 2) {
2346       if (!silc_idlist_del_channel(server->local_list, channel))
2347         silc_idlist_del_channel(server->global_list, channel);
2348       silc_buffer_free(clidp);
2349       server->stat.my_channels--;
2350       return FALSE;
2351     }
2352
2353     /* Remove client from channel's client list */
2354     silc_list_del(channel->user_list, chl);
2355     silc_free(chl);
2356     server->stat.my_chanclients--;
2357
2358     /* If there is no global users on the channel anymore mark the channel
2359        as local channel. */
2360     if (server->server_type == SILC_SERVER &&
2361         !silc_server_channel_has_global(channel))
2362       channel->global_users = FALSE;
2363
2364     /* If there is not at least one local user on the channel then we don't
2365        need the channel entry anymore, we can remove it safely. */
2366     if (server->server_type == SILC_SERVER &&
2367         !silc_server_channel_has_local(channel)) {
2368       /* Notify about leaving client if this channel has global users. */
2369       if (notify && channel->global_users)
2370         silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2371                                            SILC_NOTIFY_TYPE_LEAVE, 1,
2372                                            clidp->data, clidp->len);
2373
2374       if (!silc_idlist_del_channel(server->local_list, channel))
2375         silc_idlist_del_channel(server->global_list, channel);
2376       silc_buffer_free(clidp);
2377       server->stat.my_channels--;
2378       return FALSE;
2379     }
2380
2381     /* Send notify to channel about client leaving the channel */
2382     if (notify)
2383       silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2384                                          SILC_NOTIFY_TYPE_LEAVE, 1,
2385                                          clidp->data, clidp->len);
2386     break;
2387   }
2388
2389   silc_buffer_free(clidp);
2390   return TRUE;
2391 }
2392
2393 /* Returns TRUE if the given client is on the channel.  FALSE if not. 
2394    This works because we assure that the user list on the channel is
2395    always in up to date thus we can only check the channel list from 
2396    `client' which is faster than checking the user list from `channel'. */
2397
2398 int silc_server_client_on_channel(SilcClientEntry client,
2399                                   SilcChannelEntry channel)
2400 {
2401   SilcChannelClientEntry chl;
2402
2403   if (!client || !channel)
2404     return FALSE;
2405
2406   silc_list_start(client->channels);
2407   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END)
2408     if (chl->channel == channel)
2409       return TRUE;
2410
2411   return FALSE;
2412 }
2413
2414 /* Timeout callback. This is called if connection is idle or for some
2415    other reason is not responding within some period of time. This 
2416    disconnects the remote end. */
2417
2418 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2419 {
2420   SilcServer server = (SilcServer)context;
2421   SilcSocketConnection sock = server->sockets[fd];
2422
2423   if (!sock)
2424     return;
2425
2426   if (sock->user_data)
2427     silc_server_free_sock_user_data(server, sock);
2428
2429   silc_server_disconnect_remote(server, sock, 
2430                                 "Server closed connection: "
2431                                 "Connection timeout");
2432 }
2433
2434 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2435    function may be used only by router. In real SILC network all channels
2436    are created by routers thus this function is never used by normal
2437    server. */
2438
2439 SilcChannelEntry silc_server_create_new_channel(SilcServer server, 
2440                                                 SilcServerID *router_id,
2441                                                 char *cipher, 
2442                                                 char *hmac,
2443                                                 char *channel_name,
2444                                                 int broadcast)
2445 {
2446   SilcChannelID *channel_id;
2447   SilcChannelEntry entry;
2448   SilcCipher key;
2449   SilcHmac newhmac;
2450
2451   SILC_LOG_DEBUG(("Creating new channel"));
2452
2453   if (!cipher)
2454     cipher = "aes-256-cbc";
2455   if (!hmac)
2456     hmac = "hmac-sha1-96";
2457
2458   /* Allocate cipher */
2459   if (!silc_cipher_alloc(cipher, &key))
2460     return NULL;
2461
2462   /* Allocate hmac */
2463   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2464     silc_cipher_free(key);
2465     return NULL;
2466   }
2467
2468   channel_name = strdup(channel_name);
2469
2470   /* Create the channel */
2471   silc_id_create_channel_id(router_id, server->rng, &channel_id);
2472   entry = silc_idlist_add_channel(server->local_list, channel_name, 
2473                                   SILC_CHANNEL_MODE_NONE, channel_id, 
2474                                   NULL, key, newhmac);
2475   if (!entry) {
2476     silc_free(channel_name);
2477     return NULL;
2478   }
2479
2480   /* Now create the actual key material */
2481   silc_server_create_channel_key(server, entry, 
2482                                  silc_cipher_get_key_len(key) / 8);
2483
2484   /* Notify other routers about the new channel. We send the packet
2485      to our primary route. */
2486   if (broadcast && server->standalone == FALSE)
2487     silc_server_send_new_channel(server, server->router->connection, TRUE, 
2488                                  channel_name, entry->id, SILC_ID_CHANNEL_LEN,
2489                                  entry->mode);
2490
2491   server->stat.my_channels++;
2492
2493   return entry;
2494 }
2495
2496 /* Same as above but creates the channel with Channel ID `channel_id. */
2497
2498 SilcChannelEntry 
2499 silc_server_create_new_channel_with_id(SilcServer server, 
2500                                        char *cipher, 
2501                                        char *hmac,
2502                                        char *channel_name,
2503                                        SilcChannelID *channel_id,
2504                                        int broadcast)
2505 {
2506   SilcChannelEntry entry;
2507   SilcCipher key;
2508   SilcHmac newhmac;
2509
2510   SILC_LOG_DEBUG(("Creating new channel"));
2511
2512   if (!cipher)
2513     cipher = "aes-256-cbc";
2514   if (!hmac)
2515     hmac = "hmac-sha1-96";
2516
2517   /* Allocate cipher */
2518   if (!silc_cipher_alloc(cipher, &key))
2519     return NULL;
2520
2521   /* Allocate hmac */
2522   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2523     silc_cipher_free(key);
2524     return NULL;
2525   }
2526
2527   channel_name = strdup(channel_name);
2528
2529   /* Create the channel */
2530   entry = silc_idlist_add_channel(server->local_list, channel_name, 
2531                                   SILC_CHANNEL_MODE_NONE, channel_id, 
2532                                   NULL, key, newhmac);
2533   if (!entry) {
2534     silc_free(channel_name);
2535     return NULL;
2536   }
2537
2538   /* Now create the actual key material */
2539   silc_server_create_channel_key(server, entry, 
2540                                  silc_cipher_get_key_len(key) / 8);
2541
2542   /* Notify other routers about the new channel. We send the packet
2543      to our primary route. */
2544   if (broadcast && server->standalone == FALSE)
2545     silc_server_send_new_channel(server, server->router->connection, TRUE, 
2546                                  channel_name, entry->id, SILC_ID_CHANNEL_LEN,
2547                                  entry->mode);
2548
2549   server->stat.my_channels++;
2550
2551   return entry;
2552 }
2553
2554 /* Generates new channel key. This is used to create the initial channel key
2555    but also to re-generate new key for channel. If `key_len' is provided
2556    it is the bytes of the key length. */
2557
2558 void silc_server_create_channel_key(SilcServer server, 
2559                                     SilcChannelEntry channel,
2560                                     unsigned int key_len)
2561 {
2562   int i;
2563   unsigned char channel_key[32], hash[32];
2564   unsigned int len;
2565
2566   SILC_LOG_DEBUG(("Generating channel key"));
2567
2568   if (!channel->channel_key)
2569     if (!silc_cipher_alloc("aes-256-cbc", &channel->channel_key))
2570       return;
2571
2572   if (key_len)
2573     len = key_len;
2574   else if (channel->key_len)
2575     len = channel->key_len / 8;
2576   else
2577     len = silc_cipher_get_key_len(channel->channel_key) / 8;
2578
2579   /* Create channel key */
2580   for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
2581   
2582   /* Set the key */
2583   silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
2584
2585   /* Remove old key if exists */
2586   if (channel->key) {
2587     memset(channel->key, 0, channel->key_len / 8);
2588     silc_free(channel->key);
2589   }
2590
2591   /* Save the key */
2592   channel->key_len = len * 8;
2593   channel->key = silc_calloc(len, sizeof(*channel->key));
2594   memcpy(channel->key, channel_key, len);
2595   memset(channel_key, 0, sizeof(channel_key));
2596
2597   /* Generate HMAC key from the channel key data and set it */
2598   if (!channel->hmac)
2599     silc_hmac_alloc("hmac-sha1-96", NULL, &channel->hmac);
2600   silc_hash_make(channel->hmac->hash, channel->key, len, hash);
2601   silc_hmac_set_key(channel->hmac, hash, silc_hash_len(channel->hmac->hash));
2602   memset(hash, 0, sizeof(hash));
2603 }
2604
2605 /* Saves the channel key found in the encoded `key_payload' buffer. This 
2606    function is used when we receive Channel Key Payload and also when we're
2607    processing JOIN command reply. Returns entry to the channel. */
2608
2609 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
2610                                               SilcBuffer key_payload,
2611                                               SilcChannelEntry channel)
2612 {
2613   SilcChannelKeyPayload payload = NULL;
2614   SilcChannelID *id = NULL;
2615   unsigned char *tmp, hash[32];
2616   unsigned int tmp_len;
2617   char *cipher;
2618
2619   /* Decode channel key payload */
2620   payload = silc_channel_key_payload_parse(key_payload);
2621   if (!payload) {
2622     SILC_LOG_ERROR(("Bad channel key payload, dropped"));
2623     channel = NULL;
2624     goto out;
2625   }
2626
2627   /* Get the channel entry */
2628   if (!channel) {
2629
2630     /* Get channel ID */
2631     tmp = silc_channel_key_get_id(payload, &tmp_len);
2632     id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
2633     if (!id) {
2634       channel = NULL;
2635       goto out;
2636     }
2637
2638     channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
2639     if (!channel) {
2640       channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
2641       if (!channel) {
2642         SILC_LOG_ERROR(("Received key for non-existent channel"));
2643         goto out;
2644       }
2645     }
2646   }
2647
2648   tmp = silc_channel_key_get_key(payload, &tmp_len);
2649   if (!tmp) {
2650     channel = NULL;
2651     goto out;
2652   }
2653
2654   cipher = silc_channel_key_get_cipher(payload, NULL);
2655   if (!cipher) {
2656     channel = NULL;
2657     goto out;
2658   }
2659
2660   /* Remove old key if exists */
2661   if (channel->key) {
2662     memset(channel->key, 0, channel->key_len / 8);
2663     silc_free(channel->key);
2664     silc_cipher_free(channel->channel_key);
2665   }
2666
2667   /* Create new cipher */
2668   if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
2669     channel = NULL;
2670     goto out;
2671   }
2672
2673   /* Save the key */
2674   channel->key_len = tmp_len * 8;
2675   channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
2676   memcpy(channel->key, tmp, tmp_len);
2677   silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
2678
2679   /* Generate HMAC key from the channel key data and set it */
2680   if (!channel->hmac)
2681     silc_hmac_alloc("hmac-sha1-96", NULL, &channel->hmac);
2682   silc_hash_make(channel->hmac->hash, tmp, tmp_len, hash);
2683   silc_hmac_set_key(channel->hmac, hash, silc_hash_len(channel->hmac->hash));
2684
2685   memset(hash, 0, sizeof(hash));
2686   memset(tmp, 0, tmp_len);
2687
2688  out:
2689   if (id)
2690     silc_free(id);
2691   if (payload)
2692     silc_channel_key_payload_free(payload);
2693
2694   return channel;
2695 }
2696
2697 /* Heartbeat callback. This function is set as argument for the
2698    silc_socket_set_heartbeat function. The library will call this function
2699    at the set time interval. */
2700
2701 void silc_server_perform_heartbeat(SilcSocketConnection sock,
2702                                    void *hb_context)
2703 {
2704   SilcServerHBContext hb = (SilcServerHBContext)hb_context;
2705
2706   SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname,
2707                   sock->ip));
2708
2709   /* Send the heartbeat */
2710   silc_server_send_heartbeat(hb->server, sock);
2711 }
2712
2713 /* Returns assembled of all servers in the given ID list. The packet's
2714    form is dictated by the New ID payload. */
2715
2716 static void silc_server_announce_get_servers(SilcServer server,
2717                                              SilcIDList id_list,
2718                                              SilcBuffer *servers)
2719 {
2720   SilcIDCacheList list;
2721   SilcIDCacheEntry id_cache;
2722   SilcServerEntry entry;
2723   SilcBuffer idp;
2724
2725   /* Go through all clients in the list */
2726   if (silc_idcache_find_by_id(id_list->clients, SILC_ID_CACHE_ANY, 
2727                               SILC_ID_SERVER, &list)) {
2728     if (silc_idcache_list_first(list, &id_cache)) {
2729       while (id_cache) {
2730         entry = (SilcServerEntry)id_cache->context;
2731
2732         idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
2733
2734         *servers = silc_buffer_realloc(*servers, 
2735                                        (*servers ? 
2736                                         (*servers)->truelen + idp->len : 
2737                                         idp->len));
2738         silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
2739         silc_buffer_put(*servers, idp->data, idp->len);
2740         silc_buffer_pull(*servers, idp->len);
2741         silc_buffer_free(idp);
2742
2743         if (!silc_idcache_list_next(list, &id_cache))
2744           break;
2745       }
2746     }
2747
2748     silc_idcache_list_free(list);
2749   }
2750 }
2751
2752 /* This function is used by router to announce existing servers to our
2753    primary router when we've connected to it. */
2754
2755 void silc_server_announce_servers(SilcServer server)
2756 {
2757   SilcBuffer servers = NULL;
2758
2759   SILC_LOG_DEBUG(("Announcing servers"));
2760
2761   /* Get servers in local list */
2762   silc_server_announce_get_servers(server, server->local_list, &servers);
2763
2764   /* Get servers in global list */
2765   silc_server_announce_get_servers(server, server->global_list, &servers);
2766
2767   if (servers) {
2768     silc_buffer_push(servers, servers->data - servers->head);
2769     SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
2770
2771     /* Send the packet */
2772     silc_server_packet_send(server, server->router->connection,
2773                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
2774                             servers->data, servers->len, TRUE);
2775
2776     silc_buffer_free(servers);
2777   }
2778 }
2779
2780 /* Returns assembled packet of all clients in the given ID list. The
2781    packet's form is dictated by the New ID Payload. */
2782
2783 static void silc_server_announce_get_clients(SilcServer server,
2784                                              SilcIDList id_list,
2785                                              SilcBuffer *clients)
2786 {
2787   SilcIDCacheList list;
2788   SilcIDCacheEntry id_cache;
2789   SilcClientEntry client;
2790   SilcBuffer idp;
2791
2792   /* Go through all clients in the list */
2793   if (silc_idcache_find_by_id(id_list->clients, SILC_ID_CACHE_ANY, 
2794                               SILC_ID_CLIENT, &list)) {
2795     if (silc_idcache_list_first(list, &id_cache)) {
2796       while (id_cache) {
2797         client = (SilcClientEntry)id_cache->context;
2798
2799         idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2800
2801         *clients = silc_buffer_realloc(*clients, 
2802                                        (*clients ? 
2803                                         (*clients)->truelen + idp->len : 
2804                                         idp->len));
2805         silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
2806         silc_buffer_put(*clients, idp->data, idp->len);
2807         silc_buffer_pull(*clients, idp->len);
2808         silc_buffer_free(idp);
2809
2810         if (!silc_idcache_list_next(list, &id_cache))
2811           break;
2812       }
2813     }
2814
2815     silc_idcache_list_free(list);
2816   }
2817 }
2818
2819 /* This function is used to announce our existing clients to our router
2820    when we've connected to it. */
2821
2822 void silc_server_announce_clients(SilcServer server)
2823 {
2824   SilcBuffer clients = NULL;
2825
2826   SILC_LOG_DEBUG(("Announcing clients"));
2827
2828   /* Get clients in local list */
2829   silc_server_announce_get_clients(server, server->local_list,
2830                                    &clients);
2831
2832   /* As router we announce our global list as well */
2833   if (server->server_type == SILC_ROUTER)
2834     silc_server_announce_get_clients(server, server->global_list,
2835                                      &clients);
2836
2837   if (clients) {
2838     silc_buffer_push(clients, clients->data - clients->head);
2839     SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
2840
2841     /* Send the packet */
2842     silc_server_packet_send(server, server->router->connection,
2843                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
2844                             clients->data, clients->len, TRUE);
2845
2846     silc_buffer_free(clients);
2847   }
2848 }
2849
2850 static SilcBuffer 
2851 silc_server_announce_encode_join(unsigned int argc, ...)
2852 {
2853   va_list ap;
2854
2855   va_start(ap, argc);
2856   return silc_notify_payload_encode(SILC_NOTIFY_TYPE_JOIN, argc, ap);
2857 }
2858
2859 /* Returns assembled packets for all channels and users on those channels
2860    from the given ID List. The packets are in the form dictated by the
2861    New Channel and New Channel User payloads. */
2862
2863 static void silc_server_announce_get_channels(SilcServer server,
2864                                               SilcIDList id_list,
2865                                               SilcBuffer *channels,
2866                                               SilcBuffer *channel_users)
2867 {
2868   SilcIDCacheList list;
2869   SilcIDCacheEntry id_cache;
2870   SilcChannelEntry channel;
2871   SilcChannelClientEntry chl;
2872   SilcBuffer chidp;
2873   unsigned char *cid;
2874   unsigned short name_len;
2875   int len;
2876
2877   /* Go through all channels in the list */
2878   if (silc_idcache_find_by_id(id_list->channels, SILC_ID_CACHE_ANY, 
2879                               SILC_ID_CHANNEL, &list)) {
2880     if (silc_idcache_list_first(list, &id_cache)) {
2881       while (id_cache) {
2882         channel = (SilcChannelEntry)id_cache->context;
2883         
2884         cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
2885         name_len = strlen(channel->channel_name);
2886
2887         len = 4 + name_len + SILC_ID_CHANNEL_LEN + 4;
2888         *channels = 
2889           silc_buffer_realloc(*channels, 
2890                               (*channels ? (*channels)->truelen + len : len));
2891         silc_buffer_pull_tail(*channels, 
2892                               ((*channels)->end - (*channels)->data));
2893         silc_buffer_format(*channels,
2894                            SILC_STR_UI_SHORT(name_len),
2895                            SILC_STR_UI_XNSTRING(channel->channel_name, 
2896                                                 name_len),
2897                            SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
2898                            SILC_STR_UI_XNSTRING(cid, SILC_ID_CHANNEL_LEN),
2899                            SILC_STR_UI_INT(0),
2900                            SILC_STR_END);
2901         silc_buffer_pull(*channels, len);
2902
2903         /* Now find all users on the channel */
2904         chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
2905         silc_list_start(channel->user_list);
2906         while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2907           SilcBuffer clidp;
2908           SilcBuffer tmp;
2909
2910           clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
2911
2912           tmp = silc_server_announce_encode_join(2, clidp->data, clidp->len,
2913                                                  chidp->data, chidp->len);
2914           len = tmp->len;
2915           *channel_users = 
2916             silc_buffer_realloc(*channel_users, 
2917                                 (*channel_users ? 
2918                                  (*channel_users)->truelen + len : len));
2919           silc_buffer_pull_tail(*channel_users, 
2920                                 ((*channel_users)->end - 
2921                                  (*channel_users)->data));
2922
2923           silc_buffer_put(*channel_users, tmp->data, tmp->len);
2924           silc_buffer_pull(*channel_users, len);
2925           silc_buffer_free(clidp);
2926           silc_buffer_free(tmp);
2927         }
2928         silc_buffer_free(chidp);
2929
2930         silc_free(cid);
2931
2932         if (!silc_idcache_list_next(list, &id_cache))
2933           break;
2934       }
2935     }
2936
2937     silc_idcache_list_free(list);
2938   }
2939 }
2940
2941 /* This function is used to announce our existing channels to our router
2942    when we've connected to it. This also announces the users on the
2943    channels to the router. */
2944
2945 void silc_server_announce_channels(SilcServer server)
2946 {
2947   SilcBuffer channels = NULL, channel_users = NULL;
2948
2949   SILC_LOG_DEBUG(("Announcing channels and channel users"));
2950
2951   /* Get channels and channel users in local list */
2952   silc_server_announce_get_channels(server, server->local_list,
2953                                     &channels, &channel_users);
2954
2955   /* Get channels and channel users in global list */
2956   silc_server_announce_get_channels(server, server->global_list,
2957                                     &channels, &channel_users);
2958
2959   if (channels) {
2960     silc_buffer_push(channels, channels->data - channels->head);
2961     SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
2962
2963     /* Send the packet */
2964     silc_server_packet_send(server, server->router->connection,
2965                             SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
2966                             channels->data, channels->len,
2967                             FALSE);
2968
2969     silc_buffer_free(channels);
2970   }
2971
2972   if (channel_users) {
2973     silc_buffer_push(channel_users, channel_users->data - channel_users->head);
2974     SILC_LOG_HEXDUMP(("channel users"), channel_users->data, 
2975                      channel_users->len);
2976
2977     /* Send the packet */
2978     silc_server_packet_send(server, server->router->connection,
2979                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
2980                             channel_users->data, channel_users->len,
2981                             FALSE);
2982
2983     silc_buffer_free(channel_users);
2984   }
2985 }
2986
2987 /* Failure timeout callback. If this is called then we will immediately
2988    process the received failure. We always process the failure with timeout
2989    since we do not want to blindly trust to received failure packets. 
2990    This won't be called (the timeout is cancelled) if the failure was
2991    bogus (it is bogus if remote does not close the connection after sending
2992    the failure). */
2993
2994 SILC_TASK_CALLBACK(silc_server_failure_callback)
2995 {
2996   SilcServerFailureContext f = (SilcServerFailureContext)context;
2997
2998   if (f->sock->protocol) {
2999     f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3000     f->sock->protocol->execute(f->server->timeout_queue, 0,
3001                                f->sock->protocol, f->sock->sock, 0, 0);
3002   }
3003
3004   silc_free(f);
3005 }
3006
3007 /* Assembles user list and users mode list from the `channel'. */
3008
3009 void silc_server_get_users_on_channel(SilcServer server,
3010                                       SilcChannelEntry channel,
3011                                       SilcBuffer *user_list,
3012                                       SilcBuffer *mode_list,
3013                                       unsigned int *user_count)
3014 {
3015   SilcChannelClientEntry chl;
3016   SilcBuffer client_id_list;
3017   SilcBuffer client_mode_list;
3018   SilcBuffer idp;
3019   unsigned int list_count = 0;
3020
3021   client_id_list = silc_buffer_alloc((SILC_ID_CLIENT_LEN + 4) * 
3022                                      silc_list_count(channel->user_list));
3023   client_mode_list = silc_buffer_alloc(4 * 
3024                                        silc_list_count(channel->user_list));
3025   silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3026   silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3027   silc_list_start(channel->user_list);
3028   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
3029     /* Client ID */
3030     idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3031     silc_buffer_put(client_id_list, idp->data, idp->len);
3032     silc_buffer_pull(client_id_list, idp->len);
3033     silc_buffer_free(idp);
3034
3035     /* Client's mode on channel */
3036     SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3037     silc_buffer_pull(client_mode_list, 4);
3038
3039     list_count++;
3040   }
3041   silc_buffer_push(client_id_list, 
3042                    client_id_list->data - client_id_list->head);
3043   silc_buffer_push(client_mode_list, 
3044                    client_mode_list->data - client_mode_list->head);
3045
3046   *user_list = client_id_list;
3047   *mode_list = client_mode_list;
3048   *user_count = list_count;
3049 }
3050
3051 /* Saves users and their modes to the `channel'. */
3052
3053 void silc_server_save_users_on_channel(SilcServer server,
3054                                        SilcSocketConnection sock,
3055                                        SilcChannelEntry channel,
3056                                        SilcClientID *noadd,
3057                                        SilcBuffer user_list,
3058                                        SilcBuffer mode_list,
3059                                        unsigned int user_count)
3060 {
3061   int i;
3062
3063   /* Cache the received Client ID's and modes. This cache expires
3064      whenever server sends notify message to channel. It means two things;
3065      some user has joined or leaved the channel. XXX TODO! */
3066   for (i = 0; i < user_count; i++) {
3067     unsigned short idp_len;
3068     unsigned int mode;
3069     SilcClientID *client_id;
3070     SilcClientEntry client;
3071
3072     /* Client ID */
3073     SILC_GET16_MSB(idp_len, user_list->data + 2);
3074     idp_len += 4;
3075     client_id = silc_id_payload_parse_id(user_list->data, idp_len);
3076     silc_buffer_pull(user_list, idp_len);
3077     if (!client_id)
3078       continue;
3079
3080     /* Mode */
3081     SILC_GET32_MSB(mode, mode_list->data);
3082     silc_buffer_pull(mode_list, 4);
3083
3084     if (noadd && !SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3085       silc_free(client_id);
3086       continue;
3087     }
3088     
3089     /* Check if we have this client cached already. */
3090     client = silc_idlist_find_client_by_id(server->local_list, client_id,
3091                                            NULL);
3092     if (!client)
3093       client = silc_idlist_find_client_by_id(server->global_list, 
3094                                              client_id, NULL);
3095     if (!client) {
3096       /* If router did not find such Client ID in its lists then this must
3097          be bogus client or some router in the net is buggy. */
3098       if (server->server_type == SILC_ROUTER) {
3099         silc_free(client_id);
3100         continue;
3101       }
3102
3103       /* We don't have that client anywhere, add it. The client is added
3104          to global list since server didn't have it in the lists so it must be 
3105          global. */
3106       client = silc_idlist_add_client(server->global_list, NULL, 0, NULL, 
3107                                       NULL, 
3108                                       silc_id_dup(client_id, SILC_ID_CLIENT), 
3109                                       sock->user_data, NULL);
3110       if (!client) {
3111         silc_free(client_id);
3112         continue;
3113       }
3114
3115       client->data.registered = TRUE;
3116     }
3117
3118     silc_free(client_id);
3119
3120     if (!silc_server_client_on_channel(client, channel)) {
3121       /* Client was not on the channel, add it. */
3122       SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3123       chl->client = client;
3124       chl->mode = mode;
3125       chl->channel = channel;
3126       silc_list_add(channel->user_list, chl);
3127       silc_list_add(client->channels, chl);
3128     }
3129   }
3130 }
3131
3132 /* Lookups route to the client indicated by `id' client ID. The connection
3133    object and internal data object is returned. Returns NULL if route
3134    could not be found to the client. If the `client_id' is specified then
3135    it is used and the `id_data' is ignored. */
3136
3137 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3138                                                   unsigned char *id_data,
3139                                                   unsigned int id_len,
3140                                                   SilcClientID *client_id,
3141                                                   SilcIDListData *idata)
3142 {
3143   SilcClientID *id;
3144   SilcClientEntry client;
3145
3146   SILC_LOG_DEBUG(("Start"));
3147
3148   /* Decode destination Client ID */
3149   if (!client_id) {
3150     id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3151     if (!id) {
3152       SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3153       return NULL;
3154     }
3155   } else {
3156     id = silc_id_dup(client_id, SILC_ID_CLIENT);
3157   }
3158
3159   /* If the destination belongs to our server we don't have to route
3160      the packet anywhere but to send it to the local destination. */
3161   client = silc_idlist_find_client_by_id(server->local_list, id, NULL);
3162   if (client) {
3163     silc_free(id);
3164
3165     if (client && client->data.registered == FALSE)
3166       return NULL;
3167
3168     /* If we are router and the client has router then the client is in
3169        our cell but not directly connected to us. */
3170     if (server->server_type == SILC_ROUTER && client->router) {
3171       /* We are of course in this case the client's router thus the real
3172          "router" of the client is the server who owns the client. Thus
3173          we will send the packet to that server. */
3174       *idata = (SilcIDListData)client->router;
3175       return client->router->connection;
3176     }
3177
3178     /* Seems that client really is directly connected to us */
3179     *idata = (SilcIDListData)client;
3180     return client->connection;
3181   }
3182
3183   /* Destination belongs to someone not in this server. If we are normal
3184      server our action is to send the packet to our router. */
3185   if (server->server_type == SILC_SERVER && !server->standalone) {
3186     silc_free(id);
3187     *idata = (SilcIDListData)server->router;
3188     return server->router->connection;
3189   }
3190
3191   /* We are router and we will perform route lookup for the destination 
3192      and send the packet to fastest route. */
3193   if (server->server_type == SILC_ROUTER && !server->standalone) {
3194     /* Check first that the ID is valid */
3195     client = silc_idlist_find_client_by_id(server->global_list, id, NULL);
3196     if (client) {
3197       SilcSocketConnection dst_sock;
3198
3199       dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
3200
3201       silc_free(id);
3202       *idata = (SilcIDListData)dst_sock->user_data;
3203       return dst_sock;
3204     }
3205   }
3206
3207   silc_free(id);
3208   return NULL;
3209 }
3210
3211 /* Encodes and returns channel list of channels the `client' has joined.
3212    Secret channels are not put to the list. */
3213
3214 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
3215                                                SilcClientEntry client)
3216 {
3217   SilcBuffer buffer = NULL;
3218   SilcChannelEntry channel;
3219   SilcChannelClientEntry chl;
3220   unsigned char *cid;
3221   unsigned short name_len;
3222   int len;
3223
3224   silc_list_start(client->channels);
3225   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
3226     channel = chl->channel;
3227
3228     if (channel->mode & SILC_CHANNEL_MODE_SECRET)
3229       continue;
3230
3231     cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3232     name_len = strlen(channel->channel_name);
3233     
3234     len = 4 + name_len + SILC_ID_CHANNEL_LEN + 4;
3235     buffer = silc_buffer_realloc(buffer, 
3236                                  (buffer ? (buffer)->truelen + len : len));
3237     silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
3238     silc_buffer_format(buffer,
3239                        SILC_STR_UI_SHORT(name_len),
3240                        SILC_STR_UI_XNSTRING(channel->channel_name, 
3241                                             name_len),
3242                        SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
3243                        SILC_STR_UI_XNSTRING(cid, SILC_ID_CHANNEL_LEN),
3244                        SILC_STR_UI_INT(chl->mode), /* Client's mode */
3245                        SILC_STR_END);
3246     silc_buffer_pull(buffer, len);
3247     silc_free(cid);
3248   }
3249
3250   if (buffer)
3251     silc_buffer_push(buffer, buffer->data - buffer->head);
3252
3253   return buffer;
3254 }
3255
3256 /* Finds client entry by Client ID and if it is not found then resolves
3257    it using WHOIS command. */
3258
3259 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
3260                                                SilcClientID *client_id)
3261 {
3262   SilcClientEntry client;
3263
3264   client = silc_idlist_find_client_by_id(server->local_list, client_id, NULL);
3265   if (!client) {
3266     client = silc_idlist_find_client_by_id(server->global_list, 
3267                                            client_id, NULL);
3268     if (!client && server->server_type == SILC_ROUTER)
3269       return NULL;
3270   }
3271
3272   if (!client && server->standalone)
3273     return NULL;
3274
3275   if (!client || !client->nickname || !client->username) {
3276     SilcBuffer buffer, idp;
3277
3278     idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3279     buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
3280                                             ++server->cmd_ident, 1,
3281                                             3, idp->data, idp->len);
3282     silc_server_packet_send(server, client ? client->router->connection :
3283                             server->router->connection,
3284                             SILC_PACKET_COMMAND, 0,
3285                             buffer->data, buffer->len, FALSE);
3286     silc_buffer_free(idp);
3287     silc_buffer_free(buffer);
3288   }
3289
3290   return client;
3291 }