updates.
[silc.git] / apps / silcd / server.c
1 /*
2
3   server.c
4
5   Author: Pekka Riikonen <priikone@poseidon.pspt.fi>
6
7   Copyright (C) 1997 - 2001 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; either version 2 of the License, or
12   (at your option) any later version.
13   
14   This program is distributed in the hope that it will be useful,
15   but WITHOUT ANY WARRANTY; without even the implied warranty of
16   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   GNU General Public License for more details.
18
19 */
20 /*
21  * This is the actual SILC server than handles everything relating to
22  * servicing the SILC connections. This is also a SILC router as a router 
23  * is also normal server.
24  */
25 /* $Id$ */
26
27 #include "serverincludes.h"
28 #include "server_internal.h"
29
30 /* Static prototypes */
31 SILC_TASK_CALLBACK(silc_server_connect_router);
32 SILC_TASK_CALLBACK(silc_server_connect_to_router);
33 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
35 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
38 SILC_TASK_CALLBACK(silc_server_packet_process);
39 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
40 SILC_TASK_CALLBACK(silc_server_timeout_remote);
41 SILC_TASK_CALLBACK(silc_server_failure_callback);
42
43 /* Allocates a new SILC server object. This has to be done before the server
44    can be used. After allocation one must call silc_server_init to initialize
45    the server. The new allocated server object is returned to the new_server
46    argument. */
47
48 int silc_server_alloc(SilcServer *new_server)
49 {
50   SilcServer server;
51
52   SILC_LOG_DEBUG(("Allocating new server object"));
53
54   server = silc_calloc(1, sizeof(*server));
55   server->server_type = SILC_SERVER;
56   server->standalone = TRUE;
57   server->local_list = silc_calloc(1, sizeof(*server->local_list));
58   server->global_list = silc_calloc(1, sizeof(*server->global_list));
59   server->pending_commands = silc_dlist_init();
60 #ifdef SILC_SIM
61   server->sim = silc_dlist_init();
62 #endif
63
64   *new_server = server;
65
66   return TRUE;
67 }
68
69 /* Free's the SILC server object. This is called at the very end before
70    the program ends. */
71
72 void silc_server_free(SilcServer server)
73 {
74   if (server) {
75 #ifdef SILC_SIM
76     SilcSimContext *sim;
77 #endif
78
79     if (server->local_list)
80       silc_free(server->local_list);
81     if (server->global_list)
82       silc_free(server->global_list);
83     if (server->rng)
84       silc_rng_free(server->rng);
85
86 #ifdef SILC_SIM
87     while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
88       silc_dlist_del(server->sim, sim);
89       silc_sim_free(sim);
90     }
91     silc_dlist_uninit(server->sim);
92 #endif
93
94     if (server->params)
95       silc_free(server->params);
96
97     if (server->pending_commands)
98       silc_dlist_uninit(server->pending_commands);
99
100     silc_free(server);
101   }
102 }
103
104 /* Initializes the entire SILC server. This is called always before running
105    the server. This is called only once at the initialization of the program.
106    This binds the server to its listenning port. After this function returns 
107    one should call silc_server_run to start the server. This returns TRUE 
108    when everything is ok to run the server. Configuration file must be
109    read and parsed before calling this. */
110
111 int silc_server_init(SilcServer server)
112 {
113   int *sock = NULL, sock_count = 0, i;
114   SilcServerID *id;
115   SilcServerEntry id_entry;
116
117   SILC_LOG_DEBUG(("Initializing server"));
118   assert(server);
119   assert(server->config);
120
121   /* XXX After server is made as Silc Server Library this can be given
122      as argument, for now this is hard coded */
123   server->params = silc_calloc(1, sizeof(*server->params));
124   server->params->retry_count = SILC_SERVER_RETRY_COUNT;
125   server->params->retry_interval_min = SILC_SERVER_RETRY_INTERVAL_MIN;
126   server->params->retry_interval_max = SILC_SERVER_RETRY_INTERVAL_MAX;
127   server->params->retry_keep_trying = FALSE;
128   server->params->protocol_timeout = 60;
129   server->params->require_reverse_mapping = FALSE;
130
131   /* Set log files where log message should be saved. */
132   server->config->server = server;
133   silc_server_config_setlogfiles(server->config);
134  
135   /* Register all configured ciphers, PKCS and hash functions. */
136   silc_server_config_register_ciphers(server->config);
137   silc_server_config_register_pkcs(server->config);
138   silc_server_config_register_hashfuncs(server->config);
139   silc_server_config_register_hmacs(server->config);
140
141   /* Initialize random number generator for the server. */
142   server->rng = silc_rng_alloc();
143   silc_rng_init(server->rng);
144   silc_rng_global_init(server->rng);
145
146   /* Initialize hash functions for server to use */
147   silc_hash_alloc("md5", &server->md5hash);
148   silc_hash_alloc("sha1", &server->sha1hash);
149
150   /* Initialize none cipher */
151   silc_cipher_alloc("none", &server->none_cipher);
152
153   /* XXXXX Generate RSA key pair */
154   {
155     unsigned char *public_key;
156     unsigned char *private_key;
157     unsigned int pk_len, prv_len;
158     struct stat st;
159
160     if (stat("pubkey.pub", &st) < 0 && stat("privkey.prv", &st) < 0) {
161
162       if (silc_pkcs_alloc("rsa", &server->pkcs) == FALSE) {
163         SILC_LOG_ERROR(("Could not create RSA key pair"));
164         goto err0;
165       }
166       
167       if (server->pkcs->pkcs->init(server->pkcs->context, 
168                                    1024, server->rng) == FALSE) {
169         SILC_LOG_ERROR(("Could not generate RSA key pair"));
170         goto err0;
171       }
172       
173       public_key = server->pkcs->pkcs->get_public_key(server->pkcs->context,
174                                                       &pk_len);
175       private_key = server->pkcs->pkcs->get_private_key(server->pkcs->context,
176                                                         &prv_len);
177       
178       SILC_LOG_HEXDUMP(("public key"), public_key, pk_len);
179       SILC_LOG_HEXDUMP(("private key"), private_key, prv_len);
180       
181       server->public_key = 
182         silc_pkcs_public_key_alloc("rsa", "UN=root, HN=dummy",
183                                    public_key, pk_len);
184       server->private_key = 
185         silc_pkcs_private_key_alloc("rsa", private_key, prv_len);
186       
187       /* XXX Save keys */
188       silc_pkcs_save_public_key("pubkey.pub", server->public_key,
189                                 SILC_PKCS_FILE_PEM);
190       silc_pkcs_save_private_key("privkey.prv", server->private_key, NULL,
191                                  SILC_PKCS_FILE_BIN);
192
193       memset(public_key, 0, pk_len);
194       memset(private_key, 0, prv_len);
195       silc_free(public_key);
196       silc_free(private_key);
197     } else {
198       silc_pkcs_load_public_key("pubkey.pub", &server->public_key,
199                                 SILC_PKCS_FILE_PEM);
200       silc_pkcs_load_private_key("privkey.prv", &server->private_key,
201                                  SILC_PKCS_FILE_BIN);
202     }
203   }
204
205   /* Create a listening server. Note that our server can listen on
206      multiple ports. All listeners are created here and now. */
207   /* XXX Still check this whether to use server_info or listen_port. */
208   sock_count = 0;
209   while(server->config->listen_port) {
210     int tmp;
211
212     tmp = silc_net_create_server(server->config->listen_port->port,
213                                  server->config->listen_port->host);
214     if (tmp < 0)
215       goto err0;
216
217     sock = silc_realloc(sock, (sizeof(int *) * (sock_count + 1)));
218     sock[sock_count] = tmp;
219     server->config->listen_port = server->config->listen_port->next;
220     sock_count++;
221   }
222
223   /* Initialize ID caches */
224   server->local_list->clients = silc_idcache_alloc(0);
225   server->local_list->servers = silc_idcache_alloc(0);
226   server->local_list->channels = silc_idcache_alloc(0);
227
228   /* These are allocated for normal server as well as these hold some 
229      global information that the server has fetched from its router. For 
230      router these are used as they are supposed to be used on router. */
231   server->global_list->clients = silc_idcache_alloc(0);
232   server->global_list->servers = silc_idcache_alloc(0);
233   server->global_list->channels = silc_idcache_alloc(0);
234
235   /* Allocate the entire socket list that is used in server. Eventually 
236      all connections will have entry in this table (it is a table of 
237      pointers to the actual object that is allocated individually 
238      later). */
239   server->sockets = silc_calloc(SILC_SERVER_MAX_CONNECTIONS,
240                                 sizeof(*server->sockets));
241
242   for (i = 0; i < sock_count; i++) {
243     SilcSocketConnection newsocket = NULL;
244
245     /* Set socket to non-blocking mode */
246     silc_net_set_socket_nonblock(sock[i]);
247     server->sock = sock[i];
248     
249     /* Create a Server ID for the server. */
250     silc_id_create_server_id(sock[i], server->rng, &id);
251     if (!id) {
252       goto err0;
253     }
254     
255     server->id = id;
256     server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
257     server->id_string_len = silc_id_get_len(SILC_ID_SERVER);
258     server->id_type = SILC_ID_SERVER;
259     server->server_name = server->config->server_info->server_name;
260
261     /* Add ourselves to the server list. We don't have a router yet 
262        beacuse we haven't established a route yet. It will be done later. 
263        For now, NULL is sent as router. This allocates new entry to
264        the ID list. */
265     id_entry = 
266       silc_idlist_add_server(server->local_list,
267                              server->config->server_info->server_name,
268                              server->server_type, server->id, NULL, NULL);
269     if (!id_entry) {
270       SILC_LOG_ERROR(("Could not add ourselves to cache"));
271       goto err0;
272     }
273     
274     /* Add ourselves also to the socket table. The entry allocated above
275        is sent as argument for fast referencing in the future. */
276     silc_socket_alloc(sock[i], SILC_SOCKET_TYPE_SERVER, id_entry, 
277                       &newsocket);
278
279     server->sockets[sock[i]] = newsocket;
280
281     /* Put the allocated socket pointer also to the entry allocated above 
282        for fast back-referencing to the socket list. */
283     id_entry->connection = (void *)server->sockets[sock[i]];
284     server->id_entry = id_entry;
285   }
286
287   /* Register the task queues. In SILC we have by default three task queues. 
288      One task queue for non-timeout tasks which perform different kind of 
289      I/O on file descriptors, timeout task queue for timeout tasks, and,
290      generic non-timeout task queue whose tasks apply to all connections. */
291   silc_task_queue_alloc(&server->io_queue, TRUE);
292   if (!server->io_queue) {
293     goto err0;
294   }
295   silc_task_queue_alloc(&server->timeout_queue, TRUE);
296   if (!server->timeout_queue) {
297     goto err1;
298   }
299   silc_task_queue_alloc(&server->generic_queue, TRUE);
300   if (!server->generic_queue) {
301     goto err1;
302   }
303
304   /* Register protocols */
305   silc_server_protocols_register();
306
307   /* Initialize the scheduler */
308   silc_schedule_init(&server->io_queue, &server->timeout_queue, 
309                      &server->generic_queue, 
310                      SILC_SERVER_MAX_CONNECTIONS);
311   
312   /* Add the first task to the queue. This is task that is executed by
313      timeout. It expires as soon as the caller calls silc_server_run. This
314      task performs authentication protocol and key exchange with our
315      primary router. */
316   silc_task_register(server->timeout_queue, sock[0], 
317                      silc_server_connect_to_router,
318                      (void *)server, 0, 1,
319                      SILC_TASK_TIMEOUT,
320                      SILC_TASK_PRI_NORMAL);
321
322   /* Add listener task to the queue. This task receives new connections to the 
323      server. This task remains on the queue until the end of the program. */
324   silc_task_register(server->io_queue, sock[0],
325                      silc_server_accept_new_connection,
326                      (void *)server, 0, 0, 
327                      SILC_TASK_FD,
328                      SILC_TASK_PRI_NORMAL);
329   server->listenning = TRUE;
330
331   /* If server connections has been configured then we must be router as
332      normal server cannot have server connections, only router connections. */
333   if (server->config->servers)
334     server->server_type = SILC_ROUTER;
335
336   SILC_LOG_DEBUG(("Server initialized"));
337
338   /* We are done here, return succesfully */
339   return TRUE;
340
341   silc_task_queue_free(server->timeout_queue);
342  err1:
343   silc_task_queue_free(server->io_queue);
344  err0:
345   for (i = 0; i < sock_count; i++)
346     silc_net_close_server(sock[i]);
347
348   return FALSE;
349 }
350
351 /* Fork server to background and set gid+uid to non-root.
352    Silcd will not run as root, so trying to set either user or group to
353    root will cause silcd to exit. */
354
355 void silc_server_daemonise(SilcServer server)
356 {
357   /* Are we executing silcd as root or a regular user? */
358   if (geteuid()==0) {
359     
360     struct passwd *pw;
361     struct group *gr;
362     char *user, *group;
363     
364     if (!server->config->identity || !server->config->identity->user || 
365         !server->config->identity->group) {
366       fprintf(stderr, "Error:"
367        "\tSILC server must not be run as root.  For the security of your\n"
368        "\tsystem it is strongly suggested that you run SILC under dedicated\n"
369        "\tuser account.  Modify the [Identity] configuration section to run\n"
370        "\tthe server as non-root user.\n");
371       exit(1);
372     }
373     
374     /* Get the values given for user and group in configuration file */
375     user=server->config->identity->user;
376     group=server->config->identity->group;
377     
378     /* Check whether the user/group information is text */ 
379     if (atoi(user)!=0 || atoi(group)!=0) {
380       SILC_LOG_DEBUG(("Invalid user and/or group information"));
381       SILC_LOG_DEBUG(("User and/or group given as number"));
382       fprintf(stderr, "Invalid user and/or group information\n");
383       fprintf(stderr, "Please assign them as names, not numbers\n");
384       exit(1);
385     }
386     
387     /* Catch the nasty incident of string "0" returning 0 from atoi */
388     if (strcmp("0", user)==0 || strcmp("0", group)==0) {
389       SILC_LOG_DEBUG(("User and/or group configured to 0. Unacceptable"));
390       fprintf(stderr, "User and/or group configured to 0. Exiting\n");
391       exit(1);
392     }
393     
394     pw=getpwnam(user);
395     gr=getgrnam(group);
396
397     if (!pw) {
398       fprintf(stderr, "No such user %s found\n", user);
399       exit(1);
400     }
401
402     if (!gr) {
403       fprintf(stderr, "No such group %s found\n", group);
404       exit(1);
405     }
406     
407     /* Check whether user and/or group is set to root. If yes, exit
408        immediately. Otherwise, setgid and setuid server to user.group */
409     if (gr->gr_gid==0 || pw->pw_uid==0) {
410       fprintf(stderr, "Error:"
411        "\tSILC server must not be run as root.  For the security of your\n"
412        "\tsystem it is strongly suggested that you run SILC under dedicated\n"
413        "\tuser account.  Modify the [Identity] configuration section to run\n"
414        "\tthe server as non-root user.\n");
415       exit(1);
416     } else {
417       /* Fork server to background, making it a daemon */
418       if (fork()) {
419         SILC_LOG_DEBUG(("Server started as root. Dropping privileges."));
420         SILC_LOG_DEBUG(("Forking SILC server to background"));
421         exit(0);
422       } 
423       setsid();
424       
425       SILC_LOG_DEBUG(("Changing to group %s", group));
426       if(setgid(gr->gr_gid)==0) {
427         SILC_LOG_DEBUG(("Setgid to %s", group));
428       } else {
429         SILC_LOG_DEBUG(("Setgid to %s failed", group));
430         fprintf(stderr, "Tried to setgid %s but no such group. Exiting\n",
431                 group);
432         exit(1);
433       }
434       SILC_LOG_DEBUG(("Changing to user nobody"));
435       if(setuid(pw->pw_uid)==0) {
436         SILC_LOG_DEBUG(("Setuid to %s", user));
437       } else {
438         SILC_LOG_DEBUG(("Setuid to %s failed", user));
439         fprintf(stderr, "Tried to setuid %s but no such user. Exiting\n",
440                 user);
441         exit(1);
442       }
443     }
444   } else {
445     /* Fork server to background, making it a daemon */
446     if (fork()) {
447       SILC_LOG_DEBUG(("Server started as user")); 
448       SILC_LOG_DEBUG(("Forking SILC server to background"));
449       exit(0);
450     }
451     setsid();
452   }
453 }
454
455 /* Stops the SILC server. This function is used to shutdown the server. 
456    This is usually called after the scheduler has returned. After stopping 
457    the server one should call silc_server_free. */
458
459 void silc_server_stop(SilcServer server)
460 {
461   SILC_LOG_DEBUG(("Stopping server"));
462
463   /* Stop the scheduler, although it might be already stopped. This
464      doesn't hurt anyone. This removes all the tasks and task queues,
465      as well. */
466   silc_schedule_stop();
467   silc_schedule_uninit();
468
469   silc_server_protocols_unregister();
470
471   SILC_LOG_DEBUG(("Server stopped"));
472 }
473
474 /* The heart of the server. This runs the scheduler thus runs the server. 
475    When this returns the server has been stopped and the program will
476    be terminated. */
477
478 void silc_server_run(SilcServer server)
479 {
480   SILC_LOG_DEBUG(("Running server"));
481
482   /* Start the scheduler, the heart of the SILC server. When this returns
483      the program will be terminated. */
484   silc_schedule();
485 }
486
487 /* Timeout callback that will be called to retry connecting to remote
488    router. This is used by both normal and router server. This will wait
489    before retrying the connecting. The timeout is generated by exponential
490    backoff algorithm. */
491
492 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
493 {
494   SilcServerConnection sconn = (SilcServerConnection)context;
495   SilcServer server = sconn->server;
496
497   SILC_LOG_INFO(("Retrying connecting to a router"));
498
499   /* Calculate next timeout */
500   if (sconn->retry_count >= 1) {
501     sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
502     if (sconn->retry_timeout > SILC_SERVER_RETRY_INTERVAL_MAX)
503       sconn->retry_timeout = SILC_SERVER_RETRY_INTERVAL_MAX;
504   } else {
505     sconn->retry_timeout = server->params->retry_interval_min;
506   }
507   sconn->retry_count++;
508   sconn->retry_timeout = sconn->retry_timeout +
509     silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
510
511   /* If we've reached max retry count, give up. */
512   if (sconn->retry_count > server->params->retry_count && 
513       server->params->retry_keep_trying == FALSE) {
514     SILC_LOG_ERROR(("Could not connect to router, giving up"));
515     return;
516   }
517
518   /* Wait one before retrying */
519   silc_task_register(server->timeout_queue, fd, silc_server_connect_router,
520                      context, sconn->retry_timeout, 
521                      server->params->retry_interval_min_usec,
522                      SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
523 }
524
525 /* Generic routine to use connect to a router. */
526
527 SILC_TASK_CALLBACK(silc_server_connect_router)
528 {    
529   SilcServerConnection sconn = (SilcServerConnection)context;
530   SilcServer server = sconn->server;
531   SilcSocketConnection newsocket;
532   SilcProtocol protocol;
533   SilcServerKEInternalContext *proto_ctx;
534   int sock;
535
536   /* Connect to remote host */
537   sock = silc_net_create_connection(sconn->remote_port, 
538                                     sconn->remote_host);
539   if (sock < 0) {
540     SILC_LOG_ERROR(("Could not connect to router"));
541     silc_task_register(server->timeout_queue, fd, 
542                        silc_server_connect_to_router_retry,
543                        context, 0, 1, SILC_TASK_TIMEOUT, 
544                        SILC_TASK_PRI_NORMAL);
545     return;
546   }
547
548   /* Set socket options */
549   silc_net_set_socket_nonblock(sock);
550   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
551
552   /* Create socket connection for the connection. Even though we
553      know that we are connecting to a router we will mark the socket
554      to be unknown connection until we have executed authentication
555      protocol. */
556   silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
557   server->sockets[sock] = newsocket;
558   newsocket->hostname = strdup(sconn->remote_host);
559   newsocket->ip = strdup(sconn->remote_host);
560   newsocket->port = sconn->remote_port;
561   sconn->sock = newsocket;
562
563   /* Allocate internal protocol context. This is sent as context
564      to the protocol. */
565   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
566   proto_ctx->server = (void *)server;
567   proto_ctx->context = (void *)sconn;
568   proto_ctx->sock = newsocket;
569   proto_ctx->rng = server->rng;
570   proto_ctx->responder = FALSE;
571       
572   /* Perform key exchange protocol. silc_server_connect_to_router_second
573      will be called after the protocol is finished. */
574   silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE, 
575                       &protocol, proto_ctx,
576                       silc_server_connect_to_router_second);
577   newsocket->protocol = protocol;
578       
579   /* Register a timeout task that will be executed if the protocol
580      is not executed within set limit. */
581   proto_ctx->timeout_task = 
582     silc_task_register(server->timeout_queue, sock, 
583                        silc_server_timeout_remote,
584                        server, server->params->protocol_timeout,
585                        server->params->protocol_timeout_usec,
586                        SILC_TASK_TIMEOUT,
587                        SILC_TASK_PRI_LOW);
588
589   /* Register the connection for network input and output. This sets
590      that scheduler will listen for incoming packets for this connection 
591      and sets that outgoing packets may be sent to this connection as 
592      well. However, this doesn't set the scheduler for outgoing traffic,
593      it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
594      later when outgoing data is available. */
595   context = (void *)server;
596   SILC_REGISTER_CONNECTION_FOR_IO(sock);
597   
598   /* Run the protocol */
599   protocol->execute(server->timeout_queue, 0, protocol, sock, 0, 0);
600 }
601   
602 /* This function connects to our primary router or if we are a router this
603    establishes all our primary routes. This is called at the start of the
604    server to do authentication and key exchange with our router - called
605    from schedule. */
606
607 SILC_TASK_CALLBACK(silc_server_connect_to_router)
608 {
609   SilcServer server = (SilcServer)context;
610   SilcServerConnection sconn;
611
612   SILC_LOG_DEBUG(("Connecting to router(s)"));
613
614   /* If we are normal SILC server we need to connect to our cell's
615      router. */
616   if (server->server_type == SILC_SERVER) {
617     SILC_LOG_DEBUG(("We are normal server"));
618
619     /* Create connection to the router, if configured. */
620     if (server->config->routers) {
621
622       /* Allocate connection object for hold connection specific stuff. */
623       sconn = silc_calloc(1, sizeof(*sconn));
624       sconn->server = server;
625       sconn->remote_host = strdup(server->config->routers->host);
626       sconn->remote_port = server->config->routers->port;
627
628       silc_task_register(server->timeout_queue, fd, 
629                          silc_server_connect_router,
630                          (void *)sconn, 0, 1, SILC_TASK_TIMEOUT, 
631                          SILC_TASK_PRI_NORMAL);
632       return;
633     }
634   }
635
636   /* If we are a SILC router we need to establish all of our primary
637      routes. */
638   if (server->server_type == SILC_ROUTER) {
639     SilcServerConfigSectionServerConnection *ptr;
640
641     SILC_LOG_DEBUG(("We are router"));
642
643     /* Create the connections to all our routes */
644     ptr = server->config->routers;
645     while (ptr) {
646
647       SILC_LOG_DEBUG(("Router connection [%s] %s:%d",
648                       ptr->initiator ? "Initiator" : "Responder",
649                       ptr->host, ptr->port));
650
651       if (ptr->initiator) {
652         /* Allocate connection object for hold connection specific stuff. */
653         sconn = silc_calloc(1, sizeof(*sconn));
654         sconn->server = server;
655         sconn->remote_host = strdup(ptr->host);
656         sconn->remote_port = ptr->port;
657
658         silc_task_register(server->timeout_queue, fd, 
659                            silc_server_connect_router,
660                            (void *)sconn, 0, 1, SILC_TASK_TIMEOUT, 
661                            SILC_TASK_PRI_NORMAL);
662       }
663
664       if (!ptr->next)
665         return;
666
667       ptr = ptr->next;
668     }
669   }
670
671   SILC_LOG_DEBUG(("No router(s), server will be standalone"));
672   
673   /* There wasn't a configured router, we will continue but we don't
674      have a connection to outside world.  We will be standalone server. */
675   server->standalone = TRUE;
676 }
677
678 /* Second part of connecting to router(s). Key exchange protocol has been
679    executed and now we will execute authentication protocol. */
680
681 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
682 {
683   SilcProtocol protocol = (SilcProtocol)context;
684   SilcServerKEInternalContext *ctx = 
685     (SilcServerKEInternalContext *)protocol->context;
686   SilcServer server = (SilcServer)ctx->server;
687   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
688   SilcSocketConnection sock = NULL;
689   SilcServerConnAuthInternalContext *proto_ctx;
690
691   SILC_LOG_DEBUG(("Start"));
692
693   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
694     /* Error occured during protocol */
695     silc_protocol_free(protocol);
696     silc_ske_free_key_material(ctx->keymat);
697     if (ctx->packet)
698       silc_packet_context_free(ctx->packet);
699     if (ctx->ske)
700       silc_ske_free(ctx->ske);
701     if (ctx->dest_id)
702       silc_free(ctx->dest_id);
703     silc_free(ctx);
704     silc_task_unregister_by_callback(server->timeout_queue,
705                                      silc_server_failure_callback);
706     silc_server_disconnect_remote(server, sock, "Server closed connection: "
707                                   "Key exchange failed");
708     return;
709   }
710   
711   /* We now have the key material as the result of the key exchange
712      protocol. Take the key material into use. Free the raw key material
713      as soon as we've set them into use. */
714   if (!silc_server_protocol_ke_set_keys(ctx->ske, ctx->sock, ctx->keymat,
715                                         ctx->ske->prop->cipher,
716                                         ctx->ske->prop->pkcs,
717                                         ctx->ske->prop->hash,
718                                         ctx->ske->prop->hmac,
719                                         ctx->responder)) {
720     silc_protocol_free(protocol);
721     silc_ske_free_key_material(ctx->keymat);
722     if (ctx->packet)
723       silc_packet_context_free(ctx->packet);
724     if (ctx->ske)
725       silc_ske_free(ctx->ske);
726     if (ctx->dest_id)
727       silc_free(ctx->dest_id);
728     silc_free(ctx);
729     silc_task_unregister_by_callback(server->timeout_queue,
730                                      silc_server_failure_callback);
731     silc_server_disconnect_remote(server, sock, "Server closed connection: "
732                                   "Key exchange failed");
733     return;
734   }    
735   silc_ske_free_key_material(ctx->keymat);
736
737   /* Allocate internal context for the authentication protocol. This
738      is sent as context for the protocol. */
739   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
740   proto_ctx->server = (void *)server;
741   proto_ctx->context = (void *)sconn;
742   proto_ctx->sock = sock = server->sockets[fd];
743   proto_ctx->ske = ctx->ske;       /* Save SKE object from previous protocol */
744   proto_ctx->dest_id_type = ctx->dest_id_type;
745   proto_ctx->dest_id = ctx->dest_id;
746
747   /* Resolve the authentication method used in this connection */
748   proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
749   if (server->config->routers) {
750     SilcServerConfigSectionServerConnection *conn = NULL;
751
752     /* Check if we find a match from user configured connections */
753     conn = silc_server_config_find_router_conn(server->config,
754                                                sock->hostname,
755                                                sock->port);
756     if (conn) {
757       /* Match found. Use the configured authentication method */
758       proto_ctx->auth_meth = conn->auth_meth;
759       if (conn->auth_data) {
760         proto_ctx->auth_data = strdup(conn->auth_data);
761         proto_ctx->auth_data_len = strlen(conn->auth_data);
762       }
763     } else {
764       /* No match found. */
765       /* XXX */
766     }
767   } else {
768     /* XXX */
769   }
770
771   /* Free old protocol as it is finished now */
772   silc_protocol_free(protocol);
773   if (ctx->packet)
774     silc_packet_context_free(ctx->packet);
775   silc_free(ctx);
776   sock->protocol = NULL;
777
778   /* Allocate the authentication protocol. This is allocated here
779      but we won't start it yet. We will be receiving party of this
780      protocol thus we will wait that connecting party will make
781      their first move. */
782   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH, 
783                       &sock->protocol, proto_ctx, 
784                       silc_server_connect_to_router_final);
785
786   /* Register timeout task. If the protocol is not executed inside
787      this timelimit the connection will be terminated. Currently
788      this is 15 seconds and is hard coded limit (XXX). */
789   proto_ctx->timeout_task = 
790     silc_task_register(server->timeout_queue, sock->sock, 
791                        silc_server_timeout_remote,
792                        (void *)server, 15, 0,
793                        SILC_TASK_TIMEOUT,
794                        SILC_TASK_PRI_LOW);
795
796   /* Run the protocol */
797   sock->protocol->execute(server->timeout_queue, 0, 
798                           sock->protocol, sock->sock, 0, 0);
799 }
800
801 /* Finalizes the connection to router. Registers a server task to the
802    queue so that we can accept new connections. */
803
804 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
805 {
806   SilcProtocol protocol = (SilcProtocol)context;
807   SilcServerConnAuthInternalContext *ctx = 
808     (SilcServerConnAuthInternalContext *)protocol->context;
809   SilcServer server = (SilcServer)ctx->server;
810   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
811   SilcSocketConnection sock = ctx->sock;
812   SilcServerEntry id_entry;
813   SilcBuffer packet;
814   SilcServerHBContext hb_context;
815   unsigned char *id_string;
816
817   SILC_LOG_DEBUG(("Start"));
818
819   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
820     /* Error occured during protocol */
821     if (ctx->dest_id)
822       silc_free(ctx->dest_id);
823     silc_server_disconnect_remote(server, sock, "Server closed connection: "
824                                   "Authentication failed");
825     goto out;
826   }
827
828   /* Add a task to the queue. This task receives new connections to the 
829      server. This task remains on the queue until the end of the program. */
830   if (!server->listenning) {
831     silc_task_register(server->io_queue, server->sock, 
832                        silc_server_accept_new_connection,
833                        (void *)server, 0, 0, 
834                        SILC_TASK_FD,
835                        SILC_TASK_PRI_NORMAL);
836     server->listenning = TRUE;
837   }
838
839   /* Send NEW_SERVER packet to the router. We will become registered
840      to the SILC network after sending this packet. */
841   id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
842   packet = silc_buffer_alloc(2 + 2 + SILC_ID_SERVER_LEN + 
843                              strlen(server->server_name));
844   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
845   silc_buffer_format(packet,
846                      SILC_STR_UI_SHORT(SILC_ID_SERVER_LEN),
847                      SILC_STR_UI_XNSTRING(id_string, SILC_ID_SERVER_LEN),
848                      SILC_STR_UI_SHORT(strlen(server->server_name)),
849                      SILC_STR_UI_XNSTRING(server->server_name,
850                                           strlen(server->server_name)),
851                      SILC_STR_END);
852
853   /* Send the packet */
854   silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
855                           packet->data, packet->len, TRUE);
856   silc_buffer_free(packet);
857   silc_free(id_string);
858
859   SILC_LOG_DEBUG(("Connected to router %s", sock->hostname));
860
861   /* Add the connected router to local server list */
862   server->standalone = FALSE;
863   id_entry = silc_idlist_add_server(server->local_list, sock->hostname,
864                                     SILC_ROUTER, ctx->dest_id, NULL, sock);
865   if (!id_entry) {
866     if (ctx->dest_id)
867       silc_free(ctx->dest_id);
868     silc_server_disconnect_remote(server, sock, "Server closed connection: "
869                                   "Authentication failed");
870     goto out;
871   }
872
873   silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
874   silc_free(sock->user_data);
875   sock->user_data = (void *)id_entry;
876   sock->type = SILC_SOCKET_TYPE_ROUTER;
877   server->id_entry->router = id_entry;
878   server->router = id_entry;
879   server->router->data.registered = TRUE;
880
881   /* Perform keepalive. The `hb_context' will be freed automatically
882      when finally calling the silc_socket_free function. XXX hardcoded 
883      timeout!! */
884   hb_context = silc_calloc(1, sizeof(*hb_context));
885   hb_context->server = server;
886   silc_socket_set_heartbeat(sock, 600, hb_context,
887                             silc_server_perform_heartbeat,
888                             server->timeout_queue);
889
890   /* If we are router then announce our possible servers. */
891   if (server->server_type == SILC_ROUTER)
892     silc_server_announce_servers(server);
893
894   /* Announce our clients and channels to the router */
895   silc_server_announce_clients(server);
896   silc_server_announce_channels(server);
897
898  out:
899   /* Free the temporary connection data context */
900   if (sconn) {
901     silc_free(sconn->remote_host);
902     silc_free(sconn);
903   }
904
905   /* Free the protocol object */
906   silc_protocol_free(protocol);
907   if (ctx->packet)
908     silc_packet_context_free(ctx->packet);
909   if (ctx->ske)
910     silc_ske_free(ctx->ske);
911   silc_free(ctx);
912   sock->protocol = NULL;
913 }
914
915 /* Accepts new connections to the server. Accepting new connections are
916    done in three parts to make it async. */
917
918 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
919 {
920   SilcServer server = (SilcServer)context;
921   SilcSocketConnection newsocket;
922   SilcServerKEInternalContext *proto_ctx;
923   int sock;
924
925   SILC_LOG_DEBUG(("Accepting new connection"));
926
927   server->stat.conn_attempts++;
928
929   sock = silc_net_accept_connection(server->sock);
930   if (sock < 0) {
931     SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
932     server->stat.conn_failures++;
933     return;
934   }
935
936   /* Check max connections */
937   if (sock > SILC_SERVER_MAX_CONNECTIONS) {
938     if (server->config->redirect) {
939       /* XXX Redirecting connection to somewhere else now?? */
940       /*silc_server_send_notify("Server is full, trying to redirect..."); */
941     } else {
942       SILC_LOG_ERROR(("Refusing connection, server is full"));
943       server->stat.conn_failures++;
944     }
945     return;
946   }
947
948   /* Set socket options */
949   silc_net_set_socket_nonblock(sock);
950   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
951
952   /* We don't create a ID yet, since we don't know what type of connection
953      this is yet. But, we do add the connection to the socket table. */
954   silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
955   server->sockets[sock] = newsocket;
956
957   /* XXX This MUST be done async as this will block the entire server
958      process. Either we have to do our own resolver stuff or in the future
959      we can use threads. */
960   /* Perform name and address lookups for the remote host. */
961   silc_net_check_host_by_sock(sock, &newsocket->hostname, &newsocket->ip);
962   if ((server->params->require_reverse_mapping && !newsocket->hostname) ||
963       !newsocket->ip) {
964     SILC_LOG_ERROR(("IP/DNS lookup failed"));
965     server->stat.conn_failures++;
966     return;
967   }
968   if (!newsocket->hostname)
969     newsocket->hostname = strdup(newsocket->ip);
970   newsocket->port = silc_net_get_remote_port(sock);
971
972   SILC_LOG_INFO(("Incoming connection from %s (%s)", newsocket->hostname,
973                  newsocket->ip));
974
975   /* Allocate internal context for key exchange protocol. This is
976      sent as context for the protocol. */
977   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
978   proto_ctx->server = context;
979   proto_ctx->sock = newsocket;
980   proto_ctx->rng = server->rng;
981   proto_ctx->responder = TRUE;
982
983   /* Prepare the connection for key exchange protocol. We allocate the
984      protocol but will not start it yet. The connector will be the
985      initiator of the protocol thus we will wait for initiation from 
986      there before we start the protocol. */
987   server->stat.auth_attempts++;
988   silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE, 
989                       &newsocket->protocol, proto_ctx, 
990                       silc_server_accept_new_connection_second);
991
992   /* Register a timeout task that will be executed if the connector
993      will not start the key exchange protocol within 60 seconds. For
994      now, this is a hard coded limit. After 60 secs the connection will
995      be closed if the key exchange protocol has not been started. */
996   proto_ctx->timeout_task = 
997     silc_task_register(server->timeout_queue, newsocket->sock, 
998                        silc_server_timeout_remote,
999                        context, 60, 0,
1000                        SILC_TASK_TIMEOUT,
1001                        SILC_TASK_PRI_LOW);
1002
1003   /* Register the connection for network input and output. This sets
1004      that scheduler will listen for incoming packets for this connection 
1005      and sets that outgoing packets may be sent to this connection as well.
1006      However, this doesn't set the scheduler for outgoing traffic, it
1007      will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1008      later when outgoing data is available. */
1009   SILC_REGISTER_CONNECTION_FOR_IO(sock);
1010 }
1011
1012 /* Second part of accepting new connection. Key exchange protocol has been
1013    performed and now it is time to do little connection authentication
1014    protocol to figure out whether this connection is client or server
1015    and whether it has right to access this server (especially server
1016    connections needs to be authenticated). */
1017
1018 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1019 {
1020   SilcProtocol protocol = (SilcProtocol)context;
1021   SilcServerKEInternalContext *ctx = 
1022     (SilcServerKEInternalContext *)protocol->context;
1023   SilcServer server = (SilcServer)ctx->server;
1024   SilcSocketConnection sock = NULL;
1025   SilcServerConnAuthInternalContext *proto_ctx;
1026
1027   SILC_LOG_DEBUG(("Start"));
1028
1029   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
1030     /* Error occured during protocol */
1031     silc_protocol_free(protocol);
1032     silc_ske_free_key_material(ctx->keymat);
1033     if (ctx->packet)
1034       silc_packet_context_free(ctx->packet);
1035     if (ctx->ske)
1036       silc_ske_free(ctx->ske);
1037     if (ctx->dest_id)
1038       silc_free(ctx->dest_id);
1039     silc_free(ctx);
1040     silc_task_unregister_by_callback(server->timeout_queue,
1041                                      silc_server_failure_callback);
1042     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1043                                   "Key exchange failed");
1044     server->stat.auth_failures++;
1045     return;
1046   }
1047
1048   /* We now have the key material as the result of the key exchange
1049      protocol. Take the key material into use. Free the raw key material
1050      as soon as we've set them into use. */
1051   if (!silc_server_protocol_ke_set_keys(ctx->ske, ctx->sock, ctx->keymat,
1052                                         ctx->ske->prop->cipher,
1053                                         ctx->ske->prop->pkcs,
1054                                         ctx->ske->prop->hash,
1055                                         ctx->ske->prop->hmac,
1056                                         ctx->responder)) {
1057     silc_protocol_free(protocol);
1058     silc_ske_free_key_material(ctx->keymat);
1059     if (ctx->packet)
1060       silc_packet_context_free(ctx->packet);
1061     if (ctx->ske)
1062       silc_ske_free(ctx->ske);
1063     if (ctx->dest_id)
1064       silc_free(ctx->dest_id);
1065     silc_free(ctx);
1066     silc_task_unregister_by_callback(server->timeout_queue,
1067                                      silc_server_failure_callback);
1068     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1069                                   "Key exchange failed");
1070     server->stat.auth_failures++;
1071     return;
1072   }    
1073   silc_ske_free_key_material(ctx->keymat);
1074
1075   /* Allocate internal context for the authentication protocol. This
1076      is sent as context for the protocol. */
1077   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1078   proto_ctx->server = (void *)server;
1079   proto_ctx->sock = sock = server->sockets[fd];
1080   proto_ctx->ske = ctx->ske;    /* Save SKE object from previous protocol */
1081   proto_ctx->responder = TRUE;
1082   proto_ctx->dest_id_type = ctx->dest_id_type;
1083   proto_ctx->dest_id = ctx->dest_id;
1084
1085   /* Free old protocol as it is finished now */
1086   silc_protocol_free(protocol);
1087   if (ctx->packet)
1088     silc_packet_context_free(ctx->packet);
1089   silc_free(ctx);
1090   sock->protocol = NULL;
1091
1092   /* Allocate the authentication protocol. This is allocated here
1093      but we won't start it yet. We will be receiving party of this
1094      protocol thus we will wait that connecting party will make
1095      their first move. */
1096   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH, 
1097                       &sock->protocol, proto_ctx, 
1098                       silc_server_accept_new_connection_final);
1099
1100   /* Register timeout task. If the protocol is not executed inside
1101      this timelimit the connection will be terminated. Currently
1102      this is 60 seconds and is hard coded limit (XXX). */
1103   proto_ctx->timeout_task = 
1104     silc_task_register(server->timeout_queue, sock->sock, 
1105                        silc_server_timeout_remote,
1106                        (void *)server, 60, 0,
1107                        SILC_TASK_TIMEOUT,
1108                        SILC_TASK_PRI_LOW);
1109 }
1110
1111 /* Final part of accepting new connection. The connection has now
1112    been authenticated and keys has been exchanged. We also know whether
1113    this is client or server connection. */
1114
1115 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1116 {
1117   SilcProtocol protocol = (SilcProtocol)context;
1118   SilcServerConnAuthInternalContext *ctx = 
1119     (SilcServerConnAuthInternalContext *)protocol->context;
1120   SilcServer server = (SilcServer)ctx->server;
1121   SilcSocketConnection sock = ctx->sock;
1122   SilcServerHBContext hb_context;
1123   void *id_entry = NULL;
1124
1125   SILC_LOG_DEBUG(("Start"));
1126
1127   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
1128     /* Error occured during protocol */
1129     silc_protocol_free(protocol);
1130     if (ctx->packet)
1131       silc_packet_context_free(ctx->packet);
1132     if (ctx->ske)
1133       silc_ske_free(ctx->ske);
1134     if (ctx->dest_id)
1135       silc_free(ctx->dest_id);
1136     silc_free(ctx);
1137     if (sock)
1138       sock->protocol = NULL;
1139     silc_task_unregister_by_callback(server->timeout_queue,
1140                                      silc_server_failure_callback);
1141     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1142                                   "Authentication failed");
1143     server->stat.auth_failures++;
1144     return;
1145   }
1146
1147   sock->type = ctx->conn_type;
1148   switch(sock->type) {
1149   case SILC_SOCKET_TYPE_CLIENT:
1150     {
1151       SilcClientEntry client;
1152
1153       SILC_LOG_DEBUG(("Remote host is client"));
1154       SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
1155                      sock->ip));
1156
1157       /* Add the client to the client ID cache. The nickname and Client ID
1158          and other information is created after we have received NEW_CLIENT
1159          packet from client. */
1160       client = silc_idlist_add_client(server->local_list, 
1161                                       NULL, NULL, NULL, NULL, NULL, sock);
1162       if (!client) {
1163         SILC_LOG_ERROR(("Could not add new client to cache"));
1164         silc_free(sock->user_data);
1165         break;
1166       }
1167
1168       /* Statistics */
1169       server->stat.my_clients++;
1170       server->stat.clients++;
1171       if (server->server_type == SILC_ROUTER)
1172         server->stat.cell_clients++;
1173
1174       id_entry = (void *)client;
1175       break;
1176     }
1177   case SILC_SOCKET_TYPE_SERVER:
1178   case SILC_SOCKET_TYPE_ROUTER:
1179     {
1180       SilcServerEntry new_server;
1181
1182       SILC_LOG_DEBUG(("Remote host is %s", 
1183                       sock->type == SILC_SOCKET_TYPE_SERVER ? 
1184                       "server" : "router"));
1185       SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
1186                      sock->ip, sock->type == SILC_SOCKET_TYPE_SERVER ? 
1187                      "server" : "router"));
1188
1189       /* Add the server into server cache. The server name and Server ID
1190          is updated after we have received NEW_SERVER packet from the
1191          server. We mark ourselves as router for this server if we really
1192          are router. */
1193       new_server = 
1194         silc_idlist_add_server(server->local_list, NULL,
1195                                sock->type == SILC_SOCKET_TYPE_SERVER ?
1196                                SILC_SERVER : SILC_ROUTER, NULL, 
1197                                sock->type == SILC_SOCKET_TYPE_SERVER ?
1198                                server->id_entry : NULL, sock);
1199       if (!new_server) {
1200         SILC_LOG_ERROR(("Could not add new server to cache"));
1201         silc_free(sock->user_data);
1202         break;
1203       }
1204
1205       /* Statistics */
1206       if (sock->type == SILC_SOCKET_TYPE_SERVER)
1207         server->stat.my_servers++;
1208       else
1209         server->stat.my_routers++;
1210       server->stat.servers++;
1211
1212       id_entry = (void *)new_server;
1213       
1214       /* There is connection to other server now, if it is router then
1215          we will have connection to outside world.  If we are router but
1216          normal server connected to us then we will remain standalone,
1217          if we are standlone. */
1218       if (server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER) {
1219         SILC_LOG_DEBUG(("We are not standalone server anymore"));
1220         server->standalone = FALSE;
1221         if (!server->id_entry->router) {
1222           server->id_entry->router = id_entry;
1223           server->router = id_entry;
1224         }
1225       }
1226       break;
1227     }
1228   default:
1229     break;
1230   }
1231
1232   /* Add the common data structure to the ID entry. */
1233   if (id_entry)
1234     silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1235       
1236   /* Add to sockets internal pointer for fast referencing */
1237   silc_free(sock->user_data);
1238   sock->user_data = id_entry;
1239
1240   /* Connection has been fully established now. Everything is ok. */
1241   SILC_LOG_DEBUG(("New connection authenticated"));
1242
1243   /* Perform keepalive. The `hb_context' will be freed automatically
1244      when finally calling the silc_socket_free function. XXX hardcoded 
1245      timeout!! */
1246   hb_context = silc_calloc(1, sizeof(*hb_context));
1247   hb_context->server = server;
1248   silc_socket_set_heartbeat(sock, 600, hb_context,
1249                             silc_server_perform_heartbeat,
1250                             server->timeout_queue);
1251
1252   silc_task_unregister_by_callback(server->timeout_queue,
1253                                    silc_server_failure_callback);
1254   silc_protocol_free(protocol);
1255   if (ctx->packet)
1256     silc_packet_context_free(ctx->packet);
1257   if (ctx->ske)
1258     silc_ske_free(ctx->ske);
1259   if (ctx->dest_id)
1260     silc_free(ctx->dest_id);
1261   silc_free(ctx);
1262   sock->protocol = NULL;
1263 }
1264
1265 /* This function is used to read packets from network and send packets to
1266    network. This is usually a generic task. */
1267
1268 SILC_TASK_CALLBACK(silc_server_packet_process)
1269 {
1270   SilcServer server = (SilcServer)context;
1271   SilcSocketConnection sock = server->sockets[fd];
1272   SilcIDListData idata;
1273   SilcCipher cipher = NULL;
1274   SilcHmac hmac = NULL;
1275   int ret;
1276
1277   if (!sock)
1278     return;
1279
1280   SILC_LOG_DEBUG(("Processing packet"));
1281
1282   /* Packet sending */
1283
1284   if (type == SILC_TASK_WRITE) {
1285     /* Do not send data to disconnected connection */
1286     if (SILC_IS_DISCONNECTED(sock))
1287       return;
1288
1289     server->stat.packets_sent++;
1290
1291     if (sock->outbuf->data - sock->outbuf->head)
1292       silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1293
1294     ret = silc_server_packet_send_real(server, sock, TRUE);
1295
1296     /* If returned -2 could not write to connection now, will do
1297        it later. */
1298     if (ret == -2)
1299       return;
1300
1301     if (ret == -1)
1302       return;
1303     
1304     /* The packet has been sent and now it is time to set the connection
1305        back to only for input. When there is again some outgoing data 
1306        available for this connection it will be set for output as well. 
1307        This call clears the output setting and sets it only for input. */
1308     SILC_SET_CONNECTION_FOR_INPUT(fd);
1309     SILC_UNSET_OUTBUF_PENDING(sock);
1310
1311     silc_buffer_clear(sock->outbuf);
1312     return;
1313   }
1314
1315   /* Packet receiving */
1316
1317   /* Read some data from connection */
1318   ret = silc_packet_receive(sock);
1319   if (ret < 0)
1320     return;
1321     
1322   /* EOF */
1323   if (ret == 0) {
1324     SILC_LOG_DEBUG(("Read EOF"));
1325       
1326     /* If connection is disconnecting already we will finally
1327        close the connection */
1328     if (SILC_IS_DISCONNECTING(sock)) {
1329       if (sock->user_data)
1330         silc_server_free_sock_user_data(server, sock);
1331       silc_server_close_connection(server, sock);
1332       return;
1333     }
1334       
1335     SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1336     SILC_SET_DISCONNECTING(sock);
1337
1338     /* If the closed connection was our primary router connection the
1339        start re-connecting phase. */
1340     if (!server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER && 
1341         sock == server->router->connection)
1342       silc_task_register(server->timeout_queue, 0, 
1343                          silc_server_connect_to_router,
1344                          context, 1, 0,
1345                          SILC_TASK_TIMEOUT,
1346                          SILC_TASK_PRI_NORMAL);
1347
1348     if (sock->user_data)
1349       silc_server_free_sock_user_data(server, sock);
1350     silc_server_close_connection(server, sock);
1351     return;
1352   }
1353
1354   /* If connection is disconnecting or disconnected we will ignore
1355      what we read. */
1356   if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1357     SILC_LOG_DEBUG(("Ignoring read data from disonnected connection"));
1358     return;
1359   }
1360
1361   server->stat.packets_received++;
1362
1363   /* Get keys and stuff from ID entry */
1364   idata = (SilcIDListData)sock->user_data;
1365   if (idata) {
1366     idata->last_receive = time(NULL);
1367     cipher = idata->receive_key;
1368     hmac = idata->hmac;
1369   }
1370  
1371   /* Process the packet. This will call the parser that will then
1372      decrypt and parse the packet. */
1373   silc_packet_receive_process(sock, cipher, hmac, silc_server_packet_parse, 
1374                               server);
1375 }
1376
1377 /* Callback function that the silc_packet_decrypt will call to make the
1378    decision whether the packet is normal or special packet. We will 
1379    return TRUE if it is normal and FALSE if it is special */
1380
1381 static int silc_server_packet_decrypt_check(SilcPacketType packet_type,
1382                                             SilcBuffer buffer,
1383                                             SilcPacketContext *packet,
1384                                             void *context)
1385 {
1386   SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1387   SilcServer server = (SilcServer)parse_ctx->context;
1388
1389   /* Packet is normal packet, if: 
1390
1391      1) packet is private message packet and does not have private key set
1392      2) is other packet than channel message packet
1393      3) is channel message packet and remote is router and we are router 
1394
1395      all other packets are special packets 
1396   */
1397   if ((packet_type == SILC_PACKET_PRIVATE_MESSAGE &&
1398        !(buffer->data[2] & SILC_PACKET_FLAG_PRIVMSG_KEY)) ||
1399       packet_type != SILC_PACKET_CHANNEL_MESSAGE || 
1400       (packet_type == SILC_PACKET_CHANNEL_MESSAGE &&
1401        parse_ctx->sock->type == SILC_SOCKET_TYPE_ROUTER &&
1402        server->server_type == SILC_ROUTER))
1403     return TRUE;
1404
1405   return FALSE;
1406 }
1407
1408 /* Parses whole packet, received earlier. */
1409
1410 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1411 {
1412   SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1413   SilcServer server = (SilcServer)parse_ctx->context;
1414   SilcSocketConnection sock = parse_ctx->sock;
1415   SilcPacketContext *packet = parse_ctx->packet;
1416   int ret;
1417
1418   SILC_LOG_DEBUG(("Start"));
1419
1420   /* Decrypt the received packet */
1421   ret = silc_packet_decrypt(parse_ctx->cipher, parse_ctx->hmac, 
1422                             packet->buffer, packet,
1423                             silc_server_packet_decrypt_check, parse_ctx);
1424   if (ret < 0)
1425     goto out;
1426
1427   if (ret == 0) {
1428     /* Parse the packet. Packet type is returned. */
1429     ret = silc_packet_parse(packet);
1430   } else {
1431     /* Parse the packet header in special way as this is "special"
1432        packet type. */
1433     ret = silc_packet_parse_special(packet);
1434   }
1435
1436   if (ret == SILC_PACKET_NONE)
1437     goto out;
1438
1439   /* Check that the the current client ID is same as in the client's packet. */
1440   if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1441     SilcClientEntry client = (SilcClientEntry)sock->user_data;
1442     if (client && client->id) {
1443       void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1444                                 packet->src_id_type);
1445       if (SILC_ID_CLIENT_COMPARE(client->id, id)) {
1446         silc_free(id);
1447         goto out;
1448       }
1449       silc_free(id);
1450     }
1451   }
1452
1453   if (server->server_type == SILC_ROUTER) {
1454     /* Route the packet if it is not destined to us. Other ID types but
1455        server are handled separately after processing them. */
1456     if (packet->dst_id_type == SILC_ID_SERVER && 
1457         sock->type != SILC_SOCKET_TYPE_CLIENT &&
1458         SILC_ID_SERVER_COMPARE(packet->dst_id, server->id_string)) {
1459       
1460       /* Route the packet to fastest route for the destination ID */
1461       void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len, 
1462                                 packet->dst_id_type);
1463       if (!id)
1464         goto out;
1465       silc_server_packet_route(server,
1466                                silc_server_route_get(server, id,
1467                                                      packet->dst_id_type),
1468                                packet);
1469       silc_free(id);
1470       goto out;
1471     }
1472     
1473     /* Broadcast packet if it is marked as broadcast packet and it is
1474        originated from router and we are router. */
1475     if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1476         packet->flags & SILC_PACKET_FLAG_BROADCAST) {
1477       silc_server_packet_broadcast(server, server->router->connection, packet);
1478     }
1479   }
1480
1481   /* Parse the incoming packet type */
1482   silc_server_packet_parse_type(server, sock, packet);
1483
1484  out:
1485   silc_buffer_clear(sock->inbuf);
1486   silc_packet_context_free(packet);
1487   silc_free(parse_ctx);
1488 }
1489
1490 /* Parser callback called by silc_packet_receive_process. This merely
1491    registers timeout that will handle the actual parsing when appropriate. */
1492
1493 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1494 {
1495   SilcServer server = (SilcServer)parser_context->context;
1496   SilcSocketConnection sock = parser_context->sock;
1497
1498   switch (sock->type) {
1499   case SILC_SOCKET_TYPE_CLIENT:
1500   case SILC_SOCKET_TYPE_UNKNOWN:
1501     /* Parse the packet with timeout */
1502     silc_task_register(server->timeout_queue, sock->sock,
1503                        silc_server_packet_parse_real,
1504                        (void *)parser_context, 0, 100000,
1505                        SILC_TASK_TIMEOUT,
1506                        SILC_TASK_PRI_NORMAL);
1507     break;
1508   case SILC_SOCKET_TYPE_SERVER:
1509   case SILC_SOCKET_TYPE_ROUTER:
1510     /* Packets from servers are parsed as soon as possible */
1511     silc_task_register(server->timeout_queue, sock->sock,
1512                        silc_server_packet_parse_real,
1513                        (void *)parser_context, 0, 1,
1514                        SILC_TASK_TIMEOUT,
1515                        SILC_TASK_PRI_NORMAL);
1516     break;
1517   default:
1518     return;
1519   }
1520 }
1521
1522 /* Parses the packet type and calls what ever routines the packet type
1523    requires. This is done for all incoming packets. */
1524
1525 void silc_server_packet_parse_type(SilcServer server, 
1526                                    SilcSocketConnection sock,
1527                                    SilcPacketContext *packet)
1528 {
1529   SilcPacketType type = packet->type;
1530
1531   SILC_LOG_DEBUG(("Parsing packet type %d", type));
1532
1533   /* Parse the packet type */
1534   switch(type) {
1535   case SILC_PACKET_DISCONNECT:
1536     SILC_LOG_DEBUG(("Disconnect packet"));
1537     if (packet->flags & SILC_PACKET_FLAG_LIST)
1538       break;
1539     break;
1540
1541   case SILC_PACKET_SUCCESS:
1542     /*
1543      * Success received for something. For now we can have only
1544      * one protocol for connection executing at once hence this
1545      * success message is for whatever protocol is executing currently.
1546      */
1547     SILC_LOG_DEBUG(("Success packet"));
1548     if (packet->flags & SILC_PACKET_FLAG_LIST)
1549       break;
1550     if (sock->protocol) {
1551       sock->protocol->execute(server->timeout_queue, 0,
1552                               sock->protocol, sock->sock, 0, 0);
1553     }
1554     break;
1555
1556   case SILC_PACKET_FAILURE:
1557     /*
1558      * Failure received for something. For now we can have only
1559      * one protocol for connection executing at once hence this
1560      * failure message is for whatever protocol is executing currently.
1561      */
1562     SILC_LOG_DEBUG(("Failure packet"));
1563     if (packet->flags & SILC_PACKET_FLAG_LIST)
1564       break;
1565     if (sock->protocol) {
1566       SilcServerFailureContext f;
1567       f = silc_calloc(1, sizeof(*f));
1568       f->server = server;
1569       f->sock = sock;
1570       
1571       /* We will wait 5 seconds to process this failure packet */
1572       silc_task_register(server->timeout_queue, sock->sock,
1573                          silc_server_failure_callback, (void *)f, 5, 0,
1574                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1575     }
1576     break;
1577
1578   case SILC_PACKET_REJECT:
1579     SILC_LOG_DEBUG(("Reject packet"));
1580     if (packet->flags & SILC_PACKET_FLAG_LIST)
1581       break;
1582     return;
1583     break;
1584
1585   case SILC_PACKET_NOTIFY:
1586     /*
1587      * Received notify packet. Server can receive notify packets from
1588      * router. Server then relays the notify messages to clients if needed.
1589      */
1590     SILC_LOG_DEBUG(("Notify packet"));
1591     if (packet->flags & SILC_PACKET_FLAG_LIST)
1592       silc_server_notify_list(server, sock, packet);
1593     else
1594       silc_server_notify(server, sock, packet);
1595     break;
1596
1597     /* 
1598      * Channel packets
1599      */
1600   case SILC_PACKET_CHANNEL_MESSAGE:
1601     /*
1602      * Received channel message. Channel messages are special packets
1603      * (although probably most common ones) thus they are handled
1604      * specially.
1605      */
1606     SILC_LOG_DEBUG(("Channel Message packet"));
1607     if (packet->flags & SILC_PACKET_FLAG_LIST)
1608       break;
1609     silc_server_channel_message(server, sock, packet);
1610     break;
1611
1612   case SILC_PACKET_CHANNEL_KEY:
1613     /*
1614      * Received key for channel. As channels are created by the router
1615      * the keys are as well. We will distribute the key to all of our
1616      * locally connected clients on the particular channel. Router
1617      * never receives this channel and thus is ignored.
1618      */
1619     SILC_LOG_DEBUG(("Channel Key packet"));
1620     if (packet->flags & SILC_PACKET_FLAG_LIST)
1621       break;
1622     silc_server_channel_key(server, sock, packet);
1623     break;
1624
1625     /*
1626      * Command packets
1627      */
1628   case SILC_PACKET_COMMAND:
1629     /*
1630      * Recived command. Processes the command request and allocates the
1631      * command context and calls the command.
1632      */
1633     SILC_LOG_DEBUG(("Command packet"));
1634     if (packet->flags & SILC_PACKET_FLAG_LIST)
1635       break;
1636     silc_server_command_process(server, sock, packet);
1637     break;
1638
1639   case SILC_PACKET_COMMAND_REPLY:
1640     /*
1641      * Received command reply packet. Received command reply to command. It
1642      * may be reply to command sent by us or reply to command sent by client
1643      * that we've routed further.
1644      */
1645     SILC_LOG_DEBUG(("Command Reply packet"));
1646     if (packet->flags & SILC_PACKET_FLAG_LIST)
1647       break;
1648     silc_server_command_reply(server, sock, packet);
1649     break;
1650
1651     /*
1652      * Private Message packets
1653      */
1654   case SILC_PACKET_PRIVATE_MESSAGE:
1655     /*
1656      * Received private message packet. The packet is coming from either
1657      * client or server.
1658      */
1659     SILC_LOG_DEBUG(("Private Message packet"));
1660     if (packet->flags & SILC_PACKET_FLAG_LIST)
1661       break;
1662     silc_server_private_message(server, sock, packet);
1663     break;
1664
1665   case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1666     /*
1667      * Private message key packet.
1668      */
1669     if (packet->flags & SILC_PACKET_FLAG_LIST)
1670       break;
1671     silc_server_private_message_key(server, sock, packet);
1672     break;
1673
1674     /*
1675      * Key Exchange protocol packets
1676      */
1677   case SILC_PACKET_KEY_EXCHANGE:
1678     SILC_LOG_DEBUG(("KE packet"));
1679     if (packet->flags & SILC_PACKET_FLAG_LIST)
1680       break;
1681
1682     if (sock->protocol && sock->protocol->protocol->type 
1683         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1684
1685       SilcServerKEInternalContext *proto_ctx = 
1686         (SilcServerKEInternalContext *)sock->protocol->context;
1687
1688       proto_ctx->packet = silc_packet_context_dup(packet);
1689
1690       /* Let the protocol handle the packet */
1691       sock->protocol->execute(server->timeout_queue, 0, 
1692                               sock->protocol, sock->sock, 0, 100000);
1693     } else {
1694       SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1695                       "protocol active, packet dropped."));
1696
1697       /* XXX Trigger KE protocol?? Rekey actually, maybe. */
1698     }
1699     break;
1700
1701   case SILC_PACKET_KEY_EXCHANGE_1:
1702     SILC_LOG_DEBUG(("KE 1 packet"));
1703     if (packet->flags & SILC_PACKET_FLAG_LIST)
1704       break;
1705
1706     if (sock->protocol && sock->protocol->protocol->type 
1707         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1708
1709       SilcServerKEInternalContext *proto_ctx = 
1710         (SilcServerKEInternalContext *)sock->protocol->context;
1711
1712       if (proto_ctx->packet)
1713         silc_packet_context_free(proto_ctx->packet);
1714
1715       proto_ctx->packet = silc_packet_context_dup(packet);
1716       proto_ctx->dest_id_type = packet->src_id_type;
1717       proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1718                                           packet->src_id_type);
1719       if (!proto_ctx->dest_id)
1720         break;
1721
1722       /* Let the protocol handle the packet */
1723       sock->protocol->execute(server->timeout_queue, 0, 
1724                               sock->protocol, sock->sock,
1725                               0, 100000);
1726     } else {
1727       SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1728                       "protocol active, packet dropped."));
1729     }
1730     break;
1731
1732   case SILC_PACKET_KEY_EXCHANGE_2:
1733     SILC_LOG_DEBUG(("KE 2 packet"));
1734     if (packet->flags & SILC_PACKET_FLAG_LIST)
1735       break;
1736
1737     if (sock->protocol && sock->protocol->protocol->type 
1738         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1739
1740       SilcServerKEInternalContext *proto_ctx = 
1741         (SilcServerKEInternalContext *)sock->protocol->context;
1742
1743       if (proto_ctx->packet)
1744         silc_packet_context_free(proto_ctx->packet);
1745
1746       proto_ctx->packet = silc_packet_context_dup(packet);
1747       proto_ctx->dest_id_type = packet->src_id_type;
1748       proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1749                                           packet->src_id_type);
1750       if (!proto_ctx->dest_id)
1751         break;
1752
1753       /* Let the protocol handle the packet */
1754       sock->protocol->execute(server->timeout_queue, 0, 
1755                               sock->protocol, sock->sock,
1756                               0, 100000);
1757     } else {
1758       SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1759                       "protocol active, packet dropped."));
1760     }
1761     break;
1762
1763   case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1764     /*
1765      * Connection authentication request packet. When we receive this packet
1766      * we will send to the other end information about our mandatory
1767      * authentication method for the connection. This packet maybe received
1768      * at any time. 
1769      */
1770     SILC_LOG_DEBUG(("Connection authentication request packet"));
1771     if (packet->flags & SILC_PACKET_FLAG_LIST)
1772       break;
1773     break;
1774
1775     /*
1776      * Connection Authentication protocol packets
1777      */
1778   case SILC_PACKET_CONNECTION_AUTH:
1779     /* Start of the authentication protocol. We receive here the 
1780        authentication data and will verify it. */
1781     SILC_LOG_DEBUG(("Connection auth packet"));
1782     if (packet->flags & SILC_PACKET_FLAG_LIST)
1783       break;
1784
1785     if (sock->protocol && sock->protocol->protocol->type 
1786         == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1787
1788       SilcServerConnAuthInternalContext *proto_ctx = 
1789         (SilcServerConnAuthInternalContext *)sock->protocol->context;
1790
1791       proto_ctx->packet = silc_packet_context_dup(packet);
1792
1793       /* Let the protocol handle the packet */
1794       sock->protocol->execute(server->timeout_queue, 0, 
1795                               sock->protocol, sock->sock, 0, 0);
1796     } else {
1797       SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1798                       "protocol active, packet dropped."));
1799     }
1800     break;
1801
1802   case SILC_PACKET_NEW_ID:
1803     /*
1804      * Received New ID packet. This includes some new ID that has been
1805      * created. It may be for client, server or channel. This is the way
1806      * to distribute information about new registered entities in the
1807      * SILC network.
1808      */
1809     SILC_LOG_DEBUG(("New ID packet"));
1810     if (packet->flags & SILC_PACKET_FLAG_LIST)
1811       silc_server_new_id_list(server, sock, packet);
1812     else
1813       silc_server_new_id(server, sock, packet);
1814     break;
1815
1816   case SILC_PACKET_NEW_CLIENT:
1817     /*
1818      * Received new client packet. This includes client information that
1819      * we will use to create initial client ID. After creating new
1820      * ID we will send it to the client.
1821      */
1822     SILC_LOG_DEBUG(("New Client packet"));
1823     if (packet->flags & SILC_PACKET_FLAG_LIST)
1824       break;
1825     silc_server_new_client(server, sock, packet);
1826     break;
1827
1828   case SILC_PACKET_NEW_SERVER:
1829     /*
1830      * Received new server packet. This includes Server ID and some other
1831      * information that we may save. This is received after server has 
1832      * connected to us.
1833      */
1834     SILC_LOG_DEBUG(("New Server packet"));
1835     if (packet->flags & SILC_PACKET_FLAG_LIST)
1836       break;
1837     silc_server_new_server(server, sock, packet);
1838     break;
1839
1840   case SILC_PACKET_NEW_CHANNEL:
1841     /*
1842      * Received new channel packet. Information about new channel in the
1843      * network are distributed using this packet.
1844      */
1845     SILC_LOG_DEBUG(("New Channel packet"));
1846     if (packet->flags & SILC_PACKET_FLAG_LIST)
1847       silc_server_new_channel_list(server, sock, packet);
1848     else
1849       silc_server_new_channel(server, sock, packet);
1850     break;
1851
1852   case SILC_PACKET_HEARTBEAT:
1853     /*
1854      * Received heartbeat.
1855      */
1856     SILC_LOG_DEBUG(("Heartbeat packet"));
1857     if (packet->flags & SILC_PACKET_FLAG_LIST)
1858       break;
1859     break;
1860
1861   case SILC_PACKET_KEY_AGREEMENT:
1862     /*
1863      * Received heartbeat.
1864      */
1865     SILC_LOG_DEBUG(("Key agreement packet"));
1866     if (packet->flags & SILC_PACKET_FLAG_LIST)
1867       break;
1868     silc_server_key_agreement(server, sock, packet);
1869     break;
1870
1871   default:
1872     SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
1873     break;
1874   }
1875   
1876 }
1877
1878 /* Creates connection to a remote router. */
1879
1880 void silc_server_create_connection(SilcServer server,
1881                                    char *remote_host, unsigned int port)
1882 {
1883   SilcServerConnection sconn;
1884
1885   /* Allocate connection object for hold connection specific stuff. */
1886   sconn = silc_calloc(1, sizeof(*sconn));
1887   sconn->server = server;
1888   sconn->remote_host = strdup(remote_host);
1889   sconn->remote_port = port;
1890
1891   silc_task_register(server->timeout_queue, 0, 
1892                      silc_server_connect_router,
1893                      (void *)sconn, 0, 1, SILC_TASK_TIMEOUT, 
1894                      SILC_TASK_PRI_NORMAL);
1895 }
1896
1897 /* Closes connection to socket connection */
1898
1899 void silc_server_close_connection(SilcServer server,
1900                                   SilcSocketConnection sock)
1901 {
1902   SILC_LOG_DEBUG(("Closing connection %d", sock->sock));
1903
1904   /* We won't listen for this connection anymore */
1905   silc_schedule_unset_listen_fd(sock->sock);
1906
1907   /* Unregister all tasks */
1908   silc_task_unregister_by_fd(server->io_queue, sock->sock);
1909   silc_task_unregister_by_fd(server->timeout_queue, sock->sock);
1910
1911   /* Close the actual connection */
1912   silc_net_close_connection(sock->sock);
1913   server->sockets[sock->sock] = NULL;
1914   silc_socket_free(sock);
1915 }
1916
1917 /* Sends disconnect message to remote connection and disconnects the 
1918    connection. */
1919
1920 void silc_server_disconnect_remote(SilcServer server,
1921                                    SilcSocketConnection sock,
1922                                    const char *fmt, ...)
1923 {
1924   va_list ap;
1925   unsigned char buf[4096];
1926
1927   if (!sock)
1928     return;
1929
1930   memset(buf, 0, sizeof(buf));
1931   va_start(ap, fmt);
1932   vsprintf(buf, fmt, ap);
1933   va_end(ap);
1934
1935   SILC_LOG_DEBUG(("Disconnecting remote host"));
1936
1937   SILC_LOG_INFO(("Disconnecting %s:%d [%s]", sock->hostname,
1938                   sock->port,
1939                   (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1940                    sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1941                    sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1942                    "Router")));
1943
1944   /* Notify remote end that the conversation is over. The notify message
1945      is tried to be sent immediately. */
1946   silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,  
1947                           buf, strlen(buf), TRUE);
1948
1949   /* Mark the connection to be disconnected */
1950   SILC_SET_DISCONNECTED(sock);
1951   silc_server_close_connection(server, sock);
1952 }
1953
1954 /* Frees client data and notifies about client's signoff. */
1955
1956 void silc_server_free_client_data(SilcServer server, 
1957                                   SilcSocketConnection sock,
1958                                   SilcClientEntry user_data, char *signoff)
1959 {
1960   /* Send REMOVE_ID packet to routers. */
1961   if (!server->standalone && server->router)
1962     silc_server_send_notify_signoff(server, server->router->connection,
1963                                     server->server_type == SILC_SERVER ?
1964                                     FALSE : TRUE, user_data->id, 
1965                                     SILC_ID_CLIENT_LEN, signoff);
1966
1967   /* Remove client from all channels */
1968   silc_server_remove_from_channels(server, sock, user_data, signoff);
1969
1970   /* XXX must take some info to history before freeing */
1971
1972   /* Free the client entry and everything in it */
1973   silc_idlist_del_data(user_data);
1974   silc_idlist_del_client(server->local_list, user_data);
1975   server->stat.my_clients--;
1976   server->stat.clients--;
1977   if (server->server_type == SILC_ROUTER)
1978     server->stat.cell_clients--;
1979 }
1980
1981 /* Frees user_data pointer from socket connection object. This also sends
1982    appropriate notify packets to the network to inform about leaving
1983    entities. */
1984
1985 void silc_server_free_sock_user_data(SilcServer server, 
1986                                      SilcSocketConnection sock)
1987 {
1988   SILC_LOG_DEBUG(("Start"));
1989
1990   switch(sock->type) {
1991   case SILC_SOCKET_TYPE_CLIENT:
1992     {
1993       SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
1994       silc_server_free_client_data(server, sock, user_data, NULL);
1995       break;
1996     }
1997   case SILC_SOCKET_TYPE_SERVER:
1998   case SILC_SOCKET_TYPE_ROUTER:
1999     {
2000       SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2001
2002       /* Send REMOVE_ID packet to routers. */
2003       if (!server->standalone && server->router)
2004         silc_server_send_notify_server_signoff(server, 
2005                                                server->router->connection,
2006                                                server->server_type == 
2007                                                SILC_SERVER ?
2008                                                FALSE : TRUE, user_data->id, 
2009                                                SILC_ID_SERVER_LEN);
2010
2011       /* Then also free all client entries that this server owns as
2012          they will become invalid now as well. */
2013       silc_server_remove_clients_by_server(server, user_data);
2014
2015       /* If this was our primary router connection then we're lost to
2016          the outside world. */
2017       if (server->router == user_data) {
2018         server->id_entry->router = NULL;
2019         server->router = NULL;
2020         server->standalone = TRUE;
2021       }
2022
2023       /* Free the server entry */
2024       silc_idlist_del_data(user_data);
2025       silc_idlist_del_server(server->local_list, user_data);
2026       server->stat.my_servers--;
2027       server->stat.servers--;
2028       if (server->server_type == SILC_ROUTER)
2029         server->stat.cell_servers--;
2030       break;
2031     }
2032   default:
2033     {
2034       SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2035
2036       silc_idlist_del_data(user_data);
2037       silc_free(user_data);
2038       break;
2039     }
2040   }
2041
2042   sock->user_data = NULL;
2043 }
2044
2045 /* This function is used to remove all client entries by the server `entry'.
2046    This is called when the connection is lost to the server. In this case
2047    we must invalidate all the client entries owned by the server `entry'. */
2048
2049 int silc_server_remove_clients_by_server(SilcServer server, 
2050                                          SilcServerEntry entry)
2051 {
2052   SilcIDCacheList list = NULL;
2053   SilcIDCacheEntry id_cache = NULL;
2054   SilcClientEntry client = NULL;
2055
2056   SILC_LOG_DEBUG(("Start"));
2057
2058   if (silc_idcache_find_by_id(server->local_list->clients, 
2059                               SILC_ID_CACHE_ANY, SILC_ID_CLIENT, &list)) {
2060
2061     if (silc_idcache_list_first(list, &id_cache)) {
2062       while (id_cache) {
2063         client = (SilcClientEntry)id_cache->context;
2064         
2065         if (client->router != entry) {
2066           if (!silc_idcache_list_next(list, &id_cache))
2067             break;
2068           else
2069             continue;
2070         }
2071
2072         /* Remove the client entry */
2073         silc_server_remove_from_channels(server, NULL, client, NULL);
2074         silc_idlist_del_client(server->local_list, client);
2075
2076         if (!silc_idcache_list_next(list, &id_cache))
2077           break;
2078       }
2079     }
2080     silc_idcache_list_free(list);
2081   }
2082   
2083   if (silc_idcache_find_by_id(server->global_list->clients, 
2084                               SILC_ID_CACHE_ANY, SILC_ID_CLIENT, &list)) {
2085
2086     if (silc_idcache_list_first(list, &id_cache)) {
2087       while (id_cache) {
2088         client = (SilcClientEntry)id_cache->context;
2089         
2090         if (client->router != entry) {
2091           if (!silc_idcache_list_next(list, &id_cache))
2092             break;
2093           else
2094             continue;
2095         }
2096
2097         /* Remove the client entry */
2098         silc_server_remove_from_channels(server, NULL, client, NULL);
2099         silc_idlist_del_client(server->global_list, client);
2100
2101         if (!silc_idcache_list_next(list, &id_cache))
2102           break;
2103       }
2104     }
2105     silc_idcache_list_free(list);
2106   }
2107   
2108   return TRUE;
2109 }
2110
2111 /* Checks whether given channel has global users.  If it does this returns
2112    TRUE and FALSE if there is only locally connected clients on the channel. */
2113
2114 int silc_server_channel_has_global(SilcChannelEntry channel)
2115 {
2116   SilcChannelClientEntry chl;
2117
2118   silc_list_start(channel->user_list);
2119   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2120     if (chl->client->router)
2121       return TRUE;
2122   }
2123
2124   return FALSE;
2125 }
2126
2127 /* Checks whether given channel has locally connected users.  If it does this
2128    returns TRUE and FALSE if there is not one locally connected client. */
2129
2130 int silc_server_channel_has_local(SilcChannelEntry channel)
2131 {
2132   SilcChannelClientEntry chl;
2133
2134   silc_list_start(channel->user_list);
2135   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2136     if (!chl->client->router)
2137       return TRUE;
2138   }
2139
2140   return FALSE;
2141 }
2142
2143 /* Removes client from all channels it has joined. This is used when client
2144    connection is disconnected. If the client on a channel is last, the
2145    channel is removed as well. This sends the SIGNOFF notify types. */
2146
2147 void silc_server_remove_from_channels(SilcServer server, 
2148                                       SilcSocketConnection sock,
2149                                       SilcClientEntry client,
2150                                       char *signoff_message)
2151 {
2152   SilcChannelEntry channel;
2153   SilcChannelClientEntry chl;
2154   SilcBuffer clidp;
2155
2156   SILC_LOG_DEBUG(("Start"));
2157
2158   if (!client || !client->id)
2159     return;
2160
2161   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2162
2163   /* Remove the client from all channels. The client is removed from
2164      the channels' user list. */
2165   silc_list_start(client->channels);
2166   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2167     channel = chl->channel;
2168
2169     /* Remove channel from client's channel list */
2170     silc_list_del(client->channels, chl);
2171
2172     /* Remove channel if there is no users anymore */
2173     if (server->server_type == SILC_ROUTER &&
2174         silc_list_count(channel->user_list) < 2) {
2175       if (!silc_idlist_del_channel(server->local_list, channel))
2176         silc_idlist_del_channel(server->global_list, channel);
2177       server->stat.my_channels--;
2178       continue;
2179     }
2180
2181     /* Remove client from channel's client list */
2182     silc_list_del(channel->user_list, chl);
2183     silc_free(chl);
2184     server->stat.my_chanclients--;
2185
2186     /* If there is no global users on the channel anymore mark the channel
2187        as local channel. */
2188     if (server->server_type == SILC_SERVER &&
2189         !silc_server_channel_has_global(channel))
2190       channel->global_users = FALSE;
2191
2192     /* If there is not at least one local user on the channel then we don't
2193        need the channel entry anymore, we can remove it safely. */
2194     if (server->server_type == SILC_SERVER &&
2195         !silc_server_channel_has_local(channel)) {
2196       /* Notify about leaving client if this channel has global users. */
2197       if (channel->global_users)
2198         silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2199                                            SILC_NOTIFY_TYPE_SIGNOFF, 
2200                                            signoff_message ? 2 : 1,
2201                                            clidp->data, clidp->len,
2202                                            signoff_message, signoff_message ?
2203                                            strlen(signoff_message) : 0);
2204
2205       if (!silc_idlist_del_channel(server->local_list, channel))
2206         silc_idlist_del_channel(server->global_list, channel);
2207       server->stat.my_channels--;
2208       continue;
2209     }
2210
2211     /* Send notify to channel about client leaving SILC and thus
2212        the entire channel. */
2213     silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2214                                        SILC_NOTIFY_TYPE_SIGNOFF, 
2215                                        signoff_message ? 2 : 1,
2216                                        clidp->data, clidp->len,
2217                                        signoff_message, signoff_message ?
2218                                        strlen(signoff_message) : 0);
2219   }
2220
2221   silc_buffer_free(clidp);
2222 }
2223
2224 /* Removes client from one channel. This is used for example when client
2225    calls LEAVE command to remove itself from the channel. Returns TRUE
2226    if channel still exists and FALSE if the channel is removed when
2227    last client leaves the channel. If `notify' is FALSE notify messages
2228    are not sent. */
2229
2230 int silc_server_remove_from_one_channel(SilcServer server, 
2231                                         SilcSocketConnection sock,
2232                                         SilcChannelEntry channel,
2233                                         SilcClientEntry client,
2234                                         int notify)
2235 {
2236   SilcChannelEntry ch;
2237   SilcChannelClientEntry chl;
2238   SilcBuffer clidp;
2239
2240   SILC_LOG_DEBUG(("Start"));
2241
2242   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2243
2244   /* Remove the client from the channel. The client is removed from
2245      the channel's user list. */
2246   silc_list_start(client->channels);
2247   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2248     if (chl->channel != channel)
2249       continue;
2250
2251     ch = chl->channel;
2252
2253     /* Remove channel from client's channel list */
2254     silc_list_del(client->channels, chl);
2255
2256     /* Remove channel if there is no users anymore */
2257     if (server->server_type == SILC_ROUTER &&
2258         silc_list_count(channel->user_list) < 2) {
2259       if (!silc_idlist_del_channel(server->local_list, channel))
2260         silc_idlist_del_channel(server->global_list, channel);
2261       silc_buffer_free(clidp);
2262       server->stat.my_channels--;
2263       return FALSE;
2264     }
2265
2266     /* Remove client from channel's client list */
2267     silc_list_del(channel->user_list, chl);
2268     silc_free(chl);
2269     server->stat.my_chanclients--;
2270
2271     /* If there is no global users on the channel anymore mark the channel
2272        as local channel. */
2273     if (server->server_type == SILC_SERVER &&
2274         !silc_server_channel_has_global(channel))
2275       channel->global_users = FALSE;
2276
2277     /* If there is not at least one local user on the channel then we don't
2278        need the channel entry anymore, we can remove it safely. */
2279     if (server->server_type == SILC_SERVER &&
2280         !silc_server_channel_has_local(channel)) {
2281       /* Notify about leaving client if this channel has global users. */
2282       if (notify && channel->global_users)
2283         silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2284                                            SILC_NOTIFY_TYPE_LEAVE, 1,
2285                                            clidp->data, clidp->len);
2286
2287       if (!silc_idlist_del_channel(server->local_list, channel))
2288         silc_idlist_del_channel(server->global_list, channel);
2289       silc_buffer_free(clidp);
2290       server->stat.my_channels--;
2291       return FALSE;
2292     }
2293
2294     /* Send notify to channel about client leaving the channel */
2295     if (notify)
2296       silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2297                                          SILC_NOTIFY_TYPE_LEAVE, 1,
2298                                          clidp->data, clidp->len);
2299     break;
2300   }
2301
2302   silc_buffer_free(clidp);
2303   return TRUE;
2304 }
2305
2306 /* Returns TRUE if the given client is on the channel.  FALSE if not. 
2307    This works because we assure that the user list on the channel is
2308    always in up to date thus we can only check the channel list from 
2309    `client' which is faster than checking the user list from `channel'. */
2310
2311 int silc_server_client_on_channel(SilcClientEntry client,
2312                                   SilcChannelEntry channel)
2313 {
2314   SilcChannelClientEntry chl;
2315
2316   if (!client || !channel)
2317     return FALSE;
2318
2319   silc_list_start(client->channels);
2320   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END)
2321     if (chl->channel == channel)
2322       return TRUE;
2323
2324   return FALSE;
2325 }
2326
2327 /* Timeout callback. This is called if connection is idle or for some
2328    other reason is not responding within some period of time. This 
2329    disconnects the remote end. */
2330
2331 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2332 {
2333   SilcServer server = (SilcServer)context;
2334   SilcSocketConnection sock = server->sockets[fd];
2335
2336   if (!sock)
2337     return;
2338
2339   if (sock->user_data)
2340     silc_server_free_sock_user_data(server, sock);
2341
2342   silc_server_disconnect_remote(server, sock, 
2343                                 "Server closed connection: "
2344                                 "Connection timeout");
2345 }
2346
2347 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2348    function may be used only by router. In real SILC network all channels
2349    are created by routers thus this function is never used by normal
2350    server. */
2351
2352 SilcChannelEntry silc_server_create_new_channel(SilcServer server, 
2353                                                 SilcServerID *router_id,
2354                                                 char *cipher, 
2355                                                 char *hmac,
2356                                                 char *channel_name,
2357                                                 int broadcast)
2358 {
2359   SilcChannelID *channel_id;
2360   SilcChannelEntry entry;
2361   SilcCipher key;
2362   SilcHmac newhmac;
2363
2364   SILC_LOG_DEBUG(("Creating new channel"));
2365
2366   if (!cipher)
2367     cipher = "aes-256-cbc";
2368   if (!hmac)
2369     hmac = "hmac-sha1-96";
2370
2371   /* Allocate cipher */
2372   if (!silc_cipher_alloc(cipher, &key))
2373     return NULL;
2374
2375   /* Allocate hmac */
2376   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2377     silc_cipher_free(key);
2378     return NULL;
2379   }
2380
2381   channel_name = strdup(channel_name);
2382
2383   /* Create the channel */
2384   silc_id_create_channel_id(router_id, server->rng, &channel_id);
2385   entry = silc_idlist_add_channel(server->local_list, channel_name, 
2386                                   SILC_CHANNEL_MODE_NONE, channel_id, 
2387                                   NULL, key, newhmac);
2388   if (!entry) {
2389     silc_free(channel_name);
2390     return NULL;
2391   }
2392
2393   /* Now create the actual key material */
2394   silc_server_create_channel_key(server, entry, 
2395                                  silc_cipher_get_key_len(key) / 8);
2396
2397   /* Notify other routers about the new channel. We send the packet
2398      to our primary route. */
2399   if (broadcast && server->standalone == FALSE) {
2400     silc_server_send_new_channel(server, server->router->connection, TRUE, 
2401                                  channel_name, entry->id, SILC_ID_CHANNEL_LEN);
2402   }
2403
2404   server->stat.my_channels++;
2405
2406   return entry;
2407 }
2408
2409 /* Same as above but creates the channel with Channel ID `channel_id. */
2410
2411 SilcChannelEntry 
2412 silc_server_create_new_channel_with_id(SilcServer server, 
2413                                        char *cipher, 
2414                                        char *hmac,
2415                                        char *channel_name,
2416                                        SilcChannelID *channel_id,
2417                                        int broadcast)
2418 {
2419   SilcChannelEntry entry;
2420   SilcCipher key;
2421   SilcHmac newhmac;
2422
2423   SILC_LOG_DEBUG(("Creating new channel"));
2424
2425   if (!cipher)
2426     cipher = "aes-256-cbc";
2427   if (!hmac)
2428     hmac = "hmac-sha1-96";
2429
2430   /* Allocate cipher */
2431   if (!silc_cipher_alloc(cipher, &key))
2432     return NULL;
2433
2434   /* Allocate hmac */
2435   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2436     silc_cipher_free(key);
2437     return NULL;
2438   }
2439
2440   channel_name = strdup(channel_name);
2441
2442   /* Create the channel */
2443   entry = silc_idlist_add_channel(server->local_list, channel_name, 
2444                                   SILC_CHANNEL_MODE_NONE, channel_id, 
2445                                   NULL, key, newhmac);
2446   if (!entry) {
2447     silc_free(channel_name);
2448     return NULL;
2449   }
2450
2451   /* Now create the actual key material */
2452   silc_server_create_channel_key(server, entry, 
2453                                  silc_cipher_get_key_len(key) / 8);
2454
2455   /* Notify other routers about the new channel. We send the packet
2456      to our primary route. */
2457   if (broadcast && server->standalone == FALSE) {
2458     silc_server_send_new_channel(server, server->router->connection, TRUE, 
2459                                  channel_name, entry->id, SILC_ID_CHANNEL_LEN);
2460   }
2461
2462   server->stat.my_channels++;
2463
2464   return entry;
2465 }
2466
2467 /* Generates new channel key. This is used to create the initial channel key
2468    but also to re-generate new key for channel. If `key_len' is provided
2469    it is the bytes of the key length. */
2470
2471 void silc_server_create_channel_key(SilcServer server, 
2472                                     SilcChannelEntry channel,
2473                                     unsigned int key_len)
2474 {
2475   int i;
2476   unsigned char channel_key[32], hash[32];
2477   unsigned int len;
2478
2479   if (!channel->channel_key)
2480     if (!silc_cipher_alloc("aes-256-cbc", &channel->channel_key))
2481       return;
2482
2483   if (key_len)
2484     len = key_len;
2485   else if (channel->key_len)
2486     len = channel->key_len / 8;
2487   else
2488     len = silc_cipher_get_key_len(channel->channel_key) / 8;
2489
2490   /* Create channel key */
2491   for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
2492   
2493   /* Set the key */
2494   silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
2495
2496   /* Remove old key if exists */
2497   if (channel->key) {
2498     memset(channel->key, 0, channel->key_len / 8);
2499     silc_free(channel->key);
2500   }
2501
2502   /* Save the key */
2503   channel->key_len = len * 8;
2504   channel->key = silc_calloc(len, sizeof(*channel->key));
2505   memcpy(channel->key, channel_key, len);
2506   memset(channel_key, 0, sizeof(channel_key));
2507
2508   /* Generate HMAC key from the channel key data and set it */
2509   if (!channel->hmac)
2510     silc_hmac_alloc("hmac-sha1-96", NULL, &channel->hmac);
2511   silc_hash_make(channel->hmac->hash, channel->key, len, hash);
2512   silc_hmac_set_key(channel->hmac, hash, silc_hash_len(channel->hmac->hash));
2513   memset(hash, 0, sizeof(hash));
2514 }
2515
2516 /* Saves the channel key found in the encoded `key_payload' buffer. This 
2517    function is used when we receive Channel Key Payload and also when we're
2518    processing JOIN command reply. Returns entry to the channel. */
2519
2520 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
2521                                               SilcBuffer key_payload,
2522                                               SilcChannelEntry channel)
2523 {
2524   SilcChannelKeyPayload payload = NULL;
2525   SilcChannelID *id = NULL;
2526   unsigned char *tmp, hash[32];
2527   unsigned int tmp_len;
2528   char *cipher;
2529
2530   /* Decode channel key payload */
2531   payload = silc_channel_key_payload_parse(key_payload);
2532   if (!payload) {
2533     SILC_LOG_ERROR(("Bad channel key payload, dropped"));
2534     channel = NULL;
2535     goto out;
2536   }
2537
2538   /* Get the channel entry */
2539   if (!channel) {
2540
2541     /* Get channel ID */
2542     tmp = silc_channel_key_get_id(payload, &tmp_len);
2543     id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
2544     if (!id) {
2545       channel = NULL;
2546       goto out;
2547     }
2548
2549     channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
2550     if (!channel) {
2551       channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
2552       if (!channel) {
2553         SILC_LOG_ERROR(("Received key for non-existent channel"));
2554         goto out;
2555       }
2556     }
2557   }
2558
2559   tmp = silc_channel_key_get_key(payload, &tmp_len);
2560   if (!tmp) {
2561     channel = NULL;
2562     goto out;
2563   }
2564
2565   cipher = silc_channel_key_get_cipher(payload, NULL);
2566   if (!cipher) {
2567     channel = NULL;
2568     goto out;
2569   }
2570
2571   /* Remove old key if exists */
2572   if (channel->key) {
2573     memset(channel->key, 0, channel->key_len / 8);
2574     silc_free(channel->key);
2575     silc_cipher_free(channel->channel_key);
2576   }
2577
2578   /* Create new cipher */
2579   if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
2580     channel = NULL;
2581     goto out;
2582   }
2583
2584   /* Save the key */
2585   channel->key_len = tmp_len * 8;
2586   channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
2587   memcpy(channel->key, tmp, tmp_len);
2588   silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
2589
2590   /* Generate HMAC key from the channel key data and set it */
2591   if (!channel->hmac)
2592     silc_hmac_alloc("hmac-sha1-96", NULL, &channel->hmac);
2593   silc_hash_make(channel->hmac->hash, tmp, tmp_len, hash);
2594   silc_hmac_set_key(channel->hmac, hash, silc_hash_len(channel->hmac->hash));
2595
2596   memset(hash, 0, sizeof(hash));
2597   memset(tmp, 0, tmp_len);
2598
2599  out:
2600   if (id)
2601     silc_free(id);
2602   if (payload)
2603     silc_channel_key_payload_free(payload);
2604
2605   return channel;
2606 }
2607
2608 /* Heartbeat callback. This function is set as argument for the
2609    silc_socket_set_heartbeat function. The library will call this function
2610    at the set time interval. */
2611
2612 void silc_server_perform_heartbeat(SilcSocketConnection sock,
2613                                    void *hb_context)
2614 {
2615   SilcServerHBContext hb = (SilcServerHBContext)hb_context;
2616
2617   SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname,
2618                   sock->ip));
2619
2620   /* Send the heartbeat */
2621   silc_server_send_heartbeat(hb->server, sock);
2622 }
2623
2624 /* Returns assembled of all servers in the given ID list. The packet's
2625    form is dictated by the New ID payload. */
2626
2627 static void silc_server_announce_get_servers(SilcServer server,
2628                                              SilcIDList id_list,
2629                                              SilcBuffer *servers)
2630 {
2631   SilcIDCacheList list;
2632   SilcIDCacheEntry id_cache;
2633   SilcServerEntry entry;
2634   SilcBuffer idp;
2635
2636   /* Go through all clients in the list */
2637   if (silc_idcache_find_by_id(id_list->clients, SILC_ID_CACHE_ANY, 
2638                               SILC_ID_SERVER, &list)) {
2639     if (silc_idcache_list_first(list, &id_cache)) {
2640       while (id_cache) {
2641         entry = (SilcServerEntry)id_cache->context;
2642
2643         idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
2644
2645         *servers = silc_buffer_realloc(*servers, 
2646                                        (*servers ? 
2647                                         (*servers)->truelen + idp->len : 
2648                                         idp->len));
2649         silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
2650         silc_buffer_put(*servers, idp->data, idp->len);
2651         silc_buffer_pull(*servers, idp->len);
2652         silc_buffer_free(idp);
2653
2654         if (!silc_idcache_list_next(list, &id_cache))
2655           break;
2656       }
2657     }
2658
2659     silc_idcache_list_free(list);
2660   }
2661 }
2662
2663 /* This function is used by router to announce existing servers to our
2664    primary router when we've connected to it. */
2665
2666 void silc_server_announce_servers(SilcServer server)
2667 {
2668   SilcBuffer servers = NULL;
2669
2670   SILC_LOG_DEBUG(("Announcing servers"));
2671
2672   /* Get servers in local list */
2673   silc_server_announce_get_servers(server, server->local_list, &servers);
2674
2675   /* Get servers in global list */
2676   silc_server_announce_get_servers(server, server->global_list, &servers);
2677
2678   if (servers) {
2679     silc_buffer_push(servers, servers->data - servers->head);
2680     SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
2681
2682     /* Send the packet */
2683     silc_server_packet_send(server, server->router->connection,
2684                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
2685                             servers->data, servers->len, TRUE);
2686
2687     silc_buffer_free(servers);
2688   }
2689 }
2690
2691 /* Returns assembled packet of all clients in the given ID list. The
2692    packet's form is dictated by the New ID Payload. */
2693
2694 static void silc_server_announce_get_clients(SilcServer server,
2695                                              SilcIDList id_list,
2696                                              SilcBuffer *clients)
2697 {
2698   SilcIDCacheList list;
2699   SilcIDCacheEntry id_cache;
2700   SilcClientEntry client;
2701   SilcBuffer idp;
2702
2703   /* Go through all clients in the list */
2704   if (silc_idcache_find_by_id(id_list->clients, SILC_ID_CACHE_ANY, 
2705                               SILC_ID_CLIENT, &list)) {
2706     if (silc_idcache_list_first(list, &id_cache)) {
2707       while (id_cache) {
2708         client = (SilcClientEntry)id_cache->context;
2709
2710         idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2711
2712         *clients = silc_buffer_realloc(*clients, 
2713                                        (*clients ? 
2714                                         (*clients)->truelen + idp->len : 
2715                                         idp->len));
2716         silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
2717         silc_buffer_put(*clients, idp->data, idp->len);
2718         silc_buffer_pull(*clients, idp->len);
2719         silc_buffer_free(idp);
2720
2721         if (!silc_idcache_list_next(list, &id_cache))
2722           break;
2723       }
2724     }
2725
2726     silc_idcache_list_free(list);
2727   }
2728 }
2729
2730 /* This function is used to announce our existing clients to our router
2731    when we've connected to it. */
2732
2733 void silc_server_announce_clients(SilcServer server)
2734 {
2735   SilcBuffer clients = NULL;
2736
2737   SILC_LOG_DEBUG(("Announcing clients"));
2738
2739   /* Get clients in local list */
2740   silc_server_announce_get_clients(server, server->local_list,
2741                                    &clients);
2742
2743   /* As router we announce our global list as well */
2744   if (server->server_type == SILC_ROUTER)
2745     silc_server_announce_get_clients(server, server->global_list,
2746                                      &clients);
2747
2748   if (clients) {
2749     silc_buffer_push(clients, clients->data - clients->head);
2750     SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
2751
2752     /* Send the packet */
2753     silc_server_packet_send(server, server->router->connection,
2754                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
2755                             clients->data, clients->len, TRUE);
2756
2757     silc_buffer_free(clients);
2758   }
2759 }
2760
2761 static SilcBuffer 
2762 silc_server_announce_encode_join(unsigned int argc, ...)
2763 {
2764   va_list ap;
2765
2766   va_start(ap, argc);
2767   return silc_notify_payload_encode(SILC_NOTIFY_TYPE_JOIN, argc, ap);
2768 }
2769
2770 /* Returns assembled packets for all channels and users on those channels
2771    from the given ID List. The packets are in the form dictated by the
2772    New Channel and New Channel User payloads. */
2773
2774 static void silc_server_announce_get_channels(SilcServer server,
2775                                               SilcIDList id_list,
2776                                               SilcBuffer *channels,
2777                                               SilcBuffer *channel_users)
2778 {
2779   SilcIDCacheList list;
2780   SilcIDCacheEntry id_cache;
2781   SilcChannelEntry channel;
2782   SilcChannelClientEntry chl;
2783   SilcBuffer chidp;
2784   unsigned char *cid;
2785   unsigned short name_len;
2786   int len;
2787
2788   /* Go through all channels in the list */
2789   if (silc_idcache_find_by_id(id_list->channels, SILC_ID_CACHE_ANY, 
2790                               SILC_ID_CHANNEL, &list)) {
2791     if (silc_idcache_list_first(list, &id_cache)) {
2792       while (id_cache) {
2793         channel = (SilcChannelEntry)id_cache->context;
2794         
2795         cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
2796         name_len = strlen(channel->channel_name);
2797
2798         len = 4 + name_len + SILC_ID_CHANNEL_LEN;
2799         *channels = 
2800           silc_buffer_realloc(*channels, 
2801                               (*channels ? (*channels)->truelen + len : len));
2802         silc_buffer_pull_tail(*channels, 
2803                               ((*channels)->end - (*channels)->data));
2804         silc_buffer_format(*channels,
2805                            SILC_STR_UI_SHORT(name_len),
2806                            SILC_STR_UI_XNSTRING(channel->channel_name, 
2807                                                 name_len),
2808                            SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
2809                            SILC_STR_UI_XNSTRING(cid, SILC_ID_CHANNEL_LEN),
2810                            SILC_STR_END);
2811         silc_buffer_pull(*channels, len);
2812
2813         /* Now find all users on the channel */
2814         chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
2815         silc_list_start(channel->user_list);
2816         while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2817           SilcBuffer clidp;
2818           SilcBuffer tmp;
2819
2820           clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
2821
2822           tmp = silc_server_announce_encode_join(2, clidp->data, clidp->len,
2823                                                  chidp->data, chidp->len);
2824           len = tmp->len;
2825           *channel_users = 
2826             silc_buffer_realloc(*channel_users, 
2827                                 (*channel_users ? 
2828                                  (*channel_users)->truelen + len : len));
2829           silc_buffer_pull_tail(*channel_users, 
2830                                 ((*channel_users)->end - 
2831                                  (*channel_users)->data));
2832
2833           silc_buffer_put(*channel_users, tmp->data, tmp->len);
2834           silc_buffer_pull(*channel_users, len);
2835           silc_buffer_free(clidp);
2836           silc_buffer_free(tmp);
2837         }
2838         silc_buffer_free(chidp);
2839
2840         silc_free(cid);
2841
2842         if (!silc_idcache_list_next(list, &id_cache))
2843           break;
2844       }
2845     }
2846
2847     silc_idcache_list_free(list);
2848   }
2849 }
2850
2851 /* This function is used to announce our existing channels to our router
2852    when we've connected to it. This also announces the users on the
2853    channels to the router. */
2854
2855 void silc_server_announce_channels(SilcServer server)
2856 {
2857   SilcBuffer channels = NULL, channel_users = NULL;
2858
2859   SILC_LOG_DEBUG(("Announcing channels and channel users"));
2860
2861   /* Get channels and channel users in local list */
2862   silc_server_announce_get_channels(server, server->local_list,
2863                                     &channels, &channel_users);
2864
2865   /* Get channels and channel users in global list */
2866   silc_server_announce_get_channels(server, server->global_list,
2867                                     &channels, &channel_users);
2868
2869   if (channels) {
2870     silc_buffer_push(channels, channels->data - channels->head);
2871     SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
2872
2873     /* Send the packet */
2874     silc_server_packet_send(server, server->router->connection,
2875                             SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
2876                             channels->data, channels->len,
2877                             FALSE);
2878
2879     silc_buffer_free(channels);
2880   }
2881
2882   if (channel_users) {
2883     silc_buffer_push(channel_users, channel_users->data - channel_users->head);
2884     SILC_LOG_HEXDUMP(("channel users"), channel_users->data, 
2885                      channel_users->len);
2886
2887     /* Send the packet */
2888     silc_server_packet_send(server, server->router->connection,
2889                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
2890                             channel_users->data, channel_users->len,
2891                             FALSE);
2892
2893     silc_buffer_free(channel_users);
2894   }
2895 }
2896
2897 /* Failure timeout callback. If this is called then we will immediately
2898    process the received failure. We always process the failure with timeout
2899    since we do not want to blindly trust to received failure packets. 
2900    This won't be called (the timeout is cancelled) if the failure was
2901    bogus (it is bogus if remote does not close the connection after sending
2902    the failure). */
2903
2904 SILC_TASK_CALLBACK(silc_server_failure_callback)
2905 {
2906   SilcServerFailureContext f = (SilcServerFailureContext)context;
2907
2908   if (f->sock->protocol) {
2909     f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
2910     f->sock->protocol->execute(f->server->timeout_queue, 0,
2911                                f->sock->protocol, f->sock->sock, 0, 0);
2912   }
2913
2914   silc_free(f);
2915 }
2916
2917 /* Assembles user list and users mode list from the `channel'. */
2918
2919 void silc_server_get_users_on_channel(SilcServer server,
2920                                       SilcChannelEntry channel,
2921                                       SilcBuffer *user_list,
2922                                       SilcBuffer *mode_list,
2923                                       unsigned int *user_count)
2924 {
2925   SilcChannelClientEntry chl;
2926   SilcBuffer client_id_list;
2927   SilcBuffer client_mode_list;
2928   SilcBuffer idp;
2929   unsigned int list_count = 0;
2930
2931   client_id_list = silc_buffer_alloc((SILC_ID_CLIENT_LEN + 4) * 
2932                                      silc_list_count(channel->user_list));
2933   client_mode_list = silc_buffer_alloc(4 * 
2934                                        silc_list_count(channel->user_list));
2935   silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
2936   silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
2937   silc_list_start(channel->user_list);
2938   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2939     /* Client ID */
2940     idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
2941     silc_buffer_put(client_id_list, idp->data, idp->len);
2942     silc_buffer_pull(client_id_list, idp->len);
2943     silc_buffer_free(idp);
2944
2945     /* Client's mode on channel */
2946     SILC_PUT32_MSB(chl->mode, client_mode_list->data);
2947     silc_buffer_pull(client_mode_list, 4);
2948
2949     list_count++;
2950   }
2951   silc_buffer_push(client_id_list, 
2952                    client_id_list->data - client_id_list->head);
2953   silc_buffer_push(client_mode_list, 
2954                    client_mode_list->data - client_mode_list->head);
2955
2956   *user_list = client_id_list;
2957   *mode_list = client_mode_list;
2958   *user_count = list_count;
2959 }
2960
2961 /* Saves users and their modes to the `channel'. */
2962
2963 void silc_server_save_users_on_channel(SilcServer server,
2964                                        SilcSocketConnection sock,
2965                                        SilcChannelEntry channel,
2966                                        SilcClientID *noadd,
2967                                        SilcBuffer user_list,
2968                                        SilcBuffer mode_list,
2969                                        unsigned int user_count)
2970 {
2971   int i;
2972
2973   /* Cache the received Client ID's and modes. This cache expires
2974      whenever server sends notify message to channel. It means two things;
2975      some user has joined or leaved the channel. XXX TODO! */
2976   for (i = 0; i < user_count; i++) {
2977     unsigned short idp_len;
2978     unsigned int mode;
2979     SilcClientID *client_id;
2980     SilcClientEntry client;
2981
2982     /* Client ID */
2983     SILC_GET16_MSB(idp_len, user_list->data + 2);
2984     idp_len += 4;
2985     client_id = silc_id_payload_parse_id(user_list->data, idp_len);
2986     silc_buffer_pull(user_list, idp_len);
2987     if (!client_id)
2988       continue;
2989
2990     /* Mode */
2991     SILC_GET32_MSB(mode, mode_list->data);
2992     silc_buffer_pull(mode_list, 4);
2993
2994     if (noadd && !SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
2995       silc_free(client_id);
2996       continue;
2997     }
2998     
2999     /* Check if we have this client cached already. */
3000     client = silc_idlist_find_client_by_id(server->local_list, client_id,
3001                                            NULL);
3002     if (!client)
3003       client = silc_idlist_find_client_by_id(server->global_list, 
3004                                              client_id, NULL);
3005     if (!client) {
3006       /* If router did not find such Client ID in its lists then this must
3007          be bogus client or some router in the net is buggy. */
3008       if (server->server_type == SILC_ROUTER) {
3009         silc_free(client_id);
3010         continue;
3011       }
3012
3013       /* We don't have that client anywhere, add it. The client is added
3014          to global list since server didn't have it in the lists so it must be 
3015          global. */
3016       client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL, 
3017                                       silc_id_dup(client_id, SILC_ID_CLIENT), 
3018                                       sock->user_data, NULL);
3019       if (!client) {
3020         silc_free(client_id);
3021         continue;
3022       }
3023     }
3024
3025     silc_free(client_id);
3026
3027     if (!silc_server_client_on_channel(client, channel)) {
3028       /* Client was not on the channel, add it. */
3029       SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3030       chl->client = client;
3031       chl->mode = mode;
3032       chl->channel = channel;
3033       silc_list_add(channel->user_list, chl);
3034       silc_list_add(client->channels, chl);
3035     }
3036   }
3037 }