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