5 Author: Pekka Riikonen <priikone@silcnet.org>
7 Copyright (C) 1997 - 2005 Pekka Riikonen
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; version 2 of the License.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
20 * This is the actual SILC server than handles everything relating to
21 * servicing the SILC connections. This is also a SILC router as a router
22 * is also normal server.
26 #include "serverincludes.h"
27 #include "server_internal.h"
29 /* Static prototypes */
30 SILC_TASK_CALLBACK(silc_server_rehash_close_connection);
31 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry);
32 SILC_TASK_CALLBACK(silc_server_connect_router);
33 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
35 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
38 SILC_TASK_CALLBACK(silc_server_packet_process);
39 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
40 SILC_TASK_CALLBACK(silc_server_close_connection_final);
41 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout);
42 SILC_TASK_CALLBACK(silc_server_timeout_remote);
43 SILC_TASK_CALLBACK(silc_server_channel_key_rekey);
44 SILC_TASK_CALLBACK(silc_server_get_stats);
45 SILC_TASK_CALLBACK(silc_server_connect_router);
47 /* Allocates a new SILC server object. This has to be done before the server
48 can be used. After allocation one must call silc_server_init to initialize
49 the server. The new allocated server object is returned to the new_server
52 int silc_server_alloc(SilcServer *new_server)
56 SILC_LOG_DEBUG(("Allocating new server object"));
58 server = silc_calloc(1, sizeof(*server));
59 server->server_type = SILC_SERVER;
60 server->standalone = TRUE;
61 server->local_list = silc_calloc(1, sizeof(*server->local_list));
62 server->global_list = silc_calloc(1, sizeof(*server->global_list));
63 server->pending_commands = silc_dlist_init();
65 server->sim = silc_dlist_init();
73 /* Free's the SILC server object. This is called at the very end before
76 void silc_server_free(SilcServer server)
79 SilcIDCacheEntry cache;
87 silc_dlist_start(server->sim);
88 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
89 silc_dlist_del(server->sim, sim);
93 silc_dlist_uninit(server->sim);
97 silc_server_backup_free(server);
98 silc_server_config_unref(&server->config_ref);
100 silc_rng_free(server->rng);
102 silc_pkcs_free(server->pkcs);
103 if (server->public_key)
104 silc_pkcs_public_key_free(server->public_key);
105 if (server->private_key)
106 silc_pkcs_private_key_free(server->private_key);
107 if (server->pending_commands)
108 silc_dlist_uninit(server->pending_commands);
109 if (server->id_entry)
110 silc_idlist_del_server(server->local_list, server->id_entry);
112 /* Delete all channels */
114 if (silc_idcache_get_all(server->local_list->channels, &list) &&
115 silc_idcache_list_first(list, &cache)) {
116 silc_idlist_del_channel(server->local_list, cache->context);
117 while (silc_idcache_list_next(list, &cache))
118 silc_idlist_del_channel(server->local_list, cache->context);
121 silc_idcache_list_free(list);
123 if (silc_idcache_get_all(server->global_list->channels, &list) &&
124 silc_idcache_list_first(list, &cache)) {
125 silc_idlist_del_channel(server->global_list, cache->context);
126 while (silc_idcache_list_next(list, &cache))
127 silc_idlist_del_channel(server->global_list, cache->context);
130 silc_idcache_list_free(list);
133 silc_hash_table_free(server->pk_hash);
135 /* Delete all clients */
137 if (silc_idcache_get_all(server->local_list->clients, &list) &&
138 silc_idcache_list_first(list, &cache)) {
139 silc_idlist_del_client(server->local_list, cache->context);
140 while (silc_idcache_list_next(list, &cache))
141 silc_idlist_del_client(server->local_list, cache->context);
144 silc_idcache_list_free(list);
146 if (silc_idcache_get_all(server->global_list->clients, &list) &&
147 silc_idcache_list_first(list, &cache)) {
148 silc_idlist_del_client(server->global_list, cache->context);
149 while (silc_idcache_list_next(list, &cache))
150 silc_idlist_del_client(server->global_list, cache->context);
153 silc_idcache_list_free(list);
156 /* Delete all servers */
158 if (silc_idcache_get_all(server->local_list->servers, &list) &&
159 silc_idcache_list_first(list, &cache)) {
160 silc_idlist_del_server(server->local_list, cache->context);
161 while (silc_idcache_list_next(list, &cache))
162 silc_idlist_del_server(server->local_list, cache->context);
165 silc_idcache_list_free(list);
167 if (silc_idcache_get_all(server->global_list->servers, &list) &&
168 silc_idcache_list_first(list, &cache)) {
169 silc_idlist_del_server(server->global_list, cache->context);
170 while (silc_idcache_list_next(list, &cache))
171 silc_idlist_del_server(server->global_list, cache->context);
174 silc_idcache_list_free(list);
176 silc_idcache_free(server->local_list->clients);
177 silc_idcache_free(server->local_list->servers);
178 silc_idcache_free(server->local_list->channels);
179 silc_idcache_free(server->global_list->clients);
180 silc_idcache_free(server->global_list->servers);
181 silc_idcache_free(server->global_list->channels);
182 silc_hash_table_free(server->watcher_list);
183 silc_hash_table_free(server->watcher_list_pk);
185 silc_hash_free(server->md5hash);
186 silc_hash_free(server->sha1hash);
187 silc_hmac_unregister_all();
188 silc_hash_unregister_all();
189 silc_cipher_unregister_all();
190 silc_pkcs_unregister_all();
192 silc_free(server->local_list);
193 silc_free(server->global_list);
194 silc_free(server->server_name);
195 silc_free(server->id_string);
196 silc_free(server->purge_i);
197 silc_free(server->purge_g);
201 /* Creates a new server listener. */
203 static bool silc_server_listen(SilcServer server, const char *server_ip,
204 SilcUInt16 port, int *sock)
206 *sock = silc_net_create_server(port, server_ip);
208 SILC_SERVER_LOG_ERROR(("Could not create server listener: %s on %hu",
215 /* Adds a secondary listener. */
217 bool silc_server_init_secondary(SilcServer server)
219 int sock = 0, sock_list[server->config->param.connections_max];
220 SilcSocketConnection newsocket = NULL;
221 SilcServerConfigServerInfoInterface *interface;
223 for (interface = server->config->server_info->secondary; interface;
224 interface = interface->next, sock++) {
226 if (!silc_server_listen(server,
227 interface->server_ip, interface->port, &sock_list[sock]))
230 /* Set socket to non-blocking mode */
231 silc_net_set_socket_nonblock(sock_list[sock]);
233 /* Add ourselves also to the socket table. The entry allocated above
234 is sent as argument for fast referencing in the future. */
235 silc_socket_alloc(sock_list[sock],
236 SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
237 server->sockets[sock_list[sock]] = newsocket;
238 SILC_SET_LISTENER(newsocket);
240 /* Perform name and address lookups to resolve the listenning address
242 if (!silc_net_check_local_by_sock(sock_list[sock], &newsocket->hostname,
244 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
246 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
247 newsocket->hostname ? newsocket->hostname :
248 newsocket->ip ? newsocket->ip : ""));
249 server->stat.conn_failures++;
252 if (!newsocket->hostname)
253 newsocket->hostname = strdup(newsocket->ip);
255 newsocket->port = silc_net_get_local_port(sock);
257 newsocket->user_data = (void *)server->id_entry;
258 silc_schedule_task_add(server->schedule, sock_list[sock],
259 silc_server_accept_new_connection,
260 (void *)server, 0, 0,
262 SILC_TASK_PRI_NORMAL);
268 do silc_net_close_server(sock_list[sock--]); while (sock >= 0);
272 /* Initializes the entire SILC server. This is called always before running
273 the server. This is called only once at the initialization of the program.
274 This binds the server to its listenning port. After this function returns
275 one should call silc_server_run to start the server. This returns TRUE
276 when everything is ok to run the server. Configuration file must be
277 read and parsed before calling this. */
279 bool silc_server_init(SilcServer server)
283 SilcServerEntry id_entry;
284 SilcIDListPurge purge;
285 SilcSocketConnection newsocket = NULL;
287 SILC_LOG_DEBUG(("Initializing server"));
289 server->starttime = time(NULL);
291 /* Take config object for us */
292 silc_server_config_ref(&server->config_ref, server->config,
296 /* Set debugging on if configured */
297 if (server->config->debug_string) {
299 silc_log_set_debug_string(server->config->debug_string);
301 #endif /* SILC_DEBUG */
303 /* Steal public and private key from the config object */
304 server->public_key = server->config->server_info->public_key;
305 server->private_key = server->config->server_info->private_key;
306 server->config->server_info->public_key = NULL;
307 server->config->server_info->private_key = NULL;
309 /* Register all configured ciphers, PKCS and hash functions. */
310 if (!silc_server_config_register_ciphers(server))
311 silc_cipher_register_default();
312 if (!silc_server_config_register_pkcs(server))
313 silc_pkcs_register_default();
314 if (!silc_server_config_register_hashfuncs(server))
315 silc_hash_register_default();
316 if (!silc_server_config_register_hmacs(server))
317 silc_hmac_register_default();
319 /* Initialize random number generator for the server. */
320 server->rng = silc_rng_alloc();
321 silc_rng_init(server->rng);
322 silc_rng_global_init(server->rng);
324 /* Initialize hash functions for server to use */
325 silc_hash_alloc("md5", &server->md5hash);
326 silc_hash_alloc("sha1", &server->sha1hash);
328 /* Allocate PKCS context for local public and private keys */
329 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
331 silc_pkcs_public_key_set(server->pkcs, server->public_key);
332 silc_pkcs_private_key_set(server->pkcs, server->private_key);
334 /* Initialize the scheduler */
335 server->schedule = silc_schedule_init(server->config->param.connections_max,
337 if (!server->schedule)
340 /* First, register log files configuration for error output */
341 silc_server_config_setlogfiles(server);
343 /* Initialize ID caches */
344 server->local_list->clients =
345 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor,
347 server->local_list->servers =
348 silc_idcache_alloc(0, SILC_ID_SERVER, NULL, FALSE, TRUE);
349 server->local_list->channels =
350 silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL, FALSE, TRUE);
352 /* These are allocated for normal server as well as these hold some
353 global information that the server has fetched from its router. For
354 router these are used as they are supposed to be used on router. */
355 server->global_list->clients =
356 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor,
358 server->global_list->servers =
359 silc_idcache_alloc(0, SILC_ID_SERVER, NULL, FALSE, TRUE);
360 server->global_list->channels =
361 silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL, FALSE, TRUE);
363 /* Init watcher lists */
364 server->watcher_list =
365 silc_hash_table_alloc(1, silc_hash_client_id_hash, NULL,
366 silc_hash_data_compare, (void *)CLIENTID_HASH_LEN,
368 if (!server->watcher_list)
370 server->watcher_list_pk =
371 silc_hash_table_alloc(1, silc_hash_public_key, NULL,
372 silc_hash_public_key_compare, NULL,
374 if (!server->watcher_list_pk)
377 /* Init public key list */
379 silc_hash_table_alloc(0, silc_hash_public_key, NULL,
380 silc_hash_public_key_compare, NULL,
383 if (!server->pk_hash)
386 /* Create a listening server */
387 if (!silc_server_listen(server,
388 server->config->server_info->primary == NULL ? NULL :
389 server->config->server_info->primary->server_ip,
390 server->config->server_info->primary == NULL ? 0 :
391 server->config->server_info->primary->port,
395 /* Set socket to non-blocking mode */
396 silc_net_set_socket_nonblock(sock);
399 /* Allocate the entire socket list that is used in server. Eventually
400 all connections will have entry in this table (it is a table of
401 pointers to the actual object that is allocated individually
403 server->sockets = silc_calloc(server->config->param.connections_max,
404 sizeof(*server->sockets));
405 if (!server->sockets)
408 /* Add ourselves also to the socket table. The entry allocated above
409 is sent as argument for fast referencing in the future. */
410 silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
411 server->sockets[sock] = newsocket;
412 SILC_SET_LISTENER(newsocket);
414 /* Perform name and address lookups to resolve the listenning address
416 if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
418 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
420 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
421 newsocket->hostname ? newsocket->hostname :
422 newsocket->ip ? newsocket->ip : ""));
423 server->stat.conn_failures++;
426 if (!newsocket->hostname)
427 newsocket->hostname = strdup(newsocket->ip);
429 newsocket->port = silc_net_get_local_port(sock);
431 /* Create a Server ID for the server. */
432 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
437 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
438 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
439 server->server_name = server->config->server_info->server_name;
440 server->config->server_info->server_name = NULL;
442 /* Add ourselves to the server list. We don't have a router yet
443 beacuse we haven't established a route yet. It will be done later.
444 For now, NULL is sent as router. This allocates new entry to
447 silc_idlist_add_server(server->local_list, strdup(server->server_name),
448 server->server_type, server->id, NULL, NULL);
450 SILC_LOG_ERROR(("Could not add ourselves to cache"));
453 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
455 /* Put the allocated socket pointer also to the entry allocated above
456 for fast back-referencing to the socket list. */
457 newsocket->user_data = (void *)id_entry;
458 id_entry->connection = (void *)newsocket;
459 server->id_entry = id_entry;
461 /* Register protocols */
462 silc_server_protocols_register();
464 /* Create connections to configured routers. */
465 silc_server_create_connections(server);
467 /* Add listener task to the scheduler. This task receives new connections
468 to the server. This task remains on the queue until the end of the
470 silc_schedule_task_add(server->schedule, sock,
471 silc_server_accept_new_connection,
472 (void *)server, 0, 0,
474 SILC_TASK_PRI_NORMAL);
476 if (silc_server_init_secondary(server) == FALSE)
479 server->listenning = TRUE;
481 /* If server connections has been configured then we must be router as
482 normal server cannot have server connections, only router connections. */
483 if (server->config->servers) {
484 SilcServerConfigServer *ptr = server->config->servers;
486 server->server_type = SILC_ROUTER;
488 if (ptr->backup_router) {
489 server->server_type = SILC_BACKUP_ROUTER;
490 server->backup_router = TRUE;
491 server->id_entry->server_type = SILC_BACKUP_ROUTER;
498 /* Register the ID Cache purge task. This periodically purges the ID cache
499 and removes the expired cache entries. */
501 /* Clients local list */
502 server->purge_i = purge = silc_calloc(1, sizeof(*purge));
503 purge->cache = server->local_list->clients;
504 purge->timeout = 600;
505 silc_schedule_task_add(server->schedule, 0, silc_idlist_purge,
506 (void *)purge, purge->timeout, 0,
507 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
509 /* Clients global list */
510 server->purge_g = purge = silc_calloc(1, sizeof(*purge));
511 purge->cache = server->global_list->clients;
512 purge->timeout = 300;
513 silc_schedule_task_add(server->schedule, 0, silc_idlist_purge,
514 (void *)purge, purge->timeout, 0,
515 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
517 /* If we are normal server we'll retrieve network statisticial information
518 once in a while from the router. */
519 if (server->server_type != SILC_ROUTER)
520 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
521 server, 10, 0, SILC_TASK_TIMEOUT,
524 if (server->server_type == SILC_ROUTER)
525 server->stat.routers++;
527 SILC_LOG_DEBUG(("Server initialized"));
529 /* We are done here, return succesfully */
533 silc_server_config_unref(&server->config_ref);
534 silc_net_close_server(sock);
538 /* Task callback to close a socket connection after rehash */
540 SILC_TASK_CALLBACK(silc_server_rehash_close_connection)
542 SilcServer server = context;
543 SilcSocketConnection sock = server->sockets[fd];
548 SILC_LOG_INFO(("Connection %s:%d [%s] is unconfigured",
549 sock->hostname, sock->port,
550 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
551 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
552 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
554 silc_schedule_task_del_by_context(server->schedule, sock);
555 silc_server_disconnect_remote(server, sock,
556 SILC_STATUS_ERR_BANNED_FROM_SERVER,
557 "This connection is removed from "
560 silc_server_free_sock_user_data(server, sock, NULL);
563 /* This function basically reads the config file again and switches the config
564 object pointed by the server object. After that, we have to fix various
565 things such as the server_name and the listening ports.
566 Keep in mind that we no longer have the root privileges at this point. */
568 bool silc_server_rehash(SilcServer server)
570 SilcServerConfig newconfig;
572 SILC_LOG_INFO(("Rehashing server"));
574 /* Reset the logging system */
575 silc_log_quick = TRUE;
576 silc_log_flush_all();
578 /* Start the main rehash phase (read again the config file) */
579 newconfig = silc_server_config_alloc(server->config_file);
581 SILC_LOG_ERROR(("Rehash FAILED."));
585 /* Reinit scheduler if necessary */
586 if (newconfig->param.connections_max > server->config->param.connections_max)
587 if (!silc_schedule_reinit(server->schedule,
588 newconfig->param.connections_max))
591 /* Fix the server_name field */
592 if (strcmp(server->server_name, newconfig->server_info->server_name)) {
593 silc_free(server->server_name);
595 /* Check server name */
596 server->server_name =
597 silc_identifier_check(newconfig->server_info->server_name,
598 strlen(newconfig->server_info->server_name),
599 SILC_STRING_LOCALE, 256, NULL);
600 if (!server->server_name) {
601 SILC_LOG_ERROR(("Malformed server name string '%s'",
602 server->config->server_info->server_name));
606 /* Update the idcache list with a fresh pointer */
607 silc_free(server->id_entry->server_name);
608 server->id_entry->server_name = strdup(server->server_name);
609 if (!silc_idcache_del_by_context(server->local_list->servers,
612 if (!silc_idcache_add(server->local_list->servers,
613 strdup(server->id_entry->server_name),
614 server->id_entry->id, server->id_entry, 0, NULL))
619 silc_server_config_setlogfiles(server);
621 /* Change new key pair if necessary */
622 if (newconfig->server_info->public_key &&
623 !silc_pkcs_public_key_compare(server->public_key,
624 newconfig->server_info->public_key)) {
625 silc_pkcs_public_key_free(server->public_key);
626 silc_pkcs_private_key_free(server->private_key);
627 server->public_key = newconfig->server_info->public_key;
628 server->private_key = newconfig->server_info->private_key;
629 newconfig->server_info->public_key = NULL;
630 newconfig->server_info->private_key = NULL;
632 /* Allocate PKCS context for local public and private keys */
633 silc_pkcs_free(server->pkcs);
634 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
636 silc_pkcs_public_key_set(server->pkcs, server->public_key);
637 silc_pkcs_private_key_set(server->pkcs, server->private_key);
640 /* Check for unconfigured server and router connections and close
641 connections that were unconfigured. */
643 if (server->config->routers) {
644 SilcServerConfigRouter *ptr;
645 SilcServerConfigRouter *newptr;
648 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
651 /* Check whether new config has this one too */
652 for (newptr = newconfig->routers; newptr; newptr = newptr->next) {
653 if (silc_string_compare(newptr->host, ptr->host) &&
654 newptr->port == ptr->port &&
655 newptr->initiator == ptr->initiator) {
661 if (!found && ptr->host) {
662 /* Remove this connection */
663 SilcSocketConnection sock;
664 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_ROUTER,
665 ptr->host, ptr->port);
666 if (sock && !SILC_IS_LISTENER(sock))
667 silc_schedule_task_add(server->schedule, sock->sock,
668 silc_server_rehash_close_connection,
669 server, 0, 1, SILC_TASK_TIMEOUT,
670 SILC_TASK_PRI_NORMAL);
675 if (server->config->servers) {
676 SilcServerConfigServer *ptr;
677 SilcServerConfigServer *newptr;
680 for (ptr = server->config->servers; ptr; ptr = ptr->next) {
683 /* Check whether new config has this one too */
684 for (newptr = newconfig->servers; newptr; newptr = newptr->next) {
685 if (silc_string_compare(newptr->host, ptr->host)) {
691 if (!found && ptr->host) {
692 /* Remove this connection */
693 SilcSocketConnection sock;
694 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_SERVER,
696 if (sock && !SILC_IS_LISTENER(sock))
697 silc_schedule_task_add(server->schedule, sock->sock,
698 silc_server_rehash_close_connection,
699 server, 0, 1, SILC_TASK_TIMEOUT,
700 SILC_TASK_PRI_NORMAL);
705 if (server->config->clients) {
706 SilcServerConfigClient *ptr;
707 SilcServerConfigClient *newptr;
710 for (ptr = server->config->clients; ptr; ptr = ptr->next) {
713 /* Check whether new config has this one too */
714 for (newptr = newconfig->clients; newptr; newptr = newptr->next) {
715 if (silc_string_compare(newptr->host, ptr->host)) {
721 if (!found && ptr->host) {
722 /* Remove this connection */
723 SilcSocketConnection sock;
724 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_CLIENT,
727 silc_schedule_task_add(server->schedule, sock->sock,
728 silc_server_rehash_close_connection,
729 server, 0, 1, SILC_TASK_TIMEOUT,
730 SILC_TASK_PRI_NORMAL);
735 /* Create connections after rehash */
736 silc_server_create_connections(server);
738 /* Check whether our router status has changed */
739 if (newconfig->servers) {
740 SilcServerConfigServer *ptr = newconfig->servers;
742 server->server_type = SILC_ROUTER;
744 if (ptr->backup_router) {
745 server->server_type = SILC_BACKUP_ROUTER;
746 server->backup_router = TRUE;
747 server->id_entry->server_type = SILC_BACKUP_ROUTER;
754 /* Our old config is gone now. We'll unreference our reference made in
755 silc_server_init and then destroy it since we are destroying it
756 underneath the application (layer which called silc_server_init). */
757 silc_server_config_unref(&server->config_ref);
758 silc_server_config_destroy(server->config);
760 /* Take new config context */
761 server->config = newconfig;
762 silc_server_config_ref(&server->config_ref, server->config, server->config);
765 /* Set debugging on if configured */
766 if (server->config->debug_string) {
768 silc_log_set_debug_string(server->config->debug_string);
770 #endif /* SILC_DEBUG */
772 SILC_LOG_DEBUG(("Server rehashed"));
777 /* The heart of the server. This runs the scheduler thus runs the server.
778 When this returns the server has been stopped and the program will
781 void silc_server_run(SilcServer server)
783 SILC_LOG_INFO(("SILC Server started"));
785 /* Start the scheduler, the heart of the SILC server. When this returns
786 the program will be terminated. */
787 silc_schedule(server->schedule);
790 /* Stops the SILC server. This function is used to shutdown the server.
791 This is usually called after the scheduler has returned. After stopping
792 the server one should call silc_server_free. */
794 void silc_server_stop(SilcServer server)
796 SILC_LOG_INFO(("SILC Server shutting down"));
798 if (server->schedule) {
801 server->server_shutdown = TRUE;
803 /* Close all connections */
804 for (i = 0; i < server->config->param.connections_max; i++) {
805 if (!server->sockets[i])
807 if (!SILC_IS_LISTENER(server->sockets[i])) {
808 SilcSocketConnection sock = server->sockets[i];
809 SilcIDListData idata = sock->user_data;
812 idata->status &= ~SILC_IDLIST_STATUS_DISABLED;
814 silc_schedule_task_del_by_context(server->schedule,
816 silc_schedule_task_del_by_fd(server->schedule,
817 server->sockets[i]->sock);
818 silc_server_disconnect_remote(server, server->sockets[i],
820 "Server is shutting down");
821 if (server->sockets[i]) {
823 silc_server_free_sock_user_data(server, sock,
824 "Server is shutting down");
825 silc_socket_free(sock);
828 silc_socket_free(server->sockets[i]);
829 server->sockets[i] = NULL;
830 server->stat.conn_num--;
834 /* We are not connected to network anymore */
835 server->standalone = TRUE;
837 silc_schedule_stop(server->schedule);
838 silc_schedule_uninit(server->schedule);
839 server->schedule = NULL;
841 silc_free(server->sockets);
842 server->sockets = NULL;
845 silc_server_protocols_unregister();
847 SILC_LOG_DEBUG(("Server stopped"));
850 /* Function that is called when the network connection to a router has
851 been established. This will continue with the key exchange protocol
852 with the remote router. */
854 void silc_server_start_key_exchange(SilcServer server,
855 SilcServerConnection sconn,
858 SilcSocketConnection newsocket;
859 SilcProtocol protocol;
860 SilcServerKEInternalContext *proto_ctx;
861 SilcServerConfigRouter *conn =
862 (SilcServerConfigRouter *) sconn->conn.ref_ptr;
865 /* Cancel any possible retry timeouts */
866 silc_schedule_task_del_by_callback(server->schedule,
867 silc_server_connect_to_router_retry);
869 /* Set socket options */
870 silc_net_set_socket_nonblock(sock);
871 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
873 /* Create socket connection for the connection. Even though we
874 know that we are connecting to a router we will mark the socket
875 to be unknown connection until we have executed authentication
877 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
878 server->sockets[sock] = newsocket;
879 newsocket->hostname = strdup(sconn->remote_host);
880 newsocket->ip = strdup(sconn->remote_host);
881 newsocket->port = sconn->remote_port;
882 sconn->sock = newsocket;
884 /* Allocate internal protocol context. This is sent as context
886 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
887 proto_ctx->server = (void *)server;
888 proto_ctx->context = (void *)sconn;
889 proto_ctx->sock = newsocket;
890 proto_ctx->rng = server->rng;
891 proto_ctx->responder = FALSE;
893 /* Set Key Exchange flags from configuration, but fall back to global
895 SILC_GET_SKE_FLAGS(conn, proto_ctx);
896 if (server->config->param.key_exchange_pfs)
897 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
899 /* Perform key exchange protocol. silc_server_connect_to_router_second
900 will be called after the protocol is finished. */
901 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
902 &protocol, proto_ctx,
903 silc_server_connect_to_router_second);
904 newsocket->protocol = protocol;
906 /* Register a timeout task that will be executed if the protocol
907 is not executed within set limit. */
908 proto_ctx->timeout_task =
909 silc_schedule_task_add(server->schedule, sock,
910 silc_server_timeout_remote,
911 server, server->config->key_exchange_timeout, 0,
915 /* Register the connection for network input and output. This sets
916 that scheduler will listen for incoming packets for this connection
917 and sets that outgoing packets may be sent to this connection as
918 well. However, this doesn't set the scheduler for outgoing traffic,
919 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
920 later when outgoing data is available. */
921 context = (void *)server;
922 SILC_REGISTER_CONNECTION_FOR_IO(sock);
924 /* Run the protocol */
925 silc_protocol_execute(protocol, server->schedule, 0, 0);
928 /* Timeout callback that will be called to retry connecting to remote
929 router. This is used by both normal and router server. This will wait
930 before retrying the connecting. The timeout is generated by exponential
931 backoff algorithm. */
933 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
935 SilcServer server = app_context;
936 SilcServerConnection sconn = (SilcServerConnection)context;
937 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
938 SilcServerConfigConnParams *param =
939 (conn->param ? conn->param : &server->config->param);
941 /* Don't retry if we are shutting down. */
942 if (server->server_shutdown) {
943 silc_server_config_unref(&sconn->conn);
944 silc_free(sconn->remote_host);
945 silc_free(sconn->backup_replace_ip);
950 SILC_LOG_INFO(("Retrying connecting to a router"));
952 /* Calculate next timeout */
953 if (sconn->retry_count >= 1) {
954 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
955 if (sconn->retry_timeout > param->reconnect_interval_max)
956 sconn->retry_timeout = param->reconnect_interval_max;
958 sconn->retry_timeout = param->reconnect_interval;
960 sconn->retry_count++;
961 sconn->retry_timeout = sconn->retry_timeout +
962 (silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER);
964 /* If we've reached max retry count, give up. */
965 if ((sconn->retry_count > param->reconnect_count) &&
966 !param->reconnect_keep_trying) {
967 SILC_LOG_ERROR(("Could not connect to router, giving up"));
968 silc_server_config_unref(&sconn->conn);
969 silc_free(sconn->remote_host);
970 silc_free(sconn->backup_replace_ip);
975 SILC_LOG_DEBUG(("Retrying connecting to a router in %d seconds",
976 sconn->retry_timeout));
978 /* We will lookup a fresh pointer later */
979 silc_server_config_unref(&sconn->conn);
981 /* Wait one before retrying */
982 silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
983 context, sconn->retry_timeout, 0,
984 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
987 /* Callback for async connection to remote router */
989 SILC_TASK_CALLBACK(silc_server_connection_established)
991 SilcServer server = app_context;
992 SilcServerConnection sconn = (SilcServerConnection)context;
994 int opt = EINVAL, optlen = sizeof(opt), ret;
996 ret = silc_net_get_socket_opt(sock, SOL_SOCKET, SO_ERROR, &opt, &optlen);
998 silc_schedule_task_del_by_fd(server->schedule, sock);
999 silc_schedule_unset_listen_fd(server->schedule, sock);
1001 if (ret != 0 || opt != 0) {
1002 SILC_LOG_ERROR(("Could not connect to router %s:%d: %s",
1003 sconn->remote_host, sconn->remote_port, strerror(opt)));
1004 silc_net_close_connection(sock);
1005 if (!sconn->no_reconnect) {
1006 silc_schedule_task_add(server->schedule, 0,
1007 silc_server_connect_to_router_retry,
1008 context, 1, 0, SILC_TASK_TIMEOUT,
1009 SILC_TASK_PRI_NORMAL);
1011 silc_server_config_unref(&sconn->conn);
1012 silc_free(sconn->remote_host);
1013 silc_free(sconn->backup_replace_ip);
1019 SILC_LOG_DEBUG(("Connection to router %s:%d established", sconn->remote_host,
1020 sconn->remote_port));
1022 /* Continue with key exchange protocol */
1023 silc_server_start_key_exchange(server, sconn, sock);
1026 /* Generic routine to use connect to a router. */
1028 SILC_TASK_CALLBACK(silc_server_connect_router)
1030 SilcServer server = app_context;
1031 SilcServerConnection sconn = (SilcServerConnection)context;
1032 SilcServerConfigRouter *rconn;
1035 /* Don't connect if we are shutting down. */
1036 if (server->server_shutdown) {
1037 silc_free(sconn->remote_host);
1038 silc_free(sconn->backup_replace_ip);
1043 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
1044 (sconn->backup ? "backup router" : "router"),
1045 sconn->remote_host, sconn->remote_port));
1047 server->router_connect = time(NULL);
1048 rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
1049 sconn->remote_port);
1051 SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
1052 (sconn->backup ? "backup router" : "router"),
1053 sconn->remote_host, sconn->remote_port));
1054 silc_free(sconn->remote_host);
1055 silc_free(sconn->backup_replace_ip);
1059 silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
1061 /* Connect to remote host */
1062 sock = silc_net_create_connection_async(
1063 (!server->config->server_info->primary ? NULL :
1064 server->config->server_info->primary->server_ip),
1065 sconn->remote_port, sconn->remote_host);
1067 SILC_LOG_ERROR(("Could not connect to router %s:%d",
1068 sconn->remote_host, sconn->remote_port));
1069 if (!sconn->no_reconnect) {
1070 silc_schedule_task_add(server->schedule, 0,
1071 silc_server_connect_to_router_retry,
1072 context, 1, 0, SILC_TASK_TIMEOUT,
1073 SILC_TASK_PRI_NORMAL);
1075 silc_server_config_unref(&sconn->conn);
1076 silc_free(sconn->remote_host);
1077 silc_free(sconn->backup_replace_ip);
1083 /* wait for the connection to be established */
1084 silc_schedule_task_add(server->schedule, sock,
1085 silc_server_connection_established,
1086 context, 0, 0, SILC_TASK_FD,
1087 SILC_TASK_PRI_NORMAL);
1088 silc_schedule_set_listen_fd(server->schedule, sock,
1089 SILC_TASK_WRITE, FALSE);
1092 /* This function connects to our primary router or if we are a router this
1093 establishes all our primary routes. This is called at the start of the
1094 server to do authentication and key exchange with our router - called
1097 SILC_TASK_CALLBACK_GLOBAL(silc_server_connect_to_router)
1099 SilcServer server = (SilcServer)context;
1100 SilcServerConnection sconn;
1101 SilcServerConfigRouter *ptr;
1103 /* Don't connect if we are shutting down. */
1104 if (server->server_shutdown)
1107 SILC_LOG_DEBUG(("We are %s",
1108 (server->server_type == SILC_SERVER ?
1109 "normal server" : server->server_type == SILC_ROUTER ?
1110 "router" : "backup router/normal server")));
1112 if (!server->config->routers) {
1113 /* There wasn't a configured router, we will continue but we don't
1114 have a connection to outside world. We will be standalone server. */
1115 SILC_LOG_DEBUG(("No router(s), we are standalone"));
1116 server->standalone = TRUE;
1120 /* Cancel any possible retry timeouts */
1121 silc_schedule_task_del_by_callback(server->schedule,
1122 silc_server_connect_router);
1123 silc_schedule_task_del_by_callback(server->schedule,
1124 silc_server_connect_to_router_retry);
1126 /* Create the connections to all our routes */
1127 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
1129 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
1130 ptr->backup_router ? "Backup router" : "Router",
1131 ptr->initiator ? "Initiator" : "Responder",
1132 ptr->host, ptr->port));
1134 if (server->server_type == SILC_ROUTER && ptr->backup_router &&
1135 ptr->initiator == FALSE && !server->backup_router &&
1136 !silc_server_config_get_backup_router(server))
1137 server->wait_backup = TRUE;
1139 if (ptr->initiator) {
1140 /* Check whether we are connecting or connected to this host already */
1141 if (silc_server_num_sockets_by_remote(server,
1142 silc_net_is_ip(ptr->host) ?
1144 silc_net_is_ip(ptr->host) ?
1145 NULL : ptr->host, ptr->port,
1146 SILC_SOCKET_TYPE_ROUTER)) {
1147 SILC_LOG_DEBUG(("We are already connected to this router"));
1149 /* If we don't have primary router and this connection is our
1150 primary router we are in desync. Reconnect to the primary. */
1151 if (server->standalone && !server->router) {
1152 SilcServerConfigRouter *primary =
1153 silc_server_config_get_primary_router(server);
1154 if (primary == ptr) {
1155 SilcSocketConnection sock =
1156 silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_ROUTER,
1157 ptr->host, ptr->port);
1159 server->backup_noswitch = TRUE;
1160 if (sock->user_data)
1161 silc_server_free_sock_user_data(server, sock, NULL);
1162 silc_server_disconnect_remote(server, sock, 0, NULL);
1163 server->backup_noswitch = FALSE;
1164 SILC_LOG_DEBUG(("Reconnecting to primary router"));
1175 if (silc_server_num_sockets_by_remote(server,
1176 silc_net_is_ip(ptr->host) ?
1178 silc_net_is_ip(ptr->host) ?
1179 NULL : ptr->host, ptr->port,
1180 SILC_SOCKET_TYPE_UNKNOWN)) {
1181 SILC_LOG_DEBUG(("We are already connecting to this router"));
1185 /* Allocate connection object for hold connection specific stuff. */
1186 sconn = silc_calloc(1, sizeof(*sconn));
1187 sconn->remote_host = strdup(ptr->host);
1188 sconn->remote_port = ptr->port;
1189 sconn->backup = ptr->backup_router;
1190 if (sconn->backup) {
1191 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
1192 sconn->backup_replace_port = ptr->backup_replace_port;
1195 if (!server->router_conn && !sconn->backup)
1196 server->router_conn = sconn;
1198 silc_schedule_task_add(server->schedule, 0,
1199 silc_server_connect_router,
1200 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
1201 SILC_TASK_PRI_NORMAL);
1206 /* Second part of connecting to router(s). Key exchange protocol has been
1207 executed and now we will execute authentication protocol. */
1209 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
1211 SilcProtocol protocol = (SilcProtocol)context;
1212 SilcServerKEInternalContext *ctx =
1213 (SilcServerKEInternalContext *)protocol->context;
1214 SilcServer server = (SilcServer)ctx->server;
1215 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1216 SilcSocketConnection sock = ctx->sock;
1217 SilcServerConnAuthInternalContext *proto_ctx;
1218 SilcServerConfigRouter *conn = NULL;
1220 SILC_LOG_DEBUG(("Start"));
1222 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1223 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1224 /* Error occured during protocol */
1225 silc_protocol_free(protocol);
1226 sock->protocol = NULL;
1227 silc_ske_free_key_material(ctx->keymat);
1229 silc_packet_context_free(ctx->packet);
1231 silc_ske_free(ctx->ske);
1232 silc_free(ctx->dest_id);
1234 silc_server_disconnect_remote(server, sock,
1235 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1237 /* Try reconnecting if configuration wants it */
1238 if (!sconn->no_reconnect) {
1239 silc_schedule_task_add(server->schedule, 0,
1240 silc_server_connect_to_router_retry,
1241 sconn, 1, 0, SILC_TASK_TIMEOUT,
1242 SILC_TASK_PRI_NORMAL);
1246 /* Call completion to indicate error */
1247 if (sconn->callback)
1248 (*sconn->callback)(server, NULL, sconn->callback_context);
1250 silc_server_config_unref(&sconn->conn);
1251 silc_free(sconn->remote_host);
1252 silc_free(sconn->backup_replace_ip);
1257 /* We now have the key material as the result of the key exchange
1258 protocol. Take the key material into use. Free the raw key material
1259 as soon as we've set them into use. */
1260 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1261 ctx->sock, ctx->keymat,
1262 ctx->ske->prop->cipher,
1263 ctx->ske->prop->pkcs,
1264 ctx->ske->prop->hash,
1265 ctx->ske->prop->hmac,
1266 ctx->ske->prop->group,
1268 silc_protocol_free(protocol);
1269 sock->protocol = NULL;
1270 silc_ske_free_key_material(ctx->keymat);
1272 silc_packet_context_free(ctx->packet);
1274 silc_ske_free(ctx->ske);
1275 silc_free(ctx->dest_id);
1277 silc_server_disconnect_remote(server, sock,
1278 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1280 /* Try reconnecting if configuration wants it */
1281 if (!sconn->no_reconnect) {
1282 silc_schedule_task_add(server->schedule, 0,
1283 silc_server_connect_to_router_retry,
1284 sconn, 1, 0, SILC_TASK_TIMEOUT,
1285 SILC_TASK_PRI_NORMAL);
1289 /* Call completion to indicate error */
1290 if (sconn->callback)
1291 (*sconn->callback)(server, NULL, sconn->callback_context);
1293 silc_server_config_unref(&sconn->conn);
1294 silc_free(sconn->remote_host);
1295 silc_free(sconn->backup_replace_ip);
1299 silc_ske_free_key_material(ctx->keymat);
1301 /* Allocate internal context for the authentication protocol. This
1302 is sent as context for the protocol. */
1303 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1304 proto_ctx->server = (void *)server;
1305 proto_ctx->context = (void *)sconn;
1306 proto_ctx->sock = sock;
1307 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1308 proto_ctx->dest_id_type = ctx->dest_id_type;
1309 proto_ctx->dest_id = ctx->dest_id;
1311 /* Resolve the authentication method used in this connection. Check if
1312 we find a match from user configured connections */
1313 if (!sconn->conn.ref_ptr)
1314 conn = silc_server_config_find_router_conn(server, sock->hostname,
1317 conn = sconn->conn.ref_ptr;
1320 /* Match found. Use the configured authentication method. Take only
1321 the passphrase, since for public key auth we automatically use
1322 our local key pair. */
1323 if (conn->passphrase) {
1324 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
1325 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1327 proto_ctx->auth_data = strdup(conn->passphrase);
1328 proto_ctx->auth_data_len = strlen(conn->passphrase);
1329 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
1331 } else if (conn->publickeys) {
1332 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1334 proto_ctx->auth_meth = SILC_AUTH_NONE;
1337 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
1338 sock->hostname, sock->ip, sock->port));
1339 silc_protocol_free(protocol);
1340 sock->protocol = NULL;
1342 silc_packet_context_free(ctx->packet);
1344 silc_ske_free(ctx->ske);
1345 silc_free(ctx->dest_id);
1347 silc_server_config_unref(&sconn->conn);
1348 silc_free(sconn->remote_host);
1349 silc_free(sconn->backup_replace_ip);
1351 silc_server_disconnect_remote(server, sock,
1352 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1356 /* Free old protocol as it is finished now */
1357 silc_protocol_free(protocol);
1359 silc_packet_context_free(ctx->packet);
1361 sock->protocol = NULL;
1363 /* Allocate the authentication protocol. This is allocated here
1364 but we won't start it yet. We will be receiving party of this
1365 protocol thus we will wait that connecting party will make
1366 their first move. */
1367 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1368 &sock->protocol, proto_ctx,
1369 silc_server_connect_to_router_final);
1371 /* Register timeout task. If the protocol is not executed inside
1372 this timelimit the connection will be terminated. */
1373 proto_ctx->timeout_task =
1374 silc_schedule_task_add(server->schedule, sock->sock,
1375 silc_server_timeout_remote,
1377 server->config->conn_auth_timeout, 0,
1381 /* Run the protocol */
1382 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1385 /* Finalizes the connection to router. Registers a server task to the
1386 queue so that we can accept new connections. */
1388 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
1390 SilcProtocol protocol = (SilcProtocol)context;
1391 SilcServerConnAuthInternalContext *ctx =
1392 (SilcServerConnAuthInternalContext *)protocol->context;
1393 SilcServer server = (SilcServer)ctx->server;
1394 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1395 SilcSocketConnection sock = ctx->sock;
1396 SilcServerEntry id_entry = NULL;
1398 unsigned char *id_string;
1400 SilcIDListData idata;
1401 SilcServerConfigRouter *conn = NULL;
1402 SilcServerConfigConnParams *param = NULL;
1404 SILC_LOG_DEBUG(("Start"));
1406 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1407 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1408 /* Error occured during protocol */
1409 silc_free(ctx->dest_id);
1410 sock->protocol = NULL;
1411 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1413 sock->protocol = protocol;
1415 /* Try reconnecting if configuration wants it */
1416 if (!sconn->no_reconnect) {
1417 silc_schedule_task_add(server->schedule, 0,
1418 silc_server_connect_to_router_retry,
1419 sconn, 1, 0, SILC_TASK_TIMEOUT,
1420 SILC_TASK_PRI_NORMAL);
1427 /* Add a task to the queue. This task receives new connections to the
1428 server. This task remains on the queue until the end of the program. */
1429 if (!server->listenning && !sconn->backup) {
1430 silc_schedule_task_add(server->schedule, server->sock,
1431 silc_server_accept_new_connection,
1432 (void *)server, 0, 0,
1434 SILC_TASK_PRI_NORMAL);
1435 server->listenning = TRUE;
1438 /* Send NEW_SERVER packet to the router. We will become registered
1439 to the SILC network after sending this packet. */
1440 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
1441 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1442 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
1443 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1444 silc_buffer_format(packet,
1445 SILC_STR_UI_SHORT(id_len),
1446 SILC_STR_UI_XNSTRING(id_string, id_len),
1447 SILC_STR_UI_SHORT(strlen(server->server_name)),
1448 SILC_STR_UI_XNSTRING(server->server_name,
1449 strlen(server->server_name)),
1452 /* Send the packet */
1453 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
1454 packet->data, packet->len, TRUE);
1455 silc_buffer_free(packet);
1456 silc_free(id_string);
1458 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
1460 /* Check that we do not have this ID already */
1461 id_entry = silc_idlist_find_server_by_id(server->local_list,
1462 ctx->dest_id, TRUE, NULL);
1464 silc_idcache_del_by_context(server->local_list->servers, id_entry);
1466 id_entry = silc_idlist_find_server_by_id(server->global_list,
1467 ctx->dest_id, TRUE, NULL);
1469 silc_idcache_del_by_context(server->global_list->servers, id_entry);
1472 SILC_LOG_DEBUG(("New server id(%s)",
1473 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1475 /* Add the connected router to global server list. Router is sent
1476 as NULL since it's local to us. */
1477 id_entry = silc_idlist_add_server(server->global_list,
1478 strdup(sock->hostname),
1479 SILC_ROUTER, ctx->dest_id, NULL, sock);
1481 silc_free(ctx->dest_id);
1482 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1483 sock->protocol = NULL;
1484 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1486 sock->protocol = protocol;
1490 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1491 silc_free(sock->user_data);
1492 sock->user_data = (void *)id_entry;
1493 sock->type = SILC_SOCKET_TYPE_ROUTER;
1494 idata = (SilcIDListData)sock->user_data;
1495 idata->status |= (SILC_IDLIST_STATUS_REGISTERED |
1496 SILC_IDLIST_STATUS_LOCAL);
1498 conn = sconn->conn.ref_ptr;
1499 param = &server->config->param;
1500 if (conn && conn->param)
1501 param = conn->param;
1503 /* Perform keepalive. */
1504 silc_socket_set_heartbeat(sock, param->keepalive_secs, server,
1505 silc_server_perform_heartbeat,
1508 /* Register re-key timeout */
1509 idata->rekey->timeout = param->key_exchange_rekey;
1510 silc_schedule_task_add(server->schedule, sock->sock,
1511 silc_server_rekey_callback,
1512 (void *)sock, idata->rekey->timeout, 0,
1513 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1515 if (!sconn->backup) {
1516 /* Mark this router our primary router if we're still standalone */
1517 if (server->standalone) {
1518 SILC_LOG_DEBUG(("This connection is our primary router"));
1519 server->id_entry->router = id_entry;
1520 server->router = id_entry;
1521 server->router->server_type = SILC_ROUTER;
1522 server->standalone = FALSE;
1523 server->backup_primary = FALSE;
1525 /* Announce data if we are not backup router (unless not as primary
1526 currently). Backup router announces later at the end of
1527 resuming protocol. */
1528 if (server->backup_router && server->server_type == SILC_ROUTER) {
1529 SILC_LOG_DEBUG(("Announce data after resume protocol"));
1531 /* If we are router then announce our possible servers. Backup
1532 router announces also global servers. */
1533 if (server->server_type == SILC_ROUTER)
1534 silc_server_announce_servers(server,
1535 server->backup_router ? TRUE : FALSE,
1536 0, SILC_PRIMARY_ROUTE(server));
1538 /* Announce our clients and channels to the router */
1539 silc_server_announce_clients(server, 0, SILC_PRIMARY_ROUTE(server));
1540 silc_server_announce_channels(server, 0, SILC_PRIMARY_ROUTE(server));
1543 /* If we are backup router then this primary router is whom we are
1545 if (server->server_type == SILC_BACKUP_ROUTER)
1546 silc_server_backup_add(server, server->id_entry, sock->ip,
1547 sconn->remote_port, TRUE);
1550 /* Add this server to be our backup router */
1551 id_entry->server_type = SILC_BACKUP_ROUTER;
1552 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1553 sconn->backup_replace_port, FALSE);
1556 sock->protocol = NULL;
1559 /* Call the completion callback to indicate that we've connected to
1561 if (sconn && sconn->callback)
1562 (*sconn->callback)(server, id_entry, sconn->callback_context);
1564 /* Free the temporary connection data context */
1566 silc_server_config_unref(&sconn->conn);
1567 silc_free(sconn->remote_host);
1568 silc_free(sconn->backup_replace_ip);
1571 if (sconn == server->router_conn)
1572 server->router_conn = NULL;
1575 /* Free the protocol object */
1576 if (sock->protocol == protocol)
1577 sock->protocol = NULL;
1578 silc_protocol_free(protocol);
1580 silc_packet_context_free(ctx->packet);
1582 silc_ske_free(ctx->ske);
1583 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1584 silc_free(ctx->auth_data);
1588 /* Host lookup callback that is called after the incoming connection's
1589 IP and FQDN lookup is performed. This will actually check the acceptance
1590 of the incoming connection and will register the key exchange protocol
1591 for this connection. */
1594 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1597 SilcServerKEInternalContext *proto_ctx =
1598 (SilcServerKEInternalContext *)context;
1599 SilcServer server = (SilcServer)proto_ctx->server;
1600 SilcServerConfigClient *cconfig = NULL;
1601 SilcServerConfigServer *sconfig = NULL;
1602 SilcServerConfigRouter *rconfig = NULL;
1603 SilcServerConfigDeny *deny;
1606 /* Check whether we could resolve both IP and FQDN. */
1607 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1608 server->config->require_reverse_lookup)) {
1609 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1610 sock->hostname ? sock->hostname :
1611 sock->ip ? sock->ip : ""));
1612 server->stat.conn_failures++;
1613 silc_server_disconnect_remote(server, sock,
1614 SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
1615 "Unknown host or IP");
1616 silc_free(proto_ctx);
1620 /* Register the connection for network input and output. This sets
1621 that scheduler will listen for incoming packets for this connection
1622 and sets that outgoing packets may be sent to this connection as well.
1623 However, this doesn't set the scheduler for outgoing traffic, it
1624 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1625 later when outgoing data is available. */
1626 context = (void *)server;
1627 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1629 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1632 /* Listenning port */
1633 if (!server->sockets[SILC_PTR_TO_32(proto_ctx->context)]) {
1634 silc_server_disconnect_remote(server, sock,
1635 SILC_STATUS_ERR_RESOURCE_LIMIT,
1636 "Connection refused");
1637 server->stat.conn_failures++;
1638 silc_free(proto_ctx);
1641 port = server->sockets[SILC_PTR_TO_32(proto_ctx->context)]->port;
1643 /* Check whether this connection is denied to connect to us. */
1644 deny = silc_server_config_find_denied(server, sock->ip);
1646 deny = silc_server_config_find_denied(server, sock->hostname);
1648 /* The connection is denied */
1649 SILC_LOG_INFO(("Connection %s (%s) is denied",
1650 sock->hostname, sock->ip));
1651 silc_server_disconnect_remote(server, sock,
1652 SILC_STATUS_ERR_BANNED_FROM_SERVER,
1654 server->stat.conn_failures++;
1655 silc_free(proto_ctx);
1659 /* Check whether we have configured this sort of connection at all. We
1660 have to check all configurations since we don't know what type of
1661 connection this is. */
1662 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1663 cconfig = silc_server_config_find_client(server, sock->hostname);
1664 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1665 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1666 if (server->server_type == SILC_ROUTER) {
1667 if (!(rconfig = silc_server_config_find_router_conn(server,
1668 sock->ip, sock->port)))
1669 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1672 if (!cconfig && !sconfig && !rconfig) {
1673 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1675 silc_server_disconnect_remote(server, sock,
1676 SILC_STATUS_ERR_BANNED_FROM_SERVER, NULL);
1677 server->stat.conn_failures++;
1678 silc_free(proto_ctx);
1682 /* The connection is allowed */
1684 /* Set internal context for key exchange protocol. This is
1685 sent as context for the protocol. */
1686 proto_ctx->sock = sock;
1687 proto_ctx->rng = server->rng;
1688 proto_ctx->responder = TRUE;
1689 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1690 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1691 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1693 /* Take flags for key exchange. Since we do not know what type of connection
1694 this is, we go through all found configurations and use the global ones
1695 as well. This will result always into strictest key exchange flags. */
1696 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1697 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1698 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1699 if (server->config->param.key_exchange_pfs)
1700 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1702 /* Prepare the connection for key exchange protocol. We allocate the
1703 protocol but will not start it yet. The connector will be the
1704 initiator of the protocol thus we will wait for initiation from
1705 there before we start the protocol. */
1706 server->stat.auth_attempts++;
1707 SILC_LOG_DEBUG(("Starting key exchange protocol"));
1708 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1709 &sock->protocol, proto_ctx,
1710 silc_server_accept_new_connection_second);
1712 /* Register a timeout task that will be executed if the connector
1713 will not start the key exchange protocol within specified timeout
1714 and the connection will be closed. */
1715 proto_ctx->timeout_task =
1716 silc_schedule_task_add(server->schedule, sock->sock,
1717 silc_server_timeout_remote,
1719 server->config->key_exchange_timeout, 0,
1724 /* Accepts new connections to the server. Accepting new connections are
1725 done in three parts to make it async. */
1727 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1729 SilcServer server = (SilcServer)context;
1730 SilcSocketConnection newsocket;
1731 SilcServerKEInternalContext *proto_ctx;
1734 SILC_LOG_DEBUG(("Accepting new connection"));
1736 server->stat.conn_attempts++;
1738 sock = silc_net_accept_connection(fd);
1740 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1741 server->stat.conn_failures++;
1745 /* Check for maximum allowed connections */
1746 if (sock > server->config->param.connections_max) {
1747 SILC_LOG_ERROR(("Refusing connection, server is full"));
1748 server->stat.conn_failures++;
1749 silc_net_close_connection(sock);
1752 server->stat.conn_num++;
1754 /* Set socket options */
1755 silc_net_set_socket_nonblock(sock);
1756 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1758 /* We don't create a ID yet, since we don't know what type of connection
1759 this is yet. But, we do add the connection to the socket table. */
1760 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1761 server->sockets[sock] = newsocket;
1763 /* Perform asynchronous host lookup. This will lookup the IP and the
1764 FQDN of the remote connection. After the lookup is done the connection
1765 is accepted further. */
1766 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1767 proto_ctx->server = server;
1768 proto_ctx->context = SILC_32_TO_PTR(fd);
1769 silc_socket_host_lookup(newsocket, TRUE,
1770 silc_server_accept_new_connection_lookup,
1771 (void *)proto_ctx, server->schedule);
1774 /* Second part of accepting new connection. Key exchange protocol has been
1775 performed and now it is time to do little connection authentication
1776 protocol to figure out whether this connection is client or server
1777 and whether it has right to access this server (especially server
1778 connections needs to be authenticated). */
1780 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1782 SilcProtocol protocol = (SilcProtocol)context;
1783 SilcServerKEInternalContext *ctx =
1784 (SilcServerKEInternalContext *)protocol->context;
1785 SilcServer server = (SilcServer)ctx->server;
1786 SilcSocketConnection sock = ctx->sock;
1787 SilcServerConnAuthInternalContext *proto_ctx;
1789 SILC_LOG_DEBUG(("Start"));
1791 if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1792 (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1793 /* Error occured during protocol */
1794 SILC_LOG_DEBUG(("Error in key exchange protocol"));
1795 silc_protocol_free(protocol);
1796 sock->protocol = NULL;
1797 silc_ske_free_key_material(ctx->keymat);
1799 silc_packet_context_free(ctx->packet);
1801 silc_ske_free(ctx->ske);
1802 silc_free(ctx->dest_id);
1803 silc_server_config_unref(&ctx->cconfig);
1804 silc_server_config_unref(&ctx->sconfig);
1805 silc_server_config_unref(&ctx->rconfig);
1808 if (!SILC_IS_DISCONNECTING(sock)) {
1809 SILC_LOG_INFO(("Key exchange failed for %s:%d [%s]", sock->hostname,
1811 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1812 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1813 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1815 silc_server_disconnect_remote(server, sock,
1816 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
1820 server->stat.auth_failures++;
1824 /* We now have the key material as the result of the key exchange
1825 protocol. Take the key material into use. Free the raw key material
1826 as soon as we've set them into use. */
1827 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1828 ctx->sock, ctx->keymat,
1829 ctx->ske->prop->cipher,
1830 ctx->ske->prop->pkcs,
1831 ctx->ske->prop->hash,
1832 ctx->ske->prop->hmac,
1833 ctx->ske->prop->group,
1835 SILC_LOG_ERROR(("Error setting key material in use"));
1836 silc_protocol_free(protocol);
1837 sock->protocol = NULL;
1838 silc_ske_free_key_material(ctx->keymat);
1840 silc_packet_context_free(ctx->packet);
1842 silc_ske_free(ctx->ske);
1843 silc_free(ctx->dest_id);
1844 silc_server_config_unref(&ctx->cconfig);
1845 silc_server_config_unref(&ctx->sconfig);
1846 silc_server_config_unref(&ctx->rconfig);
1848 silc_server_disconnect_remote(server, sock,
1849 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1850 server->stat.auth_failures++;
1853 silc_ske_free_key_material(ctx->keymat);
1855 /* Allocate internal context for the authentication protocol. This
1856 is sent as context for the protocol. */
1857 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1858 proto_ctx->server = (void *)server;
1859 proto_ctx->sock = sock;
1860 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1861 proto_ctx->responder = TRUE;
1862 proto_ctx->dest_id_type = ctx->dest_id_type;
1863 proto_ctx->dest_id = ctx->dest_id;
1864 proto_ctx->cconfig = ctx->cconfig;
1865 proto_ctx->sconfig = ctx->sconfig;
1866 proto_ctx->rconfig = ctx->rconfig;
1868 /* Free old protocol as it is finished now */
1869 silc_protocol_free(protocol);
1871 silc_packet_context_free(ctx->packet);
1873 sock->protocol = NULL;
1875 /* Allocate the authentication protocol. This is allocated here
1876 but we won't start it yet. We will be receiving party of this
1877 protocol thus we will wait that connecting party will make
1878 their first move. */
1879 SILC_LOG_DEBUG(("Starting connection authentication protocol"));
1880 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1881 &sock->protocol, proto_ctx,
1882 silc_server_accept_new_connection_final);
1884 /* Register timeout task. If the protocol is not executed inside
1885 this timelimit the connection will be terminated. */
1886 proto_ctx->timeout_task =
1887 silc_schedule_task_add(server->schedule, sock->sock,
1888 silc_server_timeout_remote,
1890 server->config->conn_auth_timeout, 0,
1895 /* After this is called, server don't wait for backup router anymore.
1896 This gets called automatically even after we have backup router
1897 connection established. */
1899 SILC_TASK_CALLBACK(silc_server_backup_router_wait)
1901 SilcServer server = context;
1902 server->wait_backup = FALSE;
1905 /* Final part of accepting new connection. The connection has now
1906 been authenticated and keys has been exchanged. We also know whether
1907 this is client or server connection. */
1909 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1911 SilcProtocol protocol = (SilcProtocol)context;
1912 SilcServerConnAuthInternalContext *ctx =
1913 (SilcServerConnAuthInternalContext *)protocol->context;
1914 SilcServer server = (SilcServer)ctx->server;
1915 SilcSocketConnection sock = ctx->sock;
1916 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1918 SilcServerConfigConnParams *param = &server->config->param;
1920 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1921 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1922 /* Error occured during protocol */
1923 SILC_LOG_DEBUG(("Error during authentication protocol"));
1924 silc_protocol_free(protocol);
1925 sock->protocol = NULL;
1927 silc_packet_context_free(ctx->packet);
1929 silc_ske_free(ctx->ske);
1930 silc_free(ctx->dest_id);
1931 silc_server_config_unref(&ctx->cconfig);
1932 silc_server_config_unref(&ctx->sconfig);
1933 silc_server_config_unref(&ctx->rconfig);
1936 if (!SILC_IS_DISCONNECTING(sock)) {
1937 SILC_LOG_INFO(("Authentication failed for %s:%d [%s]", sock->hostname,
1939 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1940 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1941 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1943 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1946 server->stat.auth_failures++;
1950 entry->data.last_receive = time(NULL);
1952 switch (ctx->conn_type) {
1953 case SILC_SOCKET_TYPE_CLIENT:
1955 SilcClientEntry client;
1956 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1958 /* Verify whether this connection is after all allowed to connect */
1959 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1960 &server->config->param,
1961 conn->param, ctx->ske)) {
1962 server->stat.auth_failures++;
1966 /* If we are primary router and we have backup router configured
1967 but it has not connected to use yet, do not accept any other
1969 if (server->wait_backup && server->server_type == SILC_ROUTER &&
1970 !server->backup_router) {
1971 SilcServerConfigRouter *router;
1972 router = silc_server_config_get_backup_router(server);
1973 if (router && strcmp(server->config->server_info->primary->server_ip,
1975 silc_server_find_socket_by_host(server,
1976 SILC_SOCKET_TYPE_SERVER,
1977 router->backup_replace_ip, 0)) {
1978 SILC_LOG_INFO(("Will not accept connections because we do "
1979 "not have backup router connection established"));
1980 sock->protocol = NULL;
1981 silc_server_disconnect_remote(server, sock,
1982 SILC_STATUS_ERR_PERM_DENIED,
1983 "We do not have connection to backup "
1984 "router established, try later");
1985 silc_free(sock->user_data);
1986 server->stat.auth_failures++;
1988 /* From here on, wait 20 seconds for the backup router to appear. */
1989 silc_schedule_task_add(server->schedule, 0,
1990 silc_server_backup_router_wait,
1991 (void *)server, 20, 0,
1992 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1997 SILC_LOG_DEBUG(("Remote host is client"));
1998 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
2001 /* Add the client to the client ID cache. The nickname and Client ID
2002 and other information is created after we have received NEW_CLIENT
2003 packet from client. */
2004 client = silc_idlist_add_client(server->local_list,
2005 NULL, NULL, NULL, NULL, NULL, sock, 0);
2007 SILC_LOG_ERROR(("Could not add new client to cache"));
2008 silc_free(sock->user_data);
2009 sock->protocol = NULL;
2010 silc_server_disconnect_remote(server, sock,
2011 SILC_STATUS_ERR_AUTH_FAILED, NULL);
2012 server->stat.auth_failures++;
2015 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
2018 server->stat.my_clients++;
2019 server->stat.clients++;
2020 server->stat.cell_clients++;
2022 /* Get connection parameters */
2024 param = conn->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;
2037 /* Check if to be anonymous connection */
2038 if (param->anonymous)
2039 client->mode |= SILC_UMODE_ANONYMOUS;
2042 /* Add public key to hash list (for whois using attributes) */
2043 silc_hash_table_add(server->pk_hash,
2044 entry->data.public_key, client);
2046 id_entry = (void *)client;
2049 case SILC_SOCKET_TYPE_SERVER:
2050 case SILC_SOCKET_TYPE_ROUTER:
2052 SilcServerEntry new_server;
2053 bool initiator = FALSE;
2054 bool backup_local = FALSE;
2055 bool backup_router = FALSE;
2056 char *backup_replace_ip = NULL;
2057 SilcUInt16 backup_replace_port = 0;
2058 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
2059 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
2061 /* If we are backup router and this is incoming server connection
2062 and we do not have connection to primary router, do not allow
2064 if (server->server_type == SILC_BACKUP_ROUTER &&
2065 ctx->conn_type == SILC_SOCKET_TYPE_SERVER &&
2066 !SILC_PRIMARY_ROUTE(server)) {
2067 SILC_LOG_INFO(("Will not accept server connection because we do "
2068 "not have primary router connection established"));
2069 sock->protocol = NULL;
2070 silc_server_disconnect_remote(server, sock,
2071 SILC_STATUS_ERR_PERM_DENIED,
2072 "We do not have connection to primary "
2073 "router established, try later");
2074 silc_free(sock->user_data);
2075 server->stat.auth_failures++;
2079 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
2080 /* Verify whether this connection is after all allowed to connect */
2081 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
2082 &server->config->param,
2083 rconn ? rconn->param : NULL,
2085 silc_free(sock->user_data);
2086 server->stat.auth_failures++;
2092 param = rconn->param;
2094 if (!param->keepalive_secs)
2095 param->keepalive_secs = server->config->param.keepalive_secs;
2097 if (!param->qos && server->config->param.qos) {
2098 param->qos = server->config->param.qos;
2099 param->qos_rate_limit = server->config->param.qos_rate_limit;
2100 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
2101 param->qos_limit_sec = server->config->param.qos_limit_sec;
2102 param->qos_limit_usec = server->config->param.qos_limit_usec;
2106 initiator = rconn->initiator;
2107 backup_local = rconn->backup_local;
2108 backup_router = rconn->backup_router;
2109 backup_replace_ip = rconn->backup_replace_ip;
2110 backup_replace_port = rconn->backup_replace_port;
2114 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
2115 /* Verify whether this connection is after all allowed to connect */
2116 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
2117 &server->config->param,
2118 sconn ? sconn->param : NULL,
2120 silc_free(sock->user_data);
2121 server->stat.auth_failures++;
2126 param = sconn->param;
2128 if (!param->keepalive_secs)
2129 param->keepalive_secs = server->config->param.keepalive_secs;
2131 if (!param->qos && server->config->param.qos) {
2132 param->qos = server->config->param.qos;
2133 param->qos_rate_limit = server->config->param.qos_rate_limit;
2134 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
2135 param->qos_limit_sec = server->config->param.qos_limit_sec;
2136 param->qos_limit_usec = server->config->param.qos_limit_usec;
2140 backup_router = sconn->backup_router;
2144 /* If we are primary router and we have backup router configured
2145 but it has not connected to use yet, do not accept any other
2147 if (server->wait_backup && server->server_type == SILC_ROUTER &&
2148 !server->backup_router && !backup_router) {
2149 SilcServerConfigRouter *router;
2150 router = silc_server_config_get_backup_router(server);
2151 if (router && strcmp(server->config->server_info->primary->server_ip,
2153 silc_server_find_socket_by_host(server,
2154 SILC_SOCKET_TYPE_SERVER,
2155 router->backup_replace_ip, 0)) {
2156 SILC_LOG_INFO(("Will not accept connections because we do "
2157 "not have backup router connection established"));
2158 sock->protocol = NULL;
2159 silc_server_disconnect_remote(server, sock,
2160 SILC_STATUS_ERR_PERM_DENIED,
2161 "We do not have connection to backup "
2162 "router established, try later");
2163 silc_free(sock->user_data);
2164 server->stat.auth_failures++;
2166 /* From here on, wait 20 seconds for the backup router to appear. */
2167 silc_schedule_task_add(server->schedule, 0,
2168 silc_server_backup_router_wait,
2169 (void *)server, 20, 0,
2170 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2175 SILC_LOG_DEBUG(("Remote host is %s",
2176 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2177 "server" : (backup_router ?
2178 "backup router" : "router")));
2179 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
2180 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2181 "server" : (backup_router ?
2182 "backup router" : "router")));
2184 /* Add the server into server cache. The server name and Server ID
2185 is updated after we have received NEW_SERVER packet from the
2186 server. We mark ourselves as router for this server if we really
2189 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2190 server->local_list : (backup_router ?
2191 server->local_list :
2192 server->global_list)),
2194 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2195 SILC_SERVER : SILC_ROUTER),
2197 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2198 server->id_entry : (backup_router ?
2199 server->id_entry : NULL)),
2202 SILC_LOG_ERROR(("Could not add new server to cache"));
2203 silc_free(sock->user_data);
2204 sock->protocol = NULL;
2205 silc_server_disconnect_remote(server, sock,
2206 SILC_STATUS_ERR_AUTH_FAILED, NULL);
2207 server->stat.auth_failures++;
2210 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
2212 id_entry = (void *)new_server;
2214 /* If the incoming connection is router and marked as backup router
2215 then add it to be one of our backups */
2216 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
2217 /* Change it back to SERVER type since that's what it really is. */
2219 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
2220 new_server->server_type = SILC_BACKUP_ROUTER;
2222 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
2223 ("Backup router %s is now online",
2226 /* Remove the backup waiting with timeout */
2227 silc_schedule_task_add(server->schedule, 0,
2228 silc_server_backup_router_wait,
2229 (void *)server, 10, 0,
2230 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2234 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
2235 server->stat.my_servers++;
2236 server->stat.servers++;
2238 server->stat.my_routers++;
2239 server->stat.routers++;
2242 /* Check whether this connection is to be our primary router connection
2243 if we do not already have the primary route. */
2244 if (!backup_router &&
2245 server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
2246 if (silc_server_config_is_primary_route(server) && !initiator)
2249 SILC_LOG_DEBUG(("We are not standalone server anymore"));
2250 server->standalone = FALSE;
2251 if (!server->id_entry->router) {
2252 server->id_entry->router = id_entry;
2253 server->router = id_entry;
2264 sock->type = ctx->conn_type;
2266 /* Add the common data structure to the ID entry. */
2267 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
2269 /* Add to sockets internal pointer for fast referencing */
2270 silc_free(sock->user_data);
2271 sock->user_data = id_entry;
2273 /* Connection has been fully established now. Everything is ok. */
2274 SILC_LOG_DEBUG(("New connection authenticated"));
2276 /* Perform keepalive. */
2277 if (param->keepalive_secs)
2278 silc_socket_set_heartbeat(sock, param->keepalive_secs, server,
2279 silc_server_perform_heartbeat,
2282 /* Perform Quality of Service */
2284 silc_socket_set_qos(sock, param->qos_rate_limit, param->qos_bytes_limit,
2285 param->qos_limit_sec, param->qos_limit_usec,
2289 if (sock->protocol == protocol)
2290 silc_protocol_free(protocol);
2292 silc_packet_context_free(ctx->packet);
2294 silc_ske_free(ctx->ske);
2295 silc_free(ctx->dest_id);
2296 silc_server_config_unref(&ctx->cconfig);
2297 silc_server_config_unref(&ctx->sconfig);
2298 silc_server_config_unref(&ctx->rconfig);
2300 sock->protocol = NULL;
2303 /* This function is used to read packets from network and send packets to
2304 network. This is usually a generic task. */
2306 SILC_TASK_CALLBACK(silc_server_packet_process)
2308 SilcServer server = (SilcServer)context;
2309 SilcSocketConnection sock = server->sockets[fd];
2310 SilcIDListData idata;
2311 SilcCipher cipher = NULL;
2312 SilcHmac hmac = NULL;
2313 SilcUInt32 sequence = 0;
2314 bool local_is_router;
2318 SILC_LOG_DEBUG(("Unknown socket connection"));
2322 /* Packet sending */
2324 if (type == SILC_TASK_WRITE) {
2325 /* Do not send data to disconnected connection */
2326 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2327 SILC_LOG_DEBUG(("Disconnected socket connection, cannot send"));
2328 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
2329 SILC_UNSET_OUTBUF_PENDING(sock);
2330 silc_buffer_clear(sock->outbuf);
2334 server->stat.packets_sent++;
2336 /* Send the packet */
2337 ret = silc_packet_send(sock, TRUE);
2339 /* If returned -2 could not write to connection now, will do
2344 /* The packet has been sent and now it is time to set the connection
2345 back to only for input. When there is again some outgoing data
2346 available for this connection it will be set for output as well.
2347 This call clears the output setting and sets it only for input. */
2348 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
2349 SILC_UNSET_OUTBUF_PENDING(sock);
2350 silc_buffer_clear(sock->outbuf);
2353 SILC_LOG_ERROR(("Error sending packet to connection "
2354 "%s:%d [%s]", sock->hostname, sock->port,
2355 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2356 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2357 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2360 if (sock->user_data) {
2361 /* If backup then mark that resuming will not be allowed */
2362 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2363 sock->type == SILC_SOCKET_TYPE_SERVER) {
2364 SilcServerEntry server_entry = sock->user_data;
2365 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2366 server->backup_closed = TRUE;
2369 silc_server_free_sock_user_data(server, sock, NULL);
2371 SILC_SET_DISCONNECTING(sock);
2372 silc_server_close_connection(server, sock);
2377 /* Packet receiving */
2379 /* Read some data from connection */
2380 ret = silc_packet_receive(sock);
2384 SILC_LOG_ERROR(("Error receiving packet from connection "
2385 "%s:%d [%s] %s", sock->hostname, sock->port,
2386 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2387 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2388 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2389 "Router"), strerror(errno)));
2391 if (sock->user_data) {
2392 /* If backup then mark that resuming will not be allowed */
2393 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2394 sock->type == SILC_SOCKET_TYPE_SERVER) {
2395 SilcServerEntry server_entry = sock->user_data;
2396 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2397 server->backup_closed = TRUE;
2400 silc_server_free_sock_user_data(server, sock, NULL);
2402 SILC_SET_DISCONNECTING(sock);
2403 silc_server_close_connection(server, sock);
2410 SILC_LOG_DEBUG(("Read EOF"));
2412 /* If connection is disconnecting already we will finally
2413 close the connection */
2414 if (SILC_IS_DISCONNECTING(sock)) {
2415 if (sock->user_data)
2416 silc_server_free_sock_user_data(server, sock, NULL);
2417 silc_server_close_connection(server, sock);
2421 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
2423 if (sock->user_data) {
2426 /* If backup disconnected then mark that resuming will not be allowed */
2427 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2428 sock->type == SILC_SOCKET_TYPE_SERVER && sock->user_data) {
2429 SilcServerEntry server_entry = sock->user_data;
2430 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2431 server->backup_closed = TRUE;
2434 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
2435 silc_server_free_sock_user_data(server, sock, tmp);
2437 silc_server_free_sock_user_data(server, sock, NULL);
2438 } else if (server->router_conn && server->router_conn->sock == sock &&
2439 !server->router && server->standalone) {
2440 silc_server_create_connections(server);
2443 SILC_SET_DISCONNECTING(sock);
2444 silc_server_close_connection(server, sock);
2448 /* If connection is disconnecting or disconnected we will ignore
2450 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2451 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
2455 /* Get keys and stuff from ID entry */
2456 idata = (SilcIDListData)sock->user_data;
2458 cipher = idata->receive_key;
2459 hmac = idata->hmac_receive;
2460 sequence = idata->psn_receive;
2463 /* Then, process the packet. This will call the parser that will then
2464 decrypt and parse the packet. */
2466 local_is_router = (server->server_type == SILC_ROUTER);
2468 /* If socket connection is our primary, we are backup and we are doing
2469 backup resuming, we won't process the packet as being a router
2470 (affects channel message decryption). */
2471 if (server->backup_router && SILC_SERVER_IS_BACKUP(sock) &&
2472 SILC_PRIMARY_ROUTE(server) == sock)
2473 local_is_router = FALSE;
2475 ret = silc_packet_receive_process(sock, local_is_router,
2476 cipher, hmac, sequence,
2477 silc_server_packet_parse, server);
2479 /* If processing failed the connection is closed. */
2481 /* On packet processing errors we may close our primary router
2482 connection but won't become primary router if we are the backup
2483 since this is local error condition. */
2484 if (SILC_PRIMARY_ROUTE(server) == sock && server->backup_router)
2485 server->backup_noswitch = TRUE;
2487 if (sock->user_data) {
2488 /* If we are router and backup errorred then mark that resuming
2489 will not be allowed */
2490 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2491 sock->type == SILC_SOCKET_TYPE_SERVER) {
2492 SilcServerEntry server_entry = sock->user_data;
2493 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2494 server->backup_closed = TRUE;
2497 silc_server_free_sock_user_data(server, sock, NULL);
2499 SILC_SET_DISCONNECTING(sock);
2500 silc_server_close_connection(server, sock);
2504 /* Parses whole packet, received earlier. */
2506 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
2508 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
2509 SilcServer server = (SilcServer)parse_ctx->context;
2510 SilcSocketConnection sock = parse_ctx->sock;
2511 SilcPacketContext *packet = parse_ctx->packet;
2512 SilcIDListData idata = (SilcIDListData)sock->user_data;
2515 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2516 SILC_LOG_DEBUG(("Connection is disconnected"));
2520 server->stat.packets_received++;
2522 /* Parse the packet */
2523 if (parse_ctx->normal)
2524 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
2526 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
2528 /* If entry is disabled ignore what we got. */
2529 if (idata && idata->status & SILC_IDLIST_STATUS_DISABLED &&
2530 ret != SILC_PACKET_HEARTBEAT && ret != SILC_PACKET_RESUME_ROUTER &&
2531 ret != SILC_PACKET_REKEY && ret != SILC_PACKET_REKEY_DONE &&
2532 ret != SILC_PACKET_KEY_EXCHANGE_1 && ret != SILC_PACKET_KEY_EXCHANGE_2) {
2533 SILC_LOG_DEBUG(("Connection is disabled (packet %s dropped)",
2534 silc_get_packet_name(ret)));
2538 if (ret == SILC_PACKET_NONE) {
2539 SILC_LOG_DEBUG(("Error parsing packet"));
2543 /* Check that the the current client ID is same as in the client's packet. */
2544 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
2545 SilcClientEntry client = (SilcClientEntry)sock->user_data;
2546 if (client && client->id && packet->src_id) {
2547 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
2548 packet->src_id_type);
2549 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
2551 SILC_LOG_DEBUG(("Packet source is not same as sender"));
2558 if (server->server_type == SILC_ROUTER) {
2559 /* Route the packet if it is not destined to us. Other ID types but
2560 server are handled separately after processing them. */
2561 if (packet->dst_id && !(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
2562 packet->dst_id_type == SILC_ID_SERVER &&
2563 sock->type != SILC_SOCKET_TYPE_CLIENT &&
2564 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
2565 SilcSocketConnection conn;
2567 /* Route the packet to fastest route for the destination ID */
2568 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
2569 packet->dst_id_type);
2573 conn = silc_server_route_get(server, id, packet->dst_id_type);
2575 SILC_LOG_WARNING(("Packet to unknown server ID %s, dropped (no route)",
2576 silc_id_render(id, SILC_ID_SERVER)));
2580 silc_server_packet_route(server, conn, packet);
2586 /* Parse the incoming packet type */
2587 silc_server_packet_parse_type(server, sock, packet);
2589 /* Broadcast packet if it is marked as broadcast packet and it is
2590 originated from router and we are router. */
2591 if (server->server_type == SILC_ROUTER &&
2592 sock->type == SILC_SOCKET_TYPE_ROUTER &&
2593 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
2594 /* Broadcast to our primary route */
2595 silc_server_packet_broadcast(server, SILC_PRIMARY_ROUTE(server), packet);
2597 /* If we have backup routers then we need to feed all broadcast
2598 data to those servers. */
2599 silc_server_backup_broadcast(server, sock, packet);
2603 silc_packet_context_free(packet);
2604 silc_free(parse_ctx);
2607 /* Parser callback called by silc_packet_receive_process. This merely
2608 registers timeout that will handle the actual parsing when appropriate. */
2610 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
2613 SilcServer server = (SilcServer)context;
2614 SilcSocketConnection sock = parser_context->sock;
2615 SilcIDListData idata = (SilcIDListData)sock->user_data;
2619 idata->psn_receive = parser_context->packet->sequence + 1;
2621 /* If protocol for this connection is key exchange or rekey then we'll
2622 process all packets synchronously, since there might be packets in
2623 queue that we are not able to decrypt without first processing the
2624 packets before them. */
2625 if (sock->protocol && sock->protocol->protocol &&
2626 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2627 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2628 silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2631 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2632 SILC_LOG_DEBUG(("Connection is disconnected"));
2636 /* Reprocess data since we'll return FALSE here. This is because
2637 the idata->receive_key might have become valid in the last packet
2638 and we want to call this processor with valid cipher. */
2640 ret = silc_packet_receive_process(
2641 sock, server->server_type == SILC_ROUTER,
2643 idata->hmac_receive, idata->psn_receive,
2644 silc_server_packet_parse, server);
2646 ret = silc_packet_receive_process(
2647 sock, server->server_type == SILC_ROUTER,
2649 silc_server_packet_parse, server);
2652 /* On packet processing errors we may close our primary router
2653 connection but won't become primary router if we are the backup
2654 since this is local error condition. */
2655 if (SILC_PRIMARY_ROUTE(server) == sock && server->backup_router)
2656 server->backup_noswitch = TRUE;
2658 if (sock->user_data)
2659 silc_server_free_sock_user_data(server, sock, NULL);
2660 SILC_SET_DISCONNECTING(sock);
2661 silc_server_close_connection(server, sock);
2667 switch (sock->type) {
2668 case SILC_SOCKET_TYPE_UNKNOWN:
2669 case SILC_SOCKET_TYPE_CLIENT:
2670 /* Parse the packet with timeout */
2671 silc_schedule_task_add(server->schedule, sock->sock,
2672 silc_server_packet_parse_real,
2673 (void *)parser_context, 0, 100000,
2675 SILC_TASK_PRI_NORMAL);
2677 case SILC_SOCKET_TYPE_SERVER:
2678 case SILC_SOCKET_TYPE_ROUTER:
2679 /* Packets from servers are parsed immediately */
2680 silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2688 /* Parses the packet type and calls what ever routines the packet type
2689 requires. This is done for all incoming packets. */
2691 void silc_server_packet_parse_type(SilcServer server,
2692 SilcSocketConnection sock,
2693 SilcPacketContext *packet)
2695 SilcPacketType type = packet->type;
2696 SilcIDListData idata = (SilcIDListData)sock->user_data;
2698 SILC_LOG_DEBUG(("Received %s packet [flags %d]",
2699 silc_get_packet_name(type), packet->flags));
2701 /* Parse the packet type */
2703 case SILC_PACKET_DISCONNECT:
2706 char *message = NULL;
2708 if (packet->flags & SILC_PACKET_FLAG_LIST)
2710 if (packet->buffer->len < 1)
2713 status = (SilcStatus)packet->buffer->data[0];
2714 if (packet->buffer->len > 1 &&
2715 silc_utf8_valid(packet->buffer->data + 1, packet->buffer->len - 1))
2716 message = silc_memdup(packet->buffer->data + 1,
2717 packet->buffer->len - 1);
2719 SILC_LOG_INFO(("Disconnected by %s (%s): %s (%d) %s",
2720 sock->ip, sock->hostname,
2721 silc_get_status_message(status), status,
2722 message ? message : ""));
2725 /* Do not switch to backup in case of error */
2726 server->backup_noswitch = (status == SILC_STATUS_OK ? FALSE : TRUE);
2728 /* If backup disconnected then mark that resuming will not be allowed */
2729 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2730 sock->type == SILC_SOCKET_TYPE_SERVER && sock->user_data) {
2731 SilcServerEntry server_entry = sock->user_data;
2732 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2733 server->backup_closed = TRUE;
2736 /* Handle the disconnection from our end too */
2737 if (sock->user_data && SILC_IS_LOCAL(sock->user_data))
2738 silc_server_free_sock_user_data(server, sock, NULL);
2739 SILC_SET_DISCONNECTING(sock);
2740 silc_server_close_connection(server, sock);
2741 server->backup_noswitch = FALSE;
2745 case SILC_PACKET_SUCCESS:
2747 * Success received for something. For now we can have only
2748 * one protocol for connection executing at once hence this
2749 * success message is for whatever protocol is executing currently.
2751 if (packet->flags & SILC_PACKET_FLAG_LIST)
2754 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2757 case SILC_PACKET_FAILURE:
2759 * Failure received for something. For now we can have only
2760 * one protocol for connection executing at once hence this
2761 * failure message is for whatever protocol is executing currently.
2763 if (packet->flags & SILC_PACKET_FLAG_LIST)
2766 /* Check for failure START_USE from backup router */
2767 if (server->server_type == SILC_SERVER &&
2768 server->backup_primary && packet->buffer->len == 4) {
2770 SILC_GET32_MSB(type, packet->buffer->data);
2771 if (type == SILC_SERVER_BACKUP_START_USE) {
2772 /* Attempt to reconnect to primary */
2773 SILC_LOG_DEBUG(("Received failed START_USE from backup %s", sock->ip));
2775 /* Default action is to disconnect from backup and reconnect to
2776 primary. Since this failure can happen during switching to
2777 backup (backup might have not noticed the primary going down yet),
2778 we will wait a while and keep sending START_USE to backup.
2779 Only after that we'll give up. */
2780 if (server->router == sock->user_data &&
2781 (time(0) - server->router_connect) < 30) {
2782 SILC_LOG_DEBUG(("Resending START_USE to backup router"));
2783 silc_server_backup_send_start_use(server, sock, FALSE);
2787 /* If backup is our primary, disconnect now. */
2788 if (server->router == sock->user_data) {
2789 if (sock->user_data)
2790 silc_server_free_sock_user_data(server, sock, NULL);
2791 SILC_SET_DISCONNECTING(sock);
2792 silc_server_close_connection(server, sock);
2796 silc_server_create_connections(server);
2800 /* Execute protocol */
2801 if (sock->protocol) {
2802 sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
2803 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2808 case SILC_PACKET_REJECT:
2809 if (packet->flags & SILC_PACKET_FLAG_LIST)
2814 case SILC_PACKET_NOTIFY:
2816 * Received notify packet. Server can receive notify packets from
2817 * router. Server then relays the notify messages to clients if needed.
2819 if (packet->flags & SILC_PACKET_FLAG_LIST)
2820 silc_server_notify_list(server, sock, packet);
2822 silc_server_notify(server, sock, packet);
2828 case SILC_PACKET_CHANNEL_MESSAGE:
2830 * Received channel message. Channel messages are special packets
2831 * (although probably most common ones) thus they are handled
2834 if (packet->flags & SILC_PACKET_FLAG_LIST)
2836 idata->last_receive = time(NULL);
2837 silc_server_channel_message(server, sock, packet);
2840 case SILC_PACKET_CHANNEL_KEY:
2842 * Received key for channel. As channels are created by the router
2843 * the keys are as well. We will distribute the key to all of our
2844 * locally connected clients on the particular channel. Router
2845 * never receives this channel and thus is ignored.
2847 if (packet->flags & SILC_PACKET_FLAG_LIST)
2849 silc_server_channel_key(server, sock, packet);
2855 case SILC_PACKET_COMMAND:
2857 * Recived command. Processes the command request and allocates the
2858 * command context and calls the command.
2860 if (packet->flags & SILC_PACKET_FLAG_LIST)
2862 silc_server_command_process(server, sock, packet);
2865 case SILC_PACKET_COMMAND_REPLY:
2867 * Received command reply packet. Received command reply to command. It
2868 * may be reply to command sent by us or reply to command sent by client
2869 * that we've routed further.
2871 if (packet->flags & SILC_PACKET_FLAG_LIST)
2873 silc_server_command_reply(server, sock, packet);
2877 * Private Message packets
2879 case SILC_PACKET_PRIVATE_MESSAGE:
2881 * Received private message packet. The packet is coming from either
2884 if (packet->flags & SILC_PACKET_FLAG_LIST)
2886 idata->last_receive = time(NULL);
2887 silc_server_private_message(server, sock, packet);
2890 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2892 * Private message key packet.
2894 if (packet->flags & SILC_PACKET_FLAG_LIST)
2896 silc_server_private_message_key(server, sock, packet);
2900 * Key Exchange protocol packets
2902 case SILC_PACKET_KEY_EXCHANGE:
2903 if (packet->flags & SILC_PACKET_FLAG_LIST)
2906 if (sock->protocol && sock->protocol->protocol &&
2907 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2908 SilcServerKEInternalContext *proto_ctx =
2909 (SilcServerKEInternalContext *)sock->protocol->context;
2911 proto_ctx->packet = silc_packet_context_dup(packet);
2913 /* Let the protocol handle the packet */
2914 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2916 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2917 "protocol active (%s:%d [%s]).", sock->hostname,
2919 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2920 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2921 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2926 case SILC_PACKET_KEY_EXCHANGE_1:
2927 if (packet->flags & SILC_PACKET_FLAG_LIST)
2930 if (sock->protocol && sock->protocol->protocol &&
2931 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2932 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2934 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2935 SilcServerRekeyInternalContext *proto_ctx =
2936 (SilcServerRekeyInternalContext *)sock->protocol->context;
2938 if (proto_ctx->packet)
2939 silc_packet_context_free(proto_ctx->packet);
2941 proto_ctx->packet = silc_packet_context_dup(packet);
2943 /* Let the protocol handle the packet */
2944 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2946 SilcServerKEInternalContext *proto_ctx =
2947 (SilcServerKEInternalContext *)sock->protocol->context;
2949 if (proto_ctx->packet)
2950 silc_packet_context_free(proto_ctx->packet);
2952 proto_ctx->packet = silc_packet_context_dup(packet);
2953 proto_ctx->dest_id_type = packet->src_id_type;
2954 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2955 packet->src_id_type);
2956 if (!proto_ctx->dest_id)
2959 /* Let the protocol handle the packet */
2960 silc_protocol_execute(sock->protocol, server->schedule,
2964 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2965 "protocol active (%s:%d [%s]).", sock->hostname,
2967 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2968 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2969 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2974 case SILC_PACKET_KEY_EXCHANGE_2:
2975 if (packet->flags & SILC_PACKET_FLAG_LIST)
2978 if (sock->protocol && sock->protocol->protocol &&
2979 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2980 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2982 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2983 SilcServerRekeyInternalContext *proto_ctx =
2984 (SilcServerRekeyInternalContext *)sock->protocol->context;
2986 if (proto_ctx->packet)
2987 silc_packet_context_free(proto_ctx->packet);
2989 proto_ctx->packet = silc_packet_context_dup(packet);
2991 /* Let the protocol handle the packet */
2992 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2994 SilcServerKEInternalContext *proto_ctx =
2995 (SilcServerKEInternalContext *)sock->protocol->context;
2997 if (proto_ctx->packet)
2998 silc_packet_context_free(proto_ctx->packet);
3000 proto_ctx->packet = silc_packet_context_dup(packet);
3001 proto_ctx->dest_id_type = packet->src_id_type;
3002 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
3003 packet->src_id_type);
3004 if (!proto_ctx->dest_id)
3007 /* Let the protocol handle the packet */
3008 silc_protocol_execute(sock->protocol, server->schedule,
3012 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
3013 "protocol active (%s:%d [%s]).", sock->hostname,
3015 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
3016 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
3017 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
3022 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
3024 * Connection authentication request packet. When we receive this packet
3025 * we will send to the other end information about our mandatory
3026 * authentication method for the connection. This packet maybe received
3029 if (packet->flags & SILC_PACKET_FLAG_LIST)
3031 silc_server_connection_auth_request(server, sock, packet);
3035 * Connection Authentication protocol packets
3037 case SILC_PACKET_CONNECTION_AUTH:
3038 /* Start of the authentication protocol. We receive here the
3039 authentication data and will verify it. */
3040 if (packet->flags & SILC_PACKET_FLAG_LIST)
3043 if (sock->protocol && sock->protocol->protocol->type
3044 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
3046 SilcServerConnAuthInternalContext *proto_ctx =
3047 (SilcServerConnAuthInternalContext *)sock->protocol->context;
3049 proto_ctx->packet = silc_packet_context_dup(packet);
3051 /* Let the protocol handle the packet */
3052 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
3054 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
3055 "protocol active (%s:%d [%s]).", sock->hostname,
3057 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
3058 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
3059 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
3064 case SILC_PACKET_NEW_ID:
3066 * Received New ID packet. This includes some new ID that has been
3067 * created. It may be for client, server or channel. This is the way
3068 * to distribute information about new registered entities in the
3071 if (packet->flags & SILC_PACKET_FLAG_LIST)
3072 silc_server_new_id_list(server, sock, packet);
3074 silc_server_new_id(server, sock, packet);
3077 case SILC_PACKET_NEW_CLIENT:
3079 * Received new client packet. This includes client information that
3080 * we will use to create initial client ID. After creating new
3081 * ID we will send it to the client.
3083 if (packet->flags & SILC_PACKET_FLAG_LIST)
3085 silc_server_new_client(server, sock, packet);
3088 case SILC_PACKET_NEW_SERVER:
3090 * Received new server packet. This includes Server ID and some other
3091 * information that we may save. This is received after server has
3094 if (packet->flags & SILC_PACKET_FLAG_LIST)
3096 silc_server_new_server(server, sock, packet);
3099 case SILC_PACKET_NEW_CHANNEL:
3101 * Received new channel packet. Information about new channel in the
3102 * network are distributed using this packet.
3104 if (packet->flags & SILC_PACKET_FLAG_LIST)
3105 silc_server_new_channel_list(server, sock, packet);
3107 silc_server_new_channel(server, sock, packet);
3110 case SILC_PACKET_HEARTBEAT:
3112 * Received heartbeat.
3114 if (packet->flags & SILC_PACKET_FLAG_LIST)
3118 case SILC_PACKET_KEY_AGREEMENT:
3120 * Received heartbeat.
3122 if (packet->flags & SILC_PACKET_FLAG_LIST)
3124 silc_server_key_agreement(server, sock, packet);
3127 case SILC_PACKET_REKEY:
3129 * Received re-key packet. The sender wants to regenerate the session
3132 if (packet->flags & SILC_PACKET_FLAG_LIST)
3134 silc_server_rekey(server, sock, packet);
3137 case SILC_PACKET_REKEY_DONE:
3139 * The re-key is done.
3141 if (packet->flags & SILC_PACKET_FLAG_LIST)
3144 if (sock->protocol && sock->protocol->protocol &&
3145 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
3147 SilcServerRekeyInternalContext *proto_ctx =
3148 (SilcServerRekeyInternalContext *)sock->protocol->context;
3150 if (proto_ctx->packet)
3151 silc_packet_context_free(proto_ctx->packet);
3153 proto_ctx->packet = silc_packet_context_dup(packet);
3155 /* Let the protocol handle the packet */
3156 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
3158 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
3159 "protocol active (%s:%d [%s]).", sock->hostname,
3161 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
3162 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
3163 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
3168 case SILC_PACKET_FTP:
3170 if (packet->flags & SILC_PACKET_FLAG_LIST)
3172 silc_server_ftp(server, sock, packet);
3175 case SILC_PACKET_RESUME_CLIENT:
3177 if (packet->flags & SILC_PACKET_FLAG_LIST)
3179 silc_server_resume_client(server, sock, packet);
3182 case SILC_PACKET_RESUME_ROUTER:
3183 /* Resume router packet received. This packet is received for backup
3184 router resuming protocol. */
3185 if (packet->flags & SILC_PACKET_FLAG_LIST)
3187 silc_server_backup_resume_router(server, sock, packet);
3191 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
3196 /* Creates connection to a remote router. */
3198 void silc_server_create_connection(SilcServer server,
3199 const char *remote_host, SilcUInt32 port)
3201 SilcServerConnection sconn;
3203 /* Allocate connection object for hold connection specific stuff. */
3204 sconn = silc_calloc(1, sizeof(*sconn));
3205 sconn->remote_host = strdup(remote_host);
3206 sconn->remote_port = port;
3207 sconn->no_reconnect = TRUE;
3209 silc_schedule_task_add(server->schedule, 0,
3210 silc_server_connect_router,
3211 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
3212 SILC_TASK_PRI_NORMAL);
3215 SILC_TASK_CALLBACK(silc_server_close_connection_final)
3217 SilcServer server = app_context;
3218 SilcSocketConnection sock = context;
3220 SILC_LOG_DEBUG(("Deleting socket %p", sock));
3222 /* Close the actual connection */
3223 silc_net_close_connection(sock->sock);
3224 server->sockets[sock->sock] = NULL;
3225 server->stat.conn_num--;
3227 /* We won't listen for this connection anymore */
3228 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
3229 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
3231 silc_socket_free(sock);
3234 /* Closes connection to socket connection */
3236 void silc_server_close_connection(SilcServer server,
3237 SilcSocketConnection sock)
3241 if (SILC_IS_DISCONNECTED(sock)) {
3242 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
3243 silc_schedule_task_add(server->schedule, sock->sock,
3244 silc_server_close_connection_final,
3245 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
3246 SILC_TASK_PRI_NORMAL);
3247 server->sockets[sock->sock] = NULL;
3251 /* If any protocol is active cancel its execution. It will call
3252 the final callback which will finalize the disconnection. */
3253 if (sock->protocol && sock->protocol->protocol &&
3254 sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3255 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3256 silc_protocol_cancel(sock->protocol, server->schedule);
3257 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3258 silc_protocol_execute_final(sock->protocol, server->schedule);
3259 sock->protocol = NULL;
3263 memset(tmp, 0, sizeof(tmp));
3264 silc_socket_get_error(sock, tmp, sizeof(tmp));
3265 SILC_LOG_INFO(("Closing connection %s:%d [%s] %s", sock->hostname,
3267 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
3268 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
3269 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
3270 "Router"), tmp[0] ? tmp : ""));
3272 SILC_SET_DISCONNECTED(sock);
3273 silc_socket_set_qos(sock, 0, 0, 0, 0, NULL);
3274 silc_schedule_task_add(server->schedule, sock->sock,
3275 silc_server_close_connection_final,
3276 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
3277 SILC_TASK_PRI_NORMAL);
3278 server->sockets[sock->sock] = NULL;
3281 /* Sends disconnect message to remote connection and disconnects the
3282 connection. NOTE: If this is called from protocol callback
3283 then sock->protocol must be set NULL before calling this, since
3284 this routine dispatches protocol callbacks too. */
3286 void silc_server_disconnect_remote(SilcServer server,
3287 SilcSocketConnection sock,
3288 SilcStatus status, ...)
3291 unsigned char buf[512];
3299 if (SILC_IS_DISCONNECTING(sock)) {
3300 SILC_SET_DISCONNECTED(sock);
3301 silc_server_close_connection(server, sock);
3305 memset(buf, 0, sizeof(buf));
3306 va_start(ap, status);
3307 cp = va_arg(ap, char *);
3309 vsnprintf(buf, sizeof(buf) - 1, cp, ap);
3314 SILC_LOG_DEBUG(("Disconnecting remote host"));
3316 /* Notify remote end that the conversation is over. The notify message
3317 is tried to be sent immediately. */
3321 len += silc_utf8_encoded_len(buf, strlen(buf), SILC_STRING_ASCII);
3323 buffer = silc_buffer_alloc_size(len);
3327 buffer->data[0] = status;
3329 silc_utf8_encode(buf, strlen(buf), SILC_STRING_ASCII, buffer->data + 1,
3331 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
3332 buffer->data, buffer->len, TRUE);
3333 silc_buffer_free(buffer);
3336 silc_server_packet_queue_purge(server, sock);
3338 /* Mark the connection to be disconnected */
3339 SILC_SET_DISCONNECTING(sock);
3340 silc_server_close_connection(server, sock);
3343 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
3345 SilcServer server = app_context;
3346 SilcClientEntry client = context;
3348 assert(!silc_hash_table_count(client->channels));
3350 silc_idlist_del_data(client);
3351 silc_idcache_purge_by_context(server->local_list->clients, client);
3354 /* Frees client data and notifies about client's signoff. */
3356 void silc_server_free_client_data(SilcServer server,
3357 SilcSocketConnection sock,
3358 SilcClientEntry client,
3360 const char *signoff)
3362 SILC_LOG_DEBUG(("Freeing client data"));
3364 /* If there is pending outgoing data for the client then purge it
3365 to the network before removing the client entry. */
3366 silc_server_packet_queue_purge(server, sock);
3369 /* Check if anyone is watching this nickname */
3370 if (server->server_type == SILC_ROUTER)
3371 silc_server_check_watcher_list(server, client, NULL,
3372 SILC_NOTIFY_TYPE_SIGNOFF);
3374 /* Send SIGNOFF notify to routers. */
3376 silc_server_send_notify_signoff(server, SILC_PRIMARY_ROUTE(server),
3377 SILC_BROADCAST(server), client->id,
3381 /* Remove client from all channels */
3383 silc_server_remove_from_channels(server, NULL, client,
3384 TRUE, (char *)signoff, TRUE, FALSE);
3386 silc_server_remove_from_channels(server, NULL, client,
3387 FALSE, NULL, FALSE, FALSE);
3389 /* Remove this client from watcher list if it is */
3390 silc_server_del_from_watcher_list(server, client);
3392 /* Remove this client from the public key hash list */
3393 if (client->data.public_key)
3394 silc_hash_table_del_by_context(server->pk_hash,
3395 client->data.public_key, client);
3397 /* Update statistics */
3398 server->stat.my_clients--;
3399 server->stat.clients--;
3400 if (server->stat.cell_clients)
3401 server->stat.cell_clients--;
3402 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
3403 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
3404 silc_schedule_task_del_by_context(server->schedule, client);
3406 /* We will not delete the client entry right away. We will take it
3407 into history (for WHOWAS command) for 5 minutes, unless we're
3408 shutting down server. */
3409 if (!server->server_shutdown) {
3410 silc_schedule_task_add(server->schedule, 0,
3411 silc_server_free_client_data_timeout,
3413 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
3414 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
3415 client->data.status &= ~SILC_IDLIST_STATUS_LOCAL;
3417 client->router = NULL;
3418 client->connection = NULL;
3420 /* Delete directly since we're shutting down server */
3421 silc_idlist_del_data(client);
3422 silc_idlist_del_client(server->local_list, client);
3426 /* Frees user_data pointer from socket connection object. This also sends
3427 appropriate notify packets to the network to inform about leaving
3430 void silc_server_free_sock_user_data(SilcServer server,
3431 SilcSocketConnection sock,
3432 const char *signoff_message)
3435 /* If any protocol is active cancel its execution */
3436 if (sock->protocol && sock->protocol->protocol &&
3437 sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3438 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3439 silc_protocol_cancel(sock->protocol, server->schedule);
3440 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3441 silc_protocol_execute_final(sock->protocol, server->schedule);
3442 sock->protocol = NULL;
3443 if (!sock->user_data)
3447 switch (sock->type) {
3448 case SILC_SOCKET_TYPE_CLIENT:
3450 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
3451 silc_server_free_client_data(server, sock, user_data, TRUE,
3455 case SILC_SOCKET_TYPE_SERVER:
3456 case SILC_SOCKET_TYPE_ROUTER:
3458 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
3459 SilcServerEntry backup_router = NULL;
3461 SILC_LOG_DEBUG(("Freeing server data"));
3464 backup_router = silc_server_backup_get(server, user_data->id);
3466 if (!server->backup_router && server->server_type == SILC_ROUTER &&
3467 backup_router == server->id_entry &&
3468 sock->type != SILC_SOCKET_TYPE_ROUTER)
3469 backup_router = NULL;
3471 if (server->server_shutdown || server->backup_noswitch)
3472 backup_router = NULL;
3474 /* If this was our primary router connection then we're lost to
3475 the outside world. */
3476 if (server->router == user_data) {
3477 /* Check whether we have a backup router connection */
3478 if (!backup_router || backup_router == user_data) {
3479 if (!server->no_reconnect)
3480 silc_server_create_connections(server);
3481 server->id_entry->router = NULL;
3482 server->router = NULL;
3483 server->standalone = TRUE;
3484 server->backup_primary = FALSE;
3485 backup_router = NULL;
3487 if (server->id_entry != backup_router) {
3488 SILC_LOG_INFO(("New primary router is backup router %s",
3489 backup_router->server_name));
3490 server->id_entry->router = backup_router;
3491 server->router = backup_router;
3492 server->router_connect = time(0);
3493 server->backup_primary = TRUE;
3494 backup_router->data.status &= ~SILC_IDLIST_STATUS_DISABLED;
3496 /* Send START_USE to backup router to indicate we have switched */
3497 silc_server_backup_send_start_use(server,
3498 backup_router->connection,
3501 SILC_LOG_INFO(("We are now new primary router in this cell"));
3502 server->id_entry->router = NULL;
3503 server->router = NULL;
3504 server->standalone = TRUE;
3507 /* We stop here to take a breath */
3510 if (server->backup_router) {
3511 server->server_type = SILC_ROUTER;
3513 /* We'll need to constantly try to reconnect to the primary
3514 router so that we'll see when it comes back online. */
3515 silc_server_backup_reconnect(server, sock->ip, sock->port,
3516 silc_server_backup_connected,
3520 /* Mark this connection as replaced */
3521 silc_server_backup_replaced_add(server, user_data->id,
3524 } else if (backup_router) {
3525 SILC_LOG_INFO(("Enabling the use of backup router %s",
3526 backup_router->server_name));
3528 /* Mark this connection as replaced */
3529 silc_server_backup_replaced_add(server, user_data->id,
3531 } else if (server->server_type == SILC_SERVER &&
3532 sock->type == SILC_SOCKET_TYPE_ROUTER) {
3533 /* Reconnect to the router (backup) */
3534 if (!server->no_reconnect)
3535 silc_server_create_connections(server);
3538 if (user_data->server_name)
3539 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
3540 ("Server %s signoff", user_data->server_name));
3542 if (!backup_router) {
3543 /* Remove all servers that are originated from this server, and
3544 remove the clients of those servers too. */
3545 silc_server_remove_servers_by_server(server, user_data, TRUE);
3548 /* Remove the clients that this server owns as they will become
3549 invalid now too. For backup router the server is actually
3550 coming from the primary router, so mark that as the owner
3552 if (server->server_type == SILC_BACKUP_ROUTER &&
3553 sock->type == SILC_SOCKET_TYPE_SERVER)
3554 silc_server_remove_clients_by_server(server, server->router,
3558 silc_server_remove_clients_by_server(server, user_data,
3561 /* Remove channels owned by this server */
3562 if (server->server_type == SILC_SERVER)
3563 silc_server_remove_channels_by_server(server, user_data);
3565 /* Enable local server connections that may be disabled */
3566 silc_server_local_servers_toggle_enabled(server, TRUE);
3568 /* Update the client entries of this server to the new backup
3569 router. If we are the backup router we also resolve the real
3570 servers for the clients. After updating is over this also
3571 removes the clients that this server explicitly owns. */
3572 silc_server_update_clients_by_server(server, user_data,
3573 backup_router, TRUE);
3575 /* If we are router and just lost our primary router (now standlaone)
3576 we remove everything that was behind it, since we don't know
3578 if (server->server_type == SILC_ROUTER && server->standalone)
3579 /* Remove all servers that are originated from this server, and
3580 remove the clients of those servers too. */
3581 silc_server_remove_servers_by_server(server, user_data, TRUE);
3583 /* Finally remove the clients that are explicitly owned by this
3584 server. They go down with the server. */
3585 silc_server_remove_clients_by_server(server, user_data,
3588 /* Update our server cache to use the new backup router too. */
3589 silc_server_update_servers_by_server(server, user_data, backup_router);
3590 if (server->server_type == SILC_SERVER)
3591 silc_server_update_channels_by_server(server, user_data,
3594 /* Send notify about primary router going down to local operators */
3595 if (server->backup_router)
3596 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3597 SILC_NOTIFY_TYPE_NONE,
3598 ("%s switched to backup router %s "
3599 "(we are primary router now)",
3600 server->server_name, server->server_name));
3601 else if (server->router)
3602 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3603 SILC_NOTIFY_TYPE_NONE,
3604 ("%s switched to backup router %s",
3605 server->server_name,
3606 server->router->server_name));
3608 server->backup_noswitch = FALSE;
3610 /* Free the server entry */
3611 silc_server_backup_del(server, user_data);
3612 silc_server_backup_replaced_del(server, user_data);
3613 silc_idlist_del_data(user_data);
3614 if (!silc_idlist_del_server(server->local_list, user_data))
3615 silc_idlist_del_server(server->global_list, user_data);
3616 if (sock->type == SILC_SOCKET_TYPE_SERVER) {
3617 server->stat.my_servers--;
3618 server->stat.servers--;
3620 server->stat.my_routers--;
3621 server->stat.routers--;
3623 if (server->server_type == SILC_ROUTER)
3624 server->stat.cell_servers--;
3626 if (backup_router && backup_router != server->id_entry) {
3627 /* Announce all of our stuff that was created about 5 minutes ago.
3628 The backup router knows all the other stuff already. */
3629 if (server->server_type == SILC_ROUTER)
3630 silc_server_announce_servers(server, FALSE, time(0) - 300,
3631 backup_router->connection);
3633 /* Announce our clients and channels to the router */
3634 silc_server_announce_clients(server, time(0) - 300,
3635 backup_router->connection);
3636 silc_server_announce_channels(server, time(0) - 300,
3637 backup_router->connection);
3643 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
3645 SILC_LOG_DEBUG(("Freeing unknown connection data"));
3647 silc_idlist_del_data(user_data);
3648 silc_free(user_data);
3653 sock->user_data = NULL;
3656 /* Removes client from all channels it has joined. This is used when client
3657 connection is disconnected. If the client on a channel is last, the
3658 channel is removed as well. This sends the SIGNOFF notify types. */
3660 void silc_server_remove_from_channels(SilcServer server,
3661 SilcSocketConnection sock,
3662 SilcClientEntry client,
3664 const char *signoff_message,
3668 SilcChannelEntry channel;
3669 SilcChannelClientEntry chl;
3670 SilcHashTableList htl;
3671 SilcBuffer clidp = NULL;
3676 if (notify && !client->id)
3679 SILC_LOG_DEBUG(("Removing client %s from joined channels",
3680 notify ? silc_id_render(client->id, SILC_ID_CLIENT) : ""));
3683 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3688 /* Remove the client from all channels. The client is removed from
3689 the channels' user list. */
3690 silc_hash_table_list(client->channels, &htl);
3691 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3692 channel = chl->channel;
3694 /* Remove channel if this is last client leaving the channel, unless
3695 the channel is permanent. */
3696 if (server->server_type != SILC_SERVER &&
3697 silc_hash_table_count(channel->user_list) < 2) {
3698 silc_server_channel_delete(server, channel);
3702 silc_hash_table_del(client->channels, channel);
3703 silc_hash_table_del(channel->user_list, client);
3704 channel->user_count--;
3706 /* If there is no global users on the channel anymore mark the channel
3707 as local channel. Do not check if the removed client is local client. */
3708 if (server->server_type == SILC_SERVER && channel->global_users &&
3709 chl->client->router && !silc_server_channel_has_global(channel))
3710 channel->global_users = FALSE;
3712 memset(chl, 'A', sizeof(*chl));
3715 /* Update statistics */
3716 if (SILC_IS_LOCAL(client))
3717 server->stat.my_chanclients--;
3718 if (server->server_type == SILC_ROUTER) {
3719 server->stat.cell_chanclients--;
3720 server->stat.chanclients--;
3723 /* If there is not at least one local user on the channel then we don't
3724 need the channel entry anymore, we can remove it safely, unless the
3725 channel is permanent channel */
3726 if (server->server_type == SILC_SERVER &&
3727 !silc_server_channel_has_local(channel)) {
3728 /* Notify about leaving client if this channel has global users. */
3729 if (notify && channel->global_users)
3730 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3731 SILC_NOTIFY_TYPE_SIGNOFF,
3732 signoff_message ? 2 : 1,
3733 clidp->data, clidp->len,
3734 signoff_message, signoff_message ?
3735 strlen(signoff_message) : 0);
3737 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3738 silc_server_channel_delete(server, channel);
3742 /* Send notify to channel about client leaving SILC and channel too */
3744 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3745 SILC_NOTIFY_TYPE_SIGNOFF,
3746 signoff_message ? 2 : 1,
3747 clidp->data, clidp->len,
3748 signoff_message, signoff_message ?
3749 strlen(signoff_message) : 0);
3751 if (killed && clidp) {
3752 /* Remove the client from channel's invite list */
3753 if (channel->invite_list &&
3754 silc_hash_table_count(channel->invite_list)) {
3756 SilcArgumentPayload iargs;
3757 ab = silc_argument_payload_encode_one(NULL, clidp->data,
3759 iargs = silc_argument_payload_parse(ab->data, ab->len, 1);
3760 silc_server_inviteban_process(server, channel->invite_list, 1, iargs);
3761 silc_buffer_free(ab);
3762 silc_argument_payload_free(iargs);
3766 /* Don't create keys if we are shutting down */
3767 if (server->server_shutdown)
3770 /* Re-generate channel key if needed */
3771 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3772 if (!silc_server_create_channel_key(server, channel, 0))
3775 /* Send the channel key to the channel. The key of course is not sent
3776 to the client who was removed from the channel. */
3777 silc_server_send_channel_key(server, client->connection, channel,
3778 server->server_type == SILC_ROUTER ?
3779 FALSE : !server->standalone);
3783 silc_hash_table_list_reset(&htl);
3785 silc_buffer_free(clidp);
3788 /* Removes client from one channel. This is used for example when client
3789 calls LEAVE command to remove itself from the channel. Returns TRUE
3790 if channel still exists and FALSE if the channel is removed when
3791 last client leaves the channel. If `notify' is FALSE notify messages
3794 bool silc_server_remove_from_one_channel(SilcServer server,
3795 SilcSocketConnection sock,
3796 SilcChannelEntry channel,
3797 SilcClientEntry client,
3800 SilcChannelClientEntry chl;
3803 SILC_LOG_DEBUG(("Removing %s from channel %s",
3804 silc_id_render(client->id, SILC_ID_CLIENT),
3805 channel->channel_name));
3807 /* Get the entry to the channel, if this client is not on the channel
3809 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
3812 /* Remove channel if this is last client leaving the channel, unless
3813 the channel is permanent. */
3814 if (server->server_type != SILC_SERVER &&
3815 silc_hash_table_count(channel->user_list) < 2) {
3816 silc_server_channel_delete(server, channel);
3820 silc_hash_table_del(client->channels, channel);
3821 silc_hash_table_del(channel->user_list, client);
3822 channel->user_count--;
3824 /* If there is no global users on the channel anymore mark the channel
3825 as local channel. Do not check if the client is local client. */
3826 if (server->server_type == SILC_SERVER && channel->global_users &&
3827 chl->client->router && !silc_server_channel_has_global(channel))
3828 channel->global_users = FALSE;
3830 memset(chl, 'O', sizeof(*chl));
3833 /* Update statistics */
3834 if (SILC_IS_LOCAL(client))
3835 server->stat.my_chanclients--;
3836 if (server->server_type == SILC_ROUTER) {
3837 server->stat.cell_chanclients--;
3838 server->stat.chanclients--;
3841 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3845 /* If there is not at least one local user on the channel then we don't
3846 need the channel entry anymore, we can remove it safely, unless the
3847 channel is permanent channel */
3848 if (server->server_type == SILC_SERVER &&
3849 !silc_server_channel_has_local(channel)) {
3850 /* Notify about leaving client if this channel has global users. */
3851 if (notify && channel->global_users)
3852 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3853 SILC_NOTIFY_TYPE_LEAVE, 1,
3854 clidp->data, clidp->len);
3856 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3857 silc_server_channel_delete(server, channel);
3858 silc_buffer_free(clidp);
3862 /* Send notify to channel about client leaving the channel */
3864 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3865 SILC_NOTIFY_TYPE_LEAVE, 1,
3866 clidp->data, clidp->len);
3868 silc_buffer_free(clidp);
3872 /* Timeout callback. This is called if connection is idle or for some
3873 other reason is not responding within some period of time. This
3874 disconnects the remote end. */
3876 SILC_TASK_CALLBACK(silc_server_timeout_remote)
3878 SilcServer server = (SilcServer)context;
3879 SilcSocketConnection sock = server->sockets[fd];
3880 SilcProtocolType protocol = 0;
3882 SILC_LOG_DEBUG(("Start"));
3887 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
3888 sock->hostname, sock->ip));
3890 /* If we have protocol active we must assure that we call the protocol's
3891 final callback so that all the memory is freed. */
3892 if (sock->protocol && sock->protocol->protocol &&
3893 sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3894 protocol = sock->protocol->protocol->type;
3895 silc_protocol_cancel(sock->protocol, server->schedule);
3896 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3897 silc_protocol_execute_final(sock->protocol, server->schedule);
3898 sock->protocol = NULL;
3902 silc_server_disconnect_remote(server, sock,
3904 SILC_PROTOCOL_SERVER_CONNECTION_AUTH ?
3905 SILC_STATUS_ERR_AUTH_FAILED :
3906 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
3907 "Connection timeout");
3909 if (sock->user_data)
3910 silc_server_free_sock_user_data(server, sock, NULL);
3913 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
3914 function may be used only by router. In real SILC network all channels
3915 are created by routers thus this function is never used by normal
3918 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3919 SilcServerID *router_id,
3925 SilcChannelID *channel_id;
3926 SilcChannelEntry entry;
3930 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3933 cipher = SILC_DEFAULT_CIPHER;
3935 hmac = SILC_DEFAULT_HMAC;
3937 /* Allocate cipher */
3938 if (!silc_cipher_alloc(cipher, &key))
3942 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3943 silc_cipher_free(key);
3947 channel_name = strdup(channel_name);
3949 /* Create the channel ID */
3950 if (!silc_id_create_channel_id(server, router_id, server->rng,
3952 silc_free(channel_name);
3953 silc_cipher_free(key);
3954 silc_hmac_free(newhmac);
3958 /* Create the channel */
3959 entry = silc_idlist_add_channel(server->local_list, channel_name,
3960 SILC_CHANNEL_MODE_NONE, channel_id,
3961 NULL, key, newhmac, 0);
3963 silc_free(channel_name);
3964 silc_cipher_free(key);
3965 silc_hmac_free(newhmac);
3966 silc_free(channel_id);
3970 entry->cipher = strdup(cipher);
3971 entry->hmac_name = strdup(hmac);
3973 /* Now create the actual key material */
3974 if (!silc_server_create_channel_key(server, entry,
3975 silc_cipher_get_key_len(key) / 8)) {
3976 silc_idlist_del_channel(server->local_list, entry);
3980 /* Notify other routers about the new channel. We send the packet
3981 to our primary route. */
3983 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3984 channel_name, entry->id,
3985 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3988 /* Distribute to backup routers */
3989 if (broadcast && server->server_type == SILC_ROUTER) {
3992 SilcUInt32 name_len = strlen(channel_name);
3993 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3994 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3996 packet = silc_channel_payload_encode(channel_name, name_len,
3997 cid, channel_id_len, entry->mode);
3998 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3999 packet->data, packet->len, FALSE, TRUE);
4001 silc_buffer_free(packet);
4004 server->stat.my_channels++;
4005 if (server->server_type == SILC_ROUTER) {
4006 server->stat.channels++;
4007 server->stat.cell_channels++;
4008 entry->users_resolved = TRUE;
4014 /* Same as above but creates the channel with Channel ID `channel_id. */
4017 silc_server_create_new_channel_with_id(SilcServer server,
4021 SilcChannelID *channel_id,
4024 SilcChannelEntry entry;
4028 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
4031 cipher = SILC_DEFAULT_CIPHER;
4033 hmac = SILC_DEFAULT_HMAC;
4035 /* Allocate cipher */
4036 if (!silc_cipher_alloc(cipher, &key))
4040 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
4041 silc_cipher_free(key);
4045 channel_name = strdup(channel_name);
4047 /* Create the channel */
4048 entry = silc_idlist_add_channel(server->local_list, channel_name,
4049 SILC_CHANNEL_MODE_NONE, channel_id,
4050 NULL, key, newhmac, 0);
4052 silc_cipher_free(key);
4053 silc_hmac_free(newhmac);
4054 silc_free(channel_name);
4058 /* Now create the actual key material */
4059 if (!silc_server_create_channel_key(server, entry,
4060 silc_cipher_get_key_len(key) / 8)) {
4061 silc_idlist_del_channel(server->local_list, entry);
4065 /* Notify other routers about the new channel. We send the packet
4066 to our primary route. */
4068 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
4069 channel_name, entry->id,
4070 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
4073 /* Distribute to backup routers */
4074 if (broadcast && server->server_type == SILC_ROUTER) {
4077 SilcUInt32 name_len = strlen(channel_name);
4078 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
4079 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
4081 packet = silc_channel_payload_encode(channel_name, name_len,
4082 cid, channel_id_len, entry->mode);
4083 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
4084 packet->data, packet->len, FALSE, TRUE);
4086 silc_buffer_free(packet);
4089 server->stat.my_channels++;
4090 if (server->server_type == SILC_ROUTER) {
4091 server->stat.channels++;
4092 server->stat.cell_channels++;
4093 entry->users_resolved = TRUE;
4099 /* Channel's key re-key timeout callback. */
4101 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
4103 SilcServer server = app_context;
4104 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
4108 /* Return now if we are shutting down */
4109 if (server->server_shutdown)
4112 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
4115 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
4118 /* Generates new channel key. This is used to create the initial channel key
4119 but also to re-generate new key for channel. If `key_len' is provided
4120 it is the bytes of the key length. */
4122 bool silc_server_create_channel_key(SilcServer server,
4123 SilcChannelEntry channel,
4127 unsigned char channel_key[32], hash[32];
4130 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
4131 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
4135 SILC_LOG_DEBUG(("Generating channel %s key", channel->channel_name));
4137 if (!channel->channel_key)
4138 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
4139 channel->channel_key = NULL;
4145 else if (channel->key_len)
4146 len = channel->key_len / 8;
4148 len = silc_cipher_get_key_len(channel->channel_key) / 8;
4150 /* Create channel key */
4151 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
4154 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
4156 /* Remove old key if exists */
4158 memset(channel->key, 0, channel->key_len / 8);
4159 silc_free(channel->key);
4163 channel->key_len = len * 8;
4164 channel->key = silc_memdup(channel_key, len);
4165 memset(channel_key, 0, sizeof(channel_key));
4167 /* Generate HMAC key from the channel key data and set it */
4169 if (!silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac)) {
4170 memset(channel->key, 0, channel->key_len / 8);
4171 silc_free(channel->key);
4172 channel->channel_key = NULL;
4175 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
4176 silc_hmac_set_key(channel->hmac, hash,
4177 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
4178 memset(hash, 0, sizeof(hash));
4180 if (server->server_type == SILC_ROUTER) {
4181 if (!channel->rekey)
4182 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
4183 channel->rekey->channel = channel;
4184 channel->rekey->key_len = key_len;
4185 if (channel->rekey->task)
4186 silc_schedule_task_del(server->schedule, channel->rekey->task);
4188 channel->rekey->task =
4189 silc_schedule_task_add(server->schedule, 0,
4190 silc_server_channel_key_rekey,
4191 (void *)channel->rekey,
4192 server->config->channel_rekey_secs, 0,
4194 SILC_TASK_PRI_NORMAL);
4200 /* Saves the channel key found in the encoded `key_payload' buffer. This
4201 function is used when we receive Channel Key Payload and also when we're
4202 processing JOIN command reply. Returns entry to the channel. */
4204 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
4205 SilcBuffer key_payload,
4206 SilcChannelEntry channel)
4208 SilcChannelKeyPayload payload = NULL;
4209 SilcChannelID *id = NULL;
4210 unsigned char *tmp, hash[32];
4214 /* Decode channel key payload */
4215 payload = silc_channel_key_payload_parse(key_payload->data,
4218 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
4223 /* Get the channel entry */
4226 /* Get channel ID */
4227 tmp = silc_channel_key_get_id(payload, &tmp_len);
4228 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
4234 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
4236 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
4238 if (server->server_type == SILC_ROUTER)
4239 SILC_LOG_ERROR(("Received key for non-existent channel %s",
4240 silc_id_render(id, SILC_ID_CHANNEL)));
4246 SILC_LOG_DEBUG(("Saving new channel %s key", channel->channel_name));
4248 tmp = silc_channel_key_get_key(payload, &tmp_len);
4254 cipher = silc_channel_key_get_cipher(payload, NULL);
4260 /* Remove old key if exists */
4262 memset(channel->key, 0, channel->key_len / 8);
4263 silc_free(channel->key);
4264 silc_cipher_free(channel->channel_key);
4267 /* Create new cipher */
4268 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
4269 channel->channel_key = NULL;
4274 if (channel->cipher)
4275 silc_free(channel->cipher);
4276 channel->cipher = strdup(cipher);
4279 channel->key_len = tmp_len * 8;
4280 channel->key = silc_memdup(tmp, tmp_len);
4281 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
4283 /* Generate HMAC key from the channel key data and set it */
4285 if (!silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac)) {
4286 memset(channel->key, 0, channel->key_len / 8);
4287 silc_free(channel->key);
4288 channel->channel_key = NULL;
4291 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
4292 silc_hmac_set_key(channel->hmac, hash,
4293 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
4295 memset(hash, 0, sizeof(hash));
4296 memset(tmp, 0, tmp_len);
4298 if (server->server_type == SILC_ROUTER) {
4299 if (!channel->rekey)
4300 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
4301 channel->rekey->channel = channel;
4302 if (channel->rekey->task)
4303 silc_schedule_task_del(server->schedule, channel->rekey->task);
4305 channel->rekey->task =
4306 silc_schedule_task_add(server->schedule, 0,
4307 silc_server_channel_key_rekey,
4308 (void *)channel->rekey,
4309 server->config->channel_rekey_secs, 0,
4311 SILC_TASK_PRI_NORMAL);
4317 silc_channel_key_payload_free(payload);
4322 /* Heartbeat callback. This function is set as argument for the
4323 silc_socket_set_heartbeat function. The library will call this function
4324 at the set time interval. */
4326 void silc_server_perform_heartbeat(SilcSocketConnection sock,
4329 SilcServer server = hb_context;
4331 SILC_LOG_DEBUG(("Sending heartbeat to %s:%d (%s)", sock->hostname,
4332 sock->port, sock->ip));
4334 /* Send the heartbeat */
4335 silc_server_send_heartbeat(server, sock);
4338 /* Returns assembled of all servers in the given ID list. The packet's
4339 form is dictated by the New ID payload. */
4341 static void silc_server_announce_get_servers(SilcServer server,
4342 SilcServerEntry remote,
4344 SilcBuffer *servers,
4345 unsigned long creation_time)
4347 SilcIDCacheList list;
4348 SilcIDCacheEntry id_cache;
4349 SilcServerEntry entry;
4352 /* Go through all clients in the list */
4353 if (silc_idcache_get_all(id_list->servers, &list)) {
4354 if (silc_idcache_list_first(list, &id_cache)) {
4356 entry = (SilcServerEntry)id_cache->context;
4358 /* Do not announce the one we've sending our announcements and
4359 do not announce ourself. Also check the creation time if it's
4361 if ((entry == remote) || (entry == server->id_entry) ||
4362 (creation_time && entry->data.created < creation_time)) {
4363 if (!silc_idcache_list_next(list, &id_cache))
4368 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
4370 *servers = silc_buffer_realloc(*servers,
4372 (*servers)->truelen + idp->len :
4374 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
4375 silc_buffer_put(*servers, idp->data, idp->len);
4376 silc_buffer_pull(*servers, idp->len);
4377 silc_buffer_free(idp);
4379 if (!silc_idcache_list_next(list, &id_cache))
4384 silc_idcache_list_free(list);
4389 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
4395 p = silc_notify_payload_encode(notify, argc, ap);
4401 /* This function is used by router to announce existing servers to our
4402 primary router when we've connected to it. If `creation_time' is non-zero
4403 then only the servers that has been created after the `creation_time'
4404 will be announced. */
4406 void silc_server_announce_servers(SilcServer server, bool global,
4407 unsigned long creation_time,
4408 SilcSocketConnection remote)
4410 SilcBuffer servers = NULL;
4412 SILC_LOG_DEBUG(("Announcing servers"));
4414 /* Get servers in local list */
4415 silc_server_announce_get_servers(server, remote->user_data,
4416 server->local_list, &servers,
4420 /* Get servers in global list */
4421 silc_server_announce_get_servers(server, remote->user_data,
4422 server->global_list, &servers,
4426 silc_buffer_push(servers, servers->data - servers->head);
4427 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
4429 /* Send the packet */
4430 silc_server_packet_send(server, remote,
4431 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4432 servers->data, servers->len, TRUE);
4434 silc_buffer_free(servers);
4438 /* Returns assembled packet of all clients in the given ID list. The
4439 packet's form is dictated by the New ID Payload. */
4441 static void silc_server_announce_get_clients(SilcServer server,
4443 SilcBuffer *clients,
4445 unsigned long creation_time)
4447 SilcIDCacheList list;
4448 SilcIDCacheEntry id_cache;
4449 SilcClientEntry client;
4452 unsigned char mode[4];
4454 /* Go through all clients in the list */
4455 if (silc_idcache_get_all(id_list->clients, &list)) {
4456 if (silc_idcache_list_first(list, &id_cache)) {
4458 client = (SilcClientEntry)id_cache->context;
4460 if (creation_time && client->data.created < creation_time) {
4461 if (!silc_idcache_list_next(list, &id_cache))
4465 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
4466 if (!silc_idcache_list_next(list, &id_cache))
4470 if (!client->connection && !client->router) {
4471 if (!silc_idcache_list_next(list, &id_cache))
4476 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
4478 *clients = silc_buffer_realloc(*clients,
4480 (*clients)->truelen + idp->len :
4482 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
4483 silc_buffer_put(*clients, idp->data, idp->len);
4484 silc_buffer_pull(*clients, idp->len);
4486 SILC_PUT32_MSB(client->mode, mode);
4488 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
4489 2, idp->data, idp->len,
4491 *umodes = silc_buffer_realloc(*umodes,
4493 (*umodes)->truelen + tmp->len :
4495 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
4496 silc_buffer_put(*umodes, tmp->data, tmp->len);
4497 silc_buffer_pull(*umodes, tmp->len);
4498 silc_buffer_free(tmp);
4500 silc_buffer_free(idp);
4502 if (!silc_idcache_list_next(list, &id_cache))
4507 silc_idcache_list_free(list);
4511 /* This function is used to announce our existing clients to our router
4512 when we've connected to it. If `creation_time' is non-zero then only
4513 the clients that has been created after the `creation_time' will be
4516 void silc_server_announce_clients(SilcServer server,
4517 unsigned long creation_time,
4518 SilcSocketConnection remote)
4520 SilcBuffer clients = NULL;
4521 SilcBuffer umodes = NULL;
4523 SILC_LOG_DEBUG(("Announcing clients"));
4525 /* Get clients in local list */
4526 silc_server_announce_get_clients(server, server->local_list,
4527 &clients, &umodes, creation_time);
4529 /* As router we announce our global list as well */
4530 if (server->server_type == SILC_ROUTER)
4531 silc_server_announce_get_clients(server, server->global_list,
4532 &clients, &umodes, creation_time);
4535 silc_buffer_push(clients, clients->data - clients->head);
4536 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
4538 /* Send the packet */
4539 silc_server_packet_send(server, remote,
4540 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4541 clients->data, clients->len, TRUE);
4543 silc_buffer_free(clients);
4547 silc_buffer_push(umodes, umodes->data - umodes->head);
4548 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
4550 /* Send the packet */
4551 silc_server_packet_send(server, remote,
4552 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4553 umodes->data, umodes->len, TRUE);
4555 silc_buffer_free(umodes);
4559 /* Returns channel's topic for announcing it */
4561 void silc_server_announce_get_channel_topic(SilcServer server,
4562 SilcChannelEntry channel,
4567 if (channel->topic) {
4568 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4569 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
4570 chidp->data, chidp->len,
4572 strlen(channel->topic));
4573 silc_buffer_free(chidp);
4577 /* Returns channel's invite and ban lists */
4579 void silc_server_announce_get_inviteban(SilcServer server,
4580 SilcChannelEntry channel,
4584 SilcBuffer list, idp, idp2, tmp2;
4586 SilcHashTableList htl;
4587 const unsigned char a[1] = { 0x03 };
4589 idp = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
4591 /* Encode invite list */
4592 if (channel->invite_list && silc_hash_table_count(channel->invite_list)) {
4593 list = silc_buffer_alloc_size(2);
4594 type = silc_hash_table_count(channel->invite_list);
4595 SILC_PUT16_MSB(type, list->data);
4596 silc_hash_table_list(channel->invite_list, &htl);
4597 while (silc_hash_table_get(&htl, (void *)&type, (void *)&tmp2))
4598 list = silc_argument_payload_encode_one(list, tmp2->data, tmp2->len,
4600 silc_hash_table_list_reset(&htl);
4602 idp2 = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4604 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_INVITE, 5,
4605 idp->data, idp->len,
4606 channel->channel_name,
4607 strlen(channel->channel_name),
4608 idp2->data, idp2->len,
4610 list->data, list->len);
4611 silc_buffer_free(idp2);
4612 silc_buffer_free(list);
4615 /* Encode ban list */
4616 if (channel->ban_list && silc_hash_table_count(channel->ban_list)) {
4617 list = silc_buffer_alloc_size(2);
4618 type = silc_hash_table_count(channel->ban_list);
4619 SILC_PUT16_MSB(type, list->data);
4620 silc_hash_table_list(channel->ban_list, &htl);
4621 while (silc_hash_table_get(&htl, (void *)&type, (void *)&tmp2))
4622 list = silc_argument_payload_encode_one(list, tmp2->data, tmp2->len,
4624 silc_hash_table_list_reset(&htl);
4627 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_BAN, 3,
4628 idp->data, idp->len,
4630 list->data, list->len);
4631 silc_buffer_free(list);
4634 silc_buffer_free(idp);
4637 /* Returns assembled packets for channel users of the `channel'. */
4639 void silc_server_announce_get_channel_users(SilcServer server,
4640 SilcChannelEntry channel,
4641 SilcBuffer *channel_modes,
4642 SilcBuffer *channel_users,
4643 SilcBuffer *channel_users_modes)
4645 SilcChannelClientEntry chl;
4646 SilcHashTableList htl;
4647 SilcBuffer chidp, clidp, csidp;
4648 SilcBuffer tmp, fkey = NULL, chpklist;
4650 unsigned char mode[4], ulimit[4];
4653 SILC_LOG_DEBUG(("Start"));
4655 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4656 csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4657 chpklist = silc_server_get_channel_pk_list(server, channel, TRUE, FALSE);
4660 SILC_PUT32_MSB(channel->mode, mode);
4661 if (channel->mode & SILC_CHANNEL_MODE_ULIMIT)
4662 SILC_PUT32_MSB(channel->user_limit, ulimit);
4663 hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
4664 if (channel->founder_key)
4665 fkey = silc_pkcs_public_key_payload_encode(channel->founder_key);
4667 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
4668 8, csidp->data, csidp->len,
4671 hmac, hmac ? strlen(hmac) : 0,
4672 channel->passphrase,
4673 channel->passphrase ?
4674 strlen(channel->passphrase) : 0,
4675 fkey ? fkey->data : NULL,
4676 fkey ? fkey->len : 0,
4677 chpklist ? chpklist->data : NULL,
4678 chpklist ? chpklist->len : 0,
4680 SILC_CHANNEL_MODE_ULIMIT ?
4683 SILC_CHANNEL_MODE_ULIMIT ?
4684 sizeof(ulimit) : 0));
4687 silc_buffer_realloc(*channel_modes,
4689 (*channel_modes)->truelen + len : len));
4690 silc_buffer_pull_tail(*channel_modes,
4691 ((*channel_modes)->end -
4692 (*channel_modes)->data));
4693 silc_buffer_put(*channel_modes, tmp->data, tmp->len);
4694 silc_buffer_pull(*channel_modes, len);
4695 silc_buffer_free(tmp);
4696 silc_buffer_free(fkey);
4699 /* Now find all users on the channel */
4700 silc_hash_table_list(channel->user_list, &htl);
4701 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4702 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4705 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
4706 clidp->data, clidp->len,
4707 chidp->data, chidp->len);
4710 silc_buffer_realloc(*channel_users,
4712 (*channel_users)->truelen + len : len));
4713 silc_buffer_pull_tail(*channel_users,
4714 ((*channel_users)->end -
4715 (*channel_users)->data));
4717 silc_buffer_put(*channel_users, tmp->data, tmp->len);
4718 silc_buffer_pull(*channel_users, len);
4719 silc_buffer_free(tmp);
4721 /* CUMODE notify for mode change on the channel */
4722 SILC_PUT32_MSB(chl->mode, mode);
4723 if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
4724 fkey = silc_pkcs_public_key_payload_encode(channel->founder_key);
4725 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
4726 4, csidp->data, csidp->len,
4728 clidp->data, clidp->len,
4729 fkey ? fkey->data : NULL,
4730 fkey ? fkey->len : 0);
4732 *channel_users_modes =
4733 silc_buffer_realloc(*channel_users_modes,
4734 (*channel_users_modes ?
4735 (*channel_users_modes)->truelen + len : len));
4736 silc_buffer_pull_tail(*channel_users_modes,
4737 ((*channel_users_modes)->end -
4738 (*channel_users_modes)->data));
4740 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
4741 silc_buffer_pull(*channel_users_modes, len);
4742 silc_buffer_free(tmp);
4743 silc_buffer_free(fkey);
4745 silc_buffer_free(clidp);
4747 silc_hash_table_list_reset(&htl);
4748 silc_buffer_free(chidp);
4749 silc_buffer_free(csidp);
4752 /* Returns assembled packets for all channels and users on those channels
4753 from the given ID List. The packets are in the form dictated by the
4754 New Channel and New Channel User payloads. */
4756 void silc_server_announce_get_channels(SilcServer server,
4758 SilcBuffer *channels,
4759 SilcBuffer **channel_modes,
4760 SilcBuffer *channel_users,
4761 SilcBuffer **channel_users_modes,
4762 SilcUInt32 *channel_users_modes_c,
4763 SilcBuffer **channel_topics,
4764 SilcBuffer **channel_invites,
4765 SilcBuffer **channel_bans,
4766 SilcChannelID ***channel_ids,
4767 unsigned long creation_time)
4769 SilcIDCacheList list;
4770 SilcIDCacheEntry id_cache;
4771 SilcChannelEntry channel;
4774 SilcUInt16 name_len;
4776 int i = *channel_users_modes_c;
4779 SILC_LOG_DEBUG(("Start"));
4781 /* Go through all channels in the list */
4782 if (silc_idcache_get_all(id_list->channels, &list)) {
4783 if (silc_idcache_list_first(list, &id_cache)) {
4785 channel = (SilcChannelEntry)id_cache->context;
4787 if (creation_time && channel->created < creation_time)
4792 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4793 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4794 name_len = strlen(channel->channel_name);
4797 len = 4 + name_len + id_len + 4;
4799 silc_buffer_realloc(*channels,
4800 (*channels ? (*channels)->truelen +
4802 silc_buffer_pull_tail(*channels,
4803 ((*channels)->end - (*channels)->data));
4804 silc_buffer_format(*channels,
4805 SILC_STR_UI_SHORT(name_len),
4806 SILC_STR_UI_XNSTRING(channel->channel_name,
4808 SILC_STR_UI_SHORT(id_len),
4809 SILC_STR_UI_XNSTRING(cid, id_len),
4810 SILC_STR_UI_INT(channel->mode),
4812 silc_buffer_pull(*channels, len);
4815 if (creation_time && channel->updated < creation_time)
4821 /* Channel user modes */
4822 *channel_users_modes = silc_realloc(*channel_users_modes,
4823 sizeof(**channel_users_modes) *
4825 (*channel_users_modes)[i] = NULL;
4826 *channel_modes = silc_realloc(*channel_modes,
4827 sizeof(**channel_modes) * (i + 1));
4828 (*channel_modes)[i] = NULL;
4829 *channel_ids = silc_realloc(*channel_ids,
4830 sizeof(**channel_ids) * (i + 1));
4831 (*channel_ids)[i] = NULL;
4832 silc_server_announce_get_channel_users(server, channel,
4833 &(*channel_modes)[i],
4835 &(*channel_users_modes)[i]);
4836 (*channel_ids)[i] = channel->id;
4838 /* Channel's topic */
4839 *channel_topics = silc_realloc(*channel_topics,
4840 sizeof(**channel_topics) * (i + 1));
4841 (*channel_topics)[i] = NULL;
4842 silc_server_announce_get_channel_topic(server, channel,
4843 &(*channel_topics)[i]);
4845 /* Channel's invite and ban list */
4846 *channel_invites = silc_realloc(*channel_invites,
4847 sizeof(**channel_invites) * (i + 1));
4848 (*channel_invites)[i] = NULL;
4849 *channel_bans = silc_realloc(*channel_bans,
4850 sizeof(**channel_bans) * (i + 1));
4851 (*channel_bans)[i] = NULL;
4852 silc_server_announce_get_inviteban(server, channel,
4853 &(*channel_invites)[i],
4854 &(*channel_bans)[i]);
4856 (*channel_users_modes_c)++;
4862 if (!silc_idcache_list_next(list, &id_cache))
4867 silc_idcache_list_free(list);
4871 /* This function is used to announce our existing channels to our router
4872 when we've connected to it. This also announces the users on the
4873 channels to the router. If the `creation_time' is non-zero only the
4874 channels that was created after the `creation_time' are announced.
4875 Note that the channel users are still announced even if the `creation_time'
4878 void silc_server_announce_channels(SilcServer server,
4879 unsigned long creation_time,
4880 SilcSocketConnection remote)
4882 SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
4883 SilcBuffer *channel_users_modes = NULL;
4884 SilcBuffer *channel_topics = NULL;
4885 SilcBuffer *channel_invites = NULL;
4886 SilcBuffer *channel_bans = NULL;
4887 SilcUInt32 channel_users_modes_c = 0;
4888 SilcChannelID **channel_ids = NULL;
4890 SILC_LOG_DEBUG(("Announcing channels and channel users"));
4892 /* Get channels and channel users in local list */
4893 silc_server_announce_get_channels(server, server->local_list,
4894 &channels, &channel_modes,
4896 &channel_users_modes,
4897 &channel_users_modes_c,
4901 &channel_ids, creation_time);
4903 /* Get channels and channel users in global list */
4904 if (server->server_type != SILC_SERVER)
4905 silc_server_announce_get_channels(server, server->global_list,
4906 &channels, &channel_modes,
4908 &channel_users_modes,
4909 &channel_users_modes_c,
4913 &channel_ids, creation_time);
4916 silc_buffer_push(channels, channels->data - channels->head);
4917 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
4919 /* Send the packet */
4920 silc_server_packet_send(server, remote,
4921 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
4922 channels->data, channels->len,
4925 silc_buffer_free(channels);
4928 if (channel_users) {
4929 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
4930 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
4931 channel_users->len);
4933 /* Send the packet */
4934 silc_server_packet_send(server, remote,
4935 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4936 channel_users->data, channel_users->len,
4939 silc_buffer_free(channel_users);
4942 if (channel_modes) {
4945 for (i = 0; i < channel_users_modes_c; i++) {
4946 if (!channel_modes[i])
4948 silc_buffer_push(channel_modes[i],
4949 channel_modes[i]->data -
4950 channel_modes[i]->head);
4951 SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
4952 channel_modes[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_modes[i]->data,
4957 channel_modes[i]->len,
4959 silc_buffer_free(channel_modes[i]);
4961 silc_free(channel_modes);
4964 if (channel_users_modes) {
4967 for (i = 0; i < channel_users_modes_c; i++) {
4968 if (!channel_users_modes[i])
4970 silc_buffer_push(channel_users_modes[i],
4971 channel_users_modes[i]->data -
4972 channel_users_modes[i]->head);
4973 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
4974 channel_users_modes[i]->len);
4975 silc_server_packet_send_dest(server, remote,
4976 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4977 channel_ids[i], SILC_ID_CHANNEL,
4978 channel_users_modes[i]->data,
4979 channel_users_modes[i]->len,
4981 silc_buffer_free(channel_users_modes[i]);
4983 silc_free(channel_users_modes);
4986 if (channel_topics) {
4989 for (i = 0; i < channel_users_modes_c; i++) {
4990 if (!channel_topics[i])
4993 silc_buffer_push(channel_topics[i],
4994 channel_topics[i]->data -
4995 channel_topics[i]->head);
4996 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
4997 channel_topics[i]->len);
4998 silc_server_packet_send_dest(server, remote,
4999 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
5000 channel_ids[i], SILC_ID_CHANNEL,
5001 channel_topics[i]->data,
5002 channel_topics[i]->len,
5004 silc_buffer_free(channel_topics[i]);
5006 silc_free(channel_topics);
5009 if (channel_invites) {
5012 for (i = 0; i < channel_users_modes_c; i++) {
5013 if (!channel_invites[i])
5016 silc_buffer_push(channel_invites[i],
5017 channel_invites[i]->data -
5018 channel_invites[i]->head);
5019 SILC_LOG_HEXDUMP(("channel invite list"), channel_invites[i]->data,
5020 channel_invites[i]->len);
5021 silc_server_packet_send_dest(server, remote,
5022 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
5023 channel_ids[i], SILC_ID_CHANNEL,
5024 channel_invites[i]->data,
5025 channel_invites[i]->len,
5027 silc_buffer_free(channel_invites[i]);
5029 silc_free(channel_invites);
5035 for (i = 0; i < channel_users_modes_c; i++) {
5036 if (!channel_bans[i])
5039 silc_buffer_push(channel_bans[i],
5040 channel_bans[i]->data -
5041 channel_bans[i]->head);
5042 SILC_LOG_HEXDUMP(("channel ban list"), channel_bans[i]->data,
5043 channel_bans[i]->len);
5044 silc_server_packet_send_dest(server, remote,
5045 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
5046 channel_ids[i], SILC_ID_CHANNEL,
5047 channel_bans[i]->data,
5048 channel_bans[i]->len,
5050 silc_buffer_free(channel_bans[i]);
5052 silc_free(channel_bans);
5055 silc_free(channel_ids);
5058 /* Assembles user list and users mode list from the `channel'. */
5060 bool silc_server_get_users_on_channel(SilcServer server,
5061 SilcChannelEntry channel,
5062 SilcBuffer *user_list,
5063 SilcBuffer *mode_list,
5064 SilcUInt32 *user_count)
5066 SilcChannelClientEntry chl;
5067 SilcHashTableList htl;
5068 SilcBuffer client_id_list;
5069 SilcBuffer client_mode_list;
5071 SilcUInt32 list_count = 0, len = 0;
5073 if (!silc_hash_table_count(channel->user_list))
5076 silc_hash_table_list(channel->user_list, &htl);
5077 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
5078 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
5079 silc_hash_table_list_reset(&htl);
5081 client_id_list = silc_buffer_alloc(len);
5083 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
5084 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
5085 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
5087 silc_hash_table_list(channel->user_list, &htl);
5088 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5090 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
5091 silc_buffer_put(client_id_list, idp->data, idp->len);
5092 silc_buffer_pull(client_id_list, idp->len);
5093 silc_buffer_free(idp);
5095 /* Client's mode on channel */
5096 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
5097 silc_buffer_pull(client_mode_list, 4);
5101 silc_hash_table_list_reset(&htl);
5102 silc_buffer_push(client_id_list,
5103 client_id_list->data - client_id_list->head);
5104 silc_buffer_push(client_mode_list,
5105 client_mode_list->data - client_mode_list->head);
5107 *user_list = client_id_list;
5108 *mode_list = client_mode_list;
5109 *user_count = list_count;
5113 /* Saves users and their modes to the `channel'. */
5115 void silc_server_save_users_on_channel(SilcServer server,
5116 SilcSocketConnection sock,
5117 SilcChannelEntry channel,
5118 SilcClientID *noadd,
5119 SilcBuffer user_list,
5120 SilcBuffer mode_list,
5121 SilcUInt32 user_count)
5126 SilcClientID *client_id;
5127 SilcClientEntry client;
5128 SilcIDCacheEntry cache;
5129 SilcChannelClientEntry chl;
5131 SILC_LOG_DEBUG(("Saving %d users on %s channel", user_count,
5132 channel->channel_name));
5134 for (i = 0; i < user_count; i++) {
5136 SILC_GET16_MSB(idp_len, user_list->data + 2);
5138 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
5139 silc_buffer_pull(user_list, idp_len);
5144 SILC_GET32_MSB(mode, mode_list->data);
5145 silc_buffer_pull(mode_list, 4);
5147 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
5148 silc_free(client_id);
5154 /* Check if we have this client cached already. */
5155 client = silc_idlist_find_client_by_id(server->local_list, client_id,
5156 server->server_type, &cache);
5158 client = silc_idlist_find_client_by_id(server->global_list,
5159 client_id, server->server_type,
5162 /* If router did not find such Client ID in its lists then this must
5163 be bogus client or some router in the net is buggy. */
5164 if (server->server_type != SILC_SERVER) {
5165 silc_free(client_id);
5169 /* We don't have that client anywhere, add it. The client is added
5170 to global list since server didn't have it in the lists so it must be
5172 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
5173 silc_id_dup(client_id, SILC_ID_CLIENT),
5174 sock->user_data, NULL, 0);
5176 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
5177 silc_free(client_id);
5181 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
5186 silc_free(client_id);
5188 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
5189 SILC_LOG_ERROR(("Attempting to add unregistered client to channel ",
5190 "%s", channel->channel_name));
5194 if (!silc_server_client_on_channel(client, channel, &chl)) {
5195 /* Client was not on the channel, add it. */
5196 chl = silc_calloc(1, sizeof(*chl));
5197 chl->client = client;
5199 chl->channel = channel;
5200 silc_hash_table_add(channel->user_list, chl->client, chl);
5201 silc_hash_table_add(client->channels, chl->channel, chl);
5202 channel->user_count++;
5210 /* Saves channels and channels user modes to the `client'. Removes
5211 the client from those channels that are not sent in the list but
5214 void silc_server_save_user_channels(SilcServer server,
5215 SilcSocketConnection sock,
5216 SilcClientEntry client,
5217 SilcBuffer channels,
5218 SilcBuffer channels_user_modes)
5221 SilcUInt32 *chumodes;
5222 SilcChannelPayload entry;
5223 SilcChannelEntry channel;
5224 SilcChannelID *channel_id;
5225 SilcChannelClientEntry chl;
5226 SilcHashTable ht = NULL;
5227 SilcHashTableList htl;
5231 if (!channels || !channels_user_modes ||
5232 !(client->data.status & SILC_IDLIST_STATUS_REGISTERED))
5235 ch = silc_channel_payload_parse_list(channels->data, channels->len);
5236 if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
5238 ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL,
5239 NULL, NULL, NULL, TRUE);
5240 silc_dlist_start(ch);
5241 while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
5242 /* Check if we have this channel, and add it if we don't have it.
5243 Also add the client on the channel unless it is there already. */
5244 channel_id = silc_channel_get_id_parse(entry);
5245 channel = silc_idlist_find_channel_by_id(server->local_list,
5248 channel = silc_idlist_find_channel_by_id(server->global_list,
5251 if (server->server_type != SILC_SERVER) {
5252 silc_free(channel_id);
5257 /* We don't have that channel anywhere, add it. */
5258 name = silc_channel_get_name(entry, NULL);
5259 channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
5260 channel_id, server->router,
5263 silc_free(channel_id);
5270 channel->mode = silc_channel_get_mode(entry);
5272 /* Add the client on the channel */
5273 if (!silc_server_client_on_channel(client, channel, &chl)) {
5274 chl = silc_calloc(1, sizeof(*chl));
5275 chl->client = client;
5276 chl->mode = chumodes[i++];
5277 chl->channel = channel;
5278 silc_hash_table_add(channel->user_list, chl->client, chl);
5279 silc_hash_table_add(client->channels, chl->channel, chl);
5280 channel->user_count++;
5283 chl->mode = chumodes[i++];
5286 silc_hash_table_add(ht, channel, channel);
5287 silc_free(channel_id);
5289 silc_channel_payload_list_free(ch);
5290 silc_free(chumodes);
5294 /* Go through the list again and remove client from channels that
5295 are no part of the list. */
5297 silc_hash_table_list(client->channels, &htl);
5298 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5299 if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
5300 silc_hash_table_del(chl->channel->user_list, chl->client);
5301 silc_hash_table_del(chl->client->channels, chl->channel);
5305 silc_hash_table_list_reset(&htl);
5306 silc_hash_table_free(ht);
5308 silc_hash_table_list(client->channels, &htl);
5309 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5310 silc_hash_table_del(chl->channel->user_list, chl->client);
5311 silc_hash_table_del(chl->client->channels, chl->channel);
5314 silc_hash_table_list_reset(&htl);
5318 /* Lookups route to the client indicated by the `id_data'. The connection
5319 object and internal data object is returned. Returns NULL if route
5320 could not be found to the client. If the `client_id' is specified then
5321 it is used and the `id_data' is ignored. */
5323 SilcSocketConnection
5324 silc_server_get_client_route(SilcServer server,
5325 unsigned char *id_data,
5327 SilcClientID *client_id,
5328 SilcIDListData *idata,
5329 SilcClientEntry *client_entry)
5332 SilcClientEntry client;
5334 SILC_LOG_DEBUG(("Start"));
5337 *client_entry = NULL;
5339 /* Decode destination Client ID */
5341 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
5343 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
5347 id = silc_id_dup(client_id, SILC_ID_CLIENT);
5350 /* If the destination belongs to our server we don't have to route
5351 the packet anywhere but to send it to the local destination. */
5352 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
5356 /* If we are router and the client has router then the client is in
5357 our cell but not directly connected to us. */
5358 if (server->server_type == SILC_ROUTER && client->router) {
5359 /* We are of course in this case the client's router thus the route
5360 to the client is the server who owns the client. So, we will send
5361 the packet to that server. */
5363 *idata = (SilcIDListData)client->router;
5364 return client->router->connection;
5367 /* Seems that client really is directly connected to us */
5369 *idata = (SilcIDListData)client;
5371 *client_entry = client;
5372 return client->connection;
5375 /* Destination belongs to someone not in this server. If we are normal
5376 server our action is to send the packet to our router. */
5377 if (server->server_type != SILC_ROUTER && !server->standalone) {
5380 *idata = (SilcIDListData)server->router;
5381 return SILC_PRIMARY_ROUTE(server);
5384 /* We are router and we will perform route lookup for the destination
5385 and send the packet to fastest route. */
5386 if (server->server_type == SILC_ROUTER && !server->standalone) {
5387 /* Check first that the ID is valid */
5388 client = silc_idlist_find_client_by_id(server->global_list, id,
5391 SilcSocketConnection dst_sock;
5393 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
5396 if (idata && dst_sock)
5397 *idata = (SilcIDListData)dst_sock->user_data;
5406 /* Encodes and returns channel list of channels the `client' has joined.
5407 Secret channels are not put to the list. */
5409 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
5410 SilcClientEntry client,
5413 SilcBuffer *user_mode_list)
5415 SilcBuffer buffer = NULL;
5416 SilcChannelEntry channel;
5417 SilcChannelClientEntry chl;
5418 SilcHashTableList htl;
5421 SilcUInt16 name_len;
5425 *user_mode_list = NULL;
5427 silc_hash_table_list(client->channels, &htl);
5428 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5429 channel = chl->channel;
5431 if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
5433 if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
5436 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
5437 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
5438 name_len = strlen(channel->channel_name);
5440 len = 4 + name_len + id_len + 4;
5441 buffer = silc_buffer_realloc(buffer,
5442 (buffer ? buffer->truelen + len : len));
5443 silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
5444 silc_buffer_format(buffer,
5445 SILC_STR_UI_SHORT(name_len),
5446 SILC_STR_UI_XNSTRING(channel->channel_name,
5448 SILC_STR_UI_SHORT(id_len),
5449 SILC_STR_UI_XNSTRING(cid, id_len),
5450 SILC_STR_UI_INT(chl->channel->mode),
5452 silc_buffer_pull(buffer, len);
5455 if (user_mode_list) {
5456 *user_mode_list = silc_buffer_realloc(*user_mode_list,
5458 (*user_mode_list)->truelen + 4 :
5460 silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
5461 (*user_mode_list)->data));
5462 SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
5463 silc_buffer_pull(*user_mode_list, 4);
5466 silc_hash_table_list_reset(&htl);
5469 silc_buffer_push(buffer, buffer->data - buffer->head);
5470 if (user_mode_list && *user_mode_list)
5471 silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
5472 (*user_mode_list)->head));
5477 /* Timeout callback for unsuccessful rekey. The rekey did not go through
5480 SILC_TASK_CALLBACK(silc_server_rekey_timeout)
5482 SilcServerRekeyInternalContext *ctx = context;
5483 SilcServer server = app_context;
5484 SilcSocketConnection sock = ctx->sock;
5486 SILC_LOG_DEBUG(("Timeout occurred in rekey protocol with %s:%d [%s]",
5487 sock->hostname, sock->port,
5488 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5489 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5490 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5493 SILC_LOG_WARNING(("Timeout occurred in rekey protocol with %s:%d [%s]",
5494 sock->hostname, sock->port,
5495 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5496 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5497 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5500 if (sock->protocol) {
5501 silc_protocol_cancel(sock->protocol, server->schedule);
5502 silc_protocol_free(sock->protocol);
5503 sock->protocol = NULL;
5506 silc_packet_context_free(ctx->packet);
5508 silc_ske_free(ctx->ske);
5509 silc_socket_free(sock);
5512 /* Disconnect since we failed to rekey, the keys are probably wrong. */
5513 silc_server_disconnect_remote(server, sock,
5514 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
5515 if (sock->user_data)
5516 silc_server_free_sock_user_data(server, sock, NULL);
5519 if (sock->type != SILC_SOCKET_TYPE_CLIENT)
5520 silc_server_create_connections(server);
5523 /* A timeout callback for the re-key. We will be the initiator of the
5526 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_callback)
5528 SilcServer server = app_context;
5529 SilcSocketConnection sock = (SilcSocketConnection)context;
5530 SilcIDListData idata = (SilcIDListData)sock->user_data;
5531 SilcProtocol protocol;
5532 SilcServerRekeyInternalContext *proto_ctx;
5537 /* Do not execute rekey with disabled connections, as it would not
5538 go through anyway. */
5539 if (idata->status & SILC_IDLIST_STATUS_DISABLED)
5542 /* If rekey protocol is active already wait for it to finish */
5543 if (sock->protocol && sock->protocol->protocol &&
5544 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)
5547 /* If any other protocol is active do not start this protocol yet. */
5548 if (sock->protocol) {
5549 SILC_LOG_DEBUG(("Waiting for other protocol to finish before rekeying"));
5550 silc_schedule_task_add(server->schedule, sock->sock,
5551 silc_server_rekey_callback,
5552 sock, 60, 0, SILC_TASK_TIMEOUT,
5553 SILC_TASK_PRI_NORMAL);
5557 SILC_LOG_DEBUG(("Executing rekey protocol with %s:%d [%s]",
5558 sock->hostname, sock->port,
5559 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5560 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5561 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5564 /* Allocate internal protocol context. This is sent as context
5566 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
5567 proto_ctx->server = (void *)server;
5568 proto_ctx->sock = silc_socket_dup(sock);
5569 proto_ctx->responder = FALSE;
5570 proto_ctx->pfs = idata->rekey->pfs;
5572 /* Perform rekey protocol. Will call the final callback after the
5573 protocol is over. */
5574 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
5575 &protocol, proto_ctx, silc_server_rekey_final);
5576 sock->protocol = protocol;
5578 /* Register timeout callback in case the rekey does not go through. */
5579 proto_ctx->timeout_task =
5580 silc_schedule_task_add(server->schedule, sock->sock,
5581 silc_server_rekey_timeout,
5583 (idata->rekey->timeout >
5584 server->config->key_exchange_timeout ?
5585 idata->rekey->timeout :
5586 server->config->key_exchange_timeout * 4), 0,
5590 /* Run the protocol */
5591 silc_protocol_execute(protocol, server->schedule, 0, 0);
5594 /* The final callback for the REKEY protocol. This will actually take the
5595 new key material into use. */
5597 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
5599 SilcProtocol protocol = (SilcProtocol)context;
5600 SilcServerRekeyInternalContext *ctx =
5601 (SilcServerRekeyInternalContext *)protocol->context;
5602 SilcServer server = (SilcServer)ctx->server;
5603 SilcSocketConnection sock = ctx->sock;
5604 SilcIDListData idata = (SilcIDListData)sock->user_data;
5606 if (ctx->timeout_task)
5607 silc_schedule_task_del(server->schedule, ctx->timeout_task);
5609 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
5610 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
5611 /* Error occured during protocol */
5612 SILC_LOG_ERROR(("Error occurred during rekey protocol with "
5613 "%s (%s)", sock->hostname, sock->ip));
5614 silc_protocol_cancel(protocol, server->schedule);
5615 silc_protocol_free(protocol);
5616 sock->protocol = NULL;
5618 silc_packet_context_free(ctx->packet);
5620 silc_ske_free(ctx->ske);
5621 silc_socket_free(sock);
5623 silc_server_disconnect_remote(server, sock,
5624 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
5625 if (sock->user_data)
5626 silc_server_free_sock_user_data(server, sock, NULL);
5629 if (sock->type != SILC_SOCKET_TYPE_CLIENT)
5630 silc_server_create_connections(server);
5634 SILC_LOG_DEBUG(("Rekey protocol completed with %s:%d [%s]",
5635 sock->hostname, sock->port,
5636 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5637 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5638 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5641 /* Purge the outgoing data queue to assure that all rekey packets really
5642 go to the network before we quit the protocol. */
5643 silc_server_packet_queue_purge(server, sock);
5645 /* Re-register re-key timeout */
5646 if (ctx->responder == FALSE)
5647 silc_schedule_task_add(server->schedule, sock->sock,
5648 silc_server_rekey_callback,
5649 sock, idata->rekey->timeout, 0,
5650 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
5653 silc_protocol_free(protocol);
5654 sock->protocol = NULL;
5656 silc_packet_context_free(ctx->packet);
5658 silc_ske_free(ctx->ske);
5659 silc_socket_free(sock);
5663 /* Task callback used to retrieve network statistical information from
5664 router server once in a while. */
5666 SILC_TASK_CALLBACK(silc_server_get_stats)
5668 SilcServer server = (SilcServer)context;
5669 SilcBuffer idp, packet;
5671 if (!server->standalone) {
5672 SILC_LOG_DEBUG(("Retrieving stats from router"));
5673 idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
5674 packet = silc_command_payload_encode_va(SILC_COMMAND_STATS,
5675 ++server->cmd_ident, 1,
5676 1, idp->data, idp->len);
5677 silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
5678 SILC_PACKET_COMMAND, 0, packet->data,
5679 packet->len, FALSE);
5680 silc_buffer_free(packet);
5681 silc_buffer_free(idp);
5684 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
5685 server, 120, 0, SILC_TASK_TIMEOUT,