5 Author: Pekka Riikonen <priikone@silcnet.org>
7 Copyright (C) 1997 - 2002 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,
289 /* Steal public and private key from the config object */
290 server->public_key = server->config->server_info->public_key;
291 server->private_key = server->config->server_info->private_key;
292 server->config->server_info->public_key = NULL;
293 server->config->server_info->private_key = NULL;
295 /* Register all configured ciphers, PKCS and hash functions. */
296 if (!silc_server_config_register_ciphers(server))
297 silc_cipher_register_default();
298 if (!silc_server_config_register_pkcs(server))
299 silc_pkcs_register_default();
300 if (!silc_server_config_register_hashfuncs(server))
301 silc_hash_register_default();
302 if (!silc_server_config_register_hmacs(server))
303 silc_hmac_register_default();
305 /* Initialize random number generator for the server. */
306 server->rng = silc_rng_alloc();
307 silc_rng_init(server->rng);
308 silc_rng_global_init(server->rng);
310 /* Initialize hash functions for server to use */
311 silc_hash_alloc("md5", &server->md5hash);
312 silc_hash_alloc("sha1", &server->sha1hash);
314 /* Allocate PKCS context for local public and private keys */
315 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
317 silc_pkcs_public_key_set(server->pkcs, server->public_key);
318 silc_pkcs_private_key_set(server->pkcs, server->private_key);
320 /* Initialize the scheduler */
321 server->schedule = silc_schedule_init(server->config->param.connections_max,
323 if (!server->schedule)
326 /* First, register log files configuration for error output */
327 silc_server_config_setlogfiles(server);
329 /* Initialize ID caches */
330 server->local_list->clients =
331 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
332 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
333 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
335 /* These are allocated for normal server as well as these hold some
336 global information that the server has fetched from its router. For
337 router these are used as they are supposed to be used on router. */
338 server->global_list->clients =
339 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
340 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
341 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
343 /* Init watcher list */
344 server->watcher_list =
345 silc_hash_table_alloc(1, silc_hash_client_id_hash, NULL,
346 silc_hash_data_compare, (void *)CLIENTID_HASH_LEN,
348 if (!server->watcher_list)
351 /* Create a listening server */
352 if (!silc_server_listen(server,
353 server->config->server_info->primary == NULL ? NULL :
354 server->config->server_info->primary->server_ip,
355 server->config->server_info->primary == NULL ? 0 :
356 server->config->server_info->primary->port,
360 /* Set socket to non-blocking mode */
361 silc_net_set_socket_nonblock(sock);
364 /* Allocate the entire socket list that is used in server. Eventually
365 all connections will have entry in this table (it is a table of
366 pointers to the actual object that is allocated individually
368 server->sockets = silc_calloc(server->config->param.connections_max,
369 sizeof(*server->sockets));
370 if (!server->sockets)
373 /* Add ourselves also to the socket table. The entry allocated above
374 is sent as argument for fast referencing in the future. */
375 silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
376 server->sockets[sock] = newsocket;
377 SILC_SET_LISTENER(newsocket);
379 /* Perform name and address lookups to resolve the listenning address
381 if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
383 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
385 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
386 newsocket->hostname ? newsocket->hostname :
387 newsocket->ip ? newsocket->ip : ""));
388 server->stat.conn_failures++;
391 if (!newsocket->hostname)
392 newsocket->hostname = strdup(newsocket->ip);
394 newsocket->port = silc_net_get_local_port(sock);
396 /* Create a Server ID for the server. */
397 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
402 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
403 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
404 server->server_name = server->config->server_info->server_name;
405 server->config->server_info->server_name = NULL;
407 /* Add ourselves to the server list. We don't have a router yet
408 beacuse we haven't established a route yet. It will be done later.
409 For now, NULL is sent as router. This allocates new entry to
412 silc_idlist_add_server(server->local_list, strdup(server->server_name),
413 server->server_type, server->id, NULL, NULL);
415 SILC_LOG_ERROR(("Could not add ourselves to cache"));
418 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
420 /* Put the allocated socket pointer also to the entry allocated above
421 for fast back-referencing to the socket list. */
422 newsocket->user_data = (void *)id_entry;
423 id_entry->connection = (void *)newsocket;
424 server->id_entry = id_entry;
426 /* Register protocols */
427 silc_server_protocols_register();
429 /* Add the first task to the scheduler. This is task that is executed by
430 timeout. It expires as soon as the caller calls silc_server_run. This
431 task performs authentication protocol and key exchange with our
433 silc_schedule_task_add(server->schedule, 0,
434 silc_server_connect_to_router,
435 (void *)server, 0, 1,
437 SILC_TASK_PRI_NORMAL);
439 /* Add listener task to the scheduler. This task receives new connections
440 to the server. This task remains on the queue until the end of the
442 silc_schedule_task_add(server->schedule, sock,
443 silc_server_accept_new_connection,
444 (void *)server, 0, 0,
446 SILC_TASK_PRI_NORMAL);
448 if (silc_server_init_secondary(server) == FALSE)
451 server->listenning = TRUE;
453 /* If server connections has been configured then we must be router as
454 normal server cannot have server connections, only router connections. */
455 if (server->config->servers) {
456 SilcServerConfigServer *ptr = server->config->servers;
458 server->server_type = SILC_ROUTER;
460 if (ptr->backup_router) {
461 server->server_type = SILC_BACKUP_ROUTER;
462 server->backup_router = TRUE;
463 server->id_entry->server_type = SILC_BACKUP_ROUTER;
470 /* Register the ID Cache purge task. This periodically purges the ID cache
471 and removes the expired cache entries. */
473 /* Clients local list */
474 server->purge_i = purge = silc_calloc(1, sizeof(*purge));
475 purge->cache = server->local_list->clients;
476 purge->timeout = 600;
477 silc_schedule_task_add(server->schedule, 0, silc_idlist_purge,
478 (void *)purge, purge->timeout, 0,
479 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
481 /* Clients global list */
482 server->purge_g = purge = silc_calloc(1, sizeof(*purge));
483 purge->cache = server->global_list->clients;
484 purge->timeout = 300;
485 silc_schedule_task_add(server->schedule, 0, silc_idlist_purge,
486 (void *)purge, purge->timeout, 0,
487 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
489 /* If we are normal server we'll retrieve network statisticial information
490 once in a while from the router. */
491 if (server->server_type != SILC_ROUTER)
492 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
493 server, 10, 0, SILC_TASK_TIMEOUT,
496 if (server->server_type == SILC_ROUTER)
497 server->stat.routers++;
499 SILC_LOG_DEBUG(("Server initialized"));
501 /* We are done here, return succesfully */
505 silc_server_config_unref(&server->config_ref);
506 silc_net_close_server(sock);
510 /* Task callback to close a socket connection after rehash */
512 SILC_TASK_CALLBACK(silc_server_rehash_close_connection)
514 SilcServer server = context;
515 SilcSocketConnection sock = server->sockets[fd];
520 SILC_LOG_INFO(("Connection %s:%d [%s] is unconfigured",
521 sock->hostname, sock->port,
522 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
523 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
524 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
526 silc_schedule_task_del_by_context(server->schedule, sock);
527 silc_server_disconnect_remote(server, sock,
528 SILC_STATUS_ERR_BANNED_FROM_SERVER,
529 "This connection is removed from "
532 silc_server_free_sock_user_data(server, sock, NULL);
535 /* This function basically reads the config file again and switches the config
536 object pointed by the server object. After that, we have to fix various
537 things such as the server_name and the listening ports.
538 Keep in mind that we no longer have the root privileges at this point. */
540 bool silc_server_rehash(SilcServer server)
542 SilcServerConfig newconfig;
544 SILC_LOG_INFO(("Rehashing server"));
546 /* Reset the logging system */
547 silc_log_quick = TRUE;
548 silc_log_flush_all();
550 /* Start the main rehash phase (read again the config file) */
551 newconfig = silc_server_config_alloc(server->config_file);
553 SILC_LOG_ERROR(("Rehash FAILED."));
557 /* Reinit scheduler if necessary */
558 if (newconfig->param.connections_max > server->config->param.connections_max)
559 if (!silc_schedule_reinit(server->schedule,
560 newconfig->param.connections_max))
563 /* Fix the server_name field */
564 if (strcmp(server->server_name, newconfig->server_info->server_name)) {
565 silc_free(server->server_name);
566 server->server_name = newconfig->server_info->server_name;
567 newconfig->server_info->server_name = NULL;
569 /* Update the idcache list with a fresh pointer */
570 silc_free(server->id_entry->server_name);
571 server->id_entry->server_name = strdup(server->server_name);
572 if (!silc_idcache_del_by_context(server->local_list->servers,
575 if (!silc_idcache_add(server->local_list->servers,
576 server->id_entry->server_name,
577 server->id_entry->id, server->id_entry, 0, NULL))
582 silc_server_config_setlogfiles(server);
584 /* Change new key pair if necessary */
585 if (newconfig->server_info->public_key &&
586 !silc_pkcs_public_key_compare(server->public_key,
587 newconfig->server_info->public_key)) {
588 silc_pkcs_public_key_free(server->public_key);
589 silc_pkcs_private_key_free(server->private_key);
590 server->public_key = newconfig->server_info->public_key;
591 server->private_key = newconfig->server_info->private_key;
592 newconfig->server_info->public_key = NULL;
593 newconfig->server_info->private_key = NULL;
595 /* Allocate PKCS context for local public and private keys */
596 silc_pkcs_free(server->pkcs);
597 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
599 silc_pkcs_public_key_set(server->pkcs, server->public_key);
600 silc_pkcs_private_key_set(server->pkcs, server->private_key);
603 /* Check for unconfigured server and router connections and close
604 connections that were unconfigured. */
606 if (server->config->routers) {
607 SilcServerConfigRouter *ptr;
608 SilcServerConfigRouter *newptr;
611 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
614 /* Check whether new config has this one too */
615 for (newptr = newconfig->routers; newptr; newptr = newptr->next) {
616 if (silc_string_compare(newptr->host, ptr->host) &&
617 newptr->port == ptr->port &&
618 newptr->initiator == ptr->initiator) {
624 if (!found && ptr->host) {
625 /* Remove this connection */
626 SilcSocketConnection sock;
627 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_ROUTER,
628 ptr->host, ptr->port);
629 if (sock && !SILC_IS_LISTENER(sock))
630 silc_schedule_task_add(server->schedule, sock->sock,
631 silc_server_rehash_close_connection,
632 server, 0, 1, SILC_TASK_TIMEOUT,
633 SILC_TASK_PRI_NORMAL);
638 if (server->config->servers) {
639 SilcServerConfigServer *ptr;
640 SilcServerConfigServer *newptr;
643 for (ptr = server->config->servers; ptr; ptr = ptr->next) {
646 /* Check whether new config has this one too */
647 for (newptr = newconfig->servers; newptr; newptr = newptr->next) {
648 if (silc_string_compare(newptr->host, ptr->host)) {
654 if (!found && ptr->host) {
655 /* Remove this connection */
656 SilcSocketConnection sock;
657 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_SERVER,
659 if (sock && !SILC_IS_LISTENER(sock))
660 silc_schedule_task_add(server->schedule, sock->sock,
661 silc_server_rehash_close_connection,
662 server, 0, 1, SILC_TASK_TIMEOUT,
663 SILC_TASK_PRI_NORMAL);
668 if (server->config->clients) {
669 SilcServerConfigClient *ptr;
670 SilcServerConfigClient *newptr;
673 for (ptr = server->config->clients; ptr; ptr = ptr->next) {
676 /* Check whether new config has this one too */
677 for (newptr = newconfig->clients; newptr; newptr = newptr->next) {
678 if (silc_string_compare(newptr->host, ptr->host)) {
684 if (!found && ptr->host) {
685 /* Remove this connection */
686 SilcSocketConnection sock;
687 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_CLIENT,
690 silc_schedule_task_add(server->schedule, sock->sock,
691 silc_server_rehash_close_connection,
692 server, 0, 1, SILC_TASK_TIMEOUT,
693 SILC_TASK_PRI_NORMAL);
698 /* Go through all configured routers after rehash */
699 silc_schedule_task_add(server->schedule, 0,
700 silc_server_connect_to_router,
701 (void *)server, 0, 1,
703 SILC_TASK_PRI_NORMAL);
705 /* Check whether our router status has changed */
706 if (newconfig->servers) {
707 SilcServerConfigServer *ptr = newconfig->servers;
709 server->server_type = SILC_ROUTER;
711 if (ptr->backup_router) {
712 server->server_type = SILC_BACKUP_ROUTER;
713 server->backup_router = TRUE;
714 server->id_entry->server_type = SILC_BACKUP_ROUTER;
721 /* Our old config is gone now. We'll unreference our reference made in
722 silc_server_init and then destroy it since we are destroying it
723 underneath the application (layer which called silc_server_init). */
724 silc_server_config_unref(&server->config_ref);
725 silc_server_config_destroy(server->config);
727 /* Take new config context */
728 server->config = newconfig;
729 silc_server_config_ref(&server->config_ref, server->config, server->config);
731 SILC_LOG_DEBUG(("Server rehashed"));
736 /* The heart of the server. This runs the scheduler thus runs the server.
737 When this returns the server has been stopped and the program will
740 void silc_server_run(SilcServer server)
742 SILC_LOG_INFO(("SILC Server started"));
744 /* Start the scheduler, the heart of the SILC server. When this returns
745 the program will be terminated. */
746 silc_schedule(server->schedule);
749 /* Stops the SILC server. This function is used to shutdown the server.
750 This is usually called after the scheduler has returned. After stopping
751 the server one should call silc_server_free. */
753 void silc_server_stop(SilcServer server)
755 SILC_LOG_INFO(("SILC Server shutting down"));
757 if (server->schedule) {
760 server->server_shutdown = TRUE;
762 /* Close all connections */
763 for (i = 0; i < server->config->param.connections_max; i++) {
764 if (!server->sockets[i])
766 if (!SILC_IS_LISTENER(server->sockets[i])) {
767 SilcSocketConnection sock = server->sockets[i];
768 SilcIDListData idata = sock->user_data;
771 idata->status &= ~SILC_IDLIST_STATUS_DISABLED;
773 silc_schedule_task_del_by_context(server->schedule,
775 silc_server_disconnect_remote(server, server->sockets[i],
777 "Server is shutting down");
779 silc_server_free_sock_user_data(server, sock,
780 "Server is shutting down");
781 silc_socket_free(sock);
783 silc_socket_free(server->sockets[i]);
784 server->sockets[i] = NULL;
788 /* We are not connected to network anymore */
789 server->standalone = TRUE;
791 silc_schedule_stop(server->schedule);
792 silc_schedule_uninit(server->schedule);
793 server->schedule = NULL;
795 silc_free(server->sockets);
796 server->sockets = NULL;
799 silc_server_protocols_unregister();
801 SILC_LOG_DEBUG(("Server stopped"));
804 /* Function that is called when the network connection to a router has
805 been established. This will continue with the key exchange protocol
806 with the remote router. */
808 void silc_server_start_key_exchange(SilcServer server,
809 SilcServerConnection sconn,
812 SilcSocketConnection newsocket;
813 SilcProtocol protocol;
814 SilcServerKEInternalContext *proto_ctx;
815 SilcServerConfigRouter *conn =
816 (SilcServerConfigRouter *) sconn->conn.ref_ptr;
819 /* Cancel any possible retry timeouts */
820 silc_schedule_task_del_by_callback(server->schedule,
821 silc_server_connect_to_router_retry);
823 /* Set socket options */
824 silc_net_set_socket_nonblock(sock);
825 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
827 /* Create socket connection for the connection. Even though we
828 know that we are connecting to a router we will mark the socket
829 to be unknown connection until we have executed authentication
831 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
832 server->sockets[sock] = newsocket;
833 newsocket->hostname = strdup(sconn->remote_host);
834 newsocket->ip = strdup(sconn->remote_host);
835 newsocket->port = sconn->remote_port;
836 sconn->sock = newsocket;
838 /* Allocate internal protocol context. This is sent as context
840 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
841 proto_ctx->server = (void *)server;
842 proto_ctx->context = (void *)sconn;
843 proto_ctx->sock = newsocket;
844 proto_ctx->rng = server->rng;
845 proto_ctx->responder = FALSE;
847 /* Set Key Exchange flags from configuration, but fall back to global
849 SILC_GET_SKE_FLAGS(conn, proto_ctx);
850 if (server->config->param.key_exchange_pfs)
851 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
853 /* Perform key exchange protocol. silc_server_connect_to_router_second
854 will be called after the protocol is finished. */
855 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
856 &protocol, proto_ctx,
857 silc_server_connect_to_router_second);
858 newsocket->protocol = protocol;
860 /* Register a timeout task that will be executed if the protocol
861 is not executed within set limit. */
862 proto_ctx->timeout_task =
863 silc_schedule_task_add(server->schedule, sock,
864 silc_server_timeout_remote,
865 server, server->config->key_exchange_timeout, 0,
869 /* Register the connection for network input and output. This sets
870 that scheduler will listen for incoming packets for this connection
871 and sets that outgoing packets may be sent to this connection as
872 well. However, this doesn't set the scheduler for outgoing traffic,
873 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
874 later when outgoing data is available. */
875 context = (void *)server;
876 SILC_REGISTER_CONNECTION_FOR_IO(sock);
878 /* Run the protocol */
879 silc_protocol_execute(protocol, server->schedule, 0, 0);
882 /* Timeout callback that will be called to retry connecting to remote
883 router. This is used by both normal and router server. This will wait
884 before retrying the connecting. The timeout is generated by exponential
885 backoff algorithm. */
887 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
889 SilcServer server = app_context;
890 SilcServerConnection sconn = (SilcServerConnection)context;
891 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
892 SilcServerConfigConnParams *param =
893 (conn->param ? conn->param : &server->config->param);
895 /* Don't retry if we are shutting down. */
896 if (server->server_shutdown) {
897 silc_server_config_unref(&sconn->conn);
898 silc_free(sconn->remote_host);
899 silc_free(sconn->backup_replace_ip);
904 SILC_LOG_INFO(("Retrying connecting to a router"));
906 /* Calculate next timeout */
907 if (sconn->retry_count >= 1) {
908 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
909 if (sconn->retry_timeout > param->reconnect_interval_max)
910 sconn->retry_timeout = param->reconnect_interval_max;
912 sconn->retry_timeout = param->reconnect_interval;
914 sconn->retry_count++;
915 sconn->retry_timeout = sconn->retry_timeout +
916 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
918 /* If we've reached max retry count, give up. */
919 if ((sconn->retry_count > param->reconnect_count) &&
920 !param->reconnect_keep_trying) {
921 SILC_LOG_ERROR(("Could not connect to router, giving up"));
922 silc_server_config_unref(&sconn->conn);
923 silc_free(sconn->remote_host);
924 silc_free(sconn->backup_replace_ip);
929 SILC_LOG_DEBUG(("Retrying connecting to a router in %d seconds",
930 sconn->retry_timeout));
932 /* We will lookup a fresh pointer later */
933 silc_server_config_unref(&sconn->conn);
935 /* Wait one before retrying */
936 silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
937 context, sconn->retry_timeout, 0,
938 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
941 /* Generic routine to use connect to a router. */
943 SILC_TASK_CALLBACK(silc_server_connect_router)
945 SilcServer server = app_context;
946 SilcServerConnection sconn = (SilcServerConnection)context;
947 SilcServerConfigRouter *rconn;
950 /* Don't connect if we are shutting down. */
951 if (server->server_shutdown) {
952 silc_free(sconn->remote_host);
953 silc_free(sconn->backup_replace_ip);
958 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
959 (sconn->backup ? "backup router" : "router"),
960 sconn->remote_host, sconn->remote_port));
962 server->router_connect = time(NULL);
963 rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
966 SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
967 (sconn->backup ? "backup router" : "router"),
968 sconn->remote_host, sconn->remote_port));
969 silc_free(sconn->remote_host);
970 silc_free(sconn->backup_replace_ip);
974 silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
976 /* Connect to remote host */
977 sock = silc_net_create_connection(
978 (!server->config->server_info->primary ? NULL :
979 server->config->server_info->primary->server_ip),
980 sconn->remote_port, sconn->remote_host);
982 SILC_LOG_ERROR(("Could not connect to router %s:%d",
983 sconn->remote_host, sconn->remote_port));
984 if (!sconn->no_reconnect)
985 silc_schedule_task_add(server->schedule, 0,
986 silc_server_connect_to_router_retry,
987 context, 0, 1, SILC_TASK_TIMEOUT,
988 SILC_TASK_PRI_NORMAL);
990 silc_server_config_unref(&sconn->conn);
991 silc_free(sconn->remote_host);
992 silc_free(sconn->backup_replace_ip);
998 /* Continue with key exchange protocol */
999 silc_server_start_key_exchange(server, sconn, sock);
1002 /* This function connects to our primary router or if we are a router this
1003 establishes all our primary routes. This is called at the start of the
1004 server to do authentication and key exchange with our router - called
1007 SILC_TASK_CALLBACK_GLOBAL(silc_server_connect_to_router)
1009 SilcServer server = (SilcServer)context;
1010 SilcServerConnection sconn;
1011 SilcServerConfigRouter *ptr;
1013 /* Don't connect if we are shutting down. */
1014 if (server->server_shutdown)
1017 SILC_LOG_DEBUG(("We are %s",
1018 (server->server_type == SILC_SERVER ?
1019 "normal server" : server->server_type == SILC_ROUTER ?
1020 "router" : "backup router/normal server")));
1022 if (!server->config->routers) {
1023 /* There wasn't a configured router, we will continue but we don't
1024 have a connection to outside world. We will be standalone server. */
1025 SILC_LOG_DEBUG(("No router(s), we are standalone"));
1026 server->standalone = TRUE;
1030 /* Cancel any possible retry timeouts */
1031 silc_schedule_task_del_by_callback(server->schedule,
1032 silc_server_connect_router);
1033 silc_schedule_task_del_by_callback(server->schedule,
1034 silc_server_connect_to_router_retry);
1036 /* Create the connections to all our routes */
1037 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
1039 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
1040 ptr->backup_router ? "Backup router" : "Router",
1041 ptr->initiator ? "Initiator" : "Responder",
1042 ptr->host, ptr->port));
1044 if (server->server_type == SILC_ROUTER && ptr->backup_router &&
1045 ptr->initiator == FALSE && !server->backup_router &&
1046 !silc_server_config_get_backup_router(server))
1047 server->wait_backup = TRUE;
1049 if (ptr->initiator) {
1050 /* Check whether we are connected to this host already */
1051 if (silc_server_num_sockets_by_remote(server,
1052 silc_net_is_ip(ptr->host) ?
1054 silc_net_is_ip(ptr->host) ?
1055 NULL : ptr->host, ptr->port,
1056 SILC_SOCKET_TYPE_ROUTER)) {
1057 SILC_LOG_DEBUG(("We are already connected to this router"));
1061 /* Allocate connection object for hold connection specific stuff. */
1062 sconn = silc_calloc(1, sizeof(*sconn));
1063 sconn->remote_host = strdup(ptr->host);
1064 sconn->remote_port = ptr->port;
1065 sconn->backup = ptr->backup_router;
1066 if (sconn->backup) {
1067 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
1068 sconn->backup_replace_port = ptr->backup_replace_port;
1071 if (!server->router_conn && !sconn->backup)
1072 server->router_conn = sconn;
1074 silc_schedule_task_add(server->schedule, 0,
1075 silc_server_connect_router,
1076 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
1077 SILC_TASK_PRI_NORMAL);
1082 /* Second part of connecting to router(s). Key exchange protocol has been
1083 executed and now we will execute authentication protocol. */
1085 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
1087 SilcProtocol protocol = (SilcProtocol)context;
1088 SilcServerKEInternalContext *ctx =
1089 (SilcServerKEInternalContext *)protocol->context;
1090 SilcServer server = (SilcServer)ctx->server;
1091 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1092 SilcSocketConnection sock = ctx->sock;
1093 SilcServerConnAuthInternalContext *proto_ctx;
1094 SilcServerConfigRouter *conn = NULL;
1096 SILC_LOG_DEBUG(("Start"));
1098 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1099 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1100 /* Error occured during protocol */
1101 silc_protocol_free(protocol);
1102 sock->protocol = NULL;
1103 silc_ske_free_key_material(ctx->keymat);
1105 silc_packet_context_free(ctx->packet);
1107 silc_ske_free(ctx->ske);
1108 silc_free(ctx->dest_id);
1110 silc_server_disconnect_remote(server, sock,
1111 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1113 /* Try reconnecting if configuration wants it */
1114 if (!sconn->no_reconnect) {
1115 silc_schedule_task_add(server->schedule, 0,
1116 silc_server_connect_to_router_retry,
1117 sconn, 0, 1, SILC_TASK_TIMEOUT,
1118 SILC_TASK_PRI_NORMAL);
1122 /* Call completion to indicate error */
1123 if (sconn->callback)
1124 (*sconn->callback)(server, NULL, sconn->callback_context);
1126 silc_server_config_unref(&sconn->conn);
1127 silc_free(sconn->remote_host);
1128 silc_free(sconn->backup_replace_ip);
1133 /* We now have the key material as the result of the key exchange
1134 protocol. Take the key material into use. Free the raw key material
1135 as soon as we've set them into use. */
1136 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1137 ctx->sock, ctx->keymat,
1138 ctx->ske->prop->cipher,
1139 ctx->ske->prop->pkcs,
1140 ctx->ske->prop->hash,
1141 ctx->ske->prop->hmac,
1142 ctx->ske->prop->group,
1144 silc_protocol_free(protocol);
1145 sock->protocol = NULL;
1146 silc_ske_free_key_material(ctx->keymat);
1148 silc_packet_context_free(ctx->packet);
1150 silc_ske_free(ctx->ske);
1151 silc_free(ctx->dest_id);
1153 silc_server_disconnect_remote(server, sock,
1154 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1156 /* Try reconnecting if configuration wants it */
1157 if (!sconn->no_reconnect) {
1158 silc_schedule_task_add(server->schedule, 0,
1159 silc_server_connect_to_router_retry,
1160 sconn, 0, 1, SILC_TASK_TIMEOUT,
1161 SILC_TASK_PRI_NORMAL);
1165 /* Call completion to indicate error */
1166 if (sconn->callback)
1167 (*sconn->callback)(server, NULL, sconn->callback_context);
1169 silc_server_config_unref(&sconn->conn);
1170 silc_free(sconn->remote_host);
1171 silc_free(sconn->backup_replace_ip);
1175 silc_ske_free_key_material(ctx->keymat);
1177 /* Allocate internal context for the authentication protocol. This
1178 is sent as context for the protocol. */
1179 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1180 proto_ctx->server = (void *)server;
1181 proto_ctx->context = (void *)sconn;
1182 proto_ctx->sock = sock;
1183 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1184 proto_ctx->dest_id_type = ctx->dest_id_type;
1185 proto_ctx->dest_id = ctx->dest_id;
1187 /* Resolve the authentication method used in this connection. Check if
1188 we find a match from user configured connections */
1189 if (!sconn->conn.ref_ptr)
1190 conn = silc_server_config_find_router_conn(server, sock->hostname,
1193 conn = sconn->conn.ref_ptr;
1196 /* Match found. Use the configured authentication method. Take only
1197 the passphrase, since for public key auth we automatically use
1198 our local key pair. */
1199 if (conn->passphrase) {
1200 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
1201 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1203 proto_ctx->auth_data = strdup(conn->passphrase);
1204 proto_ctx->auth_data_len = strlen(conn->passphrase);
1205 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
1207 } else if (conn->publickeys) {
1208 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1210 proto_ctx->auth_meth = SILC_AUTH_NONE;
1213 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
1214 sock->hostname, sock->ip, sock->port));
1215 silc_protocol_free(protocol);
1216 sock->protocol = NULL;
1218 silc_packet_context_free(ctx->packet);
1220 silc_ske_free(ctx->ske);
1221 silc_free(ctx->dest_id);
1223 silc_server_config_unref(&sconn->conn);
1224 silc_free(sconn->remote_host);
1225 silc_free(sconn->backup_replace_ip);
1227 silc_server_disconnect_remote(server, sock,
1228 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1232 /* Free old protocol as it is finished now */
1233 silc_protocol_free(protocol);
1235 silc_packet_context_free(ctx->packet);
1237 sock->protocol = NULL;
1239 /* Allocate the authentication protocol. This is allocated here
1240 but we won't start it yet. We will be receiving party of this
1241 protocol thus we will wait that connecting party will make
1242 their first move. */
1243 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1244 &sock->protocol, proto_ctx,
1245 silc_server_connect_to_router_final);
1247 /* Register timeout task. If the protocol is not executed inside
1248 this timelimit the connection will be terminated. */
1249 proto_ctx->timeout_task =
1250 silc_schedule_task_add(server->schedule, sock->sock,
1251 silc_server_timeout_remote,
1253 server->config->conn_auth_timeout, 0,
1257 /* Run the protocol */
1258 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1261 /* Finalizes the connection to router. Registers a server task to the
1262 queue so that we can accept new connections. */
1264 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
1266 SilcProtocol protocol = (SilcProtocol)context;
1267 SilcServerConnAuthInternalContext *ctx =
1268 (SilcServerConnAuthInternalContext *)protocol->context;
1269 SilcServer server = (SilcServer)ctx->server;
1270 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1271 SilcSocketConnection sock = ctx->sock;
1272 SilcServerEntry id_entry = NULL;
1274 unsigned char *id_string;
1276 SilcIDListData idata;
1277 SilcServerConfigRouter *conn = NULL;
1278 SilcServerConfigConnParams *param = NULL;
1280 SILC_LOG_DEBUG(("Start"));
1282 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1283 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1284 /* Error occured during protocol */
1285 silc_free(ctx->dest_id);
1286 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1289 /* Try reconnecting if configuration wants it */
1290 if (!sconn->no_reconnect) {
1291 silc_schedule_task_add(server->schedule, 0,
1292 silc_server_connect_to_router_retry,
1293 sconn, 0, 1, SILC_TASK_TIMEOUT,
1294 SILC_TASK_PRI_NORMAL);
1301 /* Add a task to the queue. This task receives new connections to the
1302 server. This task remains on the queue until the end of the program. */
1303 if (!server->listenning && !sconn->backup) {
1304 silc_schedule_task_add(server->schedule, server->sock,
1305 silc_server_accept_new_connection,
1306 (void *)server, 0, 0,
1308 SILC_TASK_PRI_NORMAL);
1309 server->listenning = TRUE;
1312 /* Send NEW_SERVER packet to the router. We will become registered
1313 to the SILC network after sending this packet. */
1314 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
1315 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1316 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
1317 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1318 silc_buffer_format(packet,
1319 SILC_STR_UI_SHORT(id_len),
1320 SILC_STR_UI_XNSTRING(id_string, id_len),
1321 SILC_STR_UI_SHORT(strlen(server->server_name)),
1322 SILC_STR_UI_XNSTRING(server->server_name,
1323 strlen(server->server_name)),
1326 /* Send the packet */
1327 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
1328 packet->data, packet->len, TRUE);
1329 silc_buffer_free(packet);
1330 silc_free(id_string);
1332 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
1334 /* Check that we do not have this ID already */
1335 id_entry = silc_idlist_find_server_by_id(server->local_list,
1336 ctx->dest_id, TRUE, NULL);
1338 silc_idcache_del_by_context(server->local_list->servers, id_entry);
1340 id_entry = silc_idlist_find_server_by_id(server->global_list,
1341 ctx->dest_id, TRUE, NULL);
1343 silc_idcache_del_by_context(server->global_list->servers, id_entry);
1346 SILC_LOG_DEBUG(("New server id(%s)",
1347 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1349 /* Add the connected router to global server list. Router is sent
1350 as NULL since it's local to us. */
1351 id_entry = silc_idlist_add_server(server->global_list,
1352 strdup(sock->hostname),
1353 SILC_ROUTER, ctx->dest_id, NULL, sock);
1355 silc_free(ctx->dest_id);
1356 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1357 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1362 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1363 silc_free(sock->user_data);
1364 sock->user_data = (void *)id_entry;
1365 sock->type = SILC_SOCKET_TYPE_ROUTER;
1366 idata = (SilcIDListData)sock->user_data;
1367 idata->status |= (SILC_IDLIST_STATUS_REGISTERED |
1368 SILC_IDLIST_STATUS_LOCAL);
1370 conn = sconn->conn.ref_ptr;
1371 param = &server->config->param;
1372 if (conn && conn->param)
1373 param = conn->param;
1375 /* Perform keepalive. */
1376 silc_socket_set_heartbeat(sock, param->keepalive_secs, server,
1377 silc_server_perform_heartbeat,
1380 /* Register re-key timeout */
1381 idata->rekey->timeout = param->key_exchange_rekey;
1382 silc_schedule_task_add(server->schedule, sock->sock,
1383 silc_server_rekey_callback,
1384 (void *)sock, idata->rekey->timeout, 0,
1385 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1387 if (!sconn->backup) {
1388 /* Mark this router our primary router if we're still standalone */
1389 if (server->standalone) {
1390 SILC_LOG_DEBUG(("This connection is our primary router"));
1391 server->id_entry->router = id_entry;
1392 server->router = id_entry;
1393 server->standalone = FALSE;
1395 /* If we are router then announce our possible servers. Backup
1396 router announces also global servers. */
1397 if (server->server_type == SILC_ROUTER)
1398 silc_server_announce_servers(server,
1399 server->backup_router ? TRUE : FALSE,
1400 0, SILC_PRIMARY_ROUTE(server));
1402 /* Announce our clients and channels to the router */
1403 silc_server_announce_clients(server, 0, SILC_PRIMARY_ROUTE(server));
1404 silc_server_announce_channels(server, 0, SILC_PRIMARY_ROUTE(server));
1406 /* If we are backup router then this primary router is whom we are
1408 if (server->server_type == SILC_BACKUP_ROUTER)
1409 silc_server_backup_add(server, server->id_entry, sock->ip,
1410 sconn->remote_port, TRUE);
1413 /* Add this server to be our backup router */
1414 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1415 sconn->backup_replace_port, FALSE);
1418 sock->protocol = NULL;
1421 /* Call the completion callback to indicate that we've connected to
1423 if (sconn && sconn->callback)
1424 (*sconn->callback)(server, id_entry, sconn->callback_context);
1426 /* Free the temporary connection data context */
1428 silc_server_config_unref(&sconn->conn);
1429 silc_free(sconn->remote_host);
1430 silc_free(sconn->backup_replace_ip);
1433 if (sconn == server->router_conn)
1434 server->router_conn = NULL;
1437 /* Free the protocol object */
1438 if (sock->protocol == protocol)
1439 sock->protocol = NULL;
1440 silc_protocol_free(protocol);
1442 silc_packet_context_free(ctx->packet);
1444 silc_ske_free(ctx->ske);
1445 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1446 silc_free(ctx->auth_data);
1450 /* Host lookup callback that is called after the incoming connection's
1451 IP and FQDN lookup is performed. This will actually check the acceptance
1452 of the incoming connection and will register the key exchange protocol
1453 for this connection. */
1456 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1459 SilcServerKEInternalContext *proto_ctx =
1460 (SilcServerKEInternalContext *)context;
1461 SilcServer server = (SilcServer)proto_ctx->server;
1462 SilcServerConfigClient *cconfig = NULL;
1463 SilcServerConfigServer *sconfig = NULL;
1464 SilcServerConfigRouter *rconfig = NULL;
1465 SilcServerConfigDeny *deny;
1468 /* Check whether we could resolve both IP and FQDN. */
1469 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1470 server->config->require_reverse_lookup)) {
1471 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1472 sock->hostname ? sock->hostname :
1473 sock->ip ? sock->ip : ""));
1474 server->stat.conn_failures++;
1475 silc_server_disconnect_remote(server, sock,
1476 SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
1477 "Unknown host or IP");
1478 silc_free(proto_ctx);
1482 /* Register the connection for network input and output. This sets
1483 that scheduler will listen for incoming packets for this connection
1484 and sets that outgoing packets may be sent to this connection as well.
1485 However, this doesn't set the scheduler for outgoing traffic, it
1486 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1487 later when outgoing data is available. */
1488 context = (void *)server;
1489 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1491 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1494 /* Listenning port */
1495 if (!server->sockets[(SilcUInt32)proto_ctx->context]) {
1496 silc_server_disconnect_remote(server, sock,
1497 SILC_STATUS_ERR_RESOURCE_LIMIT,
1498 "Connection refused");
1499 server->stat.conn_failures++;
1500 silc_free(proto_ctx);
1503 port = server->sockets[(SilcUInt32)proto_ctx->context]->port;
1505 /* Check whether this connection is denied to connect to us. */
1506 deny = silc_server_config_find_denied(server, sock->ip);
1508 deny = silc_server_config_find_denied(server, sock->hostname);
1510 /* The connection is denied */
1511 SILC_LOG_INFO(("Connection %s (%s) is denied",
1512 sock->hostname, sock->ip));
1513 silc_server_disconnect_remote(server, sock,
1514 SILC_STATUS_ERR_BANNED_FROM_SERVER,
1516 server->stat.conn_failures++;
1517 silc_free(proto_ctx);
1521 /* Check whether we have configured this sort of connection at all. We
1522 have to check all configurations since we don't know what type of
1523 connection this is. */
1524 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1525 cconfig = silc_server_config_find_client(server, sock->hostname);
1526 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1527 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1528 if (server->server_type == SILC_ROUTER) {
1529 if (!(rconfig = silc_server_config_find_router_conn(server,
1530 sock->ip, sock->port)))
1531 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1534 if (!cconfig && !sconfig && !rconfig) {
1535 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1537 silc_server_disconnect_remote(server, sock,
1538 SILC_STATUS_ERR_BANNED_FROM_SERVER, NULL);
1539 server->stat.conn_failures++;
1540 silc_free(proto_ctx);
1544 /* The connection is allowed */
1546 /* Set internal context for key exchange protocol. This is
1547 sent as context for the protocol. */
1548 proto_ctx->sock = sock;
1549 proto_ctx->rng = server->rng;
1550 proto_ctx->responder = TRUE;
1551 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1552 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1553 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1555 /* Take flags for key exchange. Since we do not know what type of connection
1556 this is, we go through all found configurations and use the global ones
1557 as well. This will result always into strictest key exchange flags. */
1558 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1559 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1560 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1561 if (server->config->param.key_exchange_pfs)
1562 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1564 /* Prepare the connection for key exchange protocol. We allocate the
1565 protocol but will not start it yet. The connector will be the
1566 initiator of the protocol thus we will wait for initiation from
1567 there before we start the protocol. */
1568 server->stat.auth_attempts++;
1569 SILC_LOG_DEBUG(("Starting key exchange protocol"));
1570 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1571 &sock->protocol, proto_ctx,
1572 silc_server_accept_new_connection_second);
1574 /* Register a timeout task that will be executed if the connector
1575 will not start the key exchange protocol within specified timeout
1576 and the connection will be closed. */
1577 proto_ctx->timeout_task =
1578 silc_schedule_task_add(server->schedule, sock->sock,
1579 silc_server_timeout_remote,
1581 server->config->key_exchange_timeout, 0,
1586 /* Accepts new connections to the server. Accepting new connections are
1587 done in three parts to make it async. */
1589 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1591 SilcServer server = (SilcServer)context;
1592 SilcSocketConnection newsocket;
1593 SilcServerKEInternalContext *proto_ctx;
1596 SILC_LOG_DEBUG(("Accepting new connection"));
1598 server->stat.conn_attempts++;
1600 sock = silc_net_accept_connection(fd);
1602 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1603 server->stat.conn_failures++;
1607 /* Check for maximum allowed connections */
1608 if (sock > server->config->param.connections_max) {
1609 SILC_LOG_ERROR(("Refusing connection, server is full"));
1610 server->stat.conn_failures++;
1611 silc_net_close_connection(sock);
1615 /* Set socket options */
1616 silc_net_set_socket_nonblock(sock);
1617 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1619 /* We don't create a ID yet, since we don't know what type of connection
1620 this is yet. But, we do add the connection to the socket table. */
1621 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1622 server->sockets[sock] = newsocket;
1624 /* Perform asynchronous host lookup. This will lookup the IP and the
1625 FQDN of the remote connection. After the lookup is done the connection
1626 is accepted further. */
1627 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1628 proto_ctx->server = server;
1629 proto_ctx->context = (void *)fd;
1630 silc_socket_host_lookup(newsocket, TRUE,
1631 silc_server_accept_new_connection_lookup,
1632 (void *)proto_ctx, server->schedule);
1635 /* Second part of accepting new connection. Key exchange protocol has been
1636 performed and now it is time to do little connection authentication
1637 protocol to figure out whether this connection is client or server
1638 and whether it has right to access this server (especially server
1639 connections needs to be authenticated). */
1641 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1643 SilcProtocol protocol = (SilcProtocol)context;
1644 SilcServerKEInternalContext *ctx =
1645 (SilcServerKEInternalContext *)protocol->context;
1646 SilcServer server = (SilcServer)ctx->server;
1647 SilcSocketConnection sock = ctx->sock;
1648 SilcServerConnAuthInternalContext *proto_ctx;
1650 SILC_LOG_DEBUG(("Start"));
1652 if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1653 (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1654 /* Error occured during protocol */
1655 SILC_LOG_DEBUG(("Error key exchange protocol"));
1656 silc_protocol_free(protocol);
1657 sock->protocol = NULL;
1658 silc_ske_free_key_material(ctx->keymat);
1660 silc_packet_context_free(ctx->packet);
1662 silc_ske_free(ctx->ske);
1663 silc_free(ctx->dest_id);
1664 silc_server_config_unref(&ctx->cconfig);
1665 silc_server_config_unref(&ctx->sconfig);
1666 silc_server_config_unref(&ctx->rconfig);
1668 silc_server_disconnect_remote(server, sock,
1669 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
1671 server->stat.auth_failures++;
1675 /* We now have the key material as the result of the key exchange
1676 protocol. Take the key material into use. Free the raw key material
1677 as soon as we've set them into use. */
1678 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1679 ctx->sock, ctx->keymat,
1680 ctx->ske->prop->cipher,
1681 ctx->ske->prop->pkcs,
1682 ctx->ske->prop->hash,
1683 ctx->ske->prop->hmac,
1684 ctx->ske->prop->group,
1686 SILC_LOG_ERROR(("Error setting key material in use"));
1687 silc_protocol_free(protocol);
1688 sock->protocol = NULL;
1689 silc_ske_free_key_material(ctx->keymat);
1691 silc_packet_context_free(ctx->packet);
1693 silc_ske_free(ctx->ske);
1694 silc_free(ctx->dest_id);
1695 silc_server_config_unref(&ctx->cconfig);
1696 silc_server_config_unref(&ctx->sconfig);
1697 silc_server_config_unref(&ctx->rconfig);
1699 silc_server_disconnect_remote(server, sock,
1700 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1701 server->stat.auth_failures++;
1704 silc_ske_free_key_material(ctx->keymat);
1706 /* Allocate internal context for the authentication protocol. This
1707 is sent as context for the protocol. */
1708 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1709 proto_ctx->server = (void *)server;
1710 proto_ctx->sock = sock;
1711 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1712 proto_ctx->responder = TRUE;
1713 proto_ctx->dest_id_type = ctx->dest_id_type;
1714 proto_ctx->dest_id = ctx->dest_id;
1715 proto_ctx->cconfig = ctx->cconfig;
1716 proto_ctx->sconfig = ctx->sconfig;
1717 proto_ctx->rconfig = ctx->rconfig;
1719 /* Free old protocol as it is finished now */
1720 silc_protocol_free(protocol);
1722 silc_packet_context_free(ctx->packet);
1724 sock->protocol = NULL;
1726 /* Allocate the authentication protocol. This is allocated here
1727 but we won't start it yet. We will be receiving party of this
1728 protocol thus we will wait that connecting party will make
1729 their first move. */
1730 SILC_LOG_DEBUG(("Starting connection authentication protocol"));
1731 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1732 &sock->protocol, proto_ctx,
1733 silc_server_accept_new_connection_final);
1735 /* Register timeout task. If the protocol is not executed inside
1736 this timelimit the connection will be terminated. */
1737 proto_ctx->timeout_task =
1738 silc_schedule_task_add(server->schedule, sock->sock,
1739 silc_server_timeout_remote,
1741 server->config->conn_auth_timeout, 0,
1746 /* After this is called, server don't wait for backup router anymore.
1747 This gets called automatically even after we have backup router
1748 connection established. */
1750 SILC_TASK_CALLBACK(silc_server_backup_router_wait)
1752 SilcServer server = context;
1753 server->wait_backup = FALSE;
1756 /* Final part of accepting new connection. The connection has now
1757 been authenticated and keys has been exchanged. We also know whether
1758 this is client or server connection. */
1760 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1762 SilcProtocol protocol = (SilcProtocol)context;
1763 SilcServerConnAuthInternalContext *ctx =
1764 (SilcServerConnAuthInternalContext *)protocol->context;
1765 SilcServer server = (SilcServer)ctx->server;
1766 SilcSocketConnection sock = ctx->sock;
1767 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1769 SilcServerConfigConnParams *param = &server->config->param;
1771 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1772 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1773 /* Error occured during protocol */
1774 SILC_LOG_DEBUG(("Error during authentication protocol"));
1775 silc_protocol_free(protocol);
1776 sock->protocol = NULL;
1778 silc_packet_context_free(ctx->packet);
1780 silc_ske_free(ctx->ske);
1781 silc_free(ctx->dest_id);
1782 silc_server_config_unref(&ctx->cconfig);
1783 silc_server_config_unref(&ctx->sconfig);
1784 silc_server_config_unref(&ctx->rconfig);
1786 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1788 server->stat.auth_failures++;
1792 entry->data.last_receive = time(NULL);
1794 switch (ctx->conn_type) {
1795 case SILC_SOCKET_TYPE_CLIENT:
1797 SilcClientEntry client;
1798 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1800 /* Verify whether this connection is after all allowed to connect */
1801 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1802 &server->config->param,
1803 conn->param, ctx->ske)) {
1804 server->stat.auth_failures++;
1808 /* If we are primary router and we have backup router configured
1809 but it has not connected to use yet, do not accept any other
1811 if (server->wait_backup && server->server_type == SILC_ROUTER &&
1812 !server->backup_router) {
1813 SilcServerConfigRouter *router;
1814 router = silc_server_config_get_backup_router(server);
1815 if (router && strcmp(server->config->server_info->primary->server_ip,
1817 silc_server_find_socket_by_host(server,
1818 SILC_SOCKET_TYPE_SERVER,
1819 router->backup_replace_ip, 0)) {
1820 SILC_LOG_INFO(("Will not accept connections because we do "
1821 "not have backup router connection established"));
1822 silc_server_disconnect_remote(server, sock,
1823 SILC_STATUS_ERR_PERM_DENIED,
1824 "We do not have connection to backup "
1825 "router established, try later");
1826 silc_free(sock->user_data);
1827 server->stat.auth_failures++;
1829 /* From here on, wait 10 seconds for the backup router to appear. */
1830 silc_schedule_task_add(server->schedule, 0,
1831 silc_server_backup_router_wait,
1832 (void *)server, 10, 0,
1833 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1838 SILC_LOG_DEBUG(("Remote host is client"));
1839 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1842 /* Add the client to the client ID cache. The nickname and Client ID
1843 and other information is created after we have received NEW_CLIENT
1844 packet from client. */
1845 client = silc_idlist_add_client(server->local_list,
1846 NULL, NULL, NULL, NULL, NULL, sock, 0);
1848 SILC_LOG_ERROR(("Could not add new client to cache"));
1849 silc_free(sock->user_data);
1850 silc_server_disconnect_remote(server, sock,
1851 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1852 server->stat.auth_failures++;
1855 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
1858 server->stat.my_clients++;
1859 server->stat.clients++;
1860 server->stat.cell_clients++;
1862 /* Get connection parameters */
1864 param = conn->param;
1866 if (!param->keepalive_secs)
1867 param->keepalive_secs = server->config->param.keepalive_secs;
1869 if (!param->qos && server->config->param.qos) {
1870 param->qos = server->config->param.qos;
1871 param->qos_rate_limit = server->config->param.qos_rate_limit;
1872 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
1873 param->qos_limit_sec = server->config->param.qos_limit_sec;
1874 param->qos_limit_usec = server->config->param.qos_limit_usec;
1877 /* Check if to be anonymous connection */
1878 if (param->anonymous)
1879 client->mode |= SILC_UMODE_ANONYMOUS;
1882 id_entry = (void *)client;
1885 case SILC_SOCKET_TYPE_SERVER:
1886 case SILC_SOCKET_TYPE_ROUTER:
1888 SilcServerEntry new_server;
1889 bool initiator = FALSE;
1890 bool backup_local = FALSE;
1891 bool backup_router = FALSE;
1892 char *backup_replace_ip = NULL;
1893 SilcUInt16 backup_replace_port = 0;
1894 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1895 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1897 /* If we are backup router and this is incoming server connection
1898 and we do not have connection to primary router, do not allow
1900 if (server->server_type == SILC_BACKUP_ROUTER &&
1901 ctx->conn_type == SILC_SOCKET_TYPE_SERVER &&
1902 !SILC_PRIMARY_ROUTE(server)) {
1903 SILC_LOG_INFO(("Will not accept server connection because we do "
1904 "not have primary router connection established"));
1905 silc_server_disconnect_remote(server, sock,
1906 SILC_STATUS_ERR_PERM_DENIED,
1907 "We do not have connection to primary "
1908 "router established, try later");
1909 silc_free(sock->user_data);
1910 server->stat.auth_failures++;
1914 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1915 /* Verify whether this connection is after all allowed to connect */
1916 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1917 &server->config->param,
1918 rconn ? rconn->param : NULL,
1920 silc_free(sock->user_data);
1921 server->stat.auth_failures++;
1927 param = rconn->param;
1929 if (!param->keepalive_secs)
1930 param->keepalive_secs = server->config->param.keepalive_secs;
1932 if (!param->qos && server->config->param.qos) {
1933 param->qos = server->config->param.qos;
1934 param->qos_rate_limit = server->config->param.qos_rate_limit;
1935 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
1936 param->qos_limit_sec = server->config->param.qos_limit_sec;
1937 param->qos_limit_usec = server->config->param.qos_limit_usec;
1941 initiator = rconn->initiator;
1942 backup_local = rconn->backup_local;
1943 backup_router = rconn->backup_router;
1944 backup_replace_ip = rconn->backup_replace_ip;
1945 backup_replace_port = rconn->backup_replace_port;
1949 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1950 /* Verify whether this connection is after all allowed to connect */
1951 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1952 &server->config->param,
1953 sconn ? sconn->param : NULL,
1955 silc_free(sock->user_data);
1956 server->stat.auth_failures++;
1961 param = sconn->param;
1963 if (!param->keepalive_secs)
1964 param->keepalive_secs = server->config->param.keepalive_secs;
1966 if (!param->qos && server->config->param.qos) {
1967 param->qos = server->config->param.qos;
1968 param->qos_rate_limit = server->config->param.qos_rate_limit;
1969 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
1970 param->qos_limit_sec = server->config->param.qos_limit_sec;
1971 param->qos_limit_usec = server->config->param.qos_limit_usec;
1975 backup_router = sconn->backup_router;
1979 /* If we are primary router and we have backup router configured
1980 but it has not connected to use yet, do not accept any other
1982 if (server->wait_backup && server->server_type == SILC_ROUTER &&
1983 !server->backup_router && !backup_router) {
1984 SilcServerConfigRouter *router;
1985 router = silc_server_config_get_backup_router(server);
1986 if (router && strcmp(server->config->server_info->primary->server_ip,
1988 silc_server_find_socket_by_host(server,
1989 SILC_SOCKET_TYPE_SERVER,
1990 router->backup_replace_ip, 0)) {
1991 SILC_LOG_INFO(("Will not accept connections because we do "
1992 "not have backup router connection established"));
1993 silc_server_disconnect_remote(server, sock,
1994 SILC_STATUS_ERR_PERM_DENIED,
1995 "We do not have connection to backup "
1996 "router established, try later");
1997 silc_free(sock->user_data);
1998 server->stat.auth_failures++;
2000 /* From here on, wait 10 seconds for the backup router to appear. */
2001 silc_schedule_task_add(server->schedule, 0,
2002 silc_server_backup_router_wait,
2003 (void *)server, 10, 0,
2004 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2009 SILC_LOG_DEBUG(("Remote host is %s",
2010 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2011 "server" : (backup_router ?
2012 "backup router" : "router")));
2013 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
2014 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2015 "server" : (backup_router ?
2016 "backup router" : "router")));
2018 /* Add the server into server cache. The server name and Server ID
2019 is updated after we have received NEW_SERVER packet from the
2020 server. We mark ourselves as router for this server if we really
2023 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2024 server->local_list : (backup_router ?
2025 server->local_list :
2026 server->global_list)),
2028 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2029 SILC_SERVER : SILC_ROUTER),
2031 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2032 server->id_entry : (backup_router ?
2033 server->id_entry : NULL)),
2036 SILC_LOG_ERROR(("Could not add new server to cache"));
2037 silc_free(sock->user_data);
2038 silc_server_disconnect_remote(server, sock,
2039 SILC_STATUS_ERR_AUTH_FAILED, NULL);
2040 server->stat.auth_failures++;
2043 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
2045 id_entry = (void *)new_server;
2047 /* If the incoming connection is router and marked as backup router
2048 then add it to be one of our backups */
2049 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
2050 /* Change it back to SERVER type since that's what it really is. */
2052 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
2053 new_server->server_type = SILC_BACKUP_ROUTER;
2055 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
2056 ("Backup router %s is now online",
2059 /* Remove the backup waiting with timeout */
2060 silc_schedule_task_add(server->schedule, 0,
2061 silc_server_backup_router_wait,
2062 (void *)server, 5, 0,
2063 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2067 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
2068 server->stat.my_servers++;
2070 server->stat.my_routers++;
2071 server->stat.routers++;
2073 server->stat.servers++;
2075 /* Check whether this connection is to be our primary router connection
2076 if we do not already have the primary route. */
2077 if (!backup_router &&
2078 server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
2079 if (silc_server_config_is_primary_route(server) && !initiator)
2082 SILC_LOG_DEBUG(("We are not standalone server anymore"));
2083 server->standalone = FALSE;
2084 if (!server->id_entry->router) {
2085 server->id_entry->router = id_entry;
2086 server->router = id_entry;
2097 sock->type = ctx->conn_type;
2099 /* Add the common data structure to the ID entry. */
2100 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
2102 /* Add to sockets internal pointer for fast referencing */
2103 silc_free(sock->user_data);
2104 sock->user_data = id_entry;
2106 /* Connection has been fully established now. Everything is ok. */
2107 SILC_LOG_DEBUG(("New connection authenticated"));
2109 /* Perform keepalive. */
2110 if (param->keepalive_secs)
2111 silc_socket_set_heartbeat(sock, param->keepalive_secs, server,
2112 silc_server_perform_heartbeat,
2115 /* Perform Quality of Service */
2117 silc_socket_set_qos(sock, param->qos_rate_limit, param->qos_bytes_limit,
2118 param->qos_limit_sec, param->qos_limit_usec,
2122 silc_protocol_free(protocol);
2124 silc_packet_context_free(ctx->packet);
2126 silc_ske_free(ctx->ske);
2127 silc_free(ctx->dest_id);
2128 silc_server_config_unref(&ctx->cconfig);
2129 silc_server_config_unref(&ctx->sconfig);
2130 silc_server_config_unref(&ctx->rconfig);
2132 sock->protocol = NULL;
2135 /* This function is used to read packets from network and send packets to
2136 network. This is usually a generic task. */
2138 SILC_TASK_CALLBACK(silc_server_packet_process)
2140 SilcServer server = (SilcServer)context;
2141 SilcSocketConnection sock = server->sockets[fd];
2142 SilcIDListData idata;
2143 SilcCipher cipher = NULL;
2144 SilcHmac hmac = NULL;
2145 SilcUInt32 sequence = 0;
2146 bool local_is_router;
2150 SILC_LOG_DEBUG(("Unknown socket connection"));
2154 /* Packet sending */
2156 if (type == SILC_TASK_WRITE) {
2157 /* Do not send data to disconnected connection */
2158 if (SILC_IS_DISCONNECTED(sock)) {
2159 SILC_LOG_DEBUG(("Disconnected socket connection, cannot send"));
2163 server->stat.packets_sent++;
2165 /* Send the packet */
2166 ret = silc_packet_send(sock, TRUE);
2168 /* If returned -2 could not write to connection now, will do
2173 /* The packet has been sent and now it is time to set the connection
2174 back to only for input. When there is again some outgoing data
2175 available for this connection it will be set for output as well.
2176 This call clears the output setting and sets it only for input. */
2177 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
2178 SILC_UNSET_OUTBUF_PENDING(sock);
2179 silc_buffer_clear(sock->outbuf);
2182 SILC_LOG_ERROR(("Error sending packet to connection "
2183 "%s:%d [%s]", sock->hostname, sock->port,
2184 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2185 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2186 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2189 SILC_SET_DISCONNECTING(sock);
2190 if (sock->user_data)
2191 silc_server_free_sock_user_data(server, sock, NULL);
2192 silc_server_close_connection(server, sock);
2197 /* Packet receiving */
2199 /* Read some data from connection */
2200 ret = silc_packet_receive(sock);
2204 SILC_LOG_ERROR(("Error receiving packet from connection "
2205 "%s:%d [%s] %s", sock->hostname, sock->port,
2206 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2207 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2208 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2209 "Router"), strerror(errno)));
2211 SILC_SET_DISCONNECTING(sock);
2212 if (sock->user_data)
2213 silc_server_free_sock_user_data(server, sock, NULL);
2214 silc_server_close_connection(server, sock);
2221 SILC_LOG_DEBUG(("Read EOF"));
2223 /* If connection is disconnecting already we will finally
2224 close the connection */
2225 if (SILC_IS_DISCONNECTING(sock)) {
2226 if (sock->user_data)
2227 silc_server_free_sock_user_data(server, sock, NULL);
2228 silc_server_close_connection(server, sock);
2232 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
2233 SILC_SET_DISCONNECTING(sock);
2235 if (sock->user_data) {
2237 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
2238 silc_server_free_sock_user_data(server, sock, tmp);
2240 silc_server_free_sock_user_data(server, sock, NULL);
2241 } else if (server->router_conn && server->router_conn->sock == sock &&
2242 !server->router && server->standalone)
2243 silc_schedule_task_add(server->schedule, 0,
2244 silc_server_connect_to_router,
2247 SILC_TASK_PRI_NORMAL);
2249 silc_server_close_connection(server, sock);
2253 /* If connection is disconnecting or disconnected we will ignore
2255 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2256 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
2260 /* Get keys and stuff from ID entry */
2261 idata = (SilcIDListData)sock->user_data;
2263 cipher = idata->receive_key;
2264 hmac = idata->hmac_receive;
2265 sequence = idata->psn_receive;
2268 /* Then, process the packet. This will call the parser that will then
2269 decrypt and parse the packet. */
2271 local_is_router = (server->server_type == SILC_ROUTER);
2273 /* If socket connection is our primary, we are backup and we are doing
2274 backup resuming, we won't process the packet as being a router
2275 (affects channel message decryption). */
2276 if (server->backup_router && SILC_SERVER_IS_BACKUP(sock) &&
2277 SILC_PRIMARY_ROUTE(server) == sock)
2278 local_is_router = FALSE;
2280 ret = silc_packet_receive_process(sock, local_is_router,
2281 cipher, hmac, sequence,
2282 silc_server_packet_parse, server);
2284 /* If processing failed the connection is closed. */
2286 /* On packet processing errors we may close our primary router
2287 connection but won't become primary router if we are the backup
2288 since this is local error condition. */
2289 if (SILC_PRIMARY_ROUTE(server) == sock && server->backup_router)
2290 server->backup_noswitch = TRUE;
2292 if (sock->user_data)
2293 silc_server_free_sock_user_data(server, sock, NULL);
2294 silc_server_close_connection(server, sock);
2298 /* Parses whole packet, received earlier. */
2300 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
2302 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
2303 SilcServer server = (SilcServer)parse_ctx->context;
2304 SilcSocketConnection sock = parse_ctx->sock;
2305 SilcPacketContext *packet = parse_ctx->packet;
2306 SilcIDListData idata = (SilcIDListData)sock->user_data;
2309 server->stat.packets_received++;
2311 /* Parse the packet */
2312 if (parse_ctx->normal)
2313 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
2315 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
2317 /* If entry is disabled ignore what we got. */
2318 if (idata && idata->status & SILC_IDLIST_STATUS_DISABLED &&
2319 ret != SILC_PACKET_HEARTBEAT && ret != SILC_PACKET_RESUME_ROUTER &&
2320 ret != SILC_PACKET_REKEY && ret != SILC_PACKET_REKEY_DONE) {
2321 SILC_LOG_DEBUG(("Connection is disabled"));
2325 if (ret == SILC_PACKET_NONE) {
2326 SILC_LOG_DEBUG(("Error parsing packet"));
2330 /* Check that the the current client ID is same as in the client's packet. */
2331 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
2332 SilcClientEntry client = (SilcClientEntry)sock->user_data;
2333 if (client && client->id && packet->src_id) {
2334 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
2335 packet->src_id_type);
2336 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
2338 SILC_LOG_DEBUG(("Packet source is not same as sender"));
2345 if (server->server_type == SILC_ROUTER) {
2346 /* Route the packet if it is not destined to us. Other ID types but
2347 server are handled separately after processing them. */
2348 if (packet->dst_id && !(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
2349 packet->dst_id_type == SILC_ID_SERVER &&
2350 sock->type != SILC_SOCKET_TYPE_CLIENT &&
2351 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
2353 /* Route the packet to fastest route for the destination ID */
2354 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
2355 packet->dst_id_type);
2358 silc_server_packet_route(server,
2359 silc_server_route_get(server, id,
2360 packet->dst_id_type),
2367 /* Parse the incoming packet type */
2368 silc_server_packet_parse_type(server, sock, packet);
2370 /* Broadcast packet if it is marked as broadcast packet and it is
2371 originated from router and we are router. */
2372 if (server->server_type == SILC_ROUTER &&
2373 sock->type == SILC_SOCKET_TYPE_ROUTER &&
2374 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
2375 /* Broadcast to our primary route */
2376 silc_server_packet_broadcast(server, SILC_PRIMARY_ROUTE(server), packet);
2378 /* If we have backup routers then we need to feed all broadcast
2379 data to those servers. */
2380 silc_server_backup_broadcast(server, sock, packet);
2384 silc_packet_context_free(packet);
2385 silc_free(parse_ctx);
2388 /* Parser callback called by silc_packet_receive_process. This merely
2389 registers timeout that will handle the actual parsing when appropriate. */
2391 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
2394 SilcServer server = (SilcServer)context;
2395 SilcSocketConnection sock = parser_context->sock;
2396 SilcIDListData idata = (SilcIDListData)sock->user_data;
2400 idata->psn_receive = parser_context->packet->sequence + 1;
2402 /* If protocol for this connection is key exchange or rekey then we'll
2403 process all packets synchronously, since there might be packets in
2404 queue that we are not able to decrypt without first processing the
2405 packets before them. */
2406 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
2407 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
2408 (sock->protocol && sock->protocol->protocol &&
2409 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2410 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
2411 silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2414 /* Reprocess data since we'll return FALSE here. This is because
2415 the idata->receive_key might have become valid in the last packet
2416 and we want to call this processor with valid cipher. */
2418 ret = silc_packet_receive_process(
2419 sock, server->server_type == SILC_ROUTER,
2421 idata->hmac_receive, idata->psn_receive,
2422 silc_server_packet_parse, server);
2424 ret = silc_packet_receive_process(
2425 sock, server->server_type == SILC_ROUTER,
2427 silc_server_packet_parse, server);
2430 /* On packet processing errors we may close our primary router
2431 connection but won't become primary router if we are the backup
2432 since this is local error condition. */
2433 if (SILC_PRIMARY_ROUTE(server) == sock && server->backup_router)
2434 server->backup_noswitch = TRUE;
2436 if (sock->user_data)
2437 silc_server_free_sock_user_data(server, sock, NULL);
2438 silc_server_close_connection(server, sock);
2444 switch (sock->type) {
2445 case SILC_SOCKET_TYPE_UNKNOWN:
2446 case SILC_SOCKET_TYPE_CLIENT:
2447 /* Parse the packet with timeout */
2448 silc_schedule_task_add(server->schedule, sock->sock,
2449 silc_server_packet_parse_real,
2450 (void *)parser_context, 0, 100000,
2452 SILC_TASK_PRI_NORMAL);
2454 case SILC_SOCKET_TYPE_SERVER:
2455 case SILC_SOCKET_TYPE_ROUTER:
2456 /* Packets from servers are parsed immediately */
2457 silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2467 /* Parses the packet type and calls what ever routines the packet type
2468 requires. This is done for all incoming packets. */
2470 void silc_server_packet_parse_type(SilcServer server,
2471 SilcSocketConnection sock,
2472 SilcPacketContext *packet)
2474 SilcPacketType type = packet->type;
2475 SilcIDListData idata = (SilcIDListData)sock->user_data;
2477 SILC_LOG_DEBUG(("Received %s packet [flags %d]",
2478 silc_get_packet_name(type), packet->flags));
2480 /* Parse the packet type */
2482 case SILC_PACKET_DISCONNECT:
2485 char *message = NULL;
2487 if (packet->flags & SILC_PACKET_FLAG_LIST)
2489 if (packet->buffer->len < 1)
2492 status = (SilcStatus)packet->buffer->data[0];
2493 if (packet->buffer->len > 1 &&
2494 silc_utf8_valid(packet->buffer->data + 1, packet->buffer->len - 1))
2495 message = silc_memdup(packet->buffer->data + 1,
2496 packet->buffer->len - 1);
2498 SILC_LOG_INFO(("Disconnected by %s (%s): %s (%d) %s",
2499 sock->ip, sock->hostname,
2500 silc_get_status_message(status), status,
2501 message ? message : ""));
2504 /* Handle the disconnection from our end too */
2505 if (sock->user_data && SILC_IS_LOCAL(sock->user_data))
2506 silc_server_free_sock_user_data(server, sock, NULL);
2507 silc_server_close_connection(server, sock);
2511 case SILC_PACKET_SUCCESS:
2513 * Success received for something. For now we can have only
2514 * one protocol for connection executing at once hence this
2515 * success message is for whatever protocol is executing currently.
2517 if (packet->flags & SILC_PACKET_FLAG_LIST)
2520 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2523 case SILC_PACKET_FAILURE:
2525 * Failure received for something. For now we can have only
2526 * one protocol for connection executing at once hence this
2527 * failure message is for whatever protocol is executing currently.
2529 if (packet->flags & SILC_PACKET_FLAG_LIST)
2531 if (sock->protocol) {
2532 sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
2533 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2537 case SILC_PACKET_REJECT:
2538 if (packet->flags & SILC_PACKET_FLAG_LIST)
2543 case SILC_PACKET_NOTIFY:
2545 * Received notify packet. Server can receive notify packets from
2546 * router. Server then relays the notify messages to clients if needed.
2548 if (packet->flags & SILC_PACKET_FLAG_LIST)
2549 silc_server_notify_list(server, sock, packet);
2551 silc_server_notify(server, sock, packet);
2557 case SILC_PACKET_CHANNEL_MESSAGE:
2559 * Received channel message. Channel messages are special packets
2560 * (although probably most common ones) thus they are handled
2563 if (packet->flags & SILC_PACKET_FLAG_LIST)
2565 idata->last_receive = time(NULL);
2566 silc_server_channel_message(server, sock, packet);
2569 case SILC_PACKET_CHANNEL_KEY:
2571 * Received key for channel. As channels are created by the router
2572 * the keys are as well. We will distribute the key to all of our
2573 * locally connected clients on the particular channel. Router
2574 * never receives this channel and thus is ignored.
2576 if (packet->flags & SILC_PACKET_FLAG_LIST)
2578 silc_server_channel_key(server, sock, packet);
2584 case SILC_PACKET_COMMAND:
2586 * Recived command. Processes the command request and allocates the
2587 * command context and calls the command.
2589 if (packet->flags & SILC_PACKET_FLAG_LIST)
2591 silc_server_command_process(server, sock, packet);
2594 case SILC_PACKET_COMMAND_REPLY:
2596 * Received command reply packet. Received command reply to command. It
2597 * may be reply to command sent by us or reply to command sent by client
2598 * that we've routed further.
2600 if (packet->flags & SILC_PACKET_FLAG_LIST)
2602 silc_server_command_reply(server, sock, packet);
2606 * Private Message packets
2608 case SILC_PACKET_PRIVATE_MESSAGE:
2610 * Received private message packet. The packet is coming from either
2613 if (packet->flags & SILC_PACKET_FLAG_LIST)
2615 idata->last_receive = time(NULL);
2616 silc_server_private_message(server, sock, packet);
2619 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2621 * Private message key packet.
2623 if (packet->flags & SILC_PACKET_FLAG_LIST)
2625 silc_server_private_message_key(server, sock, packet);
2629 * Key Exchange protocol packets
2631 case SILC_PACKET_KEY_EXCHANGE:
2632 if (packet->flags & SILC_PACKET_FLAG_LIST)
2635 if (sock->protocol && sock->protocol->protocol &&
2636 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2637 SilcServerKEInternalContext *proto_ctx =
2638 (SilcServerKEInternalContext *)sock->protocol->context;
2640 proto_ctx->packet = silc_packet_context_dup(packet);
2642 /* Let the protocol handle the packet */
2643 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2645 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2646 "protocol active, packet dropped."));
2650 case SILC_PACKET_KEY_EXCHANGE_1:
2651 if (packet->flags & SILC_PACKET_FLAG_LIST)
2654 if (sock->protocol && sock->protocol->protocol &&
2655 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2656 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2658 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2659 SilcServerRekeyInternalContext *proto_ctx =
2660 (SilcServerRekeyInternalContext *)sock->protocol->context;
2662 if (proto_ctx->packet)
2663 silc_packet_context_free(proto_ctx->packet);
2665 proto_ctx->packet = silc_packet_context_dup(packet);
2667 /* Let the protocol handle the packet */
2668 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2670 SilcServerKEInternalContext *proto_ctx =
2671 (SilcServerKEInternalContext *)sock->protocol->context;
2673 if (proto_ctx->packet)
2674 silc_packet_context_free(proto_ctx->packet);
2676 proto_ctx->packet = silc_packet_context_dup(packet);
2677 proto_ctx->dest_id_type = packet->src_id_type;
2678 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2679 packet->src_id_type);
2680 if (!proto_ctx->dest_id)
2683 /* Let the protocol handle the packet */
2684 silc_protocol_execute(sock->protocol, server->schedule,
2688 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2689 "protocol active, packet dropped."));
2693 case SILC_PACKET_KEY_EXCHANGE_2:
2694 if (packet->flags & SILC_PACKET_FLAG_LIST)
2697 if (sock->protocol && sock->protocol->protocol &&
2698 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2699 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2701 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2702 SilcServerRekeyInternalContext *proto_ctx =
2703 (SilcServerRekeyInternalContext *)sock->protocol->context;
2705 if (proto_ctx->packet)
2706 silc_packet_context_free(proto_ctx->packet);
2708 proto_ctx->packet = silc_packet_context_dup(packet);
2710 /* Let the protocol handle the packet */
2711 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2713 SilcServerKEInternalContext *proto_ctx =
2714 (SilcServerKEInternalContext *)sock->protocol->context;
2716 if (proto_ctx->packet)
2717 silc_packet_context_free(proto_ctx->packet);
2719 proto_ctx->packet = silc_packet_context_dup(packet);
2720 proto_ctx->dest_id_type = packet->src_id_type;
2721 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2722 packet->src_id_type);
2723 if (!proto_ctx->dest_id)
2726 /* Let the protocol handle the packet */
2727 silc_protocol_execute(sock->protocol, server->schedule,
2731 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2732 "protocol active, packet dropped."));
2736 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2738 * Connection authentication request packet. When we receive this packet
2739 * we will send to the other end information about our mandatory
2740 * authentication method for the connection. This packet maybe received
2743 if (packet->flags & SILC_PACKET_FLAG_LIST)
2745 silc_server_connection_auth_request(server, sock, packet);
2749 * Connection Authentication protocol packets
2751 case SILC_PACKET_CONNECTION_AUTH:
2752 /* Start of the authentication protocol. We receive here the
2753 authentication data and will verify it. */
2754 if (packet->flags & SILC_PACKET_FLAG_LIST)
2757 if (sock->protocol && sock->protocol->protocol->type
2758 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2760 SilcServerConnAuthInternalContext *proto_ctx =
2761 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2763 proto_ctx->packet = silc_packet_context_dup(packet);
2765 /* Let the protocol handle the packet */
2766 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2768 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2769 "protocol active, packet dropped."));
2773 case SILC_PACKET_NEW_ID:
2775 * Received New ID packet. This includes some new ID that has been
2776 * created. It may be for client, server or channel. This is the way
2777 * to distribute information about new registered entities in the
2780 if (packet->flags & SILC_PACKET_FLAG_LIST)
2781 silc_server_new_id_list(server, sock, packet);
2783 silc_server_new_id(server, sock, packet);
2786 case SILC_PACKET_NEW_CLIENT:
2788 * Received new client packet. This includes client information that
2789 * we will use to create initial client ID. After creating new
2790 * ID we will send it to the client.
2792 if (packet->flags & SILC_PACKET_FLAG_LIST)
2794 silc_server_new_client(server, sock, packet);
2797 case SILC_PACKET_NEW_SERVER:
2799 * Received new server packet. This includes Server ID and some other
2800 * information that we may save. This is received after server has
2803 if (packet->flags & SILC_PACKET_FLAG_LIST)
2805 silc_server_new_server(server, sock, packet);
2808 case SILC_PACKET_NEW_CHANNEL:
2810 * Received new channel packet. Information about new channel in the
2811 * network are distributed using this packet.
2813 if (packet->flags & SILC_PACKET_FLAG_LIST)
2814 silc_server_new_channel_list(server, sock, packet);
2816 silc_server_new_channel(server, sock, packet);
2819 case SILC_PACKET_HEARTBEAT:
2821 * Received heartbeat.
2823 if (packet->flags & SILC_PACKET_FLAG_LIST)
2827 case SILC_PACKET_KEY_AGREEMENT:
2829 * Received heartbeat.
2831 if (packet->flags & SILC_PACKET_FLAG_LIST)
2833 silc_server_key_agreement(server, sock, packet);
2836 case SILC_PACKET_REKEY:
2838 * Received re-key packet. The sender wants to regenerate the session
2841 if (packet->flags & SILC_PACKET_FLAG_LIST)
2843 silc_server_rekey(server, sock, packet);
2846 case SILC_PACKET_REKEY_DONE:
2848 * The re-key is done.
2850 if (packet->flags & SILC_PACKET_FLAG_LIST)
2853 if (sock->protocol && sock->protocol->protocol &&
2854 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2856 SilcServerRekeyInternalContext *proto_ctx =
2857 (SilcServerRekeyInternalContext *)sock->protocol->context;
2859 if (proto_ctx->packet)
2860 silc_packet_context_free(proto_ctx->packet);
2862 proto_ctx->packet = silc_packet_context_dup(packet);
2864 /* Let the protocol handle the packet */
2865 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2867 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2868 "protocol active, packet dropped."));
2872 case SILC_PACKET_FTP:
2874 if (packet->flags & SILC_PACKET_FLAG_LIST)
2876 silc_server_ftp(server, sock, packet);
2879 case SILC_PACKET_RESUME_CLIENT:
2881 if (packet->flags & SILC_PACKET_FLAG_LIST)
2883 silc_server_resume_client(server, sock, packet);
2886 case SILC_PACKET_RESUME_ROUTER:
2887 /* Resume router packet received. This packet is received for backup
2888 router resuming protocol. */
2889 if (packet->flags & SILC_PACKET_FLAG_LIST)
2891 silc_server_backup_resume_router(server, sock, packet);
2895 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2900 /* Creates connection to a remote router. */
2902 void silc_server_create_connection(SilcServer server,
2903 const char *remote_host, SilcUInt32 port)
2905 SilcServerConnection sconn;
2907 /* Allocate connection object for hold connection specific stuff. */
2908 sconn = silc_calloc(1, sizeof(*sconn));
2909 sconn->remote_host = strdup(remote_host);
2910 sconn->remote_port = port;
2911 sconn->no_reconnect = TRUE;
2913 silc_schedule_task_add(server->schedule, 0,
2914 silc_server_connect_router,
2915 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2916 SILC_TASK_PRI_NORMAL);
2919 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2921 silc_socket_free(context);
2924 /* Closes connection to socket connection */
2926 void silc_server_close_connection(SilcServer server,
2927 SilcSocketConnection sock)
2931 if (!server->sockets[sock->sock] && SILC_IS_DISCONNECTED(sock)) {
2932 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2933 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2934 silc_schedule_task_add(server->schedule, sock->sock,
2935 silc_server_close_connection_final,
2936 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2937 SILC_TASK_PRI_NORMAL);
2941 memset(tmp, 0, sizeof(tmp));
2942 silc_socket_get_error(sock, tmp, sizeof(tmp));
2943 SILC_LOG_INFO(("Closing connection %s:%d [%s] %s", sock->hostname,
2945 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2946 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2947 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2948 "Router"), tmp[0] ? tmp : ""));
2950 /* Unregister all tasks */
2951 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2953 /* Close the actual connection */
2954 silc_net_close_connection(sock->sock);
2955 server->sockets[sock->sock] = NULL;
2957 /* If sock->user_data is NULL then we'll check for active protocols
2958 here since the silc_server_free_sock_user_data has not been called
2959 for this connection. */
2960 if (!sock->user_data) {
2961 /* If any protocol is active cancel its execution. It will call
2962 the final callback which will finalize the disconnection. */
2963 if (sock->protocol && sock->protocol->protocol &&
2964 sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
2965 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
2966 silc_protocol_cancel(sock->protocol, server->schedule);
2967 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2968 silc_protocol_execute_final(sock->protocol, server->schedule);
2969 sock->protocol = NULL;
2974 /* We won't listen for this connection anymore */
2975 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2977 silc_schedule_task_add(server->schedule, sock->sock,
2978 silc_server_close_connection_final,
2979 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2980 SILC_TASK_PRI_NORMAL);
2983 /* Sends disconnect message to remote connection and disconnects the
2986 void silc_server_disconnect_remote(SilcServer server,
2987 SilcSocketConnection sock,
2988 SilcStatus status, ...)
2991 unsigned char buf[512];
2996 if (!sock || SILC_IS_DISCONNECTED(sock))
2999 memset(buf, 0, sizeof(buf));
3000 va_start(ap, status);
3001 cp = va_arg(ap, char *);
3003 vsnprintf(buf, sizeof(buf) - 1, cp, ap);
3008 SILC_LOG_DEBUG(("Disconnecting remote host"));
3010 /* Notify remote end that the conversation is over. The notify message
3011 is tried to be sent immediately. */
3015 len += silc_utf8_encoded_len(buf, strlen(buf), SILC_STRING_ASCII);
3017 buffer = silc_buffer_alloc_size(len);
3021 buffer->data[0] = status;
3023 silc_utf8_encode(buf, strlen(buf), SILC_STRING_ASCII, buffer->data + 1,
3025 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
3026 buffer->data, buffer->len, TRUE);
3027 silc_buffer_free(buffer);
3030 silc_server_packet_queue_purge(server, sock);
3032 /* Mark the connection to be disconnected */
3033 SILC_SET_DISCONNECTED(sock);
3034 silc_server_close_connection(server, sock);
3037 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
3039 SilcServer server = app_context;
3040 SilcClientEntry client = context;
3042 assert(!silc_hash_table_count(client->channels));
3044 silc_idlist_del_data(client);
3045 silc_idcache_purge_by_context(server->local_list->clients, client);
3048 /* Frees client data and notifies about client's signoff. */
3050 void silc_server_free_client_data(SilcServer server,
3051 SilcSocketConnection sock,
3052 SilcClientEntry client,
3054 const char *signoff)
3056 SILC_LOG_DEBUG(("Freeing client data"));
3058 /* If there is pending outgoing data for the client then purge it
3059 to the network before removing the client entry. */
3060 silc_server_packet_queue_purge(server, sock);
3063 /* Check if anyone is watching this nickname */
3064 if (server->server_type == SILC_ROUTER)
3065 silc_server_check_watcher_list(server, client, NULL,
3066 SILC_NOTIFY_TYPE_SIGNOFF);
3068 /* Send SIGNOFF notify to routers. */
3070 silc_server_send_notify_signoff(server, SILC_PRIMARY_ROUTE(server),
3071 SILC_BROADCAST(server), client->id,
3075 /* Remove client from all channels */
3077 silc_server_remove_from_channels(server, NULL, client,
3078 TRUE, (char *)signoff, TRUE, FALSE);
3080 silc_server_remove_from_channels(server, NULL, client,
3081 FALSE, NULL, FALSE, FALSE);
3083 /* Remove this client from watcher list if it is */
3084 silc_server_del_from_watcher_list(server, client);
3086 /* Update statistics */
3087 server->stat.my_clients--;
3088 server->stat.clients--;
3089 if (server->stat.cell_clients)
3090 server->stat.cell_clients--;
3091 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
3092 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
3093 silc_schedule_task_del_by_context(server->schedule, client);
3095 /* We will not delete the client entry right away. We will take it
3096 into history (for WHOWAS command) for 5 minutes, unless we're
3097 shutting down server. */
3098 if (!server->server_shutdown) {
3099 silc_schedule_task_add(server->schedule, 0,
3100 silc_server_free_client_data_timeout,
3102 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
3103 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
3104 client->data.status &= ~SILC_IDLIST_STATUS_LOCAL;
3106 client->router = NULL;
3107 client->connection = NULL;
3109 /* Delete directly since we're shutting down server */
3110 silc_idlist_del_data(client);
3111 silc_idlist_del_client(server->local_list, client);
3115 /* Frees user_data pointer from socket connection object. This also sends
3116 appropriate notify packets to the network to inform about leaving
3119 void silc_server_free_sock_user_data(SilcServer server,
3120 SilcSocketConnection sock,
3121 const char *signoff_message)
3123 switch (sock->type) {
3124 case SILC_SOCKET_TYPE_CLIENT:
3126 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
3127 silc_server_free_client_data(server, sock, user_data, TRUE,
3131 case SILC_SOCKET_TYPE_SERVER:
3132 case SILC_SOCKET_TYPE_ROUTER:
3134 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
3135 SilcServerEntry backup_router = NULL;
3137 SILC_LOG_DEBUG(("Freeing server data"));
3140 backup_router = silc_server_backup_get(server, user_data->id);
3142 if (!server->backup_router && server->server_type == SILC_ROUTER &&
3143 backup_router == server->id_entry &&
3144 sock->type != SILC_SOCKET_TYPE_ROUTER)
3145 backup_router = NULL;
3147 if (server->server_shutdown || server->backup_noswitch)
3148 backup_router = NULL;
3150 /* If this was our primary router connection then we're lost to
3151 the outside world. */
3152 if (server->router == user_data) {
3153 /* Check whether we have a backup router connection */
3154 if (!backup_router || backup_router == user_data) {
3155 silc_schedule_task_add(server->schedule, 0,
3156 silc_server_connect_to_router,
3159 SILC_TASK_PRI_NORMAL);
3161 server->id_entry->router = NULL;
3162 server->router = NULL;
3163 server->standalone = TRUE;
3164 server->backup_primary = FALSE;
3165 backup_router = NULL;
3167 if (server->id_entry != backup_router) {
3168 SILC_LOG_INFO(("New primary router is backup router %s",
3169 backup_router->server_name));
3170 server->id_entry->router = backup_router;
3171 server->router = backup_router;
3172 server->router_connect = time(0);
3173 server->backup_primary = TRUE;
3175 SILC_LOG_INFO(("We are now new primary router in this cell"));
3176 server->id_entry->router = NULL;
3177 server->router = NULL;
3178 server->standalone = TRUE;
3180 /* We stop here to take a breath */
3184 if (server->server_type == SILC_BACKUP_ROUTER) {
3185 server->server_type = SILC_ROUTER;
3187 /* We'll need to constantly try to reconnect to the primary
3188 router so that we'll see when it comes back online. */
3189 silc_server_backup_reconnect(server, sock->ip, sock->port,
3190 silc_server_backup_connected,
3194 /* Mark this connection as replaced */
3195 silc_server_backup_replaced_add(server, user_data->id,
3198 } else if (backup_router) {
3199 SILC_LOG_INFO(("Enabling the use of backup router %s",
3200 backup_router->server_name));
3202 /* Mark this connection as replaced */
3203 silc_server_backup_replaced_add(server, user_data->id,
3205 } else if (server->server_type == SILC_SERVER &&
3206 sock->type == SILC_SOCKET_TYPE_ROUTER) {
3207 /* Reconnect to the router (backup) */
3208 silc_schedule_task_add(server->schedule, 0,
3209 silc_server_connect_to_router,
3212 SILC_TASK_PRI_NORMAL);
3215 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
3216 ("Server %s signoff", user_data->server_name));
3218 if (!backup_router) {
3219 /* Remove all servers that are originated from this server, and
3220 remove the clients of those servers too. */
3221 silc_server_remove_servers_by_server(server, user_data, TRUE);
3224 /* Remove the clients that this server owns as they will become
3225 invalid now too. For backup router the server is actually
3226 coming from the primary router, so mark that as the owner
3228 if (server->server_type == SILC_BACKUP_ROUTER &&
3229 sock->type == SILC_SOCKET_TYPE_SERVER)
3230 silc_server_remove_clients_by_server(server, server->router,
3234 silc_server_remove_clients_by_server(server, user_data,
3237 /* Remove channels owned by this server */
3238 if (server->server_type == SILC_SERVER)
3239 silc_server_remove_channels_by_server(server, user_data);
3241 /* Enable local server connections that may be disabled */
3242 silc_server_local_servers_toggle_enabled(server, TRUE);
3244 /* Update the client entries of this server to the new backup
3245 router. If we are the backup router we also resolve the real
3246 servers for the clients. After updating is over this also
3247 removes the clients that this server explicitly owns. */
3248 silc_server_update_clients_by_server(server, user_data,
3249 backup_router, TRUE);
3251 /* If we are router and just lost our primary router (now standlaone)
3252 we remove everything that was behind it, since we don't know
3254 if (server->server_type == SILC_ROUTER && server->standalone)
3255 /* Remove all servers that are originated from this server, and
3256 remove the clients of those servers too. */
3257 silc_server_remove_servers_by_server(server, user_data, TRUE);
3259 /* Finally remove the clients that are explicitly owned by this
3260 server. They go down with the server. */
3261 silc_server_remove_clients_by_server(server, user_data,
3264 /* Update our server cache to use the new backup router too. */
3265 silc_server_update_servers_by_server(server, user_data, backup_router);
3266 if (server->server_type == SILC_SERVER)
3267 silc_server_update_channels_by_server(server, user_data,
3270 /* Send notify about primary router going down to local operators */
3271 if (server->backup_router)
3272 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3273 SILC_NOTIFY_TYPE_NONE,
3274 ("%s switched to backup router %s "
3275 "(we are primary router now)",
3276 server->server_name, server->server_name));
3277 else if (server->router)
3278 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3279 SILC_NOTIFY_TYPE_NONE,
3280 ("%s switched to backup router %s",
3281 server->server_name,
3282 server->router->server_name));
3284 server->backup_noswitch = FALSE;
3286 /* Free the server entry */
3287 silc_server_backup_del(server, user_data);
3288 silc_server_backup_replaced_del(server, user_data);
3289 silc_idlist_del_data(user_data);
3290 if (!silc_idlist_del_server(server->local_list, user_data))
3291 silc_idlist_del_server(server->global_list, user_data);
3292 if (sock->type == SILC_SOCKET_TYPE_SERVER) {
3293 server->stat.my_servers--;
3295 server->stat.my_routers--;
3296 server->stat.routers--;
3298 server->stat.servers--;
3299 if (server->server_type == SILC_ROUTER)
3300 server->stat.cell_servers--;
3302 if (backup_router && backup_router != server->id_entry) {
3303 /* Announce all of our stuff that was created about 5 minutes ago.
3304 The backup router knows all the other stuff already. */
3305 if (server->server_type == SILC_ROUTER)
3306 silc_server_announce_servers(server, FALSE, time(0) - 300,
3307 backup_router->connection);
3309 /* Announce our clients and channels to the router */
3310 silc_server_announce_clients(server, time(0) - 300,
3311 backup_router->connection);
3312 silc_server_announce_channels(server, time(0) - 300,
3313 backup_router->connection);
3319 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
3321 SILC_LOG_DEBUG(("Freeing unknown connection data"));
3323 silc_idlist_del_data(user_data);
3324 silc_free(user_data);
3329 /* If any protocol is active cancel its execution */
3330 if (sock->protocol && sock->protocol->protocol &&
3331 sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3332 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3333 silc_protocol_cancel(sock->protocol, server->schedule);
3334 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3335 silc_protocol_execute_final(sock->protocol, server->schedule);
3336 sock->protocol = NULL;
3339 sock->user_data = NULL;
3342 /* Removes client from all channels it has joined. This is used when client
3343 connection is disconnected. If the client on a channel is last, the
3344 channel is removed as well. This sends the SIGNOFF notify types. */
3346 void silc_server_remove_from_channels(SilcServer server,
3347 SilcSocketConnection sock,
3348 SilcClientEntry client,
3350 const char *signoff_message,
3354 SilcChannelEntry channel;
3355 SilcChannelClientEntry chl;
3356 SilcHashTableList htl;
3357 SilcBuffer clidp = NULL;
3362 SILC_LOG_DEBUG(("Removing client from joined channels"));
3364 if (notify && !client->id)
3368 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3373 /* Remove the client from all channels. The client is removed from
3374 the channels' user list. */
3375 silc_hash_table_list(client->channels, &htl);
3376 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3377 channel = chl->channel;
3379 /* Remove channel if this is last client leaving the channel, unless
3380 the channel is permanent. */
3381 if (server->server_type != SILC_SERVER &&
3382 silc_hash_table_count(channel->user_list) < 2) {
3383 silc_server_channel_delete(server, channel);
3387 silc_hash_table_del(client->channels, channel);
3388 silc_hash_table_del(channel->user_list, client);
3389 channel->user_count--;
3391 /* If there is no global users on the channel anymore mark the channel
3392 as local channel. Do not check if the removed client is local client. */
3393 if (server->server_type == SILC_SERVER && channel->global_users &&
3394 chl->client->router && !silc_server_channel_has_global(channel))
3395 channel->global_users = FALSE;
3397 memset(chl, 'A', sizeof(*chl));
3400 /* Update statistics */
3401 if (SILC_IS_LOCAL(client))
3402 server->stat.my_chanclients--;
3403 if (server->server_type == SILC_ROUTER) {
3404 server->stat.cell_chanclients--;
3405 server->stat.chanclients--;
3408 /* If there is not at least one local user on the channel then we don't
3409 need the channel entry anymore, we can remove it safely, unless the
3410 channel is permanent channel */
3411 if (server->server_type == SILC_SERVER &&
3412 !silc_server_channel_has_local(channel)) {
3413 /* Notify about leaving client if this channel has global users. */
3414 if (notify && channel->global_users)
3415 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3416 SILC_NOTIFY_TYPE_SIGNOFF,
3417 signoff_message ? 2 : 1,
3418 clidp->data, clidp->len,
3419 signoff_message, signoff_message ?
3420 strlen(signoff_message) : 0);
3422 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3423 silc_server_channel_delete(server, channel);
3427 /* Send notify to channel about client leaving SILC and channel too */
3429 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3430 SILC_NOTIFY_TYPE_SIGNOFF,
3431 signoff_message ? 2 : 1,
3432 clidp->data, clidp->len,
3433 signoff_message, signoff_message ?
3434 strlen(signoff_message) : 0);
3436 if (killed && clidp) {
3437 /* Remove the client from channel's invite list */
3438 if (channel->invite_list &&
3439 silc_hash_table_count(channel->invite_list)) {
3441 SilcArgumentPayload iargs;
3442 ab = silc_argument_payload_encode_one(NULL, clidp->data,
3444 iargs = silc_argument_payload_parse(ab->data, ab->len, 1);
3445 silc_server_inviteban_process(server, channel->invite_list, 1, iargs);
3446 silc_buffer_free(ab);
3447 silc_argument_payload_free(iargs);
3451 /* Don't create keys if we are shutting down */
3452 if (server->server_shutdown)
3455 /* Re-generate channel key if needed */
3456 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3457 if (!silc_server_create_channel_key(server, channel, 0))
3460 /* Send the channel key to the channel. The key of course is not sent
3461 to the client who was removed from the channel. */
3462 silc_server_send_channel_key(server, client->connection, channel,
3463 server->server_type == SILC_ROUTER ?
3464 FALSE : !server->standalone);
3468 silc_hash_table_list_reset(&htl);
3470 silc_buffer_free(clidp);
3473 /* Removes client from one channel. This is used for example when client
3474 calls LEAVE command to remove itself from the channel. Returns TRUE
3475 if channel still exists and FALSE if the channel is removed when
3476 last client leaves the channel. If `notify' is FALSE notify messages
3479 bool silc_server_remove_from_one_channel(SilcServer server,
3480 SilcSocketConnection sock,
3481 SilcChannelEntry channel,
3482 SilcClientEntry client,
3485 SilcChannelClientEntry chl;
3488 SILC_LOG_DEBUG(("Removing %s from channel %s",
3489 silc_id_render(client->id, SILC_ID_CLIENT),
3490 channel->channel_name));
3492 /* Get the entry to the channel, if this client is not on the channel
3494 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
3497 /* Remove channel if this is last client leaving the channel, unless
3498 the channel is permanent. */
3499 if (server->server_type != SILC_SERVER &&
3500 silc_hash_table_count(channel->user_list) < 2) {
3501 silc_server_channel_delete(server, channel);
3505 silc_hash_table_del(client->channels, channel);
3506 silc_hash_table_del(channel->user_list, client);
3507 channel->user_count--;
3509 /* If there is no global users on the channel anymore mark the channel
3510 as local channel. Do not check if the client is local client. */
3511 if (server->server_type == SILC_SERVER && channel->global_users &&
3512 chl->client->router && !silc_server_channel_has_global(channel))
3513 channel->global_users = FALSE;
3515 memset(chl, 'O', sizeof(*chl));
3518 /* Update statistics */
3519 if (SILC_IS_LOCAL(client))
3520 server->stat.my_chanclients--;
3521 if (server->server_type == SILC_ROUTER) {
3522 server->stat.cell_chanclients--;
3523 server->stat.chanclients--;
3526 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3530 /* If there is not at least one local user on the channel then we don't
3531 need the channel entry anymore, we can remove it safely, unless the
3532 channel is permanent channel */
3533 if (server->server_type == SILC_SERVER &&
3534 !silc_server_channel_has_local(channel)) {
3535 /* Notify about leaving client if this channel has global users. */
3536 if (notify && channel->global_users)
3537 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3538 SILC_NOTIFY_TYPE_LEAVE, 1,
3539 clidp->data, clidp->len);
3541 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3542 silc_server_channel_delete(server, channel);
3543 silc_buffer_free(clidp);
3547 /* Send notify to channel about client leaving the channel */
3549 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3550 SILC_NOTIFY_TYPE_LEAVE, 1,
3551 clidp->data, clidp->len);
3553 silc_buffer_free(clidp);
3557 /* Timeout callback. This is called if connection is idle or for some
3558 other reason is not responding within some period of time. This
3559 disconnects the remote end. */
3561 SILC_TASK_CALLBACK(silc_server_timeout_remote)
3563 SilcServer server = (SilcServer)context;
3564 SilcSocketConnection sock = server->sockets[fd];
3565 SilcProtocolType protocol = 0;
3567 SILC_LOG_DEBUG(("Start"));
3572 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
3573 sock->hostname, sock->ip));
3575 /* If we have protocol active we must assure that we call the protocol's
3576 final callback so that all the memory is freed. */
3577 if (sock->protocol && sock->protocol->protocol &&
3578 sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3579 protocol = sock->protocol->protocol->type;
3580 silc_protocol_cancel(sock->protocol, server->schedule);
3581 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3582 silc_protocol_execute_final(sock->protocol, server->schedule);
3583 sock->protocol = NULL;
3587 silc_server_disconnect_remote(server, sock,
3589 SILC_PROTOCOL_SERVER_CONNECTION_AUTH ?
3590 SILC_STATUS_ERR_AUTH_FAILED :
3591 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
3592 "Connection timeout");
3594 if (sock->user_data)
3595 silc_server_free_sock_user_data(server, sock, NULL);
3598 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
3599 function may be used only by router. In real SILC network all channels
3600 are created by routers thus this function is never used by normal
3603 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3604 SilcServerID *router_id,
3610 SilcChannelID *channel_id;
3611 SilcChannelEntry entry;
3615 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3618 cipher = SILC_DEFAULT_CIPHER;
3620 hmac = SILC_DEFAULT_HMAC;
3622 /* Allocate cipher */
3623 if (!silc_cipher_alloc(cipher, &key))
3627 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3628 silc_cipher_free(key);
3632 channel_name = strdup(channel_name);
3634 /* Create the channel ID */
3635 if (!silc_id_create_channel_id(server, router_id, server->rng,
3637 silc_free(channel_name);
3638 silc_cipher_free(key);
3639 silc_hmac_free(newhmac);
3643 /* Create the channel */
3644 entry = silc_idlist_add_channel(server->local_list, channel_name,
3645 SILC_CHANNEL_MODE_NONE, channel_id,
3646 NULL, key, newhmac, 0);
3648 silc_free(channel_name);
3649 silc_cipher_free(key);
3650 silc_hmac_free(newhmac);
3651 silc_free(channel_id);
3655 entry->cipher = strdup(cipher);
3656 entry->hmac_name = strdup(hmac);
3658 /* Now create the actual key material */
3659 if (!silc_server_create_channel_key(server, entry,
3660 silc_cipher_get_key_len(key) / 8)) {
3661 silc_idlist_del_channel(server->local_list, entry);
3665 /* Notify other routers about the new channel. We send the packet
3666 to our primary route. */
3668 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3669 channel_name, entry->id,
3670 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3673 /* Distribute to backup routers */
3674 if (broadcast && server->server_type == SILC_ROUTER) {
3677 SilcUInt32 name_len = strlen(channel_name);
3678 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3679 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3681 packet = silc_channel_payload_encode(channel_name, name_len,
3682 cid, channel_id_len, entry->mode);
3683 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3684 packet->data, packet->len, FALSE, TRUE);
3686 silc_buffer_free(packet);
3689 server->stat.my_channels++;
3690 if (server->server_type == SILC_ROUTER) {
3691 server->stat.channels++;
3692 server->stat.cell_channels++;
3693 entry->users_resolved = TRUE;
3699 /* Same as above but creates the channel with Channel ID `channel_id. */
3702 silc_server_create_new_channel_with_id(SilcServer server,
3706 SilcChannelID *channel_id,
3709 SilcChannelEntry entry;
3713 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3716 cipher = SILC_DEFAULT_CIPHER;
3718 hmac = SILC_DEFAULT_HMAC;
3720 /* Allocate cipher */
3721 if (!silc_cipher_alloc(cipher, &key))
3725 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3726 silc_cipher_free(key);
3730 channel_name = strdup(channel_name);
3732 /* Create the channel */
3733 entry = silc_idlist_add_channel(server->local_list, channel_name,
3734 SILC_CHANNEL_MODE_NONE, channel_id,
3735 NULL, key, newhmac, 0);
3737 silc_cipher_free(key);
3738 silc_hmac_free(newhmac);
3739 silc_free(channel_name);
3743 /* Now create the actual key material */
3744 if (!silc_server_create_channel_key(server, entry,
3745 silc_cipher_get_key_len(key) / 8)) {
3746 silc_idlist_del_channel(server->local_list, entry);
3750 /* Notify other routers about the new channel. We send the packet
3751 to our primary route. */
3753 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3754 channel_name, entry->id,
3755 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3758 /* Distribute to backup routers */
3759 if (broadcast && server->server_type == SILC_ROUTER) {
3762 SilcUInt32 name_len = strlen(channel_name);
3763 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3764 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3766 packet = silc_channel_payload_encode(channel_name, name_len,
3767 cid, channel_id_len, entry->mode);
3768 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3769 packet->data, packet->len, FALSE, TRUE);
3771 silc_buffer_free(packet);
3774 server->stat.my_channels++;
3775 if (server->server_type == SILC_ROUTER) {
3776 server->stat.channels++;
3777 server->stat.cell_channels++;
3778 entry->users_resolved = TRUE;
3784 /* Channel's key re-key timeout callback. */
3786 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3788 SilcServer server = app_context;
3789 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3793 /* Return now if we are shutting down */
3794 if (server->server_shutdown)
3797 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3800 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3803 /* Generates new channel key. This is used to create the initial channel key
3804 but also to re-generate new key for channel. If `key_len' is provided
3805 it is the bytes of the key length. */
3807 bool silc_server_create_channel_key(SilcServer server,
3808 SilcChannelEntry channel,
3812 unsigned char channel_key[32], hash[32];
3815 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3816 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3820 SILC_LOG_DEBUG(("Generating channel %s key", channel->channel_name));
3822 if (!channel->channel_key)
3823 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3824 channel->channel_key = NULL;
3830 else if (channel->key_len)
3831 len = channel->key_len / 8;
3833 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3835 /* Create channel key */
3836 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3839 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3841 /* Remove old key if exists */
3843 memset(channel->key, 0, channel->key_len / 8);
3844 silc_free(channel->key);
3848 channel->key_len = len * 8;
3849 channel->key = silc_memdup(channel_key, len);
3850 memset(channel_key, 0, sizeof(channel_key));
3852 /* Generate HMAC key from the channel key data and set it */
3854 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3855 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3856 silc_hmac_set_key(channel->hmac, hash,
3857 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3858 memset(hash, 0, sizeof(hash));
3860 if (server->server_type == SILC_ROUTER) {
3861 if (!channel->rekey)
3862 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3863 channel->rekey->channel = channel;
3864 channel->rekey->key_len = key_len;
3865 if (channel->rekey->task)
3866 silc_schedule_task_del(server->schedule, channel->rekey->task);
3868 channel->rekey->task =
3869 silc_schedule_task_add(server->schedule, 0,
3870 silc_server_channel_key_rekey,
3871 (void *)channel->rekey,
3872 server->config->channel_rekey_secs, 0,
3874 SILC_TASK_PRI_NORMAL);
3880 /* Saves the channel key found in the encoded `key_payload' buffer. This
3881 function is used when we receive Channel Key Payload and also when we're
3882 processing JOIN command reply. Returns entry to the channel. */
3884 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3885 SilcBuffer key_payload,
3886 SilcChannelEntry channel)
3888 SilcChannelKeyPayload payload = NULL;
3889 SilcChannelID *id = NULL;
3890 unsigned char *tmp, hash[32];
3894 /* Decode channel key payload */
3895 payload = silc_channel_key_payload_parse(key_payload->data,
3898 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3903 /* Get the channel entry */
3906 /* Get channel ID */
3907 tmp = silc_channel_key_get_id(payload, &tmp_len);
3908 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3914 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3916 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3918 if (server->server_type == SILC_ROUTER)
3919 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3920 silc_id_render(id, SILC_ID_CHANNEL)));
3926 SILC_LOG_DEBUG(("Saving new channel %s key", channel->channel_name));
3928 tmp = silc_channel_key_get_key(payload, &tmp_len);
3934 cipher = silc_channel_key_get_cipher(payload, NULL);
3940 /* Remove old key if exists */
3942 memset(channel->key, 0, channel->key_len / 8);
3943 silc_free(channel->key);
3944 silc_cipher_free(channel->channel_key);
3947 /* Create new cipher */
3948 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3949 channel->channel_key = NULL;
3954 if (channel->cipher)
3955 silc_free(channel->cipher);
3956 channel->cipher = strdup(cipher);
3959 channel->key_len = tmp_len * 8;
3960 channel->key = silc_memdup(tmp, tmp_len);
3961 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3963 /* Generate HMAC key from the channel key data and set it */
3965 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3966 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3967 silc_hmac_set_key(channel->hmac, hash,
3968 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3970 memset(hash, 0, sizeof(hash));
3971 memset(tmp, 0, tmp_len);
3973 if (server->server_type == SILC_ROUTER) {
3974 if (!channel->rekey)
3975 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3976 channel->rekey->channel = channel;
3977 if (channel->rekey->task)
3978 silc_schedule_task_del(server->schedule, channel->rekey->task);
3980 channel->rekey->task =
3981 silc_schedule_task_add(server->schedule, 0,
3982 silc_server_channel_key_rekey,
3983 (void *)channel->rekey,
3984 server->config->channel_rekey_secs, 0,
3986 SILC_TASK_PRI_NORMAL);
3992 silc_channel_key_payload_free(payload);
3997 /* Heartbeat callback. This function is set as argument for the
3998 silc_socket_set_heartbeat function. The library will call this function
3999 at the set time interval. */
4001 void silc_server_perform_heartbeat(SilcSocketConnection sock,
4004 SilcServer server = hb_context;
4006 SILC_LOG_DEBUG(("Sending heartbeat to %s:%d (%s)", sock->hostname,
4007 sock->port, sock->ip));
4009 /* Send the heartbeat */
4010 silc_server_send_heartbeat(server, sock);
4013 /* Returns assembled of all servers in the given ID list. The packet's
4014 form is dictated by the New ID payload. */
4016 static void silc_server_announce_get_servers(SilcServer server,
4017 SilcServerEntry remote,
4019 SilcBuffer *servers,
4020 unsigned long creation_time)
4022 SilcIDCacheList list;
4023 SilcIDCacheEntry id_cache;
4024 SilcServerEntry entry;
4027 /* Go through all clients in the list */
4028 if (silc_idcache_get_all(id_list->servers, &list)) {
4029 if (silc_idcache_list_first(list, &id_cache)) {
4031 entry = (SilcServerEntry)id_cache->context;
4033 /* Do not announce the one we've sending our announcements and
4034 do not announce ourself. Also check the creation time if it's
4036 if ((entry == remote) || (entry == server->id_entry) ||
4037 (creation_time && entry->data.created < creation_time)) {
4038 if (!silc_idcache_list_next(list, &id_cache))
4043 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
4045 *servers = silc_buffer_realloc(*servers,
4047 (*servers)->truelen + idp->len :
4049 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
4050 silc_buffer_put(*servers, idp->data, idp->len);
4051 silc_buffer_pull(*servers, idp->len);
4052 silc_buffer_free(idp);
4054 if (!silc_idcache_list_next(list, &id_cache))
4059 silc_idcache_list_free(list);
4064 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
4070 p = silc_notify_payload_encode(notify, argc, ap);
4076 /* This function is used by router to announce existing servers to our
4077 primary router when we've connected to it. If `creation_time' is non-zero
4078 then only the servers that has been created after the `creation_time'
4079 will be announced. */
4081 void silc_server_announce_servers(SilcServer server, bool global,
4082 unsigned long creation_time,
4083 SilcSocketConnection remote)
4085 SilcBuffer servers = NULL;
4087 SILC_LOG_DEBUG(("Announcing servers"));
4089 /* Get servers in local list */
4090 silc_server_announce_get_servers(server, remote->user_data,
4091 server->local_list, &servers,
4095 /* Get servers in global list */
4096 silc_server_announce_get_servers(server, remote->user_data,
4097 server->global_list, &servers,
4101 silc_buffer_push(servers, servers->data - servers->head);
4102 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
4104 /* Send the packet */
4105 silc_server_packet_send(server, remote,
4106 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4107 servers->data, servers->len, TRUE);
4109 silc_buffer_free(servers);
4113 /* Returns assembled packet of all clients in the given ID list. The
4114 packet's form is dictated by the New ID Payload. */
4116 static void silc_server_announce_get_clients(SilcServer server,
4118 SilcBuffer *clients,
4120 unsigned long creation_time)
4122 SilcIDCacheList list;
4123 SilcIDCacheEntry id_cache;
4124 SilcClientEntry client;
4127 unsigned char mode[4];
4129 /* Go through all clients in the list */
4130 if (silc_idcache_get_all(id_list->clients, &list)) {
4131 if (silc_idcache_list_first(list, &id_cache)) {
4133 client = (SilcClientEntry)id_cache->context;
4135 if (creation_time && client->data.created < creation_time) {
4136 if (!silc_idcache_list_next(list, &id_cache))
4140 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED) &&
4141 !client->connection && !client->router && !SILC_IS_LOCAL(client)) {
4142 if (!silc_idcache_list_next(list, &id_cache))
4147 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
4149 *clients = silc_buffer_realloc(*clients,
4151 (*clients)->truelen + idp->len :
4153 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
4154 silc_buffer_put(*clients, idp->data, idp->len);
4155 silc_buffer_pull(*clients, idp->len);
4157 SILC_PUT32_MSB(client->mode, mode);
4159 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
4160 2, idp->data, idp->len,
4162 *umodes = silc_buffer_realloc(*umodes,
4164 (*umodes)->truelen + tmp->len :
4166 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
4167 silc_buffer_put(*umodes, tmp->data, tmp->len);
4168 silc_buffer_pull(*umodes, tmp->len);
4169 silc_buffer_free(tmp);
4171 silc_buffer_free(idp);
4173 if (!silc_idcache_list_next(list, &id_cache))
4178 silc_idcache_list_free(list);
4182 /* This function is used to announce our existing clients to our router
4183 when we've connected to it. If `creation_time' is non-zero then only
4184 the clients that has been created after the `creation_time' will be
4187 void silc_server_announce_clients(SilcServer server,
4188 unsigned long creation_time,
4189 SilcSocketConnection remote)
4191 SilcBuffer clients = NULL;
4192 SilcBuffer umodes = NULL;
4194 SILC_LOG_DEBUG(("Announcing clients"));
4196 /* Get clients in local list */
4197 silc_server_announce_get_clients(server, server->local_list,
4198 &clients, &umodes, creation_time);
4200 /* As router we announce our global list as well */
4201 if (server->server_type == SILC_ROUTER)
4202 silc_server_announce_get_clients(server, server->global_list,
4203 &clients, &umodes, creation_time);
4206 silc_buffer_push(clients, clients->data - clients->head);
4207 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
4209 /* Send the packet */
4210 silc_server_packet_send(server, remote,
4211 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4212 clients->data, clients->len, TRUE);
4214 silc_buffer_free(clients);
4218 silc_buffer_push(umodes, umodes->data - umodes->head);
4219 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
4221 /* Send the packet */
4222 silc_server_packet_send(server, remote,
4223 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4224 umodes->data, umodes->len, TRUE);
4226 silc_buffer_free(umodes);
4230 /* Returns channel's topic for announcing it */
4232 void silc_server_announce_get_channel_topic(SilcServer server,
4233 SilcChannelEntry channel,
4238 if (channel->topic) {
4239 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4240 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
4241 chidp->data, chidp->len,
4243 strlen(channel->topic));
4244 silc_buffer_free(chidp);
4248 /* Returns assembled packets for channel users of the `channel'. */
4250 void silc_server_announce_get_channel_users(SilcServer server,
4251 SilcChannelEntry channel,
4252 SilcBuffer *channel_modes,
4253 SilcBuffer *channel_users,
4254 SilcBuffer *channel_users_modes)
4256 SilcChannelClientEntry chl;
4257 SilcHashTableList htl;
4258 SilcBuffer chidp, clidp, csidp;
4259 SilcBuffer tmp, fkey = NULL;
4261 unsigned char mode[4];
4264 SILC_LOG_DEBUG(("Start"));
4266 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4267 csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4270 SILC_PUT32_MSB(channel->mode, mode);
4271 hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
4272 if (channel->founder_key)
4273 fkey = silc_pkcs_public_key_payload_encode(channel->founder_key);
4275 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
4276 6, csidp->data, csidp->len,
4279 hmac, hmac ? strlen(hmac) : 0,
4280 channel->passphrase,
4281 channel->passphrase ?
4282 strlen(channel->passphrase) : 0,
4283 fkey ? fkey->data : NULL,
4284 fkey ? fkey->len : 0);
4287 silc_buffer_realloc(*channel_modes,
4289 (*channel_modes)->truelen + len : len));
4290 silc_buffer_pull_tail(*channel_modes,
4291 ((*channel_modes)->end -
4292 (*channel_modes)->data));
4293 silc_buffer_put(*channel_modes, tmp->data, tmp->len);
4294 silc_buffer_pull(*channel_modes, len);
4295 silc_buffer_free(tmp);
4296 silc_buffer_free(fkey);
4299 /* Now find all users on the channel */
4300 silc_hash_table_list(channel->user_list, &htl);
4301 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4302 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4305 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
4306 clidp->data, clidp->len,
4307 chidp->data, chidp->len);
4310 silc_buffer_realloc(*channel_users,
4312 (*channel_users)->truelen + len : len));
4313 silc_buffer_pull_tail(*channel_users,
4314 ((*channel_users)->end -
4315 (*channel_users)->data));
4317 silc_buffer_put(*channel_users, tmp->data, tmp->len);
4318 silc_buffer_pull(*channel_users, len);
4319 silc_buffer_free(tmp);
4321 /* CUMODE notify for mode change on the channel */
4322 SILC_PUT32_MSB(chl->mode, mode);
4323 if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
4324 fkey = silc_pkcs_public_key_payload_encode(channel->founder_key);
4325 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
4326 4, csidp->data, csidp->len,
4328 clidp->data, clidp->len,
4329 fkey ? fkey->data : NULL,
4330 fkey ? fkey->len : 0);
4332 *channel_users_modes =
4333 silc_buffer_realloc(*channel_users_modes,
4334 (*channel_users_modes ?
4335 (*channel_users_modes)->truelen + len : len));
4336 silc_buffer_pull_tail(*channel_users_modes,
4337 ((*channel_users_modes)->end -
4338 (*channel_users_modes)->data));
4340 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
4341 silc_buffer_pull(*channel_users_modes, len);
4342 silc_buffer_free(tmp);
4343 silc_buffer_free(fkey);
4345 silc_buffer_free(clidp);
4347 silc_hash_table_list_reset(&htl);
4348 silc_buffer_free(chidp);
4349 silc_buffer_free(csidp);
4352 /* Returns assembled packets for all channels and users on those channels
4353 from the given ID List. The packets are in the form dictated by the
4354 New Channel and New Channel User payloads. */
4356 void silc_server_announce_get_channels(SilcServer server,
4358 SilcBuffer *channels,
4359 SilcBuffer **channel_modes,
4360 SilcBuffer *channel_users,
4361 SilcBuffer **channel_users_modes,
4362 SilcUInt32 *channel_users_modes_c,
4363 SilcBuffer **channel_topics,
4364 SilcChannelID ***channel_ids,
4365 unsigned long creation_time)
4367 SilcIDCacheList list;
4368 SilcIDCacheEntry id_cache;
4369 SilcChannelEntry channel;
4372 SilcUInt16 name_len;
4374 int i = *channel_users_modes_c;
4377 SILC_LOG_DEBUG(("Start"));
4379 /* Go through all channels in the list */
4380 if (silc_idcache_get_all(id_list->channels, &list)) {
4381 if (silc_idcache_list_first(list, &id_cache)) {
4383 channel = (SilcChannelEntry)id_cache->context;
4385 if (creation_time && channel->created < creation_time)
4390 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4391 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4392 name_len = strlen(channel->channel_name);
4395 len = 4 + name_len + id_len + 4;
4397 silc_buffer_realloc(*channels,
4398 (*channels ? (*channels)->truelen +
4400 silc_buffer_pull_tail(*channels,
4401 ((*channels)->end - (*channels)->data));
4402 silc_buffer_format(*channels,
4403 SILC_STR_UI_SHORT(name_len),
4404 SILC_STR_UI_XNSTRING(channel->channel_name,
4406 SILC_STR_UI_SHORT(id_len),
4407 SILC_STR_UI_XNSTRING(cid, id_len),
4408 SILC_STR_UI_INT(channel->mode),
4410 silc_buffer_pull(*channels, len);
4413 if (creation_time && channel->updated < creation_time)
4419 /* Channel user modes */
4420 *channel_users_modes = silc_realloc(*channel_users_modes,
4421 sizeof(**channel_users_modes) *
4423 (*channel_users_modes)[i] = NULL;
4424 *channel_modes = silc_realloc(*channel_modes,
4425 sizeof(**channel_modes) * (i + 1));
4426 (*channel_modes)[i] = NULL;
4427 *channel_ids = silc_realloc(*channel_ids,
4428 sizeof(**channel_ids) * (i + 1));
4429 (*channel_ids)[i] = NULL;
4430 silc_server_announce_get_channel_users(server, channel,
4431 &(*channel_modes)[i],
4433 &(*channel_users_modes)[i]);
4434 (*channel_ids)[i] = channel->id;
4436 /* Channel's topic */
4437 *channel_topics = silc_realloc(*channel_topics,
4438 sizeof(**channel_topics) * (i + 1));
4439 (*channel_topics)[i] = NULL;
4440 silc_server_announce_get_channel_topic(server, channel,
4441 &(*channel_topics)[i]);
4442 (*channel_users_modes_c)++;
4449 if (!silc_idcache_list_next(list, &id_cache))
4454 silc_idcache_list_free(list);
4458 /* This function is used to announce our existing channels to our router
4459 when we've connected to it. This also announces the users on the
4460 channels to the router. If the `creation_time' is non-zero only the
4461 channels that was created after the `creation_time' are announced.
4462 Note that the channel users are still announced even if the `creation_time'
4465 void silc_server_announce_channels(SilcServer server,
4466 unsigned long creation_time,
4467 SilcSocketConnection remote)
4469 SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
4470 SilcBuffer *channel_users_modes = NULL;
4471 SilcBuffer *channel_topics = NULL;
4472 SilcUInt32 channel_users_modes_c = 0;
4473 SilcChannelID **channel_ids = NULL;
4475 SILC_LOG_DEBUG(("Announcing channels and channel users"));
4477 /* Get channels and channel users in local list */
4478 silc_server_announce_get_channels(server, server->local_list,
4479 &channels, &channel_modes,
4481 &channel_users_modes,
4482 &channel_users_modes_c,
4484 &channel_ids, creation_time);
4486 /* Get channels and channel users in global list */
4487 if (server->server_type != SILC_SERVER)
4488 silc_server_announce_get_channels(server, server->global_list,
4489 &channels, &channel_modes,
4491 &channel_users_modes,
4492 &channel_users_modes_c,
4494 &channel_ids, creation_time);
4497 silc_buffer_push(channels, channels->data - channels->head);
4498 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
4500 /* Send the packet */
4501 silc_server_packet_send(server, remote,
4502 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
4503 channels->data, channels->len,
4506 silc_buffer_free(channels);
4509 if (channel_users) {
4510 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
4511 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
4512 channel_users->len);
4514 /* Send the packet */
4515 silc_server_packet_send(server, remote,
4516 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4517 channel_users->data, channel_users->len,
4520 silc_buffer_free(channel_users);
4523 if (channel_modes) {
4526 for (i = 0; i < channel_users_modes_c; i++) {
4527 if (!channel_modes[i])
4529 silc_buffer_push(channel_modes[i],
4530 channel_modes[i]->data -
4531 channel_modes[i]->head);
4532 SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
4533 channel_modes[i]->len);
4534 silc_server_packet_send_dest(server, remote,
4535 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4536 channel_ids[i], SILC_ID_CHANNEL,
4537 channel_modes[i]->data,
4538 channel_modes[i]->len,
4540 silc_buffer_free(channel_modes[i]);
4542 silc_free(channel_modes);
4545 if (channel_users_modes) {
4548 for (i = 0; i < channel_users_modes_c; i++) {
4549 if (!channel_users_modes[i])
4551 silc_buffer_push(channel_users_modes[i],
4552 channel_users_modes[i]->data -
4553 channel_users_modes[i]->head);
4554 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
4555 channel_users_modes[i]->len);
4556 silc_server_packet_send_dest(server, remote,
4557 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4558 channel_ids[i], SILC_ID_CHANNEL,
4559 channel_users_modes[i]->data,
4560 channel_users_modes[i]->len,
4562 silc_buffer_free(channel_users_modes[i]);
4564 silc_free(channel_users_modes);
4567 if (channel_topics) {
4570 for (i = 0; i < channel_users_modes_c; i++) {
4571 if (!channel_topics[i])
4574 silc_buffer_push(channel_topics[i],
4575 channel_topics[i]->data -
4576 channel_topics[i]->head);
4577 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
4578 channel_topics[i]->len);
4579 silc_server_packet_send_dest(server, remote,
4580 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4581 channel_ids[i], SILC_ID_CHANNEL,
4582 channel_topics[i]->data,
4583 channel_topics[i]->len,
4585 silc_buffer_free(channel_topics[i]);
4587 silc_free(channel_topics);
4590 silc_free(channel_ids);
4593 /* Assembles user list and users mode list from the `channel'. */
4595 bool silc_server_get_users_on_channel(SilcServer server,
4596 SilcChannelEntry channel,
4597 SilcBuffer *user_list,
4598 SilcBuffer *mode_list,
4599 SilcUInt32 *user_count)
4601 SilcChannelClientEntry chl;
4602 SilcHashTableList htl;
4603 SilcBuffer client_id_list;
4604 SilcBuffer client_mode_list;
4606 SilcUInt32 list_count = 0, len = 0;
4608 if (!silc_hash_table_count(channel->user_list))
4611 silc_hash_table_list(channel->user_list, &htl);
4612 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4613 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
4614 silc_hash_table_list_reset(&htl);
4616 client_id_list = silc_buffer_alloc(len);
4618 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
4619 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
4620 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
4622 silc_hash_table_list(channel->user_list, &htl);
4623 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4625 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4626 silc_buffer_put(client_id_list, idp->data, idp->len);
4627 silc_buffer_pull(client_id_list, idp->len);
4628 silc_buffer_free(idp);
4630 /* Client's mode on channel */
4631 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
4632 silc_buffer_pull(client_mode_list, 4);
4636 silc_hash_table_list_reset(&htl);
4637 silc_buffer_push(client_id_list,
4638 client_id_list->data - client_id_list->head);
4639 silc_buffer_push(client_mode_list,
4640 client_mode_list->data - client_mode_list->head);
4642 *user_list = client_id_list;
4643 *mode_list = client_mode_list;
4644 *user_count = list_count;
4648 /* Saves users and their modes to the `channel'. */
4650 void silc_server_save_users_on_channel(SilcServer server,
4651 SilcSocketConnection sock,
4652 SilcChannelEntry channel,
4653 SilcClientID *noadd,
4654 SilcBuffer user_list,
4655 SilcBuffer mode_list,
4656 SilcUInt32 user_count)
4661 SilcClientID *client_id;
4662 SilcClientEntry client;
4663 SilcIDCacheEntry cache;
4664 SilcChannelClientEntry chl;
4666 SILC_LOG_DEBUG(("Saving %d users on %s channel", user_count,
4667 channel->channel_name));
4669 for (i = 0; i < user_count; i++) {
4671 SILC_GET16_MSB(idp_len, user_list->data + 2);
4673 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
4674 silc_buffer_pull(user_list, idp_len);
4679 SILC_GET32_MSB(mode, mode_list->data);
4680 silc_buffer_pull(mode_list, 4);
4682 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
4683 silc_free(client_id);
4689 /* Check if we have this client cached already. */
4690 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4691 server->server_type, &cache);
4693 client = silc_idlist_find_client_by_id(server->global_list,
4694 client_id, server->server_type,
4697 /* If router did not find such Client ID in its lists then this must
4698 be bogus client or some router in the net is buggy. */
4699 if (server->server_type != SILC_SERVER) {
4700 silc_free(client_id);
4704 /* We don't have that client anywhere, add it. The client is added
4705 to global list since server didn't have it in the lists so it must be
4707 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
4708 silc_id_dup(client_id, SILC_ID_CLIENT),
4709 sock->user_data, NULL, 0);
4711 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
4712 silc_free(client_id);
4716 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
4721 silc_free(client_id);
4723 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
4724 SILC_LOG_ERROR(("Attempting to add unregistered client to channel ",
4725 "%s", channel->channel_name));
4729 if (!silc_server_client_on_channel(client, channel, &chl)) {
4730 /* Client was not on the channel, add it. */
4731 chl = silc_calloc(1, sizeof(*chl));
4732 chl->client = client;
4734 chl->channel = channel;
4735 silc_hash_table_add(channel->user_list, chl->client, chl);
4736 silc_hash_table_add(client->channels, chl->channel, chl);
4737 channel->user_count++;
4745 /* Saves channels and channels user modes to the `client'. Removes
4746 the client from those channels that are not sent in the list but
4749 void silc_server_save_user_channels(SilcServer server,
4750 SilcSocketConnection sock,
4751 SilcClientEntry client,
4752 SilcBuffer channels,
4753 SilcBuffer channels_user_modes)
4756 SilcUInt32 *chumodes;
4757 SilcChannelPayload entry;
4758 SilcChannelEntry channel;
4759 SilcChannelID *channel_id;
4760 SilcChannelClientEntry chl;
4761 SilcHashTable ht = NULL;
4762 SilcHashTableList htl;
4766 if (!channels || !channels_user_modes ||
4767 !(client->data.status & SILC_IDLIST_STATUS_REGISTERED))
4770 ch = silc_channel_payload_parse_list(channels->data, channels->len);
4771 if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
4773 ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL,
4774 NULL, NULL, NULL, TRUE);
4775 silc_dlist_start(ch);
4776 while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
4777 /* Check if we have this channel, and add it if we don't have it.
4778 Also add the client on the channel unless it is there already. */
4779 channel_id = silc_channel_get_id_parse(entry);
4780 channel = silc_idlist_find_channel_by_id(server->local_list,
4783 channel = silc_idlist_find_channel_by_id(server->global_list,
4786 if (server->server_type != SILC_SERVER) {
4787 silc_free(channel_id);
4792 /* We don't have that channel anywhere, add it. */
4793 name = silc_channel_get_name(entry, NULL);
4794 channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
4795 channel_id, server->router,
4798 silc_free(channel_id);
4805 channel->mode = silc_channel_get_mode(entry);
4807 /* Add the client on the channel */
4808 if (!silc_server_client_on_channel(client, channel, &chl)) {
4809 chl = silc_calloc(1, sizeof(*chl));
4810 chl->client = client;
4811 chl->mode = chumodes[i++];
4812 chl->channel = channel;
4813 silc_hash_table_add(channel->user_list, chl->client, chl);
4814 silc_hash_table_add(client->channels, chl->channel, chl);
4815 channel->user_count++;
4818 chl->mode = chumodes[i++];
4821 silc_hash_table_add(ht, channel, channel);
4822 silc_free(channel_id);
4824 silc_channel_payload_list_free(ch);
4825 silc_free(chumodes);
4829 /* Go through the list again and remove client from channels that
4830 are no part of the list. */
4832 silc_hash_table_list(client->channels, &htl);
4833 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4834 if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
4835 silc_hash_table_del(chl->channel->user_list, chl->client);
4836 silc_hash_table_del(chl->client->channels, chl->channel);
4840 silc_hash_table_list_reset(&htl);
4841 silc_hash_table_free(ht);
4843 silc_hash_table_list(client->channels, &htl);
4844 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4845 silc_hash_table_del(chl->channel->user_list, chl->client);
4846 silc_hash_table_del(chl->client->channels, chl->channel);
4849 silc_hash_table_list_reset(&htl);
4853 /* Lookups route to the client indicated by the `id_data'. The connection
4854 object and internal data object is returned. Returns NULL if route
4855 could not be found to the client. If the `client_id' is specified then
4856 it is used and the `id_data' is ignored. */
4858 SilcSocketConnection
4859 silc_server_get_client_route(SilcServer server,
4860 unsigned char *id_data,
4862 SilcClientID *client_id,
4863 SilcIDListData *idata,
4864 SilcClientEntry *client_entry)
4867 SilcClientEntry client;
4869 SILC_LOG_DEBUG(("Start"));
4872 *client_entry = NULL;
4874 /* Decode destination Client ID */
4876 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
4878 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
4882 id = silc_id_dup(client_id, SILC_ID_CLIENT);
4885 /* If the destination belongs to our server we don't have to route
4886 the packet anywhere but to send it to the local destination. */
4887 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
4891 /* If we are router and the client has router then the client is in
4892 our cell but not directly connected to us. */
4893 if (server->server_type == SILC_ROUTER && client->router) {
4894 /* We are of course in this case the client's router thus the route
4895 to the client is the server who owns the client. So, we will send
4896 the packet to that server. */
4898 *idata = (SilcIDListData)client->router;
4899 return client->router->connection;
4902 /* Seems that client really is directly connected to us */
4904 *idata = (SilcIDListData)client;
4906 *client_entry = client;
4907 return client->connection;
4910 /* Destination belongs to someone not in this server. If we are normal
4911 server our action is to send the packet to our router. */
4912 if (server->server_type != SILC_ROUTER && !server->standalone) {
4915 *idata = (SilcIDListData)server->router;
4916 return SILC_PRIMARY_ROUTE(server);
4919 /* We are router and we will perform route lookup for the destination
4920 and send the packet to fastest route. */
4921 if (server->server_type == SILC_ROUTER && !server->standalone) {
4922 /* Check first that the ID is valid */
4923 client = silc_idlist_find_client_by_id(server->global_list, id,
4926 SilcSocketConnection dst_sock;
4928 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
4932 *idata = (SilcIDListData)dst_sock->user_data;
4941 /* Encodes and returns channel list of channels the `client' has joined.
4942 Secret channels are not put to the list. */
4944 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
4945 SilcClientEntry client,
4948 SilcBuffer *user_mode_list)
4950 SilcBuffer buffer = NULL;
4951 SilcChannelEntry channel;
4952 SilcChannelClientEntry chl;
4953 SilcHashTableList htl;
4956 SilcUInt16 name_len;
4960 *user_mode_list = NULL;
4962 silc_hash_table_list(client->channels, &htl);
4963 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4964 channel = chl->channel;
4966 if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
4968 if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
4971 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4972 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4973 name_len = strlen(channel->channel_name);
4975 len = 4 + name_len + id_len + 4;
4976 buffer = silc_buffer_realloc(buffer,
4977 (buffer ? buffer->truelen + len : len));
4978 silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
4979 silc_buffer_format(buffer,
4980 SILC_STR_UI_SHORT(name_len),
4981 SILC_STR_UI_XNSTRING(channel->channel_name,
4983 SILC_STR_UI_SHORT(id_len),
4984 SILC_STR_UI_XNSTRING(cid, id_len),
4985 SILC_STR_UI_INT(chl->channel->mode),
4987 silc_buffer_pull(buffer, len);
4990 if (user_mode_list) {
4991 *user_mode_list = silc_buffer_realloc(*user_mode_list,
4993 (*user_mode_list)->truelen + 4 :
4995 silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
4996 (*user_mode_list)->data));
4997 SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
4998 silc_buffer_pull(*user_mode_list, 4);
5001 silc_hash_table_list_reset(&htl);
5004 silc_buffer_push(buffer, buffer->data - buffer->head);
5005 if (user_mode_list && *user_mode_list)
5006 silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
5007 (*user_mode_list)->head));
5012 /* A timeout callback for the re-key. We will be the initiator of the
5015 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_callback)
5017 SilcServer server = app_context;
5018 SilcSocketConnection sock = (SilcSocketConnection)context;
5019 SilcIDListData idata = (SilcIDListData)sock->user_data;
5020 SilcProtocol protocol;
5021 SilcServerRekeyInternalContext *proto_ctx;
5023 /* Allocate internal protocol context. This is sent as context
5025 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
5026 proto_ctx->server = (void *)server;
5027 proto_ctx->sock = sock;
5028 proto_ctx->responder = FALSE;
5029 proto_ctx->pfs = idata->rekey->pfs;
5031 /* Perform rekey protocol. Will call the final callback after the
5032 protocol is over. */
5033 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
5034 &protocol, proto_ctx, silc_server_rekey_final);
5035 sock->protocol = protocol;
5037 /* Run the protocol */
5038 silc_protocol_execute(protocol, server->schedule, 0, 0);
5040 SILC_LOG_DEBUG(("Rekey protocol completed"));
5042 /* Re-register re-key timeout */
5043 silc_schedule_task_add(server->schedule, sock->sock,
5044 silc_server_rekey_callback,
5045 context, idata->rekey->timeout, 0,
5046 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
5049 /* The final callback for the REKEY protocol. This will actually take the
5050 new key material into use. */
5052 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
5054 SilcProtocol protocol = (SilcProtocol)context;
5055 SilcServerRekeyInternalContext *ctx =
5056 (SilcServerRekeyInternalContext *)protocol->context;
5057 SilcServer server = (SilcServer)ctx->server;
5058 SilcSocketConnection sock = ctx->sock;
5060 SILC_LOG_DEBUG(("Start"));
5062 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
5063 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
5064 /* Error occured during protocol */
5065 SILC_LOG_ERROR(("Error occurred during rekey protocol with
5066 %s (%s)", sock->hostname, sock->ip));
5067 silc_protocol_cancel(protocol, server->schedule);
5068 silc_protocol_free(protocol);
5069 sock->protocol = NULL;
5071 silc_packet_context_free(ctx->packet);
5073 silc_ske_free(ctx->ske);
5078 /* Purge the outgoing data queue to assure that all rekey packets really
5079 go to the network before we quit the protocol. */
5080 silc_server_packet_queue_purge(server, sock);
5083 silc_protocol_free(protocol);
5084 sock->protocol = NULL;
5086 silc_packet_context_free(ctx->packet);
5088 silc_ske_free(ctx->ske);
5092 /* Task callback used to retrieve network statistical information from
5093 router server once in a while. */
5095 SILC_TASK_CALLBACK(silc_server_get_stats)
5097 SilcServer server = (SilcServer)context;
5098 SilcBuffer idp, packet;
5100 SILC_LOG_DEBUG(("Retrieving stats from router"));
5102 if (!server->standalone) {
5103 idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
5104 packet = silc_command_payload_encode_va(SILC_COMMAND_STATS,
5105 ++server->cmd_ident, 1,
5106 1, idp->data, idp->len);
5107 silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
5108 SILC_PACKET_COMMAND, 0, packet->data,
5109 packet->len, FALSE);
5110 silc_buffer_free(packet);
5111 silc_buffer_free(idp);
5114 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
5115 server, 120, 0, SILC_TASK_TIMEOUT,