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