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);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
35 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
38 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
39 SILC_TASK_CALLBACK(silc_server_packet_process);
40 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
41 SILC_TASK_CALLBACK(silc_server_close_connection_final);
42 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout);
43 SILC_TASK_CALLBACK(silc_server_timeout_remote);
44 SILC_TASK_CALLBACK(silc_server_channel_key_rekey);
45 SILC_TASK_CALLBACK(silc_server_failure_callback);
46 SILC_TASK_CALLBACK(silc_server_rekey_callback);
47 SILC_TASK_CALLBACK(silc_server_get_stats);
49 /* Allocates a new SILC server object. This has to be done before the server
50 can be used. After allocation one must call silc_server_init to initialize
51 the server. The new allocated server object is returned to the new_server
54 int silc_server_alloc(SilcServer *new_server)
58 SILC_LOG_DEBUG(("Allocating new server object"));
60 server = silc_calloc(1, sizeof(*server));
61 server->server_type = SILC_SERVER;
62 server->standalone = TRUE;
63 server->local_list = silc_calloc(1, sizeof(*server->local_list));
64 server->global_list = silc_calloc(1, sizeof(*server->global_list));
65 server->pending_commands = silc_dlist_init();
67 server->sim = silc_dlist_init();
75 /* Free's the SILC server object. This is called at the very end before
78 void silc_server_free(SilcServer server)
81 SilcIDCacheEntry cache;
90 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
91 silc_dlist_del(server->sim, sim);
94 silc_dlist_uninit(server->sim);
98 silc_server_backup_free(server);
99 silc_server_config_unref(&server->config_ref);
101 silc_rng_free(server->rng);
103 silc_pkcs_free(server->pkcs);
104 if (server->public_key)
105 silc_pkcs_public_key_free(server->public_key);
106 if (server->private_key)
107 silc_pkcs_private_key_free(server->private_key);
108 if (server->pending_commands)
109 silc_dlist_uninit(server->pending_commands);
110 if (server->id_entry)
111 silc_idlist_del_server(server->local_list, server->id_entry);
113 /* Delete all channels */
115 if (silc_idcache_get_all(server->local_list->channels, &list) &&
116 silc_idcache_list_first(list, &cache)) {
117 silc_idlist_del_channel(server->local_list, cache->context);
118 while (silc_idcache_list_next(list, &cache))
119 silc_idlist_del_channel(server->local_list, cache->context);
122 silc_idcache_list_free(list);
124 if (silc_idcache_get_all(server->global_list->channels, &list) &&
125 silc_idcache_list_first(list, &cache)) {
126 silc_idlist_del_channel(server->global_list, cache->context);
127 while (silc_idcache_list_next(list, &cache))
128 silc_idlist_del_channel(server->global_list, cache->context);
131 silc_idcache_list_free(list);
133 /* Delete all clients */
135 if (silc_idcache_get_all(server->local_list->clients, &list) &&
136 silc_idcache_list_first(list, &cache)) {
137 silc_idlist_del_client(server->local_list, cache->context);
138 while (silc_idcache_list_next(list, &cache))
139 silc_idlist_del_client(server->local_list, cache->context);
142 silc_idcache_list_free(list);
144 if (silc_idcache_get_all(server->global_list->clients, &list) &&
145 silc_idcache_list_first(list, &cache)) {
146 silc_idlist_del_client(server->global_list, cache->context);
147 while (silc_idcache_list_next(list, &cache))
148 silc_idlist_del_client(server->global_list, cache->context);
151 silc_idcache_list_free(list);
153 /* Delete all servers */
155 if (silc_idcache_get_all(server->local_list->servers, &list) &&
156 silc_idcache_list_first(list, &cache)) {
157 silc_idlist_del_server(server->local_list, cache->context);
158 while (silc_idcache_list_next(list, &cache))
159 silc_idlist_del_server(server->local_list, cache->context);
162 silc_idcache_list_free(list);
164 if (silc_idcache_get_all(server->global_list->servers, &list) &&
165 silc_idcache_list_first(list, &cache)) {
166 silc_idlist_del_server(server->global_list, cache->context);
167 while (silc_idcache_list_next(list, &cache))
168 silc_idlist_del_server(server->global_list, cache->context);
171 silc_idcache_list_free(list);
173 silc_idcache_free(server->local_list->clients);
174 silc_idcache_free(server->local_list->servers);
175 silc_idcache_free(server->local_list->channels);
176 silc_idcache_free(server->global_list->clients);
177 silc_idcache_free(server->global_list->servers);
178 silc_idcache_free(server->global_list->channels);
179 silc_hash_table_free(server->watcher_list);
181 silc_hash_free(server->md5hash);
182 silc_hash_free(server->sha1hash);
183 silc_hmac_unregister_all();
184 silc_hash_unregister_all();
185 silc_cipher_unregister_all();
186 silc_pkcs_unregister_all();
188 silc_free(server->local_list);
189 silc_free(server->global_list);
190 silc_free(server->server_name);
191 silc_free(server->id_string);
192 silc_free(server->purge_i);
193 silc_free(server->purge_g);
197 /* Creates a new server listener. */
199 static bool silc_server_listen(SilcServer server, const char *server_ip,
200 SilcUInt16 port, int *sock)
202 *sock = silc_net_create_server(port, server_ip);
204 SILC_SERVER_LOG_ERROR(("Could not create server listener: %s on %hu",
211 /* Adds a secondary listener. */
213 bool silc_server_init_secondary(SilcServer server)
215 int sock = 0, sock_list[server->config->param.connections_max];
216 SilcSocketConnection newsocket = NULL;
217 SilcServerConfigServerInfoInterface *interface;
219 for (interface = server->config->server_info->secondary; interface;
220 interface = interface->next, sock++) {
222 if (!silc_server_listen(server,
223 interface->server_ip, interface->port, &sock_list[sock]))
226 /* Set socket to non-blocking mode */
227 silc_net_set_socket_nonblock(sock_list[sock]);
229 /* Add ourselves also to the socket table. The entry allocated above
230 is sent as argument for fast referencing in the future. */
231 silc_socket_alloc(sock_list[sock],
232 SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
233 server->sockets[sock_list[sock]] = newsocket;
234 SILC_SET_LISTENER(newsocket);
236 /* Perform name and address lookups to resolve the listenning address
238 if (!silc_net_check_local_by_sock(sock_list[sock], &newsocket->hostname,
240 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
242 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
243 newsocket->hostname ? newsocket->hostname :
244 newsocket->ip ? newsocket->ip : ""));
245 server->stat.conn_failures++;
248 if (!newsocket->hostname)
249 newsocket->hostname = strdup(newsocket->ip);
251 newsocket->port = silc_net_get_local_port(sock);
253 newsocket->user_data = (void *)server->id_entry;
254 silc_schedule_task_add(server->schedule, sock_list[sock],
255 silc_server_accept_new_connection,
256 (void *)server, 0, 0,
258 SILC_TASK_PRI_NORMAL);
264 do silc_net_close_server(sock_list[sock--]); while (sock >= 0);
268 /* Initializes the entire SILC server. This is called always before running
269 the server. This is called only once at the initialization of the program.
270 This binds the server to its listenning port. After this function returns
271 one should call silc_server_run to start the server. This returns TRUE
272 when everything is ok to run the server. Configuration file must be
273 read and parsed before calling this. */
275 bool silc_server_init(SilcServer server)
279 SilcServerEntry id_entry;
280 SilcIDListPurge purge;
281 SilcSocketConnection newsocket = NULL;
283 SILC_LOG_DEBUG(("Initializing server"));
285 server->starttime = time(NULL);
287 /* Take config object for us */
288 silc_server_config_ref(&server->config_ref, server->config,
291 /* Steal public and private key from the config object */
292 server->public_key = server->config->server_info->public_key;
293 server->private_key = server->config->server_info->private_key;
294 server->config->server_info->public_key = NULL;
295 server->config->server_info->private_key = NULL;
297 /* Register all configured ciphers, PKCS and hash functions. */
298 if (!silc_server_config_register_ciphers(server))
299 silc_cipher_register_default();
300 if (!silc_server_config_register_pkcs(server))
301 silc_pkcs_register_default();
302 if (!silc_server_config_register_hashfuncs(server))
303 silc_hash_register_default();
304 if (!silc_server_config_register_hmacs(server))
305 silc_hmac_register_default();
307 /* Initialize random number generator for the server. */
308 server->rng = silc_rng_alloc();
309 silc_rng_init(server->rng);
310 silc_rng_global_init(server->rng);
312 /* Initialize hash functions for server to use */
313 silc_hash_alloc("md5", &server->md5hash);
314 silc_hash_alloc("sha1", &server->sha1hash);
316 /* Allocate PKCS context for local public and private keys */
317 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
319 silc_pkcs_public_key_set(server->pkcs, server->public_key);
320 silc_pkcs_private_key_set(server->pkcs, server->private_key);
322 /* Initialize the scheduler */
323 server->schedule = silc_schedule_init(server->config->param.connections_max,
325 if (!server->schedule)
328 /* First, register log files configuration for error output */
329 silc_server_config_setlogfiles(server);
331 /* Initialize ID caches */
332 server->local_list->clients =
333 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
334 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
335 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
337 /* These are allocated for normal server as well as these hold some
338 global information that the server has fetched from its router. For
339 router these are used as they are supposed to be used on router. */
340 server->global_list->clients =
341 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
342 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
343 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
345 /* Init watcher list */
346 server->watcher_list =
347 silc_hash_table_alloc(1, silc_hash_client_id_hash, NULL,
348 silc_hash_data_compare, (void *)CLIENTID_HASH_LEN,
350 if (!server->watcher_list)
353 /* Create a listening server */
354 if (!silc_server_listen(server,
355 server->config->server_info->primary == NULL ? NULL :
356 server->config->server_info->primary->server_ip,
357 server->config->server_info->primary == NULL ? 0 :
358 server->config->server_info->primary->port,
362 /* Set socket to non-blocking mode */
363 silc_net_set_socket_nonblock(sock);
366 /* Allocate the entire socket list that is used in server. Eventually
367 all connections will have entry in this table (it is a table of
368 pointers to the actual object that is allocated individually
370 server->sockets = silc_calloc(server->config->param.connections_max,
371 sizeof(*server->sockets));
372 if (!server->sockets)
375 /* Add ourselves also to the socket table. The entry allocated above
376 is sent as argument for fast referencing in the future. */
377 silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
378 server->sockets[sock] = newsocket;
379 SILC_SET_LISTENER(newsocket);
381 /* Perform name and address lookups to resolve the listenning address
383 if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
385 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
387 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
388 newsocket->hostname ? newsocket->hostname :
389 newsocket->ip ? newsocket->ip : ""));
390 server->stat.conn_failures++;
393 if (!newsocket->hostname)
394 newsocket->hostname = strdup(newsocket->ip);
396 newsocket->port = silc_net_get_local_port(sock);
398 /* Create a Server ID for the server. */
399 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
404 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
405 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
406 server->server_name = server->config->server_info->server_name;
407 server->config->server_info->server_name = NULL;
409 /* Add ourselves to the server list. We don't have a router yet
410 beacuse we haven't established a route yet. It will be done later.
411 For now, NULL is sent as router. This allocates new entry to
414 silc_idlist_add_server(server->local_list, strdup(server->server_name),
415 server->server_type, server->id, NULL, NULL);
417 SILC_LOG_ERROR(("Could not add ourselves to cache"));
420 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
422 /* Put the allocated socket pointer also to the entry allocated above
423 for fast back-referencing to the socket list. */
424 newsocket->user_data = (void *)id_entry;
425 id_entry->connection = (void *)newsocket;
426 server->id_entry = id_entry;
428 /* Register protocols */
429 silc_server_protocols_register();
431 /* Add the first task to the scheduler. This is task that is executed by
432 timeout. It expires as soon as the caller calls silc_server_run. This
433 task performs authentication protocol and key exchange with our
435 silc_schedule_task_add(server->schedule, 0,
436 silc_server_connect_to_router,
437 (void *)server, 0, 1,
439 SILC_TASK_PRI_NORMAL);
441 /* Add listener task to the scheduler. This task receives new connections
442 to the server. This task remains on the queue until the end of the
444 silc_schedule_task_add(server->schedule, sock,
445 silc_server_accept_new_connection,
446 (void *)server, 0, 0,
448 SILC_TASK_PRI_NORMAL);
450 if (silc_server_init_secondary(server) == FALSE)
453 server->listenning = TRUE;
455 /* If server connections has been configured then we must be router as
456 normal server cannot have server connections, only router connections. */
457 if (server->config->servers) {
458 SilcServerConfigServer *ptr = server->config->servers;
460 server->server_type = SILC_ROUTER;
462 if (ptr->backup_router) {
463 server->server_type = SILC_BACKUP_ROUTER;
464 server->backup_router = TRUE;
465 server->id_entry->server_type = SILC_BACKUP_ROUTER;
472 /* Register the ID Cache purge task. This periodically purges the ID cache
473 and removes the expired cache entries. */
475 /* Clients local list */
476 server->purge_i = purge = silc_calloc(1, sizeof(*purge));
477 purge->cache = server->local_list->clients;
478 purge->timeout = 600;
479 silc_schedule_task_add(server->schedule, 0, silc_idlist_purge,
480 (void *)purge, purge->timeout, 0,
481 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
483 /* Clients global list */
484 server->purge_g = purge = silc_calloc(1, sizeof(*purge));
485 purge->cache = server->global_list->clients;
486 purge->timeout = 300;
487 silc_schedule_task_add(server->schedule, 0, silc_idlist_purge,
488 (void *)purge, purge->timeout, 0,
489 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
491 /* If we are normal server we'll retrieve network statisticial information
492 once in a while from the router. */
493 if (server->server_type != SILC_ROUTER)
494 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
495 server, 10, 0, SILC_TASK_TIMEOUT,
498 if (server->server_type == SILC_ROUTER)
499 server->stat.routers++;
501 SILC_LOG_DEBUG(("Server initialized"));
503 /* We are done here, return succesfully */
507 silc_server_config_unref(&server->config_ref);
508 silc_net_close_server(sock);
512 /* Task callback to close a socket connection after rehash */
514 SILC_TASK_CALLBACK(silc_server_rehash_close_connection)
516 SilcServer server = context;
517 SilcSocketConnection sock = server->sockets[fd];
522 SILC_LOG_INFO(("Connection %s:%d [%s] is unconfigured",
523 sock->hostname, sock->port,
524 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
525 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
526 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
528 silc_schedule_task_del_by_context(server->schedule, sock);
529 silc_server_disconnect_remote(server, sock,
530 SILC_STATUS_ERR_BANNED_FROM_SERVER,
531 "This connection is removed from "
534 silc_server_free_sock_user_data(server, sock, NULL);
537 /* This function basically reads the config file again and switches the config
538 object pointed by the server object. After that, we have to fix various
539 things such as the server_name and the listening ports.
540 Keep in mind that we no longer have the root privileges at this point. */
542 bool silc_server_rehash(SilcServer server)
544 SilcServerConfig newconfig;
546 SILC_LOG_INFO(("Rehashing server"));
548 /* Reset the logging system */
549 silc_log_quick = TRUE;
550 silc_log_flush_all();
552 /* Start the main rehash phase (read again the config file) */
553 newconfig = silc_server_config_alloc(server->config_file);
555 SILC_LOG_ERROR(("Rehash FAILED."));
559 /* Reinit scheduler if necessary */
560 if (newconfig->param.connections_max > server->config->param.connections_max)
561 if (!silc_schedule_reinit(server->schedule,
562 newconfig->param.connections_max))
565 /* Fix the server_name field */
566 if (strcmp(server->server_name, newconfig->server_info->server_name)) {
567 silc_free(server->server_name);
568 server->server_name = newconfig->server_info->server_name;
569 newconfig->server_info->server_name = NULL;
571 /* Update the idcache list with a fresh pointer */
572 silc_free(server->id_entry->server_name);
573 server->id_entry->server_name = strdup(server->server_name);
574 if (!silc_idcache_del_by_context(server->local_list->servers,
577 if (!silc_idcache_add(server->local_list->servers,
578 server->id_entry->server_name,
579 server->id_entry->id, server->id_entry, 0, NULL))
584 silc_server_config_setlogfiles(server);
586 /* Change new key pair if necessary */
587 if (newconfig->server_info->public_key &&
588 !silc_pkcs_public_key_compare(server->public_key,
589 newconfig->server_info->public_key)) {
590 silc_pkcs_public_key_free(server->public_key);
591 silc_pkcs_private_key_free(server->private_key);
592 server->public_key = newconfig->server_info->public_key;
593 server->private_key = newconfig->server_info->private_key;
594 newconfig->server_info->public_key = NULL;
595 newconfig->server_info->private_key = NULL;
597 /* Allocate PKCS context for local public and private keys */
598 silc_pkcs_free(server->pkcs);
599 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
601 silc_pkcs_public_key_set(server->pkcs, server->public_key);
602 silc_pkcs_private_key_set(server->pkcs, server->private_key);
605 /* Check for unconfigured server and router connections and close
606 connections that were unconfigured. */
608 if (server->config->routers) {
609 SilcServerConfigRouter *ptr;
610 SilcServerConfigRouter *newptr;
613 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
616 /* Check whether new config has this one too */
617 for (newptr = newconfig->routers; newptr; newptr = newptr->next) {
618 if (silc_string_compare(newptr->host, ptr->host) &&
619 newptr->port == ptr->port &&
620 newptr->initiator == ptr->initiator) {
626 if (!found && ptr->host) {
627 /* Remove this connection */
628 SilcSocketConnection sock;
629 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_ROUTER,
630 ptr->host, ptr->port);
631 if (sock && !SILC_IS_LISTENER(sock))
632 silc_schedule_task_add(server->schedule, sock->sock,
633 silc_server_rehash_close_connection,
634 server, 0, 1, SILC_TASK_TIMEOUT,
635 SILC_TASK_PRI_NORMAL);
640 if (server->config->servers) {
641 SilcServerConfigServer *ptr;
642 SilcServerConfigServer *newptr;
645 for (ptr = server->config->servers; ptr; ptr = ptr->next) {
648 /* Check whether new config has this one too */
649 for (newptr = newconfig->servers; newptr; newptr = newptr->next) {
650 if (silc_string_compare(newptr->host, ptr->host)) {
656 if (!found && ptr->host) {
657 /* Remove this connection */
658 SilcSocketConnection sock;
659 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_SERVER,
661 if (sock && !SILC_IS_LISTENER(sock))
662 silc_schedule_task_add(server->schedule, sock->sock,
663 silc_server_rehash_close_connection,
664 server, 0, 1, SILC_TASK_TIMEOUT,
665 SILC_TASK_PRI_NORMAL);
670 if (server->config->clients) {
671 SilcServerConfigClient *ptr;
672 SilcServerConfigClient *newptr;
675 for (ptr = server->config->clients; ptr; ptr = ptr->next) {
678 /* Check whether new config has this one too */
679 for (newptr = newconfig->clients; newptr; newptr = newptr->next) {
680 if (silc_string_compare(newptr->host, ptr->host)) {
686 if (!found && ptr->host) {
687 /* Remove this connection */
688 SilcSocketConnection sock;
689 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_CLIENT,
692 silc_schedule_task_add(server->schedule, sock->sock,
693 silc_server_rehash_close_connection,
694 server, 0, 1, SILC_TASK_TIMEOUT,
695 SILC_TASK_PRI_NORMAL);
700 /* Go through all configured routers after rehash */
701 silc_schedule_task_add(server->schedule, 0,
702 silc_server_connect_to_router,
703 (void *)server, 0, 1,
705 SILC_TASK_PRI_NORMAL);
707 /* Check whether our router status has changed */
708 if (newconfig->servers) {
709 SilcServerConfigServer *ptr = newconfig->servers;
711 server->server_type = SILC_ROUTER;
713 if (ptr->backup_router) {
714 server->server_type = SILC_BACKUP_ROUTER;
715 server->backup_router = TRUE;
716 server->id_entry->server_type = SILC_BACKUP_ROUTER;
723 /* Our old config is gone now. We'll unreference our reference made in
724 silc_server_init and then destroy it since we are destroying it
725 underneath the application (layer which called silc_server_init). */
726 silc_server_config_unref(&server->config_ref);
727 silc_server_config_destroy(server->config);
729 /* Take new config context */
730 server->config = newconfig;
731 silc_server_config_ref(&server->config_ref, server->config, server->config);
733 SILC_LOG_DEBUG(("Server rehashed"));
738 /* The heart of the server. This runs the scheduler thus runs the server.
739 When this returns the server has been stopped and the program will
742 void silc_server_run(SilcServer server)
744 SILC_LOG_INFO(("SILC Server started"));
746 /* Start the scheduler, the heart of the SILC server. When this returns
747 the program will be terminated. */
748 silc_schedule(server->schedule);
751 /* Stops the SILC server. This function is used to shutdown the server.
752 This is usually called after the scheduler has returned. After stopping
753 the server one should call silc_server_free. */
755 void silc_server_stop(SilcServer server)
757 SILC_LOG_INFO(("SILC Server shutting down"));
759 if (server->schedule) {
762 server->server_shutdown = TRUE;
764 /* Close all connections */
765 for (i = 0; i < server->config->param.connections_max; i++) {
766 if (!server->sockets[i])
768 if (!SILC_IS_LISTENER(server->sockets[i])) {
769 SilcSocketConnection sock = server->sockets[i];
770 SilcIDListData idata = sock->user_data;
773 idata->status &= ~SILC_IDLIST_STATUS_DISABLED;
775 silc_schedule_task_del_by_context(server->schedule,
777 silc_server_disconnect_remote(server, server->sockets[i],
779 "Server is shutting down");
781 silc_server_free_sock_user_data(server, sock,
782 "Server is shutting down");
783 silc_socket_free(sock);
785 silc_socket_free(server->sockets[i]);
786 server->sockets[i] = NULL;
790 /* We are not connected to network anymore */
791 server->standalone = TRUE;
793 silc_schedule_stop(server->schedule);
794 silc_schedule_uninit(server->schedule);
795 server->schedule = NULL;
797 silc_free(server->sockets);
798 server->sockets = NULL;
801 silc_server_protocols_unregister();
803 SILC_LOG_DEBUG(("Server stopped"));
806 /* Function that is called when the network connection to a router has
807 been established. This will continue with the key exchange protocol
808 with the remote router. */
810 void silc_server_start_key_exchange(SilcServer server,
811 SilcServerConnection sconn,
814 SilcSocketConnection newsocket;
815 SilcProtocol protocol;
816 SilcServerKEInternalContext *proto_ctx;
817 SilcServerConfigRouter *conn =
818 (SilcServerConfigRouter *) sconn->conn.ref_ptr;
821 /* Cancel any possible retry timeouts */
822 silc_schedule_task_del_by_callback(server->schedule,
823 silc_server_connect_to_router_retry);
825 /* Set socket options */
826 silc_net_set_socket_nonblock(sock);
827 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
829 /* Create socket connection for the connection. Even though we
830 know that we are connecting to a router we will mark the socket
831 to be unknown connection until we have executed authentication
833 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
834 server->sockets[sock] = newsocket;
835 newsocket->hostname = strdup(sconn->remote_host);
836 newsocket->ip = strdup(sconn->remote_host);
837 newsocket->port = sconn->remote_port;
838 sconn->sock = newsocket;
840 /* Allocate internal protocol context. This is sent as context
842 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
843 proto_ctx->server = (void *)server;
844 proto_ctx->context = (void *)sconn;
845 proto_ctx->sock = newsocket;
846 proto_ctx->rng = server->rng;
847 proto_ctx->responder = FALSE;
849 /* Set Key Exchange flags from configuration, but fall back to global
851 SILC_GET_SKE_FLAGS(conn, proto_ctx);
852 if (server->config->param.key_exchange_pfs)
853 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
855 /* Perform key exchange protocol. silc_server_connect_to_router_second
856 will be called after the protocol is finished. */
857 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
858 &protocol, proto_ctx,
859 silc_server_connect_to_router_second);
860 newsocket->protocol = protocol;
862 /* Register a timeout task that will be executed if the protocol
863 is not executed within set limit. */
864 proto_ctx->timeout_task =
865 silc_schedule_task_add(server->schedule, sock,
866 silc_server_timeout_remote,
867 server, server->config->key_exchange_timeout, 0,
871 /* Register the connection for network input and output. This sets
872 that scheduler will listen for incoming packets for this connection
873 and sets that outgoing packets may be sent to this connection as
874 well. However, this doesn't set the scheduler for outgoing traffic,
875 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
876 later when outgoing data is available. */
877 context = (void *)server;
878 SILC_REGISTER_CONNECTION_FOR_IO(sock);
880 /* Run the protocol */
881 silc_protocol_execute(protocol, server->schedule, 0, 0);
884 /* Timeout callback that will be called to retry connecting to remote
885 router. This is used by both normal and router server. This will wait
886 before retrying the connecting. The timeout is generated by exponential
887 backoff algorithm. */
889 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
891 SilcServer server = app_context;
892 SilcServerConnection sconn = (SilcServerConnection)context;
893 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
894 SilcServerConfigConnParams *param =
895 (conn->param ? conn->param : &server->config->param);
897 /* Don't retry if we are shutting down. */
898 if (server->server_shutdown) {
899 silc_server_config_unref(&sconn->conn);
900 silc_free(sconn->remote_host);
901 silc_free(sconn->backup_replace_ip);
906 SILC_LOG_INFO(("Retrying connecting to a router"));
908 /* Calculate next timeout */
909 if (sconn->retry_count >= 1) {
910 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
911 if (sconn->retry_timeout > param->reconnect_interval_max)
912 sconn->retry_timeout = param->reconnect_interval_max;
914 sconn->retry_timeout = param->reconnect_interval;
916 sconn->retry_count++;
917 sconn->retry_timeout = sconn->retry_timeout +
918 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
920 /* If we've reached max retry count, give up. */
921 if ((sconn->retry_count > param->reconnect_count) &&
922 !param->reconnect_keep_trying) {
923 SILC_LOG_ERROR(("Could not connect to router, giving up"));
924 silc_server_config_unref(&sconn->conn);
925 silc_free(sconn->remote_host);
926 silc_free(sconn->backup_replace_ip);
931 SILC_LOG_DEBUG(("Retrying connecting to a router in %d seconds",
932 sconn->retry_timeout));
934 /* We will lookup a fresh pointer later */
935 silc_server_config_unref(&sconn->conn);
937 /* Wait one before retrying */
938 silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
939 context, sconn->retry_timeout, 0,
940 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
943 /* Generic routine to use connect to a router. */
945 SILC_TASK_CALLBACK(silc_server_connect_router)
947 SilcServer server = app_context;
948 SilcServerConnection sconn = (SilcServerConnection)context;
949 SilcServerConfigRouter *rconn;
952 /* Don't connect if we are shutting down. */
953 if (server->server_shutdown) {
954 silc_free(sconn->remote_host);
955 silc_free(sconn->backup_replace_ip);
960 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
961 (sconn->backup ? "backup router" : "router"),
962 sconn->remote_host, sconn->remote_port));
964 server->router_connect = time(NULL);
965 rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
968 SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
969 (sconn->backup ? "backup router" : "router"),
970 sconn->remote_host, sconn->remote_port));
971 silc_free(sconn->remote_host);
972 silc_free(sconn->backup_replace_ip);
976 silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
978 /* Connect to remote host */
979 sock = silc_net_create_connection(
980 (!server->config->server_info->primary ? NULL :
981 server->config->server_info->primary->server_ip),
982 sconn->remote_port, sconn->remote_host);
984 SILC_LOG_ERROR(("Could not connect to router %s:%d",
985 sconn->remote_host, sconn->remote_port));
986 if (!sconn->no_reconnect)
987 silc_schedule_task_add(server->schedule, 0,
988 silc_server_connect_to_router_retry,
989 context, 0, 1, SILC_TASK_TIMEOUT,
990 SILC_TASK_PRI_NORMAL);
992 silc_server_config_unref(&sconn->conn);
993 silc_free(sconn->remote_host);
994 silc_free(sconn->backup_replace_ip);
1000 /* Continue with key exchange protocol */
1001 silc_server_start_key_exchange(server, sconn, sock);
1004 /* This function connects to our primary router or if we are a router this
1005 establishes all our primary routes. This is called at the start of the
1006 server to do authentication and key exchange with our router - called
1009 SILC_TASK_CALLBACK(silc_server_connect_to_router)
1011 SilcServer server = (SilcServer)context;
1012 SilcServerConnection sconn;
1013 SilcServerConfigRouter *ptr;
1015 /* Don't connect if we are shutting down. */
1016 if (server->server_shutdown)
1019 SILC_LOG_DEBUG(("We are %s",
1020 (server->server_type == SILC_SERVER ?
1021 "normal server" : server->server_type == SILC_ROUTER ?
1022 "router" : "backup router/normal server")));
1024 if (!server->config->routers) {
1025 /* There wasn't a configured router, we will continue but we don't
1026 have a connection to outside world. We will be standalone server. */
1027 SILC_LOG_DEBUG(("No router(s), we are standalone"));
1028 server->standalone = TRUE;
1032 /* Cancel any possible retry timeouts */
1033 silc_schedule_task_del_by_callback(server->schedule,
1034 silc_server_connect_router);
1035 silc_schedule_task_del_by_callback(server->schedule,
1036 silc_server_connect_to_router_retry);
1038 /* Create the connections to all our routes */
1039 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
1041 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
1042 ptr->backup_router ? "Backup router" : "Router",
1043 ptr->initiator ? "Initiator" : "Responder",
1044 ptr->host, ptr->port));
1046 if (server->server_type == SILC_ROUTER && ptr->backup_router &&
1047 ptr->initiator == FALSE && !server->backup_router &&
1048 !silc_server_config_get_backup_router(server))
1049 server->wait_backup = TRUE;
1051 if (ptr->initiator) {
1052 /* Check whether we are connected to this host already */
1053 if (silc_server_num_sockets_by_remote(server,
1054 silc_net_is_ip(ptr->host) ?
1056 silc_net_is_ip(ptr->host) ?
1057 NULL : ptr->host, ptr->port,
1058 SILC_SOCKET_TYPE_ROUTER)) {
1059 SILC_LOG_DEBUG(("We are already connected to this router"));
1063 /* Allocate connection object for hold connection specific stuff. */
1064 sconn = silc_calloc(1, sizeof(*sconn));
1065 sconn->remote_host = strdup(ptr->host);
1066 sconn->remote_port = ptr->port;
1067 sconn->backup = ptr->backup_router;
1068 if (sconn->backup) {
1069 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
1070 sconn->backup_replace_port = ptr->backup_replace_port;
1073 if (!server->router_conn && !sconn->backup)
1074 server->router_conn = sconn;
1076 silc_schedule_task_add(server->schedule, 0,
1077 silc_server_connect_router,
1078 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
1079 SILC_TASK_PRI_NORMAL);
1084 /* Second part of connecting to router(s). Key exchange protocol has been
1085 executed and now we will execute authentication protocol. */
1087 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
1089 SilcProtocol protocol = (SilcProtocol)context;
1090 SilcServerKEInternalContext *ctx =
1091 (SilcServerKEInternalContext *)protocol->context;
1092 SilcServer server = (SilcServer)ctx->server;
1093 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1094 SilcSocketConnection sock = ctx->sock;
1095 SilcServerConnAuthInternalContext *proto_ctx;
1096 SilcServerConfigRouter *conn = NULL;
1098 SILC_LOG_DEBUG(("Start"));
1100 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1101 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1102 /* Error occured during protocol */
1103 silc_protocol_free(protocol);
1104 sock->protocol = NULL;
1105 silc_ske_free_key_material(ctx->keymat);
1107 silc_packet_context_free(ctx->packet);
1109 silc_ske_free(ctx->ske);
1110 silc_free(ctx->dest_id);
1112 silc_schedule_task_del_by_callback(server->schedule,
1113 silc_server_failure_callback);
1114 silc_server_disconnect_remote(server, sock,
1115 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1117 /* Try reconnecting if configuration wants it */
1118 if (!sconn->no_reconnect) {
1119 silc_schedule_task_add(server->schedule, 0,
1120 silc_server_connect_to_router_retry,
1121 sconn, 0, 1, SILC_TASK_TIMEOUT,
1122 SILC_TASK_PRI_NORMAL);
1126 /* Call completion to indicate error */
1127 if (sconn->callback)
1128 (*sconn->callback)(server, NULL, sconn->callback_context);
1130 silc_server_config_unref(&sconn->conn);
1131 silc_free(sconn->remote_host);
1132 silc_free(sconn->backup_replace_ip);
1137 /* We now have the key material as the result of the key exchange
1138 protocol. Take the key material into use. Free the raw key material
1139 as soon as we've set them into use. */
1140 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1141 ctx->sock, ctx->keymat,
1142 ctx->ske->prop->cipher,
1143 ctx->ske->prop->pkcs,
1144 ctx->ske->prop->hash,
1145 ctx->ske->prop->hmac,
1146 ctx->ske->prop->group,
1148 silc_protocol_free(protocol);
1149 sock->protocol = NULL;
1150 silc_ske_free_key_material(ctx->keymat);
1152 silc_packet_context_free(ctx->packet);
1154 silc_ske_free(ctx->ske);
1155 silc_free(ctx->dest_id);
1157 silc_schedule_task_del_by_callback(server->schedule,
1158 silc_server_failure_callback);
1159 silc_server_disconnect_remote(server, sock,
1160 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1162 /* Try reconnecting if configuration wants it */
1163 if (!sconn->no_reconnect) {
1164 silc_schedule_task_add(server->schedule, 0,
1165 silc_server_connect_to_router_retry,
1166 sconn, 0, 1, SILC_TASK_TIMEOUT,
1167 SILC_TASK_PRI_NORMAL);
1171 /* Call completion to indicate error */
1172 if (sconn->callback)
1173 (*sconn->callback)(server, NULL, sconn->callback_context);
1175 silc_server_config_unref(&sconn->conn);
1176 silc_free(sconn->remote_host);
1177 silc_free(sconn->backup_replace_ip);
1181 silc_ske_free_key_material(ctx->keymat);
1183 /* Allocate internal context for the authentication protocol. This
1184 is sent as context for the protocol. */
1185 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1186 proto_ctx->server = (void *)server;
1187 proto_ctx->context = (void *)sconn;
1188 proto_ctx->sock = sock;
1189 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1190 proto_ctx->dest_id_type = ctx->dest_id_type;
1191 proto_ctx->dest_id = ctx->dest_id;
1193 /* Resolve the authentication method used in this connection. Check if
1194 we find a match from user configured connections */
1195 if (!sconn->conn.ref_ptr)
1196 conn = silc_server_config_find_router_conn(server, sock->hostname,
1199 conn = sconn->conn.ref_ptr;
1202 /* Match found. Use the configured authentication method. Take only
1203 the passphrase, since for public key auth we automatically use
1204 our local key pair. */
1205 if (conn->passphrase) {
1206 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
1207 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1209 proto_ctx->auth_data = strdup(conn->passphrase);
1210 proto_ctx->auth_data_len = strlen(conn->passphrase);
1211 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
1213 } else if (conn->publickeys) {
1214 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1216 proto_ctx->auth_meth = SILC_AUTH_NONE;
1219 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
1220 sock->hostname, sock->ip, sock->port));
1221 silc_protocol_free(protocol);
1222 sock->protocol = NULL;
1224 silc_packet_context_free(ctx->packet);
1226 silc_ske_free(ctx->ske);
1227 silc_free(ctx->dest_id);
1229 silc_server_config_unref(&sconn->conn);
1230 silc_free(sconn->remote_host);
1231 silc_free(sconn->backup_replace_ip);
1233 silc_schedule_task_del_by_callback(server->schedule,
1234 silc_server_failure_callback);
1235 silc_server_disconnect_remote(server, sock,
1236 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1240 /* Free old protocol as it is finished now */
1241 silc_protocol_free(protocol);
1243 silc_packet_context_free(ctx->packet);
1245 sock->protocol = NULL;
1247 /* Allocate the authentication protocol. This is allocated here
1248 but we won't start it yet. We will be receiving party of this
1249 protocol thus we will wait that connecting party will make
1250 their first move. */
1251 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1252 &sock->protocol, proto_ctx,
1253 silc_server_connect_to_router_final);
1255 /* Register timeout task. If the protocol is not executed inside
1256 this timelimit the connection will be terminated. */
1257 proto_ctx->timeout_task =
1258 silc_schedule_task_add(server->schedule, sock->sock,
1259 silc_server_timeout_remote,
1261 server->config->conn_auth_timeout, 0,
1265 /* Run the protocol */
1266 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1269 /* Finalizes the connection to router. Registers a server task to the
1270 queue so that we can accept new connections. */
1272 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
1274 SilcProtocol protocol = (SilcProtocol)context;
1275 SilcServerConnAuthInternalContext *ctx =
1276 (SilcServerConnAuthInternalContext *)protocol->context;
1277 SilcServer server = (SilcServer)ctx->server;
1278 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1279 SilcSocketConnection sock = ctx->sock;
1280 SilcServerEntry id_entry = NULL;
1282 unsigned char *id_string;
1284 SilcIDListData idata;
1285 SilcServerConfigRouter *conn = NULL;
1286 SilcServerConfigConnParams *param = NULL;
1288 SILC_LOG_DEBUG(("Start"));
1290 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1291 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1292 /* Error occured during protocol */
1293 silc_free(ctx->dest_id);
1294 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1297 /* Try reconnecting if configuration wants it */
1298 if (!sconn->no_reconnect) {
1299 silc_schedule_task_add(server->schedule, 0,
1300 silc_server_connect_to_router_retry,
1301 sconn, 0, 1, SILC_TASK_TIMEOUT,
1302 SILC_TASK_PRI_NORMAL);
1309 /* Add a task to the queue. This task receives new connections to the
1310 server. This task remains on the queue until the end of the program. */
1311 if (!server->listenning && !sconn->backup) {
1312 silc_schedule_task_add(server->schedule, server->sock,
1313 silc_server_accept_new_connection,
1314 (void *)server, 0, 0,
1316 SILC_TASK_PRI_NORMAL);
1317 server->listenning = TRUE;
1320 /* Send NEW_SERVER packet to the router. We will become registered
1321 to the SILC network after sending this packet. */
1322 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
1323 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1324 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
1325 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1326 silc_buffer_format(packet,
1327 SILC_STR_UI_SHORT(id_len),
1328 SILC_STR_UI_XNSTRING(id_string, id_len),
1329 SILC_STR_UI_SHORT(strlen(server->server_name)),
1330 SILC_STR_UI_XNSTRING(server->server_name,
1331 strlen(server->server_name)),
1334 /* Send the packet */
1335 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
1336 packet->data, packet->len, TRUE);
1337 silc_buffer_free(packet);
1338 silc_free(id_string);
1340 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
1342 /* Check that we do not have this ID already */
1343 id_entry = silc_idlist_find_server_by_id(server->local_list,
1344 ctx->dest_id, TRUE, NULL);
1346 silc_idcache_del_by_context(server->local_list->servers, id_entry);
1348 id_entry = silc_idlist_find_server_by_id(server->global_list,
1349 ctx->dest_id, TRUE, NULL);
1351 silc_idcache_del_by_context(server->global_list->servers, id_entry);
1354 SILC_LOG_DEBUG(("New server id(%s)",
1355 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1357 /* Add the connected router to global server list. Router is sent
1358 as NULL since it's local to us. */
1359 id_entry = silc_idlist_add_server(server->global_list,
1360 strdup(sock->hostname),
1361 SILC_ROUTER, ctx->dest_id, NULL, sock);
1363 silc_free(ctx->dest_id);
1364 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1365 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1370 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1371 silc_free(sock->user_data);
1372 sock->user_data = (void *)id_entry;
1373 sock->type = SILC_SOCKET_TYPE_ROUTER;
1374 idata = (SilcIDListData)sock->user_data;
1375 idata->status |= (SILC_IDLIST_STATUS_REGISTERED |
1376 SILC_IDLIST_STATUS_LOCAL);
1378 conn = sconn->conn.ref_ptr;
1379 param = &server->config->param;
1380 if (conn && conn->param)
1381 param = conn->param;
1383 /* Perform keepalive. */
1384 silc_socket_set_heartbeat(sock, param->keepalive_secs, server,
1385 silc_server_perform_heartbeat,
1388 /* Register re-key timeout */
1389 idata->rekey->timeout = param->key_exchange_rekey;
1390 silc_schedule_task_add(server->schedule, sock->sock,
1391 silc_server_rekey_callback,
1392 (void *)sock, idata->rekey->timeout, 0,
1393 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1395 if (!sconn->backup) {
1396 /* Mark this router our primary router if we're still standalone */
1397 if (server->standalone) {
1398 SILC_LOG_DEBUG(("This connection is our primary router"));
1399 server->id_entry->router = id_entry;
1400 server->router = id_entry;
1401 server->standalone = FALSE;
1403 /* If we are router then announce our possible servers. Backup
1404 router announces also global servers. */
1405 if (server->server_type == SILC_ROUTER)
1406 silc_server_announce_servers(server,
1407 server->backup_router ? TRUE : FALSE,
1408 0, SILC_PRIMARY_ROUTE(server));
1410 /* Announce our clients and channels to the router */
1411 silc_server_announce_clients(server, 0, SILC_PRIMARY_ROUTE(server));
1412 silc_server_announce_channels(server, 0, SILC_PRIMARY_ROUTE(server));
1414 /* If we are backup router then this primary router is whom we are
1416 if (server->server_type == SILC_BACKUP_ROUTER)
1417 silc_server_backup_add(server, server->id_entry, sock->ip,
1418 sconn->remote_port, TRUE);
1421 /* Add this server to be our backup router */
1422 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1423 sconn->backup_replace_port, FALSE);
1426 sock->protocol = NULL;
1429 /* Call the completion callback to indicate that we've connected to
1431 if (sconn && sconn->callback)
1432 (*sconn->callback)(server, id_entry, sconn->callback_context);
1434 /* Free the temporary connection data context */
1436 silc_server_config_unref(&sconn->conn);
1437 silc_free(sconn->remote_host);
1438 silc_free(sconn->backup_replace_ip);
1441 if (sconn == server->router_conn)
1442 server->router_conn = NULL;
1445 /* Free the protocol object */
1446 if (sock->protocol == protocol)
1447 sock->protocol = NULL;
1448 silc_protocol_free(protocol);
1450 silc_packet_context_free(ctx->packet);
1452 silc_ske_free(ctx->ske);
1453 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1454 silc_free(ctx->auth_data);
1458 /* Host lookup callback that is called after the incoming connection's
1459 IP and FQDN lookup is performed. This will actually check the acceptance
1460 of the incoming connection and will register the key exchange protocol
1461 for this connection. */
1464 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1467 SilcServerKEInternalContext *proto_ctx =
1468 (SilcServerKEInternalContext *)context;
1469 SilcServer server = (SilcServer)proto_ctx->server;
1470 SilcServerConfigClient *cconfig = NULL;
1471 SilcServerConfigServer *sconfig = NULL;
1472 SilcServerConfigRouter *rconfig = NULL;
1473 SilcServerConfigDeny *deny;
1476 /* Check whether we could resolve both IP and FQDN. */
1477 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1478 server->config->require_reverse_lookup)) {
1479 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1480 sock->hostname ? sock->hostname :
1481 sock->ip ? sock->ip : ""));
1482 server->stat.conn_failures++;
1483 silc_server_disconnect_remote(server, sock,
1484 SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
1485 "Unknown host or IP");
1486 silc_free(proto_ctx);
1490 /* Register the connection for network input and output. This sets
1491 that scheduler will listen for incoming packets for this connection
1492 and sets that outgoing packets may be sent to this connection as well.
1493 However, this doesn't set the scheduler for outgoing traffic, it
1494 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1495 later when outgoing data is available. */
1496 context = (void *)server;
1497 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1499 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1502 /* Listenning port */
1503 if (!server->sockets[(SilcUInt32)proto_ctx->context]) {
1504 silc_server_disconnect_remote(server, sock,
1505 SILC_STATUS_ERR_RESOURCE_LIMIT,
1506 "Connection refused");
1507 server->stat.conn_failures++;
1508 silc_free(proto_ctx);
1511 port = server->sockets[(SilcUInt32)proto_ctx->context]->port;
1513 /* Check whether this connection is denied to connect to us. */
1514 deny = silc_server_config_find_denied(server, sock->ip);
1516 deny = silc_server_config_find_denied(server, sock->hostname);
1518 /* The connection is denied */
1519 SILC_LOG_INFO(("Connection %s (%s) is denied",
1520 sock->hostname, sock->ip));
1521 silc_server_disconnect_remote(server, sock,
1522 SILC_STATUS_ERR_BANNED_FROM_SERVER,
1524 server->stat.conn_failures++;
1525 silc_free(proto_ctx);
1529 /* Check whether we have configured this sort of connection at all. We
1530 have to check all configurations since we don't know what type of
1531 connection this is. */
1532 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1533 cconfig = silc_server_config_find_client(server, sock->hostname);
1534 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1535 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1536 if (server->server_type == SILC_ROUTER) {
1537 if (!(rconfig = silc_server_config_find_router_conn(server,
1538 sock->ip, sock->port)))
1539 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1542 if (!cconfig && !sconfig && !rconfig) {
1543 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1545 silc_server_disconnect_remote(server, sock,
1546 SILC_STATUS_ERR_BANNED_FROM_SERVER, NULL);
1547 server->stat.conn_failures++;
1548 silc_free(proto_ctx);
1552 /* The connection is allowed */
1554 /* Set internal context for key exchange protocol. This is
1555 sent as context for the protocol. */
1556 proto_ctx->sock = sock;
1557 proto_ctx->rng = server->rng;
1558 proto_ctx->responder = TRUE;
1559 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1560 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1561 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1563 /* Take flags for key exchange. Since we do not know what type of connection
1564 this is, we go through all found configurations and use the global ones
1565 as well. This will result always into strictest key exchange flags. */
1566 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1567 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1568 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1569 if (server->config->param.key_exchange_pfs)
1570 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1572 /* Prepare the connection for key exchange protocol. We allocate the
1573 protocol but will not start it yet. The connector will be the
1574 initiator of the protocol thus we will wait for initiation from
1575 there before we start the protocol. */
1576 server->stat.auth_attempts++;
1577 SILC_LOG_DEBUG(("Starting key exchange protocol"));
1578 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1579 &sock->protocol, proto_ctx,
1580 silc_server_accept_new_connection_second);
1582 /* Register a timeout task that will be executed if the connector
1583 will not start the key exchange protocol within specified timeout
1584 and the connection will be closed. */
1585 proto_ctx->timeout_task =
1586 silc_schedule_task_add(server->schedule, sock->sock,
1587 silc_server_timeout_remote,
1589 server->config->key_exchange_timeout, 0,
1594 /* Accepts new connections to the server. Accepting new connections are
1595 done in three parts to make it async. */
1597 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1599 SilcServer server = (SilcServer)context;
1600 SilcSocketConnection newsocket;
1601 SilcServerKEInternalContext *proto_ctx;
1604 SILC_LOG_DEBUG(("Accepting new connection"));
1606 server->stat.conn_attempts++;
1608 sock = silc_net_accept_connection(fd);
1610 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1611 server->stat.conn_failures++;
1615 /* Check for maximum allowed connections */
1616 if (sock > server->config->param.connections_max) {
1617 SILC_LOG_ERROR(("Refusing connection, server is full"));
1618 server->stat.conn_failures++;
1619 silc_net_close_connection(sock);
1623 /* Set socket options */
1624 silc_net_set_socket_nonblock(sock);
1625 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1627 /* We don't create a ID yet, since we don't know what type of connection
1628 this is yet. But, we do add the connection to the socket table. */
1629 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1630 server->sockets[sock] = newsocket;
1632 /* Perform asynchronous host lookup. This will lookup the IP and the
1633 FQDN of the remote connection. After the lookup is done the connection
1634 is accepted further. */
1635 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1636 proto_ctx->server = server;
1637 proto_ctx->context = (void *)fd;
1638 silc_socket_host_lookup(newsocket, TRUE,
1639 silc_server_accept_new_connection_lookup,
1640 (void *)proto_ctx, server->schedule);
1643 /* Second part of accepting new connection. Key exchange protocol has been
1644 performed and now it is time to do little connection authentication
1645 protocol to figure out whether this connection is client or server
1646 and whether it has right to access this server (especially server
1647 connections needs to be authenticated). */
1649 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1651 SilcProtocol protocol = (SilcProtocol)context;
1652 SilcServerKEInternalContext *ctx =
1653 (SilcServerKEInternalContext *)protocol->context;
1654 SilcServer server = (SilcServer)ctx->server;
1655 SilcSocketConnection sock = ctx->sock;
1656 SilcServerConnAuthInternalContext *proto_ctx;
1658 SILC_LOG_DEBUG(("Start"));
1660 if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1661 (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1662 /* Error occured during protocol */
1663 SILC_LOG_DEBUG(("Error key exchange protocol"));
1664 silc_protocol_free(protocol);
1665 sock->protocol = NULL;
1666 silc_ske_free_key_material(ctx->keymat);
1668 silc_packet_context_free(ctx->packet);
1670 silc_ske_free(ctx->ske);
1671 silc_free(ctx->dest_id);
1672 silc_server_config_unref(&ctx->cconfig);
1673 silc_server_config_unref(&ctx->sconfig);
1674 silc_server_config_unref(&ctx->rconfig);
1676 silc_schedule_task_del_by_callback(server->schedule,
1677 silc_server_failure_callback);
1678 silc_server_disconnect_remote(server, sock,
1679 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
1681 server->stat.auth_failures++;
1685 /* We now have the key material as the result of the key exchange
1686 protocol. Take the key material into use. Free the raw key material
1687 as soon as we've set them into use. */
1688 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1689 ctx->sock, ctx->keymat,
1690 ctx->ske->prop->cipher,
1691 ctx->ske->prop->pkcs,
1692 ctx->ske->prop->hash,
1693 ctx->ske->prop->hmac,
1694 ctx->ske->prop->group,
1696 SILC_LOG_ERROR(("Error setting key material in use"));
1697 silc_protocol_free(protocol);
1698 sock->protocol = NULL;
1699 silc_ske_free_key_material(ctx->keymat);
1701 silc_packet_context_free(ctx->packet);
1703 silc_ske_free(ctx->ske);
1704 silc_free(ctx->dest_id);
1705 silc_server_config_unref(&ctx->cconfig);
1706 silc_server_config_unref(&ctx->sconfig);
1707 silc_server_config_unref(&ctx->rconfig);
1709 silc_schedule_task_del_by_callback(server->schedule,
1710 silc_server_failure_callback);
1711 silc_server_disconnect_remote(server, sock,
1712 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1713 server->stat.auth_failures++;
1716 silc_ske_free_key_material(ctx->keymat);
1718 /* Allocate internal context for the authentication protocol. This
1719 is sent as context for the protocol. */
1720 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1721 proto_ctx->server = (void *)server;
1722 proto_ctx->sock = sock;
1723 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1724 proto_ctx->responder = TRUE;
1725 proto_ctx->dest_id_type = ctx->dest_id_type;
1726 proto_ctx->dest_id = ctx->dest_id;
1727 proto_ctx->cconfig = ctx->cconfig;
1728 proto_ctx->sconfig = ctx->sconfig;
1729 proto_ctx->rconfig = ctx->rconfig;
1731 /* Free old protocol as it is finished now */
1732 silc_protocol_free(protocol);
1734 silc_packet_context_free(ctx->packet);
1736 sock->protocol = NULL;
1738 /* Allocate the authentication protocol. This is allocated here
1739 but we won't start it yet. We will be receiving party of this
1740 protocol thus we will wait that connecting party will make
1741 their first move. */
1742 SILC_LOG_DEBUG(("Starting connection authentication protocol"));
1743 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1744 &sock->protocol, proto_ctx,
1745 silc_server_accept_new_connection_final);
1747 /* Register timeout task. If the protocol is not executed inside
1748 this timelimit the connection will be terminated. */
1749 proto_ctx->timeout_task =
1750 silc_schedule_task_add(server->schedule, sock->sock,
1751 silc_server_timeout_remote,
1753 server->config->conn_auth_timeout, 0,
1758 /* After this is called, server don't wait for backup router anymore.
1759 This gets called automatically even after we have backup router
1760 connection established. */
1762 SILC_TASK_CALLBACK(silc_server_backup_router_wait)
1764 SilcServer server = context;
1765 server->wait_backup = FALSE;
1768 /* Final part of accepting new connection. The connection has now
1769 been authenticated and keys has been exchanged. We also know whether
1770 this is client or server connection. */
1772 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1774 SilcProtocol protocol = (SilcProtocol)context;
1775 SilcServerConnAuthInternalContext *ctx =
1776 (SilcServerConnAuthInternalContext *)protocol->context;
1777 SilcServer server = (SilcServer)ctx->server;
1778 SilcSocketConnection sock = ctx->sock;
1779 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1781 SilcServerConfigConnParams *param = &server->config->param;
1783 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1784 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1785 /* Error occured during protocol */
1786 SILC_LOG_DEBUG(("Error during authentication protocol"));
1787 silc_protocol_free(protocol);
1788 sock->protocol = NULL;
1790 silc_packet_context_free(ctx->packet);
1792 silc_ske_free(ctx->ske);
1793 silc_free(ctx->dest_id);
1794 silc_server_config_unref(&ctx->cconfig);
1795 silc_server_config_unref(&ctx->sconfig);
1796 silc_server_config_unref(&ctx->rconfig);
1798 silc_schedule_task_del_by_callback(server->schedule,
1799 silc_server_failure_callback);
1800 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1802 server->stat.auth_failures++;
1806 entry->data.last_receive = time(NULL);
1808 switch (ctx->conn_type) {
1809 case SILC_SOCKET_TYPE_CLIENT:
1811 SilcClientEntry client;
1812 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1814 /* Verify whether this connection is after all allowed to connect */
1815 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1816 &server->config->param,
1817 conn->param, ctx->ske)) {
1818 server->stat.auth_failures++;
1822 /* If we are primary router and we have backup router configured
1823 but it has not connected to use yet, do not accept any other
1825 if (server->wait_backup && server->server_type == SILC_ROUTER &&
1826 !server->backup_router) {
1827 SilcServerConfigRouter *router;
1828 router = silc_server_config_get_backup_router(server);
1829 if (router && strcmp(server->config->server_info->primary->server_ip,
1831 silc_server_find_socket_by_host(server,
1832 SILC_SOCKET_TYPE_SERVER,
1833 router->backup_replace_ip, 0)) {
1834 SILC_LOG_INFO(("Will not accept connections because we do "
1835 "not have backup router connection established"));
1836 silc_server_disconnect_remote(server, sock,
1837 SILC_STATUS_ERR_PERM_DENIED,
1838 "We do not have connection to backup "
1839 "router established, try later");
1840 silc_free(sock->user_data);
1841 server->stat.auth_failures++;
1843 /* From here on, wait 10 seconds for the backup router to appear. */
1844 silc_schedule_task_add(server->schedule, 0,
1845 silc_server_backup_router_wait,
1846 (void *)server, 10, 0,
1847 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1852 SILC_LOG_DEBUG(("Remote host is client"));
1853 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1856 /* Add the client to the client ID cache. The nickname and Client ID
1857 and other information is created after we have received NEW_CLIENT
1858 packet from client. */
1859 client = silc_idlist_add_client(server->local_list,
1860 NULL, NULL, NULL, NULL, NULL, sock, 0);
1862 SILC_LOG_ERROR(("Could not add new client to cache"));
1863 silc_free(sock->user_data);
1864 silc_server_disconnect_remote(server, sock,
1865 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1866 server->stat.auth_failures++;
1869 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
1872 server->stat.my_clients++;
1873 server->stat.clients++;
1874 server->stat.cell_clients++;
1876 /* Get connection parameters */
1878 param = conn->param;
1880 if (!param->keepalive_secs)
1881 param->keepalive_secs = server->config->param.keepalive_secs;
1883 if (!param->qos && server->config->param.qos) {
1884 param->qos = server->config->param.qos;
1885 param->qos_rate_limit = server->config->param.qos_rate_limit;
1886 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
1887 param->qos_limit_sec = server->config->param.qos_limit_sec;
1888 param->qos_limit_usec = server->config->param.qos_limit_usec;
1891 /* Check if to be anonymous connection */
1892 if (param->anonymous)
1893 client->mode |= SILC_UMODE_ANONYMOUS;
1896 id_entry = (void *)client;
1899 case SILC_SOCKET_TYPE_SERVER:
1900 case SILC_SOCKET_TYPE_ROUTER:
1902 SilcServerEntry new_server;
1903 bool initiator = FALSE;
1904 bool backup_local = FALSE;
1905 bool backup_router = FALSE;
1906 char *backup_replace_ip = NULL;
1907 SilcUInt16 backup_replace_port = 0;
1908 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1909 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1911 /* If we are backup router and this is incoming server connection
1912 and we do not have connection to primary router, do not allow
1914 if (server->server_type == SILC_BACKUP_ROUTER &&
1915 ctx->conn_type == SILC_SOCKET_TYPE_SERVER &&
1916 !SILC_PRIMARY_ROUTE(server)) {
1917 SILC_LOG_INFO(("Will not accept server connection because we do "
1918 "not have primary router connection established"));
1919 silc_server_disconnect_remote(server, sock,
1920 SILC_STATUS_ERR_PERM_DENIED,
1921 "We do not have connection to primary "
1922 "router established, try later");
1923 silc_free(sock->user_data);
1924 server->stat.auth_failures++;
1928 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1929 /* Verify whether this connection is after all allowed to connect */
1930 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1931 &server->config->param,
1932 rconn ? rconn->param : NULL,
1934 silc_free(sock->user_data);
1935 server->stat.auth_failures++;
1941 param = rconn->param;
1943 if (!param->keepalive_secs)
1944 param->keepalive_secs = server->config->param.keepalive_secs;
1946 if (!param->qos && server->config->param.qos) {
1947 param->qos = server->config->param.qos;
1948 param->qos_rate_limit = server->config->param.qos_rate_limit;
1949 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
1950 param->qos_limit_sec = server->config->param.qos_limit_sec;
1951 param->qos_limit_usec = server->config->param.qos_limit_usec;
1955 initiator = rconn->initiator;
1956 backup_local = rconn->backup_local;
1957 backup_router = rconn->backup_router;
1958 backup_replace_ip = rconn->backup_replace_ip;
1959 backup_replace_port = rconn->backup_replace_port;
1963 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1964 /* Verify whether this connection is after all allowed to connect */
1965 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1966 &server->config->param,
1967 sconn ? sconn->param : NULL,
1969 silc_free(sock->user_data);
1970 server->stat.auth_failures++;
1975 param = sconn->param;
1977 if (!param->keepalive_secs)
1978 param->keepalive_secs = server->config->param.keepalive_secs;
1980 if (!param->qos && server->config->param.qos) {
1981 param->qos = server->config->param.qos;
1982 param->qos_rate_limit = server->config->param.qos_rate_limit;
1983 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
1984 param->qos_limit_sec = server->config->param.qos_limit_sec;
1985 param->qos_limit_usec = server->config->param.qos_limit_usec;
1989 backup_router = sconn->backup_router;
1993 /* If we are primary router and we have backup router configured
1994 but it has not connected to use yet, do not accept any other
1996 if (server->wait_backup && server->server_type == SILC_ROUTER &&
1997 !server->backup_router && !backup_router) {
1998 SilcServerConfigRouter *router;
1999 router = silc_server_config_get_backup_router(server);
2000 if (router && strcmp(server->config->server_info->primary->server_ip,
2002 silc_server_find_socket_by_host(server,
2003 SILC_SOCKET_TYPE_SERVER,
2004 router->backup_replace_ip, 0)) {
2005 SILC_LOG_INFO(("Will not accept connections because we do "
2006 "not have backup router connection established"));
2007 silc_server_disconnect_remote(server, sock,
2008 SILC_STATUS_ERR_PERM_DENIED,
2009 "We do not have connection to backup "
2010 "router established, try later");
2011 silc_free(sock->user_data);
2012 server->stat.auth_failures++;
2014 /* From here on, wait 10 seconds for the backup router to appear. */
2015 silc_schedule_task_add(server->schedule, 0,
2016 silc_server_backup_router_wait,
2017 (void *)server, 10, 0,
2018 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2023 SILC_LOG_DEBUG(("Remote host is %s",
2024 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2025 "server" : (backup_router ?
2026 "backup router" : "router")));
2027 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
2028 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2029 "server" : (backup_router ?
2030 "backup router" : "router")));
2032 /* Add the server into server cache. The server name and Server ID
2033 is updated after we have received NEW_SERVER packet from the
2034 server. We mark ourselves as router for this server if we really
2037 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2038 server->local_list : (backup_router ?
2039 server->local_list :
2040 server->global_list)),
2042 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2043 SILC_SERVER : SILC_ROUTER),
2045 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2046 server->id_entry : (backup_router ?
2047 server->id_entry : NULL)),
2050 SILC_LOG_ERROR(("Could not add new server to cache"));
2051 silc_free(sock->user_data);
2052 silc_server_disconnect_remote(server, sock,
2053 SILC_STATUS_ERR_AUTH_FAILED, NULL);
2054 server->stat.auth_failures++;
2057 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
2059 id_entry = (void *)new_server;
2061 /* If the incoming connection is router and marked as backup router
2062 then add it to be one of our backups */
2063 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
2064 /* Change it back to SERVER type since that's what it really is. */
2066 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
2067 new_server->server_type = SILC_BACKUP_ROUTER;
2069 /* Remove the backup waiting with timeout */
2070 silc_schedule_task_add(server->schedule, 0,
2071 silc_server_backup_router_wait,
2072 (void *)server, 5, 0,
2073 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2077 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
2078 server->stat.my_servers++;
2080 server->stat.my_routers++;
2081 server->stat.routers++;
2083 server->stat.servers++;
2085 /* Check whether this connection is to be our primary router connection
2086 if we do not already have the primary route. */
2087 if (!backup_router &&
2088 server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
2089 if (silc_server_config_is_primary_route(server) && !initiator)
2092 SILC_LOG_DEBUG(("We are not standalone server anymore"));
2093 server->standalone = FALSE;
2094 if (!server->id_entry->router) {
2095 server->id_entry->router = id_entry;
2096 server->router = id_entry;
2107 sock->type = ctx->conn_type;
2109 /* Add the common data structure to the ID entry. */
2110 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
2112 /* Add to sockets internal pointer for fast referencing */
2113 silc_free(sock->user_data);
2114 sock->user_data = id_entry;
2116 /* Connection has been fully established now. Everything is ok. */
2117 SILC_LOG_DEBUG(("New connection authenticated"));
2119 /* Perform keepalive. */
2120 if (param->keepalive_secs)
2121 silc_socket_set_heartbeat(sock, param->keepalive_secs, server,
2122 silc_server_perform_heartbeat,
2125 /* Perform Quality of Service */
2127 silc_socket_set_qos(sock, param->qos_rate_limit, param->qos_bytes_limit,
2128 param->qos_limit_sec, param->qos_limit_usec,
2132 silc_schedule_task_del_by_callback(server->schedule,
2133 silc_server_failure_callback);
2134 silc_protocol_free(protocol);
2136 silc_packet_context_free(ctx->packet);
2138 silc_ske_free(ctx->ske);
2139 silc_free(ctx->dest_id);
2140 silc_server_config_unref(&ctx->cconfig);
2141 silc_server_config_unref(&ctx->sconfig);
2142 silc_server_config_unref(&ctx->rconfig);
2144 sock->protocol = NULL;
2147 /* This function is used to read packets from network and send packets to
2148 network. This is usually a generic task. */
2150 SILC_TASK_CALLBACK(silc_server_packet_process)
2152 SilcServer server = (SilcServer)context;
2153 SilcSocketConnection sock = server->sockets[fd];
2154 SilcIDListData idata;
2155 SilcCipher cipher = NULL;
2156 SilcHmac hmac = NULL;
2157 SilcUInt32 sequence = 0;
2161 SILC_LOG_DEBUG(("Unknown socket connection"));
2165 /* Packet sending */
2167 if (type == SILC_TASK_WRITE) {
2168 /* Do not send data to disconnected connection */
2169 if (SILC_IS_DISCONNECTED(sock)) {
2170 SILC_LOG_DEBUG(("Disconnected socket connection, cannot send"));
2174 server->stat.packets_sent++;
2176 /* Send the packet */
2177 ret = silc_packet_send(sock, TRUE);
2179 /* If returned -2 could not write to connection now, will do
2185 SILC_LOG_ERROR(("Error sending packet to connection "
2186 "%s:%d [%s]", sock->hostname, sock->port,
2187 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2188 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2189 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2194 /* The packet has been sent and now it is time to set the connection
2195 back to only for input. When there is again some outgoing data
2196 available for this connection it will be set for output as well.
2197 This call clears the output setting and sets it only for input. */
2198 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
2199 SILC_UNSET_OUTBUF_PENDING(sock);
2201 silc_buffer_clear(sock->outbuf);
2205 /* Packet receiving */
2207 /* Read some data from connection */
2208 ret = silc_packet_receive(sock);
2212 SILC_LOG_ERROR(("Error receiving packet from connection "
2213 "%s:%d [%s] %s", sock->hostname, sock->port,
2214 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2215 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2216 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2217 "Router"), strerror(errno)));
2223 SILC_LOG_DEBUG(("Read EOF"));
2225 /* If connection is disconnecting already we will finally
2226 close the connection */
2227 if (SILC_IS_DISCONNECTING(sock)) {
2228 if (sock->user_data)
2229 silc_server_free_sock_user_data(server, sock, NULL);
2230 silc_server_close_connection(server, sock);
2234 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
2235 SILC_SET_DISCONNECTING(sock);
2237 if (sock->user_data) {
2239 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
2240 silc_server_free_sock_user_data(server, sock, tmp);
2242 silc_server_free_sock_user_data(server, sock, NULL);
2243 } else if (server->router_conn && server->router_conn->sock == sock &&
2244 !server->router && server->standalone)
2245 silc_schedule_task_add(server->schedule, 0,
2246 silc_server_connect_to_router,
2249 SILC_TASK_PRI_NORMAL);
2251 silc_server_close_connection(server, sock);
2255 /* If connection is disconnecting or disconnected we will ignore
2257 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2258 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
2262 /* Get keys and stuff from ID entry */
2263 idata = (SilcIDListData)sock->user_data;
2265 cipher = idata->receive_key;
2266 hmac = idata->hmac_receive;
2267 sequence = idata->psn_receive;
2270 /* Process the packet. This will call the parser that will then
2271 decrypt and parse the packet. */
2272 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
2273 TRUE : FALSE, cipher, hmac, sequence,
2274 silc_server_packet_parse, server);
2276 /* If processing failed the connection is closed. */
2278 /* On packet processing errors we may close our primary router
2279 connection but won't become primary router if we are the backup
2280 since this is local error condition. */
2281 if (SILC_PRIMARY_ROUTE(server) == sock && server->backup_router)
2282 server->backup_noswitch = TRUE;
2284 if (sock->user_data)
2285 silc_server_free_sock_user_data(server, sock, NULL);
2286 silc_server_close_connection(server, sock);
2290 /* Parses whole packet, received earlier. */
2292 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
2294 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
2295 SilcServer server = (SilcServer)parse_ctx->context;
2296 SilcSocketConnection sock = parse_ctx->sock;
2297 SilcPacketContext *packet = parse_ctx->packet;
2298 SilcIDListData idata = (SilcIDListData)sock->user_data;
2301 server->stat.packets_received++;
2303 /* Parse the packet */
2304 if (parse_ctx->normal)
2305 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
2307 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
2309 /* If entry is disabled ignore what we got. */
2310 if (idata && idata->status & SILC_IDLIST_STATUS_DISABLED &&
2311 ret != SILC_PACKET_HEARTBEAT && ret != SILC_PACKET_RESUME_ROUTER &&
2312 ret != SILC_PACKET_REKEY && ret != SILC_PACKET_REKEY_DONE) {
2313 SILC_LOG_DEBUG(("Connection is disabled"));
2317 if (ret == SILC_PACKET_NONE) {
2318 SILC_LOG_DEBUG(("Error parsing packet"));
2322 /* Check that the the current client ID is same as in the client's packet. */
2323 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
2324 SilcClientEntry client = (SilcClientEntry)sock->user_data;
2325 if (client && client->id && packet->src_id) {
2326 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
2327 packet->src_id_type);
2328 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
2330 SILC_LOG_DEBUG(("Packet source is not same as sender"));
2337 if (server->server_type == SILC_ROUTER) {
2338 /* Route the packet if it is not destined to us. Other ID types but
2339 server are handled separately after processing them. */
2340 if (packet->dst_id && !(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
2341 packet->dst_id_type == SILC_ID_SERVER &&
2342 sock->type != SILC_SOCKET_TYPE_CLIENT &&
2343 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
2345 /* Route the packet to fastest route for the destination ID */
2346 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
2347 packet->dst_id_type);
2350 silc_server_packet_route(server,
2351 silc_server_route_get(server, id,
2352 packet->dst_id_type),
2359 /* Parse the incoming packet type */
2360 silc_server_packet_parse_type(server, sock, packet);
2362 /* Broadcast packet if it is marked as broadcast packet and it is
2363 originated from router and we are router. */
2364 if (server->server_type == SILC_ROUTER &&
2365 sock->type == SILC_SOCKET_TYPE_ROUTER &&
2366 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
2367 /* Broadcast to our primary route */
2368 silc_server_packet_broadcast(server, SILC_PRIMARY_ROUTE(server), packet);
2370 /* If we have backup routers then we need to feed all broadcast
2371 data to those servers. */
2372 silc_server_backup_broadcast(server, sock, packet);
2376 silc_packet_context_free(packet);
2377 silc_free(parse_ctx);
2380 /* Parser callback called by silc_packet_receive_process. This merely
2381 registers timeout that will handle the actual parsing when appropriate. */
2383 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
2386 SilcServer server = (SilcServer)context;
2387 SilcSocketConnection sock = parser_context->sock;
2388 SilcIDListData idata = (SilcIDListData)sock->user_data;
2392 idata->psn_receive = parser_context->packet->sequence + 1;
2394 /* If protocol for this connection is key exchange or rekey then we'll
2395 process all packets synchronously, since there might be packets in
2396 queue that we are not able to decrypt without first processing the
2397 packets before them. */
2398 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
2399 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
2400 (sock->protocol && sock->protocol->protocol &&
2401 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2402 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
2403 silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2406 /* Reprocess data since we'll return FALSE here. This is because
2407 the idata->receive_key might have become valid in the last packet
2408 and we want to call this processor with valid cipher. */
2410 ret = silc_packet_receive_process(
2411 sock, server->server_type == SILC_ROUTER ?
2412 TRUE : FALSE, idata->receive_key,
2413 idata->hmac_receive, idata->psn_receive,
2414 silc_server_packet_parse, server);
2416 ret = silc_packet_receive_process(
2417 sock, server->server_type == SILC_ROUTER ?
2418 TRUE : FALSE, NULL, NULL, 0,
2419 silc_server_packet_parse, server);
2422 /* On packet processing errors we may close our primary router
2423 connection but won't become primary router if we are the backup
2424 since this is local error condition. */
2425 if (SILC_PRIMARY_ROUTE(server) == sock && server->backup_router)
2426 server->backup_noswitch = TRUE;
2428 if (sock->user_data)
2429 silc_server_free_sock_user_data(server, sock, NULL);
2430 silc_server_close_connection(server, sock);
2436 switch (sock->type) {
2437 case SILC_SOCKET_TYPE_UNKNOWN:
2438 case SILC_SOCKET_TYPE_CLIENT:
2439 /* Parse the packet with timeout */
2440 silc_schedule_task_add(server->schedule, sock->sock,
2441 silc_server_packet_parse_real,
2442 (void *)parser_context, 0, 100000,
2444 SILC_TASK_PRI_NORMAL);
2446 case SILC_SOCKET_TYPE_SERVER:
2447 case SILC_SOCKET_TYPE_ROUTER:
2448 /* Packets from servers are parsed immediately */
2449 silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2459 /* Parses the packet type and calls what ever routines the packet type
2460 requires. This is done for all incoming packets. */
2462 void silc_server_packet_parse_type(SilcServer server,
2463 SilcSocketConnection sock,
2464 SilcPacketContext *packet)
2466 SilcPacketType type = packet->type;
2467 SilcIDListData idata = (SilcIDListData)sock->user_data;
2469 SILC_LOG_DEBUG(("Received %s packet [flags %d]",
2470 silc_get_packet_name(type), packet->flags));
2472 /* Parse the packet type */
2474 case SILC_PACKET_DISCONNECT:
2477 char *message = NULL;
2479 if (packet->flags & SILC_PACKET_FLAG_LIST)
2481 if (packet->buffer->len < 1)
2484 status = (SilcStatus)packet->buffer->data[0];
2485 if (packet->buffer->len > 1 &&
2486 silc_utf8_valid(packet->buffer->data + 1, packet->buffer->len - 1))
2487 message = silc_memdup(packet->buffer->data + 1,
2488 packet->buffer->len - 1);
2490 SILC_LOG_INFO(("Disconnected by %s (%s): %s (%d) %s",
2491 sock->ip, sock->hostname,
2492 silc_get_status_message(status), status,
2493 message ? message : ""));
2496 /* Handle the disconnection from our end too */
2497 if (sock->user_data && SILC_IS_LOCAL(sock->user_data))
2498 silc_server_free_sock_user_data(server, sock, NULL);
2499 silc_server_close_connection(server, sock);
2503 case SILC_PACKET_SUCCESS:
2505 * Success received for something. For now we can have only
2506 * one protocol for connection executing at once hence this
2507 * success message is for whatever protocol is executing currently.
2509 if (packet->flags & SILC_PACKET_FLAG_LIST)
2512 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2515 case SILC_PACKET_FAILURE:
2517 * Failure received for something. For now we can have only
2518 * one protocol for connection executing at once hence this
2519 * failure message is for whatever protocol is executing currently.
2521 if (packet->flags & SILC_PACKET_FLAG_LIST)
2523 if (sock->protocol) {
2524 SilcServerFailureContext f;
2525 f = silc_calloc(1, sizeof(*f));
2526 f->sock = silc_socket_dup(sock);
2528 /* We will wait 5 seconds to process this failure packet */
2529 silc_schedule_task_add(server->schedule, sock->sock,
2530 silc_server_failure_callback, (void *)f, 5, 0,
2531 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2535 case SILC_PACKET_REJECT:
2536 if (packet->flags & SILC_PACKET_FLAG_LIST)
2541 case SILC_PACKET_NOTIFY:
2543 * Received notify packet. Server can receive notify packets from
2544 * router. Server then relays the notify messages to clients if needed.
2546 if (packet->flags & SILC_PACKET_FLAG_LIST)
2547 silc_server_notify_list(server, sock, packet);
2549 silc_server_notify(server, sock, packet);
2555 case SILC_PACKET_CHANNEL_MESSAGE:
2557 * Received channel message. Channel messages are special packets
2558 * (although probably most common ones) thus they are handled
2561 if (packet->flags & SILC_PACKET_FLAG_LIST)
2563 idata->last_receive = time(NULL);
2564 silc_server_channel_message(server, sock, packet);
2567 case SILC_PACKET_CHANNEL_KEY:
2569 * Received key for channel. As channels are created by the router
2570 * the keys are as well. We will distribute the key to all of our
2571 * locally connected clients on the particular channel. Router
2572 * never receives this channel and thus is ignored.
2574 if (packet->flags & SILC_PACKET_FLAG_LIST)
2576 silc_server_channel_key(server, sock, packet);
2582 case SILC_PACKET_COMMAND:
2584 * Recived command. Processes the command request and allocates the
2585 * command context and calls the command.
2587 if (packet->flags & SILC_PACKET_FLAG_LIST)
2589 silc_server_command_process(server, sock, packet);
2592 case SILC_PACKET_COMMAND_REPLY:
2594 * Received command reply packet. Received command reply to command. It
2595 * may be reply to command sent by us or reply to command sent by client
2596 * that we've routed further.
2598 if (packet->flags & SILC_PACKET_FLAG_LIST)
2600 silc_server_command_reply(server, sock, packet);
2604 * Private Message packets
2606 case SILC_PACKET_PRIVATE_MESSAGE:
2608 * Received private message packet. The packet is coming from either
2611 if (packet->flags & SILC_PACKET_FLAG_LIST)
2613 idata->last_receive = time(NULL);
2614 silc_server_private_message(server, sock, packet);
2617 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2619 * Private message key packet.
2621 if (packet->flags & SILC_PACKET_FLAG_LIST)
2623 silc_server_private_message_key(server, sock, packet);
2627 * Key Exchange protocol packets
2629 case SILC_PACKET_KEY_EXCHANGE:
2630 if (packet->flags & SILC_PACKET_FLAG_LIST)
2633 if (sock->protocol && sock->protocol->protocol &&
2634 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2635 SilcServerKEInternalContext *proto_ctx =
2636 (SilcServerKEInternalContext *)sock->protocol->context;
2638 proto_ctx->packet = silc_packet_context_dup(packet);
2640 /* Let the protocol handle the packet */
2641 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2643 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2644 "protocol active, packet dropped."));
2648 case SILC_PACKET_KEY_EXCHANGE_1:
2649 if (packet->flags & SILC_PACKET_FLAG_LIST)
2652 if (sock->protocol && sock->protocol->protocol &&
2653 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2654 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2656 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2657 SilcServerRekeyInternalContext *proto_ctx =
2658 (SilcServerRekeyInternalContext *)sock->protocol->context;
2660 if (proto_ctx->packet)
2661 silc_packet_context_free(proto_ctx->packet);
2663 proto_ctx->packet = silc_packet_context_dup(packet);
2665 /* Let the protocol handle the packet */
2666 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2668 SilcServerKEInternalContext *proto_ctx =
2669 (SilcServerKEInternalContext *)sock->protocol->context;
2671 if (proto_ctx->packet)
2672 silc_packet_context_free(proto_ctx->packet);
2674 proto_ctx->packet = silc_packet_context_dup(packet);
2675 proto_ctx->dest_id_type = packet->src_id_type;
2676 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2677 packet->src_id_type);
2678 if (!proto_ctx->dest_id)
2681 /* Let the protocol handle the packet */
2682 silc_protocol_execute(sock->protocol, server->schedule,
2686 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2687 "protocol active, packet dropped."));
2691 case SILC_PACKET_KEY_EXCHANGE_2:
2692 if (packet->flags & SILC_PACKET_FLAG_LIST)
2695 if (sock->protocol && sock->protocol->protocol &&
2696 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2697 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2699 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2700 SilcServerRekeyInternalContext *proto_ctx =
2701 (SilcServerRekeyInternalContext *)sock->protocol->context;
2703 if (proto_ctx->packet)
2704 silc_packet_context_free(proto_ctx->packet);
2706 proto_ctx->packet = silc_packet_context_dup(packet);
2708 /* Let the protocol handle the packet */
2709 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2711 SilcServerKEInternalContext *proto_ctx =
2712 (SilcServerKEInternalContext *)sock->protocol->context;
2714 if (proto_ctx->packet)
2715 silc_packet_context_free(proto_ctx->packet);
2717 proto_ctx->packet = silc_packet_context_dup(packet);
2718 proto_ctx->dest_id_type = packet->src_id_type;
2719 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2720 packet->src_id_type);
2721 if (!proto_ctx->dest_id)
2724 /* Let the protocol handle the packet */
2725 silc_protocol_execute(sock->protocol, server->schedule,
2729 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2730 "protocol active, packet dropped."));
2734 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2736 * Connection authentication request packet. When we receive this packet
2737 * we will send to the other end information about our mandatory
2738 * authentication method for the connection. This packet maybe received
2741 if (packet->flags & SILC_PACKET_FLAG_LIST)
2743 silc_server_connection_auth_request(server, sock, packet);
2747 * Connection Authentication protocol packets
2749 case SILC_PACKET_CONNECTION_AUTH:
2750 /* Start of the authentication protocol. We receive here the
2751 authentication data and will verify it. */
2752 if (packet->flags & SILC_PACKET_FLAG_LIST)
2755 if (sock->protocol && sock->protocol->protocol->type
2756 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2758 SilcServerConnAuthInternalContext *proto_ctx =
2759 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2761 proto_ctx->packet = silc_packet_context_dup(packet);
2763 /* Let the protocol handle the packet */
2764 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2766 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2767 "protocol active, packet dropped."));
2771 case SILC_PACKET_NEW_ID:
2773 * Received New ID packet. This includes some new ID that has been
2774 * created. It may be for client, server or channel. This is the way
2775 * to distribute information about new registered entities in the
2778 if (packet->flags & SILC_PACKET_FLAG_LIST)
2779 silc_server_new_id_list(server, sock, packet);
2781 silc_server_new_id(server, sock, packet);
2784 case SILC_PACKET_NEW_CLIENT:
2786 * Received new client packet. This includes client information that
2787 * we will use to create initial client ID. After creating new
2788 * ID we will send it to the client.
2790 if (packet->flags & SILC_PACKET_FLAG_LIST)
2792 silc_server_new_client(server, sock, packet);
2795 case SILC_PACKET_NEW_SERVER:
2797 * Received new server packet. This includes Server ID and some other
2798 * information that we may save. This is received after server has
2801 if (packet->flags & SILC_PACKET_FLAG_LIST)
2803 silc_server_new_server(server, sock, packet);
2806 case SILC_PACKET_NEW_CHANNEL:
2808 * Received new channel packet. Information about new channel in the
2809 * network are distributed using this packet.
2811 if (packet->flags & SILC_PACKET_FLAG_LIST)
2812 silc_server_new_channel_list(server, sock, packet);
2814 silc_server_new_channel(server, sock, packet);
2817 case SILC_PACKET_HEARTBEAT:
2819 * Received heartbeat.
2821 if (packet->flags & SILC_PACKET_FLAG_LIST)
2825 case SILC_PACKET_KEY_AGREEMENT:
2827 * Received heartbeat.
2829 if (packet->flags & SILC_PACKET_FLAG_LIST)
2831 silc_server_key_agreement(server, sock, packet);
2834 case SILC_PACKET_REKEY:
2836 * Received re-key packet. The sender wants to regenerate the session
2839 if (packet->flags & SILC_PACKET_FLAG_LIST)
2841 silc_server_rekey(server, sock, packet);
2844 case SILC_PACKET_REKEY_DONE:
2846 * The re-key is done.
2848 if (packet->flags & SILC_PACKET_FLAG_LIST)
2851 if (sock->protocol && sock->protocol->protocol &&
2852 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2854 SilcServerRekeyInternalContext *proto_ctx =
2855 (SilcServerRekeyInternalContext *)sock->protocol->context;
2857 if (proto_ctx->packet)
2858 silc_packet_context_free(proto_ctx->packet);
2860 proto_ctx->packet = silc_packet_context_dup(packet);
2862 /* Let the protocol handle the packet */
2863 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2865 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2866 "protocol active, packet dropped."));
2870 case SILC_PACKET_FTP:
2872 if (packet->flags & SILC_PACKET_FLAG_LIST)
2874 silc_server_ftp(server, sock, packet);
2877 case SILC_PACKET_RESUME_CLIENT:
2879 if (packet->flags & SILC_PACKET_FLAG_LIST)
2881 silc_server_resume_client(server, sock, packet);
2884 case SILC_PACKET_RESUME_ROUTER:
2885 /* Resume router packet received. This packet is received for backup
2886 router resuming protocol. */
2887 if (packet->flags & SILC_PACKET_FLAG_LIST)
2889 silc_server_backup_resume_router(server, sock, packet);
2893 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2898 /* Creates connection to a remote router. */
2900 void silc_server_create_connection(SilcServer server,
2901 const char *remote_host, SilcUInt32 port)
2903 SilcServerConnection sconn;
2905 /* Allocate connection object for hold connection specific stuff. */
2906 sconn = silc_calloc(1, sizeof(*sconn));
2907 sconn->remote_host = strdup(remote_host);
2908 sconn->remote_port = port;
2909 sconn->no_reconnect = TRUE;
2911 silc_schedule_task_add(server->schedule, 0,
2912 silc_server_connect_router,
2913 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2914 SILC_TASK_PRI_NORMAL);
2917 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2919 silc_socket_free(context);
2922 /* Closes connection to socket connection */
2924 void silc_server_close_connection(SilcServer server,
2925 SilcSocketConnection sock)
2929 if (!server->sockets[sock->sock] && SILC_IS_DISCONNECTED(sock)) {
2930 silc_schedule_task_add(server->schedule, 0,
2931 silc_server_close_connection_final,
2932 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2933 SILC_TASK_PRI_NORMAL);
2937 memset(tmp, 0, sizeof(tmp));
2938 silc_socket_get_error(sock, tmp, sizeof(tmp));
2939 SILC_LOG_INFO(("Closing connection %s:%d [%s] %s", sock->hostname,
2941 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2942 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2943 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2944 "Router"), tmp[0] ? tmp : ""));
2946 /* We won't listen for this connection anymore */
2947 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2949 /* Unregister all tasks */
2950 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2952 /* Close the actual connection */
2953 silc_net_close_connection(sock->sock);
2954 server->sockets[sock->sock] = NULL;
2956 /* If sock->user_data is NULL then we'll check for active protocols
2957 here since the silc_server_free_sock_user_data has not been called
2958 for this connection. */
2959 if (!sock->user_data) {
2960 /* If any protocol is active cancel its execution. It will call
2961 the final callback which will finalize the disconnection. */
2962 if (sock->protocol) {
2963 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
2964 silc_protocol_cancel(sock->protocol, server->schedule);
2965 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2966 silc_protocol_execute_final(sock->protocol, server->schedule);
2967 sock->protocol = NULL;
2972 silc_schedule_task_add(server->schedule, 0,
2973 silc_server_close_connection_final,
2974 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2975 SILC_TASK_PRI_NORMAL);
2978 /* Sends disconnect message to remote connection and disconnects the
2981 void silc_server_disconnect_remote(SilcServer server,
2982 SilcSocketConnection sock,
2983 SilcStatus status, ...)
2986 unsigned char buf[512];
2991 if (!sock || SILC_IS_DISCONNECTED(sock))
2994 memset(buf, 0, sizeof(buf));
2995 va_start(ap, status);
2996 cp = va_arg(ap, char *);
2998 vsnprintf(buf, sizeof(buf) - 1, cp, ap);
3003 SILC_LOG_DEBUG(("Disconnecting remote host"));
3005 /* Notify remote end that the conversation is over. The notify message
3006 is tried to be sent immediately. */
3010 len += silc_utf8_encoded_len(buf, strlen(buf), SILC_STRING_ASCII);
3012 buffer = silc_buffer_alloc_size(len);
3016 buffer->data[0] = status;
3018 silc_utf8_encode(buf, strlen(buf), SILC_STRING_ASCII, buffer->data + 1,
3020 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
3021 buffer->data, buffer->len, TRUE);
3022 silc_buffer_free(buffer);
3025 silc_server_packet_queue_purge(server, sock);
3027 /* Mark the connection to be disconnected */
3028 SILC_SET_DISCONNECTED(sock);
3029 silc_server_close_connection(server, sock);
3032 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
3034 SilcServer server = app_context;
3035 SilcClientEntry client = context;
3037 assert(!silc_hash_table_count(client->channels));
3039 silc_idlist_del_data(client);
3040 silc_idcache_purge_by_context(server->local_list->clients, client);
3043 /* Frees client data and notifies about client's signoff. */
3045 void silc_server_free_client_data(SilcServer server,
3046 SilcSocketConnection sock,
3047 SilcClientEntry client,
3049 const char *signoff)
3051 SILC_LOG_DEBUG(("Freeing client data"));
3053 /* If there is pending outgoing data for the client then purge it
3054 to the network before removing the client entry. */
3055 silc_server_packet_queue_purge(server, sock);
3058 /* Check if anyone is watching this nickname */
3059 if (server->server_type == SILC_ROUTER)
3060 silc_server_check_watcher_list(server, client, NULL,
3061 SILC_NOTIFY_TYPE_SIGNOFF);
3063 /* Send SIGNOFF notify to routers. */
3065 silc_server_send_notify_signoff(server, SILC_PRIMARY_ROUTE(server),
3066 SILC_BROADCAST(server), client->id,
3070 /* Remove client from all channels */
3072 silc_server_remove_from_channels(server, NULL, client,
3073 TRUE, (char *)signoff, TRUE);
3075 silc_server_remove_from_channels(server, NULL, client,
3076 FALSE, NULL, FALSE);
3078 /* Remove this client from watcher list if it is */
3079 silc_server_del_from_watcher_list(server, client);
3081 /* Update statistics */
3082 server->stat.my_clients--;
3083 server->stat.clients--;
3084 if (server->stat.cell_clients)
3085 server->stat.cell_clients--;
3086 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
3087 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
3088 silc_schedule_task_del_by_context(server->schedule, client);
3090 /* We will not delete the client entry right away. We will take it
3091 into history (for WHOWAS command) for 5 minutes, unless we're
3092 shutting down server. */
3093 if (!server->server_shutdown) {
3094 silc_schedule_task_add(server->schedule, 0,
3095 silc_server_free_client_data_timeout,
3097 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
3098 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
3099 client->data.status &= ~SILC_IDLIST_STATUS_LOCAL;
3101 client->router = NULL;
3102 client->connection = NULL;
3104 /* Delete directly since we're shutting down server */
3105 silc_idlist_del_data(client);
3106 silc_idlist_del_client(server->local_list, client);
3110 /* Frees user_data pointer from socket connection object. This also sends
3111 appropriate notify packets to the network to inform about leaving
3114 void silc_server_free_sock_user_data(SilcServer server,
3115 SilcSocketConnection sock,
3116 const char *signoff_message)
3118 switch (sock->type) {
3119 case SILC_SOCKET_TYPE_CLIENT:
3121 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
3122 silc_server_free_client_data(server, sock, user_data, TRUE,
3126 case SILC_SOCKET_TYPE_SERVER:
3127 case SILC_SOCKET_TYPE_ROUTER:
3129 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
3130 SilcServerEntry backup_router = NULL;
3132 SILC_LOG_DEBUG(("Freeing server data"));
3135 backup_router = silc_server_backup_get(server, user_data->id);
3137 if (!server->backup_router && server->server_type == SILC_ROUTER &&
3138 backup_router == server->id_entry &&
3139 sock->type != SILC_SOCKET_TYPE_ROUTER)
3140 backup_router = NULL;
3142 if (server->server_shutdown || server->backup_noswitch)
3143 backup_router = NULL;
3145 /* If this was our primary router connection then we're lost to
3146 the outside world. */
3147 if (server->router == user_data) {
3148 /* Check whether we have a backup router connection */
3149 if (!backup_router || backup_router == user_data) {
3150 silc_schedule_task_add(server->schedule, 0,
3151 silc_server_connect_to_router,
3154 SILC_TASK_PRI_NORMAL);
3156 server->id_entry->router = NULL;
3157 server->router = NULL;
3158 server->standalone = TRUE;
3159 backup_router = NULL;
3161 if (server->id_entry != backup_router) {
3162 SILC_LOG_INFO(("New primary router is backup router %s",
3163 backup_router->server_name));
3164 server->id_entry->router = backup_router;
3165 server->router = backup_router;
3166 server->router_connect = time(0);
3167 server->backup_primary = TRUE;
3169 SILC_LOG_INFO(("We are now new primary router in this cell"));
3170 server->id_entry->router = NULL;
3171 server->router = NULL;
3172 server->standalone = TRUE;
3174 /* We stop here to take a breath */
3178 if (server->server_type == SILC_BACKUP_ROUTER) {
3179 server->server_type = SILC_ROUTER;
3181 /* We'll need to constantly try to reconnect to the primary
3182 router so that we'll see when it comes back online. */
3183 silc_server_backup_reconnect(server, sock->ip, sock->port,
3184 silc_server_backup_connected,
3188 /* Mark this connection as replaced */
3189 silc_server_backup_replaced_add(server, user_data->id,
3192 } else if (backup_router) {
3193 SILC_LOG_INFO(("Enabling the use of backup router %s",
3194 backup_router->server_name));
3195 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
3196 backup_router->server_name));
3198 /* Mark this connection as replaced */
3199 silc_server_backup_replaced_add(server, user_data->id,
3201 } else if (server->server_type == SILC_SERVER &&
3202 sock->type == SILC_SOCKET_TYPE_ROUTER) {
3203 /* Reconnect to the router (backup) */
3204 silc_schedule_task_add(server->schedule, 0,
3205 silc_server_connect_to_router,
3208 SILC_TASK_PRI_NORMAL);
3211 if (!backup_router) {
3212 /* Remove all servers that are originated from this server, and
3213 remove the clients of those servers too. */
3214 silc_server_remove_servers_by_server(server, user_data, TRUE);
3216 /* Remove the clients that this server owns as they will become
3217 invalid now too. For backup router the server is actually
3218 coming from the primary router, so mark that as the owner
3220 if (server->server_type == SILC_BACKUP_ROUTER &&
3221 sock->type == SILC_SOCKET_TYPE_SERVER)
3222 silc_server_remove_clients_by_server(server, server->router,
3225 silc_server_remove_clients_by_server(server, user_data,
3228 /* Remove channels owned by this server */
3229 if (server->server_type == SILC_SERVER)
3230 silc_server_remove_channels_by_server(server, user_data);
3232 /* Enable local server connections that may be disabled */
3233 silc_server_local_servers_toggle_enabled(server, TRUE);
3235 /* Update the client entries of this server to the new backup
3236 router. If we are the backup router we also resolve the real
3237 servers for the clients. After updating is over this also
3238 removes the clients that this server explicitly owns. */
3239 silc_server_update_clients_by_server(server, user_data,
3240 backup_router, TRUE);
3242 /* If we are router and just lost our primary router (now standlaone)
3243 we remove everything that was behind it, since we don't know
3245 if (server->server_type == SILC_ROUTER && server->standalone)
3246 /* Remove all servers that are originated from this server, and
3247 remove the clients of those servers too. */
3248 silc_server_remove_servers_by_server(server, user_data, TRUE);
3250 /* Finally remove the clients that are explicitly owned by this
3251 server. They go down with the server. */
3252 silc_server_remove_clients_by_server(server, user_data,
3255 /* Update our server cache to use the new backup router too. */
3256 silc_server_update_servers_by_server(server, user_data, backup_router);
3257 if (server->server_type == SILC_SERVER)
3258 silc_server_update_channels_by_server(server, user_data,
3261 /* Send notify about primary router going down to local operators */
3262 if (server->backup_router)
3263 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3264 SILC_NOTIFY_TYPE_NONE,
3265 ("%s switched to backup router %s "
3266 "(we are primary router now)",
3267 server->server_name, server->server_name));
3268 else if (server->router)
3269 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3270 SILC_NOTIFY_TYPE_NONE,
3271 ("%s switched to backup router %s",
3272 server->server_name,
3273 server->router->server_name));
3275 server->backup_noswitch = FALSE;
3277 /* Free the server entry */
3278 silc_server_backup_del(server, user_data);
3279 silc_server_backup_replaced_del(server, user_data);
3280 silc_idlist_del_data(user_data);
3281 if (!silc_idlist_del_server(server->local_list, user_data))
3282 silc_idlist_del_server(server->global_list, user_data);
3283 if (sock->type == SILC_SOCKET_TYPE_SERVER) {
3284 server->stat.my_servers--;
3286 server->stat.my_routers--;
3287 server->stat.routers--;
3289 server->stat.servers--;
3290 if (server->server_type == SILC_ROUTER)
3291 server->stat.cell_servers--;
3293 if (backup_router && backup_router != server->id_entry) {
3294 /* Announce all of our stuff that was created about 5 minutes ago.
3295 The backup router knows all the other stuff already. */
3296 if (server->server_type == SILC_ROUTER)
3297 silc_server_announce_servers(server, FALSE, time(0) - 300,
3298 backup_router->connection);
3300 /* Announce our clients and channels to the router */
3301 silc_server_announce_clients(server, time(0) - 300,
3302 backup_router->connection);
3303 silc_server_announce_channels(server, time(0) - 300,
3304 backup_router->connection);
3310 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
3312 SILC_LOG_DEBUG(("Freeing unknown connection data"));
3314 silc_idlist_del_data(user_data);
3315 silc_free(user_data);
3320 /* If any protocol is active cancel its execution */
3321 if (sock->protocol) {
3322 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3323 silc_protocol_cancel(sock->protocol, server->schedule);
3324 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3325 silc_protocol_execute_final(sock->protocol, server->schedule);
3326 sock->protocol = NULL;
3329 sock->user_data = NULL;
3332 /* Removes client from all channels it has joined. This is used when client
3333 connection is disconnected. If the client on a channel is last, the
3334 channel is removed as well. This sends the SIGNOFF notify types. */
3336 void silc_server_remove_from_channels(SilcServer server,
3337 SilcSocketConnection sock,
3338 SilcClientEntry client,
3340 const char *signoff_message,
3343 SilcChannelEntry channel;
3344 SilcChannelClientEntry chl;
3345 SilcHashTableList htl;
3346 SilcBuffer clidp = NULL;
3351 SILC_LOG_DEBUG(("Removing client from joined channels"));
3353 if (notify && !client->id)
3357 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3362 /* Remove the client from all channels. The client is removed from
3363 the channels' user list. */
3364 silc_hash_table_list(client->channels, &htl);
3365 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3366 channel = chl->channel;
3368 /* Remove channel if this is last client leaving the channel, unless
3369 the channel is permanent. */
3370 if (server->server_type != SILC_SERVER &&
3371 silc_hash_table_count(channel->user_list) < 2) {
3372 silc_server_channel_delete(server, channel);
3376 silc_hash_table_del(client->channels, channel);
3377 silc_hash_table_del(channel->user_list, client);
3378 channel->user_count--;
3380 /* If there is no global users on the channel anymore mark the channel
3381 as local channel. Do not check if the removed client is local client. */
3382 if (server->server_type == SILC_SERVER && channel->global_users &&
3383 chl->client->router && !silc_server_channel_has_global(channel))
3384 channel->global_users = FALSE;
3386 memset(chl, 'A', sizeof(*chl));
3389 /* Update statistics */
3390 if (SILC_IS_LOCAL(client))
3391 server->stat.my_chanclients--;
3392 if (server->server_type == SILC_ROUTER) {
3393 server->stat.cell_chanclients--;
3394 server->stat.chanclients--;
3397 /* If there is not at least one local user on the channel then we don't
3398 need the channel entry anymore, we can remove it safely, unless the
3399 channel is permanent channel */
3400 if (server->server_type == SILC_SERVER &&
3401 !silc_server_channel_has_local(channel)) {
3402 /* Notify about leaving client if this channel has global users. */
3403 if (notify && channel->global_users)
3404 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3405 SILC_NOTIFY_TYPE_SIGNOFF,
3406 signoff_message ? 2 : 1,
3407 clidp->data, clidp->len,
3408 signoff_message, signoff_message ?
3409 strlen(signoff_message) : 0);
3411 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3412 silc_server_channel_delete(server, channel);
3416 /* Send notify to channel about client leaving SILC and channel too */
3418 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3419 SILC_NOTIFY_TYPE_SIGNOFF,
3420 signoff_message ? 2 : 1,
3421 clidp->data, clidp->len,
3422 signoff_message, signoff_message ?
3423 strlen(signoff_message) : 0);
3425 /* Don't create keys if we are shutting down */
3426 if (server->server_shutdown)
3429 /* Re-generate channel key if needed */
3430 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3431 if (!silc_server_create_channel_key(server, channel, 0))
3434 /* Send the channel key to the channel. The key of course is not sent
3435 to the client who was removed from the channel. */
3436 silc_server_send_channel_key(server, client->connection, channel,
3437 server->server_type == SILC_ROUTER ?
3438 FALSE : !server->standalone);
3442 silc_hash_table_list_reset(&htl);
3444 silc_buffer_free(clidp);
3447 /* Removes client from one channel. This is used for example when client
3448 calls LEAVE command to remove itself from the channel. Returns TRUE
3449 if channel still exists and FALSE if the channel is removed when
3450 last client leaves the channel. If `notify' is FALSE notify messages
3453 bool silc_server_remove_from_one_channel(SilcServer server,
3454 SilcSocketConnection sock,
3455 SilcChannelEntry channel,
3456 SilcClientEntry client,
3459 SilcChannelClientEntry chl;
3462 SILC_LOG_DEBUG(("Removing %s from channel %s",
3463 silc_id_render(client->id, SILC_ID_CLIENT),
3464 channel->channel_name));
3466 /* Get the entry to the channel, if this client is not on the channel
3468 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
3471 /* Remove channel if this is last client leaving the channel, unless
3472 the channel is permanent. */
3473 if (server->server_type != SILC_SERVER &&
3474 silc_hash_table_count(channel->user_list) < 2) {
3475 silc_server_channel_delete(server, channel);
3479 silc_hash_table_del(client->channels, channel);
3480 silc_hash_table_del(channel->user_list, client);
3481 channel->user_count--;
3483 /* If there is no global users on the channel anymore mark the channel
3484 as local channel. Do not check if the client is local client. */
3485 if (server->server_type == SILC_SERVER && channel->global_users &&
3486 chl->client->router && !silc_server_channel_has_global(channel))
3487 channel->global_users = FALSE;
3489 memset(chl, 'O', sizeof(*chl));
3492 /* Update statistics */
3493 if (SILC_IS_LOCAL(client))
3494 server->stat.my_chanclients--;
3495 if (server->server_type == SILC_ROUTER) {
3496 server->stat.cell_chanclients--;
3497 server->stat.chanclients--;
3500 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3504 /* If there is not at least one local user on the channel then we don't
3505 need the channel entry anymore, we can remove it safely, unless the
3506 channel is permanent channel */
3507 if (server->server_type == SILC_SERVER &&
3508 !silc_server_channel_has_local(channel)) {
3509 /* Notify about leaving client if this channel has global users. */
3510 if (notify && channel->global_users)
3511 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3512 SILC_NOTIFY_TYPE_LEAVE, 1,
3513 clidp->data, clidp->len);
3515 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3516 silc_server_channel_delete(server, channel);
3517 silc_buffer_free(clidp);
3521 /* Send notify to channel about client leaving the channel */
3523 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3524 SILC_NOTIFY_TYPE_LEAVE, 1,
3525 clidp->data, clidp->len);
3527 silc_buffer_free(clidp);
3531 /* Timeout callback. This is called if connection is idle or for some
3532 other reason is not responding within some period of time. This
3533 disconnects the remote end. */
3535 SILC_TASK_CALLBACK(silc_server_timeout_remote)
3537 SilcServer server = (SilcServer)context;
3538 SilcSocketConnection sock = server->sockets[fd];
3539 SilcProtocolType protocol = 0;
3541 SILC_LOG_DEBUG(("Start"));
3546 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
3547 sock->hostname, sock->ip));
3549 /* If we have protocol active we must assure that we call the protocol's
3550 final callback so that all the memory is freed. */
3551 if (sock->protocol) {
3552 protocol = sock->protocol->protocol->type;
3553 silc_protocol_cancel(sock->protocol, server->schedule);
3554 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3555 silc_protocol_execute_final(sock->protocol, server->schedule);
3556 sock->protocol = NULL;
3560 silc_server_disconnect_remote(server, sock,
3562 SILC_PROTOCOL_SERVER_CONNECTION_AUTH ?
3563 SILC_STATUS_ERR_AUTH_FAILED :
3564 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
3565 "Connection timeout");
3567 if (sock->user_data)
3568 silc_server_free_sock_user_data(server, sock, NULL);
3571 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
3572 function may be used only by router. In real SILC network all channels
3573 are created by routers thus this function is never used by normal
3576 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3577 SilcServerID *router_id,
3583 SilcChannelID *channel_id;
3584 SilcChannelEntry entry;
3588 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3591 cipher = SILC_DEFAULT_CIPHER;
3593 hmac = SILC_DEFAULT_HMAC;
3595 /* Allocate cipher */
3596 if (!silc_cipher_alloc(cipher, &key))
3600 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3601 silc_cipher_free(key);
3605 channel_name = strdup(channel_name);
3607 /* Create the channel ID */
3608 if (!silc_id_create_channel_id(server, router_id, server->rng,
3610 silc_free(channel_name);
3611 silc_cipher_free(key);
3612 silc_hmac_free(newhmac);
3616 /* Create the channel */
3617 entry = silc_idlist_add_channel(server->local_list, channel_name,
3618 SILC_CHANNEL_MODE_NONE, channel_id,
3619 NULL, key, newhmac, 0);
3621 silc_free(channel_name);
3622 silc_cipher_free(key);
3623 silc_hmac_free(newhmac);
3624 silc_free(channel_id);
3628 entry->cipher = strdup(cipher);
3629 entry->hmac_name = strdup(hmac);
3631 /* Now create the actual key material */
3632 if (!silc_server_create_channel_key(server, entry,
3633 silc_cipher_get_key_len(key) / 8)) {
3634 silc_idlist_del_channel(server->local_list, entry);
3638 /* Notify other routers about the new channel. We send the packet
3639 to our primary route. */
3641 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3642 channel_name, entry->id,
3643 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3646 /* Distribute to backup routers */
3647 if (broadcast && server->server_type == SILC_ROUTER) {
3650 SilcUInt32 name_len = strlen(channel_name);
3651 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3652 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3654 packet = silc_channel_payload_encode(channel_name, name_len,
3655 cid, channel_id_len, entry->mode);
3656 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3657 packet->data, packet->len, FALSE, TRUE);
3659 silc_buffer_free(packet);
3662 server->stat.my_channels++;
3663 if (server->server_type == SILC_ROUTER) {
3664 server->stat.channels++;
3665 server->stat.cell_channels++;
3666 entry->users_resolved = TRUE;
3672 /* Same as above but creates the channel with Channel ID `channel_id. */
3675 silc_server_create_new_channel_with_id(SilcServer server,
3679 SilcChannelID *channel_id,
3682 SilcChannelEntry entry;
3686 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3689 cipher = SILC_DEFAULT_CIPHER;
3691 hmac = SILC_DEFAULT_HMAC;
3693 /* Allocate cipher */
3694 if (!silc_cipher_alloc(cipher, &key))
3698 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3699 silc_cipher_free(key);
3703 channel_name = strdup(channel_name);
3705 /* Create the channel */
3706 entry = silc_idlist_add_channel(server->local_list, channel_name,
3707 SILC_CHANNEL_MODE_NONE, channel_id,
3708 NULL, key, newhmac, 0);
3710 silc_cipher_free(key);
3711 silc_hmac_free(newhmac);
3712 silc_free(channel_name);
3716 /* Now create the actual key material */
3717 if (!silc_server_create_channel_key(server, entry,
3718 silc_cipher_get_key_len(key) / 8)) {
3719 silc_idlist_del_channel(server->local_list, entry);
3723 /* Notify other routers about the new channel. We send the packet
3724 to our primary route. */
3726 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3727 channel_name, entry->id,
3728 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3731 /* Distribute to backup routers */
3732 if (broadcast && server->server_type == SILC_ROUTER) {
3735 SilcUInt32 name_len = strlen(channel_name);
3736 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3737 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3739 packet = silc_channel_payload_encode(channel_name, name_len,
3740 cid, channel_id_len, entry->mode);
3741 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3742 packet->data, packet->len, FALSE, TRUE);
3744 silc_buffer_free(packet);
3747 server->stat.my_channels++;
3748 if (server->server_type == SILC_ROUTER) {
3749 server->stat.channels++;
3750 server->stat.cell_channels++;
3751 entry->users_resolved = TRUE;
3757 /* Channel's key re-key timeout callback. */
3759 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3761 SilcServer server = app_context;
3762 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3766 /* Return now if we are shutting down */
3767 if (server->server_shutdown)
3770 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3773 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3776 /* Generates new channel key. This is used to create the initial channel key
3777 but also to re-generate new key for channel. If `key_len' is provided
3778 it is the bytes of the key length. */
3780 bool silc_server_create_channel_key(SilcServer server,
3781 SilcChannelEntry channel,
3785 unsigned char channel_key[32], hash[32];
3788 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3789 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3793 SILC_LOG_DEBUG(("Generating channel %s key", channel->channel_name));
3795 if (!channel->channel_key)
3796 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3797 channel->channel_key = NULL;
3803 else if (channel->key_len)
3804 len = channel->key_len / 8;
3806 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3808 /* Create channel key */
3809 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3812 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3814 /* Remove old key if exists */
3816 memset(channel->key, 0, channel->key_len / 8);
3817 silc_free(channel->key);
3821 channel->key_len = len * 8;
3822 channel->key = silc_memdup(channel_key, len);
3823 memset(channel_key, 0, sizeof(channel_key));
3825 /* Generate HMAC key from the channel key data and set it */
3827 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3828 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3829 silc_hmac_set_key(channel->hmac, hash,
3830 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3831 memset(hash, 0, sizeof(hash));
3833 if (server->server_type == SILC_ROUTER) {
3834 if (!channel->rekey)
3835 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3836 channel->rekey->channel = channel;
3837 channel->rekey->key_len = key_len;
3838 if (channel->rekey->task)
3839 silc_schedule_task_del(server->schedule, channel->rekey->task);
3841 channel->rekey->task =
3842 silc_schedule_task_add(server->schedule, 0,
3843 silc_server_channel_key_rekey,
3844 (void *)channel->rekey,
3845 server->config->channel_rekey_secs, 0,
3847 SILC_TASK_PRI_NORMAL);
3853 /* Saves the channel key found in the encoded `key_payload' buffer. This
3854 function is used when we receive Channel Key Payload and also when we're
3855 processing JOIN command reply. Returns entry to the channel. */
3857 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3858 SilcBuffer key_payload,
3859 SilcChannelEntry channel)
3861 SilcChannelKeyPayload payload = NULL;
3862 SilcChannelID *id = NULL;
3863 unsigned char *tmp, hash[32];
3867 /* Decode channel key payload */
3868 payload = silc_channel_key_payload_parse(key_payload->data,
3871 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3876 /* Get the channel entry */
3879 /* Get channel ID */
3880 tmp = silc_channel_key_get_id(payload, &tmp_len);
3881 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3887 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3889 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3891 if (server->server_type == SILC_ROUTER)
3892 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3893 silc_id_render(id, SILC_ID_CHANNEL)));
3899 SILC_LOG_DEBUG(("Saving new channel %s key", channel->channel_name));
3901 tmp = silc_channel_key_get_key(payload, &tmp_len);
3907 cipher = silc_channel_key_get_cipher(payload, NULL);
3913 /* Remove old key if exists */
3915 memset(channel->key, 0, channel->key_len / 8);
3916 silc_free(channel->key);
3917 silc_cipher_free(channel->channel_key);
3920 /* Create new cipher */
3921 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3922 channel->channel_key = NULL;
3927 if (channel->cipher)
3928 silc_free(channel->cipher);
3929 channel->cipher = strdup(cipher);
3932 channel->key_len = tmp_len * 8;
3933 channel->key = silc_memdup(tmp, tmp_len);
3934 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3936 /* Generate HMAC key from the channel key data and set it */
3938 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3939 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3940 silc_hmac_set_key(channel->hmac, hash,
3941 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3943 memset(hash, 0, sizeof(hash));
3944 memset(tmp, 0, tmp_len);
3946 if (server->server_type == SILC_ROUTER) {
3947 if (!channel->rekey)
3948 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3949 channel->rekey->channel = channel;
3950 if (channel->rekey->task)
3951 silc_schedule_task_del(server->schedule, channel->rekey->task);
3953 channel->rekey->task =
3954 silc_schedule_task_add(server->schedule, 0,
3955 silc_server_channel_key_rekey,
3956 (void *)channel->rekey,
3957 server->config->channel_rekey_secs, 0,
3959 SILC_TASK_PRI_NORMAL);
3965 silc_channel_key_payload_free(payload);
3970 /* Heartbeat callback. This function is set as argument for the
3971 silc_socket_set_heartbeat function. The library will call this function
3972 at the set time interval. */
3974 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3977 SilcServer server = hb_context;
3979 SILC_LOG_DEBUG(("Sending heartbeat to %s:%d (%s)", sock->hostname,
3980 sock->port, sock->ip));
3982 /* Send the heartbeat */
3983 silc_server_send_heartbeat(server, sock);
3986 /* Returns assembled of all servers in the given ID list. The packet's
3987 form is dictated by the New ID payload. */
3989 static void silc_server_announce_get_servers(SilcServer server,
3990 SilcServerEntry remote,
3992 SilcBuffer *servers,
3993 unsigned long creation_time)
3995 SilcIDCacheList list;
3996 SilcIDCacheEntry id_cache;
3997 SilcServerEntry entry;
4000 /* Go through all clients in the list */
4001 if (silc_idcache_get_all(id_list->servers, &list)) {
4002 if (silc_idcache_list_first(list, &id_cache)) {
4004 entry = (SilcServerEntry)id_cache->context;
4006 /* Do not announce the one we've sending our announcements and
4007 do not announce ourself. Also check the creation time if it's
4009 if ((entry == remote) || (entry == server->id_entry) ||
4010 (creation_time && entry->data.created < creation_time)) {
4011 if (!silc_idcache_list_next(list, &id_cache))
4016 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
4018 *servers = silc_buffer_realloc(*servers,
4020 (*servers)->truelen + idp->len :
4022 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
4023 silc_buffer_put(*servers, idp->data, idp->len);
4024 silc_buffer_pull(*servers, idp->len);
4025 silc_buffer_free(idp);
4027 if (!silc_idcache_list_next(list, &id_cache))
4032 silc_idcache_list_free(list);
4037 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
4043 p = silc_notify_payload_encode(notify, argc, ap);
4049 /* This function is used by router to announce existing servers to our
4050 primary router when we've connected to it. If `creation_time' is non-zero
4051 then only the servers that has been created after the `creation_time'
4052 will be announced. */
4054 void silc_server_announce_servers(SilcServer server, bool global,
4055 unsigned long creation_time,
4056 SilcSocketConnection remote)
4058 SilcBuffer servers = NULL;
4060 SILC_LOG_DEBUG(("Announcing servers"));
4062 /* Get servers in local list */
4063 silc_server_announce_get_servers(server, remote->user_data,
4064 server->local_list, &servers,
4068 /* Get servers in global list */
4069 silc_server_announce_get_servers(server, remote->user_data,
4070 server->global_list, &servers,
4074 silc_buffer_push(servers, servers->data - servers->head);
4075 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
4077 /* Send the packet */
4078 silc_server_packet_send(server, remote,
4079 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4080 servers->data, servers->len, TRUE);
4082 silc_buffer_free(servers);
4086 /* Returns assembled packet of all clients in the given ID list. The
4087 packet's form is dictated by the New ID Payload. */
4089 static void silc_server_announce_get_clients(SilcServer server,
4091 SilcBuffer *clients,
4093 unsigned long creation_time)
4095 SilcIDCacheList list;
4096 SilcIDCacheEntry id_cache;
4097 SilcClientEntry client;
4100 unsigned char mode[4];
4102 /* Go through all clients in the list */
4103 if (silc_idcache_get_all(id_list->clients, &list)) {
4104 if (silc_idcache_list_first(list, &id_cache)) {
4106 client = (SilcClientEntry)id_cache->context;
4108 if (creation_time && client->data.created < creation_time) {
4109 if (!silc_idcache_list_next(list, &id_cache))
4113 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED) &&
4114 !client->connection && !client->router && !SILC_IS_LOCAL(client)) {
4115 if (!silc_idcache_list_next(list, &id_cache))
4120 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
4122 *clients = silc_buffer_realloc(*clients,
4124 (*clients)->truelen + idp->len :
4126 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
4127 silc_buffer_put(*clients, idp->data, idp->len);
4128 silc_buffer_pull(*clients, idp->len);
4130 SILC_PUT32_MSB(client->mode, mode);
4132 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
4133 2, idp->data, idp->len,
4135 *umodes = silc_buffer_realloc(*umodes,
4137 (*umodes)->truelen + tmp->len :
4139 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
4140 silc_buffer_put(*umodes, tmp->data, tmp->len);
4141 silc_buffer_pull(*umodes, tmp->len);
4142 silc_buffer_free(tmp);
4144 silc_buffer_free(idp);
4146 if (!silc_idcache_list_next(list, &id_cache))
4151 silc_idcache_list_free(list);
4155 /* This function is used to announce our existing clients to our router
4156 when we've connected to it. If `creation_time' is non-zero then only
4157 the clients that has been created after the `creation_time' will be
4160 void silc_server_announce_clients(SilcServer server,
4161 unsigned long creation_time,
4162 SilcSocketConnection remote)
4164 SilcBuffer clients = NULL;
4165 SilcBuffer umodes = NULL;
4167 SILC_LOG_DEBUG(("Announcing clients"));
4169 /* Get clients in local list */
4170 silc_server_announce_get_clients(server, server->local_list,
4171 &clients, &umodes, creation_time);
4173 /* As router we announce our global list as well */
4174 if (server->server_type == SILC_ROUTER)
4175 silc_server_announce_get_clients(server, server->global_list,
4176 &clients, &umodes, creation_time);
4179 silc_buffer_push(clients, clients->data - clients->head);
4180 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
4182 /* Send the packet */
4183 silc_server_packet_send(server, remote,
4184 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4185 clients->data, clients->len, TRUE);
4187 silc_buffer_free(clients);
4191 silc_buffer_push(umodes, umodes->data - umodes->head);
4192 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
4194 /* Send the packet */
4195 silc_server_packet_send(server, remote,
4196 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4197 umodes->data, umodes->len, TRUE);
4199 silc_buffer_free(umodes);
4203 /* Returns channel's topic for announcing it */
4205 void silc_server_announce_get_channel_topic(SilcServer server,
4206 SilcChannelEntry channel,
4211 if (channel->topic) {
4212 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4213 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
4214 chidp->data, chidp->len,
4216 strlen(channel->topic));
4217 silc_buffer_free(chidp);
4221 /* Returns assembled packets for channel users of the `channel'. */
4223 void silc_server_announce_get_channel_users(SilcServer server,
4224 SilcChannelEntry channel,
4225 SilcBuffer *channel_modes,
4226 SilcBuffer *channel_users,
4227 SilcBuffer *channel_users_modes)
4229 SilcChannelClientEntry chl;
4230 SilcHashTableList htl;
4231 SilcBuffer chidp, clidp, csidp;
4234 unsigned char mode[4], *fkey = NULL;
4235 SilcUInt32 fkey_len = 0;
4238 SILC_LOG_DEBUG(("Start"));
4240 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4241 csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4244 SILC_PUT32_MSB(channel->mode, mode);
4245 hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
4246 if (channel->founder_key)
4247 fkey = silc_pkcs_public_key_encode(channel->founder_key, &fkey_len);
4249 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
4250 6, csidp->data, csidp->len,
4253 hmac, hmac ? strlen(hmac) : 0,
4254 channel->passphrase,
4255 channel->passphrase ?
4256 strlen(channel->passphrase) : 0,
4260 silc_buffer_realloc(*channel_modes,
4262 (*channel_modes)->truelen + len : len));
4263 silc_buffer_pull_tail(*channel_modes,
4264 ((*channel_modes)->end -
4265 (*channel_modes)->data));
4266 silc_buffer_put(*channel_modes, tmp->data, tmp->len);
4267 silc_buffer_pull(*channel_modes, len);
4268 silc_buffer_free(tmp);
4273 /* Now find all users on the channel */
4274 silc_hash_table_list(channel->user_list, &htl);
4275 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4276 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4279 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
4280 clidp->data, clidp->len,
4281 chidp->data, chidp->len);
4284 silc_buffer_realloc(*channel_users,
4286 (*channel_users)->truelen + len : len));
4287 silc_buffer_pull_tail(*channel_users,
4288 ((*channel_users)->end -
4289 (*channel_users)->data));
4291 silc_buffer_put(*channel_users, tmp->data, tmp->len);
4292 silc_buffer_pull(*channel_users, len);
4293 silc_buffer_free(tmp);
4295 /* CUMODE notify for mode change on the channel */
4296 SILC_PUT32_MSB(chl->mode, mode);
4297 if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
4298 fkey = silc_pkcs_public_key_encode(channel->founder_key, &fkey_len);
4299 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
4300 4, csidp->data, csidp->len,
4302 clidp->data, clidp->len,
4305 *channel_users_modes =
4306 silc_buffer_realloc(*channel_users_modes,
4307 (*channel_users_modes ?
4308 (*channel_users_modes)->truelen + len : len));
4309 silc_buffer_pull_tail(*channel_users_modes,
4310 ((*channel_users_modes)->end -
4311 (*channel_users_modes)->data));
4313 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
4314 silc_buffer_pull(*channel_users_modes, len);
4315 silc_buffer_free(tmp);
4319 silc_buffer_free(clidp);
4321 silc_hash_table_list_reset(&htl);
4322 silc_buffer_free(chidp);
4323 silc_buffer_free(csidp);
4326 /* Returns assembled packets for all channels and users on those channels
4327 from the given ID List. The packets are in the form dictated by the
4328 New Channel and New Channel User payloads. */
4330 void silc_server_announce_get_channels(SilcServer server,
4332 SilcBuffer *channels,
4333 SilcBuffer **channel_modes,
4334 SilcBuffer *channel_users,
4335 SilcBuffer **channel_users_modes,
4336 SilcUInt32 *channel_users_modes_c,
4337 SilcBuffer **channel_topics,
4338 SilcChannelID ***channel_ids,
4339 unsigned long creation_time)
4341 SilcIDCacheList list;
4342 SilcIDCacheEntry id_cache;
4343 SilcChannelEntry channel;
4346 SilcUInt16 name_len;
4348 int i = *channel_users_modes_c;
4351 SILC_LOG_DEBUG(("Start"));
4353 /* Go through all channels in the list */
4354 if (silc_idcache_get_all(id_list->channels, &list)) {
4355 if (silc_idcache_list_first(list, &id_cache)) {
4357 channel = (SilcChannelEntry)id_cache->context;
4359 if (creation_time && channel->created < creation_time)
4364 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4365 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4366 name_len = strlen(channel->channel_name);
4369 len = 4 + name_len + id_len + 4;
4371 silc_buffer_realloc(*channels,
4372 (*channels ? (*channels)->truelen +
4374 silc_buffer_pull_tail(*channels,
4375 ((*channels)->end - (*channels)->data));
4376 silc_buffer_format(*channels,
4377 SILC_STR_UI_SHORT(name_len),
4378 SILC_STR_UI_XNSTRING(channel->channel_name,
4380 SILC_STR_UI_SHORT(id_len),
4381 SILC_STR_UI_XNSTRING(cid, id_len),
4382 SILC_STR_UI_INT(channel->mode),
4384 silc_buffer_pull(*channels, len);
4387 if (creation_time && channel->updated < creation_time)
4393 /* Channel user modes */
4394 *channel_users_modes = silc_realloc(*channel_users_modes,
4395 sizeof(**channel_users_modes) *
4397 (*channel_users_modes)[i] = NULL;
4398 *channel_modes = silc_realloc(*channel_modes,
4399 sizeof(**channel_modes) * (i + 1));
4400 (*channel_modes)[i] = NULL;
4401 *channel_ids = silc_realloc(*channel_ids,
4402 sizeof(**channel_ids) * (i + 1));
4403 (*channel_ids)[i] = NULL;
4404 silc_server_announce_get_channel_users(server, channel,
4405 &(*channel_modes)[i],
4407 &(*channel_users_modes)[i]);
4408 (*channel_ids)[i] = channel->id;
4410 /* Channel's topic */
4411 *channel_topics = silc_realloc(*channel_topics,
4412 sizeof(**channel_topics) * (i + 1));
4413 (*channel_topics)[i] = NULL;
4414 silc_server_announce_get_channel_topic(server, channel,
4415 &(*channel_topics)[i]);
4416 (*channel_users_modes_c)++;
4423 if (!silc_idcache_list_next(list, &id_cache))
4428 silc_idcache_list_free(list);
4432 /* This function is used to announce our existing channels to our router
4433 when we've connected to it. This also announces the users on the
4434 channels to the router. If the `creation_time' is non-zero only the
4435 channels that was created after the `creation_time' are announced.
4436 Note that the channel users are still announced even if the `creation_time'
4439 void silc_server_announce_channels(SilcServer server,
4440 unsigned long creation_time,
4441 SilcSocketConnection remote)
4443 SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
4444 SilcBuffer *channel_users_modes = NULL;
4445 SilcBuffer *channel_topics = NULL;
4446 SilcUInt32 channel_users_modes_c = 0;
4447 SilcChannelID **channel_ids = NULL;
4449 SILC_LOG_DEBUG(("Announcing channels and channel users"));
4451 /* Get channels and channel users in local list */
4452 silc_server_announce_get_channels(server, server->local_list,
4453 &channels, &channel_modes,
4455 &channel_users_modes,
4456 &channel_users_modes_c,
4458 &channel_ids, creation_time);
4460 /* Get channels and channel users in global list */
4461 if (server->server_type != SILC_SERVER)
4462 silc_server_announce_get_channels(server, server->global_list,
4463 &channels, &channel_modes,
4465 &channel_users_modes,
4466 &channel_users_modes_c,
4468 &channel_ids, creation_time);
4471 silc_buffer_push(channels, channels->data - channels->head);
4472 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
4474 /* Send the packet */
4475 silc_server_packet_send(server, remote,
4476 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
4477 channels->data, channels->len,
4480 silc_buffer_free(channels);
4483 if (channel_users) {
4484 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
4485 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
4486 channel_users->len);
4488 /* Send the packet */
4489 silc_server_packet_send(server, remote,
4490 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4491 channel_users->data, channel_users->len,
4494 silc_buffer_free(channel_users);
4497 if (channel_modes) {
4500 for (i = 0; i < channel_users_modes_c; i++) {
4501 if (!channel_modes[i])
4503 silc_buffer_push(channel_modes[i],
4504 channel_modes[i]->data -
4505 channel_modes[i]->head);
4506 SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
4507 channel_modes[i]->len);
4508 silc_server_packet_send_dest(server, remote,
4509 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4510 channel_ids[i], SILC_ID_CHANNEL,
4511 channel_modes[i]->data,
4512 channel_modes[i]->len,
4514 silc_buffer_free(channel_modes[i]);
4516 silc_free(channel_modes);
4519 if (channel_users_modes) {
4522 for (i = 0; i < channel_users_modes_c; i++) {
4523 if (!channel_users_modes[i])
4525 silc_buffer_push(channel_users_modes[i],
4526 channel_users_modes[i]->data -
4527 channel_users_modes[i]->head);
4528 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
4529 channel_users_modes[i]->len);
4530 silc_server_packet_send_dest(server, remote,
4531 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4532 channel_ids[i], SILC_ID_CHANNEL,
4533 channel_users_modes[i]->data,
4534 channel_users_modes[i]->len,
4536 silc_buffer_free(channel_users_modes[i]);
4538 silc_free(channel_users_modes);
4541 if (channel_topics) {
4544 for (i = 0; i < channel_users_modes_c; i++) {
4545 if (!channel_topics[i])
4548 silc_buffer_push(channel_topics[i],
4549 channel_topics[i]->data -
4550 channel_topics[i]->head);
4551 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
4552 channel_topics[i]->len);
4553 silc_server_packet_send_dest(server, remote,
4554 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4555 channel_ids[i], SILC_ID_CHANNEL,
4556 channel_topics[i]->data,
4557 channel_topics[i]->len,
4559 silc_buffer_free(channel_topics[i]);
4561 silc_free(channel_topics);
4564 silc_free(channel_ids);
4567 /* Failure timeout callback. If this is called then we will immediately
4568 process the received failure. We always process the failure with timeout
4569 since we do not want to blindly trust to received failure packets.
4570 This won't be called (the timeout is cancelled) if the failure was
4571 bogus (it is bogus if remote does not close the connection after sending
4574 SILC_TASK_CALLBACK(silc_server_failure_callback)
4576 SilcServer server = app_context;
4577 SilcServerFailureContext f = (SilcServerFailureContext)context;
4579 if (f->sock->protocol) {
4580 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
4581 silc_protocol_execute(f->sock->protocol, server->schedule, 0, 0);
4584 silc_socket_free(f->sock);
4588 /* Assembles user list and users mode list from the `channel'. */
4590 bool silc_server_get_users_on_channel(SilcServer server,
4591 SilcChannelEntry channel,
4592 SilcBuffer *user_list,
4593 SilcBuffer *mode_list,
4594 SilcUInt32 *user_count)
4596 SilcChannelClientEntry chl;
4597 SilcHashTableList htl;
4598 SilcBuffer client_id_list;
4599 SilcBuffer client_mode_list;
4601 SilcUInt32 list_count = 0, len = 0;
4603 if (!silc_hash_table_count(channel->user_list))
4606 silc_hash_table_list(channel->user_list, &htl);
4607 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4608 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
4609 silc_hash_table_list_reset(&htl);
4611 client_id_list = silc_buffer_alloc(len);
4613 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
4614 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
4615 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
4617 silc_hash_table_list(channel->user_list, &htl);
4618 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4620 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4621 silc_buffer_put(client_id_list, idp->data, idp->len);
4622 silc_buffer_pull(client_id_list, idp->len);
4623 silc_buffer_free(idp);
4625 /* Client's mode on channel */
4626 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
4627 silc_buffer_pull(client_mode_list, 4);
4631 silc_hash_table_list_reset(&htl);
4632 silc_buffer_push(client_id_list,
4633 client_id_list->data - client_id_list->head);
4634 silc_buffer_push(client_mode_list,
4635 client_mode_list->data - client_mode_list->head);
4637 *user_list = client_id_list;
4638 *mode_list = client_mode_list;
4639 *user_count = list_count;
4643 /* Saves users and their modes to the `channel'. */
4645 void silc_server_save_users_on_channel(SilcServer server,
4646 SilcSocketConnection sock,
4647 SilcChannelEntry channel,
4648 SilcClientID *noadd,
4649 SilcBuffer user_list,
4650 SilcBuffer mode_list,
4651 SilcUInt32 user_count)
4656 SilcClientID *client_id;
4657 SilcClientEntry client;
4658 SilcIDCacheEntry cache;
4659 SilcChannelClientEntry chl;
4661 SILC_LOG_DEBUG(("Saving %d users on %s channel", user_count,
4662 channel->channel_name));
4664 for (i = 0; i < user_count; i++) {
4666 SILC_GET16_MSB(idp_len, user_list->data + 2);
4668 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
4669 silc_buffer_pull(user_list, idp_len);
4674 SILC_GET32_MSB(mode, mode_list->data);
4675 silc_buffer_pull(mode_list, 4);
4677 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
4678 silc_free(client_id);
4684 /* Check if we have this client cached already. */
4685 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4686 server->server_type, &cache);
4688 client = silc_idlist_find_client_by_id(server->global_list,
4689 client_id, server->server_type,
4692 /* If router did not find such Client ID in its lists then this must
4693 be bogus client or some router in the net is buggy. */
4694 if (server->server_type != SILC_SERVER) {
4695 silc_free(client_id);
4699 /* We don't have that client anywhere, add it. The client is added
4700 to global list since server didn't have it in the lists so it must be
4702 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
4703 silc_id_dup(client_id, SILC_ID_CLIENT),
4704 sock->user_data, NULL, 0);
4706 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
4707 silc_free(client_id);
4711 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
4716 silc_free(client_id);
4718 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
4719 SILC_LOG_ERROR(("Attempting to add unregistered client to channel ",
4720 "%s", channel->channel_name));
4724 if (!silc_server_client_on_channel(client, channel, &chl)) {
4725 /* Client was not on the channel, add it. */
4726 chl = silc_calloc(1, sizeof(*chl));
4727 chl->client = client;
4729 chl->channel = channel;
4730 silc_hash_table_add(channel->user_list, chl->client, chl);
4731 silc_hash_table_add(client->channels, chl->channel, chl);
4732 channel->user_count++;
4740 /* Saves channels and channels user modes to the `client'. Removes
4741 the client from those channels that are not sent in the list but
4744 void silc_server_save_user_channels(SilcServer server,
4745 SilcSocketConnection sock,
4746 SilcClientEntry client,
4747 SilcBuffer channels,
4748 SilcBuffer channels_user_modes)
4751 SilcUInt32 *chumodes;
4752 SilcChannelPayload entry;
4753 SilcChannelEntry channel;
4754 SilcChannelID *channel_id;
4755 SilcChannelClientEntry chl;
4756 SilcHashTable ht = NULL;
4757 SilcHashTableList htl;
4761 if (!channels || !channels_user_modes ||
4762 !(client->data.status & SILC_IDLIST_STATUS_REGISTERED))
4765 ch = silc_channel_payload_parse_list(channels->data, channels->len);
4766 if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
4768 ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL,
4769 NULL, NULL, NULL, TRUE);
4770 silc_dlist_start(ch);
4771 while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
4772 /* Check if we have this channel, and add it if we don't have it.
4773 Also add the client on the channel unless it is there already. */
4774 channel_id = silc_channel_get_id_parse(entry);
4775 channel = silc_idlist_find_channel_by_id(server->local_list,
4778 channel = silc_idlist_find_channel_by_id(server->global_list,
4781 if (server->server_type != SILC_SERVER) {
4782 silc_free(channel_id);
4787 /* We don't have that channel anywhere, add it. */
4788 name = silc_channel_get_name(entry, NULL);
4789 channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
4790 channel_id, server->router,
4793 silc_free(channel_id);
4800 channel->mode = silc_channel_get_mode(entry);
4802 /* Add the client on the channel */
4803 if (!silc_server_client_on_channel(client, channel, &chl)) {
4804 chl = silc_calloc(1, sizeof(*chl));
4805 chl->client = client;
4806 chl->mode = chumodes[i++];
4807 chl->channel = channel;
4808 silc_hash_table_add(channel->user_list, chl->client, chl);
4809 silc_hash_table_add(client->channels, chl->channel, chl);
4810 channel->user_count++;
4813 chl->mode = chumodes[i++];
4816 silc_hash_table_add(ht, channel, channel);
4817 silc_free(channel_id);
4819 silc_channel_payload_list_free(ch);
4820 silc_free(chumodes);
4824 /* Go through the list again and remove client from channels that
4825 are no part of the list. */
4827 silc_hash_table_list(client->channels, &htl);
4828 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4829 if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
4830 silc_hash_table_del(chl->channel->user_list, chl->client);
4831 silc_hash_table_del(chl->client->channels, chl->channel);
4835 silc_hash_table_list_reset(&htl);
4836 silc_hash_table_free(ht);
4838 silc_hash_table_list(client->channels, &htl);
4839 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4840 silc_hash_table_del(chl->channel->user_list, chl->client);
4841 silc_hash_table_del(chl->client->channels, chl->channel);
4844 silc_hash_table_list_reset(&htl);
4848 /* Lookups route to the client indicated by the `id_data'. The connection
4849 object and internal data object is returned. Returns NULL if route
4850 could not be found to the client. If the `client_id' is specified then
4851 it is used and the `id_data' is ignored. */
4853 SilcSocketConnection
4854 silc_server_get_client_route(SilcServer server,
4855 unsigned char *id_data,
4857 SilcClientID *client_id,
4858 SilcIDListData *idata,
4859 SilcClientEntry *client_entry)
4862 SilcClientEntry client;
4864 SILC_LOG_DEBUG(("Start"));
4867 *client_entry = NULL;
4869 /* Decode destination Client ID */
4871 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
4873 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
4877 id = silc_id_dup(client_id, SILC_ID_CLIENT);
4880 /* If the destination belongs to our server we don't have to route
4881 the packet anywhere but to send it to the local destination. */
4882 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
4886 /* If we are router and the client has router then the client is in
4887 our cell but not directly connected to us. */
4888 if (server->server_type == SILC_ROUTER && client->router) {
4889 /* We are of course in this case the client's router thus the route
4890 to the client is the server who owns the client. So, we will send
4891 the packet to that server. */
4893 *idata = (SilcIDListData)client->router;
4894 return client->router->connection;
4897 /* Seems that client really is directly connected to us */
4899 *idata = (SilcIDListData)client;
4901 *client_entry = client;
4902 return client->connection;
4905 /* Destination belongs to someone not in this server. If we are normal
4906 server our action is to send the packet to our router. */
4907 if (server->server_type != SILC_ROUTER && !server->standalone) {
4910 *idata = (SilcIDListData)server->router;
4911 return SILC_PRIMARY_ROUTE(server);
4914 /* We are router and we will perform route lookup for the destination
4915 and send the packet to fastest route. */
4916 if (server->server_type == SILC_ROUTER && !server->standalone) {
4917 /* Check first that the ID is valid */
4918 client = silc_idlist_find_client_by_id(server->global_list, id,
4921 SilcSocketConnection dst_sock;
4923 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
4927 *idata = (SilcIDListData)dst_sock->user_data;
4936 /* Encodes and returns channel list of channels the `client' has joined.
4937 Secret channels are not put to the list. */
4939 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
4940 SilcClientEntry client,
4943 SilcBuffer *user_mode_list)
4945 SilcBuffer buffer = NULL;
4946 SilcChannelEntry channel;
4947 SilcChannelClientEntry chl;
4948 SilcHashTableList htl;
4951 SilcUInt16 name_len;
4955 *user_mode_list = NULL;
4957 silc_hash_table_list(client->channels, &htl);
4958 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4959 channel = chl->channel;
4961 if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
4963 if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
4966 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4967 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4968 name_len = strlen(channel->channel_name);
4970 len = 4 + name_len + id_len + 4;
4971 buffer = silc_buffer_realloc(buffer,
4972 (buffer ? buffer->truelen + len : len));
4973 silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
4974 silc_buffer_format(buffer,
4975 SILC_STR_UI_SHORT(name_len),
4976 SILC_STR_UI_XNSTRING(channel->channel_name,
4978 SILC_STR_UI_SHORT(id_len),
4979 SILC_STR_UI_XNSTRING(cid, id_len),
4980 SILC_STR_UI_INT(chl->channel->mode),
4982 silc_buffer_pull(buffer, len);
4985 if (user_mode_list) {
4986 *user_mode_list = silc_buffer_realloc(*user_mode_list,
4988 (*user_mode_list)->truelen + 4 :
4990 silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
4991 (*user_mode_list)->data));
4992 SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
4993 silc_buffer_pull(*user_mode_list, 4);
4996 silc_hash_table_list_reset(&htl);
4999 silc_buffer_push(buffer, buffer->data - buffer->head);
5000 if (user_mode_list && *user_mode_list)
5001 silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
5002 (*user_mode_list)->head));
5007 /* A timeout callback for the re-key. We will be the initiator of the
5010 SILC_TASK_CALLBACK(silc_server_rekey_callback)
5012 SilcServer server = app_context;
5013 SilcSocketConnection sock = (SilcSocketConnection)context;
5014 SilcIDListData idata = (SilcIDListData)sock->user_data;
5015 SilcProtocol protocol;
5016 SilcServerRekeyInternalContext *proto_ctx;
5018 /* Allocate internal protocol context. This is sent as context
5020 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
5021 proto_ctx->server = (void *)server;
5022 proto_ctx->sock = sock;
5023 proto_ctx->responder = FALSE;
5024 proto_ctx->pfs = idata->rekey->pfs;
5026 /* Perform rekey protocol. Will call the final callback after the
5027 protocol is over. */
5028 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
5029 &protocol, proto_ctx, silc_server_rekey_final);
5030 sock->protocol = protocol;
5032 /* Run the protocol */
5033 silc_protocol_execute(protocol, server->schedule, 0, 0);
5035 SILC_LOG_DEBUG(("Rekey protocol completed"));
5037 /* Re-register re-key timeout */
5038 silc_schedule_task_add(server->schedule, sock->sock,
5039 silc_server_rekey_callback,
5040 context, idata->rekey->timeout, 0,
5041 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
5044 /* The final callback for the REKEY protocol. This will actually take the
5045 new key material into use. */
5047 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
5049 SilcProtocol protocol = (SilcProtocol)context;
5050 SilcServerRekeyInternalContext *ctx =
5051 (SilcServerRekeyInternalContext *)protocol->context;
5052 SilcServer server = (SilcServer)ctx->server;
5053 SilcSocketConnection sock = ctx->sock;
5055 SILC_LOG_DEBUG(("Start"));
5057 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
5058 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
5059 /* Error occured during protocol */
5060 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
5061 silc_protocol_cancel(protocol, server->schedule);
5062 silc_protocol_free(protocol);
5063 sock->protocol = NULL;
5065 silc_packet_context_free(ctx->packet);
5067 silc_ske_free(ctx->ske);
5072 /* Purge the outgoing data queue to assure that all rekey packets really
5073 go to the network before we quit the protocol. */
5074 silc_server_packet_queue_purge(server, sock);
5077 silc_protocol_free(protocol);
5078 sock->protocol = NULL;
5080 silc_packet_context_free(ctx->packet);
5082 silc_ske_free(ctx->ske);
5086 /* Task callback used to retrieve network statistical information from
5087 router server once in a while. */
5089 SILC_TASK_CALLBACK(silc_server_get_stats)
5091 SilcServer server = (SilcServer)context;
5092 SilcBuffer idp, packet;
5094 SILC_LOG_DEBUG(("Retrieving stats from router"));
5096 if (!server->standalone) {
5097 idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
5098 packet = silc_command_payload_encode_va(SILC_COMMAND_STATS,
5099 ++server->cmd_ident, 1,
5100 1, idp->data, idp->len);
5101 silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
5102 SILC_PACKET_COMMAND, 0, packet->data,
5103 packet->len, FALSE);
5104 silc_buffer_free(packet);
5105 silc_buffer_free(idp);
5108 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
5109 server, 120, 0, SILC_TASK_TIMEOUT,