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