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 20 seconds for the backup router to appear. */
1921 silc_schedule_task_add(server->schedule, 0,
1922 silc_server_backup_router_wait,
1923 (void *)server, 20, 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 20 seconds for the backup router to appear. */
2099 silc_schedule_task_add(server->schedule, 0,
2100 silc_server_backup_router_wait,
2101 (void *)server, 20, 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 /* If backup then mark that resuming will not be allowed */
2294 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2295 sock->type == SILC_SOCKET_TYPE_SERVER) {
2296 SilcServerEntry server_entry = sock->user_data;
2297 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2298 server->backup_closed = TRUE;
2301 silc_server_free_sock_user_data(server, sock, NULL);
2303 SILC_SET_DISCONNECTING(sock);
2304 silc_server_close_connection(server, sock);
2309 /* Packet receiving */
2311 /* Read some data from connection */
2312 ret = silc_packet_receive(sock);
2316 SILC_LOG_ERROR(("Error receiving packet from connection "
2317 "%s:%d [%s] %s", sock->hostname, sock->port,
2318 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2319 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2320 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2321 "Router"), strerror(errno)));
2323 if (sock->user_data) {
2324 /* If backup then mark that resuming will not be allowed */
2325 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2326 sock->type == SILC_SOCKET_TYPE_SERVER) {
2327 SilcServerEntry server_entry = sock->user_data;
2328 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2329 server->backup_closed = TRUE;
2332 silc_server_free_sock_user_data(server, sock, NULL);
2334 SILC_SET_DISCONNECTING(sock);
2335 silc_server_close_connection(server, sock);
2342 SILC_LOG_DEBUG(("Read EOF"));
2344 /* If connection is disconnecting already we will finally
2345 close the connection */
2346 if (SILC_IS_DISCONNECTING(sock)) {
2347 if (sock->user_data)
2348 silc_server_free_sock_user_data(server, sock, NULL);
2349 silc_server_close_connection(server, sock);
2353 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
2355 if (sock->user_data) {
2358 /* If backup disconnected then mark that resuming will not be allowed */
2359 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2360 sock->type == SILC_SOCKET_TYPE_SERVER && sock->user_data) {
2361 SilcServerEntry server_entry = sock->user_data;
2362 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2363 server->backup_closed = TRUE;
2366 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
2367 silc_server_free_sock_user_data(server, sock, tmp);
2369 silc_server_free_sock_user_data(server, sock, NULL);
2370 } else if (server->router_conn && server->router_conn->sock == sock &&
2371 !server->router && server->standalone) {
2372 silc_server_create_connections(server);
2375 SILC_SET_DISCONNECTING(sock);
2376 silc_server_close_connection(server, sock);
2380 /* If connection is disconnecting or disconnected we will ignore
2382 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2383 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
2387 /* Get keys and stuff from ID entry */
2388 idata = (SilcIDListData)sock->user_data;
2390 cipher = idata->receive_key;
2391 hmac = idata->hmac_receive;
2392 sequence = idata->psn_receive;
2395 /* Then, process the packet. This will call the parser that will then
2396 decrypt and parse the packet. */
2398 local_is_router = (server->server_type == SILC_ROUTER);
2400 /* If socket connection is our primary, we are backup and we are doing
2401 backup resuming, we won't process the packet as being a router
2402 (affects channel message decryption). */
2403 if (server->backup_router && SILC_SERVER_IS_BACKUP(sock) &&
2404 SILC_PRIMARY_ROUTE(server) == sock)
2405 local_is_router = FALSE;
2407 ret = silc_packet_receive_process(sock, local_is_router,
2408 cipher, hmac, sequence,
2409 silc_server_packet_parse, server);
2411 /* If processing failed the connection is closed. */
2413 /* On packet processing errors we may close our primary router
2414 connection but won't become primary router if we are the backup
2415 since this is local error condition. */
2416 if (SILC_PRIMARY_ROUTE(server) == sock && server->backup_router)
2417 server->backup_noswitch = TRUE;
2419 if (sock->user_data) {
2420 /* If we are router and backup errorred then mark that resuming
2421 will not be allowed */
2422 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2423 sock->type == SILC_SOCKET_TYPE_SERVER) {
2424 SilcServerEntry server_entry = sock->user_data;
2425 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2426 server->backup_closed = TRUE;
2429 silc_server_free_sock_user_data(server, sock, NULL);
2431 SILC_SET_DISCONNECTING(sock);
2432 silc_server_close_connection(server, sock);
2436 /* Parses whole packet, received earlier. */
2438 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
2440 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
2441 SilcServer server = (SilcServer)parse_ctx->context;
2442 SilcSocketConnection sock = parse_ctx->sock;
2443 SilcPacketContext *packet = parse_ctx->packet;
2444 SilcIDListData idata = (SilcIDListData)sock->user_data;
2447 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2448 SILC_LOG_DEBUG(("Connection is disconnected"));
2452 server->stat.packets_received++;
2454 /* Parse the packet */
2455 if (parse_ctx->normal)
2456 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
2458 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
2460 /* If entry is disabled ignore what we got. */
2461 if (idata && idata->status & SILC_IDLIST_STATUS_DISABLED &&
2462 ret != SILC_PACKET_HEARTBEAT && ret != SILC_PACKET_RESUME_ROUTER &&
2463 ret != SILC_PACKET_REKEY && ret != SILC_PACKET_REKEY_DONE) {
2464 SILC_LOG_DEBUG(("Connection is disabled"));
2468 if (ret == SILC_PACKET_NONE) {
2469 SILC_LOG_DEBUG(("Error parsing packet"));
2473 /* Check that the the current client ID is same as in the client's packet. */
2474 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
2475 SilcClientEntry client = (SilcClientEntry)sock->user_data;
2476 if (client && client->id && packet->src_id) {
2477 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
2478 packet->src_id_type);
2479 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
2481 SILC_LOG_DEBUG(("Packet source is not same as sender"));
2488 if (server->server_type == SILC_ROUTER) {
2489 /* Route the packet if it is not destined to us. Other ID types but
2490 server are handled separately after processing them. */
2491 if (packet->dst_id && !(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
2492 packet->dst_id_type == SILC_ID_SERVER &&
2493 sock->type != SILC_SOCKET_TYPE_CLIENT &&
2494 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
2496 /* Route the packet to fastest route for the destination ID */
2497 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
2498 packet->dst_id_type);
2501 silc_server_packet_route(server,
2502 silc_server_route_get(server, id,
2503 packet->dst_id_type),
2510 /* Parse the incoming packet type */
2511 silc_server_packet_parse_type(server, sock, packet);
2513 /* Broadcast packet if it is marked as broadcast packet and it is
2514 originated from router and we are router. */
2515 if (server->server_type == SILC_ROUTER &&
2516 sock->type == SILC_SOCKET_TYPE_ROUTER &&
2517 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
2518 /* Broadcast to our primary route */
2519 silc_server_packet_broadcast(server, SILC_PRIMARY_ROUTE(server), packet);
2521 /* If we have backup routers then we need to feed all broadcast
2522 data to those servers. */
2523 silc_server_backup_broadcast(server, sock, packet);
2527 silc_packet_context_free(packet);
2528 silc_free(parse_ctx);
2531 /* Parser callback called by silc_packet_receive_process. This merely
2532 registers timeout that will handle the actual parsing when appropriate. */
2534 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
2537 SilcServer server = (SilcServer)context;
2538 SilcSocketConnection sock = parser_context->sock;
2539 SilcIDListData idata = (SilcIDListData)sock->user_data;
2543 idata->psn_receive = parser_context->packet->sequence + 1;
2545 /* If protocol for this connection is key exchange or rekey then we'll
2546 process all packets synchronously, since there might be packets in
2547 queue that we are not able to decrypt without first processing the
2548 packets before them. */
2549 if (sock->protocol && sock->protocol->protocol &&
2550 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2551 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2552 silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2555 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2556 SILC_LOG_DEBUG(("Connection is disconnected"));
2560 /* Reprocess data since we'll return FALSE here. This is because
2561 the idata->receive_key might have become valid in the last packet
2562 and we want to call this processor with valid cipher. */
2564 ret = silc_packet_receive_process(
2565 sock, server->server_type == SILC_ROUTER,
2567 idata->hmac_receive, idata->psn_receive,
2568 silc_server_packet_parse, server);
2570 ret = silc_packet_receive_process(
2571 sock, server->server_type == SILC_ROUTER,
2573 silc_server_packet_parse, server);
2576 /* On packet processing errors we may close our primary router
2577 connection but won't become primary router if we are the backup
2578 since this is local error condition. */
2579 if (SILC_PRIMARY_ROUTE(server) == sock && server->backup_router)
2580 server->backup_noswitch = TRUE;
2582 if (sock->user_data)
2583 silc_server_free_sock_user_data(server, sock, NULL);
2584 SILC_SET_DISCONNECTING(sock);
2585 silc_server_close_connection(server, sock);
2591 switch (sock->type) {
2592 case SILC_SOCKET_TYPE_UNKNOWN:
2593 case SILC_SOCKET_TYPE_CLIENT:
2594 /* Parse the packet with timeout */
2595 silc_schedule_task_add(server->schedule, sock->sock,
2596 silc_server_packet_parse_real,
2597 (void *)parser_context, 0, 100000,
2599 SILC_TASK_PRI_NORMAL);
2601 case SILC_SOCKET_TYPE_SERVER:
2602 case SILC_SOCKET_TYPE_ROUTER:
2603 /* Packets from servers are parsed immediately */
2604 silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2612 /* Parses the packet type and calls what ever routines the packet type
2613 requires. This is done for all incoming packets. */
2615 void silc_server_packet_parse_type(SilcServer server,
2616 SilcSocketConnection sock,
2617 SilcPacketContext *packet)
2619 SilcPacketType type = packet->type;
2620 SilcIDListData idata = (SilcIDListData)sock->user_data;
2622 SILC_LOG_DEBUG(("Received %s packet [flags %d]",
2623 silc_get_packet_name(type), packet->flags));
2625 /* Parse the packet type */
2627 case SILC_PACKET_DISCONNECT:
2630 char *message = NULL;
2632 if (packet->flags & SILC_PACKET_FLAG_LIST)
2634 if (packet->buffer->len < 1)
2637 status = (SilcStatus)packet->buffer->data[0];
2638 if (packet->buffer->len > 1 &&
2639 silc_utf8_valid(packet->buffer->data + 1, packet->buffer->len - 1))
2640 message = silc_memdup(packet->buffer->data + 1,
2641 packet->buffer->len - 1);
2643 SILC_LOG_INFO(("Disconnected by %s (%s): %s (%d) %s",
2644 sock->ip, sock->hostname,
2645 silc_get_status_message(status), status,
2646 message ? message : ""));
2649 /* Do not switch to backup in case of error */
2650 server->backup_noswitch = (status == SILC_STATUS_OK ? FALSE : TRUE);
2652 /* If backup disconnected then mark that resuming will not be allowed */
2653 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2654 sock->type == SILC_SOCKET_TYPE_SERVER && sock->user_data) {
2655 SilcServerEntry server_entry = sock->user_data;
2656 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2657 server->backup_closed = TRUE;
2660 /* Handle the disconnection from our end too */
2661 if (sock->user_data && SILC_IS_LOCAL(sock->user_data))
2662 silc_server_free_sock_user_data(server, sock, NULL);
2663 SILC_SET_DISCONNECTING(sock);
2664 silc_server_close_connection(server, sock);
2665 server->backup_noswitch = FALSE;
2669 case SILC_PACKET_SUCCESS:
2671 * Success received for something. For now we can have only
2672 * one protocol for connection executing at once hence this
2673 * success message is for whatever protocol is executing currently.
2675 if (packet->flags & SILC_PACKET_FLAG_LIST)
2678 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2681 case SILC_PACKET_FAILURE:
2683 * Failure received for something. For now we can have only
2684 * one protocol for connection executing at once hence this
2685 * failure message is for whatever protocol is executing currently.
2687 if (packet->flags & SILC_PACKET_FLAG_LIST)
2690 /* Check for failure START_USE from backup router */
2691 if (server->server_type == SILC_SERVER &&
2692 server->backup_primary && packet->buffer->len == 4) {
2694 SILC_GET32_MSB(type, packet->buffer->data);
2695 if (type == SILC_SERVER_BACKUP_START_USE) {
2696 /* Attempt to reconnect to primary */
2697 SILC_LOG_DEBUG(("Received failed START_USE from backup %s", sock->ip));
2699 /* Default action is to disconnect from backup and reconnect to
2700 primary. Since this failure can happen during switching to
2701 backup (backup might have not noticed the primary going down yet),
2702 we will wait a while and keep sending START_USE to backup.
2703 Only after that we'll give up. */
2704 if (server->router == sock->user_data &&
2705 (time(0) - server->router_connect) < 30) {
2706 SILC_LOG_DEBUG(("Resending START_USE to backup router"));
2707 silc_server_backup_send_start_use(server, sock, FALSE);
2711 /* If backup is our primary, disconnect now. */
2712 if (server->router == sock->user_data) {
2713 if (sock->user_data)
2714 silc_server_free_sock_user_data(server, sock, NULL);
2715 SILC_SET_DISCONNECTING(sock);
2716 silc_server_close_connection(server, sock);
2720 silc_server_create_connections(server);
2724 /* Execute protocol */
2725 if (sock->protocol) {
2726 sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
2727 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2732 case SILC_PACKET_REJECT:
2733 if (packet->flags & SILC_PACKET_FLAG_LIST)
2738 case SILC_PACKET_NOTIFY:
2740 * Received notify packet. Server can receive notify packets from
2741 * router. Server then relays the notify messages to clients if needed.
2743 if (packet->flags & SILC_PACKET_FLAG_LIST)
2744 silc_server_notify_list(server, sock, packet);
2746 silc_server_notify(server, sock, packet);
2752 case SILC_PACKET_CHANNEL_MESSAGE:
2754 * Received channel message. Channel messages are special packets
2755 * (although probably most common ones) thus they are handled
2758 if (packet->flags & SILC_PACKET_FLAG_LIST)
2760 idata->last_receive = time(NULL);
2761 silc_server_channel_message(server, sock, packet);
2764 case SILC_PACKET_CHANNEL_KEY:
2766 * Received key for channel. As channels are created by the router
2767 * the keys are as well. We will distribute the key to all of our
2768 * locally connected clients on the particular channel. Router
2769 * never receives this channel and thus is ignored.
2771 if (packet->flags & SILC_PACKET_FLAG_LIST)
2773 silc_server_channel_key(server, sock, packet);
2779 case SILC_PACKET_COMMAND:
2781 * Recived command. Processes the command request and allocates the
2782 * command context and calls the command.
2784 if (packet->flags & SILC_PACKET_FLAG_LIST)
2786 silc_server_command_process(server, sock, packet);
2789 case SILC_PACKET_COMMAND_REPLY:
2791 * Received command reply packet. Received command reply to command. It
2792 * may be reply to command sent by us or reply to command sent by client
2793 * that we've routed further.
2795 if (packet->flags & SILC_PACKET_FLAG_LIST)
2797 silc_server_command_reply(server, sock, packet);
2801 * Private Message packets
2803 case SILC_PACKET_PRIVATE_MESSAGE:
2805 * Received private message packet. The packet is coming from either
2808 if (packet->flags & SILC_PACKET_FLAG_LIST)
2810 idata->last_receive = time(NULL);
2811 silc_server_private_message(server, sock, packet);
2814 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2816 * Private message key packet.
2818 if (packet->flags & SILC_PACKET_FLAG_LIST)
2820 silc_server_private_message_key(server, sock, packet);
2824 * Key Exchange protocol packets
2826 case SILC_PACKET_KEY_EXCHANGE:
2827 if (packet->flags & SILC_PACKET_FLAG_LIST)
2830 if (sock->protocol && sock->protocol->protocol &&
2831 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2832 SilcServerKEInternalContext *proto_ctx =
2833 (SilcServerKEInternalContext *)sock->protocol->context;
2835 proto_ctx->packet = silc_packet_context_dup(packet);
2837 /* Let the protocol handle the packet */
2838 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2840 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2841 "protocol active (%s:%d [%s]).", sock->hostname,
2843 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2844 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2845 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2850 case SILC_PACKET_KEY_EXCHANGE_1:
2851 if (packet->flags & SILC_PACKET_FLAG_LIST)
2854 if (sock->protocol && sock->protocol->protocol &&
2855 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2856 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2858 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2859 SilcServerRekeyInternalContext *proto_ctx =
2860 (SilcServerRekeyInternalContext *)sock->protocol->context;
2862 if (proto_ctx->packet)
2863 silc_packet_context_free(proto_ctx->packet);
2865 proto_ctx->packet = silc_packet_context_dup(packet);
2867 /* Let the protocol handle the packet */
2868 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2870 SilcServerKEInternalContext *proto_ctx =
2871 (SilcServerKEInternalContext *)sock->protocol->context;
2873 if (proto_ctx->packet)
2874 silc_packet_context_free(proto_ctx->packet);
2876 proto_ctx->packet = silc_packet_context_dup(packet);
2877 proto_ctx->dest_id_type = packet->src_id_type;
2878 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2879 packet->src_id_type);
2880 if (!proto_ctx->dest_id)
2883 /* Let the protocol handle the packet */
2884 silc_protocol_execute(sock->protocol, server->schedule,
2888 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2889 "protocol active (%s:%d [%s]).", sock->hostname,
2891 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2892 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2893 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2898 case SILC_PACKET_KEY_EXCHANGE_2:
2899 if (packet->flags & SILC_PACKET_FLAG_LIST)
2902 if (sock->protocol && sock->protocol->protocol &&
2903 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2904 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2906 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2907 SilcServerRekeyInternalContext *proto_ctx =
2908 (SilcServerRekeyInternalContext *)sock->protocol->context;
2910 if (proto_ctx->packet)
2911 silc_packet_context_free(proto_ctx->packet);
2913 proto_ctx->packet = silc_packet_context_dup(packet);
2915 /* Let the protocol handle the packet */
2916 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2918 SilcServerKEInternalContext *proto_ctx =
2919 (SilcServerKEInternalContext *)sock->protocol->context;
2921 if (proto_ctx->packet)
2922 silc_packet_context_free(proto_ctx->packet);
2924 proto_ctx->packet = silc_packet_context_dup(packet);
2925 proto_ctx->dest_id_type = packet->src_id_type;
2926 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2927 packet->src_id_type);
2928 if (!proto_ctx->dest_id)
2931 /* Let the protocol handle the packet */
2932 silc_protocol_execute(sock->protocol, server->schedule,
2936 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2937 "protocol active (%s:%d [%s]).", sock->hostname,
2939 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2940 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2941 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2946 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2948 * Connection authentication request packet. When we receive this packet
2949 * we will send to the other end information about our mandatory
2950 * authentication method for the connection. This packet maybe received
2953 if (packet->flags & SILC_PACKET_FLAG_LIST)
2955 silc_server_connection_auth_request(server, sock, packet);
2959 * Connection Authentication protocol packets
2961 case SILC_PACKET_CONNECTION_AUTH:
2962 /* Start of the authentication protocol. We receive here the
2963 authentication data and will verify it. */
2964 if (packet->flags & SILC_PACKET_FLAG_LIST)
2967 if (sock->protocol && sock->protocol->protocol->type
2968 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2970 SilcServerConnAuthInternalContext *proto_ctx =
2971 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2973 proto_ctx->packet = silc_packet_context_dup(packet);
2975 /* Let the protocol handle the packet */
2976 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2978 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2979 "protocol active (%s:%d [%s]).", sock->hostname,
2981 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2982 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2983 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2988 case SILC_PACKET_NEW_ID:
2990 * Received New ID packet. This includes some new ID that has been
2991 * created. It may be for client, server or channel. This is the way
2992 * to distribute information about new registered entities in the
2995 if (packet->flags & SILC_PACKET_FLAG_LIST)
2996 silc_server_new_id_list(server, sock, packet);
2998 silc_server_new_id(server, sock, packet);
3001 case SILC_PACKET_NEW_CLIENT:
3003 * Received new client packet. This includes client information that
3004 * we will use to create initial client ID. After creating new
3005 * ID we will send it to the client.
3007 if (packet->flags & SILC_PACKET_FLAG_LIST)
3009 silc_server_new_client(server, sock, packet);
3012 case SILC_PACKET_NEW_SERVER:
3014 * Received new server packet. This includes Server ID and some other
3015 * information that we may save. This is received after server has
3018 if (packet->flags & SILC_PACKET_FLAG_LIST)
3020 silc_server_new_server(server, sock, packet);
3023 case SILC_PACKET_NEW_CHANNEL:
3025 * Received new channel packet. Information about new channel in the
3026 * network are distributed using this packet.
3028 if (packet->flags & SILC_PACKET_FLAG_LIST)
3029 silc_server_new_channel_list(server, sock, packet);
3031 silc_server_new_channel(server, sock, packet);
3034 case SILC_PACKET_HEARTBEAT:
3036 * Received heartbeat.
3038 if (packet->flags & SILC_PACKET_FLAG_LIST)
3042 case SILC_PACKET_KEY_AGREEMENT:
3044 * Received heartbeat.
3046 if (packet->flags & SILC_PACKET_FLAG_LIST)
3048 silc_server_key_agreement(server, sock, packet);
3051 case SILC_PACKET_REKEY:
3053 * Received re-key packet. The sender wants to regenerate the session
3056 if (packet->flags & SILC_PACKET_FLAG_LIST)
3058 silc_server_rekey(server, sock, packet);
3061 case SILC_PACKET_REKEY_DONE:
3063 * The re-key is done.
3065 if (packet->flags & SILC_PACKET_FLAG_LIST)
3068 if (sock->protocol && sock->protocol->protocol &&
3069 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
3071 SilcServerRekeyInternalContext *proto_ctx =
3072 (SilcServerRekeyInternalContext *)sock->protocol->context;
3074 if (proto_ctx->packet)
3075 silc_packet_context_free(proto_ctx->packet);
3077 proto_ctx->packet = silc_packet_context_dup(packet);
3079 /* Let the protocol handle the packet */
3080 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
3082 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
3083 "protocol active (%s:%d [%s]).", sock->hostname,
3085 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
3086 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
3087 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
3092 case SILC_PACKET_FTP:
3094 if (packet->flags & SILC_PACKET_FLAG_LIST)
3096 silc_server_ftp(server, sock, packet);
3099 case SILC_PACKET_RESUME_CLIENT:
3101 if (packet->flags & SILC_PACKET_FLAG_LIST)
3103 silc_server_resume_client(server, sock, packet);
3106 case SILC_PACKET_RESUME_ROUTER:
3107 /* Resume router packet received. This packet is received for backup
3108 router resuming protocol. */
3109 if (packet->flags & SILC_PACKET_FLAG_LIST)
3111 silc_server_backup_resume_router(server, sock, packet);
3115 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
3120 /* Creates connection to a remote router. */
3122 void silc_server_create_connection(SilcServer server,
3123 const char *remote_host, SilcUInt32 port)
3125 SilcServerConnection sconn;
3127 /* Allocate connection object for hold connection specific stuff. */
3128 sconn = silc_calloc(1, sizeof(*sconn));
3129 sconn->remote_host = strdup(remote_host);
3130 sconn->remote_port = port;
3131 sconn->no_reconnect = TRUE;
3133 silc_schedule_task_add(server->schedule, 0,
3134 silc_server_connect_router,
3135 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
3136 SILC_TASK_PRI_NORMAL);
3139 SILC_TASK_CALLBACK(silc_server_close_connection_final)
3141 SilcServer server = app_context;
3142 SilcSocketConnection sock = context;
3144 SILC_LOG_DEBUG(("Deleting socket %p", sock));
3146 /* Close the actual connection */
3147 silc_net_close_connection(sock->sock);
3148 server->sockets[sock->sock] = NULL;
3150 /* We won't listen for this connection anymore */
3151 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
3152 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
3154 silc_socket_free(sock);
3157 /* Closes connection to socket connection */
3159 void silc_server_close_connection(SilcServer server,
3160 SilcSocketConnection sock)
3164 if (SILC_IS_DISCONNECTED(sock)) {
3165 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
3166 silc_schedule_task_add(server->schedule, sock->sock,
3167 silc_server_close_connection_final,
3168 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
3169 SILC_TASK_PRI_NORMAL);
3170 server->sockets[sock->sock] = NULL;
3174 /* If any protocol is active cancel its execution. It will call
3175 the final callback which will finalize the disconnection. */
3176 if (sock->protocol && sock->protocol->protocol &&
3177 sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3178 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3179 silc_protocol_cancel(sock->protocol, server->schedule);
3180 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3181 silc_protocol_execute_final(sock->protocol, server->schedule);
3182 sock->protocol = NULL;
3186 memset(tmp, 0, sizeof(tmp));
3187 silc_socket_get_error(sock, tmp, sizeof(tmp));
3188 SILC_LOG_INFO(("Closing connection %s:%d [%s] %s", sock->hostname,
3190 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
3191 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
3192 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
3193 "Router"), tmp[0] ? tmp : ""));
3195 SILC_SET_DISCONNECTED(sock);
3196 silc_socket_set_qos(sock, 0, 0, 0, 0, NULL);
3197 silc_schedule_task_add(server->schedule, sock->sock,
3198 silc_server_close_connection_final,
3199 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
3200 SILC_TASK_PRI_NORMAL);
3201 server->sockets[sock->sock] = NULL;
3204 /* Sends disconnect message to remote connection and disconnects the
3205 connection. NOTE: If this is called from protocol callback
3206 then sock->protocol must be set NULL before calling this, since
3207 this routine dispatches protocol callbacks too. */
3209 void silc_server_disconnect_remote(SilcServer server,
3210 SilcSocketConnection sock,
3211 SilcStatus status, ...)
3214 unsigned char buf[512];
3222 if (SILC_IS_DISCONNECTING(sock)) {
3223 SILC_SET_DISCONNECTED(sock);
3224 silc_server_close_connection(server, sock);
3228 memset(buf, 0, sizeof(buf));
3229 va_start(ap, status);
3230 cp = va_arg(ap, char *);
3232 vsnprintf(buf, sizeof(buf) - 1, cp, ap);
3237 SILC_LOG_DEBUG(("Disconnecting remote host"));
3239 /* Notify remote end that the conversation is over. The notify message
3240 is tried to be sent immediately. */
3244 len += silc_utf8_encoded_len(buf, strlen(buf), SILC_STRING_ASCII);
3246 buffer = silc_buffer_alloc_size(len);
3250 buffer->data[0] = status;
3252 silc_utf8_encode(buf, strlen(buf), SILC_STRING_ASCII, buffer->data + 1,
3254 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
3255 buffer->data, buffer->len, TRUE);
3256 silc_buffer_free(buffer);
3259 silc_server_packet_queue_purge(server, sock);
3261 /* Mark the connection to be disconnected */
3262 SILC_SET_DISCONNECTING(sock);
3263 silc_server_close_connection(server, sock);
3266 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
3268 SilcServer server = app_context;
3269 SilcClientEntry client = context;
3271 assert(!silc_hash_table_count(client->channels));
3273 silc_idlist_del_data(client);
3274 silc_idcache_purge_by_context(server->local_list->clients, client);
3277 /* Frees client data and notifies about client's signoff. */
3279 void silc_server_free_client_data(SilcServer server,
3280 SilcSocketConnection sock,
3281 SilcClientEntry client,
3283 const char *signoff)
3285 SILC_LOG_DEBUG(("Freeing client data"));
3287 /* If there is pending outgoing data for the client then purge it
3288 to the network before removing the client entry. */
3289 silc_server_packet_queue_purge(server, sock);
3292 /* Check if anyone is watching this nickname */
3293 if (server->server_type == SILC_ROUTER)
3294 silc_server_check_watcher_list(server, client, NULL,
3295 SILC_NOTIFY_TYPE_SIGNOFF);
3297 /* Send SIGNOFF notify to routers. */
3299 silc_server_send_notify_signoff(server, SILC_PRIMARY_ROUTE(server),
3300 SILC_BROADCAST(server), client->id,
3304 /* Remove client from all channels */
3306 silc_server_remove_from_channels(server, NULL, client,
3307 TRUE, (char *)signoff, TRUE, FALSE);
3309 silc_server_remove_from_channels(server, NULL, client,
3310 FALSE, NULL, FALSE, FALSE);
3312 /* Remove this client from watcher list if it is */
3313 silc_server_del_from_watcher_list(server, client);
3315 /* Remove this client from the public key hash list */
3316 if (client->data.public_key)
3317 silc_hash_table_del_by_context(server->pk_hash,
3318 client->data.public_key, client);
3320 /* Update statistics */
3321 server->stat.my_clients--;
3322 server->stat.clients--;
3323 if (server->stat.cell_clients)
3324 server->stat.cell_clients--;
3325 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
3326 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
3327 silc_schedule_task_del_by_context(server->schedule, client);
3329 /* We will not delete the client entry right away. We will take it
3330 into history (for WHOWAS command) for 5 minutes, unless we're
3331 shutting down server. */
3332 if (!server->server_shutdown) {
3333 silc_schedule_task_add(server->schedule, 0,
3334 silc_server_free_client_data_timeout,
3336 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
3337 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
3338 client->data.status &= ~SILC_IDLIST_STATUS_LOCAL;
3340 client->router = NULL;
3341 client->connection = NULL;
3343 /* Delete directly since we're shutting down server */
3344 silc_idlist_del_data(client);
3345 silc_idlist_del_client(server->local_list, client);
3349 /* Frees user_data pointer from socket connection object. This also sends
3350 appropriate notify packets to the network to inform about leaving
3353 void silc_server_free_sock_user_data(SilcServer server,
3354 SilcSocketConnection sock,
3355 const char *signoff_message)
3358 /* If any protocol is active cancel its execution */
3359 if (sock->protocol && sock->protocol->protocol &&
3360 sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3361 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3362 silc_protocol_cancel(sock->protocol, server->schedule);
3363 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3364 silc_protocol_execute_final(sock->protocol, server->schedule);
3365 sock->protocol = NULL;
3368 switch (sock->type) {
3369 case SILC_SOCKET_TYPE_CLIENT:
3371 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
3372 silc_server_free_client_data(server, sock, user_data, TRUE,
3376 case SILC_SOCKET_TYPE_SERVER:
3377 case SILC_SOCKET_TYPE_ROUTER:
3379 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
3380 SilcServerEntry backup_router = NULL;
3382 SILC_LOG_DEBUG(("Freeing server data"));
3385 backup_router = silc_server_backup_get(server, user_data->id);
3387 if (!server->backup_router && server->server_type == SILC_ROUTER &&
3388 backup_router == server->id_entry &&
3389 sock->type != SILC_SOCKET_TYPE_ROUTER)
3390 backup_router = NULL;
3392 if (server->server_shutdown || server->backup_noswitch)
3393 backup_router = NULL;
3395 /* If this was our primary router connection then we're lost to
3396 the outside world. */
3397 if (server->router == user_data) {
3398 /* Check whether we have a backup router connection */
3399 if (!backup_router || backup_router == user_data) {
3400 if (!server->no_reconnect)
3401 silc_server_create_connections(server);
3402 server->id_entry->router = NULL;
3403 server->router = NULL;
3404 server->standalone = TRUE;
3405 server->backup_primary = FALSE;
3406 backup_router = NULL;
3408 if (server->id_entry != backup_router) {
3409 SILC_LOG_INFO(("New primary router is backup router %s",
3410 backup_router->server_name));
3411 server->id_entry->router = backup_router;
3412 server->router = backup_router;
3413 server->router_connect = time(0);
3414 server->backup_primary = TRUE;
3415 backup_router->data.status &= ~SILC_IDLIST_STATUS_DISABLED;
3417 /* Send START_USE to backup router to indicate we have switched */
3418 silc_server_backup_send_start_use(server,
3419 backup_router->connection,
3422 SILC_LOG_INFO(("We are now new primary router in this cell"));
3423 server->id_entry->router = NULL;
3424 server->router = NULL;
3425 server->standalone = TRUE;
3428 /* We stop here to take a breath */
3431 if (server->backup_router) {
3432 server->server_type = SILC_ROUTER;
3434 /* We'll need to constantly try to reconnect to the primary
3435 router so that we'll see when it comes back online. */
3436 silc_server_backup_reconnect(server, sock->ip, sock->port,
3437 silc_server_backup_connected,
3441 /* Mark this connection as replaced */
3442 silc_server_backup_replaced_add(server, user_data->id,
3445 } else if (backup_router) {
3446 SILC_LOG_INFO(("Enabling the use of backup router %s",
3447 backup_router->server_name));
3449 /* Mark this connection as replaced */
3450 silc_server_backup_replaced_add(server, user_data->id,
3452 } else if (server->server_type == SILC_SERVER &&
3453 sock->type == SILC_SOCKET_TYPE_ROUTER) {
3454 /* Reconnect to the router (backup) */
3455 if (!server->no_reconnect)
3456 silc_server_create_connections(server);
3459 if (user_data->server_name)
3460 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
3461 ("Server %s signoff", user_data->server_name));
3463 if (!backup_router) {
3464 /* Remove all servers that are originated from this server, and
3465 remove the clients of those servers too. */
3466 silc_server_remove_servers_by_server(server, user_data, TRUE);
3469 /* Remove the clients that this server owns as they will become
3470 invalid now too. For backup router the server is actually
3471 coming from the primary router, so mark that as the owner
3473 if (server->server_type == SILC_BACKUP_ROUTER &&
3474 sock->type == SILC_SOCKET_TYPE_SERVER)
3475 silc_server_remove_clients_by_server(server, server->router,
3479 silc_server_remove_clients_by_server(server, user_data,
3482 /* Remove channels owned by this server */
3483 if (server->server_type == SILC_SERVER)
3484 silc_server_remove_channels_by_server(server, user_data);
3486 /* Enable local server connections that may be disabled */
3487 silc_server_local_servers_toggle_enabled(server, TRUE);
3489 /* Update the client entries of this server to the new backup
3490 router. If we are the backup router we also resolve the real
3491 servers for the clients. After updating is over this also
3492 removes the clients that this server explicitly owns. */
3493 silc_server_update_clients_by_server(server, user_data,
3494 backup_router, TRUE);
3496 /* If we are router and just lost our primary router (now standlaone)
3497 we remove everything that was behind it, since we don't know
3499 if (server->server_type == SILC_ROUTER && server->standalone)
3500 /* Remove all servers that are originated from this server, and
3501 remove the clients of those servers too. */
3502 silc_server_remove_servers_by_server(server, user_data, TRUE);
3504 /* Finally remove the clients that are explicitly owned by this
3505 server. They go down with the server. */
3506 silc_server_remove_clients_by_server(server, user_data,
3509 /* Update our server cache to use the new backup router too. */
3510 silc_server_update_servers_by_server(server, user_data, backup_router);
3511 if (server->server_type == SILC_SERVER)
3512 silc_server_update_channels_by_server(server, user_data,
3515 /* Send notify about primary router going down to local operators */
3516 if (server->backup_router)
3517 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3518 SILC_NOTIFY_TYPE_NONE,
3519 ("%s switched to backup router %s "
3520 "(we are primary router now)",
3521 server->server_name, server->server_name));
3522 else if (server->router)
3523 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3524 SILC_NOTIFY_TYPE_NONE,
3525 ("%s switched to backup router %s",
3526 server->server_name,
3527 server->router->server_name));
3529 server->backup_noswitch = FALSE;
3531 /* Free the server entry */
3532 silc_server_backup_del(server, user_data);
3533 silc_server_backup_replaced_del(server, user_data);
3534 silc_idlist_del_data(user_data);
3535 if (!silc_idlist_del_server(server->local_list, user_data))
3536 silc_idlist_del_server(server->global_list, user_data);
3537 if (sock->type == SILC_SOCKET_TYPE_SERVER) {
3538 server->stat.my_servers--;
3540 server->stat.my_routers--;
3541 server->stat.routers--;
3543 server->stat.servers--;
3544 if (server->server_type == SILC_ROUTER)
3545 server->stat.cell_servers--;
3547 if (backup_router && backup_router != server->id_entry) {
3548 /* Announce all of our stuff that was created about 5 minutes ago.
3549 The backup router knows all the other stuff already. */
3550 if (server->server_type == SILC_ROUTER)
3551 silc_server_announce_servers(server, FALSE, time(0) - 300,
3552 backup_router->connection);
3554 /* Announce our clients and channels to the router */
3555 silc_server_announce_clients(server, time(0) - 300,
3556 backup_router->connection);
3557 silc_server_announce_channels(server, time(0) - 300,
3558 backup_router->connection);
3564 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
3566 SILC_LOG_DEBUG(("Freeing unknown connection data"));
3568 silc_idlist_del_data(user_data);
3569 silc_free(user_data);
3574 sock->user_data = NULL;
3577 /* Removes client from all channels it has joined. This is used when client
3578 connection is disconnected. If the client on a channel is last, the
3579 channel is removed as well. This sends the SIGNOFF notify types. */
3581 void silc_server_remove_from_channels(SilcServer server,
3582 SilcSocketConnection sock,
3583 SilcClientEntry client,
3585 const char *signoff_message,
3589 SilcChannelEntry channel;
3590 SilcChannelClientEntry chl;
3591 SilcHashTableList htl;
3592 SilcBuffer clidp = NULL;
3597 if (notify && !client->id)
3600 SILC_LOG_DEBUG(("Removing client %s from joined channels",
3601 notify ? silc_id_render(client->id, SILC_ID_CLIENT) : ""));
3604 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3609 /* Remove the client from all channels. The client is removed from
3610 the channels' user list. */
3611 silc_hash_table_list(client->channels, &htl);
3612 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3613 channel = chl->channel;
3615 /* Remove channel if this is last client leaving the channel, unless
3616 the channel is permanent. */
3617 if (server->server_type != SILC_SERVER &&
3618 silc_hash_table_count(channel->user_list) < 2) {
3619 silc_server_channel_delete(server, channel);
3623 silc_hash_table_del(client->channels, channel);
3624 silc_hash_table_del(channel->user_list, client);
3625 channel->user_count--;
3627 /* If there is no global users on the channel anymore mark the channel
3628 as local channel. Do not check if the removed client is local client. */
3629 if (server->server_type == SILC_SERVER && channel->global_users &&
3630 chl->client->router && !silc_server_channel_has_global(channel))
3631 channel->global_users = FALSE;
3633 memset(chl, 'A', sizeof(*chl));
3636 /* Update statistics */
3637 if (SILC_IS_LOCAL(client))
3638 server->stat.my_chanclients--;
3639 if (server->server_type == SILC_ROUTER) {
3640 server->stat.cell_chanclients--;
3641 server->stat.chanclients--;
3644 /* If there is not at least one local user on the channel then we don't
3645 need the channel entry anymore, we can remove it safely, unless the
3646 channel is permanent channel */
3647 if (server->server_type == SILC_SERVER &&
3648 !silc_server_channel_has_local(channel)) {
3649 /* Notify about leaving client if this channel has global users. */
3650 if (notify && channel->global_users)
3651 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3652 SILC_NOTIFY_TYPE_SIGNOFF,
3653 signoff_message ? 2 : 1,
3654 clidp->data, clidp->len,
3655 signoff_message, signoff_message ?
3656 strlen(signoff_message) : 0);
3658 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3659 silc_server_channel_delete(server, channel);
3663 /* Send notify to channel about client leaving SILC and channel too */
3665 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3666 SILC_NOTIFY_TYPE_SIGNOFF,
3667 signoff_message ? 2 : 1,
3668 clidp->data, clidp->len,
3669 signoff_message, signoff_message ?
3670 strlen(signoff_message) : 0);
3672 if (killed && clidp) {
3673 /* Remove the client from channel's invite list */
3674 if (channel->invite_list &&
3675 silc_hash_table_count(channel->invite_list)) {
3677 SilcArgumentPayload iargs;
3678 ab = silc_argument_payload_encode_one(NULL, clidp->data,
3680 iargs = silc_argument_payload_parse(ab->data, ab->len, 1);
3681 silc_server_inviteban_process(server, channel->invite_list, 1, iargs);
3682 silc_buffer_free(ab);
3683 silc_argument_payload_free(iargs);
3687 /* Don't create keys if we are shutting down */
3688 if (server->server_shutdown)
3691 /* Re-generate channel key if needed */
3692 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3693 if (!silc_server_create_channel_key(server, channel, 0))
3696 /* Send the channel key to the channel. The key of course is not sent
3697 to the client who was removed from the channel. */
3698 silc_server_send_channel_key(server, client->connection, channel,
3699 server->server_type == SILC_ROUTER ?
3700 FALSE : !server->standalone);
3704 silc_hash_table_list_reset(&htl);
3706 silc_buffer_free(clidp);
3709 /* Removes client from one channel. This is used for example when client
3710 calls LEAVE command to remove itself from the channel. Returns TRUE
3711 if channel still exists and FALSE if the channel is removed when
3712 last client leaves the channel. If `notify' is FALSE notify messages
3715 bool silc_server_remove_from_one_channel(SilcServer server,
3716 SilcSocketConnection sock,
3717 SilcChannelEntry channel,
3718 SilcClientEntry client,
3721 SilcChannelClientEntry chl;
3724 SILC_LOG_DEBUG(("Removing %s from channel %s",
3725 silc_id_render(client->id, SILC_ID_CLIENT),
3726 channel->channel_name));
3728 /* Get the entry to the channel, if this client is not on the channel
3730 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
3733 /* Remove channel if this is last client leaving the channel, unless
3734 the channel is permanent. */
3735 if (server->server_type != SILC_SERVER &&
3736 silc_hash_table_count(channel->user_list) < 2) {
3737 silc_server_channel_delete(server, channel);
3741 silc_hash_table_del(client->channels, channel);
3742 silc_hash_table_del(channel->user_list, client);
3743 channel->user_count--;
3745 /* If there is no global users on the channel anymore mark the channel
3746 as local channel. Do not check if the client is local client. */
3747 if (server->server_type == SILC_SERVER && channel->global_users &&
3748 chl->client->router && !silc_server_channel_has_global(channel))
3749 channel->global_users = FALSE;
3751 memset(chl, 'O', sizeof(*chl));
3754 /* Update statistics */
3755 if (SILC_IS_LOCAL(client))
3756 server->stat.my_chanclients--;
3757 if (server->server_type == SILC_ROUTER) {
3758 server->stat.cell_chanclients--;
3759 server->stat.chanclients--;
3762 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3766 /* If there is not at least one local user on the channel then we don't
3767 need the channel entry anymore, we can remove it safely, unless the
3768 channel is permanent channel */
3769 if (server->server_type == SILC_SERVER &&
3770 !silc_server_channel_has_local(channel)) {
3771 /* Notify about leaving client if this channel has global users. */
3772 if (notify && channel->global_users)
3773 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3774 SILC_NOTIFY_TYPE_LEAVE, 1,
3775 clidp->data, clidp->len);
3777 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3778 silc_server_channel_delete(server, channel);
3779 silc_buffer_free(clidp);
3783 /* Send notify to channel about client leaving the channel */
3785 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3786 SILC_NOTIFY_TYPE_LEAVE, 1,
3787 clidp->data, clidp->len);
3789 silc_buffer_free(clidp);
3793 /* Timeout callback. This is called if connection is idle or for some
3794 other reason is not responding within some period of time. This
3795 disconnects the remote end. */
3797 SILC_TASK_CALLBACK(silc_server_timeout_remote)
3799 SilcServer server = (SilcServer)context;
3800 SilcSocketConnection sock = server->sockets[fd];
3801 SilcProtocolType protocol = 0;
3803 SILC_LOG_DEBUG(("Start"));
3808 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
3809 sock->hostname, sock->ip));
3811 /* If we have protocol active we must assure that we call the protocol's
3812 final callback so that all the memory is freed. */
3813 if (sock->protocol && sock->protocol->protocol &&
3814 sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3815 protocol = sock->protocol->protocol->type;
3816 silc_protocol_cancel(sock->protocol, server->schedule);
3817 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3818 silc_protocol_execute_final(sock->protocol, server->schedule);
3819 sock->protocol = NULL;
3823 silc_server_disconnect_remote(server, sock,
3825 SILC_PROTOCOL_SERVER_CONNECTION_AUTH ?
3826 SILC_STATUS_ERR_AUTH_FAILED :
3827 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
3828 "Connection timeout");
3830 if (sock->user_data)
3831 silc_server_free_sock_user_data(server, sock, NULL);
3834 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
3835 function may be used only by router. In real SILC network all channels
3836 are created by routers thus this function is never used by normal
3839 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3840 SilcServerID *router_id,
3846 SilcChannelID *channel_id;
3847 SilcChannelEntry entry;
3851 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3854 cipher = SILC_DEFAULT_CIPHER;
3856 hmac = SILC_DEFAULT_HMAC;
3858 /* Allocate cipher */
3859 if (!silc_cipher_alloc(cipher, &key))
3863 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3864 silc_cipher_free(key);
3868 channel_name = strdup(channel_name);
3870 /* Create the channel ID */
3871 if (!silc_id_create_channel_id(server, router_id, server->rng,
3873 silc_free(channel_name);
3874 silc_cipher_free(key);
3875 silc_hmac_free(newhmac);
3879 /* Create the channel */
3880 entry = silc_idlist_add_channel(server->local_list, channel_name,
3881 SILC_CHANNEL_MODE_NONE, channel_id,
3882 NULL, key, newhmac, 0);
3884 silc_free(channel_name);
3885 silc_cipher_free(key);
3886 silc_hmac_free(newhmac);
3887 silc_free(channel_id);
3891 entry->cipher = strdup(cipher);
3892 entry->hmac_name = strdup(hmac);
3894 /* Now create the actual key material */
3895 if (!silc_server_create_channel_key(server, entry,
3896 silc_cipher_get_key_len(key) / 8)) {
3897 silc_idlist_del_channel(server->local_list, entry);
3901 /* Notify other routers about the new channel. We send the packet
3902 to our primary route. */
3904 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3905 channel_name, entry->id,
3906 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3909 /* Distribute to backup routers */
3910 if (broadcast && server->server_type == SILC_ROUTER) {
3913 SilcUInt32 name_len = strlen(channel_name);
3914 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3915 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3917 packet = silc_channel_payload_encode(channel_name, name_len,
3918 cid, channel_id_len, entry->mode);
3919 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3920 packet->data, packet->len, FALSE, TRUE);
3922 silc_buffer_free(packet);
3925 server->stat.my_channels++;
3926 if (server->server_type == SILC_ROUTER) {
3927 server->stat.channels++;
3928 server->stat.cell_channels++;
3929 entry->users_resolved = TRUE;
3935 /* Same as above but creates the channel with Channel ID `channel_id. */
3938 silc_server_create_new_channel_with_id(SilcServer server,
3942 SilcChannelID *channel_id,
3945 SilcChannelEntry entry;
3949 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3952 cipher = SILC_DEFAULT_CIPHER;
3954 hmac = SILC_DEFAULT_HMAC;
3956 /* Allocate cipher */
3957 if (!silc_cipher_alloc(cipher, &key))
3961 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3962 silc_cipher_free(key);
3966 channel_name = strdup(channel_name);
3968 /* Create the channel */
3969 entry = silc_idlist_add_channel(server->local_list, channel_name,
3970 SILC_CHANNEL_MODE_NONE, channel_id,
3971 NULL, key, newhmac, 0);
3973 silc_cipher_free(key);
3974 silc_hmac_free(newhmac);
3975 silc_free(channel_name);
3979 /* Now create the actual key material */
3980 if (!silc_server_create_channel_key(server, entry,
3981 silc_cipher_get_key_len(key) / 8)) {
3982 silc_idlist_del_channel(server->local_list, entry);
3986 /* Notify other routers about the new channel. We send the packet
3987 to our primary route. */
3989 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3990 channel_name, entry->id,
3991 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3994 /* Distribute to backup routers */
3995 if (broadcast && server->server_type == SILC_ROUTER) {
3998 SilcUInt32 name_len = strlen(channel_name);
3999 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
4000 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
4002 packet = silc_channel_payload_encode(channel_name, name_len,
4003 cid, channel_id_len, entry->mode);
4004 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
4005 packet->data, packet->len, FALSE, TRUE);
4007 silc_buffer_free(packet);
4010 server->stat.my_channels++;
4011 if (server->server_type == SILC_ROUTER) {
4012 server->stat.channels++;
4013 server->stat.cell_channels++;
4014 entry->users_resolved = TRUE;
4020 /* Channel's key re-key timeout callback. */
4022 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
4024 SilcServer server = app_context;
4025 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
4029 /* Return now if we are shutting down */
4030 if (server->server_shutdown)
4033 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
4036 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
4039 /* Generates new channel key. This is used to create the initial channel key
4040 but also to re-generate new key for channel. If `key_len' is provided
4041 it is the bytes of the key length. */
4043 bool silc_server_create_channel_key(SilcServer server,
4044 SilcChannelEntry channel,
4048 unsigned char channel_key[32], hash[32];
4051 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
4052 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
4056 SILC_LOG_DEBUG(("Generating channel %s key", channel->channel_name));
4058 if (!channel->channel_key)
4059 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
4060 channel->channel_key = NULL;
4066 else if (channel->key_len)
4067 len = channel->key_len / 8;
4069 len = silc_cipher_get_key_len(channel->channel_key) / 8;
4071 /* Create channel key */
4072 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
4075 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
4077 /* Remove old key if exists */
4079 memset(channel->key, 0, channel->key_len / 8);
4080 silc_free(channel->key);
4084 channel->key_len = len * 8;
4085 channel->key = silc_memdup(channel_key, len);
4086 memset(channel_key, 0, sizeof(channel_key));
4088 /* Generate HMAC key from the channel key data and set it */
4090 if (!silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac)) {
4091 memset(channel->key, 0, channel->key_len / 8);
4092 silc_free(channel->key);
4093 channel->channel_key = NULL;
4096 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
4097 silc_hmac_set_key(channel->hmac, hash,
4098 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
4099 memset(hash, 0, sizeof(hash));
4101 if (server->server_type == SILC_ROUTER) {
4102 if (!channel->rekey)
4103 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
4104 channel->rekey->channel = channel;
4105 channel->rekey->key_len = key_len;
4106 if (channel->rekey->task)
4107 silc_schedule_task_del(server->schedule, channel->rekey->task);
4109 channel->rekey->task =
4110 silc_schedule_task_add(server->schedule, 0,
4111 silc_server_channel_key_rekey,
4112 (void *)channel->rekey,
4113 server->config->channel_rekey_secs, 0,
4115 SILC_TASK_PRI_NORMAL);
4121 /* Saves the channel key found in the encoded `key_payload' buffer. This
4122 function is used when we receive Channel Key Payload and also when we're
4123 processing JOIN command reply. Returns entry to the channel. */
4125 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
4126 SilcBuffer key_payload,
4127 SilcChannelEntry channel)
4129 SilcChannelKeyPayload payload = NULL;
4130 SilcChannelID *id = NULL;
4131 unsigned char *tmp, hash[32];
4135 /* Decode channel key payload */
4136 payload = silc_channel_key_payload_parse(key_payload->data,
4139 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
4144 /* Get the channel entry */
4147 /* Get channel ID */
4148 tmp = silc_channel_key_get_id(payload, &tmp_len);
4149 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
4155 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
4157 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
4159 if (server->server_type == SILC_ROUTER)
4160 SILC_LOG_ERROR(("Received key for non-existent channel %s",
4161 silc_id_render(id, SILC_ID_CHANNEL)));
4167 SILC_LOG_DEBUG(("Saving new channel %s key", channel->channel_name));
4169 tmp = silc_channel_key_get_key(payload, &tmp_len);
4175 cipher = silc_channel_key_get_cipher(payload, NULL);
4181 /* Remove old key if exists */
4183 memset(channel->key, 0, channel->key_len / 8);
4184 silc_free(channel->key);
4185 silc_cipher_free(channel->channel_key);
4188 /* Create new cipher */
4189 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
4190 channel->channel_key = NULL;
4195 if (channel->cipher)
4196 silc_free(channel->cipher);
4197 channel->cipher = strdup(cipher);
4200 channel->key_len = tmp_len * 8;
4201 channel->key = silc_memdup(tmp, tmp_len);
4202 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
4204 /* Generate HMAC key from the channel key data and set it */
4206 if (!silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac)) {
4207 memset(channel->key, 0, channel->key_len / 8);
4208 silc_free(channel->key);
4209 channel->channel_key = NULL;
4212 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
4213 silc_hmac_set_key(channel->hmac, hash,
4214 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
4216 memset(hash, 0, sizeof(hash));
4217 memset(tmp, 0, tmp_len);
4219 if (server->server_type == SILC_ROUTER) {
4220 if (!channel->rekey)
4221 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
4222 channel->rekey->channel = channel;
4223 if (channel->rekey->task)
4224 silc_schedule_task_del(server->schedule, channel->rekey->task);
4226 channel->rekey->task =
4227 silc_schedule_task_add(server->schedule, 0,
4228 silc_server_channel_key_rekey,
4229 (void *)channel->rekey,
4230 server->config->channel_rekey_secs, 0,
4232 SILC_TASK_PRI_NORMAL);
4238 silc_channel_key_payload_free(payload);
4243 /* Heartbeat callback. This function is set as argument for the
4244 silc_socket_set_heartbeat function. The library will call this function
4245 at the set time interval. */
4247 void silc_server_perform_heartbeat(SilcSocketConnection sock,
4250 SilcServer server = hb_context;
4252 SILC_LOG_DEBUG(("Sending heartbeat to %s:%d (%s)", sock->hostname,
4253 sock->port, sock->ip));
4255 /* Send the heartbeat */
4256 silc_server_send_heartbeat(server, sock);
4259 /* Returns assembled of all servers in the given ID list. The packet's
4260 form is dictated by the New ID payload. */
4262 static void silc_server_announce_get_servers(SilcServer server,
4263 SilcServerEntry remote,
4265 SilcBuffer *servers,
4266 unsigned long creation_time)
4268 SilcIDCacheList list;
4269 SilcIDCacheEntry id_cache;
4270 SilcServerEntry entry;
4273 /* Go through all clients in the list */
4274 if (silc_idcache_get_all(id_list->servers, &list)) {
4275 if (silc_idcache_list_first(list, &id_cache)) {
4277 entry = (SilcServerEntry)id_cache->context;
4279 /* Do not announce the one we've sending our announcements and
4280 do not announce ourself. Also check the creation time if it's
4282 if ((entry == remote) || (entry == server->id_entry) ||
4283 (creation_time && entry->data.created < creation_time)) {
4284 if (!silc_idcache_list_next(list, &id_cache))
4289 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
4291 *servers = silc_buffer_realloc(*servers,
4293 (*servers)->truelen + idp->len :
4295 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
4296 silc_buffer_put(*servers, idp->data, idp->len);
4297 silc_buffer_pull(*servers, idp->len);
4298 silc_buffer_free(idp);
4300 if (!silc_idcache_list_next(list, &id_cache))
4305 silc_idcache_list_free(list);
4310 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
4316 p = silc_notify_payload_encode(notify, argc, ap);
4322 /* This function is used by router to announce existing servers to our
4323 primary router when we've connected to it. If `creation_time' is non-zero
4324 then only the servers that has been created after the `creation_time'
4325 will be announced. */
4327 void silc_server_announce_servers(SilcServer server, bool global,
4328 unsigned long creation_time,
4329 SilcSocketConnection remote)
4331 SilcBuffer servers = NULL;
4333 SILC_LOG_DEBUG(("Announcing servers"));
4335 /* Get servers in local list */
4336 silc_server_announce_get_servers(server, remote->user_data,
4337 server->local_list, &servers,
4341 /* Get servers in global list */
4342 silc_server_announce_get_servers(server, remote->user_data,
4343 server->global_list, &servers,
4347 silc_buffer_push(servers, servers->data - servers->head);
4348 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
4350 /* Send the packet */
4351 silc_server_packet_send(server, remote,
4352 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4353 servers->data, servers->len, TRUE);
4355 silc_buffer_free(servers);
4359 /* Returns assembled packet of all clients in the given ID list. The
4360 packet's form is dictated by the New ID Payload. */
4362 static void silc_server_announce_get_clients(SilcServer server,
4364 SilcBuffer *clients,
4366 unsigned long creation_time)
4368 SilcIDCacheList list;
4369 SilcIDCacheEntry id_cache;
4370 SilcClientEntry client;
4373 unsigned char mode[4];
4375 /* Go through all clients in the list */
4376 if (silc_idcache_get_all(id_list->clients, &list)) {
4377 if (silc_idcache_list_first(list, &id_cache)) {
4379 client = (SilcClientEntry)id_cache->context;
4381 if (creation_time && client->data.created < creation_time) {
4382 if (!silc_idcache_list_next(list, &id_cache))
4386 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED) &&
4387 !client->connection && !client->router && !SILC_IS_LOCAL(client)) {
4388 if (!silc_idcache_list_next(list, &id_cache))
4393 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
4395 *clients = silc_buffer_realloc(*clients,
4397 (*clients)->truelen + idp->len :
4399 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
4400 silc_buffer_put(*clients, idp->data, idp->len);
4401 silc_buffer_pull(*clients, idp->len);
4403 SILC_PUT32_MSB(client->mode, mode);
4405 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
4406 2, idp->data, idp->len,
4408 *umodes = silc_buffer_realloc(*umodes,
4410 (*umodes)->truelen + tmp->len :
4412 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
4413 silc_buffer_put(*umodes, tmp->data, tmp->len);
4414 silc_buffer_pull(*umodes, tmp->len);
4415 silc_buffer_free(tmp);
4417 silc_buffer_free(idp);
4419 if (!silc_idcache_list_next(list, &id_cache))
4424 silc_idcache_list_free(list);
4428 /* This function is used to announce our existing clients to our router
4429 when we've connected to it. If `creation_time' is non-zero then only
4430 the clients that has been created after the `creation_time' will be
4433 void silc_server_announce_clients(SilcServer server,
4434 unsigned long creation_time,
4435 SilcSocketConnection remote)
4437 SilcBuffer clients = NULL;
4438 SilcBuffer umodes = NULL;
4440 SILC_LOG_DEBUG(("Announcing clients"));
4442 /* Get clients in local list */
4443 silc_server_announce_get_clients(server, server->local_list,
4444 &clients, &umodes, creation_time);
4446 /* As router we announce our global list as well */
4447 if (server->server_type == SILC_ROUTER)
4448 silc_server_announce_get_clients(server, server->global_list,
4449 &clients, &umodes, creation_time);
4452 silc_buffer_push(clients, clients->data - clients->head);
4453 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
4455 /* Send the packet */
4456 silc_server_packet_send(server, remote,
4457 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4458 clients->data, clients->len, TRUE);
4460 silc_buffer_free(clients);
4464 silc_buffer_push(umodes, umodes->data - umodes->head);
4465 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
4467 /* Send the packet */
4468 silc_server_packet_send(server, remote,
4469 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4470 umodes->data, umodes->len, TRUE);
4472 silc_buffer_free(umodes);
4476 /* Returns channel's topic for announcing it */
4478 void silc_server_announce_get_channel_topic(SilcServer server,
4479 SilcChannelEntry channel,
4484 if (channel->topic) {
4485 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4486 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
4487 chidp->data, chidp->len,
4489 strlen(channel->topic));
4490 silc_buffer_free(chidp);
4494 /* Returns channel's invite and ban lists */
4496 void silc_server_announce_get_inviteban(SilcServer server,
4497 SilcChannelEntry channel,
4501 SilcBuffer list, idp, idp2, tmp2;
4503 SilcHashTableList htl;
4504 const unsigned char a[1] = { 0x03 };
4506 idp = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
4508 /* Encode invite list */
4509 if (channel->invite_list && silc_hash_table_count(channel->invite_list)) {
4510 list = silc_buffer_alloc_size(2);
4511 type = silc_hash_table_count(channel->invite_list);
4512 SILC_PUT16_MSB(type, list->data);
4513 silc_hash_table_list(channel->invite_list, &htl);
4514 while (silc_hash_table_get(&htl, (void *)&type, (void *)&tmp2))
4515 list = silc_argument_payload_encode_one(list, tmp2->data, tmp2->len,
4517 silc_hash_table_list_reset(&htl);
4519 idp2 = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4521 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_INVITE, 5,
4522 idp->data, idp->len,
4523 channel->channel_name,
4524 strlen(channel->channel_name),
4525 idp2->data, idp2->len,
4527 list->data, list->len);
4528 silc_buffer_free(idp2);
4529 silc_buffer_free(list);
4532 /* Encode ban list */
4533 if (channel->ban_list && silc_hash_table_count(channel->ban_list)) {
4534 list = silc_buffer_alloc_size(2);
4535 type = silc_hash_table_count(channel->ban_list);
4536 SILC_PUT16_MSB(type, list->data);
4537 silc_hash_table_list(channel->ban_list, &htl);
4538 while (silc_hash_table_get(&htl, (void *)&type, (void *)&tmp2))
4539 list = silc_argument_payload_encode_one(list, tmp2->data, tmp2->len,
4541 silc_hash_table_list_reset(&htl);
4544 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_BAN, 3,
4545 idp->data, idp->len,
4547 list->data, list->len);
4548 silc_buffer_free(list);
4551 silc_buffer_free(idp);
4554 /* Returns assembled packets for channel users of the `channel'. */
4556 void silc_server_announce_get_channel_users(SilcServer server,
4557 SilcChannelEntry channel,
4558 SilcBuffer *channel_modes,
4559 SilcBuffer *channel_users,
4560 SilcBuffer *channel_users_modes)
4562 SilcChannelClientEntry chl;
4563 SilcHashTableList htl;
4564 SilcBuffer chidp, clidp, csidp;
4565 SilcBuffer tmp, fkey = NULL, chpklist;
4567 unsigned char mode[4];
4570 SILC_LOG_DEBUG(("Start"));
4572 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4573 csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4574 chpklist = silc_server_get_channel_pk_list(server, channel, TRUE, FALSE);
4577 SILC_PUT32_MSB(channel->mode, mode);
4578 hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
4579 if (channel->founder_key)
4580 fkey = silc_pkcs_public_key_payload_encode(channel->founder_key);
4582 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
4583 7, csidp->data, csidp->len,
4586 hmac, hmac ? strlen(hmac) : 0,
4587 channel->passphrase,
4588 channel->passphrase ?
4589 strlen(channel->passphrase) : 0,
4590 fkey ? fkey->data : NULL,
4591 fkey ? fkey->len : 0,
4592 chpklist ? chpklist->data : NULL,
4593 chpklist ? chpklist->len : 0);
4596 silc_buffer_realloc(*channel_modes,
4598 (*channel_modes)->truelen + len : len));
4599 silc_buffer_pull_tail(*channel_modes,
4600 ((*channel_modes)->end -
4601 (*channel_modes)->data));
4602 silc_buffer_put(*channel_modes, tmp->data, tmp->len);
4603 silc_buffer_pull(*channel_modes, len);
4604 silc_buffer_free(tmp);
4605 silc_buffer_free(fkey);
4608 /* Now find all users on the channel */
4609 silc_hash_table_list(channel->user_list, &htl);
4610 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4611 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4614 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
4615 clidp->data, clidp->len,
4616 chidp->data, chidp->len);
4619 silc_buffer_realloc(*channel_users,
4621 (*channel_users)->truelen + len : len));
4622 silc_buffer_pull_tail(*channel_users,
4623 ((*channel_users)->end -
4624 (*channel_users)->data));
4626 silc_buffer_put(*channel_users, tmp->data, tmp->len);
4627 silc_buffer_pull(*channel_users, len);
4628 silc_buffer_free(tmp);
4630 /* CUMODE notify for mode change on the channel */
4631 SILC_PUT32_MSB(chl->mode, mode);
4632 if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
4633 fkey = silc_pkcs_public_key_payload_encode(channel->founder_key);
4634 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
4635 4, csidp->data, csidp->len,
4637 clidp->data, clidp->len,
4638 fkey ? fkey->data : NULL,
4639 fkey ? fkey->len : 0);
4641 *channel_users_modes =
4642 silc_buffer_realloc(*channel_users_modes,
4643 (*channel_users_modes ?
4644 (*channel_users_modes)->truelen + len : len));
4645 silc_buffer_pull_tail(*channel_users_modes,
4646 ((*channel_users_modes)->end -
4647 (*channel_users_modes)->data));
4649 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
4650 silc_buffer_pull(*channel_users_modes, len);
4651 silc_buffer_free(tmp);
4652 silc_buffer_free(fkey);
4654 silc_buffer_free(clidp);
4656 silc_hash_table_list_reset(&htl);
4657 silc_buffer_free(chidp);
4658 silc_buffer_free(csidp);
4661 /* Returns assembled packets for all channels and users on those channels
4662 from the given ID List. The packets are in the form dictated by the
4663 New Channel and New Channel User payloads. */
4665 void silc_server_announce_get_channels(SilcServer server,
4667 SilcBuffer *channels,
4668 SilcBuffer **channel_modes,
4669 SilcBuffer *channel_users,
4670 SilcBuffer **channel_users_modes,
4671 SilcUInt32 *channel_users_modes_c,
4672 SilcBuffer **channel_topics,
4673 SilcBuffer **channel_invites,
4674 SilcBuffer **channel_bans,
4675 SilcChannelID ***channel_ids,
4676 unsigned long creation_time)
4678 SilcIDCacheList list;
4679 SilcIDCacheEntry id_cache;
4680 SilcChannelEntry channel;
4683 SilcUInt16 name_len;
4685 int i = *channel_users_modes_c;
4688 SILC_LOG_DEBUG(("Start"));
4690 /* Go through all channels in the list */
4691 if (silc_idcache_get_all(id_list->channels, &list)) {
4692 if (silc_idcache_list_first(list, &id_cache)) {
4694 channel = (SilcChannelEntry)id_cache->context;
4696 if (creation_time && channel->created < creation_time)
4701 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4702 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4703 name_len = strlen(channel->channel_name);
4706 len = 4 + name_len + id_len + 4;
4708 silc_buffer_realloc(*channels,
4709 (*channels ? (*channels)->truelen +
4711 silc_buffer_pull_tail(*channels,
4712 ((*channels)->end - (*channels)->data));
4713 silc_buffer_format(*channels,
4714 SILC_STR_UI_SHORT(name_len),
4715 SILC_STR_UI_XNSTRING(channel->channel_name,
4717 SILC_STR_UI_SHORT(id_len),
4718 SILC_STR_UI_XNSTRING(cid, id_len),
4719 SILC_STR_UI_INT(channel->mode),
4721 silc_buffer_pull(*channels, len);
4724 if (creation_time && channel->updated < creation_time)
4730 /* Channel user modes */
4731 *channel_users_modes = silc_realloc(*channel_users_modes,
4732 sizeof(**channel_users_modes) *
4734 (*channel_users_modes)[i] = NULL;
4735 *channel_modes = silc_realloc(*channel_modes,
4736 sizeof(**channel_modes) * (i + 1));
4737 (*channel_modes)[i] = NULL;
4738 *channel_ids = silc_realloc(*channel_ids,
4739 sizeof(**channel_ids) * (i + 1));
4740 (*channel_ids)[i] = NULL;
4741 silc_server_announce_get_channel_users(server, channel,
4742 &(*channel_modes)[i],
4744 &(*channel_users_modes)[i]);
4745 (*channel_ids)[i] = channel->id;
4747 /* Channel's topic */
4748 *channel_topics = silc_realloc(*channel_topics,
4749 sizeof(**channel_topics) * (i + 1));
4750 (*channel_topics)[i] = NULL;
4751 silc_server_announce_get_channel_topic(server, channel,
4752 &(*channel_topics)[i]);
4754 /* Channel's invite and ban list */
4755 *channel_invites = silc_realloc(*channel_invites,
4756 sizeof(**channel_invites) * (i + 1));
4757 (*channel_invites)[i] = NULL;
4758 *channel_bans = silc_realloc(*channel_bans,
4759 sizeof(**channel_bans) * (i + 1));
4760 (*channel_bans)[i] = NULL;
4761 silc_server_announce_get_inviteban(server, channel,
4762 &(*channel_invites)[i],
4763 &(*channel_bans)[i]);
4765 (*channel_users_modes_c)++;
4771 if (!silc_idcache_list_next(list, &id_cache))
4776 silc_idcache_list_free(list);
4780 /* This function is used to announce our existing channels to our router
4781 when we've connected to it. This also announces the users on the
4782 channels to the router. If the `creation_time' is non-zero only the
4783 channels that was created after the `creation_time' are announced.
4784 Note that the channel users are still announced even if the `creation_time'
4787 void silc_server_announce_channels(SilcServer server,
4788 unsigned long creation_time,
4789 SilcSocketConnection remote)
4791 SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
4792 SilcBuffer *channel_users_modes = NULL;
4793 SilcBuffer *channel_topics = NULL;
4794 SilcBuffer *channel_invites = NULL;
4795 SilcBuffer *channel_bans = NULL;
4796 SilcUInt32 channel_users_modes_c = 0;
4797 SilcChannelID **channel_ids = NULL;
4799 SILC_LOG_DEBUG(("Announcing channels and channel users"));
4801 /* Get channels and channel users in local list */
4802 silc_server_announce_get_channels(server, server->local_list,
4803 &channels, &channel_modes,
4805 &channel_users_modes,
4806 &channel_users_modes_c,
4810 &channel_ids, creation_time);
4812 /* Get channels and channel users in global list */
4813 if (server->server_type != SILC_SERVER)
4814 silc_server_announce_get_channels(server, server->global_list,
4815 &channels, &channel_modes,
4817 &channel_users_modes,
4818 &channel_users_modes_c,
4822 &channel_ids, creation_time);
4825 silc_buffer_push(channels, channels->data - channels->head);
4826 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
4828 /* Send the packet */
4829 silc_server_packet_send(server, remote,
4830 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
4831 channels->data, channels->len,
4834 silc_buffer_free(channels);
4837 if (channel_users) {
4838 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
4839 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
4840 channel_users->len);
4842 /* Send the packet */
4843 silc_server_packet_send(server, remote,
4844 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4845 channel_users->data, channel_users->len,
4848 silc_buffer_free(channel_users);
4851 if (channel_modes) {
4854 for (i = 0; i < channel_users_modes_c; i++) {
4855 if (!channel_modes[i])
4857 silc_buffer_push(channel_modes[i],
4858 channel_modes[i]->data -
4859 channel_modes[i]->head);
4860 SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
4861 channel_modes[i]->len);
4862 silc_server_packet_send_dest(server, remote,
4863 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4864 channel_ids[i], SILC_ID_CHANNEL,
4865 channel_modes[i]->data,
4866 channel_modes[i]->len,
4868 silc_buffer_free(channel_modes[i]);
4870 silc_free(channel_modes);
4873 if (channel_users_modes) {
4876 for (i = 0; i < channel_users_modes_c; i++) {
4877 if (!channel_users_modes[i])
4879 silc_buffer_push(channel_users_modes[i],
4880 channel_users_modes[i]->data -
4881 channel_users_modes[i]->head);
4882 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
4883 channel_users_modes[i]->len);
4884 silc_server_packet_send_dest(server, remote,
4885 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4886 channel_ids[i], SILC_ID_CHANNEL,
4887 channel_users_modes[i]->data,
4888 channel_users_modes[i]->len,
4890 silc_buffer_free(channel_users_modes[i]);
4892 silc_free(channel_users_modes);
4895 if (channel_topics) {
4898 for (i = 0; i < channel_users_modes_c; i++) {
4899 if (!channel_topics[i])
4902 silc_buffer_push(channel_topics[i],
4903 channel_topics[i]->data -
4904 channel_topics[i]->head);
4905 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
4906 channel_topics[i]->len);
4907 silc_server_packet_send_dest(server, remote,
4908 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4909 channel_ids[i], SILC_ID_CHANNEL,
4910 channel_topics[i]->data,
4911 channel_topics[i]->len,
4913 silc_buffer_free(channel_topics[i]);
4915 silc_free(channel_topics);
4918 if (channel_invites) {
4921 for (i = 0; i < channel_users_modes_c; i++) {
4922 if (!channel_invites[i])
4925 silc_buffer_push(channel_invites[i],
4926 channel_invites[i]->data -
4927 channel_invites[i]->head);
4928 SILC_LOG_HEXDUMP(("channel invite list"), channel_invites[i]->data,
4929 channel_invites[i]->len);
4930 silc_server_packet_send_dest(server, remote,
4931 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4932 channel_ids[i], SILC_ID_CHANNEL,
4933 channel_invites[i]->data,
4934 channel_invites[i]->len,
4936 silc_buffer_free(channel_invites[i]);
4938 silc_free(channel_invites);
4944 for (i = 0; i < channel_users_modes_c; i++) {
4945 if (!channel_bans[i])
4948 silc_buffer_push(channel_bans[i],
4949 channel_bans[i]->data -
4950 channel_bans[i]->head);
4951 SILC_LOG_HEXDUMP(("channel ban list"), channel_bans[i]->data,
4952 channel_bans[i]->len);
4953 silc_server_packet_send_dest(server, remote,
4954 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4955 channel_ids[i], SILC_ID_CHANNEL,
4956 channel_bans[i]->data,
4957 channel_bans[i]->len,
4959 silc_buffer_free(channel_bans[i]);
4961 silc_free(channel_bans);
4964 silc_free(channel_ids);
4967 /* Assembles user list and users mode list from the `channel'. */
4969 bool silc_server_get_users_on_channel(SilcServer server,
4970 SilcChannelEntry channel,
4971 SilcBuffer *user_list,
4972 SilcBuffer *mode_list,
4973 SilcUInt32 *user_count)
4975 SilcChannelClientEntry chl;
4976 SilcHashTableList htl;
4977 SilcBuffer client_id_list;
4978 SilcBuffer client_mode_list;
4980 SilcUInt32 list_count = 0, len = 0;
4982 if (!silc_hash_table_count(channel->user_list))
4985 silc_hash_table_list(channel->user_list, &htl);
4986 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4987 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
4988 silc_hash_table_list_reset(&htl);
4990 client_id_list = silc_buffer_alloc(len);
4992 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
4993 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
4994 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
4996 silc_hash_table_list(channel->user_list, &htl);
4997 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4999 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
5000 silc_buffer_put(client_id_list, idp->data, idp->len);
5001 silc_buffer_pull(client_id_list, idp->len);
5002 silc_buffer_free(idp);
5004 /* Client's mode on channel */
5005 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
5006 silc_buffer_pull(client_mode_list, 4);
5010 silc_hash_table_list_reset(&htl);
5011 silc_buffer_push(client_id_list,
5012 client_id_list->data - client_id_list->head);
5013 silc_buffer_push(client_mode_list,
5014 client_mode_list->data - client_mode_list->head);
5016 *user_list = client_id_list;
5017 *mode_list = client_mode_list;
5018 *user_count = list_count;
5022 /* Saves users and their modes to the `channel'. */
5024 void silc_server_save_users_on_channel(SilcServer server,
5025 SilcSocketConnection sock,
5026 SilcChannelEntry channel,
5027 SilcClientID *noadd,
5028 SilcBuffer user_list,
5029 SilcBuffer mode_list,
5030 SilcUInt32 user_count)
5035 SilcClientID *client_id;
5036 SilcClientEntry client;
5037 SilcIDCacheEntry cache;
5038 SilcChannelClientEntry chl;
5040 SILC_LOG_DEBUG(("Saving %d users on %s channel", user_count,
5041 channel->channel_name));
5043 for (i = 0; i < user_count; i++) {
5045 SILC_GET16_MSB(idp_len, user_list->data + 2);
5047 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
5048 silc_buffer_pull(user_list, idp_len);
5053 SILC_GET32_MSB(mode, mode_list->data);
5054 silc_buffer_pull(mode_list, 4);
5056 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
5057 silc_free(client_id);
5063 /* Check if we have this client cached already. */
5064 client = silc_idlist_find_client_by_id(server->local_list, client_id,
5065 server->server_type, &cache);
5067 client = silc_idlist_find_client_by_id(server->global_list,
5068 client_id, server->server_type,
5071 /* If router did not find such Client ID in its lists then this must
5072 be bogus client or some router in the net is buggy. */
5073 if (server->server_type != SILC_SERVER) {
5074 silc_free(client_id);
5078 /* We don't have that client anywhere, add it. The client is added
5079 to global list since server didn't have it in the lists so it must be
5081 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
5082 silc_id_dup(client_id, SILC_ID_CLIENT),
5083 sock->user_data, NULL, 0);
5085 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
5086 silc_free(client_id);
5090 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
5095 silc_free(client_id);
5097 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
5098 SILC_LOG_ERROR(("Attempting to add unregistered client to channel ",
5099 "%s", channel->channel_name));
5103 if (!silc_server_client_on_channel(client, channel, &chl)) {
5104 /* Client was not on the channel, add it. */
5105 chl = silc_calloc(1, sizeof(*chl));
5106 chl->client = client;
5108 chl->channel = channel;
5109 silc_hash_table_add(channel->user_list, chl->client, chl);
5110 silc_hash_table_add(client->channels, chl->channel, chl);
5111 channel->user_count++;
5119 /* Saves channels and channels user modes to the `client'. Removes
5120 the client from those channels that are not sent in the list but
5123 void silc_server_save_user_channels(SilcServer server,
5124 SilcSocketConnection sock,
5125 SilcClientEntry client,
5126 SilcBuffer channels,
5127 SilcBuffer channels_user_modes)
5130 SilcUInt32 *chumodes;
5131 SilcChannelPayload entry;
5132 SilcChannelEntry channel;
5133 SilcChannelID *channel_id;
5134 SilcChannelClientEntry chl;
5135 SilcHashTable ht = NULL;
5136 SilcHashTableList htl;
5140 if (!channels || !channels_user_modes ||
5141 !(client->data.status & SILC_IDLIST_STATUS_REGISTERED))
5144 ch = silc_channel_payload_parse_list(channels->data, channels->len);
5145 if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
5147 ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL,
5148 NULL, NULL, NULL, TRUE);
5149 silc_dlist_start(ch);
5150 while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
5151 /* Check if we have this channel, and add it if we don't have it.
5152 Also add the client on the channel unless it is there already. */
5153 channel_id = silc_channel_get_id_parse(entry);
5154 channel = silc_idlist_find_channel_by_id(server->local_list,
5157 channel = silc_idlist_find_channel_by_id(server->global_list,
5160 if (server->server_type != SILC_SERVER) {
5161 silc_free(channel_id);
5166 /* We don't have that channel anywhere, add it. */
5167 name = silc_channel_get_name(entry, NULL);
5168 channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
5169 channel_id, server->router,
5172 silc_free(channel_id);
5179 channel->mode = silc_channel_get_mode(entry);
5181 /* Add the client on the channel */
5182 if (!silc_server_client_on_channel(client, channel, &chl)) {
5183 chl = silc_calloc(1, sizeof(*chl));
5184 chl->client = client;
5185 chl->mode = chumodes[i++];
5186 chl->channel = channel;
5187 silc_hash_table_add(channel->user_list, chl->client, chl);
5188 silc_hash_table_add(client->channels, chl->channel, chl);
5189 channel->user_count++;
5192 chl->mode = chumodes[i++];
5195 silc_hash_table_add(ht, channel, channel);
5196 silc_free(channel_id);
5198 silc_channel_payload_list_free(ch);
5199 silc_free(chumodes);
5203 /* Go through the list again and remove client from channels that
5204 are no part of the list. */
5206 silc_hash_table_list(client->channels, &htl);
5207 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5208 if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
5209 silc_hash_table_del(chl->channel->user_list, chl->client);
5210 silc_hash_table_del(chl->client->channels, chl->channel);
5214 silc_hash_table_list_reset(&htl);
5215 silc_hash_table_free(ht);
5217 silc_hash_table_list(client->channels, &htl);
5218 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5219 silc_hash_table_del(chl->channel->user_list, chl->client);
5220 silc_hash_table_del(chl->client->channels, chl->channel);
5223 silc_hash_table_list_reset(&htl);
5227 /* Lookups route to the client indicated by the `id_data'. The connection
5228 object and internal data object is returned. Returns NULL if route
5229 could not be found to the client. If the `client_id' is specified then
5230 it is used and the `id_data' is ignored. */
5232 SilcSocketConnection
5233 silc_server_get_client_route(SilcServer server,
5234 unsigned char *id_data,
5236 SilcClientID *client_id,
5237 SilcIDListData *idata,
5238 SilcClientEntry *client_entry)
5241 SilcClientEntry client;
5243 SILC_LOG_DEBUG(("Start"));
5246 *client_entry = NULL;
5248 /* Decode destination Client ID */
5250 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
5252 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
5256 id = silc_id_dup(client_id, SILC_ID_CLIENT);
5259 /* If the destination belongs to our server we don't have to route
5260 the packet anywhere but to send it to the local destination. */
5261 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
5265 /* If we are router and the client has router then the client is in
5266 our cell but not directly connected to us. */
5267 if (server->server_type == SILC_ROUTER && client->router) {
5268 /* We are of course in this case the client's router thus the route
5269 to the client is the server who owns the client. So, we will send
5270 the packet to that server. */
5272 *idata = (SilcIDListData)client->router;
5273 return client->router->connection;
5276 /* Seems that client really is directly connected to us */
5278 *idata = (SilcIDListData)client;
5280 *client_entry = client;
5281 return client->connection;
5284 /* Destination belongs to someone not in this server. If we are normal
5285 server our action is to send the packet to our router. */
5286 if (server->server_type != SILC_ROUTER && !server->standalone) {
5289 *idata = (SilcIDListData)server->router;
5290 return SILC_PRIMARY_ROUTE(server);
5293 /* We are router and we will perform route lookup for the destination
5294 and send the packet to fastest route. */
5295 if (server->server_type == SILC_ROUTER && !server->standalone) {
5296 /* Check first that the ID is valid */
5297 client = silc_idlist_find_client_by_id(server->global_list, id,
5300 SilcSocketConnection dst_sock;
5302 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
5306 *idata = (SilcIDListData)dst_sock->user_data;
5315 /* Encodes and returns channel list of channels the `client' has joined.
5316 Secret channels are not put to the list. */
5318 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
5319 SilcClientEntry client,
5322 SilcBuffer *user_mode_list)
5324 SilcBuffer buffer = NULL;
5325 SilcChannelEntry channel;
5326 SilcChannelClientEntry chl;
5327 SilcHashTableList htl;
5330 SilcUInt16 name_len;
5334 *user_mode_list = NULL;
5336 silc_hash_table_list(client->channels, &htl);
5337 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5338 channel = chl->channel;
5340 if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
5342 if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
5345 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
5346 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
5347 name_len = strlen(channel->channel_name);
5349 len = 4 + name_len + id_len + 4;
5350 buffer = silc_buffer_realloc(buffer,
5351 (buffer ? buffer->truelen + len : len));
5352 silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
5353 silc_buffer_format(buffer,
5354 SILC_STR_UI_SHORT(name_len),
5355 SILC_STR_UI_XNSTRING(channel->channel_name,
5357 SILC_STR_UI_SHORT(id_len),
5358 SILC_STR_UI_XNSTRING(cid, id_len),
5359 SILC_STR_UI_INT(chl->channel->mode),
5361 silc_buffer_pull(buffer, len);
5364 if (user_mode_list) {
5365 *user_mode_list = silc_buffer_realloc(*user_mode_list,
5367 (*user_mode_list)->truelen + 4 :
5369 silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
5370 (*user_mode_list)->data));
5371 SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
5372 silc_buffer_pull(*user_mode_list, 4);
5375 silc_hash_table_list_reset(&htl);
5378 silc_buffer_push(buffer, buffer->data - buffer->head);
5379 if (user_mode_list && *user_mode_list)
5380 silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
5381 (*user_mode_list)->head));
5386 /* Timeout callback for unsuccessful rekey. The rekey did not go through
5389 SILC_TASK_CALLBACK(silc_server_rekey_timeout)
5391 SilcServerRekeyInternalContext *ctx = context;
5392 SilcServer server = app_context;
5393 SilcSocketConnection sock = ctx->sock;
5395 SILC_LOG_DEBUG(("Timeout occurred in rekey protocol with %s:%d [%s]",
5396 sock->hostname, sock->port,
5397 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5398 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5399 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5402 SILC_LOG_WARNING(("Timeout occurred in rekey protocol with %s:%d [%s]",
5403 sock->hostname, sock->port,
5404 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5405 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5406 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5409 if (sock->protocol) {
5410 silc_protocol_cancel(sock->protocol, server->schedule);
5411 silc_protocol_free(sock->protocol);
5412 sock->protocol = NULL;
5415 silc_packet_context_free(ctx->packet);
5417 silc_ske_free(ctx->ske);
5418 silc_socket_free(sock);
5421 /* Disconnect since we failed to rekey, the keys are probably wrong. */
5422 silc_server_disconnect_remote(server, sock,
5423 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
5426 if (sock->type != SILC_SOCKET_TYPE_CLIENT)
5427 silc_server_create_connections(server);
5430 /* A timeout callback for the re-key. We will be the initiator of the
5433 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_callback)
5435 SilcServer server = app_context;
5436 SilcSocketConnection sock = (SilcSocketConnection)context;
5437 SilcIDListData idata = (SilcIDListData)sock->user_data;
5438 SilcProtocol protocol;
5439 SilcServerRekeyInternalContext *proto_ctx;
5444 /* Do not execute rekey with disabled connections, as it would not
5445 go through anyway. */
5446 if (idata->status & SILC_IDLIST_STATUS_DISABLED)
5449 /* If rekey protocol is active already wait for it to finish */
5450 if (sock->protocol && sock->protocol->protocol &&
5451 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)
5454 /* If any other protocol is active do not start this protocol yet. */
5455 if (sock->protocol) {
5456 SILC_LOG_DEBUG(("Waiting for other protocol to finish before rekeying"));
5457 silc_schedule_task_add(server->schedule, sock->sock,
5458 silc_server_rekey_callback,
5459 sock, 60, 0, SILC_TASK_TIMEOUT,
5460 SILC_TASK_PRI_NORMAL);
5464 SILC_LOG_DEBUG(("Executing rekey protocol with %s:%d [%s]",
5465 sock->hostname, sock->port,
5466 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5467 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5468 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5471 /* Allocate internal protocol context. This is sent as context
5473 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
5474 proto_ctx->server = (void *)server;
5475 proto_ctx->sock = silc_socket_dup(sock);
5476 proto_ctx->responder = FALSE;
5477 proto_ctx->pfs = idata->rekey->pfs;
5479 /* Perform rekey protocol. Will call the final callback after the
5480 protocol is over. */
5481 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
5482 &protocol, proto_ctx, silc_server_rekey_final);
5483 sock->protocol = protocol;
5485 /* Register timeout callback in case the rekey does not go through. */
5486 proto_ctx->timeout_task =
5487 silc_schedule_task_add(server->schedule, sock->sock,
5488 silc_server_rekey_timeout,
5490 (idata->rekey->timeout >
5491 server->config->key_exchange_timeout ?
5492 idata->rekey->timeout :
5493 server->config->key_exchange_timeout * 4), 0,
5497 /* Run the protocol */
5498 silc_protocol_execute(protocol, server->schedule, 0, 0);
5501 /* The final callback for the REKEY protocol. This will actually take the
5502 new key material into use. */
5504 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
5506 SilcProtocol protocol = (SilcProtocol)context;
5507 SilcServerRekeyInternalContext *ctx =
5508 (SilcServerRekeyInternalContext *)protocol->context;
5509 SilcServer server = (SilcServer)ctx->server;
5510 SilcSocketConnection sock = ctx->sock;
5511 SilcIDListData idata = (SilcIDListData)sock->user_data;
5513 if (ctx->timeout_task)
5514 silc_schedule_task_del(server->schedule, ctx->timeout_task);
5516 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
5517 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
5518 /* Error occured during protocol */
5519 SILC_LOG_ERROR(("Error occurred during rekey protocol with "
5520 "%s (%s)", sock->hostname, sock->ip));
5521 silc_protocol_cancel(protocol, server->schedule);
5522 silc_protocol_free(protocol);
5523 sock->protocol = NULL;
5525 silc_packet_context_free(ctx->packet);
5527 silc_ske_free(ctx->ske);
5528 silc_socket_free(sock);
5530 silc_server_disconnect_remote(server, sock,
5531 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
5534 if (sock->type != SILC_SOCKET_TYPE_CLIENT)
5535 silc_server_create_connections(server);
5539 SILC_LOG_DEBUG(("Rekey protocol completed with %s:%d [%s]",
5540 sock->hostname, sock->port,
5541 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5542 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5543 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5546 /* Purge the outgoing data queue to assure that all rekey packets really
5547 go to the network before we quit the protocol. */
5548 silc_server_packet_queue_purge(server, sock);
5550 /* Re-register re-key timeout */
5551 if (ctx->responder == FALSE)
5552 silc_schedule_task_add(server->schedule, sock->sock,
5553 silc_server_rekey_callback,
5554 sock, idata->rekey->timeout, 0,
5555 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
5558 silc_protocol_free(protocol);
5559 sock->protocol = NULL;
5561 silc_packet_context_free(ctx->packet);
5563 silc_ske_free(ctx->ske);
5564 silc_socket_free(sock);
5568 /* Task callback used to retrieve network statistical information from
5569 router server once in a while. */
5571 SILC_TASK_CALLBACK(silc_server_get_stats)
5573 SilcServer server = (SilcServer)context;
5574 SilcBuffer idp, packet;
5576 if (!server->standalone) {
5577 SILC_LOG_DEBUG(("Retrieving stats from router"));
5578 idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
5579 packet = silc_command_payload_encode_va(SILC_COMMAND_STATS,
5580 ++server->cmd_ident, 1,
5581 1, idp->data, idp->len);
5582 silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
5583 SILC_PACKET_COMMAND, 0, packet->data,
5584 packet->len, FALSE);
5585 silc_buffer_free(packet);
5586 silc_buffer_free(idp);
5589 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
5590 server, 120, 0, SILC_TASK_TIMEOUT,