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