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_SERVER)
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);
996 /* Continue with key exchange protocol */
997 silc_server_start_key_exchange(server, sconn, sock);
1000 /* This function connects to our primary router or if we are a router this
1001 establishes all our primary routes. This is called at the start of the
1002 server to do authentication and key exchange with our router - called
1005 SILC_TASK_CALLBACK(silc_server_connect_to_router)
1007 SilcServer server = (SilcServer)context;
1008 SilcServerConnection sconn;
1009 SilcServerConfigRouter *ptr;
1011 /* Don't connect if we are shutting down. */
1012 if (server->server_shutdown)
1015 SILC_LOG_DEBUG(("We are %s",
1016 (server->server_type == SILC_SERVER ?
1017 "normal server" : server->server_type == SILC_ROUTER ?
1018 "router" : "backup router/normal server")));
1020 if (!server->config->routers) {
1021 /* There wasn't a configured router, we will continue but we don't
1022 have a connection to outside world. We will be standalone server. */
1023 SILC_LOG_DEBUG(("No router(s), we are standalone"));
1024 server->standalone = TRUE;
1028 /* Cancel any possible retry timeouts */
1029 silc_schedule_task_del_by_callback(server->schedule,
1030 silc_server_connect_router);
1031 silc_schedule_task_del_by_callback(server->schedule,
1032 silc_server_connect_to_router_retry);
1034 /* Create the connections to all our routes */
1035 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
1037 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
1038 ptr->backup_router ? "Backup router" : "Router",
1039 ptr->initiator ? "Initiator" : "Responder",
1040 ptr->host, ptr->port));
1042 if (server->server_type == SILC_ROUTER && ptr->backup_router &&
1043 ptr->initiator == FALSE && !server->backup_router &&
1044 !silc_server_config_get_backup_router(server))
1045 server->wait_backup = TRUE;
1047 if (ptr->initiator) {
1048 /* Check whether we are connected to this host already */
1049 if (silc_server_num_sockets_by_remote(server,
1050 silc_net_is_ip(ptr->host) ?
1052 silc_net_is_ip(ptr->host) ?
1053 NULL : ptr->host, ptr->port,
1054 SILC_SOCKET_TYPE_ROUTER)) {
1055 SILC_LOG_DEBUG(("We are already connected to this router"));
1059 /* Allocate connection object for hold connection specific stuff. */
1060 sconn = silc_calloc(1, sizeof(*sconn));
1061 sconn->remote_host = strdup(ptr->host);
1062 sconn->remote_port = ptr->port;
1063 sconn->backup = ptr->backup_router;
1064 if (sconn->backup) {
1065 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
1066 sconn->backup_replace_port = ptr->backup_replace_port;
1069 if (!server->router_conn && !sconn->backup)
1070 server->router_conn = sconn;
1072 silc_schedule_task_add(server->schedule, 0,
1073 silc_server_connect_router,
1074 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
1075 SILC_TASK_PRI_NORMAL);
1080 /* Second part of connecting to router(s). Key exchange protocol has been
1081 executed and now we will execute authentication protocol. */
1083 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
1085 SilcProtocol protocol = (SilcProtocol)context;
1086 SilcServerKEInternalContext *ctx =
1087 (SilcServerKEInternalContext *)protocol->context;
1088 SilcServer server = (SilcServer)ctx->server;
1089 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1090 SilcSocketConnection sock = ctx->sock;
1091 SilcServerConnAuthInternalContext *proto_ctx;
1092 SilcServerConfigRouter *conn = NULL;
1094 SILC_LOG_DEBUG(("Start"));
1096 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1097 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1098 /* Error occured during protocol */
1099 silc_protocol_free(protocol);
1100 sock->protocol = NULL;
1101 silc_ske_free_key_material(ctx->keymat);
1103 silc_packet_context_free(ctx->packet);
1105 silc_ske_free(ctx->ske);
1106 silc_free(ctx->dest_id);
1108 silc_schedule_task_del_by_callback(server->schedule,
1109 silc_server_failure_callback);
1110 silc_server_disconnect_remote(server, sock,
1111 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1113 /* Try reconnecting if configuration wants it */
1114 if (!sconn->no_reconnect) {
1115 silc_schedule_task_add(server->schedule, 0,
1116 silc_server_connect_to_router_retry,
1117 sconn, 0, 1, SILC_TASK_TIMEOUT,
1118 SILC_TASK_PRI_NORMAL);
1122 /* Call completion to indicate error */
1123 if (sconn->callback)
1124 (*sconn->callback)(server, NULL, sconn->callback_context);
1126 silc_server_config_unref(&sconn->conn);
1127 silc_free(sconn->remote_host);
1128 silc_free(sconn->backup_replace_ip);
1133 /* We now have the key material as the result of the key exchange
1134 protocol. Take the key material into use. Free the raw key material
1135 as soon as we've set them into use. */
1136 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1137 ctx->sock, ctx->keymat,
1138 ctx->ske->prop->cipher,
1139 ctx->ske->prop->pkcs,
1140 ctx->ske->prop->hash,
1141 ctx->ske->prop->hmac,
1142 ctx->ske->prop->group,
1144 silc_protocol_free(protocol);
1145 sock->protocol = NULL;
1146 silc_ske_free_key_material(ctx->keymat);
1148 silc_packet_context_free(ctx->packet);
1150 silc_ske_free(ctx->ske);
1151 silc_free(ctx->dest_id);
1153 silc_schedule_task_del_by_callback(server->schedule,
1154 silc_server_failure_callback);
1155 silc_server_disconnect_remote(server, sock,
1156 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1158 /* Try reconnecting if configuration wants it */
1159 if (!sconn->no_reconnect) {
1160 silc_schedule_task_add(server->schedule, 0,
1161 silc_server_connect_to_router_retry,
1162 sconn, 0, 1, SILC_TASK_TIMEOUT,
1163 SILC_TASK_PRI_NORMAL);
1167 /* Call completion to indicate error */
1168 if (sconn->callback)
1169 (*sconn->callback)(server, NULL, sconn->callback_context);
1171 silc_server_config_unref(&sconn->conn);
1172 silc_free(sconn->remote_host);
1173 silc_free(sconn->backup_replace_ip);
1177 silc_ske_free_key_material(ctx->keymat);
1179 /* Allocate internal context for the authentication protocol. This
1180 is sent as context for the protocol. */
1181 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1182 proto_ctx->server = (void *)server;
1183 proto_ctx->context = (void *)sconn;
1184 proto_ctx->sock = sock;
1185 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1186 proto_ctx->dest_id_type = ctx->dest_id_type;
1187 proto_ctx->dest_id = ctx->dest_id;
1189 /* Resolve the authentication method used in this connection. Check if
1190 we find a match from user configured connections */
1191 if (!sconn->conn.ref_ptr)
1192 conn = silc_server_config_find_router_conn(server, sock->hostname,
1195 conn = sconn->conn.ref_ptr;
1198 /* Match found. Use the configured authentication method. Take only
1199 the passphrase, since for public key auth we automatically use
1200 our local key pair. */
1201 if (conn->passphrase) {
1202 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
1203 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1205 proto_ctx->auth_data = strdup(conn->passphrase);
1206 proto_ctx->auth_data_len = strlen(conn->passphrase);
1207 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
1209 } else if (conn->publickeys) {
1210 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1212 proto_ctx->auth_meth = SILC_AUTH_NONE;
1215 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
1216 sock->hostname, sock->ip, sock->port));
1217 silc_protocol_free(protocol);
1218 sock->protocol = NULL;
1220 silc_packet_context_free(ctx->packet);
1222 silc_ske_free(ctx->ske);
1223 silc_free(ctx->dest_id);
1225 silc_server_config_unref(&sconn->conn);
1226 silc_free(sconn->remote_host);
1227 silc_free(sconn->backup_replace_ip);
1229 silc_schedule_task_del_by_callback(server->schedule,
1230 silc_server_failure_callback);
1231 silc_server_disconnect_remote(server, sock,
1232 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1236 /* Free old protocol as it is finished now */
1237 silc_protocol_free(protocol);
1239 silc_packet_context_free(ctx->packet);
1241 sock->protocol = NULL;
1243 /* Allocate the authentication protocol. This is allocated here
1244 but we won't start it yet. We will be receiving party of this
1245 protocol thus we will wait that connecting party will make
1246 their first move. */
1247 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1248 &sock->protocol, proto_ctx,
1249 silc_server_connect_to_router_final);
1251 /* Register timeout task. If the protocol is not executed inside
1252 this timelimit the connection will be terminated. */
1253 proto_ctx->timeout_task =
1254 silc_schedule_task_add(server->schedule, sock->sock,
1255 silc_server_timeout_remote,
1257 server->config->conn_auth_timeout, 0,
1261 /* Run the protocol */
1262 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1265 /* Finalizes the connection to router. Registers a server task to the
1266 queue so that we can accept new connections. */
1268 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
1270 SilcProtocol protocol = (SilcProtocol)context;
1271 SilcServerConnAuthInternalContext *ctx =
1272 (SilcServerConnAuthInternalContext *)protocol->context;
1273 SilcServer server = (SilcServer)ctx->server;
1274 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1275 SilcSocketConnection sock = ctx->sock;
1276 SilcServerEntry id_entry = NULL;
1278 unsigned char *id_string;
1280 SilcIDListData idata;
1281 SilcServerConfigRouter *conn = NULL;
1282 SilcServerConfigConnParams *param = NULL;
1284 SILC_LOG_DEBUG(("Start"));
1286 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1287 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1288 /* Error occured during protocol */
1289 silc_free(ctx->dest_id);
1290 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1293 /* Try reconnecting if configuration wants it */
1294 if (!sconn->no_reconnect) {
1295 silc_schedule_task_add(server->schedule, 0,
1296 silc_server_connect_to_router_retry,
1297 sconn, 0, 1, SILC_TASK_TIMEOUT,
1298 SILC_TASK_PRI_NORMAL);
1305 /* Add a task to the queue. This task receives new connections to the
1306 server. This task remains on the queue until the end of the program. */
1307 if (!server->listenning && !sconn->backup) {
1308 silc_schedule_task_add(server->schedule, server->sock,
1309 silc_server_accept_new_connection,
1310 (void *)server, 0, 0,
1312 SILC_TASK_PRI_NORMAL);
1313 server->listenning = TRUE;
1316 /* Send NEW_SERVER packet to the router. We will become registered
1317 to the SILC network after sending this packet. */
1318 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
1319 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1320 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
1321 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1322 silc_buffer_format(packet,
1323 SILC_STR_UI_SHORT(id_len),
1324 SILC_STR_UI_XNSTRING(id_string, id_len),
1325 SILC_STR_UI_SHORT(strlen(server->server_name)),
1326 SILC_STR_UI_XNSTRING(server->server_name,
1327 strlen(server->server_name)),
1330 /* Send the packet */
1331 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
1332 packet->data, packet->len, TRUE);
1333 silc_buffer_free(packet);
1334 silc_free(id_string);
1336 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
1338 /* Check that we do not have this ID already */
1339 id_entry = silc_idlist_find_server_by_id(server->local_list,
1340 ctx->dest_id, TRUE, NULL);
1342 silc_idcache_del_by_context(server->local_list->servers, id_entry);
1344 id_entry = silc_idlist_find_server_by_id(server->global_list,
1345 ctx->dest_id, TRUE, NULL);
1347 silc_idcache_del_by_context(server->global_list->servers, id_entry);
1350 SILC_LOG_DEBUG(("New server id(%s)",
1351 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1353 /* Add the connected router to global server list. Router is sent
1354 as NULL since it's local to us. */
1355 id_entry = silc_idlist_add_server(server->global_list,
1356 strdup(sock->hostname),
1357 SILC_ROUTER, ctx->dest_id, NULL, sock);
1359 silc_free(ctx->dest_id);
1360 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1361 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1366 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1367 silc_free(sock->user_data);
1368 sock->user_data = (void *)id_entry;
1369 sock->type = SILC_SOCKET_TYPE_ROUTER;
1370 idata = (SilcIDListData)sock->user_data;
1371 idata->status |= (SILC_IDLIST_STATUS_REGISTERED |
1372 SILC_IDLIST_STATUS_LOCAL);
1374 conn = sconn->conn.ref_ptr;
1375 param = &server->config->param;
1376 if (conn && conn->param)
1377 param = conn->param;
1379 /* Perform keepalive. The `hb_context' will be freed automatically
1380 when finally calling the silc_socket_free function. */
1381 silc_socket_set_heartbeat(sock, param->keepalive_secs, server,
1382 silc_server_perform_heartbeat,
1385 /* Register re-key timeout */
1386 idata->rekey->timeout = param->key_exchange_rekey;
1387 silc_schedule_task_add(server->schedule, sock->sock,
1388 silc_server_rekey_callback,
1389 (void *)sock, idata->rekey->timeout, 0,
1390 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1392 if (!sconn->backup) {
1393 /* Mark this router our primary router if we're still standalone */
1394 if (server->standalone) {
1395 SILC_LOG_DEBUG(("This connection is our primary router"));
1396 server->id_entry->router = id_entry;
1397 server->router = id_entry;
1398 server->standalone = FALSE;
1400 /* If we are router then announce our possible servers. Backup
1401 router announces also global servers. */
1402 if (server->server_type == SILC_ROUTER)
1403 silc_server_announce_servers(server,
1404 server->backup_router ? TRUE : FALSE,
1405 0, SILC_PRIMARY_ROUTE(server));
1407 /* Announce our clients and channels to the router */
1408 silc_server_announce_clients(server, 0, SILC_PRIMARY_ROUTE(server));
1409 silc_server_announce_channels(server, 0, SILC_PRIMARY_ROUTE(server));
1411 /* If we are backup router then this primary router is whom we are
1413 if (server->server_type == SILC_BACKUP_ROUTER)
1414 silc_server_backup_add(server, server->id_entry, sock->ip, 0, TRUE);
1417 /* Add this server to be our backup router */
1418 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1419 sconn->backup_replace_port, FALSE);
1422 sock->protocol = NULL;
1425 /* Call the completion callback to indicate that we've connected to
1427 if (sconn && sconn->callback)
1428 (*sconn->callback)(server, id_entry, sconn->callback_context);
1430 /* Free the temporary connection data context */
1432 silc_server_config_unref(&sconn->conn);
1433 silc_free(sconn->remote_host);
1434 silc_free(sconn->backup_replace_ip);
1437 if (sconn == server->router_conn)
1438 server->router_conn = NULL;
1441 /* Free the protocol object */
1442 if (sock->protocol == protocol)
1443 sock->protocol = NULL;
1444 silc_protocol_free(protocol);
1446 silc_packet_context_free(ctx->packet);
1448 silc_ske_free(ctx->ske);
1449 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1450 silc_free(ctx->auth_data);
1454 /* Host lookup callback that is called after the incoming connection's
1455 IP and FQDN lookup is performed. This will actually check the acceptance
1456 of the incoming connection and will register the key exchange protocol
1457 for this connection. */
1460 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1463 SilcServerKEInternalContext *proto_ctx =
1464 (SilcServerKEInternalContext *)context;
1465 SilcServer server = (SilcServer)proto_ctx->server;
1466 SilcServerConfigClient *cconfig = NULL;
1467 SilcServerConfigServer *sconfig = NULL;
1468 SilcServerConfigRouter *rconfig = NULL;
1469 SilcServerConfigDeny *deny;
1472 /* Check whether we could resolve both IP and FQDN. */
1473 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1474 server->config->require_reverse_lookup)) {
1475 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1476 sock->hostname ? sock->hostname :
1477 sock->ip ? sock->ip : ""));
1478 server->stat.conn_failures++;
1479 silc_server_disconnect_remote(server, sock,
1480 SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
1481 "Unknown host or IP");
1482 silc_free(proto_ctx);
1486 /* Register the connection for network input and output. This sets
1487 that scheduler will listen for incoming packets for this connection
1488 and sets that outgoing packets may be sent to this connection as well.
1489 However, this doesn't set the scheduler for outgoing traffic, it
1490 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1491 later when outgoing data is available. */
1492 context = (void *)server;
1493 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1495 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1498 /* Listenning port */
1499 if (!server->sockets[(SilcUInt32)proto_ctx->context]) {
1500 silc_server_disconnect_remote(server, sock,
1501 SILC_STATUS_ERR_RESOURCE_LIMIT,
1502 "Connection refused");
1503 server->stat.conn_failures++;
1504 silc_free(proto_ctx);
1507 port = server->sockets[(SilcUInt32)proto_ctx->context]->port;
1509 /* Check whether this connection is denied to connect to us. */
1510 deny = silc_server_config_find_denied(server, sock->ip);
1512 deny = silc_server_config_find_denied(server, sock->hostname);
1514 /* The connection is denied */
1515 SILC_LOG_INFO(("Connection %s (%s) is denied",
1516 sock->hostname, sock->ip));
1517 silc_server_disconnect_remote(server, sock,
1518 SILC_STATUS_ERR_BANNED_FROM_SERVER,
1520 server->stat.conn_failures++;
1521 silc_free(proto_ctx);
1525 /* Check whether we have configured this sort of connection at all. We
1526 have to check all configurations since we don't know what type of
1527 connection this is. */
1528 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1529 cconfig = silc_server_config_find_client(server, sock->hostname);
1530 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1531 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1532 if (server->server_type == SILC_ROUTER) {
1533 if (!(rconfig = silc_server_config_find_router_conn(server,
1534 sock->ip, sock->port)))
1535 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1538 if (!cconfig && !sconfig && !rconfig) {
1539 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1541 silc_server_disconnect_remote(server, sock,
1542 SILC_STATUS_ERR_BANNED_FROM_SERVER, NULL);
1543 server->stat.conn_failures++;
1544 silc_free(proto_ctx);
1548 /* The connection is allowed */
1550 /* Set internal context for key exchange protocol. This is
1551 sent as context for the protocol. */
1552 proto_ctx->sock = sock;
1553 proto_ctx->rng = server->rng;
1554 proto_ctx->responder = TRUE;
1555 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1556 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1557 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1559 /* Take flags for key exchange. Since we do not know what type of connection
1560 this is, we go through all found configurations and use the global ones
1561 as well. This will result always into strictest key exchange flags. */
1562 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1563 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1564 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1565 if (server->config->param.key_exchange_pfs)
1566 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1568 /* Prepare the connection for key exchange protocol. We allocate the
1569 protocol but will not start it yet. The connector will be the
1570 initiator of the protocol thus we will wait for initiation from
1571 there before we start the protocol. */
1572 server->stat.auth_attempts++;
1573 SILC_LOG_DEBUG(("Starting key exchange protocol"));
1574 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1575 &sock->protocol, proto_ctx,
1576 silc_server_accept_new_connection_second);
1578 /* Register a timeout task that will be executed if the connector
1579 will not start the key exchange protocol within specified timeout
1580 and the connection will be closed. */
1581 proto_ctx->timeout_task =
1582 silc_schedule_task_add(server->schedule, sock->sock,
1583 silc_server_timeout_remote,
1585 server->config->key_exchange_timeout, 0,
1590 /* Accepts new connections to the server. Accepting new connections are
1591 done in three parts to make it async. */
1593 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1595 SilcServer server = (SilcServer)context;
1596 SilcSocketConnection newsocket;
1597 SilcServerKEInternalContext *proto_ctx;
1600 SILC_LOG_DEBUG(("Accepting new connection"));
1602 server->stat.conn_attempts++;
1604 sock = silc_net_accept_connection(fd);
1606 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1607 server->stat.conn_failures++;
1611 /* Check for maximum allowed connections */
1612 if (sock > server->config->param.connections_max) {
1613 SILC_LOG_ERROR(("Refusing connection, server is full"));
1614 server->stat.conn_failures++;
1615 silc_net_close_connection(sock);
1619 /* Set socket options */
1620 silc_net_set_socket_nonblock(sock);
1621 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1623 /* We don't create a ID yet, since we don't know what type of connection
1624 this is yet. But, we do add the connection to the socket table. */
1625 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1626 server->sockets[sock] = newsocket;
1628 /* Perform asynchronous host lookup. This will lookup the IP and the
1629 FQDN of the remote connection. After the lookup is done the connection
1630 is accepted further. */
1631 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1632 proto_ctx->server = server;
1633 proto_ctx->context = (void *)fd;
1634 silc_socket_host_lookup(newsocket, TRUE,
1635 silc_server_accept_new_connection_lookup,
1636 (void *)proto_ctx, server->schedule);
1639 /* Second part of accepting new connection. Key exchange protocol has been
1640 performed and now it is time to do little connection authentication
1641 protocol to figure out whether this connection is client or server
1642 and whether it has right to access this server (especially server
1643 connections needs to be authenticated). */
1645 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1647 SilcProtocol protocol = (SilcProtocol)context;
1648 SilcServerKEInternalContext *ctx =
1649 (SilcServerKEInternalContext *)protocol->context;
1650 SilcServer server = (SilcServer)ctx->server;
1651 SilcSocketConnection sock = ctx->sock;
1652 SilcServerConnAuthInternalContext *proto_ctx;
1654 SILC_LOG_DEBUG(("Start"));
1656 if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1657 (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1658 /* Error occured during protocol */
1659 SILC_LOG_DEBUG(("Error key exchange protocol"));
1660 silc_protocol_free(protocol);
1661 sock->protocol = NULL;
1662 silc_ske_free_key_material(ctx->keymat);
1664 silc_packet_context_free(ctx->packet);
1666 silc_ske_free(ctx->ske);
1667 silc_free(ctx->dest_id);
1668 silc_server_config_unref(&ctx->cconfig);
1669 silc_server_config_unref(&ctx->sconfig);
1670 silc_server_config_unref(&ctx->rconfig);
1672 silc_schedule_task_del_by_callback(server->schedule,
1673 silc_server_failure_callback);
1674 silc_server_disconnect_remote(server, sock,
1675 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
1677 server->stat.auth_failures++;
1681 /* We now have the key material as the result of the key exchange
1682 protocol. Take the key material into use. Free the raw key material
1683 as soon as we've set them into use. */
1684 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1685 ctx->sock, ctx->keymat,
1686 ctx->ske->prop->cipher,
1687 ctx->ske->prop->pkcs,
1688 ctx->ske->prop->hash,
1689 ctx->ske->prop->hmac,
1690 ctx->ske->prop->group,
1692 SILC_LOG_ERROR(("Error setting key material in use"));
1693 silc_protocol_free(protocol);
1694 sock->protocol = NULL;
1695 silc_ske_free_key_material(ctx->keymat);
1697 silc_packet_context_free(ctx->packet);
1699 silc_ske_free(ctx->ske);
1700 silc_free(ctx->dest_id);
1701 silc_server_config_unref(&ctx->cconfig);
1702 silc_server_config_unref(&ctx->sconfig);
1703 silc_server_config_unref(&ctx->rconfig);
1705 silc_schedule_task_del_by_callback(server->schedule,
1706 silc_server_failure_callback);
1707 silc_server_disconnect_remote(server, sock,
1708 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1709 server->stat.auth_failures++;
1712 silc_ske_free_key_material(ctx->keymat);
1714 /* Allocate internal context for the authentication protocol. This
1715 is sent as context for the protocol. */
1716 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1717 proto_ctx->server = (void *)server;
1718 proto_ctx->sock = sock;
1719 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1720 proto_ctx->responder = TRUE;
1721 proto_ctx->dest_id_type = ctx->dest_id_type;
1722 proto_ctx->dest_id = ctx->dest_id;
1723 proto_ctx->cconfig = ctx->cconfig;
1724 proto_ctx->sconfig = ctx->sconfig;
1725 proto_ctx->rconfig = ctx->rconfig;
1727 /* Free old protocol as it is finished now */
1728 silc_protocol_free(protocol);
1730 silc_packet_context_free(ctx->packet);
1732 sock->protocol = NULL;
1734 /* Allocate the authentication protocol. This is allocated here
1735 but we won't start it yet. We will be receiving party of this
1736 protocol thus we will wait that connecting party will make
1737 their first move. */
1738 SILC_LOG_DEBUG(("Starting connection authentication protocol"));
1739 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1740 &sock->protocol, proto_ctx,
1741 silc_server_accept_new_connection_final);
1743 /* Register timeout task. If the protocol is not executed inside
1744 this timelimit the connection will be terminated. */
1745 proto_ctx->timeout_task =
1746 silc_schedule_task_add(server->schedule, sock->sock,
1747 silc_server_timeout_remote,
1749 server->config->conn_auth_timeout, 0,
1754 /* After this is called, server don't wait for backup router anymore.
1755 This gets called automatically even after we have backup router
1756 connection established. */
1758 SILC_TASK_CALLBACK(silc_server_backup_router_wait)
1760 SilcServer server = context;
1761 server->wait_backup = FALSE;
1764 /* Final part of accepting new connection. The connection has now
1765 been authenticated and keys has been exchanged. We also know whether
1766 this is client or server connection. */
1768 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1770 SilcProtocol protocol = (SilcProtocol)context;
1771 SilcServerConnAuthInternalContext *ctx =
1772 (SilcServerConnAuthInternalContext *)protocol->context;
1773 SilcServer server = (SilcServer)ctx->server;
1774 SilcSocketConnection sock = ctx->sock;
1775 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1777 SilcUInt32 hearbeat_timeout = server->config->param.keepalive_secs;
1779 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1780 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1781 /* Error occured during protocol */
1782 SILC_LOG_DEBUG(("Error during authentication protocol"));
1783 silc_protocol_free(protocol);
1784 sock->protocol = NULL;
1786 silc_packet_context_free(ctx->packet);
1788 silc_ske_free(ctx->ske);
1789 silc_free(ctx->dest_id);
1790 silc_server_config_unref(&ctx->cconfig);
1791 silc_server_config_unref(&ctx->sconfig);
1792 silc_server_config_unref(&ctx->rconfig);
1794 silc_schedule_task_del_by_callback(server->schedule,
1795 silc_server_failure_callback);
1796 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1798 server->stat.auth_failures++;
1802 entry->data.last_receive = time(NULL);
1804 switch (ctx->conn_type) {
1805 case SILC_SOCKET_TYPE_CLIENT:
1807 SilcClientEntry client;
1808 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1810 /* Verify whether this connection is after all allowed to connect */
1811 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1812 &server->config->param,
1813 conn->param, ctx->ske)) {
1814 server->stat.auth_failures++;
1818 /* If we are primary router and we have backup router configured
1819 but it has not connected to use yet, do not accept any other
1821 if (server->wait_backup && server->server_type == SILC_ROUTER &&
1822 !server->backup_router) {
1823 SilcServerConfigRouter *router;
1824 router = silc_server_config_get_backup_router(server);
1825 if (router && strcmp(server->config->server_info->primary->server_ip,
1827 silc_server_find_socket_by_host(server,
1828 SILC_SOCKET_TYPE_SERVER,
1829 router->backup_replace_ip, 0)) {
1830 SILC_LOG_INFO(("Will not accept connections because we do "
1831 "not have backup router connection established"));
1832 silc_server_disconnect_remote(server, sock,
1833 SILC_STATUS_ERR_PERM_DENIED,
1834 "We do not have connection to backup "
1835 "router established, try later");
1836 silc_free(sock->user_data);
1837 server->stat.auth_failures++;
1839 /* From here on, wait 10 seconds for the backup router to appear. */
1840 silc_schedule_task_add(server->schedule, 0,
1841 silc_server_backup_router_wait,
1842 (void *)server, 10, 0,
1843 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1848 SILC_LOG_DEBUG(("Remote host is client"));
1849 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1852 /* Add the client to the client ID cache. The nickname and Client ID
1853 and other information is created after we have received NEW_CLIENT
1854 packet from client. */
1855 client = silc_idlist_add_client(server->local_list,
1856 NULL, NULL, NULL, NULL, NULL, sock, 0);
1858 SILC_LOG_ERROR(("Could not add new client to cache"));
1859 silc_free(sock->user_data);
1860 silc_server_disconnect_remote(server, sock,
1861 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1862 server->stat.auth_failures++;
1865 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
1868 server->stat.my_clients++;
1869 server->stat.clients++;
1870 server->stat.cell_clients++;
1872 /* Get connection parameters */
1874 if (conn->param->keepalive_secs)
1875 hearbeat_timeout = conn->param->keepalive_secs;
1877 /* Check if to be anonymous connection */
1878 if (conn->param->anonymous)
1879 client->mode |= SILC_UMODE_ANONYMOUS;
1882 id_entry = (void *)client;
1885 case SILC_SOCKET_TYPE_SERVER:
1886 case SILC_SOCKET_TYPE_ROUTER:
1888 SilcServerEntry new_server;
1889 bool initiator = FALSE;
1890 bool backup_local = FALSE;
1891 bool backup_router = FALSE;
1892 char *backup_replace_ip = NULL;
1893 SilcUInt16 backup_replace_port = 0;
1894 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1895 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1897 /* If we are backup router and this is incoming server connection
1898 and we do not have connection to primary router, do not allow
1900 if (server->server_type == SILC_BACKUP_ROUTER &&
1901 ctx->conn_type == SILC_SOCKET_TYPE_SERVER &&
1902 !SILC_PRIMARY_ROUTE(server)) {
1903 SILC_LOG_INFO(("Will not accept server connection because we do "
1904 "not have primary router connection established"));
1905 silc_server_disconnect_remote(server, sock,
1906 SILC_STATUS_ERR_PERM_DENIED,
1907 "We do not have connection to primary "
1908 "router established, try later");
1909 silc_free(sock->user_data);
1910 server->stat.auth_failures++;
1914 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1915 /* Verify whether this connection is after all allowed to connect */
1916 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1917 &server->config->param,
1918 rconn ? rconn->param : NULL,
1920 silc_free(sock->user_data);
1921 server->stat.auth_failures++;
1927 if (rconn->param->keepalive_secs)
1928 hearbeat_timeout = rconn->param->keepalive_secs;
1931 initiator = rconn->initiator;
1932 backup_local = rconn->backup_local;
1933 backup_router = rconn->backup_router;
1934 backup_replace_ip = rconn->backup_replace_ip;
1935 backup_replace_port = rconn->backup_replace_port;
1939 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1940 /* Verify whether this connection is after all allowed to connect */
1941 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1942 &server->config->param,
1943 sconn ? sconn->param : NULL,
1945 silc_free(sock->user_data);
1946 server->stat.auth_failures++;
1951 if (sconn->param->keepalive_secs)
1952 hearbeat_timeout = sconn->param->keepalive_secs;
1955 backup_router = sconn->backup_router;
1959 /* If we are primary router and we have backup router configured
1960 but it has not connected to use yet, do not accept any other
1962 if (server->wait_backup && server->server_type == SILC_ROUTER &&
1963 !server->backup_router && !backup_router) {
1964 SilcServerConfigRouter *router;
1965 router = silc_server_config_get_backup_router(server);
1966 if (router && strcmp(server->config->server_info->primary->server_ip,
1968 silc_server_find_socket_by_host(server,
1969 SILC_SOCKET_TYPE_SERVER,
1970 router->backup_replace_ip, 0)) {
1971 SILC_LOG_INFO(("Will not accept connections because we do "
1972 "not have backup router connection established"));
1973 silc_server_disconnect_remote(server, sock,
1974 SILC_STATUS_ERR_PERM_DENIED,
1975 "We do not have connection to backup "
1976 "router established, try later");
1977 silc_free(sock->user_data);
1978 server->stat.auth_failures++;
1980 /* From here on, wait 10 seconds for the backup router to appear. */
1981 silc_schedule_task_add(server->schedule, 0,
1982 silc_server_backup_router_wait,
1983 (void *)server, 10, 0,
1984 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1989 SILC_LOG_DEBUG(("Remote host is %s",
1990 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1991 "server" : (backup_router ?
1992 "backup router" : "router")));
1993 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
1994 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1995 "server" : (backup_router ?
1996 "backup router" : "router")));
1998 /* Add the server into server cache. The server name and Server ID
1999 is updated after we have received NEW_SERVER packet from the
2000 server. We mark ourselves as router for this server if we really
2003 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2004 server->local_list : (backup_router ?
2005 server->local_list :
2006 server->global_list)),
2008 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2009 SILC_SERVER : SILC_ROUTER),
2011 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2012 server->id_entry : (backup_router ?
2013 server->id_entry : NULL)),
2016 SILC_LOG_ERROR(("Could not add new server to cache"));
2017 silc_free(sock->user_data);
2018 silc_server_disconnect_remote(server, sock,
2019 SILC_STATUS_ERR_AUTH_FAILED, NULL);
2020 server->stat.auth_failures++;
2023 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
2025 id_entry = (void *)new_server;
2027 /* If the incoming connection is router and marked as backup router
2028 then add it to be one of our backups */
2029 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
2030 /* Change it back to SERVER type since that's what it really is. */
2032 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
2033 new_server->server_type = SILC_BACKUP_ROUTER;
2035 /* Remove the backup waiting with timeout */
2036 silc_schedule_task_add(server->schedule, 0,
2037 silc_server_backup_router_wait,
2038 (void *)server, 5, 0,
2039 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2043 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
2044 server->stat.my_servers++;
2046 server->stat.my_routers++;
2047 server->stat.routers++;
2049 server->stat.servers++;
2051 /* Check whether this connection is to be our primary router connection
2052 if we do not already have the primary route. */
2053 if (!backup_router &&
2054 server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
2055 if (silc_server_config_is_primary_route(server) && !initiator)
2058 SILC_LOG_DEBUG(("We are not standalone server anymore"));
2059 server->standalone = FALSE;
2060 if (!server->id_entry->router) {
2061 server->id_entry->router = id_entry;
2062 server->router = id_entry;
2073 sock->type = ctx->conn_type;
2075 /* Add the common data structure to the ID entry. */
2076 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
2078 /* Add to sockets internal pointer for fast referencing */
2079 silc_free(sock->user_data);
2080 sock->user_data = id_entry;
2082 /* Connection has been fully established now. Everything is ok. */
2083 SILC_LOG_DEBUG(("New connection authenticated"));
2085 /* Perform keepalive. The `hb_context' will be freed automatically
2086 when finally calling the silc_socket_free function. */
2087 silc_socket_set_heartbeat(sock, hearbeat_timeout, server,
2088 silc_server_perform_heartbeat,
2092 silc_schedule_task_del_by_callback(server->schedule,
2093 silc_server_failure_callback);
2094 silc_protocol_free(protocol);
2096 silc_packet_context_free(ctx->packet);
2098 silc_ske_free(ctx->ske);
2099 silc_free(ctx->dest_id);
2100 silc_server_config_unref(&ctx->cconfig);
2101 silc_server_config_unref(&ctx->sconfig);
2102 silc_server_config_unref(&ctx->rconfig);
2104 sock->protocol = NULL;
2107 /* This function is used to read packets from network and send packets to
2108 network. This is usually a generic task. */
2110 SILC_TASK_CALLBACK(silc_server_packet_process)
2112 SilcServer server = (SilcServer)context;
2113 SilcSocketConnection sock = server->sockets[fd];
2114 SilcIDListData idata;
2115 SilcCipher cipher = NULL;
2116 SilcHmac hmac = NULL;
2117 SilcUInt32 sequence = 0;
2121 SILC_LOG_DEBUG(("Unknown socket connection"));
2125 /* Packet sending */
2127 if (type == SILC_TASK_WRITE) {
2128 /* Do not send data to disconnected connection */
2129 if (SILC_IS_DISCONNECTED(sock)) {
2130 SILC_LOG_DEBUG(("Disconnected socket connection, cannot send"));
2134 server->stat.packets_sent++;
2136 /* Send the packet */
2137 ret = silc_packet_send(sock, TRUE);
2139 /* If returned -2 could not write to connection now, will do
2145 SILC_LOG_ERROR(("Error sending packet to connection "
2146 "%s:%d [%s]", sock->hostname, sock->port,
2147 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2148 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2149 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2154 /* The packet has been sent and now it is time to set the connection
2155 back to only for input. When there is again some outgoing data
2156 available for this connection it will be set for output as well.
2157 This call clears the output setting and sets it only for input. */
2158 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
2159 SILC_UNSET_OUTBUF_PENDING(sock);
2161 silc_buffer_clear(sock->outbuf);
2165 /* Packet receiving */
2167 /* Read some data from connection */
2168 ret = silc_packet_receive(sock);
2172 SILC_LOG_ERROR(("Error receiving packet from connection "
2173 "%s:%d [%s] %s", sock->hostname, sock->port,
2174 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2175 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2176 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2177 "Router"), strerror(errno)));
2183 SILC_LOG_DEBUG(("Read EOF"));
2185 /* If connection is disconnecting already we will finally
2186 close the connection */
2187 if (SILC_IS_DISCONNECTING(sock)) {
2188 if (sock->user_data)
2189 silc_server_free_sock_user_data(server, sock, NULL);
2190 silc_server_close_connection(server, sock);
2194 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
2195 SILC_SET_DISCONNECTING(sock);
2197 if (sock->user_data) {
2199 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
2200 silc_server_free_sock_user_data(server, sock, tmp);
2202 silc_server_free_sock_user_data(server, sock, NULL);
2203 } else if (server->router_conn && server->router_conn->sock == sock &&
2204 !server->router && server->standalone)
2205 silc_schedule_task_add(server->schedule, 0,
2206 silc_server_connect_to_router,
2209 SILC_TASK_PRI_NORMAL);
2211 silc_server_close_connection(server, sock);
2215 /* If connection is disconnecting or disconnected we will ignore
2217 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2218 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
2222 /* Get keys and stuff from ID entry */
2223 idata = (SilcIDListData)sock->user_data;
2225 cipher = idata->receive_key;
2226 hmac = idata->hmac_receive;
2227 sequence = idata->psn_receive;
2230 /* Process the packet. This will call the parser that will then
2231 decrypt and parse the packet. */
2232 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
2233 TRUE : FALSE, cipher, hmac, sequence,
2234 silc_server_packet_parse, server);
2236 /* If processing failed the connection is closed. */
2238 if (sock->user_data)
2239 silc_server_free_sock_user_data(server, sock, NULL);
2240 silc_server_close_connection(server, sock);
2244 /* Parses whole packet, received earlier. */
2246 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
2248 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
2249 SilcServer server = (SilcServer)parse_ctx->context;
2250 SilcSocketConnection sock = parse_ctx->sock;
2251 SilcPacketContext *packet = parse_ctx->packet;
2252 SilcIDListData idata = (SilcIDListData)sock->user_data;
2255 server->stat.packets_received++;
2257 /* Parse the packet */
2258 if (parse_ctx->normal)
2259 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
2261 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
2263 /* If entry is disabled ignore what we got. */
2264 if (idata && idata->status & SILC_IDLIST_STATUS_DISABLED &&
2265 ret != SILC_PACKET_HEARTBEAT && ret != SILC_PACKET_RESUME_ROUTER &&
2266 ret != SILC_PACKET_REKEY && ret != SILC_PACKET_REKEY_DONE) {
2267 SILC_LOG_DEBUG(("Connection is disabled"));
2271 if (ret == SILC_PACKET_NONE) {
2272 SILC_LOG_DEBUG(("Error parsing packet"));
2276 /* Check that the the current client ID is same as in the client's packet. */
2277 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
2278 SilcClientEntry client = (SilcClientEntry)sock->user_data;
2279 if (client && client->id && packet->src_id) {
2280 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
2281 packet->src_id_type);
2282 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
2284 SILC_LOG_DEBUG(("Packet source is not same as sender"));
2291 if (server->server_type == SILC_ROUTER) {
2292 /* Route the packet if it is not destined to us. Other ID types but
2293 server are handled separately after processing them. */
2294 if (packet->dst_id && !(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
2295 packet->dst_id_type == SILC_ID_SERVER &&
2296 sock->type != SILC_SOCKET_TYPE_CLIENT &&
2297 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
2299 /* Route the packet to fastest route for the destination ID */
2300 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
2301 packet->dst_id_type);
2304 silc_server_packet_route(server,
2305 silc_server_route_get(server, id,
2306 packet->dst_id_type),
2313 /* Parse the incoming packet type */
2314 silc_server_packet_parse_type(server, sock, packet);
2316 /* Broadcast packet if it is marked as broadcast packet and it is
2317 originated from router and we are router. */
2318 if (server->server_type == SILC_ROUTER &&
2319 sock->type == SILC_SOCKET_TYPE_ROUTER &&
2320 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
2321 /* Broadcast to our primary route */
2322 silc_server_packet_broadcast(server, SILC_PRIMARY_ROUTE(server), packet);
2324 /* If we have backup routers then we need to feed all broadcast
2325 data to those servers. */
2326 silc_server_backup_broadcast(server, sock, packet);
2330 silc_packet_context_free(packet);
2331 silc_free(parse_ctx);
2334 /* Parser callback called by silc_packet_receive_process. This merely
2335 registers timeout that will handle the actual parsing when appropriate. */
2337 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
2340 SilcServer server = (SilcServer)context;
2341 SilcSocketConnection sock = parser_context->sock;
2342 SilcIDListData idata = (SilcIDListData)sock->user_data;
2345 idata->psn_receive = parser_context->packet->sequence + 1;
2347 /* If protocol for this connection is key exchange or rekey then we'll
2348 process all packets synchronously, since there might be packets in
2349 queue that we are not able to decrypt without first processing the
2350 packets before them. */
2351 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
2352 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
2353 (sock->protocol && sock->protocol->protocol &&
2354 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2355 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
2356 silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2359 /* Reprocess data since we'll return FALSE here. This is because
2360 the idata->receive_key might have become valid in the last packet
2361 and we want to call this processor with valid cipher. */
2363 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
2364 TRUE : FALSE, idata->receive_key,
2365 idata->hmac_receive, idata->psn_receive,
2366 silc_server_packet_parse, server);
2368 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
2369 TRUE : FALSE, NULL, NULL, 0,
2370 silc_server_packet_parse, server);
2374 switch (sock->type) {
2375 case SILC_SOCKET_TYPE_UNKNOWN:
2376 case SILC_SOCKET_TYPE_CLIENT:
2377 /* Parse the packet with timeout */
2378 silc_schedule_task_add(server->schedule, sock->sock,
2379 silc_server_packet_parse_real,
2380 (void *)parser_context, 0, 100000,
2382 SILC_TASK_PRI_NORMAL);
2384 case SILC_SOCKET_TYPE_SERVER:
2385 case SILC_SOCKET_TYPE_ROUTER:
2386 /* Packets from servers are parsed immediately */
2387 silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2397 /* Parses the packet type and calls what ever routines the packet type
2398 requires. This is done for all incoming packets. */
2400 void silc_server_packet_parse_type(SilcServer server,
2401 SilcSocketConnection sock,
2402 SilcPacketContext *packet)
2404 SilcPacketType type = packet->type;
2405 SilcIDListData idata = (SilcIDListData)sock->user_data;
2407 SILC_LOG_DEBUG(("Received %s packet [flags %d]",
2408 silc_get_packet_name(type), packet->flags));
2410 /* Parse the packet type */
2412 case SILC_PACKET_DISCONNECT:
2415 char *message = NULL;
2417 if (packet->flags & SILC_PACKET_FLAG_LIST)
2419 if (packet->buffer->len < 1)
2422 status = (SilcStatus)packet->buffer->data[0];
2423 if (packet->buffer->len > 1 &&
2424 silc_utf8_valid(packet->buffer->data + 1, packet->buffer->len - 1))
2425 message = silc_memdup(packet->buffer->data + 1,
2426 packet->buffer->len - 1);
2428 SILC_LOG_INFO(("Disconnected by %s (%s): %s (%d) %s",
2429 sock->ip, sock->hostname,
2430 silc_get_status_message(status), status,
2431 message ? message : ""));
2434 /* Handle the disconnection from our end too */
2435 if (sock->user_data && SILC_IS_LOCAL(sock->user_data))
2436 silc_server_free_sock_user_data(server, sock, NULL);
2437 silc_server_close_connection(server, sock);
2441 case SILC_PACKET_SUCCESS:
2443 * Success received for something. For now we can have only
2444 * one protocol for connection executing at once hence this
2445 * success message is for whatever protocol is executing currently.
2447 if (packet->flags & SILC_PACKET_FLAG_LIST)
2450 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2453 case SILC_PACKET_FAILURE:
2455 * Failure received for something. For now we can have only
2456 * one protocol for connection executing at once hence this
2457 * failure message is for whatever protocol is executing currently.
2459 if (packet->flags & SILC_PACKET_FLAG_LIST)
2461 if (sock->protocol) {
2462 SilcServerFailureContext f;
2463 f = silc_calloc(1, sizeof(*f));
2464 f->sock = silc_socket_dup(sock);
2466 /* We will wait 5 seconds to process this failure packet */
2467 silc_schedule_task_add(server->schedule, sock->sock,
2468 silc_server_failure_callback, (void *)f, 5, 0,
2469 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2473 case SILC_PACKET_REJECT:
2474 if (packet->flags & SILC_PACKET_FLAG_LIST)
2479 case SILC_PACKET_NOTIFY:
2481 * Received notify packet. Server can receive notify packets from
2482 * router. Server then relays the notify messages to clients if needed.
2484 if (packet->flags & SILC_PACKET_FLAG_LIST)
2485 silc_server_notify_list(server, sock, packet);
2487 silc_server_notify(server, sock, packet);
2493 case SILC_PACKET_CHANNEL_MESSAGE:
2495 * Received channel message. Channel messages are special packets
2496 * (although probably most common ones) thus they are handled
2499 if (packet->flags & SILC_PACKET_FLAG_LIST)
2501 idata->last_receive = time(NULL);
2502 silc_server_channel_message(server, sock, packet);
2505 case SILC_PACKET_CHANNEL_KEY:
2507 * Received key for channel. As channels are created by the router
2508 * the keys are as well. We will distribute the key to all of our
2509 * locally connected clients on the particular channel. Router
2510 * never receives this channel and thus is ignored.
2512 if (packet->flags & SILC_PACKET_FLAG_LIST)
2514 silc_server_channel_key(server, sock, packet);
2520 case SILC_PACKET_COMMAND:
2522 * Recived command. Processes the command request and allocates the
2523 * command context and calls the command.
2525 if (packet->flags & SILC_PACKET_FLAG_LIST)
2527 silc_server_command_process(server, sock, packet);
2530 case SILC_PACKET_COMMAND_REPLY:
2532 * Received command reply packet. Received command reply to command. It
2533 * may be reply to command sent by us or reply to command sent by client
2534 * that we've routed further.
2536 if (packet->flags & SILC_PACKET_FLAG_LIST)
2538 silc_server_command_reply(server, sock, packet);
2542 * Private Message packets
2544 case SILC_PACKET_PRIVATE_MESSAGE:
2546 * Received private message packet. The packet is coming from either
2549 if (packet->flags & SILC_PACKET_FLAG_LIST)
2551 idata->last_receive = time(NULL);
2552 silc_server_private_message(server, sock, packet);
2555 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2557 * Private message key packet.
2559 if (packet->flags & SILC_PACKET_FLAG_LIST)
2561 silc_server_private_message_key(server, sock, packet);
2565 * Key Exchange protocol packets
2567 case SILC_PACKET_KEY_EXCHANGE:
2568 if (packet->flags & SILC_PACKET_FLAG_LIST)
2571 if (sock->protocol && sock->protocol->protocol &&
2572 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2573 SilcServerKEInternalContext *proto_ctx =
2574 (SilcServerKEInternalContext *)sock->protocol->context;
2576 proto_ctx->packet = silc_packet_context_dup(packet);
2578 /* Let the protocol handle the packet */
2579 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2581 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2582 "protocol active, packet dropped."));
2586 case SILC_PACKET_KEY_EXCHANGE_1:
2587 if (packet->flags & SILC_PACKET_FLAG_LIST)
2590 if (sock->protocol && sock->protocol->protocol &&
2591 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2592 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2594 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2595 SilcServerRekeyInternalContext *proto_ctx =
2596 (SilcServerRekeyInternalContext *)sock->protocol->context;
2598 if (proto_ctx->packet)
2599 silc_packet_context_free(proto_ctx->packet);
2601 proto_ctx->packet = silc_packet_context_dup(packet);
2603 /* Let the protocol handle the packet */
2604 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2606 SilcServerKEInternalContext *proto_ctx =
2607 (SilcServerKEInternalContext *)sock->protocol->context;
2609 if (proto_ctx->packet)
2610 silc_packet_context_free(proto_ctx->packet);
2612 proto_ctx->packet = silc_packet_context_dup(packet);
2613 proto_ctx->dest_id_type = packet->src_id_type;
2614 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2615 packet->src_id_type);
2616 if (!proto_ctx->dest_id)
2619 /* Let the protocol handle the packet */
2620 silc_protocol_execute(sock->protocol, server->schedule,
2624 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2625 "protocol active, packet dropped."));
2629 case SILC_PACKET_KEY_EXCHANGE_2:
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 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2637 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2638 SilcServerRekeyInternalContext *proto_ctx =
2639 (SilcServerRekeyInternalContext *)sock->protocol->context;
2641 if (proto_ctx->packet)
2642 silc_packet_context_free(proto_ctx->packet);
2644 proto_ctx->packet = silc_packet_context_dup(packet);
2646 /* Let the protocol handle the packet */
2647 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2649 SilcServerKEInternalContext *proto_ctx =
2650 (SilcServerKEInternalContext *)sock->protocol->context;
2652 if (proto_ctx->packet)
2653 silc_packet_context_free(proto_ctx->packet);
2655 proto_ctx->packet = silc_packet_context_dup(packet);
2656 proto_ctx->dest_id_type = packet->src_id_type;
2657 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2658 packet->src_id_type);
2659 if (!proto_ctx->dest_id)
2662 /* Let the protocol handle the packet */
2663 silc_protocol_execute(sock->protocol, server->schedule,
2667 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2668 "protocol active, packet dropped."));
2672 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2674 * Connection authentication request packet. When we receive this packet
2675 * we will send to the other end information about our mandatory
2676 * authentication method for the connection. This packet maybe received
2679 if (packet->flags & SILC_PACKET_FLAG_LIST)
2681 silc_server_connection_auth_request(server, sock, packet);
2685 * Connection Authentication protocol packets
2687 case SILC_PACKET_CONNECTION_AUTH:
2688 /* Start of the authentication protocol. We receive here the
2689 authentication data and will verify it. */
2690 if (packet->flags & SILC_PACKET_FLAG_LIST)
2693 if (sock->protocol && sock->protocol->protocol->type
2694 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2696 SilcServerConnAuthInternalContext *proto_ctx =
2697 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2699 proto_ctx->packet = silc_packet_context_dup(packet);
2701 /* Let the protocol handle the packet */
2702 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2704 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2705 "protocol active, packet dropped."));
2709 case SILC_PACKET_NEW_ID:
2711 * Received New ID packet. This includes some new ID that has been
2712 * created. It may be for client, server or channel. This is the way
2713 * to distribute information about new registered entities in the
2716 if (packet->flags & SILC_PACKET_FLAG_LIST)
2717 silc_server_new_id_list(server, sock, packet);
2719 silc_server_new_id(server, sock, packet);
2722 case SILC_PACKET_NEW_CLIENT:
2724 * Received new client packet. This includes client information that
2725 * we will use to create initial client ID. After creating new
2726 * ID we will send it to the client.
2728 if (packet->flags & SILC_PACKET_FLAG_LIST)
2730 silc_server_new_client(server, sock, packet);
2733 case SILC_PACKET_NEW_SERVER:
2735 * Received new server packet. This includes Server ID and some other
2736 * information that we may save. This is received after server has
2739 if (packet->flags & SILC_PACKET_FLAG_LIST)
2741 silc_server_new_server(server, sock, packet);
2744 case SILC_PACKET_NEW_CHANNEL:
2746 * Received new channel packet. Information about new channel in the
2747 * network are distributed using this packet.
2749 if (packet->flags & SILC_PACKET_FLAG_LIST)
2750 silc_server_new_channel_list(server, sock, packet);
2752 silc_server_new_channel(server, sock, packet);
2755 case SILC_PACKET_HEARTBEAT:
2757 * Received heartbeat.
2759 if (packet->flags & SILC_PACKET_FLAG_LIST)
2763 case SILC_PACKET_KEY_AGREEMENT:
2765 * Received heartbeat.
2767 if (packet->flags & SILC_PACKET_FLAG_LIST)
2769 silc_server_key_agreement(server, sock, packet);
2772 case SILC_PACKET_REKEY:
2774 * Received re-key packet. The sender wants to regenerate the session
2777 if (packet->flags & SILC_PACKET_FLAG_LIST)
2779 silc_server_rekey(server, sock, packet);
2782 case SILC_PACKET_REKEY_DONE:
2784 * The re-key is done.
2786 if (packet->flags & SILC_PACKET_FLAG_LIST)
2789 if (sock->protocol && sock->protocol->protocol &&
2790 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2792 SilcServerRekeyInternalContext *proto_ctx =
2793 (SilcServerRekeyInternalContext *)sock->protocol->context;
2795 if (proto_ctx->packet)
2796 silc_packet_context_free(proto_ctx->packet);
2798 proto_ctx->packet = silc_packet_context_dup(packet);
2800 /* Let the protocol handle the packet */
2801 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2803 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2804 "protocol active, packet dropped."));
2808 case SILC_PACKET_FTP:
2810 if (packet->flags & SILC_PACKET_FLAG_LIST)
2812 silc_server_ftp(server, sock, packet);
2815 case SILC_PACKET_RESUME_CLIENT:
2817 if (packet->flags & SILC_PACKET_FLAG_LIST)
2819 silc_server_resume_client(server, sock, packet);
2822 case SILC_PACKET_RESUME_ROUTER:
2823 /* Resume router packet received. This packet is received for backup
2824 router resuming protocol. */
2825 if (packet->flags & SILC_PACKET_FLAG_LIST)
2827 silc_server_backup_resume_router(server, sock, packet);
2831 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2836 /* Creates connection to a remote router. */
2838 void silc_server_create_connection(SilcServer server,
2839 const char *remote_host, SilcUInt32 port)
2841 SilcServerConnection sconn;
2843 /* Allocate connection object for hold connection specific stuff. */
2844 sconn = silc_calloc(1, sizeof(*sconn));
2845 sconn->remote_host = strdup(remote_host);
2846 sconn->remote_port = port;
2847 sconn->no_reconnect = TRUE;
2849 silc_schedule_task_add(server->schedule, 0,
2850 silc_server_connect_router,
2851 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2852 SILC_TASK_PRI_NORMAL);
2855 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2857 silc_socket_free(context);
2860 /* Closes connection to socket connection */
2862 void silc_server_close_connection(SilcServer server,
2863 SilcSocketConnection sock)
2867 if (!server->sockets[sock->sock] && SILC_IS_DISCONNECTED(sock)) {
2868 silc_schedule_task_add(server->schedule, 0,
2869 silc_server_close_connection_final,
2870 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2871 SILC_TASK_PRI_NORMAL);
2875 memset(tmp, 0, sizeof(tmp));
2876 silc_socket_get_error(sock, tmp, sizeof(tmp));
2877 SILC_LOG_INFO(("Closing connection %s:%d [%s] %s", sock->hostname,
2879 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2880 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2881 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2882 "Router"), tmp[0] ? tmp : ""));
2884 /* We won't listen for this connection anymore */
2885 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2887 /* Unregister all tasks */
2888 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2890 /* Close the actual connection */
2891 silc_net_close_connection(sock->sock);
2892 server->sockets[sock->sock] = NULL;
2894 /* If sock->user_data is NULL then we'll check for active protocols
2895 here since the silc_server_free_sock_user_data has not been called
2896 for this connection. */
2897 if (!sock->user_data) {
2898 /* If any protocol is active cancel its execution. It will call
2899 the final callback which will finalize the disconnection. */
2900 if (sock->protocol) {
2901 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
2902 silc_protocol_cancel(sock->protocol, server->schedule);
2903 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2904 silc_protocol_execute_final(sock->protocol, server->schedule);
2905 sock->protocol = NULL;
2910 silc_schedule_task_add(server->schedule, 0,
2911 silc_server_close_connection_final,
2912 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2913 SILC_TASK_PRI_NORMAL);
2916 /* Sends disconnect message to remote connection and disconnects the
2919 void silc_server_disconnect_remote(SilcServer server,
2920 SilcSocketConnection sock,
2921 SilcStatus status, ...)
2924 unsigned char buf[512];
2929 if (!sock || SILC_IS_DISCONNECTED(sock))
2932 memset(buf, 0, sizeof(buf));
2933 va_start(ap, status);
2934 cp = va_arg(ap, char *);
2936 vsnprintf(buf, sizeof(buf) - 1, cp, ap);
2941 SILC_LOG_DEBUG(("Disconnecting remote host"));
2943 /* Notify remote end that the conversation is over. The notify message
2944 is tried to be sent immediately. */
2948 len += silc_utf8_encoded_len(buf, strlen(buf), SILC_STRING_ASCII);
2950 buffer = silc_buffer_alloc_size(len);
2954 buffer->data[0] = status;
2956 silc_utf8_encode(buf, strlen(buf), SILC_STRING_ASCII, buffer->data + 1,
2958 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2959 buffer->data, buffer->len, TRUE);
2960 silc_buffer_free(buffer);
2963 silc_server_packet_queue_purge(server, sock);
2965 /* Mark the connection to be disconnected */
2966 SILC_SET_DISCONNECTED(sock);
2967 silc_server_close_connection(server, sock);
2970 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2972 SilcServer server = app_context;
2973 SilcClientEntry client = context;
2975 assert(!silc_hash_table_count(client->channels));
2977 silc_idlist_del_data(client);
2978 silc_idcache_purge_by_context(server->local_list->clients, client);
2981 /* Frees client data and notifies about client's signoff. */
2983 void silc_server_free_client_data(SilcServer server,
2984 SilcSocketConnection sock,
2985 SilcClientEntry client,
2987 const char *signoff)
2989 SILC_LOG_DEBUG(("Freeing client data"));
2991 /* If there is pending outgoing data for the client then purge it
2992 to the network before removing the client entry. */
2993 silc_server_packet_queue_purge(server, sock);
2996 /* Check if anyone is watching this nickname */
2997 if (server->server_type == SILC_ROUTER)
2998 silc_server_check_watcher_list(server, client, NULL,
2999 SILC_NOTIFY_TYPE_SIGNOFF);
3001 /* Send SIGNOFF notify to routers. */
3003 silc_server_send_notify_signoff(server, SILC_PRIMARY_ROUTE(server),
3004 SILC_BROADCAST(server), client->id,
3008 /* Remove client from all channels */
3010 silc_server_remove_from_channels(server, NULL, client,
3011 TRUE, (char *)signoff, TRUE);
3013 silc_server_remove_from_channels(server, NULL, client,
3014 FALSE, NULL, FALSE);
3016 /* Remove this client from watcher list if it is */
3017 silc_server_del_from_watcher_list(server, client);
3019 /* Update statistics */
3020 server->stat.my_clients--;
3021 server->stat.clients--;
3022 if (server->stat.cell_clients)
3023 server->stat.cell_clients--;
3024 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
3025 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
3026 silc_schedule_task_del_by_context(server->schedule, client);
3028 /* We will not delete the client entry right away. We will take it
3029 into history (for WHOWAS command) for 5 minutes, unless we're
3030 shutting down server. */
3031 if (!server->server_shutdown) {
3032 silc_schedule_task_add(server->schedule, 0,
3033 silc_server_free_client_data_timeout,
3035 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
3036 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
3037 client->data.status &= ~SILC_IDLIST_STATUS_LOCAL;
3039 client->router = NULL;
3040 client->connection = NULL;
3042 /* Delete directly since we're shutting down server */
3043 silc_idlist_del_data(client);
3044 silc_idlist_del_client(server->local_list, client);
3048 /* Frees user_data pointer from socket connection object. This also sends
3049 appropriate notify packets to the network to inform about leaving
3052 void silc_server_free_sock_user_data(SilcServer server,
3053 SilcSocketConnection sock,
3054 const char *signoff_message)
3056 switch (sock->type) {
3057 case SILC_SOCKET_TYPE_CLIENT:
3059 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
3060 silc_server_free_client_data(server, sock, user_data, TRUE,
3064 case SILC_SOCKET_TYPE_SERVER:
3065 case SILC_SOCKET_TYPE_ROUTER:
3067 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
3068 SilcServerEntry backup_router = NULL;
3070 SILC_LOG_DEBUG(("Freeing server data"));
3073 backup_router = silc_server_backup_get(server, user_data->id);
3075 if (!server->backup_router && server->server_type == SILC_ROUTER &&
3076 backup_router == server->id_entry &&
3077 sock->type != SILC_SOCKET_TYPE_ROUTER)
3078 backup_router = NULL;
3080 if (server->server_shutdown)
3081 backup_router = NULL;
3083 /* If this was our primary router connection then we're lost to
3084 the outside world. */
3085 if (server->router == user_data) {
3086 /* Check whether we have a backup router connection */
3087 if (!backup_router || backup_router == user_data) {
3088 silc_schedule_task_add(server->schedule, 0,
3089 silc_server_connect_to_router,
3092 SILC_TASK_PRI_NORMAL);
3094 server->id_entry->router = NULL;
3095 server->router = NULL;
3096 server->standalone = TRUE;
3097 backup_router = NULL;
3099 if (server->id_entry != backup_router) {
3100 SILC_LOG_INFO(("New primary router is backup router %s",
3101 backup_router->server_name));
3102 server->id_entry->router = backup_router;
3103 server->router = backup_router;
3104 server->router_connect = time(0);
3105 server->backup_primary = TRUE;
3107 SILC_LOG_INFO(("We are now new primary router in this cell"));
3108 server->id_entry->router = NULL;
3109 server->router = NULL;
3110 server->standalone = TRUE;
3112 /* We stop here to take a breath */
3116 if (server->server_type == SILC_BACKUP_ROUTER) {
3117 server->server_type = SILC_ROUTER;
3119 /* We'll need to constantly try to reconnect to the primary
3120 router so that we'll see when it comes back online. */
3121 silc_server_backup_reconnect(server, sock->ip, sock->port,
3122 silc_server_backup_connected,
3126 /* Mark this connection as replaced */
3127 silc_server_backup_replaced_add(server, user_data->id,
3130 } else if (backup_router) {
3131 SILC_LOG_INFO(("Enabling the use of backup router %s",
3132 backup_router->server_name));
3133 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
3134 backup_router->server_name));
3136 /* Mark this connection as replaced */
3137 silc_server_backup_replaced_add(server, user_data->id,
3141 if (!backup_router) {
3142 /* Remove all servers that are originated from this server, and
3143 remove the clients of those servers too. */
3144 silc_server_remove_servers_by_server(server, user_data, TRUE);
3146 /* Remove the clients that this server owns as they will become
3147 invalid now too. For backup router the server is actually
3148 coming from the primary router, so mark that as the owner
3150 if (server->server_type == SILC_BACKUP_ROUTER &&
3151 sock->type == SILC_SOCKET_TYPE_SERVER)
3152 silc_server_remove_clients_by_server(server, server->router,
3155 silc_server_remove_clients_by_server(server, user_data,
3158 /* Remove channels owned by this server */
3159 if (server->server_type == SILC_SERVER)
3160 silc_server_remove_channels_by_server(server, user_data);
3162 /* Enable local server connections that may be disabled */
3163 silc_server_local_servers_toggle_enabled(server, TRUE);
3165 /* Update the client entries of this server to the new backup
3166 router. If we are the backup router we also resolve the real
3167 servers for the clients. After updating is over this also
3168 removes the clients that this server explicitly owns. */
3169 silc_server_update_clients_by_server(server, user_data,
3170 backup_router, TRUE);
3172 /* If we are router and just lost our primary router (now standlaone)
3173 we remove everything that was behind it, since we don't know
3175 if (server->server_type == SILC_ROUTER && server->standalone)
3176 /* Remove all servers that are originated from this server, and
3177 remove the clients of those servers too. */
3178 silc_server_remove_servers_by_server(server, user_data, TRUE);
3180 /* Finally remove the clients that are explicitly owned by this
3181 server. They go down with the server. */
3182 silc_server_remove_clients_by_server(server, user_data,
3185 /* Update our server cache to use the new backup router too. */
3186 silc_server_update_servers_by_server(server, user_data, backup_router);
3187 if (server->server_type == SILC_SERVER)
3188 silc_server_update_channels_by_server(server, user_data,
3191 /* Send notify about primary router going down to local operators */
3192 if (server->backup_router)
3193 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3194 SILC_NOTIFY_TYPE_NONE,
3195 ("%s switched to backup router %s "
3196 "(we are primary router now)",
3197 server->server_name, server->server_name));
3198 else if (server->router)
3199 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3200 SILC_NOTIFY_TYPE_NONE,
3201 ("%s switched to backup router %s",
3202 server->server_name,
3203 server->router->server_name));
3206 /* Free the server entry */
3207 silc_server_backup_del(server, user_data);
3208 silc_server_backup_replaced_del(server, user_data);
3209 silc_idlist_del_data(user_data);
3210 if (!silc_idlist_del_server(server->local_list, user_data))
3211 silc_idlist_del_server(server->global_list, user_data);
3212 if (sock->type == SILC_SOCKET_TYPE_SERVER) {
3213 server->stat.my_servers--;
3215 server->stat.my_routers--;
3216 server->stat.routers--;
3218 server->stat.servers--;
3219 if (server->server_type == SILC_ROUTER)
3220 server->stat.cell_servers--;
3222 if (backup_router && backup_router != server->id_entry) {
3223 /* Announce all of our stuff that was created about 5 minutes ago.
3224 The backup router knows all the other stuff already. */
3225 if (server->server_type == SILC_ROUTER)
3226 silc_server_announce_servers(server, FALSE, time(0) - 300,
3227 backup_router->connection);
3229 /* Announce our clients and channels to the router */
3230 silc_server_announce_clients(server, time(0) - 300,
3231 backup_router->connection);
3232 silc_server_announce_channels(server, time(0) - 300,
3233 backup_router->connection);
3239 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
3241 SILC_LOG_DEBUG(("Freeing unknown connection data"));
3243 silc_idlist_del_data(user_data);
3244 silc_free(user_data);
3249 /* If any protocol is active cancel its execution */
3250 if (sock->protocol) {
3251 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3252 silc_protocol_cancel(sock->protocol, server->schedule);
3253 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3254 silc_protocol_execute_final(sock->protocol, server->schedule);
3255 sock->protocol = NULL;
3258 sock->user_data = NULL;
3261 /* Removes client from all channels it has joined. This is used when client
3262 connection is disconnected. If the client on a channel is last, the
3263 channel is removed as well. This sends the SIGNOFF notify types. */
3265 void silc_server_remove_from_channels(SilcServer server,
3266 SilcSocketConnection sock,
3267 SilcClientEntry client,
3269 const char *signoff_message,
3272 SilcChannelEntry channel;
3273 SilcChannelClientEntry chl;
3274 SilcHashTableList htl;
3275 SilcBuffer clidp = NULL;
3280 SILC_LOG_DEBUG(("Removing client from joined channels"));
3282 if (notify && !client->id)
3286 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3291 /* Remove the client from all channels. The client is removed from
3292 the channels' user list. */
3293 silc_hash_table_list(client->channels, &htl);
3294 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3295 channel = chl->channel;
3297 /* Remove channel if this is last client leaving the channel, unless
3298 the channel is permanent. */
3299 if (server->server_type != SILC_SERVER &&
3300 silc_hash_table_count(channel->user_list) < 2) {
3301 silc_server_channel_delete(server, channel);
3305 silc_hash_table_del(client->channels, channel);
3306 silc_hash_table_del(channel->user_list, client);
3307 channel->user_count--;
3309 /* If there is no global users on the channel anymore mark the channel
3310 as local channel. Do not check if the removed client is local client. */
3311 if (server->server_type == SILC_SERVER && channel->global_users &&
3312 chl->client->router && !silc_server_channel_has_global(channel))
3313 channel->global_users = FALSE;
3315 memset(chl, 'A', sizeof(*chl));
3318 /* Update statistics */
3319 if (SILC_IS_LOCAL(client))
3320 server->stat.my_chanclients--;
3321 if (server->server_type == SILC_ROUTER) {
3322 server->stat.cell_chanclients--;
3323 server->stat.chanclients--;
3326 /* If there is not at least one local user on the channel then we don't
3327 need the channel entry anymore, we can remove it safely, unless the
3328 channel is permanent channel */
3329 if (server->server_type == SILC_SERVER &&
3330 !silc_server_channel_has_local(channel)) {
3331 /* Notify about leaving client if this channel has global users. */
3332 if (notify && channel->global_users)
3333 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3334 SILC_NOTIFY_TYPE_SIGNOFF,
3335 signoff_message ? 2 : 1,
3336 clidp->data, clidp->len,
3337 signoff_message, signoff_message ?
3338 strlen(signoff_message) : 0);
3340 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3341 silc_server_channel_delete(server, channel);
3345 /* Send notify to channel about client leaving SILC and channel too */
3347 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3348 SILC_NOTIFY_TYPE_SIGNOFF,
3349 signoff_message ? 2 : 1,
3350 clidp->data, clidp->len,
3351 signoff_message, signoff_message ?
3352 strlen(signoff_message) : 0);
3354 /* Don't create keys if we are shutting down */
3355 if (server->server_shutdown)
3358 /* Re-generate channel key if needed */
3359 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3360 if (!silc_server_create_channel_key(server, channel, 0))
3363 /* Send the channel key to the channel. The key of course is not sent
3364 to the client who was removed from the channel. */
3365 silc_server_send_channel_key(server, client->connection, channel,
3366 server->server_type == SILC_ROUTER ?
3367 FALSE : !server->standalone);
3371 silc_hash_table_list_reset(&htl);
3373 silc_buffer_free(clidp);
3376 /* Removes client from one channel. This is used for example when client
3377 calls LEAVE command to remove itself from the channel. Returns TRUE
3378 if channel still exists and FALSE if the channel is removed when
3379 last client leaves the channel. If `notify' is FALSE notify messages
3382 bool silc_server_remove_from_one_channel(SilcServer server,
3383 SilcSocketConnection sock,
3384 SilcChannelEntry channel,
3385 SilcClientEntry client,
3388 SilcChannelClientEntry chl;
3391 SILC_LOG_DEBUG(("Removing %s from channel %s",
3392 silc_id_render(client->id, SILC_ID_CLIENT),
3393 channel->channel_name));
3395 /* Get the entry to the channel, if this client is not on the channel
3397 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
3400 /* Remove channel if this is last client leaving the channel, unless
3401 the channel is permanent. */
3402 if (server->server_type != SILC_SERVER &&
3403 silc_hash_table_count(channel->user_list) < 2) {
3404 silc_server_channel_delete(server, channel);
3408 silc_hash_table_del(client->channels, channel);
3409 silc_hash_table_del(channel->user_list, client);
3410 channel->user_count--;
3412 /* If there is no global users on the channel anymore mark the channel
3413 as local channel. Do not check if the client is local client. */
3414 if (server->server_type == SILC_SERVER && channel->global_users &&
3415 chl->client->router && !silc_server_channel_has_global(channel))
3416 channel->global_users = FALSE;
3418 memset(chl, 'O', sizeof(*chl));
3421 /* Update statistics */
3422 if (SILC_IS_LOCAL(client))
3423 server->stat.my_chanclients--;
3424 if (server->server_type == SILC_ROUTER) {
3425 server->stat.cell_chanclients--;
3426 server->stat.chanclients--;
3429 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3433 /* If there is not at least one local user on the channel then we don't
3434 need the channel entry anymore, we can remove it safely, unless the
3435 channel is permanent channel */
3436 if (server->server_type == SILC_SERVER &&
3437 !silc_server_channel_has_local(channel)) {
3438 /* Notify about leaving client if this channel has global users. */
3439 if (notify && channel->global_users)
3440 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3441 SILC_NOTIFY_TYPE_LEAVE, 1,
3442 clidp->data, clidp->len);
3444 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3445 silc_server_channel_delete(server, channel);
3446 silc_buffer_free(clidp);
3450 /* Send notify to channel about client leaving the channel */
3452 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3453 SILC_NOTIFY_TYPE_LEAVE, 1,
3454 clidp->data, clidp->len);
3456 silc_buffer_free(clidp);
3460 /* Timeout callback. This is called if connection is idle or for some
3461 other reason is not responding within some period of time. This
3462 disconnects the remote end. */
3464 SILC_TASK_CALLBACK(silc_server_timeout_remote)
3466 SilcServer server = (SilcServer)context;
3467 SilcSocketConnection sock = server->sockets[fd];
3468 SilcProtocolType protocol = 0;
3470 SILC_LOG_DEBUG(("Start"));
3475 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
3476 sock->hostname, sock->ip));
3478 /* If we have protocol active we must assure that we call the protocol's
3479 final callback so that all the memory is freed. */
3480 if (sock->protocol) {
3481 protocol = sock->protocol->protocol->type;
3482 silc_protocol_cancel(sock->protocol, server->schedule);
3483 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3484 silc_protocol_execute_final(sock->protocol, server->schedule);
3485 sock->protocol = NULL;
3489 if (sock->user_data)
3490 silc_server_free_sock_user_data(server, sock, NULL);
3492 silc_server_disconnect_remote(server, sock,
3494 SILC_PROTOCOL_SERVER_CONNECTION_AUTH ?
3495 SILC_STATUS_ERR_AUTH_FAILED :
3496 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
3497 "Connection timeout");
3500 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
3501 function may be used only by router. In real SILC network all channels
3502 are created by routers thus this function is never used by normal
3505 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3506 SilcServerID *router_id,
3512 SilcChannelID *channel_id;
3513 SilcChannelEntry entry;
3517 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3520 cipher = SILC_DEFAULT_CIPHER;
3522 hmac = SILC_DEFAULT_HMAC;
3524 /* Allocate cipher */
3525 if (!silc_cipher_alloc(cipher, &key))
3529 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3530 silc_cipher_free(key);
3534 channel_name = strdup(channel_name);
3536 /* Create the channel ID */
3537 if (!silc_id_create_channel_id(server, router_id, server->rng,
3539 silc_free(channel_name);
3540 silc_cipher_free(key);
3541 silc_hmac_free(newhmac);
3545 /* Create the channel */
3546 entry = silc_idlist_add_channel(server->local_list, channel_name,
3547 SILC_CHANNEL_MODE_NONE, channel_id,
3548 NULL, key, newhmac, 0);
3550 silc_free(channel_name);
3551 silc_cipher_free(key);
3552 silc_hmac_free(newhmac);
3553 silc_free(channel_id);
3557 entry->cipher = strdup(cipher);
3558 entry->hmac_name = strdup(hmac);
3560 /* Now create the actual key material */
3561 if (!silc_server_create_channel_key(server, entry,
3562 silc_cipher_get_key_len(key) / 8)) {
3563 silc_idlist_del_channel(server->local_list, entry);
3567 /* Notify other routers about the new channel. We send the packet
3568 to our primary route. */
3570 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3571 channel_name, entry->id,
3572 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3575 /* Distribute to backup routers */
3576 if (broadcast && server->server_type == SILC_ROUTER) {
3579 SilcUInt32 name_len = strlen(channel_name);
3580 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3581 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3583 packet = silc_channel_payload_encode(channel_name, name_len,
3584 cid, channel_id_len, entry->mode);
3585 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3586 packet->data, packet->len, FALSE, TRUE);
3588 silc_buffer_free(packet);
3591 server->stat.my_channels++;
3592 if (server->server_type == SILC_ROUTER) {
3593 server->stat.channels++;
3594 server->stat.cell_channels++;
3595 entry->users_resolved = TRUE;
3601 /* Same as above but creates the channel with Channel ID `channel_id. */
3604 silc_server_create_new_channel_with_id(SilcServer server,
3608 SilcChannelID *channel_id,
3611 SilcChannelEntry entry;
3615 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3618 cipher = SILC_DEFAULT_CIPHER;
3620 hmac = SILC_DEFAULT_HMAC;
3622 /* Allocate cipher */
3623 if (!silc_cipher_alloc(cipher, &key))
3627 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3628 silc_cipher_free(key);
3632 channel_name = strdup(channel_name);
3634 /* Create the channel */
3635 entry = silc_idlist_add_channel(server->local_list, channel_name,
3636 SILC_CHANNEL_MODE_NONE, channel_id,
3637 NULL, key, newhmac, 0);
3639 silc_cipher_free(key);
3640 silc_hmac_free(newhmac);
3641 silc_free(channel_name);
3645 /* Now create the actual key material */
3646 if (!silc_server_create_channel_key(server, entry,
3647 silc_cipher_get_key_len(key) / 8)) {
3648 silc_idlist_del_channel(server->local_list, entry);
3652 /* Notify other routers about the new channel. We send the packet
3653 to our primary route. */
3655 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3656 channel_name, entry->id,
3657 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3660 /* Distribute to backup routers */
3661 if (broadcast && server->server_type == SILC_ROUTER) {
3664 SilcUInt32 name_len = strlen(channel_name);
3665 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3666 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3668 packet = silc_channel_payload_encode(channel_name, name_len,
3669 cid, channel_id_len, entry->mode);
3670 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3671 packet->data, packet->len, FALSE, TRUE);
3673 silc_buffer_free(packet);
3676 server->stat.my_channels++;
3677 if (server->server_type == SILC_ROUTER) {
3678 server->stat.channels++;
3679 server->stat.cell_channels++;
3680 entry->users_resolved = TRUE;
3686 /* Channel's key re-key timeout callback. */
3688 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3690 SilcServer server = app_context;
3691 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3695 /* Return now if we are shutting down */
3696 if (server->server_shutdown)
3699 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3702 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3705 /* Generates new channel key. This is used to create the initial channel key
3706 but also to re-generate new key for channel. If `key_len' is provided
3707 it is the bytes of the key length. */
3709 bool silc_server_create_channel_key(SilcServer server,
3710 SilcChannelEntry channel,
3714 unsigned char channel_key[32], hash[32];
3717 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3718 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3722 SILC_LOG_DEBUG(("Generating channel %s key", channel->channel_name));
3724 if (!channel->channel_key)
3725 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3726 channel->channel_key = NULL;
3732 else if (channel->key_len)
3733 len = channel->key_len / 8;
3735 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3737 /* Create channel key */
3738 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3741 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3743 /* Remove old key if exists */
3745 memset(channel->key, 0, channel->key_len / 8);
3746 silc_free(channel->key);
3750 channel->key_len = len * 8;
3751 channel->key = silc_memdup(channel_key, len);
3752 memset(channel_key, 0, sizeof(channel_key));
3754 /* Generate HMAC key from the channel key data and set it */
3756 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3757 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3758 silc_hmac_set_key(channel->hmac, hash,
3759 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3760 memset(hash, 0, sizeof(hash));
3762 if (server->server_type == SILC_ROUTER) {
3763 if (!channel->rekey)
3764 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3765 channel->rekey->channel = channel;
3766 channel->rekey->key_len = key_len;
3767 if (channel->rekey->task)
3768 silc_schedule_task_del(server->schedule, channel->rekey->task);
3770 channel->rekey->task =
3771 silc_schedule_task_add(server->schedule, 0,
3772 silc_server_channel_key_rekey,
3773 (void *)channel->rekey,
3774 server->config->channel_rekey_secs, 0,
3776 SILC_TASK_PRI_NORMAL);
3782 /* Saves the channel key found in the encoded `key_payload' buffer. This
3783 function is used when we receive Channel Key Payload and also when we're
3784 processing JOIN command reply. Returns entry to the channel. */
3786 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3787 SilcBuffer key_payload,
3788 SilcChannelEntry channel)
3790 SilcChannelKeyPayload payload = NULL;
3791 SilcChannelID *id = NULL;
3792 unsigned char *tmp, hash[32];
3796 /* Decode channel key payload */
3797 payload = silc_channel_key_payload_parse(key_payload->data,
3800 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3805 /* Get the channel entry */
3808 /* Get channel ID */
3809 tmp = silc_channel_key_get_id(payload, &tmp_len);
3810 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3816 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3818 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3820 if (server->server_type == SILC_ROUTER)
3821 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3822 silc_id_render(id, SILC_ID_CHANNEL)));
3828 SILC_LOG_DEBUG(("Saving new channel %s key", channel->channel_name));
3830 tmp = silc_channel_key_get_key(payload, &tmp_len);
3836 cipher = silc_channel_key_get_cipher(payload, NULL);
3842 /* Remove old key if exists */
3844 memset(channel->key, 0, channel->key_len / 8);
3845 silc_free(channel->key);
3846 silc_cipher_free(channel->channel_key);
3849 /* Create new cipher */
3850 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3851 channel->channel_key = NULL;
3856 if (channel->cipher)
3857 silc_free(channel->cipher);
3858 channel->cipher = strdup(cipher);
3861 channel->key_len = tmp_len * 8;
3862 channel->key = silc_memdup(tmp, tmp_len);
3863 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3865 /* Generate HMAC key from the channel key data and set it */
3867 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3868 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3869 silc_hmac_set_key(channel->hmac, hash,
3870 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3872 memset(hash, 0, sizeof(hash));
3873 memset(tmp, 0, tmp_len);
3875 if (server->server_type == SILC_ROUTER) {
3876 if (!channel->rekey)
3877 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3878 channel->rekey->channel = channel;
3879 if (channel->rekey->task)
3880 silc_schedule_task_del(server->schedule, channel->rekey->task);
3882 channel->rekey->task =
3883 silc_schedule_task_add(server->schedule, 0,
3884 silc_server_channel_key_rekey,
3885 (void *)channel->rekey,
3886 server->config->channel_rekey_secs, 0,
3888 SILC_TASK_PRI_NORMAL);
3894 silc_channel_key_payload_free(payload);
3899 /* Heartbeat callback. This function is set as argument for the
3900 silc_socket_set_heartbeat function. The library will call this function
3901 at the set time interval. */
3903 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3906 SilcServer server = hb_context;
3908 SILC_LOG_DEBUG(("Sending heartbeat to %s:%d (%s)", sock->hostname,
3909 sock->port, sock->ip));
3911 /* Send the heartbeat */
3912 silc_server_send_heartbeat(server, sock);
3915 /* Returns assembled of all servers in the given ID list. The packet's
3916 form is dictated by the New ID payload. */
3918 static void silc_server_announce_get_servers(SilcServer server,
3919 SilcServerEntry remote,
3921 SilcBuffer *servers,
3922 unsigned long creation_time)
3924 SilcIDCacheList list;
3925 SilcIDCacheEntry id_cache;
3926 SilcServerEntry entry;
3929 /* Go through all clients in the list */
3930 if (silc_idcache_get_all(id_list->servers, &list)) {
3931 if (silc_idcache_list_first(list, &id_cache)) {
3933 entry = (SilcServerEntry)id_cache->context;
3935 /* Do not announce the one we've sending our announcements and
3936 do not announce ourself. Also check the creation time if it's
3938 if ((entry == remote) || (entry == server->id_entry) ||
3939 (creation_time && entry->data.created < creation_time)) {
3940 if (!silc_idcache_list_next(list, &id_cache))
3945 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3947 *servers = silc_buffer_realloc(*servers,
3949 (*servers)->truelen + idp->len :
3951 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3952 silc_buffer_put(*servers, idp->data, idp->len);
3953 silc_buffer_pull(*servers, idp->len);
3954 silc_buffer_free(idp);
3956 if (!silc_idcache_list_next(list, &id_cache))
3961 silc_idcache_list_free(list);
3966 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3972 p = silc_notify_payload_encode(notify, argc, ap);
3978 /* This function is used by router to announce existing servers to our
3979 primary router when we've connected to it. If `creation_time' is non-zero
3980 then only the servers that has been created after the `creation_time'
3981 will be announced. */
3983 void silc_server_announce_servers(SilcServer server, bool global,
3984 unsigned long creation_time,
3985 SilcSocketConnection remote)
3987 SilcBuffer servers = NULL;
3989 SILC_LOG_DEBUG(("Announcing servers"));
3991 /* Get servers in local list */
3992 silc_server_announce_get_servers(server, remote->user_data,
3993 server->local_list, &servers,
3997 /* Get servers in global list */
3998 silc_server_announce_get_servers(server, remote->user_data,
3999 server->global_list, &servers,
4003 silc_buffer_push(servers, servers->data - servers->head);
4004 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
4006 /* Send the packet */
4007 silc_server_packet_send(server, remote,
4008 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4009 servers->data, servers->len, TRUE);
4011 silc_buffer_free(servers);
4015 /* Returns assembled packet of all clients in the given ID list. The
4016 packet's form is dictated by the New ID Payload. */
4018 static void silc_server_announce_get_clients(SilcServer server,
4020 SilcBuffer *clients,
4022 unsigned long creation_time)
4024 SilcIDCacheList list;
4025 SilcIDCacheEntry id_cache;
4026 SilcClientEntry client;
4029 unsigned char mode[4];
4031 /* Go through all clients in the list */
4032 if (silc_idcache_get_all(id_list->clients, &list)) {
4033 if (silc_idcache_list_first(list, &id_cache)) {
4035 client = (SilcClientEntry)id_cache->context;
4037 if (creation_time && client->data.created < creation_time) {
4038 if (!silc_idcache_list_next(list, &id_cache))
4042 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED) &&
4043 !client->connection && !client->router && !SILC_IS_LOCAL(client)) {
4044 if (!silc_idcache_list_next(list, &id_cache))
4049 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
4051 *clients = silc_buffer_realloc(*clients,
4053 (*clients)->truelen + idp->len :
4055 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
4056 silc_buffer_put(*clients, idp->data, idp->len);
4057 silc_buffer_pull(*clients, idp->len);
4059 SILC_PUT32_MSB(client->mode, mode);
4061 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
4062 2, idp->data, idp->len,
4064 *umodes = silc_buffer_realloc(*umodes,
4066 (*umodes)->truelen + tmp->len :
4068 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
4069 silc_buffer_put(*umodes, tmp->data, tmp->len);
4070 silc_buffer_pull(*umodes, tmp->len);
4071 silc_buffer_free(tmp);
4073 silc_buffer_free(idp);
4075 if (!silc_idcache_list_next(list, &id_cache))
4080 silc_idcache_list_free(list);
4084 /* This function is used to announce our existing clients to our router
4085 when we've connected to it. If `creation_time' is non-zero then only
4086 the clients that has been created after the `creation_time' will be
4089 void silc_server_announce_clients(SilcServer server,
4090 unsigned long creation_time,
4091 SilcSocketConnection remote)
4093 SilcBuffer clients = NULL;
4094 SilcBuffer umodes = NULL;
4096 SILC_LOG_DEBUG(("Announcing clients"));
4098 /* Get clients in local list */
4099 silc_server_announce_get_clients(server, server->local_list,
4100 &clients, &umodes, creation_time);
4102 /* As router we announce our global list as well */
4103 if (server->server_type == SILC_ROUTER)
4104 silc_server_announce_get_clients(server, server->global_list,
4105 &clients, &umodes, creation_time);
4108 silc_buffer_push(clients, clients->data - clients->head);
4109 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
4111 /* Send the packet */
4112 silc_server_packet_send(server, remote,
4113 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4114 clients->data, clients->len, TRUE);
4116 silc_buffer_free(clients);
4120 silc_buffer_push(umodes, umodes->data - umodes->head);
4121 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
4123 /* Send the packet */
4124 silc_server_packet_send(server, remote,
4125 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4126 umodes->data, umodes->len, TRUE);
4128 silc_buffer_free(umodes);
4132 /* Returns channel's topic for announcing it */
4134 void silc_server_announce_get_channel_topic(SilcServer server,
4135 SilcChannelEntry channel,
4140 if (channel->topic) {
4141 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4142 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
4143 chidp->data, chidp->len,
4145 strlen(channel->topic));
4146 silc_buffer_free(chidp);
4150 /* Returns assembled packets for channel users of the `channel'. */
4152 void silc_server_announce_get_channel_users(SilcServer server,
4153 SilcChannelEntry channel,
4154 SilcBuffer *channel_modes,
4155 SilcBuffer *channel_users,
4156 SilcBuffer *channel_users_modes)
4158 SilcChannelClientEntry chl;
4159 SilcHashTableList htl;
4160 SilcBuffer chidp, clidp, csidp;
4163 unsigned char mode[4], *fkey = NULL;
4164 SilcUInt32 fkey_len = 0;
4167 SILC_LOG_DEBUG(("Start"));
4169 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4170 csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4173 SILC_PUT32_MSB(channel->mode, mode);
4174 hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
4175 if (channel->founder_key)
4176 fkey = silc_pkcs_public_key_encode(channel->founder_key, &fkey_len);
4178 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
4179 6, csidp->data, csidp->len,
4182 hmac, hmac ? strlen(hmac) : 0,
4183 channel->passphrase,
4184 channel->passphrase ?
4185 strlen(channel->passphrase) : 0,
4189 silc_buffer_realloc(*channel_modes,
4191 (*channel_modes)->truelen + len : len));
4192 silc_buffer_pull_tail(*channel_modes,
4193 ((*channel_modes)->end -
4194 (*channel_modes)->data));
4195 silc_buffer_put(*channel_modes, tmp->data, tmp->len);
4196 silc_buffer_pull(*channel_modes, len);
4197 silc_buffer_free(tmp);
4202 /* Now find all users on the channel */
4203 silc_hash_table_list(channel->user_list, &htl);
4204 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4205 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4208 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
4209 clidp->data, clidp->len,
4210 chidp->data, chidp->len);
4213 silc_buffer_realloc(*channel_users,
4215 (*channel_users)->truelen + len : len));
4216 silc_buffer_pull_tail(*channel_users,
4217 ((*channel_users)->end -
4218 (*channel_users)->data));
4220 silc_buffer_put(*channel_users, tmp->data, tmp->len);
4221 silc_buffer_pull(*channel_users, len);
4222 silc_buffer_free(tmp);
4224 /* CUMODE notify for mode change on the channel */
4225 SILC_PUT32_MSB(chl->mode, mode);
4226 if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
4227 fkey = silc_pkcs_public_key_encode(channel->founder_key, &fkey_len);
4228 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
4229 4, csidp->data, csidp->len,
4231 clidp->data, clidp->len,
4234 *channel_users_modes =
4235 silc_buffer_realloc(*channel_users_modes,
4236 (*channel_users_modes ?
4237 (*channel_users_modes)->truelen + len : len));
4238 silc_buffer_pull_tail(*channel_users_modes,
4239 ((*channel_users_modes)->end -
4240 (*channel_users_modes)->data));
4242 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
4243 silc_buffer_pull(*channel_users_modes, len);
4244 silc_buffer_free(tmp);
4248 silc_buffer_free(clidp);
4250 silc_hash_table_list_reset(&htl);
4251 silc_buffer_free(chidp);
4252 silc_buffer_free(csidp);
4255 /* Returns assembled packets for all channels and users on those channels
4256 from the given ID List. The packets are in the form dictated by the
4257 New Channel and New Channel User payloads. */
4259 void silc_server_announce_get_channels(SilcServer server,
4261 SilcBuffer *channels,
4262 SilcBuffer **channel_modes,
4263 SilcBuffer *channel_users,
4264 SilcBuffer **channel_users_modes,
4265 SilcUInt32 *channel_users_modes_c,
4266 SilcBuffer **channel_topics,
4267 SilcChannelID ***channel_ids,
4268 unsigned long creation_time)
4270 SilcIDCacheList list;
4271 SilcIDCacheEntry id_cache;
4272 SilcChannelEntry channel;
4275 SilcUInt16 name_len;
4277 int i = *channel_users_modes_c;
4280 SILC_LOG_DEBUG(("Start"));
4282 /* Go through all channels in the list */
4283 if (silc_idcache_get_all(id_list->channels, &list)) {
4284 if (silc_idcache_list_first(list, &id_cache)) {
4286 channel = (SilcChannelEntry)id_cache->context;
4288 if (creation_time && channel->created < creation_time)
4293 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4294 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4295 name_len = strlen(channel->channel_name);
4298 len = 4 + name_len + id_len + 4;
4300 silc_buffer_realloc(*channels,
4301 (*channels ? (*channels)->truelen +
4303 silc_buffer_pull_tail(*channels,
4304 ((*channels)->end - (*channels)->data));
4305 silc_buffer_format(*channels,
4306 SILC_STR_UI_SHORT(name_len),
4307 SILC_STR_UI_XNSTRING(channel->channel_name,
4309 SILC_STR_UI_SHORT(id_len),
4310 SILC_STR_UI_XNSTRING(cid, id_len),
4311 SILC_STR_UI_INT(channel->mode),
4313 silc_buffer_pull(*channels, len);
4316 if (creation_time && channel->updated < creation_time)
4322 /* Channel user modes */
4323 *channel_users_modes = silc_realloc(*channel_users_modes,
4324 sizeof(**channel_users_modes) *
4326 (*channel_users_modes)[i] = NULL;
4327 *channel_modes = silc_realloc(*channel_modes,
4328 sizeof(**channel_modes) * (i + 1));
4329 (*channel_modes)[i] = NULL;
4330 *channel_ids = silc_realloc(*channel_ids,
4331 sizeof(**channel_ids) * (i + 1));
4332 (*channel_ids)[i] = NULL;
4333 silc_server_announce_get_channel_users(server, channel,
4334 &(*channel_modes)[i],
4336 &(*channel_users_modes)[i]);
4337 (*channel_ids)[i] = channel->id;
4339 /* Channel's topic */
4340 *channel_topics = silc_realloc(*channel_topics,
4341 sizeof(**channel_topics) * (i + 1));
4342 (*channel_topics)[i] = NULL;
4343 silc_server_announce_get_channel_topic(server, channel,
4344 &(*channel_topics)[i]);
4345 (*channel_users_modes_c)++;
4349 if (!silc_idcache_list_next(list, &id_cache))
4354 silc_idcache_list_free(list);
4358 /* This function is used to announce our existing channels to our router
4359 when we've connected to it. This also announces the users on the
4360 channels to the router. If the `creation_time' is non-zero only the
4361 channels that was created after the `creation_time' are announced.
4362 Note that the channel users are still announced even if the `creation_time'
4365 void silc_server_announce_channels(SilcServer server,
4366 unsigned long creation_time,
4367 SilcSocketConnection remote)
4369 SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
4370 SilcBuffer *channel_users_modes = NULL;
4371 SilcBuffer *channel_topics = NULL;
4372 SilcUInt32 channel_users_modes_c = 0;
4373 SilcChannelID **channel_ids = NULL;
4375 SILC_LOG_DEBUG(("Announcing channels and channel users"));
4377 /* Get channels and channel users in local list */
4378 silc_server_announce_get_channels(server, server->local_list,
4379 &channels, &channel_modes,
4381 &channel_users_modes,
4382 &channel_users_modes_c,
4384 &channel_ids, creation_time);
4386 /* Get channels and channel users in global list */
4387 if (server->server_type != SILC_SERVER)
4388 silc_server_announce_get_channels(server, server->global_list,
4389 &channels, &channel_modes,
4391 &channel_users_modes,
4392 &channel_users_modes_c,
4394 &channel_ids, creation_time);
4397 silc_buffer_push(channels, channels->data - channels->head);
4398 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
4400 /* Send the packet */
4401 silc_server_packet_send(server, remote,
4402 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
4403 channels->data, channels->len,
4406 silc_buffer_free(channels);
4409 if (channel_users) {
4410 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
4411 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
4412 channel_users->len);
4414 /* Send the packet */
4415 silc_server_packet_send(server, remote,
4416 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4417 channel_users->data, channel_users->len,
4420 silc_buffer_free(channel_users);
4423 if (channel_modes) {
4426 for (i = 0; i < channel_users_modes_c; i++) {
4427 if (!channel_modes[i])
4429 silc_buffer_push(channel_modes[i],
4430 channel_modes[i]->data -
4431 channel_modes[i]->head);
4432 SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
4433 channel_modes[i]->len);
4434 silc_server_packet_send_dest(server, remote,
4435 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4436 channel_ids[i], SILC_ID_CHANNEL,
4437 channel_modes[i]->data,
4438 channel_modes[i]->len,
4440 silc_buffer_free(channel_modes[i]);
4442 silc_free(channel_modes);
4445 if (channel_users_modes) {
4448 for (i = 0; i < channel_users_modes_c; i++) {
4449 if (!channel_users_modes[i])
4451 silc_buffer_push(channel_users_modes[i],
4452 channel_users_modes[i]->data -
4453 channel_users_modes[i]->head);
4454 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
4455 channel_users_modes[i]->len);
4456 silc_server_packet_send_dest(server, remote,
4457 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4458 channel_ids[i], SILC_ID_CHANNEL,
4459 channel_users_modes[i]->data,
4460 channel_users_modes[i]->len,
4462 silc_buffer_free(channel_users_modes[i]);
4464 silc_free(channel_users_modes);
4467 if (channel_topics) {
4470 for (i = 0; i < channel_users_modes_c; i++) {
4471 if (!channel_topics[i])
4474 silc_buffer_push(channel_topics[i],
4475 channel_topics[i]->data -
4476 channel_topics[i]->head);
4477 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
4478 channel_topics[i]->len);
4479 silc_server_packet_send_dest(server, remote,
4480 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4481 channel_ids[i], SILC_ID_CHANNEL,
4482 channel_topics[i]->data,
4483 channel_topics[i]->len,
4485 silc_buffer_free(channel_topics[i]);
4487 silc_free(channel_topics);
4490 silc_free(channel_ids);
4493 /* Failure timeout callback. If this is called then we will immediately
4494 process the received failure. We always process the failure with timeout
4495 since we do not want to blindly trust to received failure packets.
4496 This won't be called (the timeout is cancelled) if the failure was
4497 bogus (it is bogus if remote does not close the connection after sending
4500 SILC_TASK_CALLBACK(silc_server_failure_callback)
4502 SilcServer server = app_context;
4503 SilcServerFailureContext f = (SilcServerFailureContext)context;
4505 if (f->sock->protocol) {
4506 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
4507 silc_protocol_execute(f->sock->protocol, server->schedule, 0, 0);
4510 silc_socket_free(f->sock);
4514 /* Assembles user list and users mode list from the `channel'. */
4516 bool silc_server_get_users_on_channel(SilcServer server,
4517 SilcChannelEntry channel,
4518 SilcBuffer *user_list,
4519 SilcBuffer *mode_list,
4520 SilcUInt32 *user_count)
4522 SilcChannelClientEntry chl;
4523 SilcHashTableList htl;
4524 SilcBuffer client_id_list;
4525 SilcBuffer client_mode_list;
4527 SilcUInt32 list_count = 0, len = 0;
4529 if (!silc_hash_table_count(channel->user_list))
4532 silc_hash_table_list(channel->user_list, &htl);
4533 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4534 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
4535 silc_hash_table_list_reset(&htl);
4537 client_id_list = silc_buffer_alloc(len);
4539 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
4540 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
4541 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
4543 silc_hash_table_list(channel->user_list, &htl);
4544 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4546 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4547 silc_buffer_put(client_id_list, idp->data, idp->len);
4548 silc_buffer_pull(client_id_list, idp->len);
4549 silc_buffer_free(idp);
4551 /* Client's mode on channel */
4552 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
4553 silc_buffer_pull(client_mode_list, 4);
4557 silc_hash_table_list_reset(&htl);
4558 silc_buffer_push(client_id_list,
4559 client_id_list->data - client_id_list->head);
4560 silc_buffer_push(client_mode_list,
4561 client_mode_list->data - client_mode_list->head);
4563 *user_list = client_id_list;
4564 *mode_list = client_mode_list;
4565 *user_count = list_count;
4569 /* Saves users and their modes to the `channel'. */
4571 void silc_server_save_users_on_channel(SilcServer server,
4572 SilcSocketConnection sock,
4573 SilcChannelEntry channel,
4574 SilcClientID *noadd,
4575 SilcBuffer user_list,
4576 SilcBuffer mode_list,
4577 SilcUInt32 user_count)
4582 SilcClientID *client_id;
4583 SilcClientEntry client;
4584 SilcIDCacheEntry cache;
4585 SilcChannelClientEntry chl;
4587 SILC_LOG_DEBUG(("Saving %d users on %s channel", user_count,
4588 channel->channel_name));
4590 for (i = 0; i < user_count; i++) {
4592 SILC_GET16_MSB(idp_len, user_list->data + 2);
4594 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
4595 silc_buffer_pull(user_list, idp_len);
4600 SILC_GET32_MSB(mode, mode_list->data);
4601 silc_buffer_pull(mode_list, 4);
4603 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
4604 silc_free(client_id);
4610 /* Check if we have this client cached already. */
4611 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4612 server->server_type, &cache);
4614 client = silc_idlist_find_client_by_id(server->global_list,
4615 client_id, server->server_type,
4618 /* If router did not find such Client ID in its lists then this must
4619 be bogus client or some router in the net is buggy. */
4620 if (server->server_type != SILC_SERVER) {
4621 silc_free(client_id);
4625 /* We don't have that client anywhere, add it. The client is added
4626 to global list since server didn't have it in the lists so it must be
4628 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
4629 silc_id_dup(client_id, SILC_ID_CLIENT),
4630 sock->user_data, NULL, 0);
4632 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
4633 silc_free(client_id);
4637 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
4642 silc_free(client_id);
4644 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
4645 SILC_LOG_ERROR(("Attempting to add unregistered client to channel ",
4646 "%s", channel->channel_name));
4650 if (!silc_server_client_on_channel(client, channel, &chl)) {
4651 /* Client was not on the channel, add it. */
4652 chl = silc_calloc(1, sizeof(*chl));
4653 chl->client = client;
4655 chl->channel = channel;
4656 silc_hash_table_add(channel->user_list, chl->client, chl);
4657 silc_hash_table_add(client->channels, chl->channel, chl);
4658 channel->user_count++;
4666 /* Saves channels and channels user modes to the `client'. Removes
4667 the client from those channels that are not sent in the list but
4670 void silc_server_save_user_channels(SilcServer server,
4671 SilcSocketConnection sock,
4672 SilcClientEntry client,
4673 SilcBuffer channels,
4674 SilcBuffer channels_user_modes)
4677 SilcUInt32 *chumodes;
4678 SilcChannelPayload entry;
4679 SilcChannelEntry channel;
4680 SilcChannelID *channel_id;
4681 SilcChannelClientEntry chl;
4682 SilcHashTable ht = NULL;
4683 SilcHashTableList htl;
4687 if (!channels || !channels_user_modes ||
4688 !(client->data.status & SILC_IDLIST_STATUS_REGISTERED))
4691 ch = silc_channel_payload_parse_list(channels->data, channels->len);
4692 if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
4694 ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL,
4695 NULL, NULL, NULL, TRUE);
4696 silc_dlist_start(ch);
4697 while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
4698 /* Check if we have this channel, and add it if we don't have it.
4699 Also add the client on the channel unless it is there already. */
4700 channel_id = silc_channel_get_id_parse(entry);
4701 channel = silc_idlist_find_channel_by_id(server->local_list,
4704 channel = silc_idlist_find_channel_by_id(server->global_list,
4707 if (server->server_type != SILC_SERVER) {
4708 silc_free(channel_id);
4713 /* We don't have that channel anywhere, add it. */
4714 name = silc_channel_get_name(entry, NULL);
4715 channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
4716 channel_id, server->router,
4719 silc_free(channel_id);
4726 channel->mode = silc_channel_get_mode(entry);
4728 /* Add the client on the channel */
4729 if (!silc_server_client_on_channel(client, channel, &chl)) {
4730 chl = silc_calloc(1, sizeof(*chl));
4731 chl->client = client;
4732 chl->mode = chumodes[i++];
4733 chl->channel = channel;
4734 silc_hash_table_add(channel->user_list, chl->client, chl);
4735 silc_hash_table_add(client->channels, chl->channel, chl);
4736 channel->user_count++;
4739 chl->mode = chumodes[i++];
4742 silc_hash_table_add(ht, channel, channel);
4743 silc_free(channel_id);
4745 silc_channel_payload_list_free(ch);
4746 silc_free(chumodes);
4750 /* Go through the list again and remove client from channels that
4751 are no part of the list. */
4753 silc_hash_table_list(client->channels, &htl);
4754 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4755 if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
4756 silc_hash_table_del(chl->channel->user_list, chl->client);
4757 silc_hash_table_del(chl->client->channels, chl->channel);
4761 silc_hash_table_list_reset(&htl);
4762 silc_hash_table_free(ht);
4764 silc_hash_table_list(client->channels, &htl);
4765 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4766 silc_hash_table_del(chl->channel->user_list, chl->client);
4767 silc_hash_table_del(chl->client->channels, chl->channel);
4770 silc_hash_table_list_reset(&htl);
4774 /* Lookups route to the client indicated by the `id_data'. The connection
4775 object and internal data object is returned. Returns NULL if route
4776 could not be found to the client. If the `client_id' is specified then
4777 it is used and the `id_data' is ignored. */
4779 SilcSocketConnection
4780 silc_server_get_client_route(SilcServer server,
4781 unsigned char *id_data,
4783 SilcClientID *client_id,
4784 SilcIDListData *idata,
4785 SilcClientEntry *client_entry)
4788 SilcClientEntry client;
4790 SILC_LOG_DEBUG(("Start"));
4793 *client_entry = NULL;
4795 /* Decode destination Client ID */
4797 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
4799 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
4803 id = silc_id_dup(client_id, SILC_ID_CLIENT);
4806 /* If the destination belongs to our server we don't have to route
4807 the packet anywhere but to send it to the local destination. */
4808 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
4812 /* If we are router and the client has router then the client is in
4813 our cell but not directly connected to us. */
4814 if (server->server_type == SILC_ROUTER && client->router) {
4815 /* We are of course in this case the client's router thus the route
4816 to the client is the server who owns the client. So, we will send
4817 the packet to that server. */
4819 *idata = (SilcIDListData)client->router;
4820 return client->router->connection;
4823 /* Seems that client really is directly connected to us */
4825 *idata = (SilcIDListData)client;
4827 *client_entry = client;
4828 return client->connection;
4831 /* Destination belongs to someone not in this server. If we are normal
4832 server our action is to send the packet to our router. */
4833 if (server->server_type != SILC_ROUTER && !server->standalone) {
4836 *idata = (SilcIDListData)server->router;
4837 return SILC_PRIMARY_ROUTE(server);
4840 /* We are router and we will perform route lookup for the destination
4841 and send the packet to fastest route. */
4842 if (server->server_type == SILC_ROUTER && !server->standalone) {
4843 /* Check first that the ID is valid */
4844 client = silc_idlist_find_client_by_id(server->global_list, id,
4847 SilcSocketConnection dst_sock;
4849 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
4853 *idata = (SilcIDListData)dst_sock->user_data;
4862 /* Encodes and returns channel list of channels the `client' has joined.
4863 Secret channels are not put to the list. */
4865 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
4866 SilcClientEntry client,
4869 SilcBuffer *user_mode_list)
4871 SilcBuffer buffer = NULL;
4872 SilcChannelEntry channel;
4873 SilcChannelClientEntry chl;
4874 SilcHashTableList htl;
4877 SilcUInt16 name_len;
4881 *user_mode_list = NULL;
4883 silc_hash_table_list(client->channels, &htl);
4884 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4885 channel = chl->channel;
4887 if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
4889 if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
4892 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4893 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4894 name_len = strlen(channel->channel_name);
4896 len = 4 + name_len + id_len + 4;
4897 buffer = silc_buffer_realloc(buffer,
4898 (buffer ? buffer->truelen + len : len));
4899 silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
4900 silc_buffer_format(buffer,
4901 SILC_STR_UI_SHORT(name_len),
4902 SILC_STR_UI_XNSTRING(channel->channel_name,
4904 SILC_STR_UI_SHORT(id_len),
4905 SILC_STR_UI_XNSTRING(cid, id_len),
4906 SILC_STR_UI_INT(chl->channel->mode),
4908 silc_buffer_pull(buffer, len);
4911 if (user_mode_list) {
4912 *user_mode_list = silc_buffer_realloc(*user_mode_list,
4914 (*user_mode_list)->truelen + 4 :
4916 silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
4917 (*user_mode_list)->data));
4918 SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
4919 silc_buffer_pull(*user_mode_list, 4);
4922 silc_hash_table_list_reset(&htl);
4925 silc_buffer_push(buffer, buffer->data - buffer->head);
4926 if (user_mode_list && *user_mode_list)
4927 silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
4928 (*user_mode_list)->head));
4933 /* A timeout callback for the re-key. We will be the initiator of the
4936 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4938 SilcServer server = app_context;
4939 SilcSocketConnection sock = (SilcSocketConnection)context;
4940 SilcIDListData idata = (SilcIDListData)sock->user_data;
4941 SilcProtocol protocol;
4942 SilcServerRekeyInternalContext *proto_ctx;
4944 /* Allocate internal protocol context. This is sent as context
4946 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4947 proto_ctx->server = (void *)server;
4948 proto_ctx->sock = sock;
4949 proto_ctx->responder = FALSE;
4950 proto_ctx->pfs = idata->rekey->pfs;
4952 /* Perform rekey protocol. Will call the final callback after the
4953 protocol is over. */
4954 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4955 &protocol, proto_ctx, silc_server_rekey_final);
4956 sock->protocol = protocol;
4958 /* Run the protocol */
4959 silc_protocol_execute(protocol, server->schedule, 0, 0);
4961 SILC_LOG_DEBUG(("Rekey protocol completed"));
4963 /* Re-register re-key timeout */
4964 silc_schedule_task_add(server->schedule, sock->sock,
4965 silc_server_rekey_callback,
4966 context, idata->rekey->timeout, 0,
4967 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4970 /* The final callback for the REKEY protocol. This will actually take the
4971 new key material into use. */
4973 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4975 SilcProtocol protocol = (SilcProtocol)context;
4976 SilcServerRekeyInternalContext *ctx =
4977 (SilcServerRekeyInternalContext *)protocol->context;
4978 SilcServer server = (SilcServer)ctx->server;
4979 SilcSocketConnection sock = ctx->sock;
4981 SILC_LOG_DEBUG(("Start"));
4983 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4984 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4985 /* Error occured during protocol */
4986 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4987 silc_protocol_cancel(protocol, server->schedule);
4988 silc_protocol_free(protocol);
4989 sock->protocol = NULL;
4991 silc_packet_context_free(ctx->packet);
4993 silc_ske_free(ctx->ske);
4998 /* Purge the outgoing data queue to assure that all rekey packets really
4999 go to the network before we quit the protocol. */
5000 silc_server_packet_queue_purge(server, sock);
5003 silc_protocol_free(protocol);
5004 sock->protocol = NULL;
5006 silc_packet_context_free(ctx->packet);
5008 silc_ske_free(ctx->ske);
5012 /* Task callback used to retrieve network statistical information from
5013 router server once in a while. */
5015 SILC_TASK_CALLBACK(silc_server_get_stats)
5017 SilcServer server = (SilcServer)context;
5018 SilcBuffer idp, packet;
5020 SILC_LOG_DEBUG(("Retrieving stats from router"));
5022 if (!server->standalone) {
5023 idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
5024 packet = silc_command_payload_encode_va(SILC_COMMAND_STATS,
5025 ++server->cmd_ident, 1,
5026 1, idp->data, idp->len);
5027 silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
5028 SILC_PACKET_COMMAND, 0, packet->data,
5029 packet->len, FALSE);
5030 silc_buffer_free(packet);
5031 silc_buffer_free(idp);
5034 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
5035 server, 120, 0, SILC_TASK_TIMEOUT,