Added silc_server_send_opers[_notify] to send packets to operators.
[runtime.git] / apps / silcd / server.c
1 /*
2
3   server.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 1997 - 2002 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_rehash_close_connection);
32 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry);
33 SILC_TASK_CALLBACK(silc_server_connect_router);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router);
35 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
36 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
38 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
39 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
40 SILC_TASK_CALLBACK(silc_server_packet_process);
41 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
42 SILC_TASK_CALLBACK(silc_server_close_connection_final);
43 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout);
44 SILC_TASK_CALLBACK(silc_server_timeout_remote);
45 SILC_TASK_CALLBACK(silc_server_channel_key_rekey);
46 SILC_TASK_CALLBACK(silc_server_failure_callback);
47 SILC_TASK_CALLBACK(silc_server_rekey_callback);
48 SILC_TASK_CALLBACK(silc_server_get_stats);
49
50 /* Allocates a new SILC server object. This has to be done before the server
51    can be used. After allocation one must call silc_server_init to initialize
52    the server. The new allocated server object is returned to the new_server
53    argument. */
54
55 int silc_server_alloc(SilcServer *new_server)
56 {
57   SilcServer server;
58
59   SILC_LOG_DEBUG(("Allocating new server object"));
60
61   server = silc_calloc(1, sizeof(*server));
62   server->server_type = SILC_SERVER;
63   server->standalone = TRUE;
64   server->local_list = silc_calloc(1, sizeof(*server->local_list));
65   server->global_list = silc_calloc(1, sizeof(*server->global_list));
66   server->pending_commands = silc_dlist_init();
67 #ifdef SILC_SIM
68   server->sim = silc_dlist_init();
69 #endif
70
71   *new_server = server;
72
73   return TRUE;
74 }
75
76 /* Free's the SILC server object. This is called at the very end before
77    the program ends. */
78
79 void silc_server_free(SilcServer server)
80 {
81   if (!server)
82     return;
83
84 #ifdef SILC_SIM
85   {
86     SilcSim sim;
87     
88     while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
89       silc_dlist_del(server->sim, sim);
90       silc_sim_free(sim);
91     }
92     silc_dlist_uninit(server->sim);
93   }
94 #endif
95
96   silc_server_config_unref(&server->config_ref);
97   if (server->rng)
98     silc_rng_free(server->rng);
99   if (server->pkcs)
100     silc_pkcs_free(server->pkcs);
101   if (server->public_key)
102     silc_pkcs_public_key_free(server->public_key);
103   if (server->private_key)
104     silc_pkcs_private_key_free(server->private_key);
105   if (server->pending_commands)
106     silc_dlist_uninit(server->pending_commands);
107   if (server->id_entry)
108     silc_idlist_del_server(server->local_list, server->id_entry);
109
110   silc_idcache_free(server->local_list->clients);
111   silc_idcache_free(server->local_list->servers);
112   silc_idcache_free(server->local_list->channels);
113   silc_idcache_free(server->global_list->clients);
114   silc_idcache_free(server->global_list->servers);
115   silc_idcache_free(server->global_list->channels);
116   silc_hash_table_free(server->watcher_list);
117
118   silc_hash_free(server->md5hash);
119   silc_hash_free(server->sha1hash);
120   silc_hmac_unregister_all();
121   silc_hash_unregister_all();
122   silc_cipher_unregister_all();
123   silc_pkcs_unregister_all();
124
125   silc_free(server->local_list);
126   silc_free(server->global_list);
127   silc_free(server->server_name);
128   silc_free(server->id_string);
129   silc_free(server->purge_i);
130   silc_free(server->purge_g);
131   silc_free(server);
132 }
133
134 /* Creates a new server listener. */
135
136 static bool silc_server_listen(SilcServer server, const char *server_ip,
137                                SilcUInt16 port, int *sock)
138 {
139   *sock = silc_net_create_server(port, server_ip);
140   if (*sock < 0) {
141     SILC_LOG_ERROR(("Could not create server listener: %s on %hu",
142                         server_ip, port));
143     return FALSE;
144   }
145   return TRUE;
146 }
147
148 /* Adds a secondary listener. */
149
150 bool silc_server_init_secondary(SilcServer server)
151 {
152   int sock = 0, sock_list[server->config->param.connections_max];
153   SilcSocketConnection newsocket = NULL;
154   SilcServerConfigServerInfoInterface *interface;
155
156   for (interface = server->config->server_info->secondary; interface; 
157         interface = interface->next, sock++) {
158
159     if (!silc_server_listen(server,
160         interface->server_ip, interface->port, &sock_list[sock]))
161       goto err;
162
163     /* Set socket to non-blocking mode */
164     silc_net_set_socket_nonblock(sock_list[sock]);
165
166     /* Add ourselves also to the socket table. The entry allocated above
167        is sent as argument for fast referencing in the future. */
168     silc_socket_alloc(sock_list[sock],
169                       SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
170     server->sockets[sock_list[sock]] = newsocket;
171     SILC_SET_LISTENER(newsocket);
172
173     /* Perform name and address lookups to resolve the listenning address
174        and port. */
175     if (!silc_net_check_local_by_sock(sock_list[sock], &newsocket->hostname,
176                             &newsocket->ip)) {
177       if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
178         !newsocket->ip) {
179         SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
180                       newsocket->hostname ? newsocket->hostname :
181                       newsocket->ip ? newsocket->ip : ""));
182         server->stat.conn_failures++;
183         goto err;
184       }
185       if (!newsocket->hostname)
186         newsocket->hostname = strdup(newsocket->ip);
187     }
188     newsocket->port = silc_net_get_local_port(sock);
189
190     newsocket->user_data = (void *)server->id_entry;
191     silc_schedule_task_add(server->schedule, sock_list[sock],
192                          silc_server_accept_new_connection,
193                          (void *)server, 0, 0,
194                          SILC_TASK_FD,
195                          SILC_TASK_PRI_NORMAL);
196   }
197
198   return TRUE;
199
200  err:
201   do silc_net_close_server(sock_list[sock--]); while (sock >= 0);
202   return FALSE;
203 }
204
205 /* Initializes the entire SILC server. This is called always before running
206    the server. This is called only once at the initialization of the program.
207    This binds the server to its listenning port. After this function returns
208    one should call silc_server_run to start the server. This returns TRUE
209    when everything is ok to run the server. Configuration file must be
210    read and parsed before calling this. */
211
212 bool silc_server_init(SilcServer server)
213 {
214   int sock;
215   SilcServerID *id;
216   SilcServerEntry id_entry;
217   SilcIDListPurge purge;
218   SilcSocketConnection newsocket = NULL;
219
220   SILC_LOG_DEBUG(("Initializing server"));
221
222   server->starttime = time(NULL);
223
224   /* Take config object for us */
225   silc_server_config_ref(&server->config_ref, server->config, 
226                          server->config);
227
228   /* Steal public and private key from the config object */
229   server->public_key = server->config->server_info->public_key;
230   server->private_key = server->config->server_info->private_key;
231   server->config->server_info->public_key = NULL;
232   server->config->server_info->private_key = NULL;
233
234   /* Register all configured ciphers, PKCS and hash functions. */
235   if (!silc_server_config_register_ciphers(server))
236     silc_cipher_register_default();
237   if (!silc_server_config_register_pkcs(server))
238     silc_pkcs_register_default();
239   if (!silc_server_config_register_hashfuncs(server))
240     silc_hash_register_default();
241   if (!silc_server_config_register_hmacs(server))
242     silc_hmac_register_default();
243
244   /* Initialize random number generator for the server. */
245   server->rng = silc_rng_alloc();
246   silc_rng_init(server->rng);
247   silc_rng_global_init(server->rng);
248
249   /* Initialize hash functions for server to use */
250   silc_hash_alloc("md5", &server->md5hash);
251   silc_hash_alloc("sha1", &server->sha1hash);
252
253   /* Allocate PKCS context for local public and private keys */
254   if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
255     goto err;
256   silc_pkcs_public_key_set(server->pkcs, server->public_key);
257   silc_pkcs_private_key_set(server->pkcs, server->private_key);
258
259   /* Initialize the scheduler */
260   server->schedule = silc_schedule_init(server->config->param.connections_max);
261   if (!server->schedule)
262     goto err;
263
264   /* First, register log files configuration for error output */
265   silc_server_config_setlogfiles(server);
266
267   /* Initialize ID caches */
268   server->local_list->clients =
269     silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
270   server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
271   server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
272
273   /* These are allocated for normal server as well as these hold some
274      global information that the server has fetched from its router. For
275      router these are used as they are supposed to be used on router. */
276   server->global_list->clients =
277     silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
278   server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
279   server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
280
281   /* Init watcher list */
282   server->watcher_list = 
283     silc_hash_table_alloc(1, silc_hash_client_id_hash, NULL,
284                           silc_hash_data_compare, (void *)CLIENTID_HASH_LEN,
285                           NULL, NULL, TRUE);
286   if (!server->watcher_list)
287     goto err;
288
289   /* Create a listening server */
290   if (!silc_server_listen(server,
291                 server->config->server_info->primary == NULL ? NULL :
292                         server->config->server_info->primary->server_ip,
293                 server->config->server_info->primary == NULL ? 0 :
294                         server->config->server_info->primary->port,
295                 &sock))
296     goto err;
297
298   /* Set socket to non-blocking mode */
299   silc_net_set_socket_nonblock(sock);
300   server->sock = sock;
301
302   /* Allocate the entire socket list that is used in server. Eventually
303      all connections will have entry in this table (it is a table of
304      pointers to the actual object that is allocated individually
305      later). */
306   server->sockets = silc_calloc(server->config->param.connections_max,
307                                 sizeof(*server->sockets));
308   if (!server->sockets)
309     goto err;
310
311   /* Add ourselves also to the socket table. The entry allocated above
312      is sent as argument for fast referencing in the future. */
313   silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
314   server->sockets[sock] = newsocket;
315   SILC_SET_LISTENER(newsocket);
316
317   /* Perform name and address lookups to resolve the listenning address
318      and port. */
319   if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
320                                     &newsocket->ip)) {
321     if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
322         !newsocket->ip) {
323       SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
324                       newsocket->hostname ? newsocket->hostname :
325                       newsocket->ip ? newsocket->ip : ""));
326       server->stat.conn_failures++;
327       goto err;
328     }
329     if (!newsocket->hostname)
330       newsocket->hostname = strdup(newsocket->ip);
331   }
332   newsocket->port = silc_net_get_local_port(sock);
333
334   /* Create a Server ID for the server. */
335   silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
336   if (!id)
337     goto err;
338
339   server->id = id;
340   server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
341   server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
342   server->server_name = server->config->server_info->server_name;
343   server->config->server_info->server_name = NULL;
344
345   /* Add ourselves to the server list. We don't have a router yet
346      beacuse we haven't established a route yet. It will be done later.
347      For now, NULL is sent as router. This allocates new entry to
348      the ID list. */
349   id_entry =
350     silc_idlist_add_server(server->local_list, strdup(server->server_name),
351                            server->server_type, server->id, NULL, NULL);
352   if (!id_entry) {
353     SILC_LOG_ERROR(("Could not add ourselves to cache"));
354     goto err;
355   }
356   id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
357
358   /* Put the allocated socket pointer also to the entry allocated above
359      for fast back-referencing to the socket list. */
360   newsocket->user_data = (void *)id_entry;
361   id_entry->connection = (void *)newsocket;
362   server->id_entry = id_entry;
363
364   /* Register protocols */
365   silc_server_protocols_register();
366
367   /* Add the first task to the scheduler. This is task that is executed by
368      timeout. It expires as soon as the caller calls silc_server_run. This
369      task performs authentication protocol and key exchange with our
370      primary router. */
371   silc_schedule_task_add(server->schedule, 0,
372                          silc_server_connect_to_router,
373                          (void *)server, 0, 1,
374                          SILC_TASK_TIMEOUT,
375                          SILC_TASK_PRI_NORMAL);
376
377   /* Add listener task to the scheduler. This task receives new connections
378      to the server. This task remains on the queue until the end of the
379      program. */
380   silc_schedule_task_add(server->schedule, sock,
381                          silc_server_accept_new_connection,
382                          (void *)server, 0, 0,
383                          SILC_TASK_FD,
384                          SILC_TASK_PRI_NORMAL);
385
386   if (silc_server_init_secondary(server) == FALSE)
387     goto err;
388   
389   server->listenning = TRUE;
390
391   /* If server connections has been configured then we must be router as
392      normal server cannot have server connections, only router connections. */
393   if (server->config->servers) {
394     SilcServerConfigServer *ptr = server->config->servers;
395
396     server->server_type = SILC_ROUTER;
397     while (ptr) {
398       if (ptr->backup_router) {
399         server->server_type = SILC_BACKUP_ROUTER;
400         server->backup_router = TRUE;
401         server->id_entry->server_type = SILC_BACKUP_ROUTER;
402         break;
403       }
404       ptr = ptr->next;
405     }
406   }
407
408   /* Register the ID Cache purge task. This periodically purges the ID cache
409      and removes the expired cache entries. */
410
411   /* Clients local list */
412   server->purge_i = purge = silc_calloc(1, sizeof(*purge));
413   purge->cache = server->local_list->clients;
414   purge->schedule = server->schedule;
415   purge->timeout = 600;
416   silc_schedule_task_add(purge->schedule, 0,
417                          silc_idlist_purge,
418                          (void *)purge, purge->timeout, 0,
419                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
420
421   /* Clients global list */
422   server->purge_g = purge = silc_calloc(1, sizeof(*purge));
423   purge->cache = server->global_list->clients;
424   purge->schedule = server->schedule;
425   purge->timeout = 300;
426   silc_schedule_task_add(purge->schedule, 0,
427                          silc_idlist_purge,
428                          (void *)purge, purge->timeout, 0,
429                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
430
431   /* If we are normal server we'll retrieve network statisticial information
432      once in a while from the router. */
433   if (server->server_type == SILC_SERVER)
434     silc_schedule_task_add(purge->schedule, 0, silc_server_get_stats,
435                            server, 10, 0, SILC_TASK_TIMEOUT,
436                            SILC_TASK_PRI_LOW);
437
438   if (server->server_type == SILC_ROUTER)
439     server->stat.routers++;
440
441   SILC_LOG_DEBUG(("Server initialized"));
442
443   /* We are done here, return succesfully */
444   return TRUE;
445
446  err:
447   silc_server_config_unref(&server->config_ref);
448   silc_net_close_server(sock);
449   return FALSE;
450 }
451
452 /* Task callback to close a socket connection after rehash */
453
454 SILC_TASK_CALLBACK(silc_server_rehash_close_connection)
455 {
456   SilcServer server = context;
457   SilcSocketConnection sock = server->sockets[fd];
458
459   if (!sock)
460     return;
461
462   SILC_LOG_INFO(("Closing connection %s:%d [%s]: connection is unconfigured",
463                  sock->hostname, sock->port,
464                  (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
465                   sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
466                   sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
467                   "Router")));
468   silc_schedule_task_del_by_context(server->schedule, sock);
469   silc_server_disconnect_remote(server, sock,
470                                 SILC_STATUS_ERR_BANNED_FROM_SERVER,
471                                 "This connection is removed from "
472                                 "configuration");
473   if (sock->user_data)
474     silc_server_free_sock_user_data(server, sock, NULL);
475 }
476
477 /* This function basically reads the config file again and switches the config
478    object pointed by the server object. After that, we have to fix various
479    things such as the server_name and the listening ports.
480    Keep in mind that we no longer have the root privileges at this point. */
481
482 bool silc_server_rehash(SilcServer server)
483 {
484   SilcServerConfig newconfig;
485
486   SILC_LOG_INFO(("Rehashing server"));
487
488   /* Reset the logging system */
489   silc_log_quick = TRUE;
490   silc_log_flush_all();
491
492   /* Start the main rehash phase (read again the config file) */
493   newconfig = silc_server_config_alloc(server->config_file);
494   if (!newconfig) {
495     SILC_LOG_ERROR(("Rehash FAILED."));
496     return FALSE;
497   }
498
499   /* Reinit scheduler if necessary */
500   if (newconfig->param.connections_max > server->config->param.connections_max)
501     if (!silc_schedule_reinit(server->schedule, 
502                               newconfig->param.connections_max))
503       return FALSE;
504
505   /* Fix the server_name field */
506   if (strcmp(server->server_name, newconfig->server_info->server_name)) {
507     silc_free(server->server_name);
508     server->server_name = newconfig->server_info->server_name;
509     newconfig->server_info->server_name = NULL;
510
511     /* Update the idcache list with a fresh pointer */
512     silc_free(server->id_entry->server_name);
513     server->id_entry->server_name = strdup(server->server_name);
514     if (!silc_idcache_del_by_context(server->local_list->servers, 
515                                      server->id_entry))
516       return FALSE;
517     if (!silc_idcache_add(server->local_list->servers,
518                           server->id_entry->server_name,
519                           server->id_entry->id, server->id_entry, 0, NULL))
520       return FALSE;
521   }
522
523   /* Set logging */
524   silc_server_config_setlogfiles(server);
525
526   /* Change new key pair if necessary */
527   if (newconfig->server_info->public_key &&
528       !silc_pkcs_public_key_compare(server->public_key,
529                                     newconfig->server_info->public_key)) {
530     silc_pkcs_public_key_free(server->public_key);
531     silc_pkcs_private_key_free(server->private_key);
532     server->public_key = newconfig->server_info->public_key;
533     server->private_key = newconfig->server_info->private_key;
534     newconfig->server_info->public_key = NULL;
535     newconfig->server_info->private_key = NULL;
536
537     /* Allocate PKCS context for local public and private keys */
538     silc_pkcs_free(server->pkcs);
539     if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
540       return FALSE;
541     silc_pkcs_public_key_set(server->pkcs, server->public_key);
542     silc_pkcs_private_key_set(server->pkcs, server->private_key);
543   }
544
545   /* Check for unconfigured server and router connections and close
546      connections that were unconfigured. */
547
548   if (server->config->routers) {
549     SilcServerConfigRouter *ptr;
550     SilcServerConfigRouter *newptr;
551     bool found;
552
553     for (ptr = server->config->routers; ptr; ptr = ptr->next) {
554       found = FALSE;
555
556       /* Check whether new config has this one too */
557       for (newptr = newconfig->routers; newptr; newptr = newptr->next) {
558         if (!strcmp(newptr->host, ptr->host) && newptr->port == ptr->port &&
559             newptr->initiator == ptr->initiator) {
560           found = TRUE;
561           break;
562         }
563       }
564
565       if (!found) {
566         /* Remove this connection */
567         SilcSocketConnection sock;
568         sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_ROUTER,
569                                                ptr->host, ptr->port);
570         if (sock && !SILC_IS_LISTENER(sock))
571           silc_schedule_task_add(server->schedule, sock->sock,
572                                  silc_server_rehash_close_connection,
573                                  server, 0, 1, SILC_TASK_TIMEOUT,
574                                  SILC_TASK_PRI_NORMAL);
575       }
576     }
577   }
578
579   if (server->config->servers) {
580     SilcServerConfigServer *ptr;
581     SilcServerConfigServer *newptr;
582     bool found;
583
584     for (ptr = server->config->servers; ptr; ptr = ptr->next) {
585       found = FALSE;
586
587       /* Check whether new config has this one too */
588       for (newptr = newconfig->servers; newptr; newptr = newptr->next) {
589         if (!strcmp(newptr->host, ptr->host)) {
590           found = TRUE;
591           break;
592         }
593       }
594
595       if (!found) {
596         /* Remove this connection */
597         SilcSocketConnection sock;
598         sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_SERVER,
599                                                ptr->host, 0);
600         if (sock && !SILC_IS_LISTENER(sock))
601           silc_schedule_task_add(server->schedule, sock->sock,
602                                  silc_server_rehash_close_connection,
603                                  server, 0, 1, SILC_TASK_TIMEOUT,
604                                  SILC_TASK_PRI_NORMAL);
605       }
606     }
607   }
608
609   /* Go through all configured routers after rehash */
610   silc_schedule_task_add(server->schedule, 0,
611                          silc_server_connect_to_router,
612                          (void *)server, 0, 1,
613                          SILC_TASK_TIMEOUT,
614                          SILC_TASK_PRI_NORMAL);
615
616   /* Check whether our router status has changed */
617   if (newconfig->servers) {
618     SilcServerConfigServer *ptr = newconfig->servers;
619
620     server->server_type = SILC_ROUTER;
621     while (ptr) {
622       if (ptr->backup_router) {
623         server->server_type = SILC_BACKUP_ROUTER;
624         server->backup_router = TRUE;
625         server->id_entry->server_type = SILC_BACKUP_ROUTER;
626         break;
627       }
628       ptr = ptr->next;
629     }
630   }
631
632   /* Our old config is gone now. We'll unreference our reference made in
633      silc_server_init and then destroy it since we are destroying it
634      underneath the application (layer which called silc_server_init). */
635   silc_server_config_unref(&server->config_ref);
636   silc_server_config_destroy(server->config);
637
638   /* Take new config context */
639   server->config = newconfig;
640   silc_server_config_ref(&server->config_ref, server->config, server->config);
641
642   SILC_LOG_DEBUG(("Server rehashed"));
643
644   return TRUE;
645 }
646
647 /* The heart of the server. This runs the scheduler thus runs the server.
648    When this returns the server has been stopped and the program will
649    be terminated. */
650
651 void silc_server_run(SilcServer server)
652 {
653   SILC_LOG_INFO(("SILC Server started"));
654
655   /* Start the scheduler, the heart of the SILC server. When this returns
656      the program will be terminated. */
657   silc_schedule(server->schedule);
658 }
659
660 /* Stops the SILC server. This function is used to shutdown the server.
661    This is usually called after the scheduler has returned. After stopping
662    the server one should call silc_server_free. */
663
664 void silc_server_stop(SilcServer server)
665 {
666   SILC_LOG_DEBUG(("Stopping server"));
667
668   if (server->schedule) {
669     int i;
670
671     /* Close all connections */
672     for (i = 0; i < server->config->param.connections_max; i++) {
673       if (!server->sockets[i])
674         continue;
675       if (!SILC_IS_LISTENER(server->sockets[i])) {
676         silc_schedule_task_del_by_context(server->schedule,
677                                           server->sockets[i]);
678         silc_server_disconnect_remote(server, server->sockets[i], 
679                                       SILC_STATUS_OK, 
680                                       "Server is shutting down");
681       } else {
682         silc_socket_free(server->sockets[i]);
683         server->sockets[i] = NULL;
684       }
685     }
686
687     /* We are not connected to network anymore */
688     server->standalone = TRUE;
689
690     silc_schedule_stop(server->schedule);
691     silc_schedule_uninit(server->schedule);
692     server->schedule = NULL;
693
694     silc_free(server->sockets);
695     server->sockets = NULL;
696   }
697
698   silc_server_protocols_unregister();
699
700   SILC_LOG_DEBUG(("Server stopped"));
701 }
702
703 /* Function that is called when the network connection to a router has
704    been established.  This will continue with the key exchange protocol
705    with the remote router. */
706
707 void silc_server_start_key_exchange(SilcServer server,
708                                     SilcServerConnection sconn,
709                                     int sock)
710 {
711   SilcSocketConnection newsocket;
712   SilcProtocol protocol;
713   SilcServerKEInternalContext *proto_ctx;
714   SilcServerConfigRouter *conn =
715     (SilcServerConfigRouter *) sconn->conn.ref_ptr;
716   void *context;
717
718   /* Cancel any possible retry timeouts */
719   silc_schedule_task_del_by_callback(server->schedule,
720                                      silc_server_connect_to_router_retry);
721
722   /* Set socket options */
723   silc_net_set_socket_nonblock(sock);
724   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
725
726   /* Create socket connection for the connection. Even though we
727      know that we are connecting to a router we will mark the socket
728      to be unknown connection until we have executed authentication
729      protocol. */
730   silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
731   server->sockets[sock] = newsocket;
732   newsocket->hostname = strdup(sconn->remote_host);
733   newsocket->ip = strdup(sconn->remote_host);
734   newsocket->port = sconn->remote_port;
735   sconn->sock = newsocket;
736
737   /* Allocate internal protocol context. This is sent as context
738      to the protocol. */
739   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
740   proto_ctx->server = (void *)server;
741   proto_ctx->context = (void *)sconn;
742   proto_ctx->sock = newsocket;
743   proto_ctx->rng = server->rng;
744   proto_ctx->responder = FALSE;
745
746   /* Set Key Exchange flags from configuration, but fall back to global
747      settings too. */
748   SILC_GET_SKE_FLAGS(conn, proto_ctx);
749   if (server->config->param.key_exchange_pfs)
750     proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
751
752   /* Perform key exchange protocol. silc_server_connect_to_router_second
753      will be called after the protocol is finished. */
754   silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
755                       &protocol, proto_ctx,
756                       silc_server_connect_to_router_second);
757   newsocket->protocol = protocol;
758
759   /* Register a timeout task that will be executed if the protocol
760      is not executed within set limit. */
761   proto_ctx->timeout_task =
762     silc_schedule_task_add(server->schedule, sock,
763                            silc_server_timeout_remote,
764                            server, server->config->key_exchange_timeout, 0,
765                            SILC_TASK_TIMEOUT,
766                            SILC_TASK_PRI_LOW);
767
768   /* Register the connection for network input and output. This sets
769      that scheduler will listen for incoming packets for this connection
770      and sets that outgoing packets may be sent to this connection as
771      well. However, this doesn't set the scheduler for outgoing traffic,
772      it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
773      later when outgoing data is available. */
774   context = (void *)server;
775   SILC_REGISTER_CONNECTION_FOR_IO(sock);
776
777   /* Run the protocol */
778   silc_protocol_execute(protocol, server->schedule, 0, 0);
779 }
780
781 /* Timeout callback that will be called to retry connecting to remote
782    router. This is used by both normal and router server. This will wait
783    before retrying the connecting. The timeout is generated by exponential
784    backoff algorithm. */
785
786 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
787 {
788   SilcServerConnection sconn = (SilcServerConnection)context;
789   SilcServer server = sconn->server;
790   SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
791   SilcServerConfigConnParams *param =
792                 (conn->param ? conn->param : &server->config->param);
793
794   SILC_LOG_INFO(("Retrying connecting to a router"));
795
796   /* Calculate next timeout */
797   if (sconn->retry_count >= 1) {
798     sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
799     if (sconn->retry_timeout > param->reconnect_interval_max)
800       sconn->retry_timeout = param->reconnect_interval_max;
801   } else {
802     sconn->retry_timeout = param->reconnect_interval;
803   }
804   sconn->retry_count++;
805   sconn->retry_timeout = sconn->retry_timeout +
806     silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
807
808   /* If we've reached max retry count, give up. */
809   if ((sconn->retry_count > param->reconnect_count) &&
810       !param->reconnect_keep_trying) {
811     SILC_LOG_ERROR(("Could not connect to router, giving up"));
812     silc_server_config_unref(&sconn->conn);
813     silc_free(sconn->remote_host);
814     silc_free(sconn->backup_replace_ip);
815     silc_free(sconn);
816     return;
817   }
818
819   SILC_LOG_DEBUG(("Retrying connecting to a router in %d seconds",
820                   sconn->retry_timeout));
821
822   /* We will lookup a fresh pointer later */
823   silc_server_config_unref(&sconn->conn);
824
825   /* Wait one before retrying */
826   silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
827                          context, sconn->retry_timeout, 0,
828                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
829 }
830
831 /* Generic routine to use connect to a router. */
832
833 SILC_TASK_CALLBACK(silc_server_connect_router)
834 {
835   SilcServerConnection sconn = (SilcServerConnection)context;
836   SilcServer server = sconn->server;
837   SilcServerConfigRouter *rconn;
838   int sock;
839
840   SILC_LOG_INFO(("Connecting to the %s %s on port %d",
841                  (sconn->backup ? "backup router" : "router"),
842                  sconn->remote_host, sconn->remote_port));
843
844   server->router_connect = time(NULL);
845   rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
846                                               sconn->remote_port);
847   if (!rconn) {
848     SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
849                    (sconn->backup ? "backup router" : "router"),
850                    sconn->remote_host, sconn->remote_port));
851     silc_free(sconn->remote_host);
852     silc_free(sconn->backup_replace_ip);
853     silc_free(sconn);
854     return;
855   }
856   silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
857
858   /* Connect to remote host */
859   sock = silc_net_create_connection(
860                  (!server->config->server_info->primary ? NULL :
861                   server->config->server_info->primary->server_ip),
862                  sconn->remote_port, sconn->remote_host);
863   if (sock < 0) {
864     SILC_LOG_ERROR(("Could not connect to router %s:%d",
865                     sconn->remote_host, sconn->remote_port));
866     if (!sconn->no_reconnect)
867       silc_schedule_task_add(server->schedule, 0,
868                              silc_server_connect_to_router_retry,
869                              context, 0, 1, SILC_TASK_TIMEOUT,
870                              SILC_TASK_PRI_NORMAL);
871     else
872       silc_server_config_unref(&sconn->conn);
873     return;
874   }
875
876   /* Continue with key exchange protocol */
877   silc_server_start_key_exchange(server, sconn, sock);
878 }
879
880 /* This function connects to our primary router or if we are a router this
881    establishes all our primary routes. This is called at the start of the
882    server to do authentication and key exchange with our router - called
883    from schedule. */
884
885 SILC_TASK_CALLBACK(silc_server_connect_to_router)
886 {
887   SilcServer server = (SilcServer)context;
888   SilcServerConnection sconn;
889   SilcServerConfigRouter *ptr;
890
891   SILC_LOG_DEBUG(("Connecting to router(s)"));
892
893   if (server->server_type == SILC_SERVER) {
894     SILC_LOG_DEBUG(("We are normal server"));
895   } else if (server->server_type == SILC_ROUTER) {
896     SILC_LOG_DEBUG(("We are router"));
897   } else {
898     SILC_LOG_DEBUG(("We are backup router/normal server"));
899   }
900
901   if (!server->config->routers) {
902     /* There wasn't a configured router, we will continue but we don't
903        have a connection to outside world.  We will be standalone server. */
904     SILC_LOG_DEBUG(("No router(s), server will be standalone"));
905     server->standalone = TRUE;
906     return;
907   }
908
909   /* Cancel any possible retry timeouts */
910   silc_schedule_task_del_by_callback(server->schedule,
911                                      silc_server_connect_router);
912   silc_schedule_task_del_by_callback(server->schedule,
913                                      silc_server_connect_to_router_retry);
914
915   /* Create the connections to all our routes */
916   for (ptr = server->config->routers; ptr; ptr = ptr->next) {
917
918     SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
919                     ptr->backup_router ? "Backup router" : "Router",
920                     ptr->initiator ? "Initiator" : "Responder",
921                     ptr->host, ptr->port));
922
923     if (ptr->initiator) {
924       /* Check whether we are connected to this host already */
925       if (silc_server_num_sockets_by_remote(server, 
926                                             silc_net_is_ip(ptr->host) ?
927                                             ptr->host : NULL,
928                                             silc_net_is_ip(ptr->host) ?
929                                             NULL : ptr->host, ptr->port,
930                                             SILC_SOCKET_TYPE_ROUTER)) {
931         SILC_LOG_DEBUG(("We are already connected to this router"));
932         continue;
933       }
934
935       /* Allocate connection object for hold connection specific stuff. */
936       sconn = silc_calloc(1, sizeof(*sconn));
937       sconn->server = server;
938       sconn->remote_host = strdup(ptr->host);
939       sconn->remote_port = ptr->port;
940       sconn->backup = ptr->backup_router;
941       if (sconn->backup) {
942         sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
943         sconn->backup_replace_port = ptr->backup_replace_port;
944       }
945
946       if (!server->router_conn && !sconn->backup)
947         server->router_conn = sconn;
948
949       silc_schedule_task_add(server->schedule, 0,
950                              silc_server_connect_router,
951                              (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
952                              SILC_TASK_PRI_NORMAL);
953     }
954   }
955 }
956
957 /* Second part of connecting to router(s). Key exchange protocol has been
958    executed and now we will execute authentication protocol. */
959
960 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
961 {
962   SilcProtocol protocol = (SilcProtocol)context;
963   SilcServerKEInternalContext *ctx =
964     (SilcServerKEInternalContext *)protocol->context;
965   SilcServer server = (SilcServer)ctx->server;
966   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
967   SilcSocketConnection sock = ctx->sock;
968   SilcServerConnAuthInternalContext *proto_ctx;
969   SilcServerConfigRouter *conn = NULL;
970
971   SILC_LOG_DEBUG(("Start"));
972
973   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
974       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
975     /* Error occured during protocol */
976     silc_protocol_free(protocol);
977     sock->protocol = NULL;
978     silc_ske_free_key_material(ctx->keymat);
979     if (ctx->packet)
980       silc_packet_context_free(ctx->packet);
981     if (ctx->ske)
982       silc_ske_free(ctx->ske);
983     silc_free(ctx->dest_id);
984     silc_free(ctx);
985     silc_schedule_task_del_by_callback(server->schedule,
986                                        silc_server_failure_callback);
987     silc_server_disconnect_remote(server, sock, 
988                                   SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
989
990     /* Try reconnecting if configuration wants it */
991     if (!sconn->no_reconnect) {
992       silc_schedule_task_add(server->schedule, 0,
993                              silc_server_connect_to_router_retry,
994                              sconn, 0, 1, SILC_TASK_TIMEOUT,
995                              SILC_TASK_PRI_NORMAL);
996       return;
997     }
998     silc_server_config_unref(&sconn->conn);
999     silc_free(sconn->remote_host);
1000     silc_free(sconn->backup_replace_ip);
1001     silc_free(sconn);
1002     return;
1003   }
1004
1005   /* We now have the key material as the result of the key exchange
1006      protocol. Take the key material into use. Free the raw key material
1007      as soon as we've set them into use. */
1008   if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1009                                         ctx->sock, ctx->keymat,
1010                                         ctx->ske->prop->cipher,
1011                                         ctx->ske->prop->pkcs,
1012                                         ctx->ske->prop->hash,
1013                                         ctx->ske->prop->hmac,
1014                                         ctx->ske->prop->group,
1015                                         ctx->responder)) {
1016     silc_protocol_free(protocol);
1017     sock->protocol = NULL;
1018     silc_ske_free_key_material(ctx->keymat);
1019     if (ctx->packet)
1020       silc_packet_context_free(ctx->packet);
1021     if (ctx->ske)
1022       silc_ske_free(ctx->ske);
1023     silc_free(ctx->dest_id);
1024     silc_free(ctx);
1025     silc_schedule_task_del_by_callback(server->schedule,
1026                                        silc_server_failure_callback);
1027     silc_server_disconnect_remote(server, sock, 
1028                                   SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1029
1030     /* Try reconnecting if configuration wants it */
1031     if (!sconn->no_reconnect) {
1032       silc_schedule_task_add(server->schedule, 0,
1033                              silc_server_connect_to_router_retry,
1034                              sconn, 0, 1, SILC_TASK_TIMEOUT,
1035                              SILC_TASK_PRI_NORMAL);
1036       return;
1037     }
1038     silc_server_config_unref(&sconn->conn);
1039     silc_free(sconn->remote_host);
1040     silc_free(sconn->backup_replace_ip);
1041     silc_free(sconn);
1042     return;
1043   }
1044   silc_ske_free_key_material(ctx->keymat);
1045
1046   /* Allocate internal context for the authentication protocol. This
1047      is sent as context for the protocol. */
1048   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1049   proto_ctx->server = (void *)server;
1050   proto_ctx->context = (void *)sconn;
1051   proto_ctx->sock = sock;
1052   proto_ctx->ske = ctx->ske;       /* Save SKE object from previous protocol */
1053   proto_ctx->dest_id_type = ctx->dest_id_type;
1054   proto_ctx->dest_id = ctx->dest_id;
1055
1056   /* Resolve the authentication method used in this connection. Check if
1057      we find a match from user configured connections */
1058   if (!sconn->conn.ref_ptr)
1059     conn = silc_server_config_find_router_conn(server, sock->hostname,
1060                                                sock->port);
1061   else
1062     conn = sconn->conn.ref_ptr;
1063
1064   if (conn) {
1065     /* Match found. Use the configured authentication method. Take only
1066        the passphrase, since for public key auth we automatically use
1067        our local key pair. */
1068     if (conn->passphrase) {
1069       if (conn->publickeys && !server->config->prefer_passphrase_auth) {
1070         proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1071       } else {
1072         proto_ctx->auth_data = strdup(conn->passphrase);
1073         proto_ctx->auth_data_len = strlen(conn->passphrase);
1074         proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
1075       }
1076     } else if (conn->publickeys) {
1077       proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1078     } else {
1079       proto_ctx->auth_meth = SILC_AUTH_NONE;
1080     }
1081   } else {
1082     SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
1083                     sock->hostname, sock->ip, sock->port));
1084     silc_protocol_free(protocol);
1085     sock->protocol = NULL;
1086     if (ctx->packet)
1087       silc_packet_context_free(ctx->packet);
1088     if (ctx->ske)
1089       silc_ske_free(ctx->ske);
1090     silc_free(ctx->dest_id);
1091     silc_free(ctx);
1092     silc_server_config_unref(&sconn->conn);
1093     silc_free(sconn->remote_host);
1094     silc_free(sconn->backup_replace_ip);
1095     silc_free(sconn);
1096     silc_schedule_task_del_by_callback(server->schedule,
1097                                        silc_server_failure_callback);
1098     silc_server_disconnect_remote(server, sock, 
1099                                   SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1100     return;
1101   }
1102
1103   /* Free old protocol as it is finished now */
1104   silc_protocol_free(protocol);
1105   if (ctx->packet)
1106     silc_packet_context_free(ctx->packet);
1107   silc_free(ctx);
1108   sock->protocol = NULL;
1109
1110   /* Allocate the authentication protocol. This is allocated here
1111      but we won't start it yet. We will be receiving party of this
1112      protocol thus we will wait that connecting party will make
1113      their first move. */
1114   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1115                       &sock->protocol, proto_ctx,
1116                       silc_server_connect_to_router_final);
1117
1118   /* Register timeout task. If the protocol is not executed inside
1119      this timelimit the connection will be terminated. */
1120   proto_ctx->timeout_task =
1121     silc_schedule_task_add(server->schedule, sock->sock,
1122                            silc_server_timeout_remote,
1123                            (void *)server,
1124                            server->config->conn_auth_timeout, 0,
1125                            SILC_TASK_TIMEOUT,
1126                            SILC_TASK_PRI_LOW);
1127
1128   /* Run the protocol */
1129   silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1130 }
1131
1132 /* Finalizes the connection to router. Registers a server task to the
1133    queue so that we can accept new connections. */
1134
1135 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
1136 {
1137   SilcProtocol protocol = (SilcProtocol)context;
1138   SilcServerConnAuthInternalContext *ctx =
1139     (SilcServerConnAuthInternalContext *)protocol->context;
1140   SilcServer server = (SilcServer)ctx->server;
1141   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1142   SilcSocketConnection sock = ctx->sock;
1143   SilcServerEntry id_entry;
1144   SilcBuffer packet;
1145   SilcServerHBContext hb_context;
1146   unsigned char *id_string;
1147   SilcUInt32 id_len;
1148   SilcIDListData idata;
1149   SilcServerConfigRouter *conn = NULL;
1150   SilcServerConfigConnParams *param = NULL;
1151
1152   SILC_LOG_DEBUG(("Start"));
1153
1154   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1155       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1156     /* Error occured during protocol */
1157     silc_free(ctx->dest_id);
1158     silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1159                                   NULL);
1160
1161     /* Try reconnecting if configuration wants it */
1162     if (!sconn->no_reconnect) {
1163       silc_schedule_task_add(server->schedule, 0,
1164                              silc_server_connect_to_router_retry,
1165                              sconn, 0, 1, SILC_TASK_TIMEOUT,
1166                              SILC_TASK_PRI_NORMAL);
1167       goto out2;
1168     }
1169
1170     goto out;
1171   }
1172
1173   /* Add a task to the queue. This task receives new connections to the
1174      server. This task remains on the queue until the end of the program. */
1175   if (!server->listenning && !sconn->backup) {
1176     silc_schedule_task_add(server->schedule, server->sock,
1177                            silc_server_accept_new_connection,
1178                            (void *)server, 0, 0,
1179                            SILC_TASK_FD,
1180                            SILC_TASK_PRI_NORMAL);
1181     server->listenning = TRUE;
1182   }
1183
1184   /* Send NEW_SERVER packet to the router. We will become registered
1185      to the SILC network after sending this packet. */
1186   id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
1187   id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1188   packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
1189   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1190   silc_buffer_format(packet,
1191                      SILC_STR_UI_SHORT(id_len),
1192                      SILC_STR_UI_XNSTRING(id_string, id_len),
1193                      SILC_STR_UI_SHORT(strlen(server->server_name)),
1194                      SILC_STR_UI_XNSTRING(server->server_name,
1195                                           strlen(server->server_name)),
1196                      SILC_STR_END);
1197
1198   /* Send the packet */
1199   silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
1200                           packet->data, packet->len, TRUE);
1201   silc_buffer_free(packet);
1202   silc_free(id_string);
1203
1204   SILC_LOG_INFO(("Connected to router %s", sock->hostname));
1205
1206   /* Check that we do not have this ID already */
1207   id_entry = silc_idlist_find_server_by_id(server->local_list,
1208                                            ctx->dest_id, TRUE, NULL);
1209   if (id_entry) {
1210     silc_idcache_del_by_context(server->local_list->servers, id_entry);
1211   } else {
1212     id_entry = silc_idlist_find_server_by_id(server->global_list,
1213                                              ctx->dest_id, TRUE, NULL);
1214     if (id_entry)
1215       silc_idcache_del_by_context(server->global_list->servers, id_entry);
1216   }
1217
1218   SILC_LOG_DEBUG(("New server id(%s)",
1219                   silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1220
1221   /* Add the connected router to global server list */
1222   id_entry = silc_idlist_add_server(server->global_list,
1223                                     strdup(sock->hostname),
1224                                     SILC_ROUTER, ctx->dest_id, NULL, sock);
1225   if (!id_entry) {
1226     silc_free(ctx->dest_id);
1227     SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1228     silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1229                                   NULL);
1230     goto out;
1231   }
1232
1233   silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1234   silc_free(sock->user_data);
1235   sock->user_data = (void *)id_entry;
1236   sock->type = SILC_SOCKET_TYPE_ROUTER;
1237   idata = (SilcIDListData)sock->user_data;
1238   idata->status |= SILC_IDLIST_STATUS_REGISTERED;
1239
1240   conn = sconn->conn.ref_ptr;
1241   param = &server->config->param;
1242   if (conn && conn->param)
1243     param = conn->param;
1244
1245   /* Perform keepalive. The `hb_context' will be freed automatically
1246      when finally calling the silc_socket_free function. */
1247   hb_context = silc_calloc(1, sizeof(*hb_context));
1248   hb_context->server = server;
1249   silc_socket_set_heartbeat(sock, param->keepalive_secs, hb_context,
1250                             silc_server_perform_heartbeat,
1251                             server->schedule);
1252
1253   /* Register re-key timeout */
1254   idata->rekey->timeout = param->key_exchange_rekey;
1255   idata->rekey->context = (void *)server;
1256   silc_schedule_task_add(server->schedule, sock->sock,
1257                          silc_server_rekey_callback,
1258                          (void *)sock, idata->rekey->timeout, 0,
1259                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1260
1261   if (!sconn->backup) {
1262     /* Mark this router our primary router if we're still standalone */
1263     if (server->standalone) {
1264       server->id_entry->router = id_entry;
1265       server->router = id_entry;
1266       server->standalone = FALSE;
1267
1268       /* If we are router then announce our possible servers. */
1269       if (server->server_type == SILC_ROUTER)
1270         silc_server_announce_servers(server, FALSE, 0,
1271                                      SILC_PRIMARY_ROUTE(server));
1272
1273       /* Announce our clients and channels to the router */
1274       silc_server_announce_clients(server, 0, SILC_PRIMARY_ROUTE(server));
1275       silc_server_announce_channels(server, 0, SILC_PRIMARY_ROUTE(server));
1276
1277       /* If we are backup router then this primary router is whom we are
1278          backing up. */
1279       if (server->server_type == SILC_BACKUP_ROUTER)
1280         silc_server_backup_add(server, server->id_entry, sock->ip, 0, TRUE);
1281     }
1282   } else {
1283     /* Add this server to be our backup router */
1284     silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1285                            sconn->backup_replace_port, FALSE);
1286   }
1287
1288   sock->protocol = NULL;
1289
1290   /* Call the completion callback to indicate that we've connected to
1291      the router */
1292   if (sconn->callback)
1293     (*sconn->callback)(server, id_entry, sconn->callback_context);
1294
1295  out:
1296   /* Free the temporary connection data context */
1297   if (sconn) {
1298     silc_server_config_unref(&sconn->conn);
1299     silc_free(sconn->remote_host);
1300     silc_free(sconn->backup_replace_ip);
1301     silc_free(sconn);
1302   }
1303   if (sconn == server->router_conn)
1304     server->router_conn = NULL;
1305
1306  out2:
1307   /* Free the protocol object */
1308   if (sock->protocol == protocol)
1309     sock->protocol = NULL;
1310   silc_protocol_free(protocol);
1311   if (ctx->packet)
1312     silc_packet_context_free(ctx->packet);
1313   if (ctx->ske)
1314     silc_ske_free(ctx->ske);
1315   if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1316     silc_free(ctx->auth_data);
1317   silc_free(ctx);
1318 }
1319
1320 /* Host lookup callback that is called after the incoming connection's
1321    IP and FQDN lookup is performed. This will actually check the acceptance
1322    of the incoming connection and will register the key exchange protocol
1323    for this connection. */
1324
1325 static void
1326 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1327                                          void *context)
1328 {
1329   SilcServerKEInternalContext *proto_ctx =
1330     (SilcServerKEInternalContext *)context;
1331   SilcServer server = (SilcServer)proto_ctx->server;
1332   SilcServerConfigClient *cconfig = NULL;
1333   SilcServerConfigServer *sconfig = NULL;
1334   SilcServerConfigRouter *rconfig = NULL;
1335   SilcServerConfigDeny *deny;
1336   int port;
1337
1338   context = (void *)server;
1339
1340   /* Check whether we could resolve both IP and FQDN. */
1341   if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1342                     server->config->require_reverse_lookup)) {
1343     SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1344                     sock->hostname ? sock->hostname :
1345                     sock->ip ? sock->ip : ""));
1346     server->stat.conn_failures++;
1347     silc_server_disconnect_remote(server, sock,
1348                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
1349                                   "Unknown host or IP");
1350     silc_free(proto_ctx);
1351     return;
1352   }
1353
1354   /* Register the connection for network input and output. This sets
1355      that scheduler will listen for incoming packets for this connection
1356      and sets that outgoing packets may be sent to this connection as well.
1357      However, this doesn't set the scheduler for outgoing traffic, it
1358      will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1359      later when outgoing data is available. */
1360   SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1361
1362   SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1363                  sock->ip));
1364
1365   /* Listenning port */
1366   if (!server->sockets[(SilcUInt32)proto_ctx->context]) {
1367     silc_server_disconnect_remote(server, sock,
1368                                   SILC_STATUS_ERR_RESOURCE_LIMIT,
1369                                   "Connection refused");
1370     server->stat.conn_failures++;
1371     silc_free(proto_ctx);
1372     return;
1373   }
1374   port = server->sockets[(SilcUInt32)proto_ctx->context]->port;
1375
1376   /* Check whether this connection is denied to connect to us. */
1377   deny = silc_server_config_find_denied(server, sock->ip);
1378   if (!deny)
1379     deny = silc_server_config_find_denied(server, sock->hostname);
1380   if (deny) {
1381     /* The connection is denied */
1382     SILC_LOG_INFO(("Connection %s (%s) is denied",
1383                    sock->hostname, sock->ip));
1384     silc_server_disconnect_remote(server, sock,
1385                                   SILC_STATUS_ERR_BANNED_FROM_SERVER,
1386                                   deny->reason);
1387     server->stat.conn_failures++;
1388     silc_free(proto_ctx);
1389     return;
1390   }
1391
1392   /* Check whether we have configured this sort of connection at all. We
1393      have to check all configurations since we don't know what type of
1394      connection this is. */
1395   if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1396     cconfig = silc_server_config_find_client(server, sock->hostname);
1397   if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1398     sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1399   if (server->server_type == SILC_ROUTER) {
1400     if (!(rconfig = silc_server_config_find_router_conn(server,
1401                                                         sock->ip, sock->port)))
1402       rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1403                                                     sock->port);
1404   }
1405   if (!cconfig && !sconfig && !rconfig) {
1406     SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1407                    sock->ip));
1408     silc_server_disconnect_remote(server, sock,
1409                                   SILC_STATUS_ERR_BANNED_FROM_SERVER, NULL);
1410     server->stat.conn_failures++;
1411     silc_free(proto_ctx);
1412     return;
1413   }
1414
1415   /* The connection is allowed */
1416
1417   /* Set internal context for key exchange protocol. This is
1418      sent as context for the protocol. */
1419   proto_ctx->sock = sock;
1420   proto_ctx->rng = server->rng;
1421   proto_ctx->responder = TRUE;
1422   silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1423   silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1424   silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1425
1426   /* Take flags for key exchange. Since we do not know what type of connection
1427      this is, we go through all found configurations and use the global ones
1428      as well. This will result always into strictest key exchange flags. */
1429   SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1430   SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1431   SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1432   if (server->config->param.key_exchange_pfs)
1433     proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1434
1435   /* Prepare the connection for key exchange protocol. We allocate the
1436      protocol but will not start it yet. The connector will be the
1437      initiator of the protocol thus we will wait for initiation from
1438      there before we start the protocol. */
1439   server->stat.auth_attempts++;
1440   SILC_LOG_DEBUG(("Starting key exchange protocol"));
1441   silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1442                       &sock->protocol, proto_ctx,
1443                       silc_server_accept_new_connection_second);
1444
1445   /* Register a timeout task that will be executed if the connector
1446      will not start the key exchange protocol within specified timeout
1447      and the connection will be closed. */
1448   proto_ctx->timeout_task =
1449     silc_schedule_task_add(server->schedule, sock->sock,
1450                            silc_server_timeout_remote,
1451                            (void *)server,
1452                            server->config->key_exchange_timeout, 0,
1453                            SILC_TASK_TIMEOUT,
1454                            SILC_TASK_PRI_LOW);
1455 }
1456
1457 /* Accepts new connections to the server. Accepting new connections are
1458    done in three parts to make it async. */
1459
1460 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1461 {
1462   SilcServer server = (SilcServer)context;
1463   SilcSocketConnection newsocket;
1464   SilcServerKEInternalContext *proto_ctx;
1465   int sock;
1466
1467   SILC_LOG_DEBUG(("Accepting new connection"));
1468
1469   server->stat.conn_attempts++;
1470
1471   sock = silc_net_accept_connection(fd);
1472   if (sock < 0) {
1473     SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1474     server->stat.conn_failures++;
1475     return;
1476   }
1477
1478   /* Check for maximum allowed connections */
1479   if (sock > server->config->param.connections_max) {
1480     SILC_LOG_ERROR(("Refusing connection, server is full"));
1481     server->stat.conn_failures++;
1482     silc_net_close_connection(sock);
1483     return;
1484   }
1485
1486   /* Set socket options */
1487   silc_net_set_socket_nonblock(sock);
1488   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1489
1490   /* We don't create a ID yet, since we don't know what type of connection
1491      this is yet. But, we do add the connection to the socket table. */
1492   silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1493   server->sockets[sock] = newsocket;
1494
1495   /* Perform asynchronous host lookup. This will lookup the IP and the
1496      FQDN of the remote connection. After the lookup is done the connection
1497      is accepted further. */
1498   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1499   proto_ctx->server = server;
1500   proto_ctx->context = (void *)fd;
1501   silc_socket_host_lookup(newsocket, TRUE,
1502                           silc_server_accept_new_connection_lookup,
1503                           (void *)proto_ctx, server->schedule);
1504 }
1505
1506 /* Second part of accepting new connection. Key exchange protocol has been
1507    performed and now it is time to do little connection authentication
1508    protocol to figure out whether this connection is client or server
1509    and whether it has right to access this server (especially server
1510    connections needs to be authenticated). */
1511
1512 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1513 {
1514   SilcProtocol protocol = (SilcProtocol)context;
1515   SilcServerKEInternalContext *ctx =
1516     (SilcServerKEInternalContext *)protocol->context;
1517   SilcServer server = (SilcServer)ctx->server;
1518   SilcSocketConnection sock = ctx->sock;
1519   SilcServerConnAuthInternalContext *proto_ctx;
1520
1521   SILC_LOG_DEBUG(("Start"));
1522
1523   if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1524       (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1525     /* Error occured during protocol */
1526     SILC_LOG_DEBUG(("Error key exchange protocol"));
1527     silc_protocol_free(protocol);
1528     sock->protocol = NULL;
1529     silc_ske_free_key_material(ctx->keymat);
1530     if (ctx->packet)
1531       silc_packet_context_free(ctx->packet);
1532     if (ctx->ske)
1533       silc_ske_free(ctx->ske);
1534     silc_free(ctx->dest_id);
1535     silc_server_config_unref(&ctx->cconfig);
1536     silc_server_config_unref(&ctx->sconfig);
1537     silc_server_config_unref(&ctx->rconfig);
1538     silc_free(ctx);
1539     silc_schedule_task_del_by_callback(server->schedule,
1540                                        silc_server_failure_callback);
1541     silc_server_disconnect_remote(server, sock, 
1542                                   SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
1543                                   NULL);
1544     server->stat.auth_failures++;
1545     return;
1546   }
1547
1548   /* We now have the key material as the result of the key exchange
1549      protocol. Take the key material into use. Free the raw key material
1550      as soon as we've set them into use. */
1551   if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1552                                         ctx->sock, ctx->keymat,
1553                                         ctx->ske->prop->cipher,
1554                                         ctx->ske->prop->pkcs,
1555                                         ctx->ske->prop->hash,
1556                                         ctx->ske->prop->hmac,
1557                                         ctx->ske->prop->group,
1558                                         ctx->responder)) {
1559     SILC_LOG_ERROR(("Error setting key material in use"));
1560     silc_protocol_free(protocol);
1561     sock->protocol = NULL;
1562     silc_ske_free_key_material(ctx->keymat);
1563     if (ctx->packet)
1564       silc_packet_context_free(ctx->packet);
1565     if (ctx->ske)
1566       silc_ske_free(ctx->ske);
1567     silc_free(ctx->dest_id);
1568     silc_server_config_unref(&ctx->cconfig);
1569     silc_server_config_unref(&ctx->sconfig);
1570     silc_server_config_unref(&ctx->rconfig);
1571     silc_free(ctx);
1572     silc_schedule_task_del_by_callback(server->schedule,
1573                                        silc_server_failure_callback);
1574     silc_server_disconnect_remote(server, sock, 
1575                                   SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1576     server->stat.auth_failures++;
1577     return;
1578   }
1579   silc_ske_free_key_material(ctx->keymat);
1580
1581   /* Allocate internal context for the authentication protocol. This
1582      is sent as context for the protocol. */
1583   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1584   proto_ctx->server = (void *)server;
1585   proto_ctx->sock = sock;
1586   proto_ctx->ske = ctx->ske;    /* Save SKE object from previous protocol */
1587   proto_ctx->responder = TRUE;
1588   proto_ctx->dest_id_type = ctx->dest_id_type;
1589   proto_ctx->dest_id = ctx->dest_id;
1590   proto_ctx->cconfig = ctx->cconfig;
1591   proto_ctx->sconfig = ctx->sconfig;
1592   proto_ctx->rconfig = ctx->rconfig;
1593
1594   /* Free old protocol as it is finished now */
1595   silc_protocol_free(protocol);
1596   if (ctx->packet)
1597     silc_packet_context_free(ctx->packet);
1598   silc_free(ctx);
1599   sock->protocol = NULL;
1600
1601   /* Allocate the authentication protocol. This is allocated here
1602      but we won't start it yet. We will be receiving party of this
1603      protocol thus we will wait that connecting party will make
1604      their first move. */
1605   SILC_LOG_DEBUG(("Starting connection authentication protocol"));
1606   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1607                       &sock->protocol, proto_ctx,
1608                       silc_server_accept_new_connection_final);
1609
1610   /* Register timeout task. If the protocol is not executed inside
1611      this timelimit the connection will be terminated. */
1612   proto_ctx->timeout_task =
1613     silc_schedule_task_add(server->schedule, sock->sock,
1614                            silc_server_timeout_remote,
1615                            (void *)server,
1616                            server->config->conn_auth_timeout, 0,
1617                            SILC_TASK_TIMEOUT,
1618                            SILC_TASK_PRI_LOW);
1619 }
1620
1621 /* Final part of accepting new connection. The connection has now
1622    been authenticated and keys has been exchanged. We also know whether
1623    this is client or server connection. */
1624
1625 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1626 {
1627   SilcProtocol protocol = (SilcProtocol)context;
1628   SilcServerConnAuthInternalContext *ctx =
1629     (SilcServerConnAuthInternalContext *)protocol->context;
1630   SilcServer server = (SilcServer)ctx->server;
1631   SilcSocketConnection sock = ctx->sock;
1632   SilcServerHBContext hb_context;
1633   SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1634   void *id_entry;
1635   SilcUInt32 hearbeat_timeout = server->config->param.keepalive_secs;
1636
1637   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1638       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1639     /* Error occured during protocol */
1640     SILC_LOG_DEBUG(("Error during authentication protocol"));
1641     silc_protocol_free(protocol);
1642     sock->protocol = NULL;
1643     if (ctx->packet)
1644       silc_packet_context_free(ctx->packet);
1645     if (ctx->ske)
1646       silc_ske_free(ctx->ske);
1647     silc_free(ctx->dest_id);
1648     silc_server_config_unref(&ctx->cconfig);
1649     silc_server_config_unref(&ctx->sconfig);
1650     silc_server_config_unref(&ctx->rconfig);
1651     silc_free(ctx);
1652     silc_schedule_task_del_by_callback(server->schedule,
1653                                        silc_server_failure_callback);
1654     silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1655                                   NULL);
1656     server->stat.auth_failures++;
1657     return;
1658   }
1659
1660   entry->data.last_receive = time(NULL);
1661
1662   switch (ctx->conn_type) {
1663   case SILC_SOCKET_TYPE_CLIENT:
1664     {
1665       SilcClientEntry client;
1666       SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1667
1668       /* Verify whether this connection is after all allowed to connect */
1669       if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1670                                           &server->config->param,
1671                                           conn->param, ctx->ske)) {
1672         server->stat.auth_failures++;
1673         goto out;
1674       }
1675
1676       SILC_LOG_DEBUG(("Remote host is client"));
1677       SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1678                      sock->ip));
1679
1680       /* Add the client to the client ID cache. The nickname and Client ID
1681          and other information is created after we have received NEW_CLIENT
1682          packet from client. */
1683       client = silc_idlist_add_client(server->local_list,
1684                                       NULL, NULL, NULL, NULL, NULL, sock, 0);
1685       if (!client) {
1686         SILC_LOG_ERROR(("Could not add new client to cache"));
1687         silc_free(sock->user_data);
1688         silc_server_disconnect_remote(server, sock, 
1689                                       SILC_STATUS_ERR_AUTH_FAILED, NULL);
1690         server->stat.auth_failures++;
1691         goto out;
1692       }
1693       entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
1694
1695       /* Statistics */
1696       server->stat.my_clients++;
1697       server->stat.clients++;
1698       server->stat.cell_clients++;
1699
1700       /* Get connection parameters */
1701       if (conn->param) {
1702         if (conn->param->keepalive_secs)
1703           hearbeat_timeout = conn->param->keepalive_secs;
1704       }
1705
1706       id_entry = (void *)client;
1707       break;
1708     }
1709   case SILC_SOCKET_TYPE_SERVER:
1710   case SILC_SOCKET_TYPE_ROUTER:
1711     {
1712       SilcServerEntry new_server;
1713       bool initiator = FALSE;
1714       bool backup_local = FALSE;
1715       bool backup_router = FALSE;
1716       char *backup_replace_ip = NULL;
1717       SilcUInt16 backup_replace_port = 0;
1718       SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1719       SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1720
1721       /* If we are backup router and this is incoming server connection
1722          and we do not have connection to primary router, do not allow
1723          the connection. */
1724       if (server->server_type == SILC_BACKUP_ROUTER &&
1725           ctx->conn_type == SILC_SOCKET_TYPE_SERVER &&
1726           !SILC_PRIMARY_ROUTE(server)) {
1727         SILC_LOG_INFO(("Will not accept server connection because we do "
1728                        "not have primary router connection established"));
1729         silc_server_disconnect_remote(server, sock, 
1730                                       SILC_STATUS_ERR_PERM_DENIED,
1731                                       "We do not have connection to primary "
1732                                       "router established, try later");
1733         silc_free(sock->user_data);
1734         server->stat.auth_failures++;
1735         goto out;
1736       }
1737
1738       if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1739         /* Verify whether this connection is after all allowed to connect */
1740         if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1741                                             &server->config->param,
1742                                             rconn ? rconn->param : NULL,
1743                                             ctx->ske)) {
1744           silc_free(sock->user_data);
1745           server->stat.auth_failures++;
1746           goto out;
1747         }
1748
1749         if (rconn) {
1750           if (rconn->param) {
1751             if (rconn->param->keepalive_secs)
1752               hearbeat_timeout = rconn->param->keepalive_secs;
1753           }
1754
1755           initiator = rconn->initiator;
1756           backup_local = rconn->backup_local;
1757           backup_router = rconn->backup_router;
1758           backup_replace_ip = rconn->backup_replace_ip;
1759           backup_replace_port = rconn->backup_replace_port;
1760         }
1761       }
1762
1763       if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1764         /* Verify whether this connection is after all allowed to connect */
1765         if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1766                                             &server->config->param,
1767                                             sconn ? sconn->param : NULL,
1768                                             ctx->ske)) {
1769           silc_free(sock->user_data);
1770           server->stat.auth_failures++;
1771           goto out;
1772         }
1773         if (sconn) {
1774           if (sconn->param) {
1775             if (sconn->param->keepalive_secs)
1776               hearbeat_timeout = sconn->param->keepalive_secs;
1777           }
1778
1779           backup_router = sconn->backup_router;
1780         }
1781       }
1782
1783       SILC_LOG_DEBUG(("Remote host is %s",
1784                       ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1785                       "server" : (backup_router ?
1786                                   "backup router" : "router")));
1787       SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
1788                      sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1789                      "server" : (backup_router ?
1790                                  "backup router" : "router")));
1791
1792       /* Add the server into server cache. The server name and Server ID
1793          is updated after we have received NEW_SERVER packet from the
1794          server. We mark ourselves as router for this server if we really
1795          are router. */
1796       new_server =
1797         silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1798                                 server->local_list : (backup_router ?
1799                                                       server->local_list :
1800                                                       server->global_list)),
1801                                NULL,
1802                                (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1803                                 SILC_SERVER : SILC_ROUTER),
1804                                NULL,
1805                                (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1806                                 server->id_entry : (backup_router ?
1807                                                     server->id_entry : NULL)),
1808                                sock);
1809       if (!new_server) {
1810         SILC_LOG_ERROR(("Could not add new server to cache"));
1811         silc_free(sock->user_data);
1812         silc_server_disconnect_remote(server, sock, 
1813                                       SILC_STATUS_ERR_AUTH_FAILED, NULL);
1814         server->stat.auth_failures++;
1815         goto out;
1816       }
1817       entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
1818
1819       id_entry = (void *)new_server;
1820
1821       /* If the incoming connection is router and marked as backup router
1822          then add it to be one of our backups */
1823       if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
1824         silc_server_backup_add(server, new_server, backup_replace_ip,
1825                                backup_replace_port, backup_local);
1826
1827         /* Change it back to SERVER type since that's what it really is. */
1828         if (backup_local)
1829           ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1830
1831         new_server->server_type = SILC_BACKUP_ROUTER;
1832       }
1833
1834       /* Statistics */
1835       if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1836         server->stat.my_servers++;
1837       } else {
1838         server->stat.my_routers++;
1839         server->stat.routers++;
1840       }
1841       server->stat.servers++;
1842
1843       /* Check whether this connection is to be our primary router connection
1844          if we do not already have the primary route. */
1845       if (!backup_router &&
1846           server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1847         if (silc_server_config_is_primary_route(server) && !initiator)
1848           break;
1849
1850         SILC_LOG_DEBUG(("We are not standalone server anymore"));
1851         server->standalone = FALSE;
1852         if (!server->id_entry->router) {
1853           server->id_entry->router = id_entry;
1854           server->router = id_entry;
1855         }
1856       }
1857
1858       break;
1859     }
1860   default:
1861     goto out;
1862     break;
1863   }
1864
1865   sock->type = ctx->conn_type;
1866
1867   /* Add the common data structure to the ID entry. */
1868   silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1869
1870   /* Add to sockets internal pointer for fast referencing */
1871   silc_free(sock->user_data);
1872   sock->user_data = id_entry;
1873
1874   /* Connection has been fully established now. Everything is ok. */
1875   SILC_LOG_DEBUG(("New connection authenticated"));
1876
1877   /* Perform keepalive. The `hb_context' will be freed automatically
1878      when finally calling the silc_socket_free function. */
1879   hb_context = silc_calloc(1, sizeof(*hb_context));
1880   hb_context->server = server;
1881   silc_socket_set_heartbeat(sock, hearbeat_timeout, hb_context,
1882                             silc_server_perform_heartbeat,
1883                             server->schedule);
1884
1885  out:
1886   silc_schedule_task_del_by_callback(server->schedule,
1887                                      silc_server_failure_callback);
1888   silc_protocol_free(protocol);
1889   if (ctx->packet)
1890     silc_packet_context_free(ctx->packet);
1891   if (ctx->ske)
1892     silc_ske_free(ctx->ske);
1893   silc_free(ctx->dest_id);
1894   silc_server_config_unref(&ctx->cconfig);
1895   silc_server_config_unref(&ctx->sconfig);
1896   silc_server_config_unref(&ctx->rconfig);
1897   silc_free(ctx);
1898   sock->protocol = NULL;
1899 }
1900
1901 /* This function is used to read packets from network and send packets to
1902    network. This is usually a generic task. */
1903
1904 SILC_TASK_CALLBACK(silc_server_packet_process)
1905 {
1906   SilcServer server = (SilcServer)context;
1907   SilcSocketConnection sock = server->sockets[fd];
1908   SilcIDListData idata;
1909   SilcCipher cipher = NULL;
1910   SilcHmac hmac = NULL;
1911   SilcUInt32 sequence = 0;
1912   int ret;
1913
1914   if (!sock) {
1915     SILC_LOG_DEBUG(("Unknown socket connection"));
1916     return;
1917   }
1918
1919   /* Packet sending */
1920
1921   if (type == SILC_TASK_WRITE) {
1922     /* Do not send data to disconnected connection */
1923     if (SILC_IS_DISCONNECTED(sock)) {
1924       SILC_LOG_DEBUG(("Disconnected socket connection, cannot send"));
1925       return;
1926     }
1927
1928     server->stat.packets_sent++;
1929
1930     /* Send the packet */
1931     ret = silc_packet_send(sock, TRUE);
1932
1933     /* If returned -2 could not write to connection now, will do
1934        it later. */
1935     if (ret == -2)
1936       return;
1937
1938     if (ret == -1) {
1939       SILC_LOG_ERROR(("Error sending packet to connection "
1940                       "%s:%d [%s]", sock->hostname, sock->port,
1941                       (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1942                        sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1943                        sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1944                        "Router")));
1945       return;
1946     }
1947
1948     /* The packet has been sent and now it is time to set the connection
1949        back to only for input. When there is again some outgoing data
1950        available for this connection it will be set for output as well.
1951        This call clears the output setting and sets it only for input. */
1952     SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1953     SILC_UNSET_OUTBUF_PENDING(sock);
1954
1955     silc_buffer_clear(sock->outbuf);
1956     return;
1957   }
1958
1959   /* Packet receiving */
1960
1961   /* Read some data from connection */
1962   ret = silc_packet_receive(sock);
1963   if (ret < 0) {
1964
1965     if (ret == -1)
1966       SILC_LOG_ERROR(("Error receiving packet from connection "
1967                       "%s:%d [%s] %s", sock->hostname, sock->port,
1968                       (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1969                        sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1970                        sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1971                        "Router"), strerror(errno)));
1972     return;
1973   }
1974
1975   /* EOF */
1976   if (ret == 0) {
1977     SILC_LOG_DEBUG(("Read EOF"));
1978
1979     /* If connection is disconnecting already we will finally
1980        close the connection */
1981     if (SILC_IS_DISCONNECTING(sock)) {
1982       if (sock->user_data)
1983         silc_server_free_sock_user_data(server, sock, NULL);
1984       silc_server_close_connection(server, sock);
1985       return;
1986     }
1987
1988     SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1989     SILC_SET_DISCONNECTING(sock);
1990
1991     if (sock->user_data) {
1992       char tmp[128];
1993       if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
1994         silc_server_free_sock_user_data(server, sock, tmp);
1995       else
1996         silc_server_free_sock_user_data(server, sock, NULL);
1997     } else if (server->router_conn && server->router_conn->sock == sock &&
1998              !server->router && server->standalone)
1999       silc_schedule_task_add(server->schedule, 0,
2000                              silc_server_connect_to_router,
2001                              server, 1, 0,
2002                              SILC_TASK_TIMEOUT,
2003                              SILC_TASK_PRI_NORMAL);
2004
2005     silc_server_close_connection(server, sock);
2006     return;
2007   }
2008
2009   /* If connection is disconnecting or disconnected we will ignore
2010      what we read. */
2011   if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2012     SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
2013     return;
2014   }
2015
2016   /* Get keys and stuff from ID entry */
2017   idata = (SilcIDListData)sock->user_data;
2018   if (idata) {
2019     cipher = idata->receive_key;
2020     hmac = idata->hmac_receive;
2021     sequence = idata->psn_receive;
2022   }
2023
2024   /* Process the packet. This will call the parser that will then
2025      decrypt and parse the packet. */
2026   ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
2027                                     TRUE : FALSE, cipher, hmac, sequence,
2028                                     silc_server_packet_parse, server);
2029
2030   /* If this socket connection is not authenticated yet and the packet
2031      processing failed we will drop the connection since it can be
2032      a malicious flooder. */
2033   if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
2034       (!sock->protocol || sock->protocol->protocol->type ==
2035        SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
2036     SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
2037     SILC_SET_DISCONNECTING(sock);
2038
2039     if (sock->user_data)
2040       silc_server_free_sock_user_data(server, sock, NULL);
2041     silc_server_close_connection(server, sock);
2042   }
2043 }
2044
2045 /* Parses whole packet, received earlier. */
2046
2047 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
2048 {
2049   SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
2050   SilcServer server = (SilcServer)parse_ctx->context;
2051   SilcSocketConnection sock = parse_ctx->sock;
2052   SilcPacketContext *packet = parse_ctx->packet;
2053   SilcIDListData idata = (SilcIDListData)sock->user_data;
2054   int ret;
2055
2056   server->stat.packets_received++;
2057
2058   /* Parse the packet */
2059   if (parse_ctx->normal)
2060     ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
2061   else
2062     ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
2063
2064   /* If entry is disabled ignore what we got. */
2065   if (ret != SILC_PACKET_RESUME_ROUTER &&
2066       idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
2067     SILC_LOG_DEBUG(("Connection is disabled"));
2068     goto out;
2069   }
2070
2071   if (ret == SILC_PACKET_NONE) {
2072     SILC_LOG_DEBUG(("Error parsing packet"));
2073     goto out;
2074   }
2075
2076   /* Check that the the current client ID is same as in the client's packet. */
2077   if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
2078     SilcClientEntry client = (SilcClientEntry)sock->user_data;
2079     if (client && client->id) {
2080       void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
2081                                 packet->src_id_type);
2082       if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
2083         silc_free(id);
2084         SILC_LOG_DEBUG(("Packet source is not same as sender"));
2085         goto out;
2086       }
2087       silc_free(id);
2088     }
2089   }
2090
2091   if (server->server_type == SILC_ROUTER) {
2092     /* Route the packet if it is not destined to us. Other ID types but
2093        server are handled separately after processing them. */
2094     if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
2095         packet->dst_id_type == SILC_ID_SERVER &&
2096         sock->type != SILC_SOCKET_TYPE_CLIENT &&
2097         memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
2098
2099       /* Route the packet to fastest route for the destination ID */
2100       void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
2101                                 packet->dst_id_type);
2102       if (!id)
2103         goto out;
2104       silc_server_packet_route(server,
2105                                silc_server_route_get(server, id,
2106                                                      packet->dst_id_type),
2107                                packet);
2108       silc_free(id);
2109       goto out;
2110     }
2111   }
2112
2113   /* Parse the incoming packet type */
2114   silc_server_packet_parse_type(server, sock, packet);
2115
2116   /* Broadcast packet if it is marked as broadcast packet and it is
2117      originated from router and we are router. */
2118   if (server->server_type == SILC_ROUTER &&
2119       sock->type == SILC_SOCKET_TYPE_ROUTER &&
2120       packet->flags & SILC_PACKET_FLAG_BROADCAST) {
2121     /* Broadcast to our primary route */
2122     silc_server_packet_broadcast(server, SILC_PRIMARY_ROUTE(server), packet);
2123
2124     /* If we have backup routers then we need to feed all broadcast
2125        data to those servers. */
2126     silc_server_backup_broadcast(server, sock, packet);
2127   }
2128
2129  out:
2130   silc_packet_context_free(packet);
2131   silc_free(parse_ctx);
2132 }
2133
2134 /* Parser callback called by silc_packet_receive_process. This merely
2135    registers timeout that will handle the actual parsing when appropriate. */
2136
2137 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
2138                               void *context)
2139 {
2140   SilcServer server = (SilcServer)context;
2141   SilcSocketConnection sock = parser_context->sock;
2142   SilcIDListData idata = (SilcIDListData)sock->user_data;
2143
2144   if (idata)
2145     idata->psn_receive = parser_context->packet->sequence + 1;
2146
2147   /* If protocol for this connection is key exchange or rekey then we'll
2148      process all packets synchronously, since there might be packets in
2149      queue that we are not able to decrypt without first processing the
2150      packets before them. */
2151   if ((parser_context->packet->type == SILC_PACKET_REKEY ||
2152        parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
2153       (sock->protocol && sock->protocol->protocol &&
2154        (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2155         sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
2156     silc_server_packet_parse_real(server->schedule, 0, sock->sock,
2157                                   parser_context);
2158
2159     /* Reprocess data since we'll return FALSE here.  This is because
2160        the idata->receive_key might have become valid in the last packet
2161        and we want to call this processor with valid cipher. */
2162     if (idata)
2163       silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
2164                                   TRUE : FALSE, idata->receive_key,
2165                                   idata->hmac_receive, idata->psn_receive,
2166                                   silc_server_packet_parse, server);
2167     else
2168       silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
2169                                   TRUE : FALSE, NULL, NULL, 0,
2170                                   silc_server_packet_parse, server);
2171     return FALSE;
2172   }
2173
2174   switch (sock->type) {
2175   case SILC_SOCKET_TYPE_UNKNOWN:
2176   case SILC_SOCKET_TYPE_CLIENT:
2177     /* Parse the packet with timeout */
2178     silc_schedule_task_add(server->schedule, sock->sock,
2179                            silc_server_packet_parse_real,
2180                            (void *)parser_context, 0, 100000,
2181                            SILC_TASK_TIMEOUT,
2182                            SILC_TASK_PRI_NORMAL);
2183     break;
2184   case SILC_SOCKET_TYPE_SERVER:
2185   case SILC_SOCKET_TYPE_ROUTER:
2186     /* Packets from servers are parsed immediately */
2187     silc_server_packet_parse_real(server->schedule, 0, sock->sock,
2188                                   parser_context);
2189     break;
2190   default:
2191     return TRUE;
2192   }
2193
2194   return TRUE;
2195 }
2196
2197 /* Parses the packet type and calls what ever routines the packet type
2198    requires. This is done for all incoming packets. */
2199
2200 void silc_server_packet_parse_type(SilcServer server,
2201                                    SilcSocketConnection sock,
2202                                    SilcPacketContext *packet)
2203 {
2204   SilcPacketType type = packet->type;
2205   SilcIDListData idata = (SilcIDListData)sock->user_data;
2206
2207   SILC_LOG_DEBUG(("Received %s packet [flags %d]",
2208                   silc_get_packet_name(type), packet->flags));
2209
2210   /* Parse the packet type */
2211   switch (type) {
2212   case SILC_PACKET_DISCONNECT:
2213     {
2214       SilcStatus status;
2215       char *message = NULL;
2216
2217       if (packet->flags & SILC_PACKET_FLAG_LIST)
2218         break;
2219       if (packet->buffer->len < 1)
2220         break;
2221
2222       status = (SilcStatus)packet->buffer->data[0];
2223       if (packet->buffer->len > 1 &&
2224           silc_utf8_valid(packet->buffer->data + 1, packet->buffer->len - 1))
2225         message = silc_memdup(packet->buffer->data + 1,
2226                               packet->buffer->len - 1);
2227
2228       SILC_LOG_INFO(("Disconnected by %s (%s): %s (%d) %s", 
2229                      sock->ip, sock->hostname,
2230                      silc_get_status_message(status), status,
2231                      message ? message : ""));
2232       silc_free(message);
2233     }
2234     break;
2235
2236   case SILC_PACKET_SUCCESS:
2237     /*
2238      * Success received for something. For now we can have only
2239      * one protocol for connection executing at once hence this
2240      * success message is for whatever protocol is executing currently.
2241      */
2242     if (packet->flags & SILC_PACKET_FLAG_LIST)
2243       break;
2244     if (sock->protocol)
2245       silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2246     break;
2247
2248   case SILC_PACKET_FAILURE:
2249     /*
2250      * Failure received for something. For now we can have only
2251      * one protocol for connection executing at once hence this
2252      * failure message is for whatever protocol is executing currently.
2253      */
2254     if (packet->flags & SILC_PACKET_FLAG_LIST)
2255       break;
2256     if (sock->protocol) {
2257       SilcServerFailureContext f;
2258       f = silc_calloc(1, sizeof(*f));
2259       f->server = server;
2260       f->sock = sock;
2261
2262       /* We will wait 5 seconds to process this failure packet */
2263       silc_schedule_task_add(server->schedule, sock->sock,
2264                          silc_server_failure_callback, (void *)f, 5, 0,
2265                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2266     }
2267     break;
2268
2269   case SILC_PACKET_REJECT:
2270     if (packet->flags & SILC_PACKET_FLAG_LIST)
2271       break;
2272     return;
2273     break;
2274
2275   case SILC_PACKET_NOTIFY:
2276     /*
2277      * Received notify packet. Server can receive notify packets from
2278      * router. Server then relays the notify messages to clients if needed.
2279      */
2280     if (packet->flags & SILC_PACKET_FLAG_LIST)
2281       silc_server_notify_list(server, sock, packet);
2282     else
2283       silc_server_notify(server, sock, packet);
2284     break;
2285
2286     /*
2287      * Channel packets
2288      */
2289   case SILC_PACKET_CHANNEL_MESSAGE:
2290     /*
2291      * Received channel message. Channel messages are special packets
2292      * (although probably most common ones) thus they are handled
2293      * specially.
2294      */
2295     if (packet->flags & SILC_PACKET_FLAG_LIST)
2296       break;
2297     idata->last_receive = time(NULL);
2298     silc_server_channel_message(server, sock, packet);
2299     break;
2300
2301   case SILC_PACKET_CHANNEL_KEY:
2302     /*
2303      * Received key for channel. As channels are created by the router
2304      * the keys are as well. We will distribute the key to all of our
2305      * locally connected clients on the particular channel. Router
2306      * never receives this channel and thus is ignored.
2307      */
2308     if (packet->flags & SILC_PACKET_FLAG_LIST)
2309       break;
2310     silc_server_channel_key(server, sock, packet);
2311     break;
2312
2313     /*
2314      * Command packets
2315      */
2316   case SILC_PACKET_COMMAND:
2317     /*
2318      * Recived command. Processes the command request and allocates the
2319      * command context and calls the command.
2320      */
2321     if (packet->flags & SILC_PACKET_FLAG_LIST)
2322       break;
2323     silc_server_command_process(server, sock, packet);
2324     break;
2325
2326   case SILC_PACKET_COMMAND_REPLY:
2327     /*
2328      * Received command reply packet. Received command reply to command. It
2329      * may be reply to command sent by us or reply to command sent by client
2330      * that we've routed further.
2331      */
2332     if (packet->flags & SILC_PACKET_FLAG_LIST)
2333       break;
2334     silc_server_command_reply(server, sock, packet);
2335     break;
2336
2337     /*
2338      * Private Message packets
2339      */
2340   case SILC_PACKET_PRIVATE_MESSAGE:
2341     /*
2342      * Received private message packet. The packet is coming from either
2343      * client or server.
2344      */
2345     if (packet->flags & SILC_PACKET_FLAG_LIST)
2346       break;
2347     idata->last_receive = time(NULL);
2348     silc_server_private_message(server, sock, packet);
2349     break;
2350
2351   case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2352     /*
2353      * Private message key packet.
2354      */
2355     if (packet->flags & SILC_PACKET_FLAG_LIST)
2356       break;
2357     silc_server_private_message_key(server, sock, packet);
2358     break;
2359
2360     /*
2361      * Key Exchange protocol packets
2362      */
2363   case SILC_PACKET_KEY_EXCHANGE:
2364     if (packet->flags & SILC_PACKET_FLAG_LIST)
2365       break;
2366
2367     if (sock->protocol && sock->protocol->protocol &&
2368         sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2369       SilcServerKEInternalContext *proto_ctx =
2370         (SilcServerKEInternalContext *)sock->protocol->context;
2371
2372       proto_ctx->packet = silc_packet_context_dup(packet);
2373
2374       /* Let the protocol handle the packet */
2375       silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2376     } else {
2377       SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2378                       "protocol active, packet dropped."));
2379     }
2380     break;
2381
2382   case SILC_PACKET_KEY_EXCHANGE_1:
2383     if (packet->flags & SILC_PACKET_FLAG_LIST)
2384       break;
2385
2386     if (sock->protocol && sock->protocol->protocol &&
2387         (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2388          sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2389
2390       if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2391         SilcServerRekeyInternalContext *proto_ctx =
2392           (SilcServerRekeyInternalContext *)sock->protocol->context;
2393
2394         if (proto_ctx->packet)
2395           silc_packet_context_free(proto_ctx->packet);
2396
2397         proto_ctx->packet = silc_packet_context_dup(packet);
2398
2399         /* Let the protocol handle the packet */
2400         silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2401       } else {
2402         SilcServerKEInternalContext *proto_ctx =
2403           (SilcServerKEInternalContext *)sock->protocol->context;
2404
2405         if (proto_ctx->packet)
2406           silc_packet_context_free(proto_ctx->packet);
2407
2408         proto_ctx->packet = silc_packet_context_dup(packet);
2409         proto_ctx->dest_id_type = packet->src_id_type;
2410         proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2411                                             packet->src_id_type);
2412         if (!proto_ctx->dest_id)
2413           break;
2414
2415         /* Let the protocol handle the packet */
2416         silc_protocol_execute(sock->protocol, server->schedule,
2417                               0, 100000);
2418       }
2419     } else {
2420       SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2421                       "protocol active, packet dropped."));
2422     }
2423     break;
2424
2425   case SILC_PACKET_KEY_EXCHANGE_2:
2426     if (packet->flags & SILC_PACKET_FLAG_LIST)
2427       break;
2428
2429     if (sock->protocol && sock->protocol->protocol &&
2430         (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2431          sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2432
2433       if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2434         SilcServerRekeyInternalContext *proto_ctx =
2435           (SilcServerRekeyInternalContext *)sock->protocol->context;
2436
2437         if (proto_ctx->packet)
2438           silc_packet_context_free(proto_ctx->packet);
2439
2440         proto_ctx->packet = silc_packet_context_dup(packet);
2441
2442         /* Let the protocol handle the packet */
2443         silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2444       } else {
2445         SilcServerKEInternalContext *proto_ctx =
2446           (SilcServerKEInternalContext *)sock->protocol->context;
2447
2448         if (proto_ctx->packet)
2449           silc_packet_context_free(proto_ctx->packet);
2450
2451         proto_ctx->packet = silc_packet_context_dup(packet);
2452         proto_ctx->dest_id_type = packet->src_id_type;
2453         proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2454                                             packet->src_id_type);
2455         if (!proto_ctx->dest_id)
2456           break;
2457
2458         /* Let the protocol handle the packet */
2459         silc_protocol_execute(sock->protocol, server->schedule,
2460                               0, 100000);
2461       }
2462     } else {
2463       SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2464                       "protocol active, packet dropped."));
2465     }
2466     break;
2467
2468   case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2469     /*
2470      * Connection authentication request packet. When we receive this packet
2471      * we will send to the other end information about our mandatory
2472      * authentication method for the connection. This packet maybe received
2473      * at any time.
2474      */
2475     if (packet->flags & SILC_PACKET_FLAG_LIST)
2476       break;
2477     silc_server_connection_auth_request(server, sock, packet);
2478     break;
2479
2480     /*
2481      * Connection Authentication protocol packets
2482      */
2483   case SILC_PACKET_CONNECTION_AUTH:
2484     /* Start of the authentication protocol. We receive here the
2485        authentication data and will verify it. */
2486     if (packet->flags & SILC_PACKET_FLAG_LIST)
2487       break;
2488
2489     if (sock->protocol && sock->protocol->protocol->type
2490         == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2491
2492       SilcServerConnAuthInternalContext *proto_ctx =
2493         (SilcServerConnAuthInternalContext *)sock->protocol->context;
2494
2495       proto_ctx->packet = silc_packet_context_dup(packet);
2496
2497       /* Let the protocol handle the packet */
2498       silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2499     } else {
2500       SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2501                       "protocol active, packet dropped."));
2502     }
2503     break;
2504
2505   case SILC_PACKET_NEW_ID:
2506     /*
2507      * Received New ID packet. This includes some new ID that has been
2508      * created. It may be for client, server or channel. This is the way
2509      * to distribute information about new registered entities in the
2510      * SILC network.
2511      */
2512     if (packet->flags & SILC_PACKET_FLAG_LIST)
2513       silc_server_new_id_list(server, sock, packet);
2514     else
2515       silc_server_new_id(server, sock, packet);
2516     break;
2517
2518   case SILC_PACKET_NEW_CLIENT:
2519     /*
2520      * Received new client packet. This includes client information that
2521      * we will use to create initial client ID. After creating new
2522      * ID we will send it to the client.
2523      */
2524     if (packet->flags & SILC_PACKET_FLAG_LIST)
2525       break;
2526     silc_server_new_client(server, sock, packet);
2527     break;
2528
2529   case SILC_PACKET_NEW_SERVER:
2530     /*
2531      * Received new server packet. This includes Server ID and some other
2532      * information that we may save. This is received after server has
2533      * connected to us.
2534      */
2535     if (packet->flags & SILC_PACKET_FLAG_LIST)
2536       break;
2537     silc_server_new_server(server, sock, packet);
2538     break;
2539
2540   case SILC_PACKET_NEW_CHANNEL:
2541     /*
2542      * Received new channel packet. Information about new channel in the
2543      * network are distributed using this packet.
2544      */
2545     if (packet->flags & SILC_PACKET_FLAG_LIST)
2546       silc_server_new_channel_list(server, sock, packet);
2547     else
2548       silc_server_new_channel(server, sock, packet);
2549     break;
2550
2551   case SILC_PACKET_HEARTBEAT:
2552     /*
2553      * Received heartbeat.
2554      */
2555     if (packet->flags & SILC_PACKET_FLAG_LIST)
2556       break;
2557     break;
2558
2559   case SILC_PACKET_KEY_AGREEMENT:
2560     /*
2561      * Received heartbeat.
2562      */
2563     if (packet->flags & SILC_PACKET_FLAG_LIST)
2564       break;
2565     silc_server_key_agreement(server, sock, packet);
2566     break;
2567
2568   case SILC_PACKET_REKEY:
2569     /*
2570      * Received re-key packet. The sender wants to regenerate the session
2571      * keys.
2572      */
2573     if (packet->flags & SILC_PACKET_FLAG_LIST)
2574       break;
2575     silc_server_rekey(server, sock, packet);
2576     break;
2577
2578   case SILC_PACKET_REKEY_DONE:
2579     /*
2580      * The re-key is done.
2581      */
2582     if (packet->flags & SILC_PACKET_FLAG_LIST)
2583       break;
2584
2585     if (sock->protocol && sock->protocol->protocol &&
2586         sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2587
2588       SilcServerRekeyInternalContext *proto_ctx =
2589         (SilcServerRekeyInternalContext *)sock->protocol->context;
2590
2591       if (proto_ctx->packet)
2592         silc_packet_context_free(proto_ctx->packet);
2593
2594       proto_ctx->packet = silc_packet_context_dup(packet);
2595
2596       /* Let the protocol handle the packet */
2597       silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2598     } else {
2599       SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2600                       "protocol active, packet dropped."));
2601     }
2602     break;
2603
2604   case SILC_PACKET_FTP:
2605     /* FTP packet */
2606     if (packet->flags & SILC_PACKET_FLAG_LIST)
2607       break;
2608     silc_server_ftp(server, sock, packet);
2609     break;
2610
2611   case SILC_PACKET_RESUME_CLIENT:
2612     /* Resume client */
2613     if (packet->flags & SILC_PACKET_FLAG_LIST)
2614       break;
2615     silc_server_resume_client(server, sock, packet);
2616     break;
2617
2618   case SILC_PACKET_RESUME_ROUTER:
2619     /* Resume router packet received. This packet is received for backup
2620        router resuming protocol. */
2621     if (packet->flags & SILC_PACKET_FLAG_LIST)
2622       break;
2623     silc_server_backup_resume_router(server, sock, packet);
2624     break;
2625
2626   default:
2627     SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2628     break;
2629   }
2630 }
2631
2632 /* Creates connection to a remote router. */
2633
2634 void silc_server_create_connection(SilcServer server,
2635                                    const char *remote_host, SilcUInt32 port)
2636 {
2637   SilcServerConnection sconn;
2638
2639   /* Allocate connection object for hold connection specific stuff. */
2640   sconn = silc_calloc(1, sizeof(*sconn));
2641   sconn->server = server;
2642   sconn->remote_host = strdup(remote_host);
2643   sconn->remote_port = port;
2644   sconn->no_reconnect = TRUE;
2645
2646   silc_schedule_task_add(server->schedule, 0,
2647                          silc_server_connect_router,
2648                          (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2649                          SILC_TASK_PRI_NORMAL);
2650 }
2651
2652 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2653 {
2654   silc_socket_free(context);
2655 }
2656
2657 /* Closes connection to socket connection */
2658
2659 void silc_server_close_connection(SilcServer server,
2660                                   SilcSocketConnection sock)
2661 {
2662   if (!server->sockets[sock->sock] && SILC_IS_DISCONNECTED(sock)) {
2663     silc_socket_free(sock);
2664     return;
2665   }
2666
2667   SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2668                   sock->port,
2669                   (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2670                    sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2671                    sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2672                    "Router")));
2673
2674   /* We won't listen for this connection anymore */
2675   silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2676
2677   /* Unregister all tasks */
2678   silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2679
2680   /* Close the actual connection */
2681   silc_net_close_connection(sock->sock);
2682   server->sockets[sock->sock] = NULL;
2683
2684   /* If sock->user_data is NULL then we'll check for active protocols
2685      here since the silc_server_free_sock_user_data has not been called
2686      for this connection. */
2687   if (!sock->user_data) {
2688     /* If any protocol is active cancel its execution. It will call
2689        the final callback which will finalize the disconnection. */
2690     if (sock->protocol) {
2691       SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
2692       silc_protocol_cancel(sock->protocol, server->schedule);
2693       sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2694       silc_protocol_execute_final(sock->protocol, server->schedule);
2695       sock->protocol = NULL;
2696       return;
2697     }
2698   }
2699
2700   silc_schedule_task_add(server->schedule, 0,
2701                          silc_server_close_connection_final,
2702                          (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2703                          SILC_TASK_PRI_NORMAL);
2704 }
2705
2706 /* Sends disconnect message to remote connection and disconnects the
2707    connection. */
2708
2709 void silc_server_disconnect_remote(SilcServer server,
2710                                    SilcSocketConnection sock,
2711                                    SilcStatus status, ...)
2712 {
2713   va_list ap;
2714   unsigned char buf[512];
2715   SilcBuffer buffer;
2716   char *cp;
2717   int len;
2718
2719   if (!sock)
2720     return;
2721
2722   memset(buf, 0, sizeof(buf));
2723   va_start(ap, status);
2724   cp = va_arg(ap, char *);
2725   if (cp) {
2726     vsnprintf(buf, sizeof(buf) - 1, cp, ap);
2727     cp = buf;
2728   }
2729   va_end(ap);
2730
2731   SILC_LOG_DEBUG(("Disconnecting remote host"));
2732
2733   /* Notify remote end that the conversation is over. The notify message
2734      is tried to be sent immediately. */
2735
2736   len = 1;
2737   if (cp)
2738     len += silc_utf8_encoded_len(buf, strlen(buf), SILC_STRING_ASCII);
2739
2740   buffer = silc_buffer_alloc_size(len);
2741   if (!buffer)
2742     goto out;
2743
2744   buffer->data[0] = status;
2745   if (cp)
2746     silc_utf8_encode(buf, strlen(buf), SILC_STRING_ASCII, buffer->data + 1,
2747                      buffer->len - 1);
2748   silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2749                           buffer->data, buffer->len, TRUE);
2750   silc_buffer_free(buffer);
2751
2752  out:
2753   silc_server_packet_queue_purge(server, sock);
2754
2755   /* Mark the connection to be disconnected */
2756   SILC_SET_DISCONNECTED(sock);
2757   silc_server_close_connection(server, sock);
2758 }
2759
2760 typedef struct {
2761   SilcServer server;
2762   SilcClientEntry client;
2763 } *FreeClientInternal;
2764
2765 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2766 {
2767   FreeClientInternal i = (FreeClientInternal)context;
2768
2769   silc_idlist_del_data(i->client);
2770   silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2771   silc_free(i);
2772 }
2773
2774 /* Frees client data and notifies about client's signoff. */
2775
2776 void silc_server_free_client_data(SilcServer server,
2777                                   SilcSocketConnection sock,
2778                                   SilcClientEntry client,
2779                                   int notify,
2780                                   const char *signoff)
2781 {
2782   FreeClientInternal i = silc_calloc(1, sizeof(*i));
2783
2784   SILC_LOG_DEBUG(("Freeing client data"));
2785
2786 #if 1
2787   if (!client->router && !client->connection &&
2788       !(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
2789     SILC_LOG_ERROR(("****** freeing data for already unregistered client -s"));
2790     SILC_LOG_ERROR(("****** Contact Pekka"));
2791     SILC_LOG_ERROR(("****** freeing data for already unregistered client -e"));
2792     return;
2793   }
2794 #endif
2795
2796   /* If there is pending outgoing data for the client then purge it
2797      to the network before removing the client entry. */
2798   silc_server_packet_queue_purge(server, sock);
2799
2800   if (client->id) {
2801     /* Check if anyone is watching this nickname */
2802     if (server->server_type == SILC_ROUTER)
2803       silc_server_check_watcher_list(server, client, NULL,
2804                                      SILC_NOTIFY_TYPE_SIGNOFF);
2805
2806     /* Send SIGNOFF notify to routers. */
2807     if (notify)
2808       silc_server_send_notify_signoff(server, SILC_PRIMARY_ROUTE(server),
2809                                       SILC_BROADCAST(server), client->id,
2810                                       signoff);
2811   }
2812
2813   /* Remove client from all channels */
2814   if (notify)
2815     silc_server_remove_from_channels(server, NULL, client,
2816                                      TRUE, (char *)signoff, TRUE);
2817   else
2818     silc_server_remove_from_channels(server, NULL, client,
2819                                      FALSE, NULL, FALSE);
2820
2821   /* Remove this client from watcher list if it is */
2822   silc_server_del_from_watcher_list(server, client);
2823
2824   /* Update statistics */
2825   server->stat.my_clients--;
2826   server->stat.clients--;
2827   if (server->stat.cell_clients)
2828     server->stat.cell_clients--;
2829   SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2830   SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2831   silc_schedule_task_del_by_context(server->schedule, client);
2832
2833   /* We will not delete the client entry right away. We will take it
2834      into history (for WHOWAS command) for 5 minutes */
2835   i->server = server;
2836   i->client = client;
2837   silc_schedule_task_add(server->schedule, 0,
2838                          silc_server_free_client_data_timeout,
2839                          (void *)i, 300, 0,
2840                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2841   client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2842   client->mode = 0;
2843   client->router = NULL;
2844   client->connection = NULL;
2845 }
2846
2847 /* Frees user_data pointer from socket connection object. This also sends
2848    appropriate notify packets to the network to inform about leaving
2849    entities. */
2850
2851 void silc_server_free_sock_user_data(SilcServer server,
2852                                      SilcSocketConnection sock,
2853                                      const char *signoff_message)
2854 {
2855   switch (sock->type) {
2856   case SILC_SOCKET_TYPE_CLIENT:
2857     {
2858       SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2859       silc_server_free_client_data(server, sock, user_data, TRUE,
2860                                    signoff_message);
2861       break;
2862     }
2863   case SILC_SOCKET_TYPE_SERVER:
2864   case SILC_SOCKET_TYPE_ROUTER:
2865     {
2866       SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2867       SilcServerEntry backup_router = NULL;
2868
2869       SILC_LOG_DEBUG(("Freeing server data"));
2870
2871       if (user_data->id)
2872         backup_router = silc_server_backup_get(server, user_data->id);
2873
2874       /* If this was our primary router connection then we're lost to
2875          the outside world. */
2876       if (server->router == user_data) {
2877         /* Check whether we have a backup router connection */
2878         if (!backup_router || backup_router == user_data) {
2879           silc_schedule_task_add(server->schedule, 0,
2880                                  silc_server_connect_to_router,
2881                                  server, 1, 0,
2882                                  SILC_TASK_TIMEOUT,
2883                                  SILC_TASK_PRI_NORMAL);
2884
2885           server->id_entry->router = NULL;
2886           server->router = NULL;
2887           server->standalone = TRUE;
2888           backup_router = NULL;
2889         } else {
2890           if (server->id_entry == backup_router) {
2891             SILC_LOG_INFO(("We are now new router in this cell"));
2892             SILC_LOG_DEBUG(("We are now new router in this cell"));
2893           } else {
2894             SILC_LOG_INFO(("New primary router is backup router %s",
2895                            backup_router->server_name));
2896             SILC_LOG_DEBUG(("New primary router is backup router %s",
2897                             backup_router->server_name));
2898           }
2899           if (server->id_entry != backup_router) {
2900             server->id_entry->router = backup_router;
2901             server->router = backup_router;
2902             server->router_connect = time(0);
2903             server->backup_primary = TRUE;
2904           } else {
2905             server->id_entry->router = NULL;
2906             server->router = NULL;
2907             server->standalone = TRUE;
2908           }
2909
2910           if (server->server_type == SILC_BACKUP_ROUTER) {
2911             server->server_type = SILC_ROUTER;
2912
2913             /* We'll need to constantly try to reconnect to the primary
2914                router so that we'll see when it comes back online. */
2915             silc_server_backup_reconnect(server, sock->ip, sock->port,
2916                                          silc_server_backup_connected,
2917                                          NULL);
2918           }
2919
2920           /* Mark this connection as replaced */
2921           silc_server_backup_replaced_add(server, user_data->id,
2922                                           backup_router);
2923         }
2924       } else if (backup_router) {
2925         SILC_LOG_INFO(("Enabling the use of backup router %s",
2926                        backup_router->server_name));
2927         SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2928                         backup_router->server_name));
2929
2930         /* Mark this connection as replaced */
2931         silc_server_backup_replaced_add(server, user_data->id,
2932                                         backup_router);
2933       }
2934
2935       if (!backup_router) {
2936         /* As router, remove clients and channels always.  As normal server
2937            remove only if it is our primary router.  Other connections
2938            may be backup routers and these normal server don't handle here. */
2939         if (server->server_type != SILC_SERVER ||
2940             server->standalone || sock == SILC_PRIMARY_ROUTE(server)) {
2941           /* Free all client entries that this server owns as they will
2942              become invalid now as well. */
2943           silc_server_remove_clients_by_server(server, user_data, TRUE);
2944           if (server->server_type == SILC_SERVER)
2945             silc_server_remove_channels_by_server(server, user_data);
2946         }
2947       } else {
2948         /* Update the client entries of this server to the new backup
2949            router. This also removes the clients that *really* was owned
2950            by the primary router and went down with the router.  */
2951         silc_server_update_clients_by_server(server, user_data, backup_router,
2952                                              TRUE, TRUE);
2953         silc_server_update_servers_by_server(server, user_data, backup_router,
2954                                              TRUE);
2955         if (server->server_type == SILC_SERVER)
2956           silc_server_update_channels_by_server(server, user_data,
2957                                                 backup_router);
2958
2959         /* Send notify about primary router going down to local operators */
2960         if (server->backup_router)
2961           SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
2962                                  SILC_NOTIFY_TYPE_NONE,
2963                                  ("%s switched to backup router %s "
2964                                   "(we are primary router now)",
2965                                   server->server_name, server->server_name));
2966         else
2967           SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
2968                                  SILC_NOTIFY_TYPE_NONE,
2969                                  ("%s switched to backup router %s",
2970                                   server->server_name,
2971                                   server->router->server_name));
2972       }
2973
2974       /* Free the server entry */
2975       silc_server_backup_del(server, user_data);
2976       silc_server_backup_replaced_del(server, user_data);
2977       silc_idlist_del_data(user_data);
2978       if (!silc_idlist_del_server(server->local_list, user_data))
2979         silc_idlist_del_server(server->global_list, user_data);
2980       if (sock->type == SILC_SOCKET_TYPE_SERVER) {
2981         server->stat.my_servers--;
2982       } else {
2983         server->stat.my_routers--;
2984         server->stat.routers--;
2985       }
2986       server->stat.servers--;
2987       if (server->server_type == SILC_ROUTER)
2988         server->stat.cell_servers--;
2989
2990       if (backup_router && backup_router != server->id_entry) {
2991         /* Announce all of our stuff that was created about 5 minutes ago.
2992            The backup router knows all the other stuff already. */
2993         if (server->server_type == SILC_ROUTER)
2994           silc_server_announce_servers(server, FALSE, time(0) - 300,
2995                                        backup_router->connection);
2996
2997         /* Announce our clients and channels to the router */
2998         silc_server_announce_clients(server, time(0) - 300,
2999                                      backup_router->connection);
3000         silc_server_announce_channels(server, time(0) - 300,
3001                                       backup_router->connection);
3002       }
3003       break;
3004     }
3005   default:
3006     {
3007       SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
3008
3009       SILC_LOG_DEBUG(("Freeing unknown connection data"));
3010
3011       silc_idlist_del_data(user_data);
3012       silc_free(user_data);
3013       break;
3014     }
3015   }
3016
3017   /* If any protocol is active cancel its execution */
3018   if (sock->protocol) {
3019     SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3020     silc_protocol_cancel(sock->protocol, server->schedule);
3021     sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3022     silc_protocol_execute_final(sock->protocol, server->schedule);
3023     sock->protocol = NULL;
3024   }
3025
3026   sock->user_data = NULL;
3027 }
3028
3029 /* Removes client from all channels it has joined. This is used when client
3030    connection is disconnected. If the client on a channel is last, the
3031    channel is removed as well. This sends the SIGNOFF notify types. */
3032
3033 void silc_server_remove_from_channels(SilcServer server,
3034                                       SilcSocketConnection sock,
3035                                       SilcClientEntry client,
3036                                       bool notify,
3037                                       const char *signoff_message,
3038                                       bool keygen)
3039 {
3040   SilcChannelEntry channel;
3041   SilcChannelClientEntry chl;
3042   SilcHashTableList htl;
3043   SilcBuffer clidp = NULL;
3044
3045   if (!client)
3046     return;
3047
3048   SILC_LOG_DEBUG(("Removing client from joined channels"));
3049
3050   if (notify && !client->id)
3051     notify = FALSE;
3052
3053   if (notify) {
3054     clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3055     if (!clidp)
3056       notify = FALSE;
3057   }
3058
3059   /* Remove the client from all channels. The client is removed from
3060      the channels' user list. */
3061   silc_hash_table_list(client->channels, &htl);
3062   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3063     channel = chl->channel;
3064
3065     /* Remove channel if this is last client leaving the channel, unless
3066        the channel is permanent. */
3067     if (server->server_type == SILC_ROUTER &&
3068         silc_hash_table_count(channel->user_list) < 2) {
3069       silc_server_channel_delete(server, channel);
3070       continue;
3071     }
3072
3073     silc_hash_table_del(client->channels, channel);
3074     silc_hash_table_del(channel->user_list, chl->client);
3075     channel->user_count--;
3076
3077     /* If there is no global users on the channel anymore mark the channel
3078        as local channel. Do not check if the removed client is local client. */
3079     if (server->server_type != SILC_ROUTER && channel->global_users &&
3080         chl->client->router && !silc_server_channel_has_global(channel))
3081       channel->global_users = FALSE;
3082
3083     silc_free(chl);
3084
3085     /* Update statistics */
3086     if (SILC_IS_LOCAL(client))
3087       server->stat.my_chanclients--;
3088     if (server->server_type == SILC_ROUTER) {
3089       server->stat.cell_chanclients--;
3090       server->stat.chanclients--;
3091     }
3092
3093     /* If there is not at least one local user on the channel then we don't
3094        need the channel entry anymore, we can remove it safely, unless the
3095        channel is permanent channel */
3096     if (server->server_type != SILC_ROUTER &&
3097         !silc_server_channel_has_local(channel)) {
3098       /* Notify about leaving client if this channel has global users. */
3099       if (notify && channel->global_users)
3100         silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3101                                            SILC_NOTIFY_TYPE_SIGNOFF,
3102                                            signoff_message ? 2 : 1,
3103                                            clidp->data, clidp->len,
3104                                            signoff_message, signoff_message ?
3105                                            strlen(signoff_message) : 0);
3106
3107       silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3108       silc_server_channel_delete(server, channel);
3109       continue;
3110     }
3111
3112     /* Send notify to channel about client leaving SILC and channel too */
3113     if (notify)
3114       silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3115                                          SILC_NOTIFY_TYPE_SIGNOFF,
3116                                          signoff_message ? 2 : 1,
3117                                          clidp->data, clidp->len,
3118                                          signoff_message, signoff_message ?
3119                                          strlen(signoff_message) : 0);
3120
3121     /* Re-generate channel key if needed */
3122     if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3123       if (!silc_server_create_channel_key(server, channel, 0))
3124         continue;
3125
3126       /* Send the channel key to the channel. The key of course is not sent
3127          to the client who was removed from the channel. */
3128       silc_server_send_channel_key(server, client->connection, channel,
3129                                    server->server_type == SILC_ROUTER ?
3130                                    FALSE : !server->standalone);
3131     }
3132   }
3133
3134   silc_hash_table_list_reset(&htl);
3135   if (clidp)
3136     silc_buffer_free(clidp);
3137 }
3138
3139 /* Removes client from one channel. This is used for example when client
3140    calls LEAVE command to remove itself from the channel. Returns TRUE
3141    if channel still exists and FALSE if the channel is removed when
3142    last client leaves the channel. If `notify' is FALSE notify messages
3143    are not sent. */
3144
3145 bool silc_server_remove_from_one_channel(SilcServer server,
3146                                          SilcSocketConnection sock,
3147                                          SilcChannelEntry channel,
3148                                          SilcClientEntry client,
3149                                          bool notify)
3150 {
3151   SilcChannelClientEntry chl;
3152   SilcBuffer clidp;
3153
3154   SILC_LOG_DEBUG(("Removing %s from channel %s",
3155                   silc_id_render(client->id, SILC_ID_CLIENT), 
3156                   channel->channel_name));
3157
3158   /* Get the entry to the channel, if this client is not on the channel
3159      then return Ok. */
3160   if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
3161     return TRUE;
3162
3163   /* Remove channel if this is last client leaving the channel, unless
3164      the channel is permanent. */
3165   if (server->server_type == SILC_ROUTER &&
3166       silc_hash_table_count(channel->user_list) < 2) {
3167     silc_server_channel_delete(server, channel);
3168     return FALSE;
3169   }
3170
3171   silc_hash_table_del(client->channels, chl->channel);
3172   silc_hash_table_del(channel->user_list, chl->client);
3173   channel->user_count--;
3174
3175   /* If there is no global users on the channel anymore mark the channel
3176      as local channel. Do not check if the client is local client. */
3177   if (server->server_type != SILC_ROUTER && channel->global_users &&
3178       chl->client->router && !silc_server_channel_has_global(channel))
3179     channel->global_users = FALSE;
3180
3181   silc_free(chl);
3182
3183   /* Update statistics */
3184   if (SILC_IS_LOCAL(client))
3185     server->stat.my_chanclients--;
3186   if (server->server_type == SILC_ROUTER) {
3187     server->stat.cell_chanclients--;
3188     server->stat.chanclients--;
3189   }
3190
3191   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3192   if (!clidp)
3193     notify = FALSE;
3194
3195   /* If there is not at least one local user on the channel then we don't
3196      need the channel entry anymore, we can remove it safely, unless the
3197      channel is permanent channel */
3198   if (server->server_type != SILC_ROUTER &&
3199       !silc_server_channel_has_local(channel)) {
3200     /* Notify about leaving client if this channel has global users. */
3201     if (notify && channel->global_users)
3202       silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3203                                          SILC_NOTIFY_TYPE_LEAVE, 1,
3204                                          clidp->data, clidp->len);
3205
3206     silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3207     silc_server_channel_delete(server, channel);
3208     silc_buffer_free(clidp);
3209     return FALSE;
3210   }
3211
3212   /* Send notify to channel about client leaving the channel */
3213   if (notify)
3214     silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3215                                        SILC_NOTIFY_TYPE_LEAVE, 1,
3216                                        clidp->data, clidp->len);
3217
3218   silc_buffer_free(clidp);
3219   return TRUE;
3220 }
3221
3222 /* Timeout callback. This is called if connection is idle or for some
3223    other reason is not responding within some period of time. This
3224    disconnects the remote end. */
3225
3226 SILC_TASK_CALLBACK(silc_server_timeout_remote)
3227 {
3228   SilcServer server = (SilcServer)context;
3229   SilcSocketConnection sock = server->sockets[fd];
3230   SilcProtocolType protocol = 0;
3231
3232   SILC_LOG_DEBUG(("Start"));
3233
3234   if (!sock)
3235     return;
3236
3237   SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
3238                   sock->hostname, sock->ip));
3239
3240   /* If we have protocol active we must assure that we call the protocol's
3241      final callback so that all the memory is freed. */
3242   if (sock->protocol) {
3243     protocol = sock->protocol->protocol->type;
3244     silc_protocol_cancel(sock->protocol, server->schedule);
3245     sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3246     silc_protocol_execute_final(sock->protocol, server->schedule);
3247     sock->protocol = NULL;
3248     return;
3249   }
3250
3251   if (sock->user_data)
3252     silc_server_free_sock_user_data(server, sock, NULL);
3253
3254   silc_server_disconnect_remote(server, sock, 
3255                                 protocol == 
3256                                 SILC_PROTOCOL_SERVER_CONNECTION_AUTH ?
3257                                 SILC_STATUS_ERR_AUTH_FAILED :
3258                                 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
3259                                 "Connection timeout");
3260 }
3261
3262 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
3263    function may be used only by router. In real SILC network all channels
3264    are created by routers thus this function is never used by normal
3265    server. */
3266
3267 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3268                                                 SilcServerID *router_id,
3269                                                 char *cipher,
3270                                                 char *hmac,
3271                                                 char *channel_name,
3272                                                 int broadcast)
3273 {
3274   SilcChannelID *channel_id;
3275   SilcChannelEntry entry;
3276   SilcCipher key;
3277   SilcHmac newhmac;
3278
3279   SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3280
3281   if (!cipher)
3282     cipher = SILC_DEFAULT_CIPHER;
3283   if (!hmac)
3284     hmac = SILC_DEFAULT_HMAC;
3285
3286   /* Allocate cipher */
3287   if (!silc_cipher_alloc(cipher, &key))
3288     return NULL;
3289
3290   /* Allocate hmac */
3291   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3292     silc_cipher_free(key);
3293     return NULL;
3294   }
3295
3296   channel_name = strdup(channel_name);
3297
3298   /* Create the channel ID */
3299   if (!silc_id_create_channel_id(server, router_id, server->rng,
3300                                  &channel_id)) {
3301     silc_free(channel_name);
3302     silc_cipher_free(key);
3303     silc_hmac_free(newhmac);
3304     return NULL;
3305   }
3306
3307   /* Create the channel */
3308   entry = silc_idlist_add_channel(server->local_list, channel_name,
3309                                   SILC_CHANNEL_MODE_NONE, channel_id,
3310                                   NULL, key, newhmac, 0);
3311   if (!entry) {
3312     silc_free(channel_name);
3313     silc_cipher_free(key);
3314     silc_hmac_free(newhmac);
3315     silc_free(channel_id);
3316     return NULL;
3317   }
3318
3319   entry->cipher = strdup(cipher);
3320   entry->hmac_name = strdup(hmac);
3321
3322   /* Now create the actual key material */
3323   if (!silc_server_create_channel_key(server, entry,
3324                                       silc_cipher_get_key_len(key) / 8)) {
3325     silc_idlist_del_channel(server->local_list, entry);
3326     return NULL;
3327   }
3328
3329   /* Notify other routers about the new channel. We send the packet
3330      to our primary route. */
3331   if (broadcast)
3332     silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3333                                  channel_name, entry->id,
3334                                  silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3335                                  entry->mode);
3336
3337   /* Distribute to backup routers */
3338   if (broadcast && server->server_type == SILC_ROUTER) {
3339     SilcBuffer packet;
3340     unsigned char *cid;
3341     SilcUInt32 name_len = strlen(channel_name);
3342     SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3343     cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3344
3345     packet = silc_channel_payload_encode(channel_name, name_len,
3346                                          cid, channel_id_len, entry->mode);
3347     silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3348                             packet->data, packet->len, FALSE, TRUE);
3349     silc_free(cid);
3350     silc_buffer_free(packet);
3351   }
3352
3353   server->stat.my_channels++;
3354   if (server->server_type == SILC_ROUTER) {
3355     server->stat.channels++;
3356     server->stat.cell_channels++;
3357     entry->users_resolved = TRUE;
3358   }
3359
3360   return entry;
3361 }
3362
3363 /* Same as above but creates the channel with Channel ID `channel_id. */
3364
3365 SilcChannelEntry
3366 silc_server_create_new_channel_with_id(SilcServer server,
3367                                        char *cipher,
3368                                        char *hmac,
3369                                        char *channel_name,
3370                                        SilcChannelID *channel_id,
3371                                        int broadcast)
3372 {
3373   SilcChannelEntry entry;
3374   SilcCipher key;
3375   SilcHmac newhmac;
3376
3377   SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3378
3379   if (!cipher)
3380     cipher = SILC_DEFAULT_CIPHER;
3381   if (!hmac)
3382     hmac = SILC_DEFAULT_HMAC;
3383
3384   /* Allocate cipher */
3385   if (!silc_cipher_alloc(cipher, &key))
3386     return NULL;
3387
3388   /* Allocate hmac */
3389   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3390     silc_cipher_free(key);
3391     return NULL;
3392   }
3393
3394   channel_name = strdup(channel_name);
3395
3396   /* Create the channel */
3397   entry = silc_idlist_add_channel(server->local_list, channel_name,
3398                                   SILC_CHANNEL_MODE_NONE, channel_id,
3399                                   NULL, key, newhmac, 0);
3400   if (!entry) {
3401     silc_cipher_free(key);
3402     silc_hmac_free(newhmac);
3403     silc_free(channel_name);
3404     return NULL;
3405   }
3406
3407   /* Now create the actual key material */
3408   if (!silc_server_create_channel_key(server, entry,
3409                                       silc_cipher_get_key_len(key) / 8)) {
3410     silc_idlist_del_channel(server->local_list, entry);
3411     return NULL;
3412   }
3413
3414   /* Notify other routers about the new channel. We send the packet
3415      to our primary route. */
3416   if (broadcast)
3417     silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3418                                  channel_name, entry->id,
3419                                  silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3420                                  entry->mode);
3421
3422   /* Distribute to backup routers */
3423   if (broadcast && server->server_type == SILC_ROUTER) {
3424     SilcBuffer packet;
3425     unsigned char *cid;
3426     SilcUInt32 name_len = strlen(channel_name);
3427     SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3428     cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3429
3430     packet = silc_channel_payload_encode(channel_name, name_len,
3431                                          cid, channel_id_len, entry->mode);
3432     silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3433                             packet->data, packet->len, FALSE, TRUE);
3434     silc_free(cid);
3435     silc_buffer_free(packet);
3436   }
3437
3438   server->stat.my_channels++;
3439   if (server->server_type == SILC_ROUTER) {
3440     server->stat.channels++;
3441     server->stat.cell_channels++;
3442     entry->users_resolved = TRUE;
3443   }
3444
3445   return entry;
3446 }
3447
3448 /* Channel's key re-key timeout callback. */
3449
3450 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3451 {
3452   SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3453   SilcServer server = (SilcServer)rekey->context;
3454
3455   rekey->task = NULL;
3456
3457   if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3458     return;
3459
3460   silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3461 }
3462
3463 /* Generates new channel key. This is used to create the initial channel key
3464    but also to re-generate new key for channel. If `key_len' is provided
3465    it is the bytes of the key length. */
3466
3467 bool silc_server_create_channel_key(SilcServer server,
3468                                     SilcChannelEntry channel,
3469                                     SilcUInt32 key_len)
3470 {
3471   int i;
3472   unsigned char channel_key[32], hash[32];
3473   SilcUInt32 len;
3474
3475   SILC_LOG_DEBUG(("Generating channel key"));
3476
3477   if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3478     SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3479     return TRUE;
3480   }
3481
3482   if (!channel->channel_key)
3483     if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3484       channel->channel_key = NULL;
3485       return FALSE;
3486     }
3487
3488   if (key_len)
3489     len = key_len;
3490   else if (channel->key_len)
3491     len = channel->key_len / 8;
3492   else
3493     len = silc_cipher_get_key_len(channel->channel_key) / 8;
3494
3495   /* Create channel key */
3496   for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3497
3498   /* Set the key */
3499   silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3500
3501   /* Remove old key if exists */
3502   if (channel->key) {
3503     memset(channel->key, 0, channel->key_len / 8);
3504     silc_free(channel->key);
3505   }
3506
3507   /* Save the key */
3508   channel->key_len = len * 8;
3509   channel->key = silc_memdup(channel_key, len);
3510   memset(channel_key, 0, sizeof(channel_key));
3511
3512   /* Generate HMAC key from the channel key data and set it */
3513   if (!channel->hmac)
3514     silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3515   silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3516   silc_hmac_set_key(channel->hmac, hash,
3517                     silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3518   memset(hash, 0, sizeof(hash));
3519
3520   if (server->server_type == SILC_ROUTER) {
3521     if (!channel->rekey)
3522       channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3523     channel->rekey->context = (void *)server;
3524     channel->rekey->channel = channel;
3525     channel->rekey->key_len = key_len;
3526     if (channel->rekey->task)
3527       silc_schedule_task_del(server->schedule, channel->rekey->task);
3528
3529     channel->rekey->task =
3530       silc_schedule_task_add(server->schedule, 0,
3531                              silc_server_channel_key_rekey,
3532                              (void *)channel->rekey,
3533                              server->config->channel_rekey_secs, 0,
3534                              SILC_TASK_TIMEOUT,
3535                              SILC_TASK_PRI_NORMAL);
3536   }
3537
3538   return TRUE;
3539 }
3540
3541 /* Saves the channel key found in the encoded `key_payload' buffer. This
3542    function is used when we receive Channel Key Payload and also when we're
3543    processing JOIN command reply. Returns entry to the channel. */
3544
3545 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3546                                               SilcBuffer key_payload,
3547                                               SilcChannelEntry channel)
3548 {
3549   SilcChannelKeyPayload payload = NULL;
3550   SilcChannelID *id = NULL;
3551   unsigned char *tmp, hash[32];
3552   SilcUInt32 tmp_len;
3553   char *cipher;
3554
3555   SILC_LOG_DEBUG(("Saving new channel key"));
3556
3557   /* Decode channel key payload */
3558   payload = silc_channel_key_payload_parse(key_payload->data,
3559                                            key_payload->len);
3560   if (!payload) {
3561     SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3562     channel = NULL;
3563     goto out;
3564   }
3565
3566   /* Get the channel entry */
3567   if (!channel) {
3568
3569     /* Get channel ID */
3570     tmp = silc_channel_key_get_id(payload, &tmp_len);
3571     id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3572     if (!id) {
3573       channel = NULL;
3574       goto out;
3575     }
3576
3577     channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3578     if (!channel) {
3579       channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3580       if (!channel) {
3581         SILC_LOG_ERROR(("Received key for non-existent channel %s",
3582                         silc_id_render(id, SILC_ID_CHANNEL)));
3583         goto out;
3584       }
3585     }
3586   }
3587
3588   tmp = silc_channel_key_get_key(payload, &tmp_len);
3589   if (!tmp) {
3590     channel = NULL;
3591     goto out;
3592   }
3593
3594   cipher = silc_channel_key_get_cipher(payload, NULL);
3595   if (!cipher) {
3596     channel = NULL;
3597     goto out;
3598   }
3599
3600   /* Remove old key if exists */
3601   if (channel->key) {
3602     memset(channel->key, 0, channel->key_len / 8);
3603     silc_free(channel->key);
3604     silc_cipher_free(channel->channel_key);
3605   }
3606
3607   /* Create new cipher */
3608   if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3609     channel->channel_key = NULL;
3610     channel = NULL;
3611     goto out;
3612   }
3613
3614   if (channel->cipher)
3615     silc_free(channel->cipher);
3616   channel->cipher = strdup(cipher);
3617
3618   /* Save the key */
3619   channel->key_len = tmp_len * 8;
3620   channel->key = silc_memdup(tmp, tmp_len);
3621   silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3622
3623   /* Generate HMAC key from the channel key data and set it */
3624   if (!channel->hmac)
3625     silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3626   silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3627   silc_hmac_set_key(channel->hmac, hash,
3628                     silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3629
3630   memset(hash, 0, sizeof(hash));
3631   memset(tmp, 0, tmp_len);
3632
3633   if (server->server_type == SILC_ROUTER) {
3634     if (!channel->rekey)
3635       channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3636     channel->rekey->context = (void *)server;
3637     channel->rekey->channel = channel;
3638     if (channel->rekey->task)
3639       silc_schedule_task_del(server->schedule, channel->rekey->task);
3640
3641     channel->rekey->task =
3642       silc_schedule_task_add(server->schedule, 0,
3643                              silc_server_channel_key_rekey,
3644                              (void *)channel->rekey,
3645                              server->config->channel_rekey_secs, 0,
3646                              SILC_TASK_TIMEOUT,
3647                              SILC_TASK_PRI_NORMAL);
3648   }
3649
3650  out:
3651   silc_free(id);
3652   if (payload)
3653     silc_channel_key_payload_free(payload);
3654
3655   return channel;
3656 }
3657
3658 /* Heartbeat callback. This function is set as argument for the
3659    silc_socket_set_heartbeat function. The library will call this function
3660    at the set time interval. */
3661
3662 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3663                                    void *hb_context)
3664 {
3665   SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3666
3667   SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3668
3669   /* Send the heartbeat */
3670   silc_server_send_heartbeat(hb->server, sock);
3671 }
3672
3673 /* Returns assembled of all servers in the given ID list. The packet's
3674    form is dictated by the New ID payload. */
3675
3676 static void silc_server_announce_get_servers(SilcServer server,
3677                                              SilcServerEntry remote,
3678                                              SilcIDList id_list,
3679                                              SilcBuffer *servers,
3680                                              unsigned long creation_time)
3681 {
3682   SilcIDCacheList list;
3683   SilcIDCacheEntry id_cache;
3684   SilcServerEntry entry;
3685   SilcBuffer idp;
3686
3687   /* Go through all clients in the list */
3688   if (silc_idcache_get_all(id_list->servers, &list)) {
3689     if (silc_idcache_list_first(list, &id_cache)) {
3690       while (id_cache) {
3691         entry = (SilcServerEntry)id_cache->context;
3692
3693         /* Do not announce the one we've sending our announcements and
3694            do not announce ourself. Also check the creation time if it's
3695            provided. */
3696         if ((entry == remote) || (entry == server->id_entry) ||
3697             (creation_time && entry->data.created < creation_time)) {
3698           if (!silc_idcache_list_next(list, &id_cache))
3699             break;
3700           continue;
3701         }
3702
3703         idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3704
3705         *servers = silc_buffer_realloc(*servers,
3706                                        (*servers ?
3707                                         (*servers)->truelen + idp->len :
3708                                         idp->len));
3709         silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3710         silc_buffer_put(*servers, idp->data, idp->len);
3711         silc_buffer_pull(*servers, idp->len);
3712         silc_buffer_free(idp);
3713
3714         if (!silc_idcache_list_next(list, &id_cache))
3715           break;
3716       }
3717     }
3718
3719     silc_idcache_list_free(list);
3720   }
3721 }
3722
3723 static SilcBuffer
3724 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3725 {
3726   va_list ap;
3727   SilcBuffer p;
3728
3729   va_start(ap, argc);
3730   p = silc_notify_payload_encode(notify, argc, ap);
3731   va_end(ap);
3732
3733   return p;
3734 }
3735
3736 /* This function is used by router to announce existing servers to our
3737    primary router when we've connected to it. If `creation_time' is non-zero
3738    then only the servers that has been created after the `creation_time'
3739    will be announced. */
3740
3741 void silc_server_announce_servers(SilcServer server, bool global,
3742                                   unsigned long creation_time,
3743                                   SilcSocketConnection remote)
3744 {
3745   SilcBuffer servers = NULL;
3746
3747   SILC_LOG_DEBUG(("Announcing servers"));
3748
3749   /* Get servers in local list */
3750   silc_server_announce_get_servers(server, remote->user_data,
3751                                    server->local_list, &servers,
3752                                    creation_time);
3753
3754   if (global)
3755     /* Get servers in global list */
3756     silc_server_announce_get_servers(server, remote->user_data,
3757                                      server->global_list, &servers,
3758                                      creation_time);
3759
3760   if (servers) {
3761     silc_buffer_push(servers, servers->data - servers->head);
3762     SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3763
3764     /* Send the packet */
3765     silc_server_packet_send(server, remote,
3766                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3767                             servers->data, servers->len, TRUE);
3768
3769     silc_buffer_free(servers);
3770   }
3771 }
3772
3773 /* Returns assembled packet of all clients in the given ID list. The
3774    packet's form is dictated by the New ID Payload. */
3775
3776 static void silc_server_announce_get_clients(SilcServer server,
3777                                              SilcIDList id_list,
3778                                              SilcBuffer *clients,
3779                                              SilcBuffer *umodes,
3780                                              unsigned long creation_time)
3781 {
3782   SilcIDCacheList list;
3783   SilcIDCacheEntry id_cache;
3784   SilcClientEntry client;
3785   SilcBuffer idp;
3786   SilcBuffer tmp;
3787   unsigned char mode[4];
3788
3789   /* Go through all clients in the list */
3790   if (silc_idcache_get_all(id_list->clients, &list)) {
3791     if (silc_idcache_list_first(list, &id_cache)) {
3792       while (id_cache) {
3793         client = (SilcClientEntry)id_cache->context;
3794
3795         if (creation_time && client->data.created < creation_time) {
3796           if (!silc_idcache_list_next(list, &id_cache))
3797             break;
3798           continue;
3799         }
3800
3801         idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3802
3803         *clients = silc_buffer_realloc(*clients,
3804                                        (*clients ?
3805                                         (*clients)->truelen + idp->len :
3806                                         idp->len));
3807         silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3808         silc_buffer_put(*clients, idp->data, idp->len);
3809         silc_buffer_pull(*clients, idp->len);
3810
3811         SILC_PUT32_MSB(client->mode, mode);
3812         tmp =
3813           silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3814                                              2, idp->data, idp->len,
3815                                              mode, 4);
3816         *umodes = silc_buffer_realloc(*umodes,
3817                                       (*umodes ?
3818                                        (*umodes)->truelen + tmp->len :
3819                                        tmp->len));
3820         silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3821         silc_buffer_put(*umodes, tmp->data, tmp->len);
3822         silc_buffer_pull(*umodes, tmp->len);
3823         silc_buffer_free(tmp);
3824
3825         silc_buffer_free(idp);
3826
3827         if (!silc_idcache_list_next(list, &id_cache))
3828           break;
3829       }
3830     }
3831
3832     silc_idcache_list_free(list);
3833   }
3834 }
3835
3836 /* This function is used to announce our existing clients to our router
3837    when we've connected to it. If `creation_time' is non-zero then only
3838    the clients that has been created after the `creation_time' will be
3839    announced. */
3840
3841 void silc_server_announce_clients(SilcServer server,
3842                                   unsigned long creation_time,
3843                                   SilcSocketConnection remote)
3844 {
3845   SilcBuffer clients = NULL;
3846   SilcBuffer umodes = NULL;
3847
3848   SILC_LOG_DEBUG(("Announcing clients"));
3849
3850   /* Get clients in local list */
3851   silc_server_announce_get_clients(server, server->local_list,
3852                                    &clients, &umodes, creation_time);
3853
3854   /* As router we announce our global list as well */
3855   if (server->server_type == SILC_ROUTER)
3856     silc_server_announce_get_clients(server, server->global_list,
3857                                      &clients, &umodes, creation_time);
3858
3859   if (clients) {
3860     silc_buffer_push(clients, clients->data - clients->head);
3861     SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3862
3863     /* Send the packet */
3864     silc_server_packet_send(server, remote,
3865                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3866                             clients->data, clients->len, TRUE);
3867
3868     silc_buffer_free(clients);
3869   }
3870
3871   if (umodes) {
3872     silc_buffer_push(umodes, umodes->data - umodes->head);
3873     SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3874
3875     /* Send the packet */
3876     silc_server_packet_send(server, remote,
3877                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3878                             umodes->data, umodes->len, TRUE);
3879
3880     silc_buffer_free(umodes);
3881   }
3882 }
3883
3884 /* Returns channel's topic for announcing it */
3885
3886 void silc_server_announce_get_channel_topic(SilcServer server,
3887                                             SilcChannelEntry channel,
3888                                             SilcBuffer *topic)
3889 {
3890   SilcBuffer chidp;
3891
3892   if (channel->topic) {
3893     chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3894     *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3895                                                 chidp->data, chidp->len,
3896                                                 channel->topic,
3897                                                 strlen(channel->topic));
3898     silc_buffer_free(chidp);
3899   }
3900 }
3901
3902 /* Returns assembled packets for channel users of the `channel'. */
3903
3904 void silc_server_announce_get_channel_users(SilcServer server,
3905                                             SilcChannelEntry channel,
3906                                             SilcBuffer *channel_modes,
3907                                             SilcBuffer *channel_users,
3908                                             SilcBuffer *channel_users_modes)
3909 {
3910   SilcChannelClientEntry chl;
3911   SilcHashTableList htl;
3912   SilcBuffer chidp, clidp, csidp;
3913   SilcBuffer tmp;
3914   int len;
3915   unsigned char mode[4], *fkey = NULL;
3916   SilcUInt32 fkey_len = 0;
3917   char *hmac;
3918
3919   SILC_LOG_DEBUG(("Start"));
3920
3921   chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3922   csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
3923
3924   /* CMODE notify */
3925   SILC_PUT32_MSB(channel->mode, mode);
3926   hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
3927   if (channel->founder_key)
3928     fkey = silc_pkcs_public_key_encode(channel->founder_key, &fkey_len);
3929   tmp = 
3930     silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
3931                                        6, csidp->data, csidp->len,
3932                                        mode, sizeof(mode),
3933                                        NULL, 0,
3934                                        hmac, hmac ? strlen(hmac) : 0,
3935                                        channel->passphrase,
3936                                        channel->passphrase ?
3937                                        strlen(channel->passphrase) : 0,
3938                                        fkey, fkey_len);
3939   len = tmp->len;
3940   *channel_modes =
3941     silc_buffer_realloc(*channel_modes,
3942                         (*channel_modes ?
3943                          (*channel_modes)->truelen + len : len));
3944   silc_buffer_pull_tail(*channel_modes,
3945                         ((*channel_modes)->end -
3946                          (*channel_modes)->data));
3947   silc_buffer_put(*channel_modes, tmp->data, tmp->len);
3948   silc_buffer_pull(*channel_modes, len);
3949   silc_buffer_free(tmp);
3950   silc_free(fkey);
3951   fkey = NULL;
3952   fkey_len = 0;
3953
3954   /* Now find all users on the channel */
3955   silc_hash_table_list(channel->user_list, &htl);
3956   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3957     clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3958
3959     /* JOIN Notify */
3960     tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3961                                              clidp->data, clidp->len,
3962                                              chidp->data, chidp->len);
3963     len = tmp->len;
3964     *channel_users =
3965       silc_buffer_realloc(*channel_users,
3966                           (*channel_users ?
3967                            (*channel_users)->truelen + len : len));
3968     silc_buffer_pull_tail(*channel_users,
3969                           ((*channel_users)->end -
3970                            (*channel_users)->data));
3971
3972     silc_buffer_put(*channel_users, tmp->data, tmp->len);
3973     silc_buffer_pull(*channel_users, len);
3974     silc_buffer_free(tmp);
3975
3976     /* CUMODE notify for mode change on the channel */
3977     SILC_PUT32_MSB(chl->mode, mode);
3978     if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
3979       fkey = silc_pkcs_public_key_encode(channel->founder_key, &fkey_len);
3980     tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3981                                              4, csidp->data, csidp->len,
3982                                              mode, sizeof(mode),
3983                                              clidp->data, clidp->len,
3984                                              fkey, fkey_len);
3985     len = tmp->len;
3986     *channel_users_modes =
3987       silc_buffer_realloc(*channel_users_modes,
3988                           (*channel_users_modes ?
3989                            (*channel_users_modes)->truelen + len : len));
3990     silc_buffer_pull_tail(*channel_users_modes,
3991                           ((*channel_users_modes)->end -
3992                            (*channel_users_modes)->data));
3993
3994     silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3995     silc_buffer_pull(*channel_users_modes, len);
3996     silc_buffer_free(tmp);
3997     silc_free(fkey);
3998     fkey = NULL;
3999     fkey_len = 0;
4000     silc_buffer_free(clidp);
4001   }
4002   silc_hash_table_list_reset(&htl);
4003   silc_buffer_free(chidp);
4004   silc_buffer_free(csidp);
4005 }
4006
4007 /* Returns assembled packets for all channels and users on those channels
4008    from the given ID List. The packets are in the form dictated by the
4009    New Channel and New Channel User payloads. */
4010
4011 void silc_server_announce_get_channels(SilcServer server,
4012                                        SilcIDList id_list,
4013                                        SilcBuffer *channels,
4014                                        SilcBuffer **channel_modes,
4015                                        SilcBuffer *channel_users,
4016                                        SilcBuffer **channel_users_modes,
4017                                        SilcUInt32 *channel_users_modes_c,
4018                                        SilcBuffer **channel_topics,
4019                                        SilcChannelID ***channel_ids,
4020                                        unsigned long creation_time)
4021 {
4022   SilcIDCacheList list;
4023   SilcIDCacheEntry id_cache;
4024   SilcChannelEntry channel;
4025   unsigned char *cid;
4026   SilcUInt32 id_len;
4027   SilcUInt16 name_len;
4028   int len;
4029   int i = *channel_users_modes_c;
4030   bool announce;
4031
4032   SILC_LOG_DEBUG(("Start"));
4033
4034   /* Go through all channels in the list */
4035   if (silc_idcache_get_all(id_list->channels, &list)) {
4036     if (silc_idcache_list_first(list, &id_cache)) {
4037       while (id_cache) {
4038         channel = (SilcChannelEntry)id_cache->context;
4039
4040         if (creation_time && channel->created < creation_time)
4041           announce = FALSE;
4042         else
4043           announce = TRUE;
4044
4045         cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4046         id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4047         name_len = strlen(channel->channel_name);
4048
4049         if (announce) {
4050           len = 4 + name_len + id_len + 4;
4051           *channels =
4052             silc_buffer_realloc(*channels,
4053                                 (*channels ? (*channels)->truelen +
4054                                  len : len));
4055           silc_buffer_pull_tail(*channels,
4056                                 ((*channels)->end - (*channels)->data));
4057           silc_buffer_format(*channels,
4058                              SILC_STR_UI_SHORT(name_len),
4059                              SILC_STR_UI_XNSTRING(channel->channel_name,
4060                                                   name_len),
4061                              SILC_STR_UI_SHORT(id_len),
4062                              SILC_STR_UI_XNSTRING(cid, id_len),
4063                              SILC_STR_UI_INT(channel->mode),
4064                              SILC_STR_END);
4065           silc_buffer_pull(*channels, len);
4066         }
4067
4068         /* Channel user modes */
4069         *channel_users_modes = silc_realloc(*channel_users_modes,
4070                                             sizeof(**channel_users_modes) *
4071                                             (i + 1));
4072         (*channel_users_modes)[i] = NULL;
4073         *channel_modes = silc_realloc(*channel_modes,
4074                                       sizeof(**channel_modes) * (i + 1));
4075         (*channel_modes)[i] = NULL;
4076         *channel_ids = silc_realloc(*channel_ids,
4077                                     sizeof(**channel_ids) * (i + 1));
4078         (*channel_ids)[i] = NULL;
4079         silc_server_announce_get_channel_users(server, channel,
4080                                                &(*channel_modes)[i], 
4081                                                channel_users,
4082                                                &(*channel_users_modes)[i]);
4083         (*channel_ids)[i] = channel->id;
4084
4085         /* Channel's topic */
4086         *channel_topics = silc_realloc(*channel_topics,
4087                                        sizeof(**channel_topics) * (i + 1));
4088         (*channel_topics)[i] = NULL;
4089         silc_server_announce_get_channel_topic(server, channel,
4090                                                &(*channel_topics)[i]);
4091         i++;
4092
4093         if (!silc_idcache_list_next(list, &id_cache))
4094           break;
4095       }
4096
4097       *channel_users_modes_c += i;
4098     }
4099
4100     silc_idcache_list_free(list);
4101   }
4102 }
4103
4104 /* This function is used to announce our existing channels to our router
4105    when we've connected to it. This also announces the users on the
4106    channels to the router. If the `creation_time' is non-zero only the
4107    channels that was created after the `creation_time' are announced.
4108    Note that the channel users are still announced even if the `creation_time'
4109    was provided. */
4110
4111 void silc_server_announce_channels(SilcServer server,
4112                                    unsigned long creation_time,
4113                                    SilcSocketConnection remote)
4114 {
4115   SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
4116   SilcBuffer *channel_users_modes = NULL;
4117   SilcBuffer *channel_topics = NULL;
4118   SilcUInt32 channel_users_modes_c = 0;
4119   SilcChannelID **channel_ids = NULL;
4120
4121   SILC_LOG_DEBUG(("Announcing channels and channel users"));
4122
4123   /* Get channels and channel users in local list */
4124   silc_server_announce_get_channels(server, server->local_list,
4125                                     &channels, &channel_modes,
4126                                     &channel_users,
4127                                     &channel_users_modes,
4128                                     &channel_users_modes_c,
4129                                     &channel_topics,
4130                                     &channel_ids, creation_time);
4131
4132   /* Get channels and channel users in global list */
4133   if (server->server_type != SILC_SERVER)
4134     silc_server_announce_get_channels(server, server->global_list,
4135                                       &channels, &channel_modes,
4136                                       &channel_users,
4137                                       &channel_users_modes,
4138                                       &channel_users_modes_c,
4139                                       &channel_topics,
4140                                       &channel_ids, creation_time);
4141
4142   if (channels) {
4143     silc_buffer_push(channels, channels->data - channels->head);
4144     SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
4145
4146     /* Send the packet */
4147     silc_server_packet_send(server, remote,
4148                             SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
4149                             channels->data, channels->len,
4150                             FALSE);
4151
4152     silc_buffer_free(channels);
4153   }
4154
4155   if (channel_users) {
4156     silc_buffer_push(channel_users, channel_users->data - channel_users->head);
4157     SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
4158                      channel_users->len);
4159
4160     /* Send the packet */
4161     silc_server_packet_send(server, remote,
4162                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4163                             channel_users->data, channel_users->len,
4164                             FALSE);
4165
4166     silc_buffer_free(channel_users);
4167   }
4168
4169   if (channel_modes) {
4170     int i;
4171
4172     for (i = 0; i < channel_users_modes_c; i++) {
4173       if (!channel_modes[i])
4174         continue;
4175       silc_buffer_push(channel_modes[i],
4176                        channel_modes[i]->data -
4177                        channel_modes[i]->head);
4178       SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
4179                        channel_modes[i]->len);
4180       silc_server_packet_send_dest(server, remote,
4181                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4182                                    channel_ids[i], SILC_ID_CHANNEL,
4183                                    channel_modes[i]->data,
4184                                    channel_modes[i]->len,
4185                                    FALSE);
4186       silc_buffer_free(channel_modes[i]);
4187     }
4188     silc_free(channel_modes);
4189   }
4190
4191   if (channel_users_modes) {
4192     int i;
4193
4194     for (i = 0; i < channel_users_modes_c; i++) {
4195       if (!channel_users_modes[i])
4196         continue;
4197       silc_buffer_push(channel_users_modes[i],
4198                        channel_users_modes[i]->data -
4199                        channel_users_modes[i]->head);
4200       SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
4201                        channel_users_modes[i]->len);
4202       silc_server_packet_send_dest(server, remote,
4203                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4204                                    channel_ids[i], SILC_ID_CHANNEL,
4205                                    channel_users_modes[i]->data,
4206                                    channel_users_modes[i]->len,
4207                                    FALSE);
4208       silc_buffer_free(channel_users_modes[i]);
4209     }
4210     silc_free(channel_users_modes);
4211   }
4212
4213   if (channel_topics) {
4214     int i;
4215
4216     for (i = 0; i < channel_users_modes_c; i++) {
4217       if (!channel_topics[i])
4218         continue;
4219
4220       silc_buffer_push(channel_topics[i],
4221                        channel_topics[i]->data -
4222                        channel_topics[i]->head);
4223       SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
4224                        channel_topics[i]->len);
4225       silc_server_packet_send_dest(server, remote,
4226                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4227                                    channel_ids[i], SILC_ID_CHANNEL,
4228                                    channel_topics[i]->data,
4229                                    channel_topics[i]->len,
4230                                    FALSE);
4231       silc_buffer_free(channel_topics[i]);
4232     }
4233     silc_free(channel_topics);
4234   }
4235
4236   silc_free(channel_ids);
4237 }
4238
4239 /* Failure timeout callback. If this is called then we will immediately
4240    process the received failure. We always process the failure with timeout
4241    since we do not want to blindly trust to received failure packets.
4242    This won't be called (the timeout is cancelled) if the failure was
4243    bogus (it is bogus if remote does not close the connection after sending
4244    the failure). */
4245
4246 SILC_TASK_CALLBACK(silc_server_failure_callback)
4247 {
4248   SilcServerFailureContext f = (SilcServerFailureContext)context;
4249
4250   if (f->sock->protocol) {
4251     f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
4252     silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
4253   }
4254
4255   silc_free(f);
4256 }
4257
4258 /* Assembles user list and users mode list from the `channel'. */
4259
4260 bool silc_server_get_users_on_channel(SilcServer server,
4261                                       SilcChannelEntry channel,
4262                                       SilcBuffer *user_list,
4263                                       SilcBuffer *mode_list,
4264                                       SilcUInt32 *user_count)
4265 {
4266   SilcChannelClientEntry chl;
4267   SilcHashTableList htl;
4268   SilcBuffer client_id_list;
4269   SilcBuffer client_mode_list;
4270   SilcBuffer idp;
4271   SilcUInt32 list_count = 0, len = 0;
4272
4273   if (!silc_hash_table_count(channel->user_list))
4274     return FALSE;
4275
4276   silc_hash_table_list(channel->user_list, &htl);
4277   while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4278     len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
4279   silc_hash_table_list_reset(&htl);
4280
4281   client_id_list = silc_buffer_alloc(len);
4282   client_mode_list =
4283     silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
4284   silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
4285   silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
4286
4287   silc_hash_table_list(channel->user_list, &htl);
4288   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4289     /* Client ID */
4290     idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4291     silc_buffer_put(client_id_list, idp->data, idp->len);
4292     silc_buffer_pull(client_id_list, idp->len);
4293     silc_buffer_free(idp);
4294
4295     /* Client's mode on channel */
4296     SILC_PUT32_MSB(chl->mode, client_mode_list->data);
4297     silc_buffer_pull(client_mode_list, 4);
4298
4299     list_count++;
4300   }
4301   silc_hash_table_list_reset(&htl);
4302   silc_buffer_push(client_id_list,
4303                    client_id_list->data - client_id_list->head);
4304   silc_buffer_push(client_mode_list,
4305                    client_mode_list->data - client_mode_list->head);
4306
4307   *user_list = client_id_list;
4308   *mode_list = client_mode_list;
4309   *user_count = list_count;
4310   return TRUE;
4311 }
4312
4313 /* Saves users and their modes to the `channel'. */
4314
4315 void silc_server_save_users_on_channel(SilcServer server,
4316                                        SilcSocketConnection sock,
4317                                        SilcChannelEntry channel,
4318                                        SilcClientID *noadd,
4319                                        SilcBuffer user_list,
4320                                        SilcBuffer mode_list,
4321                                        SilcUInt32 user_count)
4322 {
4323   int i;
4324   SilcUInt16 idp_len;
4325   SilcUInt32 mode;
4326   SilcClientID *client_id;
4327   SilcClientEntry client;
4328   SilcIDCacheEntry cache;
4329   SilcChannelClientEntry chl;
4330   bool global;
4331
4332   SILC_LOG_DEBUG(("Start"));
4333
4334   for (i = 0; i < user_count; i++) {
4335     /* Client ID */
4336     SILC_GET16_MSB(idp_len, user_list->data + 2);
4337     idp_len += 4;
4338     client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
4339     silc_buffer_pull(user_list, idp_len);
4340     if (!client_id)
4341       continue;
4342
4343     /* Mode */
4344     SILC_GET32_MSB(mode, mode_list->data);
4345     silc_buffer_pull(mode_list, 4);
4346
4347     if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
4348       silc_free(client_id);
4349       continue;
4350     }
4351
4352     global = FALSE;
4353
4354     /* Check if we have this client cached already. */
4355     client = silc_idlist_find_client_by_id(server->local_list, client_id,
4356                                            server->server_type, &cache);
4357     if (!client) {
4358       client = silc_idlist_find_client_by_id(server->global_list,
4359                                              client_id, server->server_type,
4360                                              &cache);
4361       global = TRUE;
4362     }
4363     if (!client) {
4364       /* If router did not find such Client ID in its lists then this must
4365          be bogus client or some router in the net is buggy. */
4366       if (server->server_type == SILC_ROUTER) {
4367         silc_free(client_id);
4368         continue;
4369       }
4370
4371       /* We don't have that client anywhere, add it. The client is added
4372          to global list since server didn't have it in the lists so it must be
4373          global. */
4374       client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
4375                                       silc_id_dup(client_id, SILC_ID_CLIENT),
4376                                       sock->user_data, NULL, 0);
4377       if (!client) {
4378         SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
4379         silc_free(client_id);
4380         continue;
4381       }
4382
4383       client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
4384     } else {
4385       /* Found, if it is from global list we'll assure that we won't
4386          expire it now that the entry is on channel. */
4387       if (global)
4388         cache->expire = 0;
4389     }
4390
4391     silc_free(client_id);
4392
4393     if (!silc_server_client_on_channel(client, channel, &chl)) {
4394       /* Client was not on the channel, add it. */
4395       chl = silc_calloc(1, sizeof(*chl));
4396       chl->client = client;
4397       chl->mode = mode;
4398       chl->channel = channel;
4399       silc_hash_table_add(channel->user_list, chl->client, chl);
4400       silc_hash_table_add(client->channels, chl->channel, chl);
4401       channel->user_count++;
4402     } else {
4403       /* Update mode */
4404       chl->mode = mode;
4405     }
4406   }
4407 }
4408
4409 /* Saves channels and channels user modes to the `client'.  Removes
4410    the client from those channels that are not sent in the list but
4411    it has joined. */
4412
4413 void silc_server_save_user_channels(SilcServer server,
4414                                     SilcSocketConnection sock,
4415                                     SilcClientEntry client,
4416                                     SilcBuffer channels,
4417                                     SilcBuffer channels_user_modes)
4418 {
4419   SilcDList ch;
4420   SilcUInt32 *chumodes;
4421   SilcChannelPayload entry;
4422   SilcChannelEntry channel;
4423   SilcChannelID *channel_id;
4424   SilcChannelClientEntry chl;
4425   SilcHashTable ht = NULL;
4426   SilcHashTableList htl;
4427   char *name;
4428   int i = 0;
4429
4430   if (!channels ||!channels_user_modes)
4431     goto out;
4432   
4433   ch = silc_channel_payload_parse_list(channels->data, channels->len);
4434   if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
4435                                &chumodes)) {
4436     ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL, 
4437                                NULL, NULL, NULL, TRUE);
4438     silc_dlist_start(ch);
4439     while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
4440       /* Check if we have this channel, and add it if we don't have it.
4441          Also add the client on the channel unless it is there already. */
4442       channel_id = silc_channel_get_id_parse(entry);
4443       channel = silc_idlist_find_channel_by_id(server->local_list, 
4444                                                channel_id, NULL);
4445       if (!channel)
4446         channel = silc_idlist_find_channel_by_id(server->global_list,
4447                                                  channel_id, NULL);
4448       if (!channel) {
4449         if (server->server_type != SILC_SERVER) {
4450           silc_free(channel_id);
4451           i++;
4452           continue;
4453         }
4454         
4455         /* We don't have that channel anywhere, add it. */
4456         name = silc_channel_get_name(entry, NULL);
4457         channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
4458                                           channel_id, server->router,
4459                                           NULL, NULL, 0);
4460         if (!channel) {
4461           silc_free(channel_id);
4462           i++;
4463           continue;
4464         }
4465         channel_id = NULL;
4466       }
4467
4468       channel->mode = silc_channel_get_mode(entry);
4469
4470       /* Add the client on the channel */
4471       if (!silc_server_client_on_channel(client, channel, &chl)) {
4472         chl = silc_calloc(1, sizeof(*chl));
4473         chl->client = client;
4474         chl->mode = chumodes[i++];
4475         chl->channel = channel;
4476         silc_hash_table_add(channel->user_list, chl->client, chl);
4477         silc_hash_table_add(client->channels, chl->channel, chl);
4478         channel->user_count++;
4479       } else {
4480         /* Update mode */
4481         chl->mode = chumodes[i++];
4482       }
4483
4484       silc_hash_table_add(ht, channel, channel);
4485       silc_free(channel_id);
4486     }
4487     silc_channel_payload_list_free(ch);
4488     silc_free(chumodes);
4489   }
4490
4491  out:
4492   /* Go through the list again and remove client from channels that
4493      are no part of the list. */
4494   if (ht) {
4495     silc_hash_table_list(client->channels, &htl);
4496     while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4497       if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
4498         silc_hash_table_del(chl->channel->user_list, chl->client);
4499         silc_hash_table_del(chl->client->channels, chl->channel);
4500         silc_free(chl);
4501       }
4502     }
4503     silc_hash_table_list_reset(&htl);
4504     silc_hash_table_free(ht);
4505   } else {
4506     silc_hash_table_list(client->channels, &htl);
4507     while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4508       silc_hash_table_del(chl->channel->user_list, chl->client);
4509       silc_hash_table_del(chl->client->channels, chl->channel);
4510       silc_free(chl);
4511     }
4512     silc_hash_table_list_reset(&htl);
4513   }
4514 }
4515
4516 /* Lookups route to the client indicated by the `id_data'. The connection
4517    object and internal data object is returned. Returns NULL if route
4518    could not be found to the client. If the `client_id' is specified then
4519    it is used and the `id_data' is ignored. */
4520
4521 SilcSocketConnection
4522 silc_server_get_client_route(SilcServer server,
4523                              unsigned char *id_data,
4524                              SilcUInt32 id_len,
4525                              SilcClientID *client_id,
4526                              SilcIDListData *idata,
4527                              SilcClientEntry *client_entry)
4528 {
4529   SilcClientID *id;
4530   SilcClientEntry client;
4531
4532   SILC_LOG_DEBUG(("Start"));
4533
4534   if (client_entry)
4535     *client_entry = NULL;
4536
4537   /* Decode destination Client ID */
4538   if (!client_id) {
4539     id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
4540     if (!id) {
4541       SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
4542       return NULL;
4543     }
4544   } else {
4545     id = silc_id_dup(client_id, SILC_ID_CLIENT);
4546   }
4547
4548   /* If the destination belongs to our server we don't have to route
4549      the packet anywhere but to send it to the local destination. */
4550   client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
4551   if (client) {
4552     silc_free(id);
4553
4554     /* If we are router and the client has router then the client is in
4555        our cell but not directly connected to us. */
4556     if (server->server_type == SILC_ROUTER && client->router) {
4557       /* We are of course in this case the client's router thus the route
4558          to the client is the server who owns the client. So, we will send
4559          the packet to that server. */
4560       if (idata)
4561         *idata = (SilcIDListData)client->router;
4562       return client->router->connection;
4563     }
4564
4565     /* Seems that client really is directly connected to us */
4566     if (idata)
4567       *idata = (SilcIDListData)client;
4568     if (client_entry)
4569       *client_entry = client;
4570     return client->connection;
4571   }
4572
4573   /* Destination belongs to someone not in this server. If we are normal
4574      server our action is to send the packet to our router. */
4575   if (server->server_type != SILC_ROUTER && !server->standalone) {
4576     silc_free(id);
4577     if (idata)
4578       *idata = (SilcIDListData)server->router;
4579     return SILC_PRIMARY_ROUTE(server);
4580   }
4581
4582   /* We are router and we will perform route lookup for the destination
4583      and send the packet to fastest route. */
4584   if (server->server_type == SILC_ROUTER && !server->standalone) {
4585     /* Check first that the ID is valid */
4586     client = silc_idlist_find_client_by_id(server->global_list, id,
4587                                            TRUE, NULL);
4588     if (client) {
4589       SilcSocketConnection dst_sock;
4590
4591       dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
4592
4593       silc_free(id);
4594       if (idata)
4595         *idata = (SilcIDListData)dst_sock->user_data;
4596       return dst_sock;
4597     }
4598   }
4599
4600   silc_free(id);
4601   return NULL;
4602 }
4603
4604 /* Encodes and returns channel list of channels the `client' has joined.
4605    Secret channels are not put to the list. */
4606
4607 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
4608                                                SilcClientEntry client,
4609                                                bool get_private,
4610                                                bool get_secret,
4611                                                SilcBuffer *user_mode_list)
4612 {
4613   SilcBuffer buffer = NULL;
4614   SilcChannelEntry channel;
4615   SilcChannelClientEntry chl;
4616   SilcHashTableList htl;
4617   unsigned char *cid;
4618   SilcUInt32 id_len;
4619   SilcUInt16 name_len;
4620   int len;
4621
4622   if (user_mode_list)
4623     *user_mode_list = NULL;
4624
4625   silc_hash_table_list(client->channels, &htl);
4626   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4627     channel = chl->channel;
4628
4629     if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
4630       continue;
4631     if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
4632       continue;
4633
4634     cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4635     id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4636     name_len = strlen(channel->channel_name);
4637
4638     len = 4 + name_len + id_len + 4;
4639     buffer = silc_buffer_realloc(buffer,
4640                                  (buffer ? buffer->truelen + len : len));
4641     silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
4642     silc_buffer_format(buffer,
4643                        SILC_STR_UI_SHORT(name_len),
4644                        SILC_STR_UI_XNSTRING(channel->channel_name,
4645                                             name_len),
4646                        SILC_STR_UI_SHORT(id_len),
4647                        SILC_STR_UI_XNSTRING(cid, id_len),
4648                        SILC_STR_UI_INT(chl->channel->mode),
4649                        SILC_STR_END);
4650     silc_buffer_pull(buffer, len);
4651     silc_free(cid);
4652
4653     if (user_mode_list) {
4654       *user_mode_list = silc_buffer_realloc(*user_mode_list,
4655                                             (*user_mode_list ?
4656                                              (*user_mode_list)->truelen + 4 :
4657                                              4));
4658       silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
4659                                               (*user_mode_list)->data));
4660       SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
4661       silc_buffer_pull(*user_mode_list, 4);
4662     }
4663   }
4664   silc_hash_table_list_reset(&htl);
4665
4666   if (buffer)
4667     silc_buffer_push(buffer, buffer->data - buffer->head);
4668   if (user_mode_list && *user_mode_list)
4669     silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
4670                                        (*user_mode_list)->head));
4671
4672   return buffer;
4673 }
4674
4675 /* Finds client entry by Client ID and if it is not found then resolves
4676    it using WHOIS command. */
4677
4678 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4679                                                SilcClientID *client_id,
4680                                                bool always_resolve,
4681                                                bool *resolved)
4682 {
4683   SilcClientEntry client;
4684
4685   if (resolved)
4686     *resolved = FALSE;
4687
4688   client = silc_idlist_find_client_by_id(server->local_list, client_id,
4689                                          TRUE, NULL);
4690   if (!client) {
4691     client = silc_idlist_find_client_by_id(server->global_list,
4692                                            client_id, TRUE, NULL);
4693     if (!client && server->server_type == SILC_ROUTER)
4694       return NULL;
4695   }
4696
4697   if (!client && server->standalone)
4698     return NULL;
4699
4700   if (!client || !client->nickname || !client->username ||
4701       always_resolve) {
4702     SilcBuffer buffer, idp;
4703
4704     if (client) {
4705       client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4706       client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4707       client->resolve_cmd_ident = ++server->cmd_ident;
4708     }
4709
4710     idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4711     buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4712                                             server->cmd_ident, 1,
4713                                             4, idp->data, idp->len);
4714     silc_server_packet_send(server, client ? client->router->connection :
4715                             SILC_PRIMARY_ROUTE(server),
4716                             SILC_PACKET_COMMAND, 0,
4717                             buffer->data, buffer->len, FALSE);
4718     silc_buffer_free(idp);
4719     silc_buffer_free(buffer);
4720
4721     if (resolved)
4722       *resolved = TRUE;
4723
4724     return NULL;
4725   }
4726
4727   return client;
4728 }
4729
4730 /* A timeout callback for the re-key. We will be the initiator of the
4731    re-key protocol. */
4732
4733 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4734 {
4735   SilcSocketConnection sock = (SilcSocketConnection)context;
4736   SilcIDListData idata = (SilcIDListData)sock->user_data;
4737   SilcServer server = (SilcServer)idata->rekey->context;
4738   SilcProtocol protocol;
4739   SilcServerRekeyInternalContext *proto_ctx;
4740
4741   SILC_LOG_DEBUG(("Start"));
4742
4743   /* Allocate internal protocol context. This is sent as context
4744      to the protocol. */
4745   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4746   proto_ctx->server = (void *)server;
4747   proto_ctx->sock = sock;
4748   proto_ctx->responder = FALSE;
4749   proto_ctx->pfs = idata->rekey->pfs;
4750
4751   /* Perform rekey protocol. Will call the final callback after the
4752      protocol is over. */
4753   silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4754                       &protocol, proto_ctx, silc_server_rekey_final);
4755   sock->protocol = protocol;
4756
4757   /* Run the protocol */
4758   silc_protocol_execute(protocol, server->schedule, 0, 0);
4759
4760   /* Re-register re-key timeout */
4761   silc_schedule_task_add(server->schedule, sock->sock,
4762                          silc_server_rekey_callback,
4763                          context, idata->rekey->timeout, 0,
4764                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4765 }
4766
4767 /* The final callback for the REKEY protocol. This will actually take the
4768    new key material into use. */
4769
4770 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4771 {
4772   SilcProtocol protocol = (SilcProtocol)context;
4773   SilcServerRekeyInternalContext *ctx =
4774     (SilcServerRekeyInternalContext *)protocol->context;
4775   SilcServer server = (SilcServer)ctx->server;
4776   SilcSocketConnection sock = ctx->sock;
4777
4778   SILC_LOG_DEBUG(("Start"));
4779
4780   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4781       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4782     /* Error occured during protocol */
4783     SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4784     silc_protocol_cancel(protocol, server->schedule);
4785     silc_protocol_free(protocol);
4786     sock->protocol = NULL;
4787     if (ctx->packet)
4788       silc_packet_context_free(ctx->packet);
4789     if (ctx->ske)
4790       silc_ske_free(ctx->ske);
4791     silc_free(ctx);
4792     return;
4793   }
4794
4795   /* Purge the outgoing data queue to assure that all rekey packets really
4796      go to the network before we quit the protocol. */
4797   silc_server_packet_queue_purge(server, sock);
4798
4799   /* Cleanup */
4800   silc_protocol_free(protocol);
4801   sock->protocol = NULL;
4802   if (ctx->packet)
4803     silc_packet_context_free(ctx->packet);
4804   if (ctx->ske)
4805     silc_ske_free(ctx->ske);
4806   silc_free(ctx);
4807 }
4808
4809 /* Task callback used to retrieve network statistical information from
4810    router server once in a while. */
4811
4812 SILC_TASK_CALLBACK(silc_server_get_stats)
4813 {
4814   SilcServer server = (SilcServer)context;
4815   SilcBuffer idp, packet;
4816
4817   SILC_LOG_DEBUG(("Retrieving stats from router"));
4818
4819   if (!server->standalone) {
4820     idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
4821     packet = silc_command_payload_encode_va(SILC_COMMAND_STATS, 
4822                                             ++server->cmd_ident, 1,
4823                                             1, idp->data, idp->len);
4824     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
4825                             SILC_PACKET_COMMAND, 0, packet->data,
4826                             packet->len, FALSE);
4827     silc_buffer_free(packet);
4828     silc_buffer_free(idp);
4829   }
4830
4831   silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
4832                          server, 120, 0, SILC_TASK_TIMEOUT,
4833                          SILC_TASK_PRI_LOW);
4834 }