Added [Identity] config entry and forking support to server.
[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->user || 
366          !server->config->identity->group) {
367        SILC_LOG_DEBUG(("User and/or group not set"));
368        fprintf(stderr, "User and/or group not set, exiting\n");
369        exit(1);
370      }
371
372      /* Get the values given for user and group in configuration file */
373      user=server->config->identity->user;
374      group=server->config->identity->group;
375
376      /* Check whether the user/group information is text */ 
377      if (atoi(user)!=0 || atoi(group)!=0) {
378        SILC_LOG_DEBUG(("Invalid user and/or group information"));
379        SILC_LOG_DEBUG(("User and/or group given as number"));
380        fprintf(stderr, "Invalid user and/or group information\n");
381        fprintf(stderr, "Please assign them as names, not numbers\n");
382        exit(1);
383      }
384
385      /* Catch the nasty incident of string "0" returning 0 from atoi */
386      if (strcmp("0", user)==0 || strcmp("0", group)==0) {
387        SILC_LOG_DEBUG(("User and/or group configured to 0. Unacceptable"));
388        fprintf(stderr, "User and/or group configured to 0. Exiting\n");
389        exit(1);
390      }
391
392      pw=getpwnam(user);
393      gr=getgrnam(group);
394
395     /* Check whether user and/or group is set to root. If yes, exit
396        immediately. Otherwise, setgid and setuid server to user.group */
397     if (gr->gr_gid==0 || pw->pw_uid==0) {
398       SILC_LOG_DEBUG(("FATAL: silcd will not run at root privileges"));
399       fprintf(stderr, "User and/or group not set. Please set them\n");
400       exit(1);
401     } else {
402       /* Fork server to background, making it a daemon */
403       if (fork()) {
404         SILC_LOG_DEBUG(("Server started as root. Dropping privileges."));
405         SILC_LOG_DEBUG(("Forking SILC server to background"));
406         exit(0);
407       } 
408       setsid();
409    
410        SILC_LOG_DEBUG(("Changing to group %s", group));
411       if(setgid(gr->gr_gid)==0) {
412         SILC_LOG_DEBUG(("Setgid to %s", group));
413       } else {
414         SILC_LOG_DEBUG(("Setgid to %s failed", group));
415         fprintf(stderr, "Tried to setgid %s but no such group. Exiting\n",
416                 group);
417         exit(1);
418       }
419       SILC_LOG_DEBUG(("Changing to user nobody"));
420       if(setuid(pw->pw_uid)==0) {
421         SILC_LOG_DEBUG(("Setuid to %s", user));
422       } else {
423         SILC_LOG_DEBUG(("Setuid to %s failed", user));
424         fprintf(stderr, "Tried to setuid %s but no such user. Exiting\n",
425                 user);
426         exit(1);
427       }
428     }
429   } else {
430     /* Fork server to background, making it a daemon */
431     if (fork()) {
432       SILC_LOG_DEBUG(("Server started as user")); 
433       SILC_LOG_DEBUG(("Forking SILC server to background"));
434       exit(0);
435     }
436     setsid();
437   }
438 }
439
440
441 /* Stops the SILC server. This function is used to shutdown the server. 
442    This is usually called after the scheduler has returned. After stopping 
443    the server one should call silc_server_free. */
444
445 void silc_server_stop(SilcServer server)
446 {
447   SILC_LOG_DEBUG(("Stopping server"));
448
449   /* Stop the scheduler, although it might be already stopped. This
450      doesn't hurt anyone. This removes all the tasks and task queues,
451      as well. */
452   silc_schedule_stop();
453   silc_schedule_uninit();
454
455   silc_server_protocols_unregister();
456
457   SILC_LOG_DEBUG(("Server stopped"));
458 }
459
460 /* The heart of the server. This runs the scheduler thus runs the server. 
461    When this returns the server has been stopped and the program will
462    be terminated. */
463
464 void silc_server_run(SilcServer server)
465 {
466   SILC_LOG_DEBUG(("Running server"));
467
468   /* Start the scheduler, the heart of the SILC server. When this returns
469      the program will be terminated. */
470   silc_schedule();
471 }
472
473 /* Timeout callback that will be called to retry connecting to remote
474    router. This is used by both normal and router server. This will wait
475    before retrying the connecting. The timeout is generated by exponential
476    backoff algorithm. */
477
478 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
479 {
480   SilcServerConnection sconn = (SilcServerConnection)context;
481   SilcServer server = sconn->server;
482
483   SILC_LOG_INFO(("Retrying connecting to a router"));
484
485   /* Calculate next timeout */
486   if (sconn->retry_count >= 1) {
487     sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
488     if (sconn->retry_timeout > SILC_SERVER_RETRY_INTERVAL_MAX)
489       sconn->retry_timeout = SILC_SERVER_RETRY_INTERVAL_MAX;
490   } else {
491     sconn->retry_timeout = server->params->retry_interval_min;
492   }
493   sconn->retry_count++;
494   sconn->retry_timeout = sconn->retry_timeout +
495     silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
496
497   /* If we've reached max retry count, give up. */
498   if (sconn->retry_count > server->params->retry_count && 
499       server->params->retry_keep_trying == FALSE) {
500     SILC_LOG_ERROR(("Could not connect to router, giving up"));
501     return;
502   }
503
504   /* Wait one before retrying */
505   silc_task_register(server->timeout_queue, fd, silc_server_connect_router,
506                      context, sconn->retry_timeout, 
507                      server->params->retry_interval_min_usec,
508                      SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
509 }
510
511 /* Generic routine to use connect to a router. */
512
513 SILC_TASK_CALLBACK(silc_server_connect_router)
514 {    
515   SilcServerConnection sconn = (SilcServerConnection)context;
516   SilcServer server = sconn->server;
517   SilcSocketConnection newsocket;
518   SilcProtocol protocol;
519   SilcServerKEInternalContext *proto_ctx;
520   int sock;
521
522   /* Connect to remote host */
523   sock = silc_net_create_connection(sconn->remote_port, 
524                                     sconn->remote_host);
525   if (sock < 0) {
526     SILC_LOG_ERROR(("Could not connect to router"));
527     silc_task_register(server->timeout_queue, fd, 
528                        silc_server_connect_to_router_retry,
529                        context, 0, 1, SILC_TASK_TIMEOUT, 
530                        SILC_TASK_PRI_NORMAL);
531     return;
532   }
533
534   /* Set socket options */
535   silc_net_set_socket_nonblock(sock);
536   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
537
538   /* Create socket connection for the connection. Even though we
539      know that we are connecting to a router we will mark the socket
540      to be unknown connection until we have executed authentication
541      protocol. */
542   silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
543   server->sockets[sock] = newsocket;
544   newsocket->hostname = strdup(sconn->remote_host);
545   newsocket->port = sconn->remote_port;
546   sconn->sock = newsocket;
547
548   /* Allocate internal protocol context. This is sent as context
549      to the protocol. */
550   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
551   proto_ctx->server = (void *)server;
552   proto_ctx->context = (void *)sconn;
553   proto_ctx->sock = newsocket;
554   proto_ctx->rng = server->rng;
555   proto_ctx->responder = FALSE;
556       
557   /* Perform key exchange protocol. silc_server_connect_to_router_second
558      will be called after the protocol is finished. */
559   silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE, 
560                       &protocol, proto_ctx,
561                       silc_server_connect_to_router_second);
562   newsocket->protocol = protocol;
563       
564   /* Register a timeout task that will be executed if the protocol
565      is not executed within set limit. */
566   proto_ctx->timeout_task = 
567     silc_task_register(server->timeout_queue, sock, 
568                        silc_server_timeout_remote,
569                        server, server->params->protocol_timeout,
570                        server->params->protocol_timeout_usec,
571                        SILC_TASK_TIMEOUT,
572                        SILC_TASK_PRI_LOW);
573
574   /* Register the connection for network input and output. This sets
575      that scheduler will listen for incoming packets for this connection 
576      and sets that outgoing packets may be sent to this connection as 
577      well. However, this doesn't set the scheduler for outgoing traffic,
578      it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
579      later when outgoing data is available. */
580   context = (void *)server;
581   SILC_REGISTER_CONNECTION_FOR_IO(sock);
582   
583   /* Run the protocol */
584   protocol->execute(server->timeout_queue, 0, protocol, sock, 0, 0);
585 }
586   
587 /* This function connects to our primary router or if we are a router this
588    establishes all our primary routes. This is called at the start of the
589    server to do authentication and key exchange with our router - called
590    from schedule. */
591
592 SILC_TASK_CALLBACK(silc_server_connect_to_router)
593 {
594   SilcServer server = (SilcServer)context;
595   SilcServerConnection sconn;
596
597   SILC_LOG_DEBUG(("Connecting to router(s)"));
598
599   /* If we are normal SILC server we need to connect to our cell's
600      router. */
601   if (server->server_type == SILC_SERVER) {
602     SILC_LOG_DEBUG(("We are normal server"));
603
604     /* Create connection to the router, if configured. */
605     if (server->config->routers) {
606
607       /* Allocate connection object for hold connection specific stuff. */
608       sconn = silc_calloc(1, sizeof(*sconn));
609       sconn->server = server;
610       sconn->remote_host = server->config->routers->host;
611       sconn->remote_port = server->config->routers->port;
612
613       silc_task_register(server->timeout_queue, fd, 
614                          silc_server_connect_router,
615                          (void *)sconn, 0, 1, SILC_TASK_TIMEOUT, 
616                          SILC_TASK_PRI_NORMAL);
617       return;
618     }
619   }
620
621   /* If we are a SILC router we need to establish all of our primary
622      routes. */
623   if (server->server_type == SILC_ROUTER) {
624     SilcConfigServerSectionServerConnection *ptr;
625
626     SILC_LOG_DEBUG(("We are router"));
627
628     /* Create the connections to all our routes */
629     ptr = server->config->routers;
630     while (ptr) {
631
632       SILC_LOG_DEBUG(("Router connection [%s] %s:%d",
633                       ptr->initiator ? "Initiator" : "Responder",
634                       ptr->host, ptr->port));
635
636       if (ptr->initiator) {
637         /* Allocate connection object for hold connection specific stuff. */
638         sconn = silc_calloc(1, sizeof(*sconn));
639         sconn->server = server;
640         sconn->remote_host = ptr->host;
641         sconn->remote_port = ptr->port;
642
643         silc_task_register(server->timeout_queue, fd, 
644                            silc_server_connect_router,
645                            (void *)sconn, 0, 1, SILC_TASK_TIMEOUT, 
646                            SILC_TASK_PRI_NORMAL);
647       }
648
649       if (!ptr->next)
650         return;
651
652       ptr = ptr->next;
653     }
654   }
655
656   SILC_LOG_DEBUG(("No router(s), server will be standalone"));
657   
658   /* There wasn't a configured router, we will continue but we don't
659      have a connection to outside world.  We will be standalone server. */
660   server->standalone = TRUE;
661 }
662
663 /* Second part of connecting to router(s). Key exchange protocol has been
664    executed and now we will execute authentication protocol. */
665
666 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
667 {
668   SilcProtocol protocol = (SilcProtocol)context;
669   SilcServerKEInternalContext *ctx = 
670     (SilcServerKEInternalContext *)protocol->context;
671   SilcServer server = (SilcServer)ctx->server;
672   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
673   SilcSocketConnection sock = NULL;
674   SilcServerConnAuthInternalContext *proto_ctx;
675
676   SILC_LOG_DEBUG(("Start"));
677
678   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
679     /* Error occured during protocol */
680     silc_protocol_free(protocol);
681     if (ctx->packet)
682       silc_packet_context_free(ctx->packet);
683     if (ctx->ske)
684       silc_ske_free(ctx->ske);
685     if (ctx->dest_id)
686       silc_free(ctx->dest_id);
687     silc_free(ctx);
688     sock->protocol = NULL;
689     silc_server_disconnect_remote(server, sock, "Server closed connection: "
690                                   "Key exchange failed");
691     return;
692   }
693   
694   /* Allocate internal context for the authentication protocol. This
695      is sent as context for the protocol. */
696   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
697   proto_ctx->server = (void *)server;
698   proto_ctx->context = (void *)sconn;
699   proto_ctx->sock = sock = server->sockets[fd];
700   proto_ctx->ske = ctx->ske;       /* Save SKE object from previous protocol */
701   proto_ctx->dest_id_type = ctx->dest_id_type;
702   proto_ctx->dest_id = ctx->dest_id;
703
704   /* Resolve the authentication method used in this connection */
705   proto_ctx->auth_meth = SILC_PROTOCOL_CONN_AUTH_PASSWORD;
706   if (server->config->routers) {
707     SilcConfigServerSectionServerConnection *conn = NULL;
708
709     /* Check if we find a match from user configured connections */
710     conn = silc_config_server_find_router_conn(server->config,
711                                                sock->hostname,
712                                                sock->port);
713     if (conn) {
714       /* Match found. Use the configured authentication method */
715       proto_ctx->auth_meth = conn->auth_meth;
716       if (conn->auth_data) {
717         proto_ctx->auth_data = strdup(conn->auth_data);
718         proto_ctx->auth_data_len = strlen(conn->auth_data);
719       }
720     } else {
721       /* No match found. */
722       /* XXX */
723     }
724   } else {
725     /* XXX */
726   }
727
728   /* Free old protocol as it is finished now */
729   silc_protocol_free(protocol);
730   if (ctx->packet)
731     silc_packet_context_free(ctx->packet);
732   silc_free(ctx);
733   sock->protocol = NULL;
734
735   /* Allocate the authentication protocol. This is allocated here
736      but we won't start it yet. We will be receiving party of this
737      protocol thus we will wait that connecting party will make
738      their first move. */
739   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH, 
740                       &sock->protocol, proto_ctx, 
741                       silc_server_connect_to_router_final);
742
743   /* Register timeout task. If the protocol is not executed inside
744      this timelimit the connection will be terminated. Currently
745      this is 15 seconds and is hard coded limit (XXX). */
746   proto_ctx->timeout_task = 
747     silc_task_register(server->timeout_queue, sock->sock, 
748                        silc_server_timeout_remote,
749                        (void *)server, 15, 0,
750                        SILC_TASK_TIMEOUT,
751                        SILC_TASK_PRI_LOW);
752
753   /* Run the protocol */
754   sock->protocol->execute(server->timeout_queue, 0, 
755                           sock->protocol, sock->sock, 0, 0);
756 }
757
758 /* Finalizes the connection to router. Registers a server task to the
759    queue so that we can accept new connections. */
760
761 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
762 {
763   SilcProtocol protocol = (SilcProtocol)context;
764   SilcServerConnAuthInternalContext *ctx = 
765     (SilcServerConnAuthInternalContext *)protocol->context;
766   SilcServer server = (SilcServer)ctx->server;
767   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
768   SilcSocketConnection sock = ctx->sock;
769   SilcServerEntry id_entry;
770   SilcBuffer packet;
771   unsigned char *id_string;
772
773   SILC_LOG_DEBUG(("Start"));
774
775   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
776     /* Error occured during protocol */
777     if (ctx->dest_id)
778       silc_free(ctx->dest_id);
779     silc_server_disconnect_remote(server, sock, "Server closed connection: "
780                                   "Authentication failed");
781     goto out;
782   }
783
784   /* Add a task to the queue. This task receives new connections to the 
785      server. This task remains on the queue until the end of the program. */
786   if (!server->listenning) {
787     silc_task_register(server->io_queue, server->sock, 
788                        silc_server_accept_new_connection,
789                        (void *)server, 0, 0, 
790                        SILC_TASK_FD,
791                        SILC_TASK_PRI_NORMAL);
792     server->listenning = TRUE;
793   }
794
795   /* Send NEW_SERVER packet to the router. We will become registered
796      to the SILC network after sending this packet. */
797   id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
798   packet = silc_buffer_alloc(2 + 2 + SILC_ID_SERVER_LEN + 
799                              strlen(server->server_name));
800   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
801   silc_buffer_format(packet,
802                      SILC_STR_UI_SHORT(SILC_ID_SERVER_LEN),
803                      SILC_STR_UI_XNSTRING(id_string, SILC_ID_SERVER_LEN),
804                      SILC_STR_UI_SHORT(strlen(server->server_name)),
805                      SILC_STR_UI_XNSTRING(server->server_name,
806                                           strlen(server->server_name)),
807                      SILC_STR_END);
808
809   /* Send the packet */
810   silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
811                           packet->data, packet->len, TRUE);
812   silc_buffer_free(packet);
813   silc_free(id_string);
814
815   SILC_LOG_DEBUG(("Connected to router %s", sock->hostname));
816
817   /* Add the connected router to local server list */
818   server->standalone = FALSE;
819   id_entry = silc_idlist_add_server(server->local_list, sock->hostname,
820                                     SILC_ROUTER, ctx->dest_id, NULL, sock);
821   if (!id_entry) {
822     if (ctx->dest_id)
823       silc_free(ctx->dest_id);
824     silc_server_disconnect_remote(server, sock, "Server closed connection: "
825                                   "Authentication failed");
826     goto out;
827   }
828
829   silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
830   silc_free(sock->user_data);
831   sock->user_data = (void *)id_entry;
832   sock->type = SILC_SOCKET_TYPE_ROUTER;
833   server->id_entry->router = id_entry;
834   server->router = id_entry;
835   server->router->data.registered = TRUE;
836
837  out:
838   /* Free the temporary connection data context */
839   if (sconn)
840     silc_free(sconn);
841
842   /* Free the protocol object */
843   silc_protocol_free(protocol);
844   if (ctx->packet)
845     silc_packet_context_free(ctx->packet);
846   if (ctx->ske)
847     silc_ske_free(ctx->ske);
848   silc_free(ctx);
849   sock->protocol = NULL;
850 }
851
852 /* Accepts new connections to the server. Accepting new connections are
853    done in three parts to make it async. */
854
855 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
856 {
857   SilcServer server = (SilcServer)context;
858   SilcSocketConnection newsocket;
859   SilcServerKEInternalContext *proto_ctx;
860   int sock;
861
862   SILC_LOG_DEBUG(("Accepting new connection"));
863
864   server->stat.conn_attempts++;
865
866   sock = silc_net_accept_connection(server->sock);
867   if (sock < 0) {
868     SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
869     server->stat.conn_failures++;
870     return;
871   }
872
873   /* Check max connections */
874   if (sock > SILC_SERVER_MAX_CONNECTIONS) {
875     if (server->config->redirect) {
876       /* XXX Redirecting connection to somewhere else now?? */
877       /*silc_server_send_notify("Server is full, trying to redirect..."); */
878     } else {
879       SILC_LOG_ERROR(("Refusing connection, server is full"));
880       server->stat.conn_failures++;
881     }
882     return;
883   }
884
885   /* Set socket options */
886   silc_net_set_socket_nonblock(sock);
887   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
888
889   /* We don't create a ID yet, since we don't know what type of connection
890      this is yet. But, we do add the connection to the socket table. */
891   silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
892   server->sockets[sock] = newsocket;
893
894   /* XXX This MUST be done async as this will block the entire server
895      process. Either we have to do our own resolver stuff or in the future
896      we can use threads. */
897   /* Perform name and address lookups for the remote host. */
898   silc_net_check_host_by_sock(sock, &newsocket->hostname, &newsocket->ip);
899   if ((server->params->require_reverse_mapping && !newsocket->hostname) ||
900       !newsocket->ip) {
901     SILC_LOG_ERROR(("IP/DNS lookup failed"));
902     server->stat.conn_failures++;
903     return;
904   }
905   if (!newsocket->hostname)
906     newsocket->hostname = strdup(newsocket->ip);
907
908   SILC_LOG_INFO(("Incoming connection from %s (%s)", newsocket->hostname,
909                  newsocket->ip));
910
911   /* Allocate internal context for key exchange protocol. This is
912      sent as context for the protocol. */
913   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
914   proto_ctx->server = context;
915   proto_ctx->sock = newsocket;
916   proto_ctx->rng = server->rng;
917   proto_ctx->responder = TRUE;
918
919   /* Prepare the connection for key exchange protocol. We allocate the
920      protocol but will not start it yet. The connector will be the
921      initiator of the protocol thus we will wait for initiation from 
922      there before we start the protocol. */
923   server->stat.auth_attempts++;
924   silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE, 
925                       &newsocket->protocol, proto_ctx, 
926                       silc_server_accept_new_connection_second);
927
928   /* Register a timeout task that will be executed if the connector
929      will not start the key exchange protocol within 60 seconds. For
930      now, this is a hard coded limit. After 60 secs the connection will
931      be closed if the key exchange protocol has not been started. */
932   proto_ctx->timeout_task = 
933     silc_task_register(server->timeout_queue, newsocket->sock, 
934                        silc_server_timeout_remote,
935                        context, 60, 0,
936                        SILC_TASK_TIMEOUT,
937                        SILC_TASK_PRI_LOW);
938
939   /* Register the connection for network input and output. This sets
940      that scheduler will listen for incoming packets for this connection 
941      and sets that outgoing packets may be sent to this connection as well.
942      However, this doesn't set the scheduler for outgoing traffic, it
943      will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
944      later when outgoing data is available. */
945   SILC_REGISTER_CONNECTION_FOR_IO(sock);
946 }
947
948 /* Second part of accepting new connection. Key exchange protocol has been
949    performed and now it is time to do little connection authentication
950    protocol to figure out whether this connection is client or server
951    and whether it has right to access this server (especially server
952    connections needs to be authenticated). */
953
954 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
955 {
956   SilcProtocol protocol = (SilcProtocol)context;
957   SilcServerKEInternalContext *ctx = 
958     (SilcServerKEInternalContext *)protocol->context;
959   SilcServer server = (SilcServer)ctx->server;
960   SilcSocketConnection sock = NULL;
961   SilcServerConnAuthInternalContext *proto_ctx;
962
963   SILC_LOG_DEBUG(("Start"));
964
965   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
966     /* Error occured during protocol */
967     silc_protocol_free(protocol);
968     if (ctx->packet)
969       silc_packet_context_free(ctx->packet);
970     if (ctx->ske)
971       silc_ske_free(ctx->ske);
972     if (ctx->dest_id)
973       silc_free(ctx->dest_id);
974     silc_free(ctx);
975     if (sock)
976       sock->protocol = NULL;
977     silc_server_disconnect_remote(server, sock, "Server closed connection: "
978                                   "Key exchange failed");
979     server->stat.auth_failures++;
980     return;
981   }
982
983   /* Allocate internal context for the authentication protocol. This
984      is sent as context for the protocol. */
985   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
986   proto_ctx->server = (void *)server;
987   proto_ctx->sock = sock = server->sockets[fd];
988   proto_ctx->ske = ctx->ske;    /* Save SKE object from previous protocol */
989   proto_ctx->responder = TRUE;
990   proto_ctx->dest_id_type = ctx->dest_id_type;
991   proto_ctx->dest_id = ctx->dest_id;
992
993   /* Free old protocol as it is finished now */
994   silc_protocol_free(protocol);
995   if (ctx->packet)
996     silc_packet_context_free(ctx->packet);
997   silc_free(ctx);
998   sock->protocol = NULL;
999
1000   /* Allocate the authentication protocol. This is allocated here
1001      but we won't start it yet. We will be receiving party of this
1002      protocol thus we will wait that connecting party will make
1003      their first move. */
1004   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH, 
1005                       &sock->protocol, proto_ctx, 
1006                       silc_server_accept_new_connection_final);
1007
1008   /* Register timeout task. If the protocol is not executed inside
1009      this timelimit the connection will be terminated. Currently
1010      this is 60 seconds and is hard coded limit (XXX). */
1011   proto_ctx->timeout_task = 
1012     silc_task_register(server->timeout_queue, sock->sock, 
1013                        silc_server_timeout_remote,
1014                        (void *)server, 60, 0,
1015                        SILC_TASK_TIMEOUT,
1016                        SILC_TASK_PRI_LOW);
1017 }
1018
1019 /* Final part of accepting new connection. The connection has now
1020    been authenticated and keys has been exchanged. We also know whether
1021    this is client or server connection. */
1022
1023 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1024 {
1025   SilcProtocol protocol = (SilcProtocol)context;
1026   SilcServerConnAuthInternalContext *ctx = 
1027     (SilcServerConnAuthInternalContext *)protocol->context;
1028   SilcServer server = (SilcServer)ctx->server;
1029   SilcSocketConnection sock = ctx->sock;
1030   void *id_entry = NULL;
1031
1032   SILC_LOG_DEBUG(("Start"));
1033
1034   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
1035     /* Error occured during protocol */
1036     silc_protocol_free(protocol);
1037     if (ctx->packet)
1038       silc_packet_context_free(ctx->packet);
1039     if (ctx->ske)
1040       silc_ske_free(ctx->ske);
1041     if (ctx->dest_id)
1042       silc_free(ctx->dest_id);
1043     silc_free(ctx);
1044     if (sock)
1045       sock->protocol = NULL;
1046     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1047                                   "Authentication failed");
1048     server->stat.auth_failures++;
1049     return;
1050   }
1051
1052   sock->type = ctx->conn_type;
1053   switch(sock->type) {
1054   case SILC_SOCKET_TYPE_CLIENT:
1055     {
1056       SilcClientEntry client;
1057
1058       SILC_LOG_DEBUG(("Remote host is client"));
1059       SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
1060                      sock->ip));
1061
1062       /* Add the client to the client ID cache. The nickname and Client ID
1063          and other information is created after we have received NEW_CLIENT
1064          packet from client. */
1065       client = silc_idlist_add_client(server->local_list, 
1066                                       NULL, NULL, NULL, NULL, NULL, sock);
1067       if (!client) {
1068         SILC_LOG_ERROR(("Could not add new client to cache"));
1069         silc_free(sock->user_data);
1070         break;
1071       }
1072
1073       /* Statistics */
1074       server->stat.my_clients++;
1075       server->stat.clients++;
1076       if (server->server_type == SILC_ROUTER)
1077         server->stat.cell_clients++;
1078
1079       id_entry = (void *)client;
1080       break;
1081     }
1082   case SILC_SOCKET_TYPE_SERVER:
1083   case SILC_SOCKET_TYPE_ROUTER:
1084     {
1085       SilcServerEntry new_server;
1086
1087       SILC_LOG_DEBUG(("Remote host is %s", 
1088                       sock->type == SILC_SOCKET_TYPE_SERVER ? 
1089                       "server" : "router"));
1090       SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
1091                      sock->ip, sock->type == SILC_SOCKET_TYPE_SERVER ? 
1092                      "server" : "router"));
1093
1094       /* Add the server into server cache. The server name and Server ID
1095          is updated after we have received NEW_SERVER packet from the
1096          server. We mark ourselves as router for this server if we really
1097          are router. */
1098       new_server = 
1099         silc_idlist_add_server(server->local_list, NULL,
1100                                sock->type == SILC_SOCKET_TYPE_SERVER ?
1101                                SILC_SERVER : SILC_ROUTER, NULL, 
1102                                sock->type == SILC_SOCKET_TYPE_SERVER ?
1103                                server->id_entry : NULL, sock);
1104       if (!new_server) {
1105         SILC_LOG_ERROR(("Could not add new server to cache"));
1106         silc_free(sock->user_data);
1107         break;
1108       }
1109
1110       /* Statistics */
1111       if (sock->type == SILC_SOCKET_TYPE_SERVER)
1112         server->stat.my_servers++;
1113       else
1114         server->stat.my_routers++;
1115       server->stat.servers++;
1116
1117       id_entry = (void *)new_server;
1118       
1119       /* There is connection to other server now, if it is router then
1120          we will have connection to outside world.  If we are router but
1121          normal server connected to us then we will remain standalone,
1122          if we are standlone. */
1123       if (server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER) {
1124         SILC_LOG_DEBUG(("We are not standalone server anymore"));
1125         server->standalone = FALSE;
1126         if (!server->id_entry->router) {
1127           server->id_entry->router = id_entry;
1128           server->router = id_entry;
1129         }
1130       }
1131       break;
1132     }
1133   default:
1134     break;
1135   }
1136
1137   /* Add the common data structure to the ID entry. */
1138   if (id_entry)
1139     silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1140       
1141   /* Add to sockets internal pointer for fast referencing */
1142   silc_free(sock->user_data);
1143   sock->user_data = id_entry;
1144
1145   /* Connection has been fully established now. Everything is ok. */
1146   SILC_LOG_DEBUG(("New connection authenticated"));
1147
1148   silc_protocol_free(protocol);
1149   if (ctx->packet)
1150     silc_packet_context_free(ctx->packet);
1151   if (ctx->ske)
1152     silc_ske_free(ctx->ske);
1153   if (ctx->dest_id)
1154     silc_free(ctx->dest_id);
1155   silc_free(ctx);
1156   sock->protocol = NULL;
1157 }
1158
1159 /* This function is used to read packets from network and send packets to
1160    network. This is usually a generic task. */
1161
1162 SILC_TASK_CALLBACK(silc_server_packet_process)
1163 {
1164   SilcServer server = (SilcServer)context;
1165   SilcSocketConnection sock = server->sockets[fd];
1166   SilcIDListData idata;
1167   SilcCipher cipher = NULL;
1168   SilcHmac hmac = NULL;
1169   int ret;
1170
1171   if (!sock)
1172     return;
1173
1174   SILC_LOG_DEBUG(("Processing packet"));
1175
1176   /* Packet sending */
1177
1178   if (type == SILC_TASK_WRITE) {
1179     server->stat.packets_sent++;
1180
1181     if (sock->outbuf->data - sock->outbuf->head)
1182       silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1183
1184     ret = silc_server_packet_send_real(server, sock, TRUE);
1185
1186     /* If returned -2 could not write to connection now, will do
1187        it later. */
1188     if (ret == -2)
1189       return;
1190
1191     if (ret == -1)
1192       return;
1193     
1194     /* The packet has been sent and now it is time to set the connection
1195        back to only for input. When there is again some outgoing data 
1196        available for this connection it will be set for output as well. 
1197        This call clears the output setting and sets it only for input. */
1198     SILC_SET_CONNECTION_FOR_INPUT(fd);
1199     SILC_UNSET_OUTBUF_PENDING(sock);
1200
1201     silc_buffer_clear(sock->outbuf);
1202     return;
1203   }
1204
1205   /* Packet receiving */
1206
1207   /* Read some data from connection */
1208   ret = silc_packet_receive(sock);
1209   if (ret < 0)
1210     return;
1211     
1212   /* EOF */
1213   if (ret == 0) {
1214     SILC_LOG_DEBUG(("Read EOF"));
1215       
1216     /* If connection is disconnecting already we will finally
1217        close the connection */
1218     if (SILC_IS_DISCONNECTING(sock)) {
1219       if (sock->user_data)
1220         silc_server_free_sock_user_data(server, sock);
1221       silc_server_close_connection(server, sock);
1222       return;
1223     }
1224       
1225     SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1226
1227     /* If the closed connection was our primary router connection the
1228        start re-connecting phase. */
1229     if (!server->standalone && server->server_type == SILC_SERVER && 
1230         sock == server->router->connection)
1231       silc_task_register(server->timeout_queue, 0, 
1232                          silc_server_connect_to_router,
1233                          context, 0, 500000,
1234                          SILC_TASK_TIMEOUT,
1235                          SILC_TASK_PRI_NORMAL);
1236
1237     if (sock->user_data)
1238       silc_server_free_sock_user_data(server, sock);
1239     silc_server_close_connection(server, sock);
1240     return;
1241   }
1242
1243   /* If connection is disconnecting or disconnected we will ignore
1244      what we read. */
1245   if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1246     SILC_LOG_DEBUG(("Ignoring read data from invalid connection"));
1247     return;
1248   }
1249
1250   server->stat.packets_received++;
1251
1252   /* Get keys and stuff from ID entry */
1253   idata = (SilcIDListData)sock->user_data;
1254   if (idata) {
1255     idata->last_receive = time(NULL);
1256     cipher = idata->receive_key;
1257     hmac = idata->hmac;
1258   }
1259  
1260   /* Process the packet. This will call the parser that will then
1261      decrypt and parse the packet. */
1262   silc_packet_receive_process(sock, cipher, hmac, silc_server_packet_parse, 
1263                               server);
1264 }
1265
1266 /* Parses whole packet, received earlier. */
1267
1268 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1269 {
1270   SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1271   SilcServer server = (SilcServer)parse_ctx->context;
1272   SilcSocketConnection sock = parse_ctx->sock;
1273   SilcPacketContext *packet = parse_ctx->packet;
1274   int ret;
1275
1276   SILC_LOG_DEBUG(("Start"));
1277
1278   /* Decrypt the received packet */
1279   ret = silc_packet_decrypt(parse_ctx->cipher, parse_ctx->hmac, 
1280                             packet->buffer, packet);
1281   if (ret < 0)
1282     goto out;
1283
1284   if (ret == 0) {
1285     /* Parse the packet. Packet type is returned. */
1286     ret = silc_packet_parse(packet);
1287   } else {
1288     /* Parse the packet header in special way as this is "special"
1289        packet type. */
1290     ret = silc_packet_parse_special(packet);
1291   }
1292
1293   if (ret == SILC_PACKET_NONE)
1294     goto out;
1295
1296   if (server->server_type == SILC_ROUTER) {
1297     /* Route the packet if it is not destined to us. Other ID types but
1298        server are handled separately after processing them. */
1299     if (packet->dst_id_type == SILC_ID_SERVER && 
1300         sock->type != SILC_SOCKET_TYPE_CLIENT &&
1301         SILC_ID_SERVER_COMPARE(packet->dst_id, server->id_string)) {
1302       
1303       /* Route the packet to fastest route for the destination ID */
1304       void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len, 
1305                                 packet->dst_id_type);
1306       if (!id)
1307         goto out;
1308       silc_server_packet_route(server,
1309                                silc_server_route_get(server, id,
1310                                                      packet->dst_id_type),
1311                                packet);
1312       silc_free(id);
1313       goto out;
1314     }
1315     
1316     /* Broadcast packet if it is marked as broadcast packet and it is
1317        originated from router and we are router. */
1318     if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1319         packet->flags & SILC_PACKET_FLAG_BROADCAST) {
1320       silc_server_packet_broadcast(server, server->router->connection, packet);
1321     }
1322   }
1323
1324   /* Parse the incoming packet type */
1325   silc_server_packet_parse_type(server, sock, packet);
1326
1327  out:
1328   silc_buffer_clear(sock->inbuf);
1329   silc_packet_context_free(packet);
1330   silc_free(parse_ctx);
1331 }
1332
1333 /* Parser callback called by silc_packet_receive_process. This merely
1334    registers timeout that will handle the actual parsing when appropriate. */
1335
1336 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1337 {
1338   SilcServer server = (SilcServer)parser_context->context;
1339   SilcSocketConnection sock = parser_context->sock;
1340
1341   switch (sock->type) {
1342   case SILC_SOCKET_TYPE_CLIENT:
1343   case SILC_SOCKET_TYPE_UNKNOWN:
1344     /* Parse the packet with timeout */
1345     silc_task_register(server->timeout_queue, sock->sock,
1346                        silc_server_packet_parse_real,
1347                        (void *)parser_context, 0, 100000,
1348                        SILC_TASK_TIMEOUT,
1349                        SILC_TASK_PRI_NORMAL);
1350     break;
1351   case SILC_SOCKET_TYPE_SERVER:
1352   case SILC_SOCKET_TYPE_ROUTER:
1353     /* Packets from servers are parsed as soon as possible */
1354     silc_task_register(server->timeout_queue, sock->sock,
1355                        silc_server_packet_parse_real,
1356                        (void *)parser_context, 0, 1,
1357                        SILC_TASK_TIMEOUT,
1358                        SILC_TASK_PRI_NORMAL);
1359     break;
1360   default:
1361     return;
1362   }
1363 }
1364
1365 /* Parses the packet type and calls what ever routines the packet type
1366    requires. This is done for all incoming packets. */
1367
1368 void silc_server_packet_parse_type(SilcServer server, 
1369                                    SilcSocketConnection sock,
1370                                    SilcPacketContext *packet)
1371 {
1372   SilcPacketType type = packet->type;
1373
1374   SILC_LOG_DEBUG(("Parsing packet type %d", type));
1375
1376   /* Parse the packet type */
1377   switch(type) {
1378   case SILC_PACKET_DISCONNECT:
1379     SILC_LOG_DEBUG(("Disconnect packet"));
1380     break;
1381
1382   case SILC_PACKET_SUCCESS:
1383     /*
1384      * Success received for something. For now we can have only
1385      * one protocol for connection executing at once hence this
1386      * success message is for whatever protocol is executing currently.
1387      */
1388     SILC_LOG_DEBUG(("Success packet"));
1389     if (sock->protocol) {
1390       sock->protocol->execute(server->timeout_queue, 0,
1391                               sock->protocol, sock->sock, 0, 0);
1392     }
1393     break;
1394
1395   case SILC_PACKET_FAILURE:
1396     /*
1397      * Failure received for something. For now we can have only
1398      * one protocol for connection executing at once hence this
1399      * failure message is for whatever protocol is executing currently.
1400      */
1401     SILC_LOG_DEBUG(("Failure packet"));
1402     if (sock->protocol) {
1403       /* XXX Audit the failure type */
1404       sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
1405       sock->protocol->execute(server->timeout_queue, 0,
1406                               sock->protocol, sock->sock, 0, 0);
1407     }
1408     break;
1409
1410   case SILC_PACKET_REJECT:
1411     SILC_LOG_DEBUG(("Reject packet"));
1412     return;
1413     break;
1414
1415   case SILC_PACKET_NOTIFY:
1416     /*
1417      * Received notify packet. Server can receive notify packets from
1418      * router. Server then relays the notify messages to clients if needed.
1419      */
1420     SILC_LOG_DEBUG(("Notify packet"));
1421     silc_server_notify(server, sock, packet);
1422     break;
1423
1424     /* 
1425      * Channel packets
1426      */
1427   case SILC_PACKET_CHANNEL_MESSAGE:
1428     /*
1429      * Received channel message. Channel messages are special packets
1430      * (although probably most common ones) thus they are handled
1431      * specially.
1432      */
1433     SILC_LOG_DEBUG(("Channel Message packet"));
1434     silc_server_channel_message(server, sock, packet);
1435     break;
1436
1437   case SILC_PACKET_CHANNEL_KEY:
1438     /*
1439      * Received key for channel. As channels are created by the router
1440      * the keys are as well. We will distribute the key to all of our
1441      * locally connected clients on the particular channel. Router
1442      * never receives this channel and thus is ignored.
1443      */
1444     SILC_LOG_DEBUG(("Channel Key packet"));
1445     silc_server_channel_key(server, sock, packet);
1446     break;
1447
1448     /*
1449      * Command packets
1450      */
1451   case SILC_PACKET_COMMAND:
1452     /*
1453      * Recived command. Processes the command request and allocates the
1454      * command context and calls the command.
1455      */
1456     SILC_LOG_DEBUG(("Command packet"));
1457     silc_server_command_process(server, sock, packet);
1458     break;
1459
1460   case SILC_PACKET_COMMAND_REPLY:
1461     /*
1462      * Received command reply packet. Received command reply to command. It
1463      * may be reply to command sent by us or reply to command sent by client
1464      * that we've routed further.
1465      */
1466     SILC_LOG_DEBUG(("Command Reply packet"));
1467     silc_server_command_reply(server, sock, packet);
1468     break;
1469
1470     /*
1471      * Private Message packets
1472      */
1473   case SILC_PACKET_PRIVATE_MESSAGE:
1474     /*
1475      * Received private message packet. The packet is coming from either
1476      * client or server.
1477      */
1478     SILC_LOG_DEBUG(("Private Message packet"));
1479     silc_server_private_message(server, sock, packet);
1480     break;
1481
1482   case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1483     /*
1484      * Private message key packet.
1485      */
1486     break;
1487
1488     /*
1489      * Key Exchange protocol packets
1490      */
1491   case SILC_PACKET_KEY_EXCHANGE:
1492     SILC_LOG_DEBUG(("KE packet"));
1493     if (sock->protocol && sock->protocol->protocol->type 
1494         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1495
1496       SilcServerKEInternalContext *proto_ctx = 
1497         (SilcServerKEInternalContext *)sock->protocol->context;
1498
1499       proto_ctx->packet = silc_packet_context_dup(packet);
1500
1501       /* Let the protocol handle the packet */
1502       sock->protocol->execute(server->timeout_queue, 0, 
1503                               sock->protocol, sock->sock, 0, 100000);
1504     } else {
1505       SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1506                       "protocol active, packet dropped."));
1507
1508       /* XXX Trigger KE protocol?? Rekey actually, maybe. */
1509     }
1510     break;
1511
1512   case SILC_PACKET_KEY_EXCHANGE_1:
1513     SILC_LOG_DEBUG(("KE 1 packet"));
1514     if (sock->protocol && sock->protocol->protocol->type 
1515         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1516
1517       SilcServerKEInternalContext *proto_ctx = 
1518         (SilcServerKEInternalContext *)sock->protocol->context;
1519
1520       if (proto_ctx->packet)
1521         silc_packet_context_free(proto_ctx->packet);
1522
1523       proto_ctx->packet = silc_packet_context_dup(packet);
1524       proto_ctx->dest_id_type = packet->src_id_type;
1525       proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1526                                           packet->src_id_type);
1527       if (!proto_ctx->dest_id)
1528         break;
1529
1530       /* Let the protocol handle the packet */
1531       sock->protocol->execute(server->timeout_queue, 0, 
1532                               sock->protocol, sock->sock,
1533                               0, 100000);
1534     } else {
1535       SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1536                       "protocol active, packet dropped."));
1537     }
1538     break;
1539
1540   case SILC_PACKET_KEY_EXCHANGE_2:
1541     SILC_LOG_DEBUG(("KE 2 packet"));
1542     if (sock->protocol && sock->protocol->protocol->type 
1543         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1544
1545       SilcServerKEInternalContext *proto_ctx = 
1546         (SilcServerKEInternalContext *)sock->protocol->context;
1547
1548       if (proto_ctx->packet)
1549         silc_packet_context_free(proto_ctx->packet);
1550
1551       proto_ctx->packet = silc_packet_context_dup(packet);
1552       proto_ctx->dest_id_type = packet->src_id_type;
1553       proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1554                                           packet->src_id_type);
1555       if (!proto_ctx->dest_id)
1556         break;
1557
1558       /* Let the protocol handle the packet */
1559       sock->protocol->execute(server->timeout_queue, 0, 
1560                               sock->protocol, sock->sock,
1561                               0, 100000);
1562     } else {
1563       SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1564                       "protocol active, packet dropped."));
1565     }
1566     break;
1567
1568   case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1569     /*
1570      * Connection authentication request packet. When we receive this packet
1571      * we will send to the other end information about our mandatory
1572      * authentication method for the connection. This packet maybe received
1573      * at any time. 
1574      */
1575     SILC_LOG_DEBUG(("Connection authentication request packet"));
1576     break;
1577
1578     /*
1579      * Connection Authentication protocol packets
1580      */
1581   case SILC_PACKET_CONNECTION_AUTH:
1582     /* Start of the authentication protocol. We receive here the 
1583        authentication data and will verify it. */
1584     SILC_LOG_DEBUG(("Connection auth packet"));
1585     if (sock->protocol && sock->protocol->protocol->type 
1586         == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1587
1588       SilcServerConnAuthInternalContext *proto_ctx = 
1589         (SilcServerConnAuthInternalContext *)sock->protocol->context;
1590
1591       proto_ctx->packet = silc_packet_context_dup(packet);
1592
1593       /* Let the protocol handle the packet */
1594       sock->protocol->execute(server->timeout_queue, 0, 
1595                               sock->protocol, sock->sock, 0, 0);
1596     } else {
1597       SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1598                       "protocol active, packet dropped."));
1599     }
1600     break;
1601
1602   case SILC_PACKET_NEW_ID:
1603     /*
1604      * Received New ID packet. This includes some new ID that has been
1605      * created. It may be for client, server or channel. This is the way
1606      * to distribute information about new registered entities in the
1607      * SILC network.
1608      */
1609     SILC_LOG_DEBUG(("New ID packet"));
1610     silc_server_new_id(server, sock, packet);
1611     break;
1612
1613   case SILC_PACKET_NEW_CLIENT:
1614     /*
1615      * Received new client packet. This includes client information that
1616      * we will use to create initial client ID. After creating new
1617      * ID we will send it to the client.
1618      */
1619     SILC_LOG_DEBUG(("New Client packet"));
1620     silc_server_new_client(server, sock, packet);
1621     break;
1622
1623   case SILC_PACKET_NEW_SERVER:
1624     /*
1625      * Received new server packet. This includes Server ID and some other
1626      * information that we may save. This is received after server has 
1627      * connected to us.
1628      */
1629     SILC_LOG_DEBUG(("New Server packet"));
1630     silc_server_new_server(server, sock, packet);
1631     break;
1632
1633   case SILC_PACKET_NEW_CHANNEL:
1634     /*
1635      * Received new channel packet. Information about new channel in the
1636      * network are distributed using this packet.
1637      */
1638     SILC_LOG_DEBUG(("New Channel packet"));
1639     silc_server_new_channel(server, sock, packet);
1640     break;
1641
1642   case SILC_PACKET_NEW_CHANNEL_USER:
1643     /*
1644      * Received new channel user packet. Information about new users on a
1645      * channel are distributed between routers using this packet.  The
1646      * router receiving this will redistribute it and also sent JOIN notify
1647      * to local clients on the same channel. Normal server sends JOIN notify
1648      * to its local clients on the channel.
1649      */
1650     SILC_LOG_DEBUG(("New Channel User packet"));
1651     silc_server_new_channel_user(server, sock, packet);
1652     break;
1653
1654   case SILC_PACKET_NEW_CHANNEL_LIST:
1655     /*
1656      * List of new channel packets received. This is usually received when
1657      * existing server or router connects to us and distributes information
1658      * of all channels it has.
1659      */
1660     break;
1661
1662   case SILC_PACKET_NEW_CHANNEL_USER_LIST:
1663     /*
1664      * List of new channel user packets received. This is usually received
1665      * when existing server or router connects to us and distributes 
1666      * information of all channel users it has.
1667      */
1668     break;
1669
1670   case SILC_PACKET_REPLACE_ID:
1671     /*
1672      * Received replace ID packet. This sends the old ID that is to be
1673      * replaced with the new one included into the packet. Client must not
1674      * send this packet.
1675      */
1676     SILC_LOG_DEBUG(("Replace ID packet"));
1677     silc_server_replace_id(server, sock, packet);
1678     break;
1679
1680   case SILC_PACKET_REMOVE_ID:
1681     /*
1682      * Received remove ID Packet. 
1683      */
1684     SILC_LOG_DEBUG(("Remove ID packet"));
1685     silc_server_remove_id(server, sock, packet);
1686     break;
1687
1688   case SILC_PACKET_REMOVE_CHANNEL_USER:
1689     /*
1690      * Received packet to remove user from a channel. Routers notify other
1691      * routers about a user leaving a channel.
1692      */
1693     SILC_LOG_DEBUG(("Remove Channel User packet"));
1694     silc_server_remove_channel_user(server, sock, packet);
1695     break;
1696
1697   case SILC_PACKET_SET_MODE:
1698     /*
1699      * Received packet to set the mode of channel or client's channel mode.
1700      */
1701     SILC_LOG_DEBUG(("Set Mode packet"));
1702     silc_server_set_mode(server, sock, packet);
1703     break;
1704
1705   default:
1706     SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
1707     break;
1708   }
1709   
1710 }
1711
1712 /* Closes connection to socket connection */
1713
1714 void silc_server_close_connection(SilcServer server,
1715                                   SilcSocketConnection sock)
1716 {
1717   SILC_LOG_DEBUG(("Closing connection %d", sock->sock));
1718
1719   /* We won't listen for this connection anymore */
1720   silc_schedule_unset_listen_fd(sock->sock);
1721
1722   /* Unregister all tasks */
1723   silc_task_unregister_by_fd(server->io_queue, sock->sock);
1724   silc_task_unregister_by_fd(server->timeout_queue, sock->sock);
1725
1726   /* Close the actual connection */
1727   silc_net_close_connection(sock->sock);
1728   server->sockets[sock->sock] = NULL;
1729   silc_socket_free(sock);
1730 }
1731
1732 /* Sends disconnect message to remote connection and disconnects the 
1733    connection. */
1734
1735 void silc_server_disconnect_remote(SilcServer server,
1736                                    SilcSocketConnection sock,
1737                                    const char *fmt, ...)
1738 {
1739   va_list ap;
1740   unsigned char buf[4096];
1741
1742   if (!sock)
1743     return;
1744
1745   memset(buf, 0, sizeof(buf));
1746   va_start(ap, fmt);
1747   vsprintf(buf, fmt, ap);
1748   va_end(ap);
1749
1750   SILC_LOG_DEBUG(("Disconnecting remote host"));
1751
1752   /* Notify remote end that the conversation is over. The notify message
1753      is tried to be sent immediately. */
1754   silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,  
1755                           buf, strlen(buf), TRUE);
1756
1757   /* Mark the connection to be disconnected */
1758   SILC_SET_DISCONNECTED(sock);
1759   silc_server_close_connection(server, sock);
1760 }
1761
1762 /* Free's user_data pointer from socket connection object. This also sends
1763    appropriate notify packets to the network to inform about leaving
1764    entities. */
1765
1766 void silc_server_free_sock_user_data(SilcServer server, 
1767                                      SilcSocketConnection sock)
1768 {
1769   SILC_LOG_DEBUG(("Start"));
1770
1771   switch(sock->type) {
1772   case SILC_SOCKET_TYPE_CLIENT:
1773     {
1774       SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
1775
1776       /* Remove client from all channels */
1777       silc_server_remove_from_channels(server, sock, user_data);
1778
1779       /* XXX must take some info to history before freeing */
1780
1781       /* Send REMOVE_ID packet to routers. */
1782       if (!server->standalone && server->router)
1783         silc_server_send_remove_id(server, server->router->connection,
1784                                    server->server_type == SILC_SERVER ?
1785                                    FALSE : TRUE, user_data->id, 
1786                                    SILC_ID_CLIENT_LEN, SILC_ID_CLIENT);
1787
1788       /* Free the client entry and everything in it */
1789       silc_idlist_del_data(user_data);
1790       silc_idlist_del_client(server->local_list, user_data);
1791       server->stat.my_clients--;
1792       server->stat.clients--;
1793       if (server->server_type == SILC_ROUTER)
1794         server->stat.cell_clients--;
1795       break;
1796     }
1797   case SILC_SOCKET_TYPE_SERVER:
1798   case SILC_SOCKET_TYPE_ROUTER:
1799     {
1800       SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
1801
1802       /* Send REMOVE_ID packet to routers. */
1803       if (!server->standalone && server->router)
1804         silc_server_send_remove_id(server, server->router->connection,
1805                                    server->server_type == SILC_SERVER ?
1806                                    FALSE : TRUE, user_data->id, 
1807                                    SILC_ID_CLIENT_LEN, SILC_ID_CLIENT);
1808
1809       /* Free the server entry */
1810       silc_idlist_del_data(user_data);
1811       silc_idlist_del_server(server->local_list, user_data);
1812       server->stat.my_servers--;
1813       server->stat.servers--;
1814       if (server->server_type == SILC_ROUTER)
1815         server->stat.cell_servers--;
1816       break;
1817     }
1818   default:
1819     {
1820       SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
1821
1822       silc_idlist_del_data(user_data);
1823       silc_free(user_data);
1824       break;
1825     }
1826   }
1827
1828   sock->user_data = NULL;
1829 }
1830
1831 /* Checks whether given channel has global users.  If it does this returns
1832    TRUE and FALSE if there is only locally connected clients on the channel. */
1833
1834 int silc_server_channel_has_global(SilcChannelEntry channel)
1835 {
1836   SilcChannelClientEntry chl;
1837
1838   silc_list_start(channel->user_list);
1839   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
1840     if (chl->client->router)
1841       return TRUE;
1842   }
1843
1844   return FALSE;
1845 }
1846
1847 /* Checks whether given channel has locally connected users.  If it does this
1848    returns TRUE and FALSE if there is not one locally connected client. */
1849
1850 int silc_server_channel_has_local(SilcChannelEntry channel)
1851 {
1852   SilcChannelClientEntry chl;
1853
1854   silc_list_start(channel->user_list);
1855   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
1856     if (!chl->client->router)
1857       return TRUE;
1858   }
1859
1860   return FALSE;
1861 }
1862
1863 /* Removes client from all channels it has joined. This is used when client
1864    connection is disconnected. If the client on a channel is last, the
1865    channel is removed as well. This sends the SIGNOFF notify types. */
1866
1867 void silc_server_remove_from_channels(SilcServer server, 
1868                                       SilcSocketConnection sock,
1869                                       SilcClientEntry client)
1870 {
1871   SilcChannelEntry channel;
1872   SilcChannelClientEntry chl;
1873   SilcBuffer chidp, clidp;
1874
1875   SILC_LOG_DEBUG(("Start"));
1876
1877   if (!client || !client->id)
1878     return;
1879
1880   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
1881
1882   /* Remove the client from all channels. The client is removed from
1883      the channels' user list. */
1884   silc_list_start(client->channels);
1885   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
1886     channel = chl->channel;
1887     chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
1888
1889     /* Remove from list */
1890     silc_list_del(client->channels, chl);
1891
1892     /* If this client is last one on the channel the channel
1893        is removed all together. */
1894     if (silc_list_count(channel->user_list) < 2) {
1895
1896       /* However, if the channel has marked global users then the 
1897          channel is not created locally, and this does not remove the
1898          channel globally from SILC network, in this case we will
1899          notify that this client has left the channel. */
1900       if (channel->global_users)
1901         silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
1902                                            SILC_NOTIFY_TYPE_SIGNOFF, 1,
1903                                            clidp->data, clidp->len);
1904       
1905       silc_idlist_del_channel(server->local_list, channel);
1906       server->stat.my_channels--;
1907       continue;
1908     }
1909
1910     /* Remove from list */
1911     silc_list_del(channel->user_list, chl);
1912     silc_free(chl);
1913     server->stat.my_chanclients--;
1914
1915     /* Send notify to channel about client leaving SILC and thus
1916        the entire channel. */
1917     silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
1918                                        SILC_NOTIFY_TYPE_SIGNOFF, 1,
1919                                        clidp->data, clidp->len);
1920     silc_buffer_free(chidp);
1921   }
1922
1923   silc_buffer_free(clidp);
1924 }
1925
1926 /* Removes client from one channel. This is used for example when client
1927    calls LEAVE command to remove itself from the channel. Returns TRUE
1928    if channel still exists and FALSE if the channel is removed when
1929    last client leaves the channel. If `notify' is FALSE notify messages
1930    are not sent. */
1931
1932 int silc_server_remove_from_one_channel(SilcServer server, 
1933                                         SilcSocketConnection sock,
1934                                         SilcChannelEntry channel,
1935                                         SilcClientEntry client,
1936                                         int notify)
1937 {
1938   SilcChannelEntry ch;
1939   SilcChannelClientEntry chl;
1940   SilcBuffer clidp;
1941
1942   SILC_LOG_DEBUG(("Start"));
1943
1944   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
1945
1946   /* Remove the client from the channel. The client is removed from
1947      the channel's user list. */
1948   silc_list_start(client->channels);
1949   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
1950     if (chl->channel != channel)
1951       continue;
1952
1953     ch = chl->channel;
1954
1955     /* Remove from list */
1956     silc_list_del(client->channels, chl);
1957
1958     /* If this client is last one on the channel the channel
1959        is removed all together. */
1960     if (silc_list_count(channel->user_list) < 2) {
1961       /* Notify about leaving client if this channel has global users. */
1962       if (notify && channel->global_users)
1963         silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
1964                                            SILC_NOTIFY_TYPE_LEAVE, 1,
1965                                            clidp->data, clidp->len);
1966       
1967       silc_idlist_del_channel(server->local_list, channel);
1968       silc_buffer_free(clidp);
1969       server->stat.my_channels--;
1970       return FALSE;
1971     }
1972
1973     /* Remove from list */
1974     silc_list_del(channel->user_list, chl);
1975     silc_free(chl);
1976     server->stat.my_chanclients--;
1977
1978     /* If there is no global users on the channel anymore mark the channel
1979        as local channel. */
1980     if (server->server_type == SILC_SERVER &&
1981         !silc_server_channel_has_global(channel))
1982       channel->global_users = FALSE;
1983
1984     /* If tehre is not at least one local user on the channel then we don't
1985        need the channel entry anymore, we can remove it safely. */
1986     if (server->server_type == SILC_SERVER &&
1987         !silc_server_channel_has_local(channel)) {
1988       silc_idlist_del_channel(server->local_list, channel);
1989       silc_buffer_free(clidp);
1990       server->stat.my_channels--;
1991       return FALSE;
1992     }
1993
1994     /* Send notify to channel about client leaving the channel */
1995     if (notify)
1996       silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
1997                                          SILC_NOTIFY_TYPE_LEAVE, 1,
1998                                          clidp->data, clidp->len);
1999     break;
2000   }
2001
2002   silc_buffer_free(clidp);
2003   return TRUE;
2004 }
2005
2006 /* Returns TRUE if the given client is on the channel.  FALSE if not. 
2007    This works because we assure that the user list on the channel is
2008    always in up to date thus we can only check the channel list from 
2009    `client' which is faster than checking the user list from `channel'. */
2010
2011 int silc_server_client_on_channel(SilcClientEntry client,
2012                                   SilcChannelEntry channel)
2013 {
2014   SilcChannelClientEntry chl;
2015
2016   if (!client || !channel)
2017     return FALSE;
2018
2019   silc_list_start(client->channels);
2020   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END)
2021     if (chl->channel == channel)
2022       return TRUE;
2023
2024   return FALSE;
2025 }
2026
2027 /* Timeout callback. This is called if connection is idle or for some
2028    other reason is not responding within some period of time. This 
2029    disconnects the remote end. */
2030
2031 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2032 {
2033   SilcServer server = (SilcServer)context;
2034   SilcSocketConnection sock = server->sockets[fd];
2035
2036   if (!sock)
2037     return;
2038
2039   if (sock->user_data)
2040     silc_server_free_sock_user_data(server, sock);
2041
2042   silc_server_disconnect_remote(server, sock, 
2043                                 "Server closed connection: "
2044                                 "Connection timeout");
2045 }
2046
2047 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2048    function may be used only by router. In real SILC network all channels
2049    are created by routers thus this function is never used by normal
2050    server. */
2051
2052 SilcChannelEntry silc_server_create_new_channel(SilcServer server, 
2053                                                 SilcServerID *router_id,
2054                                                 char *cipher, 
2055                                                 char *channel_name)
2056 {
2057   SilcChannelID *channel_id;
2058   SilcChannelEntry entry;
2059   SilcCipher key;
2060
2061   SILC_LOG_DEBUG(("Creating new channel"));
2062
2063   if (!cipher)
2064     cipher = "twofish";
2065
2066   /* Allocate cipher */
2067   silc_cipher_alloc(cipher, &key);
2068
2069   channel_name = strdup(channel_name);
2070
2071   /* Create the channel */
2072   silc_id_create_channel_id(router_id, server->rng, &channel_id);
2073   entry = silc_idlist_add_channel(server->local_list, channel_name, 
2074                                   SILC_CHANNEL_MODE_NONE, channel_id, 
2075                                   NULL, key);
2076   if (!entry) {
2077     silc_free(channel_name);
2078     return NULL;
2079   }
2080
2081   /* Now create the actual key material */
2082   silc_server_create_channel_key(server, entry, 16);
2083
2084   /* Notify other routers about the new channel. We send the packet
2085      to our primary route. */
2086   if (server->standalone == FALSE) {
2087     silc_server_send_new_channel(server, server->router->connection, TRUE, 
2088                                  channel_name, entry->id, SILC_ID_CHANNEL_LEN);
2089   }
2090
2091   server->stat.my_channels++;
2092
2093   return entry;
2094 }
2095
2096 /* Generates new channel key. This is used to create the initial channel key
2097    but also to re-generate new key for channel. If `key_len' is provided
2098    it is the bytes of the key length. */
2099
2100 void silc_server_create_channel_key(SilcServer server, 
2101                                     SilcChannelEntry channel,
2102                                     unsigned int key_len)
2103 {
2104   int i;
2105   unsigned char channel_key[32];
2106   unsigned int len;
2107
2108   if (!channel->channel_key)
2109     silc_cipher_alloc("twofish", &channel->channel_key);
2110
2111   if (key_len)
2112     len = key_len;
2113   else if (channel->key_len)
2114     len = channel->key_len / 8;
2115   else
2116     len = sizeof(channel_key);
2117
2118   /* Create channel key */
2119   for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
2120   
2121   /* Set the key */
2122   channel->channel_key->cipher->set_key(channel->channel_key->context, 
2123                                         channel_key, len);
2124
2125   /* Remove old key if exists */
2126   if (channel->key) {
2127     memset(channel->key, 0, channel->key_len / 8);
2128     silc_free(channel->key);
2129   }
2130
2131   /* Save the key */
2132   channel->key_len = len * 8;
2133   channel->key = silc_calloc(len, sizeof(*channel->key));
2134   memcpy(channel->key, channel_key, len);
2135   memset(channel_key, 0, sizeof(channel_key));
2136 }
2137
2138 /* Saves the channel key found in the encoded `key_payload' buffer. This 
2139    function is used when we receive Channel Key Payload and also when we're
2140    processing JOIN command reply. Returns entry to the channel. */
2141
2142 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
2143                                               SilcBuffer key_payload,
2144                                               SilcChannelEntry channel)
2145 {
2146   SilcChannelKeyPayload payload = NULL;
2147   SilcChannelID *id = NULL;
2148   unsigned char *tmp;
2149   unsigned int tmp_len;
2150   char *cipher;
2151
2152   /* Decode channel key payload */
2153   payload = silc_channel_key_payload_parse(key_payload);
2154   if (!payload) {
2155     SILC_LOG_ERROR(("Bad channel key payload, dropped"));
2156     channel = NULL;
2157     goto out;
2158   }
2159
2160   /* Get the channel entry */
2161   if (!channel) {
2162
2163     /* Get channel ID */
2164     tmp = silc_channel_key_get_id(payload, &tmp_len);
2165     id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
2166     if (!id) {
2167       channel = NULL;
2168       goto out;
2169     }
2170
2171     channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
2172     if (!channel) {
2173       SILC_LOG_ERROR(("Received key for non-existent channel"));
2174       goto out;
2175     }
2176   }
2177
2178   tmp = silc_channel_key_get_key(payload, &tmp_len);
2179   if (!tmp) {
2180     channel = NULL;
2181     goto out;
2182   }
2183
2184   cipher = silc_channel_key_get_cipher(payload, NULL);;
2185   if (!cipher) {
2186     channel = NULL;
2187     goto out;
2188   }
2189
2190   /* Remove old key if exists */
2191   if (channel->key) {
2192     memset(channel->key, 0, channel->key_len / 8);
2193     silc_free(channel->key);
2194     silc_cipher_free(channel->channel_key);
2195   }
2196
2197   /* Create new cipher */
2198   if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
2199     channel = NULL;
2200     goto out;
2201   }
2202
2203   /* Save the key */
2204   channel->key_len = tmp_len * 8;
2205   channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
2206   memcpy(channel->key, tmp, tmp_len);
2207   channel->channel_key->cipher->set_key(channel->channel_key->context, 
2208                                         tmp, tmp_len);
2209
2210  out:
2211   if (id)
2212     silc_free(id);
2213   if (payload)
2214     silc_channel_key_payload_free(payload);
2215
2216   return channel;
2217 }