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