5 Author: Pekka Riikonen <priikone@silcnet.org>
7 Copyright (C) 1997 - 2003 Pekka Riikonen
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; version 2 of the License.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
20 * This is the actual SILC server than handles everything relating to
21 * servicing the SILC connections. This is also a SILC router as a router
22 * is also normal server.
26 #include "serverincludes.h"
27 #include "server_internal.h"
29 /* Static prototypes */
30 SILC_TASK_CALLBACK(silc_server_rehash_close_connection);
31 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry);
32 SILC_TASK_CALLBACK(silc_server_connect_router);
33 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
35 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
38 SILC_TASK_CALLBACK(silc_server_packet_process);
39 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
40 SILC_TASK_CALLBACK(silc_server_close_connection_final);
41 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout);
42 SILC_TASK_CALLBACK(silc_server_timeout_remote);
43 SILC_TASK_CALLBACK(silc_server_channel_key_rekey);
44 SILC_TASK_CALLBACK(silc_server_get_stats);
46 /* Allocates a new SILC server object. This has to be done before the server
47 can be used. After allocation one must call silc_server_init to initialize
48 the server. The new allocated server object is returned to the new_server
51 int silc_server_alloc(SilcServer *new_server)
55 SILC_LOG_DEBUG(("Allocating new server object"));
57 server = silc_calloc(1, sizeof(*server));
58 server->server_type = SILC_SERVER;
59 server->standalone = TRUE;
60 server->local_list = silc_calloc(1, sizeof(*server->local_list));
61 server->global_list = silc_calloc(1, sizeof(*server->global_list));
62 server->pending_commands = silc_dlist_init();
64 server->sim = silc_dlist_init();
72 /* Free's the SILC server object. This is called at the very end before
75 void silc_server_free(SilcServer server)
78 SilcIDCacheEntry cache;
86 silc_dlist_start(server->sim);
87 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
88 silc_dlist_del(server->sim, sim);
92 silc_dlist_uninit(server->sim);
96 silc_server_backup_free(server);
97 silc_server_config_unref(&server->config_ref);
99 silc_rng_free(server->rng);
101 silc_pkcs_free(server->pkcs);
102 if (server->public_key)
103 silc_pkcs_public_key_free(server->public_key);
104 if (server->private_key)
105 silc_pkcs_private_key_free(server->private_key);
106 if (server->pending_commands)
107 silc_dlist_uninit(server->pending_commands);
108 if (server->id_entry)
109 silc_idlist_del_server(server->local_list, server->id_entry);
111 /* Delete all channels */
113 if (silc_idcache_get_all(server->local_list->channels, &list) &&
114 silc_idcache_list_first(list, &cache)) {
115 silc_idlist_del_channel(server->local_list, cache->context);
116 while (silc_idcache_list_next(list, &cache))
117 silc_idlist_del_channel(server->local_list, cache->context);
120 silc_idcache_list_free(list);
122 if (silc_idcache_get_all(server->global_list->channels, &list) &&
123 silc_idcache_list_first(list, &cache)) {
124 silc_idlist_del_channel(server->global_list, cache->context);
125 while (silc_idcache_list_next(list, &cache))
126 silc_idlist_del_channel(server->global_list, cache->context);
129 silc_idcache_list_free(list);
131 /* Delete all clients */
133 if (silc_idcache_get_all(server->local_list->clients, &list) &&
134 silc_idcache_list_first(list, &cache)) {
135 silc_idlist_del_client(server->local_list, cache->context);
136 while (silc_idcache_list_next(list, &cache))
137 silc_idlist_del_client(server->local_list, cache->context);
140 silc_idcache_list_free(list);
142 if (silc_idcache_get_all(server->global_list->clients, &list) &&
143 silc_idcache_list_first(list, &cache)) {
144 silc_idlist_del_client(server->global_list, cache->context);
145 while (silc_idcache_list_next(list, &cache))
146 silc_idlist_del_client(server->global_list, cache->context);
149 silc_idcache_list_free(list);
151 /* Delete all servers */
153 if (silc_idcache_get_all(server->local_list->servers, &list) &&
154 silc_idcache_list_first(list, &cache)) {
155 silc_idlist_del_server(server->local_list, cache->context);
156 while (silc_idcache_list_next(list, &cache))
157 silc_idlist_del_server(server->local_list, cache->context);
160 silc_idcache_list_free(list);
162 if (silc_idcache_get_all(server->global_list->servers, &list) &&
163 silc_idcache_list_first(list, &cache)) {
164 silc_idlist_del_server(server->global_list, cache->context);
165 while (silc_idcache_list_next(list, &cache))
166 silc_idlist_del_server(server->global_list, cache->context);
169 silc_idcache_list_free(list);
171 silc_idcache_free(server->local_list->clients);
172 silc_idcache_free(server->local_list->servers);
173 silc_idcache_free(server->local_list->channels);
174 silc_idcache_free(server->global_list->clients);
175 silc_idcache_free(server->global_list->servers);
176 silc_idcache_free(server->global_list->channels);
177 silc_hash_table_free(server->watcher_list);
179 silc_hash_free(server->md5hash);
180 silc_hash_free(server->sha1hash);
181 silc_hmac_unregister_all();
182 silc_hash_unregister_all();
183 silc_cipher_unregister_all();
184 silc_pkcs_unregister_all();
186 silc_free(server->local_list);
187 silc_free(server->global_list);
188 silc_free(server->server_name);
189 silc_free(server->id_string);
190 silc_free(server->purge_i);
191 silc_free(server->purge_g);
195 /* Creates a new server listener. */
197 static bool silc_server_listen(SilcServer server, const char *server_ip,
198 SilcUInt16 port, int *sock)
200 *sock = silc_net_create_server(port, server_ip);
202 SILC_SERVER_LOG_ERROR(("Could not create server listener: %s on %hu",
209 /* Adds a secondary listener. */
211 bool silc_server_init_secondary(SilcServer server)
213 int sock = 0, sock_list[server->config->param.connections_max];
214 SilcSocketConnection newsocket = NULL;
215 SilcServerConfigServerInfoInterface *interface;
217 for (interface = server->config->server_info->secondary; interface;
218 interface = interface->next, sock++) {
220 if (!silc_server_listen(server,
221 interface->server_ip, interface->port, &sock_list[sock]))
224 /* Set socket to non-blocking mode */
225 silc_net_set_socket_nonblock(sock_list[sock]);
227 /* Add ourselves also to the socket table. The entry allocated above
228 is sent as argument for fast referencing in the future. */
229 silc_socket_alloc(sock_list[sock],
230 SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
231 server->sockets[sock_list[sock]] = newsocket;
232 SILC_SET_LISTENER(newsocket);
234 /* Perform name and address lookups to resolve the listenning address
236 if (!silc_net_check_local_by_sock(sock_list[sock], &newsocket->hostname,
238 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
240 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
241 newsocket->hostname ? newsocket->hostname :
242 newsocket->ip ? newsocket->ip : ""));
243 server->stat.conn_failures++;
246 if (!newsocket->hostname)
247 newsocket->hostname = strdup(newsocket->ip);
249 newsocket->port = silc_net_get_local_port(sock);
251 newsocket->user_data = (void *)server->id_entry;
252 silc_schedule_task_add(server->schedule, sock_list[sock],
253 silc_server_accept_new_connection,
254 (void *)server, 0, 0,
256 SILC_TASK_PRI_NORMAL);
262 do silc_net_close_server(sock_list[sock--]); while (sock >= 0);
266 /* Initializes the entire SILC server. This is called always before running
267 the server. This is called only once at the initialization of the program.
268 This binds the server to its listenning port. After this function returns
269 one should call silc_server_run to start the server. This returns TRUE
270 when everything is ok to run the server. Configuration file must be
271 read and parsed before calling this. */
273 bool silc_server_init(SilcServer server)
277 SilcServerEntry id_entry;
278 SilcIDListPurge purge;
279 SilcSocketConnection newsocket = NULL;
281 SILC_LOG_DEBUG(("Initializing server"));
283 server->starttime = time(NULL);
285 /* Take config object for us */
286 silc_server_config_ref(&server->config_ref, server->config,
290 /* Set debugging on if configured */
291 if (server->config->debug_string) {
293 silc_log_set_debug_string(server->config->debug_string);
295 #endif /* SILC_DEBUG */
297 /* Steal public and private key from the config object */
298 server->public_key = server->config->server_info->public_key;
299 server->private_key = server->config->server_info->private_key;
300 server->config->server_info->public_key = NULL;
301 server->config->server_info->private_key = NULL;
303 /* Register all configured ciphers, PKCS and hash functions. */
304 if (!silc_server_config_register_ciphers(server))
305 silc_cipher_register_default();
306 if (!silc_server_config_register_pkcs(server))
307 silc_pkcs_register_default();
308 if (!silc_server_config_register_hashfuncs(server))
309 silc_hash_register_default();
310 if (!silc_server_config_register_hmacs(server))
311 silc_hmac_register_default();
313 /* Initialize random number generator for the server. */
314 server->rng = silc_rng_alloc();
315 silc_rng_init(server->rng);
316 silc_rng_global_init(server->rng);
318 /* Initialize hash functions for server to use */
319 silc_hash_alloc("md5", &server->md5hash);
320 silc_hash_alloc("sha1", &server->sha1hash);
322 /* Allocate PKCS context for local public and private keys */
323 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
325 silc_pkcs_public_key_set(server->pkcs, server->public_key);
326 silc_pkcs_private_key_set(server->pkcs, server->private_key);
328 /* Initialize the scheduler */
329 server->schedule = silc_schedule_init(server->config->param.connections_max,
331 if (!server->schedule)
334 /* First, register log files configuration for error output */
335 silc_server_config_setlogfiles(server);
337 /* Initialize ID caches */
338 server->local_list->clients =
339 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
340 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
341 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
343 /* These are allocated for normal server as well as these hold some
344 global information that the server has fetched from its router. For
345 router these are used as they are supposed to be used on router. */
346 server->global_list->clients =
347 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
348 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
349 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
351 /* Init watcher list */
352 server->watcher_list =
353 silc_hash_table_alloc(1, silc_hash_client_id_hash, NULL,
354 silc_hash_data_compare, (void *)CLIENTID_HASH_LEN,
356 if (!server->watcher_list)
359 /* Create a listening server */
360 if (!silc_server_listen(server,
361 server->config->server_info->primary == NULL ? NULL :
362 server->config->server_info->primary->server_ip,
363 server->config->server_info->primary == NULL ? 0 :
364 server->config->server_info->primary->port,
368 /* Set socket to non-blocking mode */
369 silc_net_set_socket_nonblock(sock);
372 /* Allocate the entire socket list that is used in server. Eventually
373 all connections will have entry in this table (it is a table of
374 pointers to the actual object that is allocated individually
376 server->sockets = silc_calloc(server->config->param.connections_max,
377 sizeof(*server->sockets));
378 if (!server->sockets)
381 /* Add ourselves also to the socket table. The entry allocated above
382 is sent as argument for fast referencing in the future. */
383 silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
384 server->sockets[sock] = newsocket;
385 SILC_SET_LISTENER(newsocket);
387 /* Perform name and address lookups to resolve the listenning address
389 if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
391 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
393 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
394 newsocket->hostname ? newsocket->hostname :
395 newsocket->ip ? newsocket->ip : ""));
396 server->stat.conn_failures++;
399 if (!newsocket->hostname)
400 newsocket->hostname = strdup(newsocket->ip);
402 newsocket->port = silc_net_get_local_port(sock);
404 /* Create a Server ID for the server. */
405 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
410 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
411 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
412 server->server_name = server->config->server_info->server_name;
413 server->config->server_info->server_name = NULL;
415 /* Add ourselves to the server list. We don't have a router yet
416 beacuse we haven't established a route yet. It will be done later.
417 For now, NULL is sent as router. This allocates new entry to
420 silc_idlist_add_server(server->local_list, strdup(server->server_name),
421 server->server_type, server->id, NULL, NULL);
423 SILC_LOG_ERROR(("Could not add ourselves to cache"));
426 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
428 /* Put the allocated socket pointer also to the entry allocated above
429 for fast back-referencing to the socket list. */
430 newsocket->user_data = (void *)id_entry;
431 id_entry->connection = (void *)newsocket;
432 server->id_entry = id_entry;
434 /* Register protocols */
435 silc_server_protocols_register();
437 /* Create connections to configured routers. */
438 silc_server_create_connections(server);
440 /* Add listener task to the scheduler. This task receives new connections
441 to the server. This task remains on the queue until the end of the
443 silc_schedule_task_add(server->schedule, sock,
444 silc_server_accept_new_connection,
445 (void *)server, 0, 0,
447 SILC_TASK_PRI_NORMAL);
449 if (silc_server_init_secondary(server) == FALSE)
452 server->listenning = TRUE;
454 /* If server connections has been configured then we must be router as
455 normal server cannot have server connections, only router connections. */
456 if (server->config->servers) {
457 SilcServerConfigServer *ptr = server->config->servers;
459 server->server_type = SILC_ROUTER;
461 if (ptr->backup_router) {
462 server->server_type = SILC_BACKUP_ROUTER;
463 server->backup_router = TRUE;
464 server->id_entry->server_type = SILC_BACKUP_ROUTER;
471 /* Register the ID Cache purge task. This periodically purges the ID cache
472 and removes the expired cache entries. */
474 /* Clients local list */
475 server->purge_i = purge = silc_calloc(1, sizeof(*purge));
476 purge->cache = server->local_list->clients;
477 purge->timeout = 600;
478 silc_schedule_task_add(server->schedule, 0, silc_idlist_purge,
479 (void *)purge, purge->timeout, 0,
480 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
482 /* Clients global list */
483 server->purge_g = purge = silc_calloc(1, sizeof(*purge));
484 purge->cache = server->global_list->clients;
485 purge->timeout = 300;
486 silc_schedule_task_add(server->schedule, 0, silc_idlist_purge,
487 (void *)purge, purge->timeout, 0,
488 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
490 /* If we are normal server we'll retrieve network statisticial information
491 once in a while from the router. */
492 if (server->server_type != SILC_ROUTER)
493 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
494 server, 10, 0, SILC_TASK_TIMEOUT,
497 if (server->server_type == SILC_ROUTER)
498 server->stat.routers++;
500 SILC_LOG_DEBUG(("Server initialized"));
502 /* We are done here, return succesfully */
506 silc_server_config_unref(&server->config_ref);
507 silc_net_close_server(sock);
511 /* Task callback to close a socket connection after rehash */
513 SILC_TASK_CALLBACK(silc_server_rehash_close_connection)
515 SilcServer server = context;
516 SilcSocketConnection sock = server->sockets[fd];
521 SILC_LOG_INFO(("Connection %s:%d [%s] is unconfigured",
522 sock->hostname, sock->port,
523 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
524 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
525 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
527 silc_schedule_task_del_by_context(server->schedule, sock);
528 silc_server_disconnect_remote(server, sock,
529 SILC_STATUS_ERR_BANNED_FROM_SERVER,
530 "This connection is removed from "
533 silc_server_free_sock_user_data(server, sock, NULL);
536 /* This function basically reads the config file again and switches the config
537 object pointed by the server object. After that, we have to fix various
538 things such as the server_name and the listening ports.
539 Keep in mind that we no longer have the root privileges at this point. */
541 bool silc_server_rehash(SilcServer server)
543 SilcServerConfig newconfig;
545 SILC_LOG_INFO(("Rehashing server"));
547 /* Reset the logging system */
548 silc_log_quick = TRUE;
549 silc_log_flush_all();
551 /* Start the main rehash phase (read again the config file) */
552 newconfig = silc_server_config_alloc(server->config_file);
554 SILC_LOG_ERROR(("Rehash FAILED."));
558 /* Reinit scheduler if necessary */
559 if (newconfig->param.connections_max > server->config->param.connections_max)
560 if (!silc_schedule_reinit(server->schedule,
561 newconfig->param.connections_max))
564 /* Fix the server_name field */
565 if (strcmp(server->server_name, newconfig->server_info->server_name)) {
566 silc_free(server->server_name);
567 server->server_name = newconfig->server_info->server_name;
568 newconfig->server_info->server_name = NULL;
570 /* Update the idcache list with a fresh pointer */
571 silc_free(server->id_entry->server_name);
572 server->id_entry->server_name = strdup(server->server_name);
573 if (!silc_idcache_del_by_context(server->local_list->servers,
576 if (!silc_idcache_add(server->local_list->servers,
577 server->id_entry->server_name,
578 server->id_entry->id, server->id_entry, 0, NULL))
583 silc_server_config_setlogfiles(server);
585 /* Change new key pair if necessary */
586 if (newconfig->server_info->public_key &&
587 !silc_pkcs_public_key_compare(server->public_key,
588 newconfig->server_info->public_key)) {
589 silc_pkcs_public_key_free(server->public_key);
590 silc_pkcs_private_key_free(server->private_key);
591 server->public_key = newconfig->server_info->public_key;
592 server->private_key = newconfig->server_info->private_key;
593 newconfig->server_info->public_key = NULL;
594 newconfig->server_info->private_key = NULL;
596 /* Allocate PKCS context for local public and private keys */
597 silc_pkcs_free(server->pkcs);
598 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
600 silc_pkcs_public_key_set(server->pkcs, server->public_key);
601 silc_pkcs_private_key_set(server->pkcs, server->private_key);
604 /* Check for unconfigured server and router connections and close
605 connections that were unconfigured. */
607 if (server->config->routers) {
608 SilcServerConfigRouter *ptr;
609 SilcServerConfigRouter *newptr;
612 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
615 /* Check whether new config has this one too */
616 for (newptr = newconfig->routers; newptr; newptr = newptr->next) {
617 if (silc_string_compare(newptr->host, ptr->host) &&
618 newptr->port == ptr->port &&
619 newptr->initiator == ptr->initiator) {
625 if (!found && ptr->host) {
626 /* Remove this connection */
627 SilcSocketConnection sock;
628 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_ROUTER,
629 ptr->host, ptr->port);
630 if (sock && !SILC_IS_LISTENER(sock))
631 silc_schedule_task_add(server->schedule, sock->sock,
632 silc_server_rehash_close_connection,
633 server, 0, 1, SILC_TASK_TIMEOUT,
634 SILC_TASK_PRI_NORMAL);
639 if (server->config->servers) {
640 SilcServerConfigServer *ptr;
641 SilcServerConfigServer *newptr;
644 for (ptr = server->config->servers; ptr; ptr = ptr->next) {
647 /* Check whether new config has this one too */
648 for (newptr = newconfig->servers; newptr; newptr = newptr->next) {
649 if (silc_string_compare(newptr->host, ptr->host)) {
655 if (!found && ptr->host) {
656 /* Remove this connection */
657 SilcSocketConnection sock;
658 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_SERVER,
660 if (sock && !SILC_IS_LISTENER(sock))
661 silc_schedule_task_add(server->schedule, sock->sock,
662 silc_server_rehash_close_connection,
663 server, 0, 1, SILC_TASK_TIMEOUT,
664 SILC_TASK_PRI_NORMAL);
669 if (server->config->clients) {
670 SilcServerConfigClient *ptr;
671 SilcServerConfigClient *newptr;
674 for (ptr = server->config->clients; ptr; ptr = ptr->next) {
677 /* Check whether new config has this one too */
678 for (newptr = newconfig->clients; newptr; newptr = newptr->next) {
679 if (silc_string_compare(newptr->host, ptr->host)) {
685 if (!found && ptr->host) {
686 /* Remove this connection */
687 SilcSocketConnection sock;
688 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_CLIENT,
691 silc_schedule_task_add(server->schedule, sock->sock,
692 silc_server_rehash_close_connection,
693 server, 0, 1, SILC_TASK_TIMEOUT,
694 SILC_TASK_PRI_NORMAL);
699 /* Create connections after rehash */
700 silc_server_create_connections(server);
702 /* Check whether our router status has changed */
703 if (newconfig->servers) {
704 SilcServerConfigServer *ptr = newconfig->servers;
706 server->server_type = SILC_ROUTER;
708 if (ptr->backup_router) {
709 server->server_type = SILC_BACKUP_ROUTER;
710 server->backup_router = TRUE;
711 server->id_entry->server_type = SILC_BACKUP_ROUTER;
718 /* Our old config is gone now. We'll unreference our reference made in
719 silc_server_init and then destroy it since we are destroying it
720 underneath the application (layer which called silc_server_init). */
721 silc_server_config_unref(&server->config_ref);
722 silc_server_config_destroy(server->config);
724 /* Take new config context */
725 server->config = newconfig;
726 silc_server_config_ref(&server->config_ref, server->config, server->config);
729 /* Set debugging on if configured */
730 if (server->config->debug_string) {
732 silc_log_set_debug_string(server->config->debug_string);
736 #endif /* SILC_DEBUG */
738 SILC_LOG_DEBUG(("Server rehashed"));
743 /* The heart of the server. This runs the scheduler thus runs the server.
744 When this returns the server has been stopped and the program will
747 void silc_server_run(SilcServer server)
749 SILC_LOG_INFO(("SILC Server started"));
751 /* Start the scheduler, the heart of the SILC server. When this returns
752 the program will be terminated. */
753 silc_schedule(server->schedule);
756 /* Stops the SILC server. This function is used to shutdown the server.
757 This is usually called after the scheduler has returned. After stopping
758 the server one should call silc_server_free. */
760 void silc_server_stop(SilcServer server)
762 SILC_LOG_INFO(("SILC Server shutting down"));
764 if (server->schedule) {
767 server->server_shutdown = TRUE;
769 /* Close all connections */
770 for (i = 0; i < server->config->param.connections_max; i++) {
771 if (!server->sockets[i])
773 if (!SILC_IS_LISTENER(server->sockets[i])) {
774 SilcSocketConnection sock = server->sockets[i];
775 SilcIDListData idata = sock->user_data;
778 idata->status &= ~SILC_IDLIST_STATUS_DISABLED;
780 silc_schedule_task_del_by_context(server->schedule,
782 silc_schedule_task_del_by_fd(server->schedule,
783 server->sockets[i]->sock);
784 silc_server_disconnect_remote(server, server->sockets[i],
786 "Server is shutting down");
787 if (server->sockets[i]) {
789 silc_server_free_sock_user_data(server, sock,
790 "Server is shutting down");
791 silc_socket_free(sock);
794 silc_socket_free(server->sockets[i]);
795 server->sockets[i] = NULL;
799 /* We are not connected to network anymore */
800 server->standalone = TRUE;
802 silc_schedule_stop(server->schedule);
803 silc_schedule_uninit(server->schedule);
804 server->schedule = NULL;
806 silc_free(server->sockets);
807 server->sockets = NULL;
810 silc_server_protocols_unregister();
812 SILC_LOG_DEBUG(("Server stopped"));
815 /* Function that is called when the network connection to a router has
816 been established. This will continue with the key exchange protocol
817 with the remote router. */
819 void silc_server_start_key_exchange(SilcServer server,
820 SilcServerConnection sconn,
823 SilcSocketConnection newsocket;
824 SilcProtocol protocol;
825 SilcServerKEInternalContext *proto_ctx;
826 SilcServerConfigRouter *conn =
827 (SilcServerConfigRouter *) sconn->conn.ref_ptr;
830 /* Cancel any possible retry timeouts */
831 silc_schedule_task_del_by_callback(server->schedule,
832 silc_server_connect_to_router_retry);
834 /* Set socket options */
835 silc_net_set_socket_nonblock(sock);
836 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
838 /* Create socket connection for the connection. Even though we
839 know that we are connecting to a router we will mark the socket
840 to be unknown connection until we have executed authentication
842 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
843 server->sockets[sock] = newsocket;
844 newsocket->hostname = strdup(sconn->remote_host);
845 newsocket->ip = strdup(sconn->remote_host);
846 newsocket->port = sconn->remote_port;
847 sconn->sock = newsocket;
849 /* Allocate internal protocol context. This is sent as context
851 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
852 proto_ctx->server = (void *)server;
853 proto_ctx->context = (void *)sconn;
854 proto_ctx->sock = newsocket;
855 proto_ctx->rng = server->rng;
856 proto_ctx->responder = FALSE;
858 /* Set Key Exchange flags from configuration, but fall back to global
860 SILC_GET_SKE_FLAGS(conn, proto_ctx);
861 if (server->config->param.key_exchange_pfs)
862 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
864 /* Perform key exchange protocol. silc_server_connect_to_router_second
865 will be called after the protocol is finished. */
866 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
867 &protocol, proto_ctx,
868 silc_server_connect_to_router_second);
869 newsocket->protocol = protocol;
871 /* Register a timeout task that will be executed if the protocol
872 is not executed within set limit. */
873 proto_ctx->timeout_task =
874 silc_schedule_task_add(server->schedule, sock,
875 silc_server_timeout_remote,
876 server, server->config->key_exchange_timeout, 0,
880 /* Register the connection for network input and output. This sets
881 that scheduler will listen for incoming packets for this connection
882 and sets that outgoing packets may be sent to this connection as
883 well. However, this doesn't set the scheduler for outgoing traffic,
884 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
885 later when outgoing data is available. */
886 context = (void *)server;
887 SILC_REGISTER_CONNECTION_FOR_IO(sock);
889 /* Run the protocol */
890 silc_protocol_execute(protocol, server->schedule, 0, 0);
893 /* Timeout callback that will be called to retry connecting to remote
894 router. This is used by both normal and router server. This will wait
895 before retrying the connecting. The timeout is generated by exponential
896 backoff algorithm. */
898 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
900 SilcServer server = app_context;
901 SilcServerConnection sconn = (SilcServerConnection)context;
902 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
903 SilcServerConfigConnParams *param =
904 (conn->param ? conn->param : &server->config->param);
906 /* Don't retry if we are shutting down. */
907 if (server->server_shutdown) {
908 silc_server_config_unref(&sconn->conn);
909 silc_free(sconn->remote_host);
910 silc_free(sconn->backup_replace_ip);
915 SILC_LOG_INFO(("Retrying connecting to a router"));
917 /* Calculate next timeout */
918 if (sconn->retry_count >= 1) {
919 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
920 if (sconn->retry_timeout > param->reconnect_interval_max)
921 sconn->retry_timeout = param->reconnect_interval_max;
923 sconn->retry_timeout = param->reconnect_interval;
925 sconn->retry_count++;
926 sconn->retry_timeout = sconn->retry_timeout +
927 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
929 /* If we've reached max retry count, give up. */
930 if ((sconn->retry_count > param->reconnect_count) &&
931 !param->reconnect_keep_trying) {
932 SILC_LOG_ERROR(("Could not connect to router, giving up"));
933 silc_server_config_unref(&sconn->conn);
934 silc_free(sconn->remote_host);
935 silc_free(sconn->backup_replace_ip);
940 SILC_LOG_DEBUG(("Retrying connecting to a router in %d seconds",
941 sconn->retry_timeout));
943 /* We will lookup a fresh pointer later */
944 silc_server_config_unref(&sconn->conn);
946 /* Wait one before retrying */
947 silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
948 context, sconn->retry_timeout, 0,
949 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
952 /* Generic routine to use connect to a router. */
954 SILC_TASK_CALLBACK(silc_server_connect_router)
956 SilcServer server = app_context;
957 SilcServerConnection sconn = (SilcServerConnection)context;
958 SilcServerConfigRouter *rconn;
961 /* Don't connect if we are shutting down. */
962 if (server->server_shutdown) {
963 silc_free(sconn->remote_host);
964 silc_free(sconn->backup_replace_ip);
969 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
970 (sconn->backup ? "backup router" : "router"),
971 sconn->remote_host, sconn->remote_port));
973 server->router_connect = time(NULL);
974 rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
977 SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
978 (sconn->backup ? "backup router" : "router"),
979 sconn->remote_host, sconn->remote_port));
980 silc_free(sconn->remote_host);
981 silc_free(sconn->backup_replace_ip);
985 silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
987 /* Connect to remote host */
988 sock = silc_net_create_connection(
989 (!server->config->server_info->primary ? NULL :
990 server->config->server_info->primary->server_ip),
991 sconn->remote_port, sconn->remote_host);
993 SILC_LOG_ERROR(("Could not connect to router %s:%d",
994 sconn->remote_host, sconn->remote_port));
995 if (!sconn->no_reconnect)
996 silc_schedule_task_add(server->schedule, 0,
997 silc_server_connect_to_router_retry,
998 context, 0, 1, SILC_TASK_TIMEOUT,
999 SILC_TASK_PRI_NORMAL);
1001 silc_server_config_unref(&sconn->conn);
1002 silc_free(sconn->remote_host);
1003 silc_free(sconn->backup_replace_ip);
1009 /* Continue with key exchange protocol */
1010 silc_server_start_key_exchange(server, sconn, sock);
1013 /* This function connects to our primary router or if we are a router this
1014 establishes all our primary routes. This is called at the start of the
1015 server to do authentication and key exchange with our router - called
1018 SILC_TASK_CALLBACK_GLOBAL(silc_server_connect_to_router)
1020 SilcServer server = (SilcServer)context;
1021 SilcServerConnection sconn;
1022 SilcServerConfigRouter *ptr;
1024 /* Don't connect if we are shutting down. */
1025 if (server->server_shutdown)
1028 SILC_LOG_DEBUG(("We are %s",
1029 (server->server_type == SILC_SERVER ?
1030 "normal server" : server->server_type == SILC_ROUTER ?
1031 "router" : "backup router/normal server")));
1033 if (!server->config->routers) {
1034 /* There wasn't a configured router, we will continue but we don't
1035 have a connection to outside world. We will be standalone server. */
1036 SILC_LOG_DEBUG(("No router(s), we are standalone"));
1037 server->standalone = TRUE;
1041 /* Cancel any possible retry timeouts */
1042 silc_schedule_task_del_by_callback(server->schedule,
1043 silc_server_connect_router);
1044 silc_schedule_task_del_by_callback(server->schedule,
1045 silc_server_connect_to_router_retry);
1047 /* Create the connections to all our routes */
1048 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
1050 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
1051 ptr->backup_router ? "Backup router" : "Router",
1052 ptr->initiator ? "Initiator" : "Responder",
1053 ptr->host, ptr->port));
1055 if (server->server_type == SILC_ROUTER && ptr->backup_router &&
1056 ptr->initiator == FALSE && !server->backup_router &&
1057 !silc_server_config_get_backup_router(server))
1058 server->wait_backup = TRUE;
1060 if (ptr->initiator) {
1061 /* Check whether we are connecting or connected to this host already */
1062 if (silc_server_num_sockets_by_remote(server,
1063 silc_net_is_ip(ptr->host) ?
1065 silc_net_is_ip(ptr->host) ?
1066 NULL : ptr->host, ptr->port,
1067 SILC_SOCKET_TYPE_ROUTER)) {
1068 SILC_LOG_DEBUG(("We are already connected to this router"));
1070 /* If we don't have primary router and this connection is our
1071 primary router we are in desync. Reconnect to the primary. */
1072 if (server->standalone && !server->router) {
1073 SilcServerConfigRouter *primary =
1074 silc_server_config_get_primary_router(server);
1075 if (primary == ptr) {
1076 SilcSocketConnection sock =
1077 silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_ROUTER,
1078 ptr->host, ptr->port);
1080 server->backup_noswitch = TRUE;
1081 if (sock->user_data)
1082 silc_server_free_sock_user_data(server, sock, NULL);
1083 silc_server_disconnect_remote(server, sock, 0, NULL);
1084 server->backup_noswitch = FALSE;
1085 SILC_LOG_DEBUG(("Reconnecting to primary router"));
1096 if (silc_server_num_sockets_by_remote(server,
1097 silc_net_is_ip(ptr->host) ?
1099 silc_net_is_ip(ptr->host) ?
1100 NULL : ptr->host, ptr->port,
1101 SILC_SOCKET_TYPE_UNKNOWN)) {
1102 SILC_LOG_DEBUG(("We are already connecting to this router"));
1106 /* Allocate connection object for hold connection specific stuff. */
1107 sconn = silc_calloc(1, sizeof(*sconn));
1108 sconn->remote_host = strdup(ptr->host);
1109 sconn->remote_port = ptr->port;
1110 sconn->backup = ptr->backup_router;
1111 if (sconn->backup) {
1112 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
1113 sconn->backup_replace_port = ptr->backup_replace_port;
1116 if (!server->router_conn && !sconn->backup)
1117 server->router_conn = sconn;
1119 silc_schedule_task_add(server->schedule, 0,
1120 silc_server_connect_router,
1121 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
1122 SILC_TASK_PRI_NORMAL);
1127 /* Second part of connecting to router(s). Key exchange protocol has been
1128 executed and now we will execute authentication protocol. */
1130 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
1132 SilcProtocol protocol = (SilcProtocol)context;
1133 SilcServerKEInternalContext *ctx =
1134 (SilcServerKEInternalContext *)protocol->context;
1135 SilcServer server = (SilcServer)ctx->server;
1136 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1137 SilcSocketConnection sock = ctx->sock;
1138 SilcServerConnAuthInternalContext *proto_ctx;
1139 SilcServerConfigRouter *conn = NULL;
1141 SILC_LOG_DEBUG(("Start"));
1143 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1144 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1145 /* Error occured during protocol */
1146 silc_protocol_free(protocol);
1147 sock->protocol = NULL;
1148 silc_ske_free_key_material(ctx->keymat);
1150 silc_packet_context_free(ctx->packet);
1152 silc_ske_free(ctx->ske);
1153 silc_free(ctx->dest_id);
1155 silc_server_disconnect_remote(server, sock,
1156 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1158 /* Try reconnecting if configuration wants it */
1159 if (!sconn->no_reconnect) {
1160 silc_schedule_task_add(server->schedule, 0,
1161 silc_server_connect_to_router_retry,
1162 sconn, 0, 1, SILC_TASK_TIMEOUT,
1163 SILC_TASK_PRI_NORMAL);
1167 /* Call completion to indicate error */
1168 if (sconn->callback)
1169 (*sconn->callback)(server, NULL, sconn->callback_context);
1171 silc_server_config_unref(&sconn->conn);
1172 silc_free(sconn->remote_host);
1173 silc_free(sconn->backup_replace_ip);
1178 /* We now have the key material as the result of the key exchange
1179 protocol. Take the key material into use. Free the raw key material
1180 as soon as we've set them into use. */
1181 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1182 ctx->sock, ctx->keymat,
1183 ctx->ske->prop->cipher,
1184 ctx->ske->prop->pkcs,
1185 ctx->ske->prop->hash,
1186 ctx->ske->prop->hmac,
1187 ctx->ske->prop->group,
1189 silc_protocol_free(protocol);
1190 sock->protocol = NULL;
1191 silc_ske_free_key_material(ctx->keymat);
1193 silc_packet_context_free(ctx->packet);
1195 silc_ske_free(ctx->ske);
1196 silc_free(ctx->dest_id);
1198 silc_server_disconnect_remote(server, sock,
1199 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1201 /* Try reconnecting if configuration wants it */
1202 if (!sconn->no_reconnect) {
1203 silc_schedule_task_add(server->schedule, 0,
1204 silc_server_connect_to_router_retry,
1205 sconn, 0, 1, SILC_TASK_TIMEOUT,
1206 SILC_TASK_PRI_NORMAL);
1210 /* Call completion to indicate error */
1211 if (sconn->callback)
1212 (*sconn->callback)(server, NULL, sconn->callback_context);
1214 silc_server_config_unref(&sconn->conn);
1215 silc_free(sconn->remote_host);
1216 silc_free(sconn->backup_replace_ip);
1220 silc_ske_free_key_material(ctx->keymat);
1222 /* Allocate internal context for the authentication protocol. This
1223 is sent as context for the protocol. */
1224 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1225 proto_ctx->server = (void *)server;
1226 proto_ctx->context = (void *)sconn;
1227 proto_ctx->sock = sock;
1228 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1229 proto_ctx->dest_id_type = ctx->dest_id_type;
1230 proto_ctx->dest_id = ctx->dest_id;
1232 /* Resolve the authentication method used in this connection. Check if
1233 we find a match from user configured connections */
1234 if (!sconn->conn.ref_ptr)
1235 conn = silc_server_config_find_router_conn(server, sock->hostname,
1238 conn = sconn->conn.ref_ptr;
1241 /* Match found. Use the configured authentication method. Take only
1242 the passphrase, since for public key auth we automatically use
1243 our local key pair. */
1244 if (conn->passphrase) {
1245 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
1246 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1248 proto_ctx->auth_data = strdup(conn->passphrase);
1249 proto_ctx->auth_data_len = strlen(conn->passphrase);
1250 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
1252 } else if (conn->publickeys) {
1253 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1255 proto_ctx->auth_meth = SILC_AUTH_NONE;
1258 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
1259 sock->hostname, sock->ip, sock->port));
1260 silc_protocol_free(protocol);
1261 sock->protocol = NULL;
1263 silc_packet_context_free(ctx->packet);
1265 silc_ske_free(ctx->ske);
1266 silc_free(ctx->dest_id);
1268 silc_server_config_unref(&sconn->conn);
1269 silc_free(sconn->remote_host);
1270 silc_free(sconn->backup_replace_ip);
1272 silc_server_disconnect_remote(server, sock,
1273 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1277 /* Free old protocol as it is finished now */
1278 silc_protocol_free(protocol);
1280 silc_packet_context_free(ctx->packet);
1282 sock->protocol = NULL;
1284 /* Allocate the authentication protocol. This is allocated here
1285 but we won't start it yet. We will be receiving party of this
1286 protocol thus we will wait that connecting party will make
1287 their first move. */
1288 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1289 &sock->protocol, proto_ctx,
1290 silc_server_connect_to_router_final);
1292 /* Register timeout task. If the protocol is not executed inside
1293 this timelimit the connection will be terminated. */
1294 proto_ctx->timeout_task =
1295 silc_schedule_task_add(server->schedule, sock->sock,
1296 silc_server_timeout_remote,
1298 server->config->conn_auth_timeout, 0,
1302 /* Run the protocol */
1303 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1306 /* Finalizes the connection to router. Registers a server task to the
1307 queue so that we can accept new connections. */
1309 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
1311 SilcProtocol protocol = (SilcProtocol)context;
1312 SilcServerConnAuthInternalContext *ctx =
1313 (SilcServerConnAuthInternalContext *)protocol->context;
1314 SilcServer server = (SilcServer)ctx->server;
1315 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1316 SilcSocketConnection sock = ctx->sock;
1317 SilcServerEntry id_entry = NULL;
1319 unsigned char *id_string;
1321 SilcIDListData idata;
1322 SilcServerConfigRouter *conn = NULL;
1323 SilcServerConfigConnParams *param = NULL;
1325 SILC_LOG_DEBUG(("Start"));
1327 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1328 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1329 /* Error occured during protocol */
1330 silc_free(ctx->dest_id);
1331 sock->protocol = NULL;
1332 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1334 sock->protocol = protocol;
1336 /* Try reconnecting if configuration wants it */
1337 if (!sconn->no_reconnect) {
1338 silc_schedule_task_add(server->schedule, 0,
1339 silc_server_connect_to_router_retry,
1340 sconn, 0, 1, SILC_TASK_TIMEOUT,
1341 SILC_TASK_PRI_NORMAL);
1348 /* Add a task to the queue. This task receives new connections to the
1349 server. This task remains on the queue until the end of the program. */
1350 if (!server->listenning && !sconn->backup) {
1351 silc_schedule_task_add(server->schedule, server->sock,
1352 silc_server_accept_new_connection,
1353 (void *)server, 0, 0,
1355 SILC_TASK_PRI_NORMAL);
1356 server->listenning = TRUE;
1359 /* Send NEW_SERVER packet to the router. We will become registered
1360 to the SILC network after sending this packet. */
1361 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
1362 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1363 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
1364 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1365 silc_buffer_format(packet,
1366 SILC_STR_UI_SHORT(id_len),
1367 SILC_STR_UI_XNSTRING(id_string, id_len),
1368 SILC_STR_UI_SHORT(strlen(server->server_name)),
1369 SILC_STR_UI_XNSTRING(server->server_name,
1370 strlen(server->server_name)),
1373 /* Send the packet */
1374 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
1375 packet->data, packet->len, TRUE);
1376 silc_buffer_free(packet);
1377 silc_free(id_string);
1379 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
1381 /* Check that we do not have this ID already */
1382 id_entry = silc_idlist_find_server_by_id(server->local_list,
1383 ctx->dest_id, TRUE, NULL);
1385 silc_idcache_del_by_context(server->local_list->servers, id_entry);
1387 id_entry = silc_idlist_find_server_by_id(server->global_list,
1388 ctx->dest_id, TRUE, NULL);
1390 silc_idcache_del_by_context(server->global_list->servers, id_entry);
1393 SILC_LOG_DEBUG(("New server id(%s)",
1394 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1396 /* Add the connected router to global server list. Router is sent
1397 as NULL since it's local to us. */
1398 id_entry = silc_idlist_add_server(server->global_list,
1399 strdup(sock->hostname),
1400 SILC_ROUTER, ctx->dest_id, NULL, sock);
1402 silc_free(ctx->dest_id);
1403 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1404 sock->protocol = NULL;
1405 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1407 sock->protocol = protocol;
1411 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1412 silc_free(sock->user_data);
1413 sock->user_data = (void *)id_entry;
1414 sock->type = SILC_SOCKET_TYPE_ROUTER;
1415 idata = (SilcIDListData)sock->user_data;
1416 idata->status |= (SILC_IDLIST_STATUS_REGISTERED |
1417 SILC_IDLIST_STATUS_LOCAL);
1419 conn = sconn->conn.ref_ptr;
1420 param = &server->config->param;
1421 if (conn && conn->param)
1422 param = conn->param;
1424 /* Perform keepalive. */
1425 silc_socket_set_heartbeat(sock, param->keepalive_secs, server,
1426 silc_server_perform_heartbeat,
1429 /* Register re-key timeout */
1430 idata->rekey->timeout = param->key_exchange_rekey;
1431 silc_schedule_task_add(server->schedule, sock->sock,
1432 silc_server_rekey_callback,
1433 (void *)sock, idata->rekey->timeout, 0,
1434 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1436 if (!sconn->backup) {
1437 /* Mark this router our primary router if we're still standalone */
1438 if (server->standalone) {
1439 SILC_LOG_DEBUG(("This connection is our primary router"));
1440 server->id_entry->router = id_entry;
1441 server->router = id_entry;
1442 server->router->server_type = SILC_ROUTER;
1443 server->standalone = FALSE;
1444 server->backup_primary = FALSE;
1446 /* Announce data if we are not backup router (unless not as primary
1447 currently). Backup router announces later at the end of
1448 resuming protocol. */
1449 if (server->backup_router && server->server_type == SILC_ROUTER) {
1450 SILC_LOG_DEBUG(("Announce data after resume protocol"));
1452 /* If we are router then announce our possible servers. Backup
1453 router announces also global servers. */
1454 if (server->server_type == SILC_ROUTER)
1455 silc_server_announce_servers(server,
1456 server->backup_router ? TRUE : FALSE,
1457 0, SILC_PRIMARY_ROUTE(server));
1459 /* Announce our clients and channels to the router */
1460 silc_server_announce_clients(server, 0, SILC_PRIMARY_ROUTE(server));
1461 silc_server_announce_channels(server, 0, SILC_PRIMARY_ROUTE(server));
1464 /* If we are backup router then this primary router is whom we are
1466 if (server->server_type == SILC_BACKUP_ROUTER)
1467 silc_server_backup_add(server, server->id_entry, sock->ip,
1468 sconn->remote_port, TRUE);
1471 /* Add this server to be our backup router */
1472 id_entry->server_type = SILC_BACKUP_ROUTER;
1473 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1474 sconn->backup_replace_port, FALSE);
1477 sock->protocol = NULL;
1480 /* Call the completion callback to indicate that we've connected to
1482 if (sconn && sconn->callback)
1483 (*sconn->callback)(server, id_entry, sconn->callback_context);
1485 /* Free the temporary connection data context */
1487 silc_server_config_unref(&sconn->conn);
1488 silc_free(sconn->remote_host);
1489 silc_free(sconn->backup_replace_ip);
1492 if (sconn == server->router_conn)
1493 server->router_conn = NULL;
1496 /* Free the protocol object */
1497 if (sock->protocol == protocol)
1498 sock->protocol = NULL;
1499 silc_protocol_free(protocol);
1501 silc_packet_context_free(ctx->packet);
1503 silc_ske_free(ctx->ske);
1504 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1505 silc_free(ctx->auth_data);
1509 /* Host lookup callback that is called after the incoming connection's
1510 IP and FQDN lookup is performed. This will actually check the acceptance
1511 of the incoming connection and will register the key exchange protocol
1512 for this connection. */
1515 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1518 SilcServerKEInternalContext *proto_ctx =
1519 (SilcServerKEInternalContext *)context;
1520 SilcServer server = (SilcServer)proto_ctx->server;
1521 SilcServerConfigClient *cconfig = NULL;
1522 SilcServerConfigServer *sconfig = NULL;
1523 SilcServerConfigRouter *rconfig = NULL;
1524 SilcServerConfigDeny *deny;
1527 /* Check whether we could resolve both IP and FQDN. */
1528 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1529 server->config->require_reverse_lookup)) {
1530 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1531 sock->hostname ? sock->hostname :
1532 sock->ip ? sock->ip : ""));
1533 server->stat.conn_failures++;
1534 silc_server_disconnect_remote(server, sock,
1535 SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
1536 "Unknown host or IP");
1537 silc_free(proto_ctx);
1541 /* Register the connection for network input and output. This sets
1542 that scheduler will listen for incoming packets for this connection
1543 and sets that outgoing packets may be sent to this connection as well.
1544 However, this doesn't set the scheduler for outgoing traffic, it
1545 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1546 later when outgoing data is available. */
1547 context = (void *)server;
1548 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1550 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1553 /* Listenning port */
1554 if (!server->sockets[(SilcUInt32)proto_ctx->context]) {
1555 silc_server_disconnect_remote(server, sock,
1556 SILC_STATUS_ERR_RESOURCE_LIMIT,
1557 "Connection refused");
1558 server->stat.conn_failures++;
1559 silc_free(proto_ctx);
1562 port = server->sockets[(SilcUInt32)proto_ctx->context]->port;
1564 /* Check whether this connection is denied to connect to us. */
1565 deny = silc_server_config_find_denied(server, sock->ip);
1567 deny = silc_server_config_find_denied(server, sock->hostname);
1569 /* The connection is denied */
1570 SILC_LOG_INFO(("Connection %s (%s) is denied",
1571 sock->hostname, sock->ip));
1572 silc_server_disconnect_remote(server, sock,
1573 SILC_STATUS_ERR_BANNED_FROM_SERVER,
1575 server->stat.conn_failures++;
1576 silc_free(proto_ctx);
1580 /* Check whether we have configured this sort of connection at all. We
1581 have to check all configurations since we don't know what type of
1582 connection this is. */
1583 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1584 cconfig = silc_server_config_find_client(server, sock->hostname);
1585 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1586 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1587 if (server->server_type == SILC_ROUTER) {
1588 if (!(rconfig = silc_server_config_find_router_conn(server,
1589 sock->ip, sock->port)))
1590 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1593 if (!cconfig && !sconfig && !rconfig) {
1594 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1596 silc_server_disconnect_remote(server, sock,
1597 SILC_STATUS_ERR_BANNED_FROM_SERVER, NULL);
1598 server->stat.conn_failures++;
1599 silc_free(proto_ctx);
1603 /* The connection is allowed */
1605 /* Set internal context for key exchange protocol. This is
1606 sent as context for the protocol. */
1607 proto_ctx->sock = sock;
1608 proto_ctx->rng = server->rng;
1609 proto_ctx->responder = TRUE;
1610 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1611 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1612 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1614 /* Take flags for key exchange. Since we do not know what type of connection
1615 this is, we go through all found configurations and use the global ones
1616 as well. This will result always into strictest key exchange flags. */
1617 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1618 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1619 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1620 if (server->config->param.key_exchange_pfs)
1621 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1623 /* Prepare the connection for key exchange protocol. We allocate the
1624 protocol but will not start it yet. The connector will be the
1625 initiator of the protocol thus we will wait for initiation from
1626 there before we start the protocol. */
1627 server->stat.auth_attempts++;
1628 SILC_LOG_DEBUG(("Starting key exchange protocol"));
1629 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1630 &sock->protocol, proto_ctx,
1631 silc_server_accept_new_connection_second);
1633 /* Register a timeout task that will be executed if the connector
1634 will not start the key exchange protocol within specified timeout
1635 and the connection will be closed. */
1636 proto_ctx->timeout_task =
1637 silc_schedule_task_add(server->schedule, sock->sock,
1638 silc_server_timeout_remote,
1640 server->config->key_exchange_timeout, 0,
1645 /* Accepts new connections to the server. Accepting new connections are
1646 done in three parts to make it async. */
1648 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1650 SilcServer server = (SilcServer)context;
1651 SilcSocketConnection newsocket;
1652 SilcServerKEInternalContext *proto_ctx;
1655 SILC_LOG_DEBUG(("Accepting new connection"));
1657 server->stat.conn_attempts++;
1659 sock = silc_net_accept_connection(fd);
1661 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1662 server->stat.conn_failures++;
1666 /* Check for maximum allowed connections */
1667 if (sock > server->config->param.connections_max) {
1668 SILC_LOG_ERROR(("Refusing connection, server is full"));
1669 server->stat.conn_failures++;
1670 silc_net_close_connection(sock);
1674 /* Set socket options */
1675 silc_net_set_socket_nonblock(sock);
1676 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1678 /* We don't create a ID yet, since we don't know what type of connection
1679 this is yet. But, we do add the connection to the socket table. */
1680 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1681 server->sockets[sock] = newsocket;
1683 /* Perform asynchronous host lookup. This will lookup the IP and the
1684 FQDN of the remote connection. After the lookup is done the connection
1685 is accepted further. */
1686 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1687 proto_ctx->server = server;
1688 proto_ctx->context = (void *)fd;
1689 silc_socket_host_lookup(newsocket, TRUE,
1690 silc_server_accept_new_connection_lookup,
1691 (void *)proto_ctx, server->schedule);
1694 /* Second part of accepting new connection. Key exchange protocol has been
1695 performed and now it is time to do little connection authentication
1696 protocol to figure out whether this connection is client or server
1697 and whether it has right to access this server (especially server
1698 connections needs to be authenticated). */
1700 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1702 SilcProtocol protocol = (SilcProtocol)context;
1703 SilcServerKEInternalContext *ctx =
1704 (SilcServerKEInternalContext *)protocol->context;
1705 SilcServer server = (SilcServer)ctx->server;
1706 SilcSocketConnection sock = ctx->sock;
1707 SilcServerConnAuthInternalContext *proto_ctx;
1709 SILC_LOG_DEBUG(("Start"));
1711 if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1712 (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1713 /* Error occured during protocol */
1714 SILC_LOG_DEBUG(("Error in key exchange protocol"));
1715 silc_protocol_free(protocol);
1716 sock->protocol = NULL;
1717 silc_ske_free_key_material(ctx->keymat);
1719 silc_packet_context_free(ctx->packet);
1721 silc_ske_free(ctx->ske);
1722 silc_free(ctx->dest_id);
1723 silc_server_config_unref(&ctx->cconfig);
1724 silc_server_config_unref(&ctx->sconfig);
1725 silc_server_config_unref(&ctx->rconfig);
1728 if (!SILC_IS_DISCONNECTING(sock)) {
1729 SILC_LOG_INFO(("Key exchange failed for %s:%d [%s]", sock->hostname,
1731 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1732 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1733 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1735 silc_server_disconnect_remote(server, sock,
1736 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
1740 server->stat.auth_failures++;
1744 /* We now have the key material as the result of the key exchange
1745 protocol. Take the key material into use. Free the raw key material
1746 as soon as we've set them into use. */
1747 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1748 ctx->sock, ctx->keymat,
1749 ctx->ske->prop->cipher,
1750 ctx->ske->prop->pkcs,
1751 ctx->ske->prop->hash,
1752 ctx->ske->prop->hmac,
1753 ctx->ske->prop->group,
1755 SILC_LOG_ERROR(("Error setting key material in use"));
1756 silc_protocol_free(protocol);
1757 sock->protocol = NULL;
1758 silc_ske_free_key_material(ctx->keymat);
1760 silc_packet_context_free(ctx->packet);
1762 silc_ske_free(ctx->ske);
1763 silc_free(ctx->dest_id);
1764 silc_server_config_unref(&ctx->cconfig);
1765 silc_server_config_unref(&ctx->sconfig);
1766 silc_server_config_unref(&ctx->rconfig);
1768 silc_server_disconnect_remote(server, sock,
1769 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1770 server->stat.auth_failures++;
1773 silc_ske_free_key_material(ctx->keymat);
1775 /* Allocate internal context for the authentication protocol. This
1776 is sent as context for the protocol. */
1777 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1778 proto_ctx->server = (void *)server;
1779 proto_ctx->sock = sock;
1780 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1781 proto_ctx->responder = TRUE;
1782 proto_ctx->dest_id_type = ctx->dest_id_type;
1783 proto_ctx->dest_id = ctx->dest_id;
1784 proto_ctx->cconfig = ctx->cconfig;
1785 proto_ctx->sconfig = ctx->sconfig;
1786 proto_ctx->rconfig = ctx->rconfig;
1788 /* Free old protocol as it is finished now */
1789 silc_protocol_free(protocol);
1791 silc_packet_context_free(ctx->packet);
1793 sock->protocol = NULL;
1795 /* Allocate the authentication protocol. This is allocated here
1796 but we won't start it yet. We will be receiving party of this
1797 protocol thus we will wait that connecting party will make
1798 their first move. */
1799 SILC_LOG_DEBUG(("Starting connection authentication protocol"));
1800 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1801 &sock->protocol, proto_ctx,
1802 silc_server_accept_new_connection_final);
1804 /* Register timeout task. If the protocol is not executed inside
1805 this timelimit the connection will be terminated. */
1806 proto_ctx->timeout_task =
1807 silc_schedule_task_add(server->schedule, sock->sock,
1808 silc_server_timeout_remote,
1810 server->config->conn_auth_timeout, 0,
1815 /* After this is called, server don't wait for backup router anymore.
1816 This gets called automatically even after we have backup router
1817 connection established. */
1819 SILC_TASK_CALLBACK(silc_server_backup_router_wait)
1821 SilcServer server = context;
1822 server->wait_backup = FALSE;
1825 /* Final part of accepting new connection. The connection has now
1826 been authenticated and keys has been exchanged. We also know whether
1827 this is client or server connection. */
1829 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1831 SilcProtocol protocol = (SilcProtocol)context;
1832 SilcServerConnAuthInternalContext *ctx =
1833 (SilcServerConnAuthInternalContext *)protocol->context;
1834 SilcServer server = (SilcServer)ctx->server;
1835 SilcSocketConnection sock = ctx->sock;
1836 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1838 SilcServerConfigConnParams *param = &server->config->param;
1840 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1841 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1842 /* Error occured during protocol */
1843 SILC_LOG_DEBUG(("Error during authentication protocol"));
1844 silc_protocol_free(protocol);
1845 sock->protocol = NULL;
1847 silc_packet_context_free(ctx->packet);
1849 silc_ske_free(ctx->ske);
1850 silc_free(ctx->dest_id);
1851 silc_server_config_unref(&ctx->cconfig);
1852 silc_server_config_unref(&ctx->sconfig);
1853 silc_server_config_unref(&ctx->rconfig);
1856 if (!SILC_IS_DISCONNECTING(sock)) {
1857 SILC_LOG_INFO(("Authentication failed for %s:%d [%s]", sock->hostname,
1859 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1860 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1861 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1863 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1866 server->stat.auth_failures++;
1870 entry->data.last_receive = time(NULL);
1872 switch (ctx->conn_type) {
1873 case SILC_SOCKET_TYPE_CLIENT:
1875 SilcClientEntry client;
1876 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1878 /* Verify whether this connection is after all allowed to connect */
1879 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1880 &server->config->param,
1881 conn->param, ctx->ske)) {
1882 server->stat.auth_failures++;
1886 /* If we are primary router and we have backup router configured
1887 but it has not connected to use yet, do not accept any other
1889 if (server->wait_backup && server->server_type == SILC_ROUTER &&
1890 !server->backup_router) {
1891 SilcServerConfigRouter *router;
1892 router = silc_server_config_get_backup_router(server);
1893 if (router && strcmp(server->config->server_info->primary->server_ip,
1895 silc_server_find_socket_by_host(server,
1896 SILC_SOCKET_TYPE_SERVER,
1897 router->backup_replace_ip, 0)) {
1898 SILC_LOG_INFO(("Will not accept connections because we do "
1899 "not have backup router connection established"));
1900 sock->protocol = NULL;
1901 silc_server_disconnect_remote(server, sock,
1902 SILC_STATUS_ERR_PERM_DENIED,
1903 "We do not have connection to backup "
1904 "router established, try later");
1905 silc_free(sock->user_data);
1906 server->stat.auth_failures++;
1908 /* From here on, wait 10 seconds for the backup router to appear. */
1909 silc_schedule_task_add(server->schedule, 0,
1910 silc_server_backup_router_wait,
1911 (void *)server, 10, 0,
1912 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1917 SILC_LOG_DEBUG(("Remote host is client"));
1918 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1921 /* Add the client to the client ID cache. The nickname and Client ID
1922 and other information is created after we have received NEW_CLIENT
1923 packet from client. */
1924 client = silc_idlist_add_client(server->local_list,
1925 NULL, NULL, NULL, NULL, NULL, sock, 0);
1927 SILC_LOG_ERROR(("Could not add new client to cache"));
1928 silc_free(sock->user_data);
1929 sock->protocol = NULL;
1930 silc_server_disconnect_remote(server, sock,
1931 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1932 server->stat.auth_failures++;
1935 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
1938 server->stat.my_clients++;
1939 server->stat.clients++;
1940 server->stat.cell_clients++;
1942 /* Get connection parameters */
1944 param = conn->param;
1946 if (!param->keepalive_secs)
1947 param->keepalive_secs = server->config->param.keepalive_secs;
1949 if (!param->qos && server->config->param.qos) {
1950 param->qos = server->config->param.qos;
1951 param->qos_rate_limit = server->config->param.qos_rate_limit;
1952 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
1953 param->qos_limit_sec = server->config->param.qos_limit_sec;
1954 param->qos_limit_usec = server->config->param.qos_limit_usec;
1957 /* Check if to be anonymous connection */
1958 if (param->anonymous)
1959 client->mode |= SILC_UMODE_ANONYMOUS;
1962 id_entry = (void *)client;
1965 case SILC_SOCKET_TYPE_SERVER:
1966 case SILC_SOCKET_TYPE_ROUTER:
1968 SilcServerEntry new_server;
1969 bool initiator = FALSE;
1970 bool backup_local = FALSE;
1971 bool backup_router = FALSE;
1972 char *backup_replace_ip = NULL;
1973 SilcUInt16 backup_replace_port = 0;
1974 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1975 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1977 /* If we are backup router and this is incoming server connection
1978 and we do not have connection to primary router, do not allow
1980 if (server->server_type == SILC_BACKUP_ROUTER &&
1981 ctx->conn_type == SILC_SOCKET_TYPE_SERVER &&
1982 !SILC_PRIMARY_ROUTE(server)) {
1983 SILC_LOG_INFO(("Will not accept server connection because we do "
1984 "not have primary router connection established"));
1985 sock->protocol = NULL;
1986 silc_server_disconnect_remote(server, sock,
1987 SILC_STATUS_ERR_PERM_DENIED,
1988 "We do not have connection to primary "
1989 "router established, try later");
1990 silc_free(sock->user_data);
1991 server->stat.auth_failures++;
1995 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1996 /* Verify whether this connection is after all allowed to connect */
1997 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1998 &server->config->param,
1999 rconn ? rconn->param : NULL,
2001 silc_free(sock->user_data);
2002 server->stat.auth_failures++;
2008 param = rconn->param;
2010 if (!param->keepalive_secs)
2011 param->keepalive_secs = server->config->param.keepalive_secs;
2013 if (!param->qos && server->config->param.qos) {
2014 param->qos = server->config->param.qos;
2015 param->qos_rate_limit = server->config->param.qos_rate_limit;
2016 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
2017 param->qos_limit_sec = server->config->param.qos_limit_sec;
2018 param->qos_limit_usec = server->config->param.qos_limit_usec;
2022 initiator = rconn->initiator;
2023 backup_local = rconn->backup_local;
2024 backup_router = rconn->backup_router;
2025 backup_replace_ip = rconn->backup_replace_ip;
2026 backup_replace_port = rconn->backup_replace_port;
2030 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
2031 /* Verify whether this connection is after all allowed to connect */
2032 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
2033 &server->config->param,
2034 sconn ? sconn->param : NULL,
2036 silc_free(sock->user_data);
2037 server->stat.auth_failures++;
2042 param = sconn->param;
2044 if (!param->keepalive_secs)
2045 param->keepalive_secs = server->config->param.keepalive_secs;
2047 if (!param->qos && server->config->param.qos) {
2048 param->qos = server->config->param.qos;
2049 param->qos_rate_limit = server->config->param.qos_rate_limit;
2050 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
2051 param->qos_limit_sec = server->config->param.qos_limit_sec;
2052 param->qos_limit_usec = server->config->param.qos_limit_usec;
2056 backup_router = sconn->backup_router;
2060 /* If we are primary router and we have backup router configured
2061 but it has not connected to use yet, do not accept any other
2063 if (server->wait_backup && server->server_type == SILC_ROUTER &&
2064 !server->backup_router && !backup_router) {
2065 SilcServerConfigRouter *router;
2066 router = silc_server_config_get_backup_router(server);
2067 if (router && strcmp(server->config->server_info->primary->server_ip,
2069 silc_server_find_socket_by_host(server,
2070 SILC_SOCKET_TYPE_SERVER,
2071 router->backup_replace_ip, 0)) {
2072 SILC_LOG_INFO(("Will not accept connections because we do "
2073 "not have backup router connection established"));
2074 sock->protocol = NULL;
2075 silc_server_disconnect_remote(server, sock,
2076 SILC_STATUS_ERR_PERM_DENIED,
2077 "We do not have connection to backup "
2078 "router established, try later");
2079 silc_free(sock->user_data);
2080 server->stat.auth_failures++;
2082 /* From here on, wait 10 seconds for the backup router to appear. */
2083 silc_schedule_task_add(server->schedule, 0,
2084 silc_server_backup_router_wait,
2085 (void *)server, 10, 0,
2086 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2091 SILC_LOG_DEBUG(("Remote host is %s",
2092 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2093 "server" : (backup_router ?
2094 "backup router" : "router")));
2095 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
2096 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2097 "server" : (backup_router ?
2098 "backup router" : "router")));
2100 /* Add the server into server cache. The server name and Server ID
2101 is updated after we have received NEW_SERVER packet from the
2102 server. We mark ourselves as router for this server if we really
2105 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2106 server->local_list : (backup_router ?
2107 server->local_list :
2108 server->global_list)),
2110 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2111 SILC_SERVER : SILC_ROUTER),
2113 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2114 server->id_entry : (backup_router ?
2115 server->id_entry : NULL)),
2118 SILC_LOG_ERROR(("Could not add new server to cache"));
2119 silc_free(sock->user_data);
2120 sock->protocol = NULL;
2121 silc_server_disconnect_remote(server, sock,
2122 SILC_STATUS_ERR_AUTH_FAILED, NULL);
2123 server->stat.auth_failures++;
2126 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
2128 id_entry = (void *)new_server;
2130 /* If the incoming connection is router and marked as backup router
2131 then add it to be one of our backups */
2132 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
2133 /* Change it back to SERVER type since that's what it really is. */
2135 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
2136 new_server->server_type = SILC_BACKUP_ROUTER;
2138 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
2139 ("Backup router %s is now online",
2142 /* Remove the backup waiting with timeout */
2143 silc_schedule_task_add(server->schedule, 0,
2144 silc_server_backup_router_wait,
2145 (void *)server, 5, 0,
2146 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2150 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
2151 server->stat.my_servers++;
2153 server->stat.my_routers++;
2154 server->stat.routers++;
2156 server->stat.servers++;
2158 /* Check whether this connection is to be our primary router connection
2159 if we do not already have the primary route. */
2160 if (!backup_router &&
2161 server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
2162 if (silc_server_config_is_primary_route(server) && !initiator)
2165 SILC_LOG_DEBUG(("We are not standalone server anymore"));
2166 server->standalone = FALSE;
2167 if (!server->id_entry->router) {
2168 server->id_entry->router = id_entry;
2169 server->router = id_entry;
2180 sock->type = ctx->conn_type;
2182 /* Add the common data structure to the ID entry. */
2183 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
2185 /* Add to sockets internal pointer for fast referencing */
2186 silc_free(sock->user_data);
2187 sock->user_data = id_entry;
2189 /* Connection has been fully established now. Everything is ok. */
2190 SILC_LOG_DEBUG(("New connection authenticated"));
2192 /* Perform keepalive. */
2193 if (param->keepalive_secs)
2194 silc_socket_set_heartbeat(sock, param->keepalive_secs, server,
2195 silc_server_perform_heartbeat,
2198 /* Perform Quality of Service */
2200 silc_socket_set_qos(sock, param->qos_rate_limit, param->qos_bytes_limit,
2201 param->qos_limit_sec, param->qos_limit_usec,
2205 if (sock->protocol == protocol)
2206 silc_protocol_free(protocol);
2208 silc_packet_context_free(ctx->packet);
2210 silc_ske_free(ctx->ske);
2211 silc_free(ctx->dest_id);
2212 silc_server_config_unref(&ctx->cconfig);
2213 silc_server_config_unref(&ctx->sconfig);
2214 silc_server_config_unref(&ctx->rconfig);
2216 sock->protocol = NULL;
2219 /* This function is used to read packets from network and send packets to
2220 network. This is usually a generic task. */
2222 SILC_TASK_CALLBACK(silc_server_packet_process)
2224 SilcServer server = (SilcServer)context;
2225 SilcSocketConnection sock = server->sockets[fd];
2226 SilcIDListData idata;
2227 SilcCipher cipher = NULL;
2228 SilcHmac hmac = NULL;
2229 SilcUInt32 sequence = 0;
2230 bool local_is_router;
2234 SILC_LOG_DEBUG(("Unknown socket connection"));
2238 /* Packet sending */
2240 if (type == SILC_TASK_WRITE) {
2241 /* Do not send data to disconnected connection */
2242 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2243 SILC_LOG_DEBUG(("Disconnected socket connection, cannot send"));
2244 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
2245 SILC_UNSET_OUTBUF_PENDING(sock);
2246 silc_buffer_clear(sock->outbuf);
2250 server->stat.packets_sent++;
2252 /* Send the packet */
2253 ret = silc_packet_send(sock, TRUE);
2255 /* If returned -2 could not write to connection now, will do
2260 /* The packet has been sent and now it is time to set the connection
2261 back to only for input. When there is again some outgoing data
2262 available for this connection it will be set for output as well.
2263 This call clears the output setting and sets it only for input. */
2264 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
2265 SILC_UNSET_OUTBUF_PENDING(sock);
2266 silc_buffer_clear(sock->outbuf);
2269 SILC_LOG_ERROR(("Error sending packet to connection "
2270 "%s:%d [%s]", sock->hostname, sock->port,
2271 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2272 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2273 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2276 if (sock->user_data)
2277 silc_server_free_sock_user_data(server, sock, NULL);
2278 SILC_SET_DISCONNECTING(sock);
2279 silc_server_close_connection(server, sock);
2284 /* Packet receiving */
2286 /* Read some data from connection */
2287 ret = silc_packet_receive(sock);
2291 SILC_LOG_ERROR(("Error receiving packet from connection "
2292 "%s:%d [%s] %s", sock->hostname, sock->port,
2293 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2294 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2295 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2296 "Router"), strerror(errno)));
2298 if (sock->user_data)
2299 silc_server_free_sock_user_data(server, sock, NULL);
2300 SILC_SET_DISCONNECTING(sock);
2301 silc_server_close_connection(server, sock);
2308 SILC_LOG_DEBUG(("Read EOF"));
2310 /* If connection is disconnecting already we will finally
2311 close the connection */
2312 if (SILC_IS_DISCONNECTING(sock)) {
2313 if (sock->user_data)
2314 silc_server_free_sock_user_data(server, sock, NULL);
2315 silc_server_close_connection(server, sock);
2319 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
2321 if (sock->user_data) {
2324 /* If backup disconnected then mark that resuming willl not be allowed */
2325 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2326 sock->type == SILC_SOCKET_TYPE_SERVER && sock->user_data) {
2327 SilcServerEntry server_entry = sock->user_data;
2328 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2329 server->backup_closed = TRUE;
2332 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
2333 silc_server_free_sock_user_data(server, sock, tmp);
2335 silc_server_free_sock_user_data(server, sock, NULL);
2336 } else if (server->router_conn && server->router_conn->sock == sock &&
2337 !server->router && server->standalone) {
2338 silc_server_create_connections(server);
2341 SILC_SET_DISCONNECTING(sock);
2342 silc_server_close_connection(server, sock);
2346 /* If connection is disconnecting or disconnected we will ignore
2348 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2349 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
2353 /* Get keys and stuff from ID entry */
2354 idata = (SilcIDListData)sock->user_data;
2356 cipher = idata->receive_key;
2357 hmac = idata->hmac_receive;
2358 sequence = idata->psn_receive;
2361 /* Then, process the packet. This will call the parser that will then
2362 decrypt and parse the packet. */
2364 local_is_router = (server->server_type == SILC_ROUTER);
2366 /* If socket connection is our primary, we are backup and we are doing
2367 backup resuming, we won't process the packet as being a router
2368 (affects channel message decryption). */
2369 if (server->backup_router && SILC_SERVER_IS_BACKUP(sock) &&
2370 SILC_PRIMARY_ROUTE(server) == sock)
2371 local_is_router = FALSE;
2373 ret = silc_packet_receive_process(sock, local_is_router,
2374 cipher, hmac, sequence,
2375 silc_server_packet_parse, server);
2377 /* If processing failed the connection is closed. */
2379 /* On packet processing errors we may close our primary router
2380 connection but won't become primary router if we are the backup
2381 since this is local error condition. */
2382 if (SILC_PRIMARY_ROUTE(server) == sock && server->backup_router)
2383 server->backup_noswitch = TRUE;
2385 if (sock->user_data)
2386 silc_server_free_sock_user_data(server, sock, NULL);
2387 SILC_SET_DISCONNECTING(sock);
2388 silc_server_close_connection(server, sock);
2392 /* Parses whole packet, received earlier. */
2394 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
2396 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
2397 SilcServer server = (SilcServer)parse_ctx->context;
2398 SilcSocketConnection sock = parse_ctx->sock;
2399 SilcPacketContext *packet = parse_ctx->packet;
2400 SilcIDListData idata = (SilcIDListData)sock->user_data;
2403 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2404 SILC_LOG_DEBUG(("Connection is disconnected"));
2408 server->stat.packets_received++;
2410 /* Parse the packet */
2411 if (parse_ctx->normal)
2412 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
2414 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
2416 /* If entry is disabled ignore what we got. */
2417 if (idata && idata->status & SILC_IDLIST_STATUS_DISABLED &&
2418 ret != SILC_PACKET_HEARTBEAT && ret != SILC_PACKET_RESUME_ROUTER &&
2419 ret != SILC_PACKET_REKEY && ret != SILC_PACKET_REKEY_DONE) {
2420 SILC_LOG_DEBUG(("Connection is disabled"));
2424 if (ret == SILC_PACKET_NONE) {
2425 SILC_LOG_DEBUG(("Error parsing packet"));
2429 /* Check that the the current client ID is same as in the client's packet. */
2430 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
2431 SilcClientEntry client = (SilcClientEntry)sock->user_data;
2432 if (client && client->id && packet->src_id) {
2433 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
2434 packet->src_id_type);
2435 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
2437 SILC_LOG_DEBUG(("Packet source is not same as sender"));
2444 if (server->server_type == SILC_ROUTER) {
2445 /* Route the packet if it is not destined to us. Other ID types but
2446 server are handled separately after processing them. */
2447 if (packet->dst_id && !(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
2448 packet->dst_id_type == SILC_ID_SERVER &&
2449 sock->type != SILC_SOCKET_TYPE_CLIENT &&
2450 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
2452 /* Route the packet to fastest route for the destination ID */
2453 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
2454 packet->dst_id_type);
2457 silc_server_packet_route(server,
2458 silc_server_route_get(server, id,
2459 packet->dst_id_type),
2466 /* Parse the incoming packet type */
2467 silc_server_packet_parse_type(server, sock, packet);
2469 /* Broadcast packet if it is marked as broadcast packet and it is
2470 originated from router and we are router. */
2471 if (server->server_type == SILC_ROUTER &&
2472 sock->type == SILC_SOCKET_TYPE_ROUTER &&
2473 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
2474 /* Broadcast to our primary route */
2475 silc_server_packet_broadcast(server, SILC_PRIMARY_ROUTE(server), packet);
2477 /* If we have backup routers then we need to feed all broadcast
2478 data to those servers. */
2479 silc_server_backup_broadcast(server, sock, packet);
2483 silc_packet_context_free(packet);
2484 silc_free(parse_ctx);
2487 /* Parser callback called by silc_packet_receive_process. This merely
2488 registers timeout that will handle the actual parsing when appropriate. */
2490 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
2493 SilcServer server = (SilcServer)context;
2494 SilcSocketConnection sock = parser_context->sock;
2495 SilcIDListData idata = (SilcIDListData)sock->user_data;
2499 idata->psn_receive = parser_context->packet->sequence + 1;
2501 /* If protocol for this connection is key exchange or rekey then we'll
2502 process all packets synchronously, since there might be packets in
2503 queue that we are not able to decrypt without first processing the
2504 packets before them. */
2505 if (sock->protocol && sock->protocol->protocol &&
2506 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2507 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2508 silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2511 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2512 SILC_LOG_DEBUG(("Connection is disconnected"));
2516 /* Reprocess data since we'll return FALSE here. This is because
2517 the idata->receive_key might have become valid in the last packet
2518 and we want to call this processor with valid cipher. */
2520 ret = silc_packet_receive_process(
2521 sock, server->server_type == SILC_ROUTER,
2523 idata->hmac_receive, idata->psn_receive,
2524 silc_server_packet_parse, server);
2526 ret = silc_packet_receive_process(
2527 sock, server->server_type == SILC_ROUTER,
2529 silc_server_packet_parse, server);
2532 /* On packet processing errors we may close our primary router
2533 connection but won't become primary router if we are the backup
2534 since this is local error condition. */
2535 if (SILC_PRIMARY_ROUTE(server) == sock && server->backup_router)
2536 server->backup_noswitch = TRUE;
2538 if (sock->user_data)
2539 silc_server_free_sock_user_data(server, sock, NULL);
2540 SILC_SET_DISCONNECTING(sock);
2541 silc_server_close_connection(server, sock);
2547 switch (sock->type) {
2548 case SILC_SOCKET_TYPE_UNKNOWN:
2549 case SILC_SOCKET_TYPE_CLIENT:
2550 /* Parse the packet with timeout */
2551 silc_schedule_task_add(server->schedule, sock->sock,
2552 silc_server_packet_parse_real,
2553 (void *)parser_context, 0, 100000,
2555 SILC_TASK_PRI_NORMAL);
2557 case SILC_SOCKET_TYPE_SERVER:
2558 case SILC_SOCKET_TYPE_ROUTER:
2559 /* Packets from servers are parsed immediately */
2560 silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2568 /* Parses the packet type and calls what ever routines the packet type
2569 requires. This is done for all incoming packets. */
2571 void silc_server_packet_parse_type(SilcServer server,
2572 SilcSocketConnection sock,
2573 SilcPacketContext *packet)
2575 SilcPacketType type = packet->type;
2576 SilcIDListData idata = (SilcIDListData)sock->user_data;
2578 SILC_LOG_DEBUG(("Received %s packet [flags %d]",
2579 silc_get_packet_name(type), packet->flags));
2581 /* Parse the packet type */
2583 case SILC_PACKET_DISCONNECT:
2586 char *message = NULL;
2588 if (packet->flags & SILC_PACKET_FLAG_LIST)
2590 if (packet->buffer->len < 1)
2593 status = (SilcStatus)packet->buffer->data[0];
2594 if (packet->buffer->len > 1 &&
2595 silc_utf8_valid(packet->buffer->data + 1, packet->buffer->len - 1))
2596 message = silc_memdup(packet->buffer->data + 1,
2597 packet->buffer->len - 1);
2599 SILC_LOG_INFO(("Disconnected by %s (%s): %s (%d) %s",
2600 sock->ip, sock->hostname,
2601 silc_get_status_message(status), status,
2602 message ? message : ""));
2605 /* Do not switch to backup in case of error */
2606 server->backup_noswitch = (status == SILC_STATUS_OK ? FALSE : TRUE);
2608 /* If backup disconnected then mark that resuming willl not be allowed */
2609 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2610 sock->type == SILC_SOCKET_TYPE_SERVER && sock->user_data) {
2611 SilcServerEntry server_entry = sock->user_data;
2612 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2613 server->backup_closed = TRUE;
2616 /* Handle the disconnection from our end too */
2617 if (sock->user_data && SILC_IS_LOCAL(sock->user_data))
2618 silc_server_free_sock_user_data(server, sock, NULL);
2619 SILC_SET_DISCONNECTING(sock);
2620 silc_server_close_connection(server, sock);
2621 server->backup_noswitch = FALSE;
2625 case SILC_PACKET_SUCCESS:
2627 * Success received for something. For now we can have only
2628 * one protocol for connection executing at once hence this
2629 * success message is for whatever protocol is executing currently.
2631 if (packet->flags & SILC_PACKET_FLAG_LIST)
2634 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2637 case SILC_PACKET_FAILURE:
2639 * Failure received for something. For now we can have only
2640 * one protocol for connection executing at once hence this
2641 * failure message is for whatever protocol is executing currently.
2643 if (packet->flags & SILC_PACKET_FLAG_LIST)
2646 /* Check for failure START_USE from backup router */
2647 if (server->server_type == SILC_SERVER &&
2648 server->backup_primary && packet->buffer->len == 4) {
2650 SILC_GET32_MSB(type, packet->buffer->data);
2651 if (type == SILC_SERVER_BACKUP_START_USE) {
2652 /* Attempt to reconnect to primary */
2653 SILC_LOG_DEBUG(("Received failed START_USE from backup %s", sock->ip));
2655 /* Default action is to disconnect from backup and reconnect to
2656 primary. Since this failure can happen during switching to
2657 backup (backup might have not noticed the primary going down yet),
2658 we will wait a while and keep sending START_USE to backup.
2659 Only after that we'll give up. */
2660 if (server->router == sock->user_data &&
2661 (time(0) - server->router_connect) < 30) {
2662 SILC_LOG_DEBUG(("Resending START_USE to backup router"));
2663 silc_server_backup_send_start_use(server, sock, FALSE);
2667 /* If backup is our primary, disconnect now. */
2668 if (server->router == sock->user_data) {
2669 if (sock->user_data)
2670 silc_server_free_sock_user_data(server, sock, NULL);
2671 SILC_SET_DISCONNECTING(sock);
2672 silc_server_close_connection(server, sock);
2676 silc_server_create_connections(server);
2680 /* Execute protocol */
2681 if (sock->protocol) {
2682 sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
2683 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2688 case SILC_PACKET_REJECT:
2689 if (packet->flags & SILC_PACKET_FLAG_LIST)
2694 case SILC_PACKET_NOTIFY:
2696 * Received notify packet. Server can receive notify packets from
2697 * router. Server then relays the notify messages to clients if needed.
2699 if (packet->flags & SILC_PACKET_FLAG_LIST)
2700 silc_server_notify_list(server, sock, packet);
2702 silc_server_notify(server, sock, packet);
2708 case SILC_PACKET_CHANNEL_MESSAGE:
2710 * Received channel message. Channel messages are special packets
2711 * (although probably most common ones) thus they are handled
2714 if (packet->flags & SILC_PACKET_FLAG_LIST)
2716 idata->last_receive = time(NULL);
2717 silc_server_channel_message(server, sock, packet);
2720 case SILC_PACKET_CHANNEL_KEY:
2722 * Received key for channel. As channels are created by the router
2723 * the keys are as well. We will distribute the key to all of our
2724 * locally connected clients on the particular channel. Router
2725 * never receives this channel and thus is ignored.
2727 if (packet->flags & SILC_PACKET_FLAG_LIST)
2729 silc_server_channel_key(server, sock, packet);
2735 case SILC_PACKET_COMMAND:
2737 * Recived command. Processes the command request and allocates the
2738 * command context and calls the command.
2740 if (packet->flags & SILC_PACKET_FLAG_LIST)
2742 silc_server_command_process(server, sock, packet);
2745 case SILC_PACKET_COMMAND_REPLY:
2747 * Received command reply packet. Received command reply to command. It
2748 * may be reply to command sent by us or reply to command sent by client
2749 * that we've routed further.
2751 if (packet->flags & SILC_PACKET_FLAG_LIST)
2753 silc_server_command_reply(server, sock, packet);
2757 * Private Message packets
2759 case SILC_PACKET_PRIVATE_MESSAGE:
2761 * Received private message packet. The packet is coming from either
2764 if (packet->flags & SILC_PACKET_FLAG_LIST)
2766 idata->last_receive = time(NULL);
2767 silc_server_private_message(server, sock, packet);
2770 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2772 * Private message key packet.
2774 if (packet->flags & SILC_PACKET_FLAG_LIST)
2776 silc_server_private_message_key(server, sock, packet);
2780 * Key Exchange protocol packets
2782 case SILC_PACKET_KEY_EXCHANGE:
2783 if (packet->flags & SILC_PACKET_FLAG_LIST)
2786 if (sock->protocol && sock->protocol->protocol &&
2787 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2788 SilcServerKEInternalContext *proto_ctx =
2789 (SilcServerKEInternalContext *)sock->protocol->context;
2791 proto_ctx->packet = silc_packet_context_dup(packet);
2793 /* Let the protocol handle the packet */
2794 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2796 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2797 "protocol active (%s:%d [%s]).", sock->hostname,
2799 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2800 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2801 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2806 case SILC_PACKET_KEY_EXCHANGE_1:
2807 if (packet->flags & SILC_PACKET_FLAG_LIST)
2810 if (sock->protocol && sock->protocol->protocol &&
2811 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2812 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2814 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2815 SilcServerRekeyInternalContext *proto_ctx =
2816 (SilcServerRekeyInternalContext *)sock->protocol->context;
2818 if (proto_ctx->packet)
2819 silc_packet_context_free(proto_ctx->packet);
2821 proto_ctx->packet = silc_packet_context_dup(packet);
2823 /* Let the protocol handle the packet */
2824 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2826 SilcServerKEInternalContext *proto_ctx =
2827 (SilcServerKEInternalContext *)sock->protocol->context;
2829 if (proto_ctx->packet)
2830 silc_packet_context_free(proto_ctx->packet);
2832 proto_ctx->packet = silc_packet_context_dup(packet);
2833 proto_ctx->dest_id_type = packet->src_id_type;
2834 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2835 packet->src_id_type);
2836 if (!proto_ctx->dest_id)
2839 /* Let the protocol handle the packet */
2840 silc_protocol_execute(sock->protocol, server->schedule,
2844 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2845 "protocol active (%s:%d [%s]).", sock->hostname,
2847 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2848 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2849 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2854 case SILC_PACKET_KEY_EXCHANGE_2:
2855 if (packet->flags & SILC_PACKET_FLAG_LIST)
2858 if (sock->protocol && sock->protocol->protocol &&
2859 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2860 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2862 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2863 SilcServerRekeyInternalContext *proto_ctx =
2864 (SilcServerRekeyInternalContext *)sock->protocol->context;
2866 if (proto_ctx->packet)
2867 silc_packet_context_free(proto_ctx->packet);
2869 proto_ctx->packet = silc_packet_context_dup(packet);
2871 /* Let the protocol handle the packet */
2872 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2874 SilcServerKEInternalContext *proto_ctx =
2875 (SilcServerKEInternalContext *)sock->protocol->context;
2877 if (proto_ctx->packet)
2878 silc_packet_context_free(proto_ctx->packet);
2880 proto_ctx->packet = silc_packet_context_dup(packet);
2881 proto_ctx->dest_id_type = packet->src_id_type;
2882 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2883 packet->src_id_type);
2884 if (!proto_ctx->dest_id)
2887 /* Let the protocol handle the packet */
2888 silc_protocol_execute(sock->protocol, server->schedule,
2892 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2893 "protocol active (%s:%d [%s]).", sock->hostname,
2895 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2896 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2897 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2902 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2904 * Connection authentication request packet. When we receive this packet
2905 * we will send to the other end information about our mandatory
2906 * authentication method for the connection. This packet maybe received
2909 if (packet->flags & SILC_PACKET_FLAG_LIST)
2911 silc_server_connection_auth_request(server, sock, packet);
2915 * Connection Authentication protocol packets
2917 case SILC_PACKET_CONNECTION_AUTH:
2918 /* Start of the authentication protocol. We receive here the
2919 authentication data and will verify it. */
2920 if (packet->flags & SILC_PACKET_FLAG_LIST)
2923 if (sock->protocol && sock->protocol->protocol->type
2924 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2926 SilcServerConnAuthInternalContext *proto_ctx =
2927 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2929 proto_ctx->packet = silc_packet_context_dup(packet);
2931 /* Let the protocol handle the packet */
2932 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2934 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2935 "protocol active (%s:%d [%s]).", sock->hostname,
2937 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2938 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2939 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2944 case SILC_PACKET_NEW_ID:
2946 * Received New ID packet. This includes some new ID that has been
2947 * created. It may be for client, server or channel. This is the way
2948 * to distribute information about new registered entities in the
2951 if (packet->flags & SILC_PACKET_FLAG_LIST)
2952 silc_server_new_id_list(server, sock, packet);
2954 silc_server_new_id(server, sock, packet);
2957 case SILC_PACKET_NEW_CLIENT:
2959 * Received new client packet. This includes client information that
2960 * we will use to create initial client ID. After creating new
2961 * ID we will send it to the client.
2963 if (packet->flags & SILC_PACKET_FLAG_LIST)
2965 silc_server_new_client(server, sock, packet);
2968 case SILC_PACKET_NEW_SERVER:
2970 * Received new server packet. This includes Server ID and some other
2971 * information that we may save. This is received after server has
2974 if (packet->flags & SILC_PACKET_FLAG_LIST)
2976 silc_server_new_server(server, sock, packet);
2979 case SILC_PACKET_NEW_CHANNEL:
2981 * Received new channel packet. Information about new channel in the
2982 * network are distributed using this packet.
2984 if (packet->flags & SILC_PACKET_FLAG_LIST)
2985 silc_server_new_channel_list(server, sock, packet);
2987 silc_server_new_channel(server, sock, packet);
2990 case SILC_PACKET_HEARTBEAT:
2992 * Received heartbeat.
2994 if (packet->flags & SILC_PACKET_FLAG_LIST)
2998 case SILC_PACKET_KEY_AGREEMENT:
3000 * Received heartbeat.
3002 if (packet->flags & SILC_PACKET_FLAG_LIST)
3004 silc_server_key_agreement(server, sock, packet);
3007 case SILC_PACKET_REKEY:
3009 * Received re-key packet. The sender wants to regenerate the session
3012 if (packet->flags & SILC_PACKET_FLAG_LIST)
3014 silc_server_rekey(server, sock, packet);
3017 case SILC_PACKET_REKEY_DONE:
3019 * The re-key is done.
3021 if (packet->flags & SILC_PACKET_FLAG_LIST)
3024 if (sock->protocol && sock->protocol->protocol &&
3025 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
3027 SilcServerRekeyInternalContext *proto_ctx =
3028 (SilcServerRekeyInternalContext *)sock->protocol->context;
3030 if (proto_ctx->packet)
3031 silc_packet_context_free(proto_ctx->packet);
3033 proto_ctx->packet = silc_packet_context_dup(packet);
3035 /* Let the protocol handle the packet */
3036 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
3038 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
3039 "protocol active (%s:%d [%s]).", sock->hostname,
3041 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
3042 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
3043 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
3048 case SILC_PACKET_FTP:
3050 if (packet->flags & SILC_PACKET_FLAG_LIST)
3052 silc_server_ftp(server, sock, packet);
3055 case SILC_PACKET_RESUME_CLIENT:
3057 if (packet->flags & SILC_PACKET_FLAG_LIST)
3059 silc_server_resume_client(server, sock, packet);
3062 case SILC_PACKET_RESUME_ROUTER:
3063 /* Resume router packet received. This packet is received for backup
3064 router resuming protocol. */
3065 if (packet->flags & SILC_PACKET_FLAG_LIST)
3067 silc_server_backup_resume_router(server, sock, packet);
3071 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
3076 /* Creates connection to a remote router. */
3078 void silc_server_create_connection(SilcServer server,
3079 const char *remote_host, SilcUInt32 port)
3081 SilcServerConnection sconn;
3083 /* Allocate connection object for hold connection specific stuff. */
3084 sconn = silc_calloc(1, sizeof(*sconn));
3085 sconn->remote_host = strdup(remote_host);
3086 sconn->remote_port = port;
3087 sconn->no_reconnect = TRUE;
3089 silc_schedule_task_add(server->schedule, 0,
3090 silc_server_connect_router,
3091 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
3092 SILC_TASK_PRI_NORMAL);
3095 SILC_TASK_CALLBACK(silc_server_close_connection_final)
3097 SilcServer server = app_context;
3098 SilcSocketConnection sock = context;
3100 SILC_LOG_DEBUG(("Deleting socket %p", sock));
3102 /* Close the actual connection */
3103 silc_net_close_connection(sock->sock);
3104 server->sockets[sock->sock] = NULL;
3106 /* We won't listen for this connection anymore */
3107 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
3108 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
3110 silc_socket_free(sock);
3113 /* Closes connection to socket connection */
3115 void silc_server_close_connection(SilcServer server,
3116 SilcSocketConnection sock)
3120 if (SILC_IS_DISCONNECTED(sock)) {
3121 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
3122 silc_schedule_task_add(server->schedule, sock->sock,
3123 silc_server_close_connection_final,
3124 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
3125 SILC_TASK_PRI_NORMAL);
3126 server->sockets[sock->sock] = NULL;
3130 /* If any protocol is active cancel its execution. It will call
3131 the final callback which will finalize the disconnection. */
3132 if (sock->protocol && sock->protocol->protocol &&
3133 sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3134 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3135 silc_protocol_cancel(sock->protocol, server->schedule);
3136 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3137 silc_protocol_execute_final(sock->protocol, server->schedule);
3138 sock->protocol = NULL;
3142 memset(tmp, 0, sizeof(tmp));
3143 silc_socket_get_error(sock, tmp, sizeof(tmp));
3144 SILC_LOG_INFO(("Closing connection %s:%d [%s] %s", sock->hostname,
3146 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
3147 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
3148 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
3149 "Router"), tmp[0] ? tmp : ""));
3151 SILC_SET_DISCONNECTED(sock);
3152 silc_socket_set_qos(sock, 0, 0, 0, 0, NULL);
3153 silc_schedule_task_add(server->schedule, sock->sock,
3154 silc_server_close_connection_final,
3155 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
3156 SILC_TASK_PRI_NORMAL);
3157 server->sockets[sock->sock] = NULL;
3160 /* Sends disconnect message to remote connection and disconnects the
3161 connection. NOTE: If this is called from protocol callback
3162 then sock->protocol must be set NULL before calling this, since
3163 this routine dispatches protocol callbacks too. */
3165 void silc_server_disconnect_remote(SilcServer server,
3166 SilcSocketConnection sock,
3167 SilcStatus status, ...)
3170 unsigned char buf[512];
3178 if (SILC_IS_DISCONNECTING(sock)) {
3179 SILC_SET_DISCONNECTED(sock);
3180 silc_server_close_connection(server, sock);
3184 memset(buf, 0, sizeof(buf));
3185 va_start(ap, status);
3186 cp = va_arg(ap, char *);
3188 vsnprintf(buf, sizeof(buf) - 1, cp, ap);
3193 SILC_LOG_DEBUG(("Disconnecting remote host"));
3195 /* Notify remote end that the conversation is over. The notify message
3196 is tried to be sent immediately. */
3200 len += silc_utf8_encoded_len(buf, strlen(buf), SILC_STRING_ASCII);
3202 buffer = silc_buffer_alloc_size(len);
3206 buffer->data[0] = status;
3208 silc_utf8_encode(buf, strlen(buf), SILC_STRING_ASCII, buffer->data + 1,
3210 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
3211 buffer->data, buffer->len, TRUE);
3212 silc_buffer_free(buffer);
3215 silc_server_packet_queue_purge(server, sock);
3217 /* Mark the connection to be disconnected */
3218 SILC_SET_DISCONNECTING(sock);
3219 silc_server_close_connection(server, sock);
3222 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
3224 SilcServer server = app_context;
3225 SilcClientEntry client = context;
3227 assert(!silc_hash_table_count(client->channels));
3229 silc_idlist_del_data(client);
3230 silc_idcache_purge_by_context(server->local_list->clients, client);
3233 /* Frees client data and notifies about client's signoff. */
3235 void silc_server_free_client_data(SilcServer server,
3236 SilcSocketConnection sock,
3237 SilcClientEntry client,
3239 const char *signoff)
3241 SILC_LOG_DEBUG(("Freeing client data"));
3243 /* If there is pending outgoing data for the client then purge it
3244 to the network before removing the client entry. */
3245 silc_server_packet_queue_purge(server, sock);
3248 /* Check if anyone is watching this nickname */
3249 if (server->server_type == SILC_ROUTER)
3250 silc_server_check_watcher_list(server, client, NULL,
3251 SILC_NOTIFY_TYPE_SIGNOFF);
3253 /* Send SIGNOFF notify to routers. */
3255 silc_server_send_notify_signoff(server, SILC_PRIMARY_ROUTE(server),
3256 SILC_BROADCAST(server), client->id,
3260 /* Remove client from all channels */
3262 silc_server_remove_from_channels(server, NULL, client,
3263 TRUE, (char *)signoff, TRUE, FALSE);
3265 silc_server_remove_from_channels(server, NULL, client,
3266 FALSE, NULL, FALSE, FALSE);
3268 /* Remove this client from watcher list if it is */
3269 silc_server_del_from_watcher_list(server, client);
3271 /* Update statistics */
3272 server->stat.my_clients--;
3273 server->stat.clients--;
3274 if (server->stat.cell_clients)
3275 server->stat.cell_clients--;
3276 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
3277 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
3278 silc_schedule_task_del_by_context(server->schedule, client);
3280 /* We will not delete the client entry right away. We will take it
3281 into history (for WHOWAS command) for 5 minutes, unless we're
3282 shutting down server. */
3283 if (!server->server_shutdown) {
3284 silc_schedule_task_add(server->schedule, 0,
3285 silc_server_free_client_data_timeout,
3287 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
3288 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
3289 client->data.status &= ~SILC_IDLIST_STATUS_LOCAL;
3291 client->router = NULL;
3292 client->connection = NULL;
3294 /* Delete directly since we're shutting down server */
3295 silc_idlist_del_data(client);
3296 silc_idlist_del_client(server->local_list, client);
3300 /* Frees user_data pointer from socket connection object. This also sends
3301 appropriate notify packets to the network to inform about leaving
3304 void silc_server_free_sock_user_data(SilcServer server,
3305 SilcSocketConnection sock,
3306 const char *signoff_message)
3309 /* If any protocol is active cancel its execution */
3310 if (sock->protocol && sock->protocol->protocol &&
3311 sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3312 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3313 silc_protocol_cancel(sock->protocol, server->schedule);
3314 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3315 silc_protocol_execute_final(sock->protocol, server->schedule);
3316 sock->protocol = NULL;
3319 switch (sock->type) {
3320 case SILC_SOCKET_TYPE_CLIENT:
3322 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
3323 silc_server_free_client_data(server, sock, user_data, TRUE,
3327 case SILC_SOCKET_TYPE_SERVER:
3328 case SILC_SOCKET_TYPE_ROUTER:
3330 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
3331 SilcServerEntry backup_router = NULL;
3333 SILC_LOG_DEBUG(("Freeing server data"));
3336 backup_router = silc_server_backup_get(server, user_data->id);
3338 if (!server->backup_router && server->server_type == SILC_ROUTER &&
3339 backup_router == server->id_entry &&
3340 sock->type != SILC_SOCKET_TYPE_ROUTER)
3341 backup_router = NULL;
3343 if (server->server_shutdown || server->backup_noswitch)
3344 backup_router = NULL;
3346 /* If this was our primary router connection then we're lost to
3347 the outside world. */
3348 if (server->router == user_data) {
3349 /* Check whether we have a backup router connection */
3350 if (!backup_router || backup_router == user_data) {
3351 if (!server->no_reconnect)
3352 silc_server_create_connections(server);
3353 server->id_entry->router = NULL;
3354 server->router = NULL;
3355 server->standalone = TRUE;
3356 server->backup_primary = FALSE;
3357 backup_router = NULL;
3359 if (server->id_entry != backup_router) {
3360 SILC_LOG_INFO(("New primary router is backup router %s",
3361 backup_router->server_name));
3362 server->id_entry->router = backup_router;
3363 server->router = backup_router;
3364 server->router_connect = time(0);
3365 server->backup_primary = TRUE;
3366 backup_router->data.status &= ~SILC_IDLIST_STATUS_DISABLED;
3368 /* Send START_USE to backup router to indicate we have switched */
3369 silc_server_backup_send_start_use(server,
3370 backup_router->connection,
3373 SILC_LOG_INFO(("We are now new primary router in this cell"));
3374 server->id_entry->router = NULL;
3375 server->router = NULL;
3376 server->standalone = TRUE;
3379 /* We stop here to take a breath */
3382 if (server->backup_router) {
3383 server->server_type = SILC_ROUTER;
3385 /* We'll need to constantly try to reconnect to the primary
3386 router so that we'll see when it comes back online. */
3387 silc_server_backup_reconnect(server, sock->ip, sock->port,
3388 silc_server_backup_connected,
3392 /* Mark this connection as replaced */
3393 silc_server_backup_replaced_add(server, user_data->id,
3396 } else if (backup_router) {
3397 SILC_LOG_INFO(("Enabling the use of backup router %s",
3398 backup_router->server_name));
3400 /* Mark this connection as replaced */
3401 silc_server_backup_replaced_add(server, user_data->id,
3403 } else if (server->server_type == SILC_SERVER &&
3404 sock->type == SILC_SOCKET_TYPE_ROUTER) {
3405 /* Reconnect to the router (backup) */
3406 if (!server->no_reconnect)
3407 silc_server_create_connections(server);
3410 if (user_data->server_name)
3411 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
3412 ("Server %s signoff", user_data->server_name));
3414 if (!backup_router) {
3415 /* Remove all servers that are originated from this server, and
3416 remove the clients of those servers too. */
3417 silc_server_remove_servers_by_server(server, user_data, TRUE);
3420 /* Remove the clients that this server owns as they will become
3421 invalid now too. For backup router the server is actually
3422 coming from the primary router, so mark that as the owner
3424 if (server->server_type == SILC_BACKUP_ROUTER &&
3425 sock->type == SILC_SOCKET_TYPE_SERVER)
3426 silc_server_remove_clients_by_server(server, server->router,
3430 silc_server_remove_clients_by_server(server, user_data,
3433 /* Remove channels owned by this server */
3434 if (server->server_type == SILC_SERVER)
3435 silc_server_remove_channels_by_server(server, user_data);
3437 /* Enable local server connections that may be disabled */
3438 silc_server_local_servers_toggle_enabled(server, TRUE);
3440 /* Update the client entries of this server to the new backup
3441 router. If we are the backup router we also resolve the real
3442 servers for the clients. After updating is over this also
3443 removes the clients that this server explicitly owns. */
3444 silc_server_update_clients_by_server(server, user_data,
3445 backup_router, TRUE);
3447 /* If we are router and just lost our primary router (now standlaone)
3448 we remove everything that was behind it, since we don't know
3450 if (server->server_type == SILC_ROUTER && server->standalone)
3451 /* Remove all servers that are originated from this server, and
3452 remove the clients of those servers too. */
3453 silc_server_remove_servers_by_server(server, user_data, TRUE);
3455 /* Finally remove the clients that are explicitly owned by this
3456 server. They go down with the server. */
3457 silc_server_remove_clients_by_server(server, user_data,
3460 /* Update our server cache to use the new backup router too. */
3461 silc_server_update_servers_by_server(server, user_data, backup_router);
3462 if (server->server_type == SILC_SERVER)
3463 silc_server_update_channels_by_server(server, user_data,
3466 /* Send notify about primary router going down to local operators */
3467 if (server->backup_router)
3468 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3469 SILC_NOTIFY_TYPE_NONE,
3470 ("%s switched to backup router %s "
3471 "(we are primary router now)",
3472 server->server_name, server->server_name));
3473 else if (server->router)
3474 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3475 SILC_NOTIFY_TYPE_NONE,
3476 ("%s switched to backup router %s",
3477 server->server_name,
3478 server->router->server_name));
3480 server->backup_noswitch = FALSE;
3482 /* Free the server entry */
3483 silc_server_backup_del(server, user_data);
3484 silc_server_backup_replaced_del(server, user_data);
3485 silc_idlist_del_data(user_data);
3486 if (!silc_idlist_del_server(server->local_list, user_data))
3487 silc_idlist_del_server(server->global_list, user_data);
3488 if (sock->type == SILC_SOCKET_TYPE_SERVER) {
3489 server->stat.my_servers--;
3491 server->stat.my_routers--;
3492 server->stat.routers--;
3494 server->stat.servers--;
3495 if (server->server_type == SILC_ROUTER)
3496 server->stat.cell_servers--;
3498 if (backup_router && backup_router != server->id_entry) {
3499 /* Announce all of our stuff that was created about 5 minutes ago.
3500 The backup router knows all the other stuff already. */
3501 if (server->server_type == SILC_ROUTER)
3502 silc_server_announce_servers(server, FALSE, time(0) - 300,
3503 backup_router->connection);
3505 /* Announce our clients and channels to the router */
3506 silc_server_announce_clients(server, time(0) - 300,
3507 backup_router->connection);
3508 silc_server_announce_channels(server, time(0) - 300,
3509 backup_router->connection);
3515 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
3517 SILC_LOG_DEBUG(("Freeing unknown connection data"));
3519 silc_idlist_del_data(user_data);
3520 silc_free(user_data);
3525 sock->user_data = NULL;
3528 /* Removes client from all channels it has joined. This is used when client
3529 connection is disconnected. If the client on a channel is last, the
3530 channel is removed as well. This sends the SIGNOFF notify types. */
3532 void silc_server_remove_from_channels(SilcServer server,
3533 SilcSocketConnection sock,
3534 SilcClientEntry client,
3536 const char *signoff_message,
3540 SilcChannelEntry channel;
3541 SilcChannelClientEntry chl;
3542 SilcHashTableList htl;
3543 SilcBuffer clidp = NULL;
3548 if (notify && !client->id)
3551 SILC_LOG_DEBUG(("Removing client %s from joined channels",
3552 notify ? silc_id_render(client->id, SILC_ID_CLIENT) : ""));
3555 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3560 /* Remove the client from all channels. The client is removed from
3561 the channels' user list. */
3562 silc_hash_table_list(client->channels, &htl);
3563 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3564 channel = chl->channel;
3566 /* Remove channel if this is last client leaving the channel, unless
3567 the channel is permanent. */
3568 if (server->server_type != SILC_SERVER &&
3569 silc_hash_table_count(channel->user_list) < 2) {
3570 silc_server_channel_delete(server, channel);
3574 silc_hash_table_del(client->channels, channel);
3575 silc_hash_table_del(channel->user_list, client);
3576 channel->user_count--;
3578 /* If there is no global users on the channel anymore mark the channel
3579 as local channel. Do not check if the removed client is local client. */
3580 if (server->server_type == SILC_SERVER && channel->global_users &&
3581 chl->client->router && !silc_server_channel_has_global(channel))
3582 channel->global_users = FALSE;
3584 memset(chl, 'A', sizeof(*chl));
3587 /* Update statistics */
3588 if (SILC_IS_LOCAL(client))
3589 server->stat.my_chanclients--;
3590 if (server->server_type == SILC_ROUTER) {
3591 server->stat.cell_chanclients--;
3592 server->stat.chanclients--;
3595 /* If there is not at least one local user on the channel then we don't
3596 need the channel entry anymore, we can remove it safely, unless the
3597 channel is permanent channel */
3598 if (server->server_type == SILC_SERVER &&
3599 !silc_server_channel_has_local(channel)) {
3600 /* Notify about leaving client if this channel has global users. */
3601 if (notify && channel->global_users)
3602 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3603 SILC_NOTIFY_TYPE_SIGNOFF,
3604 signoff_message ? 2 : 1,
3605 clidp->data, clidp->len,
3606 signoff_message, signoff_message ?
3607 strlen(signoff_message) : 0);
3609 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3610 silc_server_channel_delete(server, channel);
3614 /* Send notify to channel about client leaving SILC and channel too */
3616 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3617 SILC_NOTIFY_TYPE_SIGNOFF,
3618 signoff_message ? 2 : 1,
3619 clidp->data, clidp->len,
3620 signoff_message, signoff_message ?
3621 strlen(signoff_message) : 0);
3623 if (killed && clidp) {
3624 /* Remove the client from channel's invite list */
3625 if (channel->invite_list &&
3626 silc_hash_table_count(channel->invite_list)) {
3628 SilcArgumentPayload iargs;
3629 ab = silc_argument_payload_encode_one(NULL, clidp->data,
3631 iargs = silc_argument_payload_parse(ab->data, ab->len, 1);
3632 silc_server_inviteban_process(server, channel->invite_list, 1, iargs);
3633 silc_buffer_free(ab);
3634 silc_argument_payload_free(iargs);
3638 /* Don't create keys if we are shutting down */
3639 if (server->server_shutdown)
3642 /* Re-generate channel key if needed */
3643 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3644 if (!silc_server_create_channel_key(server, channel, 0))
3647 /* Send the channel key to the channel. The key of course is not sent
3648 to the client who was removed from the channel. */
3649 silc_server_send_channel_key(server, client->connection, channel,
3650 server->server_type == SILC_ROUTER ?
3651 FALSE : !server->standalone);
3655 silc_hash_table_list_reset(&htl);
3657 silc_buffer_free(clidp);
3660 /* Removes client from one channel. This is used for example when client
3661 calls LEAVE command to remove itself from the channel. Returns TRUE
3662 if channel still exists and FALSE if the channel is removed when
3663 last client leaves the channel. If `notify' is FALSE notify messages
3666 bool silc_server_remove_from_one_channel(SilcServer server,
3667 SilcSocketConnection sock,
3668 SilcChannelEntry channel,
3669 SilcClientEntry client,
3672 SilcChannelClientEntry chl;
3675 SILC_LOG_DEBUG(("Removing %s from channel %s",
3676 silc_id_render(client->id, SILC_ID_CLIENT),
3677 channel->channel_name));
3679 /* Get the entry to the channel, if this client is not on the channel
3681 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
3684 /* Remove channel if this is last client leaving the channel, unless
3685 the channel is permanent. */
3686 if (server->server_type != SILC_SERVER &&
3687 silc_hash_table_count(channel->user_list) < 2) {
3688 silc_server_channel_delete(server, channel);
3692 silc_hash_table_del(client->channels, channel);
3693 silc_hash_table_del(channel->user_list, client);
3694 channel->user_count--;
3696 /* If there is no global users on the channel anymore mark the channel
3697 as local channel. Do not check if the client is local client. */
3698 if (server->server_type == SILC_SERVER && channel->global_users &&
3699 chl->client->router && !silc_server_channel_has_global(channel))
3700 channel->global_users = FALSE;
3702 memset(chl, 'O', sizeof(*chl));
3705 /* Update statistics */
3706 if (SILC_IS_LOCAL(client))
3707 server->stat.my_chanclients--;
3708 if (server->server_type == SILC_ROUTER) {
3709 server->stat.cell_chanclients--;
3710 server->stat.chanclients--;
3713 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3717 /* If there is not at least one local user on the channel then we don't
3718 need the channel entry anymore, we can remove it safely, unless the
3719 channel is permanent channel */
3720 if (server->server_type == SILC_SERVER &&
3721 !silc_server_channel_has_local(channel)) {
3722 /* Notify about leaving client if this channel has global users. */
3723 if (notify && channel->global_users)
3724 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3725 SILC_NOTIFY_TYPE_LEAVE, 1,
3726 clidp->data, clidp->len);
3728 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3729 silc_server_channel_delete(server, channel);
3730 silc_buffer_free(clidp);
3734 /* Send notify to channel about client leaving the channel */
3736 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3737 SILC_NOTIFY_TYPE_LEAVE, 1,
3738 clidp->data, clidp->len);
3740 silc_buffer_free(clidp);
3744 /* Timeout callback. This is called if connection is idle or for some
3745 other reason is not responding within some period of time. This
3746 disconnects the remote end. */
3748 SILC_TASK_CALLBACK(silc_server_timeout_remote)
3750 SilcServer server = (SilcServer)context;
3751 SilcSocketConnection sock = server->sockets[fd];
3752 SilcProtocolType protocol = 0;
3754 SILC_LOG_DEBUG(("Start"));
3759 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
3760 sock->hostname, sock->ip));
3762 /* If we have protocol active we must assure that we call the protocol's
3763 final callback so that all the memory is freed. */
3764 if (sock->protocol && sock->protocol->protocol &&
3765 sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3766 protocol = sock->protocol->protocol->type;
3767 silc_protocol_cancel(sock->protocol, server->schedule);
3768 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3769 silc_protocol_execute_final(sock->protocol, server->schedule);
3770 sock->protocol = NULL;
3774 silc_server_disconnect_remote(server, sock,
3776 SILC_PROTOCOL_SERVER_CONNECTION_AUTH ?
3777 SILC_STATUS_ERR_AUTH_FAILED :
3778 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
3779 "Connection timeout");
3781 if (sock->user_data)
3782 silc_server_free_sock_user_data(server, sock, NULL);
3785 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
3786 function may be used only by router. In real SILC network all channels
3787 are created by routers thus this function is never used by normal
3790 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3791 SilcServerID *router_id,
3797 SilcChannelID *channel_id;
3798 SilcChannelEntry entry;
3802 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3805 cipher = SILC_DEFAULT_CIPHER;
3807 hmac = SILC_DEFAULT_HMAC;
3809 /* Allocate cipher */
3810 if (!silc_cipher_alloc(cipher, &key))
3814 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3815 silc_cipher_free(key);
3819 channel_name = strdup(channel_name);
3821 /* Create the channel ID */
3822 if (!silc_id_create_channel_id(server, router_id, server->rng,
3824 silc_free(channel_name);
3825 silc_cipher_free(key);
3826 silc_hmac_free(newhmac);
3830 /* Create the channel */
3831 entry = silc_idlist_add_channel(server->local_list, channel_name,
3832 SILC_CHANNEL_MODE_NONE, channel_id,
3833 NULL, key, newhmac, 0);
3835 silc_free(channel_name);
3836 silc_cipher_free(key);
3837 silc_hmac_free(newhmac);
3838 silc_free(channel_id);
3842 entry->cipher = strdup(cipher);
3843 entry->hmac_name = strdup(hmac);
3845 /* Now create the actual key material */
3846 if (!silc_server_create_channel_key(server, entry,
3847 silc_cipher_get_key_len(key) / 8)) {
3848 silc_idlist_del_channel(server->local_list, entry);
3852 /* Notify other routers about the new channel. We send the packet
3853 to our primary route. */
3855 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3856 channel_name, entry->id,
3857 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3860 /* Distribute to backup routers */
3861 if (broadcast && server->server_type == SILC_ROUTER) {
3864 SilcUInt32 name_len = strlen(channel_name);
3865 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3866 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3868 packet = silc_channel_payload_encode(channel_name, name_len,
3869 cid, channel_id_len, entry->mode);
3870 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3871 packet->data, packet->len, FALSE, TRUE);
3873 silc_buffer_free(packet);
3876 server->stat.my_channels++;
3877 if (server->server_type == SILC_ROUTER) {
3878 server->stat.channels++;
3879 server->stat.cell_channels++;
3880 entry->users_resolved = TRUE;
3886 /* Same as above but creates the channel with Channel ID `channel_id. */
3889 silc_server_create_new_channel_with_id(SilcServer server,
3893 SilcChannelID *channel_id,
3896 SilcChannelEntry entry;
3900 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3903 cipher = SILC_DEFAULT_CIPHER;
3905 hmac = SILC_DEFAULT_HMAC;
3907 /* Allocate cipher */
3908 if (!silc_cipher_alloc(cipher, &key))
3912 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3913 silc_cipher_free(key);
3917 channel_name = strdup(channel_name);
3919 /* Create the channel */
3920 entry = silc_idlist_add_channel(server->local_list, channel_name,
3921 SILC_CHANNEL_MODE_NONE, channel_id,
3922 NULL, key, newhmac, 0);
3924 silc_cipher_free(key);
3925 silc_hmac_free(newhmac);
3926 silc_free(channel_name);
3930 /* Now create the actual key material */
3931 if (!silc_server_create_channel_key(server, entry,
3932 silc_cipher_get_key_len(key) / 8)) {
3933 silc_idlist_del_channel(server->local_list, entry);
3937 /* Notify other routers about the new channel. We send the packet
3938 to our primary route. */
3940 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3941 channel_name, entry->id,
3942 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3945 /* Distribute to backup routers */
3946 if (broadcast && server->server_type == SILC_ROUTER) {
3949 SilcUInt32 name_len = strlen(channel_name);
3950 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3951 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3953 packet = silc_channel_payload_encode(channel_name, name_len,
3954 cid, channel_id_len, entry->mode);
3955 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3956 packet->data, packet->len, FALSE, TRUE);
3958 silc_buffer_free(packet);
3961 server->stat.my_channels++;
3962 if (server->server_type == SILC_ROUTER) {
3963 server->stat.channels++;
3964 server->stat.cell_channels++;
3965 entry->users_resolved = TRUE;
3971 /* Channel's key re-key timeout callback. */
3973 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3975 SilcServer server = app_context;
3976 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3980 /* Return now if we are shutting down */
3981 if (server->server_shutdown)
3984 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3987 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3990 /* Generates new channel key. This is used to create the initial channel key
3991 but also to re-generate new key for channel. If `key_len' is provided
3992 it is the bytes of the key length. */
3994 bool silc_server_create_channel_key(SilcServer server,
3995 SilcChannelEntry channel,
3999 unsigned char channel_key[32], hash[32];
4002 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
4003 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
4007 SILC_LOG_DEBUG(("Generating channel %s key", channel->channel_name));
4009 if (!channel->channel_key)
4010 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
4011 channel->channel_key = NULL;
4017 else if (channel->key_len)
4018 len = channel->key_len / 8;
4020 len = silc_cipher_get_key_len(channel->channel_key) / 8;
4022 /* Create channel key */
4023 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
4026 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
4028 /* Remove old key if exists */
4030 memset(channel->key, 0, channel->key_len / 8);
4031 silc_free(channel->key);
4035 channel->key_len = len * 8;
4036 channel->key = silc_memdup(channel_key, len);
4037 memset(channel_key, 0, sizeof(channel_key));
4039 /* Generate HMAC key from the channel key data and set it */
4041 if (!silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac)) {
4042 memset(channel->key, 0, channel->key_len / 8);
4043 silc_free(channel->key);
4044 channel->channel_key = NULL;
4047 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
4048 silc_hmac_set_key(channel->hmac, hash,
4049 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
4050 memset(hash, 0, sizeof(hash));
4052 if (server->server_type == SILC_ROUTER) {
4053 if (!channel->rekey)
4054 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
4055 channel->rekey->channel = channel;
4056 channel->rekey->key_len = key_len;
4057 if (channel->rekey->task)
4058 silc_schedule_task_del(server->schedule, channel->rekey->task);
4060 channel->rekey->task =
4061 silc_schedule_task_add(server->schedule, 0,
4062 silc_server_channel_key_rekey,
4063 (void *)channel->rekey,
4064 server->config->channel_rekey_secs, 0,
4066 SILC_TASK_PRI_NORMAL);
4072 /* Saves the channel key found in the encoded `key_payload' buffer. This
4073 function is used when we receive Channel Key Payload and also when we're
4074 processing JOIN command reply. Returns entry to the channel. */
4076 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
4077 SilcBuffer key_payload,
4078 SilcChannelEntry channel)
4080 SilcChannelKeyPayload payload = NULL;
4081 SilcChannelID *id = NULL;
4082 unsigned char *tmp, hash[32];
4086 /* Decode channel key payload */
4087 payload = silc_channel_key_payload_parse(key_payload->data,
4090 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
4095 /* Get the channel entry */
4098 /* Get channel ID */
4099 tmp = silc_channel_key_get_id(payload, &tmp_len);
4100 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
4106 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
4108 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
4110 if (server->server_type == SILC_ROUTER)
4111 SILC_LOG_ERROR(("Received key for non-existent channel %s",
4112 silc_id_render(id, SILC_ID_CHANNEL)));
4118 SILC_LOG_DEBUG(("Saving new channel %s key", channel->channel_name));
4120 tmp = silc_channel_key_get_key(payload, &tmp_len);
4126 cipher = silc_channel_key_get_cipher(payload, NULL);
4132 /* Remove old key if exists */
4134 memset(channel->key, 0, channel->key_len / 8);
4135 silc_free(channel->key);
4136 silc_cipher_free(channel->channel_key);
4139 /* Create new cipher */
4140 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
4141 channel->channel_key = NULL;
4146 if (channel->cipher)
4147 silc_free(channel->cipher);
4148 channel->cipher = strdup(cipher);
4151 channel->key_len = tmp_len * 8;
4152 channel->key = silc_memdup(tmp, tmp_len);
4153 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
4155 /* Generate HMAC key from the channel key data and set it */
4157 if (!silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac)) {
4158 memset(channel->key, 0, channel->key_len / 8);
4159 silc_free(channel->key);
4160 channel->channel_key = NULL;
4163 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
4164 silc_hmac_set_key(channel->hmac, hash,
4165 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
4167 memset(hash, 0, sizeof(hash));
4168 memset(tmp, 0, tmp_len);
4170 if (server->server_type == SILC_ROUTER) {
4171 if (!channel->rekey)
4172 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
4173 channel->rekey->channel = channel;
4174 if (channel->rekey->task)
4175 silc_schedule_task_del(server->schedule, channel->rekey->task);
4177 channel->rekey->task =
4178 silc_schedule_task_add(server->schedule, 0,
4179 silc_server_channel_key_rekey,
4180 (void *)channel->rekey,
4181 server->config->channel_rekey_secs, 0,
4183 SILC_TASK_PRI_NORMAL);
4189 silc_channel_key_payload_free(payload);
4194 /* Heartbeat callback. This function is set as argument for the
4195 silc_socket_set_heartbeat function. The library will call this function
4196 at the set time interval. */
4198 void silc_server_perform_heartbeat(SilcSocketConnection sock,
4201 SilcServer server = hb_context;
4203 SILC_LOG_DEBUG(("Sending heartbeat to %s:%d (%s)", sock->hostname,
4204 sock->port, sock->ip));
4206 /* Send the heartbeat */
4207 silc_server_send_heartbeat(server, sock);
4210 /* Returns assembled of all servers in the given ID list. The packet's
4211 form is dictated by the New ID payload. */
4213 static void silc_server_announce_get_servers(SilcServer server,
4214 SilcServerEntry remote,
4216 SilcBuffer *servers,
4217 unsigned long creation_time)
4219 SilcIDCacheList list;
4220 SilcIDCacheEntry id_cache;
4221 SilcServerEntry entry;
4224 /* Go through all clients in the list */
4225 if (silc_idcache_get_all(id_list->servers, &list)) {
4226 if (silc_idcache_list_first(list, &id_cache)) {
4228 entry = (SilcServerEntry)id_cache->context;
4230 /* Do not announce the one we've sending our announcements and
4231 do not announce ourself. Also check the creation time if it's
4233 if ((entry == remote) || (entry == server->id_entry) ||
4234 (creation_time && entry->data.created < creation_time)) {
4235 if (!silc_idcache_list_next(list, &id_cache))
4240 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
4242 *servers = silc_buffer_realloc(*servers,
4244 (*servers)->truelen + idp->len :
4246 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
4247 silc_buffer_put(*servers, idp->data, idp->len);
4248 silc_buffer_pull(*servers, idp->len);
4249 silc_buffer_free(idp);
4251 if (!silc_idcache_list_next(list, &id_cache))
4256 silc_idcache_list_free(list);
4261 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
4267 p = silc_notify_payload_encode(notify, argc, ap);
4273 /* This function is used by router to announce existing servers to our
4274 primary router when we've connected to it. If `creation_time' is non-zero
4275 then only the servers that has been created after the `creation_time'
4276 will be announced. */
4278 void silc_server_announce_servers(SilcServer server, bool global,
4279 unsigned long creation_time,
4280 SilcSocketConnection remote)
4282 SilcBuffer servers = NULL;
4284 SILC_LOG_DEBUG(("Announcing servers"));
4286 /* Get servers in local list */
4287 silc_server_announce_get_servers(server, remote->user_data,
4288 server->local_list, &servers,
4292 /* Get servers in global list */
4293 silc_server_announce_get_servers(server, remote->user_data,
4294 server->global_list, &servers,
4298 silc_buffer_push(servers, servers->data - servers->head);
4299 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
4301 /* Send the packet */
4302 silc_server_packet_send(server, remote,
4303 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4304 servers->data, servers->len, TRUE);
4306 silc_buffer_free(servers);
4310 /* Returns assembled packet of all clients in the given ID list. The
4311 packet's form is dictated by the New ID Payload. */
4313 static void silc_server_announce_get_clients(SilcServer server,
4315 SilcBuffer *clients,
4317 unsigned long creation_time)
4319 SilcIDCacheList list;
4320 SilcIDCacheEntry id_cache;
4321 SilcClientEntry client;
4324 unsigned char mode[4];
4326 /* Go through all clients in the list */
4327 if (silc_idcache_get_all(id_list->clients, &list)) {
4328 if (silc_idcache_list_first(list, &id_cache)) {
4330 client = (SilcClientEntry)id_cache->context;
4332 if (creation_time && client->data.created < creation_time) {
4333 if (!silc_idcache_list_next(list, &id_cache))
4337 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED) &&
4338 !client->connection && !client->router && !SILC_IS_LOCAL(client)) {
4339 if (!silc_idcache_list_next(list, &id_cache))
4344 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
4346 *clients = silc_buffer_realloc(*clients,
4348 (*clients)->truelen + idp->len :
4350 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
4351 silc_buffer_put(*clients, idp->data, idp->len);
4352 silc_buffer_pull(*clients, idp->len);
4354 SILC_PUT32_MSB(client->mode, mode);
4356 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
4357 2, idp->data, idp->len,
4359 *umodes = silc_buffer_realloc(*umodes,
4361 (*umodes)->truelen + tmp->len :
4363 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
4364 silc_buffer_put(*umodes, tmp->data, tmp->len);
4365 silc_buffer_pull(*umodes, tmp->len);
4366 silc_buffer_free(tmp);
4368 silc_buffer_free(idp);
4370 if (!silc_idcache_list_next(list, &id_cache))
4375 silc_idcache_list_free(list);
4379 /* This function is used to announce our existing clients to our router
4380 when we've connected to it. If `creation_time' is non-zero then only
4381 the clients that has been created after the `creation_time' will be
4384 void silc_server_announce_clients(SilcServer server,
4385 unsigned long creation_time,
4386 SilcSocketConnection remote)
4388 SilcBuffer clients = NULL;
4389 SilcBuffer umodes = NULL;
4391 SILC_LOG_DEBUG(("Announcing clients"));
4393 /* Get clients in local list */
4394 silc_server_announce_get_clients(server, server->local_list,
4395 &clients, &umodes, creation_time);
4397 /* As router we announce our global list as well */
4398 if (server->server_type == SILC_ROUTER)
4399 silc_server_announce_get_clients(server, server->global_list,
4400 &clients, &umodes, creation_time);
4403 silc_buffer_push(clients, clients->data - clients->head);
4404 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
4406 /* Send the packet */
4407 silc_server_packet_send(server, remote,
4408 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4409 clients->data, clients->len, TRUE);
4411 silc_buffer_free(clients);
4415 silc_buffer_push(umodes, umodes->data - umodes->head);
4416 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
4418 /* Send the packet */
4419 silc_server_packet_send(server, remote,
4420 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4421 umodes->data, umodes->len, TRUE);
4423 silc_buffer_free(umodes);
4427 /* Returns channel's topic for announcing it */
4429 void silc_server_announce_get_channel_topic(SilcServer server,
4430 SilcChannelEntry channel,
4435 if (channel->topic) {
4436 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4437 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
4438 chidp->data, chidp->len,
4440 strlen(channel->topic));
4441 silc_buffer_free(chidp);
4445 /* Returns channel's invite and ban lists */
4447 void silc_server_announce_get_inviteban(SilcServer server,
4448 SilcChannelEntry channel,
4452 SilcBuffer list, idp, idp2, tmp2;
4454 SilcHashTableList htl;
4455 const unsigned char a[1] = { 0x03 };
4457 idp = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
4459 /* Encode invite list */
4460 if (channel->invite_list && silc_hash_table_count(channel->invite_list)) {
4461 list = silc_buffer_alloc_size(2);
4462 type = silc_hash_table_count(channel->invite_list);
4463 SILC_PUT16_MSB(type, list->data);
4464 silc_hash_table_list(channel->invite_list, &htl);
4465 while (silc_hash_table_get(&htl, (void **)&type, (void **)&tmp2))
4466 list = silc_argument_payload_encode_one(list, tmp2->data, tmp2->len,
4468 silc_hash_table_list_reset(&htl);
4470 idp2 = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4472 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_INVITE, 5,
4473 idp->data, idp->len,
4474 channel->channel_name,
4475 strlen(channel->channel_name),
4476 idp2->data, idp2->len,
4478 list->data, list->len);
4479 silc_buffer_free(idp2);
4480 silc_buffer_free(list);
4483 /* Encode ban list */
4484 if (channel->ban_list && silc_hash_table_count(channel->ban_list)) {
4485 list = silc_buffer_alloc_size(2);
4486 type = silc_hash_table_count(channel->ban_list);
4487 SILC_PUT16_MSB(type, list->data);
4488 silc_hash_table_list(channel->ban_list, &htl);
4489 while (silc_hash_table_get(&htl, (void **)&type, (void **)&tmp2))
4490 list = silc_argument_payload_encode_one(list, tmp2->data, tmp2->len,
4492 silc_hash_table_list_reset(&htl);
4495 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_BAN, 3,
4496 idp->data, idp->len,
4498 list->data, list->len);
4499 silc_buffer_free(list);
4502 silc_buffer_free(idp);
4505 /* Returns assembled packets for channel users of the `channel'. */
4507 void silc_server_announce_get_channel_users(SilcServer server,
4508 SilcChannelEntry channel,
4509 SilcBuffer *channel_modes,
4510 SilcBuffer *channel_users,
4511 SilcBuffer *channel_users_modes)
4513 SilcChannelClientEntry chl;
4514 SilcHashTableList htl;
4515 SilcBuffer chidp, clidp, csidp;
4516 SilcBuffer tmp, fkey = NULL, chpklist;
4518 unsigned char mode[4];
4521 SILC_LOG_DEBUG(("Start"));
4523 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4524 csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4525 chpklist = silc_server_get_channel_pk_list(server, channel, TRUE, FALSE);
4528 SILC_PUT32_MSB(channel->mode, mode);
4529 hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
4530 if (channel->founder_key)
4531 fkey = silc_pkcs_public_key_payload_encode(channel->founder_key);
4533 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
4534 7, csidp->data, csidp->len,
4537 hmac, hmac ? strlen(hmac) : 0,
4538 channel->passphrase,
4539 channel->passphrase ?
4540 strlen(channel->passphrase) : 0,
4541 fkey ? fkey->data : NULL,
4542 fkey ? fkey->len : 0,
4543 chpklist ? chpklist->data : NULL,
4544 chpklist ? chpklist->len : 0);
4547 silc_buffer_realloc(*channel_modes,
4549 (*channel_modes)->truelen + len : len));
4550 silc_buffer_pull_tail(*channel_modes,
4551 ((*channel_modes)->end -
4552 (*channel_modes)->data));
4553 silc_buffer_put(*channel_modes, tmp->data, tmp->len);
4554 silc_buffer_pull(*channel_modes, len);
4555 silc_buffer_free(tmp);
4556 silc_buffer_free(fkey);
4559 /* Now find all users on the channel */
4560 silc_hash_table_list(channel->user_list, &htl);
4561 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4562 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4565 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
4566 clidp->data, clidp->len,
4567 chidp->data, chidp->len);
4570 silc_buffer_realloc(*channel_users,
4572 (*channel_users)->truelen + len : len));
4573 silc_buffer_pull_tail(*channel_users,
4574 ((*channel_users)->end -
4575 (*channel_users)->data));
4577 silc_buffer_put(*channel_users, tmp->data, tmp->len);
4578 silc_buffer_pull(*channel_users, len);
4579 silc_buffer_free(tmp);
4581 /* CUMODE notify for mode change on the channel */
4582 SILC_PUT32_MSB(chl->mode, mode);
4583 if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
4584 fkey = silc_pkcs_public_key_payload_encode(channel->founder_key);
4585 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
4586 4, csidp->data, csidp->len,
4588 clidp->data, clidp->len,
4589 fkey ? fkey->data : NULL,
4590 fkey ? fkey->len : 0);
4592 *channel_users_modes =
4593 silc_buffer_realloc(*channel_users_modes,
4594 (*channel_users_modes ?
4595 (*channel_users_modes)->truelen + len : len));
4596 silc_buffer_pull_tail(*channel_users_modes,
4597 ((*channel_users_modes)->end -
4598 (*channel_users_modes)->data));
4600 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
4601 silc_buffer_pull(*channel_users_modes, len);
4602 silc_buffer_free(tmp);
4603 silc_buffer_free(fkey);
4605 silc_buffer_free(clidp);
4607 silc_hash_table_list_reset(&htl);
4608 silc_buffer_free(chidp);
4609 silc_buffer_free(csidp);
4612 /* Returns assembled packets for all channels and users on those channels
4613 from the given ID List. The packets are in the form dictated by the
4614 New Channel and New Channel User payloads. */
4616 void silc_server_announce_get_channels(SilcServer server,
4618 SilcBuffer *channels,
4619 SilcBuffer **channel_modes,
4620 SilcBuffer *channel_users,
4621 SilcBuffer **channel_users_modes,
4622 SilcUInt32 *channel_users_modes_c,
4623 SilcBuffer **channel_topics,
4624 SilcBuffer **channel_invites,
4625 SilcBuffer **channel_bans,
4626 SilcChannelID ***channel_ids,
4627 unsigned long creation_time)
4629 SilcIDCacheList list;
4630 SilcIDCacheEntry id_cache;
4631 SilcChannelEntry channel;
4634 SilcUInt16 name_len;
4636 int i = *channel_users_modes_c;
4639 SILC_LOG_DEBUG(("Start"));
4641 /* Go through all channels in the list */
4642 if (silc_idcache_get_all(id_list->channels, &list)) {
4643 if (silc_idcache_list_first(list, &id_cache)) {
4645 channel = (SilcChannelEntry)id_cache->context;
4647 if (creation_time && channel->created < creation_time)
4652 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4653 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4654 name_len = strlen(channel->channel_name);
4657 len = 4 + name_len + id_len + 4;
4659 silc_buffer_realloc(*channels,
4660 (*channels ? (*channels)->truelen +
4662 silc_buffer_pull_tail(*channels,
4663 ((*channels)->end - (*channels)->data));
4664 silc_buffer_format(*channels,
4665 SILC_STR_UI_SHORT(name_len),
4666 SILC_STR_UI_XNSTRING(channel->channel_name,
4668 SILC_STR_UI_SHORT(id_len),
4669 SILC_STR_UI_XNSTRING(cid, id_len),
4670 SILC_STR_UI_INT(channel->mode),
4672 silc_buffer_pull(*channels, len);
4675 if (creation_time && channel->updated < creation_time)
4681 /* Channel user modes */
4682 *channel_users_modes = silc_realloc(*channel_users_modes,
4683 sizeof(**channel_users_modes) *
4685 (*channel_users_modes)[i] = NULL;
4686 *channel_modes = silc_realloc(*channel_modes,
4687 sizeof(**channel_modes) * (i + 1));
4688 (*channel_modes)[i] = NULL;
4689 *channel_ids = silc_realloc(*channel_ids,
4690 sizeof(**channel_ids) * (i + 1));
4691 (*channel_ids)[i] = NULL;
4692 silc_server_announce_get_channel_users(server, channel,
4693 &(*channel_modes)[i],
4695 &(*channel_users_modes)[i]);
4696 (*channel_ids)[i] = channel->id;
4698 /* Channel's topic */
4699 *channel_topics = silc_realloc(*channel_topics,
4700 sizeof(**channel_topics) * (i + 1));
4701 (*channel_topics)[i] = NULL;
4702 silc_server_announce_get_channel_topic(server, channel,
4703 &(*channel_topics)[i]);
4705 /* Channel's invite and ban list */
4706 *channel_invites = silc_realloc(*channel_invites,
4707 sizeof(**channel_invites) * (i + 1));
4708 (*channel_invites)[i] = NULL;
4709 *channel_bans = silc_realloc(*channel_bans,
4710 sizeof(**channel_bans) * (i + 1));
4711 (*channel_bans)[i] = NULL;
4712 silc_server_announce_get_inviteban(server, channel,
4713 &(*channel_invites)[i],
4714 &(*channel_bans)[i]);
4716 (*channel_users_modes_c)++;
4722 if (!silc_idcache_list_next(list, &id_cache))
4727 silc_idcache_list_free(list);
4731 /* This function is used to announce our existing channels to our router
4732 when we've connected to it. This also announces the users on the
4733 channels to the router. If the `creation_time' is non-zero only the
4734 channels that was created after the `creation_time' are announced.
4735 Note that the channel users are still announced even if the `creation_time'
4738 void silc_server_announce_channels(SilcServer server,
4739 unsigned long creation_time,
4740 SilcSocketConnection remote)
4742 SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
4743 SilcBuffer *channel_users_modes = NULL;
4744 SilcBuffer *channel_topics = NULL;
4745 SilcBuffer *channel_invites = NULL;
4746 SilcBuffer *channel_bans = NULL;
4747 SilcUInt32 channel_users_modes_c = 0;
4748 SilcChannelID **channel_ids = NULL;
4750 SILC_LOG_DEBUG(("Announcing channels and channel users"));
4752 /* Get channels and channel users in local list */
4753 silc_server_announce_get_channels(server, server->local_list,
4754 &channels, &channel_modes,
4756 &channel_users_modes,
4757 &channel_users_modes_c,
4761 &channel_ids, creation_time);
4763 /* Get channels and channel users in global list */
4764 if (server->server_type != SILC_SERVER)
4765 silc_server_announce_get_channels(server, server->global_list,
4766 &channels, &channel_modes,
4768 &channel_users_modes,
4769 &channel_users_modes_c,
4773 &channel_ids, creation_time);
4776 silc_buffer_push(channels, channels->data - channels->head);
4777 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
4779 /* Send the packet */
4780 silc_server_packet_send(server, remote,
4781 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
4782 channels->data, channels->len,
4785 silc_buffer_free(channels);
4788 if (channel_users) {
4789 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
4790 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
4791 channel_users->len);
4793 /* Send the packet */
4794 silc_server_packet_send(server, remote,
4795 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4796 channel_users->data, channel_users->len,
4799 silc_buffer_free(channel_users);
4802 if (channel_modes) {
4805 for (i = 0; i < channel_users_modes_c; i++) {
4806 if (!channel_modes[i])
4808 silc_buffer_push(channel_modes[i],
4809 channel_modes[i]->data -
4810 channel_modes[i]->head);
4811 SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
4812 channel_modes[i]->len);
4813 silc_server_packet_send_dest(server, remote,
4814 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4815 channel_ids[i], SILC_ID_CHANNEL,
4816 channel_modes[i]->data,
4817 channel_modes[i]->len,
4819 silc_buffer_free(channel_modes[i]);
4821 silc_free(channel_modes);
4824 if (channel_users_modes) {
4827 for (i = 0; i < channel_users_modes_c; i++) {
4828 if (!channel_users_modes[i])
4830 silc_buffer_push(channel_users_modes[i],
4831 channel_users_modes[i]->data -
4832 channel_users_modes[i]->head);
4833 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
4834 channel_users_modes[i]->len);
4835 silc_server_packet_send_dest(server, remote,
4836 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4837 channel_ids[i], SILC_ID_CHANNEL,
4838 channel_users_modes[i]->data,
4839 channel_users_modes[i]->len,
4841 silc_buffer_free(channel_users_modes[i]);
4843 silc_free(channel_users_modes);
4846 if (channel_topics) {
4849 for (i = 0; i < channel_users_modes_c; i++) {
4850 if (!channel_topics[i])
4853 silc_buffer_push(channel_topics[i],
4854 channel_topics[i]->data -
4855 channel_topics[i]->head);
4856 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
4857 channel_topics[i]->len);
4858 silc_server_packet_send_dest(server, remote,
4859 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4860 channel_ids[i], SILC_ID_CHANNEL,
4861 channel_topics[i]->data,
4862 channel_topics[i]->len,
4864 silc_buffer_free(channel_topics[i]);
4866 silc_free(channel_topics);
4869 if (channel_invites) {
4872 for (i = 0; i < channel_users_modes_c; i++) {
4873 if (!channel_invites[i])
4876 silc_buffer_push(channel_invites[i],
4877 channel_invites[i]->data -
4878 channel_invites[i]->head);
4879 SILC_LOG_HEXDUMP(("channel invite list"), channel_invites[i]->data,
4880 channel_invites[i]->len);
4881 silc_server_packet_send_dest(server, remote,
4882 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4883 channel_ids[i], SILC_ID_CHANNEL,
4884 channel_invites[i]->data,
4885 channel_invites[i]->len,
4887 silc_buffer_free(channel_invites[i]);
4889 silc_free(channel_invites);
4895 for (i = 0; i < channel_users_modes_c; i++) {
4896 if (!channel_bans[i])
4899 silc_buffer_push(channel_bans[i],
4900 channel_bans[i]->data -
4901 channel_bans[i]->head);
4902 SILC_LOG_HEXDUMP(("channel ban list"), channel_bans[i]->data,
4903 channel_bans[i]->len);
4904 silc_server_packet_send_dest(server, remote,
4905 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4906 channel_ids[i], SILC_ID_CHANNEL,
4907 channel_bans[i]->data,
4908 channel_bans[i]->len,
4910 silc_buffer_free(channel_bans[i]);
4912 silc_free(channel_bans);
4915 silc_free(channel_ids);
4918 /* Assembles user list and users mode list from the `channel'. */
4920 bool silc_server_get_users_on_channel(SilcServer server,
4921 SilcChannelEntry channel,
4922 SilcBuffer *user_list,
4923 SilcBuffer *mode_list,
4924 SilcUInt32 *user_count)
4926 SilcChannelClientEntry chl;
4927 SilcHashTableList htl;
4928 SilcBuffer client_id_list;
4929 SilcBuffer client_mode_list;
4931 SilcUInt32 list_count = 0, len = 0;
4933 if (!silc_hash_table_count(channel->user_list))
4936 silc_hash_table_list(channel->user_list, &htl);
4937 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4938 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
4939 silc_hash_table_list_reset(&htl);
4941 client_id_list = silc_buffer_alloc(len);
4943 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
4944 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
4945 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
4947 silc_hash_table_list(channel->user_list, &htl);
4948 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4950 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4951 silc_buffer_put(client_id_list, idp->data, idp->len);
4952 silc_buffer_pull(client_id_list, idp->len);
4953 silc_buffer_free(idp);
4955 /* Client's mode on channel */
4956 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
4957 silc_buffer_pull(client_mode_list, 4);
4961 silc_hash_table_list_reset(&htl);
4962 silc_buffer_push(client_id_list,
4963 client_id_list->data - client_id_list->head);
4964 silc_buffer_push(client_mode_list,
4965 client_mode_list->data - client_mode_list->head);
4967 *user_list = client_id_list;
4968 *mode_list = client_mode_list;
4969 *user_count = list_count;
4973 /* Saves users and their modes to the `channel'. */
4975 void silc_server_save_users_on_channel(SilcServer server,
4976 SilcSocketConnection sock,
4977 SilcChannelEntry channel,
4978 SilcClientID *noadd,
4979 SilcBuffer user_list,
4980 SilcBuffer mode_list,
4981 SilcUInt32 user_count)
4986 SilcClientID *client_id;
4987 SilcClientEntry client;
4988 SilcIDCacheEntry cache;
4989 SilcChannelClientEntry chl;
4991 SILC_LOG_DEBUG(("Saving %d users on %s channel", user_count,
4992 channel->channel_name));
4994 for (i = 0; i < user_count; i++) {
4996 SILC_GET16_MSB(idp_len, user_list->data + 2);
4998 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
4999 silc_buffer_pull(user_list, idp_len);
5004 SILC_GET32_MSB(mode, mode_list->data);
5005 silc_buffer_pull(mode_list, 4);
5007 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
5008 silc_free(client_id);
5014 /* Check if we have this client cached already. */
5015 client = silc_idlist_find_client_by_id(server->local_list, client_id,
5016 server->server_type, &cache);
5018 client = silc_idlist_find_client_by_id(server->global_list,
5019 client_id, server->server_type,
5022 /* If router did not find such Client ID in its lists then this must
5023 be bogus client or some router in the net is buggy. */
5024 if (server->server_type != SILC_SERVER) {
5025 silc_free(client_id);
5029 /* We don't have that client anywhere, add it. The client is added
5030 to global list since server didn't have it in the lists so it must be
5032 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
5033 silc_id_dup(client_id, SILC_ID_CLIENT),
5034 sock->user_data, NULL, 0);
5036 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
5037 silc_free(client_id);
5041 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
5046 silc_free(client_id);
5048 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
5049 SILC_LOG_ERROR(("Attempting to add unregistered client to channel ",
5050 "%s", channel->channel_name));
5054 if (!silc_server_client_on_channel(client, channel, &chl)) {
5055 /* Client was not on the channel, add it. */
5056 chl = silc_calloc(1, sizeof(*chl));
5057 chl->client = client;
5059 chl->channel = channel;
5060 silc_hash_table_add(channel->user_list, chl->client, chl);
5061 silc_hash_table_add(client->channels, chl->channel, chl);
5062 channel->user_count++;
5070 /* Saves channels and channels user modes to the `client'. Removes
5071 the client from those channels that are not sent in the list but
5074 void silc_server_save_user_channels(SilcServer server,
5075 SilcSocketConnection sock,
5076 SilcClientEntry client,
5077 SilcBuffer channels,
5078 SilcBuffer channels_user_modes)
5081 SilcUInt32 *chumodes;
5082 SilcChannelPayload entry;
5083 SilcChannelEntry channel;
5084 SilcChannelID *channel_id;
5085 SilcChannelClientEntry chl;
5086 SilcHashTable ht = NULL;
5087 SilcHashTableList htl;
5091 if (!channels || !channels_user_modes ||
5092 !(client->data.status & SILC_IDLIST_STATUS_REGISTERED))
5095 ch = silc_channel_payload_parse_list(channels->data, channels->len);
5096 if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
5098 ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL,
5099 NULL, NULL, NULL, TRUE);
5100 silc_dlist_start(ch);
5101 while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
5102 /* Check if we have this channel, and add it if we don't have it.
5103 Also add the client on the channel unless it is there already. */
5104 channel_id = silc_channel_get_id_parse(entry);
5105 channel = silc_idlist_find_channel_by_id(server->local_list,
5108 channel = silc_idlist_find_channel_by_id(server->global_list,
5111 if (server->server_type != SILC_SERVER) {
5112 silc_free(channel_id);
5117 /* We don't have that channel anywhere, add it. */
5118 name = silc_channel_get_name(entry, NULL);
5119 channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
5120 channel_id, server->router,
5123 silc_free(channel_id);
5130 channel->mode = silc_channel_get_mode(entry);
5132 /* Add the client on the channel */
5133 if (!silc_server_client_on_channel(client, channel, &chl)) {
5134 chl = silc_calloc(1, sizeof(*chl));
5135 chl->client = client;
5136 chl->mode = chumodes[i++];
5137 chl->channel = channel;
5138 silc_hash_table_add(channel->user_list, chl->client, chl);
5139 silc_hash_table_add(client->channels, chl->channel, chl);
5140 channel->user_count++;
5143 chl->mode = chumodes[i++];
5146 silc_hash_table_add(ht, channel, channel);
5147 silc_free(channel_id);
5149 silc_channel_payload_list_free(ch);
5150 silc_free(chumodes);
5154 /* Go through the list again and remove client from channels that
5155 are no part of the list. */
5157 silc_hash_table_list(client->channels, &htl);
5158 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
5159 if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
5160 silc_hash_table_del(chl->channel->user_list, chl->client);
5161 silc_hash_table_del(chl->client->channels, chl->channel);
5165 silc_hash_table_list_reset(&htl);
5166 silc_hash_table_free(ht);
5168 silc_hash_table_list(client->channels, &htl);
5169 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
5170 silc_hash_table_del(chl->channel->user_list, chl->client);
5171 silc_hash_table_del(chl->client->channels, chl->channel);
5174 silc_hash_table_list_reset(&htl);
5178 /* Lookups route to the client indicated by the `id_data'. The connection
5179 object and internal data object is returned. Returns NULL if route
5180 could not be found to the client. If the `client_id' is specified then
5181 it is used and the `id_data' is ignored. */
5183 SilcSocketConnection
5184 silc_server_get_client_route(SilcServer server,
5185 unsigned char *id_data,
5187 SilcClientID *client_id,
5188 SilcIDListData *idata,
5189 SilcClientEntry *client_entry)
5192 SilcClientEntry client;
5194 SILC_LOG_DEBUG(("Start"));
5197 *client_entry = NULL;
5199 /* Decode destination Client ID */
5201 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
5203 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
5207 id = silc_id_dup(client_id, SILC_ID_CLIENT);
5210 /* If the destination belongs to our server we don't have to route
5211 the packet anywhere but to send it to the local destination. */
5212 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
5216 /* If we are router and the client has router then the client is in
5217 our cell but not directly connected to us. */
5218 if (server->server_type == SILC_ROUTER && client->router) {
5219 /* We are of course in this case the client's router thus the route
5220 to the client is the server who owns the client. So, we will send
5221 the packet to that server. */
5223 *idata = (SilcIDListData)client->router;
5224 return client->router->connection;
5227 /* Seems that client really is directly connected to us */
5229 *idata = (SilcIDListData)client;
5231 *client_entry = client;
5232 return client->connection;
5235 /* Destination belongs to someone not in this server. If we are normal
5236 server our action is to send the packet to our router. */
5237 if (server->server_type != SILC_ROUTER && !server->standalone) {
5240 *idata = (SilcIDListData)server->router;
5241 return SILC_PRIMARY_ROUTE(server);
5244 /* We are router and we will perform route lookup for the destination
5245 and send the packet to fastest route. */
5246 if (server->server_type == SILC_ROUTER && !server->standalone) {
5247 /* Check first that the ID is valid */
5248 client = silc_idlist_find_client_by_id(server->global_list, id,
5251 SilcSocketConnection dst_sock;
5253 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
5257 *idata = (SilcIDListData)dst_sock->user_data;
5266 /* Encodes and returns channel list of channels the `client' has joined.
5267 Secret channels are not put to the list. */
5269 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
5270 SilcClientEntry client,
5273 SilcBuffer *user_mode_list)
5275 SilcBuffer buffer = NULL;
5276 SilcChannelEntry channel;
5277 SilcChannelClientEntry chl;
5278 SilcHashTableList htl;
5281 SilcUInt16 name_len;
5285 *user_mode_list = NULL;
5287 silc_hash_table_list(client->channels, &htl);
5288 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5289 channel = chl->channel;
5291 if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
5293 if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
5296 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
5297 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
5298 name_len = strlen(channel->channel_name);
5300 len = 4 + name_len + id_len + 4;
5301 buffer = silc_buffer_realloc(buffer,
5302 (buffer ? buffer->truelen + len : len));
5303 silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
5304 silc_buffer_format(buffer,
5305 SILC_STR_UI_SHORT(name_len),
5306 SILC_STR_UI_XNSTRING(channel->channel_name,
5308 SILC_STR_UI_SHORT(id_len),
5309 SILC_STR_UI_XNSTRING(cid, id_len),
5310 SILC_STR_UI_INT(chl->channel->mode),
5312 silc_buffer_pull(buffer, len);
5315 if (user_mode_list) {
5316 *user_mode_list = silc_buffer_realloc(*user_mode_list,
5318 (*user_mode_list)->truelen + 4 :
5320 silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
5321 (*user_mode_list)->data));
5322 SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
5323 silc_buffer_pull(*user_mode_list, 4);
5326 silc_hash_table_list_reset(&htl);
5329 silc_buffer_push(buffer, buffer->data - buffer->head);
5330 if (user_mode_list && *user_mode_list)
5331 silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
5332 (*user_mode_list)->head));
5337 /* Timeout callback for unsuccessful rekey. The rekey did not go through
5340 SILC_TASK_CALLBACK(silc_server_rekey_timeout)
5342 SilcServerRekeyInternalContext *ctx = context;
5343 SilcServer server = app_context;
5344 SilcSocketConnection sock = ctx->sock;
5346 SILC_LOG_DEBUG(("Timeout occurred in rekey protocol with %s:%d [%s]",
5347 sock->hostname, sock->port,
5348 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5349 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5350 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5353 SILC_LOG_WARNING(("Timeout occurred in rekey protocol with %s:%d [%s]",
5354 sock->hostname, sock->port,
5355 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5356 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5357 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5360 if (sock->protocol) {
5361 silc_protocol_cancel(sock->protocol, server->schedule);
5362 silc_protocol_free(sock->protocol);
5363 sock->protocol = NULL;
5366 silc_packet_context_free(ctx->packet);
5368 silc_ske_free(ctx->ske);
5369 silc_socket_free(sock);
5372 /* Disconnect since we failed to rekey, the keys are probably wrong. */
5373 silc_server_disconnect_remote(server, sock,
5374 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
5377 if (sock->type != SILC_SOCKET_TYPE_CLIENT)
5378 silc_server_create_connections(server);
5381 /* A timeout callback for the re-key. We will be the initiator of the
5384 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_callback)
5386 SilcServer server = app_context;
5387 SilcSocketConnection sock = (SilcSocketConnection)context;
5388 SilcIDListData idata = (SilcIDListData)sock->user_data;
5389 SilcProtocol protocol;
5390 SilcServerRekeyInternalContext *proto_ctx;
5395 /* Do not execute rekey with disabled connections, as it would not
5396 go through anyway. */
5397 if (idata->status & SILC_IDLIST_STATUS_DISABLED)
5400 /* If rekey protocol is active already wait for it to finish */
5401 if (sock->protocol && sock->protocol->protocol &&
5402 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)
5405 /* If any other protocol is active do not start this protocol yet. */
5406 if (sock->protocol) {
5407 SILC_LOG_DEBUG(("Waiting for other protocol to finish before rekeying"));
5408 silc_schedule_task_add(server->schedule, sock->sock,
5409 silc_server_rekey_callback,
5410 sock, 60, 0, SILC_TASK_TIMEOUT,
5411 SILC_TASK_PRI_NORMAL);
5415 SILC_LOG_DEBUG(("Executing rekey protocol with %s:%d [%s]",
5416 sock->hostname, sock->port,
5417 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5418 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5419 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5422 /* Allocate internal protocol context. This is sent as context
5424 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
5425 proto_ctx->server = (void *)server;
5426 proto_ctx->sock = silc_socket_dup(sock);
5427 proto_ctx->responder = FALSE;
5428 proto_ctx->pfs = idata->rekey->pfs;
5430 /* Perform rekey protocol. Will call the final callback after the
5431 protocol is over. */
5432 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
5433 &protocol, proto_ctx, silc_server_rekey_final);
5434 sock->protocol = protocol;
5436 /* Register timeout callback in case the rekey does not go through. */
5437 proto_ctx->timeout_task =
5438 silc_schedule_task_add(server->schedule, sock->sock,
5439 silc_server_rekey_timeout,
5441 (idata->rekey->timeout >
5442 server->config->key_exchange_timeout ?
5443 idata->rekey->timeout :
5444 server->config->key_exchange_timeout * 4), 0,
5448 /* Run the protocol */
5449 silc_protocol_execute(protocol, server->schedule, 0, 0);
5452 /* The final callback for the REKEY protocol. This will actually take the
5453 new key material into use. */
5455 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
5457 SilcProtocol protocol = (SilcProtocol)context;
5458 SilcServerRekeyInternalContext *ctx =
5459 (SilcServerRekeyInternalContext *)protocol->context;
5460 SilcServer server = (SilcServer)ctx->server;
5461 SilcSocketConnection sock = ctx->sock;
5462 SilcIDListData idata = (SilcIDListData)sock->user_data;
5464 if (ctx->timeout_task)
5465 silc_schedule_task_del(server->schedule, ctx->timeout_task);
5467 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
5468 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
5469 /* Error occured during protocol */
5470 SILC_LOG_ERROR(("Error occurred during rekey protocol with "
5471 "%s (%s)", sock->hostname, sock->ip));
5472 silc_protocol_cancel(protocol, server->schedule);
5473 silc_protocol_free(protocol);
5474 sock->protocol = NULL;
5476 silc_packet_context_free(ctx->packet);
5478 silc_ske_free(ctx->ske);
5479 silc_socket_free(sock);
5481 silc_server_disconnect_remote(server, sock,
5482 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
5485 if (sock->type != SILC_SOCKET_TYPE_CLIENT)
5486 silc_server_create_connections(server);
5490 SILC_LOG_DEBUG(("Rekey protocol completed with %s:%d [%s]",
5491 sock->hostname, sock->port,
5492 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5493 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5494 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5497 /* Purge the outgoing data queue to assure that all rekey packets really
5498 go to the network before we quit the protocol. */
5499 silc_server_packet_queue_purge(server, sock);
5501 /* Re-register re-key timeout */
5502 if (ctx->responder == FALSE)
5503 silc_schedule_task_add(server->schedule, sock->sock,
5504 silc_server_rekey_callback,
5505 sock, idata->rekey->timeout, 0,
5506 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
5509 silc_protocol_free(protocol);
5510 sock->protocol = NULL;
5512 silc_packet_context_free(ctx->packet);
5514 silc_ske_free(ctx->ske);
5515 silc_socket_free(sock);
5519 /* Task callback used to retrieve network statistical information from
5520 router server once in a while. */
5522 SILC_TASK_CALLBACK(silc_server_get_stats)
5524 SilcServer server = (SilcServer)context;
5525 SilcBuffer idp, packet;
5527 if (!server->standalone) {
5528 SILC_LOG_DEBUG(("Retrieving stats from router"));
5529 idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
5530 packet = silc_command_payload_encode_va(SILC_COMMAND_STATS,
5531 ++server->cmd_ident, 1,
5532 1, idp->data, idp->len);
5533 silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
5534 SILC_PACKET_COMMAND, 0, packet->data,
5535 packet->len, FALSE);
5536 silc_buffer_free(packet);
5537 silc_buffer_free(idp);
5540 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
5541 server, 120, 0, SILC_TASK_TIMEOUT,