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