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