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