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     /* Error occured during protocol */
1033     silc_protocol_free(protocol);
1034     silc_ske_free_key_material(ctx->keymat);
1035     if (ctx->packet)
1036       silc_packet_context_free(ctx->packet);
1037     if (ctx->ske)
1038       silc_ske_free(ctx->ske);
1039     if (ctx->dest_id)
1040       silc_free(ctx->dest_id);
1041     silc_free(ctx);
1042     silc_task_unregister_by_callback(server->timeout_queue,
1043                                      silc_server_failure_callback);
1044     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1045                                   "Key exchange failed");
1046     server->stat.auth_failures++;
1047     return;
1048   }
1049
1050   /* We now have the key material as the result of the key exchange
1051      protocol. Take the key material into use. Free the raw key material
1052      as soon as we've set them into use. */
1053   if (!silc_server_protocol_ke_set_keys(ctx->ske, ctx->sock, ctx->keymat,
1054                                         ctx->ske->prop->cipher,
1055                                         ctx->ske->prop->pkcs,
1056                                         ctx->ske->prop->hash,
1057                                         ctx->ske->prop->hmac,
1058                                         ctx->responder)) {
1059     silc_protocol_free(protocol);
1060     silc_ske_free_key_material(ctx->keymat);
1061     if (ctx->packet)
1062       silc_packet_context_free(ctx->packet);
1063     if (ctx->ske)
1064       silc_ske_free(ctx->ske);
1065     if (ctx->dest_id)
1066       silc_free(ctx->dest_id);
1067     silc_free(ctx);
1068     silc_task_unregister_by_callback(server->timeout_queue,
1069                                      silc_server_failure_callback);
1070     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1071                                   "Key exchange failed");
1072     server->stat.auth_failures++;
1073     return;
1074   }    
1075   silc_ske_free_key_material(ctx->keymat);
1076
1077   /* Allocate internal context for the authentication protocol. This
1078      is sent as context for the protocol. */
1079   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1080   proto_ctx->server = (void *)server;
1081   proto_ctx->sock = sock = server->sockets[fd];
1082   proto_ctx->ske = ctx->ske;    /* Save SKE object from previous protocol */
1083   proto_ctx->responder = TRUE;
1084   proto_ctx->dest_id_type = ctx->dest_id_type;
1085   proto_ctx->dest_id = ctx->dest_id;
1086
1087   /* Free old protocol as it is finished now */
1088   silc_protocol_free(protocol);
1089   if (ctx->packet)
1090     silc_packet_context_free(ctx->packet);
1091   silc_free(ctx);
1092   sock->protocol = NULL;
1093
1094   /* Allocate the authentication protocol. This is allocated here
1095      but we won't start it yet. We will be receiving party of this
1096      protocol thus we will wait that connecting party will make
1097      their first move. */
1098   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH, 
1099                       &sock->protocol, proto_ctx, 
1100                       silc_server_accept_new_connection_final);
1101
1102   /* Register timeout task. If the protocol is not executed inside
1103      this timelimit the connection will be terminated. Currently
1104      this is 60 seconds and is hard coded limit (XXX). */
1105   proto_ctx->timeout_task = 
1106     silc_task_register(server->timeout_queue, sock->sock, 
1107                        silc_server_timeout_remote,
1108                        (void *)server, 60, 0,
1109                        SILC_TASK_TIMEOUT,
1110                        SILC_TASK_PRI_LOW);
1111 }
1112
1113 /* Final part of accepting new connection. The connection has now
1114    been authenticated and keys has been exchanged. We also know whether
1115    this is client or server connection. */
1116
1117 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1118 {
1119   SilcProtocol protocol = (SilcProtocol)context;
1120   SilcServerConnAuthInternalContext *ctx = 
1121     (SilcServerConnAuthInternalContext *)protocol->context;
1122   SilcServer server = (SilcServer)ctx->server;
1123   SilcSocketConnection sock = ctx->sock;
1124   SilcServerHBContext hb_context;
1125   void *id_entry = NULL;
1126
1127   SILC_LOG_DEBUG(("Start"));
1128
1129   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
1130     /* Error occured during protocol */
1131     silc_protocol_free(protocol);
1132     if (ctx->packet)
1133       silc_packet_context_free(ctx->packet);
1134     if (ctx->ske)
1135       silc_ske_free(ctx->ske);
1136     if (ctx->dest_id)
1137       silc_free(ctx->dest_id);
1138     silc_free(ctx);
1139     if (sock)
1140       sock->protocol = NULL;
1141     silc_task_unregister_by_callback(server->timeout_queue,
1142                                      silc_server_failure_callback);
1143     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1144                                   "Authentication failed");
1145     server->stat.auth_failures++;
1146     return;
1147   }
1148
1149   sock->type = ctx->conn_type;
1150   switch(sock->type) {
1151   case SILC_SOCKET_TYPE_CLIENT:
1152     {
1153       SilcClientEntry client;
1154
1155       SILC_LOG_DEBUG(("Remote host is client"));
1156       SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
1157                      sock->ip));
1158
1159       /* Add the client to the client ID cache. The nickname and Client ID
1160          and other information is created after we have received NEW_CLIENT
1161          packet from client. */
1162       client = silc_idlist_add_client(server->local_list, 
1163                                       NULL, NULL, NULL, NULL, NULL, sock);
1164       if (!client) {
1165         SILC_LOG_ERROR(("Could not add new client to cache"));
1166         silc_free(sock->user_data);
1167         break;
1168       }
1169
1170       /* Statistics */
1171       server->stat.my_clients++;
1172       server->stat.clients++;
1173       if (server->server_type == SILC_ROUTER)
1174         server->stat.cell_clients++;
1175
1176       id_entry = (void *)client;
1177       break;
1178     }
1179   case SILC_SOCKET_TYPE_SERVER:
1180   case SILC_SOCKET_TYPE_ROUTER:
1181     {
1182       SilcServerEntry new_server;
1183
1184       SILC_LOG_DEBUG(("Remote host is %s", 
1185                       sock->type == SILC_SOCKET_TYPE_SERVER ? 
1186                       "server" : "router"));
1187       SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
1188                      sock->ip, sock->type == SILC_SOCKET_TYPE_SERVER ? 
1189                      "server" : "router"));
1190
1191       /* Add the server into server cache. The server name and Server ID
1192          is updated after we have received NEW_SERVER packet from the
1193          server. We mark ourselves as router for this server if we really
1194          are router. */
1195       new_server = 
1196         silc_idlist_add_server(server->local_list, NULL,
1197                                sock->type == SILC_SOCKET_TYPE_SERVER ?
1198                                SILC_SERVER : SILC_ROUTER, NULL, 
1199                                sock->type == SILC_SOCKET_TYPE_SERVER ?
1200                                server->id_entry : NULL, sock);
1201       if (!new_server) {
1202         SILC_LOG_ERROR(("Could not add new server to cache"));
1203         silc_free(sock->user_data);
1204         break;
1205       }
1206
1207       /* Statistics */
1208       if (sock->type == SILC_SOCKET_TYPE_SERVER)
1209         server->stat.my_servers++;
1210       else
1211         server->stat.my_routers++;
1212       server->stat.servers++;
1213
1214       id_entry = (void *)new_server;
1215       
1216       /* There is connection to other server now, if it is router then
1217          we will have connection to outside world.  If we are router but
1218          normal server connected to us then we will remain standalone,
1219          if we are standlone. */
1220       if (server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER) {
1221         SILC_LOG_DEBUG(("We are not standalone server anymore"));
1222         server->standalone = FALSE;
1223         if (!server->id_entry->router) {
1224           server->id_entry->router = id_entry;
1225           server->router = id_entry;
1226         }
1227       }
1228       break;
1229     }
1230   default:
1231     break;
1232   }
1233
1234   /* Add the common data structure to the ID entry. */
1235   if (id_entry)
1236     silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1237       
1238   /* Add to sockets internal pointer for fast referencing */
1239   silc_free(sock->user_data);
1240   sock->user_data = id_entry;
1241
1242   /* Connection has been fully established now. Everything is ok. */
1243   SILC_LOG_DEBUG(("New connection authenticated"));
1244
1245   /* Perform keepalive. The `hb_context' will be freed automatically
1246      when finally calling the silc_socket_free function. XXX hardcoded 
1247      timeout!! */
1248   hb_context = silc_calloc(1, sizeof(*hb_context));
1249   hb_context->server = server;
1250   silc_socket_set_heartbeat(sock, 600, hb_context,
1251                             silc_server_perform_heartbeat,
1252                             server->timeout_queue);
1253
1254   silc_task_unregister_by_callback(server->timeout_queue,
1255                                    silc_server_failure_callback);
1256   silc_protocol_free(protocol);
1257   if (ctx->packet)
1258     silc_packet_context_free(ctx->packet);
1259   if (ctx->ske)
1260     silc_ske_free(ctx->ske);
1261   if (ctx->dest_id)
1262     silc_free(ctx->dest_id);
1263   silc_free(ctx);
1264   sock->protocol = NULL;
1265 }
1266
1267 /* This function is used to read packets from network and send packets to
1268    network. This is usually a generic task. */
1269
1270 SILC_TASK_CALLBACK(silc_server_packet_process)
1271 {
1272   SilcServer server = (SilcServer)context;
1273   SilcSocketConnection sock = server->sockets[fd];
1274   SilcIDListData idata;
1275   SilcCipher cipher = NULL;
1276   SilcHmac hmac = NULL;
1277   int ret;
1278
1279   if (!sock)
1280     return;
1281
1282   SILC_LOG_DEBUG(("Processing packet"));
1283
1284   /* Packet sending */
1285
1286   if (type == SILC_TASK_WRITE) {
1287     /* Do not send data to disconnected connection */
1288     if (SILC_IS_DISCONNECTED(sock))
1289       return;
1290
1291     server->stat.packets_sent++;
1292
1293     if (sock->outbuf->data - sock->outbuf->head)
1294       silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1295
1296     ret = silc_server_packet_send_real(server, sock, TRUE);
1297
1298     /* If returned -2 could not write to connection now, will do
1299        it later. */
1300     if (ret == -2)
1301       return;
1302
1303     if (ret == -1)
1304       return;
1305     
1306     /* The packet has been sent and now it is time to set the connection
1307        back to only for input. When there is again some outgoing data 
1308        available for this connection it will be set for output as well. 
1309        This call clears the output setting and sets it only for input. */
1310     SILC_SET_CONNECTION_FOR_INPUT(fd);
1311     SILC_UNSET_OUTBUF_PENDING(sock);
1312
1313     silc_buffer_clear(sock->outbuf);
1314     return;
1315   }
1316
1317   /* Packet receiving */
1318
1319   /* Read some data from connection */
1320   ret = silc_packet_receive(sock);
1321   if (ret < 0)
1322     return;
1323     
1324   /* EOF */
1325   if (ret == 0) {
1326     SILC_LOG_DEBUG(("Read EOF"));
1327       
1328     /* If connection is disconnecting already we will finally
1329        close the connection */
1330     if (SILC_IS_DISCONNECTING(sock)) {
1331       if (sock->user_data)
1332         silc_server_free_sock_user_data(server, sock);
1333       silc_server_close_connection(server, sock);
1334       return;
1335     }
1336       
1337     SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1338     SILC_SET_DISCONNECTING(sock);
1339
1340     /* If the closed connection was our primary router connection the
1341        start re-connecting phase. */
1342     if (!server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER && 
1343         sock == server->router->connection)
1344       silc_task_register(server->timeout_queue, 0, 
1345                          silc_server_connect_to_router,
1346                          context, 1, 0,
1347                          SILC_TASK_TIMEOUT,
1348                          SILC_TASK_PRI_NORMAL);
1349
1350     if (sock->user_data)
1351       silc_server_free_sock_user_data(server, sock);
1352     silc_server_close_connection(server, sock);
1353     return;
1354   }
1355
1356   /* If connection is disconnecting or disconnected we will ignore
1357      what we read. */
1358   if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1359     SILC_LOG_DEBUG(("Ignoring read data from disonnected connection"));
1360     return;
1361   }
1362
1363   server->stat.packets_received++;
1364
1365   /* Get keys and stuff from ID entry */
1366   idata = (SilcIDListData)sock->user_data;
1367   if (idata) {
1368     idata->last_receive = time(NULL);
1369     cipher = idata->receive_key;
1370     hmac = idata->hmac;
1371   }
1372  
1373   /* Process the packet. This will call the parser that will then
1374      decrypt and parse the packet. */
1375   silc_packet_receive_process(sock, cipher, hmac, silc_server_packet_parse, 
1376                               server);
1377 }
1378
1379 /* Callback function that the silc_packet_decrypt will call to make the
1380    decision whether the packet is normal or special packet. We will 
1381    return TRUE if it is normal and FALSE if it is special */
1382
1383 static int silc_server_packet_decrypt_check(SilcPacketType packet_type,
1384                                             SilcBuffer buffer,
1385                                             SilcPacketContext *packet,
1386                                             void *context)
1387 {
1388   SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1389   SilcServer server = (SilcServer)parse_ctx->context;
1390
1391   /* Packet is normal packet, if: 
1392
1393      1) packet is private message packet and does not have private key set
1394      2) is other packet than channel message packet
1395      3) is channel message packet and remote is router and we are router 
1396
1397      all other packets are special packets 
1398   */
1399   if ((packet_type == SILC_PACKET_PRIVATE_MESSAGE &&
1400        !(buffer->data[2] & SILC_PACKET_FLAG_PRIVMSG_KEY)) ||
1401       packet_type != SILC_PACKET_CHANNEL_MESSAGE || 
1402       (packet_type == SILC_PACKET_CHANNEL_MESSAGE &&
1403        parse_ctx->sock->type == SILC_SOCKET_TYPE_ROUTER &&
1404        server->server_type == SILC_ROUTER))
1405     return TRUE;
1406
1407   return FALSE;
1408 }
1409
1410 /* Parses whole packet, received earlier. */
1411
1412 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1413 {
1414   SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1415   SilcServer server = (SilcServer)parse_ctx->context;
1416   SilcSocketConnection sock = parse_ctx->sock;
1417   SilcPacketContext *packet = parse_ctx->packet;
1418   int ret;
1419
1420   SILC_LOG_DEBUG(("Start"));
1421
1422   /* Decrypt the received packet */
1423   ret = silc_packet_decrypt(parse_ctx->cipher, parse_ctx->hmac, 
1424                             packet->buffer, packet,
1425                             silc_server_packet_decrypt_check, parse_ctx);
1426   if (ret < 0)
1427     goto out;
1428
1429   if (ret == 0) {
1430     /* Parse the packet. Packet type is returned. */
1431     ret = silc_packet_parse(packet);
1432   } else {
1433     /* Parse the packet header in special way as this is "special"
1434        packet type. */
1435     ret = silc_packet_parse_special(packet);
1436   }
1437
1438   if (ret == SILC_PACKET_NONE)
1439     goto out;
1440
1441   /* Check that the the current client ID is same as in the client's packet. */
1442   if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1443     SilcClientEntry client = (SilcClientEntry)sock->user_data;
1444     if (client && client->id) {
1445       void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1446                                 packet->src_id_type);
1447       if (SILC_ID_CLIENT_COMPARE(client->id, id)) {
1448         silc_free(id);
1449         goto out;
1450       }
1451       silc_free(id);
1452     }
1453   }
1454
1455   if (server->server_type == SILC_ROUTER) {
1456     /* Route the packet if it is not destined to us. Other ID types but
1457        server are handled separately after processing them. */
1458     if (packet->dst_id_type == SILC_ID_SERVER && 
1459         sock->type != SILC_SOCKET_TYPE_CLIENT &&
1460         SILC_ID_SERVER_COMPARE(packet->dst_id, server->id_string)) {
1461       
1462       /* Route the packet to fastest route for the destination ID */
1463       void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len, 
1464                                 packet->dst_id_type);
1465       if (!id)
1466         goto out;
1467       silc_server_packet_route(server,
1468                                silc_server_route_get(server, id,
1469                                                      packet->dst_id_type),
1470                                packet);
1471       silc_free(id);
1472       goto out;
1473     }
1474     
1475     /* Broadcast packet if it is marked as broadcast packet and it is
1476        originated from router and we are router. */
1477     if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1478         packet->flags & SILC_PACKET_FLAG_BROADCAST) {
1479       silc_server_packet_broadcast(server, server->router->connection, packet);
1480     }
1481   }
1482
1483   /* Parse the incoming packet type */
1484   silc_server_packet_parse_type(server, sock, packet);
1485
1486  out:
1487   silc_buffer_clear(sock->inbuf);
1488   silc_packet_context_free(packet);
1489   silc_free(parse_ctx);
1490 }
1491
1492 /* Parser callback called by silc_packet_receive_process. This merely
1493    registers timeout that will handle the actual parsing when appropriate. */
1494
1495 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1496 {
1497   SilcServer server = (SilcServer)parser_context->context;
1498   SilcSocketConnection sock = parser_context->sock;
1499
1500   switch (sock->type) {
1501   case SILC_SOCKET_TYPE_CLIENT:
1502   case SILC_SOCKET_TYPE_UNKNOWN:
1503     /* Parse the packet with timeout */
1504     silc_task_register(server->timeout_queue, sock->sock,
1505                        silc_server_packet_parse_real,
1506                        (void *)parser_context, 0, 100000,
1507                        SILC_TASK_TIMEOUT,
1508                        SILC_TASK_PRI_NORMAL);
1509     break;
1510   case SILC_SOCKET_TYPE_SERVER:
1511   case SILC_SOCKET_TYPE_ROUTER:
1512     /* Packets from servers are parsed as soon as possible */
1513     silc_task_register(server->timeout_queue, sock->sock,
1514                        silc_server_packet_parse_real,
1515                        (void *)parser_context, 0, 1,
1516                        SILC_TASK_TIMEOUT,
1517                        SILC_TASK_PRI_NORMAL);
1518     break;
1519   default:
1520     return;
1521   }
1522 }
1523
1524 /* Parses the packet type and calls what ever routines the packet type
1525    requires. This is done for all incoming packets. */
1526
1527 void silc_server_packet_parse_type(SilcServer server, 
1528                                    SilcSocketConnection sock,
1529                                    SilcPacketContext *packet)
1530 {
1531   SilcPacketType type = packet->type;
1532
1533   SILC_LOG_DEBUG(("Parsing packet type %d", type));
1534
1535   /* Parse the packet type */
1536   switch(type) {
1537   case SILC_PACKET_DISCONNECT:
1538     SILC_LOG_DEBUG(("Disconnect packet"));
1539     if (packet->flags & SILC_PACKET_FLAG_LIST)
1540       break;
1541     break;
1542
1543   case SILC_PACKET_SUCCESS:
1544     /*
1545      * Success received for something. For now we can have only
1546      * one protocol for connection executing at once hence this
1547      * success message is for whatever protocol is executing currently.
1548      */
1549     SILC_LOG_DEBUG(("Success packet"));
1550     if (packet->flags & SILC_PACKET_FLAG_LIST)
1551       break;
1552     if (sock->protocol) {
1553       sock->protocol->execute(server->timeout_queue, 0,
1554                               sock->protocol, sock->sock, 0, 0);
1555     }
1556     break;
1557
1558   case SILC_PACKET_FAILURE:
1559     /*
1560      * Failure received for something. For now we can have only
1561      * one protocol for connection executing at once hence this
1562      * failure message is for whatever protocol is executing currently.
1563      */
1564     SILC_LOG_DEBUG(("Failure packet"));
1565     if (packet->flags & SILC_PACKET_FLAG_LIST)
1566       break;
1567     if (sock->protocol) {
1568       SilcServerFailureContext f;
1569       f = silc_calloc(1, sizeof(*f));
1570       f->server = server;
1571       f->sock = sock;
1572       
1573       /* We will wait 5 seconds to process this failure packet */
1574       silc_task_register(server->timeout_queue, sock->sock,
1575                          silc_server_failure_callback, (void *)f, 5, 0,
1576                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1577     }
1578     break;
1579
1580   case SILC_PACKET_REJECT:
1581     SILC_LOG_DEBUG(("Reject packet"));
1582     if (packet->flags & SILC_PACKET_FLAG_LIST)
1583       break;
1584     return;
1585     break;
1586
1587   case SILC_PACKET_NOTIFY:
1588     /*
1589      * Received notify packet. Server can receive notify packets from
1590      * router. Server then relays the notify messages to clients if needed.
1591      */
1592     SILC_LOG_DEBUG(("Notify packet"));
1593     if (packet->flags & SILC_PACKET_FLAG_LIST)
1594       silc_server_notify_list(server, sock, packet);
1595     else
1596       silc_server_notify(server, sock, packet);
1597     break;
1598
1599     /* 
1600      * Channel packets
1601      */
1602   case SILC_PACKET_CHANNEL_MESSAGE:
1603     /*
1604      * Received channel message. Channel messages are special packets
1605      * (although probably most common ones) thus they are handled
1606      * specially.
1607      */
1608     SILC_LOG_DEBUG(("Channel Message packet"));
1609     if (packet->flags & SILC_PACKET_FLAG_LIST)
1610       break;
1611     silc_server_channel_message(server, sock, packet);
1612     break;
1613
1614   case SILC_PACKET_CHANNEL_KEY:
1615     /*
1616      * Received key for channel. As channels are created by the router
1617      * the keys are as well. We will distribute the key to all of our
1618      * locally connected clients on the particular channel. Router
1619      * never receives this channel and thus is ignored.
1620      */
1621     SILC_LOG_DEBUG(("Channel Key packet"));
1622     if (packet->flags & SILC_PACKET_FLAG_LIST)
1623       break;
1624     silc_server_channel_key(server, sock, packet);
1625     break;
1626
1627     /*
1628      * Command packets
1629      */
1630   case SILC_PACKET_COMMAND:
1631     /*
1632      * Recived command. Processes the command request and allocates the
1633      * command context and calls the command.
1634      */
1635     SILC_LOG_DEBUG(("Command packet"));
1636     if (packet->flags & SILC_PACKET_FLAG_LIST)
1637       break;
1638     silc_server_command_process(server, sock, packet);
1639     break;
1640
1641   case SILC_PACKET_COMMAND_REPLY:
1642     /*
1643      * Received command reply packet. Received command reply to command. It
1644      * may be reply to command sent by us or reply to command sent by client
1645      * that we've routed further.
1646      */
1647     SILC_LOG_DEBUG(("Command Reply packet"));
1648     if (packet->flags & SILC_PACKET_FLAG_LIST)
1649       break;
1650     silc_server_command_reply(server, sock, packet);
1651     break;
1652
1653     /*
1654      * Private Message packets
1655      */
1656   case SILC_PACKET_PRIVATE_MESSAGE:
1657     /*
1658      * Received private message packet. The packet is coming from either
1659      * client or server.
1660      */
1661     SILC_LOG_DEBUG(("Private Message packet"));
1662     if (packet->flags & SILC_PACKET_FLAG_LIST)
1663       break;
1664     silc_server_private_message(server, sock, packet);
1665     break;
1666
1667   case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1668     /*
1669      * Private message key packet.
1670      */
1671     if (packet->flags & SILC_PACKET_FLAG_LIST)
1672       break;
1673     silc_server_private_message_key(server, sock, packet);
1674     break;
1675
1676     /*
1677      * Key Exchange protocol packets
1678      */
1679   case SILC_PACKET_KEY_EXCHANGE:
1680     SILC_LOG_DEBUG(("KE packet"));
1681     if (packet->flags & SILC_PACKET_FLAG_LIST)
1682       break;
1683
1684     if (sock->protocol && sock->protocol->protocol->type 
1685         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1686
1687       SilcServerKEInternalContext *proto_ctx = 
1688         (SilcServerKEInternalContext *)sock->protocol->context;
1689
1690       proto_ctx->packet = silc_packet_context_dup(packet);
1691
1692       /* Let the protocol handle the packet */
1693       sock->protocol->execute(server->timeout_queue, 0, 
1694                               sock->protocol, sock->sock, 0, 100000);
1695     } else {
1696       SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1697                       "protocol active, packet dropped."));
1698
1699       /* XXX Trigger KE protocol?? Rekey actually, maybe. */
1700     }
1701     break;
1702
1703   case SILC_PACKET_KEY_EXCHANGE_1:
1704     SILC_LOG_DEBUG(("KE 1 packet"));
1705     if (packet->flags & SILC_PACKET_FLAG_LIST)
1706       break;
1707
1708     if (sock->protocol && sock->protocol->protocol->type 
1709         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1710
1711       SilcServerKEInternalContext *proto_ctx = 
1712         (SilcServerKEInternalContext *)sock->protocol->context;
1713
1714       if (proto_ctx->packet)
1715         silc_packet_context_free(proto_ctx->packet);
1716
1717       proto_ctx->packet = silc_packet_context_dup(packet);
1718       proto_ctx->dest_id_type = packet->src_id_type;
1719       proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1720                                           packet->src_id_type);
1721       if (!proto_ctx->dest_id)
1722         break;
1723
1724       /* Let the protocol handle the packet */
1725       sock->protocol->execute(server->timeout_queue, 0, 
1726                               sock->protocol, sock->sock,
1727                               0, 100000);
1728     } else {
1729       SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1730                       "protocol active, packet dropped."));
1731     }
1732     break;
1733
1734   case SILC_PACKET_KEY_EXCHANGE_2:
1735     SILC_LOG_DEBUG(("KE 2 packet"));
1736     if (packet->flags & SILC_PACKET_FLAG_LIST)
1737       break;
1738
1739     if (sock->protocol && sock->protocol->protocol->type 
1740         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1741
1742       SilcServerKEInternalContext *proto_ctx = 
1743         (SilcServerKEInternalContext *)sock->protocol->context;
1744
1745       if (proto_ctx->packet)
1746         silc_packet_context_free(proto_ctx->packet);
1747
1748       proto_ctx->packet = silc_packet_context_dup(packet);
1749       proto_ctx->dest_id_type = packet->src_id_type;
1750       proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1751                                           packet->src_id_type);
1752       if (!proto_ctx->dest_id)
1753         break;
1754
1755       /* Let the protocol handle the packet */
1756       sock->protocol->execute(server->timeout_queue, 0, 
1757                               sock->protocol, sock->sock,
1758                               0, 100000);
1759     } else {
1760       SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1761                       "protocol active, packet dropped."));
1762     }
1763     break;
1764
1765   case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1766     /*
1767      * Connection authentication request packet. When we receive this packet
1768      * we will send to the other end information about our mandatory
1769      * authentication method for the connection. This packet maybe received
1770      * at any time. 
1771      */
1772     SILC_LOG_DEBUG(("Connection authentication request packet"));
1773     if (packet->flags & SILC_PACKET_FLAG_LIST)
1774       break;
1775     break;
1776
1777     /*
1778      * Connection Authentication protocol packets
1779      */
1780   case SILC_PACKET_CONNECTION_AUTH:
1781     /* Start of the authentication protocol. We receive here the 
1782        authentication data and will verify it. */
1783     SILC_LOG_DEBUG(("Connection auth packet"));
1784     if (packet->flags & SILC_PACKET_FLAG_LIST)
1785       break;
1786
1787     if (sock->protocol && sock->protocol->protocol->type 
1788         == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1789
1790       SilcServerConnAuthInternalContext *proto_ctx = 
1791         (SilcServerConnAuthInternalContext *)sock->protocol->context;
1792
1793       proto_ctx->packet = silc_packet_context_dup(packet);
1794
1795       /* Let the protocol handle the packet */
1796       sock->protocol->execute(server->timeout_queue, 0, 
1797                               sock->protocol, sock->sock, 0, 0);
1798     } else {
1799       SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1800                       "protocol active, packet dropped."));
1801     }
1802     break;
1803
1804   case SILC_PACKET_NEW_ID:
1805     /*
1806      * Received New ID packet. This includes some new ID that has been
1807      * created. It may be for client, server or channel. This is the way
1808      * to distribute information about new registered entities in the
1809      * SILC network.
1810      */
1811     SILC_LOG_DEBUG(("New ID packet"));
1812     if (packet->flags & SILC_PACKET_FLAG_LIST)
1813       silc_server_new_id_list(server, sock, packet);
1814     else
1815       silc_server_new_id(server, sock, packet);
1816     break;
1817
1818   case SILC_PACKET_NEW_CLIENT:
1819     /*
1820      * Received new client packet. This includes client information that
1821      * we will use to create initial client ID. After creating new
1822      * ID we will send it to the client.
1823      */
1824     SILC_LOG_DEBUG(("New Client packet"));
1825     if (packet->flags & SILC_PACKET_FLAG_LIST)
1826       break;
1827     silc_server_new_client(server, sock, packet);
1828     break;
1829
1830   case SILC_PACKET_NEW_SERVER:
1831     /*
1832      * Received new server packet. This includes Server ID and some other
1833      * information that we may save. This is received after server has 
1834      * connected to us.
1835      */
1836     SILC_LOG_DEBUG(("New Server packet"));
1837     if (packet->flags & SILC_PACKET_FLAG_LIST)
1838       break;
1839     silc_server_new_server(server, sock, packet);
1840     break;
1841
1842   case SILC_PACKET_NEW_CHANNEL:
1843     /*
1844      * Received new channel packet. Information about new channel in the
1845      * network are distributed using this packet.
1846      */
1847     SILC_LOG_DEBUG(("New Channel packet"));
1848     if (packet->flags & SILC_PACKET_FLAG_LIST)
1849       silc_server_new_channel_list(server, sock, packet);
1850     else
1851       silc_server_new_channel(server, sock, packet);
1852     break;
1853
1854   case SILC_PACKET_HEARTBEAT:
1855     /*
1856      * Received heartbeat.
1857      */
1858     SILC_LOG_DEBUG(("Heartbeat packet"));
1859     if (packet->flags & SILC_PACKET_FLAG_LIST)
1860       break;
1861     break;
1862
1863   case SILC_PACKET_KEY_AGREEMENT:
1864     /*
1865      * Received heartbeat.
1866      */
1867     SILC_LOG_DEBUG(("Key agreement packet"));
1868     if (packet->flags & SILC_PACKET_FLAG_LIST)
1869       break;
1870     silc_server_key_agreement(server, sock, packet);
1871     break;
1872
1873   default:
1874     SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
1875     break;
1876   }
1877   
1878 }
1879
1880 /* Creates connection to a remote router. */
1881
1882 void silc_server_create_connection(SilcServer server,
1883                                    char *remote_host, unsigned int port)
1884 {
1885   SilcServerConnection sconn;
1886
1887   /* Allocate connection object for hold connection specific stuff. */
1888   sconn = silc_calloc(1, sizeof(*sconn));
1889   sconn->server = server;
1890   sconn->remote_host = strdup(remote_host);
1891   sconn->remote_port = port;
1892
1893   silc_task_register(server->timeout_queue, 0, 
1894                      silc_server_connect_router,
1895                      (void *)sconn, 0, 1, SILC_TASK_TIMEOUT, 
1896                      SILC_TASK_PRI_NORMAL);
1897 }
1898
1899 /* Closes connection to socket connection */
1900
1901 void silc_server_close_connection(SilcServer server,
1902                                   SilcSocketConnection sock)
1903 {
1904   SILC_LOG_DEBUG(("Closing connection %d", sock->sock));
1905
1906   /* We won't listen for this connection anymore */
1907   silc_schedule_unset_listen_fd(sock->sock);
1908
1909   /* Unregister all tasks */
1910   silc_task_unregister_by_fd(server->io_queue, sock->sock);
1911   silc_task_unregister_by_fd(server->timeout_queue, sock->sock);
1912
1913   /* Close the actual connection */
1914   silc_net_close_connection(sock->sock);
1915   server->sockets[sock->sock] = NULL;
1916   silc_socket_free(sock);
1917 }
1918
1919 /* Sends disconnect message to remote connection and disconnects the 
1920    connection. */
1921
1922 void silc_server_disconnect_remote(SilcServer server,
1923                                    SilcSocketConnection sock,
1924                                    const char *fmt, ...)
1925 {
1926   va_list ap;
1927   unsigned char buf[4096];
1928
1929   if (!sock)
1930     return;
1931
1932   memset(buf, 0, sizeof(buf));
1933   va_start(ap, fmt);
1934   vsprintf(buf, fmt, ap);
1935   va_end(ap);
1936
1937   SILC_LOG_DEBUG(("Disconnecting remote host"));
1938
1939   SILC_LOG_INFO(("Disconnecting %s:%d [%s]", sock->hostname,
1940                   sock->port,
1941                   (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1942                    sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1943                    sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1944                    "Router")));
1945
1946   /* Notify remote end that the conversation is over. The notify message
1947      is tried to be sent immediately. */
1948   silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,  
1949                           buf, strlen(buf), TRUE);
1950
1951   /* Mark the connection to be disconnected */
1952   SILC_SET_DISCONNECTED(sock);
1953   silc_server_close_connection(server, sock);
1954 }
1955
1956 typedef struct {
1957   SilcServer server;
1958   SilcClientEntry client;
1959 } *FreeClientInternal;
1960
1961 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
1962 {
1963   FreeClientInternal i = (FreeClientInternal)context;
1964
1965   silc_idlist_del_data(i->client);
1966   silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
1967   silc_free(i);
1968 }
1969
1970 /* Frees client data and notifies about client's signoff. */
1971
1972 void silc_server_free_client_data(SilcServer server, 
1973                                   SilcSocketConnection sock,
1974                                   SilcClientEntry client, char *signoff)
1975 {
1976   FreeClientInternal i = silc_calloc(1, sizeof(*i));
1977
1978   /* Send REMOVE_ID packet to routers. */
1979   if (!server->standalone && server->router)
1980     silc_server_send_notify_signoff(server, server->router->connection,
1981                                     server->server_type == SILC_SERVER ?
1982                                     FALSE : TRUE, client->id, 
1983                                     SILC_ID_CLIENT_LEN, signoff);
1984
1985   /* Remove client from all channels */
1986   silc_server_remove_from_channels(server, sock, client, signoff);
1987
1988   /* We will not delete the client entry right away. We will take it
1989      into history (for WHOWAS command) for 5 minutes */
1990   i->server = server;
1991   i->client = client;
1992   silc_task_register(server->timeout_queue, 0, 
1993                      silc_server_free_client_data_timeout,
1994                      (void *)i, 300, 0,
1995                      SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
1996   client->data.registered = FALSE;
1997
1998   /* Free the client entry and everything in it */
1999   server->stat.my_clients--;
2000   server->stat.clients--;
2001   if (server->server_type == SILC_ROUTER)
2002     server->stat.cell_clients--;
2003 }
2004
2005 /* Frees user_data pointer from socket connection object. This also sends
2006    appropriate notify packets to the network to inform about leaving
2007    entities. */
2008
2009 void silc_server_free_sock_user_data(SilcServer server, 
2010                                      SilcSocketConnection sock)
2011 {
2012   SILC_LOG_DEBUG(("Start"));
2013
2014   switch(sock->type) {
2015   case SILC_SOCKET_TYPE_CLIENT:
2016     {
2017       SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2018       silc_server_free_client_data(server, sock, user_data, NULL);
2019       break;
2020     }
2021   case SILC_SOCKET_TYPE_SERVER:
2022   case SILC_SOCKET_TYPE_ROUTER:
2023     {
2024       SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2025
2026       /* Send REMOVE_ID packet to routers. */
2027       if (!server->standalone && server->router)
2028         silc_server_send_notify_server_signoff(server, 
2029                                                server->router->connection,
2030                                                server->server_type == 
2031                                                SILC_SERVER ?
2032                                                FALSE : TRUE, user_data->id, 
2033                                                SILC_ID_SERVER_LEN);
2034
2035       /* Then also free all client entries that this server owns as
2036          they will become invalid now as well. */
2037       silc_server_remove_clients_by_server(server, user_data);
2038
2039       /* If this was our primary router connection then we're lost to
2040          the outside world. */
2041       if (server->router == user_data) {
2042         server->id_entry->router = NULL;
2043         server->router = NULL;
2044         server->standalone = TRUE;
2045       }
2046
2047       /* Free the server entry */
2048       silc_idlist_del_data(user_data);
2049       silc_idlist_del_server(server->local_list, user_data);
2050       server->stat.my_servers--;
2051       server->stat.servers--;
2052       if (server->server_type == SILC_ROUTER)
2053         server->stat.cell_servers--;
2054       break;
2055     }
2056   default:
2057     {
2058       SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2059
2060       silc_idlist_del_data(user_data);
2061       silc_free(user_data);
2062       break;
2063     }
2064   }
2065
2066   sock->user_data = NULL;
2067 }
2068
2069 /* This function is used to remove all client entries by the server `entry'.
2070    This is called when the connection is lost to the server. In this case
2071    we must invalidate all the client entries owned by the server `entry'. */
2072
2073 int silc_server_remove_clients_by_server(SilcServer server, 
2074                                          SilcServerEntry entry)
2075 {
2076   SilcIDCacheList list = NULL;
2077   SilcIDCacheEntry id_cache = NULL;
2078   SilcClientEntry client = NULL;
2079
2080   SILC_LOG_DEBUG(("Start"));
2081
2082   if (silc_idcache_find_by_id(server->local_list->clients, 
2083                               SILC_ID_CACHE_ANY, SILC_ID_CLIENT, &list)) {
2084
2085     if (silc_idcache_list_first(list, &id_cache)) {
2086       while (id_cache) {
2087         client = (SilcClientEntry)id_cache->context;
2088         
2089         if (client->router != entry) {
2090           if (!silc_idcache_list_next(list, &id_cache))
2091             break;
2092           else
2093             continue;
2094         }
2095
2096         /* Remove the client entry */
2097         silc_server_remove_from_channels(server, NULL, client, NULL);
2098         silc_idlist_del_client(server->local_list, client);
2099
2100         if (!silc_idcache_list_next(list, &id_cache))
2101           break;
2102       }
2103     }
2104     silc_idcache_list_free(list);
2105   }
2106   
2107   if (silc_idcache_find_by_id(server->global_list->clients, 
2108                               SILC_ID_CACHE_ANY, SILC_ID_CLIENT, &list)) {
2109
2110     if (silc_idcache_list_first(list, &id_cache)) {
2111       while (id_cache) {
2112         client = (SilcClientEntry)id_cache->context;
2113         
2114         if (client->router != entry) {
2115           if (!silc_idcache_list_next(list, &id_cache))
2116             break;
2117           else
2118             continue;
2119         }
2120
2121         /* Remove the client entry */
2122         silc_server_remove_from_channels(server, NULL, client, NULL);
2123         silc_idlist_del_client(server->global_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   return TRUE;
2133 }
2134
2135 /* Checks whether given channel has global users.  If it does this returns
2136    TRUE and FALSE if there is only locally connected clients on the channel. */
2137
2138 int silc_server_channel_has_global(SilcChannelEntry channel)
2139 {
2140   SilcChannelClientEntry chl;
2141
2142   silc_list_start(channel->user_list);
2143   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2144     if (chl->client->router)
2145       return TRUE;
2146   }
2147
2148   return FALSE;
2149 }
2150
2151 /* Checks whether given channel has locally connected users.  If it does this
2152    returns TRUE and FALSE if there is not one locally connected client. */
2153
2154 int silc_server_channel_has_local(SilcChannelEntry channel)
2155 {
2156   SilcChannelClientEntry chl;
2157
2158   silc_list_start(channel->user_list);
2159   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2160     if (!chl->client->router)
2161       return TRUE;
2162   }
2163
2164   return FALSE;
2165 }
2166
2167 /* Removes client from all channels it has joined. This is used when client
2168    connection is disconnected. If the client on a channel is last, the
2169    channel is removed as well. This sends the SIGNOFF notify types. */
2170
2171 void silc_server_remove_from_channels(SilcServer server, 
2172                                       SilcSocketConnection sock,
2173                                       SilcClientEntry client,
2174                                       char *signoff_message)
2175 {
2176   SilcChannelEntry channel;
2177   SilcChannelClientEntry chl;
2178   SilcBuffer clidp;
2179
2180   SILC_LOG_DEBUG(("Start"));
2181
2182   if (!client || !client->id)
2183     return;
2184
2185   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2186
2187   /* Remove the client from all channels. The client is removed from
2188      the channels' user list. */
2189   silc_list_start(client->channels);
2190   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2191     channel = chl->channel;
2192
2193     /* Remove channel from client's channel list */
2194     silc_list_del(client->channels, chl);
2195
2196     /* Remove channel if there is no users anymore */
2197     if (server->server_type == SILC_ROUTER &&
2198         silc_list_count(channel->user_list) < 2) {
2199       if (!silc_idlist_del_channel(server->local_list, channel))
2200         silc_idlist_del_channel(server->global_list, channel);
2201       server->stat.my_channels--;
2202       continue;
2203     }
2204
2205     /* Remove client from channel's client list */
2206     silc_list_del(channel->user_list, chl);
2207     silc_free(chl);
2208     server->stat.my_chanclients--;
2209
2210     /* If there is no global users on the channel anymore mark the channel
2211        as local channel. */
2212     if (server->server_type == SILC_SERVER &&
2213         !silc_server_channel_has_global(channel))
2214       channel->global_users = FALSE;
2215
2216     /* If there is not at least one local user on the channel then we don't
2217        need the channel entry anymore, we can remove it safely. */
2218     if (server->server_type == SILC_SERVER &&
2219         !silc_server_channel_has_local(channel)) {
2220       /* Notify about leaving client if this channel has global users. */
2221       if (channel->global_users)
2222         silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2223                                            SILC_NOTIFY_TYPE_SIGNOFF, 
2224                                            signoff_message ? 2 : 1,
2225                                            clidp->data, clidp->len,
2226                                            signoff_message, signoff_message ?
2227                                            strlen(signoff_message) : 0);
2228
2229       if (!silc_idlist_del_channel(server->local_list, channel))
2230         silc_idlist_del_channel(server->global_list, channel);
2231       server->stat.my_channels--;
2232       continue;
2233     }
2234
2235     /* Send notify to channel about client leaving SILC and thus
2236        the entire channel. */
2237     silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2238                                        SILC_NOTIFY_TYPE_SIGNOFF, 
2239                                        signoff_message ? 2 : 1,
2240                                        clidp->data, clidp->len,
2241                                        signoff_message, signoff_message ?
2242                                        strlen(signoff_message) : 0);
2243   }
2244
2245   silc_buffer_free(clidp);
2246 }
2247
2248 /* Removes client from one channel. This is used for example when client
2249    calls LEAVE command to remove itself from the channel. Returns TRUE
2250    if channel still exists and FALSE if the channel is removed when
2251    last client leaves the channel. If `notify' is FALSE notify messages
2252    are not sent. */
2253
2254 int silc_server_remove_from_one_channel(SilcServer server, 
2255                                         SilcSocketConnection sock,
2256                                         SilcChannelEntry channel,
2257                                         SilcClientEntry client,
2258                                         int notify)
2259 {
2260   SilcChannelEntry ch;
2261   SilcChannelClientEntry chl;
2262   SilcBuffer clidp;
2263
2264   SILC_LOG_DEBUG(("Start"));
2265
2266   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2267
2268   /* Remove the client from the channel. The client is removed from
2269      the channel's user list. */
2270   silc_list_start(client->channels);
2271   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2272     if (chl->channel != channel)
2273       continue;
2274
2275     ch = chl->channel;
2276
2277     /* Remove channel from client's channel list */
2278     silc_list_del(client->channels, chl);
2279
2280     /* Remove channel if there is no users anymore */
2281     if (server->server_type == SILC_ROUTER &&
2282         silc_list_count(channel->user_list) < 2) {
2283       if (!silc_idlist_del_channel(server->local_list, channel))
2284         silc_idlist_del_channel(server->global_list, channel);
2285       silc_buffer_free(clidp);
2286       server->stat.my_channels--;
2287       return FALSE;
2288     }
2289
2290     /* Remove client from channel's client list */
2291     silc_list_del(channel->user_list, chl);
2292     silc_free(chl);
2293     server->stat.my_chanclients--;
2294
2295     /* If there is no global users on the channel anymore mark the channel
2296        as local channel. */
2297     if (server->server_type == SILC_SERVER &&
2298         !silc_server_channel_has_global(channel))
2299       channel->global_users = FALSE;
2300
2301     /* If there is not at least one local user on the channel then we don't
2302        need the channel entry anymore, we can remove it safely. */
2303     if (server->server_type == SILC_SERVER &&
2304         !silc_server_channel_has_local(channel)) {
2305       /* Notify about leaving client if this channel has global users. */
2306       if (notify && channel->global_users)
2307         silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2308                                            SILC_NOTIFY_TYPE_LEAVE, 1,
2309                                            clidp->data, clidp->len);
2310
2311       if (!silc_idlist_del_channel(server->local_list, channel))
2312         silc_idlist_del_channel(server->global_list, channel);
2313       silc_buffer_free(clidp);
2314       server->stat.my_channels--;
2315       return FALSE;
2316     }
2317
2318     /* Send notify to channel about client leaving the channel */
2319     if (notify)
2320       silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2321                                          SILC_NOTIFY_TYPE_LEAVE, 1,
2322                                          clidp->data, clidp->len);
2323     break;
2324   }
2325
2326   silc_buffer_free(clidp);
2327   return TRUE;
2328 }
2329
2330 /* Returns TRUE if the given client is on the channel.  FALSE if not. 
2331    This works because we assure that the user list on the channel is
2332    always in up to date thus we can only check the channel list from 
2333    `client' which is faster than checking the user list from `channel'. */
2334
2335 int silc_server_client_on_channel(SilcClientEntry client,
2336                                   SilcChannelEntry channel)
2337 {
2338   SilcChannelClientEntry chl;
2339
2340   if (!client || !channel)
2341     return FALSE;
2342
2343   silc_list_start(client->channels);
2344   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END)
2345     if (chl->channel == channel)
2346       return TRUE;
2347
2348   return FALSE;
2349 }
2350
2351 /* Timeout callback. This is called if connection is idle or for some
2352    other reason is not responding within some period of time. This 
2353    disconnects the remote end. */
2354
2355 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2356 {
2357   SilcServer server = (SilcServer)context;
2358   SilcSocketConnection sock = server->sockets[fd];
2359
2360   if (!sock)
2361     return;
2362
2363   if (sock->user_data)
2364     silc_server_free_sock_user_data(server, sock);
2365
2366   silc_server_disconnect_remote(server, sock, 
2367                                 "Server closed connection: "
2368                                 "Connection timeout");
2369 }
2370
2371 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2372    function may be used only by router. In real SILC network all channels
2373    are created by routers thus this function is never used by normal
2374    server. */
2375
2376 SilcChannelEntry silc_server_create_new_channel(SilcServer server, 
2377                                                 SilcServerID *router_id,
2378                                                 char *cipher, 
2379                                                 char *hmac,
2380                                                 char *channel_name,
2381                                                 int broadcast)
2382 {
2383   SilcChannelID *channel_id;
2384   SilcChannelEntry entry;
2385   SilcCipher key;
2386   SilcHmac newhmac;
2387
2388   SILC_LOG_DEBUG(("Creating new channel"));
2389
2390   if (!cipher)
2391     cipher = "aes-256-cbc";
2392   if (!hmac)
2393     hmac = "hmac-sha1-96";
2394
2395   /* Allocate cipher */
2396   if (!silc_cipher_alloc(cipher, &key))
2397     return NULL;
2398
2399   /* Allocate hmac */
2400   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2401     silc_cipher_free(key);
2402     return NULL;
2403   }
2404
2405   channel_name = strdup(channel_name);
2406
2407   /* Create the channel */
2408   silc_id_create_channel_id(router_id, server->rng, &channel_id);
2409   entry = silc_idlist_add_channel(server->local_list, channel_name, 
2410                                   SILC_CHANNEL_MODE_NONE, channel_id, 
2411                                   NULL, key, newhmac);
2412   if (!entry) {
2413     silc_free(channel_name);
2414     return NULL;
2415   }
2416
2417   /* Now create the actual key material */
2418   silc_server_create_channel_key(server, entry, 
2419                                  silc_cipher_get_key_len(key) / 8);
2420
2421   /* Notify other routers about the new channel. We send the packet
2422      to our primary route. */
2423   if (broadcast && server->standalone == FALSE) {
2424     silc_server_send_new_channel(server, server->router->connection, TRUE, 
2425                                  channel_name, entry->id, SILC_ID_CHANNEL_LEN);
2426   }
2427
2428   server->stat.my_channels++;
2429
2430   return entry;
2431 }
2432
2433 /* Same as above but creates the channel with Channel ID `channel_id. */
2434
2435 SilcChannelEntry 
2436 silc_server_create_new_channel_with_id(SilcServer server, 
2437                                        char *cipher, 
2438                                        char *hmac,
2439                                        char *channel_name,
2440                                        SilcChannelID *channel_id,
2441                                        int broadcast)
2442 {
2443   SilcChannelEntry entry;
2444   SilcCipher key;
2445   SilcHmac newhmac;
2446
2447   SILC_LOG_DEBUG(("Creating new channel"));
2448
2449   if (!cipher)
2450     cipher = "aes-256-cbc";
2451   if (!hmac)
2452     hmac = "hmac-sha1-96";
2453
2454   /* Allocate cipher */
2455   if (!silc_cipher_alloc(cipher, &key))
2456     return NULL;
2457
2458   /* Allocate hmac */
2459   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2460     silc_cipher_free(key);
2461     return NULL;
2462   }
2463
2464   channel_name = strdup(channel_name);
2465
2466   /* Create the channel */
2467   entry = silc_idlist_add_channel(server->local_list, channel_name, 
2468                                   SILC_CHANNEL_MODE_NONE, channel_id, 
2469                                   NULL, key, newhmac);
2470   if (!entry) {
2471     silc_free(channel_name);
2472     return NULL;
2473   }
2474
2475   /* Now create the actual key material */
2476   silc_server_create_channel_key(server, entry, 
2477                                  silc_cipher_get_key_len(key) / 8);
2478
2479   /* Notify other routers about the new channel. We send the packet
2480      to our primary route. */
2481   if (broadcast && server->standalone == FALSE) {
2482     silc_server_send_new_channel(server, server->router->connection, TRUE, 
2483                                  channel_name, entry->id, SILC_ID_CHANNEL_LEN);
2484   }
2485
2486   server->stat.my_channels++;
2487
2488   return entry;
2489 }
2490
2491 /* Generates new channel key. This is used to create the initial channel key
2492    but also to re-generate new key for channel. If `key_len' is provided
2493    it is the bytes of the key length. */
2494
2495 void silc_server_create_channel_key(SilcServer server, 
2496                                     SilcChannelEntry channel,
2497                                     unsigned int key_len)
2498 {
2499   int i;
2500   unsigned char channel_key[32], hash[32];
2501   unsigned int len;
2502
2503   if (!channel->channel_key)
2504     if (!silc_cipher_alloc("aes-256-cbc", &channel->channel_key))
2505       return;
2506
2507   if (key_len)
2508     len = key_len;
2509   else if (channel->key_len)
2510     len = channel->key_len / 8;
2511   else
2512     len = silc_cipher_get_key_len(channel->channel_key) / 8;
2513
2514   /* Create channel key */
2515   for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
2516   
2517   /* Set the key */
2518   silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
2519
2520   /* Remove old key if exists */
2521   if (channel->key) {
2522     memset(channel->key, 0, channel->key_len / 8);
2523     silc_free(channel->key);
2524   }
2525
2526   /* Save the key */
2527   channel->key_len = len * 8;
2528   channel->key = silc_calloc(len, sizeof(*channel->key));
2529   memcpy(channel->key, channel_key, len);
2530   memset(channel_key, 0, sizeof(channel_key));
2531
2532   /* Generate HMAC key from the channel key data and set it */
2533   if (!channel->hmac)
2534     silc_hmac_alloc("hmac-sha1-96", NULL, &channel->hmac);
2535   silc_hash_make(channel->hmac->hash, channel->key, len, hash);
2536   silc_hmac_set_key(channel->hmac, hash, silc_hash_len(channel->hmac->hash));
2537   memset(hash, 0, sizeof(hash));
2538 }
2539
2540 /* Saves the channel key found in the encoded `key_payload' buffer. This 
2541    function is used when we receive Channel Key Payload and also when we're
2542    processing JOIN command reply. Returns entry to the channel. */
2543
2544 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
2545                                               SilcBuffer key_payload,
2546                                               SilcChannelEntry channel)
2547 {
2548   SilcChannelKeyPayload payload = NULL;
2549   SilcChannelID *id = NULL;
2550   unsigned char *tmp, hash[32];
2551   unsigned int tmp_len;
2552   char *cipher;
2553
2554   /* Decode channel key payload */
2555   payload = silc_channel_key_payload_parse(key_payload);
2556   if (!payload) {
2557     SILC_LOG_ERROR(("Bad channel key payload, dropped"));
2558     channel = NULL;
2559     goto out;
2560   }
2561
2562   /* Get the channel entry */
2563   if (!channel) {
2564
2565     /* Get channel ID */
2566     tmp = silc_channel_key_get_id(payload, &tmp_len);
2567     id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
2568     if (!id) {
2569       channel = NULL;
2570       goto out;
2571     }
2572
2573     channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
2574     if (!channel) {
2575       channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
2576       if (!channel) {
2577         SILC_LOG_ERROR(("Received key for non-existent channel"));
2578         goto out;
2579       }
2580     }
2581   }
2582
2583   tmp = silc_channel_key_get_key(payload, &tmp_len);
2584   if (!tmp) {
2585     channel = NULL;
2586     goto out;
2587   }
2588
2589   cipher = silc_channel_key_get_cipher(payload, NULL);
2590   if (!cipher) {
2591     channel = NULL;
2592     goto out;
2593   }
2594
2595   /* Remove old key if exists */
2596   if (channel->key) {
2597     memset(channel->key, 0, channel->key_len / 8);
2598     silc_free(channel->key);
2599     silc_cipher_free(channel->channel_key);
2600   }
2601
2602   /* Create new cipher */
2603   if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
2604     channel = NULL;
2605     goto out;
2606   }
2607
2608   /* Save the key */
2609   channel->key_len = tmp_len * 8;
2610   channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
2611   memcpy(channel->key, tmp, tmp_len);
2612   silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
2613
2614   /* Generate HMAC key from the channel key data and set it */
2615   if (!channel->hmac)
2616     silc_hmac_alloc("hmac-sha1-96", NULL, &channel->hmac);
2617   silc_hash_make(channel->hmac->hash, tmp, tmp_len, hash);
2618   silc_hmac_set_key(channel->hmac, hash, silc_hash_len(channel->hmac->hash));
2619
2620   memset(hash, 0, sizeof(hash));
2621   memset(tmp, 0, tmp_len);
2622
2623  out:
2624   if (id)
2625     silc_free(id);
2626   if (payload)
2627     silc_channel_key_payload_free(payload);
2628
2629   return channel;
2630 }
2631
2632 /* Heartbeat callback. This function is set as argument for the
2633    silc_socket_set_heartbeat function. The library will call this function
2634    at the set time interval. */
2635
2636 void silc_server_perform_heartbeat(SilcSocketConnection sock,
2637                                    void *hb_context)
2638 {
2639   SilcServerHBContext hb = (SilcServerHBContext)hb_context;
2640
2641   SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname,
2642                   sock->ip));
2643
2644   /* Send the heartbeat */
2645   silc_server_send_heartbeat(hb->server, sock);
2646 }
2647
2648 /* Returns assembled of all servers in the given ID list. The packet's
2649    form is dictated by the New ID payload. */
2650
2651 static void silc_server_announce_get_servers(SilcServer server,
2652                                              SilcIDList id_list,
2653                                              SilcBuffer *servers)
2654 {
2655   SilcIDCacheList list;
2656   SilcIDCacheEntry id_cache;
2657   SilcServerEntry entry;
2658   SilcBuffer idp;
2659
2660   /* Go through all clients in the list */
2661   if (silc_idcache_find_by_id(id_list->clients, SILC_ID_CACHE_ANY, 
2662                               SILC_ID_SERVER, &list)) {
2663     if (silc_idcache_list_first(list, &id_cache)) {
2664       while (id_cache) {
2665         entry = (SilcServerEntry)id_cache->context;
2666
2667         idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
2668
2669         *servers = silc_buffer_realloc(*servers, 
2670                                        (*servers ? 
2671                                         (*servers)->truelen + idp->len : 
2672                                         idp->len));
2673         silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
2674         silc_buffer_put(*servers, idp->data, idp->len);
2675         silc_buffer_pull(*servers, idp->len);
2676         silc_buffer_free(idp);
2677
2678         if (!silc_idcache_list_next(list, &id_cache))
2679           break;
2680       }
2681     }
2682
2683     silc_idcache_list_free(list);
2684   }
2685 }
2686
2687 /* This function is used by router to announce existing servers to our
2688    primary router when we've connected to it. */
2689
2690 void silc_server_announce_servers(SilcServer server)
2691 {
2692   SilcBuffer servers = NULL;
2693
2694   SILC_LOG_DEBUG(("Announcing servers"));
2695
2696   /* Get servers in local list */
2697   silc_server_announce_get_servers(server, server->local_list, &servers);
2698
2699   /* Get servers in global list */
2700   silc_server_announce_get_servers(server, server->global_list, &servers);
2701
2702   if (servers) {
2703     silc_buffer_push(servers, servers->data - servers->head);
2704     SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
2705
2706     /* Send the packet */
2707     silc_server_packet_send(server, server->router->connection,
2708                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
2709                             servers->data, servers->len, TRUE);
2710
2711     silc_buffer_free(servers);
2712   }
2713 }
2714
2715 /* Returns assembled packet of all clients in the given ID list. The
2716    packet's form is dictated by the New ID Payload. */
2717
2718 static void silc_server_announce_get_clients(SilcServer server,
2719                                              SilcIDList id_list,
2720                                              SilcBuffer *clients)
2721 {
2722   SilcIDCacheList list;
2723   SilcIDCacheEntry id_cache;
2724   SilcClientEntry client;
2725   SilcBuffer idp;
2726
2727   /* Go through all clients in the list */
2728   if (silc_idcache_find_by_id(id_list->clients, SILC_ID_CACHE_ANY, 
2729                               SILC_ID_CLIENT, &list)) {
2730     if (silc_idcache_list_first(list, &id_cache)) {
2731       while (id_cache) {
2732         client = (SilcClientEntry)id_cache->context;
2733
2734         idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2735
2736         *clients = silc_buffer_realloc(*clients, 
2737                                        (*clients ? 
2738                                         (*clients)->truelen + idp->len : 
2739                                         idp->len));
2740         silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
2741         silc_buffer_put(*clients, idp->data, idp->len);
2742         silc_buffer_pull(*clients, idp->len);
2743         silc_buffer_free(idp);
2744
2745         if (!silc_idcache_list_next(list, &id_cache))
2746           break;
2747       }
2748     }
2749
2750     silc_idcache_list_free(list);
2751   }
2752 }
2753
2754 /* This function is used to announce our existing clients to our router
2755    when we've connected to it. */
2756
2757 void silc_server_announce_clients(SilcServer server)
2758 {
2759   SilcBuffer clients = NULL;
2760
2761   SILC_LOG_DEBUG(("Announcing clients"));
2762
2763   /* Get clients in local list */
2764   silc_server_announce_get_clients(server, server->local_list,
2765                                    &clients);
2766
2767   /* As router we announce our global list as well */
2768   if (server->server_type == SILC_ROUTER)
2769     silc_server_announce_get_clients(server, server->global_list,
2770                                      &clients);
2771
2772   if (clients) {
2773     silc_buffer_push(clients, clients->data - clients->head);
2774     SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
2775
2776     /* Send the packet */
2777     silc_server_packet_send(server, server->router->connection,
2778                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
2779                             clients->data, clients->len, TRUE);
2780
2781     silc_buffer_free(clients);
2782   }
2783 }
2784
2785 static SilcBuffer 
2786 silc_server_announce_encode_join(unsigned int argc, ...)
2787 {
2788   va_list ap;
2789
2790   va_start(ap, argc);
2791   return silc_notify_payload_encode(SILC_NOTIFY_TYPE_JOIN, argc, ap);
2792 }
2793
2794 /* Returns assembled packets for all channels and users on those channels
2795    from the given ID List. The packets are in the form dictated by the
2796    New Channel and New Channel User payloads. */
2797
2798 static void silc_server_announce_get_channels(SilcServer server,
2799                                               SilcIDList id_list,
2800                                               SilcBuffer *channels,
2801                                               SilcBuffer *channel_users)
2802 {
2803   SilcIDCacheList list;
2804   SilcIDCacheEntry id_cache;
2805   SilcChannelEntry channel;
2806   SilcChannelClientEntry chl;
2807   SilcBuffer chidp;
2808   unsigned char *cid;
2809   unsigned short name_len;
2810   int len;
2811
2812   /* Go through all channels in the list */
2813   if (silc_idcache_find_by_id(id_list->channels, SILC_ID_CACHE_ANY, 
2814                               SILC_ID_CHANNEL, &list)) {
2815     if (silc_idcache_list_first(list, &id_cache)) {
2816       while (id_cache) {
2817         channel = (SilcChannelEntry)id_cache->context;
2818         
2819         cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
2820         name_len = strlen(channel->channel_name);
2821
2822         len = 4 + name_len + SILC_ID_CHANNEL_LEN;
2823         *channels = 
2824           silc_buffer_realloc(*channels, 
2825                               (*channels ? (*channels)->truelen + len : len));
2826         silc_buffer_pull_tail(*channels, 
2827                               ((*channels)->end - (*channels)->data));
2828         silc_buffer_format(*channels,
2829                            SILC_STR_UI_SHORT(name_len),
2830                            SILC_STR_UI_XNSTRING(channel->channel_name, 
2831                                                 name_len),
2832                            SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
2833                            SILC_STR_UI_XNSTRING(cid, SILC_ID_CHANNEL_LEN),
2834                            SILC_STR_END);
2835         silc_buffer_pull(*channels, len);
2836
2837         /* Now find all users on the channel */
2838         chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
2839         silc_list_start(channel->user_list);
2840         while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2841           SilcBuffer clidp;
2842           SilcBuffer tmp;
2843
2844           clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
2845
2846           tmp = silc_server_announce_encode_join(2, clidp->data, clidp->len,
2847                                                  chidp->data, chidp->len);
2848           len = tmp->len;
2849           *channel_users = 
2850             silc_buffer_realloc(*channel_users, 
2851                                 (*channel_users ? 
2852                                  (*channel_users)->truelen + len : len));
2853           silc_buffer_pull_tail(*channel_users, 
2854                                 ((*channel_users)->end - 
2855                                  (*channel_users)->data));
2856
2857           silc_buffer_put(*channel_users, tmp->data, tmp->len);
2858           silc_buffer_pull(*channel_users, len);
2859           silc_buffer_free(clidp);
2860           silc_buffer_free(tmp);
2861         }
2862         silc_buffer_free(chidp);
2863
2864         silc_free(cid);
2865
2866         if (!silc_idcache_list_next(list, &id_cache))
2867           break;
2868       }
2869     }
2870
2871     silc_idcache_list_free(list);
2872   }
2873 }
2874
2875 /* This function is used to announce our existing channels to our router
2876    when we've connected to it. This also announces the users on the
2877    channels to the router. */
2878
2879 void silc_server_announce_channels(SilcServer server)
2880 {
2881   SilcBuffer channels = NULL, channel_users = NULL;
2882
2883   SILC_LOG_DEBUG(("Announcing channels and channel users"));
2884
2885   /* Get channels and channel users in local list */
2886   silc_server_announce_get_channels(server, server->local_list,
2887                                     &channels, &channel_users);
2888
2889   /* Get channels and channel users in global list */
2890   silc_server_announce_get_channels(server, server->global_list,
2891                                     &channels, &channel_users);
2892
2893   if (channels) {
2894     silc_buffer_push(channels, channels->data - channels->head);
2895     SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
2896
2897     /* Send the packet */
2898     silc_server_packet_send(server, server->router->connection,
2899                             SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
2900                             channels->data, channels->len,
2901                             FALSE);
2902
2903     silc_buffer_free(channels);
2904   }
2905
2906   if (channel_users) {
2907     silc_buffer_push(channel_users, channel_users->data - channel_users->head);
2908     SILC_LOG_HEXDUMP(("channel users"), channel_users->data, 
2909                      channel_users->len);
2910
2911     /* Send the packet */
2912     silc_server_packet_send(server, server->router->connection,
2913                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
2914                             channel_users->data, channel_users->len,
2915                             FALSE);
2916
2917     silc_buffer_free(channel_users);
2918   }
2919 }
2920
2921 /* Failure timeout callback. If this is called then we will immediately
2922    process the received failure. We always process the failure with timeout
2923    since we do not want to blindly trust to received failure packets. 
2924    This won't be called (the timeout is cancelled) if the failure was
2925    bogus (it is bogus if remote does not close the connection after sending
2926    the failure). */
2927
2928 SILC_TASK_CALLBACK(silc_server_failure_callback)
2929 {
2930   SilcServerFailureContext f = (SilcServerFailureContext)context;
2931
2932   if (f->sock->protocol) {
2933     f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
2934     f->sock->protocol->execute(f->server->timeout_queue, 0,
2935                                f->sock->protocol, f->sock->sock, 0, 0);
2936   }
2937
2938   silc_free(f);
2939 }
2940
2941 /* Assembles user list and users mode list from the `channel'. */
2942
2943 void silc_server_get_users_on_channel(SilcServer server,
2944                                       SilcChannelEntry channel,
2945                                       SilcBuffer *user_list,
2946                                       SilcBuffer *mode_list,
2947                                       unsigned int *user_count)
2948 {
2949   SilcChannelClientEntry chl;
2950   SilcBuffer client_id_list;
2951   SilcBuffer client_mode_list;
2952   SilcBuffer idp;
2953   unsigned int list_count = 0;
2954
2955   client_id_list = silc_buffer_alloc((SILC_ID_CLIENT_LEN + 4) * 
2956                                      silc_list_count(channel->user_list));
2957   client_mode_list = silc_buffer_alloc(4 * 
2958                                        silc_list_count(channel->user_list));
2959   silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
2960   silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
2961   silc_list_start(channel->user_list);
2962   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2963     /* Client ID */
2964     idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
2965     silc_buffer_put(client_id_list, idp->data, idp->len);
2966     silc_buffer_pull(client_id_list, idp->len);
2967     silc_buffer_free(idp);
2968
2969     /* Client's mode on channel */
2970     SILC_PUT32_MSB(chl->mode, client_mode_list->data);
2971     silc_buffer_pull(client_mode_list, 4);
2972
2973     list_count++;
2974   }
2975   silc_buffer_push(client_id_list, 
2976                    client_id_list->data - client_id_list->head);
2977   silc_buffer_push(client_mode_list, 
2978                    client_mode_list->data - client_mode_list->head);
2979
2980   *user_list = client_id_list;
2981   *mode_list = client_mode_list;
2982   *user_count = list_count;
2983 }
2984
2985 /* Saves users and their modes to the `channel'. */
2986
2987 void silc_server_save_users_on_channel(SilcServer server,
2988                                        SilcSocketConnection sock,
2989                                        SilcChannelEntry channel,
2990                                        SilcClientID *noadd,
2991                                        SilcBuffer user_list,
2992                                        SilcBuffer mode_list,
2993                                        unsigned int user_count)
2994 {
2995   int i;
2996
2997   /* Cache the received Client ID's and modes. This cache expires
2998      whenever server sends notify message to channel. It means two things;
2999      some user has joined or leaved the channel. XXX TODO! */
3000   for (i = 0; i < user_count; i++) {
3001     unsigned short idp_len;
3002     unsigned int mode;
3003     SilcClientID *client_id;
3004     SilcClientEntry client;
3005
3006     /* Client ID */
3007     SILC_GET16_MSB(idp_len, user_list->data + 2);
3008     idp_len += 4;
3009     client_id = silc_id_payload_parse_id(user_list->data, idp_len);
3010     silc_buffer_pull(user_list, idp_len);
3011     if (!client_id)
3012       continue;
3013
3014     /* Mode */
3015     SILC_GET32_MSB(mode, mode_list->data);
3016     silc_buffer_pull(mode_list, 4);
3017
3018     if (noadd && !SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3019       silc_free(client_id);
3020       continue;
3021     }
3022     
3023     /* Check if we have this client cached already. */
3024     client = silc_idlist_find_client_by_id(server->local_list, client_id,
3025                                            NULL);
3026     if (!client)
3027       client = silc_idlist_find_client_by_id(server->global_list, 
3028                                              client_id, NULL);
3029     if (!client) {
3030       /* If router did not find such Client ID in its lists then this must
3031          be bogus client or some router in the net is buggy. */
3032       if (server->server_type == SILC_ROUTER) {
3033         silc_free(client_id);
3034         continue;
3035       }
3036
3037       /* We don't have that client anywhere, add it. The client is added
3038          to global list since server didn't have it in the lists so it must be 
3039          global. */
3040       client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL, 
3041                                       silc_id_dup(client_id, SILC_ID_CLIENT), 
3042                                       sock->user_data, NULL);
3043       if (!client) {
3044         silc_free(client_id);
3045         continue;
3046       }
3047     }
3048
3049     silc_free(client_id);
3050
3051     if (!silc_server_client_on_channel(client, channel)) {
3052       /* Client was not on the channel, add it. */
3053       SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3054       chl->client = client;
3055       chl->mode = mode;
3056       chl->channel = channel;
3057       silc_list_add(channel->user_list, chl);
3058       silc_list_add(client->channels, chl);
3059     }
3060   }
3061 }