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