5 Author: Pekka Riikonen <priikone@silcnet.org>
7 Copyright (C) 1997 - 2004 Pekka Riikonen
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; version 2 of the License.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
20 * This is the actual SILC server than handles everything relating to
21 * servicing the SILC connections. This is also a SILC router as a router
22 * is also normal server.
26 #include "serverincludes.h"
27 #include "server_internal.h"
29 /* Static prototypes */
30 SILC_TASK_CALLBACK(silc_server_rehash_close_connection);
31 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry);
32 SILC_TASK_CALLBACK(silc_server_connect_router);
33 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
35 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
38 SILC_TASK_CALLBACK(silc_server_packet_process);
39 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
40 SILC_TASK_CALLBACK(silc_server_close_connection_final);
41 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout);
42 SILC_TASK_CALLBACK(silc_server_timeout_remote);
43 SILC_TASK_CALLBACK(silc_server_channel_key_rekey);
44 SILC_TASK_CALLBACK(silc_server_get_stats);
46 /* Allocates a new SILC server object. This has to be done before the server
47 can be used. After allocation one must call silc_server_init to initialize
48 the server. The new allocated server object is returned to the new_server
51 int silc_server_alloc(SilcServer *new_server)
55 SILC_LOG_DEBUG(("Allocating new server object"));
57 server = silc_calloc(1, sizeof(*server));
58 server->server_type = SILC_SERVER;
59 server->standalone = TRUE;
60 server->local_list = silc_calloc(1, sizeof(*server->local_list));
61 server->global_list = silc_calloc(1, sizeof(*server->global_list));
62 server->pending_commands = silc_dlist_init();
64 server->sim = silc_dlist_init();
72 /* Free's the SILC server object. This is called at the very end before
75 void silc_server_free(SilcServer server)
78 SilcIDCacheEntry cache;
86 silc_dlist_start(server->sim);
87 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
88 silc_dlist_del(server->sim, sim);
92 silc_dlist_uninit(server->sim);
96 silc_server_backup_free(server);
97 silc_server_config_unref(&server->config_ref);
99 silc_rng_free(server->rng);
101 silc_pkcs_free(server->pkcs);
102 if (server->public_key)
103 silc_pkcs_public_key_free(server->public_key);
104 if (server->private_key)
105 silc_pkcs_private_key_free(server->private_key);
106 if (server->pending_commands)
107 silc_dlist_uninit(server->pending_commands);
108 if (server->id_entry)
109 silc_idlist_del_server(server->local_list, server->id_entry);
111 /* Delete all channels */
113 if (silc_idcache_get_all(server->local_list->channels, &list) &&
114 silc_idcache_list_first(list, &cache)) {
115 silc_idlist_del_channel(server->local_list, cache->context);
116 while (silc_idcache_list_next(list, &cache))
117 silc_idlist_del_channel(server->local_list, cache->context);
120 silc_idcache_list_free(list);
122 if (silc_idcache_get_all(server->global_list->channels, &list) &&
123 silc_idcache_list_first(list, &cache)) {
124 silc_idlist_del_channel(server->global_list, cache->context);
125 while (silc_idcache_list_next(list, &cache))
126 silc_idlist_del_channel(server->global_list, cache->context);
129 silc_idcache_list_free(list);
132 silc_hash_table_free(server->pk_hash);
134 /* Delete all clients */
136 if (silc_idcache_get_all(server->local_list->clients, &list) &&
137 silc_idcache_list_first(list, &cache)) {
138 silc_idlist_del_client(server->local_list, cache->context);
139 while (silc_idcache_list_next(list, &cache))
140 silc_idlist_del_client(server->local_list, cache->context);
143 silc_idcache_list_free(list);
145 if (silc_idcache_get_all(server->global_list->clients, &list) &&
146 silc_idcache_list_first(list, &cache)) {
147 silc_idlist_del_client(server->global_list, cache->context);
148 while (silc_idcache_list_next(list, &cache))
149 silc_idlist_del_client(server->global_list, cache->context);
152 silc_idcache_list_free(list);
155 /* Delete all servers */
157 if (silc_idcache_get_all(server->local_list->servers, &list) &&
158 silc_idcache_list_first(list, &cache)) {
159 silc_idlist_del_server(server->local_list, cache->context);
160 while (silc_idcache_list_next(list, &cache))
161 silc_idlist_del_server(server->local_list, cache->context);
164 silc_idcache_list_free(list);
166 if (silc_idcache_get_all(server->global_list->servers, &list) &&
167 silc_idcache_list_first(list, &cache)) {
168 silc_idlist_del_server(server->global_list, cache->context);
169 while (silc_idcache_list_next(list, &cache))
170 silc_idlist_del_server(server->global_list, cache->context);
173 silc_idcache_list_free(list);
175 silc_idcache_free(server->local_list->clients);
176 silc_idcache_free(server->local_list->servers);
177 silc_idcache_free(server->local_list->channels);
178 silc_idcache_free(server->global_list->clients);
179 silc_idcache_free(server->global_list->servers);
180 silc_idcache_free(server->global_list->channels);
181 silc_hash_table_free(server->watcher_list);
183 silc_hash_free(server->md5hash);
184 silc_hash_free(server->sha1hash);
185 silc_hmac_unregister_all();
186 silc_hash_unregister_all();
187 silc_cipher_unregister_all();
188 silc_pkcs_unregister_all();
190 silc_free(server->local_list);
191 silc_free(server->global_list);
192 silc_free(server->server_name);
193 silc_free(server->id_string);
194 silc_free(server->purge_i);
195 silc_free(server->purge_g);
199 /* Creates a new server listener. */
201 static bool silc_server_listen(SilcServer server, const char *server_ip,
202 SilcUInt16 port, int *sock)
204 *sock = silc_net_create_server(port, server_ip);
206 SILC_SERVER_LOG_ERROR(("Could not create server listener: %s on %hu",
213 /* Adds a secondary listener. */
215 bool silc_server_init_secondary(SilcServer server)
217 int sock = 0, sock_list[server->config->param.connections_max];
218 SilcSocketConnection newsocket = NULL;
219 SilcServerConfigServerInfoInterface *interface;
221 for (interface = server->config->server_info->secondary; interface;
222 interface = interface->next, sock++) {
224 if (!silc_server_listen(server,
225 interface->server_ip, interface->port, &sock_list[sock]))
228 /* Set socket to non-blocking mode */
229 silc_net_set_socket_nonblock(sock_list[sock]);
231 /* Add ourselves also to the socket table. The entry allocated above
232 is sent as argument for fast referencing in the future. */
233 silc_socket_alloc(sock_list[sock],
234 SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
235 server->sockets[sock_list[sock]] = newsocket;
236 SILC_SET_LISTENER(newsocket);
238 /* Perform name and address lookups to resolve the listenning address
240 if (!silc_net_check_local_by_sock(sock_list[sock], &newsocket->hostname,
242 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
244 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
245 newsocket->hostname ? newsocket->hostname :
246 newsocket->ip ? newsocket->ip : ""));
247 server->stat.conn_failures++;
250 if (!newsocket->hostname)
251 newsocket->hostname = strdup(newsocket->ip);
253 newsocket->port = silc_net_get_local_port(sock);
255 newsocket->user_data = (void *)server->id_entry;
256 silc_schedule_task_add(server->schedule, sock_list[sock],
257 silc_server_accept_new_connection,
258 (void *)server, 0, 0,
260 SILC_TASK_PRI_NORMAL);
266 do silc_net_close_server(sock_list[sock--]); while (sock >= 0);
270 /* Initializes the entire SILC server. This is called always before running
271 the server. This is called only once at the initialization of the program.
272 This binds the server to its listenning port. After this function returns
273 one should call silc_server_run to start the server. This returns TRUE
274 when everything is ok to run the server. Configuration file must be
275 read and parsed before calling this. */
277 bool silc_server_init(SilcServer server)
281 SilcServerEntry id_entry;
282 SilcIDListPurge purge;
283 SilcSocketConnection newsocket = NULL;
285 SILC_LOG_DEBUG(("Initializing server"));
287 server->starttime = time(NULL);
289 /* Take config object for us */
290 silc_server_config_ref(&server->config_ref, server->config,
294 /* Set debugging on if configured */
295 if (server->config->debug_string) {
297 silc_log_set_debug_string(server->config->debug_string);
299 #endif /* SILC_DEBUG */
301 /* Steal public and private key from the config object */
302 server->public_key = server->config->server_info->public_key;
303 server->private_key = server->config->server_info->private_key;
304 server->config->server_info->public_key = NULL;
305 server->config->server_info->private_key = NULL;
307 /* Register all configured ciphers, PKCS and hash functions. */
308 if (!silc_server_config_register_ciphers(server))
309 silc_cipher_register_default();
310 if (!silc_server_config_register_pkcs(server))
311 silc_pkcs_register_default();
312 if (!silc_server_config_register_hashfuncs(server))
313 silc_hash_register_default();
314 if (!silc_server_config_register_hmacs(server))
315 silc_hmac_register_default();
317 /* Initialize random number generator for the server. */
318 server->rng = silc_rng_alloc();
319 silc_rng_init(server->rng);
320 silc_rng_global_init(server->rng);
322 /* Initialize hash functions for server to use */
323 silc_hash_alloc("md5", &server->md5hash);
324 silc_hash_alloc("sha1", &server->sha1hash);
326 /* Allocate PKCS context for local public and private keys */
327 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
329 silc_pkcs_public_key_set(server->pkcs, server->public_key);
330 silc_pkcs_private_key_set(server->pkcs, server->private_key);
332 /* Initialize the scheduler */
333 server->schedule = silc_schedule_init(server->config->param.connections_max,
335 if (!server->schedule)
338 /* First, register log files configuration for error output */
339 silc_server_config_setlogfiles(server);
341 /* Initialize ID caches */
342 server->local_list->clients =
343 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
344 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
345 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
347 /* These are allocated for normal server as well as these hold some
348 global information that the server has fetched from its router. For
349 router these are used as they are supposed to be used on router. */
350 server->global_list->clients =
351 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
352 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
353 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
355 /* Init watcher list */
356 server->watcher_list =
357 silc_hash_table_alloc(1, silc_hash_client_id_hash, NULL,
358 silc_hash_data_compare, (void *)CLIENTID_HASH_LEN,
360 if (!server->watcher_list)
363 /* Init public key list */
365 silc_hash_table_alloc(0, silc_hash_public_key, NULL,
366 silc_hash_public_key_compare, NULL,
369 if (!server->pk_hash)
372 /* Create a listening server */
373 if (!silc_server_listen(server,
374 server->config->server_info->primary == NULL ? NULL :
375 server->config->server_info->primary->server_ip,
376 server->config->server_info->primary == NULL ? 0 :
377 server->config->server_info->primary->port,
381 /* Set socket to non-blocking mode */
382 silc_net_set_socket_nonblock(sock);
385 /* Allocate the entire socket list that is used in server. Eventually
386 all connections will have entry in this table (it is a table of
387 pointers to the actual object that is allocated individually
389 server->sockets = silc_calloc(server->config->param.connections_max,
390 sizeof(*server->sockets));
391 if (!server->sockets)
394 /* Add ourselves also to the socket table. The entry allocated above
395 is sent as argument for fast referencing in the future. */
396 silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
397 server->sockets[sock] = newsocket;
398 SILC_SET_LISTENER(newsocket);
400 /* Perform name and address lookups to resolve the listenning address
402 if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
404 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
406 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
407 newsocket->hostname ? newsocket->hostname :
408 newsocket->ip ? newsocket->ip : ""));
409 server->stat.conn_failures++;
412 if (!newsocket->hostname)
413 newsocket->hostname = strdup(newsocket->ip);
415 newsocket->port = silc_net_get_local_port(sock);
417 /* Create a Server ID for the server. */
418 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
423 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
424 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
425 server->server_name = server->config->server_info->server_name;
426 server->config->server_info->server_name = NULL;
428 /* Add ourselves to the server list. We don't have a router yet
429 beacuse we haven't established a route yet. It will be done later.
430 For now, NULL is sent as router. This allocates new entry to
433 silc_idlist_add_server(server->local_list, strdup(server->server_name),
434 server->server_type, server->id, NULL, NULL);
436 SILC_LOG_ERROR(("Could not add ourselves to cache"));
439 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
441 /* Put the allocated socket pointer also to the entry allocated above
442 for fast back-referencing to the socket list. */
443 newsocket->user_data = (void *)id_entry;
444 id_entry->connection = (void *)newsocket;
445 server->id_entry = id_entry;
447 /* Register protocols */
448 silc_server_protocols_register();
450 /* Create connections to configured routers. */
451 silc_server_create_connections(server);
453 /* Add listener task to the scheduler. This task receives new connections
454 to the server. This task remains on the queue until the end of the
456 silc_schedule_task_add(server->schedule, sock,
457 silc_server_accept_new_connection,
458 (void *)server, 0, 0,
460 SILC_TASK_PRI_NORMAL);
462 if (silc_server_init_secondary(server) == FALSE)
465 server->listenning = TRUE;
467 /* If server connections has been configured then we must be router as
468 normal server cannot have server connections, only router connections. */
469 if (server->config->servers) {
470 SilcServerConfigServer *ptr = server->config->servers;
472 server->server_type = SILC_ROUTER;
474 if (ptr->backup_router) {
475 server->server_type = SILC_BACKUP_ROUTER;
476 server->backup_router = TRUE;
477 server->id_entry->server_type = SILC_BACKUP_ROUTER;
484 /* Register the ID Cache purge task. This periodically purges the ID cache
485 and removes the expired cache entries. */
487 /* Clients local list */
488 server->purge_i = purge = silc_calloc(1, sizeof(*purge));
489 purge->cache = server->local_list->clients;
490 purge->timeout = 600;
491 silc_schedule_task_add(server->schedule, 0, silc_idlist_purge,
492 (void *)purge, purge->timeout, 0,
493 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
495 /* Clients global list */
496 server->purge_g = purge = silc_calloc(1, sizeof(*purge));
497 purge->cache = server->global_list->clients;
498 purge->timeout = 300;
499 silc_schedule_task_add(server->schedule, 0, silc_idlist_purge,
500 (void *)purge, purge->timeout, 0,
501 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
503 /* If we are normal server we'll retrieve network statisticial information
504 once in a while from the router. */
505 if (server->server_type != SILC_ROUTER)
506 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
507 server, 10, 0, SILC_TASK_TIMEOUT,
510 if (server->server_type == SILC_ROUTER)
511 server->stat.routers++;
513 SILC_LOG_DEBUG(("Server initialized"));
515 /* We are done here, return succesfully */
519 silc_server_config_unref(&server->config_ref);
520 silc_net_close_server(sock);
524 /* Task callback to close a socket connection after rehash */
526 SILC_TASK_CALLBACK(silc_server_rehash_close_connection)
528 SilcServer server = context;
529 SilcSocketConnection sock = server->sockets[fd];
534 SILC_LOG_INFO(("Connection %s:%d [%s] is unconfigured",
535 sock->hostname, sock->port,
536 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
537 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
538 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
540 silc_schedule_task_del_by_context(server->schedule, sock);
541 silc_server_disconnect_remote(server, sock,
542 SILC_STATUS_ERR_BANNED_FROM_SERVER,
543 "This connection is removed from "
546 silc_server_free_sock_user_data(server, sock, NULL);
549 /* This function basically reads the config file again and switches the config
550 object pointed by the server object. After that, we have to fix various
551 things such as the server_name and the listening ports.
552 Keep in mind that we no longer have the root privileges at this point. */
554 bool silc_server_rehash(SilcServer server)
556 SilcServerConfig newconfig;
558 SILC_LOG_INFO(("Rehashing server"));
560 /* Reset the logging system */
561 silc_log_quick = TRUE;
562 silc_log_flush_all();
564 /* Start the main rehash phase (read again the config file) */
565 newconfig = silc_server_config_alloc(server->config_file);
567 SILC_LOG_ERROR(("Rehash FAILED."));
571 /* Reinit scheduler if necessary */
572 if (newconfig->param.connections_max > server->config->param.connections_max)
573 if (!silc_schedule_reinit(server->schedule,
574 newconfig->param.connections_max))
577 /* Fix the server_name field */
578 if (strcmp(server->server_name, newconfig->server_info->server_name)) {
579 silc_free(server->server_name);
580 server->server_name = newconfig->server_info->server_name;
581 newconfig->server_info->server_name = NULL;
583 /* Update the idcache list with a fresh pointer */
584 silc_free(server->id_entry->server_name);
585 server->id_entry->server_name = strdup(server->server_name);
586 if (!silc_idcache_del_by_context(server->local_list->servers,
589 if (!silc_idcache_add(server->local_list->servers,
590 server->id_entry->server_name,
591 server->id_entry->id, server->id_entry, 0, NULL))
596 silc_server_config_setlogfiles(server);
598 /* Change new key pair if necessary */
599 if (newconfig->server_info->public_key &&
600 !silc_pkcs_public_key_compare(server->public_key,
601 newconfig->server_info->public_key)) {
602 silc_pkcs_public_key_free(server->public_key);
603 silc_pkcs_private_key_free(server->private_key);
604 server->public_key = newconfig->server_info->public_key;
605 server->private_key = newconfig->server_info->private_key;
606 newconfig->server_info->public_key = NULL;
607 newconfig->server_info->private_key = NULL;
609 /* Allocate PKCS context for local public and private keys */
610 silc_pkcs_free(server->pkcs);
611 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
613 silc_pkcs_public_key_set(server->pkcs, server->public_key);
614 silc_pkcs_private_key_set(server->pkcs, server->private_key);
617 /* Check for unconfigured server and router connections and close
618 connections that were unconfigured. */
620 if (server->config->routers) {
621 SilcServerConfigRouter *ptr;
622 SilcServerConfigRouter *newptr;
625 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
628 /* Check whether new config has this one too */
629 for (newptr = newconfig->routers; newptr; newptr = newptr->next) {
630 if (silc_string_compare(newptr->host, ptr->host) &&
631 newptr->port == ptr->port &&
632 newptr->initiator == ptr->initiator) {
638 if (!found && ptr->host) {
639 /* Remove this connection */
640 SilcSocketConnection sock;
641 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_ROUTER,
642 ptr->host, ptr->port);
643 if (sock && !SILC_IS_LISTENER(sock))
644 silc_schedule_task_add(server->schedule, sock->sock,
645 silc_server_rehash_close_connection,
646 server, 0, 1, SILC_TASK_TIMEOUT,
647 SILC_TASK_PRI_NORMAL);
652 if (server->config->servers) {
653 SilcServerConfigServer *ptr;
654 SilcServerConfigServer *newptr;
657 for (ptr = server->config->servers; ptr; ptr = ptr->next) {
660 /* Check whether new config has this one too */
661 for (newptr = newconfig->servers; newptr; newptr = newptr->next) {
662 if (silc_string_compare(newptr->host, ptr->host)) {
668 if (!found && ptr->host) {
669 /* Remove this connection */
670 SilcSocketConnection sock;
671 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_SERVER,
673 if (sock && !SILC_IS_LISTENER(sock))
674 silc_schedule_task_add(server->schedule, sock->sock,
675 silc_server_rehash_close_connection,
676 server, 0, 1, SILC_TASK_TIMEOUT,
677 SILC_TASK_PRI_NORMAL);
682 if (server->config->clients) {
683 SilcServerConfigClient *ptr;
684 SilcServerConfigClient *newptr;
687 for (ptr = server->config->clients; ptr; ptr = ptr->next) {
690 /* Check whether new config has this one too */
691 for (newptr = newconfig->clients; newptr; newptr = newptr->next) {
692 if (silc_string_compare(newptr->host, ptr->host)) {
698 if (!found && ptr->host) {
699 /* Remove this connection */
700 SilcSocketConnection sock;
701 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_CLIENT,
704 silc_schedule_task_add(server->schedule, sock->sock,
705 silc_server_rehash_close_connection,
706 server, 0, 1, SILC_TASK_TIMEOUT,
707 SILC_TASK_PRI_NORMAL);
712 /* Create connections after rehash */
713 silc_server_create_connections(server);
715 /* Check whether our router status has changed */
716 if (newconfig->servers) {
717 SilcServerConfigServer *ptr = newconfig->servers;
719 server->server_type = SILC_ROUTER;
721 if (ptr->backup_router) {
722 server->server_type = SILC_BACKUP_ROUTER;
723 server->backup_router = TRUE;
724 server->id_entry->server_type = SILC_BACKUP_ROUTER;
731 /* Our old config is gone now. We'll unreference our reference made in
732 silc_server_init and then destroy it since we are destroying it
733 underneath the application (layer which called silc_server_init). */
734 silc_server_config_unref(&server->config_ref);
735 silc_server_config_destroy(server->config);
737 /* Take new config context */
738 server->config = newconfig;
739 silc_server_config_ref(&server->config_ref, server->config, server->config);
742 /* Set debugging on if configured */
743 if (server->config->debug_string) {
745 silc_log_set_debug_string(server->config->debug_string);
749 #endif /* SILC_DEBUG */
751 SILC_LOG_DEBUG(("Server rehashed"));
756 /* The heart of the server. This runs the scheduler thus runs the server.
757 When this returns the server has been stopped and the program will
760 void silc_server_run(SilcServer server)
762 SILC_LOG_INFO(("SILC Server started"));
764 /* Start the scheduler, the heart of the SILC server. When this returns
765 the program will be terminated. */
766 silc_schedule(server->schedule);
769 /* Stops the SILC server. This function is used to shutdown the server.
770 This is usually called after the scheduler has returned. After stopping
771 the server one should call silc_server_free. */
773 void silc_server_stop(SilcServer server)
775 SILC_LOG_INFO(("SILC Server shutting down"));
777 if (server->schedule) {
780 server->server_shutdown = TRUE;
782 /* Close all connections */
783 for (i = 0; i < server->config->param.connections_max; i++) {
784 if (!server->sockets[i])
786 if (!SILC_IS_LISTENER(server->sockets[i])) {
787 SilcSocketConnection sock = server->sockets[i];
788 SilcIDListData idata = sock->user_data;
791 idata->status &= ~SILC_IDLIST_STATUS_DISABLED;
793 silc_schedule_task_del_by_context(server->schedule,
795 silc_schedule_task_del_by_fd(server->schedule,
796 server->sockets[i]->sock);
797 silc_server_disconnect_remote(server, server->sockets[i],
799 "Server is shutting down");
800 if (server->sockets[i]) {
802 silc_server_free_sock_user_data(server, sock,
803 "Server is shutting down");
804 silc_socket_free(sock);
807 silc_socket_free(server->sockets[i]);
808 server->sockets[i] = NULL;
812 /* We are not connected to network anymore */
813 server->standalone = TRUE;
815 silc_schedule_stop(server->schedule);
816 silc_schedule_uninit(server->schedule);
817 server->schedule = NULL;
819 silc_free(server->sockets);
820 server->sockets = NULL;
823 silc_server_protocols_unregister();
825 SILC_LOG_DEBUG(("Server stopped"));
828 /* Function that is called when the network connection to a router has
829 been established. This will continue with the key exchange protocol
830 with the remote router. */
832 void silc_server_start_key_exchange(SilcServer server,
833 SilcServerConnection sconn,
836 SilcSocketConnection newsocket;
837 SilcProtocol protocol;
838 SilcServerKEInternalContext *proto_ctx;
839 SilcServerConfigRouter *conn =
840 (SilcServerConfigRouter *) sconn->conn.ref_ptr;
843 /* Cancel any possible retry timeouts */
844 silc_schedule_task_del_by_callback(server->schedule,
845 silc_server_connect_to_router_retry);
847 /* Set socket options */
848 silc_net_set_socket_nonblock(sock);
849 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
851 /* Create socket connection for the connection. Even though we
852 know that we are connecting to a router we will mark the socket
853 to be unknown connection until we have executed authentication
855 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
856 server->sockets[sock] = newsocket;
857 newsocket->hostname = strdup(sconn->remote_host);
858 newsocket->ip = strdup(sconn->remote_host);
859 newsocket->port = sconn->remote_port;
860 sconn->sock = newsocket;
862 /* Allocate internal protocol context. This is sent as context
864 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
865 proto_ctx->server = (void *)server;
866 proto_ctx->context = (void *)sconn;
867 proto_ctx->sock = newsocket;
868 proto_ctx->rng = server->rng;
869 proto_ctx->responder = FALSE;
871 /* Set Key Exchange flags from configuration, but fall back to global
873 SILC_GET_SKE_FLAGS(conn, proto_ctx);
874 if (server->config->param.key_exchange_pfs)
875 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
877 /* Perform key exchange protocol. silc_server_connect_to_router_second
878 will be called after the protocol is finished. */
879 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
880 &protocol, proto_ctx,
881 silc_server_connect_to_router_second);
882 newsocket->protocol = protocol;
884 /* Register a timeout task that will be executed if the protocol
885 is not executed within set limit. */
886 proto_ctx->timeout_task =
887 silc_schedule_task_add(server->schedule, sock,
888 silc_server_timeout_remote,
889 server, server->config->key_exchange_timeout, 0,
893 /* Register the connection for network input and output. This sets
894 that scheduler will listen for incoming packets for this connection
895 and sets that outgoing packets may be sent to this connection as
896 well. However, this doesn't set the scheduler for outgoing traffic,
897 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
898 later when outgoing data is available. */
899 context = (void *)server;
900 SILC_REGISTER_CONNECTION_FOR_IO(sock);
902 /* Run the protocol */
903 silc_protocol_execute(protocol, server->schedule, 0, 0);
906 /* Timeout callback that will be called to retry connecting to remote
907 router. This is used by both normal and router server. This will wait
908 before retrying the connecting. The timeout is generated by exponential
909 backoff algorithm. */
911 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
913 SilcServer server = app_context;
914 SilcServerConnection sconn = (SilcServerConnection)context;
915 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
916 SilcServerConfigConnParams *param =
917 (conn->param ? conn->param : &server->config->param);
919 /* Don't retry if we are shutting down. */
920 if (server->server_shutdown) {
921 silc_server_config_unref(&sconn->conn);
922 silc_free(sconn->remote_host);
923 silc_free(sconn->backup_replace_ip);
928 SILC_LOG_INFO(("Retrying connecting to a router"));
930 /* Calculate next timeout */
931 if (sconn->retry_count >= 1) {
932 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
933 if (sconn->retry_timeout > param->reconnect_interval_max)
934 sconn->retry_timeout = param->reconnect_interval_max;
936 sconn->retry_timeout = param->reconnect_interval;
938 sconn->retry_count++;
939 sconn->retry_timeout = sconn->retry_timeout +
940 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
942 /* If we've reached max retry count, give up. */
943 if ((sconn->retry_count > param->reconnect_count) &&
944 !param->reconnect_keep_trying) {
945 SILC_LOG_ERROR(("Could not connect to router, giving up"));
946 silc_server_config_unref(&sconn->conn);
947 silc_free(sconn->remote_host);
948 silc_free(sconn->backup_replace_ip);
953 SILC_LOG_DEBUG(("Retrying connecting to a router in %d seconds",
954 sconn->retry_timeout));
956 /* We will lookup a fresh pointer later */
957 silc_server_config_unref(&sconn->conn);
959 /* Wait one before retrying */
960 silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
961 context, sconn->retry_timeout, 0,
962 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
965 /* callback for async connection to remote router */
967 SILC_TASK_CALLBACK(silc_server_connect_router); /* forward decl */
969 SILC_TASK_CALLBACK(silc_server_connection_established)
971 SilcServer server = app_context;
972 SilcServerConnection sconn = (SilcServerConnection)context;
974 int opt = EINVAL, optlen = sizeof(opt);
976 silc_schedule_task_del_by_fd(server->schedule, sock);
977 silc_schedule_unset_listen_fd(server->schedule, sock);
979 if (silc_net_get_socket_opt(sock, SOL_SOCKET, SO_ERROR, &opt, &optlen) ||
981 SILC_LOG_ERROR(("Could not connect to router %s:%d: %s",
982 sconn->remote_host, sconn->remote_port,
984 if (!sconn->no_reconnect)
985 silc_schedule_task_add(server->schedule, 0,
986 silc_server_connect_to_router_retry,
987 context, 0, 1, SILC_TASK_TIMEOUT,
988 SILC_TASK_PRI_NORMAL);
990 silc_server_config_unref(&sconn->conn);
991 silc_free(sconn->remote_host);
992 silc_free(sconn->backup_replace_ip);
998 SILC_LOG_DEBUG(("Connection to router %s:%d established", sconn->remote_host,
999 sconn->remote_port));
1001 /* Continue with key exchange protocol */
1002 silc_server_start_key_exchange(server, sconn, sock);
1004 /* Generic routine to use connect to a router. */
1006 SILC_TASK_CALLBACK(silc_server_connect_router)
1008 SilcServer server = app_context;
1009 SilcServerConnection sconn = (SilcServerConnection)context;
1010 SilcServerConfigRouter *rconn;
1013 /* Don't connect if we are shutting down. */
1014 if (server->server_shutdown) {
1015 silc_free(sconn->remote_host);
1016 silc_free(sconn->backup_replace_ip);
1021 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
1022 (sconn->backup ? "backup router" : "router"),
1023 sconn->remote_host, sconn->remote_port));
1025 server->router_connect = time(NULL);
1026 rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
1027 sconn->remote_port);
1029 SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
1030 (sconn->backup ? "backup router" : "router"),
1031 sconn->remote_host, sconn->remote_port));
1032 silc_free(sconn->remote_host);
1033 silc_free(sconn->backup_replace_ip);
1037 silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
1039 /* Connect to remote host */
1040 sock = silc_net_create_connection_async(
1041 (!server->config->server_info->primary ? NULL :
1042 server->config->server_info->primary->server_ip),
1043 sconn->remote_port, sconn->remote_host);
1045 SILC_LOG_ERROR(("Could not connect to router %s:%d",
1046 sconn->remote_host, sconn->remote_port));
1047 if (!sconn->no_reconnect)
1048 silc_schedule_task_add(server->schedule, 0,
1049 silc_server_connect_to_router_retry,
1050 context, 0, 1, SILC_TASK_TIMEOUT,
1051 SILC_TASK_PRI_NORMAL);
1053 silc_server_config_unref(&sconn->conn);
1054 silc_free(sconn->remote_host);
1055 silc_free(sconn->backup_replace_ip);
1061 /* wait for the connection to be established */
1062 silc_schedule_task_add(server->schedule, sock,
1063 silc_server_connection_established,
1064 context, 0, 0, SILC_TASK_FD,
1065 SILC_TASK_PRI_NORMAL);
1066 silc_schedule_set_listen_fd(server->schedule, sock,
1067 SILC_TASK_WRITE, FALSE);
1070 /* This function connects to our primary router or if we are a router this
1071 establishes all our primary routes. This is called at the start of the
1072 server to do authentication and key exchange with our router - called
1075 SILC_TASK_CALLBACK_GLOBAL(silc_server_connect_to_router)
1077 SilcServer server = (SilcServer)context;
1078 SilcServerConnection sconn;
1079 SilcServerConfigRouter *ptr;
1081 /* Don't connect if we are shutting down. */
1082 if (server->server_shutdown)
1085 SILC_LOG_DEBUG(("We are %s",
1086 (server->server_type == SILC_SERVER ?
1087 "normal server" : server->server_type == SILC_ROUTER ?
1088 "router" : "backup router/normal server")));
1090 if (!server->config->routers) {
1091 /* There wasn't a configured router, we will continue but we don't
1092 have a connection to outside world. We will be standalone server. */
1093 SILC_LOG_DEBUG(("No router(s), we are standalone"));
1094 server->standalone = TRUE;
1098 /* Cancel any possible retry timeouts */
1099 silc_schedule_task_del_by_callback(server->schedule,
1100 silc_server_connect_router);
1101 silc_schedule_task_del_by_callback(server->schedule,
1102 silc_server_connect_to_router_retry);
1104 /* Create the connections to all our routes */
1105 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
1107 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
1108 ptr->backup_router ? "Backup router" : "Router",
1109 ptr->initiator ? "Initiator" : "Responder",
1110 ptr->host, ptr->port));
1112 if (server->server_type == SILC_ROUTER && ptr->backup_router &&
1113 ptr->initiator == FALSE && !server->backup_router &&
1114 !silc_server_config_get_backup_router(server))
1115 server->wait_backup = TRUE;
1117 if (ptr->initiator) {
1118 /* Check whether we are connecting or connected to this host already */
1119 if (silc_server_num_sockets_by_remote(server,
1120 silc_net_is_ip(ptr->host) ?
1122 silc_net_is_ip(ptr->host) ?
1123 NULL : ptr->host, ptr->port,
1124 SILC_SOCKET_TYPE_ROUTER)) {
1125 SILC_LOG_DEBUG(("We are already connected to this router"));
1127 /* If we don't have primary router and this connection is our
1128 primary router we are in desync. Reconnect to the primary. */
1129 if (server->standalone && !server->router) {
1130 SilcServerConfigRouter *primary =
1131 silc_server_config_get_primary_router(server);
1132 if (primary == ptr) {
1133 SilcSocketConnection sock =
1134 silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_ROUTER,
1135 ptr->host, ptr->port);
1137 server->backup_noswitch = TRUE;
1138 if (sock->user_data)
1139 silc_server_free_sock_user_data(server, sock, NULL);
1140 silc_server_disconnect_remote(server, sock, 0, NULL);
1141 server->backup_noswitch = FALSE;
1142 SILC_LOG_DEBUG(("Reconnecting to primary router"));
1153 if (silc_server_num_sockets_by_remote(server,
1154 silc_net_is_ip(ptr->host) ?
1156 silc_net_is_ip(ptr->host) ?
1157 NULL : ptr->host, ptr->port,
1158 SILC_SOCKET_TYPE_UNKNOWN)) {
1159 SILC_LOG_DEBUG(("We are already connecting to this router"));
1163 /* Allocate connection object for hold connection specific stuff. */
1164 sconn = silc_calloc(1, sizeof(*sconn));
1165 sconn->remote_host = strdup(ptr->host);
1166 sconn->remote_port = ptr->port;
1167 sconn->backup = ptr->backup_router;
1168 if (sconn->backup) {
1169 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
1170 sconn->backup_replace_port = ptr->backup_replace_port;
1173 if (!server->router_conn && !sconn->backup)
1174 server->router_conn = sconn;
1176 silc_schedule_task_add(server->schedule, 0,
1177 silc_server_connect_router,
1178 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
1179 SILC_TASK_PRI_NORMAL);
1184 /* Second part of connecting to router(s). Key exchange protocol has been
1185 executed and now we will execute authentication protocol. */
1187 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
1189 SilcProtocol protocol = (SilcProtocol)context;
1190 SilcServerKEInternalContext *ctx =
1191 (SilcServerKEInternalContext *)protocol->context;
1192 SilcServer server = (SilcServer)ctx->server;
1193 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1194 SilcSocketConnection sock = ctx->sock;
1195 SilcServerConnAuthInternalContext *proto_ctx;
1196 SilcServerConfigRouter *conn = NULL;
1198 SILC_LOG_DEBUG(("Start"));
1200 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1201 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1202 /* Error occured during protocol */
1203 silc_protocol_free(protocol);
1204 sock->protocol = NULL;
1205 silc_ske_free_key_material(ctx->keymat);
1207 silc_packet_context_free(ctx->packet);
1209 silc_ske_free(ctx->ske);
1210 silc_free(ctx->dest_id);
1212 silc_server_disconnect_remote(server, sock,
1213 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1215 /* Try reconnecting if configuration wants it */
1216 if (!sconn->no_reconnect) {
1217 silc_schedule_task_add(server->schedule, 0,
1218 silc_server_connect_to_router_retry,
1219 sconn, 0, 1, SILC_TASK_TIMEOUT,
1220 SILC_TASK_PRI_NORMAL);
1224 /* Call completion to indicate error */
1225 if (sconn->callback)
1226 (*sconn->callback)(server, NULL, sconn->callback_context);
1228 silc_server_config_unref(&sconn->conn);
1229 silc_free(sconn->remote_host);
1230 silc_free(sconn->backup_replace_ip);
1235 /* We now have the key material as the result of the key exchange
1236 protocol. Take the key material into use. Free the raw key material
1237 as soon as we've set them into use. */
1238 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1239 ctx->sock, ctx->keymat,
1240 ctx->ske->prop->cipher,
1241 ctx->ske->prop->pkcs,
1242 ctx->ske->prop->hash,
1243 ctx->ske->prop->hmac,
1244 ctx->ske->prop->group,
1246 silc_protocol_free(protocol);
1247 sock->protocol = NULL;
1248 silc_ske_free_key_material(ctx->keymat);
1250 silc_packet_context_free(ctx->packet);
1252 silc_ske_free(ctx->ske);
1253 silc_free(ctx->dest_id);
1255 silc_server_disconnect_remote(server, sock,
1256 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1258 /* Try reconnecting if configuration wants it */
1259 if (!sconn->no_reconnect) {
1260 silc_schedule_task_add(server->schedule, 0,
1261 silc_server_connect_to_router_retry,
1262 sconn, 0, 1, SILC_TASK_TIMEOUT,
1263 SILC_TASK_PRI_NORMAL);
1267 /* Call completion to indicate error */
1268 if (sconn->callback)
1269 (*sconn->callback)(server, NULL, sconn->callback_context);
1271 silc_server_config_unref(&sconn->conn);
1272 silc_free(sconn->remote_host);
1273 silc_free(sconn->backup_replace_ip);
1277 silc_ske_free_key_material(ctx->keymat);
1279 /* Allocate internal context for the authentication protocol. This
1280 is sent as context for the protocol. */
1281 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1282 proto_ctx->server = (void *)server;
1283 proto_ctx->context = (void *)sconn;
1284 proto_ctx->sock = sock;
1285 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1286 proto_ctx->dest_id_type = ctx->dest_id_type;
1287 proto_ctx->dest_id = ctx->dest_id;
1289 /* Resolve the authentication method used in this connection. Check if
1290 we find a match from user configured connections */
1291 if (!sconn->conn.ref_ptr)
1292 conn = silc_server_config_find_router_conn(server, sock->hostname,
1295 conn = sconn->conn.ref_ptr;
1298 /* Match found. Use the configured authentication method. Take only
1299 the passphrase, since for public key auth we automatically use
1300 our local key pair. */
1301 if (conn->passphrase) {
1302 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
1303 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1305 proto_ctx->auth_data = strdup(conn->passphrase);
1306 proto_ctx->auth_data_len = strlen(conn->passphrase);
1307 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
1309 } else if (conn->publickeys) {
1310 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1312 proto_ctx->auth_meth = SILC_AUTH_NONE;
1315 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
1316 sock->hostname, sock->ip, sock->port));
1317 silc_protocol_free(protocol);
1318 sock->protocol = NULL;
1320 silc_packet_context_free(ctx->packet);
1322 silc_ske_free(ctx->ske);
1323 silc_free(ctx->dest_id);
1325 silc_server_config_unref(&sconn->conn);
1326 silc_free(sconn->remote_host);
1327 silc_free(sconn->backup_replace_ip);
1329 silc_server_disconnect_remote(server, sock,
1330 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1334 /* Free old protocol as it is finished now */
1335 silc_protocol_free(protocol);
1337 silc_packet_context_free(ctx->packet);
1339 sock->protocol = NULL;
1341 /* Allocate the authentication protocol. This is allocated here
1342 but we won't start it yet. We will be receiving party of this
1343 protocol thus we will wait that connecting party will make
1344 their first move. */
1345 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1346 &sock->protocol, proto_ctx,
1347 silc_server_connect_to_router_final);
1349 /* Register timeout task. If the protocol is not executed inside
1350 this timelimit the connection will be terminated. */
1351 proto_ctx->timeout_task =
1352 silc_schedule_task_add(server->schedule, sock->sock,
1353 silc_server_timeout_remote,
1355 server->config->conn_auth_timeout, 0,
1359 /* Run the protocol */
1360 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1363 /* Finalizes the connection to router. Registers a server task to the
1364 queue so that we can accept new connections. */
1366 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
1368 SilcProtocol protocol = (SilcProtocol)context;
1369 SilcServerConnAuthInternalContext *ctx =
1370 (SilcServerConnAuthInternalContext *)protocol->context;
1371 SilcServer server = (SilcServer)ctx->server;
1372 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1373 SilcSocketConnection sock = ctx->sock;
1374 SilcServerEntry id_entry = NULL;
1376 unsigned char *id_string;
1378 SilcIDListData idata;
1379 SilcServerConfigRouter *conn = NULL;
1380 SilcServerConfigConnParams *param = NULL;
1382 SILC_LOG_DEBUG(("Start"));
1384 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1385 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1386 /* Error occured during protocol */
1387 silc_free(ctx->dest_id);
1388 sock->protocol = NULL;
1389 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1391 sock->protocol = protocol;
1393 /* Try reconnecting if configuration wants it */
1394 if (!sconn->no_reconnect) {
1395 silc_schedule_task_add(server->schedule, 0,
1396 silc_server_connect_to_router_retry,
1397 sconn, 0, 1, SILC_TASK_TIMEOUT,
1398 SILC_TASK_PRI_NORMAL);
1405 /* Add a task to the queue. This task receives new connections to the
1406 server. This task remains on the queue until the end of the program. */
1407 if (!server->listenning && !sconn->backup) {
1408 silc_schedule_task_add(server->schedule, server->sock,
1409 silc_server_accept_new_connection,
1410 (void *)server, 0, 0,
1412 SILC_TASK_PRI_NORMAL);
1413 server->listenning = TRUE;
1416 /* Send NEW_SERVER packet to the router. We will become registered
1417 to the SILC network after sending this packet. */
1418 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
1419 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1420 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
1421 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1422 silc_buffer_format(packet,
1423 SILC_STR_UI_SHORT(id_len),
1424 SILC_STR_UI_XNSTRING(id_string, id_len),
1425 SILC_STR_UI_SHORT(strlen(server->server_name)),
1426 SILC_STR_UI_XNSTRING(server->server_name,
1427 strlen(server->server_name)),
1430 /* Send the packet */
1431 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
1432 packet->data, packet->len, TRUE);
1433 silc_buffer_free(packet);
1434 silc_free(id_string);
1436 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
1438 /* Check that we do not have this ID already */
1439 id_entry = silc_idlist_find_server_by_id(server->local_list,
1440 ctx->dest_id, TRUE, NULL);
1442 silc_idcache_del_by_context(server->local_list->servers, id_entry);
1444 id_entry = silc_idlist_find_server_by_id(server->global_list,
1445 ctx->dest_id, TRUE, NULL);
1447 silc_idcache_del_by_context(server->global_list->servers, id_entry);
1450 SILC_LOG_DEBUG(("New server id(%s)",
1451 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1453 /* Add the connected router to global server list. Router is sent
1454 as NULL since it's local to us. */
1455 id_entry = silc_idlist_add_server(server->global_list,
1456 strdup(sock->hostname),
1457 SILC_ROUTER, ctx->dest_id, NULL, sock);
1459 silc_free(ctx->dest_id);
1460 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1461 sock->protocol = NULL;
1462 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1464 sock->protocol = protocol;
1468 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1469 silc_free(sock->user_data);
1470 sock->user_data = (void *)id_entry;
1471 sock->type = SILC_SOCKET_TYPE_ROUTER;
1472 idata = (SilcIDListData)sock->user_data;
1473 idata->status |= (SILC_IDLIST_STATUS_REGISTERED |
1474 SILC_IDLIST_STATUS_LOCAL);
1476 conn = sconn->conn.ref_ptr;
1477 param = &server->config->param;
1478 if (conn && conn->param)
1479 param = conn->param;
1481 /* Perform keepalive. */
1482 silc_socket_set_heartbeat(sock, param->keepalive_secs, server,
1483 silc_server_perform_heartbeat,
1486 /* Register re-key timeout */
1487 idata->rekey->timeout = param->key_exchange_rekey;
1488 silc_schedule_task_add(server->schedule, sock->sock,
1489 silc_server_rekey_callback,
1490 (void *)sock, idata->rekey->timeout, 0,
1491 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1493 if (!sconn->backup) {
1494 /* Mark this router our primary router if we're still standalone */
1495 if (server->standalone) {
1496 SILC_LOG_DEBUG(("This connection is our primary router"));
1497 server->id_entry->router = id_entry;
1498 server->router = id_entry;
1499 server->router->server_type = SILC_ROUTER;
1500 server->standalone = FALSE;
1501 server->backup_primary = FALSE;
1503 /* Announce data if we are not backup router (unless not as primary
1504 currently). Backup router announces later at the end of
1505 resuming protocol. */
1506 if (server->backup_router && server->server_type == SILC_ROUTER) {
1507 SILC_LOG_DEBUG(("Announce data after resume protocol"));
1509 /* If we are router then announce our possible servers. Backup
1510 router announces also global servers. */
1511 if (server->server_type == SILC_ROUTER)
1512 silc_server_announce_servers(server,
1513 server->backup_router ? TRUE : FALSE,
1514 0, SILC_PRIMARY_ROUTE(server));
1516 /* Announce our clients and channels to the router */
1517 silc_server_announce_clients(server, 0, SILC_PRIMARY_ROUTE(server));
1518 silc_server_announce_channels(server, 0, SILC_PRIMARY_ROUTE(server));
1521 /* If we are backup router then this primary router is whom we are
1523 if (server->server_type == SILC_BACKUP_ROUTER)
1524 silc_server_backup_add(server, server->id_entry, sock->ip,
1525 sconn->remote_port, TRUE);
1528 /* Add this server to be our backup router */
1529 id_entry->server_type = SILC_BACKUP_ROUTER;
1530 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1531 sconn->backup_replace_port, FALSE);
1534 sock->protocol = NULL;
1537 /* Call the completion callback to indicate that we've connected to
1539 if (sconn && sconn->callback)
1540 (*sconn->callback)(server, id_entry, sconn->callback_context);
1542 /* Free the temporary connection data context */
1544 silc_server_config_unref(&sconn->conn);
1545 silc_free(sconn->remote_host);
1546 silc_free(sconn->backup_replace_ip);
1549 if (sconn == server->router_conn)
1550 server->router_conn = NULL;
1553 /* Free the protocol object */
1554 if (sock->protocol == protocol)
1555 sock->protocol = NULL;
1556 silc_protocol_free(protocol);
1558 silc_packet_context_free(ctx->packet);
1560 silc_ske_free(ctx->ske);
1561 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1562 silc_free(ctx->auth_data);
1566 /* Host lookup callback that is called after the incoming connection's
1567 IP and FQDN lookup is performed. This will actually check the acceptance
1568 of the incoming connection and will register the key exchange protocol
1569 for this connection. */
1572 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1575 SilcServerKEInternalContext *proto_ctx =
1576 (SilcServerKEInternalContext *)context;
1577 SilcServer server = (SilcServer)proto_ctx->server;
1578 SilcServerConfigClient *cconfig = NULL;
1579 SilcServerConfigServer *sconfig = NULL;
1580 SilcServerConfigRouter *rconfig = NULL;
1581 SilcServerConfigDeny *deny;
1584 /* Check whether we could resolve both IP and FQDN. */
1585 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1586 server->config->require_reverse_lookup)) {
1587 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1588 sock->hostname ? sock->hostname :
1589 sock->ip ? sock->ip : ""));
1590 server->stat.conn_failures++;
1591 silc_server_disconnect_remote(server, sock,
1592 SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
1593 "Unknown host or IP");
1594 silc_free(proto_ctx);
1598 /* Register the connection for network input and output. This sets
1599 that scheduler will listen for incoming packets for this connection
1600 and sets that outgoing packets may be sent to this connection as well.
1601 However, this doesn't set the scheduler for outgoing traffic, it
1602 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1603 later when outgoing data is available. */
1604 context = (void *)server;
1605 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1607 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1610 /* Listenning port */
1611 if (!server->sockets[(SilcUInt32)proto_ctx->context]) {
1612 silc_server_disconnect_remote(server, sock,
1613 SILC_STATUS_ERR_RESOURCE_LIMIT,
1614 "Connection refused");
1615 server->stat.conn_failures++;
1616 silc_free(proto_ctx);
1619 port = server->sockets[(SilcUInt32)proto_ctx->context]->port;
1621 /* Check whether this connection is denied to connect to us. */
1622 deny = silc_server_config_find_denied(server, sock->ip);
1624 deny = silc_server_config_find_denied(server, sock->hostname);
1626 /* The connection is denied */
1627 SILC_LOG_INFO(("Connection %s (%s) is denied",
1628 sock->hostname, sock->ip));
1629 silc_server_disconnect_remote(server, sock,
1630 SILC_STATUS_ERR_BANNED_FROM_SERVER,
1632 server->stat.conn_failures++;
1633 silc_free(proto_ctx);
1637 /* Check whether we have configured this sort of connection at all. We
1638 have to check all configurations since we don't know what type of
1639 connection this is. */
1640 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1641 cconfig = silc_server_config_find_client(server, sock->hostname);
1642 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1643 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1644 if (server->server_type == SILC_ROUTER) {
1645 if (!(rconfig = silc_server_config_find_router_conn(server,
1646 sock->ip, sock->port)))
1647 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1650 if (!cconfig && !sconfig && !rconfig) {
1651 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1653 silc_server_disconnect_remote(server, sock,
1654 SILC_STATUS_ERR_BANNED_FROM_SERVER, NULL);
1655 server->stat.conn_failures++;
1656 silc_free(proto_ctx);
1660 /* The connection is allowed */
1662 /* Set internal context for key exchange protocol. This is
1663 sent as context for the protocol. */
1664 proto_ctx->sock = sock;
1665 proto_ctx->rng = server->rng;
1666 proto_ctx->responder = TRUE;
1667 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1668 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1669 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1671 /* Take flags for key exchange. Since we do not know what type of connection
1672 this is, we go through all found configurations and use the global ones
1673 as well. This will result always into strictest key exchange flags. */
1674 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1675 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1676 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1677 if (server->config->param.key_exchange_pfs)
1678 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1680 /* Prepare the connection for key exchange protocol. We allocate the
1681 protocol but will not start it yet. The connector will be the
1682 initiator of the protocol thus we will wait for initiation from
1683 there before we start the protocol. */
1684 server->stat.auth_attempts++;
1685 SILC_LOG_DEBUG(("Starting key exchange protocol"));
1686 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1687 &sock->protocol, proto_ctx,
1688 silc_server_accept_new_connection_second);
1690 /* Register a timeout task that will be executed if the connector
1691 will not start the key exchange protocol within specified timeout
1692 and the connection will be closed. */
1693 proto_ctx->timeout_task =
1694 silc_schedule_task_add(server->schedule, sock->sock,
1695 silc_server_timeout_remote,
1697 server->config->key_exchange_timeout, 0,
1702 /* Accepts new connections to the server. Accepting new connections are
1703 done in three parts to make it async. */
1705 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1707 SilcServer server = (SilcServer)context;
1708 SilcSocketConnection newsocket;
1709 SilcServerKEInternalContext *proto_ctx;
1712 SILC_LOG_DEBUG(("Accepting new connection"));
1714 server->stat.conn_attempts++;
1716 sock = silc_net_accept_connection(fd);
1718 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1719 server->stat.conn_failures++;
1723 /* Check for maximum allowed connections */
1724 if (sock > server->config->param.connections_max) {
1725 SILC_LOG_ERROR(("Refusing connection, server is full"));
1726 server->stat.conn_failures++;
1727 silc_net_close_connection(sock);
1731 /* Set socket options */
1732 silc_net_set_socket_nonblock(sock);
1733 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1735 /* We don't create a ID yet, since we don't know what type of connection
1736 this is yet. But, we do add the connection to the socket table. */
1737 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1738 server->sockets[sock] = newsocket;
1740 /* Perform asynchronous host lookup. This will lookup the IP and the
1741 FQDN of the remote connection. After the lookup is done the connection
1742 is accepted further. */
1743 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1744 proto_ctx->server = server;
1745 proto_ctx->context = (void *)fd;
1746 silc_socket_host_lookup(newsocket, TRUE,
1747 silc_server_accept_new_connection_lookup,
1748 (void *)proto_ctx, server->schedule);
1751 /* Second part of accepting new connection. Key exchange protocol has been
1752 performed and now it is time to do little connection authentication
1753 protocol to figure out whether this connection is client or server
1754 and whether it has right to access this server (especially server
1755 connections needs to be authenticated). */
1757 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1759 SilcProtocol protocol = (SilcProtocol)context;
1760 SilcServerKEInternalContext *ctx =
1761 (SilcServerKEInternalContext *)protocol->context;
1762 SilcServer server = (SilcServer)ctx->server;
1763 SilcSocketConnection sock = ctx->sock;
1764 SilcServerConnAuthInternalContext *proto_ctx;
1766 SILC_LOG_DEBUG(("Start"));
1768 if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1769 (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1770 /* Error occured during protocol */
1771 SILC_LOG_DEBUG(("Error in key exchange protocol"));
1772 silc_protocol_free(protocol);
1773 sock->protocol = NULL;
1774 silc_ske_free_key_material(ctx->keymat);
1776 silc_packet_context_free(ctx->packet);
1778 silc_ske_free(ctx->ske);
1779 silc_free(ctx->dest_id);
1780 silc_server_config_unref(&ctx->cconfig);
1781 silc_server_config_unref(&ctx->sconfig);
1782 silc_server_config_unref(&ctx->rconfig);
1785 if (!SILC_IS_DISCONNECTING(sock)) {
1786 SILC_LOG_INFO(("Key exchange failed for %s:%d [%s]", sock->hostname,
1788 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1789 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1790 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1792 silc_server_disconnect_remote(server, sock,
1793 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
1797 server->stat.auth_failures++;
1801 /* We now have the key material as the result of the key exchange
1802 protocol. Take the key material into use. Free the raw key material
1803 as soon as we've set them into use. */
1804 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1805 ctx->sock, ctx->keymat,
1806 ctx->ske->prop->cipher,
1807 ctx->ske->prop->pkcs,
1808 ctx->ske->prop->hash,
1809 ctx->ske->prop->hmac,
1810 ctx->ske->prop->group,
1812 SILC_LOG_ERROR(("Error setting key material in use"));
1813 silc_protocol_free(protocol);
1814 sock->protocol = NULL;
1815 silc_ske_free_key_material(ctx->keymat);
1817 silc_packet_context_free(ctx->packet);
1819 silc_ske_free(ctx->ske);
1820 silc_free(ctx->dest_id);
1821 silc_server_config_unref(&ctx->cconfig);
1822 silc_server_config_unref(&ctx->sconfig);
1823 silc_server_config_unref(&ctx->rconfig);
1825 silc_server_disconnect_remote(server, sock,
1826 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1827 server->stat.auth_failures++;
1830 silc_ske_free_key_material(ctx->keymat);
1832 /* Allocate internal context for the authentication protocol. This
1833 is sent as context for the protocol. */
1834 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1835 proto_ctx->server = (void *)server;
1836 proto_ctx->sock = sock;
1837 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1838 proto_ctx->responder = TRUE;
1839 proto_ctx->dest_id_type = ctx->dest_id_type;
1840 proto_ctx->dest_id = ctx->dest_id;
1841 proto_ctx->cconfig = ctx->cconfig;
1842 proto_ctx->sconfig = ctx->sconfig;
1843 proto_ctx->rconfig = ctx->rconfig;
1845 /* Free old protocol as it is finished now */
1846 silc_protocol_free(protocol);
1848 silc_packet_context_free(ctx->packet);
1850 sock->protocol = NULL;
1852 /* Allocate the authentication protocol. This is allocated here
1853 but we won't start it yet. We will be receiving party of this
1854 protocol thus we will wait that connecting party will make
1855 their first move. */
1856 SILC_LOG_DEBUG(("Starting connection authentication protocol"));
1857 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1858 &sock->protocol, proto_ctx,
1859 silc_server_accept_new_connection_final);
1861 /* Register timeout task. If the protocol is not executed inside
1862 this timelimit the connection will be terminated. */
1863 proto_ctx->timeout_task =
1864 silc_schedule_task_add(server->schedule, sock->sock,
1865 silc_server_timeout_remote,
1867 server->config->conn_auth_timeout, 0,
1872 /* After this is called, server don't wait for backup router anymore.
1873 This gets called automatically even after we have backup router
1874 connection established. */
1876 SILC_TASK_CALLBACK(silc_server_backup_router_wait)
1878 SilcServer server = context;
1879 server->wait_backup = FALSE;
1882 /* Final part of accepting new connection. The connection has now
1883 been authenticated and keys has been exchanged. We also know whether
1884 this is client or server connection. */
1886 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1888 SilcProtocol protocol = (SilcProtocol)context;
1889 SilcServerConnAuthInternalContext *ctx =
1890 (SilcServerConnAuthInternalContext *)protocol->context;
1891 SilcServer server = (SilcServer)ctx->server;
1892 SilcSocketConnection sock = ctx->sock;
1893 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1895 SilcServerConfigConnParams *param = &server->config->param;
1897 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1898 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1899 /* Error occured during protocol */
1900 SILC_LOG_DEBUG(("Error during authentication protocol"));
1901 silc_protocol_free(protocol);
1902 sock->protocol = NULL;
1904 silc_packet_context_free(ctx->packet);
1906 silc_ske_free(ctx->ske);
1907 silc_free(ctx->dest_id);
1908 silc_server_config_unref(&ctx->cconfig);
1909 silc_server_config_unref(&ctx->sconfig);
1910 silc_server_config_unref(&ctx->rconfig);
1913 if (!SILC_IS_DISCONNECTING(sock)) {
1914 SILC_LOG_INFO(("Authentication failed for %s:%d [%s]", sock->hostname,
1916 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1917 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1918 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1920 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1923 server->stat.auth_failures++;
1927 entry->data.last_receive = time(NULL);
1929 switch (ctx->conn_type) {
1930 case SILC_SOCKET_TYPE_CLIENT:
1932 SilcClientEntry client;
1933 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1935 /* Verify whether this connection is after all allowed to connect */
1936 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1937 &server->config->param,
1938 conn->param, ctx->ske)) {
1939 server->stat.auth_failures++;
1943 /* If we are primary router and we have backup router configured
1944 but it has not connected to use yet, do not accept any other
1946 if (server->wait_backup && server->server_type == SILC_ROUTER &&
1947 !server->backup_router) {
1948 SilcServerConfigRouter *router;
1949 router = silc_server_config_get_backup_router(server);
1950 if (router && strcmp(server->config->server_info->primary->server_ip,
1952 silc_server_find_socket_by_host(server,
1953 SILC_SOCKET_TYPE_SERVER,
1954 router->backup_replace_ip, 0)) {
1955 SILC_LOG_INFO(("Will not accept connections because we do "
1956 "not have backup router connection established"));
1957 sock->protocol = NULL;
1958 silc_server_disconnect_remote(server, sock,
1959 SILC_STATUS_ERR_PERM_DENIED,
1960 "We do not have connection to backup "
1961 "router established, try later");
1962 silc_free(sock->user_data);
1963 server->stat.auth_failures++;
1965 /* From here on, wait 20 seconds for the backup router to appear. */
1966 silc_schedule_task_add(server->schedule, 0,
1967 silc_server_backup_router_wait,
1968 (void *)server, 20, 0,
1969 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1974 SILC_LOG_DEBUG(("Remote host is client"));
1975 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1978 /* Add the client to the client ID cache. The nickname and Client ID
1979 and other information is created after we have received NEW_CLIENT
1980 packet from client. */
1981 client = silc_idlist_add_client(server->local_list,
1982 NULL, NULL, NULL, NULL, NULL, sock, 0);
1984 SILC_LOG_ERROR(("Could not add new client to cache"));
1985 silc_free(sock->user_data);
1986 sock->protocol = NULL;
1987 silc_server_disconnect_remote(server, sock,
1988 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1989 server->stat.auth_failures++;
1992 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
1995 server->stat.my_clients++;
1996 server->stat.clients++;
1997 server->stat.cell_clients++;
1999 /* Get connection parameters */
2001 param = conn->param;
2003 if (!param->keepalive_secs)
2004 param->keepalive_secs = server->config->param.keepalive_secs;
2006 if (!param->qos && server->config->param.qos) {
2007 param->qos = server->config->param.qos;
2008 param->qos_rate_limit = server->config->param.qos_rate_limit;
2009 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
2010 param->qos_limit_sec = server->config->param.qos_limit_sec;
2011 param->qos_limit_usec = server->config->param.qos_limit_usec;
2014 /* Check if to be anonymous connection */
2015 if (param->anonymous)
2016 client->mode |= SILC_UMODE_ANONYMOUS;
2019 /* Add public key to hash list (for whois using attributes) */
2020 silc_hash_table_add(server->pk_hash,
2021 entry->data.public_key, client);
2023 id_entry = (void *)client;
2026 case SILC_SOCKET_TYPE_SERVER:
2027 case SILC_SOCKET_TYPE_ROUTER:
2029 SilcServerEntry new_server;
2030 bool initiator = FALSE;
2031 bool backup_local = FALSE;
2032 bool backup_router = FALSE;
2033 char *backup_replace_ip = NULL;
2034 SilcUInt16 backup_replace_port = 0;
2035 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
2036 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
2038 /* If we are backup router and this is incoming server connection
2039 and we do not have connection to primary router, do not allow
2041 if (server->server_type == SILC_BACKUP_ROUTER &&
2042 ctx->conn_type == SILC_SOCKET_TYPE_SERVER &&
2043 !SILC_PRIMARY_ROUTE(server)) {
2044 SILC_LOG_INFO(("Will not accept server connection because we do "
2045 "not have primary router connection established"));
2046 sock->protocol = NULL;
2047 silc_server_disconnect_remote(server, sock,
2048 SILC_STATUS_ERR_PERM_DENIED,
2049 "We do not have connection to primary "
2050 "router established, try later");
2051 silc_free(sock->user_data);
2052 server->stat.auth_failures++;
2056 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
2057 /* Verify whether this connection is after all allowed to connect */
2058 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
2059 &server->config->param,
2060 rconn ? rconn->param : NULL,
2062 silc_free(sock->user_data);
2063 server->stat.auth_failures++;
2069 param = rconn->param;
2071 if (!param->keepalive_secs)
2072 param->keepalive_secs = server->config->param.keepalive_secs;
2074 if (!param->qos && server->config->param.qos) {
2075 param->qos = server->config->param.qos;
2076 param->qos_rate_limit = server->config->param.qos_rate_limit;
2077 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
2078 param->qos_limit_sec = server->config->param.qos_limit_sec;
2079 param->qos_limit_usec = server->config->param.qos_limit_usec;
2083 initiator = rconn->initiator;
2084 backup_local = rconn->backup_local;
2085 backup_router = rconn->backup_router;
2086 backup_replace_ip = rconn->backup_replace_ip;
2087 backup_replace_port = rconn->backup_replace_port;
2091 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
2092 /* Verify whether this connection is after all allowed to connect */
2093 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
2094 &server->config->param,
2095 sconn ? sconn->param : NULL,
2097 silc_free(sock->user_data);
2098 server->stat.auth_failures++;
2103 param = sconn->param;
2105 if (!param->keepalive_secs)
2106 param->keepalive_secs = server->config->param.keepalive_secs;
2108 if (!param->qos && server->config->param.qos) {
2109 param->qos = server->config->param.qos;
2110 param->qos_rate_limit = server->config->param.qos_rate_limit;
2111 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
2112 param->qos_limit_sec = server->config->param.qos_limit_sec;
2113 param->qos_limit_usec = server->config->param.qos_limit_usec;
2117 backup_router = sconn->backup_router;
2121 /* If we are primary router and we have backup router configured
2122 but it has not connected to use yet, do not accept any other
2124 if (server->wait_backup && server->server_type == SILC_ROUTER &&
2125 !server->backup_router && !backup_router) {
2126 SilcServerConfigRouter *router;
2127 router = silc_server_config_get_backup_router(server);
2128 if (router && strcmp(server->config->server_info->primary->server_ip,
2130 silc_server_find_socket_by_host(server,
2131 SILC_SOCKET_TYPE_SERVER,
2132 router->backup_replace_ip, 0)) {
2133 SILC_LOG_INFO(("Will not accept connections because we do "
2134 "not have backup router connection established"));
2135 sock->protocol = NULL;
2136 silc_server_disconnect_remote(server, sock,
2137 SILC_STATUS_ERR_PERM_DENIED,
2138 "We do not have connection to backup "
2139 "router established, try later");
2140 silc_free(sock->user_data);
2141 server->stat.auth_failures++;
2143 /* From here on, wait 20 seconds for the backup router to appear. */
2144 silc_schedule_task_add(server->schedule, 0,
2145 silc_server_backup_router_wait,
2146 (void *)server, 20, 0,
2147 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2152 SILC_LOG_DEBUG(("Remote host is %s",
2153 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2154 "server" : (backup_router ?
2155 "backup router" : "router")));
2156 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
2157 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2158 "server" : (backup_router ?
2159 "backup router" : "router")));
2161 /* Add the server into server cache. The server name and Server ID
2162 is updated after we have received NEW_SERVER packet from the
2163 server. We mark ourselves as router for this server if we really
2166 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2167 server->local_list : (backup_router ?
2168 server->local_list :
2169 server->global_list)),
2171 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2172 SILC_SERVER : SILC_ROUTER),
2174 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2175 server->id_entry : (backup_router ?
2176 server->id_entry : NULL)),
2179 SILC_LOG_ERROR(("Could not add new server to cache"));
2180 silc_free(sock->user_data);
2181 sock->protocol = NULL;
2182 silc_server_disconnect_remote(server, sock,
2183 SILC_STATUS_ERR_AUTH_FAILED, NULL);
2184 server->stat.auth_failures++;
2187 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
2189 id_entry = (void *)new_server;
2191 /* If the incoming connection is router and marked as backup router
2192 then add it to be one of our backups */
2193 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
2194 /* Change it back to SERVER type since that's what it really is. */
2196 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
2197 new_server->server_type = SILC_BACKUP_ROUTER;
2199 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
2200 ("Backup router %s is now online",
2203 /* Remove the backup waiting with timeout */
2204 silc_schedule_task_add(server->schedule, 0,
2205 silc_server_backup_router_wait,
2206 (void *)server, 10, 0,
2207 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2211 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
2212 server->stat.my_servers++;
2214 server->stat.my_routers++;
2215 server->stat.routers++;
2217 server->stat.servers++;
2219 /* Check whether this connection is to be our primary router connection
2220 if we do not already have the primary route. */
2221 if (!backup_router &&
2222 server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
2223 if (silc_server_config_is_primary_route(server) && !initiator)
2226 SILC_LOG_DEBUG(("We are not standalone server anymore"));
2227 server->standalone = FALSE;
2228 if (!server->id_entry->router) {
2229 server->id_entry->router = id_entry;
2230 server->router = id_entry;
2241 sock->type = ctx->conn_type;
2243 /* Add the common data structure to the ID entry. */
2244 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
2246 /* Add to sockets internal pointer for fast referencing */
2247 silc_free(sock->user_data);
2248 sock->user_data = id_entry;
2250 /* Connection has been fully established now. Everything is ok. */
2251 SILC_LOG_DEBUG(("New connection authenticated"));
2253 /* Perform keepalive. */
2254 if (param->keepalive_secs)
2255 silc_socket_set_heartbeat(sock, param->keepalive_secs, server,
2256 silc_server_perform_heartbeat,
2259 /* Perform Quality of Service */
2261 silc_socket_set_qos(sock, param->qos_rate_limit, param->qos_bytes_limit,
2262 param->qos_limit_sec, param->qos_limit_usec,
2266 if (sock->protocol == protocol)
2267 silc_protocol_free(protocol);
2269 silc_packet_context_free(ctx->packet);
2271 silc_ske_free(ctx->ske);
2272 silc_free(ctx->dest_id);
2273 silc_server_config_unref(&ctx->cconfig);
2274 silc_server_config_unref(&ctx->sconfig);
2275 silc_server_config_unref(&ctx->rconfig);
2277 sock->protocol = NULL;
2280 /* This function is used to read packets from network and send packets to
2281 network. This is usually a generic task. */
2283 SILC_TASK_CALLBACK(silc_server_packet_process)
2285 SilcServer server = (SilcServer)context;
2286 SilcSocketConnection sock = server->sockets[fd];
2287 SilcIDListData idata;
2288 SilcCipher cipher = NULL;
2289 SilcHmac hmac = NULL;
2290 SilcUInt32 sequence = 0;
2291 bool local_is_router;
2295 SILC_LOG_DEBUG(("Unknown socket connection"));
2299 /* Packet sending */
2301 if (type == SILC_TASK_WRITE) {
2302 /* Do not send data to disconnected connection */
2303 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2304 SILC_LOG_DEBUG(("Disconnected socket connection, cannot send"));
2305 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
2306 SILC_UNSET_OUTBUF_PENDING(sock);
2307 silc_buffer_clear(sock->outbuf);
2311 server->stat.packets_sent++;
2313 /* Send the packet */
2314 ret = silc_packet_send(sock, TRUE);
2316 /* If returned -2 could not write to connection now, will do
2321 /* The packet has been sent and now it is time to set the connection
2322 back to only for input. When there is again some outgoing data
2323 available for this connection it will be set for output as well.
2324 This call clears the output setting and sets it only for input. */
2325 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
2326 SILC_UNSET_OUTBUF_PENDING(sock);
2327 silc_buffer_clear(sock->outbuf);
2330 SILC_LOG_ERROR(("Error sending packet to connection "
2331 "%s:%d [%s]", sock->hostname, sock->port,
2332 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2333 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2334 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2337 if (sock->user_data) {
2338 /* If backup then mark that resuming will not be allowed */
2339 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2340 sock->type == SILC_SOCKET_TYPE_SERVER) {
2341 SilcServerEntry server_entry = sock->user_data;
2342 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2343 server->backup_closed = TRUE;
2346 silc_server_free_sock_user_data(server, sock, NULL);
2348 SILC_SET_DISCONNECTING(sock);
2349 silc_server_close_connection(server, sock);
2354 /* Packet receiving */
2356 /* Read some data from connection */
2357 ret = silc_packet_receive(sock);
2361 SILC_LOG_ERROR(("Error receiving packet from connection "
2362 "%s:%d [%s] %s", sock->hostname, sock->port,
2363 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2364 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2365 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2366 "Router"), strerror(errno)));
2368 if (sock->user_data) {
2369 /* If backup then mark that resuming will not be allowed */
2370 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2371 sock->type == SILC_SOCKET_TYPE_SERVER) {
2372 SilcServerEntry server_entry = sock->user_data;
2373 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2374 server->backup_closed = TRUE;
2377 silc_server_free_sock_user_data(server, sock, NULL);
2379 SILC_SET_DISCONNECTING(sock);
2380 silc_server_close_connection(server, sock);
2387 SILC_LOG_DEBUG(("Read EOF"));
2389 /* If connection is disconnecting already we will finally
2390 close the connection */
2391 if (SILC_IS_DISCONNECTING(sock)) {
2392 if (sock->user_data)
2393 silc_server_free_sock_user_data(server, sock, NULL);
2394 silc_server_close_connection(server, sock);
2398 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
2400 if (sock->user_data) {
2403 /* If backup disconnected then mark that resuming will not be allowed */
2404 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2405 sock->type == SILC_SOCKET_TYPE_SERVER && sock->user_data) {
2406 SilcServerEntry server_entry = sock->user_data;
2407 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2408 server->backup_closed = TRUE;
2411 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
2412 silc_server_free_sock_user_data(server, sock, tmp);
2414 silc_server_free_sock_user_data(server, sock, NULL);
2415 } else if (server->router_conn && server->router_conn->sock == sock &&
2416 !server->router && server->standalone) {
2417 silc_server_create_connections(server);
2420 SILC_SET_DISCONNECTING(sock);
2421 silc_server_close_connection(server, sock);
2425 /* If connection is disconnecting or disconnected we will ignore
2427 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2428 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
2432 /* Get keys and stuff from ID entry */
2433 idata = (SilcIDListData)sock->user_data;
2435 cipher = idata->receive_key;
2436 hmac = idata->hmac_receive;
2437 sequence = idata->psn_receive;
2440 /* Then, process the packet. This will call the parser that will then
2441 decrypt and parse the packet. */
2443 local_is_router = (server->server_type == SILC_ROUTER);
2445 /* If socket connection is our primary, we are backup and we are doing
2446 backup resuming, we won't process the packet as being a router
2447 (affects channel message decryption). */
2448 if (server->backup_router && SILC_SERVER_IS_BACKUP(sock) &&
2449 SILC_PRIMARY_ROUTE(server) == sock)
2450 local_is_router = FALSE;
2452 ret = silc_packet_receive_process(sock, local_is_router,
2453 cipher, hmac, sequence,
2454 silc_server_packet_parse, server);
2456 /* If processing failed the connection is closed. */
2458 /* On packet processing errors we may close our primary router
2459 connection but won't become primary router if we are the backup
2460 since this is local error condition. */
2461 if (SILC_PRIMARY_ROUTE(server) == sock && server->backup_router)
2462 server->backup_noswitch = TRUE;
2464 if (sock->user_data) {
2465 /* If we are router and backup errorred then mark that resuming
2466 will not be allowed */
2467 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2468 sock->type == SILC_SOCKET_TYPE_SERVER) {
2469 SilcServerEntry server_entry = sock->user_data;
2470 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2471 server->backup_closed = TRUE;
2474 silc_server_free_sock_user_data(server, sock, NULL);
2476 SILC_SET_DISCONNECTING(sock);
2477 silc_server_close_connection(server, sock);
2481 /* Parses whole packet, received earlier. */
2483 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
2485 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
2486 SilcServer server = (SilcServer)parse_ctx->context;
2487 SilcSocketConnection sock = parse_ctx->sock;
2488 SilcPacketContext *packet = parse_ctx->packet;
2489 SilcIDListData idata = (SilcIDListData)sock->user_data;
2492 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2493 SILC_LOG_DEBUG(("Connection is disconnected"));
2497 server->stat.packets_received++;
2499 /* Parse the packet */
2500 if (parse_ctx->normal)
2501 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
2503 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
2505 /* If entry is disabled ignore what we got. */
2506 if (idata && idata->status & SILC_IDLIST_STATUS_DISABLED &&
2507 ret != SILC_PACKET_HEARTBEAT && ret != SILC_PACKET_RESUME_ROUTER &&
2508 ret != SILC_PACKET_REKEY && ret != SILC_PACKET_REKEY_DONE) {
2509 SILC_LOG_DEBUG(("Connection is disabled"));
2513 if (ret == SILC_PACKET_NONE) {
2514 SILC_LOG_DEBUG(("Error parsing packet"));
2518 /* Check that the the current client ID is same as in the client's packet. */
2519 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
2520 SilcClientEntry client = (SilcClientEntry)sock->user_data;
2521 if (client && client->id && packet->src_id) {
2522 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
2523 packet->src_id_type);
2524 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
2526 SILC_LOG_DEBUG(("Packet source is not same as sender"));
2533 if (server->server_type == SILC_ROUTER) {
2534 /* Route the packet if it is not destined to us. Other ID types but
2535 server are handled separately after processing them. */
2536 if (packet->dst_id && !(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
2537 packet->dst_id_type == SILC_ID_SERVER &&
2538 sock->type != SILC_SOCKET_TYPE_CLIENT &&
2539 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
2541 /* Route the packet to fastest route for the destination ID */
2542 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
2543 packet->dst_id_type);
2546 silc_server_packet_route(server,
2547 silc_server_route_get(server, id,
2548 packet->dst_id_type),
2555 /* Parse the incoming packet type */
2556 silc_server_packet_parse_type(server, sock, packet);
2558 /* Broadcast packet if it is marked as broadcast packet and it is
2559 originated from router and we are router. */
2560 if (server->server_type == SILC_ROUTER &&
2561 sock->type == SILC_SOCKET_TYPE_ROUTER &&
2562 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
2563 /* Broadcast to our primary route */
2564 silc_server_packet_broadcast(server, SILC_PRIMARY_ROUTE(server), packet);
2566 /* If we have backup routers then we need to feed all broadcast
2567 data to those servers. */
2568 silc_server_backup_broadcast(server, sock, packet);
2572 silc_packet_context_free(packet);
2573 silc_free(parse_ctx);
2576 /* Parser callback called by silc_packet_receive_process. This merely
2577 registers timeout that will handle the actual parsing when appropriate. */
2579 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
2582 SilcServer server = (SilcServer)context;
2583 SilcSocketConnection sock = parser_context->sock;
2584 SilcIDListData idata = (SilcIDListData)sock->user_data;
2588 idata->psn_receive = parser_context->packet->sequence + 1;
2590 /* If protocol for this connection is key exchange or rekey then we'll
2591 process all packets synchronously, since there might be packets in
2592 queue that we are not able to decrypt without first processing the
2593 packets before them. */
2594 if (sock->protocol && sock->protocol->protocol &&
2595 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2596 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2597 silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2600 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2601 SILC_LOG_DEBUG(("Connection is disconnected"));
2605 /* Reprocess data since we'll return FALSE here. This is because
2606 the idata->receive_key might have become valid in the last packet
2607 and we want to call this processor with valid cipher. */
2609 ret = silc_packet_receive_process(
2610 sock, server->server_type == SILC_ROUTER,
2612 idata->hmac_receive, idata->psn_receive,
2613 silc_server_packet_parse, server);
2615 ret = silc_packet_receive_process(
2616 sock, server->server_type == SILC_ROUTER,
2618 silc_server_packet_parse, server);
2621 /* On packet processing errors we may close our primary router
2622 connection but won't become primary router if we are the backup
2623 since this is local error condition. */
2624 if (SILC_PRIMARY_ROUTE(server) == sock && server->backup_router)
2625 server->backup_noswitch = TRUE;
2627 if (sock->user_data)
2628 silc_server_free_sock_user_data(server, sock, NULL);
2629 SILC_SET_DISCONNECTING(sock);
2630 silc_server_close_connection(server, sock);
2636 switch (sock->type) {
2637 case SILC_SOCKET_TYPE_UNKNOWN:
2638 case SILC_SOCKET_TYPE_CLIENT:
2639 /* Parse the packet with timeout */
2640 silc_schedule_task_add(server->schedule, sock->sock,
2641 silc_server_packet_parse_real,
2642 (void *)parser_context, 0, 100000,
2644 SILC_TASK_PRI_NORMAL);
2646 case SILC_SOCKET_TYPE_SERVER:
2647 case SILC_SOCKET_TYPE_ROUTER:
2648 /* Packets from servers are parsed immediately */
2649 silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2657 /* Parses the packet type and calls what ever routines the packet type
2658 requires. This is done for all incoming packets. */
2660 void silc_server_packet_parse_type(SilcServer server,
2661 SilcSocketConnection sock,
2662 SilcPacketContext *packet)
2664 SilcPacketType type = packet->type;
2665 SilcIDListData idata = (SilcIDListData)sock->user_data;
2667 SILC_LOG_DEBUG(("Received %s packet [flags %d]",
2668 silc_get_packet_name(type), packet->flags));
2670 /* Parse the packet type */
2672 case SILC_PACKET_DISCONNECT:
2675 char *message = NULL;
2677 if (packet->flags & SILC_PACKET_FLAG_LIST)
2679 if (packet->buffer->len < 1)
2682 status = (SilcStatus)packet->buffer->data[0];
2683 if (packet->buffer->len > 1 &&
2684 silc_utf8_valid(packet->buffer->data + 1, packet->buffer->len - 1))
2685 message = silc_memdup(packet->buffer->data + 1,
2686 packet->buffer->len - 1);
2688 SILC_LOG_INFO(("Disconnected by %s (%s): %s (%d) %s",
2689 sock->ip, sock->hostname,
2690 silc_get_status_message(status), status,
2691 message ? message : ""));
2694 /* Do not switch to backup in case of error */
2695 server->backup_noswitch = (status == SILC_STATUS_OK ? FALSE : TRUE);
2697 /* If backup disconnected then mark that resuming will not be allowed */
2698 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2699 sock->type == SILC_SOCKET_TYPE_SERVER && sock->user_data) {
2700 SilcServerEntry server_entry = sock->user_data;
2701 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2702 server->backup_closed = TRUE;
2705 /* Handle the disconnection from our end too */
2706 if (sock->user_data && SILC_IS_LOCAL(sock->user_data))
2707 silc_server_free_sock_user_data(server, sock, NULL);
2708 SILC_SET_DISCONNECTING(sock);
2709 silc_server_close_connection(server, sock);
2710 server->backup_noswitch = FALSE;
2714 case SILC_PACKET_SUCCESS:
2716 * Success received for something. For now we can have only
2717 * one protocol for connection executing at once hence this
2718 * success message is for whatever protocol is executing currently.
2720 if (packet->flags & SILC_PACKET_FLAG_LIST)
2723 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2726 case SILC_PACKET_FAILURE:
2728 * Failure received for something. For now we can have only
2729 * one protocol for connection executing at once hence this
2730 * failure message is for whatever protocol is executing currently.
2732 if (packet->flags & SILC_PACKET_FLAG_LIST)
2735 /* Check for failure START_USE from backup router */
2736 if (server->server_type == SILC_SERVER &&
2737 server->backup_primary && packet->buffer->len == 4) {
2739 SILC_GET32_MSB(type, packet->buffer->data);
2740 if (type == SILC_SERVER_BACKUP_START_USE) {
2741 /* Attempt to reconnect to primary */
2742 SILC_LOG_DEBUG(("Received failed START_USE from backup %s", sock->ip));
2744 /* Default action is to disconnect from backup and reconnect to
2745 primary. Since this failure can happen during switching to
2746 backup (backup might have not noticed the primary going down yet),
2747 we will wait a while and keep sending START_USE to backup.
2748 Only after that we'll give up. */
2749 if (server->router == sock->user_data &&
2750 (time(0) - server->router_connect) < 30) {
2751 SILC_LOG_DEBUG(("Resending START_USE to backup router"));
2752 silc_server_backup_send_start_use(server, sock, FALSE);
2756 /* If backup is our primary, disconnect now. */
2757 if (server->router == sock->user_data) {
2758 if (sock->user_data)
2759 silc_server_free_sock_user_data(server, sock, NULL);
2760 SILC_SET_DISCONNECTING(sock);
2761 silc_server_close_connection(server, sock);
2765 silc_server_create_connections(server);
2769 /* Execute protocol */
2770 if (sock->protocol) {
2771 sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
2772 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2777 case SILC_PACKET_REJECT:
2778 if (packet->flags & SILC_PACKET_FLAG_LIST)
2783 case SILC_PACKET_NOTIFY:
2785 * Received notify packet. Server can receive notify packets from
2786 * router. Server then relays the notify messages to clients if needed.
2788 if (packet->flags & SILC_PACKET_FLAG_LIST)
2789 silc_server_notify_list(server, sock, packet);
2791 silc_server_notify(server, sock, packet);
2797 case SILC_PACKET_CHANNEL_MESSAGE:
2799 * Received channel message. Channel messages are special packets
2800 * (although probably most common ones) thus they are handled
2803 if (packet->flags & SILC_PACKET_FLAG_LIST)
2805 idata->last_receive = time(NULL);
2806 silc_server_channel_message(server, sock, packet);
2809 case SILC_PACKET_CHANNEL_KEY:
2811 * Received key for channel. As channels are created by the router
2812 * the keys are as well. We will distribute the key to all of our
2813 * locally connected clients on the particular channel. Router
2814 * never receives this channel and thus is ignored.
2816 if (packet->flags & SILC_PACKET_FLAG_LIST)
2818 silc_server_channel_key(server, sock, packet);
2824 case SILC_PACKET_COMMAND:
2826 * Recived command. Processes the command request and allocates the
2827 * command context and calls the command.
2829 if (packet->flags & SILC_PACKET_FLAG_LIST)
2831 silc_server_command_process(server, sock, packet);
2834 case SILC_PACKET_COMMAND_REPLY:
2836 * Received command reply packet. Received command reply to command. It
2837 * may be reply to command sent by us or reply to command sent by client
2838 * that we've routed further.
2840 if (packet->flags & SILC_PACKET_FLAG_LIST)
2842 silc_server_command_reply(server, sock, packet);
2846 * Private Message packets
2848 case SILC_PACKET_PRIVATE_MESSAGE:
2850 * Received private message packet. The packet is coming from either
2853 if (packet->flags & SILC_PACKET_FLAG_LIST)
2855 idata->last_receive = time(NULL);
2856 silc_server_private_message(server, sock, packet);
2859 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2861 * Private message key packet.
2863 if (packet->flags & SILC_PACKET_FLAG_LIST)
2865 silc_server_private_message_key(server, sock, packet);
2869 * Key Exchange protocol packets
2871 case SILC_PACKET_KEY_EXCHANGE:
2872 if (packet->flags & SILC_PACKET_FLAG_LIST)
2875 if (sock->protocol && sock->protocol->protocol &&
2876 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2877 SilcServerKEInternalContext *proto_ctx =
2878 (SilcServerKEInternalContext *)sock->protocol->context;
2880 proto_ctx->packet = silc_packet_context_dup(packet);
2882 /* Let the protocol handle the packet */
2883 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2885 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2886 "protocol active (%s:%d [%s]).", sock->hostname,
2888 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2889 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2890 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2895 case SILC_PACKET_KEY_EXCHANGE_1:
2896 if (packet->flags & SILC_PACKET_FLAG_LIST)
2899 if (sock->protocol && sock->protocol->protocol &&
2900 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2901 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2903 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2904 SilcServerRekeyInternalContext *proto_ctx =
2905 (SilcServerRekeyInternalContext *)sock->protocol->context;
2907 if (proto_ctx->packet)
2908 silc_packet_context_free(proto_ctx->packet);
2910 proto_ctx->packet = silc_packet_context_dup(packet);
2912 /* Let the protocol handle the packet */
2913 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2915 SilcServerKEInternalContext *proto_ctx =
2916 (SilcServerKEInternalContext *)sock->protocol->context;
2918 if (proto_ctx->packet)
2919 silc_packet_context_free(proto_ctx->packet);
2921 proto_ctx->packet = silc_packet_context_dup(packet);
2922 proto_ctx->dest_id_type = packet->src_id_type;
2923 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2924 packet->src_id_type);
2925 if (!proto_ctx->dest_id)
2928 /* Let the protocol handle the packet */
2929 silc_protocol_execute(sock->protocol, server->schedule,
2933 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2934 "protocol active (%s:%d [%s]).", sock->hostname,
2936 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2937 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2938 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2943 case SILC_PACKET_KEY_EXCHANGE_2:
2944 if (packet->flags & SILC_PACKET_FLAG_LIST)
2947 if (sock->protocol && sock->protocol->protocol &&
2948 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2949 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2951 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2952 SilcServerRekeyInternalContext *proto_ctx =
2953 (SilcServerRekeyInternalContext *)sock->protocol->context;
2955 if (proto_ctx->packet)
2956 silc_packet_context_free(proto_ctx->packet);
2958 proto_ctx->packet = silc_packet_context_dup(packet);
2960 /* Let the protocol handle the packet */
2961 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2963 SilcServerKEInternalContext *proto_ctx =
2964 (SilcServerKEInternalContext *)sock->protocol->context;
2966 if (proto_ctx->packet)
2967 silc_packet_context_free(proto_ctx->packet);
2969 proto_ctx->packet = silc_packet_context_dup(packet);
2970 proto_ctx->dest_id_type = packet->src_id_type;
2971 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2972 packet->src_id_type);
2973 if (!proto_ctx->dest_id)
2976 /* Let the protocol handle the packet */
2977 silc_protocol_execute(sock->protocol, server->schedule,
2981 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2982 "protocol active (%s:%d [%s]).", sock->hostname,
2984 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2985 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2986 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2991 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2993 * Connection authentication request packet. When we receive this packet
2994 * we will send to the other end information about our mandatory
2995 * authentication method for the connection. This packet maybe received
2998 if (packet->flags & SILC_PACKET_FLAG_LIST)
3000 silc_server_connection_auth_request(server, sock, packet);
3004 * Connection Authentication protocol packets
3006 case SILC_PACKET_CONNECTION_AUTH:
3007 /* Start of the authentication protocol. We receive here the
3008 authentication data and will verify it. */
3009 if (packet->flags & SILC_PACKET_FLAG_LIST)
3012 if (sock->protocol && sock->protocol->protocol->type
3013 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
3015 SilcServerConnAuthInternalContext *proto_ctx =
3016 (SilcServerConnAuthInternalContext *)sock->protocol->context;
3018 proto_ctx->packet = silc_packet_context_dup(packet);
3020 /* Let the protocol handle the packet */
3021 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
3023 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
3024 "protocol active (%s:%d [%s]).", sock->hostname,
3026 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
3027 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
3028 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
3033 case SILC_PACKET_NEW_ID:
3035 * Received New ID packet. This includes some new ID that has been
3036 * created. It may be for client, server or channel. This is the way
3037 * to distribute information about new registered entities in the
3040 if (packet->flags & SILC_PACKET_FLAG_LIST)
3041 silc_server_new_id_list(server, sock, packet);
3043 silc_server_new_id(server, sock, packet);
3046 case SILC_PACKET_NEW_CLIENT:
3048 * Received new client packet. This includes client information that
3049 * we will use to create initial client ID. After creating new
3050 * ID we will send it to the client.
3052 if (packet->flags & SILC_PACKET_FLAG_LIST)
3054 silc_server_new_client(server, sock, packet);
3057 case SILC_PACKET_NEW_SERVER:
3059 * Received new server packet. This includes Server ID and some other
3060 * information that we may save. This is received after server has
3063 if (packet->flags & SILC_PACKET_FLAG_LIST)
3065 silc_server_new_server(server, sock, packet);
3068 case SILC_PACKET_NEW_CHANNEL:
3070 * Received new channel packet. Information about new channel in the
3071 * network are distributed using this packet.
3073 if (packet->flags & SILC_PACKET_FLAG_LIST)
3074 silc_server_new_channel_list(server, sock, packet);
3076 silc_server_new_channel(server, sock, packet);
3079 case SILC_PACKET_HEARTBEAT:
3081 * Received heartbeat.
3083 if (packet->flags & SILC_PACKET_FLAG_LIST)
3087 case SILC_PACKET_KEY_AGREEMENT:
3089 * Received heartbeat.
3091 if (packet->flags & SILC_PACKET_FLAG_LIST)
3093 silc_server_key_agreement(server, sock, packet);
3096 case SILC_PACKET_REKEY:
3098 * Received re-key packet. The sender wants to regenerate the session
3101 if (packet->flags & SILC_PACKET_FLAG_LIST)
3103 silc_server_rekey(server, sock, packet);
3106 case SILC_PACKET_REKEY_DONE:
3108 * The re-key is done.
3110 if (packet->flags & SILC_PACKET_FLAG_LIST)
3113 if (sock->protocol && sock->protocol->protocol &&
3114 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
3116 SilcServerRekeyInternalContext *proto_ctx =
3117 (SilcServerRekeyInternalContext *)sock->protocol->context;
3119 if (proto_ctx->packet)
3120 silc_packet_context_free(proto_ctx->packet);
3122 proto_ctx->packet = silc_packet_context_dup(packet);
3124 /* Let the protocol handle the packet */
3125 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
3127 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
3128 "protocol active (%s:%d [%s]).", sock->hostname,
3130 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
3131 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
3132 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
3137 case SILC_PACKET_FTP:
3139 if (packet->flags & SILC_PACKET_FLAG_LIST)
3141 silc_server_ftp(server, sock, packet);
3144 case SILC_PACKET_RESUME_CLIENT:
3146 if (packet->flags & SILC_PACKET_FLAG_LIST)
3148 silc_server_resume_client(server, sock, packet);
3151 case SILC_PACKET_RESUME_ROUTER:
3152 /* Resume router packet received. This packet is received for backup
3153 router resuming protocol. */
3154 if (packet->flags & SILC_PACKET_FLAG_LIST)
3156 silc_server_backup_resume_router(server, sock, packet);
3160 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
3165 /* Creates connection to a remote router. */
3167 void silc_server_create_connection(SilcServer server,
3168 const char *remote_host, SilcUInt32 port)
3170 SilcServerConnection sconn;
3172 /* Allocate connection object for hold connection specific stuff. */
3173 sconn = silc_calloc(1, sizeof(*sconn));
3174 sconn->remote_host = strdup(remote_host);
3175 sconn->remote_port = port;
3176 sconn->no_reconnect = TRUE;
3178 silc_schedule_task_add(server->schedule, 0,
3179 silc_server_connect_router,
3180 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
3181 SILC_TASK_PRI_NORMAL);
3184 SILC_TASK_CALLBACK(silc_server_close_connection_final)
3186 SilcServer server = app_context;
3187 SilcSocketConnection sock = context;
3189 SILC_LOG_DEBUG(("Deleting socket %p", sock));
3191 /* Close the actual connection */
3192 silc_net_close_connection(sock->sock);
3193 server->sockets[sock->sock] = NULL;
3195 /* We won't listen for this connection anymore */
3196 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
3197 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
3199 silc_socket_free(sock);
3202 /* Closes connection to socket connection */
3204 void silc_server_close_connection(SilcServer server,
3205 SilcSocketConnection sock)
3209 if (SILC_IS_DISCONNECTED(sock)) {
3210 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
3211 silc_schedule_task_add(server->schedule, sock->sock,
3212 silc_server_close_connection_final,
3213 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
3214 SILC_TASK_PRI_NORMAL);
3215 server->sockets[sock->sock] = NULL;
3219 /* If any protocol is active cancel its execution. It will call
3220 the final callback which will finalize the disconnection. */
3221 if (sock->protocol && sock->protocol->protocol &&
3222 sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3223 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3224 silc_protocol_cancel(sock->protocol, server->schedule);
3225 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3226 silc_protocol_execute_final(sock->protocol, server->schedule);
3227 sock->protocol = NULL;
3231 memset(tmp, 0, sizeof(tmp));
3232 silc_socket_get_error(sock, tmp, sizeof(tmp));
3233 SILC_LOG_INFO(("Closing connection %s:%d [%s] %s", sock->hostname,
3235 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
3236 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
3237 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
3238 "Router"), tmp[0] ? tmp : ""));
3240 SILC_SET_DISCONNECTED(sock);
3241 silc_socket_set_qos(sock, 0, 0, 0, 0, NULL);
3242 silc_schedule_task_add(server->schedule, sock->sock,
3243 silc_server_close_connection_final,
3244 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
3245 SILC_TASK_PRI_NORMAL);
3246 server->sockets[sock->sock] = NULL;
3249 /* Sends disconnect message to remote connection and disconnects the
3250 connection. NOTE: If this is called from protocol callback
3251 then sock->protocol must be set NULL before calling this, since
3252 this routine dispatches protocol callbacks too. */
3254 void silc_server_disconnect_remote(SilcServer server,
3255 SilcSocketConnection sock,
3256 SilcStatus status, ...)
3259 unsigned char buf[512];
3267 if (SILC_IS_DISCONNECTING(sock)) {
3268 SILC_SET_DISCONNECTED(sock);
3269 silc_server_close_connection(server, sock);
3273 memset(buf, 0, sizeof(buf));
3274 va_start(ap, status);
3275 cp = va_arg(ap, char *);
3277 vsnprintf(buf, sizeof(buf) - 1, cp, ap);
3282 SILC_LOG_DEBUG(("Disconnecting remote host"));
3284 /* Notify remote end that the conversation is over. The notify message
3285 is tried to be sent immediately. */
3289 len += silc_utf8_encoded_len(buf, strlen(buf), SILC_STRING_ASCII);
3291 buffer = silc_buffer_alloc_size(len);
3295 buffer->data[0] = status;
3297 silc_utf8_encode(buf, strlen(buf), SILC_STRING_ASCII, buffer->data + 1,
3299 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
3300 buffer->data, buffer->len, TRUE);
3301 silc_buffer_free(buffer);
3304 silc_server_packet_queue_purge(server, sock);
3306 /* Mark the connection to be disconnected */
3307 SILC_SET_DISCONNECTING(sock);
3308 silc_server_close_connection(server, sock);
3311 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
3313 SilcServer server = app_context;
3314 SilcClientEntry client = context;
3316 assert(!silc_hash_table_count(client->channels));
3318 silc_idlist_del_data(client);
3319 silc_idcache_purge_by_context(server->local_list->clients, client);
3322 /* Frees client data and notifies about client's signoff. */
3324 void silc_server_free_client_data(SilcServer server,
3325 SilcSocketConnection sock,
3326 SilcClientEntry client,
3328 const char *signoff)
3330 SILC_LOG_DEBUG(("Freeing client data"));
3332 /* If there is pending outgoing data for the client then purge it
3333 to the network before removing the client entry. */
3334 silc_server_packet_queue_purge(server, sock);
3337 /* Check if anyone is watching this nickname */
3338 if (server->server_type == SILC_ROUTER)
3339 silc_server_check_watcher_list(server, client, NULL,
3340 SILC_NOTIFY_TYPE_SIGNOFF);
3342 /* Send SIGNOFF notify to routers. */
3344 silc_server_send_notify_signoff(server, SILC_PRIMARY_ROUTE(server),
3345 SILC_BROADCAST(server), client->id,
3349 /* Remove client from all channels */
3351 silc_server_remove_from_channels(server, NULL, client,
3352 TRUE, (char *)signoff, TRUE, FALSE);
3354 silc_server_remove_from_channels(server, NULL, client,
3355 FALSE, NULL, FALSE, FALSE);
3357 /* Remove this client from watcher list if it is */
3358 silc_server_del_from_watcher_list(server, client);
3360 /* Remove this client from the public key hash list */
3361 if (client->data.public_key)
3362 silc_hash_table_del_by_context(server->pk_hash,
3363 client->data.public_key, client);
3365 /* Update statistics */
3366 server->stat.my_clients--;
3367 server->stat.clients--;
3368 if (server->stat.cell_clients)
3369 server->stat.cell_clients--;
3370 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
3371 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
3372 silc_schedule_task_del_by_context(server->schedule, client);
3374 /* We will not delete the client entry right away. We will take it
3375 into history (for WHOWAS command) for 5 minutes, unless we're
3376 shutting down server. */
3377 if (!server->server_shutdown) {
3378 silc_schedule_task_add(server->schedule, 0,
3379 silc_server_free_client_data_timeout,
3381 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
3382 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
3383 client->data.status &= ~SILC_IDLIST_STATUS_LOCAL;
3385 client->router = NULL;
3386 client->connection = NULL;
3388 /* Delete directly since we're shutting down server */
3389 silc_idlist_del_data(client);
3390 silc_idlist_del_client(server->local_list, client);
3394 /* Frees user_data pointer from socket connection object. This also sends
3395 appropriate notify packets to the network to inform about leaving
3398 void silc_server_free_sock_user_data(SilcServer server,
3399 SilcSocketConnection sock,
3400 const char *signoff_message)
3403 /* If any protocol is active cancel its execution */
3404 if (sock->protocol && sock->protocol->protocol &&
3405 sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3406 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3407 silc_protocol_cancel(sock->protocol, server->schedule);
3408 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3409 silc_protocol_execute_final(sock->protocol, server->schedule);
3410 sock->protocol = NULL;
3413 switch (sock->type) {
3414 case SILC_SOCKET_TYPE_CLIENT:
3416 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
3417 silc_server_free_client_data(server, sock, user_data, TRUE,
3421 case SILC_SOCKET_TYPE_SERVER:
3422 case SILC_SOCKET_TYPE_ROUTER:
3424 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
3425 SilcServerEntry backup_router = NULL;
3427 SILC_LOG_DEBUG(("Freeing server data"));
3430 backup_router = silc_server_backup_get(server, user_data->id);
3432 if (!server->backup_router && server->server_type == SILC_ROUTER &&
3433 backup_router == server->id_entry &&
3434 sock->type != SILC_SOCKET_TYPE_ROUTER)
3435 backup_router = NULL;
3437 if (server->server_shutdown || server->backup_noswitch)
3438 backup_router = NULL;
3440 /* If this was our primary router connection then we're lost to
3441 the outside world. */
3442 if (server->router == user_data) {
3443 /* Check whether we have a backup router connection */
3444 if (!backup_router || backup_router == user_data) {
3445 if (!server->no_reconnect)
3446 silc_server_create_connections(server);
3447 server->id_entry->router = NULL;
3448 server->router = NULL;
3449 server->standalone = TRUE;
3450 server->backup_primary = FALSE;
3451 backup_router = NULL;
3453 if (server->id_entry != backup_router) {
3454 SILC_LOG_INFO(("New primary router is backup router %s",
3455 backup_router->server_name));
3456 server->id_entry->router = backup_router;
3457 server->router = backup_router;
3458 server->router_connect = time(0);
3459 server->backup_primary = TRUE;
3460 backup_router->data.status &= ~SILC_IDLIST_STATUS_DISABLED;
3462 /* Send START_USE to backup router to indicate we have switched */
3463 silc_server_backup_send_start_use(server,
3464 backup_router->connection,
3467 SILC_LOG_INFO(("We are now new primary router in this cell"));
3468 server->id_entry->router = NULL;
3469 server->router = NULL;
3470 server->standalone = TRUE;
3473 /* We stop here to take a breath */
3476 if (server->backup_router) {
3477 server->server_type = SILC_ROUTER;
3479 /* We'll need to constantly try to reconnect to the primary
3480 router so that we'll see when it comes back online. */
3481 silc_server_backup_reconnect(server, sock->ip, sock->port,
3482 silc_server_backup_connected,
3486 /* Mark this connection as replaced */
3487 silc_server_backup_replaced_add(server, user_data->id,
3490 } else if (backup_router) {
3491 SILC_LOG_INFO(("Enabling the use of backup router %s",
3492 backup_router->server_name));
3494 /* Mark this connection as replaced */
3495 silc_server_backup_replaced_add(server, user_data->id,
3497 } else if (server->server_type == SILC_SERVER &&
3498 sock->type == SILC_SOCKET_TYPE_ROUTER) {
3499 /* Reconnect to the router (backup) */
3500 if (!server->no_reconnect)
3501 silc_server_create_connections(server);
3504 if (user_data->server_name)
3505 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
3506 ("Server %s signoff", user_data->server_name));
3508 if (!backup_router) {
3509 /* Remove all servers that are originated from this server, and
3510 remove the clients of those servers too. */
3511 silc_server_remove_servers_by_server(server, user_data, TRUE);
3514 /* Remove the clients that this server owns as they will become
3515 invalid now too. For backup router the server is actually
3516 coming from the primary router, so mark that as the owner
3518 if (server->server_type == SILC_BACKUP_ROUTER &&
3519 sock->type == SILC_SOCKET_TYPE_SERVER)
3520 silc_server_remove_clients_by_server(server, server->router,
3524 silc_server_remove_clients_by_server(server, user_data,
3527 /* Remove channels owned by this server */
3528 if (server->server_type == SILC_SERVER)
3529 silc_server_remove_channels_by_server(server, user_data);
3531 /* Enable local server connections that may be disabled */
3532 silc_server_local_servers_toggle_enabled(server, TRUE);
3534 /* Update the client entries of this server to the new backup
3535 router. If we are the backup router we also resolve the real
3536 servers for the clients. After updating is over this also
3537 removes the clients that this server explicitly owns. */
3538 silc_server_update_clients_by_server(server, user_data,
3539 backup_router, TRUE);
3541 /* If we are router and just lost our primary router (now standlaone)
3542 we remove everything that was behind it, since we don't know
3544 if (server->server_type == SILC_ROUTER && server->standalone)
3545 /* Remove all servers that are originated from this server, and
3546 remove the clients of those servers too. */
3547 silc_server_remove_servers_by_server(server, user_data, TRUE);
3549 /* Finally remove the clients that are explicitly owned by this
3550 server. They go down with the server. */
3551 silc_server_remove_clients_by_server(server, user_data,
3554 /* Update our server cache to use the new backup router too. */
3555 silc_server_update_servers_by_server(server, user_data, backup_router);
3556 if (server->server_type == SILC_SERVER)
3557 silc_server_update_channels_by_server(server, user_data,
3560 /* Send notify about primary router going down to local operators */
3561 if (server->backup_router)
3562 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3563 SILC_NOTIFY_TYPE_NONE,
3564 ("%s switched to backup router %s "
3565 "(we are primary router now)",
3566 server->server_name, server->server_name));
3567 else if (server->router)
3568 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3569 SILC_NOTIFY_TYPE_NONE,
3570 ("%s switched to backup router %s",
3571 server->server_name,
3572 server->router->server_name));
3574 server->backup_noswitch = FALSE;
3576 /* Free the server entry */
3577 silc_server_backup_del(server, user_data);
3578 silc_server_backup_replaced_del(server, user_data);
3579 silc_idlist_del_data(user_data);
3580 if (!silc_idlist_del_server(server->local_list, user_data))
3581 silc_idlist_del_server(server->global_list, user_data);
3582 if (sock->type == SILC_SOCKET_TYPE_SERVER) {
3583 server->stat.my_servers--;
3585 server->stat.my_routers--;
3586 server->stat.routers--;
3588 server->stat.servers--;
3589 if (server->server_type == SILC_ROUTER)
3590 server->stat.cell_servers--;
3592 if (backup_router && backup_router != server->id_entry) {
3593 /* Announce all of our stuff that was created about 5 minutes ago.
3594 The backup router knows all the other stuff already. */
3595 if (server->server_type == SILC_ROUTER)
3596 silc_server_announce_servers(server, FALSE, time(0) - 300,
3597 backup_router->connection);
3599 /* Announce our clients and channels to the router */
3600 silc_server_announce_clients(server, time(0) - 300,
3601 backup_router->connection);
3602 silc_server_announce_channels(server, time(0) - 300,
3603 backup_router->connection);
3609 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
3611 SILC_LOG_DEBUG(("Freeing unknown connection data"));
3613 silc_idlist_del_data(user_data);
3614 silc_free(user_data);
3619 sock->user_data = NULL;
3622 /* Removes client from all channels it has joined. This is used when client
3623 connection is disconnected. If the client on a channel is last, the
3624 channel is removed as well. This sends the SIGNOFF notify types. */
3626 void silc_server_remove_from_channels(SilcServer server,
3627 SilcSocketConnection sock,
3628 SilcClientEntry client,
3630 const char *signoff_message,
3634 SilcChannelEntry channel;
3635 SilcChannelClientEntry chl;
3636 SilcHashTableList htl;
3637 SilcBuffer clidp = NULL;
3642 if (notify && !client->id)
3645 SILC_LOG_DEBUG(("Removing client %s from joined channels",
3646 notify ? silc_id_render(client->id, SILC_ID_CLIENT) : ""));
3649 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3654 /* Remove the client from all channels. The client is removed from
3655 the channels' user list. */
3656 silc_hash_table_list(client->channels, &htl);
3657 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3658 channel = chl->channel;
3660 /* Remove channel if this is last client leaving the channel, unless
3661 the channel is permanent. */
3662 if (server->server_type != SILC_SERVER &&
3663 silc_hash_table_count(channel->user_list) < 2) {
3664 silc_server_channel_delete(server, channel);
3668 silc_hash_table_del(client->channels, channel);
3669 silc_hash_table_del(channel->user_list, client);
3670 channel->user_count--;
3672 /* If there is no global users on the channel anymore mark the channel
3673 as local channel. Do not check if the removed client is local client. */
3674 if (server->server_type == SILC_SERVER && channel->global_users &&
3675 chl->client->router && !silc_server_channel_has_global(channel))
3676 channel->global_users = FALSE;
3678 memset(chl, 'A', sizeof(*chl));
3681 /* Update statistics */
3682 if (SILC_IS_LOCAL(client))
3683 server->stat.my_chanclients--;
3684 if (server->server_type == SILC_ROUTER) {
3685 server->stat.cell_chanclients--;
3686 server->stat.chanclients--;
3689 /* If there is not at least one local user on the channel then we don't
3690 need the channel entry anymore, we can remove it safely, unless the
3691 channel is permanent channel */
3692 if (server->server_type == SILC_SERVER &&
3693 !silc_server_channel_has_local(channel)) {
3694 /* Notify about leaving client if this channel has global users. */
3695 if (notify && channel->global_users)
3696 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3697 SILC_NOTIFY_TYPE_SIGNOFF,
3698 signoff_message ? 2 : 1,
3699 clidp->data, clidp->len,
3700 signoff_message, signoff_message ?
3701 strlen(signoff_message) : 0);
3703 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3704 silc_server_channel_delete(server, channel);
3708 /* Send notify to channel about client leaving SILC and channel too */
3710 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3711 SILC_NOTIFY_TYPE_SIGNOFF,
3712 signoff_message ? 2 : 1,
3713 clidp->data, clidp->len,
3714 signoff_message, signoff_message ?
3715 strlen(signoff_message) : 0);
3717 if (killed && clidp) {
3718 /* Remove the client from channel's invite list */
3719 if (channel->invite_list &&
3720 silc_hash_table_count(channel->invite_list)) {
3722 SilcArgumentPayload iargs;
3723 ab = silc_argument_payload_encode_one(NULL, clidp->data,
3725 iargs = silc_argument_payload_parse(ab->data, ab->len, 1);
3726 silc_server_inviteban_process(server, channel->invite_list, 1, iargs);
3727 silc_buffer_free(ab);
3728 silc_argument_payload_free(iargs);
3732 /* Don't create keys if we are shutting down */
3733 if (server->server_shutdown)
3736 /* Re-generate channel key if needed */
3737 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3738 if (!silc_server_create_channel_key(server, channel, 0))
3741 /* Send the channel key to the channel. The key of course is not sent
3742 to the client who was removed from the channel. */
3743 silc_server_send_channel_key(server, client->connection, channel,
3744 server->server_type == SILC_ROUTER ?
3745 FALSE : !server->standalone);
3749 silc_hash_table_list_reset(&htl);
3751 silc_buffer_free(clidp);
3754 /* Removes client from one channel. This is used for example when client
3755 calls LEAVE command to remove itself from the channel. Returns TRUE
3756 if channel still exists and FALSE if the channel is removed when
3757 last client leaves the channel. If `notify' is FALSE notify messages
3760 bool silc_server_remove_from_one_channel(SilcServer server,
3761 SilcSocketConnection sock,
3762 SilcChannelEntry channel,
3763 SilcClientEntry client,
3766 SilcChannelClientEntry chl;
3769 SILC_LOG_DEBUG(("Removing %s from channel %s",
3770 silc_id_render(client->id, SILC_ID_CLIENT),
3771 channel->channel_name));
3773 /* Get the entry to the channel, if this client is not on the channel
3775 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
3778 /* Remove channel if this is last client leaving the channel, unless
3779 the channel is permanent. */
3780 if (server->server_type != SILC_SERVER &&
3781 silc_hash_table_count(channel->user_list) < 2) {
3782 silc_server_channel_delete(server, channel);
3786 silc_hash_table_del(client->channels, channel);
3787 silc_hash_table_del(channel->user_list, client);
3788 channel->user_count--;
3790 /* If there is no global users on the channel anymore mark the channel
3791 as local channel. Do not check if the client is local client. */
3792 if (server->server_type == SILC_SERVER && channel->global_users &&
3793 chl->client->router && !silc_server_channel_has_global(channel))
3794 channel->global_users = FALSE;
3796 memset(chl, 'O', sizeof(*chl));
3799 /* Update statistics */
3800 if (SILC_IS_LOCAL(client))
3801 server->stat.my_chanclients--;
3802 if (server->server_type == SILC_ROUTER) {
3803 server->stat.cell_chanclients--;
3804 server->stat.chanclients--;
3807 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3811 /* If there is not at least one local user on the channel then we don't
3812 need the channel entry anymore, we can remove it safely, unless the
3813 channel is permanent channel */
3814 if (server->server_type == SILC_SERVER &&
3815 !silc_server_channel_has_local(channel)) {
3816 /* Notify about leaving client if this channel has global users. */
3817 if (notify && channel->global_users)
3818 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3819 SILC_NOTIFY_TYPE_LEAVE, 1,
3820 clidp->data, clidp->len);
3822 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3823 silc_server_channel_delete(server, channel);
3824 silc_buffer_free(clidp);
3828 /* Send notify to channel about client leaving the channel */
3830 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3831 SILC_NOTIFY_TYPE_LEAVE, 1,
3832 clidp->data, clidp->len);
3834 silc_buffer_free(clidp);
3838 /* Timeout callback. This is called if connection is idle or for some
3839 other reason is not responding within some period of time. This
3840 disconnects the remote end. */
3842 SILC_TASK_CALLBACK(silc_server_timeout_remote)
3844 SilcServer server = (SilcServer)context;
3845 SilcSocketConnection sock = server->sockets[fd];
3846 SilcProtocolType protocol = 0;
3848 SILC_LOG_DEBUG(("Start"));
3853 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
3854 sock->hostname, sock->ip));
3856 /* If we have protocol active we must assure that we call the protocol's
3857 final callback so that all the memory is freed. */
3858 if (sock->protocol && sock->protocol->protocol &&
3859 sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3860 protocol = sock->protocol->protocol->type;
3861 silc_protocol_cancel(sock->protocol, server->schedule);
3862 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3863 silc_protocol_execute_final(sock->protocol, server->schedule);
3864 sock->protocol = NULL;
3868 silc_server_disconnect_remote(server, sock,
3870 SILC_PROTOCOL_SERVER_CONNECTION_AUTH ?
3871 SILC_STATUS_ERR_AUTH_FAILED :
3872 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
3873 "Connection timeout");
3875 if (sock->user_data)
3876 silc_server_free_sock_user_data(server, sock, NULL);
3879 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
3880 function may be used only by router. In real SILC network all channels
3881 are created by routers thus this function is never used by normal
3884 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3885 SilcServerID *router_id,
3891 SilcChannelID *channel_id;
3892 SilcChannelEntry entry;
3896 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3899 cipher = SILC_DEFAULT_CIPHER;
3901 hmac = SILC_DEFAULT_HMAC;
3903 /* Allocate cipher */
3904 if (!silc_cipher_alloc(cipher, &key))
3908 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3909 silc_cipher_free(key);
3913 channel_name = strdup(channel_name);
3915 /* Create the channel ID */
3916 if (!silc_id_create_channel_id(server, router_id, server->rng,
3918 silc_free(channel_name);
3919 silc_cipher_free(key);
3920 silc_hmac_free(newhmac);
3924 /* Create the channel */
3925 entry = silc_idlist_add_channel(server->local_list, channel_name,
3926 SILC_CHANNEL_MODE_NONE, channel_id,
3927 NULL, key, newhmac, 0);
3929 silc_free(channel_name);
3930 silc_cipher_free(key);
3931 silc_hmac_free(newhmac);
3932 silc_free(channel_id);
3936 entry->cipher = strdup(cipher);
3937 entry->hmac_name = strdup(hmac);
3939 /* Now create the actual key material */
3940 if (!silc_server_create_channel_key(server, entry,
3941 silc_cipher_get_key_len(key) / 8)) {
3942 silc_idlist_del_channel(server->local_list, entry);
3946 /* Notify other routers about the new channel. We send the packet
3947 to our primary route. */
3949 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3950 channel_name, entry->id,
3951 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3954 /* Distribute to backup routers */
3955 if (broadcast && server->server_type == SILC_ROUTER) {
3958 SilcUInt32 name_len = strlen(channel_name);
3959 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3960 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3962 packet = silc_channel_payload_encode(channel_name, name_len,
3963 cid, channel_id_len, entry->mode);
3964 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3965 packet->data, packet->len, FALSE, TRUE);
3967 silc_buffer_free(packet);
3970 server->stat.my_channels++;
3971 if (server->server_type == SILC_ROUTER) {
3972 server->stat.channels++;
3973 server->stat.cell_channels++;
3974 entry->users_resolved = TRUE;
3980 /* Same as above but creates the channel with Channel ID `channel_id. */
3983 silc_server_create_new_channel_with_id(SilcServer server,
3987 SilcChannelID *channel_id,
3990 SilcChannelEntry entry;
3994 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3997 cipher = SILC_DEFAULT_CIPHER;
3999 hmac = SILC_DEFAULT_HMAC;
4001 /* Allocate cipher */
4002 if (!silc_cipher_alloc(cipher, &key))
4006 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
4007 silc_cipher_free(key);
4011 channel_name = strdup(channel_name);
4013 /* Create the channel */
4014 entry = silc_idlist_add_channel(server->local_list, channel_name,
4015 SILC_CHANNEL_MODE_NONE, channel_id,
4016 NULL, key, newhmac, 0);
4018 silc_cipher_free(key);
4019 silc_hmac_free(newhmac);
4020 silc_free(channel_name);
4024 /* Now create the actual key material */
4025 if (!silc_server_create_channel_key(server, entry,
4026 silc_cipher_get_key_len(key) / 8)) {
4027 silc_idlist_del_channel(server->local_list, entry);
4031 /* Notify other routers about the new channel. We send the packet
4032 to our primary route. */
4034 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
4035 channel_name, entry->id,
4036 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
4039 /* Distribute to backup routers */
4040 if (broadcast && server->server_type == SILC_ROUTER) {
4043 SilcUInt32 name_len = strlen(channel_name);
4044 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
4045 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
4047 packet = silc_channel_payload_encode(channel_name, name_len,
4048 cid, channel_id_len, entry->mode);
4049 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
4050 packet->data, packet->len, FALSE, TRUE);
4052 silc_buffer_free(packet);
4055 server->stat.my_channels++;
4056 if (server->server_type == SILC_ROUTER) {
4057 server->stat.channels++;
4058 server->stat.cell_channels++;
4059 entry->users_resolved = TRUE;
4065 /* Channel's key re-key timeout callback. */
4067 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
4069 SilcServer server = app_context;
4070 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
4074 /* Return now if we are shutting down */
4075 if (server->server_shutdown)
4078 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
4081 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
4084 /* Generates new channel key. This is used to create the initial channel key
4085 but also to re-generate new key for channel. If `key_len' is provided
4086 it is the bytes of the key length. */
4088 bool silc_server_create_channel_key(SilcServer server,
4089 SilcChannelEntry channel,
4093 unsigned char channel_key[32], hash[32];
4096 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
4097 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
4101 SILC_LOG_DEBUG(("Generating channel %s key", channel->channel_name));
4103 if (!channel->channel_key)
4104 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
4105 channel->channel_key = NULL;
4111 else if (channel->key_len)
4112 len = channel->key_len / 8;
4114 len = silc_cipher_get_key_len(channel->channel_key) / 8;
4116 /* Create channel key */
4117 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
4120 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
4122 /* Remove old key if exists */
4124 memset(channel->key, 0, channel->key_len / 8);
4125 silc_free(channel->key);
4129 channel->key_len = len * 8;
4130 channel->key = silc_memdup(channel_key, len);
4131 memset(channel_key, 0, sizeof(channel_key));
4133 /* Generate HMAC key from the channel key data and set it */
4135 if (!silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac)) {
4136 memset(channel->key, 0, channel->key_len / 8);
4137 silc_free(channel->key);
4138 channel->channel_key = NULL;
4141 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
4142 silc_hmac_set_key(channel->hmac, hash,
4143 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
4144 memset(hash, 0, sizeof(hash));
4146 if (server->server_type == SILC_ROUTER) {
4147 if (!channel->rekey)
4148 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
4149 channel->rekey->channel = channel;
4150 channel->rekey->key_len = key_len;
4151 if (channel->rekey->task)
4152 silc_schedule_task_del(server->schedule, channel->rekey->task);
4154 channel->rekey->task =
4155 silc_schedule_task_add(server->schedule, 0,
4156 silc_server_channel_key_rekey,
4157 (void *)channel->rekey,
4158 server->config->channel_rekey_secs, 0,
4160 SILC_TASK_PRI_NORMAL);
4166 /* Saves the channel key found in the encoded `key_payload' buffer. This
4167 function is used when we receive Channel Key Payload and also when we're
4168 processing JOIN command reply. Returns entry to the channel. */
4170 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
4171 SilcBuffer key_payload,
4172 SilcChannelEntry channel)
4174 SilcChannelKeyPayload payload = NULL;
4175 SilcChannelID *id = NULL;
4176 unsigned char *tmp, hash[32];
4180 /* Decode channel key payload */
4181 payload = silc_channel_key_payload_parse(key_payload->data,
4184 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
4189 /* Get the channel entry */
4192 /* Get channel ID */
4193 tmp = silc_channel_key_get_id(payload, &tmp_len);
4194 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
4200 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
4202 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
4204 if (server->server_type == SILC_ROUTER)
4205 SILC_LOG_ERROR(("Received key for non-existent channel %s",
4206 silc_id_render(id, SILC_ID_CHANNEL)));
4212 SILC_LOG_DEBUG(("Saving new channel %s key", channel->channel_name));
4214 tmp = silc_channel_key_get_key(payload, &tmp_len);
4220 cipher = silc_channel_key_get_cipher(payload, NULL);
4226 /* Remove old key if exists */
4228 memset(channel->key, 0, channel->key_len / 8);
4229 silc_free(channel->key);
4230 silc_cipher_free(channel->channel_key);
4233 /* Create new cipher */
4234 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
4235 channel->channel_key = NULL;
4240 if (channel->cipher)
4241 silc_free(channel->cipher);
4242 channel->cipher = strdup(cipher);
4245 channel->key_len = tmp_len * 8;
4246 channel->key = silc_memdup(tmp, tmp_len);
4247 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
4249 /* Generate HMAC key from the channel key data and set it */
4251 if (!silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac)) {
4252 memset(channel->key, 0, channel->key_len / 8);
4253 silc_free(channel->key);
4254 channel->channel_key = NULL;
4257 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
4258 silc_hmac_set_key(channel->hmac, hash,
4259 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
4261 memset(hash, 0, sizeof(hash));
4262 memset(tmp, 0, tmp_len);
4264 if (server->server_type == SILC_ROUTER) {
4265 if (!channel->rekey)
4266 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
4267 channel->rekey->channel = channel;
4268 if (channel->rekey->task)
4269 silc_schedule_task_del(server->schedule, channel->rekey->task);
4271 channel->rekey->task =
4272 silc_schedule_task_add(server->schedule, 0,
4273 silc_server_channel_key_rekey,
4274 (void *)channel->rekey,
4275 server->config->channel_rekey_secs, 0,
4277 SILC_TASK_PRI_NORMAL);
4283 silc_channel_key_payload_free(payload);
4288 /* Heartbeat callback. This function is set as argument for the
4289 silc_socket_set_heartbeat function. The library will call this function
4290 at the set time interval. */
4292 void silc_server_perform_heartbeat(SilcSocketConnection sock,
4295 SilcServer server = hb_context;
4297 SILC_LOG_DEBUG(("Sending heartbeat to %s:%d (%s)", sock->hostname,
4298 sock->port, sock->ip));
4300 /* Send the heartbeat */
4301 silc_server_send_heartbeat(server, sock);
4304 /* Returns assembled of all servers in the given ID list. The packet's
4305 form is dictated by the New ID payload. */
4307 static void silc_server_announce_get_servers(SilcServer server,
4308 SilcServerEntry remote,
4310 SilcBuffer *servers,
4311 unsigned long creation_time)
4313 SilcIDCacheList list;
4314 SilcIDCacheEntry id_cache;
4315 SilcServerEntry entry;
4318 /* Go through all clients in the list */
4319 if (silc_idcache_get_all(id_list->servers, &list)) {
4320 if (silc_idcache_list_first(list, &id_cache)) {
4322 entry = (SilcServerEntry)id_cache->context;
4324 /* Do not announce the one we've sending our announcements and
4325 do not announce ourself. Also check the creation time if it's
4327 if ((entry == remote) || (entry == server->id_entry) ||
4328 (creation_time && entry->data.created < creation_time)) {
4329 if (!silc_idcache_list_next(list, &id_cache))
4334 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
4336 *servers = silc_buffer_realloc(*servers,
4338 (*servers)->truelen + idp->len :
4340 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
4341 silc_buffer_put(*servers, idp->data, idp->len);
4342 silc_buffer_pull(*servers, idp->len);
4343 silc_buffer_free(idp);
4345 if (!silc_idcache_list_next(list, &id_cache))
4350 silc_idcache_list_free(list);
4355 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
4361 p = silc_notify_payload_encode(notify, argc, ap);
4367 /* This function is used by router to announce existing servers to our
4368 primary router when we've connected to it. If `creation_time' is non-zero
4369 then only the servers that has been created after the `creation_time'
4370 will be announced. */
4372 void silc_server_announce_servers(SilcServer server, bool global,
4373 unsigned long creation_time,
4374 SilcSocketConnection remote)
4376 SilcBuffer servers = NULL;
4378 SILC_LOG_DEBUG(("Announcing servers"));
4380 /* Get servers in local list */
4381 silc_server_announce_get_servers(server, remote->user_data,
4382 server->local_list, &servers,
4386 /* Get servers in global list */
4387 silc_server_announce_get_servers(server, remote->user_data,
4388 server->global_list, &servers,
4392 silc_buffer_push(servers, servers->data - servers->head);
4393 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
4395 /* Send the packet */
4396 silc_server_packet_send(server, remote,
4397 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4398 servers->data, servers->len, TRUE);
4400 silc_buffer_free(servers);
4404 /* Returns assembled packet of all clients in the given ID list. The
4405 packet's form is dictated by the New ID Payload. */
4407 static void silc_server_announce_get_clients(SilcServer server,
4409 SilcBuffer *clients,
4411 unsigned long creation_time)
4413 SilcIDCacheList list;
4414 SilcIDCacheEntry id_cache;
4415 SilcClientEntry client;
4418 unsigned char mode[4];
4420 /* Go through all clients in the list */
4421 if (silc_idcache_get_all(id_list->clients, &list)) {
4422 if (silc_idcache_list_first(list, &id_cache)) {
4424 client = (SilcClientEntry)id_cache->context;
4426 if (creation_time && client->data.created < creation_time) {
4427 if (!silc_idcache_list_next(list, &id_cache))
4431 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED) &&
4432 !client->connection && !client->router && !SILC_IS_LOCAL(client)) {
4433 if (!silc_idcache_list_next(list, &id_cache))
4438 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
4440 *clients = silc_buffer_realloc(*clients,
4442 (*clients)->truelen + idp->len :
4444 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
4445 silc_buffer_put(*clients, idp->data, idp->len);
4446 silc_buffer_pull(*clients, idp->len);
4448 SILC_PUT32_MSB(client->mode, mode);
4450 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
4451 2, idp->data, idp->len,
4453 *umodes = silc_buffer_realloc(*umodes,
4455 (*umodes)->truelen + tmp->len :
4457 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
4458 silc_buffer_put(*umodes, tmp->data, tmp->len);
4459 silc_buffer_pull(*umodes, tmp->len);
4460 silc_buffer_free(tmp);
4462 silc_buffer_free(idp);
4464 if (!silc_idcache_list_next(list, &id_cache))
4469 silc_idcache_list_free(list);
4473 /* This function is used to announce our existing clients to our router
4474 when we've connected to it. If `creation_time' is non-zero then only
4475 the clients that has been created after the `creation_time' will be
4478 void silc_server_announce_clients(SilcServer server,
4479 unsigned long creation_time,
4480 SilcSocketConnection remote)
4482 SilcBuffer clients = NULL;
4483 SilcBuffer umodes = NULL;
4485 SILC_LOG_DEBUG(("Announcing clients"));
4487 /* Get clients in local list */
4488 silc_server_announce_get_clients(server, server->local_list,
4489 &clients, &umodes, creation_time);
4491 /* As router we announce our global list as well */
4492 if (server->server_type == SILC_ROUTER)
4493 silc_server_announce_get_clients(server, server->global_list,
4494 &clients, &umodes, creation_time);
4497 silc_buffer_push(clients, clients->data - clients->head);
4498 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
4500 /* Send the packet */
4501 silc_server_packet_send(server, remote,
4502 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4503 clients->data, clients->len, TRUE);
4505 silc_buffer_free(clients);
4509 silc_buffer_push(umodes, umodes->data - umodes->head);
4510 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
4512 /* Send the packet */
4513 silc_server_packet_send(server, remote,
4514 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4515 umodes->data, umodes->len, TRUE);
4517 silc_buffer_free(umodes);
4521 /* Returns channel's topic for announcing it */
4523 void silc_server_announce_get_channel_topic(SilcServer server,
4524 SilcChannelEntry channel,
4529 if (channel->topic) {
4530 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4531 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
4532 chidp->data, chidp->len,
4534 strlen(channel->topic));
4535 silc_buffer_free(chidp);
4539 /* Returns channel's invite and ban lists */
4541 void silc_server_announce_get_inviteban(SilcServer server,
4542 SilcChannelEntry channel,
4546 SilcBuffer list, idp, idp2, tmp2;
4548 SilcHashTableList htl;
4549 const unsigned char a[1] = { 0x03 };
4551 idp = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
4553 /* Encode invite list */
4554 if (channel->invite_list && silc_hash_table_count(channel->invite_list)) {
4555 list = silc_buffer_alloc_size(2);
4556 type = silc_hash_table_count(channel->invite_list);
4557 SILC_PUT16_MSB(type, list->data);
4558 silc_hash_table_list(channel->invite_list, &htl);
4559 while (silc_hash_table_get(&htl, (void *)&type, (void *)&tmp2))
4560 list = silc_argument_payload_encode_one(list, tmp2->data, tmp2->len,
4562 silc_hash_table_list_reset(&htl);
4564 idp2 = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4566 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_INVITE, 5,
4567 idp->data, idp->len,
4568 channel->channel_name,
4569 strlen(channel->channel_name),
4570 idp2->data, idp2->len,
4572 list->data, list->len);
4573 silc_buffer_free(idp2);
4574 silc_buffer_free(list);
4577 /* Encode ban list */
4578 if (channel->ban_list && silc_hash_table_count(channel->ban_list)) {
4579 list = silc_buffer_alloc_size(2);
4580 type = silc_hash_table_count(channel->ban_list);
4581 SILC_PUT16_MSB(type, list->data);
4582 silc_hash_table_list(channel->ban_list, &htl);
4583 while (silc_hash_table_get(&htl, (void *)&type, (void *)&tmp2))
4584 list = silc_argument_payload_encode_one(list, tmp2->data, tmp2->len,
4586 silc_hash_table_list_reset(&htl);
4589 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_BAN, 3,
4590 idp->data, idp->len,
4592 list->data, list->len);
4593 silc_buffer_free(list);
4596 silc_buffer_free(idp);
4599 /* Returns assembled packets for channel users of the `channel'. */
4601 void silc_server_announce_get_channel_users(SilcServer server,
4602 SilcChannelEntry channel,
4603 SilcBuffer *channel_modes,
4604 SilcBuffer *channel_users,
4605 SilcBuffer *channel_users_modes)
4607 SilcChannelClientEntry chl;
4608 SilcHashTableList htl;
4609 SilcBuffer chidp, clidp, csidp;
4610 SilcBuffer tmp, fkey = NULL, chpklist;
4612 unsigned char mode[4];
4615 SILC_LOG_DEBUG(("Start"));
4617 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4618 csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4619 chpklist = silc_server_get_channel_pk_list(server, channel, TRUE, FALSE);
4622 SILC_PUT32_MSB(channel->mode, mode);
4623 hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
4624 if (channel->founder_key)
4625 fkey = silc_pkcs_public_key_payload_encode(channel->founder_key);
4627 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
4628 7, csidp->data, csidp->len,
4631 hmac, hmac ? strlen(hmac) : 0,
4632 channel->passphrase,
4633 channel->passphrase ?
4634 strlen(channel->passphrase) : 0,
4635 fkey ? fkey->data : NULL,
4636 fkey ? fkey->len : 0,
4637 chpklist ? chpklist->data : NULL,
4638 chpklist ? chpklist->len : 0);
4641 silc_buffer_realloc(*channel_modes,
4643 (*channel_modes)->truelen + len : len));
4644 silc_buffer_pull_tail(*channel_modes,
4645 ((*channel_modes)->end -
4646 (*channel_modes)->data));
4647 silc_buffer_put(*channel_modes, tmp->data, tmp->len);
4648 silc_buffer_pull(*channel_modes, len);
4649 silc_buffer_free(tmp);
4650 silc_buffer_free(fkey);
4653 /* Now find all users on the channel */
4654 silc_hash_table_list(channel->user_list, &htl);
4655 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4656 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4659 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
4660 clidp->data, clidp->len,
4661 chidp->data, chidp->len);
4664 silc_buffer_realloc(*channel_users,
4666 (*channel_users)->truelen + len : len));
4667 silc_buffer_pull_tail(*channel_users,
4668 ((*channel_users)->end -
4669 (*channel_users)->data));
4671 silc_buffer_put(*channel_users, tmp->data, tmp->len);
4672 silc_buffer_pull(*channel_users, len);
4673 silc_buffer_free(tmp);
4675 /* CUMODE notify for mode change on the channel */
4676 SILC_PUT32_MSB(chl->mode, mode);
4677 if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
4678 fkey = silc_pkcs_public_key_payload_encode(channel->founder_key);
4679 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
4680 4, csidp->data, csidp->len,
4682 clidp->data, clidp->len,
4683 fkey ? fkey->data : NULL,
4684 fkey ? fkey->len : 0);
4686 *channel_users_modes =
4687 silc_buffer_realloc(*channel_users_modes,
4688 (*channel_users_modes ?
4689 (*channel_users_modes)->truelen + len : len));
4690 silc_buffer_pull_tail(*channel_users_modes,
4691 ((*channel_users_modes)->end -
4692 (*channel_users_modes)->data));
4694 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
4695 silc_buffer_pull(*channel_users_modes, len);
4696 silc_buffer_free(tmp);
4697 silc_buffer_free(fkey);
4699 silc_buffer_free(clidp);
4701 silc_hash_table_list_reset(&htl);
4702 silc_buffer_free(chidp);
4703 silc_buffer_free(csidp);
4706 /* Returns assembled packets for all channels and users on those channels
4707 from the given ID List. The packets are in the form dictated by the
4708 New Channel and New Channel User payloads. */
4710 void silc_server_announce_get_channels(SilcServer server,
4712 SilcBuffer *channels,
4713 SilcBuffer **channel_modes,
4714 SilcBuffer *channel_users,
4715 SilcBuffer **channel_users_modes,
4716 SilcUInt32 *channel_users_modes_c,
4717 SilcBuffer **channel_topics,
4718 SilcBuffer **channel_invites,
4719 SilcBuffer **channel_bans,
4720 SilcChannelID ***channel_ids,
4721 unsigned long creation_time)
4723 SilcIDCacheList list;
4724 SilcIDCacheEntry id_cache;
4725 SilcChannelEntry channel;
4728 SilcUInt16 name_len;
4730 int i = *channel_users_modes_c;
4733 SILC_LOG_DEBUG(("Start"));
4735 /* Go through all channels in the list */
4736 if (silc_idcache_get_all(id_list->channels, &list)) {
4737 if (silc_idcache_list_first(list, &id_cache)) {
4739 channel = (SilcChannelEntry)id_cache->context;
4741 if (creation_time && channel->created < creation_time)
4746 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4747 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4748 name_len = strlen(channel->channel_name);
4751 len = 4 + name_len + id_len + 4;
4753 silc_buffer_realloc(*channels,
4754 (*channels ? (*channels)->truelen +
4756 silc_buffer_pull_tail(*channels,
4757 ((*channels)->end - (*channels)->data));
4758 silc_buffer_format(*channels,
4759 SILC_STR_UI_SHORT(name_len),
4760 SILC_STR_UI_XNSTRING(channel->channel_name,
4762 SILC_STR_UI_SHORT(id_len),
4763 SILC_STR_UI_XNSTRING(cid, id_len),
4764 SILC_STR_UI_INT(channel->mode),
4766 silc_buffer_pull(*channels, len);
4769 if (creation_time && channel->updated < creation_time)
4775 /* Channel user modes */
4776 *channel_users_modes = silc_realloc(*channel_users_modes,
4777 sizeof(**channel_users_modes) *
4779 (*channel_users_modes)[i] = NULL;
4780 *channel_modes = silc_realloc(*channel_modes,
4781 sizeof(**channel_modes) * (i + 1));
4782 (*channel_modes)[i] = NULL;
4783 *channel_ids = silc_realloc(*channel_ids,
4784 sizeof(**channel_ids) * (i + 1));
4785 (*channel_ids)[i] = NULL;
4786 silc_server_announce_get_channel_users(server, channel,
4787 &(*channel_modes)[i],
4789 &(*channel_users_modes)[i]);
4790 (*channel_ids)[i] = channel->id;
4792 /* Channel's topic */
4793 *channel_topics = silc_realloc(*channel_topics,
4794 sizeof(**channel_topics) * (i + 1));
4795 (*channel_topics)[i] = NULL;
4796 silc_server_announce_get_channel_topic(server, channel,
4797 &(*channel_topics)[i]);
4799 /* Channel's invite and ban list */
4800 *channel_invites = silc_realloc(*channel_invites,
4801 sizeof(**channel_invites) * (i + 1));
4802 (*channel_invites)[i] = NULL;
4803 *channel_bans = silc_realloc(*channel_bans,
4804 sizeof(**channel_bans) * (i + 1));
4805 (*channel_bans)[i] = NULL;
4806 silc_server_announce_get_inviteban(server, channel,
4807 &(*channel_invites)[i],
4808 &(*channel_bans)[i]);
4810 (*channel_users_modes_c)++;
4816 if (!silc_idcache_list_next(list, &id_cache))
4821 silc_idcache_list_free(list);
4825 /* This function is used to announce our existing channels to our router
4826 when we've connected to it. This also announces the users on the
4827 channels to the router. If the `creation_time' is non-zero only the
4828 channels that was created after the `creation_time' are announced.
4829 Note that the channel users are still announced even if the `creation_time'
4832 void silc_server_announce_channels(SilcServer server,
4833 unsigned long creation_time,
4834 SilcSocketConnection remote)
4836 SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
4837 SilcBuffer *channel_users_modes = NULL;
4838 SilcBuffer *channel_topics = NULL;
4839 SilcBuffer *channel_invites = NULL;
4840 SilcBuffer *channel_bans = NULL;
4841 SilcUInt32 channel_users_modes_c = 0;
4842 SilcChannelID **channel_ids = NULL;
4844 SILC_LOG_DEBUG(("Announcing channels and channel users"));
4846 /* Get channels and channel users in local list */
4847 silc_server_announce_get_channels(server, server->local_list,
4848 &channels, &channel_modes,
4850 &channel_users_modes,
4851 &channel_users_modes_c,
4855 &channel_ids, creation_time);
4857 /* Get channels and channel users in global list */
4858 if (server->server_type != SILC_SERVER)
4859 silc_server_announce_get_channels(server, server->global_list,
4860 &channels, &channel_modes,
4862 &channel_users_modes,
4863 &channel_users_modes_c,
4867 &channel_ids, creation_time);
4870 silc_buffer_push(channels, channels->data - channels->head);
4871 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
4873 /* Send the packet */
4874 silc_server_packet_send(server, remote,
4875 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
4876 channels->data, channels->len,
4879 silc_buffer_free(channels);
4882 if (channel_users) {
4883 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
4884 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
4885 channel_users->len);
4887 /* Send the packet */
4888 silc_server_packet_send(server, remote,
4889 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4890 channel_users->data, channel_users->len,
4893 silc_buffer_free(channel_users);
4896 if (channel_modes) {
4899 for (i = 0; i < channel_users_modes_c; i++) {
4900 if (!channel_modes[i])
4902 silc_buffer_push(channel_modes[i],
4903 channel_modes[i]->data -
4904 channel_modes[i]->head);
4905 SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
4906 channel_modes[i]->len);
4907 silc_server_packet_send_dest(server, remote,
4908 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4909 channel_ids[i], SILC_ID_CHANNEL,
4910 channel_modes[i]->data,
4911 channel_modes[i]->len,
4913 silc_buffer_free(channel_modes[i]);
4915 silc_free(channel_modes);
4918 if (channel_users_modes) {
4921 for (i = 0; i < channel_users_modes_c; i++) {
4922 if (!channel_users_modes[i])
4924 silc_buffer_push(channel_users_modes[i],
4925 channel_users_modes[i]->data -
4926 channel_users_modes[i]->head);
4927 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
4928 channel_users_modes[i]->len);
4929 silc_server_packet_send_dest(server, remote,
4930 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4931 channel_ids[i], SILC_ID_CHANNEL,
4932 channel_users_modes[i]->data,
4933 channel_users_modes[i]->len,
4935 silc_buffer_free(channel_users_modes[i]);
4937 silc_free(channel_users_modes);
4940 if (channel_topics) {
4943 for (i = 0; i < channel_users_modes_c; i++) {
4944 if (!channel_topics[i])
4947 silc_buffer_push(channel_topics[i],
4948 channel_topics[i]->data -
4949 channel_topics[i]->head);
4950 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
4951 channel_topics[i]->len);
4952 silc_server_packet_send_dest(server, remote,
4953 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4954 channel_ids[i], SILC_ID_CHANNEL,
4955 channel_topics[i]->data,
4956 channel_topics[i]->len,
4958 silc_buffer_free(channel_topics[i]);
4960 silc_free(channel_topics);
4963 if (channel_invites) {
4966 for (i = 0; i < channel_users_modes_c; i++) {
4967 if (!channel_invites[i])
4970 silc_buffer_push(channel_invites[i],
4971 channel_invites[i]->data -
4972 channel_invites[i]->head);
4973 SILC_LOG_HEXDUMP(("channel invite list"), channel_invites[i]->data,
4974 channel_invites[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_invites[i]->data,
4979 channel_invites[i]->len,
4981 silc_buffer_free(channel_invites[i]);
4983 silc_free(channel_invites);
4989 for (i = 0; i < channel_users_modes_c; i++) {
4990 if (!channel_bans[i])
4993 silc_buffer_push(channel_bans[i],
4994 channel_bans[i]->data -
4995 channel_bans[i]->head);
4996 SILC_LOG_HEXDUMP(("channel ban list"), channel_bans[i]->data,
4997 channel_bans[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_bans[i]->data,
5002 channel_bans[i]->len,
5004 silc_buffer_free(channel_bans[i]);
5006 silc_free(channel_bans);
5009 silc_free(channel_ids);
5012 /* Assembles user list and users mode list from the `channel'. */
5014 bool silc_server_get_users_on_channel(SilcServer server,
5015 SilcChannelEntry channel,
5016 SilcBuffer *user_list,
5017 SilcBuffer *mode_list,
5018 SilcUInt32 *user_count)
5020 SilcChannelClientEntry chl;
5021 SilcHashTableList htl;
5022 SilcBuffer client_id_list;
5023 SilcBuffer client_mode_list;
5025 SilcUInt32 list_count = 0, len = 0;
5027 if (!silc_hash_table_count(channel->user_list))
5030 silc_hash_table_list(channel->user_list, &htl);
5031 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
5032 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
5033 silc_hash_table_list_reset(&htl);
5035 client_id_list = silc_buffer_alloc(len);
5037 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
5038 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
5039 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
5041 silc_hash_table_list(channel->user_list, &htl);
5042 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5044 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
5045 silc_buffer_put(client_id_list, idp->data, idp->len);
5046 silc_buffer_pull(client_id_list, idp->len);
5047 silc_buffer_free(idp);
5049 /* Client's mode on channel */
5050 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
5051 silc_buffer_pull(client_mode_list, 4);
5055 silc_hash_table_list_reset(&htl);
5056 silc_buffer_push(client_id_list,
5057 client_id_list->data - client_id_list->head);
5058 silc_buffer_push(client_mode_list,
5059 client_mode_list->data - client_mode_list->head);
5061 *user_list = client_id_list;
5062 *mode_list = client_mode_list;
5063 *user_count = list_count;
5067 /* Saves users and their modes to the `channel'. */
5069 void silc_server_save_users_on_channel(SilcServer server,
5070 SilcSocketConnection sock,
5071 SilcChannelEntry channel,
5072 SilcClientID *noadd,
5073 SilcBuffer user_list,
5074 SilcBuffer mode_list,
5075 SilcUInt32 user_count)
5080 SilcClientID *client_id;
5081 SilcClientEntry client;
5082 SilcIDCacheEntry cache;
5083 SilcChannelClientEntry chl;
5085 SILC_LOG_DEBUG(("Saving %d users on %s channel", user_count,
5086 channel->channel_name));
5088 for (i = 0; i < user_count; i++) {
5090 SILC_GET16_MSB(idp_len, user_list->data + 2);
5092 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
5093 silc_buffer_pull(user_list, idp_len);
5098 SILC_GET32_MSB(mode, mode_list->data);
5099 silc_buffer_pull(mode_list, 4);
5101 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
5102 silc_free(client_id);
5108 /* Check if we have this client cached already. */
5109 client = silc_idlist_find_client_by_id(server->local_list, client_id,
5110 server->server_type, &cache);
5112 client = silc_idlist_find_client_by_id(server->global_list,
5113 client_id, server->server_type,
5116 /* If router did not find such Client ID in its lists then this must
5117 be bogus client or some router in the net is buggy. */
5118 if (server->server_type != SILC_SERVER) {
5119 silc_free(client_id);
5123 /* We don't have that client anywhere, add it. The client is added
5124 to global list since server didn't have it in the lists so it must be
5126 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
5127 silc_id_dup(client_id, SILC_ID_CLIENT),
5128 sock->user_data, NULL, 0);
5130 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
5131 silc_free(client_id);
5135 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
5140 silc_free(client_id);
5142 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
5143 SILC_LOG_ERROR(("Attempting to add unregistered client to channel ",
5144 "%s", channel->channel_name));
5148 if (!silc_server_client_on_channel(client, channel, &chl)) {
5149 /* Client was not on the channel, add it. */
5150 chl = silc_calloc(1, sizeof(*chl));
5151 chl->client = client;
5153 chl->channel = channel;
5154 silc_hash_table_add(channel->user_list, chl->client, chl);
5155 silc_hash_table_add(client->channels, chl->channel, chl);
5156 channel->user_count++;
5164 /* Saves channels and channels user modes to the `client'. Removes
5165 the client from those channels that are not sent in the list but
5168 void silc_server_save_user_channels(SilcServer server,
5169 SilcSocketConnection sock,
5170 SilcClientEntry client,
5171 SilcBuffer channels,
5172 SilcBuffer channels_user_modes)
5175 SilcUInt32 *chumodes;
5176 SilcChannelPayload entry;
5177 SilcChannelEntry channel;
5178 SilcChannelID *channel_id;
5179 SilcChannelClientEntry chl;
5180 SilcHashTable ht = NULL;
5181 SilcHashTableList htl;
5185 if (!channels || !channels_user_modes ||
5186 !(client->data.status & SILC_IDLIST_STATUS_REGISTERED))
5189 ch = silc_channel_payload_parse_list(channels->data, channels->len);
5190 if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
5192 ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL,
5193 NULL, NULL, NULL, TRUE);
5194 silc_dlist_start(ch);
5195 while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
5196 /* Check if we have this channel, and add it if we don't have it.
5197 Also add the client on the channel unless it is there already. */
5198 channel_id = silc_channel_get_id_parse(entry);
5199 channel = silc_idlist_find_channel_by_id(server->local_list,
5202 channel = silc_idlist_find_channel_by_id(server->global_list,
5205 if (server->server_type != SILC_SERVER) {
5206 silc_free(channel_id);
5211 /* We don't have that channel anywhere, add it. */
5212 name = silc_channel_get_name(entry, NULL);
5213 channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
5214 channel_id, server->router,
5217 silc_free(channel_id);
5224 channel->mode = silc_channel_get_mode(entry);
5226 /* Add the client on the channel */
5227 if (!silc_server_client_on_channel(client, channel, &chl)) {
5228 chl = silc_calloc(1, sizeof(*chl));
5229 chl->client = client;
5230 chl->mode = chumodes[i++];
5231 chl->channel = channel;
5232 silc_hash_table_add(channel->user_list, chl->client, chl);
5233 silc_hash_table_add(client->channels, chl->channel, chl);
5234 channel->user_count++;
5237 chl->mode = chumodes[i++];
5240 silc_hash_table_add(ht, channel, channel);
5241 silc_free(channel_id);
5243 silc_channel_payload_list_free(ch);
5244 silc_free(chumodes);
5248 /* Go through the list again and remove client from channels that
5249 are no part of the list. */
5251 silc_hash_table_list(client->channels, &htl);
5252 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5253 if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
5254 silc_hash_table_del(chl->channel->user_list, chl->client);
5255 silc_hash_table_del(chl->client->channels, chl->channel);
5259 silc_hash_table_list_reset(&htl);
5260 silc_hash_table_free(ht);
5262 silc_hash_table_list(client->channels, &htl);
5263 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5264 silc_hash_table_del(chl->channel->user_list, chl->client);
5265 silc_hash_table_del(chl->client->channels, chl->channel);
5268 silc_hash_table_list_reset(&htl);
5272 /* Lookups route to the client indicated by the `id_data'. The connection
5273 object and internal data object is returned. Returns NULL if route
5274 could not be found to the client. If the `client_id' is specified then
5275 it is used and the `id_data' is ignored. */
5277 SilcSocketConnection
5278 silc_server_get_client_route(SilcServer server,
5279 unsigned char *id_data,
5281 SilcClientID *client_id,
5282 SilcIDListData *idata,
5283 SilcClientEntry *client_entry)
5286 SilcClientEntry client;
5288 SILC_LOG_DEBUG(("Start"));
5291 *client_entry = NULL;
5293 /* Decode destination Client ID */
5295 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
5297 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
5301 id = silc_id_dup(client_id, SILC_ID_CLIENT);
5304 /* If the destination belongs to our server we don't have to route
5305 the packet anywhere but to send it to the local destination. */
5306 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
5310 /* If we are router and the client has router then the client is in
5311 our cell but not directly connected to us. */
5312 if (server->server_type == SILC_ROUTER && client->router) {
5313 /* We are of course in this case the client's router thus the route
5314 to the client is the server who owns the client. So, we will send
5315 the packet to that server. */
5317 *idata = (SilcIDListData)client->router;
5318 return client->router->connection;
5321 /* Seems that client really is directly connected to us */
5323 *idata = (SilcIDListData)client;
5325 *client_entry = client;
5326 return client->connection;
5329 /* Destination belongs to someone not in this server. If we are normal
5330 server our action is to send the packet to our router. */
5331 if (server->server_type != SILC_ROUTER && !server->standalone) {
5334 *idata = (SilcIDListData)server->router;
5335 return SILC_PRIMARY_ROUTE(server);
5338 /* We are router and we will perform route lookup for the destination
5339 and send the packet to fastest route. */
5340 if (server->server_type == SILC_ROUTER && !server->standalone) {
5341 /* Check first that the ID is valid */
5342 client = silc_idlist_find_client_by_id(server->global_list, id,
5345 SilcSocketConnection dst_sock;
5347 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
5351 *idata = (SilcIDListData)dst_sock->user_data;
5360 /* Encodes and returns channel list of channels the `client' has joined.
5361 Secret channels are not put to the list. */
5363 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
5364 SilcClientEntry client,
5367 SilcBuffer *user_mode_list)
5369 SilcBuffer buffer = NULL;
5370 SilcChannelEntry channel;
5371 SilcChannelClientEntry chl;
5372 SilcHashTableList htl;
5375 SilcUInt16 name_len;
5379 *user_mode_list = NULL;
5381 silc_hash_table_list(client->channels, &htl);
5382 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5383 channel = chl->channel;
5385 if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
5387 if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
5390 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
5391 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
5392 name_len = strlen(channel->channel_name);
5394 len = 4 + name_len + id_len + 4;
5395 buffer = silc_buffer_realloc(buffer,
5396 (buffer ? buffer->truelen + len : len));
5397 silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
5398 silc_buffer_format(buffer,
5399 SILC_STR_UI_SHORT(name_len),
5400 SILC_STR_UI_XNSTRING(channel->channel_name,
5402 SILC_STR_UI_SHORT(id_len),
5403 SILC_STR_UI_XNSTRING(cid, id_len),
5404 SILC_STR_UI_INT(chl->channel->mode),
5406 silc_buffer_pull(buffer, len);
5409 if (user_mode_list) {
5410 *user_mode_list = silc_buffer_realloc(*user_mode_list,
5412 (*user_mode_list)->truelen + 4 :
5414 silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
5415 (*user_mode_list)->data));
5416 SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
5417 silc_buffer_pull(*user_mode_list, 4);
5420 silc_hash_table_list_reset(&htl);
5423 silc_buffer_push(buffer, buffer->data - buffer->head);
5424 if (user_mode_list && *user_mode_list)
5425 silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
5426 (*user_mode_list)->head));
5431 /* Timeout callback for unsuccessful rekey. The rekey did not go through
5434 SILC_TASK_CALLBACK(silc_server_rekey_timeout)
5436 SilcServerRekeyInternalContext *ctx = context;
5437 SilcServer server = app_context;
5438 SilcSocketConnection sock = ctx->sock;
5440 SILC_LOG_DEBUG(("Timeout occurred in rekey protocol with %s:%d [%s]",
5441 sock->hostname, sock->port,
5442 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5443 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5444 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5447 SILC_LOG_WARNING(("Timeout occurred in rekey protocol with %s:%d [%s]",
5448 sock->hostname, sock->port,
5449 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5450 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5451 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5454 if (sock->protocol) {
5455 silc_protocol_cancel(sock->protocol, server->schedule);
5456 silc_protocol_free(sock->protocol);
5457 sock->protocol = NULL;
5460 silc_packet_context_free(ctx->packet);
5462 silc_ske_free(ctx->ske);
5463 silc_socket_free(sock);
5466 /* Disconnect since we failed to rekey, the keys are probably wrong. */
5467 silc_server_disconnect_remote(server, sock,
5468 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
5469 if (sock->user_data)
5470 silc_server_free_sock_user_data(server, sock, NULL);
5473 if (sock->type != SILC_SOCKET_TYPE_CLIENT)
5474 silc_server_create_connections(server);
5477 /* A timeout callback for the re-key. We will be the initiator of the
5480 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_callback)
5482 SilcServer server = app_context;
5483 SilcSocketConnection sock = (SilcSocketConnection)context;
5484 SilcIDListData idata = (SilcIDListData)sock->user_data;
5485 SilcProtocol protocol;
5486 SilcServerRekeyInternalContext *proto_ctx;
5491 /* Do not execute rekey with disabled connections, as it would not
5492 go through anyway. */
5493 if (idata->status & SILC_IDLIST_STATUS_DISABLED)
5496 /* If rekey protocol is active already wait for it to finish */
5497 if (sock->protocol && sock->protocol->protocol &&
5498 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)
5501 /* If any other protocol is active do not start this protocol yet. */
5502 if (sock->protocol) {
5503 SILC_LOG_DEBUG(("Waiting for other protocol to finish before rekeying"));
5504 silc_schedule_task_add(server->schedule, sock->sock,
5505 silc_server_rekey_callback,
5506 sock, 60, 0, SILC_TASK_TIMEOUT,
5507 SILC_TASK_PRI_NORMAL);
5511 SILC_LOG_DEBUG(("Executing rekey protocol with %s:%d [%s]",
5512 sock->hostname, sock->port,
5513 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5514 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5515 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5518 /* Allocate internal protocol context. This is sent as context
5520 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
5521 proto_ctx->server = (void *)server;
5522 proto_ctx->sock = silc_socket_dup(sock);
5523 proto_ctx->responder = FALSE;
5524 proto_ctx->pfs = idata->rekey->pfs;
5526 /* Perform rekey protocol. Will call the final callback after the
5527 protocol is over. */
5528 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
5529 &protocol, proto_ctx, silc_server_rekey_final);
5530 sock->protocol = protocol;
5532 /* Register timeout callback in case the rekey does not go through. */
5533 proto_ctx->timeout_task =
5534 silc_schedule_task_add(server->schedule, sock->sock,
5535 silc_server_rekey_timeout,
5537 (idata->rekey->timeout >
5538 server->config->key_exchange_timeout ?
5539 idata->rekey->timeout :
5540 server->config->key_exchange_timeout * 4), 0,
5544 /* Run the protocol */
5545 silc_protocol_execute(protocol, server->schedule, 0, 0);
5548 /* The final callback for the REKEY protocol. This will actually take the
5549 new key material into use. */
5551 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
5553 SilcProtocol protocol = (SilcProtocol)context;
5554 SilcServerRekeyInternalContext *ctx =
5555 (SilcServerRekeyInternalContext *)protocol->context;
5556 SilcServer server = (SilcServer)ctx->server;
5557 SilcSocketConnection sock = ctx->sock;
5558 SilcIDListData idata = (SilcIDListData)sock->user_data;
5560 if (ctx->timeout_task)
5561 silc_schedule_task_del(server->schedule, ctx->timeout_task);
5563 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
5564 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
5565 /* Error occured during protocol */
5566 SILC_LOG_ERROR(("Error occurred during rekey protocol with "
5567 "%s (%s)", sock->hostname, sock->ip));
5568 silc_protocol_cancel(protocol, server->schedule);
5569 silc_protocol_free(protocol);
5570 sock->protocol = NULL;
5572 silc_packet_context_free(ctx->packet);
5574 silc_ske_free(ctx->ske);
5575 silc_socket_free(sock);
5577 silc_server_disconnect_remote(server, sock,
5578 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
5579 if (sock->user_data)
5580 silc_server_free_sock_user_data(server, sock, NULL);
5583 if (sock->type != SILC_SOCKET_TYPE_CLIENT)
5584 silc_server_create_connections(server);
5588 SILC_LOG_DEBUG(("Rekey protocol completed with %s:%d [%s]",
5589 sock->hostname, sock->port,
5590 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5591 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5592 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5595 /* Purge the outgoing data queue to assure that all rekey packets really
5596 go to the network before we quit the protocol. */
5597 silc_server_packet_queue_purge(server, sock);
5599 /* Re-register re-key timeout */
5600 if (ctx->responder == FALSE)
5601 silc_schedule_task_add(server->schedule, sock->sock,
5602 silc_server_rekey_callback,
5603 sock, idata->rekey->timeout, 0,
5604 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
5607 silc_protocol_free(protocol);
5608 sock->protocol = NULL;
5610 silc_packet_context_free(ctx->packet);
5612 silc_ske_free(ctx->ske);
5613 silc_socket_free(sock);
5617 /* Task callback used to retrieve network statistical information from
5618 router server once in a while. */
5620 SILC_TASK_CALLBACK(silc_server_get_stats)
5622 SilcServer server = (SilcServer)context;
5623 SilcBuffer idp, packet;
5625 if (!server->standalone) {
5626 SILC_LOG_DEBUG(("Retrieving stats from router"));
5627 idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
5628 packet = silc_command_payload_encode_va(SILC_COMMAND_STATS,
5629 ++server->cmd_ident, 1,
5630 1, idp->data, idp->len);
5631 silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
5632 SILC_PACKET_COMMAND, 0, packet->data,
5633 packet->len, FALSE);
5634 silc_buffer_free(packet);
5635 silc_buffer_free(idp);
5638 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
5639 server, 120, 0, SILC_TASK_TIMEOUT,