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