5 Author: Pekka Riikonen <priikone@silcnet.org>
7 Copyright (C) 1997 - 2003 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);
46 /* Allocates a new SILC server object. This has to be done before the server
47 can be used. After allocation one must call silc_server_init to initialize
48 the server. The new allocated server object is returned to the new_server
51 int silc_server_alloc(SilcServer *new_server)
55 SILC_LOG_DEBUG(("Allocating new server object"));
57 server = silc_calloc(1, sizeof(*server));
58 server->server_type = SILC_SERVER;
59 server->standalone = TRUE;
60 server->local_list = silc_calloc(1, sizeof(*server->local_list));
61 server->global_list = silc_calloc(1, sizeof(*server->global_list));
62 server->pending_commands = silc_dlist_init();
64 server->sim = silc_dlist_init();
72 /* Free's the SILC server object. This is called at the very end before
75 void silc_server_free(SilcServer server)
78 SilcIDCacheEntry cache;
86 silc_dlist_start(server->sim);
87 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
88 silc_dlist_del(server->sim, sim);
92 silc_dlist_uninit(server->sim);
96 silc_server_backup_free(server);
97 silc_server_config_unref(&server->config_ref);
99 silc_rng_free(server->rng);
101 silc_pkcs_free(server->pkcs);
102 if (server->public_key)
103 silc_pkcs_public_key_free(server->public_key);
104 if (server->private_key)
105 silc_pkcs_private_key_free(server->private_key);
106 if (server->pending_commands)
107 silc_dlist_uninit(server->pending_commands);
108 if (server->id_entry)
109 silc_idlist_del_server(server->local_list, server->id_entry);
111 /* Delete all channels */
113 if (silc_idcache_get_all(server->local_list->channels, &list) &&
114 silc_idcache_list_first(list, &cache)) {
115 silc_idlist_del_channel(server->local_list, cache->context);
116 while (silc_idcache_list_next(list, &cache))
117 silc_idlist_del_channel(server->local_list, cache->context);
120 silc_idcache_list_free(list);
122 if (silc_idcache_get_all(server->global_list->channels, &list) &&
123 silc_idcache_list_first(list, &cache)) {
124 silc_idlist_del_channel(server->global_list, cache->context);
125 while (silc_idcache_list_next(list, &cache))
126 silc_idlist_del_channel(server->global_list, cache->context);
129 silc_idcache_list_free(list);
131 /* Delete all clients */
133 if (silc_idcache_get_all(server->local_list->clients, &list) &&
134 silc_idcache_list_first(list, &cache)) {
135 silc_idlist_del_client(server->local_list, cache->context);
136 while (silc_idcache_list_next(list, &cache))
137 silc_idlist_del_client(server->local_list, cache->context);
140 silc_idcache_list_free(list);
142 if (silc_idcache_get_all(server->global_list->clients, &list) &&
143 silc_idcache_list_first(list, &cache)) {
144 silc_idlist_del_client(server->global_list, cache->context);
145 while (silc_idcache_list_next(list, &cache))
146 silc_idlist_del_client(server->global_list, cache->context);
149 silc_idcache_list_free(list);
152 silc_hash_table_free(server->pk_hash);
154 /* Delete all servers */
156 if (silc_idcache_get_all(server->local_list->servers, &list) &&
157 silc_idcache_list_first(list, &cache)) {
158 silc_idlist_del_server(server->local_list, cache->context);
159 while (silc_idcache_list_next(list, &cache))
160 silc_idlist_del_server(server->local_list, cache->context);
163 silc_idcache_list_free(list);
165 if (silc_idcache_get_all(server->global_list->servers, &list) &&
166 silc_idcache_list_first(list, &cache)) {
167 silc_idlist_del_server(server->global_list, cache->context);
168 while (silc_idcache_list_next(list, &cache))
169 silc_idlist_del_server(server->global_list, cache->context);
172 silc_idcache_list_free(list);
174 silc_idcache_free(server->local_list->clients);
175 silc_idcache_free(server->local_list->servers);
176 silc_idcache_free(server->local_list->channels);
177 silc_idcache_free(server->global_list->clients);
178 silc_idcache_free(server->global_list->servers);
179 silc_idcache_free(server->global_list->channels);
180 silc_hash_table_free(server->watcher_list);
182 silc_hash_free(server->md5hash);
183 silc_hash_free(server->sha1hash);
184 silc_hmac_unregister_all();
185 silc_hash_unregister_all();
186 silc_cipher_unregister_all();
187 silc_pkcs_unregister_all();
189 silc_free(server->local_list);
190 silc_free(server->global_list);
191 silc_free(server->server_name);
192 silc_free(server->id_string);
193 silc_free(server->purge_i);
194 silc_free(server->purge_g);
198 /* Creates a new server listener. */
200 static bool silc_server_listen(SilcServer server, const char *server_ip,
201 SilcUInt16 port, int *sock)
203 *sock = silc_net_create_server(port, server_ip);
205 SILC_SERVER_LOG_ERROR(("Could not create server listener: %s on %hu",
212 /* Adds a secondary listener. */
214 bool silc_server_init_secondary(SilcServer server)
216 int sock = 0, sock_list[server->config->param.connections_max];
217 SilcSocketConnection newsocket = NULL;
218 SilcServerConfigServerInfoInterface *interface;
220 for (interface = server->config->server_info->secondary; interface;
221 interface = interface->next, sock++) {
223 if (!silc_server_listen(server,
224 interface->server_ip, interface->port, &sock_list[sock]))
227 /* Set socket to non-blocking mode */
228 silc_net_set_socket_nonblock(sock_list[sock]);
230 /* Add ourselves also to the socket table. The entry allocated above
231 is sent as argument for fast referencing in the future. */
232 silc_socket_alloc(sock_list[sock],
233 SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
234 server->sockets[sock_list[sock]] = newsocket;
235 SILC_SET_LISTENER(newsocket);
237 /* Perform name and address lookups to resolve the listenning address
239 if (!silc_net_check_local_by_sock(sock_list[sock], &newsocket->hostname,
241 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
243 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
244 newsocket->hostname ? newsocket->hostname :
245 newsocket->ip ? newsocket->ip : ""));
246 server->stat.conn_failures++;
249 if (!newsocket->hostname)
250 newsocket->hostname = strdup(newsocket->ip);
252 newsocket->port = silc_net_get_local_port(sock);
254 newsocket->user_data = (void *)server->id_entry;
255 silc_schedule_task_add(server->schedule, sock_list[sock],
256 silc_server_accept_new_connection,
257 (void *)server, 0, 0,
259 SILC_TASK_PRI_NORMAL);
265 do silc_net_close_server(sock_list[sock--]); while (sock >= 0);
269 /* Initializes the entire SILC server. This is called always before running
270 the server. This is called only once at the initialization of the program.
271 This binds the server to its listenning port. After this function returns
272 one should call silc_server_run to start the server. This returns TRUE
273 when everything is ok to run the server. Configuration file must be
274 read and parsed before calling this. */
276 bool silc_server_init(SilcServer server)
280 SilcServerEntry id_entry;
281 SilcIDListPurge purge;
282 SilcSocketConnection newsocket = NULL;
284 SILC_LOG_DEBUG(("Initializing server"));
286 server->starttime = time(NULL);
288 /* Take config object for us */
289 silc_server_config_ref(&server->config_ref, server->config,
293 /* Set debugging on if configured */
294 if (server->config->debug_string) {
296 silc_log_set_debug_string(server->config->debug_string);
298 #endif /* SILC_DEBUG */
300 /* Steal public and private key from the config object */
301 server->public_key = server->config->server_info->public_key;
302 server->private_key = server->config->server_info->private_key;
303 server->config->server_info->public_key = NULL;
304 server->config->server_info->private_key = NULL;
306 /* Register all configured ciphers, PKCS and hash functions. */
307 if (!silc_server_config_register_ciphers(server))
308 silc_cipher_register_default();
309 if (!silc_server_config_register_pkcs(server))
310 silc_pkcs_register_default();
311 if (!silc_server_config_register_hashfuncs(server))
312 silc_hash_register_default();
313 if (!silc_server_config_register_hmacs(server))
314 silc_hmac_register_default();
316 /* Initialize random number generator for the server. */
317 server->rng = silc_rng_alloc();
318 silc_rng_init(server->rng);
319 silc_rng_global_init(server->rng);
321 /* Initialize hash functions for server to use */
322 silc_hash_alloc("md5", &server->md5hash);
323 silc_hash_alloc("sha1", &server->sha1hash);
325 /* Allocate PKCS context for local public and private keys */
326 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
328 silc_pkcs_public_key_set(server->pkcs, server->public_key);
329 silc_pkcs_private_key_set(server->pkcs, server->private_key);
331 /* Initialize the scheduler */
332 server->schedule = silc_schedule_init(server->config->param.connections_max,
334 if (!server->schedule)
337 /* First, register log files configuration for error output */
338 silc_server_config_setlogfiles(server);
340 /* Initialize ID caches */
341 server->local_list->clients =
342 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
343 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
344 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
346 /* These are allocated for normal server as well as these hold some
347 global information that the server has fetched from its router. For
348 router these are used as they are supposed to be used on router. */
349 server->global_list->clients =
350 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
351 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
352 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
354 /* Init watcher list */
355 server->watcher_list =
356 silc_hash_table_alloc(1, silc_hash_client_id_hash, NULL,
357 silc_hash_data_compare, (void *)CLIENTID_HASH_LEN,
359 if (!server->watcher_list)
362 /* Init public key list */
364 silc_hash_table_alloc(0, silc_hash_public_key, NULL,
365 silc_hash_public_key_compare, NULL,
368 if (!server->pk_hash)
371 /* Create a listening server */
372 if (!silc_server_listen(server,
373 server->config->server_info->primary == NULL ? NULL :
374 server->config->server_info->primary->server_ip,
375 server->config->server_info->primary == NULL ? 0 :
376 server->config->server_info->primary->port,
380 /* Set socket to non-blocking mode */
381 silc_net_set_socket_nonblock(sock);
384 /* Allocate the entire socket list that is used in server. Eventually
385 all connections will have entry in this table (it is a table of
386 pointers to the actual object that is allocated individually
388 server->sockets = silc_calloc(server->config->param.connections_max,
389 sizeof(*server->sockets));
390 if (!server->sockets)
393 /* Add ourselves also to the socket table. The entry allocated above
394 is sent as argument for fast referencing in the future. */
395 silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
396 server->sockets[sock] = newsocket;
397 SILC_SET_LISTENER(newsocket);
399 /* Perform name and address lookups to resolve the listenning address
401 if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
403 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
405 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
406 newsocket->hostname ? newsocket->hostname :
407 newsocket->ip ? newsocket->ip : ""));
408 server->stat.conn_failures++;
411 if (!newsocket->hostname)
412 newsocket->hostname = strdup(newsocket->ip);
414 newsocket->port = silc_net_get_local_port(sock);
416 /* Create a Server ID for the server. */
417 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
422 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
423 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
424 server->server_name = server->config->server_info->server_name;
425 server->config->server_info->server_name = NULL;
427 /* Add ourselves to the server list. We don't have a router yet
428 beacuse we haven't established a route yet. It will be done later.
429 For now, NULL is sent as router. This allocates new entry to
432 silc_idlist_add_server(server->local_list, strdup(server->server_name),
433 server->server_type, server->id, NULL, NULL);
435 SILC_LOG_ERROR(("Could not add ourselves to cache"));
438 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
440 /* Put the allocated socket pointer also to the entry allocated above
441 for fast back-referencing to the socket list. */
442 newsocket->user_data = (void *)id_entry;
443 id_entry->connection = (void *)newsocket;
444 server->id_entry = id_entry;
446 /* Register protocols */
447 silc_server_protocols_register();
449 /* Create connections to configured routers. */
450 silc_server_create_connections(server);
452 /* Add listener task to the scheduler. This task receives new connections
453 to the server. This task remains on the queue until the end of the
455 silc_schedule_task_add(server->schedule, sock,
456 silc_server_accept_new_connection,
457 (void *)server, 0, 0,
459 SILC_TASK_PRI_NORMAL);
461 if (silc_server_init_secondary(server) == FALSE)
464 server->listenning = TRUE;
466 /* If server connections has been configured then we must be router as
467 normal server cannot have server connections, only router connections. */
468 if (server->config->servers) {
469 SilcServerConfigServer *ptr = server->config->servers;
471 server->server_type = SILC_ROUTER;
473 if (ptr->backup_router) {
474 server->server_type = SILC_BACKUP_ROUTER;
475 server->backup_router = TRUE;
476 server->id_entry->server_type = SILC_BACKUP_ROUTER;
483 /* Register the ID Cache purge task. This periodically purges the ID cache
484 and removes the expired cache entries. */
486 /* Clients local list */
487 server->purge_i = purge = silc_calloc(1, sizeof(*purge));
488 purge->cache = server->local_list->clients;
489 purge->timeout = 600;
490 silc_schedule_task_add(server->schedule, 0, silc_idlist_purge,
491 (void *)purge, purge->timeout, 0,
492 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
494 /* Clients global list */
495 server->purge_g = purge = silc_calloc(1, sizeof(*purge));
496 purge->cache = server->global_list->clients;
497 purge->timeout = 300;
498 silc_schedule_task_add(server->schedule, 0, silc_idlist_purge,
499 (void *)purge, purge->timeout, 0,
500 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
502 /* If we are normal server we'll retrieve network statisticial information
503 once in a while from the router. */
504 if (server->server_type != SILC_ROUTER)
505 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
506 server, 10, 0, SILC_TASK_TIMEOUT,
509 if (server->server_type == SILC_ROUTER)
510 server->stat.routers++;
512 SILC_LOG_DEBUG(("Server initialized"));
514 /* We are done here, return succesfully */
518 silc_server_config_unref(&server->config_ref);
519 silc_net_close_server(sock);
523 /* Task callback to close a socket connection after rehash */
525 SILC_TASK_CALLBACK(silc_server_rehash_close_connection)
527 SilcServer server = context;
528 SilcSocketConnection sock = server->sockets[fd];
533 SILC_LOG_INFO(("Connection %s:%d [%s] is unconfigured",
534 sock->hostname, sock->port,
535 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
536 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
537 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
539 silc_schedule_task_del_by_context(server->schedule, sock);
540 silc_server_disconnect_remote(server, sock,
541 SILC_STATUS_ERR_BANNED_FROM_SERVER,
542 "This connection is removed from "
545 silc_server_free_sock_user_data(server, sock, NULL);
548 /* This function basically reads the config file again and switches the config
549 object pointed by the server object. After that, we have to fix various
550 things such as the server_name and the listening ports.
551 Keep in mind that we no longer have the root privileges at this point. */
553 bool silc_server_rehash(SilcServer server)
555 SilcServerConfig newconfig;
557 SILC_LOG_INFO(("Rehashing server"));
559 /* Reset the logging system */
560 silc_log_quick = TRUE;
561 silc_log_flush_all();
563 /* Start the main rehash phase (read again the config file) */
564 newconfig = silc_server_config_alloc(server->config_file);
566 SILC_LOG_ERROR(("Rehash FAILED."));
570 /* Reinit scheduler if necessary */
571 if (newconfig->param.connections_max > server->config->param.connections_max)
572 if (!silc_schedule_reinit(server->schedule,
573 newconfig->param.connections_max))
576 /* Fix the server_name field */
577 if (strcmp(server->server_name, newconfig->server_info->server_name)) {
578 silc_free(server->server_name);
579 server->server_name = newconfig->server_info->server_name;
580 newconfig->server_info->server_name = NULL;
582 /* Update the idcache list with a fresh pointer */
583 silc_free(server->id_entry->server_name);
584 server->id_entry->server_name = strdup(server->server_name);
585 if (!silc_idcache_del_by_context(server->local_list->servers,
588 if (!silc_idcache_add(server->local_list->servers,
589 server->id_entry->server_name,
590 server->id_entry->id, server->id_entry, 0, NULL))
595 silc_server_config_setlogfiles(server);
597 /* Change new key pair if necessary */
598 if (newconfig->server_info->public_key &&
599 !silc_pkcs_public_key_compare(server->public_key,
600 newconfig->server_info->public_key)) {
601 silc_pkcs_public_key_free(server->public_key);
602 silc_pkcs_private_key_free(server->private_key);
603 server->public_key = newconfig->server_info->public_key;
604 server->private_key = newconfig->server_info->private_key;
605 newconfig->server_info->public_key = NULL;
606 newconfig->server_info->private_key = NULL;
608 /* Allocate PKCS context for local public and private keys */
609 silc_pkcs_free(server->pkcs);
610 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
612 silc_pkcs_public_key_set(server->pkcs, server->public_key);
613 silc_pkcs_private_key_set(server->pkcs, server->private_key);
616 /* Check for unconfigured server and router connections and close
617 connections that were unconfigured. */
619 if (server->config->routers) {
620 SilcServerConfigRouter *ptr;
621 SilcServerConfigRouter *newptr;
624 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
627 /* Check whether new config has this one too */
628 for (newptr = newconfig->routers; newptr; newptr = newptr->next) {
629 if (silc_string_compare(newptr->host, ptr->host) &&
630 newptr->port == ptr->port &&
631 newptr->initiator == ptr->initiator) {
637 if (!found && ptr->host) {
638 /* Remove this connection */
639 SilcSocketConnection sock;
640 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_ROUTER,
641 ptr->host, ptr->port);
642 if (sock && !SILC_IS_LISTENER(sock))
643 silc_schedule_task_add(server->schedule, sock->sock,
644 silc_server_rehash_close_connection,
645 server, 0, 1, SILC_TASK_TIMEOUT,
646 SILC_TASK_PRI_NORMAL);
651 if (server->config->servers) {
652 SilcServerConfigServer *ptr;
653 SilcServerConfigServer *newptr;
656 for (ptr = server->config->servers; ptr; ptr = ptr->next) {
659 /* Check whether new config has this one too */
660 for (newptr = newconfig->servers; newptr; newptr = newptr->next) {
661 if (silc_string_compare(newptr->host, ptr->host)) {
667 if (!found && ptr->host) {
668 /* Remove this connection */
669 SilcSocketConnection sock;
670 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_SERVER,
672 if (sock && !SILC_IS_LISTENER(sock))
673 silc_schedule_task_add(server->schedule, sock->sock,
674 silc_server_rehash_close_connection,
675 server, 0, 1, SILC_TASK_TIMEOUT,
676 SILC_TASK_PRI_NORMAL);
681 if (server->config->clients) {
682 SilcServerConfigClient *ptr;
683 SilcServerConfigClient *newptr;
686 for (ptr = server->config->clients; ptr; ptr = ptr->next) {
689 /* Check whether new config has this one too */
690 for (newptr = newconfig->clients; newptr; newptr = newptr->next) {
691 if (silc_string_compare(newptr->host, ptr->host)) {
697 if (!found && ptr->host) {
698 /* Remove this connection */
699 SilcSocketConnection sock;
700 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_CLIENT,
703 silc_schedule_task_add(server->schedule, sock->sock,
704 silc_server_rehash_close_connection,
705 server, 0, 1, SILC_TASK_TIMEOUT,
706 SILC_TASK_PRI_NORMAL);
711 /* Create connections after rehash */
712 silc_server_create_connections(server);
714 /* Check whether our router status has changed */
715 if (newconfig->servers) {
716 SilcServerConfigServer *ptr = newconfig->servers;
718 server->server_type = SILC_ROUTER;
720 if (ptr->backup_router) {
721 server->server_type = SILC_BACKUP_ROUTER;
722 server->backup_router = TRUE;
723 server->id_entry->server_type = SILC_BACKUP_ROUTER;
730 /* Our old config is gone now. We'll unreference our reference made in
731 silc_server_init and then destroy it since we are destroying it
732 underneath the application (layer which called silc_server_init). */
733 silc_server_config_unref(&server->config_ref);
734 silc_server_config_destroy(server->config);
736 /* Take new config context */
737 server->config = newconfig;
738 silc_server_config_ref(&server->config_ref, server->config, server->config);
741 /* Set debugging on if configured */
742 if (server->config->debug_string) {
744 silc_log_set_debug_string(server->config->debug_string);
748 #endif /* SILC_DEBUG */
750 SILC_LOG_DEBUG(("Server rehashed"));
755 /* The heart of the server. This runs the scheduler thus runs the server.
756 When this returns the server has been stopped and the program will
759 void silc_server_run(SilcServer server)
761 SILC_LOG_INFO(("SILC Server started"));
763 /* Start the scheduler, the heart of the SILC server. When this returns
764 the program will be terminated. */
765 silc_schedule(server->schedule);
768 /* Stops the SILC server. This function is used to shutdown the server.
769 This is usually called after the scheduler has returned. After stopping
770 the server one should call silc_server_free. */
772 void silc_server_stop(SilcServer server)
774 SILC_LOG_INFO(("SILC Server shutting down"));
776 if (server->schedule) {
779 server->server_shutdown = TRUE;
781 /* Close all connections */
782 for (i = 0; i < server->config->param.connections_max; i++) {
783 if (!server->sockets[i])
785 if (!SILC_IS_LISTENER(server->sockets[i])) {
786 SilcSocketConnection sock = server->sockets[i];
787 SilcIDListData idata = sock->user_data;
790 idata->status &= ~SILC_IDLIST_STATUS_DISABLED;
792 silc_schedule_task_del_by_context(server->schedule,
794 silc_schedule_task_del_by_fd(server->schedule,
795 server->sockets[i]->sock);
796 silc_server_disconnect_remote(server, server->sockets[i],
798 "Server is shutting down");
799 if (server->sockets[i]) {
801 silc_server_free_sock_user_data(server, sock,
802 "Server is shutting down");
803 silc_socket_free(sock);
806 silc_socket_free(server->sockets[i]);
807 server->sockets[i] = NULL;
811 /* We are not connected to network anymore */
812 server->standalone = TRUE;
814 silc_schedule_stop(server->schedule);
815 silc_schedule_uninit(server->schedule);
816 server->schedule = NULL;
818 silc_free(server->sockets);
819 server->sockets = NULL;
822 silc_server_protocols_unregister();
824 SILC_LOG_DEBUG(("Server stopped"));
827 /* Function that is called when the network connection to a router has
828 been established. This will continue with the key exchange protocol
829 with the remote router. */
831 void silc_server_start_key_exchange(SilcServer server,
832 SilcServerConnection sconn,
835 SilcSocketConnection newsocket;
836 SilcProtocol protocol;
837 SilcServerKEInternalContext *proto_ctx;
838 SilcServerConfigRouter *conn =
839 (SilcServerConfigRouter *) sconn->conn.ref_ptr;
842 /* Cancel any possible retry timeouts */
843 silc_schedule_task_del_by_callback(server->schedule,
844 silc_server_connect_to_router_retry);
846 /* Set socket options */
847 silc_net_set_socket_nonblock(sock);
848 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
850 /* Create socket connection for the connection. Even though we
851 know that we are connecting to a router we will mark the socket
852 to be unknown connection until we have executed authentication
854 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
855 server->sockets[sock] = newsocket;
856 newsocket->hostname = strdup(sconn->remote_host);
857 newsocket->ip = strdup(sconn->remote_host);
858 newsocket->port = sconn->remote_port;
859 sconn->sock = newsocket;
861 /* Allocate internal protocol context. This is sent as context
863 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
864 proto_ctx->server = (void *)server;
865 proto_ctx->context = (void *)sconn;
866 proto_ctx->sock = newsocket;
867 proto_ctx->rng = server->rng;
868 proto_ctx->responder = FALSE;
870 /* Set Key Exchange flags from configuration, but fall back to global
872 SILC_GET_SKE_FLAGS(conn, proto_ctx);
873 if (server->config->param.key_exchange_pfs)
874 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
876 /* Perform key exchange protocol. silc_server_connect_to_router_second
877 will be called after the protocol is finished. */
878 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
879 &protocol, proto_ctx,
880 silc_server_connect_to_router_second);
881 newsocket->protocol = protocol;
883 /* Register a timeout task that will be executed if the protocol
884 is not executed within set limit. */
885 proto_ctx->timeout_task =
886 silc_schedule_task_add(server->schedule, sock,
887 silc_server_timeout_remote,
888 server, server->config->key_exchange_timeout, 0,
892 /* Register the connection for network input and output. This sets
893 that scheduler will listen for incoming packets for this connection
894 and sets that outgoing packets may be sent to this connection as
895 well. However, this doesn't set the scheduler for outgoing traffic,
896 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
897 later when outgoing data is available. */
898 context = (void *)server;
899 SILC_REGISTER_CONNECTION_FOR_IO(sock);
901 /* Run the protocol */
902 silc_protocol_execute(protocol, server->schedule, 0, 0);
905 /* Timeout callback that will be called to retry connecting to remote
906 router. This is used by both normal and router server. This will wait
907 before retrying the connecting. The timeout is generated by exponential
908 backoff algorithm. */
910 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
912 SilcServer server = app_context;
913 SilcServerConnection sconn = (SilcServerConnection)context;
914 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
915 SilcServerConfigConnParams *param =
916 (conn->param ? conn->param : &server->config->param);
918 /* Don't retry if we are shutting down. */
919 if (server->server_shutdown) {
920 silc_server_config_unref(&sconn->conn);
921 silc_free(sconn->remote_host);
922 silc_free(sconn->backup_replace_ip);
927 SILC_LOG_INFO(("Retrying connecting to a router"));
929 /* Calculate next timeout */
930 if (sconn->retry_count >= 1) {
931 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
932 if (sconn->retry_timeout > param->reconnect_interval_max)
933 sconn->retry_timeout = param->reconnect_interval_max;
935 sconn->retry_timeout = param->reconnect_interval;
937 sconn->retry_count++;
938 sconn->retry_timeout = sconn->retry_timeout +
939 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
941 /* If we've reached max retry count, give up. */
942 if ((sconn->retry_count > param->reconnect_count) &&
943 !param->reconnect_keep_trying) {
944 SILC_LOG_ERROR(("Could not connect to router, giving up"));
945 silc_server_config_unref(&sconn->conn);
946 silc_free(sconn->remote_host);
947 silc_free(sconn->backup_replace_ip);
952 SILC_LOG_DEBUG(("Retrying connecting to a router in %d seconds",
953 sconn->retry_timeout));
955 /* We will lookup a fresh pointer later */
956 silc_server_config_unref(&sconn->conn);
958 /* Wait one before retrying */
959 silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
960 context, sconn->retry_timeout, 0,
961 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
964 /* Generic routine to use connect to a router. */
966 SILC_TASK_CALLBACK(silc_server_connect_router)
968 SilcServer server = app_context;
969 SilcServerConnection sconn = (SilcServerConnection)context;
970 SilcServerConfigRouter *rconn;
973 /* Don't connect if we are shutting down. */
974 if (server->server_shutdown) {
975 silc_free(sconn->remote_host);
976 silc_free(sconn->backup_replace_ip);
981 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
982 (sconn->backup ? "backup router" : "router"),
983 sconn->remote_host, sconn->remote_port));
985 server->router_connect = time(NULL);
986 rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
989 SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
990 (sconn->backup ? "backup router" : "router"),
991 sconn->remote_host, sconn->remote_port));
992 silc_free(sconn->remote_host);
993 silc_free(sconn->backup_replace_ip);
997 silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
999 /* Connect to remote host */
1000 sock = silc_net_create_connection(
1001 (!server->config->server_info->primary ? NULL :
1002 server->config->server_info->primary->server_ip),
1003 sconn->remote_port, sconn->remote_host);
1005 SILC_LOG_ERROR(("Could not connect to router %s:%d",
1006 sconn->remote_host, sconn->remote_port));
1007 if (!sconn->no_reconnect)
1008 silc_schedule_task_add(server->schedule, 0,
1009 silc_server_connect_to_router_retry,
1010 context, 0, 1, SILC_TASK_TIMEOUT,
1011 SILC_TASK_PRI_NORMAL);
1013 silc_server_config_unref(&sconn->conn);
1014 silc_free(sconn->remote_host);
1015 silc_free(sconn->backup_replace_ip);
1021 /* Continue with key exchange protocol */
1022 silc_server_start_key_exchange(server, sconn, sock);
1025 /* This function connects to our primary router or if we are a router this
1026 establishes all our primary routes. This is called at the start of the
1027 server to do authentication and key exchange with our router - called
1030 SILC_TASK_CALLBACK_GLOBAL(silc_server_connect_to_router)
1032 SilcServer server = (SilcServer)context;
1033 SilcServerConnection sconn;
1034 SilcServerConfigRouter *ptr;
1036 /* Don't connect if we are shutting down. */
1037 if (server->server_shutdown)
1040 SILC_LOG_DEBUG(("We are %s",
1041 (server->server_type == SILC_SERVER ?
1042 "normal server" : server->server_type == SILC_ROUTER ?
1043 "router" : "backup router/normal server")));
1045 if (!server->config->routers) {
1046 /* There wasn't a configured router, we will continue but we don't
1047 have a connection to outside world. We will be standalone server. */
1048 SILC_LOG_DEBUG(("No router(s), we are standalone"));
1049 server->standalone = TRUE;
1053 /* Cancel any possible retry timeouts */
1054 silc_schedule_task_del_by_callback(server->schedule,
1055 silc_server_connect_router);
1056 silc_schedule_task_del_by_callback(server->schedule,
1057 silc_server_connect_to_router_retry);
1059 /* Create the connections to all our routes */
1060 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
1062 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
1063 ptr->backup_router ? "Backup router" : "Router",
1064 ptr->initiator ? "Initiator" : "Responder",
1065 ptr->host, ptr->port));
1067 if (server->server_type == SILC_ROUTER && ptr->backup_router &&
1068 ptr->initiator == FALSE && !server->backup_router &&
1069 !silc_server_config_get_backup_router(server))
1070 server->wait_backup = TRUE;
1072 if (ptr->initiator) {
1073 /* Check whether we are connecting or connected to this host already */
1074 if (silc_server_num_sockets_by_remote(server,
1075 silc_net_is_ip(ptr->host) ?
1077 silc_net_is_ip(ptr->host) ?
1078 NULL : ptr->host, ptr->port,
1079 SILC_SOCKET_TYPE_ROUTER)) {
1080 SILC_LOG_DEBUG(("We are already connected to this router"));
1082 /* If we don't have primary router and this connection is our
1083 primary router we are in desync. Reconnect to the primary. */
1084 if (server->standalone && !server->router) {
1085 SilcServerConfigRouter *primary =
1086 silc_server_config_get_primary_router(server);
1087 if (primary == ptr) {
1088 SilcSocketConnection sock =
1089 silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_ROUTER,
1090 ptr->host, ptr->port);
1092 server->backup_noswitch = TRUE;
1093 if (sock->user_data)
1094 silc_server_free_sock_user_data(server, sock, NULL);
1095 silc_server_disconnect_remote(server, sock, 0, NULL);
1096 server->backup_noswitch = FALSE;
1097 SILC_LOG_DEBUG(("Reconnecting to primary router"));
1108 if (silc_server_num_sockets_by_remote(server,
1109 silc_net_is_ip(ptr->host) ?
1111 silc_net_is_ip(ptr->host) ?
1112 NULL : ptr->host, ptr->port,
1113 SILC_SOCKET_TYPE_UNKNOWN)) {
1114 SILC_LOG_DEBUG(("We are already connecting to this router"));
1118 /* Allocate connection object for hold connection specific stuff. */
1119 sconn = silc_calloc(1, sizeof(*sconn));
1120 sconn->remote_host = strdup(ptr->host);
1121 sconn->remote_port = ptr->port;
1122 sconn->backup = ptr->backup_router;
1123 if (sconn->backup) {
1124 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
1125 sconn->backup_replace_port = ptr->backup_replace_port;
1128 if (!server->router_conn && !sconn->backup)
1129 server->router_conn = sconn;
1131 silc_schedule_task_add(server->schedule, 0,
1132 silc_server_connect_router,
1133 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
1134 SILC_TASK_PRI_NORMAL);
1139 /* Second part of connecting to router(s). Key exchange protocol has been
1140 executed and now we will execute authentication protocol. */
1142 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
1144 SilcProtocol protocol = (SilcProtocol)context;
1145 SilcServerKEInternalContext *ctx =
1146 (SilcServerKEInternalContext *)protocol->context;
1147 SilcServer server = (SilcServer)ctx->server;
1148 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1149 SilcSocketConnection sock = ctx->sock;
1150 SilcServerConnAuthInternalContext *proto_ctx;
1151 SilcServerConfigRouter *conn = NULL;
1153 SILC_LOG_DEBUG(("Start"));
1155 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1156 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1157 /* Error occured during protocol */
1158 silc_protocol_free(protocol);
1159 sock->protocol = NULL;
1160 silc_ske_free_key_material(ctx->keymat);
1162 silc_packet_context_free(ctx->packet);
1164 silc_ske_free(ctx->ske);
1165 silc_free(ctx->dest_id);
1167 silc_server_disconnect_remote(server, sock,
1168 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1170 /* Try reconnecting if configuration wants it */
1171 if (!sconn->no_reconnect) {
1172 silc_schedule_task_add(server->schedule, 0,
1173 silc_server_connect_to_router_retry,
1174 sconn, 0, 1, SILC_TASK_TIMEOUT,
1175 SILC_TASK_PRI_NORMAL);
1179 /* Call completion to indicate error */
1180 if (sconn->callback)
1181 (*sconn->callback)(server, NULL, sconn->callback_context);
1183 silc_server_config_unref(&sconn->conn);
1184 silc_free(sconn->remote_host);
1185 silc_free(sconn->backup_replace_ip);
1190 /* We now have the key material as the result of the key exchange
1191 protocol. Take the key material into use. Free the raw key material
1192 as soon as we've set them into use. */
1193 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1194 ctx->sock, ctx->keymat,
1195 ctx->ske->prop->cipher,
1196 ctx->ske->prop->pkcs,
1197 ctx->ske->prop->hash,
1198 ctx->ske->prop->hmac,
1199 ctx->ske->prop->group,
1201 silc_protocol_free(protocol);
1202 sock->protocol = NULL;
1203 silc_ske_free_key_material(ctx->keymat);
1205 silc_packet_context_free(ctx->packet);
1207 silc_ske_free(ctx->ske);
1208 silc_free(ctx->dest_id);
1210 silc_server_disconnect_remote(server, sock,
1211 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1213 /* Try reconnecting if configuration wants it */
1214 if (!sconn->no_reconnect) {
1215 silc_schedule_task_add(server->schedule, 0,
1216 silc_server_connect_to_router_retry,
1217 sconn, 0, 1, SILC_TASK_TIMEOUT,
1218 SILC_TASK_PRI_NORMAL);
1222 /* Call completion to indicate error */
1223 if (sconn->callback)
1224 (*sconn->callback)(server, NULL, sconn->callback_context);
1226 silc_server_config_unref(&sconn->conn);
1227 silc_free(sconn->remote_host);
1228 silc_free(sconn->backup_replace_ip);
1232 silc_ske_free_key_material(ctx->keymat);
1234 /* Allocate internal context for the authentication protocol. This
1235 is sent as context for the protocol. */
1236 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1237 proto_ctx->server = (void *)server;
1238 proto_ctx->context = (void *)sconn;
1239 proto_ctx->sock = sock;
1240 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1241 proto_ctx->dest_id_type = ctx->dest_id_type;
1242 proto_ctx->dest_id = ctx->dest_id;
1244 /* Resolve the authentication method used in this connection. Check if
1245 we find a match from user configured connections */
1246 if (!sconn->conn.ref_ptr)
1247 conn = silc_server_config_find_router_conn(server, sock->hostname,
1250 conn = sconn->conn.ref_ptr;
1253 /* Match found. Use the configured authentication method. Take only
1254 the passphrase, since for public key auth we automatically use
1255 our local key pair. */
1256 if (conn->passphrase) {
1257 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
1258 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1260 proto_ctx->auth_data = strdup(conn->passphrase);
1261 proto_ctx->auth_data_len = strlen(conn->passphrase);
1262 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
1264 } else if (conn->publickeys) {
1265 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1267 proto_ctx->auth_meth = SILC_AUTH_NONE;
1270 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
1271 sock->hostname, sock->ip, sock->port));
1272 silc_protocol_free(protocol);
1273 sock->protocol = NULL;
1275 silc_packet_context_free(ctx->packet);
1277 silc_ske_free(ctx->ske);
1278 silc_free(ctx->dest_id);
1280 silc_server_config_unref(&sconn->conn);
1281 silc_free(sconn->remote_host);
1282 silc_free(sconn->backup_replace_ip);
1284 silc_server_disconnect_remote(server, sock,
1285 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1289 /* Free old protocol as it is finished now */
1290 silc_protocol_free(protocol);
1292 silc_packet_context_free(ctx->packet);
1294 sock->protocol = NULL;
1296 /* Allocate the authentication protocol. This is allocated here
1297 but we won't start it yet. We will be receiving party of this
1298 protocol thus we will wait that connecting party will make
1299 their first move. */
1300 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1301 &sock->protocol, proto_ctx,
1302 silc_server_connect_to_router_final);
1304 /* Register timeout task. If the protocol is not executed inside
1305 this timelimit the connection will be terminated. */
1306 proto_ctx->timeout_task =
1307 silc_schedule_task_add(server->schedule, sock->sock,
1308 silc_server_timeout_remote,
1310 server->config->conn_auth_timeout, 0,
1314 /* Run the protocol */
1315 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1318 /* Finalizes the connection to router. Registers a server task to the
1319 queue so that we can accept new connections. */
1321 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
1323 SilcProtocol protocol = (SilcProtocol)context;
1324 SilcServerConnAuthInternalContext *ctx =
1325 (SilcServerConnAuthInternalContext *)protocol->context;
1326 SilcServer server = (SilcServer)ctx->server;
1327 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1328 SilcSocketConnection sock = ctx->sock;
1329 SilcServerEntry id_entry = NULL;
1331 unsigned char *id_string;
1333 SilcIDListData idata;
1334 SilcServerConfigRouter *conn = NULL;
1335 SilcServerConfigConnParams *param = NULL;
1337 SILC_LOG_DEBUG(("Start"));
1339 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1340 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1341 /* Error occured during protocol */
1342 silc_free(ctx->dest_id);
1343 sock->protocol = NULL;
1344 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1346 sock->protocol = protocol;
1348 /* Try reconnecting if configuration wants it */
1349 if (!sconn->no_reconnect) {
1350 silc_schedule_task_add(server->schedule, 0,
1351 silc_server_connect_to_router_retry,
1352 sconn, 0, 1, SILC_TASK_TIMEOUT,
1353 SILC_TASK_PRI_NORMAL);
1360 /* Add a task to the queue. This task receives new connections to the
1361 server. This task remains on the queue until the end of the program. */
1362 if (!server->listenning && !sconn->backup) {
1363 silc_schedule_task_add(server->schedule, server->sock,
1364 silc_server_accept_new_connection,
1365 (void *)server, 0, 0,
1367 SILC_TASK_PRI_NORMAL);
1368 server->listenning = TRUE;
1371 /* Send NEW_SERVER packet to the router. We will become registered
1372 to the SILC network after sending this packet. */
1373 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
1374 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1375 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
1376 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1377 silc_buffer_format(packet,
1378 SILC_STR_UI_SHORT(id_len),
1379 SILC_STR_UI_XNSTRING(id_string, id_len),
1380 SILC_STR_UI_SHORT(strlen(server->server_name)),
1381 SILC_STR_UI_XNSTRING(server->server_name,
1382 strlen(server->server_name)),
1385 /* Send the packet */
1386 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
1387 packet->data, packet->len, TRUE);
1388 silc_buffer_free(packet);
1389 silc_free(id_string);
1391 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
1393 /* Check that we do not have this ID already */
1394 id_entry = silc_idlist_find_server_by_id(server->local_list,
1395 ctx->dest_id, TRUE, NULL);
1397 silc_idcache_del_by_context(server->local_list->servers, id_entry);
1399 id_entry = silc_idlist_find_server_by_id(server->global_list,
1400 ctx->dest_id, TRUE, NULL);
1402 silc_idcache_del_by_context(server->global_list->servers, id_entry);
1405 SILC_LOG_DEBUG(("New server id(%s)",
1406 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1408 /* Add the connected router to global server list. Router is sent
1409 as NULL since it's local to us. */
1410 id_entry = silc_idlist_add_server(server->global_list,
1411 strdup(sock->hostname),
1412 SILC_ROUTER, ctx->dest_id, NULL, sock);
1414 silc_free(ctx->dest_id);
1415 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1416 sock->protocol = NULL;
1417 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1419 sock->protocol = protocol;
1423 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1424 silc_free(sock->user_data);
1425 sock->user_data = (void *)id_entry;
1426 sock->type = SILC_SOCKET_TYPE_ROUTER;
1427 idata = (SilcIDListData)sock->user_data;
1428 idata->status |= (SILC_IDLIST_STATUS_REGISTERED |
1429 SILC_IDLIST_STATUS_LOCAL);
1431 conn = sconn->conn.ref_ptr;
1432 param = &server->config->param;
1433 if (conn && conn->param)
1434 param = conn->param;
1436 /* Perform keepalive. */
1437 silc_socket_set_heartbeat(sock, param->keepalive_secs, server,
1438 silc_server_perform_heartbeat,
1441 /* Register re-key timeout */
1442 idata->rekey->timeout = param->key_exchange_rekey;
1443 silc_schedule_task_add(server->schedule, sock->sock,
1444 silc_server_rekey_callback,
1445 (void *)sock, idata->rekey->timeout, 0,
1446 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1448 if (!sconn->backup) {
1449 /* Mark this router our primary router if we're still standalone */
1450 if (server->standalone) {
1451 SILC_LOG_DEBUG(("This connection is our primary router"));
1452 server->id_entry->router = id_entry;
1453 server->router = id_entry;
1454 server->router->server_type = SILC_ROUTER;
1455 server->standalone = FALSE;
1456 server->backup_primary = FALSE;
1458 /* Announce data if we are not backup router (unless not as primary
1459 currently). Backup router announces later at the end of
1460 resuming protocol. */
1461 if (server->backup_router && server->server_type == SILC_ROUTER) {
1462 SILC_LOG_DEBUG(("Announce data after resume protocol"));
1464 /* If we are router then announce our possible servers. Backup
1465 router announces also global servers. */
1466 if (server->server_type == SILC_ROUTER)
1467 silc_server_announce_servers(server,
1468 server->backup_router ? TRUE : FALSE,
1469 0, SILC_PRIMARY_ROUTE(server));
1471 /* Announce our clients and channels to the router */
1472 silc_server_announce_clients(server, 0, SILC_PRIMARY_ROUTE(server));
1473 silc_server_announce_channels(server, 0, SILC_PRIMARY_ROUTE(server));
1476 /* If we are backup router then this primary router is whom we are
1478 if (server->server_type == SILC_BACKUP_ROUTER)
1479 silc_server_backup_add(server, server->id_entry, sock->ip,
1480 sconn->remote_port, TRUE);
1483 /* Add this server to be our backup router */
1484 id_entry->server_type = SILC_BACKUP_ROUTER;
1485 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1486 sconn->backup_replace_port, FALSE);
1489 sock->protocol = NULL;
1492 /* Call the completion callback to indicate that we've connected to
1494 if (sconn && sconn->callback)
1495 (*sconn->callback)(server, id_entry, sconn->callback_context);
1497 /* Free the temporary connection data context */
1499 silc_server_config_unref(&sconn->conn);
1500 silc_free(sconn->remote_host);
1501 silc_free(sconn->backup_replace_ip);
1504 if (sconn == server->router_conn)
1505 server->router_conn = NULL;
1508 /* Free the protocol object */
1509 if (sock->protocol == protocol)
1510 sock->protocol = NULL;
1511 silc_protocol_free(protocol);
1513 silc_packet_context_free(ctx->packet);
1515 silc_ske_free(ctx->ske);
1516 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1517 silc_free(ctx->auth_data);
1521 /* Host lookup callback that is called after the incoming connection's
1522 IP and FQDN lookup is performed. This will actually check the acceptance
1523 of the incoming connection and will register the key exchange protocol
1524 for this connection. */
1527 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1530 SilcServerKEInternalContext *proto_ctx =
1531 (SilcServerKEInternalContext *)context;
1532 SilcServer server = (SilcServer)proto_ctx->server;
1533 SilcServerConfigClient *cconfig = NULL;
1534 SilcServerConfigServer *sconfig = NULL;
1535 SilcServerConfigRouter *rconfig = NULL;
1536 SilcServerConfigDeny *deny;
1539 /* Check whether we could resolve both IP and FQDN. */
1540 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1541 server->config->require_reverse_lookup)) {
1542 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1543 sock->hostname ? sock->hostname :
1544 sock->ip ? sock->ip : ""));
1545 server->stat.conn_failures++;
1546 silc_server_disconnect_remote(server, sock,
1547 SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
1548 "Unknown host or IP");
1549 silc_free(proto_ctx);
1553 /* Register the connection for network input and output. This sets
1554 that scheduler will listen for incoming packets for this connection
1555 and sets that outgoing packets may be sent to this connection as well.
1556 However, this doesn't set the scheduler for outgoing traffic, it
1557 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1558 later when outgoing data is available. */
1559 context = (void *)server;
1560 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1562 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1565 /* Listenning port */
1566 if (!server->sockets[(SilcUInt32)proto_ctx->context]) {
1567 silc_server_disconnect_remote(server, sock,
1568 SILC_STATUS_ERR_RESOURCE_LIMIT,
1569 "Connection refused");
1570 server->stat.conn_failures++;
1571 silc_free(proto_ctx);
1574 port = server->sockets[(SilcUInt32)proto_ctx->context]->port;
1576 /* Check whether this connection is denied to connect to us. */
1577 deny = silc_server_config_find_denied(server, sock->ip);
1579 deny = silc_server_config_find_denied(server, sock->hostname);
1581 /* The connection is denied */
1582 SILC_LOG_INFO(("Connection %s (%s) is denied",
1583 sock->hostname, sock->ip));
1584 silc_server_disconnect_remote(server, sock,
1585 SILC_STATUS_ERR_BANNED_FROM_SERVER,
1587 server->stat.conn_failures++;
1588 silc_free(proto_ctx);
1592 /* Check whether we have configured this sort of connection at all. We
1593 have to check all configurations since we don't know what type of
1594 connection this is. */
1595 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1596 cconfig = silc_server_config_find_client(server, sock->hostname);
1597 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1598 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1599 if (server->server_type == SILC_ROUTER) {
1600 if (!(rconfig = silc_server_config_find_router_conn(server,
1601 sock->ip, sock->port)))
1602 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1605 if (!cconfig && !sconfig && !rconfig) {
1606 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1608 silc_server_disconnect_remote(server, sock,
1609 SILC_STATUS_ERR_BANNED_FROM_SERVER, NULL);
1610 server->stat.conn_failures++;
1611 silc_free(proto_ctx);
1615 /* The connection is allowed */
1617 /* Set internal context for key exchange protocol. This is
1618 sent as context for the protocol. */
1619 proto_ctx->sock = sock;
1620 proto_ctx->rng = server->rng;
1621 proto_ctx->responder = TRUE;
1622 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1623 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1624 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1626 /* Take flags for key exchange. Since we do not know what type of connection
1627 this is, we go through all found configurations and use the global ones
1628 as well. This will result always into strictest key exchange flags. */
1629 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1630 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1631 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1632 if (server->config->param.key_exchange_pfs)
1633 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1635 /* Prepare the connection for key exchange protocol. We allocate the
1636 protocol but will not start it yet. The connector will be the
1637 initiator of the protocol thus we will wait for initiation from
1638 there before we start the protocol. */
1639 server->stat.auth_attempts++;
1640 SILC_LOG_DEBUG(("Starting key exchange protocol"));
1641 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1642 &sock->protocol, proto_ctx,
1643 silc_server_accept_new_connection_second);
1645 /* Register a timeout task that will be executed if the connector
1646 will not start the key exchange protocol within specified timeout
1647 and the connection will be closed. */
1648 proto_ctx->timeout_task =
1649 silc_schedule_task_add(server->schedule, sock->sock,
1650 silc_server_timeout_remote,
1652 server->config->key_exchange_timeout, 0,
1657 /* Accepts new connections to the server. Accepting new connections are
1658 done in three parts to make it async. */
1660 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1662 SilcServer server = (SilcServer)context;
1663 SilcSocketConnection newsocket;
1664 SilcServerKEInternalContext *proto_ctx;
1667 SILC_LOG_DEBUG(("Accepting new connection"));
1669 server->stat.conn_attempts++;
1671 sock = silc_net_accept_connection(fd);
1673 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1674 server->stat.conn_failures++;
1678 /* Check for maximum allowed connections */
1679 if (sock > server->config->param.connections_max) {
1680 SILC_LOG_ERROR(("Refusing connection, server is full"));
1681 server->stat.conn_failures++;
1682 silc_net_close_connection(sock);
1686 /* Set socket options */
1687 silc_net_set_socket_nonblock(sock);
1688 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1690 /* We don't create a ID yet, since we don't know what type of connection
1691 this is yet. But, we do add the connection to the socket table. */
1692 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1693 server->sockets[sock] = newsocket;
1695 /* Perform asynchronous host lookup. This will lookup the IP and the
1696 FQDN of the remote connection. After the lookup is done the connection
1697 is accepted further. */
1698 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1699 proto_ctx->server = server;
1700 proto_ctx->context = (void *)fd;
1701 silc_socket_host_lookup(newsocket, TRUE,
1702 silc_server_accept_new_connection_lookup,
1703 (void *)proto_ctx, server->schedule);
1706 /* Second part of accepting new connection. Key exchange protocol has been
1707 performed and now it is time to do little connection authentication
1708 protocol to figure out whether this connection is client or server
1709 and whether it has right to access this server (especially server
1710 connections needs to be authenticated). */
1712 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1714 SilcProtocol protocol = (SilcProtocol)context;
1715 SilcServerKEInternalContext *ctx =
1716 (SilcServerKEInternalContext *)protocol->context;
1717 SilcServer server = (SilcServer)ctx->server;
1718 SilcSocketConnection sock = ctx->sock;
1719 SilcServerConnAuthInternalContext *proto_ctx;
1721 SILC_LOG_DEBUG(("Start"));
1723 if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1724 (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1725 /* Error occured during protocol */
1726 SILC_LOG_DEBUG(("Error in key exchange protocol"));
1727 silc_protocol_free(protocol);
1728 sock->protocol = NULL;
1729 silc_ske_free_key_material(ctx->keymat);
1731 silc_packet_context_free(ctx->packet);
1733 silc_ske_free(ctx->ske);
1734 silc_free(ctx->dest_id);
1735 silc_server_config_unref(&ctx->cconfig);
1736 silc_server_config_unref(&ctx->sconfig);
1737 silc_server_config_unref(&ctx->rconfig);
1740 if (!SILC_IS_DISCONNECTING(sock)) {
1741 SILC_LOG_INFO(("Key exchange failed for %s:%d [%s]", sock->hostname,
1743 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1744 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1745 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1747 silc_server_disconnect_remote(server, sock,
1748 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
1752 server->stat.auth_failures++;
1756 /* We now have the key material as the result of the key exchange
1757 protocol. Take the key material into use. Free the raw key material
1758 as soon as we've set them into use. */
1759 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1760 ctx->sock, ctx->keymat,
1761 ctx->ske->prop->cipher,
1762 ctx->ske->prop->pkcs,
1763 ctx->ske->prop->hash,
1764 ctx->ske->prop->hmac,
1765 ctx->ske->prop->group,
1767 SILC_LOG_ERROR(("Error setting key material in use"));
1768 silc_protocol_free(protocol);
1769 sock->protocol = NULL;
1770 silc_ske_free_key_material(ctx->keymat);
1772 silc_packet_context_free(ctx->packet);
1774 silc_ske_free(ctx->ske);
1775 silc_free(ctx->dest_id);
1776 silc_server_config_unref(&ctx->cconfig);
1777 silc_server_config_unref(&ctx->sconfig);
1778 silc_server_config_unref(&ctx->rconfig);
1780 silc_server_disconnect_remote(server, sock,
1781 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1782 server->stat.auth_failures++;
1785 silc_ske_free_key_material(ctx->keymat);
1787 /* Allocate internal context for the authentication protocol. This
1788 is sent as context for the protocol. */
1789 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1790 proto_ctx->server = (void *)server;
1791 proto_ctx->sock = sock;
1792 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1793 proto_ctx->responder = TRUE;
1794 proto_ctx->dest_id_type = ctx->dest_id_type;
1795 proto_ctx->dest_id = ctx->dest_id;
1796 proto_ctx->cconfig = ctx->cconfig;
1797 proto_ctx->sconfig = ctx->sconfig;
1798 proto_ctx->rconfig = ctx->rconfig;
1800 /* Free old protocol as it is finished now */
1801 silc_protocol_free(protocol);
1803 silc_packet_context_free(ctx->packet);
1805 sock->protocol = NULL;
1807 /* Allocate the authentication protocol. This is allocated here
1808 but we won't start it yet. We will be receiving party of this
1809 protocol thus we will wait that connecting party will make
1810 their first move. */
1811 SILC_LOG_DEBUG(("Starting connection authentication protocol"));
1812 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1813 &sock->protocol, proto_ctx,
1814 silc_server_accept_new_connection_final);
1816 /* Register timeout task. If the protocol is not executed inside
1817 this timelimit the connection will be terminated. */
1818 proto_ctx->timeout_task =
1819 silc_schedule_task_add(server->schedule, sock->sock,
1820 silc_server_timeout_remote,
1822 server->config->conn_auth_timeout, 0,
1827 /* After this is called, server don't wait for backup router anymore.
1828 This gets called automatically even after we have backup router
1829 connection established. */
1831 SILC_TASK_CALLBACK(silc_server_backup_router_wait)
1833 SilcServer server = context;
1834 server->wait_backup = FALSE;
1837 /* Final part of accepting new connection. The connection has now
1838 been authenticated and keys has been exchanged. We also know whether
1839 this is client or server connection. */
1841 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1843 SilcProtocol protocol = (SilcProtocol)context;
1844 SilcServerConnAuthInternalContext *ctx =
1845 (SilcServerConnAuthInternalContext *)protocol->context;
1846 SilcServer server = (SilcServer)ctx->server;
1847 SilcSocketConnection sock = ctx->sock;
1848 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1850 SilcServerConfigConnParams *param = &server->config->param;
1852 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1853 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1854 /* Error occured during protocol */
1855 SILC_LOG_DEBUG(("Error during authentication protocol"));
1856 silc_protocol_free(protocol);
1857 sock->protocol = NULL;
1859 silc_packet_context_free(ctx->packet);
1861 silc_ske_free(ctx->ske);
1862 silc_free(ctx->dest_id);
1863 silc_server_config_unref(&ctx->cconfig);
1864 silc_server_config_unref(&ctx->sconfig);
1865 silc_server_config_unref(&ctx->rconfig);
1868 if (!SILC_IS_DISCONNECTING(sock)) {
1869 SILC_LOG_INFO(("Authentication failed for %s:%d [%s]", sock->hostname,
1871 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1872 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1873 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1875 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1878 server->stat.auth_failures++;
1882 entry->data.last_receive = time(NULL);
1884 switch (ctx->conn_type) {
1885 case SILC_SOCKET_TYPE_CLIENT:
1887 SilcClientEntry client;
1888 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1890 /* Verify whether this connection is after all allowed to connect */
1891 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1892 &server->config->param,
1893 conn->param, ctx->ske)) {
1894 server->stat.auth_failures++;
1898 /* If we are primary router and we have backup router configured
1899 but it has not connected to use yet, do not accept any other
1901 if (server->wait_backup && server->server_type == SILC_ROUTER &&
1902 !server->backup_router) {
1903 SilcServerConfigRouter *router;
1904 router = silc_server_config_get_backup_router(server);
1905 if (router && strcmp(server->config->server_info->primary->server_ip,
1907 silc_server_find_socket_by_host(server,
1908 SILC_SOCKET_TYPE_SERVER,
1909 router->backup_replace_ip, 0)) {
1910 SILC_LOG_INFO(("Will not accept connections because we do "
1911 "not have backup router connection established"));
1912 sock->protocol = NULL;
1913 silc_server_disconnect_remote(server, sock,
1914 SILC_STATUS_ERR_PERM_DENIED,
1915 "We do not have connection to backup "
1916 "router established, try later");
1917 silc_free(sock->user_data);
1918 server->stat.auth_failures++;
1920 /* From here on, wait 10 seconds for the backup router to appear. */
1921 silc_schedule_task_add(server->schedule, 0,
1922 silc_server_backup_router_wait,
1923 (void *)server, 10, 0,
1924 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1929 SILC_LOG_DEBUG(("Remote host is client"));
1930 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1933 /* Add the client to the client ID cache. The nickname and Client ID
1934 and other information is created after we have received NEW_CLIENT
1935 packet from client. */
1936 client = silc_idlist_add_client(server->local_list,
1937 NULL, NULL, NULL, NULL, NULL, sock, 0);
1939 SILC_LOG_ERROR(("Could not add new client to cache"));
1940 silc_free(sock->user_data);
1941 sock->protocol = NULL;
1942 silc_server_disconnect_remote(server, sock,
1943 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1944 server->stat.auth_failures++;
1947 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
1950 server->stat.my_clients++;
1951 server->stat.clients++;
1952 server->stat.cell_clients++;
1954 /* Get connection parameters */
1956 param = conn->param;
1958 if (!param->keepalive_secs)
1959 param->keepalive_secs = server->config->param.keepalive_secs;
1961 if (!param->qos && server->config->param.qos) {
1962 param->qos = server->config->param.qos;
1963 param->qos_rate_limit = server->config->param.qos_rate_limit;
1964 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
1965 param->qos_limit_sec = server->config->param.qos_limit_sec;
1966 param->qos_limit_usec = server->config->param.qos_limit_usec;
1969 /* Check if to be anonymous connection */
1970 if (param->anonymous)
1971 client->mode |= SILC_UMODE_ANONYMOUS;
1974 /* Add public key to hash list (for whois using attributes) */
1975 silc_hash_table_add(server->pk_hash,
1976 entry->data.public_key, client);
1978 id_entry = (void *)client;
1981 case SILC_SOCKET_TYPE_SERVER:
1982 case SILC_SOCKET_TYPE_ROUTER:
1984 SilcServerEntry new_server;
1985 bool initiator = FALSE;
1986 bool backup_local = FALSE;
1987 bool backup_router = FALSE;
1988 char *backup_replace_ip = NULL;
1989 SilcUInt16 backup_replace_port = 0;
1990 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1991 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1993 /* If we are backup router and this is incoming server connection
1994 and we do not have connection to primary router, do not allow
1996 if (server->server_type == SILC_BACKUP_ROUTER &&
1997 ctx->conn_type == SILC_SOCKET_TYPE_SERVER &&
1998 !SILC_PRIMARY_ROUTE(server)) {
1999 SILC_LOG_INFO(("Will not accept server connection because we do "
2000 "not have primary router connection established"));
2001 sock->protocol = NULL;
2002 silc_server_disconnect_remote(server, sock,
2003 SILC_STATUS_ERR_PERM_DENIED,
2004 "We do not have connection to primary "
2005 "router established, try later");
2006 silc_free(sock->user_data);
2007 server->stat.auth_failures++;
2011 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
2012 /* Verify whether this connection is after all allowed to connect */
2013 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
2014 &server->config->param,
2015 rconn ? rconn->param : NULL,
2017 silc_free(sock->user_data);
2018 server->stat.auth_failures++;
2024 param = rconn->param;
2026 if (!param->keepalive_secs)
2027 param->keepalive_secs = server->config->param.keepalive_secs;
2029 if (!param->qos && server->config->param.qos) {
2030 param->qos = server->config->param.qos;
2031 param->qos_rate_limit = server->config->param.qos_rate_limit;
2032 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
2033 param->qos_limit_sec = server->config->param.qos_limit_sec;
2034 param->qos_limit_usec = server->config->param.qos_limit_usec;
2038 initiator = rconn->initiator;
2039 backup_local = rconn->backup_local;
2040 backup_router = rconn->backup_router;
2041 backup_replace_ip = rconn->backup_replace_ip;
2042 backup_replace_port = rconn->backup_replace_port;
2046 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
2047 /* Verify whether this connection is after all allowed to connect */
2048 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
2049 &server->config->param,
2050 sconn ? sconn->param : NULL,
2052 silc_free(sock->user_data);
2053 server->stat.auth_failures++;
2058 param = sconn->param;
2060 if (!param->keepalive_secs)
2061 param->keepalive_secs = server->config->param.keepalive_secs;
2063 if (!param->qos && server->config->param.qos) {
2064 param->qos = server->config->param.qos;
2065 param->qos_rate_limit = server->config->param.qos_rate_limit;
2066 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
2067 param->qos_limit_sec = server->config->param.qos_limit_sec;
2068 param->qos_limit_usec = server->config->param.qos_limit_usec;
2072 backup_router = sconn->backup_router;
2076 /* If we are primary router and we have backup router configured
2077 but it has not connected to use yet, do not accept any other
2079 if (server->wait_backup && server->server_type == SILC_ROUTER &&
2080 !server->backup_router && !backup_router) {
2081 SilcServerConfigRouter *router;
2082 router = silc_server_config_get_backup_router(server);
2083 if (router && strcmp(server->config->server_info->primary->server_ip,
2085 silc_server_find_socket_by_host(server,
2086 SILC_SOCKET_TYPE_SERVER,
2087 router->backup_replace_ip, 0)) {
2088 SILC_LOG_INFO(("Will not accept connections because we do "
2089 "not have backup router connection established"));
2090 sock->protocol = NULL;
2091 silc_server_disconnect_remote(server, sock,
2092 SILC_STATUS_ERR_PERM_DENIED,
2093 "We do not have connection to backup "
2094 "router established, try later");
2095 silc_free(sock->user_data);
2096 server->stat.auth_failures++;
2098 /* From here on, wait 10 seconds for the backup router to appear. */
2099 silc_schedule_task_add(server->schedule, 0,
2100 silc_server_backup_router_wait,
2101 (void *)server, 10, 0,
2102 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2107 SILC_LOG_DEBUG(("Remote host is %s",
2108 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2109 "server" : (backup_router ?
2110 "backup router" : "router")));
2111 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
2112 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2113 "server" : (backup_router ?
2114 "backup router" : "router")));
2116 /* Add the server into server cache. The server name and Server ID
2117 is updated after we have received NEW_SERVER packet from the
2118 server. We mark ourselves as router for this server if we really
2121 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2122 server->local_list : (backup_router ?
2123 server->local_list :
2124 server->global_list)),
2126 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2127 SILC_SERVER : SILC_ROUTER),
2129 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2130 server->id_entry : (backup_router ?
2131 server->id_entry : NULL)),
2134 SILC_LOG_ERROR(("Could not add new server to cache"));
2135 silc_free(sock->user_data);
2136 sock->protocol = NULL;
2137 silc_server_disconnect_remote(server, sock,
2138 SILC_STATUS_ERR_AUTH_FAILED, NULL);
2139 server->stat.auth_failures++;
2142 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
2144 id_entry = (void *)new_server;
2146 /* If the incoming connection is router and marked as backup router
2147 then add it to be one of our backups */
2148 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
2149 /* Change it back to SERVER type since that's what it really is. */
2151 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
2152 new_server->server_type = SILC_BACKUP_ROUTER;
2154 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
2155 ("Backup router %s is now online",
2158 /* Remove the backup waiting with timeout */
2159 silc_schedule_task_add(server->schedule, 0,
2160 silc_server_backup_router_wait,
2161 (void *)server, 5, 0,
2162 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2166 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
2167 server->stat.my_servers++;
2169 server->stat.my_routers++;
2170 server->stat.routers++;
2172 server->stat.servers++;
2174 /* Check whether this connection is to be our primary router connection
2175 if we do not already have the primary route. */
2176 if (!backup_router &&
2177 server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
2178 if (silc_server_config_is_primary_route(server) && !initiator)
2181 SILC_LOG_DEBUG(("We are not standalone server anymore"));
2182 server->standalone = FALSE;
2183 if (!server->id_entry->router) {
2184 server->id_entry->router = id_entry;
2185 server->router = id_entry;
2196 sock->type = ctx->conn_type;
2198 /* Add the common data structure to the ID entry. */
2199 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
2201 /* Add to sockets internal pointer for fast referencing */
2202 silc_free(sock->user_data);
2203 sock->user_data = id_entry;
2205 /* Connection has been fully established now. Everything is ok. */
2206 SILC_LOG_DEBUG(("New connection authenticated"));
2208 /* Perform keepalive. */
2209 if (param->keepalive_secs)
2210 silc_socket_set_heartbeat(sock, param->keepalive_secs, server,
2211 silc_server_perform_heartbeat,
2214 /* Perform Quality of Service */
2216 silc_socket_set_qos(sock, param->qos_rate_limit, param->qos_bytes_limit,
2217 param->qos_limit_sec, param->qos_limit_usec,
2221 if (sock->protocol == protocol)
2222 silc_protocol_free(protocol);
2224 silc_packet_context_free(ctx->packet);
2226 silc_ske_free(ctx->ske);
2227 silc_free(ctx->dest_id);
2228 silc_server_config_unref(&ctx->cconfig);
2229 silc_server_config_unref(&ctx->sconfig);
2230 silc_server_config_unref(&ctx->rconfig);
2232 sock->protocol = NULL;
2235 /* This function is used to read packets from network and send packets to
2236 network. This is usually a generic task. */
2238 SILC_TASK_CALLBACK(silc_server_packet_process)
2240 SilcServer server = (SilcServer)context;
2241 SilcSocketConnection sock = server->sockets[fd];
2242 SilcIDListData idata;
2243 SilcCipher cipher = NULL;
2244 SilcHmac hmac = NULL;
2245 SilcUInt32 sequence = 0;
2246 bool local_is_router;
2250 SILC_LOG_DEBUG(("Unknown socket connection"));
2254 /* Packet sending */
2256 if (type == SILC_TASK_WRITE) {
2257 /* Do not send data to disconnected connection */
2258 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2259 SILC_LOG_DEBUG(("Disconnected socket connection, cannot send"));
2260 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
2261 SILC_UNSET_OUTBUF_PENDING(sock);
2262 silc_buffer_clear(sock->outbuf);
2266 server->stat.packets_sent++;
2268 /* Send the packet */
2269 ret = silc_packet_send(sock, TRUE);
2271 /* If returned -2 could not write to connection now, will do
2276 /* The packet has been sent and now it is time to set the connection
2277 back to only for input. When there is again some outgoing data
2278 available for this connection it will be set for output as well.
2279 This call clears the output setting and sets it only for input. */
2280 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
2281 SILC_UNSET_OUTBUF_PENDING(sock);
2282 silc_buffer_clear(sock->outbuf);
2285 SILC_LOG_ERROR(("Error sending packet to connection "
2286 "%s:%d [%s]", sock->hostname, sock->port,
2287 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2288 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2289 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2292 if (sock->user_data)
2293 silc_server_free_sock_user_data(server, sock, NULL);
2294 SILC_SET_DISCONNECTING(sock);
2295 silc_server_close_connection(server, sock);
2300 /* Packet receiving */
2302 /* Read some data from connection */
2303 ret = silc_packet_receive(sock);
2307 SILC_LOG_ERROR(("Error receiving packet from connection "
2308 "%s:%d [%s] %s", sock->hostname, sock->port,
2309 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2310 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2311 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2312 "Router"), strerror(errno)));
2314 if (sock->user_data)
2315 silc_server_free_sock_user_data(server, sock, NULL);
2316 SILC_SET_DISCONNECTING(sock);
2317 silc_server_close_connection(server, sock);
2324 SILC_LOG_DEBUG(("Read EOF"));
2326 /* If connection is disconnecting already we will finally
2327 close the connection */
2328 if (SILC_IS_DISCONNECTING(sock)) {
2329 if (sock->user_data)
2330 silc_server_free_sock_user_data(server, sock, NULL);
2331 silc_server_close_connection(server, sock);
2335 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
2337 if (sock->user_data) {
2340 /* If backup disconnected then mark that resuming willl not be allowed */
2341 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2342 sock->type == SILC_SOCKET_TYPE_SERVER && sock->user_data) {
2343 SilcServerEntry server_entry = sock->user_data;
2344 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2345 server->backup_closed = TRUE;
2348 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
2349 silc_server_free_sock_user_data(server, sock, tmp);
2351 silc_server_free_sock_user_data(server, sock, NULL);
2352 } else if (server->router_conn && server->router_conn->sock == sock &&
2353 !server->router && server->standalone) {
2354 silc_server_create_connections(server);
2357 SILC_SET_DISCONNECTING(sock);
2358 silc_server_close_connection(server, sock);
2362 /* If connection is disconnecting or disconnected we will ignore
2364 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2365 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
2369 /* Get keys and stuff from ID entry */
2370 idata = (SilcIDListData)sock->user_data;
2372 cipher = idata->receive_key;
2373 hmac = idata->hmac_receive;
2374 sequence = idata->psn_receive;
2377 /* Then, process the packet. This will call the parser that will then
2378 decrypt and parse the packet. */
2380 local_is_router = (server->server_type == SILC_ROUTER);
2382 /* If socket connection is our primary, we are backup and we are doing
2383 backup resuming, we won't process the packet as being a router
2384 (affects channel message decryption). */
2385 if (server->backup_router && SILC_SERVER_IS_BACKUP(sock) &&
2386 SILC_PRIMARY_ROUTE(server) == sock)
2387 local_is_router = FALSE;
2389 ret = silc_packet_receive_process(sock, local_is_router,
2390 cipher, hmac, sequence,
2391 silc_server_packet_parse, server);
2393 /* If processing failed the connection is closed. */
2395 /* On packet processing errors we may close our primary router
2396 connection but won't become primary router if we are the backup
2397 since this is local error condition. */
2398 if (SILC_PRIMARY_ROUTE(server) == sock && server->backup_router)
2399 server->backup_noswitch = TRUE;
2401 if (sock->user_data)
2402 silc_server_free_sock_user_data(server, sock, NULL);
2403 SILC_SET_DISCONNECTING(sock);
2404 silc_server_close_connection(server, sock);
2408 /* Parses whole packet, received earlier. */
2410 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
2412 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
2413 SilcServer server = (SilcServer)parse_ctx->context;
2414 SilcSocketConnection sock = parse_ctx->sock;
2415 SilcPacketContext *packet = parse_ctx->packet;
2416 SilcIDListData idata = (SilcIDListData)sock->user_data;
2419 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2420 SILC_LOG_DEBUG(("Connection is disconnected"));
2424 server->stat.packets_received++;
2426 /* Parse the packet */
2427 if (parse_ctx->normal)
2428 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
2430 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
2432 /* If entry is disabled ignore what we got. */
2433 if (idata && idata->status & SILC_IDLIST_STATUS_DISABLED &&
2434 ret != SILC_PACKET_HEARTBEAT && ret != SILC_PACKET_RESUME_ROUTER &&
2435 ret != SILC_PACKET_REKEY && ret != SILC_PACKET_REKEY_DONE) {
2436 SILC_LOG_DEBUG(("Connection is disabled"));
2440 if (ret == SILC_PACKET_NONE) {
2441 SILC_LOG_DEBUG(("Error parsing packet"));
2445 /* Check that the the current client ID is same as in the client's packet. */
2446 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
2447 SilcClientEntry client = (SilcClientEntry)sock->user_data;
2448 if (client && client->id && packet->src_id) {
2449 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
2450 packet->src_id_type);
2451 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
2453 SILC_LOG_DEBUG(("Packet source is not same as sender"));
2460 if (server->server_type == SILC_ROUTER) {
2461 /* Route the packet if it is not destined to us. Other ID types but
2462 server are handled separately after processing them. */
2463 if (packet->dst_id && !(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
2464 packet->dst_id_type == SILC_ID_SERVER &&
2465 sock->type != SILC_SOCKET_TYPE_CLIENT &&
2466 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
2468 /* Route the packet to fastest route for the destination ID */
2469 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
2470 packet->dst_id_type);
2473 silc_server_packet_route(server,
2474 silc_server_route_get(server, id,
2475 packet->dst_id_type),
2482 /* Parse the incoming packet type */
2483 silc_server_packet_parse_type(server, sock, packet);
2485 /* Broadcast packet if it is marked as broadcast packet and it is
2486 originated from router and we are router. */
2487 if (server->server_type == SILC_ROUTER &&
2488 sock->type == SILC_SOCKET_TYPE_ROUTER &&
2489 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
2490 /* Broadcast to our primary route */
2491 silc_server_packet_broadcast(server, SILC_PRIMARY_ROUTE(server), packet);
2493 /* If we have backup routers then we need to feed all broadcast
2494 data to those servers. */
2495 silc_server_backup_broadcast(server, sock, packet);
2499 silc_packet_context_free(packet);
2500 silc_free(parse_ctx);
2503 /* Parser callback called by silc_packet_receive_process. This merely
2504 registers timeout that will handle the actual parsing when appropriate. */
2506 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
2509 SilcServer server = (SilcServer)context;
2510 SilcSocketConnection sock = parser_context->sock;
2511 SilcIDListData idata = (SilcIDListData)sock->user_data;
2515 idata->psn_receive = parser_context->packet->sequence + 1;
2517 /* If protocol for this connection is key exchange or rekey then we'll
2518 process all packets synchronously, since there might be packets in
2519 queue that we are not able to decrypt without first processing the
2520 packets before them. */
2521 if (sock->protocol && sock->protocol->protocol &&
2522 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2523 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2524 silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2527 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2528 SILC_LOG_DEBUG(("Connection is disconnected"));
2532 /* Reprocess data since we'll return FALSE here. This is because
2533 the idata->receive_key might have become valid in the last packet
2534 and we want to call this processor with valid cipher. */
2536 ret = silc_packet_receive_process(
2537 sock, server->server_type == SILC_ROUTER,
2539 idata->hmac_receive, idata->psn_receive,
2540 silc_server_packet_parse, server);
2542 ret = silc_packet_receive_process(
2543 sock, server->server_type == SILC_ROUTER,
2545 silc_server_packet_parse, server);
2548 /* On packet processing errors we may close our primary router
2549 connection but won't become primary router if we are the backup
2550 since this is local error condition. */
2551 if (SILC_PRIMARY_ROUTE(server) == sock && server->backup_router)
2552 server->backup_noswitch = TRUE;
2554 if (sock->user_data)
2555 silc_server_free_sock_user_data(server, sock, NULL);
2556 SILC_SET_DISCONNECTING(sock);
2557 silc_server_close_connection(server, sock);
2563 switch (sock->type) {
2564 case SILC_SOCKET_TYPE_UNKNOWN:
2565 case SILC_SOCKET_TYPE_CLIENT:
2566 /* Parse the packet with timeout */
2567 silc_schedule_task_add(server->schedule, sock->sock,
2568 silc_server_packet_parse_real,
2569 (void *)parser_context, 0, 100000,
2571 SILC_TASK_PRI_NORMAL);
2573 case SILC_SOCKET_TYPE_SERVER:
2574 case SILC_SOCKET_TYPE_ROUTER:
2575 /* Packets from servers are parsed immediately */
2576 silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2584 /* Parses the packet type and calls what ever routines the packet type
2585 requires. This is done for all incoming packets. */
2587 void silc_server_packet_parse_type(SilcServer server,
2588 SilcSocketConnection sock,
2589 SilcPacketContext *packet)
2591 SilcPacketType type = packet->type;
2592 SilcIDListData idata = (SilcIDListData)sock->user_data;
2594 SILC_LOG_DEBUG(("Received %s packet [flags %d]",
2595 silc_get_packet_name(type), packet->flags));
2597 /* Parse the packet type */
2599 case SILC_PACKET_DISCONNECT:
2602 char *message = NULL;
2604 if (packet->flags & SILC_PACKET_FLAG_LIST)
2606 if (packet->buffer->len < 1)
2609 status = (SilcStatus)packet->buffer->data[0];
2610 if (packet->buffer->len > 1 &&
2611 silc_utf8_valid(packet->buffer->data + 1, packet->buffer->len - 1))
2612 message = silc_memdup(packet->buffer->data + 1,
2613 packet->buffer->len - 1);
2615 SILC_LOG_INFO(("Disconnected by %s (%s): %s (%d) %s",
2616 sock->ip, sock->hostname,
2617 silc_get_status_message(status), status,
2618 message ? message : ""));
2621 /* Do not switch to backup in case of error */
2622 server->backup_noswitch = (status == SILC_STATUS_OK ? FALSE : TRUE);
2624 /* If backup disconnected then mark that resuming willl not be allowed */
2625 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2626 sock->type == SILC_SOCKET_TYPE_SERVER && sock->user_data) {
2627 SilcServerEntry server_entry = sock->user_data;
2628 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2629 server->backup_closed = TRUE;
2632 /* Handle the disconnection from our end too */
2633 if (sock->user_data && SILC_IS_LOCAL(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);
2637 server->backup_noswitch = FALSE;
2641 case SILC_PACKET_SUCCESS:
2643 * Success received for something. For now we can have only
2644 * one protocol for connection executing at once hence this
2645 * success message is for whatever protocol is executing currently.
2647 if (packet->flags & SILC_PACKET_FLAG_LIST)
2650 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2653 case SILC_PACKET_FAILURE:
2655 * Failure received for something. For now we can have only
2656 * one protocol for connection executing at once hence this
2657 * failure message is for whatever protocol is executing currently.
2659 if (packet->flags & SILC_PACKET_FLAG_LIST)
2662 /* Check for failure START_USE from backup router */
2663 if (server->server_type == SILC_SERVER &&
2664 server->backup_primary && packet->buffer->len == 4) {
2666 SILC_GET32_MSB(type, packet->buffer->data);
2667 if (type == SILC_SERVER_BACKUP_START_USE) {
2668 /* Attempt to reconnect to primary */
2669 SILC_LOG_DEBUG(("Received failed START_USE from backup %s", sock->ip));
2671 /* Default action is to disconnect from backup and reconnect to
2672 primary. Since this failure can happen during switching to
2673 backup (backup might have not noticed the primary going down yet),
2674 we will wait a while and keep sending START_USE to backup.
2675 Only after that we'll give up. */
2676 if (server->router == sock->user_data &&
2677 (time(0) - server->router_connect) < 30) {
2678 SILC_LOG_DEBUG(("Resending START_USE to backup router"));
2679 silc_server_backup_send_start_use(server, sock, FALSE);
2683 /* If backup is our primary, disconnect now. */
2684 if (server->router == sock->user_data) {
2685 if (sock->user_data)
2686 silc_server_free_sock_user_data(server, sock, NULL);
2687 SILC_SET_DISCONNECTING(sock);
2688 silc_server_close_connection(server, sock);
2692 silc_server_create_connections(server);
2696 /* Execute protocol */
2697 if (sock->protocol) {
2698 sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
2699 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2704 case SILC_PACKET_REJECT:
2705 if (packet->flags & SILC_PACKET_FLAG_LIST)
2710 case SILC_PACKET_NOTIFY:
2712 * Received notify packet. Server can receive notify packets from
2713 * router. Server then relays the notify messages to clients if needed.
2715 if (packet->flags & SILC_PACKET_FLAG_LIST)
2716 silc_server_notify_list(server, sock, packet);
2718 silc_server_notify(server, sock, packet);
2724 case SILC_PACKET_CHANNEL_MESSAGE:
2726 * Received channel message. Channel messages are special packets
2727 * (although probably most common ones) thus they are handled
2730 if (packet->flags & SILC_PACKET_FLAG_LIST)
2732 idata->last_receive = time(NULL);
2733 silc_server_channel_message(server, sock, packet);
2736 case SILC_PACKET_CHANNEL_KEY:
2738 * Received key for channel. As channels are created by the router
2739 * the keys are as well. We will distribute the key to all of our
2740 * locally connected clients on the particular channel. Router
2741 * never receives this channel and thus is ignored.
2743 if (packet->flags & SILC_PACKET_FLAG_LIST)
2745 silc_server_channel_key(server, sock, packet);
2751 case SILC_PACKET_COMMAND:
2753 * Recived command. Processes the command request and allocates the
2754 * command context and calls the command.
2756 if (packet->flags & SILC_PACKET_FLAG_LIST)
2758 silc_server_command_process(server, sock, packet);
2761 case SILC_PACKET_COMMAND_REPLY:
2763 * Received command reply packet. Received command reply to command. It
2764 * may be reply to command sent by us or reply to command sent by client
2765 * that we've routed further.
2767 if (packet->flags & SILC_PACKET_FLAG_LIST)
2769 silc_server_command_reply(server, sock, packet);
2773 * Private Message packets
2775 case SILC_PACKET_PRIVATE_MESSAGE:
2777 * Received private message packet. The packet is coming from either
2780 if (packet->flags & SILC_PACKET_FLAG_LIST)
2782 idata->last_receive = time(NULL);
2783 silc_server_private_message(server, sock, packet);
2786 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2788 * Private message key packet.
2790 if (packet->flags & SILC_PACKET_FLAG_LIST)
2792 silc_server_private_message_key(server, sock, packet);
2796 * Key Exchange protocol packets
2798 case SILC_PACKET_KEY_EXCHANGE:
2799 if (packet->flags & SILC_PACKET_FLAG_LIST)
2802 if (sock->protocol && sock->protocol->protocol &&
2803 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2804 SilcServerKEInternalContext *proto_ctx =
2805 (SilcServerKEInternalContext *)sock->protocol->context;
2807 proto_ctx->packet = silc_packet_context_dup(packet);
2809 /* Let the protocol handle the packet */
2810 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2812 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2813 "protocol active (%s:%d [%s]).", sock->hostname,
2815 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2816 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2817 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2822 case SILC_PACKET_KEY_EXCHANGE_1:
2823 if (packet->flags & SILC_PACKET_FLAG_LIST)
2826 if (sock->protocol && sock->protocol->protocol &&
2827 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2828 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2830 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2831 SilcServerRekeyInternalContext *proto_ctx =
2832 (SilcServerRekeyInternalContext *)sock->protocol->context;
2834 if (proto_ctx->packet)
2835 silc_packet_context_free(proto_ctx->packet);
2837 proto_ctx->packet = silc_packet_context_dup(packet);
2839 /* Let the protocol handle the packet */
2840 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2842 SilcServerKEInternalContext *proto_ctx =
2843 (SilcServerKEInternalContext *)sock->protocol->context;
2845 if (proto_ctx->packet)
2846 silc_packet_context_free(proto_ctx->packet);
2848 proto_ctx->packet = silc_packet_context_dup(packet);
2849 proto_ctx->dest_id_type = packet->src_id_type;
2850 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2851 packet->src_id_type);
2852 if (!proto_ctx->dest_id)
2855 /* Let the protocol handle the packet */
2856 silc_protocol_execute(sock->protocol, server->schedule,
2860 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2861 "protocol active (%s:%d [%s]).", sock->hostname,
2863 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2864 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2865 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2870 case SILC_PACKET_KEY_EXCHANGE_2:
2871 if (packet->flags & SILC_PACKET_FLAG_LIST)
2874 if (sock->protocol && sock->protocol->protocol &&
2875 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2876 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2878 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2879 SilcServerRekeyInternalContext *proto_ctx =
2880 (SilcServerRekeyInternalContext *)sock->protocol->context;
2882 if (proto_ctx->packet)
2883 silc_packet_context_free(proto_ctx->packet);
2885 proto_ctx->packet = silc_packet_context_dup(packet);
2887 /* Let the protocol handle the packet */
2888 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2890 SilcServerKEInternalContext *proto_ctx =
2891 (SilcServerKEInternalContext *)sock->protocol->context;
2893 if (proto_ctx->packet)
2894 silc_packet_context_free(proto_ctx->packet);
2896 proto_ctx->packet = silc_packet_context_dup(packet);
2897 proto_ctx->dest_id_type = packet->src_id_type;
2898 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2899 packet->src_id_type);
2900 if (!proto_ctx->dest_id)
2903 /* Let the protocol handle the packet */
2904 silc_protocol_execute(sock->protocol, server->schedule,
2908 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2909 "protocol active (%s:%d [%s]).", sock->hostname,
2911 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2912 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2913 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2918 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2920 * Connection authentication request packet. When we receive this packet
2921 * we will send to the other end information about our mandatory
2922 * authentication method for the connection. This packet maybe received
2925 if (packet->flags & SILC_PACKET_FLAG_LIST)
2927 silc_server_connection_auth_request(server, sock, packet);
2931 * Connection Authentication protocol packets
2933 case SILC_PACKET_CONNECTION_AUTH:
2934 /* Start of the authentication protocol. We receive here the
2935 authentication data and will verify it. */
2936 if (packet->flags & SILC_PACKET_FLAG_LIST)
2939 if (sock->protocol && sock->protocol->protocol->type
2940 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2942 SilcServerConnAuthInternalContext *proto_ctx =
2943 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2945 proto_ctx->packet = silc_packet_context_dup(packet);
2947 /* Let the protocol handle the packet */
2948 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2950 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2951 "protocol active (%s:%d [%s]).", sock->hostname,
2953 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2954 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2955 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2960 case SILC_PACKET_NEW_ID:
2962 * Received New ID packet. This includes some new ID that has been
2963 * created. It may be for client, server or channel. This is the way
2964 * to distribute information about new registered entities in the
2967 if (packet->flags & SILC_PACKET_FLAG_LIST)
2968 silc_server_new_id_list(server, sock, packet);
2970 silc_server_new_id(server, sock, packet);
2973 case SILC_PACKET_NEW_CLIENT:
2975 * Received new client packet. This includes client information that
2976 * we will use to create initial client ID. After creating new
2977 * ID we will send it to the client.
2979 if (packet->flags & SILC_PACKET_FLAG_LIST)
2981 silc_server_new_client(server, sock, packet);
2984 case SILC_PACKET_NEW_SERVER:
2986 * Received new server packet. This includes Server ID and some other
2987 * information that we may save. This is received after server has
2990 if (packet->flags & SILC_PACKET_FLAG_LIST)
2992 silc_server_new_server(server, sock, packet);
2995 case SILC_PACKET_NEW_CHANNEL:
2997 * Received new channel packet. Information about new channel in the
2998 * network are distributed using this packet.
3000 if (packet->flags & SILC_PACKET_FLAG_LIST)
3001 silc_server_new_channel_list(server, sock, packet);
3003 silc_server_new_channel(server, sock, packet);
3006 case SILC_PACKET_HEARTBEAT:
3008 * Received heartbeat.
3010 if (packet->flags & SILC_PACKET_FLAG_LIST)
3014 case SILC_PACKET_KEY_AGREEMENT:
3016 * Received heartbeat.
3018 if (packet->flags & SILC_PACKET_FLAG_LIST)
3020 silc_server_key_agreement(server, sock, packet);
3023 case SILC_PACKET_REKEY:
3025 * Received re-key packet. The sender wants to regenerate the session
3028 if (packet->flags & SILC_PACKET_FLAG_LIST)
3030 silc_server_rekey(server, sock, packet);
3033 case SILC_PACKET_REKEY_DONE:
3035 * The re-key is done.
3037 if (packet->flags & SILC_PACKET_FLAG_LIST)
3040 if (sock->protocol && sock->protocol->protocol &&
3041 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
3043 SilcServerRekeyInternalContext *proto_ctx =
3044 (SilcServerRekeyInternalContext *)sock->protocol->context;
3046 if (proto_ctx->packet)
3047 silc_packet_context_free(proto_ctx->packet);
3049 proto_ctx->packet = silc_packet_context_dup(packet);
3051 /* Let the protocol handle the packet */
3052 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
3054 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
3055 "protocol active (%s:%d [%s]).", sock->hostname,
3057 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
3058 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
3059 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
3064 case SILC_PACKET_FTP:
3066 if (packet->flags & SILC_PACKET_FLAG_LIST)
3068 silc_server_ftp(server, sock, packet);
3071 case SILC_PACKET_RESUME_CLIENT:
3073 if (packet->flags & SILC_PACKET_FLAG_LIST)
3075 silc_server_resume_client(server, sock, packet);
3078 case SILC_PACKET_RESUME_ROUTER:
3079 /* Resume router packet received. This packet is received for backup
3080 router resuming protocol. */
3081 if (packet->flags & SILC_PACKET_FLAG_LIST)
3083 silc_server_backup_resume_router(server, sock, packet);
3087 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
3092 /* Creates connection to a remote router. */
3094 void silc_server_create_connection(SilcServer server,
3095 const char *remote_host, SilcUInt32 port)
3097 SilcServerConnection sconn;
3099 /* Allocate connection object for hold connection specific stuff. */
3100 sconn = silc_calloc(1, sizeof(*sconn));
3101 sconn->remote_host = strdup(remote_host);
3102 sconn->remote_port = port;
3103 sconn->no_reconnect = TRUE;
3105 silc_schedule_task_add(server->schedule, 0,
3106 silc_server_connect_router,
3107 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
3108 SILC_TASK_PRI_NORMAL);
3111 SILC_TASK_CALLBACK(silc_server_close_connection_final)
3113 SilcServer server = app_context;
3114 SilcSocketConnection sock = context;
3116 SILC_LOG_DEBUG(("Deleting socket %p", sock));
3118 /* Close the actual connection */
3119 silc_net_close_connection(sock->sock);
3120 server->sockets[sock->sock] = NULL;
3122 /* We won't listen for this connection anymore */
3123 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
3124 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
3126 silc_socket_free(sock);
3129 /* Closes connection to socket connection */
3131 void silc_server_close_connection(SilcServer server,
3132 SilcSocketConnection sock)
3136 if (SILC_IS_DISCONNECTED(sock)) {
3137 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
3138 silc_schedule_task_add(server->schedule, sock->sock,
3139 silc_server_close_connection_final,
3140 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
3141 SILC_TASK_PRI_NORMAL);
3142 server->sockets[sock->sock] = NULL;
3146 /* If any protocol is active cancel its execution. It will call
3147 the final callback which will finalize the disconnection. */
3148 if (sock->protocol && sock->protocol->protocol &&
3149 sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3150 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3151 silc_protocol_cancel(sock->protocol, server->schedule);
3152 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3153 silc_protocol_execute_final(sock->protocol, server->schedule);
3154 sock->protocol = NULL;
3158 memset(tmp, 0, sizeof(tmp));
3159 silc_socket_get_error(sock, tmp, sizeof(tmp));
3160 SILC_LOG_INFO(("Closing connection %s:%d [%s] %s", sock->hostname,
3162 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
3163 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
3164 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
3165 "Router"), tmp[0] ? tmp : ""));
3167 SILC_SET_DISCONNECTED(sock);
3168 silc_socket_set_qos(sock, 0, 0, 0, 0, NULL);
3169 silc_schedule_task_add(server->schedule, sock->sock,
3170 silc_server_close_connection_final,
3171 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
3172 SILC_TASK_PRI_NORMAL);
3173 server->sockets[sock->sock] = NULL;
3176 /* Sends disconnect message to remote connection and disconnects the
3177 connection. NOTE: If this is called from protocol callback
3178 then sock->protocol must be set NULL before calling this, since
3179 this routine dispatches protocol callbacks too. */
3181 void silc_server_disconnect_remote(SilcServer server,
3182 SilcSocketConnection sock,
3183 SilcStatus status, ...)
3186 unsigned char buf[512];
3194 if (SILC_IS_DISCONNECTING(sock)) {
3195 SILC_SET_DISCONNECTED(sock);
3196 silc_server_close_connection(server, sock);
3200 memset(buf, 0, sizeof(buf));
3201 va_start(ap, status);
3202 cp = va_arg(ap, char *);
3204 vsnprintf(buf, sizeof(buf) - 1, cp, ap);
3209 SILC_LOG_DEBUG(("Disconnecting remote host"));
3211 /* Notify remote end that the conversation is over. The notify message
3212 is tried to be sent immediately. */
3216 len += silc_utf8_encoded_len(buf, strlen(buf), SILC_STRING_ASCII);
3218 buffer = silc_buffer_alloc_size(len);
3222 buffer->data[0] = status;
3224 silc_utf8_encode(buf, strlen(buf), SILC_STRING_ASCII, buffer->data + 1,
3226 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
3227 buffer->data, buffer->len, TRUE);
3228 silc_buffer_free(buffer);
3231 silc_server_packet_queue_purge(server, sock);
3233 /* Mark the connection to be disconnected */
3234 SILC_SET_DISCONNECTING(sock);
3235 silc_server_close_connection(server, sock);
3238 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
3240 SilcServer server = app_context;
3241 SilcClientEntry client = context;
3243 assert(!silc_hash_table_count(client->channels));
3245 silc_idlist_del_data(client);
3246 silc_idcache_purge_by_context(server->local_list->clients, client);
3249 /* Frees client data and notifies about client's signoff. */
3251 void silc_server_free_client_data(SilcServer server,
3252 SilcSocketConnection sock,
3253 SilcClientEntry client,
3255 const char *signoff)
3257 SILC_LOG_DEBUG(("Freeing client data"));
3259 /* If there is pending outgoing data for the client then purge it
3260 to the network before removing the client entry. */
3261 silc_server_packet_queue_purge(server, sock);
3264 /* Check if anyone is watching this nickname */
3265 if (server->server_type == SILC_ROUTER)
3266 silc_server_check_watcher_list(server, client, NULL,
3267 SILC_NOTIFY_TYPE_SIGNOFF);
3269 /* Send SIGNOFF notify to routers. */
3271 silc_server_send_notify_signoff(server, SILC_PRIMARY_ROUTE(server),
3272 SILC_BROADCAST(server), client->id,
3276 /* Remove client from all channels */
3278 silc_server_remove_from_channels(server, NULL, client,
3279 TRUE, (char *)signoff, TRUE, FALSE);
3281 silc_server_remove_from_channels(server, NULL, client,
3282 FALSE, NULL, FALSE, FALSE);
3284 /* Remove this client from watcher list if it is */
3285 silc_server_del_from_watcher_list(server, client);
3287 /* Remove this client from the public key hash list */
3288 if (client->data.public_key)
3289 silc_hash_table_del_by_context(server->pk_hash,
3290 client->data.public_key, client);
3292 /* Update statistics */
3293 server->stat.my_clients--;
3294 server->stat.clients--;
3295 if (server->stat.cell_clients)
3296 server->stat.cell_clients--;
3297 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
3298 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
3299 silc_schedule_task_del_by_context(server->schedule, client);
3301 /* We will not delete the client entry right away. We will take it
3302 into history (for WHOWAS command) for 5 minutes, unless we're
3303 shutting down server. */
3304 if (!server->server_shutdown) {
3305 silc_schedule_task_add(server->schedule, 0,
3306 silc_server_free_client_data_timeout,
3308 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
3309 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
3310 client->data.status &= ~SILC_IDLIST_STATUS_LOCAL;
3312 client->router = NULL;
3313 client->connection = NULL;
3315 /* Delete directly since we're shutting down server */
3316 silc_idlist_del_data(client);
3317 silc_idlist_del_client(server->local_list, client);
3321 /* Frees user_data pointer from socket connection object. This also sends
3322 appropriate notify packets to the network to inform about leaving
3325 void silc_server_free_sock_user_data(SilcServer server,
3326 SilcSocketConnection sock,
3327 const char *signoff_message)
3330 /* If any protocol is active cancel its execution */
3331 if (sock->protocol && sock->protocol->protocol &&
3332 sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3333 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3334 silc_protocol_cancel(sock->protocol, server->schedule);
3335 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3336 silc_protocol_execute_final(sock->protocol, server->schedule);
3337 sock->protocol = NULL;
3340 switch (sock->type) {
3341 case SILC_SOCKET_TYPE_CLIENT:
3343 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
3344 silc_server_free_client_data(server, sock, user_data, TRUE,
3348 case SILC_SOCKET_TYPE_SERVER:
3349 case SILC_SOCKET_TYPE_ROUTER:
3351 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
3352 SilcServerEntry backup_router = NULL;
3354 SILC_LOG_DEBUG(("Freeing server data"));
3357 backup_router = silc_server_backup_get(server, user_data->id);
3359 if (!server->backup_router && server->server_type == SILC_ROUTER &&
3360 backup_router == server->id_entry &&
3361 sock->type != SILC_SOCKET_TYPE_ROUTER)
3362 backup_router = NULL;
3364 if (server->server_shutdown || server->backup_noswitch)
3365 backup_router = NULL;
3367 /* If this was our primary router connection then we're lost to
3368 the outside world. */
3369 if (server->router == user_data) {
3370 /* Check whether we have a backup router connection */
3371 if (!backup_router || backup_router == user_data) {
3372 if (!server->no_reconnect)
3373 silc_server_create_connections(server);
3374 server->id_entry->router = NULL;
3375 server->router = NULL;
3376 server->standalone = TRUE;
3377 server->backup_primary = FALSE;
3378 backup_router = NULL;
3380 if (server->id_entry != backup_router) {
3381 SILC_LOG_INFO(("New primary router is backup router %s",
3382 backup_router->server_name));
3383 server->id_entry->router = backup_router;
3384 server->router = backup_router;
3385 server->router_connect = time(0);
3386 server->backup_primary = TRUE;
3387 backup_router->data.status &= ~SILC_IDLIST_STATUS_DISABLED;
3389 /* Send START_USE to backup router to indicate we have switched */
3390 silc_server_backup_send_start_use(server,
3391 backup_router->connection,
3394 SILC_LOG_INFO(("We are now new primary router in this cell"));
3395 server->id_entry->router = NULL;
3396 server->router = NULL;
3397 server->standalone = TRUE;
3400 /* We stop here to take a breath */
3403 if (server->backup_router) {
3404 server->server_type = SILC_ROUTER;
3406 /* We'll need to constantly try to reconnect to the primary
3407 router so that we'll see when it comes back online. */
3408 silc_server_backup_reconnect(server, sock->ip, sock->port,
3409 silc_server_backup_connected,
3413 /* Mark this connection as replaced */
3414 silc_server_backup_replaced_add(server, user_data->id,
3417 } else if (backup_router) {
3418 SILC_LOG_INFO(("Enabling the use of backup router %s",
3419 backup_router->server_name));
3421 /* Mark this connection as replaced */
3422 silc_server_backup_replaced_add(server, user_data->id,
3424 } else if (server->server_type == SILC_SERVER &&
3425 sock->type == SILC_SOCKET_TYPE_ROUTER) {
3426 /* Reconnect to the router (backup) */
3427 if (!server->no_reconnect)
3428 silc_server_create_connections(server);
3431 if (user_data->server_name)
3432 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
3433 ("Server %s signoff", user_data->server_name));
3435 if (!backup_router) {
3436 /* Remove all servers that are originated from this server, and
3437 remove the clients of those servers too. */
3438 silc_server_remove_servers_by_server(server, user_data, TRUE);
3441 /* Remove the clients that this server owns as they will become
3442 invalid now too. For backup router the server is actually
3443 coming from the primary router, so mark that as the owner
3445 if (server->server_type == SILC_BACKUP_ROUTER &&
3446 sock->type == SILC_SOCKET_TYPE_SERVER)
3447 silc_server_remove_clients_by_server(server, server->router,
3451 silc_server_remove_clients_by_server(server, user_data,
3454 /* Remove channels owned by this server */
3455 if (server->server_type == SILC_SERVER)
3456 silc_server_remove_channels_by_server(server, user_data);
3458 /* Enable local server connections that may be disabled */
3459 silc_server_local_servers_toggle_enabled(server, TRUE);
3461 /* Update the client entries of this server to the new backup
3462 router. If we are the backup router we also resolve the real
3463 servers for the clients. After updating is over this also
3464 removes the clients that this server explicitly owns. */
3465 silc_server_update_clients_by_server(server, user_data,
3466 backup_router, TRUE);
3468 /* If we are router and just lost our primary router (now standlaone)
3469 we remove everything that was behind it, since we don't know
3471 if (server->server_type == SILC_ROUTER && server->standalone)
3472 /* Remove all servers that are originated from this server, and
3473 remove the clients of those servers too. */
3474 silc_server_remove_servers_by_server(server, user_data, TRUE);
3476 /* Finally remove the clients that are explicitly owned by this
3477 server. They go down with the server. */
3478 silc_server_remove_clients_by_server(server, user_data,
3481 /* Update our server cache to use the new backup router too. */
3482 silc_server_update_servers_by_server(server, user_data, backup_router);
3483 if (server->server_type == SILC_SERVER)
3484 silc_server_update_channels_by_server(server, user_data,
3487 /* Send notify about primary router going down to local operators */
3488 if (server->backup_router)
3489 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3490 SILC_NOTIFY_TYPE_NONE,
3491 ("%s switched to backup router %s "
3492 "(we are primary router now)",
3493 server->server_name, server->server_name));
3494 else if (server->router)
3495 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3496 SILC_NOTIFY_TYPE_NONE,
3497 ("%s switched to backup router %s",
3498 server->server_name,
3499 server->router->server_name));
3501 server->backup_noswitch = FALSE;
3503 /* Free the server entry */
3504 silc_server_backup_del(server, user_data);
3505 silc_server_backup_replaced_del(server, user_data);
3506 silc_idlist_del_data(user_data);
3507 if (!silc_idlist_del_server(server->local_list, user_data))
3508 silc_idlist_del_server(server->global_list, user_data);
3509 if (sock->type == SILC_SOCKET_TYPE_SERVER) {
3510 server->stat.my_servers--;
3512 server->stat.my_routers--;
3513 server->stat.routers--;
3515 server->stat.servers--;
3516 if (server->server_type == SILC_ROUTER)
3517 server->stat.cell_servers--;
3519 if (backup_router && backup_router != server->id_entry) {
3520 /* Announce all of our stuff that was created about 5 minutes ago.
3521 The backup router knows all the other stuff already. */
3522 if (server->server_type == SILC_ROUTER)
3523 silc_server_announce_servers(server, FALSE, time(0) - 300,
3524 backup_router->connection);
3526 /* Announce our clients and channels to the router */
3527 silc_server_announce_clients(server, time(0) - 300,
3528 backup_router->connection);
3529 silc_server_announce_channels(server, time(0) - 300,
3530 backup_router->connection);
3536 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
3538 SILC_LOG_DEBUG(("Freeing unknown connection data"));
3540 silc_idlist_del_data(user_data);
3541 silc_free(user_data);
3546 sock->user_data = NULL;
3549 /* Removes client from all channels it has joined. This is used when client
3550 connection is disconnected. If the client on a channel is last, the
3551 channel is removed as well. This sends the SIGNOFF notify types. */
3553 void silc_server_remove_from_channels(SilcServer server,
3554 SilcSocketConnection sock,
3555 SilcClientEntry client,
3557 const char *signoff_message,
3561 SilcChannelEntry channel;
3562 SilcChannelClientEntry chl;
3563 SilcHashTableList htl;
3564 SilcBuffer clidp = NULL;
3569 if (notify && !client->id)
3572 SILC_LOG_DEBUG(("Removing client %s from joined channels",
3573 notify ? silc_id_render(client->id, SILC_ID_CLIENT) : ""));
3576 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3581 /* Remove the client from all channels. The client is removed from
3582 the channels' user list. */
3583 silc_hash_table_list(client->channels, &htl);
3584 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3585 channel = chl->channel;
3587 /* Remove channel if this is last client leaving the channel, unless
3588 the channel is permanent. */
3589 if (server->server_type != SILC_SERVER &&
3590 silc_hash_table_count(channel->user_list) < 2) {
3591 silc_server_channel_delete(server, channel);
3595 silc_hash_table_del(client->channels, channel);
3596 silc_hash_table_del(channel->user_list, client);
3597 channel->user_count--;
3599 /* If there is no global users on the channel anymore mark the channel
3600 as local channel. Do not check if the removed client is local client. */
3601 if (server->server_type == SILC_SERVER && channel->global_users &&
3602 chl->client->router && !silc_server_channel_has_global(channel))
3603 channel->global_users = FALSE;
3605 memset(chl, 'A', sizeof(*chl));
3608 /* Update statistics */
3609 if (SILC_IS_LOCAL(client))
3610 server->stat.my_chanclients--;
3611 if (server->server_type == SILC_ROUTER) {
3612 server->stat.cell_chanclients--;
3613 server->stat.chanclients--;
3616 /* If there is not at least one local user on the channel then we don't
3617 need the channel entry anymore, we can remove it safely, unless the
3618 channel is permanent channel */
3619 if (server->server_type == SILC_SERVER &&
3620 !silc_server_channel_has_local(channel)) {
3621 /* Notify about leaving client if this channel has global users. */
3622 if (notify && channel->global_users)
3623 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3624 SILC_NOTIFY_TYPE_SIGNOFF,
3625 signoff_message ? 2 : 1,
3626 clidp->data, clidp->len,
3627 signoff_message, signoff_message ?
3628 strlen(signoff_message) : 0);
3630 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3631 silc_server_channel_delete(server, channel);
3635 /* Send notify to channel about client leaving SILC and channel too */
3637 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3638 SILC_NOTIFY_TYPE_SIGNOFF,
3639 signoff_message ? 2 : 1,
3640 clidp->data, clidp->len,
3641 signoff_message, signoff_message ?
3642 strlen(signoff_message) : 0);
3644 if (killed && clidp) {
3645 /* Remove the client from channel's invite list */
3646 if (channel->invite_list &&
3647 silc_hash_table_count(channel->invite_list)) {
3649 SilcArgumentPayload iargs;
3650 ab = silc_argument_payload_encode_one(NULL, clidp->data,
3652 iargs = silc_argument_payload_parse(ab->data, ab->len, 1);
3653 silc_server_inviteban_process(server, channel->invite_list, 1, iargs);
3654 silc_buffer_free(ab);
3655 silc_argument_payload_free(iargs);
3659 /* Don't create keys if we are shutting down */
3660 if (server->server_shutdown)
3663 /* Re-generate channel key if needed */
3664 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3665 if (!silc_server_create_channel_key(server, channel, 0))
3668 /* Send the channel key to the channel. The key of course is not sent
3669 to the client who was removed from the channel. */
3670 silc_server_send_channel_key(server, client->connection, channel,
3671 server->server_type == SILC_ROUTER ?
3672 FALSE : !server->standalone);
3676 silc_hash_table_list_reset(&htl);
3678 silc_buffer_free(clidp);
3681 /* Removes client from one channel. This is used for example when client
3682 calls LEAVE command to remove itself from the channel. Returns TRUE
3683 if channel still exists and FALSE if the channel is removed when
3684 last client leaves the channel. If `notify' is FALSE notify messages
3687 bool silc_server_remove_from_one_channel(SilcServer server,
3688 SilcSocketConnection sock,
3689 SilcChannelEntry channel,
3690 SilcClientEntry client,
3693 SilcChannelClientEntry chl;
3696 SILC_LOG_DEBUG(("Removing %s from channel %s",
3697 silc_id_render(client->id, SILC_ID_CLIENT),
3698 channel->channel_name));
3700 /* Get the entry to the channel, if this client is not on the channel
3702 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
3705 /* Remove channel if this is last client leaving the channel, unless
3706 the channel is permanent. */
3707 if (server->server_type != SILC_SERVER &&
3708 silc_hash_table_count(channel->user_list) < 2) {
3709 silc_server_channel_delete(server, channel);
3713 silc_hash_table_del(client->channels, channel);
3714 silc_hash_table_del(channel->user_list, client);
3715 channel->user_count--;
3717 /* If there is no global users on the channel anymore mark the channel
3718 as local channel. Do not check if the client is local client. */
3719 if (server->server_type == SILC_SERVER && channel->global_users &&
3720 chl->client->router && !silc_server_channel_has_global(channel))
3721 channel->global_users = FALSE;
3723 memset(chl, 'O', sizeof(*chl));
3726 /* Update statistics */
3727 if (SILC_IS_LOCAL(client))
3728 server->stat.my_chanclients--;
3729 if (server->server_type == SILC_ROUTER) {
3730 server->stat.cell_chanclients--;
3731 server->stat.chanclients--;
3734 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3738 /* If there is not at least one local user on the channel then we don't
3739 need the channel entry anymore, we can remove it safely, unless the
3740 channel is permanent channel */
3741 if (server->server_type == SILC_SERVER &&
3742 !silc_server_channel_has_local(channel)) {
3743 /* Notify about leaving client if this channel has global users. */
3744 if (notify && channel->global_users)
3745 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3746 SILC_NOTIFY_TYPE_LEAVE, 1,
3747 clidp->data, clidp->len);
3749 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3750 silc_server_channel_delete(server, channel);
3751 silc_buffer_free(clidp);
3755 /* Send notify to channel about client leaving the channel */
3757 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3758 SILC_NOTIFY_TYPE_LEAVE, 1,
3759 clidp->data, clidp->len);
3761 silc_buffer_free(clidp);
3765 /* Timeout callback. This is called if connection is idle or for some
3766 other reason is not responding within some period of time. This
3767 disconnects the remote end. */
3769 SILC_TASK_CALLBACK(silc_server_timeout_remote)
3771 SilcServer server = (SilcServer)context;
3772 SilcSocketConnection sock = server->sockets[fd];
3773 SilcProtocolType protocol = 0;
3775 SILC_LOG_DEBUG(("Start"));
3780 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
3781 sock->hostname, sock->ip));
3783 /* If we have protocol active we must assure that we call the protocol's
3784 final callback so that all the memory is freed. */
3785 if (sock->protocol && sock->protocol->protocol &&
3786 sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3787 protocol = sock->protocol->protocol->type;
3788 silc_protocol_cancel(sock->protocol, server->schedule);
3789 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3790 silc_protocol_execute_final(sock->protocol, server->schedule);
3791 sock->protocol = NULL;
3795 silc_server_disconnect_remote(server, sock,
3797 SILC_PROTOCOL_SERVER_CONNECTION_AUTH ?
3798 SILC_STATUS_ERR_AUTH_FAILED :
3799 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
3800 "Connection timeout");
3802 if (sock->user_data)
3803 silc_server_free_sock_user_data(server, sock, NULL);
3806 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
3807 function may be used only by router. In real SILC network all channels
3808 are created by routers thus this function is never used by normal
3811 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3812 SilcServerID *router_id,
3818 SilcChannelID *channel_id;
3819 SilcChannelEntry entry;
3823 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3826 cipher = SILC_DEFAULT_CIPHER;
3828 hmac = SILC_DEFAULT_HMAC;
3830 /* Allocate cipher */
3831 if (!silc_cipher_alloc(cipher, &key))
3835 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3836 silc_cipher_free(key);
3840 channel_name = strdup(channel_name);
3842 /* Create the channel ID */
3843 if (!silc_id_create_channel_id(server, router_id, server->rng,
3845 silc_free(channel_name);
3846 silc_cipher_free(key);
3847 silc_hmac_free(newhmac);
3851 /* Create the channel */
3852 entry = silc_idlist_add_channel(server->local_list, channel_name,
3853 SILC_CHANNEL_MODE_NONE, channel_id,
3854 NULL, key, newhmac, 0);
3856 silc_free(channel_name);
3857 silc_cipher_free(key);
3858 silc_hmac_free(newhmac);
3859 silc_free(channel_id);
3863 entry->cipher = strdup(cipher);
3864 entry->hmac_name = strdup(hmac);
3866 /* Now create the actual key material */
3867 if (!silc_server_create_channel_key(server, entry,
3868 silc_cipher_get_key_len(key) / 8)) {
3869 silc_idlist_del_channel(server->local_list, entry);
3873 /* Notify other routers about the new channel. We send the packet
3874 to our primary route. */
3876 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3877 channel_name, entry->id,
3878 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3881 /* Distribute to backup routers */
3882 if (broadcast && server->server_type == SILC_ROUTER) {
3885 SilcUInt32 name_len = strlen(channel_name);
3886 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3887 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3889 packet = silc_channel_payload_encode(channel_name, name_len,
3890 cid, channel_id_len, entry->mode);
3891 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3892 packet->data, packet->len, FALSE, TRUE);
3894 silc_buffer_free(packet);
3897 server->stat.my_channels++;
3898 if (server->server_type == SILC_ROUTER) {
3899 server->stat.channels++;
3900 server->stat.cell_channels++;
3901 entry->users_resolved = TRUE;
3907 /* Same as above but creates the channel with Channel ID `channel_id. */
3910 silc_server_create_new_channel_with_id(SilcServer server,
3914 SilcChannelID *channel_id,
3917 SilcChannelEntry entry;
3921 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3924 cipher = SILC_DEFAULT_CIPHER;
3926 hmac = SILC_DEFAULT_HMAC;
3928 /* Allocate cipher */
3929 if (!silc_cipher_alloc(cipher, &key))
3933 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3934 silc_cipher_free(key);
3938 channel_name = strdup(channel_name);
3940 /* Create the channel */
3941 entry = silc_idlist_add_channel(server->local_list, channel_name,
3942 SILC_CHANNEL_MODE_NONE, channel_id,
3943 NULL, key, newhmac, 0);
3945 silc_cipher_free(key);
3946 silc_hmac_free(newhmac);
3947 silc_free(channel_name);
3951 /* Now create the actual key material */
3952 if (!silc_server_create_channel_key(server, entry,
3953 silc_cipher_get_key_len(key) / 8)) {
3954 silc_idlist_del_channel(server->local_list, entry);
3958 /* Notify other routers about the new channel. We send the packet
3959 to our primary route. */
3961 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3962 channel_name, entry->id,
3963 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3966 /* Distribute to backup routers */
3967 if (broadcast && server->server_type == SILC_ROUTER) {
3970 SilcUInt32 name_len = strlen(channel_name);
3971 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3972 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3974 packet = silc_channel_payload_encode(channel_name, name_len,
3975 cid, channel_id_len, entry->mode);
3976 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3977 packet->data, packet->len, FALSE, TRUE);
3979 silc_buffer_free(packet);
3982 server->stat.my_channels++;
3983 if (server->server_type == SILC_ROUTER) {
3984 server->stat.channels++;
3985 server->stat.cell_channels++;
3986 entry->users_resolved = TRUE;
3992 /* Channel's key re-key timeout callback. */
3994 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3996 SilcServer server = app_context;
3997 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
4001 /* Return now if we are shutting down */
4002 if (server->server_shutdown)
4005 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
4008 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
4011 /* Generates new channel key. This is used to create the initial channel key
4012 but also to re-generate new key for channel. If `key_len' is provided
4013 it is the bytes of the key length. */
4015 bool silc_server_create_channel_key(SilcServer server,
4016 SilcChannelEntry channel,
4020 unsigned char channel_key[32], hash[32];
4023 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
4024 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
4028 SILC_LOG_DEBUG(("Generating channel %s key", channel->channel_name));
4030 if (!channel->channel_key)
4031 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
4032 channel->channel_key = NULL;
4038 else if (channel->key_len)
4039 len = channel->key_len / 8;
4041 len = silc_cipher_get_key_len(channel->channel_key) / 8;
4043 /* Create channel key */
4044 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
4047 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
4049 /* Remove old key if exists */
4051 memset(channel->key, 0, channel->key_len / 8);
4052 silc_free(channel->key);
4056 channel->key_len = len * 8;
4057 channel->key = silc_memdup(channel_key, len);
4058 memset(channel_key, 0, sizeof(channel_key));
4060 /* Generate HMAC key from the channel key data and set it */
4062 if (!silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac)) {
4063 memset(channel->key, 0, channel->key_len / 8);
4064 silc_free(channel->key);
4065 channel->channel_key = NULL;
4068 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
4069 silc_hmac_set_key(channel->hmac, hash,
4070 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
4071 memset(hash, 0, sizeof(hash));
4073 if (server->server_type == SILC_ROUTER) {
4074 if (!channel->rekey)
4075 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
4076 channel->rekey->channel = channel;
4077 channel->rekey->key_len = key_len;
4078 if (channel->rekey->task)
4079 silc_schedule_task_del(server->schedule, channel->rekey->task);
4081 channel->rekey->task =
4082 silc_schedule_task_add(server->schedule, 0,
4083 silc_server_channel_key_rekey,
4084 (void *)channel->rekey,
4085 server->config->channel_rekey_secs, 0,
4087 SILC_TASK_PRI_NORMAL);
4093 /* Saves the channel key found in the encoded `key_payload' buffer. This
4094 function is used when we receive Channel Key Payload and also when we're
4095 processing JOIN command reply. Returns entry to the channel. */
4097 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
4098 SilcBuffer key_payload,
4099 SilcChannelEntry channel)
4101 SilcChannelKeyPayload payload = NULL;
4102 SilcChannelID *id = NULL;
4103 unsigned char *tmp, hash[32];
4107 /* Decode channel key payload */
4108 payload = silc_channel_key_payload_parse(key_payload->data,
4111 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
4116 /* Get the channel entry */
4119 /* Get channel ID */
4120 tmp = silc_channel_key_get_id(payload, &tmp_len);
4121 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
4127 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
4129 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
4131 if (server->server_type == SILC_ROUTER)
4132 SILC_LOG_ERROR(("Received key for non-existent channel %s",
4133 silc_id_render(id, SILC_ID_CHANNEL)));
4139 SILC_LOG_DEBUG(("Saving new channel %s key", channel->channel_name));
4141 tmp = silc_channel_key_get_key(payload, &tmp_len);
4147 cipher = silc_channel_key_get_cipher(payload, NULL);
4153 /* Remove old key if exists */
4155 memset(channel->key, 0, channel->key_len / 8);
4156 silc_free(channel->key);
4157 silc_cipher_free(channel->channel_key);
4160 /* Create new cipher */
4161 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
4162 channel->channel_key = NULL;
4167 if (channel->cipher)
4168 silc_free(channel->cipher);
4169 channel->cipher = strdup(cipher);
4172 channel->key_len = tmp_len * 8;
4173 channel->key = silc_memdup(tmp, tmp_len);
4174 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
4176 /* Generate HMAC key from the channel key data and set it */
4178 if (!silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac)) {
4179 memset(channel->key, 0, channel->key_len / 8);
4180 silc_free(channel->key);
4181 channel->channel_key = NULL;
4184 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
4185 silc_hmac_set_key(channel->hmac, hash,
4186 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
4188 memset(hash, 0, sizeof(hash));
4189 memset(tmp, 0, tmp_len);
4191 if (server->server_type == SILC_ROUTER) {
4192 if (!channel->rekey)
4193 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
4194 channel->rekey->channel = channel;
4195 if (channel->rekey->task)
4196 silc_schedule_task_del(server->schedule, channel->rekey->task);
4198 channel->rekey->task =
4199 silc_schedule_task_add(server->schedule, 0,
4200 silc_server_channel_key_rekey,
4201 (void *)channel->rekey,
4202 server->config->channel_rekey_secs, 0,
4204 SILC_TASK_PRI_NORMAL);
4210 silc_channel_key_payload_free(payload);
4215 /* Heartbeat callback. This function is set as argument for the
4216 silc_socket_set_heartbeat function. The library will call this function
4217 at the set time interval. */
4219 void silc_server_perform_heartbeat(SilcSocketConnection sock,
4222 SilcServer server = hb_context;
4224 SILC_LOG_DEBUG(("Sending heartbeat to %s:%d (%s)", sock->hostname,
4225 sock->port, sock->ip));
4227 /* Send the heartbeat */
4228 silc_server_send_heartbeat(server, sock);
4231 /* Returns assembled of all servers in the given ID list. The packet's
4232 form is dictated by the New ID payload. */
4234 static void silc_server_announce_get_servers(SilcServer server,
4235 SilcServerEntry remote,
4237 SilcBuffer *servers,
4238 unsigned long creation_time)
4240 SilcIDCacheList list;
4241 SilcIDCacheEntry id_cache;
4242 SilcServerEntry entry;
4245 /* Go through all clients in the list */
4246 if (silc_idcache_get_all(id_list->servers, &list)) {
4247 if (silc_idcache_list_first(list, &id_cache)) {
4249 entry = (SilcServerEntry)id_cache->context;
4251 /* Do not announce the one we've sending our announcements and
4252 do not announce ourself. Also check the creation time if it's
4254 if ((entry == remote) || (entry == server->id_entry) ||
4255 (creation_time && entry->data.created < creation_time)) {
4256 if (!silc_idcache_list_next(list, &id_cache))
4261 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
4263 *servers = silc_buffer_realloc(*servers,
4265 (*servers)->truelen + idp->len :
4267 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
4268 silc_buffer_put(*servers, idp->data, idp->len);
4269 silc_buffer_pull(*servers, idp->len);
4270 silc_buffer_free(idp);
4272 if (!silc_idcache_list_next(list, &id_cache))
4277 silc_idcache_list_free(list);
4282 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
4288 p = silc_notify_payload_encode(notify, argc, ap);
4294 /* This function is used by router to announce existing servers to our
4295 primary router when we've connected to it. If `creation_time' is non-zero
4296 then only the servers that has been created after the `creation_time'
4297 will be announced. */
4299 void silc_server_announce_servers(SilcServer server, bool global,
4300 unsigned long creation_time,
4301 SilcSocketConnection remote)
4303 SilcBuffer servers = NULL;
4305 SILC_LOG_DEBUG(("Announcing servers"));
4307 /* Get servers in local list */
4308 silc_server_announce_get_servers(server, remote->user_data,
4309 server->local_list, &servers,
4313 /* Get servers in global list */
4314 silc_server_announce_get_servers(server, remote->user_data,
4315 server->global_list, &servers,
4319 silc_buffer_push(servers, servers->data - servers->head);
4320 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
4322 /* Send the packet */
4323 silc_server_packet_send(server, remote,
4324 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4325 servers->data, servers->len, TRUE);
4327 silc_buffer_free(servers);
4331 /* Returns assembled packet of all clients in the given ID list. The
4332 packet's form is dictated by the New ID Payload. */
4334 static void silc_server_announce_get_clients(SilcServer server,
4336 SilcBuffer *clients,
4338 unsigned long creation_time)
4340 SilcIDCacheList list;
4341 SilcIDCacheEntry id_cache;
4342 SilcClientEntry client;
4345 unsigned char mode[4];
4347 /* Go through all clients in the list */
4348 if (silc_idcache_get_all(id_list->clients, &list)) {
4349 if (silc_idcache_list_first(list, &id_cache)) {
4351 client = (SilcClientEntry)id_cache->context;
4353 if (creation_time && client->data.created < creation_time) {
4354 if (!silc_idcache_list_next(list, &id_cache))
4358 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED) &&
4359 !client->connection && !client->router && !SILC_IS_LOCAL(client)) {
4360 if (!silc_idcache_list_next(list, &id_cache))
4365 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
4367 *clients = silc_buffer_realloc(*clients,
4369 (*clients)->truelen + idp->len :
4371 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
4372 silc_buffer_put(*clients, idp->data, idp->len);
4373 silc_buffer_pull(*clients, idp->len);
4375 SILC_PUT32_MSB(client->mode, mode);
4377 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
4378 2, idp->data, idp->len,
4380 *umodes = silc_buffer_realloc(*umodes,
4382 (*umodes)->truelen + tmp->len :
4384 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
4385 silc_buffer_put(*umodes, tmp->data, tmp->len);
4386 silc_buffer_pull(*umodes, tmp->len);
4387 silc_buffer_free(tmp);
4389 silc_buffer_free(idp);
4391 if (!silc_idcache_list_next(list, &id_cache))
4396 silc_idcache_list_free(list);
4400 /* This function is used to announce our existing clients to our router
4401 when we've connected to it. If `creation_time' is non-zero then only
4402 the clients that has been created after the `creation_time' will be
4405 void silc_server_announce_clients(SilcServer server,
4406 unsigned long creation_time,
4407 SilcSocketConnection remote)
4409 SilcBuffer clients = NULL;
4410 SilcBuffer umodes = NULL;
4412 SILC_LOG_DEBUG(("Announcing clients"));
4414 /* Get clients in local list */
4415 silc_server_announce_get_clients(server, server->local_list,
4416 &clients, &umodes, creation_time);
4418 /* As router we announce our global list as well */
4419 if (server->server_type == SILC_ROUTER)
4420 silc_server_announce_get_clients(server, server->global_list,
4421 &clients, &umodes, creation_time);
4424 silc_buffer_push(clients, clients->data - clients->head);
4425 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
4427 /* Send the packet */
4428 silc_server_packet_send(server, remote,
4429 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4430 clients->data, clients->len, TRUE);
4432 silc_buffer_free(clients);
4436 silc_buffer_push(umodes, umodes->data - umodes->head);
4437 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
4439 /* Send the packet */
4440 silc_server_packet_send(server, remote,
4441 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4442 umodes->data, umodes->len, TRUE);
4444 silc_buffer_free(umodes);
4448 /* Returns channel's topic for announcing it */
4450 void silc_server_announce_get_channel_topic(SilcServer server,
4451 SilcChannelEntry channel,
4456 if (channel->topic) {
4457 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4458 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
4459 chidp->data, chidp->len,
4461 strlen(channel->topic));
4462 silc_buffer_free(chidp);
4466 /* Returns channel's invite and ban lists */
4468 void silc_server_announce_get_inviteban(SilcServer server,
4469 SilcChannelEntry channel,
4473 SilcBuffer list, idp, idp2, tmp2;
4475 SilcHashTableList htl;
4476 const unsigned char a[1] = { 0x03 };
4478 idp = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
4480 /* Encode invite list */
4481 if (channel->invite_list && silc_hash_table_count(channel->invite_list)) {
4482 list = silc_buffer_alloc_size(2);
4483 type = silc_hash_table_count(channel->invite_list);
4484 SILC_PUT16_MSB(type, list->data);
4485 silc_hash_table_list(channel->invite_list, &htl);
4486 while (silc_hash_table_get(&htl, (void *)&type, (void *)&tmp2))
4487 list = silc_argument_payload_encode_one(list, tmp2->data, tmp2->len,
4489 silc_hash_table_list_reset(&htl);
4491 idp2 = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4493 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_INVITE, 5,
4494 idp->data, idp->len,
4495 channel->channel_name,
4496 strlen(channel->channel_name),
4497 idp2->data, idp2->len,
4499 list->data, list->len);
4500 silc_buffer_free(idp2);
4501 silc_buffer_free(list);
4504 /* Encode ban list */
4505 if (channel->ban_list && silc_hash_table_count(channel->ban_list)) {
4506 list = silc_buffer_alloc_size(2);
4507 type = silc_hash_table_count(channel->ban_list);
4508 SILC_PUT16_MSB(type, list->data);
4509 silc_hash_table_list(channel->ban_list, &htl);
4510 while (silc_hash_table_get(&htl, (void *)&type, (void *)&tmp2))
4511 list = silc_argument_payload_encode_one(list, tmp2->data, tmp2->len,
4513 silc_hash_table_list_reset(&htl);
4516 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_BAN, 3,
4517 idp->data, idp->len,
4519 list->data, list->len);
4520 silc_buffer_free(list);
4523 silc_buffer_free(idp);
4526 /* Returns assembled packets for channel users of the `channel'. */
4528 void silc_server_announce_get_channel_users(SilcServer server,
4529 SilcChannelEntry channel,
4530 SilcBuffer *channel_modes,
4531 SilcBuffer *channel_users,
4532 SilcBuffer *channel_users_modes)
4534 SilcChannelClientEntry chl;
4535 SilcHashTableList htl;
4536 SilcBuffer chidp, clidp, csidp;
4537 SilcBuffer tmp, fkey = NULL, chpklist;
4539 unsigned char mode[4];
4542 SILC_LOG_DEBUG(("Start"));
4544 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4545 csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4546 chpklist = silc_server_get_channel_pk_list(server, channel, TRUE, FALSE);
4549 SILC_PUT32_MSB(channel->mode, mode);
4550 hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
4551 if (channel->founder_key)
4552 fkey = silc_pkcs_public_key_payload_encode(channel->founder_key);
4554 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
4555 7, csidp->data, csidp->len,
4558 hmac, hmac ? strlen(hmac) : 0,
4559 channel->passphrase,
4560 channel->passphrase ?
4561 strlen(channel->passphrase) : 0,
4562 fkey ? fkey->data : NULL,
4563 fkey ? fkey->len : 0,
4564 chpklist ? chpklist->data : NULL,
4565 chpklist ? chpklist->len : 0);
4568 silc_buffer_realloc(*channel_modes,
4570 (*channel_modes)->truelen + len : len));
4571 silc_buffer_pull_tail(*channel_modes,
4572 ((*channel_modes)->end -
4573 (*channel_modes)->data));
4574 silc_buffer_put(*channel_modes, tmp->data, tmp->len);
4575 silc_buffer_pull(*channel_modes, len);
4576 silc_buffer_free(tmp);
4577 silc_buffer_free(fkey);
4580 /* Now find all users on the channel */
4581 silc_hash_table_list(channel->user_list, &htl);
4582 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4583 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4586 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
4587 clidp->data, clidp->len,
4588 chidp->data, chidp->len);
4591 silc_buffer_realloc(*channel_users,
4593 (*channel_users)->truelen + len : len));
4594 silc_buffer_pull_tail(*channel_users,
4595 ((*channel_users)->end -
4596 (*channel_users)->data));
4598 silc_buffer_put(*channel_users, tmp->data, tmp->len);
4599 silc_buffer_pull(*channel_users, len);
4600 silc_buffer_free(tmp);
4602 /* CUMODE notify for mode change on the channel */
4603 SILC_PUT32_MSB(chl->mode, mode);
4604 if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
4605 fkey = silc_pkcs_public_key_payload_encode(channel->founder_key);
4606 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
4607 4, csidp->data, csidp->len,
4609 clidp->data, clidp->len,
4610 fkey ? fkey->data : NULL,
4611 fkey ? fkey->len : 0);
4613 *channel_users_modes =
4614 silc_buffer_realloc(*channel_users_modes,
4615 (*channel_users_modes ?
4616 (*channel_users_modes)->truelen + len : len));
4617 silc_buffer_pull_tail(*channel_users_modes,
4618 ((*channel_users_modes)->end -
4619 (*channel_users_modes)->data));
4621 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
4622 silc_buffer_pull(*channel_users_modes, len);
4623 silc_buffer_free(tmp);
4624 silc_buffer_free(fkey);
4626 silc_buffer_free(clidp);
4628 silc_hash_table_list_reset(&htl);
4629 silc_buffer_free(chidp);
4630 silc_buffer_free(csidp);
4633 /* Returns assembled packets for all channels and users on those channels
4634 from the given ID List. The packets are in the form dictated by the
4635 New Channel and New Channel User payloads. */
4637 void silc_server_announce_get_channels(SilcServer server,
4639 SilcBuffer *channels,
4640 SilcBuffer **channel_modes,
4641 SilcBuffer *channel_users,
4642 SilcBuffer **channel_users_modes,
4643 SilcUInt32 *channel_users_modes_c,
4644 SilcBuffer **channel_topics,
4645 SilcBuffer **channel_invites,
4646 SilcBuffer **channel_bans,
4647 SilcChannelID ***channel_ids,
4648 unsigned long creation_time)
4650 SilcIDCacheList list;
4651 SilcIDCacheEntry id_cache;
4652 SilcChannelEntry channel;
4655 SilcUInt16 name_len;
4657 int i = *channel_users_modes_c;
4660 SILC_LOG_DEBUG(("Start"));
4662 /* Go through all channels in the list */
4663 if (silc_idcache_get_all(id_list->channels, &list)) {
4664 if (silc_idcache_list_first(list, &id_cache)) {
4666 channel = (SilcChannelEntry)id_cache->context;
4668 if (creation_time && channel->created < creation_time)
4673 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4674 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4675 name_len = strlen(channel->channel_name);
4678 len = 4 + name_len + id_len + 4;
4680 silc_buffer_realloc(*channels,
4681 (*channels ? (*channels)->truelen +
4683 silc_buffer_pull_tail(*channels,
4684 ((*channels)->end - (*channels)->data));
4685 silc_buffer_format(*channels,
4686 SILC_STR_UI_SHORT(name_len),
4687 SILC_STR_UI_XNSTRING(channel->channel_name,
4689 SILC_STR_UI_SHORT(id_len),
4690 SILC_STR_UI_XNSTRING(cid, id_len),
4691 SILC_STR_UI_INT(channel->mode),
4693 silc_buffer_pull(*channels, len);
4696 if (creation_time && channel->updated < creation_time)
4702 /* Channel user modes */
4703 *channel_users_modes = silc_realloc(*channel_users_modes,
4704 sizeof(**channel_users_modes) *
4706 (*channel_users_modes)[i] = NULL;
4707 *channel_modes = silc_realloc(*channel_modes,
4708 sizeof(**channel_modes) * (i + 1));
4709 (*channel_modes)[i] = NULL;
4710 *channel_ids = silc_realloc(*channel_ids,
4711 sizeof(**channel_ids) * (i + 1));
4712 (*channel_ids)[i] = NULL;
4713 silc_server_announce_get_channel_users(server, channel,
4714 &(*channel_modes)[i],
4716 &(*channel_users_modes)[i]);
4717 (*channel_ids)[i] = channel->id;
4719 /* Channel's topic */
4720 *channel_topics = silc_realloc(*channel_topics,
4721 sizeof(**channel_topics) * (i + 1));
4722 (*channel_topics)[i] = NULL;
4723 silc_server_announce_get_channel_topic(server, channel,
4724 &(*channel_topics)[i]);
4726 /* Channel's invite and ban list */
4727 *channel_invites = silc_realloc(*channel_invites,
4728 sizeof(**channel_invites) * (i + 1));
4729 (*channel_invites)[i] = NULL;
4730 *channel_bans = silc_realloc(*channel_bans,
4731 sizeof(**channel_bans) * (i + 1));
4732 (*channel_bans)[i] = NULL;
4733 silc_server_announce_get_inviteban(server, channel,
4734 &(*channel_invites)[i],
4735 &(*channel_bans)[i]);
4737 (*channel_users_modes_c)++;
4743 if (!silc_idcache_list_next(list, &id_cache))
4748 silc_idcache_list_free(list);
4752 /* This function is used to announce our existing channels to our router
4753 when we've connected to it. This also announces the users on the
4754 channels to the router. If the `creation_time' is non-zero only the
4755 channels that was created after the `creation_time' are announced.
4756 Note that the channel users are still announced even if the `creation_time'
4759 void silc_server_announce_channels(SilcServer server,
4760 unsigned long creation_time,
4761 SilcSocketConnection remote)
4763 SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
4764 SilcBuffer *channel_users_modes = NULL;
4765 SilcBuffer *channel_topics = NULL;
4766 SilcBuffer *channel_invites = NULL;
4767 SilcBuffer *channel_bans = NULL;
4768 SilcUInt32 channel_users_modes_c = 0;
4769 SilcChannelID **channel_ids = NULL;
4771 SILC_LOG_DEBUG(("Announcing channels and channel users"));
4773 /* Get channels and channel users in local list */
4774 silc_server_announce_get_channels(server, server->local_list,
4775 &channels, &channel_modes,
4777 &channel_users_modes,
4778 &channel_users_modes_c,
4782 &channel_ids, creation_time);
4784 /* Get channels and channel users in global list */
4785 if (server->server_type != SILC_SERVER)
4786 silc_server_announce_get_channels(server, server->global_list,
4787 &channels, &channel_modes,
4789 &channel_users_modes,
4790 &channel_users_modes_c,
4794 &channel_ids, creation_time);
4797 silc_buffer_push(channels, channels->data - channels->head);
4798 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
4800 /* Send the packet */
4801 silc_server_packet_send(server, remote,
4802 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
4803 channels->data, channels->len,
4806 silc_buffer_free(channels);
4809 if (channel_users) {
4810 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
4811 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
4812 channel_users->len);
4814 /* Send the packet */
4815 silc_server_packet_send(server, remote,
4816 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4817 channel_users->data, channel_users->len,
4820 silc_buffer_free(channel_users);
4823 if (channel_modes) {
4826 for (i = 0; i < channel_users_modes_c; i++) {
4827 if (!channel_modes[i])
4829 silc_buffer_push(channel_modes[i],
4830 channel_modes[i]->data -
4831 channel_modes[i]->head);
4832 SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
4833 channel_modes[i]->len);
4834 silc_server_packet_send_dest(server, remote,
4835 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4836 channel_ids[i], SILC_ID_CHANNEL,
4837 channel_modes[i]->data,
4838 channel_modes[i]->len,
4840 silc_buffer_free(channel_modes[i]);
4842 silc_free(channel_modes);
4845 if (channel_users_modes) {
4848 for (i = 0; i < channel_users_modes_c; i++) {
4849 if (!channel_users_modes[i])
4851 silc_buffer_push(channel_users_modes[i],
4852 channel_users_modes[i]->data -
4853 channel_users_modes[i]->head);
4854 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
4855 channel_users_modes[i]->len);
4856 silc_server_packet_send_dest(server, remote,
4857 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4858 channel_ids[i], SILC_ID_CHANNEL,
4859 channel_users_modes[i]->data,
4860 channel_users_modes[i]->len,
4862 silc_buffer_free(channel_users_modes[i]);
4864 silc_free(channel_users_modes);
4867 if (channel_topics) {
4870 for (i = 0; i < channel_users_modes_c; i++) {
4871 if (!channel_topics[i])
4874 silc_buffer_push(channel_topics[i],
4875 channel_topics[i]->data -
4876 channel_topics[i]->head);
4877 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
4878 channel_topics[i]->len);
4879 silc_server_packet_send_dest(server, remote,
4880 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4881 channel_ids[i], SILC_ID_CHANNEL,
4882 channel_topics[i]->data,
4883 channel_topics[i]->len,
4885 silc_buffer_free(channel_topics[i]);
4887 silc_free(channel_topics);
4890 if (channel_invites) {
4893 for (i = 0; i < channel_users_modes_c; i++) {
4894 if (!channel_invites[i])
4897 silc_buffer_push(channel_invites[i],
4898 channel_invites[i]->data -
4899 channel_invites[i]->head);
4900 SILC_LOG_HEXDUMP(("channel invite list"), channel_invites[i]->data,
4901 channel_invites[i]->len);
4902 silc_server_packet_send_dest(server, remote,
4903 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4904 channel_ids[i], SILC_ID_CHANNEL,
4905 channel_invites[i]->data,
4906 channel_invites[i]->len,
4908 silc_buffer_free(channel_invites[i]);
4910 silc_free(channel_invites);
4916 for (i = 0; i < channel_users_modes_c; i++) {
4917 if (!channel_bans[i])
4920 silc_buffer_push(channel_bans[i],
4921 channel_bans[i]->data -
4922 channel_bans[i]->head);
4923 SILC_LOG_HEXDUMP(("channel ban list"), channel_bans[i]->data,
4924 channel_bans[i]->len);
4925 silc_server_packet_send_dest(server, remote,
4926 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4927 channel_ids[i], SILC_ID_CHANNEL,
4928 channel_bans[i]->data,
4929 channel_bans[i]->len,
4931 silc_buffer_free(channel_bans[i]);
4933 silc_free(channel_bans);
4936 silc_free(channel_ids);
4939 /* Assembles user list and users mode list from the `channel'. */
4941 bool silc_server_get_users_on_channel(SilcServer server,
4942 SilcChannelEntry channel,
4943 SilcBuffer *user_list,
4944 SilcBuffer *mode_list,
4945 SilcUInt32 *user_count)
4947 SilcChannelClientEntry chl;
4948 SilcHashTableList htl;
4949 SilcBuffer client_id_list;
4950 SilcBuffer client_mode_list;
4952 SilcUInt32 list_count = 0, len = 0;
4954 if (!silc_hash_table_count(channel->user_list))
4957 silc_hash_table_list(channel->user_list, &htl);
4958 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4959 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
4960 silc_hash_table_list_reset(&htl);
4962 client_id_list = silc_buffer_alloc(len);
4964 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
4965 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
4966 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
4968 silc_hash_table_list(channel->user_list, &htl);
4969 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4971 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4972 silc_buffer_put(client_id_list, idp->data, idp->len);
4973 silc_buffer_pull(client_id_list, idp->len);
4974 silc_buffer_free(idp);
4976 /* Client's mode on channel */
4977 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
4978 silc_buffer_pull(client_mode_list, 4);
4982 silc_hash_table_list_reset(&htl);
4983 silc_buffer_push(client_id_list,
4984 client_id_list->data - client_id_list->head);
4985 silc_buffer_push(client_mode_list,
4986 client_mode_list->data - client_mode_list->head);
4988 *user_list = client_id_list;
4989 *mode_list = client_mode_list;
4990 *user_count = list_count;
4994 /* Saves users and their modes to the `channel'. */
4996 void silc_server_save_users_on_channel(SilcServer server,
4997 SilcSocketConnection sock,
4998 SilcChannelEntry channel,
4999 SilcClientID *noadd,
5000 SilcBuffer user_list,
5001 SilcBuffer mode_list,
5002 SilcUInt32 user_count)
5007 SilcClientID *client_id;
5008 SilcClientEntry client;
5009 SilcIDCacheEntry cache;
5010 SilcChannelClientEntry chl;
5012 SILC_LOG_DEBUG(("Saving %d users on %s channel", user_count,
5013 channel->channel_name));
5015 for (i = 0; i < user_count; i++) {
5017 SILC_GET16_MSB(idp_len, user_list->data + 2);
5019 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
5020 silc_buffer_pull(user_list, idp_len);
5025 SILC_GET32_MSB(mode, mode_list->data);
5026 silc_buffer_pull(mode_list, 4);
5028 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
5029 silc_free(client_id);
5035 /* Check if we have this client cached already. */
5036 client = silc_idlist_find_client_by_id(server->local_list, client_id,
5037 server->server_type, &cache);
5039 client = silc_idlist_find_client_by_id(server->global_list,
5040 client_id, server->server_type,
5043 /* If router did not find such Client ID in its lists then this must
5044 be bogus client or some router in the net is buggy. */
5045 if (server->server_type != SILC_SERVER) {
5046 silc_free(client_id);
5050 /* We don't have that client anywhere, add it. The client is added
5051 to global list since server didn't have it in the lists so it must be
5053 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
5054 silc_id_dup(client_id, SILC_ID_CLIENT),
5055 sock->user_data, NULL, 0);
5057 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
5058 silc_free(client_id);
5062 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
5067 silc_free(client_id);
5069 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
5070 SILC_LOG_ERROR(("Attempting to add unregistered client to channel ",
5071 "%s", channel->channel_name));
5075 if (!silc_server_client_on_channel(client, channel, &chl)) {
5076 /* Client was not on the channel, add it. */
5077 chl = silc_calloc(1, sizeof(*chl));
5078 chl->client = client;
5080 chl->channel = channel;
5081 silc_hash_table_add(channel->user_list, chl->client, chl);
5082 silc_hash_table_add(client->channels, chl->channel, chl);
5083 channel->user_count++;
5091 /* Saves channels and channels user modes to the `client'. Removes
5092 the client from those channels that are not sent in the list but
5095 void silc_server_save_user_channels(SilcServer server,
5096 SilcSocketConnection sock,
5097 SilcClientEntry client,
5098 SilcBuffer channels,
5099 SilcBuffer channels_user_modes)
5102 SilcUInt32 *chumodes;
5103 SilcChannelPayload entry;
5104 SilcChannelEntry channel;
5105 SilcChannelID *channel_id;
5106 SilcChannelClientEntry chl;
5107 SilcHashTable ht = NULL;
5108 SilcHashTableList htl;
5112 if (!channels || !channels_user_modes ||
5113 !(client->data.status & SILC_IDLIST_STATUS_REGISTERED))
5116 ch = silc_channel_payload_parse_list(channels->data, channels->len);
5117 if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
5119 ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL,
5120 NULL, NULL, NULL, TRUE);
5121 silc_dlist_start(ch);
5122 while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
5123 /* Check if we have this channel, and add it if we don't have it.
5124 Also add the client on the channel unless it is there already. */
5125 channel_id = silc_channel_get_id_parse(entry);
5126 channel = silc_idlist_find_channel_by_id(server->local_list,
5129 channel = silc_idlist_find_channel_by_id(server->global_list,
5132 if (server->server_type != SILC_SERVER) {
5133 silc_free(channel_id);
5138 /* We don't have that channel anywhere, add it. */
5139 name = silc_channel_get_name(entry, NULL);
5140 channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
5141 channel_id, server->router,
5144 silc_free(channel_id);
5151 channel->mode = silc_channel_get_mode(entry);
5153 /* Add the client on the channel */
5154 if (!silc_server_client_on_channel(client, channel, &chl)) {
5155 chl = silc_calloc(1, sizeof(*chl));
5156 chl->client = client;
5157 chl->mode = chumodes[i++];
5158 chl->channel = channel;
5159 silc_hash_table_add(channel->user_list, chl->client, chl);
5160 silc_hash_table_add(client->channels, chl->channel, chl);
5161 channel->user_count++;
5164 chl->mode = chumodes[i++];
5167 silc_hash_table_add(ht, channel, channel);
5168 silc_free(channel_id);
5170 silc_channel_payload_list_free(ch);
5171 silc_free(chumodes);
5175 /* Go through the list again and remove client from channels that
5176 are no part of the list. */
5178 silc_hash_table_list(client->channels, &htl);
5179 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5180 if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
5181 silc_hash_table_del(chl->channel->user_list, chl->client);
5182 silc_hash_table_del(chl->client->channels, chl->channel);
5186 silc_hash_table_list_reset(&htl);
5187 silc_hash_table_free(ht);
5189 silc_hash_table_list(client->channels, &htl);
5190 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5191 silc_hash_table_del(chl->channel->user_list, chl->client);
5192 silc_hash_table_del(chl->client->channels, chl->channel);
5195 silc_hash_table_list_reset(&htl);
5199 /* Lookups route to the client indicated by the `id_data'. The connection
5200 object and internal data object is returned. Returns NULL if route
5201 could not be found to the client. If the `client_id' is specified then
5202 it is used and the `id_data' is ignored. */
5204 SilcSocketConnection
5205 silc_server_get_client_route(SilcServer server,
5206 unsigned char *id_data,
5208 SilcClientID *client_id,
5209 SilcIDListData *idata,
5210 SilcClientEntry *client_entry)
5213 SilcClientEntry client;
5215 SILC_LOG_DEBUG(("Start"));
5218 *client_entry = NULL;
5220 /* Decode destination Client ID */
5222 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
5224 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
5228 id = silc_id_dup(client_id, SILC_ID_CLIENT);
5231 /* If the destination belongs to our server we don't have to route
5232 the packet anywhere but to send it to the local destination. */
5233 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
5237 /* If we are router and the client has router then the client is in
5238 our cell but not directly connected to us. */
5239 if (server->server_type == SILC_ROUTER && client->router) {
5240 /* We are of course in this case the client's router thus the route
5241 to the client is the server who owns the client. So, we will send
5242 the packet to that server. */
5244 *idata = (SilcIDListData)client->router;
5245 return client->router->connection;
5248 /* Seems that client really is directly connected to us */
5250 *idata = (SilcIDListData)client;
5252 *client_entry = client;
5253 return client->connection;
5256 /* Destination belongs to someone not in this server. If we are normal
5257 server our action is to send the packet to our router. */
5258 if (server->server_type != SILC_ROUTER && !server->standalone) {
5261 *idata = (SilcIDListData)server->router;
5262 return SILC_PRIMARY_ROUTE(server);
5265 /* We are router and we will perform route lookup for the destination
5266 and send the packet to fastest route. */
5267 if (server->server_type == SILC_ROUTER && !server->standalone) {
5268 /* Check first that the ID is valid */
5269 client = silc_idlist_find_client_by_id(server->global_list, id,
5272 SilcSocketConnection dst_sock;
5274 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
5278 *idata = (SilcIDListData)dst_sock->user_data;
5287 /* Encodes and returns channel list of channels the `client' has joined.
5288 Secret channels are not put to the list. */
5290 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
5291 SilcClientEntry client,
5294 SilcBuffer *user_mode_list)
5296 SilcBuffer buffer = NULL;
5297 SilcChannelEntry channel;
5298 SilcChannelClientEntry chl;
5299 SilcHashTableList htl;
5302 SilcUInt16 name_len;
5306 *user_mode_list = NULL;
5308 silc_hash_table_list(client->channels, &htl);
5309 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5310 channel = chl->channel;
5312 if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
5314 if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
5317 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
5318 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
5319 name_len = strlen(channel->channel_name);
5321 len = 4 + name_len + id_len + 4;
5322 buffer = silc_buffer_realloc(buffer,
5323 (buffer ? buffer->truelen + len : len));
5324 silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
5325 silc_buffer_format(buffer,
5326 SILC_STR_UI_SHORT(name_len),
5327 SILC_STR_UI_XNSTRING(channel->channel_name,
5329 SILC_STR_UI_SHORT(id_len),
5330 SILC_STR_UI_XNSTRING(cid, id_len),
5331 SILC_STR_UI_INT(chl->channel->mode),
5333 silc_buffer_pull(buffer, len);
5336 if (user_mode_list) {
5337 *user_mode_list = silc_buffer_realloc(*user_mode_list,
5339 (*user_mode_list)->truelen + 4 :
5341 silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
5342 (*user_mode_list)->data));
5343 SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
5344 silc_buffer_pull(*user_mode_list, 4);
5347 silc_hash_table_list_reset(&htl);
5350 silc_buffer_push(buffer, buffer->data - buffer->head);
5351 if (user_mode_list && *user_mode_list)
5352 silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
5353 (*user_mode_list)->head));
5358 /* Timeout callback for unsuccessful rekey. The rekey did not go through
5361 SILC_TASK_CALLBACK(silc_server_rekey_timeout)
5363 SilcServerRekeyInternalContext *ctx = context;
5364 SilcServer server = app_context;
5365 SilcSocketConnection sock = ctx->sock;
5367 SILC_LOG_DEBUG(("Timeout occurred in rekey protocol with %s:%d [%s]",
5368 sock->hostname, sock->port,
5369 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5370 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5371 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5374 SILC_LOG_WARNING(("Timeout occurred in rekey protocol with %s:%d [%s]",
5375 sock->hostname, sock->port,
5376 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5377 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5378 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5381 if (sock->protocol) {
5382 silc_protocol_cancel(sock->protocol, server->schedule);
5383 silc_protocol_free(sock->protocol);
5384 sock->protocol = NULL;
5387 silc_packet_context_free(ctx->packet);
5389 silc_ske_free(ctx->ske);
5390 silc_socket_free(sock);
5393 /* Disconnect since we failed to rekey, the keys are probably wrong. */
5394 silc_server_disconnect_remote(server, sock,
5395 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
5398 if (sock->type != SILC_SOCKET_TYPE_CLIENT)
5399 silc_server_create_connections(server);
5402 /* A timeout callback for the re-key. We will be the initiator of the
5405 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_callback)
5407 SilcServer server = app_context;
5408 SilcSocketConnection sock = (SilcSocketConnection)context;
5409 SilcIDListData idata = (SilcIDListData)sock->user_data;
5410 SilcProtocol protocol;
5411 SilcServerRekeyInternalContext *proto_ctx;
5416 /* Do not execute rekey with disabled connections, as it would not
5417 go through anyway. */
5418 if (idata->status & SILC_IDLIST_STATUS_DISABLED)
5421 /* If rekey protocol is active already wait for it to finish */
5422 if (sock->protocol && sock->protocol->protocol &&
5423 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)
5426 /* If any other protocol is active do not start this protocol yet. */
5427 if (sock->protocol) {
5428 SILC_LOG_DEBUG(("Waiting for other protocol to finish before rekeying"));
5429 silc_schedule_task_add(server->schedule, sock->sock,
5430 silc_server_rekey_callback,
5431 sock, 60, 0, SILC_TASK_TIMEOUT,
5432 SILC_TASK_PRI_NORMAL);
5436 SILC_LOG_DEBUG(("Executing rekey protocol with %s:%d [%s]",
5437 sock->hostname, sock->port,
5438 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5439 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5440 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5443 /* Allocate internal protocol context. This is sent as context
5445 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
5446 proto_ctx->server = (void *)server;
5447 proto_ctx->sock = silc_socket_dup(sock);
5448 proto_ctx->responder = FALSE;
5449 proto_ctx->pfs = idata->rekey->pfs;
5451 /* Perform rekey protocol. Will call the final callback after the
5452 protocol is over. */
5453 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
5454 &protocol, proto_ctx, silc_server_rekey_final);
5455 sock->protocol = protocol;
5457 /* Register timeout callback in case the rekey does not go through. */
5458 proto_ctx->timeout_task =
5459 silc_schedule_task_add(server->schedule, sock->sock,
5460 silc_server_rekey_timeout,
5462 (idata->rekey->timeout >
5463 server->config->key_exchange_timeout ?
5464 idata->rekey->timeout :
5465 server->config->key_exchange_timeout * 4), 0,
5469 /* Run the protocol */
5470 silc_protocol_execute(protocol, server->schedule, 0, 0);
5473 /* The final callback for the REKEY protocol. This will actually take the
5474 new key material into use. */
5476 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
5478 SilcProtocol protocol = (SilcProtocol)context;
5479 SilcServerRekeyInternalContext *ctx =
5480 (SilcServerRekeyInternalContext *)protocol->context;
5481 SilcServer server = (SilcServer)ctx->server;
5482 SilcSocketConnection sock = ctx->sock;
5483 SilcIDListData idata = (SilcIDListData)sock->user_data;
5485 if (ctx->timeout_task)
5486 silc_schedule_task_del(server->schedule, ctx->timeout_task);
5488 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
5489 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
5490 /* Error occured during protocol */
5491 SILC_LOG_ERROR(("Error occurred during rekey protocol with "
5492 "%s (%s)", sock->hostname, sock->ip));
5493 silc_protocol_cancel(protocol, server->schedule);
5494 silc_protocol_free(protocol);
5495 sock->protocol = NULL;
5497 silc_packet_context_free(ctx->packet);
5499 silc_ske_free(ctx->ske);
5500 silc_socket_free(sock);
5502 silc_server_disconnect_remote(server, sock,
5503 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
5506 if (sock->type != SILC_SOCKET_TYPE_CLIENT)
5507 silc_server_create_connections(server);
5511 SILC_LOG_DEBUG(("Rekey protocol completed with %s:%d [%s]",
5512 sock->hostname, sock->port,
5513 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5514 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5515 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5518 /* Purge the outgoing data queue to assure that all rekey packets really
5519 go to the network before we quit the protocol. */
5520 silc_server_packet_queue_purge(server, sock);
5522 /* Re-register re-key timeout */
5523 if (ctx->responder == FALSE)
5524 silc_schedule_task_add(server->schedule, sock->sock,
5525 silc_server_rekey_callback,
5526 sock, idata->rekey->timeout, 0,
5527 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
5530 silc_protocol_free(protocol);
5531 sock->protocol = NULL;
5533 silc_packet_context_free(ctx->packet);
5535 silc_ske_free(ctx->ske);
5536 silc_socket_free(sock);
5540 /* Task callback used to retrieve network statistical information from
5541 router server once in a while. */
5543 SILC_TASK_CALLBACK(silc_server_get_stats)
5545 SilcServer server = (SilcServer)context;
5546 SilcBuffer idp, packet;
5548 if (!server->standalone) {
5549 SILC_LOG_DEBUG(("Retrieving stats from router"));
5550 idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
5551 packet = silc_command_payload_encode_va(SILC_COMMAND_STATS,
5552 ++server->cmd_ident, 1,
5553 1, idp->data, idp->len);
5554 silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
5555 SILC_PACKET_COMMAND, 0, packet->data,
5556 packet->len, FALSE);
5557 silc_buffer_free(packet);
5558 silc_buffer_free(idp);
5561 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
5562 server, 120, 0, SILC_TASK_TIMEOUT,