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