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