5 Author: Pekka Riikonen <priikone@silcnet.org>
7 Copyright (C) 1997 - 2004 Pekka Riikonen
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; version 2 of the License.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
20 * This is the actual SILC server than handles everything relating to
21 * servicing the SILC connections. This is also a SILC router as a router
22 * is also normal server.
26 #include "serverincludes.h"
27 #include "server_internal.h"
29 /* Static prototypes */
30 SILC_TASK_CALLBACK(silc_server_rehash_close_connection);
31 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry);
32 SILC_TASK_CALLBACK(silc_server_connect_router);
33 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
35 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
38 SILC_TASK_CALLBACK(silc_server_packet_process);
39 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
40 SILC_TASK_CALLBACK(silc_server_close_connection_final);
41 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout);
42 SILC_TASK_CALLBACK(silc_server_timeout_remote);
43 SILC_TASK_CALLBACK(silc_server_channel_key_rekey);
44 SILC_TASK_CALLBACK(silc_server_get_stats);
45 SILC_TASK_CALLBACK(silc_server_connect_router);
47 /* Allocates a new SILC server object. This has to be done before the server
48 can be used. After allocation one must call silc_server_init to initialize
49 the server. The new allocated server object is returned to the new_server
52 int silc_server_alloc(SilcServer *new_server)
56 SILC_LOG_DEBUG(("Allocating new server object"));
58 server = silc_calloc(1, sizeof(*server));
59 server->server_type = SILC_SERVER;
60 server->standalone = TRUE;
61 server->local_list = silc_calloc(1, sizeof(*server->local_list));
62 server->global_list = silc_calloc(1, sizeof(*server->global_list));
63 server->pending_commands = silc_dlist_init();
65 server->sim = silc_dlist_init();
73 /* Free's the SILC server object. This is called at the very end before
76 void silc_server_free(SilcServer server)
79 SilcIDCacheEntry cache;
87 silc_dlist_start(server->sim);
88 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
89 silc_dlist_del(server->sim, sim);
93 silc_dlist_uninit(server->sim);
97 silc_server_backup_free(server);
98 silc_server_config_unref(&server->config_ref);
100 silc_rng_free(server->rng);
102 silc_pkcs_free(server->pkcs);
103 if (server->public_key)
104 silc_pkcs_public_key_free(server->public_key);
105 if (server->private_key)
106 silc_pkcs_private_key_free(server->private_key);
107 if (server->pending_commands)
108 silc_dlist_uninit(server->pending_commands);
109 if (server->id_entry)
110 silc_idlist_del_server(server->local_list, server->id_entry);
112 /* Delete all channels */
114 if (silc_idcache_get_all(server->local_list->channels, &list) &&
115 silc_idcache_list_first(list, &cache)) {
116 silc_idlist_del_channel(server->local_list, cache->context);
117 while (silc_idcache_list_next(list, &cache))
118 silc_idlist_del_channel(server->local_list, cache->context);
121 silc_idcache_list_free(list);
123 if (silc_idcache_get_all(server->global_list->channels, &list) &&
124 silc_idcache_list_first(list, &cache)) {
125 silc_idlist_del_channel(server->global_list, cache->context);
126 while (silc_idcache_list_next(list, &cache))
127 silc_idlist_del_channel(server->global_list, cache->context);
130 silc_idcache_list_free(list);
133 silc_hash_table_free(server->pk_hash);
135 /* Delete all clients */
137 if (silc_idcache_get_all(server->local_list->clients, &list) &&
138 silc_idcache_list_first(list, &cache)) {
139 silc_idlist_del_client(server->local_list, cache->context);
140 while (silc_idcache_list_next(list, &cache))
141 silc_idlist_del_client(server->local_list, cache->context);
144 silc_idcache_list_free(list);
146 if (silc_idcache_get_all(server->global_list->clients, &list) &&
147 silc_idcache_list_first(list, &cache)) {
148 silc_idlist_del_client(server->global_list, cache->context);
149 while (silc_idcache_list_next(list, &cache))
150 silc_idlist_del_client(server->global_list, cache->context);
153 silc_idcache_list_free(list);
156 /* Delete all servers */
158 if (silc_idcache_get_all(server->local_list->servers, &list) &&
159 silc_idcache_list_first(list, &cache)) {
160 silc_idlist_del_server(server->local_list, cache->context);
161 while (silc_idcache_list_next(list, &cache))
162 silc_idlist_del_server(server->local_list, cache->context);
165 silc_idcache_list_free(list);
167 if (silc_idcache_get_all(server->global_list->servers, &list) &&
168 silc_idcache_list_first(list, &cache)) {
169 silc_idlist_del_server(server->global_list, cache->context);
170 while (silc_idcache_list_next(list, &cache))
171 silc_idlist_del_server(server->global_list, cache->context);
174 silc_idcache_list_free(list);
176 silc_idcache_free(server->local_list->clients);
177 silc_idcache_free(server->local_list->servers);
178 silc_idcache_free(server->local_list->channels);
179 silc_idcache_free(server->global_list->clients);
180 silc_idcache_free(server->global_list->servers);
181 silc_idcache_free(server->global_list->channels);
182 silc_hash_table_free(server->watcher_list);
183 silc_hash_table_free(server->watcher_list_pk);
185 silc_hash_free(server->md5hash);
186 silc_hash_free(server->sha1hash);
187 silc_hmac_unregister_all();
188 silc_hash_unregister_all();
189 silc_cipher_unregister_all();
190 silc_pkcs_unregister_all();
192 silc_free(server->local_list);
193 silc_free(server->global_list);
194 silc_free(server->server_name);
195 silc_free(server->id_string);
196 silc_free(server->purge_i);
197 silc_free(server->purge_g);
201 /* Creates a new server listener. */
203 static bool silc_server_listen(SilcServer server, const char *server_ip,
204 SilcUInt16 port, int *sock)
206 *sock = silc_net_create_server(port, server_ip);
208 SILC_SERVER_LOG_ERROR(("Could not create server listener: %s on %hu",
215 /* Adds a secondary listener. */
217 bool silc_server_init_secondary(SilcServer server)
219 int sock = 0, sock_list[server->config->param.connections_max];
220 SilcSocketConnection newsocket = NULL;
221 SilcServerConfigServerInfoInterface *interface;
223 for (interface = server->config->server_info->secondary; interface;
224 interface = interface->next, sock++) {
226 if (!silc_server_listen(server,
227 interface->server_ip, interface->port, &sock_list[sock]))
230 /* Set socket to non-blocking mode */
231 silc_net_set_socket_nonblock(sock_list[sock]);
233 /* Add ourselves also to the socket table. The entry allocated above
234 is sent as argument for fast referencing in the future. */
235 silc_socket_alloc(sock_list[sock],
236 SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
237 server->sockets[sock_list[sock]] = newsocket;
238 SILC_SET_LISTENER(newsocket);
240 /* Perform name and address lookups to resolve the listenning address
242 if (!silc_net_check_local_by_sock(sock_list[sock], &newsocket->hostname,
244 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
246 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
247 newsocket->hostname ? newsocket->hostname :
248 newsocket->ip ? newsocket->ip : ""));
249 server->stat.conn_failures++;
252 if (!newsocket->hostname)
253 newsocket->hostname = strdup(newsocket->ip);
255 newsocket->port = silc_net_get_local_port(sock);
257 newsocket->user_data = (void *)server->id_entry;
258 silc_schedule_task_add(server->schedule, sock_list[sock],
259 silc_server_accept_new_connection,
260 (void *)server, 0, 0,
262 SILC_TASK_PRI_NORMAL);
268 do silc_net_close_server(sock_list[sock--]); while (sock >= 0);
272 /* Initializes the entire SILC server. This is called always before running
273 the server. This is called only once at the initialization of the program.
274 This binds the server to its listenning port. After this function returns
275 one should call silc_server_run to start the server. This returns TRUE
276 when everything is ok to run the server. Configuration file must be
277 read and parsed before calling this. */
279 bool silc_server_init(SilcServer server)
283 SilcServerEntry id_entry;
284 SilcIDListPurge purge;
285 SilcSocketConnection newsocket = NULL;
287 SILC_LOG_DEBUG(("Initializing server"));
289 server->starttime = time(NULL);
291 /* Take config object for us */
292 silc_server_config_ref(&server->config_ref, server->config,
296 /* Set debugging on if configured */
297 if (server->config->debug_string) {
299 silc_log_set_debug_string(server->config->debug_string);
301 #endif /* SILC_DEBUG */
303 /* Steal public and private key from the config object */
304 server->public_key = server->config->server_info->public_key;
305 server->private_key = server->config->server_info->private_key;
306 server->config->server_info->public_key = NULL;
307 server->config->server_info->private_key = NULL;
309 /* Register all configured ciphers, PKCS and hash functions. */
310 if (!silc_server_config_register_ciphers(server))
311 silc_cipher_register_default();
312 if (!silc_server_config_register_pkcs(server))
313 silc_pkcs_register_default();
314 if (!silc_server_config_register_hashfuncs(server))
315 silc_hash_register_default();
316 if (!silc_server_config_register_hmacs(server))
317 silc_hmac_register_default();
319 /* Initialize random number generator for the server. */
320 server->rng = silc_rng_alloc();
321 silc_rng_init(server->rng);
322 silc_rng_global_init(server->rng);
324 /* Initialize hash functions for server to use */
325 silc_hash_alloc("md5", &server->md5hash);
326 silc_hash_alloc("sha1", &server->sha1hash);
328 /* Allocate PKCS context for local public and private keys */
329 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
331 silc_pkcs_public_key_set(server->pkcs, server->public_key);
332 silc_pkcs_private_key_set(server->pkcs, server->private_key);
334 /* Initialize the scheduler */
335 server->schedule = silc_schedule_init(server->config->param.connections_max,
337 if (!server->schedule)
340 /* First, register log files configuration for error output */
341 silc_server_config_setlogfiles(server);
343 /* Initialize ID caches */
344 server->local_list->clients =
345 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
346 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
347 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
349 /* These are allocated for normal server as well as these hold some
350 global information that the server has fetched from its router. For
351 router these are used as they are supposed to be used on router. */
352 server->global_list->clients =
353 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
354 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
355 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
357 /* Init watcher lists */
358 server->watcher_list =
359 silc_hash_table_alloc(1, silc_hash_client_id_hash, NULL,
360 silc_hash_data_compare, (void *)CLIENTID_HASH_LEN,
362 if (!server->watcher_list)
364 server->watcher_list_pk =
365 silc_hash_table_alloc(1, silc_hash_public_key, NULL,
366 silc_hash_public_key_compare, NULL,
368 if (!server->watcher_list_pk)
371 /* Init public key list */
373 silc_hash_table_alloc(0, silc_hash_public_key, NULL,
374 silc_hash_public_key_compare, NULL,
377 if (!server->pk_hash)
380 /* Create a listening server */
381 if (!silc_server_listen(server,
382 server->config->server_info->primary == NULL ? NULL :
383 server->config->server_info->primary->server_ip,
384 server->config->server_info->primary == NULL ? 0 :
385 server->config->server_info->primary->port,
389 /* Set socket to non-blocking mode */
390 silc_net_set_socket_nonblock(sock);
393 /* Allocate the entire socket list that is used in server. Eventually
394 all connections will have entry in this table (it is a table of
395 pointers to the actual object that is allocated individually
397 server->sockets = silc_calloc(server->config->param.connections_max,
398 sizeof(*server->sockets));
399 if (!server->sockets)
402 /* Add ourselves also to the socket table. The entry allocated above
403 is sent as argument for fast referencing in the future. */
404 silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
405 server->sockets[sock] = newsocket;
406 SILC_SET_LISTENER(newsocket);
408 /* Perform name and address lookups to resolve the listenning address
410 if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
412 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
414 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
415 newsocket->hostname ? newsocket->hostname :
416 newsocket->ip ? newsocket->ip : ""));
417 server->stat.conn_failures++;
420 if (!newsocket->hostname)
421 newsocket->hostname = strdup(newsocket->ip);
423 newsocket->port = silc_net_get_local_port(sock);
425 /* Create a Server ID for the server. */
426 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
431 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
432 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
433 server->server_name = server->config->server_info->server_name;
434 server->config->server_info->server_name = NULL;
436 /* Add ourselves to the server list. We don't have a router yet
437 beacuse we haven't established a route yet. It will be done later.
438 For now, NULL is sent as router. This allocates new entry to
441 silc_idlist_add_server(server->local_list, strdup(server->server_name),
442 server->server_type, server->id, NULL, NULL);
444 SILC_LOG_ERROR(("Could not add ourselves to cache"));
447 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
449 /* Put the allocated socket pointer also to the entry allocated above
450 for fast back-referencing to the socket list. */
451 newsocket->user_data = (void *)id_entry;
452 id_entry->connection = (void *)newsocket;
453 server->id_entry = id_entry;
455 /* Register protocols */
456 silc_server_protocols_register();
458 /* Create connections to configured routers. */
459 silc_server_create_connections(server);
461 /* Add listener task to the scheduler. This task receives new connections
462 to the server. This task remains on the queue until the end of the
464 silc_schedule_task_add(server->schedule, sock,
465 silc_server_accept_new_connection,
466 (void *)server, 0, 0,
468 SILC_TASK_PRI_NORMAL);
470 if (silc_server_init_secondary(server) == FALSE)
473 server->listenning = TRUE;
475 /* If server connections has been configured then we must be router as
476 normal server cannot have server connections, only router connections. */
477 if (server->config->servers) {
478 SilcServerConfigServer *ptr = server->config->servers;
480 server->server_type = SILC_ROUTER;
482 if (ptr->backup_router) {
483 server->server_type = SILC_BACKUP_ROUTER;
484 server->backup_router = TRUE;
485 server->id_entry->server_type = SILC_BACKUP_ROUTER;
492 /* Register the ID Cache purge task. This periodically purges the ID cache
493 and removes the expired cache entries. */
495 /* Clients local list */
496 server->purge_i = purge = silc_calloc(1, sizeof(*purge));
497 purge->cache = server->local_list->clients;
498 purge->timeout = 600;
499 silc_schedule_task_add(server->schedule, 0, silc_idlist_purge,
500 (void *)purge, purge->timeout, 0,
501 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
503 /* Clients global list */
504 server->purge_g = purge = silc_calloc(1, sizeof(*purge));
505 purge->cache = server->global_list->clients;
506 purge->timeout = 300;
507 silc_schedule_task_add(server->schedule, 0, silc_idlist_purge,
508 (void *)purge, purge->timeout, 0,
509 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
511 /* If we are normal server we'll retrieve network statisticial information
512 once in a while from the router. */
513 if (server->server_type != SILC_ROUTER)
514 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
515 server, 10, 0, SILC_TASK_TIMEOUT,
518 if (server->server_type == SILC_ROUTER)
519 server->stat.routers++;
521 SILC_LOG_DEBUG(("Server initialized"));
523 /* We are done here, return succesfully */
527 silc_server_config_unref(&server->config_ref);
528 silc_net_close_server(sock);
532 /* Task callback to close a socket connection after rehash */
534 SILC_TASK_CALLBACK(silc_server_rehash_close_connection)
536 SilcServer server = context;
537 SilcSocketConnection sock = server->sockets[fd];
542 SILC_LOG_INFO(("Connection %s:%d [%s] is unconfigured",
543 sock->hostname, sock->port,
544 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
545 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
546 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
548 silc_schedule_task_del_by_context(server->schedule, sock);
549 silc_server_disconnect_remote(server, sock,
550 SILC_STATUS_ERR_BANNED_FROM_SERVER,
551 "This connection is removed from "
554 silc_server_free_sock_user_data(server, sock, NULL);
557 /* This function basically reads the config file again and switches the config
558 object pointed by the server object. After that, we have to fix various
559 things such as the server_name and the listening ports.
560 Keep in mind that we no longer have the root privileges at this point. */
562 bool silc_server_rehash(SilcServer server)
564 SilcServerConfig newconfig;
566 SILC_LOG_INFO(("Rehashing server"));
568 /* Reset the logging system */
569 silc_log_quick = TRUE;
570 silc_log_flush_all();
572 /* Start the main rehash phase (read again the config file) */
573 newconfig = silc_server_config_alloc(server->config_file);
575 SILC_LOG_ERROR(("Rehash FAILED."));
579 /* Reinit scheduler if necessary */
580 if (newconfig->param.connections_max > server->config->param.connections_max)
581 if (!silc_schedule_reinit(server->schedule,
582 newconfig->param.connections_max))
585 /* Fix the server_name field */
586 if (strcmp(server->server_name, newconfig->server_info->server_name)) {
587 silc_free(server->server_name);
588 server->server_name = newconfig->server_info->server_name;
589 newconfig->server_info->server_name = NULL;
591 /* Update the idcache list with a fresh pointer */
592 silc_free(server->id_entry->server_name);
593 server->id_entry->server_name = strdup(server->server_name);
594 if (!silc_idcache_del_by_context(server->local_list->servers,
597 if (!silc_idcache_add(server->local_list->servers,
598 server->id_entry->server_name,
599 server->id_entry->id, server->id_entry, 0, NULL))
604 silc_server_config_setlogfiles(server);
606 /* Change new key pair if necessary */
607 if (newconfig->server_info->public_key &&
608 !silc_pkcs_public_key_compare(server->public_key,
609 newconfig->server_info->public_key)) {
610 silc_pkcs_public_key_free(server->public_key);
611 silc_pkcs_private_key_free(server->private_key);
612 server->public_key = newconfig->server_info->public_key;
613 server->private_key = newconfig->server_info->private_key;
614 newconfig->server_info->public_key = NULL;
615 newconfig->server_info->private_key = NULL;
617 /* Allocate PKCS context for local public and private keys */
618 silc_pkcs_free(server->pkcs);
619 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
621 silc_pkcs_public_key_set(server->pkcs, server->public_key);
622 silc_pkcs_private_key_set(server->pkcs, server->private_key);
625 /* Check for unconfigured server and router connections and close
626 connections that were unconfigured. */
628 if (server->config->routers) {
629 SilcServerConfigRouter *ptr;
630 SilcServerConfigRouter *newptr;
633 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
636 /* Check whether new config has this one too */
637 for (newptr = newconfig->routers; newptr; newptr = newptr->next) {
638 if (silc_string_compare(newptr->host, ptr->host) &&
639 newptr->port == ptr->port &&
640 newptr->initiator == ptr->initiator) {
646 if (!found && ptr->host) {
647 /* Remove this connection */
648 SilcSocketConnection sock;
649 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_ROUTER,
650 ptr->host, ptr->port);
651 if (sock && !SILC_IS_LISTENER(sock))
652 silc_schedule_task_add(server->schedule, sock->sock,
653 silc_server_rehash_close_connection,
654 server, 0, 1, SILC_TASK_TIMEOUT,
655 SILC_TASK_PRI_NORMAL);
660 if (server->config->servers) {
661 SilcServerConfigServer *ptr;
662 SilcServerConfigServer *newptr;
665 for (ptr = server->config->servers; ptr; ptr = ptr->next) {
668 /* Check whether new config has this one too */
669 for (newptr = newconfig->servers; newptr; newptr = newptr->next) {
670 if (silc_string_compare(newptr->host, ptr->host)) {
676 if (!found && ptr->host) {
677 /* Remove this connection */
678 SilcSocketConnection sock;
679 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_SERVER,
681 if (sock && !SILC_IS_LISTENER(sock))
682 silc_schedule_task_add(server->schedule, sock->sock,
683 silc_server_rehash_close_connection,
684 server, 0, 1, SILC_TASK_TIMEOUT,
685 SILC_TASK_PRI_NORMAL);
690 if (server->config->clients) {
691 SilcServerConfigClient *ptr;
692 SilcServerConfigClient *newptr;
695 for (ptr = server->config->clients; ptr; ptr = ptr->next) {
698 /* Check whether new config has this one too */
699 for (newptr = newconfig->clients; newptr; newptr = newptr->next) {
700 if (silc_string_compare(newptr->host, ptr->host)) {
706 if (!found && ptr->host) {
707 /* Remove this connection */
708 SilcSocketConnection sock;
709 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_CLIENT,
712 silc_schedule_task_add(server->schedule, sock->sock,
713 silc_server_rehash_close_connection,
714 server, 0, 1, SILC_TASK_TIMEOUT,
715 SILC_TASK_PRI_NORMAL);
720 /* Create connections after rehash */
721 silc_server_create_connections(server);
723 /* Check whether our router status has changed */
724 if (newconfig->servers) {
725 SilcServerConfigServer *ptr = newconfig->servers;
727 server->server_type = SILC_ROUTER;
729 if (ptr->backup_router) {
730 server->server_type = SILC_BACKUP_ROUTER;
731 server->backup_router = TRUE;
732 server->id_entry->server_type = SILC_BACKUP_ROUTER;
739 /* Our old config is gone now. We'll unreference our reference made in
740 silc_server_init and then destroy it since we are destroying it
741 underneath the application (layer which called silc_server_init). */
742 silc_server_config_unref(&server->config_ref);
743 silc_server_config_destroy(server->config);
745 /* Take new config context */
746 server->config = newconfig;
747 silc_server_config_ref(&server->config_ref, server->config, server->config);
750 /* Set debugging on if configured */
751 if (server->config->debug_string) {
753 silc_log_set_debug_string(server->config->debug_string);
755 #endif /* SILC_DEBUG */
757 SILC_LOG_DEBUG(("Server rehashed"));
762 /* The heart of the server. This runs the scheduler thus runs the server.
763 When this returns the server has been stopped and the program will
766 void silc_server_run(SilcServer server)
768 SILC_LOG_INFO(("SILC Server started"));
770 /* Start the scheduler, the heart of the SILC server. When this returns
771 the program will be terminated. */
772 silc_schedule(server->schedule);
775 /* Stops the SILC server. This function is used to shutdown the server.
776 This is usually called after the scheduler has returned. After stopping
777 the server one should call silc_server_free. */
779 void silc_server_stop(SilcServer server)
781 SILC_LOG_INFO(("SILC Server shutting down"));
783 if (server->schedule) {
786 server->server_shutdown = TRUE;
788 /* Close all connections */
789 for (i = 0; i < server->config->param.connections_max; i++) {
790 if (!server->sockets[i])
792 if (!SILC_IS_LISTENER(server->sockets[i])) {
793 SilcSocketConnection sock = server->sockets[i];
794 SilcIDListData idata = sock->user_data;
797 idata->status &= ~SILC_IDLIST_STATUS_DISABLED;
799 silc_schedule_task_del_by_context(server->schedule,
801 silc_schedule_task_del_by_fd(server->schedule,
802 server->sockets[i]->sock);
803 silc_server_disconnect_remote(server, server->sockets[i],
805 "Server is shutting down");
806 if (server->sockets[i]) {
808 silc_server_free_sock_user_data(server, sock,
809 "Server is shutting down");
810 silc_socket_free(sock);
813 silc_socket_free(server->sockets[i]);
814 server->sockets[i] = NULL;
818 /* We are not connected to network anymore */
819 server->standalone = TRUE;
821 silc_schedule_stop(server->schedule);
822 silc_schedule_uninit(server->schedule);
823 server->schedule = NULL;
825 silc_free(server->sockets);
826 server->sockets = NULL;
829 silc_server_protocols_unregister();
831 SILC_LOG_DEBUG(("Server stopped"));
834 /* Function that is called when the network connection to a router has
835 been established. This will continue with the key exchange protocol
836 with the remote router. */
838 void silc_server_start_key_exchange(SilcServer server,
839 SilcServerConnection sconn,
842 SilcSocketConnection newsocket;
843 SilcProtocol protocol;
844 SilcServerKEInternalContext *proto_ctx;
845 SilcServerConfigRouter *conn =
846 (SilcServerConfigRouter *) sconn->conn.ref_ptr;
849 /* Cancel any possible retry timeouts */
850 silc_schedule_task_del_by_callback(server->schedule,
851 silc_server_connect_to_router_retry);
853 /* Set socket options */
854 silc_net_set_socket_nonblock(sock);
855 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
857 /* Create socket connection for the connection. Even though we
858 know that we are connecting to a router we will mark the socket
859 to be unknown connection until we have executed authentication
861 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
862 server->sockets[sock] = newsocket;
863 newsocket->hostname = strdup(sconn->remote_host);
864 newsocket->ip = strdup(sconn->remote_host);
865 newsocket->port = sconn->remote_port;
866 sconn->sock = newsocket;
868 /* Allocate internal protocol context. This is sent as context
870 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
871 proto_ctx->server = (void *)server;
872 proto_ctx->context = (void *)sconn;
873 proto_ctx->sock = newsocket;
874 proto_ctx->rng = server->rng;
875 proto_ctx->responder = FALSE;
877 /* Set Key Exchange flags from configuration, but fall back to global
879 SILC_GET_SKE_FLAGS(conn, proto_ctx);
880 if (server->config->param.key_exchange_pfs)
881 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
883 /* Perform key exchange protocol. silc_server_connect_to_router_second
884 will be called after the protocol is finished. */
885 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
886 &protocol, proto_ctx,
887 silc_server_connect_to_router_second);
888 newsocket->protocol = protocol;
890 /* Register a timeout task that will be executed if the protocol
891 is not executed within set limit. */
892 proto_ctx->timeout_task =
893 silc_schedule_task_add(server->schedule, sock,
894 silc_server_timeout_remote,
895 server, server->config->key_exchange_timeout, 0,
899 /* Register the connection for network input and output. This sets
900 that scheduler will listen for incoming packets for this connection
901 and sets that outgoing packets may be sent to this connection as
902 well. However, this doesn't set the scheduler for outgoing traffic,
903 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
904 later when outgoing data is available. */
905 context = (void *)server;
906 SILC_REGISTER_CONNECTION_FOR_IO(sock);
908 /* Run the protocol */
909 silc_protocol_execute(protocol, server->schedule, 0, 0);
912 /* Timeout callback that will be called to retry connecting to remote
913 router. This is used by both normal and router server. This will wait
914 before retrying the connecting. The timeout is generated by exponential
915 backoff algorithm. */
917 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
919 SilcServer server = app_context;
920 SilcServerConnection sconn = (SilcServerConnection)context;
921 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
922 SilcServerConfigConnParams *param =
923 (conn->param ? conn->param : &server->config->param);
925 /* Don't retry if we are shutting down. */
926 if (server->server_shutdown) {
927 silc_server_config_unref(&sconn->conn);
928 silc_free(sconn->remote_host);
929 silc_free(sconn->backup_replace_ip);
934 SILC_LOG_INFO(("Retrying connecting to a router"));
936 /* Calculate next timeout */
937 if (sconn->retry_count >= 1) {
938 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
939 if (sconn->retry_timeout > param->reconnect_interval_max)
940 sconn->retry_timeout = param->reconnect_interval_max;
942 sconn->retry_timeout = param->reconnect_interval;
944 sconn->retry_count++;
945 sconn->retry_timeout = sconn->retry_timeout +
946 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
948 /* If we've reached max retry count, give up. */
949 if ((sconn->retry_count > param->reconnect_count) &&
950 !param->reconnect_keep_trying) {
951 SILC_LOG_ERROR(("Could not connect to router, giving up"));
952 silc_server_config_unref(&sconn->conn);
953 silc_free(sconn->remote_host);
954 silc_free(sconn->backup_replace_ip);
959 SILC_LOG_DEBUG(("Retrying connecting to a router in %d seconds",
960 sconn->retry_timeout));
962 /* We will lookup a fresh pointer later */
963 silc_server_config_unref(&sconn->conn);
965 /* Wait one before retrying */
966 silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
967 context, sconn->retry_timeout, 0,
968 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
971 /* callback for async connection to remote router */
973 SILC_TASK_CALLBACK(silc_server_connection_established)
975 SilcServer server = app_context;
976 SilcServerConnection sconn = (SilcServerConnection)context;
978 int opt = EINVAL, optlen = sizeof(opt);
980 silc_schedule_task_del_by_fd(server->schedule, sock);
981 silc_schedule_unset_listen_fd(server->schedule, sock);
983 if (silc_net_get_socket_opt(sock, SOL_SOCKET, SO_ERROR, &opt, &optlen) ||
985 SILC_LOG_ERROR(("Could not connect to router %s:%d: %s",
986 sconn->remote_host, sconn->remote_port,
988 if (!sconn->no_reconnect)
989 silc_schedule_task_add(server->schedule, 0,
990 silc_server_connect_to_router_retry,
991 context, 0, 1, SILC_TASK_TIMEOUT,
992 SILC_TASK_PRI_NORMAL);
994 silc_server_config_unref(&sconn->conn);
995 silc_free(sconn->remote_host);
996 silc_free(sconn->backup_replace_ip);
1002 SILC_LOG_DEBUG(("Connection to router %s:%d established", sconn->remote_host,
1003 sconn->remote_port));
1005 /* Continue with key exchange protocol */
1006 silc_server_start_key_exchange(server, sconn, sock);
1008 /* Generic routine to use connect to a router. */
1010 SILC_TASK_CALLBACK(silc_server_connect_router)
1012 SilcServer server = app_context;
1013 SilcServerConnection sconn = (SilcServerConnection)context;
1014 SilcServerConfigRouter *rconn;
1017 /* Don't connect if we are shutting down. */
1018 if (server->server_shutdown) {
1019 silc_free(sconn->remote_host);
1020 silc_free(sconn->backup_replace_ip);
1025 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
1026 (sconn->backup ? "backup router" : "router"),
1027 sconn->remote_host, sconn->remote_port));
1029 server->router_connect = time(NULL);
1030 rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
1031 sconn->remote_port);
1033 SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
1034 (sconn->backup ? "backup router" : "router"),
1035 sconn->remote_host, sconn->remote_port));
1036 silc_free(sconn->remote_host);
1037 silc_free(sconn->backup_replace_ip);
1041 silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
1043 /* Connect to remote host */
1044 sock = silc_net_create_connection_async(
1045 (!server->config->server_info->primary ? NULL :
1046 server->config->server_info->primary->server_ip),
1047 sconn->remote_port, sconn->remote_host);
1049 SILC_LOG_ERROR(("Could not connect to router %s:%d",
1050 sconn->remote_host, sconn->remote_port));
1051 if (!sconn->no_reconnect)
1052 silc_schedule_task_add(server->schedule, 0,
1053 silc_server_connect_to_router_retry,
1054 context, 0, 1, SILC_TASK_TIMEOUT,
1055 SILC_TASK_PRI_NORMAL);
1057 silc_server_config_unref(&sconn->conn);
1058 silc_free(sconn->remote_host);
1059 silc_free(sconn->backup_replace_ip);
1065 /* wait for the connection to be established */
1066 silc_schedule_task_add(server->schedule, sock,
1067 silc_server_connection_established,
1068 context, 0, 0, SILC_TASK_FD,
1069 SILC_TASK_PRI_NORMAL);
1070 silc_schedule_set_listen_fd(server->schedule, sock,
1071 SILC_TASK_WRITE, FALSE);
1074 /* This function connects to our primary router or if we are a router this
1075 establishes all our primary routes. This is called at the start of the
1076 server to do authentication and key exchange with our router - called
1079 SILC_TASK_CALLBACK_GLOBAL(silc_server_connect_to_router)
1081 SilcServer server = (SilcServer)context;
1082 SilcServerConnection sconn;
1083 SilcServerConfigRouter *ptr;
1085 /* Don't connect if we are shutting down. */
1086 if (server->server_shutdown)
1089 SILC_LOG_DEBUG(("We are %s",
1090 (server->server_type == SILC_SERVER ?
1091 "normal server" : server->server_type == SILC_ROUTER ?
1092 "router" : "backup router/normal server")));
1094 if (!server->config->routers) {
1095 /* There wasn't a configured router, we will continue but we don't
1096 have a connection to outside world. We will be standalone server. */
1097 SILC_LOG_DEBUG(("No router(s), we are standalone"));
1098 server->standalone = TRUE;
1102 /* Cancel any possible retry timeouts */
1103 silc_schedule_task_del_by_callback(server->schedule,
1104 silc_server_connect_router);
1105 silc_schedule_task_del_by_callback(server->schedule,
1106 silc_server_connect_to_router_retry);
1108 /* Create the connections to all our routes */
1109 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
1111 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
1112 ptr->backup_router ? "Backup router" : "Router",
1113 ptr->initiator ? "Initiator" : "Responder",
1114 ptr->host, ptr->port));
1116 if (server->server_type == SILC_ROUTER && ptr->backup_router &&
1117 ptr->initiator == FALSE && !server->backup_router &&
1118 !silc_server_config_get_backup_router(server))
1119 server->wait_backup = TRUE;
1121 if (ptr->initiator) {
1122 /* Check whether we are connecting or connected to this host already */
1123 if (silc_server_num_sockets_by_remote(server,
1124 silc_net_is_ip(ptr->host) ?
1126 silc_net_is_ip(ptr->host) ?
1127 NULL : ptr->host, ptr->port,
1128 SILC_SOCKET_TYPE_ROUTER)) {
1129 SILC_LOG_DEBUG(("We are already connected to this router"));
1131 /* If we don't have primary router and this connection is our
1132 primary router we are in desync. Reconnect to the primary. */
1133 if (server->standalone && !server->router) {
1134 SilcServerConfigRouter *primary =
1135 silc_server_config_get_primary_router(server);
1136 if (primary == ptr) {
1137 SilcSocketConnection sock =
1138 silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_ROUTER,
1139 ptr->host, ptr->port);
1141 server->backup_noswitch = TRUE;
1142 if (sock->user_data)
1143 silc_server_free_sock_user_data(server, sock, NULL);
1144 silc_server_disconnect_remote(server, sock, 0, NULL);
1145 server->backup_noswitch = FALSE;
1146 SILC_LOG_DEBUG(("Reconnecting to primary router"));
1157 if (silc_server_num_sockets_by_remote(server,
1158 silc_net_is_ip(ptr->host) ?
1160 silc_net_is_ip(ptr->host) ?
1161 NULL : ptr->host, ptr->port,
1162 SILC_SOCKET_TYPE_UNKNOWN)) {
1163 SILC_LOG_DEBUG(("We are already connecting to this router"));
1167 /* Allocate connection object for hold connection specific stuff. */
1168 sconn = silc_calloc(1, sizeof(*sconn));
1169 sconn->remote_host = strdup(ptr->host);
1170 sconn->remote_port = ptr->port;
1171 sconn->backup = ptr->backup_router;
1172 if (sconn->backup) {
1173 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
1174 sconn->backup_replace_port = ptr->backup_replace_port;
1177 if (!server->router_conn && !sconn->backup)
1178 server->router_conn = sconn;
1180 silc_schedule_task_add(server->schedule, 0,
1181 silc_server_connect_router,
1182 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
1183 SILC_TASK_PRI_NORMAL);
1188 /* Second part of connecting to router(s). Key exchange protocol has been
1189 executed and now we will execute authentication protocol. */
1191 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
1193 SilcProtocol protocol = (SilcProtocol)context;
1194 SilcServerKEInternalContext *ctx =
1195 (SilcServerKEInternalContext *)protocol->context;
1196 SilcServer server = (SilcServer)ctx->server;
1197 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1198 SilcSocketConnection sock = ctx->sock;
1199 SilcServerConnAuthInternalContext *proto_ctx;
1200 SilcServerConfigRouter *conn = NULL;
1202 SILC_LOG_DEBUG(("Start"));
1204 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1205 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1206 /* Error occured during protocol */
1207 silc_protocol_free(protocol);
1208 sock->protocol = NULL;
1209 silc_ske_free_key_material(ctx->keymat);
1211 silc_packet_context_free(ctx->packet);
1213 silc_ske_free(ctx->ske);
1214 silc_free(ctx->dest_id);
1216 silc_server_disconnect_remote(server, sock,
1217 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1219 /* Try reconnecting if configuration wants it */
1220 if (!sconn->no_reconnect) {
1221 silc_schedule_task_add(server->schedule, 0,
1222 silc_server_connect_to_router_retry,
1223 sconn, 0, 1, SILC_TASK_TIMEOUT,
1224 SILC_TASK_PRI_NORMAL);
1228 /* Call completion to indicate error */
1229 if (sconn->callback)
1230 (*sconn->callback)(server, NULL, sconn->callback_context);
1232 silc_server_config_unref(&sconn->conn);
1233 silc_free(sconn->remote_host);
1234 silc_free(sconn->backup_replace_ip);
1239 /* We now have the key material as the result of the key exchange
1240 protocol. Take the key material into use. Free the raw key material
1241 as soon as we've set them into use. */
1242 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1243 ctx->sock, ctx->keymat,
1244 ctx->ske->prop->cipher,
1245 ctx->ske->prop->pkcs,
1246 ctx->ske->prop->hash,
1247 ctx->ske->prop->hmac,
1248 ctx->ske->prop->group,
1250 silc_protocol_free(protocol);
1251 sock->protocol = NULL;
1252 silc_ske_free_key_material(ctx->keymat);
1254 silc_packet_context_free(ctx->packet);
1256 silc_ske_free(ctx->ske);
1257 silc_free(ctx->dest_id);
1259 silc_server_disconnect_remote(server, sock,
1260 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1262 /* Try reconnecting if configuration wants it */
1263 if (!sconn->no_reconnect) {
1264 silc_schedule_task_add(server->schedule, 0,
1265 silc_server_connect_to_router_retry,
1266 sconn, 0, 1, SILC_TASK_TIMEOUT,
1267 SILC_TASK_PRI_NORMAL);
1271 /* Call completion to indicate error */
1272 if (sconn->callback)
1273 (*sconn->callback)(server, NULL, sconn->callback_context);
1275 silc_server_config_unref(&sconn->conn);
1276 silc_free(sconn->remote_host);
1277 silc_free(sconn->backup_replace_ip);
1281 silc_ske_free_key_material(ctx->keymat);
1283 /* Allocate internal context for the authentication protocol. This
1284 is sent as context for the protocol. */
1285 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1286 proto_ctx->server = (void *)server;
1287 proto_ctx->context = (void *)sconn;
1288 proto_ctx->sock = sock;
1289 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1290 proto_ctx->dest_id_type = ctx->dest_id_type;
1291 proto_ctx->dest_id = ctx->dest_id;
1293 /* Resolve the authentication method used in this connection. Check if
1294 we find a match from user configured connections */
1295 if (!sconn->conn.ref_ptr)
1296 conn = silc_server_config_find_router_conn(server, sock->hostname,
1299 conn = sconn->conn.ref_ptr;
1302 /* Match found. Use the configured authentication method. Take only
1303 the passphrase, since for public key auth we automatically use
1304 our local key pair. */
1305 if (conn->passphrase) {
1306 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
1307 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1309 proto_ctx->auth_data = strdup(conn->passphrase);
1310 proto_ctx->auth_data_len = strlen(conn->passphrase);
1311 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
1313 } else if (conn->publickeys) {
1314 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1316 proto_ctx->auth_meth = SILC_AUTH_NONE;
1319 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
1320 sock->hostname, sock->ip, sock->port));
1321 silc_protocol_free(protocol);
1322 sock->protocol = NULL;
1324 silc_packet_context_free(ctx->packet);
1326 silc_ske_free(ctx->ske);
1327 silc_free(ctx->dest_id);
1329 silc_server_config_unref(&sconn->conn);
1330 silc_free(sconn->remote_host);
1331 silc_free(sconn->backup_replace_ip);
1333 silc_server_disconnect_remote(server, sock,
1334 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1338 /* Free old protocol as it is finished now */
1339 silc_protocol_free(protocol);
1341 silc_packet_context_free(ctx->packet);
1343 sock->protocol = NULL;
1345 /* Allocate the authentication protocol. This is allocated here
1346 but we won't start it yet. We will be receiving party of this
1347 protocol thus we will wait that connecting party will make
1348 their first move. */
1349 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1350 &sock->protocol, proto_ctx,
1351 silc_server_connect_to_router_final);
1353 /* Register timeout task. If the protocol is not executed inside
1354 this timelimit the connection will be terminated. */
1355 proto_ctx->timeout_task =
1356 silc_schedule_task_add(server->schedule, sock->sock,
1357 silc_server_timeout_remote,
1359 server->config->conn_auth_timeout, 0,
1363 /* Run the protocol */
1364 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1367 /* Finalizes the connection to router. Registers a server task to the
1368 queue so that we can accept new connections. */
1370 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
1372 SilcProtocol protocol = (SilcProtocol)context;
1373 SilcServerConnAuthInternalContext *ctx =
1374 (SilcServerConnAuthInternalContext *)protocol->context;
1375 SilcServer server = (SilcServer)ctx->server;
1376 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1377 SilcSocketConnection sock = ctx->sock;
1378 SilcServerEntry id_entry = NULL;
1380 unsigned char *id_string;
1382 SilcIDListData idata;
1383 SilcServerConfigRouter *conn = NULL;
1384 SilcServerConfigConnParams *param = NULL;
1386 SILC_LOG_DEBUG(("Start"));
1388 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1389 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1390 /* Error occured during protocol */
1391 silc_free(ctx->dest_id);
1392 sock->protocol = NULL;
1393 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1395 sock->protocol = protocol;
1397 /* Try reconnecting if configuration wants it */
1398 if (!sconn->no_reconnect) {
1399 silc_schedule_task_add(server->schedule, 0,
1400 silc_server_connect_to_router_retry,
1401 sconn, 0, 1, SILC_TASK_TIMEOUT,
1402 SILC_TASK_PRI_NORMAL);
1409 /* Add a task to the queue. This task receives new connections to the
1410 server. This task remains on the queue until the end of the program. */
1411 if (!server->listenning && !sconn->backup) {
1412 silc_schedule_task_add(server->schedule, server->sock,
1413 silc_server_accept_new_connection,
1414 (void *)server, 0, 0,
1416 SILC_TASK_PRI_NORMAL);
1417 server->listenning = TRUE;
1420 /* Send NEW_SERVER packet to the router. We will become registered
1421 to the SILC network after sending this packet. */
1422 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
1423 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1424 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
1425 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1426 silc_buffer_format(packet,
1427 SILC_STR_UI_SHORT(id_len),
1428 SILC_STR_UI_XNSTRING(id_string, id_len),
1429 SILC_STR_UI_SHORT(strlen(server->server_name)),
1430 SILC_STR_UI_XNSTRING(server->server_name,
1431 strlen(server->server_name)),
1434 /* Send the packet */
1435 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
1436 packet->data, packet->len, TRUE);
1437 silc_buffer_free(packet);
1438 silc_free(id_string);
1440 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
1442 /* Check that we do not have this ID already */
1443 id_entry = silc_idlist_find_server_by_id(server->local_list,
1444 ctx->dest_id, TRUE, NULL);
1446 silc_idcache_del_by_context(server->local_list->servers, id_entry);
1448 id_entry = silc_idlist_find_server_by_id(server->global_list,
1449 ctx->dest_id, TRUE, NULL);
1451 silc_idcache_del_by_context(server->global_list->servers, id_entry);
1454 SILC_LOG_DEBUG(("New server id(%s)",
1455 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1457 /* Add the connected router to global server list. Router is sent
1458 as NULL since it's local to us. */
1459 id_entry = silc_idlist_add_server(server->global_list,
1460 strdup(sock->hostname),
1461 SILC_ROUTER, ctx->dest_id, NULL, sock);
1463 silc_free(ctx->dest_id);
1464 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1465 sock->protocol = NULL;
1466 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1468 sock->protocol = protocol;
1472 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1473 silc_free(sock->user_data);
1474 sock->user_data = (void *)id_entry;
1475 sock->type = SILC_SOCKET_TYPE_ROUTER;
1476 idata = (SilcIDListData)sock->user_data;
1477 idata->status |= (SILC_IDLIST_STATUS_REGISTERED |
1478 SILC_IDLIST_STATUS_LOCAL);
1480 conn = sconn->conn.ref_ptr;
1481 param = &server->config->param;
1482 if (conn && conn->param)
1483 param = conn->param;
1485 /* Perform keepalive. */
1486 silc_socket_set_heartbeat(sock, param->keepalive_secs, server,
1487 silc_server_perform_heartbeat,
1490 /* Register re-key timeout */
1491 idata->rekey->timeout = param->key_exchange_rekey;
1492 silc_schedule_task_add(server->schedule, sock->sock,
1493 silc_server_rekey_callback,
1494 (void *)sock, idata->rekey->timeout, 0,
1495 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1497 if (!sconn->backup) {
1498 /* Mark this router our primary router if we're still standalone */
1499 if (server->standalone) {
1500 SILC_LOG_DEBUG(("This connection is our primary router"));
1501 server->id_entry->router = id_entry;
1502 server->router = id_entry;
1503 server->router->server_type = SILC_ROUTER;
1504 server->standalone = FALSE;
1505 server->backup_primary = FALSE;
1507 /* Announce data if we are not backup router (unless not as primary
1508 currently). Backup router announces later at the end of
1509 resuming protocol. */
1510 if (server->backup_router && server->server_type == SILC_ROUTER) {
1511 SILC_LOG_DEBUG(("Announce data after resume protocol"));
1513 /* If we are router then announce our possible servers. Backup
1514 router announces also global servers. */
1515 if (server->server_type == SILC_ROUTER)
1516 silc_server_announce_servers(server,
1517 server->backup_router ? TRUE : FALSE,
1518 0, SILC_PRIMARY_ROUTE(server));
1520 /* Announce our clients and channels to the router */
1521 silc_server_announce_clients(server, 0, SILC_PRIMARY_ROUTE(server));
1522 silc_server_announce_channels(server, 0, SILC_PRIMARY_ROUTE(server));
1525 /* If we are backup router then this primary router is whom we are
1527 if (server->server_type == SILC_BACKUP_ROUTER)
1528 silc_server_backup_add(server, server->id_entry, sock->ip,
1529 sconn->remote_port, TRUE);
1532 /* Add this server to be our backup router */
1533 id_entry->server_type = SILC_BACKUP_ROUTER;
1534 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1535 sconn->backup_replace_port, FALSE);
1538 sock->protocol = NULL;
1541 /* Call the completion callback to indicate that we've connected to
1543 if (sconn && sconn->callback)
1544 (*sconn->callback)(server, id_entry, sconn->callback_context);
1546 /* Free the temporary connection data context */
1548 silc_server_config_unref(&sconn->conn);
1549 silc_free(sconn->remote_host);
1550 silc_free(sconn->backup_replace_ip);
1553 if (sconn == server->router_conn)
1554 server->router_conn = NULL;
1557 /* Free the protocol object */
1558 if (sock->protocol == protocol)
1559 sock->protocol = NULL;
1560 silc_protocol_free(protocol);
1562 silc_packet_context_free(ctx->packet);
1564 silc_ske_free(ctx->ske);
1565 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1566 silc_free(ctx->auth_data);
1570 /* Host lookup callback that is called after the incoming connection's
1571 IP and FQDN lookup is performed. This will actually check the acceptance
1572 of the incoming connection and will register the key exchange protocol
1573 for this connection. */
1576 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1579 SilcServerKEInternalContext *proto_ctx =
1580 (SilcServerKEInternalContext *)context;
1581 SilcServer server = (SilcServer)proto_ctx->server;
1582 SilcServerConfigClient *cconfig = NULL;
1583 SilcServerConfigServer *sconfig = NULL;
1584 SilcServerConfigRouter *rconfig = NULL;
1585 SilcServerConfigDeny *deny;
1588 /* Check whether we could resolve both IP and FQDN. */
1589 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1590 server->config->require_reverse_lookup)) {
1591 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1592 sock->hostname ? sock->hostname :
1593 sock->ip ? sock->ip : ""));
1594 server->stat.conn_failures++;
1595 silc_server_disconnect_remote(server, sock,
1596 SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
1597 "Unknown host or IP");
1598 silc_free(proto_ctx);
1602 /* Register the connection for network input and output. This sets
1603 that scheduler will listen for incoming packets for this connection
1604 and sets that outgoing packets may be sent to this connection as well.
1605 However, this doesn't set the scheduler for outgoing traffic, it
1606 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1607 later when outgoing data is available. */
1608 context = (void *)server;
1609 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1611 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1614 /* Listenning port */
1615 if (!server->sockets[SILC_PTR_TO_32(proto_ctx->context)]) {
1616 silc_server_disconnect_remote(server, sock,
1617 SILC_STATUS_ERR_RESOURCE_LIMIT,
1618 "Connection refused");
1619 server->stat.conn_failures++;
1620 silc_free(proto_ctx);
1623 port = server->sockets[SILC_PTR_TO_32(proto_ctx->context)]->port;
1625 /* Check whether this connection is denied to connect to us. */
1626 deny = silc_server_config_find_denied(server, sock->ip);
1628 deny = silc_server_config_find_denied(server, sock->hostname);
1630 /* The connection is denied */
1631 SILC_LOG_INFO(("Connection %s (%s) is denied",
1632 sock->hostname, sock->ip));
1633 silc_server_disconnect_remote(server, sock,
1634 SILC_STATUS_ERR_BANNED_FROM_SERVER,
1636 server->stat.conn_failures++;
1637 silc_free(proto_ctx);
1641 /* Check whether we have configured this sort of connection at all. We
1642 have to check all configurations since we don't know what type of
1643 connection this is. */
1644 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1645 cconfig = silc_server_config_find_client(server, sock->hostname);
1646 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1647 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1648 if (server->server_type == SILC_ROUTER) {
1649 if (!(rconfig = silc_server_config_find_router_conn(server,
1650 sock->ip, sock->port)))
1651 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1654 if (!cconfig && !sconfig && !rconfig) {
1655 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1657 silc_server_disconnect_remote(server, sock,
1658 SILC_STATUS_ERR_BANNED_FROM_SERVER, NULL);
1659 server->stat.conn_failures++;
1660 silc_free(proto_ctx);
1664 /* The connection is allowed */
1666 /* Set internal context for key exchange protocol. This is
1667 sent as context for the protocol. */
1668 proto_ctx->sock = sock;
1669 proto_ctx->rng = server->rng;
1670 proto_ctx->responder = TRUE;
1671 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1672 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1673 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1675 /* Take flags for key exchange. Since we do not know what type of connection
1676 this is, we go through all found configurations and use the global ones
1677 as well. This will result always into strictest key exchange flags. */
1678 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1679 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1680 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1681 if (server->config->param.key_exchange_pfs)
1682 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1684 /* Prepare the connection for key exchange protocol. We allocate the
1685 protocol but will not start it yet. The connector will be the
1686 initiator of the protocol thus we will wait for initiation from
1687 there before we start the protocol. */
1688 server->stat.auth_attempts++;
1689 SILC_LOG_DEBUG(("Starting key exchange protocol"));
1690 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1691 &sock->protocol, proto_ctx,
1692 silc_server_accept_new_connection_second);
1694 /* Register a timeout task that will be executed if the connector
1695 will not start the key exchange protocol within specified timeout
1696 and the connection will be closed. */
1697 proto_ctx->timeout_task =
1698 silc_schedule_task_add(server->schedule, sock->sock,
1699 silc_server_timeout_remote,
1701 server->config->key_exchange_timeout, 0,
1706 /* Accepts new connections to the server. Accepting new connections are
1707 done in three parts to make it async. */
1709 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1711 SilcServer server = (SilcServer)context;
1712 SilcSocketConnection newsocket;
1713 SilcServerKEInternalContext *proto_ctx;
1716 SILC_LOG_DEBUG(("Accepting new connection"));
1718 server->stat.conn_attempts++;
1720 sock = silc_net_accept_connection(fd);
1722 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1723 server->stat.conn_failures++;
1727 /* Check for maximum allowed connections */
1728 if (sock > server->config->param.connections_max) {
1729 SILC_LOG_ERROR(("Refusing connection, server is full"));
1730 server->stat.conn_failures++;
1731 silc_net_close_connection(sock);
1735 /* Set socket options */
1736 silc_net_set_socket_nonblock(sock);
1737 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1739 /* We don't create a ID yet, since we don't know what type of connection
1740 this is yet. But, we do add the connection to the socket table. */
1741 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1742 server->sockets[sock] = newsocket;
1744 /* Perform asynchronous host lookup. This will lookup the IP and the
1745 FQDN of the remote connection. After the lookup is done the connection
1746 is accepted further. */
1747 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1748 proto_ctx->server = server;
1749 proto_ctx->context = SILC_32_TO_PTR(fd);
1750 silc_socket_host_lookup(newsocket, TRUE,
1751 silc_server_accept_new_connection_lookup,
1752 (void *)proto_ctx, server->schedule);
1755 /* Second part of accepting new connection. Key exchange protocol has been
1756 performed and now it is time to do little connection authentication
1757 protocol to figure out whether this connection is client or server
1758 and whether it has right to access this server (especially server
1759 connections needs to be authenticated). */
1761 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1763 SilcProtocol protocol = (SilcProtocol)context;
1764 SilcServerKEInternalContext *ctx =
1765 (SilcServerKEInternalContext *)protocol->context;
1766 SilcServer server = (SilcServer)ctx->server;
1767 SilcSocketConnection sock = ctx->sock;
1768 SilcServerConnAuthInternalContext *proto_ctx;
1770 SILC_LOG_DEBUG(("Start"));
1772 if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1773 (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1774 /* Error occured during protocol */
1775 SILC_LOG_DEBUG(("Error in key exchange protocol"));
1776 silc_protocol_free(protocol);
1777 sock->protocol = NULL;
1778 silc_ske_free_key_material(ctx->keymat);
1780 silc_packet_context_free(ctx->packet);
1782 silc_ske_free(ctx->ske);
1783 silc_free(ctx->dest_id);
1784 silc_server_config_unref(&ctx->cconfig);
1785 silc_server_config_unref(&ctx->sconfig);
1786 silc_server_config_unref(&ctx->rconfig);
1789 if (!SILC_IS_DISCONNECTING(sock)) {
1790 SILC_LOG_INFO(("Key exchange failed for %s:%d [%s]", sock->hostname,
1792 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1793 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1794 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1796 silc_server_disconnect_remote(server, sock,
1797 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
1801 server->stat.auth_failures++;
1805 /* We now have the key material as the result of the key exchange
1806 protocol. Take the key material into use. Free the raw key material
1807 as soon as we've set them into use. */
1808 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1809 ctx->sock, ctx->keymat,
1810 ctx->ske->prop->cipher,
1811 ctx->ske->prop->pkcs,
1812 ctx->ske->prop->hash,
1813 ctx->ske->prop->hmac,
1814 ctx->ske->prop->group,
1816 SILC_LOG_ERROR(("Error setting key material in use"));
1817 silc_protocol_free(protocol);
1818 sock->protocol = NULL;
1819 silc_ske_free_key_material(ctx->keymat);
1821 silc_packet_context_free(ctx->packet);
1823 silc_ske_free(ctx->ske);
1824 silc_free(ctx->dest_id);
1825 silc_server_config_unref(&ctx->cconfig);
1826 silc_server_config_unref(&ctx->sconfig);
1827 silc_server_config_unref(&ctx->rconfig);
1829 silc_server_disconnect_remote(server, sock,
1830 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1831 server->stat.auth_failures++;
1834 silc_ske_free_key_material(ctx->keymat);
1836 /* Allocate internal context for the authentication protocol. This
1837 is sent as context for the protocol. */
1838 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1839 proto_ctx->server = (void *)server;
1840 proto_ctx->sock = sock;
1841 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1842 proto_ctx->responder = TRUE;
1843 proto_ctx->dest_id_type = ctx->dest_id_type;
1844 proto_ctx->dest_id = ctx->dest_id;
1845 proto_ctx->cconfig = ctx->cconfig;
1846 proto_ctx->sconfig = ctx->sconfig;
1847 proto_ctx->rconfig = ctx->rconfig;
1849 /* Free old protocol as it is finished now */
1850 silc_protocol_free(protocol);
1852 silc_packet_context_free(ctx->packet);
1854 sock->protocol = NULL;
1856 /* Allocate the authentication protocol. This is allocated here
1857 but we won't start it yet. We will be receiving party of this
1858 protocol thus we will wait that connecting party will make
1859 their first move. */
1860 SILC_LOG_DEBUG(("Starting connection authentication protocol"));
1861 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1862 &sock->protocol, proto_ctx,
1863 silc_server_accept_new_connection_final);
1865 /* Register timeout task. If the protocol is not executed inside
1866 this timelimit the connection will be terminated. */
1867 proto_ctx->timeout_task =
1868 silc_schedule_task_add(server->schedule, sock->sock,
1869 silc_server_timeout_remote,
1871 server->config->conn_auth_timeout, 0,
1876 /* After this is called, server don't wait for backup router anymore.
1877 This gets called automatically even after we have backup router
1878 connection established. */
1880 SILC_TASK_CALLBACK(silc_server_backup_router_wait)
1882 SilcServer server = context;
1883 server->wait_backup = FALSE;
1886 /* Final part of accepting new connection. The connection has now
1887 been authenticated and keys has been exchanged. We also know whether
1888 this is client or server connection. */
1890 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1892 SilcProtocol protocol = (SilcProtocol)context;
1893 SilcServerConnAuthInternalContext *ctx =
1894 (SilcServerConnAuthInternalContext *)protocol->context;
1895 SilcServer server = (SilcServer)ctx->server;
1896 SilcSocketConnection sock = ctx->sock;
1897 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1899 SilcServerConfigConnParams *param = &server->config->param;
1901 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1902 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1903 /* Error occured during protocol */
1904 SILC_LOG_DEBUG(("Error during authentication protocol"));
1905 silc_protocol_free(protocol);
1906 sock->protocol = NULL;
1908 silc_packet_context_free(ctx->packet);
1910 silc_ske_free(ctx->ske);
1911 silc_free(ctx->dest_id);
1912 silc_server_config_unref(&ctx->cconfig);
1913 silc_server_config_unref(&ctx->sconfig);
1914 silc_server_config_unref(&ctx->rconfig);
1917 if (!SILC_IS_DISCONNECTING(sock)) {
1918 SILC_LOG_INFO(("Authentication failed for %s:%d [%s]", sock->hostname,
1920 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1921 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1922 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1924 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1927 server->stat.auth_failures++;
1931 entry->data.last_receive = time(NULL);
1933 switch (ctx->conn_type) {
1934 case SILC_SOCKET_TYPE_CLIENT:
1936 SilcClientEntry client;
1937 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1939 /* Verify whether this connection is after all allowed to connect */
1940 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1941 &server->config->param,
1942 conn->param, ctx->ske)) {
1943 server->stat.auth_failures++;
1947 /* If we are primary router and we have backup router configured
1948 but it has not connected to use yet, do not accept any other
1950 if (server->wait_backup && server->server_type == SILC_ROUTER &&
1951 !server->backup_router) {
1952 SilcServerConfigRouter *router;
1953 router = silc_server_config_get_backup_router(server);
1954 if (router && strcmp(server->config->server_info->primary->server_ip,
1956 silc_server_find_socket_by_host(server,
1957 SILC_SOCKET_TYPE_SERVER,
1958 router->backup_replace_ip, 0)) {
1959 SILC_LOG_INFO(("Will not accept connections because we do "
1960 "not have backup router connection established"));
1961 sock->protocol = NULL;
1962 silc_server_disconnect_remote(server, sock,
1963 SILC_STATUS_ERR_PERM_DENIED,
1964 "We do not have connection to backup "
1965 "router established, try later");
1966 silc_free(sock->user_data);
1967 server->stat.auth_failures++;
1969 /* From here on, wait 20 seconds for the backup router to appear. */
1970 silc_schedule_task_add(server->schedule, 0,
1971 silc_server_backup_router_wait,
1972 (void *)server, 20, 0,
1973 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1978 SILC_LOG_DEBUG(("Remote host is client"));
1979 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1982 /* Add the client to the client ID cache. The nickname and Client ID
1983 and other information is created after we have received NEW_CLIENT
1984 packet from client. */
1985 client = silc_idlist_add_client(server->local_list,
1986 NULL, NULL, NULL, NULL, NULL, sock, 0);
1988 SILC_LOG_ERROR(("Could not add new client to cache"));
1989 silc_free(sock->user_data);
1990 sock->protocol = NULL;
1991 silc_server_disconnect_remote(server, sock,
1992 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1993 server->stat.auth_failures++;
1996 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
1999 server->stat.my_clients++;
2000 server->stat.clients++;
2001 server->stat.cell_clients++;
2003 /* Get connection parameters */
2005 param = conn->param;
2007 if (!param->keepalive_secs)
2008 param->keepalive_secs = server->config->param.keepalive_secs;
2010 if (!param->qos && server->config->param.qos) {
2011 param->qos = server->config->param.qos;
2012 param->qos_rate_limit = server->config->param.qos_rate_limit;
2013 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
2014 param->qos_limit_sec = server->config->param.qos_limit_sec;
2015 param->qos_limit_usec = server->config->param.qos_limit_usec;
2018 /* Check if to be anonymous connection */
2019 if (param->anonymous)
2020 client->mode |= SILC_UMODE_ANONYMOUS;
2023 /* Add public key to hash list (for whois using attributes) */
2024 silc_hash_table_add(server->pk_hash,
2025 entry->data.public_key, client);
2027 id_entry = (void *)client;
2030 case SILC_SOCKET_TYPE_SERVER:
2031 case SILC_SOCKET_TYPE_ROUTER:
2033 SilcServerEntry new_server;
2034 bool initiator = FALSE;
2035 bool backup_local = FALSE;
2036 bool backup_router = FALSE;
2037 char *backup_replace_ip = NULL;
2038 SilcUInt16 backup_replace_port = 0;
2039 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
2040 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
2042 /* If we are backup router and this is incoming server connection
2043 and we do not have connection to primary router, do not allow
2045 if (server->server_type == SILC_BACKUP_ROUTER &&
2046 ctx->conn_type == SILC_SOCKET_TYPE_SERVER &&
2047 !SILC_PRIMARY_ROUTE(server)) {
2048 SILC_LOG_INFO(("Will not accept server connection because we do "
2049 "not have primary router connection established"));
2050 sock->protocol = NULL;
2051 silc_server_disconnect_remote(server, sock,
2052 SILC_STATUS_ERR_PERM_DENIED,
2053 "We do not have connection to primary "
2054 "router established, try later");
2055 silc_free(sock->user_data);
2056 server->stat.auth_failures++;
2060 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
2061 /* Verify whether this connection is after all allowed to connect */
2062 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
2063 &server->config->param,
2064 rconn ? rconn->param : NULL,
2066 silc_free(sock->user_data);
2067 server->stat.auth_failures++;
2073 param = rconn->param;
2075 if (!param->keepalive_secs)
2076 param->keepalive_secs = server->config->param.keepalive_secs;
2078 if (!param->qos && server->config->param.qos) {
2079 param->qos = server->config->param.qos;
2080 param->qos_rate_limit = server->config->param.qos_rate_limit;
2081 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
2082 param->qos_limit_sec = server->config->param.qos_limit_sec;
2083 param->qos_limit_usec = server->config->param.qos_limit_usec;
2087 initiator = rconn->initiator;
2088 backup_local = rconn->backup_local;
2089 backup_router = rconn->backup_router;
2090 backup_replace_ip = rconn->backup_replace_ip;
2091 backup_replace_port = rconn->backup_replace_port;
2095 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
2096 /* Verify whether this connection is after all allowed to connect */
2097 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
2098 &server->config->param,
2099 sconn ? sconn->param : NULL,
2101 silc_free(sock->user_data);
2102 server->stat.auth_failures++;
2107 param = sconn->param;
2109 if (!param->keepalive_secs)
2110 param->keepalive_secs = server->config->param.keepalive_secs;
2112 if (!param->qos && server->config->param.qos) {
2113 param->qos = server->config->param.qos;
2114 param->qos_rate_limit = server->config->param.qos_rate_limit;
2115 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
2116 param->qos_limit_sec = server->config->param.qos_limit_sec;
2117 param->qos_limit_usec = server->config->param.qos_limit_usec;
2121 backup_router = sconn->backup_router;
2125 /* If we are primary router and we have backup router configured
2126 but it has not connected to use yet, do not accept any other
2128 if (server->wait_backup && server->server_type == SILC_ROUTER &&
2129 !server->backup_router && !backup_router) {
2130 SilcServerConfigRouter *router;
2131 router = silc_server_config_get_backup_router(server);
2132 if (router && strcmp(server->config->server_info->primary->server_ip,
2134 silc_server_find_socket_by_host(server,
2135 SILC_SOCKET_TYPE_SERVER,
2136 router->backup_replace_ip, 0)) {
2137 SILC_LOG_INFO(("Will not accept connections because we do "
2138 "not have backup router connection established"));
2139 sock->protocol = NULL;
2140 silc_server_disconnect_remote(server, sock,
2141 SILC_STATUS_ERR_PERM_DENIED,
2142 "We do not have connection to backup "
2143 "router established, try later");
2144 silc_free(sock->user_data);
2145 server->stat.auth_failures++;
2147 /* From here on, wait 20 seconds for the backup router to appear. */
2148 silc_schedule_task_add(server->schedule, 0,
2149 silc_server_backup_router_wait,
2150 (void *)server, 20, 0,
2151 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2156 SILC_LOG_DEBUG(("Remote host is %s",
2157 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2158 "server" : (backup_router ?
2159 "backup router" : "router")));
2160 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
2161 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2162 "server" : (backup_router ?
2163 "backup router" : "router")));
2165 /* Add the server into server cache. The server name and Server ID
2166 is updated after we have received NEW_SERVER packet from the
2167 server. We mark ourselves as router for this server if we really
2170 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2171 server->local_list : (backup_router ?
2172 server->local_list :
2173 server->global_list)),
2175 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2176 SILC_SERVER : SILC_ROUTER),
2178 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2179 server->id_entry : (backup_router ?
2180 server->id_entry : NULL)),
2183 SILC_LOG_ERROR(("Could not add new server to cache"));
2184 silc_free(sock->user_data);
2185 sock->protocol = NULL;
2186 silc_server_disconnect_remote(server, sock,
2187 SILC_STATUS_ERR_AUTH_FAILED, NULL);
2188 server->stat.auth_failures++;
2191 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
2193 id_entry = (void *)new_server;
2195 /* If the incoming connection is router and marked as backup router
2196 then add it to be one of our backups */
2197 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
2198 /* Change it back to SERVER type since that's what it really is. */
2200 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
2201 new_server->server_type = SILC_BACKUP_ROUTER;
2203 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
2204 ("Backup router %s is now online",
2207 /* Remove the backup waiting with timeout */
2208 silc_schedule_task_add(server->schedule, 0,
2209 silc_server_backup_router_wait,
2210 (void *)server, 10, 0,
2211 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2215 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
2216 server->stat.my_servers++;
2218 server->stat.my_routers++;
2219 server->stat.routers++;
2221 server->stat.servers++;
2223 /* Check whether this connection is to be our primary router connection
2224 if we do not already have the primary route. */
2225 if (!backup_router &&
2226 server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
2227 if (silc_server_config_is_primary_route(server) && !initiator)
2230 SILC_LOG_DEBUG(("We are not standalone server anymore"));
2231 server->standalone = FALSE;
2232 if (!server->id_entry->router) {
2233 server->id_entry->router = id_entry;
2234 server->router = id_entry;
2245 sock->type = ctx->conn_type;
2247 /* Add the common data structure to the ID entry. */
2248 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
2250 /* Add to sockets internal pointer for fast referencing */
2251 silc_free(sock->user_data);
2252 sock->user_data = id_entry;
2254 /* Connection has been fully established now. Everything is ok. */
2255 SILC_LOG_DEBUG(("New connection authenticated"));
2257 /* Perform keepalive. */
2258 if (param->keepalive_secs)
2259 silc_socket_set_heartbeat(sock, param->keepalive_secs, server,
2260 silc_server_perform_heartbeat,
2263 /* Perform Quality of Service */
2265 silc_socket_set_qos(sock, param->qos_rate_limit, param->qos_bytes_limit,
2266 param->qos_limit_sec, param->qos_limit_usec,
2270 if (sock->protocol == protocol)
2271 silc_protocol_free(protocol);
2273 silc_packet_context_free(ctx->packet);
2275 silc_ske_free(ctx->ske);
2276 silc_free(ctx->dest_id);
2277 silc_server_config_unref(&ctx->cconfig);
2278 silc_server_config_unref(&ctx->sconfig);
2279 silc_server_config_unref(&ctx->rconfig);
2281 sock->protocol = NULL;
2284 /* This function is used to read packets from network and send packets to
2285 network. This is usually a generic task. */
2287 SILC_TASK_CALLBACK(silc_server_packet_process)
2289 SilcServer server = (SilcServer)context;
2290 SilcSocketConnection sock = server->sockets[fd];
2291 SilcIDListData idata;
2292 SilcCipher cipher = NULL;
2293 SilcHmac hmac = NULL;
2294 SilcUInt32 sequence = 0;
2295 bool local_is_router;
2299 SILC_LOG_DEBUG(("Unknown socket connection"));
2303 /* Packet sending */
2305 if (type == SILC_TASK_WRITE) {
2306 /* Do not send data to disconnected connection */
2307 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2308 SILC_LOG_DEBUG(("Disconnected socket connection, cannot send"));
2309 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
2310 SILC_UNSET_OUTBUF_PENDING(sock);
2311 silc_buffer_clear(sock->outbuf);
2315 server->stat.packets_sent++;
2317 /* Send the packet */
2318 ret = silc_packet_send(sock, TRUE);
2320 /* If returned -2 could not write to connection now, will do
2325 /* The packet has been sent and now it is time to set the connection
2326 back to only for input. When there is again some outgoing data
2327 available for this connection it will be set for output as well.
2328 This call clears the output setting and sets it only for input. */
2329 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
2330 SILC_UNSET_OUTBUF_PENDING(sock);
2331 silc_buffer_clear(sock->outbuf);
2334 SILC_LOG_ERROR(("Error sending packet to connection "
2335 "%s:%d [%s]", sock->hostname, sock->port,
2336 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2337 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2338 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2341 if (sock->user_data) {
2342 /* If backup then mark that resuming will not be allowed */
2343 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2344 sock->type == SILC_SOCKET_TYPE_SERVER) {
2345 SilcServerEntry server_entry = sock->user_data;
2346 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2347 server->backup_closed = TRUE;
2350 silc_server_free_sock_user_data(server, sock, NULL);
2352 SILC_SET_DISCONNECTING(sock);
2353 silc_server_close_connection(server, sock);
2358 /* Packet receiving */
2360 /* Read some data from connection */
2361 ret = silc_packet_receive(sock);
2365 SILC_LOG_ERROR(("Error receiving packet from connection "
2366 "%s:%d [%s] %s", sock->hostname, sock->port,
2367 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2368 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2369 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2370 "Router"), strerror(errno)));
2372 if (sock->user_data) {
2373 /* If backup then mark that resuming will not be allowed */
2374 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2375 sock->type == SILC_SOCKET_TYPE_SERVER) {
2376 SilcServerEntry server_entry = sock->user_data;
2377 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2378 server->backup_closed = TRUE;
2381 silc_server_free_sock_user_data(server, sock, NULL);
2383 SILC_SET_DISCONNECTING(sock);
2384 silc_server_close_connection(server, sock);
2391 SILC_LOG_DEBUG(("Read EOF"));
2393 /* If connection is disconnecting already we will finally
2394 close the connection */
2395 if (SILC_IS_DISCONNECTING(sock)) {
2396 if (sock->user_data)
2397 silc_server_free_sock_user_data(server, sock, NULL);
2398 silc_server_close_connection(server, sock);
2402 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
2404 if (sock->user_data) {
2407 /* If backup disconnected then mark that resuming will not be allowed */
2408 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2409 sock->type == SILC_SOCKET_TYPE_SERVER && sock->user_data) {
2410 SilcServerEntry server_entry = sock->user_data;
2411 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2412 server->backup_closed = TRUE;
2415 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
2416 silc_server_free_sock_user_data(server, sock, tmp);
2418 silc_server_free_sock_user_data(server, sock, NULL);
2419 } else if (server->router_conn && server->router_conn->sock == sock &&
2420 !server->router && server->standalone) {
2421 silc_server_create_connections(server);
2424 SILC_SET_DISCONNECTING(sock);
2425 silc_server_close_connection(server, sock);
2429 /* If connection is disconnecting or disconnected we will ignore
2431 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2432 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
2436 /* Get keys and stuff from ID entry */
2437 idata = (SilcIDListData)sock->user_data;
2439 cipher = idata->receive_key;
2440 hmac = idata->hmac_receive;
2441 sequence = idata->psn_receive;
2444 /* Then, process the packet. This will call the parser that will then
2445 decrypt and parse the packet. */
2447 local_is_router = (server->server_type == SILC_ROUTER);
2449 /* If socket connection is our primary, we are backup and we are doing
2450 backup resuming, we won't process the packet as being a router
2451 (affects channel message decryption). */
2452 if (server->backup_router && SILC_SERVER_IS_BACKUP(sock) &&
2453 SILC_PRIMARY_ROUTE(server) == sock)
2454 local_is_router = FALSE;
2456 ret = silc_packet_receive_process(sock, local_is_router,
2457 cipher, hmac, sequence,
2458 silc_server_packet_parse, server);
2460 /* If processing failed the connection is closed. */
2462 /* On packet processing errors we may close our primary router
2463 connection but won't become primary router if we are the backup
2464 since this is local error condition. */
2465 if (SILC_PRIMARY_ROUTE(server) == sock && server->backup_router)
2466 server->backup_noswitch = TRUE;
2468 if (sock->user_data) {
2469 /* If we are router and backup errorred then mark that resuming
2470 will not be allowed */
2471 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2472 sock->type == SILC_SOCKET_TYPE_SERVER) {
2473 SilcServerEntry server_entry = sock->user_data;
2474 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2475 server->backup_closed = TRUE;
2478 silc_server_free_sock_user_data(server, sock, NULL);
2480 SILC_SET_DISCONNECTING(sock);
2481 silc_server_close_connection(server, sock);
2485 /* Parses whole packet, received earlier. */
2487 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
2489 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
2490 SilcServer server = (SilcServer)parse_ctx->context;
2491 SilcSocketConnection sock = parse_ctx->sock;
2492 SilcPacketContext *packet = parse_ctx->packet;
2493 SilcIDListData idata = (SilcIDListData)sock->user_data;
2496 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2497 SILC_LOG_DEBUG(("Connection is disconnected"));
2501 server->stat.packets_received++;
2503 /* Parse the packet */
2504 if (parse_ctx->normal)
2505 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
2507 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
2509 /* If entry is disabled ignore what we got. */
2510 if (idata && idata->status & SILC_IDLIST_STATUS_DISABLED &&
2511 ret != SILC_PACKET_HEARTBEAT && ret != SILC_PACKET_RESUME_ROUTER &&
2512 ret != SILC_PACKET_REKEY && ret != SILC_PACKET_REKEY_DONE &&
2513 ret != SILC_PACKET_KEY_EXCHANGE_1 && ret != SILC_PACKET_KEY_EXCHANGE_2) {
2514 SILC_LOG_DEBUG(("Connection is disabled (packet %s dropped)",
2515 silc_get_packet_name(ret)));
2519 if (ret == SILC_PACKET_NONE) {
2520 SILC_LOG_DEBUG(("Error parsing packet"));
2524 /* Check that the the current client ID is same as in the client's packet. */
2525 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
2526 SilcClientEntry client = (SilcClientEntry)sock->user_data;
2527 if (client && client->id && packet->src_id) {
2528 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
2529 packet->src_id_type);
2530 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
2532 SILC_LOG_DEBUG(("Packet source is not same as sender"));
2539 if (server->server_type == SILC_ROUTER) {
2540 /* Route the packet if it is not destined to us. Other ID types but
2541 server are handled separately after processing them. */
2542 if (packet->dst_id && !(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
2543 packet->dst_id_type == SILC_ID_SERVER &&
2544 sock->type != SILC_SOCKET_TYPE_CLIENT &&
2545 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
2547 /* Route the packet to fastest route for the destination ID */
2548 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
2549 packet->dst_id_type);
2552 silc_server_packet_route(server,
2553 silc_server_route_get(server, id,
2554 packet->dst_id_type),
2561 /* Parse the incoming packet type */
2562 silc_server_packet_parse_type(server, sock, packet);
2564 /* Broadcast packet if it is marked as broadcast packet and it is
2565 originated from router and we are router. */
2566 if (server->server_type == SILC_ROUTER &&
2567 sock->type == SILC_SOCKET_TYPE_ROUTER &&
2568 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
2569 /* Broadcast to our primary route */
2570 silc_server_packet_broadcast(server, SILC_PRIMARY_ROUTE(server), packet);
2572 /* If we have backup routers then we need to feed all broadcast
2573 data to those servers. */
2574 silc_server_backup_broadcast(server, sock, packet);
2578 silc_packet_context_free(packet);
2579 silc_free(parse_ctx);
2582 /* Parser callback called by silc_packet_receive_process. This merely
2583 registers timeout that will handle the actual parsing when appropriate. */
2585 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
2588 SilcServer server = (SilcServer)context;
2589 SilcSocketConnection sock = parser_context->sock;
2590 SilcIDListData idata = (SilcIDListData)sock->user_data;
2594 idata->psn_receive = parser_context->packet->sequence + 1;
2596 /* If protocol for this connection is key exchange or rekey then we'll
2597 process all packets synchronously, since there might be packets in
2598 queue that we are not able to decrypt without first processing the
2599 packets before them. */
2600 if (sock->protocol && sock->protocol->protocol &&
2601 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2602 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2603 silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2606 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2607 SILC_LOG_DEBUG(("Connection is disconnected"));
2611 /* Reprocess data since we'll return FALSE here. This is because
2612 the idata->receive_key might have become valid in the last packet
2613 and we want to call this processor with valid cipher. */
2615 ret = silc_packet_receive_process(
2616 sock, server->server_type == SILC_ROUTER,
2618 idata->hmac_receive, idata->psn_receive,
2619 silc_server_packet_parse, server);
2621 ret = silc_packet_receive_process(
2622 sock, server->server_type == SILC_ROUTER,
2624 silc_server_packet_parse, server);
2627 /* On packet processing errors we may close our primary router
2628 connection but won't become primary router if we are the backup
2629 since this is local error condition. */
2630 if (SILC_PRIMARY_ROUTE(server) == sock && server->backup_router)
2631 server->backup_noswitch = TRUE;
2633 if (sock->user_data)
2634 silc_server_free_sock_user_data(server, sock, NULL);
2635 SILC_SET_DISCONNECTING(sock);
2636 silc_server_close_connection(server, sock);
2642 switch (sock->type) {
2643 case SILC_SOCKET_TYPE_UNKNOWN:
2644 case SILC_SOCKET_TYPE_CLIENT:
2645 /* Parse the packet with timeout */
2646 silc_schedule_task_add(server->schedule, sock->sock,
2647 silc_server_packet_parse_real,
2648 (void *)parser_context, 0, 100000,
2650 SILC_TASK_PRI_NORMAL);
2652 case SILC_SOCKET_TYPE_SERVER:
2653 case SILC_SOCKET_TYPE_ROUTER:
2654 /* Packets from servers are parsed immediately */
2655 silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2663 /* Parses the packet type and calls what ever routines the packet type
2664 requires. This is done for all incoming packets. */
2666 void silc_server_packet_parse_type(SilcServer server,
2667 SilcSocketConnection sock,
2668 SilcPacketContext *packet)
2670 SilcPacketType type = packet->type;
2671 SilcIDListData idata = (SilcIDListData)sock->user_data;
2673 SILC_LOG_DEBUG(("Received %s packet [flags %d]",
2674 silc_get_packet_name(type), packet->flags));
2676 /* Parse the packet type */
2678 case SILC_PACKET_DISCONNECT:
2681 char *message = NULL;
2683 if (packet->flags & SILC_PACKET_FLAG_LIST)
2685 if (packet->buffer->len < 1)
2688 status = (SilcStatus)packet->buffer->data[0];
2689 if (packet->buffer->len > 1 &&
2690 silc_utf8_valid(packet->buffer->data + 1, packet->buffer->len - 1))
2691 message = silc_memdup(packet->buffer->data + 1,
2692 packet->buffer->len - 1);
2694 SILC_LOG_INFO(("Disconnected by %s (%s): %s (%d) %s",
2695 sock->ip, sock->hostname,
2696 silc_get_status_message(status), status,
2697 message ? message : ""));
2700 /* Do not switch to backup in case of error */
2701 server->backup_noswitch = (status == SILC_STATUS_OK ? FALSE : TRUE);
2703 /* If backup disconnected then mark that resuming will not be allowed */
2704 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2705 sock->type == SILC_SOCKET_TYPE_SERVER && sock->user_data) {
2706 SilcServerEntry server_entry = sock->user_data;
2707 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2708 server->backup_closed = TRUE;
2711 /* Handle the disconnection from our end too */
2712 if (sock->user_data && SILC_IS_LOCAL(sock->user_data))
2713 silc_server_free_sock_user_data(server, sock, NULL);
2714 SILC_SET_DISCONNECTING(sock);
2715 silc_server_close_connection(server, sock);
2716 server->backup_noswitch = FALSE;
2720 case SILC_PACKET_SUCCESS:
2722 * Success received for something. For now we can have only
2723 * one protocol for connection executing at once hence this
2724 * success message is for whatever protocol is executing currently.
2726 if (packet->flags & SILC_PACKET_FLAG_LIST)
2729 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2732 case SILC_PACKET_FAILURE:
2734 * Failure received for something. For now we can have only
2735 * one protocol for connection executing at once hence this
2736 * failure message is for whatever protocol is executing currently.
2738 if (packet->flags & SILC_PACKET_FLAG_LIST)
2741 /* Check for failure START_USE from backup router */
2742 if (server->server_type == SILC_SERVER &&
2743 server->backup_primary && packet->buffer->len == 4) {
2745 SILC_GET32_MSB(type, packet->buffer->data);
2746 if (type == SILC_SERVER_BACKUP_START_USE) {
2747 /* Attempt to reconnect to primary */
2748 SILC_LOG_DEBUG(("Received failed START_USE from backup %s", sock->ip));
2750 /* Default action is to disconnect from backup and reconnect to
2751 primary. Since this failure can happen during switching to
2752 backup (backup might have not noticed the primary going down yet),
2753 we will wait a while and keep sending START_USE to backup.
2754 Only after that we'll give up. */
2755 if (server->router == sock->user_data &&
2756 (time(0) - server->router_connect) < 30) {
2757 SILC_LOG_DEBUG(("Resending START_USE to backup router"));
2758 silc_server_backup_send_start_use(server, sock, FALSE);
2762 /* If backup is our primary, disconnect now. */
2763 if (server->router == sock->user_data) {
2764 if (sock->user_data)
2765 silc_server_free_sock_user_data(server, sock, NULL);
2766 SILC_SET_DISCONNECTING(sock);
2767 silc_server_close_connection(server, sock);
2771 silc_server_create_connections(server);
2775 /* Execute protocol */
2776 if (sock->protocol) {
2777 sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
2778 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2783 case SILC_PACKET_REJECT:
2784 if (packet->flags & SILC_PACKET_FLAG_LIST)
2789 case SILC_PACKET_NOTIFY:
2791 * Received notify packet. Server can receive notify packets from
2792 * router. Server then relays the notify messages to clients if needed.
2794 if (packet->flags & SILC_PACKET_FLAG_LIST)
2795 silc_server_notify_list(server, sock, packet);
2797 silc_server_notify(server, sock, packet);
2803 case SILC_PACKET_CHANNEL_MESSAGE:
2805 * Received channel message. Channel messages are special packets
2806 * (although probably most common ones) thus they are handled
2809 if (packet->flags & SILC_PACKET_FLAG_LIST)
2811 idata->last_receive = time(NULL);
2812 silc_server_channel_message(server, sock, packet);
2815 case SILC_PACKET_CHANNEL_KEY:
2817 * Received key for channel. As channels are created by the router
2818 * the keys are as well. We will distribute the key to all of our
2819 * locally connected clients on the particular channel. Router
2820 * never receives this channel and thus is ignored.
2822 if (packet->flags & SILC_PACKET_FLAG_LIST)
2824 silc_server_channel_key(server, sock, packet);
2830 case SILC_PACKET_COMMAND:
2832 * Recived command. Processes the command request and allocates the
2833 * command context and calls the command.
2835 if (packet->flags & SILC_PACKET_FLAG_LIST)
2837 silc_server_command_process(server, sock, packet);
2840 case SILC_PACKET_COMMAND_REPLY:
2842 * Received command reply packet. Received command reply to command. It
2843 * may be reply to command sent by us or reply to command sent by client
2844 * that we've routed further.
2846 if (packet->flags & SILC_PACKET_FLAG_LIST)
2848 silc_server_command_reply(server, sock, packet);
2852 * Private Message packets
2854 case SILC_PACKET_PRIVATE_MESSAGE:
2856 * Received private message packet. The packet is coming from either
2859 if (packet->flags & SILC_PACKET_FLAG_LIST)
2861 idata->last_receive = time(NULL);
2862 silc_server_private_message(server, sock, packet);
2865 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2867 * Private message key packet.
2869 if (packet->flags & SILC_PACKET_FLAG_LIST)
2871 silc_server_private_message_key(server, sock, packet);
2875 * Key Exchange protocol packets
2877 case SILC_PACKET_KEY_EXCHANGE:
2878 if (packet->flags & SILC_PACKET_FLAG_LIST)
2881 if (sock->protocol && sock->protocol->protocol &&
2882 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2883 SilcServerKEInternalContext *proto_ctx =
2884 (SilcServerKEInternalContext *)sock->protocol->context;
2886 proto_ctx->packet = silc_packet_context_dup(packet);
2888 /* Let the protocol handle the packet */
2889 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2891 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2892 "protocol active (%s:%d [%s]).", sock->hostname,
2894 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2895 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2896 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2901 case SILC_PACKET_KEY_EXCHANGE_1:
2902 if (packet->flags & SILC_PACKET_FLAG_LIST)
2905 if (sock->protocol && sock->protocol->protocol &&
2906 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2907 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2909 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2910 SilcServerRekeyInternalContext *proto_ctx =
2911 (SilcServerRekeyInternalContext *)sock->protocol->context;
2913 if (proto_ctx->packet)
2914 silc_packet_context_free(proto_ctx->packet);
2916 proto_ctx->packet = silc_packet_context_dup(packet);
2918 /* Let the protocol handle the packet */
2919 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2921 SilcServerKEInternalContext *proto_ctx =
2922 (SilcServerKEInternalContext *)sock->protocol->context;
2924 if (proto_ctx->packet)
2925 silc_packet_context_free(proto_ctx->packet);
2927 proto_ctx->packet = silc_packet_context_dup(packet);
2928 proto_ctx->dest_id_type = packet->src_id_type;
2929 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2930 packet->src_id_type);
2931 if (!proto_ctx->dest_id)
2934 /* Let the protocol handle the packet */
2935 silc_protocol_execute(sock->protocol, server->schedule,
2939 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2940 "protocol active (%s:%d [%s]).", sock->hostname,
2942 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2943 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2944 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2949 case SILC_PACKET_KEY_EXCHANGE_2:
2950 if (packet->flags & SILC_PACKET_FLAG_LIST)
2953 if (sock->protocol && sock->protocol->protocol &&
2954 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2955 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2957 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2958 SilcServerRekeyInternalContext *proto_ctx =
2959 (SilcServerRekeyInternalContext *)sock->protocol->context;
2961 if (proto_ctx->packet)
2962 silc_packet_context_free(proto_ctx->packet);
2964 proto_ctx->packet = silc_packet_context_dup(packet);
2966 /* Let the protocol handle the packet */
2967 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2969 SilcServerKEInternalContext *proto_ctx =
2970 (SilcServerKEInternalContext *)sock->protocol->context;
2972 if (proto_ctx->packet)
2973 silc_packet_context_free(proto_ctx->packet);
2975 proto_ctx->packet = silc_packet_context_dup(packet);
2976 proto_ctx->dest_id_type = packet->src_id_type;
2977 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2978 packet->src_id_type);
2979 if (!proto_ctx->dest_id)
2982 /* Let the protocol handle the packet */
2983 silc_protocol_execute(sock->protocol, server->schedule,
2987 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2988 "protocol active (%s:%d [%s]).", sock->hostname,
2990 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2991 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2992 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2997 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2999 * Connection authentication request packet. When we receive this packet
3000 * we will send to the other end information about our mandatory
3001 * authentication method for the connection. This packet maybe received
3004 if (packet->flags & SILC_PACKET_FLAG_LIST)
3006 silc_server_connection_auth_request(server, sock, packet);
3010 * Connection Authentication protocol packets
3012 case SILC_PACKET_CONNECTION_AUTH:
3013 /* Start of the authentication protocol. We receive here the
3014 authentication data and will verify it. */
3015 if (packet->flags & SILC_PACKET_FLAG_LIST)
3018 if (sock->protocol && sock->protocol->protocol->type
3019 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
3021 SilcServerConnAuthInternalContext *proto_ctx =
3022 (SilcServerConnAuthInternalContext *)sock->protocol->context;
3024 proto_ctx->packet = silc_packet_context_dup(packet);
3026 /* Let the protocol handle the packet */
3027 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
3029 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
3030 "protocol active (%s:%d [%s]).", sock->hostname,
3032 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
3033 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
3034 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
3039 case SILC_PACKET_NEW_ID:
3041 * Received New ID packet. This includes some new ID that has been
3042 * created. It may be for client, server or channel. This is the way
3043 * to distribute information about new registered entities in the
3046 if (packet->flags & SILC_PACKET_FLAG_LIST)
3047 silc_server_new_id_list(server, sock, packet);
3049 silc_server_new_id(server, sock, packet);
3052 case SILC_PACKET_NEW_CLIENT:
3054 * Received new client packet. This includes client information that
3055 * we will use to create initial client ID. After creating new
3056 * ID we will send it to the client.
3058 if (packet->flags & SILC_PACKET_FLAG_LIST)
3060 silc_server_new_client(server, sock, packet);
3063 case SILC_PACKET_NEW_SERVER:
3065 * Received new server packet. This includes Server ID and some other
3066 * information that we may save. This is received after server has
3069 if (packet->flags & SILC_PACKET_FLAG_LIST)
3071 silc_server_new_server(server, sock, packet);
3074 case SILC_PACKET_NEW_CHANNEL:
3076 * Received new channel packet. Information about new channel in the
3077 * network are distributed using this packet.
3079 if (packet->flags & SILC_PACKET_FLAG_LIST)
3080 silc_server_new_channel_list(server, sock, packet);
3082 silc_server_new_channel(server, sock, packet);
3085 case SILC_PACKET_HEARTBEAT:
3087 * Received heartbeat.
3089 if (packet->flags & SILC_PACKET_FLAG_LIST)
3093 case SILC_PACKET_KEY_AGREEMENT:
3095 * Received heartbeat.
3097 if (packet->flags & SILC_PACKET_FLAG_LIST)
3099 silc_server_key_agreement(server, sock, packet);
3102 case SILC_PACKET_REKEY:
3104 * Received re-key packet. The sender wants to regenerate the session
3107 if (packet->flags & SILC_PACKET_FLAG_LIST)
3109 silc_server_rekey(server, sock, packet);
3112 case SILC_PACKET_REKEY_DONE:
3114 * The re-key is done.
3116 if (packet->flags & SILC_PACKET_FLAG_LIST)
3119 if (sock->protocol && sock->protocol->protocol &&
3120 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
3122 SilcServerRekeyInternalContext *proto_ctx =
3123 (SilcServerRekeyInternalContext *)sock->protocol->context;
3125 if (proto_ctx->packet)
3126 silc_packet_context_free(proto_ctx->packet);
3128 proto_ctx->packet = silc_packet_context_dup(packet);
3130 /* Let the protocol handle the packet */
3131 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
3133 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
3134 "protocol active (%s:%d [%s]).", sock->hostname,
3136 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
3137 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
3138 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
3143 case SILC_PACKET_FTP:
3145 if (packet->flags & SILC_PACKET_FLAG_LIST)
3147 silc_server_ftp(server, sock, packet);
3150 case SILC_PACKET_RESUME_CLIENT:
3152 if (packet->flags & SILC_PACKET_FLAG_LIST)
3154 silc_server_resume_client(server, sock, packet);
3157 case SILC_PACKET_RESUME_ROUTER:
3158 /* Resume router packet received. This packet is received for backup
3159 router resuming protocol. */
3160 if (packet->flags & SILC_PACKET_FLAG_LIST)
3162 silc_server_backup_resume_router(server, sock, packet);
3166 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
3171 /* Creates connection to a remote router. */
3173 void silc_server_create_connection(SilcServer server,
3174 const char *remote_host, SilcUInt32 port)
3176 SilcServerConnection sconn;
3178 /* Allocate connection object for hold connection specific stuff. */
3179 sconn = silc_calloc(1, sizeof(*sconn));
3180 sconn->remote_host = strdup(remote_host);
3181 sconn->remote_port = port;
3182 sconn->no_reconnect = TRUE;
3184 silc_schedule_task_add(server->schedule, 0,
3185 silc_server_connect_router,
3186 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
3187 SILC_TASK_PRI_NORMAL);
3190 SILC_TASK_CALLBACK(silc_server_close_connection_final)
3192 SilcServer server = app_context;
3193 SilcSocketConnection sock = context;
3195 SILC_LOG_DEBUG(("Deleting socket %p", sock));
3197 /* Close the actual connection */
3198 silc_net_close_connection(sock->sock);
3199 server->sockets[sock->sock] = NULL;
3201 /* We won't listen for this connection anymore */
3202 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
3203 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
3205 silc_socket_free(sock);
3208 /* Closes connection to socket connection */
3210 void silc_server_close_connection(SilcServer server,
3211 SilcSocketConnection sock)
3215 if (SILC_IS_DISCONNECTED(sock)) {
3216 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
3217 silc_schedule_task_add(server->schedule, sock->sock,
3218 silc_server_close_connection_final,
3219 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
3220 SILC_TASK_PRI_NORMAL);
3221 server->sockets[sock->sock] = NULL;
3225 /* If any protocol is active cancel its execution. It will call
3226 the final callback which will finalize the disconnection. */
3227 if (sock->protocol && sock->protocol->protocol &&
3228 sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3229 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3230 silc_protocol_cancel(sock->protocol, server->schedule);
3231 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3232 silc_protocol_execute_final(sock->protocol, server->schedule);
3233 sock->protocol = NULL;
3237 memset(tmp, 0, sizeof(tmp));
3238 silc_socket_get_error(sock, tmp, sizeof(tmp));
3239 SILC_LOG_INFO(("Closing connection %s:%d [%s] %s", sock->hostname,
3241 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
3242 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
3243 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
3244 "Router"), tmp[0] ? tmp : ""));
3246 SILC_SET_DISCONNECTED(sock);
3247 silc_socket_set_qos(sock, 0, 0, 0, 0, NULL);
3248 silc_schedule_task_add(server->schedule, sock->sock,
3249 silc_server_close_connection_final,
3250 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
3251 SILC_TASK_PRI_NORMAL);
3252 server->sockets[sock->sock] = NULL;
3255 /* Sends disconnect message to remote connection and disconnects the
3256 connection. NOTE: If this is called from protocol callback
3257 then sock->protocol must be set NULL before calling this, since
3258 this routine dispatches protocol callbacks too. */
3260 void silc_server_disconnect_remote(SilcServer server,
3261 SilcSocketConnection sock,
3262 SilcStatus status, ...)
3265 unsigned char buf[512];
3273 if (SILC_IS_DISCONNECTING(sock)) {
3274 SILC_SET_DISCONNECTED(sock);
3275 silc_server_close_connection(server, sock);
3279 memset(buf, 0, sizeof(buf));
3280 va_start(ap, status);
3281 cp = va_arg(ap, char *);
3283 vsnprintf(buf, sizeof(buf) - 1, cp, ap);
3288 SILC_LOG_DEBUG(("Disconnecting remote host"));
3290 /* Notify remote end that the conversation is over. The notify message
3291 is tried to be sent immediately. */
3295 len += silc_utf8_encoded_len(buf, strlen(buf), SILC_STRING_ASCII);
3297 buffer = silc_buffer_alloc_size(len);
3301 buffer->data[0] = status;
3303 silc_utf8_encode(buf, strlen(buf), SILC_STRING_ASCII, buffer->data + 1,
3305 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
3306 buffer->data, buffer->len, TRUE);
3307 silc_buffer_free(buffer);
3310 silc_server_packet_queue_purge(server, sock);
3312 /* Mark the connection to be disconnected */
3313 SILC_SET_DISCONNECTING(sock);
3314 silc_server_close_connection(server, sock);
3317 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
3319 SilcServer server = app_context;
3320 SilcClientEntry client = context;
3322 assert(!silc_hash_table_count(client->channels));
3324 silc_idlist_del_data(client);
3325 silc_idcache_purge_by_context(server->local_list->clients, client);
3328 /* Frees client data and notifies about client's signoff. */
3330 void silc_server_free_client_data(SilcServer server,
3331 SilcSocketConnection sock,
3332 SilcClientEntry client,
3334 const char *signoff)
3336 SILC_LOG_DEBUG(("Freeing client data"));
3338 /* If there is pending outgoing data for the client then purge it
3339 to the network before removing the client entry. */
3340 silc_server_packet_queue_purge(server, sock);
3343 /* Check if anyone is watching this nickname */
3344 if (server->server_type == SILC_ROUTER)
3345 silc_server_check_watcher_list(server, client, NULL,
3346 SILC_NOTIFY_TYPE_SIGNOFF);
3348 /* Send SIGNOFF notify to routers. */
3350 silc_server_send_notify_signoff(server, SILC_PRIMARY_ROUTE(server),
3351 SILC_BROADCAST(server), client->id,
3355 /* Remove client from all channels */
3357 silc_server_remove_from_channels(server, NULL, client,
3358 TRUE, (char *)signoff, TRUE, FALSE);
3360 silc_server_remove_from_channels(server, NULL, client,
3361 FALSE, NULL, FALSE, FALSE);
3363 /* Remove this client from watcher list if it is */
3364 silc_server_del_from_watcher_list(server, client);
3366 /* Remove this client from the public key hash list */
3367 if (client->data.public_key)
3368 silc_hash_table_del_by_context(server->pk_hash,
3369 client->data.public_key, client);
3371 /* Update statistics */
3372 server->stat.my_clients--;
3373 server->stat.clients--;
3374 if (server->stat.cell_clients)
3375 server->stat.cell_clients--;
3376 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
3377 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
3378 silc_schedule_task_del_by_context(server->schedule, client);
3380 /* We will not delete the client entry right away. We will take it
3381 into history (for WHOWAS command) for 5 minutes, unless we're
3382 shutting down server. */
3383 if (!server->server_shutdown) {
3384 silc_schedule_task_add(server->schedule, 0,
3385 silc_server_free_client_data_timeout,
3387 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
3388 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
3389 client->data.status &= ~SILC_IDLIST_STATUS_LOCAL;
3391 client->router = NULL;
3392 client->connection = NULL;
3394 /* Delete directly since we're shutting down server */
3395 silc_idlist_del_data(client);
3396 silc_idlist_del_client(server->local_list, client);
3400 /* Frees user_data pointer from socket connection object. This also sends
3401 appropriate notify packets to the network to inform about leaving
3404 void silc_server_free_sock_user_data(SilcServer server,
3405 SilcSocketConnection sock,
3406 const char *signoff_message)
3409 /* If any protocol is active cancel its execution */
3410 if (sock->protocol && sock->protocol->protocol &&
3411 sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3412 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3413 silc_protocol_cancel(sock->protocol, server->schedule);
3414 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3415 silc_protocol_execute_final(sock->protocol, server->schedule);
3416 sock->protocol = NULL;
3417 if (!sock->user_data)
3421 switch (sock->type) {
3422 case SILC_SOCKET_TYPE_CLIENT:
3424 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
3425 silc_server_free_client_data(server, sock, user_data, TRUE,
3429 case SILC_SOCKET_TYPE_SERVER:
3430 case SILC_SOCKET_TYPE_ROUTER:
3432 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
3433 SilcServerEntry backup_router = NULL;
3435 SILC_LOG_DEBUG(("Freeing server data"));
3438 backup_router = silc_server_backup_get(server, user_data->id);
3440 if (!server->backup_router && server->server_type == SILC_ROUTER &&
3441 backup_router == server->id_entry &&
3442 sock->type != SILC_SOCKET_TYPE_ROUTER)
3443 backup_router = NULL;
3445 if (server->server_shutdown || server->backup_noswitch)
3446 backup_router = NULL;
3448 /* If this was our primary router connection then we're lost to
3449 the outside world. */
3450 if (server->router == user_data) {
3451 /* Check whether we have a backup router connection */
3452 if (!backup_router || backup_router == user_data) {
3453 if (!server->no_reconnect)
3454 silc_server_create_connections(server);
3455 server->id_entry->router = NULL;
3456 server->router = NULL;
3457 server->standalone = TRUE;
3458 server->backup_primary = FALSE;
3459 backup_router = NULL;
3461 if (server->id_entry != backup_router) {
3462 SILC_LOG_INFO(("New primary router is backup router %s",
3463 backup_router->server_name));
3464 server->id_entry->router = backup_router;
3465 server->router = backup_router;
3466 server->router_connect = time(0);
3467 server->backup_primary = TRUE;
3468 backup_router->data.status &= ~SILC_IDLIST_STATUS_DISABLED;
3470 /* Send START_USE to backup router to indicate we have switched */
3471 silc_server_backup_send_start_use(server,
3472 backup_router->connection,
3475 SILC_LOG_INFO(("We are now new primary router in this cell"));
3476 server->id_entry->router = NULL;
3477 server->router = NULL;
3478 server->standalone = TRUE;
3481 /* We stop here to take a breath */
3484 if (server->backup_router) {
3485 server->server_type = SILC_ROUTER;
3487 /* We'll need to constantly try to reconnect to the primary
3488 router so that we'll see when it comes back online. */
3489 silc_server_backup_reconnect(server, sock->ip, sock->port,
3490 silc_server_backup_connected,
3494 /* Mark this connection as replaced */
3495 silc_server_backup_replaced_add(server, user_data->id,
3498 } else if (backup_router) {
3499 SILC_LOG_INFO(("Enabling the use of backup router %s",
3500 backup_router->server_name));
3502 /* Mark this connection as replaced */
3503 silc_server_backup_replaced_add(server, user_data->id,
3505 } else if (server->server_type == SILC_SERVER &&
3506 sock->type == SILC_SOCKET_TYPE_ROUTER) {
3507 /* Reconnect to the router (backup) */
3508 if (!server->no_reconnect)
3509 silc_server_create_connections(server);
3512 if (user_data->server_name)
3513 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
3514 ("Server %s signoff", user_data->server_name));
3516 if (!backup_router) {
3517 /* Remove all servers that are originated from this server, and
3518 remove the clients of those servers too. */
3519 silc_server_remove_servers_by_server(server, user_data, TRUE);
3522 /* Remove the clients that this server owns as they will become
3523 invalid now too. For backup router the server is actually
3524 coming from the primary router, so mark that as the owner
3526 if (server->server_type == SILC_BACKUP_ROUTER &&
3527 sock->type == SILC_SOCKET_TYPE_SERVER)
3528 silc_server_remove_clients_by_server(server, server->router,
3532 silc_server_remove_clients_by_server(server, user_data,
3535 /* Remove channels owned by this server */
3536 if (server->server_type == SILC_SERVER)
3537 silc_server_remove_channels_by_server(server, user_data);
3539 /* Enable local server connections that may be disabled */
3540 silc_server_local_servers_toggle_enabled(server, TRUE);
3542 /* Update the client entries of this server to the new backup
3543 router. If we are the backup router we also resolve the real
3544 servers for the clients. After updating is over this also
3545 removes the clients that this server explicitly owns. */
3546 silc_server_update_clients_by_server(server, user_data,
3547 backup_router, TRUE);
3549 /* If we are router and just lost our primary router (now standlaone)
3550 we remove everything that was behind it, since we don't know
3552 if (server->server_type == SILC_ROUTER && server->standalone)
3553 /* Remove all servers that are originated from this server, and
3554 remove the clients of those servers too. */
3555 silc_server_remove_servers_by_server(server, user_data, TRUE);
3557 /* Finally remove the clients that are explicitly owned by this
3558 server. They go down with the server. */
3559 silc_server_remove_clients_by_server(server, user_data,
3562 /* Update our server cache to use the new backup router too. */
3563 silc_server_update_servers_by_server(server, user_data, backup_router);
3564 if (server->server_type == SILC_SERVER)
3565 silc_server_update_channels_by_server(server, user_data,
3568 /* Send notify about primary router going down to local operators */
3569 if (server->backup_router)
3570 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3571 SILC_NOTIFY_TYPE_NONE,
3572 ("%s switched to backup router %s "
3573 "(we are primary router now)",
3574 server->server_name, server->server_name));
3575 else if (server->router)
3576 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3577 SILC_NOTIFY_TYPE_NONE,
3578 ("%s switched to backup router %s",
3579 server->server_name,
3580 server->router->server_name));
3582 server->backup_noswitch = FALSE;
3584 /* Free the server entry */
3585 silc_server_backup_del(server, user_data);
3586 silc_server_backup_replaced_del(server, user_data);
3587 silc_idlist_del_data(user_data);
3588 if (!silc_idlist_del_server(server->local_list, user_data))
3589 silc_idlist_del_server(server->global_list, user_data);
3590 if (sock->type == SILC_SOCKET_TYPE_SERVER) {
3591 server->stat.my_servers--;
3593 server->stat.my_routers--;
3594 server->stat.routers--;
3596 server->stat.servers--;
3597 if (server->server_type == SILC_ROUTER)
3598 server->stat.cell_servers--;
3600 if (backup_router && backup_router != server->id_entry) {
3601 /* Announce all of our stuff that was created about 5 minutes ago.
3602 The backup router knows all the other stuff already. */
3603 if (server->server_type == SILC_ROUTER)
3604 silc_server_announce_servers(server, FALSE, time(0) - 300,
3605 backup_router->connection);
3607 /* Announce our clients and channels to the router */
3608 silc_server_announce_clients(server, time(0) - 300,
3609 backup_router->connection);
3610 silc_server_announce_channels(server, time(0) - 300,
3611 backup_router->connection);
3617 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
3619 SILC_LOG_DEBUG(("Freeing unknown connection data"));
3621 silc_idlist_del_data(user_data);
3622 silc_free(user_data);
3627 sock->user_data = NULL;
3630 /* Removes client from all channels it has joined. This is used when client
3631 connection is disconnected. If the client on a channel is last, the
3632 channel is removed as well. This sends the SIGNOFF notify types. */
3634 void silc_server_remove_from_channels(SilcServer server,
3635 SilcSocketConnection sock,
3636 SilcClientEntry client,
3638 const char *signoff_message,
3642 SilcChannelEntry channel;
3643 SilcChannelClientEntry chl;
3644 SilcHashTableList htl;
3645 SilcBuffer clidp = NULL;
3650 if (notify && !client->id)
3653 SILC_LOG_DEBUG(("Removing client %s from joined channels",
3654 notify ? silc_id_render(client->id, SILC_ID_CLIENT) : ""));
3657 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3662 /* Remove the client from all channels. The client is removed from
3663 the channels' user list. */
3664 silc_hash_table_list(client->channels, &htl);
3665 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3666 channel = chl->channel;
3668 /* Remove channel if this is last client leaving the channel, unless
3669 the channel is permanent. */
3670 if (server->server_type != SILC_SERVER &&
3671 silc_hash_table_count(channel->user_list) < 2) {
3672 silc_server_channel_delete(server, channel);
3676 silc_hash_table_del(client->channels, channel);
3677 silc_hash_table_del(channel->user_list, client);
3678 channel->user_count--;
3680 /* If there is no global users on the channel anymore mark the channel
3681 as local channel. Do not check if the removed client is local client. */
3682 if (server->server_type == SILC_SERVER && channel->global_users &&
3683 chl->client->router && !silc_server_channel_has_global(channel))
3684 channel->global_users = FALSE;
3686 memset(chl, 'A', sizeof(*chl));
3689 /* Update statistics */
3690 if (SILC_IS_LOCAL(client))
3691 server->stat.my_chanclients--;
3692 if (server->server_type == SILC_ROUTER) {
3693 server->stat.cell_chanclients--;
3694 server->stat.chanclients--;
3697 /* If there is not at least one local user on the channel then we don't
3698 need the channel entry anymore, we can remove it safely, unless the
3699 channel is permanent channel */
3700 if (server->server_type == SILC_SERVER &&
3701 !silc_server_channel_has_local(channel)) {
3702 /* Notify about leaving client if this channel has global users. */
3703 if (notify && channel->global_users)
3704 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3705 SILC_NOTIFY_TYPE_SIGNOFF,
3706 signoff_message ? 2 : 1,
3707 clidp->data, clidp->len,
3708 signoff_message, signoff_message ?
3709 strlen(signoff_message) : 0);
3711 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3712 silc_server_channel_delete(server, channel);
3716 /* Send notify to channel about client leaving SILC and channel too */
3718 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3719 SILC_NOTIFY_TYPE_SIGNOFF,
3720 signoff_message ? 2 : 1,
3721 clidp->data, clidp->len,
3722 signoff_message, signoff_message ?
3723 strlen(signoff_message) : 0);
3725 if (killed && clidp) {
3726 /* Remove the client from channel's invite list */
3727 if (channel->invite_list &&
3728 silc_hash_table_count(channel->invite_list)) {
3730 SilcArgumentPayload iargs;
3731 ab = silc_argument_payload_encode_one(NULL, clidp->data,
3733 iargs = silc_argument_payload_parse(ab->data, ab->len, 1);
3734 silc_server_inviteban_process(server, channel->invite_list, 1, iargs);
3735 silc_buffer_free(ab);
3736 silc_argument_payload_free(iargs);
3740 /* Don't create keys if we are shutting down */
3741 if (server->server_shutdown)
3744 /* Re-generate channel key if needed */
3745 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3746 if (!silc_server_create_channel_key(server, channel, 0))
3749 /* Send the channel key to the channel. The key of course is not sent
3750 to the client who was removed from the channel. */
3751 silc_server_send_channel_key(server, client->connection, channel,
3752 server->server_type == SILC_ROUTER ?
3753 FALSE : !server->standalone);
3757 silc_hash_table_list_reset(&htl);
3759 silc_buffer_free(clidp);
3762 /* Removes client from one channel. This is used for example when client
3763 calls LEAVE command to remove itself from the channel. Returns TRUE
3764 if channel still exists and FALSE if the channel is removed when
3765 last client leaves the channel. If `notify' is FALSE notify messages
3768 bool silc_server_remove_from_one_channel(SilcServer server,
3769 SilcSocketConnection sock,
3770 SilcChannelEntry channel,
3771 SilcClientEntry client,
3774 SilcChannelClientEntry chl;
3777 SILC_LOG_DEBUG(("Removing %s from channel %s",
3778 silc_id_render(client->id, SILC_ID_CLIENT),
3779 channel->channel_name));
3781 /* Get the entry to the channel, if this client is not on the channel
3783 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
3786 /* Remove channel if this is last client leaving the channel, unless
3787 the channel is permanent. */
3788 if (server->server_type != SILC_SERVER &&
3789 silc_hash_table_count(channel->user_list) < 2) {
3790 silc_server_channel_delete(server, channel);
3794 silc_hash_table_del(client->channels, channel);
3795 silc_hash_table_del(channel->user_list, client);
3796 channel->user_count--;
3798 /* If there is no global users on the channel anymore mark the channel
3799 as local channel. Do not check if the client is local client. */
3800 if (server->server_type == SILC_SERVER && channel->global_users &&
3801 chl->client->router && !silc_server_channel_has_global(channel))
3802 channel->global_users = FALSE;
3804 memset(chl, 'O', sizeof(*chl));
3807 /* Update statistics */
3808 if (SILC_IS_LOCAL(client))
3809 server->stat.my_chanclients--;
3810 if (server->server_type == SILC_ROUTER) {
3811 server->stat.cell_chanclients--;
3812 server->stat.chanclients--;
3815 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3819 /* If there is not at least one local user on the channel then we don't
3820 need the channel entry anymore, we can remove it safely, unless the
3821 channel is permanent channel */
3822 if (server->server_type == SILC_SERVER &&
3823 !silc_server_channel_has_local(channel)) {
3824 /* Notify about leaving client if this channel has global users. */
3825 if (notify && channel->global_users)
3826 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3827 SILC_NOTIFY_TYPE_LEAVE, 1,
3828 clidp->data, clidp->len);
3830 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3831 silc_server_channel_delete(server, channel);
3832 silc_buffer_free(clidp);
3836 /* Send notify to channel about client leaving the channel */
3838 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3839 SILC_NOTIFY_TYPE_LEAVE, 1,
3840 clidp->data, clidp->len);
3842 silc_buffer_free(clidp);
3846 /* Timeout callback. This is called if connection is idle or for some
3847 other reason is not responding within some period of time. This
3848 disconnects the remote end. */
3850 SILC_TASK_CALLBACK(silc_server_timeout_remote)
3852 SilcServer server = (SilcServer)context;
3853 SilcSocketConnection sock = server->sockets[fd];
3854 SilcProtocolType protocol = 0;
3856 SILC_LOG_DEBUG(("Start"));
3861 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
3862 sock->hostname, sock->ip));
3864 /* If we have protocol active we must assure that we call the protocol's
3865 final callback so that all the memory is freed. */
3866 if (sock->protocol && sock->protocol->protocol &&
3867 sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3868 protocol = sock->protocol->protocol->type;
3869 silc_protocol_cancel(sock->protocol, server->schedule);
3870 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3871 silc_protocol_execute_final(sock->protocol, server->schedule);
3872 sock->protocol = NULL;
3876 silc_server_disconnect_remote(server, sock,
3878 SILC_PROTOCOL_SERVER_CONNECTION_AUTH ?
3879 SILC_STATUS_ERR_AUTH_FAILED :
3880 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
3881 "Connection timeout");
3883 if (sock->user_data)
3884 silc_server_free_sock_user_data(server, sock, NULL);
3887 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
3888 function may be used only by router. In real SILC network all channels
3889 are created by routers thus this function is never used by normal
3892 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3893 SilcServerID *router_id,
3899 SilcChannelID *channel_id;
3900 SilcChannelEntry entry;
3904 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3907 cipher = SILC_DEFAULT_CIPHER;
3909 hmac = SILC_DEFAULT_HMAC;
3911 /* Allocate cipher */
3912 if (!silc_cipher_alloc(cipher, &key))
3916 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3917 silc_cipher_free(key);
3921 channel_name = strdup(channel_name);
3923 /* Create the channel ID */
3924 if (!silc_id_create_channel_id(server, router_id, server->rng,
3926 silc_free(channel_name);
3927 silc_cipher_free(key);
3928 silc_hmac_free(newhmac);
3932 /* Create the channel */
3933 entry = silc_idlist_add_channel(server->local_list, channel_name,
3934 SILC_CHANNEL_MODE_NONE, channel_id,
3935 NULL, key, newhmac, 0);
3937 silc_free(channel_name);
3938 silc_cipher_free(key);
3939 silc_hmac_free(newhmac);
3940 silc_free(channel_id);
3944 entry->cipher = strdup(cipher);
3945 entry->hmac_name = strdup(hmac);
3947 /* Now create the actual key material */
3948 if (!silc_server_create_channel_key(server, entry,
3949 silc_cipher_get_key_len(key) / 8)) {
3950 silc_idlist_del_channel(server->local_list, entry);
3954 /* Notify other routers about the new channel. We send the packet
3955 to our primary route. */
3957 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3958 channel_name, entry->id,
3959 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3962 /* Distribute to backup routers */
3963 if (broadcast && server->server_type == SILC_ROUTER) {
3966 SilcUInt32 name_len = strlen(channel_name);
3967 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3968 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3970 packet = silc_channel_payload_encode(channel_name, name_len,
3971 cid, channel_id_len, entry->mode);
3972 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3973 packet->data, packet->len, FALSE, TRUE);
3975 silc_buffer_free(packet);
3978 server->stat.my_channels++;
3979 if (server->server_type == SILC_ROUTER) {
3980 server->stat.channels++;
3981 server->stat.cell_channels++;
3982 entry->users_resolved = TRUE;
3988 /* Same as above but creates the channel with Channel ID `channel_id. */
3991 silc_server_create_new_channel_with_id(SilcServer server,
3995 SilcChannelID *channel_id,
3998 SilcChannelEntry entry;
4002 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
4005 cipher = SILC_DEFAULT_CIPHER;
4007 hmac = SILC_DEFAULT_HMAC;
4009 /* Allocate cipher */
4010 if (!silc_cipher_alloc(cipher, &key))
4014 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
4015 silc_cipher_free(key);
4019 channel_name = strdup(channel_name);
4021 /* Create the channel */
4022 entry = silc_idlist_add_channel(server->local_list, channel_name,
4023 SILC_CHANNEL_MODE_NONE, channel_id,
4024 NULL, key, newhmac, 0);
4026 silc_cipher_free(key);
4027 silc_hmac_free(newhmac);
4028 silc_free(channel_name);
4032 /* Now create the actual key material */
4033 if (!silc_server_create_channel_key(server, entry,
4034 silc_cipher_get_key_len(key) / 8)) {
4035 silc_idlist_del_channel(server->local_list, entry);
4039 /* Notify other routers about the new channel. We send the packet
4040 to our primary route. */
4042 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
4043 channel_name, entry->id,
4044 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
4047 /* Distribute to backup routers */
4048 if (broadcast && server->server_type == SILC_ROUTER) {
4051 SilcUInt32 name_len = strlen(channel_name);
4052 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
4053 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
4055 packet = silc_channel_payload_encode(channel_name, name_len,
4056 cid, channel_id_len, entry->mode);
4057 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
4058 packet->data, packet->len, FALSE, TRUE);
4060 silc_buffer_free(packet);
4063 server->stat.my_channels++;
4064 if (server->server_type == SILC_ROUTER) {
4065 server->stat.channels++;
4066 server->stat.cell_channels++;
4067 entry->users_resolved = TRUE;
4073 /* Channel's key re-key timeout callback. */
4075 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
4077 SilcServer server = app_context;
4078 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
4082 /* Return now if we are shutting down */
4083 if (server->server_shutdown)
4086 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
4089 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
4092 /* Generates new channel key. This is used to create the initial channel key
4093 but also to re-generate new key for channel. If `key_len' is provided
4094 it is the bytes of the key length. */
4096 bool silc_server_create_channel_key(SilcServer server,
4097 SilcChannelEntry channel,
4101 unsigned char channel_key[32], hash[32];
4104 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
4105 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
4109 SILC_LOG_DEBUG(("Generating channel %s key", channel->channel_name));
4111 if (!channel->channel_key)
4112 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
4113 channel->channel_key = NULL;
4119 else if (channel->key_len)
4120 len = channel->key_len / 8;
4122 len = silc_cipher_get_key_len(channel->channel_key) / 8;
4124 /* Create channel key */
4125 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
4128 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
4130 /* Remove old key if exists */
4132 memset(channel->key, 0, channel->key_len / 8);
4133 silc_free(channel->key);
4137 channel->key_len = len * 8;
4138 channel->key = silc_memdup(channel_key, len);
4139 memset(channel_key, 0, sizeof(channel_key));
4141 /* Generate HMAC key from the channel key data and set it */
4143 if (!silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac)) {
4144 memset(channel->key, 0, channel->key_len / 8);
4145 silc_free(channel->key);
4146 channel->channel_key = NULL;
4149 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
4150 silc_hmac_set_key(channel->hmac, hash,
4151 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
4152 memset(hash, 0, sizeof(hash));
4154 if (server->server_type == SILC_ROUTER) {
4155 if (!channel->rekey)
4156 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
4157 channel->rekey->channel = channel;
4158 channel->rekey->key_len = key_len;
4159 if (channel->rekey->task)
4160 silc_schedule_task_del(server->schedule, channel->rekey->task);
4162 channel->rekey->task =
4163 silc_schedule_task_add(server->schedule, 0,
4164 silc_server_channel_key_rekey,
4165 (void *)channel->rekey,
4166 server->config->channel_rekey_secs, 0,
4168 SILC_TASK_PRI_NORMAL);
4174 /* Saves the channel key found in the encoded `key_payload' buffer. This
4175 function is used when we receive Channel Key Payload and also when we're
4176 processing JOIN command reply. Returns entry to the channel. */
4178 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
4179 SilcBuffer key_payload,
4180 SilcChannelEntry channel)
4182 SilcChannelKeyPayload payload = NULL;
4183 SilcChannelID *id = NULL;
4184 unsigned char *tmp, hash[32];
4188 /* Decode channel key payload */
4189 payload = silc_channel_key_payload_parse(key_payload->data,
4192 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
4197 /* Get the channel entry */
4200 /* Get channel ID */
4201 tmp = silc_channel_key_get_id(payload, &tmp_len);
4202 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
4208 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
4210 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
4212 if (server->server_type == SILC_ROUTER)
4213 SILC_LOG_ERROR(("Received key for non-existent channel %s",
4214 silc_id_render(id, SILC_ID_CHANNEL)));
4220 SILC_LOG_DEBUG(("Saving new channel %s key", channel->channel_name));
4222 tmp = silc_channel_key_get_key(payload, &tmp_len);
4228 cipher = silc_channel_key_get_cipher(payload, NULL);
4234 /* Remove old key if exists */
4236 memset(channel->key, 0, channel->key_len / 8);
4237 silc_free(channel->key);
4238 silc_cipher_free(channel->channel_key);
4241 /* Create new cipher */
4242 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
4243 channel->channel_key = NULL;
4248 if (channel->cipher)
4249 silc_free(channel->cipher);
4250 channel->cipher = strdup(cipher);
4253 channel->key_len = tmp_len * 8;
4254 channel->key = silc_memdup(tmp, tmp_len);
4255 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
4257 /* Generate HMAC key from the channel key data and set it */
4259 if (!silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac)) {
4260 memset(channel->key, 0, channel->key_len / 8);
4261 silc_free(channel->key);
4262 channel->channel_key = NULL;
4265 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
4266 silc_hmac_set_key(channel->hmac, hash,
4267 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
4269 memset(hash, 0, sizeof(hash));
4270 memset(tmp, 0, tmp_len);
4272 if (server->server_type == SILC_ROUTER) {
4273 if (!channel->rekey)
4274 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
4275 channel->rekey->channel = channel;
4276 if (channel->rekey->task)
4277 silc_schedule_task_del(server->schedule, channel->rekey->task);
4279 channel->rekey->task =
4280 silc_schedule_task_add(server->schedule, 0,
4281 silc_server_channel_key_rekey,
4282 (void *)channel->rekey,
4283 server->config->channel_rekey_secs, 0,
4285 SILC_TASK_PRI_NORMAL);
4291 silc_channel_key_payload_free(payload);
4296 /* Heartbeat callback. This function is set as argument for the
4297 silc_socket_set_heartbeat function. The library will call this function
4298 at the set time interval. */
4300 void silc_server_perform_heartbeat(SilcSocketConnection sock,
4303 SilcServer server = hb_context;
4305 SILC_LOG_DEBUG(("Sending heartbeat to %s:%d (%s)", sock->hostname,
4306 sock->port, sock->ip));
4308 /* Send the heartbeat */
4309 silc_server_send_heartbeat(server, sock);
4312 /* Returns assembled of all servers in the given ID list. The packet's
4313 form is dictated by the New ID payload. */
4315 static void silc_server_announce_get_servers(SilcServer server,
4316 SilcServerEntry remote,
4318 SilcBuffer *servers,
4319 unsigned long creation_time)
4321 SilcIDCacheList list;
4322 SilcIDCacheEntry id_cache;
4323 SilcServerEntry entry;
4326 /* Go through all clients in the list */
4327 if (silc_idcache_get_all(id_list->servers, &list)) {
4328 if (silc_idcache_list_first(list, &id_cache)) {
4330 entry = (SilcServerEntry)id_cache->context;
4332 /* Do not announce the one we've sending our announcements and
4333 do not announce ourself. Also check the creation time if it's
4335 if ((entry == remote) || (entry == server->id_entry) ||
4336 (creation_time && entry->data.created < creation_time)) {
4337 if (!silc_idcache_list_next(list, &id_cache))
4342 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
4344 *servers = silc_buffer_realloc(*servers,
4346 (*servers)->truelen + idp->len :
4348 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
4349 silc_buffer_put(*servers, idp->data, idp->len);
4350 silc_buffer_pull(*servers, idp->len);
4351 silc_buffer_free(idp);
4353 if (!silc_idcache_list_next(list, &id_cache))
4358 silc_idcache_list_free(list);
4363 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
4369 p = silc_notify_payload_encode(notify, argc, ap);
4375 /* This function is used by router to announce existing servers to our
4376 primary router when we've connected to it. If `creation_time' is non-zero
4377 then only the servers that has been created after the `creation_time'
4378 will be announced. */
4380 void silc_server_announce_servers(SilcServer server, bool global,
4381 unsigned long creation_time,
4382 SilcSocketConnection remote)
4384 SilcBuffer servers = NULL;
4386 SILC_LOG_DEBUG(("Announcing servers"));
4388 /* Get servers in local list */
4389 silc_server_announce_get_servers(server, remote->user_data,
4390 server->local_list, &servers,
4394 /* Get servers in global list */
4395 silc_server_announce_get_servers(server, remote->user_data,
4396 server->global_list, &servers,
4400 silc_buffer_push(servers, servers->data - servers->head);
4401 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
4403 /* Send the packet */
4404 silc_server_packet_send(server, remote,
4405 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4406 servers->data, servers->len, TRUE);
4408 silc_buffer_free(servers);
4412 /* Returns assembled packet of all clients in the given ID list. The
4413 packet's form is dictated by the New ID Payload. */
4415 static void silc_server_announce_get_clients(SilcServer server,
4417 SilcBuffer *clients,
4419 unsigned long creation_time)
4421 SilcIDCacheList list;
4422 SilcIDCacheEntry id_cache;
4423 SilcClientEntry client;
4426 unsigned char mode[4];
4428 /* Go through all clients in the list */
4429 if (silc_idcache_get_all(id_list->clients, &list)) {
4430 if (silc_idcache_list_first(list, &id_cache)) {
4432 client = (SilcClientEntry)id_cache->context;
4434 if (creation_time && client->data.created < creation_time) {
4435 if (!silc_idcache_list_next(list, &id_cache))
4439 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED) &&
4440 !client->connection && !client->router && !SILC_IS_LOCAL(client)) {
4441 if (!silc_idcache_list_next(list, &id_cache))
4446 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
4448 *clients = silc_buffer_realloc(*clients,
4450 (*clients)->truelen + idp->len :
4452 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
4453 silc_buffer_put(*clients, idp->data, idp->len);
4454 silc_buffer_pull(*clients, idp->len);
4456 SILC_PUT32_MSB(client->mode, mode);
4458 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
4459 2, idp->data, idp->len,
4461 *umodes = silc_buffer_realloc(*umodes,
4463 (*umodes)->truelen + tmp->len :
4465 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
4466 silc_buffer_put(*umodes, tmp->data, tmp->len);
4467 silc_buffer_pull(*umodes, tmp->len);
4468 silc_buffer_free(tmp);
4470 silc_buffer_free(idp);
4472 if (!silc_idcache_list_next(list, &id_cache))
4477 silc_idcache_list_free(list);
4481 /* This function is used to announce our existing clients to our router
4482 when we've connected to it. If `creation_time' is non-zero then only
4483 the clients that has been created after the `creation_time' will be
4486 void silc_server_announce_clients(SilcServer server,
4487 unsigned long creation_time,
4488 SilcSocketConnection remote)
4490 SilcBuffer clients = NULL;
4491 SilcBuffer umodes = NULL;
4493 SILC_LOG_DEBUG(("Announcing clients"));
4495 /* Get clients in local list */
4496 silc_server_announce_get_clients(server, server->local_list,
4497 &clients, &umodes, creation_time);
4499 /* As router we announce our global list as well */
4500 if (server->server_type == SILC_ROUTER)
4501 silc_server_announce_get_clients(server, server->global_list,
4502 &clients, &umodes, creation_time);
4505 silc_buffer_push(clients, clients->data - clients->head);
4506 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
4508 /* Send the packet */
4509 silc_server_packet_send(server, remote,
4510 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4511 clients->data, clients->len, TRUE);
4513 silc_buffer_free(clients);
4517 silc_buffer_push(umodes, umodes->data - umodes->head);
4518 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
4520 /* Send the packet */
4521 silc_server_packet_send(server, remote,
4522 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4523 umodes->data, umodes->len, TRUE);
4525 silc_buffer_free(umodes);
4529 /* Returns channel's topic for announcing it */
4531 void silc_server_announce_get_channel_topic(SilcServer server,
4532 SilcChannelEntry channel,
4537 if (channel->topic) {
4538 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4539 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
4540 chidp->data, chidp->len,
4542 strlen(channel->topic));
4543 silc_buffer_free(chidp);
4547 /* Returns channel's invite and ban lists */
4549 void silc_server_announce_get_inviteban(SilcServer server,
4550 SilcChannelEntry channel,
4554 SilcBuffer list, idp, idp2, tmp2;
4556 SilcHashTableList htl;
4557 const unsigned char a[1] = { 0x03 };
4559 idp = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
4561 /* Encode invite list */
4562 if (channel->invite_list && silc_hash_table_count(channel->invite_list)) {
4563 list = silc_buffer_alloc_size(2);
4564 type = silc_hash_table_count(channel->invite_list);
4565 SILC_PUT16_MSB(type, list->data);
4566 silc_hash_table_list(channel->invite_list, &htl);
4567 while (silc_hash_table_get(&htl, (void *)&type, (void *)&tmp2))
4568 list = silc_argument_payload_encode_one(list, tmp2->data, tmp2->len,
4570 silc_hash_table_list_reset(&htl);
4572 idp2 = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4574 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_INVITE, 5,
4575 idp->data, idp->len,
4576 channel->channel_name,
4577 strlen(channel->channel_name),
4578 idp2->data, idp2->len,
4580 list->data, list->len);
4581 silc_buffer_free(idp2);
4582 silc_buffer_free(list);
4585 /* Encode ban list */
4586 if (channel->ban_list && silc_hash_table_count(channel->ban_list)) {
4587 list = silc_buffer_alloc_size(2);
4588 type = silc_hash_table_count(channel->ban_list);
4589 SILC_PUT16_MSB(type, list->data);
4590 silc_hash_table_list(channel->ban_list, &htl);
4591 while (silc_hash_table_get(&htl, (void *)&type, (void *)&tmp2))
4592 list = silc_argument_payload_encode_one(list, tmp2->data, tmp2->len,
4594 silc_hash_table_list_reset(&htl);
4597 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_BAN, 3,
4598 idp->data, idp->len,
4600 list->data, list->len);
4601 silc_buffer_free(list);
4604 silc_buffer_free(idp);
4607 /* Returns assembled packets for channel users of the `channel'. */
4609 void silc_server_announce_get_channel_users(SilcServer server,
4610 SilcChannelEntry channel,
4611 SilcBuffer *channel_modes,
4612 SilcBuffer *channel_users,
4613 SilcBuffer *channel_users_modes)
4615 SilcChannelClientEntry chl;
4616 SilcHashTableList htl;
4617 SilcBuffer chidp, clidp, csidp;
4618 SilcBuffer tmp, fkey = NULL, chpklist;
4620 unsigned char mode[4], ulimit[4];
4623 SILC_LOG_DEBUG(("Start"));
4625 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4626 csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4627 chpklist = silc_server_get_channel_pk_list(server, channel, TRUE, FALSE);
4630 SILC_PUT32_MSB(channel->mode, mode);
4631 if (channel->mode & SILC_CHANNEL_MODE_ULIMIT)
4632 SILC_PUT32_MSB(channel->user_limit, ulimit);
4633 hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
4634 if (channel->founder_key)
4635 fkey = silc_pkcs_public_key_payload_encode(channel->founder_key);
4637 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
4638 8, csidp->data, csidp->len,
4641 hmac, hmac ? strlen(hmac) : 0,
4642 channel->passphrase,
4643 channel->passphrase ?
4644 strlen(channel->passphrase) : 0,
4645 fkey ? fkey->data : NULL,
4646 fkey ? fkey->len : 0,
4647 chpklist ? chpklist->data : NULL,
4648 chpklist ? chpklist->len : 0,
4650 SILC_CHANNEL_MODE_ULIMIT ?
4653 SILC_CHANNEL_MODE_ULIMIT ?
4654 sizeof(ulimit) : 0));
4657 silc_buffer_realloc(*channel_modes,
4659 (*channel_modes)->truelen + len : len));
4660 silc_buffer_pull_tail(*channel_modes,
4661 ((*channel_modes)->end -
4662 (*channel_modes)->data));
4663 silc_buffer_put(*channel_modes, tmp->data, tmp->len);
4664 silc_buffer_pull(*channel_modes, len);
4665 silc_buffer_free(tmp);
4666 silc_buffer_free(fkey);
4669 /* Now find all users on the channel */
4670 silc_hash_table_list(channel->user_list, &htl);
4671 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4672 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4675 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
4676 clidp->data, clidp->len,
4677 chidp->data, chidp->len);
4680 silc_buffer_realloc(*channel_users,
4682 (*channel_users)->truelen + len : len));
4683 silc_buffer_pull_tail(*channel_users,
4684 ((*channel_users)->end -
4685 (*channel_users)->data));
4687 silc_buffer_put(*channel_users, tmp->data, tmp->len);
4688 silc_buffer_pull(*channel_users, len);
4689 silc_buffer_free(tmp);
4691 /* CUMODE notify for mode change on the channel */
4692 SILC_PUT32_MSB(chl->mode, mode);
4693 if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
4694 fkey = silc_pkcs_public_key_payload_encode(channel->founder_key);
4695 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
4696 4, csidp->data, csidp->len,
4698 clidp->data, clidp->len,
4699 fkey ? fkey->data : NULL,
4700 fkey ? fkey->len : 0);
4702 *channel_users_modes =
4703 silc_buffer_realloc(*channel_users_modes,
4704 (*channel_users_modes ?
4705 (*channel_users_modes)->truelen + len : len));
4706 silc_buffer_pull_tail(*channel_users_modes,
4707 ((*channel_users_modes)->end -
4708 (*channel_users_modes)->data));
4710 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
4711 silc_buffer_pull(*channel_users_modes, len);
4712 silc_buffer_free(tmp);
4713 silc_buffer_free(fkey);
4715 silc_buffer_free(clidp);
4717 silc_hash_table_list_reset(&htl);
4718 silc_buffer_free(chidp);
4719 silc_buffer_free(csidp);
4722 /* Returns assembled packets for all channels and users on those channels
4723 from the given ID List. The packets are in the form dictated by the
4724 New Channel and New Channel User payloads. */
4726 void silc_server_announce_get_channels(SilcServer server,
4728 SilcBuffer *channels,
4729 SilcBuffer **channel_modes,
4730 SilcBuffer *channel_users,
4731 SilcBuffer **channel_users_modes,
4732 SilcUInt32 *channel_users_modes_c,
4733 SilcBuffer **channel_topics,
4734 SilcBuffer **channel_invites,
4735 SilcBuffer **channel_bans,
4736 SilcChannelID ***channel_ids,
4737 unsigned long creation_time)
4739 SilcIDCacheList list;
4740 SilcIDCacheEntry id_cache;
4741 SilcChannelEntry channel;
4744 SilcUInt16 name_len;
4746 int i = *channel_users_modes_c;
4749 SILC_LOG_DEBUG(("Start"));
4751 /* Go through all channels in the list */
4752 if (silc_idcache_get_all(id_list->channels, &list)) {
4753 if (silc_idcache_list_first(list, &id_cache)) {
4755 channel = (SilcChannelEntry)id_cache->context;
4757 if (creation_time && channel->created < creation_time)
4762 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4763 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4764 name_len = strlen(channel->channel_name);
4767 len = 4 + name_len + id_len + 4;
4769 silc_buffer_realloc(*channels,
4770 (*channels ? (*channels)->truelen +
4772 silc_buffer_pull_tail(*channels,
4773 ((*channels)->end - (*channels)->data));
4774 silc_buffer_format(*channels,
4775 SILC_STR_UI_SHORT(name_len),
4776 SILC_STR_UI_XNSTRING(channel->channel_name,
4778 SILC_STR_UI_SHORT(id_len),
4779 SILC_STR_UI_XNSTRING(cid, id_len),
4780 SILC_STR_UI_INT(channel->mode),
4782 silc_buffer_pull(*channels, len);
4785 if (creation_time && channel->updated < creation_time)
4791 /* Channel user modes */
4792 *channel_users_modes = silc_realloc(*channel_users_modes,
4793 sizeof(**channel_users_modes) *
4795 (*channel_users_modes)[i] = NULL;
4796 *channel_modes = silc_realloc(*channel_modes,
4797 sizeof(**channel_modes) * (i + 1));
4798 (*channel_modes)[i] = NULL;
4799 *channel_ids = silc_realloc(*channel_ids,
4800 sizeof(**channel_ids) * (i + 1));
4801 (*channel_ids)[i] = NULL;
4802 silc_server_announce_get_channel_users(server, channel,
4803 &(*channel_modes)[i],
4805 &(*channel_users_modes)[i]);
4806 (*channel_ids)[i] = channel->id;
4808 /* Channel's topic */
4809 *channel_topics = silc_realloc(*channel_topics,
4810 sizeof(**channel_topics) * (i + 1));
4811 (*channel_topics)[i] = NULL;
4812 silc_server_announce_get_channel_topic(server, channel,
4813 &(*channel_topics)[i]);
4815 /* Channel's invite and ban list */
4816 *channel_invites = silc_realloc(*channel_invites,
4817 sizeof(**channel_invites) * (i + 1));
4818 (*channel_invites)[i] = NULL;
4819 *channel_bans = silc_realloc(*channel_bans,
4820 sizeof(**channel_bans) * (i + 1));
4821 (*channel_bans)[i] = NULL;
4822 silc_server_announce_get_inviteban(server, channel,
4823 &(*channel_invites)[i],
4824 &(*channel_bans)[i]);
4826 (*channel_users_modes_c)++;
4832 if (!silc_idcache_list_next(list, &id_cache))
4837 silc_idcache_list_free(list);
4841 /* This function is used to announce our existing channels to our router
4842 when we've connected to it. This also announces the users on the
4843 channels to the router. If the `creation_time' is non-zero only the
4844 channels that was created after the `creation_time' are announced.
4845 Note that the channel users are still announced even if the `creation_time'
4848 void silc_server_announce_channels(SilcServer server,
4849 unsigned long creation_time,
4850 SilcSocketConnection remote)
4852 SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
4853 SilcBuffer *channel_users_modes = NULL;
4854 SilcBuffer *channel_topics = NULL;
4855 SilcBuffer *channel_invites = NULL;
4856 SilcBuffer *channel_bans = NULL;
4857 SilcUInt32 channel_users_modes_c = 0;
4858 SilcChannelID **channel_ids = NULL;
4860 SILC_LOG_DEBUG(("Announcing channels and channel users"));
4862 /* Get channels and channel users in local list */
4863 silc_server_announce_get_channels(server, server->local_list,
4864 &channels, &channel_modes,
4866 &channel_users_modes,
4867 &channel_users_modes_c,
4871 &channel_ids, creation_time);
4873 /* Get channels and channel users in global list */
4874 if (server->server_type != SILC_SERVER)
4875 silc_server_announce_get_channels(server, server->global_list,
4876 &channels, &channel_modes,
4878 &channel_users_modes,
4879 &channel_users_modes_c,
4883 &channel_ids, creation_time);
4886 silc_buffer_push(channels, channels->data - channels->head);
4887 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
4889 /* Send the packet */
4890 silc_server_packet_send(server, remote,
4891 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
4892 channels->data, channels->len,
4895 silc_buffer_free(channels);
4898 if (channel_users) {
4899 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
4900 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
4901 channel_users->len);
4903 /* Send the packet */
4904 silc_server_packet_send(server, remote,
4905 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4906 channel_users->data, channel_users->len,
4909 silc_buffer_free(channel_users);
4912 if (channel_modes) {
4915 for (i = 0; i < channel_users_modes_c; i++) {
4916 if (!channel_modes[i])
4918 silc_buffer_push(channel_modes[i],
4919 channel_modes[i]->data -
4920 channel_modes[i]->head);
4921 SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
4922 channel_modes[i]->len);
4923 silc_server_packet_send_dest(server, remote,
4924 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4925 channel_ids[i], SILC_ID_CHANNEL,
4926 channel_modes[i]->data,
4927 channel_modes[i]->len,
4929 silc_buffer_free(channel_modes[i]);
4931 silc_free(channel_modes);
4934 if (channel_users_modes) {
4937 for (i = 0; i < channel_users_modes_c; i++) {
4938 if (!channel_users_modes[i])
4940 silc_buffer_push(channel_users_modes[i],
4941 channel_users_modes[i]->data -
4942 channel_users_modes[i]->head);
4943 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
4944 channel_users_modes[i]->len);
4945 silc_server_packet_send_dest(server, remote,
4946 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4947 channel_ids[i], SILC_ID_CHANNEL,
4948 channel_users_modes[i]->data,
4949 channel_users_modes[i]->len,
4951 silc_buffer_free(channel_users_modes[i]);
4953 silc_free(channel_users_modes);
4956 if (channel_topics) {
4959 for (i = 0; i < channel_users_modes_c; i++) {
4960 if (!channel_topics[i])
4963 silc_buffer_push(channel_topics[i],
4964 channel_topics[i]->data -
4965 channel_topics[i]->head);
4966 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
4967 channel_topics[i]->len);
4968 silc_server_packet_send_dest(server, remote,
4969 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4970 channel_ids[i], SILC_ID_CHANNEL,
4971 channel_topics[i]->data,
4972 channel_topics[i]->len,
4974 silc_buffer_free(channel_topics[i]);
4976 silc_free(channel_topics);
4979 if (channel_invites) {
4982 for (i = 0; i < channel_users_modes_c; i++) {
4983 if (!channel_invites[i])
4986 silc_buffer_push(channel_invites[i],
4987 channel_invites[i]->data -
4988 channel_invites[i]->head);
4989 SILC_LOG_HEXDUMP(("channel invite list"), channel_invites[i]->data,
4990 channel_invites[i]->len);
4991 silc_server_packet_send_dest(server, remote,
4992 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4993 channel_ids[i], SILC_ID_CHANNEL,
4994 channel_invites[i]->data,
4995 channel_invites[i]->len,
4997 silc_buffer_free(channel_invites[i]);
4999 silc_free(channel_invites);
5005 for (i = 0; i < channel_users_modes_c; i++) {
5006 if (!channel_bans[i])
5009 silc_buffer_push(channel_bans[i],
5010 channel_bans[i]->data -
5011 channel_bans[i]->head);
5012 SILC_LOG_HEXDUMP(("channel ban list"), channel_bans[i]->data,
5013 channel_bans[i]->len);
5014 silc_server_packet_send_dest(server, remote,
5015 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
5016 channel_ids[i], SILC_ID_CHANNEL,
5017 channel_bans[i]->data,
5018 channel_bans[i]->len,
5020 silc_buffer_free(channel_bans[i]);
5022 silc_free(channel_bans);
5025 silc_free(channel_ids);
5028 /* Assembles user list and users mode list from the `channel'. */
5030 bool silc_server_get_users_on_channel(SilcServer server,
5031 SilcChannelEntry channel,
5032 SilcBuffer *user_list,
5033 SilcBuffer *mode_list,
5034 SilcUInt32 *user_count)
5036 SilcChannelClientEntry chl;
5037 SilcHashTableList htl;
5038 SilcBuffer client_id_list;
5039 SilcBuffer client_mode_list;
5041 SilcUInt32 list_count = 0, len = 0;
5043 if (!silc_hash_table_count(channel->user_list))
5046 silc_hash_table_list(channel->user_list, &htl);
5047 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
5048 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
5049 silc_hash_table_list_reset(&htl);
5051 client_id_list = silc_buffer_alloc(len);
5053 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
5054 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
5055 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
5057 silc_hash_table_list(channel->user_list, &htl);
5058 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5060 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
5061 silc_buffer_put(client_id_list, idp->data, idp->len);
5062 silc_buffer_pull(client_id_list, idp->len);
5063 silc_buffer_free(idp);
5065 /* Client's mode on channel */
5066 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
5067 silc_buffer_pull(client_mode_list, 4);
5071 silc_hash_table_list_reset(&htl);
5072 silc_buffer_push(client_id_list,
5073 client_id_list->data - client_id_list->head);
5074 silc_buffer_push(client_mode_list,
5075 client_mode_list->data - client_mode_list->head);
5077 *user_list = client_id_list;
5078 *mode_list = client_mode_list;
5079 *user_count = list_count;
5083 /* Saves users and their modes to the `channel'. */
5085 void silc_server_save_users_on_channel(SilcServer server,
5086 SilcSocketConnection sock,
5087 SilcChannelEntry channel,
5088 SilcClientID *noadd,
5089 SilcBuffer user_list,
5090 SilcBuffer mode_list,
5091 SilcUInt32 user_count)
5096 SilcClientID *client_id;
5097 SilcClientEntry client;
5098 SilcIDCacheEntry cache;
5099 SilcChannelClientEntry chl;
5101 SILC_LOG_DEBUG(("Saving %d users on %s channel", user_count,
5102 channel->channel_name));
5104 for (i = 0; i < user_count; i++) {
5106 SILC_GET16_MSB(idp_len, user_list->data + 2);
5108 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
5109 silc_buffer_pull(user_list, idp_len);
5114 SILC_GET32_MSB(mode, mode_list->data);
5115 silc_buffer_pull(mode_list, 4);
5117 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
5118 silc_free(client_id);
5124 /* Check if we have this client cached already. */
5125 client = silc_idlist_find_client_by_id(server->local_list, client_id,
5126 server->server_type, &cache);
5128 client = silc_idlist_find_client_by_id(server->global_list,
5129 client_id, server->server_type,
5132 /* If router did not find such Client ID in its lists then this must
5133 be bogus client or some router in the net is buggy. */
5134 if (server->server_type != SILC_SERVER) {
5135 silc_free(client_id);
5139 /* We don't have that client anywhere, add it. The client is added
5140 to global list since server didn't have it in the lists so it must be
5142 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
5143 silc_id_dup(client_id, SILC_ID_CLIENT),
5144 sock->user_data, NULL, 0);
5146 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
5147 silc_free(client_id);
5151 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
5156 silc_free(client_id);
5158 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
5159 SILC_LOG_ERROR(("Attempting to add unregistered client to channel ",
5160 "%s", channel->channel_name));
5164 if (!silc_server_client_on_channel(client, channel, &chl)) {
5165 /* Client was not on the channel, add it. */
5166 chl = silc_calloc(1, sizeof(*chl));
5167 chl->client = client;
5169 chl->channel = channel;
5170 silc_hash_table_add(channel->user_list, chl->client, chl);
5171 silc_hash_table_add(client->channels, chl->channel, chl);
5172 channel->user_count++;
5180 /* Saves channels and channels user modes to the `client'. Removes
5181 the client from those channels that are not sent in the list but
5184 void silc_server_save_user_channels(SilcServer server,
5185 SilcSocketConnection sock,
5186 SilcClientEntry client,
5187 SilcBuffer channels,
5188 SilcBuffer channels_user_modes)
5191 SilcUInt32 *chumodes;
5192 SilcChannelPayload entry;
5193 SilcChannelEntry channel;
5194 SilcChannelID *channel_id;
5195 SilcChannelClientEntry chl;
5196 SilcHashTable ht = NULL;
5197 SilcHashTableList htl;
5201 if (!channels || !channels_user_modes ||
5202 !(client->data.status & SILC_IDLIST_STATUS_REGISTERED))
5205 ch = silc_channel_payload_parse_list(channels->data, channels->len);
5206 if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
5208 ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL,
5209 NULL, NULL, NULL, TRUE);
5210 silc_dlist_start(ch);
5211 while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
5212 /* Check if we have this channel, and add it if we don't have it.
5213 Also add the client on the channel unless it is there already. */
5214 channel_id = silc_channel_get_id_parse(entry);
5215 channel = silc_idlist_find_channel_by_id(server->local_list,
5218 channel = silc_idlist_find_channel_by_id(server->global_list,
5221 if (server->server_type != SILC_SERVER) {
5222 silc_free(channel_id);
5227 /* We don't have that channel anywhere, add it. */
5228 name = silc_channel_get_name(entry, NULL);
5229 channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
5230 channel_id, server->router,
5233 silc_free(channel_id);
5240 channel->mode = silc_channel_get_mode(entry);
5242 /* Add the client on the channel */
5243 if (!silc_server_client_on_channel(client, channel, &chl)) {
5244 chl = silc_calloc(1, sizeof(*chl));
5245 chl->client = client;
5246 chl->mode = chumodes[i++];
5247 chl->channel = channel;
5248 silc_hash_table_add(channel->user_list, chl->client, chl);
5249 silc_hash_table_add(client->channels, chl->channel, chl);
5250 channel->user_count++;
5253 chl->mode = chumodes[i++];
5256 silc_hash_table_add(ht, channel, channel);
5257 silc_free(channel_id);
5259 silc_channel_payload_list_free(ch);
5260 silc_free(chumodes);
5264 /* Go through the list again and remove client from channels that
5265 are no part of the list. */
5267 silc_hash_table_list(client->channels, &htl);
5268 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5269 if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
5270 silc_hash_table_del(chl->channel->user_list, chl->client);
5271 silc_hash_table_del(chl->client->channels, chl->channel);
5275 silc_hash_table_list_reset(&htl);
5276 silc_hash_table_free(ht);
5278 silc_hash_table_list(client->channels, &htl);
5279 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5280 silc_hash_table_del(chl->channel->user_list, chl->client);
5281 silc_hash_table_del(chl->client->channels, chl->channel);
5284 silc_hash_table_list_reset(&htl);
5288 /* Lookups route to the client indicated by the `id_data'. The connection
5289 object and internal data object is returned. Returns NULL if route
5290 could not be found to the client. If the `client_id' is specified then
5291 it is used and the `id_data' is ignored. */
5293 SilcSocketConnection
5294 silc_server_get_client_route(SilcServer server,
5295 unsigned char *id_data,
5297 SilcClientID *client_id,
5298 SilcIDListData *idata,
5299 SilcClientEntry *client_entry)
5302 SilcClientEntry client;
5304 SILC_LOG_DEBUG(("Start"));
5307 *client_entry = NULL;
5309 /* Decode destination Client ID */
5311 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
5313 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
5317 id = silc_id_dup(client_id, SILC_ID_CLIENT);
5320 /* If the destination belongs to our server we don't have to route
5321 the packet anywhere but to send it to the local destination. */
5322 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
5326 /* If we are router and the client has router then the client is in
5327 our cell but not directly connected to us. */
5328 if (server->server_type == SILC_ROUTER && client->router) {
5329 /* We are of course in this case the client's router thus the route
5330 to the client is the server who owns the client. So, we will send
5331 the packet to that server. */
5333 *idata = (SilcIDListData)client->router;
5334 return client->router->connection;
5337 /* Seems that client really is directly connected to us */
5339 *idata = (SilcIDListData)client;
5341 *client_entry = client;
5342 return client->connection;
5345 /* Destination belongs to someone not in this server. If we are normal
5346 server our action is to send the packet to our router. */
5347 if (server->server_type != SILC_ROUTER && !server->standalone) {
5350 *idata = (SilcIDListData)server->router;
5351 return SILC_PRIMARY_ROUTE(server);
5354 /* We are router and we will perform route lookup for the destination
5355 and send the packet to fastest route. */
5356 if (server->server_type == SILC_ROUTER && !server->standalone) {
5357 /* Check first that the ID is valid */
5358 client = silc_idlist_find_client_by_id(server->global_list, id,
5361 SilcSocketConnection dst_sock;
5363 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
5367 *idata = (SilcIDListData)dst_sock->user_data;
5376 /* Encodes and returns channel list of channels the `client' has joined.
5377 Secret channels are not put to the list. */
5379 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
5380 SilcClientEntry client,
5383 SilcBuffer *user_mode_list)
5385 SilcBuffer buffer = NULL;
5386 SilcChannelEntry channel;
5387 SilcChannelClientEntry chl;
5388 SilcHashTableList htl;
5391 SilcUInt16 name_len;
5395 *user_mode_list = NULL;
5397 silc_hash_table_list(client->channels, &htl);
5398 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5399 channel = chl->channel;
5401 if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
5403 if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
5406 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
5407 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
5408 name_len = strlen(channel->channel_name);
5410 len = 4 + name_len + id_len + 4;
5411 buffer = silc_buffer_realloc(buffer,
5412 (buffer ? buffer->truelen + len : len));
5413 silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
5414 silc_buffer_format(buffer,
5415 SILC_STR_UI_SHORT(name_len),
5416 SILC_STR_UI_XNSTRING(channel->channel_name,
5418 SILC_STR_UI_SHORT(id_len),
5419 SILC_STR_UI_XNSTRING(cid, id_len),
5420 SILC_STR_UI_INT(chl->channel->mode),
5422 silc_buffer_pull(buffer, len);
5425 if (user_mode_list) {
5426 *user_mode_list = silc_buffer_realloc(*user_mode_list,
5428 (*user_mode_list)->truelen + 4 :
5430 silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
5431 (*user_mode_list)->data));
5432 SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
5433 silc_buffer_pull(*user_mode_list, 4);
5436 silc_hash_table_list_reset(&htl);
5439 silc_buffer_push(buffer, buffer->data - buffer->head);
5440 if (user_mode_list && *user_mode_list)
5441 silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
5442 (*user_mode_list)->head));
5447 /* Timeout callback for unsuccessful rekey. The rekey did not go through
5450 SILC_TASK_CALLBACK(silc_server_rekey_timeout)
5452 SilcServerRekeyInternalContext *ctx = context;
5453 SilcServer server = app_context;
5454 SilcSocketConnection sock = ctx->sock;
5456 SILC_LOG_DEBUG(("Timeout occurred in rekey protocol with %s:%d [%s]",
5457 sock->hostname, sock->port,
5458 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5459 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5460 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5463 SILC_LOG_WARNING(("Timeout occurred in rekey protocol with %s:%d [%s]",
5464 sock->hostname, sock->port,
5465 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5466 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5467 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5470 if (sock->protocol) {
5471 silc_protocol_cancel(sock->protocol, server->schedule);
5472 silc_protocol_free(sock->protocol);
5473 sock->protocol = NULL;
5476 silc_packet_context_free(ctx->packet);
5478 silc_ske_free(ctx->ske);
5479 silc_socket_free(sock);
5482 /* Disconnect since we failed to rekey, the keys are probably wrong. */
5483 silc_server_disconnect_remote(server, sock,
5484 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
5485 if (sock->user_data)
5486 silc_server_free_sock_user_data(server, sock, NULL);
5489 if (sock->type != SILC_SOCKET_TYPE_CLIENT)
5490 silc_server_create_connections(server);
5493 /* A timeout callback for the re-key. We will be the initiator of the
5496 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_callback)
5498 SilcServer server = app_context;
5499 SilcSocketConnection sock = (SilcSocketConnection)context;
5500 SilcIDListData idata = (SilcIDListData)sock->user_data;
5501 SilcProtocol protocol;
5502 SilcServerRekeyInternalContext *proto_ctx;
5507 /* Do not execute rekey with disabled connections, as it would not
5508 go through anyway. */
5509 if (idata->status & SILC_IDLIST_STATUS_DISABLED)
5512 /* If rekey protocol is active already wait for it to finish */
5513 if (sock->protocol && sock->protocol->protocol &&
5514 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)
5517 /* If any other protocol is active do not start this protocol yet. */
5518 if (sock->protocol) {
5519 SILC_LOG_DEBUG(("Waiting for other protocol to finish before rekeying"));
5520 silc_schedule_task_add(server->schedule, sock->sock,
5521 silc_server_rekey_callback,
5522 sock, 60, 0, SILC_TASK_TIMEOUT,
5523 SILC_TASK_PRI_NORMAL);
5527 SILC_LOG_DEBUG(("Executing rekey protocol with %s:%d [%s]",
5528 sock->hostname, sock->port,
5529 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5530 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5531 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5534 /* Allocate internal protocol context. This is sent as context
5536 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
5537 proto_ctx->server = (void *)server;
5538 proto_ctx->sock = silc_socket_dup(sock);
5539 proto_ctx->responder = FALSE;
5540 proto_ctx->pfs = idata->rekey->pfs;
5542 /* Perform rekey protocol. Will call the final callback after the
5543 protocol is over. */
5544 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
5545 &protocol, proto_ctx, silc_server_rekey_final);
5546 sock->protocol = protocol;
5548 /* Register timeout callback in case the rekey does not go through. */
5549 proto_ctx->timeout_task =
5550 silc_schedule_task_add(server->schedule, sock->sock,
5551 silc_server_rekey_timeout,
5553 (idata->rekey->timeout >
5554 server->config->key_exchange_timeout ?
5555 idata->rekey->timeout :
5556 server->config->key_exchange_timeout * 4), 0,
5560 /* Run the protocol */
5561 silc_protocol_execute(protocol, server->schedule, 0, 0);
5564 /* The final callback for the REKEY protocol. This will actually take the
5565 new key material into use. */
5567 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
5569 SilcProtocol protocol = (SilcProtocol)context;
5570 SilcServerRekeyInternalContext *ctx =
5571 (SilcServerRekeyInternalContext *)protocol->context;
5572 SilcServer server = (SilcServer)ctx->server;
5573 SilcSocketConnection sock = ctx->sock;
5574 SilcIDListData idata = (SilcIDListData)sock->user_data;
5576 if (ctx->timeout_task)
5577 silc_schedule_task_del(server->schedule, ctx->timeout_task);
5579 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
5580 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
5581 /* Error occured during protocol */
5582 SILC_LOG_ERROR(("Error occurred during rekey protocol with "
5583 "%s (%s)", sock->hostname, sock->ip));
5584 silc_protocol_cancel(protocol, server->schedule);
5585 silc_protocol_free(protocol);
5586 sock->protocol = NULL;
5588 silc_packet_context_free(ctx->packet);
5590 silc_ske_free(ctx->ske);
5591 silc_socket_free(sock);
5593 silc_server_disconnect_remote(server, sock,
5594 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
5595 if (sock->user_data)
5596 silc_server_free_sock_user_data(server, sock, NULL);
5599 if (sock->type != SILC_SOCKET_TYPE_CLIENT)
5600 silc_server_create_connections(server);
5604 SILC_LOG_DEBUG(("Rekey protocol completed with %s:%d [%s]",
5605 sock->hostname, sock->port,
5606 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5607 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5608 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5611 /* Purge the outgoing data queue to assure that all rekey packets really
5612 go to the network before we quit the protocol. */
5613 silc_server_packet_queue_purge(server, sock);
5615 /* Re-register re-key timeout */
5616 if (ctx->responder == FALSE)
5617 silc_schedule_task_add(server->schedule, sock->sock,
5618 silc_server_rekey_callback,
5619 sock, idata->rekey->timeout, 0,
5620 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
5623 silc_protocol_free(protocol);
5624 sock->protocol = NULL;
5626 silc_packet_context_free(ctx->packet);
5628 silc_ske_free(ctx->ske);
5629 silc_socket_free(sock);
5633 /* Task callback used to retrieve network statistical information from
5634 router server once in a while. */
5636 SILC_TASK_CALLBACK(silc_server_get_stats)
5638 SilcServer server = (SilcServer)context;
5639 SilcBuffer idp, packet;
5641 if (!server->standalone) {
5642 SILC_LOG_DEBUG(("Retrieving stats from router"));
5643 idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
5644 packet = silc_command_payload_encode_va(SILC_COMMAND_STATS,
5645 ++server->cmd_ident, 1,
5646 1, idp->data, idp->len);
5647 silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
5648 SILC_PACKET_COMMAND, 0, packet->data,
5649 packet->len, FALSE);
5650 silc_buffer_free(packet);
5651 silc_buffer_free(idp);
5654 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
5655 server, 120, 0, SILC_TASK_TIMEOUT,