updates, check CHANGES
[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 - 2000 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     SilcSimContext *sim;
75
76     if (server->local_list)
77       silc_free(server->local_list);
78     if (server->global_list)
79       silc_free(server->global_list);
80     if (server->rng)
81       silc_rng_free(server->rng);
82
83     while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
84       silc_dlist_del(server->sim, sim);
85       silc_sim_free(sim);
86     }
87     silc_dlist_uninit(server->sim);
88
89     if (server->params)
90       silc_free(server->params);
91
92     if (server->pending_commands)
93       silc_dlist_uninit(server->pending_commands);
94
95     silc_math_primegen_uninit(); /* XXX */
96     silc_free(server);
97   }
98 }
99
100 /* Initializes the entire SILC server. This is called always before running
101    the server. This is called only once at the initialization of the program.
102    This binds the server to its listenning port. After this function returns 
103    one should call silc_server_run to start the server. This returns TRUE 
104    when everything is ok to run the server. Configuration file must be
105    read and parsed before calling this. */
106
107 int silc_server_init(SilcServer server)
108 {
109   int *sock = NULL, sock_count = 0, i;
110   SilcServerID *id;
111   SilcServerEntry id_entry;
112
113   SILC_LOG_DEBUG(("Initializing server"));
114   assert(server);
115   assert(server->config);
116
117   /* XXX After server is made as Silc Server Library this can be given
118      as argument, for now this is hard coded */
119   server->params = silc_calloc(1, sizeof(*server->params));
120   server->params->retry_count = SILC_SERVER_RETRY_COUNT;
121   server->params->retry_interval_min = SILC_SERVER_RETRY_INTERVAL_MIN;
122   server->params->retry_interval_max = SILC_SERVER_RETRY_INTERVAL_MAX;
123   server->params->retry_keep_trying = FALSE;
124   server->params->protocol_timeout = 60;
125
126   /* Set log files where log message should be saved. */
127   server->config->server = server;
128   silc_config_server_setlogfiles(server->config);
129  
130   /* Register all configured ciphers, PKCS and hash functions. */
131   silc_config_server_register_ciphers(server->config);
132   silc_config_server_register_pkcs(server->config);
133   silc_config_server_register_hashfuncs(server->config);
134
135   /* Initialize random number generator for the server. */
136   server->rng = silc_rng_alloc();
137   silc_rng_init(server->rng);
138   silc_math_primegen_init(); /* XXX */
139
140   /* Initialize hash functions for server to use */
141   silc_hash_alloc("md5", &server->md5hash);
142   silc_hash_alloc("sha1", &server->sha1hash);
143
144   /* Initialize none cipher */
145   silc_cipher_alloc("none", &server->none_cipher);
146
147   /* XXXXX Generate RSA key pair */
148   {
149     unsigned char *public_key;
150     unsigned char *private_key;
151     unsigned int pk_len, prv_len;
152     struct stat st;
153
154     if (stat("pubkey.pub", &st) < 0 && stat("privkey.prv", &st) < 0) {
155
156       if (silc_pkcs_alloc("rsa", &server->pkcs) == FALSE) {
157         SILC_LOG_ERROR(("Could not create RSA key pair"));
158         goto err0;
159       }
160       
161       if (server->pkcs->pkcs->init(server->pkcs->context, 
162                                    1024, server->rng) == FALSE) {
163         SILC_LOG_ERROR(("Could not generate RSA key pair"));
164         goto err0;
165       }
166       
167       public_key = server->pkcs->pkcs->get_public_key(server->pkcs->context,
168                                                       &pk_len);
169       private_key = server->pkcs->pkcs->get_private_key(server->pkcs->context,
170                                                         &prv_len);
171       
172       SILC_LOG_HEXDUMP(("public key"), public_key, pk_len);
173       SILC_LOG_HEXDUMP(("private key"), private_key, prv_len);
174       
175       server->public_key = 
176         silc_pkcs_public_key_alloc("rsa", "UN=root, HN=dummy",
177                                    public_key, pk_len);
178       server->private_key = 
179         silc_pkcs_private_key_alloc("rsa", private_key, prv_len);
180       
181       /* XXX Save keys */
182       silc_pkcs_save_public_key("pubkey.pub", server->public_key,
183                                 SILC_PKCS_FILE_PEM);
184       silc_pkcs_save_private_key("privkey.prv", server->private_key, NULL,
185                                  SILC_PKCS_FILE_BIN);
186
187       memset(public_key, 0, pk_len);
188       memset(private_key, 0, prv_len);
189       silc_free(public_key);
190       silc_free(private_key);
191     } else {
192       silc_pkcs_load_public_key("pubkey.pub", &server->public_key,
193                                 SILC_PKCS_FILE_PEM);
194       silc_pkcs_load_private_key("privkey.prv", &server->private_key,
195                                  SILC_PKCS_FILE_BIN);
196     }
197   }
198
199   /* Create a listening server. Note that our server can listen on
200      multiple ports. All listeners are created here and now. */
201   /* XXX Still check this whether to use server_info or listen_port. */
202   sock_count = 0;
203   while(server->config->listen_port) {
204     int tmp;
205
206     tmp = silc_net_create_server(server->config->listen_port->port,
207                                  server->config->listen_port->host);
208     if (tmp < 0)
209       goto err0;
210
211     sock = silc_realloc(sock, (sizeof(int *) * (sock_count + 1)));
212     sock[sock_count] = tmp;
213     server->config->listen_port = server->config->listen_port->next;
214     sock_count++;
215   }
216
217   /* Initialize ID caches */
218   server->local_list->clients = silc_idcache_alloc(0);
219   server->local_list->servers = silc_idcache_alloc(0);
220   server->local_list->channels = silc_idcache_alloc(0);
221
222   /* XXX for now these are allocated for normal server as well as these
223      hold some global information that the server has fetched from its
224      router. For router these are used as they are supposed to be used
225      on router. The XXX can be remoevd later if this is the way we are
226      going to do this in the normal server as well. */
227   server->global_list->clients = silc_idcache_alloc(0);
228   server->global_list->servers = silc_idcache_alloc(0);
229   server->global_list->channels = silc_idcache_alloc(0);
230
231   /* Allocate the entire socket list that is used in server. Eventually 
232      all connections will have entry in this table (it is a table of 
233      pointers to the actual object that is allocated individually 
234      later). */
235   server->sockets = silc_calloc(SILC_SERVER_MAX_CONNECTIONS,
236                                 sizeof(*server->sockets));
237
238   for (i = 0; i < sock_count; i++) {
239     SilcSocketConnection newsocket = NULL;
240
241     /* Set socket to non-blocking mode */
242     silc_net_set_socket_nonblock(sock[i]);
243     server->sock = sock[i];
244     
245     /* Create a Server ID for the server. */
246     silc_id_create_server_id(sock[i], server->rng, &id);
247     if (!id) {
248       goto err0;
249     }
250     
251     server->id = id;
252     server->id_type = SILC_ID_SERVER;
253     server->server_name = server->config->server_info->server_name;
254
255     /* Add ourselves to the server list. We don't have a router yet 
256        beacuse we haven't established a route yet. It will be done later. 
257        For now, NULL is sent as router. This allocates new entry to
258        the ID list. */
259     id_entry = 
260       silc_idlist_add_server(server->local_list,
261                              server->config->server_info->server_name,
262                              server->server_type, server->id, NULL, NULL);
263     if (!id_entry) {
264       SILC_LOG_ERROR(("Could not add ourselves to cache"));
265       goto err0;
266     }
267     
268     /* Add ourselves also to the socket table. The entry allocated above
269        is sent as argument for fast referencing in the future. */
270     silc_socket_alloc(sock[i], SILC_SOCKET_TYPE_SERVER, id_entry, 
271                       &newsocket);
272     if (!newsocket)
273       goto err0;
274
275     server->sockets[sock[i]] = newsocket;
276
277     /* Put the allocated socket pointer also to the entry allocated above 
278        for fast back-referencing to the socket list. */
279     id_entry->connection = (void *)server->sockets[sock[i]];
280     server->id_entry = id_entry;
281   }
282
283   /* Register the task queues. In SILC we have by default three task queues. 
284      One task queue for non-timeout tasks which perform different kind of 
285      I/O on file descriptors, timeout task queue for timeout tasks, and,
286      generic non-timeout task queue whose tasks apply to all connections. */
287   silc_task_queue_alloc(&server->io_queue, TRUE);
288   if (!server->io_queue) {
289     goto err0;
290   }
291   silc_task_queue_alloc(&server->timeout_queue, TRUE);
292   if (!server->timeout_queue) {
293     goto err1;
294   }
295   silc_task_queue_alloc(&server->generic_queue, TRUE);
296   if (!server->generic_queue) {
297     goto err1;
298   }
299
300   /* Register protocols */
301   silc_server_protocols_register();
302
303   /* Initialize the scheduler */
304   silc_schedule_init(&server->io_queue, &server->timeout_queue, 
305                      &server->generic_queue, 
306                      SILC_SERVER_MAX_CONNECTIONS);
307   
308   /* Add the first task to the queue. This is task that is executed by
309      timeout. It expires as soon as the caller calls silc_server_run. This
310      task performs authentication protocol and key exchange with our
311      primary router. */
312   silc_task_register(server->timeout_queue, sock[0], 
313                      silc_server_connect_to_router,
314                      (void *)server, 0, 1,
315                      SILC_TASK_TIMEOUT,
316                      SILC_TASK_PRI_NORMAL);
317
318   /* Add listener task to the queue. This task receives new connections to the 
319      server. This task remains on the queue until the end of the program. */
320   silc_task_register(server->io_queue, sock[0],
321                      silc_server_accept_new_connection,
322                      (void *)server, 0, 0, 
323                      SILC_TASK_FD,
324                      SILC_TASK_PRI_NORMAL);
325   server->listenning = TRUE;
326
327   /* If server connections has been configured then we must be router as
328      normal server cannot have server connections, only router connections. */
329   if (server->config->servers)
330     server->server_type = SILC_ROUTER;
331
332   SILC_LOG_DEBUG(("Server initialized"));
333
334   /* We are done here, return succesfully */
335   return TRUE;
336
337   silc_task_queue_free(server->timeout_queue);
338  err1:
339   silc_task_queue_free(server->io_queue);
340  err0:
341   for (i = 0; i < sock_count; i++)
342     silc_net_close_server(sock[i]);
343
344   return FALSE;
345 }
346
347 /* Stops the SILC server. This function is used to shutdown the server. 
348    This is usually called after the scheduler has returned. After stopping 
349    the server one should call silc_server_free. */
350
351 void silc_server_stop(SilcServer server)
352 {
353   SILC_LOG_DEBUG(("Stopping server"));
354
355   /* Stop the scheduler, although it might be already stopped. This
356      doesn't hurt anyone. This removes all the tasks and task queues,
357      as well. */
358   silc_schedule_stop();
359   silc_schedule_uninit();
360
361   silc_server_protocols_unregister();
362
363   SILC_LOG_DEBUG(("Server stopped"));
364 }
365
366 /* The heart of the server. This runs the scheduler thus runs the server. */
367
368 void silc_server_run(SilcServer server)
369 {
370   SILC_LOG_DEBUG(("Running server"));
371
372   /* Start the scheduler, the heart of the SILC server. When this returns
373      the program will be terminated. */
374   silc_schedule();
375 }
376
377 /* Timeout callback that will be called to retry connecting to remote
378    router. This is used by both normal and router server. This will wait
379    before retrying the connecting. The timeout is generated by exponential
380    backoff algorithm. */
381
382 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
383 {
384   SilcServerConnection sconn = (SilcServerConnection)context;
385   SilcServer server = sconn->server;
386
387   SILC_LOG_INFO(("Retrying connecting to a router"));
388
389   /* Calculate next timeout */
390   if (sconn->retry_count >= 1) {
391     sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
392     if (sconn->retry_timeout > SILC_SERVER_RETRY_INTERVAL_MAX)
393       sconn->retry_timeout = SILC_SERVER_RETRY_INTERVAL_MAX;
394   } else {
395     sconn->retry_timeout = server->params->retry_interval_min;
396   }
397   sconn->retry_count++;
398   sconn->retry_timeout = sconn->retry_timeout +
399     silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
400
401   /* If we've reached max retry count, give up. */
402   if (sconn->retry_count > server->params->retry_count && 
403       server->params->retry_keep_trying == FALSE) {
404     SILC_LOG_ERROR(("Could not connect to router, giving up"));
405     return;
406   }
407
408   /* Wait one before retrying */
409   silc_task_register(server->timeout_queue, fd, silc_server_connect_router,
410                      context, sconn->retry_timeout, 
411                      server->params->retry_interval_min_usec,
412                      SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
413 }
414
415 /* Generic routine to use connect to a router. */
416
417 SILC_TASK_CALLBACK(silc_server_connect_router)
418 {    
419   SilcServerConnection sconn = (SilcServerConnection)context;
420   SilcServer server = sconn->server;
421   SilcSocketConnection newsocket;
422   SilcProtocol protocol;
423   SilcServerKEInternalContext *proto_ctx;
424   int sock;
425
426   /* Connect to remote host */
427   sock = silc_net_create_connection(sconn->remote_port, 
428                                     sconn->remote_host);
429   if (sock < 0) {
430     SILC_LOG_ERROR(("Could not connect to router"));
431     silc_task_register(server->timeout_queue, fd, 
432                        silc_server_connect_to_router_retry,
433                        context, 0, 1, SILC_TASK_TIMEOUT, 
434                        SILC_TASK_PRI_NORMAL);
435     return;
436   }
437
438   /* Set socket options */
439   silc_net_set_socket_nonblock(sock);
440   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
441
442   /* Create socket connection for the connection. Even though we
443      know that we are connecting to a router we will mark the socket
444      to be unknown connection until we have executed authentication
445      protocol. */
446   silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
447   server->sockets[sock] = newsocket;
448   newsocket->hostname = sconn->remote_host;
449   newsocket->port = sconn->remote_port;
450   sconn->sock = newsocket;
451
452   /* Allocate internal protocol context. This is sent as context
453      to the protocol. */
454   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
455   proto_ctx->server = (void *)server;
456   proto_ctx->context = (void *)sconn;
457   proto_ctx->sock = newsocket;
458   proto_ctx->rng = server->rng;
459   proto_ctx->responder = FALSE;
460       
461   /* Perform key exchange protocol. silc_server_connect_to_router_second
462      will be called after the protocol is finished. */
463   silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE, 
464                       &protocol, proto_ctx,
465                       silc_server_connect_to_router_second);
466   newsocket->protocol = protocol;
467       
468   /* Register a timeout task that will be executed if the protocol
469      is not executed within set limit. */
470   proto_ctx->timeout_task = 
471     silc_task_register(server->timeout_queue, sock, 
472                        silc_server_timeout_remote,
473                        server, server->params->protocol_timeout,
474                        server->params->protocol_timeout_usec,
475                        SILC_TASK_TIMEOUT,
476                        SILC_TASK_PRI_LOW);
477
478   /* Register the connection for network input and output. This sets
479      that scheduler will listen for incoming packets for this connection 
480      and sets that outgoing packets may be sent to this connection as 
481      well. However, this doesn't set the scheduler for outgoing traffic,
482      it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
483      later when outgoing data is available. */
484   context = (void *)server;
485   SILC_REGISTER_CONNECTION_FOR_IO(sock);
486   
487   /* Run the protocol */
488   protocol->execute(server->timeout_queue, 0, protocol, sock, 0, 0);
489 }
490   
491 /* This function connects to our primary router or if we are a router this
492    establishes all our primary routes. This is called at the start of the
493    server to do authentication and key exchange with our router - called
494    from schedule. */
495
496 SILC_TASK_CALLBACK(silc_server_connect_to_router)
497 {
498   SilcServer server = (SilcServer)context;
499   SilcServerConnection sconn;
500
501   SILC_LOG_DEBUG(("Connecting to router(s)"));
502
503   /* If we are normal SILC server we need to connect to our cell's
504      router. */
505   if (server->server_type == SILC_SERVER) {
506     SILC_LOG_DEBUG(("We are normal server"));
507
508     /* Create connection to the router, if configured. */
509     if (server->config->routers) {
510
511       /* Allocate connection object for hold connection specific stuff. */
512       sconn = silc_calloc(1, sizeof(*sconn));
513       sconn->server = server;
514       sconn->remote_host = server->config->routers->host;
515       sconn->remote_port = server->config->routers->port;
516
517       silc_task_register(server->timeout_queue, fd, 
518                          silc_server_connect_router,
519                          (void *)sconn, 0, 1, SILC_TASK_TIMEOUT, 
520                          SILC_TASK_PRI_NORMAL);
521       return;
522     }
523   }
524
525   /* If we are a SILC router we need to establish all of our primary
526      routes. */
527   if (server->server_type == SILC_ROUTER) {
528     SilcConfigServerSectionServerConnection *ptr;
529
530     SILC_LOG_DEBUG(("We are router"));
531
532     /* Create the connections to all our routes */
533     ptr = server->config->routers;
534     while (ptr) {
535
536       SILC_LOG_DEBUG(("Router connection [%s] %s:%d",
537                       ptr->initiator ? "Initiator" : "Responder",
538                       ptr->host, ptr->port));
539
540       if (ptr->initiator) {
541         /* Allocate connection object for hold connection specific stuff. */
542         sconn = silc_calloc(1, sizeof(*sconn));
543         sconn->server = server;
544         sconn->remote_host = ptr->host;
545         sconn->remote_port = ptr->port;
546
547         silc_task_register(server->timeout_queue, fd, 
548                            silc_server_connect_router,
549                            (void *)sconn, 0, 1, SILC_TASK_TIMEOUT, 
550                            SILC_TASK_PRI_NORMAL);
551       }
552
553       if (!ptr->next)
554         return;
555
556       ptr = ptr->next;
557     }
558   }
559
560   SILC_LOG_DEBUG(("No router(s), server will be standalone"));
561   
562   /* There wasn't a configured router, we will continue but we don't
563      have a connection to outside world.  We will be standalone server. */
564   server->standalone = TRUE;
565 }
566
567 /* Second part of connecting to router(s). Key exchange protocol has been
568    executed and now we will execute authentication protocol. */
569
570 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
571 {
572   SilcProtocol protocol = (SilcProtocol)context;
573   SilcServerKEInternalContext *ctx = 
574     (SilcServerKEInternalContext *)protocol->context;
575   SilcServer server = (SilcServer)ctx->server;
576   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
577   SilcSocketConnection sock = NULL;
578   SilcServerConnAuthInternalContext *proto_ctx;
579
580   SILC_LOG_DEBUG(("Start"));
581
582   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
583     /* Error occured during protocol */
584     silc_protocol_free(protocol);
585     if (ctx->packet)
586       silc_packet_context_free(ctx->packet);
587     if (ctx->ske)
588       silc_ske_free(ctx->ske);
589     if (ctx->dest_id)
590       silc_free(ctx->dest_id);
591     silc_free(ctx);
592     sock->protocol = NULL;
593     silc_server_disconnect_remote(server, sock, "Server closed connection: "
594                                   "Key exchange failed");
595     return;
596   }
597   
598   /* Allocate internal context for the authentication protocol. This
599      is sent as context for the protocol. */
600   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
601   proto_ctx->server = (void *)server;
602   proto_ctx->context = (void *)sconn;
603   proto_ctx->sock = sock = server->sockets[fd];
604   proto_ctx->ske = ctx->ske;       /* Save SKE object from previous protocol */
605   proto_ctx->dest_id_type = ctx->dest_id_type;
606   proto_ctx->dest_id = ctx->dest_id;
607
608   /* Resolve the authentication method used in this connection */
609   proto_ctx->auth_meth = SILC_PROTOCOL_CONN_AUTH_PASSWORD;
610   if (server->config->routers) {
611     SilcConfigServerSectionServerConnection *conn = NULL;
612
613     /* Check if we find a match from user configured connections */
614     conn = silc_config_server_find_router_conn(server->config,
615                                                sock->hostname,
616                                                sock->port);
617     if (conn) {
618       /* Match found. Use the configured authentication method */
619       proto_ctx->auth_meth = conn->auth_meth;
620       if (conn->auth_data) {
621         proto_ctx->auth_data = strdup(conn->auth_data);
622         proto_ctx->auth_data_len = strlen(conn->auth_data);
623       }
624     } else {
625       /* No match found. */
626       /* XXX */
627     }
628   } else {
629     /* XXX */
630   }
631
632   /* Free old protocol as it is finished now */
633   silc_protocol_free(protocol);
634   if (ctx->packet)
635     silc_packet_context_free(ctx->packet);
636   silc_free(ctx);
637   sock->protocol = NULL;
638
639   /* Allocate the authentication protocol. This is allocated here
640      but we won't start it yet. We will be receiving party of this
641      protocol thus we will wait that connecting party will make
642      their first move. */
643   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH, 
644                       &sock->protocol, proto_ctx, 
645                       silc_server_connect_to_router_final);
646
647   /* Register timeout task. If the protocol is not executed inside
648      this timelimit the connection will be terminated. Currently
649      this is 15 seconds and is hard coded limit (XXX). */
650   proto_ctx->timeout_task = 
651     silc_task_register(server->timeout_queue, sock->sock, 
652                        silc_server_timeout_remote,
653                        (void *)server, 15, 0,
654                        SILC_TASK_TIMEOUT,
655                        SILC_TASK_PRI_LOW);
656
657   /* Run the protocol */
658   sock->protocol->execute(server->timeout_queue, 0, 
659                           sock->protocol, sock->sock, 0, 0);
660 }
661
662 /* Finalizes the connection to router. Registers a server task to the
663    queue so that we can accept new connections. */
664
665 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
666 {
667   SilcProtocol protocol = (SilcProtocol)context;
668   SilcServerConnAuthInternalContext *ctx = 
669     (SilcServerConnAuthInternalContext *)protocol->context;
670   SilcServer server = (SilcServer)ctx->server;
671   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
672   SilcSocketConnection sock = ctx->sock;
673   SilcServerEntry id_entry;
674   SilcBuffer packet;
675   unsigned char *id_string;
676
677   SILC_LOG_DEBUG(("Start"));
678
679   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
680     /* Error occured during protocol */
681     if (ctx->dest_id)
682       silc_free(ctx->dest_id);
683     silc_server_disconnect_remote(server, sock, "Server closed connection: "
684                                   "Authentication failed");
685     goto out;
686   }
687
688   /* Add a task to the queue. This task receives new connections to the 
689      server. This task remains on the queue until the end of the program. */
690   if (!server->listenning) {
691     silc_task_register(server->io_queue, server->sock, 
692                        silc_server_accept_new_connection,
693                        (void *)server, 0, 0, 
694                        SILC_TASK_FD,
695                        SILC_TASK_PRI_NORMAL);
696     server->listenning = TRUE;
697   }
698
699   /* Send NEW_SERVER packet to the router. We will become registered
700      to the SILC network after sending this packet. */
701   id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
702   packet = silc_buffer_alloc(2 + 2 + SILC_ID_SERVER_LEN + 
703                              strlen(server->server_name));
704   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
705   silc_buffer_format(packet,
706                      SILC_STR_UI_SHORT(SILC_ID_SERVER_LEN),
707                      SILC_STR_UI_XNSTRING(id_string, SILC_ID_SERVER_LEN),
708                      SILC_STR_UI_SHORT(strlen(server->server_name)),
709                      SILC_STR_UI_XNSTRING(server->server_name,
710                                           strlen(server->server_name)),
711                      SILC_STR_END);
712
713   /* Send the packet */
714   silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
715                           packet->data, packet->len, TRUE);
716   silc_buffer_free(packet);
717   silc_free(id_string);
718
719   SILC_LOG_DEBUG(("Connected to router %s", sock->hostname));
720
721   /* Add the connected router to local server list */
722   server->standalone = FALSE;
723   id_entry = silc_idlist_add_server(server->local_list, 
724                                     sock->hostname ? sock->hostname : sock->ip,
725                                     SILC_ROUTER, ctx->dest_id, NULL, sock);
726   if (!id_entry) {
727     if (ctx->dest_id)
728       silc_free(ctx->dest_id);
729     silc_server_disconnect_remote(server, sock, "Server closed connection: "
730                                   "Authentication failed");
731     goto out;
732   }
733
734   silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
735   silc_free(sock->user_data);
736   sock->user_data = (void *)id_entry;
737   sock->type = SILC_SOCKET_TYPE_ROUTER;
738   server->id_entry->router = id_entry;
739   server->router = id_entry;
740
741  out:
742   /* Free the temporary connection data context */
743   if (sconn)
744     silc_free(sconn);
745
746   /* Free the protocol object */
747   silc_protocol_free(protocol);
748   if (ctx->packet)
749     silc_packet_context_free(ctx->packet);
750   if (ctx->ske)
751     silc_ske_free(ctx->ske);
752   silc_free(ctx);
753   sock->protocol = NULL;
754 }
755
756 /* Accepts new connections to the server. Accepting new connections are
757    done in three parts to make it async. */
758
759 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
760 {
761   SilcServer server = (SilcServer)context;
762   SilcSocketConnection newsocket;
763   SilcServerKEInternalContext *proto_ctx;
764   int sock;
765
766   SILC_LOG_DEBUG(("Accepting new connection"));
767
768   sock = silc_net_accept_connection(server->sock);
769   if (sock < 0) {
770     SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
771     return;
772   }
773
774   /* Check max connections */
775   if (sock > SILC_SERVER_MAX_CONNECTIONS) {
776     if (server->config->redirect) {
777       /* XXX Redirecting connection to somewhere else now?? */
778       /*silc_server_send_notify("Server is full, trying to redirect..."); */
779     } else {
780       SILC_LOG_ERROR(("Refusing connection, server is full"));
781     }
782     return;
783   }
784
785   /* Set socket options */
786   silc_net_set_socket_nonblock(sock);
787   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
788
789   /* We don't create a ID yet, since we don't know what type of connection
790      this is yet. But, we do add the connection to the socket table. */
791   silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
792   server->sockets[sock] = newsocket;
793
794   /* XXX This MUST be done async as this will block the entire server
795      process. Either we have to do our own resolver stuff or in the future
796      we can use threads. */
797   /* Perform mandatory name and address lookups for the remote host. */
798   silc_net_check_host_by_sock(sock, &newsocket->hostname, &newsocket->ip);
799   if (!newsocket->ip || !newsocket->hostname) {
800     SILC_LOG_DEBUG(("IP lookup/DNS lookup failed"));
801     SILC_LOG_ERROR(("IP lookup/DNS lookup failed"));
802     return;
803   }
804
805   SILC_LOG_INFO(("Incoming connection from %s (%s)", newsocket->hostname,
806                  newsocket->ip));
807
808   /* Allocate internal context for key exchange protocol. This is
809      sent as context for the protocol. */
810   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
811   proto_ctx->server = context;
812   proto_ctx->sock = newsocket;
813   proto_ctx->rng = server->rng;
814   proto_ctx->responder = TRUE;
815
816   /* Prepare the connection for key exchange protocol. We allocate the
817      protocol but will not start it yet. The connector will be the
818      initiator of the protocol thus we will wait for initiation from 
819      there before we start the protocol. */
820   silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE, 
821                       &newsocket->protocol, proto_ctx, 
822                       silc_server_accept_new_connection_second);
823
824   /* Register a timeout task that will be executed if the connector
825      will not start the key exchange protocol within 60 seconds. For
826      now, this is a hard coded limit. After 60 secs the connection will
827      be closed if the key exchange protocol has not been started. */
828   proto_ctx->timeout_task = 
829     silc_task_register(server->timeout_queue, newsocket->sock, 
830                        silc_server_timeout_remote,
831                        context, 60, 0,
832                        SILC_TASK_TIMEOUT,
833                        SILC_TASK_PRI_LOW);
834
835   /* Register the connection for network input and output. This sets
836      that scheduler will listen for incoming packets for this connection 
837      and sets that outgoing packets may be sent to this connection as well.
838      However, this doesn't set the scheduler for outgoing traffic, it
839      will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
840      later when outgoing data is available. */
841   SILC_REGISTER_CONNECTION_FOR_IO(sock);
842 }
843
844 /* Second part of accepting new connection. Key exchange protocol has been
845    performed and now it is time to do little connection authentication
846    protocol to figure out whether this connection is client or server
847    and whether it has right to access this server (especially server
848    connections needs to be authenticated). */
849
850 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
851 {
852   SilcProtocol protocol = (SilcProtocol)context;
853   SilcServerKEInternalContext *ctx = 
854     (SilcServerKEInternalContext *)protocol->context;
855   SilcServer server = (SilcServer)ctx->server;
856   SilcSocketConnection sock = NULL;
857   SilcServerConnAuthInternalContext *proto_ctx;
858
859   SILC_LOG_DEBUG(("Start"));
860
861   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
862     /* Error occured during protocol */
863     silc_protocol_free(protocol);
864     if (ctx->packet)
865       silc_packet_context_free(ctx->packet);
866     if (ctx->ske)
867       silc_ske_free(ctx->ske);
868     if (ctx->dest_id)
869       silc_free(ctx->dest_id);
870     silc_free(ctx);
871     if (sock)
872       sock->protocol = NULL;
873     silc_server_disconnect_remote(server, sock, "Server closed connection: "
874                                   "Key exchange failed");
875     return;
876   }
877
878   /* Allocate internal context for the authentication protocol. This
879      is sent as context for the protocol. */
880   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
881   proto_ctx->server = (void *)server;
882   proto_ctx->sock = sock = server->sockets[fd];
883   proto_ctx->ske = ctx->ske;    /* Save SKE object from previous protocol */
884   proto_ctx->responder = TRUE;
885   proto_ctx->dest_id_type = ctx->dest_id_type;
886   proto_ctx->dest_id = ctx->dest_id;
887
888   /* Free old protocol as it is finished now */
889   silc_protocol_free(protocol);
890   if (ctx->packet)
891     silc_packet_context_free(ctx->packet);
892   silc_free(ctx);
893   sock->protocol = NULL;
894
895   /* Allocate the authentication protocol. This is allocated here
896      but we won't start it yet. We will be receiving party of this
897      protocol thus we will wait that connecting party will make
898      their first move. */
899   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH, 
900                       &sock->protocol, proto_ctx, 
901                       silc_server_accept_new_connection_final);
902
903   /* Register timeout task. If the protocol is not executed inside
904      this timelimit the connection will be terminated. Currently
905      this is 60 seconds and is hard coded limit (XXX). */
906   proto_ctx->timeout_task = 
907     silc_task_register(server->timeout_queue, sock->sock, 
908                        silc_server_timeout_remote,
909                        (void *)server, 60, 0,
910                        SILC_TASK_TIMEOUT,
911                        SILC_TASK_PRI_LOW);
912 }
913
914 /* Final part of accepting new connection. The connection has now
915    been authenticated and keys has been exchanged. We also know whether
916    this is client or server connection. */
917
918 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
919 {
920   SilcProtocol protocol = (SilcProtocol)context;
921   SilcServerConnAuthInternalContext *ctx = 
922     (SilcServerConnAuthInternalContext *)protocol->context;
923   SilcServer server = (SilcServer)ctx->server;
924   SilcSocketConnection sock = ctx->sock;
925   void *id_entry = NULL;
926
927   SILC_LOG_DEBUG(("Start"));
928
929   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
930     /* Error occured during protocol */
931     silc_protocol_free(protocol);
932     if (ctx->packet)
933       silc_packet_context_free(ctx->packet);
934     if (ctx->ske)
935       silc_ske_free(ctx->ske);
936     if (ctx->dest_id)
937       silc_free(ctx->dest_id);
938     silc_free(ctx);
939     if (sock)
940       sock->protocol = NULL;
941     silc_server_disconnect_remote(server, sock, "Server closed connection: "
942                                   "Authentication failed");
943     return;
944   }
945
946   sock->type = ctx->conn_type;
947   switch(sock->type) {
948   case SILC_SOCKET_TYPE_CLIENT:
949     {
950       SilcClientEntry client;
951
952       SILC_LOG_DEBUG(("Remote host is client"));
953       SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
954                      sock->ip));
955
956       /* Add the client to the client ID cache. The nickname and Client ID
957          and other information is created after we have received NEW_CLIENT
958          packet from client. */
959       client = silc_idlist_add_client(server->local_list, 
960                                       NULL, NULL, NULL, NULL, NULL, sock);
961       if (!client) {
962         SILC_LOG_ERROR(("Could not add new client to cache"));
963         silc_free(sock->user_data);
964         break;
965       }
966
967       id_entry = (void *)client;
968       break;
969     }
970   case SILC_SOCKET_TYPE_SERVER:
971   case SILC_SOCKET_TYPE_ROUTER:
972     {
973       SilcServerEntry new_server;
974
975       SILC_LOG_DEBUG(("Remote host is %s", 
976                       sock->type == SILC_SOCKET_TYPE_SERVER ? 
977                       "server" : "router"));
978       SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
979                      sock->ip, sock->type == SILC_SOCKET_TYPE_SERVER ? 
980                      "server" : "router"));
981
982       /* Add the server into server cache. The server name and Server ID
983          is updated after we have received NEW_SERVER packet from the
984          server. We mark ourselves as router for this server if we really
985          are router. */
986       new_server = 
987         silc_idlist_add_server(server->local_list, NULL,
988                                sock->type == SILC_SOCKET_TYPE_SERVER ?
989                                SILC_SERVER : SILC_ROUTER, NULL, 
990                                sock->type == SILC_SOCKET_TYPE_SERVER ?
991                                server->id_entry : NULL, sock);
992       if (!new_server) {
993         SILC_LOG_ERROR(("Could not add new server to cache"));
994         silc_free(sock->user_data);
995         break;
996       }
997
998       id_entry = (void *)new_server;
999       
1000       /* There is connection to other server now, if it is router then
1001          we will have connection to outside world.  If we are router but
1002          normal server connected to us then we will remain standalone,
1003          if we are standlone. */
1004       if (server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER) {
1005         SILC_LOG_DEBUG(("We are not standalone server anymore"));
1006         server->standalone = FALSE;
1007         if (!server->id_entry->router) {
1008           server->id_entry->router = id_entry;
1009           server->router = id_entry;
1010         }
1011       }
1012       break;
1013     }
1014   default:
1015     break;
1016   }
1017
1018   /* Add the common data structure to the ID entry. */
1019   if (id_entry)
1020     silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1021       
1022   /* Add to sockets internal pointer for fast referencing */
1023   silc_free(sock->user_data);
1024   sock->user_data = id_entry;
1025
1026   /* Connection has been fully established now. Everything is ok. */
1027   SILC_LOG_DEBUG(("New connection authenticated"));
1028
1029   silc_protocol_free(protocol);
1030   if (ctx->packet)
1031     silc_packet_context_free(ctx->packet);
1032   if (ctx->ske)
1033     silc_ske_free(ctx->ske);
1034   if (ctx->dest_id)
1035     silc_free(ctx->dest_id);
1036   silc_free(ctx);
1037   sock->protocol = NULL;
1038 }
1039
1040 /* This function is used to read packets from network and send packets to
1041    network. This is usually a generic task. */
1042
1043 SILC_TASK_CALLBACK(silc_server_packet_process)
1044 {
1045   SilcServer server = (SilcServer)context;
1046   SilcSocketConnection sock = server->sockets[fd];
1047   SilcIDListData idata;
1048   SilcCipher cipher = NULL;
1049   SilcHmac hmac = NULL;
1050   int ret;
1051
1052   SILC_LOG_DEBUG(("Processing packet"));
1053
1054   /* Packet sending */
1055   if (type == SILC_TASK_WRITE) {
1056     SILC_LOG_DEBUG(("Writing data to connection"));
1057
1058     if (sock->outbuf->data - sock->outbuf->head)
1059       silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1060
1061     ret = silc_server_packet_send_real(server, sock, TRUE);
1062
1063     /* If returned -2 could not write to connection now, will do
1064        it later. */
1065     if (ret == -2)
1066       return;
1067     
1068     /* The packet has been sent and now it is time to set the connection
1069        back to only for input. When there is again some outgoing data 
1070        available for this connection it will be set for output as well. 
1071        This call clears the output setting and sets it only for input. */
1072     SILC_SET_CONNECTION_FOR_INPUT(fd);
1073     SILC_UNSET_OUTBUF_PENDING(sock);
1074
1075     silc_buffer_clear(sock->outbuf);
1076     return;
1077   }
1078
1079   /* Packet receiving */
1080   SILC_LOG_DEBUG(("Reading data from connection"));
1081
1082   /* Read some data from connection */
1083   ret = silc_packet_receive(sock);
1084   if (ret < 0)
1085     return;
1086     
1087   /* EOF */
1088   if (ret == 0) {
1089     SILC_LOG_DEBUG(("Read EOF"));
1090       
1091     /* If connection is disconnecting already we will finally
1092        close the connection */
1093     if (SILC_IS_DISCONNECTING(sock)) {
1094       if (sock->user_data)
1095         silc_server_free_sock_user_data(server, sock);
1096       silc_server_close_connection(server, sock);
1097       return;
1098     }
1099       
1100     SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1101
1102     if (sock->user_data)
1103       silc_server_free_sock_user_data(server, sock);
1104     silc_server_close_connection(server, sock);
1105     return;
1106   }
1107
1108   /* If connection is disconnecting or disconnected we will ignore
1109      what we read. */
1110   if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1111     SILC_LOG_DEBUG(("Ignoring read data from invalid connection"));
1112     return;
1113   }
1114
1115   /* Get keys and stuff from ID entry */
1116   idata = (SilcIDListData)sock->user_data;
1117   if (idata) {
1118     idata->last_receive = time(NULL);
1119     cipher = idata->receive_key;
1120     hmac = idata->hmac;
1121   }
1122  
1123   /* Process the packet. This will call the parser that will then
1124      decrypt and parse the packet. */
1125   silc_packet_receive_process(sock, cipher, hmac, silc_server_packet_parse, 
1126                               server);
1127 }
1128
1129 /* Parses whole packet, received earlier. */
1130
1131 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1132 {
1133   SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1134   SilcServer server = (SilcServer)parse_ctx->context;
1135   SilcSocketConnection sock = parse_ctx->sock;
1136   SilcPacketContext *packet = parse_ctx->packet;
1137   SilcBuffer buffer = packet->buffer;
1138   int ret;
1139
1140   SILC_LOG_DEBUG(("Start"));
1141
1142   /* Decrypt the received packet */
1143   ret = silc_packet_decrypt(parse_ctx->cipher, parse_ctx->hmac, 
1144                             buffer, packet);
1145   if (ret < 0)
1146     goto out;
1147
1148   if (ret == 0) {
1149     /* Parse the packet. Packet type is returned. */
1150     ret = silc_packet_parse(packet);
1151   } else {
1152     /* Parse the packet header in special way as this is "special"
1153        packet type. */
1154     ret = silc_packet_parse_special(packet);
1155   }
1156
1157   if (ret == SILC_PACKET_NONE)
1158     goto out;
1159
1160   /* Broadcast packet if it is marked as broadcast packet and it is
1161      originated from router and we are router. */
1162   if (server->server_type == SILC_ROUTER && 
1163       sock->type == SILC_SOCKET_TYPE_ROUTER &&
1164       packet->flags & SILC_PACKET_FLAG_BROADCAST) {
1165     silc_server_packet_broadcast(server, server->router->connection, packet);
1166   }
1167
1168   /* Parse the incoming packet type */
1169   silc_server_packet_parse_type(server, sock, packet);
1170
1171  out:
1172   silc_buffer_clear(sock->inbuf);
1173   silc_packet_context_free(packet);
1174   silc_free(parse_ctx);
1175 }
1176
1177 /* Parser callback called by silc_packet_receive_process. This merely
1178    registers timeout that will handle the actual parsing when appropriate. */
1179
1180 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1181 {
1182   SilcServer server = (SilcServer)parser_context->context;
1183   SilcSocketConnection sock = parser_context->sock;
1184
1185   switch (sock->type) {
1186   case SILC_SOCKET_TYPE_CLIENT:
1187   case SILC_SOCKET_TYPE_UNKNOWN:
1188     /* Parse the packet with timeout */
1189     silc_task_register(server->timeout_queue, sock->sock,
1190                        silc_server_packet_parse_real,
1191                        (void *)parser_context, 0, 100000,
1192                        SILC_TASK_TIMEOUT,
1193                        SILC_TASK_PRI_NORMAL);
1194     break;
1195   case SILC_SOCKET_TYPE_SERVER:
1196   case SILC_SOCKET_TYPE_ROUTER:
1197     /* Packets from servers are parsed as soon as possible */
1198     silc_task_register(server->timeout_queue, sock->sock,
1199                        silc_server_packet_parse_real,
1200                        (void *)parser_context, 0, 1,
1201                        SILC_TASK_TIMEOUT,
1202                        SILC_TASK_PRI_NORMAL);
1203     break;
1204   default:
1205     return;
1206   }
1207 }
1208
1209 /* Parses the packet type and calls what ever routines the packet type
1210    requires. This is done for all incoming packets. */
1211
1212 void silc_server_packet_parse_type(SilcServer server, 
1213                                    SilcSocketConnection sock,
1214                                    SilcPacketContext *packet)
1215 {
1216   SilcPacketType type = packet->type;
1217
1218   SILC_LOG_DEBUG(("Parsing packet type %d", type));
1219
1220   /* Parse the packet type */
1221   switch(type) {
1222   case SILC_PACKET_DISCONNECT:
1223     SILC_LOG_DEBUG(("Disconnect packet"));
1224     break;
1225
1226   case SILC_PACKET_SUCCESS:
1227     /*
1228      * Success received for something. For now we can have only
1229      * one protocol for connection executing at once hence this
1230      * success message is for whatever protocol is executing currently.
1231      */
1232     SILC_LOG_DEBUG(("Success packet"));
1233     if (sock->protocol) {
1234       sock->protocol->execute(server->timeout_queue, 0,
1235                               sock->protocol, sock->sock, 0, 0);
1236     }
1237     break;
1238
1239   case SILC_PACKET_FAILURE:
1240     /*
1241      * Failure received for something. For now we can have only
1242      * one protocol for connection executing at once hence this
1243      * failure message is for whatever protocol is executing currently.
1244      */
1245     SILC_LOG_DEBUG(("Failure packet"));
1246     if (sock->protocol) {
1247       /* XXX Audit the failure type */
1248       sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
1249       sock->protocol->execute(server->timeout_queue, 0,
1250                               sock->protocol, sock->sock, 0, 0);
1251     }
1252     break;
1253
1254   case SILC_PACKET_REJECT:
1255     SILC_LOG_DEBUG(("Reject packet"));
1256     return;
1257     break;
1258
1259   case SILC_PACKET_NOTIFY:
1260     /*
1261      * Received notify packet. Server can receive notify packets from
1262      * router. Server then relays the notify messages to clients if needed.
1263      */
1264     SILC_LOG_DEBUG(("Notify packet"));
1265     silc_server_notify(server, sock, packet);
1266     break;
1267
1268     /* 
1269      * Channel packets
1270      */
1271   case SILC_PACKET_CHANNEL_MESSAGE:
1272     /*
1273      * Received channel message. Channel messages are special packets
1274      * (although probably most common ones) hence they are handled
1275      * specially.
1276      */
1277     SILC_LOG_DEBUG(("Channel Message packet"));
1278     silc_server_channel_message(server, sock, packet);
1279     break;
1280
1281   case SILC_PACKET_CHANNEL_KEY:
1282     /*
1283      * Received key for channel. As channels are created by the router
1284      * the keys are as well. We will distribute the key to all of our
1285      * locally connected clients on the particular channel. Router
1286      * never receives this channel and thus is ignored.
1287      */
1288     SILC_LOG_DEBUG(("Channel Key packet"));
1289     silc_server_channel_key(server, sock, packet);
1290     break;
1291
1292     /*
1293      * Command packets
1294      */
1295   case SILC_PACKET_COMMAND:
1296     /*
1297      * Recived command. Allocate command context and execute the command.
1298      */
1299     SILC_LOG_DEBUG(("Command packet"));
1300     silc_server_command_process(server, sock, packet);
1301     break;
1302
1303   case SILC_PACKET_COMMAND_REPLY:
1304     /*
1305      * Received command reply packet. Servers never send commands thus
1306      * they don't receive command reply packets either, except in cases
1307      * where server has forwarded command packet coming from client. 
1308      * This must be the case here or we will ignore the packet.
1309      */
1310     SILC_LOG_DEBUG(("Command Reply packet"));
1311     silc_server_packet_relay_command_reply(server, sock, packet);
1312     break;
1313
1314     /*
1315      * Private Message packets
1316      */
1317   case SILC_PACKET_PRIVATE_MESSAGE:
1318     /*
1319      * Received private message packet. The packet is coming from either
1320      * client or server.
1321      */
1322     SILC_LOG_DEBUG(("Private Message packet"));
1323     silc_server_private_message(server, sock, packet);
1324     break;
1325
1326   case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1327     /*
1328      * XXX
1329      */
1330     break;
1331
1332     /*
1333      * Key Exchange protocol packets
1334      */
1335   case SILC_PACKET_KEY_EXCHANGE:
1336     SILC_LOG_DEBUG(("KE packet"));
1337     if (sock->protocol && sock->protocol->protocol->type 
1338         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1339
1340       SilcServerKEInternalContext *proto_ctx = 
1341         (SilcServerKEInternalContext *)sock->protocol->context;
1342
1343       proto_ctx->packet = silc_packet_context_dup(packet);
1344
1345       /* Let the protocol handle the packet */
1346       sock->protocol->execute(server->timeout_queue, 0, 
1347                               sock->protocol, sock->sock, 0, 100000);
1348     } else {
1349       SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1350                       "protocol active, packet dropped."));
1351
1352       /* XXX Trigger KE protocol?? Rekey actually, maybe. */
1353     }
1354     break;
1355
1356   case SILC_PACKET_KEY_EXCHANGE_1:
1357     SILC_LOG_DEBUG(("KE 1 packet"));
1358     if (sock->protocol && sock->protocol->protocol->type 
1359         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1360
1361       SilcServerKEInternalContext *proto_ctx = 
1362         (SilcServerKEInternalContext *)sock->protocol->context;
1363
1364       if (proto_ctx->packet)
1365         silc_packet_context_free(proto_ctx->packet);
1366
1367       proto_ctx->packet = silc_packet_context_dup(packet);
1368       proto_ctx->dest_id_type = packet->src_id_type;
1369       proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_type);
1370
1371       /* Let the protocol handle the packet */
1372       sock->protocol->execute(server->timeout_queue, 0, 
1373                               sock->protocol, sock->sock,
1374                               0, 100000);
1375     } else {
1376       SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1377                       "protocol active, packet dropped."));
1378     }
1379     break;
1380
1381   case SILC_PACKET_KEY_EXCHANGE_2:
1382     SILC_LOG_DEBUG(("KE 2 packet"));
1383     if (sock->protocol && sock->protocol->protocol->type 
1384         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1385
1386       SilcServerKEInternalContext *proto_ctx = 
1387         (SilcServerKEInternalContext *)sock->protocol->context;
1388
1389       if (proto_ctx->packet)
1390         silc_packet_context_free(proto_ctx->packet);
1391
1392       proto_ctx->packet = silc_packet_context_dup(packet);
1393       proto_ctx->dest_id_type = packet->src_id_type;
1394       proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_type);
1395
1396       /* Let the protocol handle the packet */
1397       sock->protocol->execute(server->timeout_queue, 0, 
1398                               sock->protocol, sock->sock,
1399                               0, 100000);
1400     } else {
1401       SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1402                       "protocol active, packet dropped."));
1403     }
1404     break;
1405
1406   case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1407     /* If we receive this packet we will send to the other end information
1408        about our mandatory authentication method for the connection. 
1409        This packet maybe received at any time. */
1410     SILC_LOG_DEBUG(("Connection authentication request packet"));
1411     break;
1412
1413     /*
1414      * Connection Authentication protocol packets
1415      */
1416   case SILC_PACKET_CONNECTION_AUTH:
1417     /* Start of the authentication protocol. We receive here the 
1418        authentication data and will verify it. */
1419     SILC_LOG_DEBUG(("Connection auth packet"));
1420     if (sock->protocol && sock->protocol->protocol->type 
1421         == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1422
1423       SilcServerConnAuthInternalContext *proto_ctx = 
1424         (SilcServerConnAuthInternalContext *)sock->protocol->context;
1425
1426       proto_ctx->packet = silc_packet_context_dup(packet);
1427
1428       /* Let the protocol handle the packet */
1429       sock->protocol->execute(server->timeout_queue, 0, 
1430                               sock->protocol, sock->sock, 0, 0);
1431     } else {
1432       SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1433                       "protocol active, packet dropped."));
1434     }
1435     break;
1436
1437   case SILC_PACKET_NEW_ID:
1438     /*
1439      * Received New ID packet. This includes some new ID that has been
1440      * created. It may be for client, server or channel. This is the way
1441      * to distribute information about new registered entities in the
1442      * SILC network.
1443      */
1444     SILC_LOG_DEBUG(("New ID packet"));
1445     silc_server_new_id(server, sock, packet);
1446     break;
1447
1448   case SILC_PACKET_NEW_CLIENT:
1449     /*
1450      * Received new client packet. This includes client information that
1451      * we will use to create initial client ID. After creating new
1452      * ID we will send it to the client.
1453      */
1454     SILC_LOG_DEBUG(("New Client packet"));
1455     silc_server_new_client(server, sock, packet);
1456     break;
1457
1458   case SILC_PACKET_NEW_SERVER:
1459     /*
1460      * Received new server packet. This includes Server ID and some other
1461      * information that we may save. This is received after server has 
1462      * connected to us.
1463      */
1464     SILC_LOG_DEBUG(("New Server packet"));
1465     silc_server_new_server(server, sock, packet);
1466     break;
1467
1468   case SILC_PACKET_NEW_CHANNEL:
1469     /*
1470      * Received new channel packet. Information about new channel in the
1471      * network are distributed using this packet.
1472      */
1473     SILC_LOG_DEBUG(("New Channel packet"));
1474     silc_server_new_channel(server, sock, packet);
1475     break;
1476
1477   case SILC_PACKET_NEW_CHANNEL_USER:
1478     /*
1479      * Received new channel user packet. Information about new users on a
1480      * channel are distributed between routers using this packet.  The
1481      * router receiving this will redistribute it and also sent JOIN notify
1482      * to local clients on the same channel. Normal server sends JOIN notify
1483      * to its local clients on the channel.
1484      */
1485     SILC_LOG_DEBUG(("New Channel User packet"));
1486     silc_server_new_channel_user(server, sock, packet);
1487     break;
1488
1489   case SILC_PACKET_NEW_CHANNEL_LIST:
1490     /*
1491      * List of new channel packets received. This is usually received when
1492      * existing server or router connects to us and distributes information
1493      * of all channels it has.
1494      */
1495     break;
1496
1497   case SILC_PACKET_NEW_CHANNEL_USER_LIST:
1498     /*
1499      * List of new channel user packets received. This is usually received
1500      * when existing server or router connects to us and distributes 
1501      * information of all channel users it has.
1502      */
1503     break;
1504
1505   case SILC_PACKET_REPLACE_ID:
1506     /*
1507      * Received replace ID packet. This sends the old ID that is to be
1508      * replaced with the new one included into the packet. Client must not
1509      * send this packet.
1510      */
1511     SILC_LOG_DEBUG(("Replace ID packet"));
1512     silc_server_replace_id(server, sock, packet);
1513     break;
1514
1515   case SILC_PACKET_REMOVE_ID:
1516     /*
1517      * Received remove ID Packet. 
1518      */
1519     SILC_LOG_DEBUG(("Remove ID packet"));
1520     break;
1521
1522   case SILC_PACKET_REMOVE_CHANNEL_USER:
1523     /*
1524      * Received packet to remove user from a channel. Routers notify other
1525      * routers about a user leaving a channel.
1526      */
1527     SILC_LOG_DEBUG(("Remove Channel User packet"));
1528     silc_server_remove_channel_user(server, sock, packet);
1529     break;
1530
1531   default:
1532     SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
1533     break;
1534   }
1535   
1536 }
1537
1538 /* Closes connection to socket connection */
1539
1540 void silc_server_close_connection(SilcServer server,
1541                                   SilcSocketConnection sock)
1542 {
1543
1544   SILC_LOG_DEBUG(("Closing connection %d", sock->sock));
1545
1546   /* We won't listen for this connection anymore */
1547   silc_schedule_unset_listen_fd(sock->sock);
1548
1549   /* Unregister all tasks */
1550   silc_task_unregister_by_fd(server->io_queue, sock->sock);
1551   silc_task_unregister_by_fd(server->timeout_queue, sock->sock);
1552
1553   /* Close the actual connection */
1554   silc_net_close_connection(sock->sock);
1555   server->sockets[sock->sock] = NULL;
1556   silc_socket_free(sock);
1557 }
1558
1559 /* Sends disconnect message to remote connection and disconnects the 
1560    connection. */
1561
1562 void silc_server_disconnect_remote(SilcServer server,
1563                                    SilcSocketConnection sock,
1564                                    const char *fmt, ...)
1565 {
1566   va_list ap;
1567   unsigned char buf[4096];
1568
1569   memset(buf, 0, sizeof(buf));
1570   va_start(ap, fmt);
1571   vsprintf(buf, fmt, ap);
1572   va_end(ap);
1573
1574   SILC_LOG_DEBUG(("Disconnecting remote host"));
1575
1576   /* Notify remote end that the conversation is over. The notify message
1577      is tried to be sent immediately. */
1578   silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,  
1579                           buf, strlen(buf), TRUE);
1580
1581   /* Mark the connection to be disconnected */
1582   SILC_SET_DISCONNECTED(sock);
1583   silc_server_close_connection(server, sock);
1584 }
1585
1586 /* Free's user_data pointer from socket connection object. As this 
1587    pointer maybe anything we wil switch here to find the correct
1588    data type and free it the way it needs to be free'd. */
1589
1590 void silc_server_free_sock_user_data(SilcServer server, 
1591                                      SilcSocketConnection sock)
1592 {
1593   SILC_LOG_DEBUG(("Start"));
1594
1595   switch(sock->type) {
1596   case SILC_SOCKET_TYPE_CLIENT:
1597     {
1598       SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
1599
1600       /* Remove client from all channels */
1601       silc_server_remove_from_channels(server, sock, user_data);
1602
1603       /* XXX must take some info to history before freeing */
1604
1605       /* Free the client entry and everything in it */
1606       silc_idlist_del_data(user_data);
1607       silc_idlist_del_client(server->local_list, user_data);
1608       break;
1609     }
1610   case SILC_SOCKET_TYPE_SERVER:
1611   case SILC_SOCKET_TYPE_ROUTER:
1612     {
1613
1614       break;
1615     }
1616     break;
1617   default:
1618     {
1619       SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
1620
1621       silc_idlist_del_data(user_data);
1622       silc_free(user_data);
1623       break;
1624     }
1625   }
1626
1627   sock->user_data = NULL;
1628 }
1629
1630 /* Removes client from all channels it has joined. This is used when
1631    client connection is disconnected. If the client on a channel
1632    is last, the channel is removed as well. */
1633
1634 void silc_server_remove_from_channels(SilcServer server, 
1635                                       SilcSocketConnection sock,
1636                                       SilcClientEntry client)
1637 {
1638   SilcChannelEntry channel;
1639   SilcChannelClientEntry chl;
1640   SilcBuffer chidp, clidp;
1641
1642   SILC_LOG_DEBUG(("Start"));
1643
1644   if (!client || !client->id)
1645     return;
1646
1647   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
1648
1649   /* Remove the client from all channels. The client is removed from
1650      the channels' user list. */
1651   silc_list_start(client->channels);
1652   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
1653     channel = chl->channel;
1654     chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
1655
1656     /* Remove from list */
1657     silc_list_del(client->channels, chl);
1658
1659     /* If this client is last one on the channel the channel
1660        is removed all together. */
1661     if (silc_list_count(channel->user_list) < 2) {
1662
1663       /* However, if the channel has marked global users then the 
1664          channel is not created locally, and this does not remove the
1665          channel globally from SILC network, in this case we will
1666          notify that this client has left the channel. */
1667       if (channel->global_users)
1668         silc_server_send_notify_to_channel(server, channel, TRUE,
1669                                            SILC_NOTIFY_TYPE_SIGNOFF, 1,
1670                                            clidp->data, clidp->len);
1671       
1672       silc_idlist_del_channel(server->local_list, channel);
1673       continue;
1674     }
1675
1676     /* Remove from list */
1677     silc_list_del(channel->user_list, chl);
1678     silc_free(chl);
1679
1680     /* Send notify to channel about client leaving SILC and thus
1681        the entire channel. */
1682     silc_server_send_notify_to_channel(server, channel, TRUE,
1683                                        SILC_NOTIFY_TYPE_SIGNOFF, 1,
1684                                        clidp->data, clidp->len);
1685     silc_buffer_free(chidp);
1686   }
1687
1688   silc_buffer_free(clidp);
1689 }
1690
1691 /* Removes client from one channel. This is used for example when client
1692    calls LEAVE command to remove itself from the channel. Returns TRUE
1693    if channel still exists and FALSE if the channel is removed when
1694    last client leaves the channel. If `notify' is FALSE notify messages
1695    are not sent. */
1696
1697 int silc_server_remove_from_one_channel(SilcServer server, 
1698                                         SilcSocketConnection sock,
1699                                         SilcChannelEntry channel,
1700                                         SilcClientEntry client,
1701                                         int notify)
1702 {
1703   SilcChannelEntry ch;
1704   SilcChannelClientEntry chl;
1705   SilcBuffer clidp;
1706
1707   SILC_LOG_DEBUG(("Start"));
1708
1709   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
1710
1711   /* Remove the client from the channel. The client is removed from
1712      the channel's user list. */
1713   silc_list_start(client->channels);
1714   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
1715     if (chl->channel != channel)
1716       continue;
1717
1718     ch = chl->channel;
1719
1720     /* Remove from list */
1721     silc_list_del(client->channels, chl);
1722
1723     /* If this client is last one on the channel the channel
1724        is removed all together. */
1725     if (silc_list_count(channel->user_list) < 2) {
1726       /* Notify about leaving client if this channel has global users,
1727          ie. the channel is not created locally. */
1728       if (notify && channel->global_users)
1729         silc_server_send_notify_to_channel(server, channel, TRUE,
1730                                            SILC_NOTIFY_TYPE_LEAVE, 1,
1731                                            clidp->data, clidp->len);
1732       
1733       silc_idlist_del_channel(server->local_list, channel);
1734       silc_buffer_free(clidp);
1735       return FALSE;
1736     }
1737
1738     /* Remove from list */
1739     silc_list_del(channel->user_list, chl);
1740     silc_free(chl);
1741
1742     /* Send notify to channel about client leaving the channel */
1743     if (notify)
1744       silc_server_send_notify_to_channel(server, channel, TRUE,
1745                                          SILC_NOTIFY_TYPE_LEAVE, 1,
1746                                          clidp->data, clidp->len);
1747     break;
1748   }
1749
1750   silc_buffer_free(clidp);
1751   return TRUE;
1752 }
1753
1754 /* Returns TRUE if the given client is on the channel.  FALSE if not. 
1755    This works because we assure that the user list on the channel is
1756    always in up to date thus we can only check the channel list from 
1757    `client' which is faster than checking the user list from `channel'. */
1758
1759 int silc_server_client_on_channel(SilcClientEntry client,
1760                                   SilcChannelEntry channel)
1761 {
1762   SilcChannelClientEntry chl;
1763
1764   if (!client || !channel)
1765     return FALSE;
1766
1767   silc_list_start(client->channels);
1768   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END)
1769     if (chl->channel == channel)
1770       return TRUE;
1771
1772   return FALSE;
1773 }
1774
1775 /* Timeout callback. This is called if connection is idle or for some
1776    other reason is not responding within some period of time. This 
1777    disconnects the remote end. */
1778
1779 SILC_TASK_CALLBACK(silc_server_timeout_remote)
1780 {
1781   SilcServerConnection sconn = (SilcServerConnection)context;
1782   SilcSocketConnection sock = sconn->server->sockets[fd];
1783
1784   silc_server_disconnect_remote(sconn->server, sock, 
1785                                 "Server closed connection: "
1786                                 "Connection timeout");
1787 }
1788
1789 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
1790    function may be used only by router. In real SILC network all channels
1791    are created by routers thus this function is never used by normal
1792    server. */
1793
1794 SilcChannelEntry silc_server_create_new_channel(SilcServer server, 
1795                                                 SilcServerID *router_id,
1796                                                 char *cipher, 
1797                                                 char *channel_name)
1798 {
1799   SilcChannelID *channel_id;
1800   SilcChannelEntry entry;
1801   SilcCipher key;
1802
1803   SILC_LOG_DEBUG(("Creating new channel"));
1804
1805   if (!cipher)
1806     cipher = "twofish";
1807
1808   /* Allocate cipher */
1809   silc_cipher_alloc(cipher, &key);
1810
1811   channel_name = strdup(channel_name);
1812
1813   /* Create the channel */
1814   silc_id_create_channel_id(router_id, server->rng, &channel_id);
1815   entry = silc_idlist_add_channel(server->local_list, channel_name, 
1816                                   SILC_CHANNEL_MODE_NONE, channel_id, 
1817                                   NULL, key);
1818   if (!entry) {
1819     silc_free(channel_name);
1820     return NULL;
1821   }
1822
1823   /* Now create the actual key material */
1824   silc_server_create_channel_key(server, entry, 16);
1825
1826   /* Notify other routers about the new channel. We send the packet
1827      to our primary route. */
1828   if (server->standalone == FALSE) {
1829     silc_server_send_new_channel(server, server->router->connection, TRUE, 
1830                                  channel_name, entry->id, SILC_ID_CHANNEL_LEN);
1831   }
1832
1833   return entry;
1834 }
1835
1836 /* Generates new channel key. This is used to create the initial channel key
1837    but also to re-generate new key for channel. If `key_len' is provided
1838    it is the bytes of the key length. */
1839
1840 void silc_server_create_channel_key(SilcServer server, 
1841                                     SilcChannelEntry channel,
1842                                     unsigned int key_len)
1843 {
1844   int i;
1845   unsigned char channel_key[32];
1846   unsigned int len;
1847
1848   if (key_len)
1849     len = key_len;
1850   else if (channel->key_len)
1851     len = channel->key_len / 8;
1852   else
1853     len = 32;
1854
1855   /* Create channel key */
1856   for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
1857   
1858   /* Set the key */
1859   channel->channel_key->cipher->set_key(channel->channel_key->context, 
1860                                         channel_key, len);
1861
1862   /* Remove old key if exists */
1863   if (channel->key) {
1864     memset(channel->key, 0, channel->key_len);
1865     silc_free(channel->key);
1866   }
1867
1868   /* Save the key */
1869   channel->key_len = len * 8;
1870   channel->key = silc_calloc(len, sizeof(*channel->key));
1871   memcpy(channel->key, channel_key, len);
1872   memset(channel_key, 0, sizeof(channel_key));
1873 }