5 Author: Pekka Riikonen <priikone@silcnet.org>
7 Copyright (C) 1997 - 2003 Pekka Riikonen
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; version 2 of the License.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
20 * This is the actual SILC server than handles everything relating to
21 * servicing the SILC connections. This is also a SILC router as a router
22 * is also normal server.
26 #include "serverincludes.h"
27 #include "server_internal.h"
29 /* Static prototypes */
30 SILC_TASK_CALLBACK(silc_server_rehash_close_connection);
31 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry);
32 SILC_TASK_CALLBACK(silc_server_connect_router);
33 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
35 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
38 SILC_TASK_CALLBACK(silc_server_packet_process);
39 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
40 SILC_TASK_CALLBACK(silc_server_close_connection_final);
41 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout);
42 SILC_TASK_CALLBACK(silc_server_timeout_remote);
43 SILC_TASK_CALLBACK(silc_server_channel_key_rekey);
44 SILC_TASK_CALLBACK(silc_server_get_stats);
46 /* Allocates a new SILC server object. This has to be done before the server
47 can be used. After allocation one must call silc_server_init to initialize
48 the server. The new allocated server object is returned to the new_server
51 int silc_server_alloc(SilcServer *new_server)
55 SILC_LOG_DEBUG(("Allocating new server object"));
57 server = silc_calloc(1, sizeof(*server));
58 server->server_type = SILC_SERVER;
59 server->standalone = TRUE;
60 server->local_list = silc_calloc(1, sizeof(*server->local_list));
61 server->global_list = silc_calloc(1, sizeof(*server->global_list));
62 server->pending_commands = silc_dlist_init();
64 server->sim = silc_dlist_init();
72 /* Free's the SILC server object. This is called at the very end before
75 void silc_server_free(SilcServer server)
78 SilcIDCacheEntry cache;
86 silc_dlist_start(server->sim);
87 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
88 silc_dlist_del(server->sim, sim);
92 silc_dlist_uninit(server->sim);
96 silc_server_backup_free(server);
97 silc_server_config_unref(&server->config_ref);
99 silc_rng_free(server->rng);
101 silc_pkcs_free(server->pkcs);
102 if (server->public_key)
103 silc_pkcs_public_key_free(server->public_key);
104 if (server->private_key)
105 silc_pkcs_private_key_free(server->private_key);
106 if (server->pending_commands)
107 silc_dlist_uninit(server->pending_commands);
108 if (server->id_entry)
109 silc_idlist_del_server(server->local_list, server->id_entry);
111 /* Delete all channels */
113 if (silc_idcache_get_all(server->local_list->channels, &list) &&
114 silc_idcache_list_first(list, &cache)) {
115 silc_idlist_del_channel(server->local_list, cache->context);
116 while (silc_idcache_list_next(list, &cache))
117 silc_idlist_del_channel(server->local_list, cache->context);
120 silc_idcache_list_free(list);
122 if (silc_idcache_get_all(server->global_list->channels, &list) &&
123 silc_idcache_list_first(list, &cache)) {
124 silc_idlist_del_channel(server->global_list, cache->context);
125 while (silc_idcache_list_next(list, &cache))
126 silc_idlist_del_channel(server->global_list, cache->context);
129 silc_idcache_list_free(list);
131 /* Delete all clients */
133 if (silc_idcache_get_all(server->local_list->clients, &list) &&
134 silc_idcache_list_first(list, &cache)) {
135 silc_idlist_del_client(server->local_list, cache->context);
136 while (silc_idcache_list_next(list, &cache))
137 silc_idlist_del_client(server->local_list, cache->context);
140 silc_idcache_list_free(list);
142 if (silc_idcache_get_all(server->global_list->clients, &list) &&
143 silc_idcache_list_first(list, &cache)) {
144 silc_idlist_del_client(server->global_list, cache->context);
145 while (silc_idcache_list_next(list, &cache))
146 silc_idlist_del_client(server->global_list, cache->context);
149 silc_idcache_list_free(list);
151 /* Delete all servers */
153 if (silc_idcache_get_all(server->local_list->servers, &list) &&
154 silc_idcache_list_first(list, &cache)) {
155 silc_idlist_del_server(server->local_list, cache->context);
156 while (silc_idcache_list_next(list, &cache))
157 silc_idlist_del_server(server->local_list, cache->context);
160 silc_idcache_list_free(list);
162 if (silc_idcache_get_all(server->global_list->servers, &list) &&
163 silc_idcache_list_first(list, &cache)) {
164 silc_idlist_del_server(server->global_list, cache->context);
165 while (silc_idcache_list_next(list, &cache))
166 silc_idlist_del_server(server->global_list, cache->context);
169 silc_idcache_list_free(list);
171 silc_idcache_free(server->local_list->clients);
172 silc_idcache_free(server->local_list->servers);
173 silc_idcache_free(server->local_list->channels);
174 silc_idcache_free(server->global_list->clients);
175 silc_idcache_free(server->global_list->servers);
176 silc_idcache_free(server->global_list->channels);
177 silc_hash_table_free(server->watcher_list);
179 silc_hash_free(server->md5hash);
180 silc_hash_free(server->sha1hash);
181 silc_hmac_unregister_all();
182 silc_hash_unregister_all();
183 silc_cipher_unregister_all();
184 silc_pkcs_unregister_all();
186 silc_free(server->local_list);
187 silc_free(server->global_list);
188 silc_free(server->server_name);
189 silc_free(server->id_string);
190 silc_free(server->purge_i);
191 silc_free(server->purge_g);
195 /* Creates a new server listener. */
197 static bool silc_server_listen(SilcServer server, const char *server_ip,
198 SilcUInt16 port, int *sock)
200 *sock = silc_net_create_server(port, server_ip);
202 SILC_SERVER_LOG_ERROR(("Could not create server listener: %s on %hu",
209 /* Adds a secondary listener. */
211 bool silc_server_init_secondary(SilcServer server)
213 int sock = 0, sock_list[server->config->param.connections_max];
214 SilcSocketConnection newsocket = NULL;
215 SilcServerConfigServerInfoInterface *interface;
217 for (interface = server->config->server_info->secondary; interface;
218 interface = interface->next, sock++) {
220 if (!silc_server_listen(server,
221 interface->server_ip, interface->port, &sock_list[sock]))
224 /* Set socket to non-blocking mode */
225 silc_net_set_socket_nonblock(sock_list[sock]);
227 /* Add ourselves also to the socket table. The entry allocated above
228 is sent as argument for fast referencing in the future. */
229 silc_socket_alloc(sock_list[sock],
230 SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
231 server->sockets[sock_list[sock]] = newsocket;
232 SILC_SET_LISTENER(newsocket);
234 /* Perform name and address lookups to resolve the listenning address
236 if (!silc_net_check_local_by_sock(sock_list[sock], &newsocket->hostname,
238 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
240 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
241 newsocket->hostname ? newsocket->hostname :
242 newsocket->ip ? newsocket->ip : ""));
243 server->stat.conn_failures++;
246 if (!newsocket->hostname)
247 newsocket->hostname = strdup(newsocket->ip);
249 newsocket->port = silc_net_get_local_port(sock);
251 newsocket->user_data = (void *)server->id_entry;
252 silc_schedule_task_add(server->schedule, sock_list[sock],
253 silc_server_accept_new_connection,
254 (void *)server, 0, 0,
256 SILC_TASK_PRI_NORMAL);
262 do silc_net_close_server(sock_list[sock--]); while (sock >= 0);
266 /* Initializes the entire SILC server. This is called always before running
267 the server. This is called only once at the initialization of the program.
268 This binds the server to its listenning port. After this function returns
269 one should call silc_server_run to start the server. This returns TRUE
270 when everything is ok to run the server. Configuration file must be
271 read and parsed before calling this. */
273 bool silc_server_init(SilcServer server)
277 SilcServerEntry id_entry;
278 SilcIDListPurge purge;
279 SilcSocketConnection newsocket = NULL;
281 SILC_LOG_DEBUG(("Initializing server"));
283 server->starttime = time(NULL);
285 /* Take config object for us */
286 silc_server_config_ref(&server->config_ref, server->config,
290 /* Set debugging on if configured */
291 if (server->config->debug_string) {
293 silc_log_set_debug_string(server->config->debug_string);
295 #endif /* SILC_DEBUG */
297 /* Steal public and private key from the config object */
298 server->public_key = server->config->server_info->public_key;
299 server->private_key = server->config->server_info->private_key;
300 server->config->server_info->public_key = NULL;
301 server->config->server_info->private_key = NULL;
303 /* Register all configured ciphers, PKCS and hash functions. */
304 if (!silc_server_config_register_ciphers(server))
305 silc_cipher_register_default();
306 if (!silc_server_config_register_pkcs(server))
307 silc_pkcs_register_default();
308 if (!silc_server_config_register_hashfuncs(server))
309 silc_hash_register_default();
310 if (!silc_server_config_register_hmacs(server))
311 silc_hmac_register_default();
313 /* Initialize random number generator for the server. */
314 server->rng = silc_rng_alloc();
315 silc_rng_init(server->rng);
316 silc_rng_global_init(server->rng);
318 /* Initialize hash functions for server to use */
319 silc_hash_alloc("md5", &server->md5hash);
320 silc_hash_alloc("sha1", &server->sha1hash);
322 /* Allocate PKCS context for local public and private keys */
323 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
325 silc_pkcs_public_key_set(server->pkcs, server->public_key);
326 silc_pkcs_private_key_set(server->pkcs, server->private_key);
328 /* Initialize the scheduler */
329 server->schedule = silc_schedule_init(server->config->param.connections_max,
331 if (!server->schedule)
334 /* First, register log files configuration for error output */
335 silc_server_config_setlogfiles(server);
337 /* Initialize ID caches */
338 server->local_list->clients =
339 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
340 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
341 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
343 /* These are allocated for normal server as well as these hold some
344 global information that the server has fetched from its router. For
345 router these are used as they are supposed to be used on router. */
346 server->global_list->clients =
347 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
348 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
349 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
351 /* Init watcher list */
352 server->watcher_list =
353 silc_hash_table_alloc(1, silc_hash_client_id_hash, NULL,
354 silc_hash_data_compare, (void *)CLIENTID_HASH_LEN,
356 if (!server->watcher_list)
359 /* Create a listening server */
360 if (!silc_server_listen(server,
361 server->config->server_info->primary == NULL ? NULL :
362 server->config->server_info->primary->server_ip,
363 server->config->server_info->primary == NULL ? 0 :
364 server->config->server_info->primary->port,
368 /* Set socket to non-blocking mode */
369 silc_net_set_socket_nonblock(sock);
372 /* Allocate the entire socket list that is used in server. Eventually
373 all connections will have entry in this table (it is a table of
374 pointers to the actual object that is allocated individually
376 server->sockets = silc_calloc(server->config->param.connections_max,
377 sizeof(*server->sockets));
378 if (!server->sockets)
381 /* Add ourselves also to the socket table. The entry allocated above
382 is sent as argument for fast referencing in the future. */
383 silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
384 server->sockets[sock] = newsocket;
385 SILC_SET_LISTENER(newsocket);
387 /* Perform name and address lookups to resolve the listenning address
389 if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
391 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
393 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
394 newsocket->hostname ? newsocket->hostname :
395 newsocket->ip ? newsocket->ip : ""));
396 server->stat.conn_failures++;
399 if (!newsocket->hostname)
400 newsocket->hostname = strdup(newsocket->ip);
402 newsocket->port = silc_net_get_local_port(sock);
404 /* Create a Server ID for the server. */
405 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
410 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
411 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
412 server->server_name = server->config->server_info->server_name;
413 server->config->server_info->server_name = NULL;
415 /* Add ourselves to the server list. We don't have a router yet
416 beacuse we haven't established a route yet. It will be done later.
417 For now, NULL is sent as router. This allocates new entry to
420 silc_idlist_add_server(server->local_list, strdup(server->server_name),
421 server->server_type, server->id, NULL, NULL);
423 SILC_LOG_ERROR(("Could not add ourselves to cache"));
426 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
428 /* Put the allocated socket pointer also to the entry allocated above
429 for fast back-referencing to the socket list. */
430 newsocket->user_data = (void *)id_entry;
431 id_entry->connection = (void *)newsocket;
432 server->id_entry = id_entry;
434 /* Register protocols */
435 silc_server_protocols_register();
437 /* Create connections to configured routers. */
438 silc_server_create_connections(server);
440 /* Add listener task to the scheduler. This task receives new connections
441 to the server. This task remains on the queue until the end of the
443 silc_schedule_task_add(server->schedule, sock,
444 silc_server_accept_new_connection,
445 (void *)server, 0, 0,
447 SILC_TASK_PRI_NORMAL);
449 if (silc_server_init_secondary(server) == FALSE)
452 server->listenning = TRUE;
454 /* If server connections has been configured then we must be router as
455 normal server cannot have server connections, only router connections. */
456 if (server->config->servers) {
457 SilcServerConfigServer *ptr = server->config->servers;
459 server->server_type = SILC_ROUTER;
461 if (ptr->backup_router) {
462 server->server_type = SILC_BACKUP_ROUTER;
463 server->backup_router = TRUE;
464 server->id_entry->server_type = SILC_BACKUP_ROUTER;
471 /* Register the ID Cache purge task. This periodically purges the ID cache
472 and removes the expired cache entries. */
474 /* Clients local list */
475 server->purge_i = purge = silc_calloc(1, sizeof(*purge));
476 purge->cache = server->local_list->clients;
477 purge->timeout = 600;
478 silc_schedule_task_add(server->schedule, 0, silc_idlist_purge,
479 (void *)purge, purge->timeout, 0,
480 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
482 /* Clients global list */
483 server->purge_g = purge = silc_calloc(1, sizeof(*purge));
484 purge->cache = server->global_list->clients;
485 purge->timeout = 300;
486 silc_schedule_task_add(server->schedule, 0, silc_idlist_purge,
487 (void *)purge, purge->timeout, 0,
488 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
490 /* If we are normal server we'll retrieve network statisticial information
491 once in a while from the router. */
492 if (server->server_type != SILC_ROUTER)
493 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
494 server, 10, 0, SILC_TASK_TIMEOUT,
497 if (server->server_type == SILC_ROUTER)
498 server->stat.routers++;
500 SILC_LOG_DEBUG(("Server initialized"));
502 /* We are done here, return succesfully */
506 silc_server_config_unref(&server->config_ref);
507 silc_net_close_server(sock);
511 /* Task callback to close a socket connection after rehash */
513 SILC_TASK_CALLBACK(silc_server_rehash_close_connection)
515 SilcServer server = context;
516 SilcSocketConnection sock = server->sockets[fd];
521 SILC_LOG_INFO(("Connection %s:%d [%s] is unconfigured",
522 sock->hostname, sock->port,
523 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
524 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
525 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
527 silc_schedule_task_del_by_context(server->schedule, sock);
528 silc_server_disconnect_remote(server, sock,
529 SILC_STATUS_ERR_BANNED_FROM_SERVER,
530 "This connection is removed from "
533 silc_server_free_sock_user_data(server, sock, NULL);
536 /* This function basically reads the config file again and switches the config
537 object pointed by the server object. After that, we have to fix various
538 things such as the server_name and the listening ports.
539 Keep in mind that we no longer have the root privileges at this point. */
541 bool silc_server_rehash(SilcServer server)
543 SilcServerConfig newconfig;
545 SILC_LOG_INFO(("Rehashing server"));
547 /* Reset the logging system */
548 silc_log_quick = TRUE;
549 silc_log_flush_all();
551 /* Start the main rehash phase (read again the config file) */
552 newconfig = silc_server_config_alloc(server->config_file);
554 SILC_LOG_ERROR(("Rehash FAILED."));
558 /* Reinit scheduler if necessary */
559 if (newconfig->param.connections_max > server->config->param.connections_max)
560 if (!silc_schedule_reinit(server->schedule,
561 newconfig->param.connections_max))
564 /* Fix the server_name field */
565 if (strcmp(server->server_name, newconfig->server_info->server_name)) {
566 silc_free(server->server_name);
567 server->server_name = newconfig->server_info->server_name;
568 newconfig->server_info->server_name = NULL;
570 /* Update the idcache list with a fresh pointer */
571 silc_free(server->id_entry->server_name);
572 server->id_entry->server_name = strdup(server->server_name);
573 if (!silc_idcache_del_by_context(server->local_list->servers,
576 if (!silc_idcache_add(server->local_list->servers,
577 server->id_entry->server_name,
578 server->id_entry->id, server->id_entry, 0, NULL))
583 silc_server_config_setlogfiles(server);
585 /* Change new key pair if necessary */
586 if (newconfig->server_info->public_key &&
587 !silc_pkcs_public_key_compare(server->public_key,
588 newconfig->server_info->public_key)) {
589 silc_pkcs_public_key_free(server->public_key);
590 silc_pkcs_private_key_free(server->private_key);
591 server->public_key = newconfig->server_info->public_key;
592 server->private_key = newconfig->server_info->private_key;
593 newconfig->server_info->public_key = NULL;
594 newconfig->server_info->private_key = NULL;
596 /* Allocate PKCS context for local public and private keys */
597 silc_pkcs_free(server->pkcs);
598 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
600 silc_pkcs_public_key_set(server->pkcs, server->public_key);
601 silc_pkcs_private_key_set(server->pkcs, server->private_key);
604 /* Check for unconfigured server and router connections and close
605 connections that were unconfigured. */
607 if (server->config->routers) {
608 SilcServerConfigRouter *ptr;
609 SilcServerConfigRouter *newptr;
612 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
615 /* Check whether new config has this one too */
616 for (newptr = newconfig->routers; newptr; newptr = newptr->next) {
617 if (silc_string_compare(newptr->host, ptr->host) &&
618 newptr->port == ptr->port &&
619 newptr->initiator == ptr->initiator) {
625 if (!found && ptr->host) {
626 /* Remove this connection */
627 SilcSocketConnection sock;
628 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_ROUTER,
629 ptr->host, ptr->port);
630 if (sock && !SILC_IS_LISTENER(sock))
631 silc_schedule_task_add(server->schedule, sock->sock,
632 silc_server_rehash_close_connection,
633 server, 0, 1, SILC_TASK_TIMEOUT,
634 SILC_TASK_PRI_NORMAL);
639 if (server->config->servers) {
640 SilcServerConfigServer *ptr;
641 SilcServerConfigServer *newptr;
644 for (ptr = server->config->servers; ptr; ptr = ptr->next) {
647 /* Check whether new config has this one too */
648 for (newptr = newconfig->servers; newptr; newptr = newptr->next) {
649 if (silc_string_compare(newptr->host, ptr->host)) {
655 if (!found && ptr->host) {
656 /* Remove this connection */
657 SilcSocketConnection sock;
658 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_SERVER,
660 if (sock && !SILC_IS_LISTENER(sock))
661 silc_schedule_task_add(server->schedule, sock->sock,
662 silc_server_rehash_close_connection,
663 server, 0, 1, SILC_TASK_TIMEOUT,
664 SILC_TASK_PRI_NORMAL);
669 if (server->config->clients) {
670 SilcServerConfigClient *ptr;
671 SilcServerConfigClient *newptr;
674 for (ptr = server->config->clients; ptr; ptr = ptr->next) {
677 /* Check whether new config has this one too */
678 for (newptr = newconfig->clients; newptr; newptr = newptr->next) {
679 if (silc_string_compare(newptr->host, ptr->host)) {
685 if (!found && ptr->host) {
686 /* Remove this connection */
687 SilcSocketConnection sock;
688 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_CLIENT,
691 silc_schedule_task_add(server->schedule, sock->sock,
692 silc_server_rehash_close_connection,
693 server, 0, 1, SILC_TASK_TIMEOUT,
694 SILC_TASK_PRI_NORMAL);
699 /* Create connections after rehash */
700 silc_server_create_connections(server);
702 /* Check whether our router status has changed */
703 if (newconfig->servers) {
704 SilcServerConfigServer *ptr = newconfig->servers;
706 server->server_type = SILC_ROUTER;
708 if (ptr->backup_router) {
709 server->server_type = SILC_BACKUP_ROUTER;
710 server->backup_router = TRUE;
711 server->id_entry->server_type = SILC_BACKUP_ROUTER;
718 /* Our old config is gone now. We'll unreference our reference made in
719 silc_server_init and then destroy it since we are destroying it
720 underneath the application (layer which called silc_server_init). */
721 silc_server_config_unref(&server->config_ref);
722 silc_server_config_destroy(server->config);
724 /* Take new config context */
725 server->config = newconfig;
726 silc_server_config_ref(&server->config_ref, server->config, server->config);
729 /* Set debugging on if configured */
730 if (server->config->debug_string) {
732 silc_log_set_debug_string(server->config->debug_string);
736 #endif /* SILC_DEBUG */
738 SILC_LOG_DEBUG(("Server rehashed"));
743 /* The heart of the server. This runs the scheduler thus runs the server.
744 When this returns the server has been stopped and the program will
747 void silc_server_run(SilcServer server)
749 SILC_LOG_INFO(("SILC Server started"));
751 /* Start the scheduler, the heart of the SILC server. When this returns
752 the program will be terminated. */
753 silc_schedule(server->schedule);
756 /* Stops the SILC server. This function is used to shutdown the server.
757 This is usually called after the scheduler has returned. After stopping
758 the server one should call silc_server_free. */
760 void silc_server_stop(SilcServer server)
762 SILC_LOG_INFO(("SILC Server shutting down"));
764 if (server->schedule) {
767 server->server_shutdown = TRUE;
769 /* Close all connections */
770 for (i = 0; i < server->config->param.connections_max; i++) {
771 if (!server->sockets[i])
773 if (!SILC_IS_LISTENER(server->sockets[i])) {
774 SilcSocketConnection sock = server->sockets[i];
775 SilcIDListData idata = sock->user_data;
778 idata->status &= ~SILC_IDLIST_STATUS_DISABLED;
780 silc_schedule_task_del_by_context(server->schedule,
782 silc_schedule_task_del_by_fd(server->schedule,
783 server->sockets[i]->sock);
784 silc_server_disconnect_remote(server, server->sockets[i],
786 "Server is shutting down");
787 if (server->sockets[i]) {
789 silc_server_free_sock_user_data(server, sock,
790 "Server is shutting down");
791 silc_socket_free(sock);
794 silc_socket_free(server->sockets[i]);
795 server->sockets[i] = NULL;
799 /* We are not connected to network anymore */
800 server->standalone = TRUE;
802 silc_schedule_stop(server->schedule);
803 silc_schedule_uninit(server->schedule);
804 server->schedule = NULL;
806 silc_free(server->sockets);
807 server->sockets = NULL;
810 silc_server_protocols_unregister();
812 SILC_LOG_DEBUG(("Server stopped"));
815 /* Function that is called when the network connection to a router has
816 been established. This will continue with the key exchange protocol
817 with the remote router. */
819 void silc_server_start_key_exchange(SilcServer server,
820 SilcServerConnection sconn,
823 SilcSocketConnection newsocket;
824 SilcProtocol protocol;
825 SilcServerKEInternalContext *proto_ctx;
826 SilcServerConfigRouter *conn =
827 (SilcServerConfigRouter *) sconn->conn.ref_ptr;
830 /* Cancel any possible retry timeouts */
831 silc_schedule_task_del_by_callback(server->schedule,
832 silc_server_connect_to_router_retry);
834 /* Set socket options */
835 silc_net_set_socket_nonblock(sock);
836 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
838 /* Create socket connection for the connection. Even though we
839 know that we are connecting to a router we will mark the socket
840 to be unknown connection until we have executed authentication
842 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
843 server->sockets[sock] = newsocket;
844 newsocket->hostname = strdup(sconn->remote_host);
845 newsocket->ip = strdup(sconn->remote_host);
846 newsocket->port = sconn->remote_port;
847 sconn->sock = newsocket;
849 /* Allocate internal protocol context. This is sent as context
851 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
852 proto_ctx->server = (void *)server;
853 proto_ctx->context = (void *)sconn;
854 proto_ctx->sock = newsocket;
855 proto_ctx->rng = server->rng;
856 proto_ctx->responder = FALSE;
858 /* Set Key Exchange flags from configuration, but fall back to global
860 SILC_GET_SKE_FLAGS(conn, proto_ctx);
861 if (server->config->param.key_exchange_pfs)
862 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
864 /* Perform key exchange protocol. silc_server_connect_to_router_second
865 will be called after the protocol is finished. */
866 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
867 &protocol, proto_ctx,
868 silc_server_connect_to_router_second);
869 newsocket->protocol = protocol;
871 /* Register a timeout task that will be executed if the protocol
872 is not executed within set limit. */
873 proto_ctx->timeout_task =
874 silc_schedule_task_add(server->schedule, sock,
875 silc_server_timeout_remote,
876 server, server->config->key_exchange_timeout, 0,
880 /* Register the connection for network input and output. This sets
881 that scheduler will listen for incoming packets for this connection
882 and sets that outgoing packets may be sent to this connection as
883 well. However, this doesn't set the scheduler for outgoing traffic,
884 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
885 later when outgoing data is available. */
886 context = (void *)server;
887 SILC_REGISTER_CONNECTION_FOR_IO(sock);
889 /* Run the protocol */
890 silc_protocol_execute(protocol, server->schedule, 0, 0);
893 /* Timeout callback that will be called to retry connecting to remote
894 router. This is used by both normal and router server. This will wait
895 before retrying the connecting. The timeout is generated by exponential
896 backoff algorithm. */
898 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
900 SilcServer server = app_context;
901 SilcServerConnection sconn = (SilcServerConnection)context;
902 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
903 SilcServerConfigConnParams *param =
904 (conn->param ? conn->param : &server->config->param);
906 /* Don't retry if we are shutting down. */
907 if (server->server_shutdown) {
908 silc_server_config_unref(&sconn->conn);
909 silc_free(sconn->remote_host);
910 silc_free(sconn->backup_replace_ip);
915 SILC_LOG_INFO(("Retrying connecting to a router"));
917 /* Calculate next timeout */
918 if (sconn->retry_count >= 1) {
919 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
920 if (sconn->retry_timeout > param->reconnect_interval_max)
921 sconn->retry_timeout = param->reconnect_interval_max;
923 sconn->retry_timeout = param->reconnect_interval;
925 sconn->retry_count++;
926 sconn->retry_timeout = sconn->retry_timeout +
927 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
929 /* If we've reached max retry count, give up. */
930 if ((sconn->retry_count > param->reconnect_count) &&
931 !param->reconnect_keep_trying) {
932 SILC_LOG_ERROR(("Could not connect to router, giving up"));
933 silc_server_config_unref(&sconn->conn);
934 silc_free(sconn->remote_host);
935 silc_free(sconn->backup_replace_ip);
940 SILC_LOG_DEBUG(("Retrying connecting to a router in %d seconds",
941 sconn->retry_timeout));
943 /* We will lookup a fresh pointer later */
944 silc_server_config_unref(&sconn->conn);
946 /* Wait one before retrying */
947 silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
948 context, sconn->retry_timeout, 0,
949 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
952 /* Generic routine to use connect to a router. */
954 SILC_TASK_CALLBACK(silc_server_connect_router)
956 SilcServer server = app_context;
957 SilcServerConnection sconn = (SilcServerConnection)context;
958 SilcServerConfigRouter *rconn;
961 /* Don't connect if we are shutting down. */
962 if (server->server_shutdown) {
963 silc_free(sconn->remote_host);
964 silc_free(sconn->backup_replace_ip);
969 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
970 (sconn->backup ? "backup router" : "router"),
971 sconn->remote_host, sconn->remote_port));
973 server->router_connect = time(NULL);
974 rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
977 SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
978 (sconn->backup ? "backup router" : "router"),
979 sconn->remote_host, sconn->remote_port));
980 silc_free(sconn->remote_host);
981 silc_free(sconn->backup_replace_ip);
985 silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
987 /* Connect to remote host */
988 sock = silc_net_create_connection(
989 (!server->config->server_info->primary ? NULL :
990 server->config->server_info->primary->server_ip),
991 sconn->remote_port, sconn->remote_host);
993 SILC_LOG_ERROR(("Could not connect to router %s:%d",
994 sconn->remote_host, sconn->remote_port));
995 if (!sconn->no_reconnect)
996 silc_schedule_task_add(server->schedule, 0,
997 silc_server_connect_to_router_retry,
998 context, 0, 1, SILC_TASK_TIMEOUT,
999 SILC_TASK_PRI_NORMAL);
1001 silc_server_config_unref(&sconn->conn);
1002 silc_free(sconn->remote_host);
1003 silc_free(sconn->backup_replace_ip);
1009 /* Continue with key exchange protocol */
1010 silc_server_start_key_exchange(server, sconn, sock);
1013 /* This function connects to our primary router or if we are a router this
1014 establishes all our primary routes. This is called at the start of the
1015 server to do authentication and key exchange with our router - called
1018 SILC_TASK_CALLBACK_GLOBAL(silc_server_connect_to_router)
1020 SilcServer server = (SilcServer)context;
1021 SilcServerConnection sconn;
1022 SilcServerConfigRouter *ptr;
1024 /* Don't connect if we are shutting down. */
1025 if (server->server_shutdown)
1028 SILC_LOG_DEBUG(("We are %s",
1029 (server->server_type == SILC_SERVER ?
1030 "normal server" : server->server_type == SILC_ROUTER ?
1031 "router" : "backup router/normal server")));
1033 if (!server->config->routers) {
1034 /* There wasn't a configured router, we will continue but we don't
1035 have a connection to outside world. We will be standalone server. */
1036 SILC_LOG_DEBUG(("No router(s), we are standalone"));
1037 server->standalone = TRUE;
1041 /* Cancel any possible retry timeouts */
1042 silc_schedule_task_del_by_callback(server->schedule,
1043 silc_server_connect_router);
1044 silc_schedule_task_del_by_callback(server->schedule,
1045 silc_server_connect_to_router_retry);
1047 /* Create the connections to all our routes */
1048 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
1050 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
1051 ptr->backup_router ? "Backup router" : "Router",
1052 ptr->initiator ? "Initiator" : "Responder",
1053 ptr->host, ptr->port));
1055 if (server->server_type == SILC_ROUTER && ptr->backup_router &&
1056 ptr->initiator == FALSE && !server->backup_router &&
1057 !silc_server_config_get_backup_router(server))
1058 server->wait_backup = TRUE;
1060 if (ptr->initiator) {
1061 /* Check whether we are connecting or connected to this host already */
1062 if (silc_server_num_sockets_by_remote(server,
1063 silc_net_is_ip(ptr->host) ?
1065 silc_net_is_ip(ptr->host) ?
1066 NULL : ptr->host, ptr->port,
1067 SILC_SOCKET_TYPE_ROUTER)) {
1068 SILC_LOG_DEBUG(("We are already connected to this router"));
1070 /* If we don't have primary router and this connection is our
1071 primary router we are in desync. Reconnect to the primary. */
1072 if (server->standalone && !server->router) {
1073 SilcServerConfigRouter *primary =
1074 silc_server_config_get_primary_router(server);
1075 if (primary == ptr) {
1076 SilcSocketConnection sock =
1077 silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_ROUTER,
1078 ptr->host, ptr->port);
1080 server->backup_noswitch = TRUE;
1081 if (sock->user_data)
1082 silc_server_free_sock_user_data(server, sock, NULL);
1083 silc_server_disconnect_remote(server, sock, 0, NULL);
1084 server->backup_noswitch = FALSE;
1085 SILC_LOG_DEBUG(("Reconnecting to primary router"));
1096 if (silc_server_num_sockets_by_remote(server,
1097 silc_net_is_ip(ptr->host) ?
1099 silc_net_is_ip(ptr->host) ?
1100 NULL : ptr->host, ptr->port,
1101 SILC_SOCKET_TYPE_UNKNOWN)) {
1102 SILC_LOG_DEBUG(("We are already connecting to this router"));
1106 /* Allocate connection object for hold connection specific stuff. */
1107 sconn = silc_calloc(1, sizeof(*sconn));
1108 sconn->remote_host = strdup(ptr->host);
1109 sconn->remote_port = ptr->port;
1110 sconn->backup = ptr->backup_router;
1111 if (sconn->backup) {
1112 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
1113 sconn->backup_replace_port = ptr->backup_replace_port;
1116 if (!server->router_conn && !sconn->backup)
1117 server->router_conn = sconn;
1119 silc_schedule_task_add(server->schedule, 0,
1120 silc_server_connect_router,
1121 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
1122 SILC_TASK_PRI_NORMAL);
1127 /* Second part of connecting to router(s). Key exchange protocol has been
1128 executed and now we will execute authentication protocol. */
1130 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
1132 SilcProtocol protocol = (SilcProtocol)context;
1133 SilcServerKEInternalContext *ctx =
1134 (SilcServerKEInternalContext *)protocol->context;
1135 SilcServer server = (SilcServer)ctx->server;
1136 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1137 SilcSocketConnection sock = ctx->sock;
1138 SilcServerConnAuthInternalContext *proto_ctx;
1139 SilcServerConfigRouter *conn = NULL;
1141 SILC_LOG_DEBUG(("Start"));
1143 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1144 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1145 /* Error occured during protocol */
1146 silc_protocol_free(protocol);
1147 sock->protocol = NULL;
1148 silc_ske_free_key_material(ctx->keymat);
1150 silc_packet_context_free(ctx->packet);
1152 silc_ske_free(ctx->ske);
1153 silc_free(ctx->dest_id);
1155 silc_server_disconnect_remote(server, sock,
1156 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1158 /* Try reconnecting if configuration wants it */
1159 if (!sconn->no_reconnect) {
1160 silc_schedule_task_add(server->schedule, 0,
1161 silc_server_connect_to_router_retry,
1162 sconn, 0, 1, SILC_TASK_TIMEOUT,
1163 SILC_TASK_PRI_NORMAL);
1167 /* Call completion to indicate error */
1168 if (sconn->callback)
1169 (*sconn->callback)(server, NULL, sconn->callback_context);
1171 silc_server_config_unref(&sconn->conn);
1172 silc_free(sconn->remote_host);
1173 silc_free(sconn->backup_replace_ip);
1178 /* We now have the key material as the result of the key exchange
1179 protocol. Take the key material into use. Free the raw key material
1180 as soon as we've set them into use. */
1181 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1182 ctx->sock, ctx->keymat,
1183 ctx->ske->prop->cipher,
1184 ctx->ske->prop->pkcs,
1185 ctx->ske->prop->hash,
1186 ctx->ske->prop->hmac,
1187 ctx->ske->prop->group,
1189 silc_protocol_free(protocol);
1190 sock->protocol = NULL;
1191 silc_ske_free_key_material(ctx->keymat);
1193 silc_packet_context_free(ctx->packet);
1195 silc_ske_free(ctx->ske);
1196 silc_free(ctx->dest_id);
1198 silc_server_disconnect_remote(server, sock,
1199 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1201 /* Try reconnecting if configuration wants it */
1202 if (!sconn->no_reconnect) {
1203 silc_schedule_task_add(server->schedule, 0,
1204 silc_server_connect_to_router_retry,
1205 sconn, 0, 1, SILC_TASK_TIMEOUT,
1206 SILC_TASK_PRI_NORMAL);
1210 /* Call completion to indicate error */
1211 if (sconn->callback)
1212 (*sconn->callback)(server, NULL, sconn->callback_context);
1214 silc_server_config_unref(&sconn->conn);
1215 silc_free(sconn->remote_host);
1216 silc_free(sconn->backup_replace_ip);
1220 silc_ske_free_key_material(ctx->keymat);
1222 /* Allocate internal context for the authentication protocol. This
1223 is sent as context for the protocol. */
1224 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1225 proto_ctx->server = (void *)server;
1226 proto_ctx->context = (void *)sconn;
1227 proto_ctx->sock = sock;
1228 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1229 proto_ctx->dest_id_type = ctx->dest_id_type;
1230 proto_ctx->dest_id = ctx->dest_id;
1232 /* Resolve the authentication method used in this connection. Check if
1233 we find a match from user configured connections */
1234 if (!sconn->conn.ref_ptr)
1235 conn = silc_server_config_find_router_conn(server, sock->hostname,
1238 conn = sconn->conn.ref_ptr;
1241 /* Match found. Use the configured authentication method. Take only
1242 the passphrase, since for public key auth we automatically use
1243 our local key pair. */
1244 if (conn->passphrase) {
1245 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
1246 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1248 proto_ctx->auth_data = strdup(conn->passphrase);
1249 proto_ctx->auth_data_len = strlen(conn->passphrase);
1250 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
1252 } else if (conn->publickeys) {
1253 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1255 proto_ctx->auth_meth = SILC_AUTH_NONE;
1258 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
1259 sock->hostname, sock->ip, sock->port));
1260 silc_protocol_free(protocol);
1261 sock->protocol = NULL;
1263 silc_packet_context_free(ctx->packet);
1265 silc_ske_free(ctx->ske);
1266 silc_free(ctx->dest_id);
1268 silc_server_config_unref(&sconn->conn);
1269 silc_free(sconn->remote_host);
1270 silc_free(sconn->backup_replace_ip);
1272 silc_server_disconnect_remote(server, sock,
1273 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1277 /* Free old protocol as it is finished now */
1278 silc_protocol_free(protocol);
1280 silc_packet_context_free(ctx->packet);
1282 sock->protocol = NULL;
1284 /* Allocate the authentication protocol. This is allocated here
1285 but we won't start it yet. We will be receiving party of this
1286 protocol thus we will wait that connecting party will make
1287 their first move. */
1288 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1289 &sock->protocol, proto_ctx,
1290 silc_server_connect_to_router_final);
1292 /* Register timeout task. If the protocol is not executed inside
1293 this timelimit the connection will be terminated. */
1294 proto_ctx->timeout_task =
1295 silc_schedule_task_add(server->schedule, sock->sock,
1296 silc_server_timeout_remote,
1298 server->config->conn_auth_timeout, 0,
1302 /* Run the protocol */
1303 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1306 /* Finalizes the connection to router. Registers a server task to the
1307 queue so that we can accept new connections. */
1309 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
1311 SilcProtocol protocol = (SilcProtocol)context;
1312 SilcServerConnAuthInternalContext *ctx =
1313 (SilcServerConnAuthInternalContext *)protocol->context;
1314 SilcServer server = (SilcServer)ctx->server;
1315 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1316 SilcSocketConnection sock = ctx->sock;
1317 SilcServerEntry id_entry = NULL;
1319 unsigned char *id_string;
1321 SilcIDListData idata;
1322 SilcServerConfigRouter *conn = NULL;
1323 SilcServerConfigConnParams *param = NULL;
1325 SILC_LOG_DEBUG(("Start"));
1327 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1328 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1329 /* Error occured during protocol */
1330 silc_free(ctx->dest_id);
1331 sock->protocol = NULL;
1332 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1334 sock->protocol = protocol;
1336 /* Try reconnecting if configuration wants it */
1337 if (!sconn->no_reconnect) {
1338 silc_schedule_task_add(server->schedule, 0,
1339 silc_server_connect_to_router_retry,
1340 sconn, 0, 1, SILC_TASK_TIMEOUT,
1341 SILC_TASK_PRI_NORMAL);
1348 /* Add a task to the queue. This task receives new connections to the
1349 server. This task remains on the queue until the end of the program. */
1350 if (!server->listenning && !sconn->backup) {
1351 silc_schedule_task_add(server->schedule, server->sock,
1352 silc_server_accept_new_connection,
1353 (void *)server, 0, 0,
1355 SILC_TASK_PRI_NORMAL);
1356 server->listenning = TRUE;
1359 /* Send NEW_SERVER packet to the router. We will become registered
1360 to the SILC network after sending this packet. */
1361 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
1362 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1363 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
1364 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1365 silc_buffer_format(packet,
1366 SILC_STR_UI_SHORT(id_len),
1367 SILC_STR_UI_XNSTRING(id_string, id_len),
1368 SILC_STR_UI_SHORT(strlen(server->server_name)),
1369 SILC_STR_UI_XNSTRING(server->server_name,
1370 strlen(server->server_name)),
1373 /* Send the packet */
1374 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
1375 packet->data, packet->len, TRUE);
1376 silc_buffer_free(packet);
1377 silc_free(id_string);
1379 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
1381 /* Check that we do not have this ID already */
1382 id_entry = silc_idlist_find_server_by_id(server->local_list,
1383 ctx->dest_id, TRUE, NULL);
1385 silc_idcache_del_by_context(server->local_list->servers, id_entry);
1387 id_entry = silc_idlist_find_server_by_id(server->global_list,
1388 ctx->dest_id, TRUE, NULL);
1390 silc_idcache_del_by_context(server->global_list->servers, id_entry);
1393 SILC_LOG_DEBUG(("New server id(%s)",
1394 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1396 /* Add the connected router to global server list. Router is sent
1397 as NULL since it's local to us. */
1398 id_entry = silc_idlist_add_server(server->global_list,
1399 strdup(sock->hostname),
1400 SILC_ROUTER, ctx->dest_id, NULL, sock);
1402 silc_free(ctx->dest_id);
1403 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1404 sock->protocol = NULL;
1405 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1407 sock->protocol = protocol;
1411 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1412 silc_free(sock->user_data);
1413 sock->user_data = (void *)id_entry;
1414 sock->type = SILC_SOCKET_TYPE_ROUTER;
1415 idata = (SilcIDListData)sock->user_data;
1416 idata->status |= (SILC_IDLIST_STATUS_REGISTERED |
1417 SILC_IDLIST_STATUS_LOCAL);
1419 conn = sconn->conn.ref_ptr;
1420 param = &server->config->param;
1421 if (conn && conn->param)
1422 param = conn->param;
1424 /* Perform keepalive. */
1425 silc_socket_set_heartbeat(sock, param->keepalive_secs, server,
1426 silc_server_perform_heartbeat,
1429 /* Register re-key timeout */
1430 idata->rekey->timeout = param->key_exchange_rekey;
1431 silc_schedule_task_add(server->schedule, sock->sock,
1432 silc_server_rekey_callback,
1433 (void *)sock, idata->rekey->timeout, 0,
1434 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1436 if (!sconn->backup) {
1437 /* Mark this router our primary router if we're still standalone */
1438 if (server->standalone) {
1439 SILC_LOG_DEBUG(("This connection is our primary router"));
1440 server->id_entry->router = id_entry;
1441 server->router = id_entry;
1442 server->router->server_type = SILC_ROUTER;
1443 server->standalone = FALSE;
1444 server->backup_primary = FALSE;
1446 /* If we are router then announce our possible servers. Backup
1447 router announces also global servers. */
1448 if (server->server_type == SILC_ROUTER)
1449 silc_server_announce_servers(server,
1450 server->backup_router ? TRUE : FALSE,
1451 0, SILC_PRIMARY_ROUTE(server));
1453 /* Announce our clients and channels to the router */
1454 silc_server_announce_clients(server, 0, SILC_PRIMARY_ROUTE(server));
1455 silc_server_announce_channels(server, 0, SILC_PRIMARY_ROUTE(server));
1457 /* If we are backup router then this primary router is whom we are
1459 if (server->server_type == SILC_BACKUP_ROUTER)
1460 silc_server_backup_add(server, server->id_entry, sock->ip,
1461 sconn->remote_port, TRUE);
1464 /* Add this server to be our backup router */
1465 id_entry->server_type = SILC_BACKUP_ROUTER;
1466 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1467 sconn->backup_replace_port, FALSE);
1470 sock->protocol = NULL;
1473 /* Call the completion callback to indicate that we've connected to
1475 if (sconn && sconn->callback)
1476 (*sconn->callback)(server, id_entry, sconn->callback_context);
1478 /* Free the temporary connection data context */
1480 silc_server_config_unref(&sconn->conn);
1481 silc_free(sconn->remote_host);
1482 silc_free(sconn->backup_replace_ip);
1485 if (sconn == server->router_conn)
1486 server->router_conn = NULL;
1489 /* Free the protocol object */
1490 if (sock->protocol == protocol)
1491 sock->protocol = NULL;
1492 silc_protocol_free(protocol);
1494 silc_packet_context_free(ctx->packet);
1496 silc_ske_free(ctx->ske);
1497 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1498 silc_free(ctx->auth_data);
1502 /* Host lookup callback that is called after the incoming connection's
1503 IP and FQDN lookup is performed. This will actually check the acceptance
1504 of the incoming connection and will register the key exchange protocol
1505 for this connection. */
1508 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1511 SilcServerKEInternalContext *proto_ctx =
1512 (SilcServerKEInternalContext *)context;
1513 SilcServer server = (SilcServer)proto_ctx->server;
1514 SilcServerConfigClient *cconfig = NULL;
1515 SilcServerConfigServer *sconfig = NULL;
1516 SilcServerConfigRouter *rconfig = NULL;
1517 SilcServerConfigDeny *deny;
1520 /* Check whether we could resolve both IP and FQDN. */
1521 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1522 server->config->require_reverse_lookup)) {
1523 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1524 sock->hostname ? sock->hostname :
1525 sock->ip ? sock->ip : ""));
1526 server->stat.conn_failures++;
1527 silc_server_disconnect_remote(server, sock,
1528 SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
1529 "Unknown host or IP");
1530 silc_free(proto_ctx);
1534 /* Register the connection for network input and output. This sets
1535 that scheduler will listen for incoming packets for this connection
1536 and sets that outgoing packets may be sent to this connection as well.
1537 However, this doesn't set the scheduler for outgoing traffic, it
1538 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1539 later when outgoing data is available. */
1540 context = (void *)server;
1541 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1543 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1546 /* Listenning port */
1547 if (!server->sockets[(SilcUInt32)proto_ctx->context]) {
1548 silc_server_disconnect_remote(server, sock,
1549 SILC_STATUS_ERR_RESOURCE_LIMIT,
1550 "Connection refused");
1551 server->stat.conn_failures++;
1552 silc_free(proto_ctx);
1555 port = server->sockets[(SilcUInt32)proto_ctx->context]->port;
1557 /* Check whether this connection is denied to connect to us. */
1558 deny = silc_server_config_find_denied(server, sock->ip);
1560 deny = silc_server_config_find_denied(server, sock->hostname);
1562 /* The connection is denied */
1563 SILC_LOG_INFO(("Connection %s (%s) is denied",
1564 sock->hostname, sock->ip));
1565 silc_server_disconnect_remote(server, sock,
1566 SILC_STATUS_ERR_BANNED_FROM_SERVER,
1568 server->stat.conn_failures++;
1569 silc_free(proto_ctx);
1573 /* Check whether we have configured this sort of connection at all. We
1574 have to check all configurations since we don't know what type of
1575 connection this is. */
1576 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1577 cconfig = silc_server_config_find_client(server, sock->hostname);
1578 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1579 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1580 if (server->server_type == SILC_ROUTER) {
1581 if (!(rconfig = silc_server_config_find_router_conn(server,
1582 sock->ip, sock->port)))
1583 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1586 if (!cconfig && !sconfig && !rconfig) {
1587 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1589 silc_server_disconnect_remote(server, sock,
1590 SILC_STATUS_ERR_BANNED_FROM_SERVER, NULL);
1591 server->stat.conn_failures++;
1592 silc_free(proto_ctx);
1596 /* The connection is allowed */
1598 /* Set internal context for key exchange protocol. This is
1599 sent as context for the protocol. */
1600 proto_ctx->sock = sock;
1601 proto_ctx->rng = server->rng;
1602 proto_ctx->responder = TRUE;
1603 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1604 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1605 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1607 /* Take flags for key exchange. Since we do not know what type of connection
1608 this is, we go through all found configurations and use the global ones
1609 as well. This will result always into strictest key exchange flags. */
1610 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1611 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1612 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1613 if (server->config->param.key_exchange_pfs)
1614 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1616 /* Prepare the connection for key exchange protocol. We allocate the
1617 protocol but will not start it yet. The connector will be the
1618 initiator of the protocol thus we will wait for initiation from
1619 there before we start the protocol. */
1620 server->stat.auth_attempts++;
1621 SILC_LOG_DEBUG(("Starting key exchange protocol"));
1622 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1623 &sock->protocol, proto_ctx,
1624 silc_server_accept_new_connection_second);
1626 /* Register a timeout task that will be executed if the connector
1627 will not start the key exchange protocol within specified timeout
1628 and the connection will be closed. */
1629 proto_ctx->timeout_task =
1630 silc_schedule_task_add(server->schedule, sock->sock,
1631 silc_server_timeout_remote,
1633 server->config->key_exchange_timeout, 0,
1638 /* Accepts new connections to the server. Accepting new connections are
1639 done in three parts to make it async. */
1641 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1643 SilcServer server = (SilcServer)context;
1644 SilcSocketConnection newsocket;
1645 SilcServerKEInternalContext *proto_ctx;
1648 SILC_LOG_DEBUG(("Accepting new connection"));
1650 server->stat.conn_attempts++;
1652 sock = silc_net_accept_connection(fd);
1654 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1655 server->stat.conn_failures++;
1659 /* Check for maximum allowed connections */
1660 if (sock > server->config->param.connections_max) {
1661 SILC_LOG_ERROR(("Refusing connection, server is full"));
1662 server->stat.conn_failures++;
1663 silc_net_close_connection(sock);
1667 /* Set socket options */
1668 silc_net_set_socket_nonblock(sock);
1669 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1671 /* We don't create a ID yet, since we don't know what type of connection
1672 this is yet. But, we do add the connection to the socket table. */
1673 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1674 server->sockets[sock] = newsocket;
1676 /* Perform asynchronous host lookup. This will lookup the IP and the
1677 FQDN of the remote connection. After the lookup is done the connection
1678 is accepted further. */
1679 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1680 proto_ctx->server = server;
1681 proto_ctx->context = (void *)fd;
1682 silc_socket_host_lookup(newsocket, TRUE,
1683 silc_server_accept_new_connection_lookup,
1684 (void *)proto_ctx, server->schedule);
1687 /* Second part of accepting new connection. Key exchange protocol has been
1688 performed and now it is time to do little connection authentication
1689 protocol to figure out whether this connection is client or server
1690 and whether it has right to access this server (especially server
1691 connections needs to be authenticated). */
1693 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1695 SilcProtocol protocol = (SilcProtocol)context;
1696 SilcServerKEInternalContext *ctx =
1697 (SilcServerKEInternalContext *)protocol->context;
1698 SilcServer server = (SilcServer)ctx->server;
1699 SilcSocketConnection sock = ctx->sock;
1700 SilcServerConnAuthInternalContext *proto_ctx;
1702 SILC_LOG_DEBUG(("Start"));
1704 if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1705 (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1706 /* Error occured during protocol */
1707 SILC_LOG_DEBUG(("Error in key exchange protocol"));
1708 silc_protocol_free(protocol);
1709 sock->protocol = NULL;
1710 silc_ske_free_key_material(ctx->keymat);
1712 silc_packet_context_free(ctx->packet);
1714 silc_ske_free(ctx->ske);
1715 silc_free(ctx->dest_id);
1716 silc_server_config_unref(&ctx->cconfig);
1717 silc_server_config_unref(&ctx->sconfig);
1718 silc_server_config_unref(&ctx->rconfig);
1721 if (!SILC_IS_DISCONNECTING(sock)) {
1722 SILC_LOG_INFO(("Key exchange failed for %s:%d [%s]", sock->hostname,
1724 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1725 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1726 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1728 silc_server_disconnect_remote(server, sock,
1729 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
1733 server->stat.auth_failures++;
1737 /* We now have the key material as the result of the key exchange
1738 protocol. Take the key material into use. Free the raw key material
1739 as soon as we've set them into use. */
1740 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1741 ctx->sock, ctx->keymat,
1742 ctx->ske->prop->cipher,
1743 ctx->ske->prop->pkcs,
1744 ctx->ske->prop->hash,
1745 ctx->ske->prop->hmac,
1746 ctx->ske->prop->group,
1748 SILC_LOG_ERROR(("Error setting key material in use"));
1749 silc_protocol_free(protocol);
1750 sock->protocol = NULL;
1751 silc_ske_free_key_material(ctx->keymat);
1753 silc_packet_context_free(ctx->packet);
1755 silc_ske_free(ctx->ske);
1756 silc_free(ctx->dest_id);
1757 silc_server_config_unref(&ctx->cconfig);
1758 silc_server_config_unref(&ctx->sconfig);
1759 silc_server_config_unref(&ctx->rconfig);
1761 silc_server_disconnect_remote(server, sock,
1762 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1763 server->stat.auth_failures++;
1766 silc_ske_free_key_material(ctx->keymat);
1768 /* Allocate internal context for the authentication protocol. This
1769 is sent as context for the protocol. */
1770 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1771 proto_ctx->server = (void *)server;
1772 proto_ctx->sock = sock;
1773 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1774 proto_ctx->responder = TRUE;
1775 proto_ctx->dest_id_type = ctx->dest_id_type;
1776 proto_ctx->dest_id = ctx->dest_id;
1777 proto_ctx->cconfig = ctx->cconfig;
1778 proto_ctx->sconfig = ctx->sconfig;
1779 proto_ctx->rconfig = ctx->rconfig;
1781 /* Free old protocol as it is finished now */
1782 silc_protocol_free(protocol);
1784 silc_packet_context_free(ctx->packet);
1786 sock->protocol = NULL;
1788 /* Allocate the authentication protocol. This is allocated here
1789 but we won't start it yet. We will be receiving party of this
1790 protocol thus we will wait that connecting party will make
1791 their first move. */
1792 SILC_LOG_DEBUG(("Starting connection authentication protocol"));
1793 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1794 &sock->protocol, proto_ctx,
1795 silc_server_accept_new_connection_final);
1797 /* Register timeout task. If the protocol is not executed inside
1798 this timelimit the connection will be terminated. */
1799 proto_ctx->timeout_task =
1800 silc_schedule_task_add(server->schedule, sock->sock,
1801 silc_server_timeout_remote,
1803 server->config->conn_auth_timeout, 0,
1808 /* After this is called, server don't wait for backup router anymore.
1809 This gets called automatically even after we have backup router
1810 connection established. */
1812 SILC_TASK_CALLBACK(silc_server_backup_router_wait)
1814 SilcServer server = context;
1815 server->wait_backup = FALSE;
1818 /* Final part of accepting new connection. The connection has now
1819 been authenticated and keys has been exchanged. We also know whether
1820 this is client or server connection. */
1822 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1824 SilcProtocol protocol = (SilcProtocol)context;
1825 SilcServerConnAuthInternalContext *ctx =
1826 (SilcServerConnAuthInternalContext *)protocol->context;
1827 SilcServer server = (SilcServer)ctx->server;
1828 SilcSocketConnection sock = ctx->sock;
1829 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1831 SilcServerConfigConnParams *param = &server->config->param;
1833 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1834 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1835 /* Error occured during protocol */
1836 SILC_LOG_DEBUG(("Error during authentication protocol"));
1837 silc_protocol_free(protocol);
1838 sock->protocol = NULL;
1840 silc_packet_context_free(ctx->packet);
1842 silc_ske_free(ctx->ske);
1843 silc_free(ctx->dest_id);
1844 silc_server_config_unref(&ctx->cconfig);
1845 silc_server_config_unref(&ctx->sconfig);
1846 silc_server_config_unref(&ctx->rconfig);
1849 if (!SILC_IS_DISCONNECTING(sock)) {
1850 SILC_LOG_INFO(("Authentication failed for %s:%d [%s]", sock->hostname,
1852 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1853 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1854 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1856 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1859 server->stat.auth_failures++;
1863 entry->data.last_receive = time(NULL);
1865 switch (ctx->conn_type) {
1866 case SILC_SOCKET_TYPE_CLIENT:
1868 SilcClientEntry client;
1869 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1871 /* Verify whether this connection is after all allowed to connect */
1872 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1873 &server->config->param,
1874 conn->param, ctx->ske)) {
1875 server->stat.auth_failures++;
1879 /* If we are primary router and we have backup router configured
1880 but it has not connected to use yet, do not accept any other
1882 if (server->wait_backup && server->server_type == SILC_ROUTER &&
1883 !server->backup_router) {
1884 SilcServerConfigRouter *router;
1885 router = silc_server_config_get_backup_router(server);
1886 if (router && strcmp(server->config->server_info->primary->server_ip,
1888 silc_server_find_socket_by_host(server,
1889 SILC_SOCKET_TYPE_SERVER,
1890 router->backup_replace_ip, 0)) {
1891 SILC_LOG_INFO(("Will not accept connections because we do "
1892 "not have backup router connection established"));
1893 sock->protocol = NULL;
1894 silc_server_disconnect_remote(server, sock,
1895 SILC_STATUS_ERR_PERM_DENIED,
1896 "We do not have connection to backup "
1897 "router established, try later");
1898 silc_free(sock->user_data);
1899 server->stat.auth_failures++;
1901 /* From here on, wait 10 seconds for the backup router to appear. */
1902 silc_schedule_task_add(server->schedule, 0,
1903 silc_server_backup_router_wait,
1904 (void *)server, 10, 0,
1905 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1910 SILC_LOG_DEBUG(("Remote host is client"));
1911 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1914 /* Add the client to the client ID cache. The nickname and Client ID
1915 and other information is created after we have received NEW_CLIENT
1916 packet from client. */
1917 client = silc_idlist_add_client(server->local_list,
1918 NULL, NULL, NULL, NULL, NULL, sock, 0);
1920 SILC_LOG_ERROR(("Could not add new client to cache"));
1921 silc_free(sock->user_data);
1922 sock->protocol = NULL;
1923 silc_server_disconnect_remote(server, sock,
1924 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1925 server->stat.auth_failures++;
1928 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
1931 server->stat.my_clients++;
1932 server->stat.clients++;
1933 server->stat.cell_clients++;
1935 /* Get connection parameters */
1937 param = conn->param;
1939 if (!param->keepalive_secs)
1940 param->keepalive_secs = server->config->param.keepalive_secs;
1942 if (!param->qos && server->config->param.qos) {
1943 param->qos = server->config->param.qos;
1944 param->qos_rate_limit = server->config->param.qos_rate_limit;
1945 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
1946 param->qos_limit_sec = server->config->param.qos_limit_sec;
1947 param->qos_limit_usec = server->config->param.qos_limit_usec;
1950 /* Check if to be anonymous connection */
1951 if (param->anonymous)
1952 client->mode |= SILC_UMODE_ANONYMOUS;
1955 id_entry = (void *)client;
1958 case SILC_SOCKET_TYPE_SERVER:
1959 case SILC_SOCKET_TYPE_ROUTER:
1961 SilcServerEntry new_server;
1962 bool initiator = FALSE;
1963 bool backup_local = FALSE;
1964 bool backup_router = FALSE;
1965 char *backup_replace_ip = NULL;
1966 SilcUInt16 backup_replace_port = 0;
1967 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1968 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1970 /* If we are backup router and this is incoming server connection
1971 and we do not have connection to primary router, do not allow
1973 if (server->server_type == SILC_BACKUP_ROUTER &&
1974 ctx->conn_type == SILC_SOCKET_TYPE_SERVER &&
1975 !SILC_PRIMARY_ROUTE(server)) {
1976 SILC_LOG_INFO(("Will not accept server connection because we do "
1977 "not have primary router connection established"));
1978 sock->protocol = NULL;
1979 silc_server_disconnect_remote(server, sock,
1980 SILC_STATUS_ERR_PERM_DENIED,
1981 "We do not have connection to primary "
1982 "router established, try later");
1983 silc_free(sock->user_data);
1984 server->stat.auth_failures++;
1988 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1989 /* Verify whether this connection is after all allowed to connect */
1990 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1991 &server->config->param,
1992 rconn ? rconn->param : NULL,
1994 silc_free(sock->user_data);
1995 server->stat.auth_failures++;
2001 param = rconn->param;
2003 if (!param->keepalive_secs)
2004 param->keepalive_secs = server->config->param.keepalive_secs;
2006 if (!param->qos && server->config->param.qos) {
2007 param->qos = server->config->param.qos;
2008 param->qos_rate_limit = server->config->param.qos_rate_limit;
2009 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
2010 param->qos_limit_sec = server->config->param.qos_limit_sec;
2011 param->qos_limit_usec = server->config->param.qos_limit_usec;
2015 initiator = rconn->initiator;
2016 backup_local = rconn->backup_local;
2017 backup_router = rconn->backup_router;
2018 backup_replace_ip = rconn->backup_replace_ip;
2019 backup_replace_port = rconn->backup_replace_port;
2023 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
2024 /* Verify whether this connection is after all allowed to connect */
2025 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
2026 &server->config->param,
2027 sconn ? sconn->param : NULL,
2029 silc_free(sock->user_data);
2030 server->stat.auth_failures++;
2035 param = sconn->param;
2037 if (!param->keepalive_secs)
2038 param->keepalive_secs = server->config->param.keepalive_secs;
2040 if (!param->qos && server->config->param.qos) {
2041 param->qos = server->config->param.qos;
2042 param->qos_rate_limit = server->config->param.qos_rate_limit;
2043 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
2044 param->qos_limit_sec = server->config->param.qos_limit_sec;
2045 param->qos_limit_usec = server->config->param.qos_limit_usec;
2049 backup_router = sconn->backup_router;
2053 /* If we are primary router and we have backup router configured
2054 but it has not connected to use yet, do not accept any other
2056 if (server->wait_backup && server->server_type == SILC_ROUTER &&
2057 !server->backup_router && !backup_router) {
2058 SilcServerConfigRouter *router;
2059 router = silc_server_config_get_backup_router(server);
2060 if (router && strcmp(server->config->server_info->primary->server_ip,
2062 silc_server_find_socket_by_host(server,
2063 SILC_SOCKET_TYPE_SERVER,
2064 router->backup_replace_ip, 0)) {
2065 SILC_LOG_INFO(("Will not accept connections because we do "
2066 "not have backup router connection established"));
2067 sock->protocol = NULL;
2068 silc_server_disconnect_remote(server, sock,
2069 SILC_STATUS_ERR_PERM_DENIED,
2070 "We do not have connection to backup "
2071 "router established, try later");
2072 silc_free(sock->user_data);
2073 server->stat.auth_failures++;
2075 /* From here on, wait 10 seconds for the backup router to appear. */
2076 silc_schedule_task_add(server->schedule, 0,
2077 silc_server_backup_router_wait,
2078 (void *)server, 10, 0,
2079 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2084 SILC_LOG_DEBUG(("Remote host is %s",
2085 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2086 "server" : (backup_router ?
2087 "backup router" : "router")));
2088 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
2089 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2090 "server" : (backup_router ?
2091 "backup router" : "router")));
2093 /* Add the server into server cache. The server name and Server ID
2094 is updated after we have received NEW_SERVER packet from the
2095 server. We mark ourselves as router for this server if we really
2098 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2099 server->local_list : (backup_router ?
2100 server->local_list :
2101 server->global_list)),
2103 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2104 SILC_SERVER : SILC_ROUTER),
2106 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2107 server->id_entry : (backup_router ?
2108 server->id_entry : NULL)),
2111 SILC_LOG_ERROR(("Could not add new server to cache"));
2112 silc_free(sock->user_data);
2113 sock->protocol = NULL;
2114 silc_server_disconnect_remote(server, sock,
2115 SILC_STATUS_ERR_AUTH_FAILED, NULL);
2116 server->stat.auth_failures++;
2119 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
2121 id_entry = (void *)new_server;
2123 /* If the incoming connection is router and marked as backup router
2124 then add it to be one of our backups */
2125 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
2126 /* Change it back to SERVER type since that's what it really is. */
2128 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
2129 new_server->server_type = SILC_BACKUP_ROUTER;
2131 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
2132 ("Backup router %s is now online",
2135 /* Remove the backup waiting with timeout */
2136 silc_schedule_task_add(server->schedule, 0,
2137 silc_server_backup_router_wait,
2138 (void *)server, 5, 0,
2139 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2143 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
2144 server->stat.my_servers++;
2146 server->stat.my_routers++;
2147 server->stat.routers++;
2149 server->stat.servers++;
2151 /* Check whether this connection is to be our primary router connection
2152 if we do not already have the primary route. */
2153 if (!backup_router &&
2154 server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
2155 if (silc_server_config_is_primary_route(server) && !initiator)
2158 SILC_LOG_DEBUG(("We are not standalone server anymore"));
2159 server->standalone = FALSE;
2160 if (!server->id_entry->router) {
2161 server->id_entry->router = id_entry;
2162 server->router = id_entry;
2173 sock->type = ctx->conn_type;
2175 /* Add the common data structure to the ID entry. */
2176 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
2178 /* Add to sockets internal pointer for fast referencing */
2179 silc_free(sock->user_data);
2180 sock->user_data = id_entry;
2182 /* Connection has been fully established now. Everything is ok. */
2183 SILC_LOG_DEBUG(("New connection authenticated"));
2185 /* Perform keepalive. */
2186 if (param->keepalive_secs)
2187 silc_socket_set_heartbeat(sock, param->keepalive_secs, server,
2188 silc_server_perform_heartbeat,
2191 /* Perform Quality of Service */
2193 silc_socket_set_qos(sock, param->qos_rate_limit, param->qos_bytes_limit,
2194 param->qos_limit_sec, param->qos_limit_usec,
2198 if (sock->protocol == protocol)
2199 silc_protocol_free(protocol);
2201 silc_packet_context_free(ctx->packet);
2203 silc_ske_free(ctx->ske);
2204 silc_free(ctx->dest_id);
2205 silc_server_config_unref(&ctx->cconfig);
2206 silc_server_config_unref(&ctx->sconfig);
2207 silc_server_config_unref(&ctx->rconfig);
2209 sock->protocol = NULL;
2212 /* This function is used to read packets from network and send packets to
2213 network. This is usually a generic task. */
2215 SILC_TASK_CALLBACK(silc_server_packet_process)
2217 SilcServer server = (SilcServer)context;
2218 SilcSocketConnection sock = server->sockets[fd];
2219 SilcIDListData idata;
2220 SilcCipher cipher = NULL;
2221 SilcHmac hmac = NULL;
2222 SilcUInt32 sequence = 0;
2223 bool local_is_router;
2227 SILC_LOG_DEBUG(("Unknown socket connection"));
2231 /* Packet sending */
2233 if (type == SILC_TASK_WRITE) {
2234 /* Do not send data to disconnected connection */
2235 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2236 SILC_LOG_DEBUG(("Disconnected socket connection, cannot send"));
2240 server->stat.packets_sent++;
2242 /* Send the packet */
2243 ret = silc_packet_send(sock, TRUE);
2245 /* If returned -2 could not write to connection now, will do
2250 /* The packet has been sent and now it is time to set the connection
2251 back to only for input. When there is again some outgoing data
2252 available for this connection it will be set for output as well.
2253 This call clears the output setting and sets it only for input. */
2254 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
2255 SILC_UNSET_OUTBUF_PENDING(sock);
2256 silc_buffer_clear(sock->outbuf);
2259 SILC_LOG_ERROR(("Error sending packet to connection "
2260 "%s:%d [%s]", sock->hostname, sock->port,
2261 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2262 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2263 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2266 if (sock->user_data)
2267 silc_server_free_sock_user_data(server, sock, NULL);
2268 SILC_SET_DISCONNECTING(sock);
2269 silc_server_close_connection(server, sock);
2274 /* Packet receiving */
2276 /* Read some data from connection */
2277 ret = silc_packet_receive(sock);
2281 SILC_LOG_ERROR(("Error receiving packet from connection "
2282 "%s:%d [%s] %s", sock->hostname, sock->port,
2283 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2284 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2285 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2286 "Router"), strerror(errno)));
2288 if (sock->user_data)
2289 silc_server_free_sock_user_data(server, sock, NULL);
2290 SILC_SET_DISCONNECTING(sock);
2291 silc_server_close_connection(server, sock);
2298 SILC_LOG_DEBUG(("Read EOF"));
2300 /* If connection is disconnecting already we will finally
2301 close the connection */
2302 if (SILC_IS_DISCONNECTING(sock)) {
2303 if (sock->user_data)
2304 silc_server_free_sock_user_data(server, sock, NULL);
2305 silc_server_close_connection(server, sock);
2309 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
2311 if (sock->user_data) {
2314 /* If backup disconnected then mark that resuming willl not be allowed */
2315 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2316 sock->type == SILC_SOCKET_TYPE_SERVER && sock->user_data) {
2317 SilcServerEntry server_entry = sock->user_data;
2318 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2319 server->backup_closed = TRUE;
2322 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
2323 silc_server_free_sock_user_data(server, sock, tmp);
2325 silc_server_free_sock_user_data(server, sock, NULL);
2326 } else if (server->router_conn && server->router_conn->sock == sock &&
2327 !server->router && server->standalone) {
2328 silc_server_create_connections(server);
2331 SILC_SET_DISCONNECTING(sock);
2332 silc_server_close_connection(server, sock);
2336 /* If connection is disconnecting or disconnected we will ignore
2338 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2339 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
2343 /* Get keys and stuff from ID entry */
2344 idata = (SilcIDListData)sock->user_data;
2346 cipher = idata->receive_key;
2347 hmac = idata->hmac_receive;
2348 sequence = idata->psn_receive;
2351 /* Then, process the packet. This will call the parser that will then
2352 decrypt and parse the packet. */
2354 local_is_router = (server->server_type == SILC_ROUTER);
2356 /* If socket connection is our primary, we are backup and we are doing
2357 backup resuming, we won't process the packet as being a router
2358 (affects channel message decryption). */
2359 if (server->backup_router && SILC_SERVER_IS_BACKUP(sock) &&
2360 SILC_PRIMARY_ROUTE(server) == sock)
2361 local_is_router = FALSE;
2363 ret = silc_packet_receive_process(sock, local_is_router,
2364 cipher, hmac, sequence,
2365 silc_server_packet_parse, server);
2367 /* If processing failed the connection is closed. */
2369 /* On packet processing errors we may close our primary router
2370 connection but won't become primary router if we are the backup
2371 since this is local error condition. */
2372 if (SILC_PRIMARY_ROUTE(server) == sock && server->backup_router)
2373 server->backup_noswitch = TRUE;
2375 if (sock->user_data)
2376 silc_server_free_sock_user_data(server, sock, NULL);
2377 SILC_SET_DISCONNECTING(sock);
2378 silc_server_close_connection(server, sock);
2382 /* Parses whole packet, received earlier. */
2384 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
2386 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
2387 SilcServer server = (SilcServer)parse_ctx->context;
2388 SilcSocketConnection sock = parse_ctx->sock;
2389 SilcPacketContext *packet = parse_ctx->packet;
2390 SilcIDListData idata = (SilcIDListData)sock->user_data;
2393 server->stat.packets_received++;
2395 /* Parse the packet */
2396 if (parse_ctx->normal)
2397 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
2399 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
2401 /* If entry is disabled ignore what we got. */
2402 if (idata && idata->status & SILC_IDLIST_STATUS_DISABLED &&
2403 ret != SILC_PACKET_HEARTBEAT && ret != SILC_PACKET_RESUME_ROUTER &&
2404 ret != SILC_PACKET_REKEY && ret != SILC_PACKET_REKEY_DONE) {
2405 SILC_LOG_DEBUG(("Connection is disabled"));
2409 if (ret == SILC_PACKET_NONE) {
2410 SILC_LOG_DEBUG(("Error parsing packet"));
2414 /* Check that the the current client ID is same as in the client's packet. */
2415 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
2416 SilcClientEntry client = (SilcClientEntry)sock->user_data;
2417 if (client && client->id && packet->src_id) {
2418 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
2419 packet->src_id_type);
2420 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
2422 SILC_LOG_DEBUG(("Packet source is not same as sender"));
2429 if (server->server_type == SILC_ROUTER) {
2430 /* Route the packet if it is not destined to us. Other ID types but
2431 server are handled separately after processing them. */
2432 if (packet->dst_id && !(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
2433 packet->dst_id_type == SILC_ID_SERVER &&
2434 sock->type != SILC_SOCKET_TYPE_CLIENT &&
2435 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
2437 /* Route the packet to fastest route for the destination ID */
2438 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
2439 packet->dst_id_type);
2442 silc_server_packet_route(server,
2443 silc_server_route_get(server, id,
2444 packet->dst_id_type),
2451 /* Parse the incoming packet type */
2452 silc_server_packet_parse_type(server, sock, packet);
2454 /* Broadcast packet if it is marked as broadcast packet and it is
2455 originated from router and we are router. */
2456 if (server->server_type == SILC_ROUTER &&
2457 sock->type == SILC_SOCKET_TYPE_ROUTER &&
2458 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
2459 /* Broadcast to our primary route */
2460 silc_server_packet_broadcast(server, SILC_PRIMARY_ROUTE(server), packet);
2462 /* If we have backup routers then we need to feed all broadcast
2463 data to those servers. */
2464 silc_server_backup_broadcast(server, sock, packet);
2468 silc_packet_context_free(packet);
2469 silc_free(parse_ctx);
2472 /* Parser callback called by silc_packet_receive_process. This merely
2473 registers timeout that will handle the actual parsing when appropriate. */
2475 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
2478 SilcServer server = (SilcServer)context;
2479 SilcSocketConnection sock = parser_context->sock;
2480 SilcIDListData idata = (SilcIDListData)sock->user_data;
2484 idata->psn_receive = parser_context->packet->sequence + 1;
2486 /* If protocol for this connection is key exchange or rekey then we'll
2487 process all packets synchronously, since there might be packets in
2488 queue that we are not able to decrypt without first processing the
2489 packets before them. */
2490 if (sock->protocol && sock->protocol->protocol &&
2491 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2492 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2493 silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2496 /* Reprocess data since we'll return FALSE here. This is because
2497 the idata->receive_key might have become valid in the last packet
2498 and we want to call this processor with valid cipher. */
2500 ret = silc_packet_receive_process(
2501 sock, server->server_type == SILC_ROUTER,
2503 idata->hmac_receive, idata->psn_receive,
2504 silc_server_packet_parse, server);
2506 ret = silc_packet_receive_process(
2507 sock, server->server_type == SILC_ROUTER,
2509 silc_server_packet_parse, server);
2512 /* On packet processing errors we may close our primary router
2513 connection but won't become primary router if we are the backup
2514 since this is local error condition. */
2515 if (SILC_PRIMARY_ROUTE(server) == sock && server->backup_router)
2516 server->backup_noswitch = TRUE;
2518 if (sock->user_data)
2519 silc_server_free_sock_user_data(server, sock, NULL);
2520 SILC_SET_DISCONNECTING(sock);
2521 silc_server_close_connection(server, sock);
2527 switch (sock->type) {
2528 case SILC_SOCKET_TYPE_UNKNOWN:
2529 case SILC_SOCKET_TYPE_CLIENT:
2530 /* Parse the packet with timeout */
2531 silc_schedule_task_add(server->schedule, sock->sock,
2532 silc_server_packet_parse_real,
2533 (void *)parser_context, 0, 100000,
2535 SILC_TASK_PRI_NORMAL);
2537 case SILC_SOCKET_TYPE_SERVER:
2538 case SILC_SOCKET_TYPE_ROUTER:
2539 /* Packets from servers are parsed immediately */
2540 silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2550 /* Parses the packet type and calls what ever routines the packet type
2551 requires. This is done for all incoming packets. */
2553 void silc_server_packet_parse_type(SilcServer server,
2554 SilcSocketConnection sock,
2555 SilcPacketContext *packet)
2557 SilcPacketType type = packet->type;
2558 SilcIDListData idata = (SilcIDListData)sock->user_data;
2560 SILC_LOG_DEBUG(("Received %s packet [flags %d]",
2561 silc_get_packet_name(type), packet->flags));
2563 /* Parse the packet type */
2565 case SILC_PACKET_DISCONNECT:
2568 char *message = NULL;
2570 if (packet->flags & SILC_PACKET_FLAG_LIST)
2572 if (packet->buffer->len < 1)
2575 status = (SilcStatus)packet->buffer->data[0];
2576 if (packet->buffer->len > 1 &&
2577 silc_utf8_valid(packet->buffer->data + 1, packet->buffer->len - 1))
2578 message = silc_memdup(packet->buffer->data + 1,
2579 packet->buffer->len - 1);
2581 SILC_LOG_INFO(("Disconnected by %s (%s): %s (%d) %s",
2582 sock->ip, sock->hostname,
2583 silc_get_status_message(status), status,
2584 message ? message : ""));
2587 /* Do not switch to backup in case of error */
2588 server->backup_noswitch = (status == SILC_STATUS_OK ? FALSE : TRUE);
2590 /* If backup disconnected then mark that resuming willl not be allowed */
2591 if (server->server_type == SILC_ROUTER && !server->backup_router &&
2592 sock->type == SILC_SOCKET_TYPE_SERVER && sock->user_data) {
2593 SilcServerEntry server_entry = sock->user_data;
2594 if (server_entry->server_type == SILC_BACKUP_ROUTER)
2595 server->backup_closed = TRUE;
2598 /* Handle the disconnection from our end too */
2599 if (sock->user_data && SILC_IS_LOCAL(sock->user_data))
2600 silc_server_free_sock_user_data(server, sock, NULL);
2601 SILC_SET_DISCONNECTING(sock);
2602 silc_server_close_connection(server, sock);
2603 server->backup_noswitch = FALSE;
2607 case SILC_PACKET_SUCCESS:
2609 * Success received for something. For now we can have only
2610 * one protocol for connection executing at once hence this
2611 * success message is for whatever protocol is executing currently.
2613 if (packet->flags & SILC_PACKET_FLAG_LIST)
2616 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2619 case SILC_PACKET_FAILURE:
2621 * Failure received for something. For now we can have only
2622 * one protocol for connection executing at once hence this
2623 * failure message is for whatever protocol is executing currently.
2625 if (packet->flags & SILC_PACKET_FLAG_LIST)
2628 /* Check for failure START_USE from backup router */
2629 if (server->server_type == SILC_SERVER &&
2630 server->backup_primary && packet->buffer->len == 4) {
2632 SILC_GET32_MSB(type, packet->buffer->data);
2633 if (type == SILC_SERVER_BACKUP_START_USE) {
2634 /* Attempt to reconnect to primary */
2635 SILC_LOG_DEBUG(("Received failed START_USE from backup %s", sock->ip));
2637 /* If backup is our primary, disconnect now. */
2638 if (server->router == sock->user_data) {
2639 if (sock->user_data)
2640 silc_server_free_sock_user_data(server, sock, NULL);
2641 SILC_SET_DISCONNECTING(sock);
2642 silc_server_close_connection(server, sock);
2646 silc_server_create_connections(server);
2650 /* Execute protocol */
2651 if (sock->protocol) {
2652 sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
2653 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2658 case SILC_PACKET_REJECT:
2659 if (packet->flags & SILC_PACKET_FLAG_LIST)
2664 case SILC_PACKET_NOTIFY:
2666 * Received notify packet. Server can receive notify packets from
2667 * router. Server then relays the notify messages to clients if needed.
2669 if (packet->flags & SILC_PACKET_FLAG_LIST)
2670 silc_server_notify_list(server, sock, packet);
2672 silc_server_notify(server, sock, packet);
2678 case SILC_PACKET_CHANNEL_MESSAGE:
2680 * Received channel message. Channel messages are special packets
2681 * (although probably most common ones) thus they are handled
2684 if (packet->flags & SILC_PACKET_FLAG_LIST)
2686 idata->last_receive = time(NULL);
2687 silc_server_channel_message(server, sock, packet);
2690 case SILC_PACKET_CHANNEL_KEY:
2692 * Received key for channel. As channels are created by the router
2693 * the keys are as well. We will distribute the key to all of our
2694 * locally connected clients on the particular channel. Router
2695 * never receives this channel and thus is ignored.
2697 if (packet->flags & SILC_PACKET_FLAG_LIST)
2699 silc_server_channel_key(server, sock, packet);
2705 case SILC_PACKET_COMMAND:
2707 * Recived command. Processes the command request and allocates the
2708 * command context and calls the command.
2710 if (packet->flags & SILC_PACKET_FLAG_LIST)
2712 silc_server_command_process(server, sock, packet);
2715 case SILC_PACKET_COMMAND_REPLY:
2717 * Received command reply packet. Received command reply to command. It
2718 * may be reply to command sent by us or reply to command sent by client
2719 * that we've routed further.
2721 if (packet->flags & SILC_PACKET_FLAG_LIST)
2723 silc_server_command_reply(server, sock, packet);
2727 * Private Message packets
2729 case SILC_PACKET_PRIVATE_MESSAGE:
2731 * Received private message packet. The packet is coming from either
2734 if (packet->flags & SILC_PACKET_FLAG_LIST)
2736 idata->last_receive = time(NULL);
2737 silc_server_private_message(server, sock, packet);
2740 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2742 * Private message key packet.
2744 if (packet->flags & SILC_PACKET_FLAG_LIST)
2746 silc_server_private_message_key(server, sock, packet);
2750 * Key Exchange protocol packets
2752 case SILC_PACKET_KEY_EXCHANGE:
2753 if (packet->flags & SILC_PACKET_FLAG_LIST)
2756 if (sock->protocol && sock->protocol->protocol &&
2757 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2758 SilcServerKEInternalContext *proto_ctx =
2759 (SilcServerKEInternalContext *)sock->protocol->context;
2761 proto_ctx->packet = silc_packet_context_dup(packet);
2763 /* Let the protocol handle the packet */
2764 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2766 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2767 "protocol active (%s:%d [%s]).", sock->hostname,
2769 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2770 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2771 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2776 case SILC_PACKET_KEY_EXCHANGE_1:
2777 if (packet->flags & SILC_PACKET_FLAG_LIST)
2780 if (sock->protocol && sock->protocol->protocol &&
2781 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2782 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2784 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2785 SilcServerRekeyInternalContext *proto_ctx =
2786 (SilcServerRekeyInternalContext *)sock->protocol->context;
2788 if (proto_ctx->packet)
2789 silc_packet_context_free(proto_ctx->packet);
2791 proto_ctx->packet = silc_packet_context_dup(packet);
2793 /* Let the protocol handle the packet */
2794 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2796 SilcServerKEInternalContext *proto_ctx =
2797 (SilcServerKEInternalContext *)sock->protocol->context;
2799 if (proto_ctx->packet)
2800 silc_packet_context_free(proto_ctx->packet);
2802 proto_ctx->packet = silc_packet_context_dup(packet);
2803 proto_ctx->dest_id_type = packet->src_id_type;
2804 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2805 packet->src_id_type);
2806 if (!proto_ctx->dest_id)
2809 /* Let the protocol handle the packet */
2810 silc_protocol_execute(sock->protocol, server->schedule,
2814 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2815 "protocol active (%s:%d [%s]).", sock->hostname,
2817 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2818 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2819 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2824 case SILC_PACKET_KEY_EXCHANGE_2:
2825 if (packet->flags & SILC_PACKET_FLAG_LIST)
2828 if (sock->protocol && sock->protocol->protocol &&
2829 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2830 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2832 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2833 SilcServerRekeyInternalContext *proto_ctx =
2834 (SilcServerRekeyInternalContext *)sock->protocol->context;
2836 if (proto_ctx->packet)
2837 silc_packet_context_free(proto_ctx->packet);
2839 proto_ctx->packet = silc_packet_context_dup(packet);
2841 /* Let the protocol handle the packet */
2842 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2844 SilcServerKEInternalContext *proto_ctx =
2845 (SilcServerKEInternalContext *)sock->protocol->context;
2847 if (proto_ctx->packet)
2848 silc_packet_context_free(proto_ctx->packet);
2850 proto_ctx->packet = silc_packet_context_dup(packet);
2851 proto_ctx->dest_id_type = packet->src_id_type;
2852 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2853 packet->src_id_type);
2854 if (!proto_ctx->dest_id)
2857 /* Let the protocol handle the packet */
2858 silc_protocol_execute(sock->protocol, server->schedule,
2862 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2863 "protocol active (%s:%d [%s]).", sock->hostname,
2865 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2866 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2867 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2872 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2874 * Connection authentication request packet. When we receive this packet
2875 * we will send to the other end information about our mandatory
2876 * authentication method for the connection. This packet maybe received
2879 if (packet->flags & SILC_PACKET_FLAG_LIST)
2881 silc_server_connection_auth_request(server, sock, packet);
2885 * Connection Authentication protocol packets
2887 case SILC_PACKET_CONNECTION_AUTH:
2888 /* Start of the authentication protocol. We receive here the
2889 authentication data and will verify it. */
2890 if (packet->flags & SILC_PACKET_FLAG_LIST)
2893 if (sock->protocol && sock->protocol->protocol->type
2894 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2896 SilcServerConnAuthInternalContext *proto_ctx =
2897 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2899 proto_ctx->packet = silc_packet_context_dup(packet);
2901 /* Let the protocol handle the packet */
2902 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2904 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2905 "protocol active (%s:%d [%s]).", sock->hostname,
2907 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2908 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2909 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2914 case SILC_PACKET_NEW_ID:
2916 * Received New ID packet. This includes some new ID that has been
2917 * created. It may be for client, server or channel. This is the way
2918 * to distribute information about new registered entities in the
2921 if (packet->flags & SILC_PACKET_FLAG_LIST)
2922 silc_server_new_id_list(server, sock, packet);
2924 silc_server_new_id(server, sock, packet);
2927 case SILC_PACKET_NEW_CLIENT:
2929 * Received new client packet. This includes client information that
2930 * we will use to create initial client ID. After creating new
2931 * ID we will send it to the client.
2933 if (packet->flags & SILC_PACKET_FLAG_LIST)
2935 silc_server_new_client(server, sock, packet);
2938 case SILC_PACKET_NEW_SERVER:
2940 * Received new server packet. This includes Server ID and some other
2941 * information that we may save. This is received after server has
2944 if (packet->flags & SILC_PACKET_FLAG_LIST)
2946 silc_server_new_server(server, sock, packet);
2949 case SILC_PACKET_NEW_CHANNEL:
2951 * Received new channel packet. Information about new channel in the
2952 * network are distributed using this packet.
2954 if (packet->flags & SILC_PACKET_FLAG_LIST)
2955 silc_server_new_channel_list(server, sock, packet);
2957 silc_server_new_channel(server, sock, packet);
2960 case SILC_PACKET_HEARTBEAT:
2962 * Received heartbeat.
2964 if (packet->flags & SILC_PACKET_FLAG_LIST)
2968 case SILC_PACKET_KEY_AGREEMENT:
2970 * Received heartbeat.
2972 if (packet->flags & SILC_PACKET_FLAG_LIST)
2974 silc_server_key_agreement(server, sock, packet);
2977 case SILC_PACKET_REKEY:
2979 * Received re-key packet. The sender wants to regenerate the session
2982 if (packet->flags & SILC_PACKET_FLAG_LIST)
2984 silc_server_rekey(server, sock, packet);
2987 case SILC_PACKET_REKEY_DONE:
2989 * The re-key is done.
2991 if (packet->flags & SILC_PACKET_FLAG_LIST)
2994 if (sock->protocol && sock->protocol->protocol &&
2995 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2997 SilcServerRekeyInternalContext *proto_ctx =
2998 (SilcServerRekeyInternalContext *)sock->protocol->context;
3000 if (proto_ctx->packet)
3001 silc_packet_context_free(proto_ctx->packet);
3003 proto_ctx->packet = silc_packet_context_dup(packet);
3005 /* Let the protocol handle the packet */
3006 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
3008 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
3009 "protocol active (%s:%d [%s]).", sock->hostname,
3011 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
3012 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
3013 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
3018 case SILC_PACKET_FTP:
3020 if (packet->flags & SILC_PACKET_FLAG_LIST)
3022 silc_server_ftp(server, sock, packet);
3025 case SILC_PACKET_RESUME_CLIENT:
3027 if (packet->flags & SILC_PACKET_FLAG_LIST)
3029 silc_server_resume_client(server, sock, packet);
3032 case SILC_PACKET_RESUME_ROUTER:
3033 /* Resume router packet received. This packet is received for backup
3034 router resuming protocol. */
3035 if (packet->flags & SILC_PACKET_FLAG_LIST)
3037 silc_server_backup_resume_router(server, sock, packet);
3041 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
3046 /* Creates connection to a remote router. */
3048 void silc_server_create_connection(SilcServer server,
3049 const char *remote_host, SilcUInt32 port)
3051 SilcServerConnection sconn;
3053 /* Allocate connection object for hold connection specific stuff. */
3054 sconn = silc_calloc(1, sizeof(*sconn));
3055 sconn->remote_host = strdup(remote_host);
3056 sconn->remote_port = port;
3057 sconn->no_reconnect = TRUE;
3059 silc_schedule_task_add(server->schedule, 0,
3060 silc_server_connect_router,
3061 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
3062 SILC_TASK_PRI_NORMAL);
3065 SILC_TASK_CALLBACK(silc_server_close_connection_final)
3067 SilcServer server = app_context;
3068 SilcSocketConnection sock = context;
3070 SILC_LOG_DEBUG(("Deleting socket %p", sock));
3072 /* Close the actual connection */
3073 silc_net_close_connection(sock->sock);
3074 server->sockets[sock->sock] = NULL;
3076 /* We won't listen for this connection anymore */
3077 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
3078 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
3080 silc_socket_free(sock);
3083 /* Closes connection to socket connection */
3085 void silc_server_close_connection(SilcServer server,
3086 SilcSocketConnection sock)
3090 if (SILC_IS_DISCONNECTED(sock)) {
3091 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
3092 silc_schedule_task_add(server->schedule, sock->sock,
3093 silc_server_close_connection_final,
3094 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
3095 SILC_TASK_PRI_NORMAL);
3096 server->sockets[sock->sock] = NULL;
3100 /* If any protocol is active cancel its execution. It will call
3101 the final callback which will finalize the disconnection. */
3102 if (sock->protocol && sock->protocol->protocol &&
3103 sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3104 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3105 silc_protocol_cancel(sock->protocol, server->schedule);
3106 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3107 silc_protocol_execute_final(sock->protocol, server->schedule);
3108 sock->protocol = NULL;
3112 memset(tmp, 0, sizeof(tmp));
3113 silc_socket_get_error(sock, tmp, sizeof(tmp));
3114 SILC_LOG_INFO(("Closing connection %s:%d [%s] %s", sock->hostname,
3116 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
3117 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
3118 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
3119 "Router"), tmp[0] ? tmp : ""));
3121 SILC_SET_DISCONNECTED(sock);
3122 silc_schedule_task_add(server->schedule, sock->sock,
3123 silc_server_close_connection_final,
3124 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
3125 SILC_TASK_PRI_NORMAL);
3126 server->sockets[sock->sock] = NULL;
3129 /* Sends disconnect message to remote connection and disconnects the
3130 connection. NOTE: If this is called from protocol callback
3131 then sock->protocol must be set NULL before calling this, since
3132 this routine dispatches protocol callbacks too. */
3134 void silc_server_disconnect_remote(SilcServer server,
3135 SilcSocketConnection sock,
3136 SilcStatus status, ...)
3139 unsigned char buf[512];
3147 if (SILC_IS_DISCONNECTING(sock)) {
3148 SILC_SET_DISCONNECTED(sock);
3149 silc_server_close_connection(server, sock);
3153 memset(buf, 0, sizeof(buf));
3154 va_start(ap, status);
3155 cp = va_arg(ap, char *);
3157 vsnprintf(buf, sizeof(buf) - 1, cp, ap);
3162 SILC_LOG_DEBUG(("Disconnecting remote host"));
3164 /* Notify remote end that the conversation is over. The notify message
3165 is tried to be sent immediately. */
3169 len += silc_utf8_encoded_len(buf, strlen(buf), SILC_STRING_ASCII);
3171 buffer = silc_buffer_alloc_size(len);
3175 buffer->data[0] = status;
3177 silc_utf8_encode(buf, strlen(buf), SILC_STRING_ASCII, buffer->data + 1,
3179 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
3180 buffer->data, buffer->len, TRUE);
3181 silc_buffer_free(buffer);
3184 silc_server_packet_queue_purge(server, sock);
3186 /* Mark the connection to be disconnected */
3187 SILC_SET_DISCONNECTING(sock);
3188 silc_server_close_connection(server, sock);
3191 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
3193 SilcServer server = app_context;
3194 SilcClientEntry client = context;
3196 assert(!silc_hash_table_count(client->channels));
3198 silc_idlist_del_data(client);
3199 silc_idcache_purge_by_context(server->local_list->clients, client);
3202 /* Frees client data and notifies about client's signoff. */
3204 void silc_server_free_client_data(SilcServer server,
3205 SilcSocketConnection sock,
3206 SilcClientEntry client,
3208 const char *signoff)
3210 SILC_LOG_DEBUG(("Freeing client data"));
3212 /* If there is pending outgoing data for the client then purge it
3213 to the network before removing the client entry. */
3214 silc_server_packet_queue_purge(server, sock);
3217 /* Check if anyone is watching this nickname */
3218 if (server->server_type == SILC_ROUTER)
3219 silc_server_check_watcher_list(server, client, NULL,
3220 SILC_NOTIFY_TYPE_SIGNOFF);
3222 /* Send SIGNOFF notify to routers. */
3224 silc_server_send_notify_signoff(server, SILC_PRIMARY_ROUTE(server),
3225 SILC_BROADCAST(server), client->id,
3229 /* Remove client from all channels */
3231 silc_server_remove_from_channels(server, NULL, client,
3232 TRUE, (char *)signoff, TRUE, FALSE);
3234 silc_server_remove_from_channels(server, NULL, client,
3235 FALSE, NULL, FALSE, FALSE);
3237 /* Remove this client from watcher list if it is */
3238 silc_server_del_from_watcher_list(server, client);
3240 /* Update statistics */
3241 server->stat.my_clients--;
3242 server->stat.clients--;
3243 if (server->stat.cell_clients)
3244 server->stat.cell_clients--;
3245 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
3246 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
3247 silc_schedule_task_del_by_context(server->schedule, client);
3249 /* We will not delete the client entry right away. We will take it
3250 into history (for WHOWAS command) for 5 minutes, unless we're
3251 shutting down server. */
3252 if (!server->server_shutdown) {
3253 silc_schedule_task_add(server->schedule, 0,
3254 silc_server_free_client_data_timeout,
3256 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
3257 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
3258 client->data.status &= ~SILC_IDLIST_STATUS_LOCAL;
3260 client->router = NULL;
3261 client->connection = NULL;
3263 /* Delete directly since we're shutting down server */
3264 silc_idlist_del_data(client);
3265 silc_idlist_del_client(server->local_list, client);
3269 /* Frees user_data pointer from socket connection object. This also sends
3270 appropriate notify packets to the network to inform about leaving
3273 void silc_server_free_sock_user_data(SilcServer server,
3274 SilcSocketConnection sock,
3275 const char *signoff_message)
3278 /* If any protocol is active cancel its execution */
3279 if (sock->protocol && sock->protocol->protocol &&
3280 sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3281 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3282 silc_protocol_cancel(sock->protocol, server->schedule);
3283 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3284 silc_protocol_execute_final(sock->protocol, server->schedule);
3285 sock->protocol = NULL;
3288 switch (sock->type) {
3289 case SILC_SOCKET_TYPE_CLIENT:
3291 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
3292 silc_server_free_client_data(server, sock, user_data, TRUE,
3296 case SILC_SOCKET_TYPE_SERVER:
3297 case SILC_SOCKET_TYPE_ROUTER:
3299 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
3300 SilcServerEntry backup_router = NULL;
3302 SILC_LOG_DEBUG(("Freeing server data"));
3305 backup_router = silc_server_backup_get(server, user_data->id);
3307 if (!server->backup_router && server->server_type == SILC_ROUTER &&
3308 backup_router == server->id_entry &&
3309 sock->type != SILC_SOCKET_TYPE_ROUTER)
3310 backup_router = NULL;
3312 if (server->server_shutdown || server->backup_noswitch)
3313 backup_router = NULL;
3315 /* If this was our primary router connection then we're lost to
3316 the outside world. */
3317 if (server->router == user_data) {
3318 /* Check whether we have a backup router connection */
3319 if (!backup_router || backup_router == user_data) {
3320 if (!server->no_reconnect)
3321 silc_server_create_connections(server);
3322 server->id_entry->router = NULL;
3323 server->router = NULL;
3324 server->standalone = TRUE;
3325 server->backup_primary = FALSE;
3326 backup_router = NULL;
3328 if (server->id_entry != backup_router) {
3329 SILC_LOG_INFO(("New primary router is backup router %s",
3330 backup_router->server_name));
3331 server->id_entry->router = backup_router;
3332 server->router = backup_router;
3333 server->router_connect = time(0);
3334 server->backup_primary = TRUE;
3335 backup_router->data.status &= ~SILC_IDLIST_STATUS_DISABLED;
3337 /* Send START_USE to backup router to indicate we have switched */
3338 silc_server_backup_send_start_use(server,
3339 backup_router->connection,
3342 SILC_LOG_INFO(("We are now new primary router in this cell"));
3343 server->id_entry->router = NULL;
3344 server->router = NULL;
3345 server->standalone = TRUE;
3348 /* We stop here to take a breath */
3351 if (server->backup_router) {
3352 server->server_type = SILC_ROUTER;
3354 /* We'll need to constantly try to reconnect to the primary
3355 router so that we'll see when it comes back online. */
3356 silc_server_backup_reconnect(server, sock->ip, sock->port,
3357 silc_server_backup_connected,
3361 /* Mark this connection as replaced */
3362 silc_server_backup_replaced_add(server, user_data->id,
3365 } else if (backup_router) {
3366 SILC_LOG_INFO(("Enabling the use of backup router %s",
3367 backup_router->server_name));
3369 /* Mark this connection as replaced */
3370 silc_server_backup_replaced_add(server, user_data->id,
3372 } else if (server->server_type == SILC_SERVER &&
3373 sock->type == SILC_SOCKET_TYPE_ROUTER) {
3374 /* Reconnect to the router (backup) */
3375 if (!server->no_reconnect)
3376 silc_server_create_connections(server);
3379 if (user_data->server_name)
3380 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
3381 ("Server %s signoff", user_data->server_name));
3383 if (!backup_router) {
3384 /* Remove all servers that are originated from this server, and
3385 remove the clients of those servers too. */
3386 silc_server_remove_servers_by_server(server, user_data, TRUE);
3389 /* Remove the clients that this server owns as they will become
3390 invalid now too. For backup router the server is actually
3391 coming from the primary router, so mark that as the owner
3393 if (server->server_type == SILC_BACKUP_ROUTER &&
3394 sock->type == SILC_SOCKET_TYPE_SERVER)
3395 silc_server_remove_clients_by_server(server, server->router,
3399 silc_server_remove_clients_by_server(server, user_data,
3402 /* Remove channels owned by this server */
3403 if (server->server_type == SILC_SERVER)
3404 silc_server_remove_channels_by_server(server, user_data);
3406 /* Enable local server connections that may be disabled */
3407 silc_server_local_servers_toggle_enabled(server, TRUE);
3409 /* Update the client entries of this server to the new backup
3410 router. If we are the backup router we also resolve the real
3411 servers for the clients. After updating is over this also
3412 removes the clients that this server explicitly owns. */
3413 silc_server_update_clients_by_server(server, user_data,
3414 backup_router, TRUE);
3416 /* If we are router and just lost our primary router (now standlaone)
3417 we remove everything that was behind it, since we don't know
3419 if (server->server_type == SILC_ROUTER && server->standalone)
3420 /* Remove all servers that are originated from this server, and
3421 remove the clients of those servers too. */
3422 silc_server_remove_servers_by_server(server, user_data, TRUE);
3424 /* Finally remove the clients that are explicitly owned by this
3425 server. They go down with the server. */
3426 silc_server_remove_clients_by_server(server, user_data,
3429 /* Update our server cache to use the new backup router too. */
3430 silc_server_update_servers_by_server(server, user_data, backup_router);
3431 if (server->server_type == SILC_SERVER)
3432 silc_server_update_channels_by_server(server, user_data,
3435 /* Send notify about primary router going down to local operators */
3436 if (server->backup_router)
3437 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3438 SILC_NOTIFY_TYPE_NONE,
3439 ("%s switched to backup router %s "
3440 "(we are primary router now)",
3441 server->server_name, server->server_name));
3442 else if (server->router)
3443 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3444 SILC_NOTIFY_TYPE_NONE,
3445 ("%s switched to backup router %s",
3446 server->server_name,
3447 server->router->server_name));
3449 server->backup_noswitch = FALSE;
3451 /* Free the server entry */
3452 silc_server_backup_del(server, user_data);
3453 silc_server_backup_replaced_del(server, user_data);
3454 silc_idlist_del_data(user_data);
3455 if (!silc_idlist_del_server(server->local_list, user_data))
3456 silc_idlist_del_server(server->global_list, user_data);
3457 if (sock->type == SILC_SOCKET_TYPE_SERVER) {
3458 server->stat.my_servers--;
3460 server->stat.my_routers--;
3461 server->stat.routers--;
3463 server->stat.servers--;
3464 if (server->server_type == SILC_ROUTER)
3465 server->stat.cell_servers--;
3467 if (backup_router && backup_router != server->id_entry) {
3468 /* Announce all of our stuff that was created about 5 minutes ago.
3469 The backup router knows all the other stuff already. */
3470 if (server->server_type == SILC_ROUTER)
3471 silc_server_announce_servers(server, FALSE, time(0) - 300,
3472 backup_router->connection);
3474 /* Announce our clients and channels to the router */
3475 silc_server_announce_clients(server, time(0) - 300,
3476 backup_router->connection);
3477 silc_server_announce_channels(server, time(0) - 300,
3478 backup_router->connection);
3484 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
3486 SILC_LOG_DEBUG(("Freeing unknown connection data"));
3488 silc_idlist_del_data(user_data);
3489 silc_free(user_data);
3494 sock->user_data = NULL;
3497 /* Removes client from all channels it has joined. This is used when client
3498 connection is disconnected. If the client on a channel is last, the
3499 channel is removed as well. This sends the SIGNOFF notify types. */
3501 void silc_server_remove_from_channels(SilcServer server,
3502 SilcSocketConnection sock,
3503 SilcClientEntry client,
3505 const char *signoff_message,
3509 SilcChannelEntry channel;
3510 SilcChannelClientEntry chl;
3511 SilcHashTableList htl;
3512 SilcBuffer clidp = NULL;
3517 if (notify && !client->id)
3520 SILC_LOG_DEBUG(("Removing client %s from joined channels",
3521 notify ? silc_id_render(client->id, SILC_ID_CLIENT) : ""));
3524 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3529 /* Remove the client from all channels. The client is removed from
3530 the channels' user list. */
3531 silc_hash_table_list(client->channels, &htl);
3532 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3533 channel = chl->channel;
3535 /* Remove channel if this is last client leaving the channel, unless
3536 the channel is permanent. */
3537 if (server->server_type != SILC_SERVER &&
3538 silc_hash_table_count(channel->user_list) < 2) {
3539 silc_server_channel_delete(server, channel);
3543 silc_hash_table_del(client->channels, channel);
3544 silc_hash_table_del(channel->user_list, client);
3545 channel->user_count--;
3547 /* If there is no global users on the channel anymore mark the channel
3548 as local channel. Do not check if the removed client is local client. */
3549 if (server->server_type == SILC_SERVER && channel->global_users &&
3550 chl->client->router && !silc_server_channel_has_global(channel))
3551 channel->global_users = FALSE;
3553 memset(chl, 'A', sizeof(*chl));
3556 /* Update statistics */
3557 if (SILC_IS_LOCAL(client))
3558 server->stat.my_chanclients--;
3559 if (server->server_type == SILC_ROUTER) {
3560 server->stat.cell_chanclients--;
3561 server->stat.chanclients--;
3564 /* If there is not at least one local user on the channel then we don't
3565 need the channel entry anymore, we can remove it safely, unless the
3566 channel is permanent channel */
3567 if (server->server_type == SILC_SERVER &&
3568 !silc_server_channel_has_local(channel)) {
3569 /* Notify about leaving client if this channel has global users. */
3570 if (notify && channel->global_users)
3571 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3572 SILC_NOTIFY_TYPE_SIGNOFF,
3573 signoff_message ? 2 : 1,
3574 clidp->data, clidp->len,
3575 signoff_message, signoff_message ?
3576 strlen(signoff_message) : 0);
3578 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3579 silc_server_channel_delete(server, channel);
3583 /* Send notify to channel about client leaving SILC and channel too */
3585 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3586 SILC_NOTIFY_TYPE_SIGNOFF,
3587 signoff_message ? 2 : 1,
3588 clidp->data, clidp->len,
3589 signoff_message, signoff_message ?
3590 strlen(signoff_message) : 0);
3592 if (killed && clidp) {
3593 /* Remove the client from channel's invite list */
3594 if (channel->invite_list &&
3595 silc_hash_table_count(channel->invite_list)) {
3597 SilcArgumentPayload iargs;
3598 ab = silc_argument_payload_encode_one(NULL, clidp->data,
3600 iargs = silc_argument_payload_parse(ab->data, ab->len, 1);
3601 silc_server_inviteban_process(server, channel->invite_list, 1, iargs);
3602 silc_buffer_free(ab);
3603 silc_argument_payload_free(iargs);
3607 /* Don't create keys if we are shutting down */
3608 if (server->server_shutdown)
3611 /* Re-generate channel key if needed */
3612 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3613 if (!silc_server_create_channel_key(server, channel, 0))
3616 /* Send the channel key to the channel. The key of course is not sent
3617 to the client who was removed from the channel. */
3618 silc_server_send_channel_key(server, client->connection, channel,
3619 server->server_type == SILC_ROUTER ?
3620 FALSE : !server->standalone);
3624 silc_hash_table_list_reset(&htl);
3626 silc_buffer_free(clidp);
3629 /* Removes client from one channel. This is used for example when client
3630 calls LEAVE command to remove itself from the channel. Returns TRUE
3631 if channel still exists and FALSE if the channel is removed when
3632 last client leaves the channel. If `notify' is FALSE notify messages
3635 bool silc_server_remove_from_one_channel(SilcServer server,
3636 SilcSocketConnection sock,
3637 SilcChannelEntry channel,
3638 SilcClientEntry client,
3641 SilcChannelClientEntry chl;
3644 SILC_LOG_DEBUG(("Removing %s from channel %s",
3645 silc_id_render(client->id, SILC_ID_CLIENT),
3646 channel->channel_name));
3648 /* Get the entry to the channel, if this client is not on the channel
3650 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
3653 /* Remove channel if this is last client leaving the channel, unless
3654 the channel is permanent. */
3655 if (server->server_type != SILC_SERVER &&
3656 silc_hash_table_count(channel->user_list) < 2) {
3657 silc_server_channel_delete(server, channel);
3661 silc_hash_table_del(client->channels, channel);
3662 silc_hash_table_del(channel->user_list, client);
3663 channel->user_count--;
3665 /* If there is no global users on the channel anymore mark the channel
3666 as local channel. Do not check if the client is local client. */
3667 if (server->server_type == SILC_SERVER && channel->global_users &&
3668 chl->client->router && !silc_server_channel_has_global(channel))
3669 channel->global_users = FALSE;
3671 memset(chl, 'O', sizeof(*chl));
3674 /* Update statistics */
3675 if (SILC_IS_LOCAL(client))
3676 server->stat.my_chanclients--;
3677 if (server->server_type == SILC_ROUTER) {
3678 server->stat.cell_chanclients--;
3679 server->stat.chanclients--;
3682 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3686 /* If there is not at least one local user on the channel then we don't
3687 need the channel entry anymore, we can remove it safely, unless the
3688 channel is permanent channel */
3689 if (server->server_type == SILC_SERVER &&
3690 !silc_server_channel_has_local(channel)) {
3691 /* Notify about leaving client if this channel has global users. */
3692 if (notify && channel->global_users)
3693 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3694 SILC_NOTIFY_TYPE_LEAVE, 1,
3695 clidp->data, clidp->len);
3697 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3698 silc_server_channel_delete(server, channel);
3699 silc_buffer_free(clidp);
3703 /* Send notify to channel about client leaving the channel */
3705 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3706 SILC_NOTIFY_TYPE_LEAVE, 1,
3707 clidp->data, clidp->len);
3709 silc_buffer_free(clidp);
3713 /* Timeout callback. This is called if connection is idle or for some
3714 other reason is not responding within some period of time. This
3715 disconnects the remote end. */
3717 SILC_TASK_CALLBACK(silc_server_timeout_remote)
3719 SilcServer server = (SilcServer)context;
3720 SilcSocketConnection sock = server->sockets[fd];
3721 SilcProtocolType protocol = 0;
3723 SILC_LOG_DEBUG(("Start"));
3728 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
3729 sock->hostname, sock->ip));
3731 /* If we have protocol active we must assure that we call the protocol's
3732 final callback so that all the memory is freed. */
3733 if (sock->protocol && sock->protocol->protocol &&
3734 sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3735 protocol = sock->protocol->protocol->type;
3736 silc_protocol_cancel(sock->protocol, server->schedule);
3737 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3738 silc_protocol_execute_final(sock->protocol, server->schedule);
3739 sock->protocol = NULL;
3743 silc_server_disconnect_remote(server, sock,
3745 SILC_PROTOCOL_SERVER_CONNECTION_AUTH ?
3746 SILC_STATUS_ERR_AUTH_FAILED :
3747 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
3748 "Connection timeout");
3750 if (sock->user_data)
3751 silc_server_free_sock_user_data(server, sock, NULL);
3754 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
3755 function may be used only by router. In real SILC network all channels
3756 are created by routers thus this function is never used by normal
3759 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3760 SilcServerID *router_id,
3766 SilcChannelID *channel_id;
3767 SilcChannelEntry entry;
3771 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3774 cipher = SILC_DEFAULT_CIPHER;
3776 hmac = SILC_DEFAULT_HMAC;
3778 /* Allocate cipher */
3779 if (!silc_cipher_alloc(cipher, &key))
3783 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3784 silc_cipher_free(key);
3788 channel_name = strdup(channel_name);
3790 /* Create the channel ID */
3791 if (!silc_id_create_channel_id(server, router_id, server->rng,
3793 silc_free(channel_name);
3794 silc_cipher_free(key);
3795 silc_hmac_free(newhmac);
3799 /* Create the channel */
3800 entry = silc_idlist_add_channel(server->local_list, channel_name,
3801 SILC_CHANNEL_MODE_NONE, channel_id,
3802 NULL, key, newhmac, 0);
3804 silc_free(channel_name);
3805 silc_cipher_free(key);
3806 silc_hmac_free(newhmac);
3807 silc_free(channel_id);
3811 entry->cipher = strdup(cipher);
3812 entry->hmac_name = strdup(hmac);
3814 /* Now create the actual key material */
3815 if (!silc_server_create_channel_key(server, entry,
3816 silc_cipher_get_key_len(key) / 8)) {
3817 silc_idlist_del_channel(server->local_list, entry);
3821 /* Notify other routers about the new channel. We send the packet
3822 to our primary route. */
3824 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3825 channel_name, entry->id,
3826 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3829 /* Distribute to backup routers */
3830 if (broadcast && server->server_type == SILC_ROUTER) {
3833 SilcUInt32 name_len = strlen(channel_name);
3834 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3835 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3837 packet = silc_channel_payload_encode(channel_name, name_len,
3838 cid, channel_id_len, entry->mode);
3839 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3840 packet->data, packet->len, FALSE, TRUE);
3842 silc_buffer_free(packet);
3845 server->stat.my_channels++;
3846 if (server->server_type == SILC_ROUTER) {
3847 server->stat.channels++;
3848 server->stat.cell_channels++;
3849 entry->users_resolved = TRUE;
3855 /* Same as above but creates the channel with Channel ID `channel_id. */
3858 silc_server_create_new_channel_with_id(SilcServer server,
3862 SilcChannelID *channel_id,
3865 SilcChannelEntry entry;
3869 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3872 cipher = SILC_DEFAULT_CIPHER;
3874 hmac = SILC_DEFAULT_HMAC;
3876 /* Allocate cipher */
3877 if (!silc_cipher_alloc(cipher, &key))
3881 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3882 silc_cipher_free(key);
3886 channel_name = strdup(channel_name);
3888 /* Create the channel */
3889 entry = silc_idlist_add_channel(server->local_list, channel_name,
3890 SILC_CHANNEL_MODE_NONE, channel_id,
3891 NULL, key, newhmac, 0);
3893 silc_cipher_free(key);
3894 silc_hmac_free(newhmac);
3895 silc_free(channel_name);
3899 /* Now create the actual key material */
3900 if (!silc_server_create_channel_key(server, entry,
3901 silc_cipher_get_key_len(key) / 8)) {
3902 silc_idlist_del_channel(server->local_list, entry);
3906 /* Notify other routers about the new channel. We send the packet
3907 to our primary route. */
3909 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3910 channel_name, entry->id,
3911 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3914 /* Distribute to backup routers */
3915 if (broadcast && server->server_type == SILC_ROUTER) {
3918 SilcUInt32 name_len = strlen(channel_name);
3919 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3920 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3922 packet = silc_channel_payload_encode(channel_name, name_len,
3923 cid, channel_id_len, entry->mode);
3924 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3925 packet->data, packet->len, FALSE, TRUE);
3927 silc_buffer_free(packet);
3930 server->stat.my_channels++;
3931 if (server->server_type == SILC_ROUTER) {
3932 server->stat.channels++;
3933 server->stat.cell_channels++;
3934 entry->users_resolved = TRUE;
3940 /* Channel's key re-key timeout callback. */
3942 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3944 SilcServer server = app_context;
3945 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3949 /* Return now if we are shutting down */
3950 if (server->server_shutdown)
3953 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3956 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3959 /* Generates new channel key. This is used to create the initial channel key
3960 but also to re-generate new key for channel. If `key_len' is provided
3961 it is the bytes of the key length. */
3963 bool silc_server_create_channel_key(SilcServer server,
3964 SilcChannelEntry channel,
3968 unsigned char channel_key[32], hash[32];
3971 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3972 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3976 SILC_LOG_DEBUG(("Generating channel %s key", channel->channel_name));
3978 if (!channel->channel_key)
3979 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3980 channel->channel_key = NULL;
3986 else if (channel->key_len)
3987 len = channel->key_len / 8;
3989 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3991 /* Create channel key */
3992 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3995 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3997 /* Remove old key if exists */
3999 memset(channel->key, 0, channel->key_len / 8);
4000 silc_free(channel->key);
4004 channel->key_len = len * 8;
4005 channel->key = silc_memdup(channel_key, len);
4006 memset(channel_key, 0, sizeof(channel_key));
4008 /* Generate HMAC key from the channel key data and set it */
4010 if (!silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac)) {
4011 memset(channel->key, 0, channel->key_len / 8);
4012 silc_free(channel->key);
4013 channel->channel_key = NULL;
4016 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
4017 silc_hmac_set_key(channel->hmac, hash,
4018 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
4019 memset(hash, 0, sizeof(hash));
4021 if (server->server_type == SILC_ROUTER) {
4022 if (!channel->rekey)
4023 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
4024 channel->rekey->channel = channel;
4025 channel->rekey->key_len = key_len;
4026 if (channel->rekey->task)
4027 silc_schedule_task_del(server->schedule, channel->rekey->task);
4029 channel->rekey->task =
4030 silc_schedule_task_add(server->schedule, 0,
4031 silc_server_channel_key_rekey,
4032 (void *)channel->rekey,
4033 server->config->channel_rekey_secs, 0,
4035 SILC_TASK_PRI_NORMAL);
4041 /* Saves the channel key found in the encoded `key_payload' buffer. This
4042 function is used when we receive Channel Key Payload and also when we're
4043 processing JOIN command reply. Returns entry to the channel. */
4045 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
4046 SilcBuffer key_payload,
4047 SilcChannelEntry channel)
4049 SilcChannelKeyPayload payload = NULL;
4050 SilcChannelID *id = NULL;
4051 unsigned char *tmp, hash[32];
4055 /* Decode channel key payload */
4056 payload = silc_channel_key_payload_parse(key_payload->data,
4059 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
4064 /* Get the channel entry */
4067 /* Get channel ID */
4068 tmp = silc_channel_key_get_id(payload, &tmp_len);
4069 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
4075 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
4077 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
4079 if (server->server_type == SILC_ROUTER)
4080 SILC_LOG_ERROR(("Received key for non-existent channel %s",
4081 silc_id_render(id, SILC_ID_CHANNEL)));
4087 SILC_LOG_DEBUG(("Saving new channel %s key", channel->channel_name));
4089 tmp = silc_channel_key_get_key(payload, &tmp_len);
4095 cipher = silc_channel_key_get_cipher(payload, NULL);
4101 /* Remove old key if exists */
4103 memset(channel->key, 0, channel->key_len / 8);
4104 silc_free(channel->key);
4105 silc_cipher_free(channel->channel_key);
4108 /* Create new cipher */
4109 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
4110 channel->channel_key = NULL;
4115 if (channel->cipher)
4116 silc_free(channel->cipher);
4117 channel->cipher = strdup(cipher);
4120 channel->key_len = tmp_len * 8;
4121 channel->key = silc_memdup(tmp, tmp_len);
4122 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
4124 /* Generate HMAC key from the channel key data and set it */
4126 if (!silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac)) {
4127 memset(channel->key, 0, channel->key_len / 8);
4128 silc_free(channel->key);
4129 channel->channel_key = NULL;
4132 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
4133 silc_hmac_set_key(channel->hmac, hash,
4134 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
4136 memset(hash, 0, sizeof(hash));
4137 memset(tmp, 0, tmp_len);
4139 if (server->server_type == SILC_ROUTER) {
4140 if (!channel->rekey)
4141 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
4142 channel->rekey->channel = channel;
4143 if (channel->rekey->task)
4144 silc_schedule_task_del(server->schedule, channel->rekey->task);
4146 channel->rekey->task =
4147 silc_schedule_task_add(server->schedule, 0,
4148 silc_server_channel_key_rekey,
4149 (void *)channel->rekey,
4150 server->config->channel_rekey_secs, 0,
4152 SILC_TASK_PRI_NORMAL);
4158 silc_channel_key_payload_free(payload);
4163 /* Heartbeat callback. This function is set as argument for the
4164 silc_socket_set_heartbeat function. The library will call this function
4165 at the set time interval. */
4167 void silc_server_perform_heartbeat(SilcSocketConnection sock,
4170 SilcServer server = hb_context;
4172 SILC_LOG_DEBUG(("Sending heartbeat to %s:%d (%s)", sock->hostname,
4173 sock->port, sock->ip));
4175 /* Send the heartbeat */
4176 silc_server_send_heartbeat(server, sock);
4179 /* Returns assembled of all servers in the given ID list. The packet's
4180 form is dictated by the New ID payload. */
4182 static void silc_server_announce_get_servers(SilcServer server,
4183 SilcServerEntry remote,
4185 SilcBuffer *servers,
4186 unsigned long creation_time)
4188 SilcIDCacheList list;
4189 SilcIDCacheEntry id_cache;
4190 SilcServerEntry entry;
4193 /* Go through all clients in the list */
4194 if (silc_idcache_get_all(id_list->servers, &list)) {
4195 if (silc_idcache_list_first(list, &id_cache)) {
4197 entry = (SilcServerEntry)id_cache->context;
4199 /* Do not announce the one we've sending our announcements and
4200 do not announce ourself. Also check the creation time if it's
4202 if ((entry == remote) || (entry == server->id_entry) ||
4203 (creation_time && entry->data.created < creation_time)) {
4204 if (!silc_idcache_list_next(list, &id_cache))
4209 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
4211 *servers = silc_buffer_realloc(*servers,
4213 (*servers)->truelen + idp->len :
4215 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
4216 silc_buffer_put(*servers, idp->data, idp->len);
4217 silc_buffer_pull(*servers, idp->len);
4218 silc_buffer_free(idp);
4220 if (!silc_idcache_list_next(list, &id_cache))
4225 silc_idcache_list_free(list);
4230 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
4236 p = silc_notify_payload_encode(notify, argc, ap);
4242 /* This function is used by router to announce existing servers to our
4243 primary router when we've connected to it. If `creation_time' is non-zero
4244 then only the servers that has been created after the `creation_time'
4245 will be announced. */
4247 void silc_server_announce_servers(SilcServer server, bool global,
4248 unsigned long creation_time,
4249 SilcSocketConnection remote)
4251 SilcBuffer servers = NULL;
4253 SILC_LOG_DEBUG(("Announcing servers"));
4255 /* Get servers in local list */
4256 silc_server_announce_get_servers(server, remote->user_data,
4257 server->local_list, &servers,
4261 /* Get servers in global list */
4262 silc_server_announce_get_servers(server, remote->user_data,
4263 server->global_list, &servers,
4267 silc_buffer_push(servers, servers->data - servers->head);
4268 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
4270 /* Send the packet */
4271 silc_server_packet_send(server, remote,
4272 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4273 servers->data, servers->len, TRUE);
4275 silc_buffer_free(servers);
4279 /* Returns assembled packet of all clients in the given ID list. The
4280 packet's form is dictated by the New ID Payload. */
4282 static void silc_server_announce_get_clients(SilcServer server,
4284 SilcBuffer *clients,
4286 unsigned long creation_time)
4288 SilcIDCacheList list;
4289 SilcIDCacheEntry id_cache;
4290 SilcClientEntry client;
4293 unsigned char mode[4];
4295 /* Go through all clients in the list */
4296 if (silc_idcache_get_all(id_list->clients, &list)) {
4297 if (silc_idcache_list_first(list, &id_cache)) {
4299 client = (SilcClientEntry)id_cache->context;
4301 if (creation_time && client->data.created < creation_time) {
4302 if (!silc_idcache_list_next(list, &id_cache))
4306 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED) &&
4307 !client->connection && !client->router && !SILC_IS_LOCAL(client)) {
4308 if (!silc_idcache_list_next(list, &id_cache))
4313 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
4315 *clients = silc_buffer_realloc(*clients,
4317 (*clients)->truelen + idp->len :
4319 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
4320 silc_buffer_put(*clients, idp->data, idp->len);
4321 silc_buffer_pull(*clients, idp->len);
4323 SILC_PUT32_MSB(client->mode, mode);
4325 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
4326 2, idp->data, idp->len,
4328 *umodes = silc_buffer_realloc(*umodes,
4330 (*umodes)->truelen + tmp->len :
4332 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
4333 silc_buffer_put(*umodes, tmp->data, tmp->len);
4334 silc_buffer_pull(*umodes, tmp->len);
4335 silc_buffer_free(tmp);
4337 silc_buffer_free(idp);
4339 if (!silc_idcache_list_next(list, &id_cache))
4344 silc_idcache_list_free(list);
4348 /* This function is used to announce our existing clients to our router
4349 when we've connected to it. If `creation_time' is non-zero then only
4350 the clients that has been created after the `creation_time' will be
4353 void silc_server_announce_clients(SilcServer server,
4354 unsigned long creation_time,
4355 SilcSocketConnection remote)
4357 SilcBuffer clients = NULL;
4358 SilcBuffer umodes = NULL;
4360 SILC_LOG_DEBUG(("Announcing clients"));
4362 /* Get clients in local list */
4363 silc_server_announce_get_clients(server, server->local_list,
4364 &clients, &umodes, creation_time);
4366 /* As router we announce our global list as well */
4367 if (server->server_type == SILC_ROUTER)
4368 silc_server_announce_get_clients(server, server->global_list,
4369 &clients, &umodes, creation_time);
4372 silc_buffer_push(clients, clients->data - clients->head);
4373 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
4375 /* Send the packet */
4376 silc_server_packet_send(server, remote,
4377 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4378 clients->data, clients->len, TRUE);
4380 silc_buffer_free(clients);
4384 silc_buffer_push(umodes, umodes->data - umodes->head);
4385 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
4387 /* Send the packet */
4388 silc_server_packet_send(server, remote,
4389 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4390 umodes->data, umodes->len, TRUE);
4392 silc_buffer_free(umodes);
4396 /* Returns channel's topic for announcing it */
4398 void silc_server_announce_get_channel_topic(SilcServer server,
4399 SilcChannelEntry channel,
4404 if (channel->topic) {
4405 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4406 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
4407 chidp->data, chidp->len,
4409 strlen(channel->topic));
4410 silc_buffer_free(chidp);
4414 /* Returns channel's invite and ban lists */
4416 void silc_server_announce_get_inviteban(SilcServer server,
4417 SilcChannelEntry channel,
4421 SilcBuffer list, idp, idp2, tmp2;
4423 SilcHashTableList htl;
4424 const unsigned char a[1] = { 0x03 };
4426 idp = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
4428 /* Encode invite list */
4429 if (channel->invite_list && silc_hash_table_count(channel->invite_list)) {
4430 list = silc_buffer_alloc_size(2);
4431 type = silc_hash_table_count(channel->invite_list);
4432 SILC_PUT16_MSB(type, list->data);
4433 silc_hash_table_list(channel->invite_list, &htl);
4434 while (silc_hash_table_get(&htl, (void **)&type, (void **)&tmp2))
4435 list = silc_argument_payload_encode_one(list, tmp2->data, tmp2->len,
4437 silc_hash_table_list_reset(&htl);
4439 idp2 = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4441 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_INVITE, 5,
4442 idp->data, idp->len,
4443 channel->channel_name,
4444 strlen(channel->channel_name),
4445 idp2->data, idp2->len,
4447 list->data, list->len);
4448 silc_buffer_free(idp2);
4449 silc_buffer_free(list);
4452 /* Encode ban list */
4453 if (channel->ban_list && silc_hash_table_count(channel->ban_list)) {
4454 list = silc_buffer_alloc_size(2);
4455 type = silc_hash_table_count(channel->ban_list);
4456 SILC_PUT16_MSB(type, list->data);
4457 silc_hash_table_list(channel->ban_list, &htl);
4458 while (silc_hash_table_get(&htl, (void **)&type, (void **)&tmp2))
4459 list = silc_argument_payload_encode_one(list, tmp2->data, tmp2->len,
4461 silc_hash_table_list_reset(&htl);
4464 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_BAN, 3,
4465 idp->data, idp->len,
4467 list->data, list->len);
4468 silc_buffer_free(list);
4471 silc_buffer_free(idp);
4474 /* Returns assembled packets for channel users of the `channel'. */
4476 void silc_server_announce_get_channel_users(SilcServer server,
4477 SilcChannelEntry channel,
4478 SilcBuffer *channel_modes,
4479 SilcBuffer *channel_users,
4480 SilcBuffer *channel_users_modes)
4482 SilcChannelClientEntry chl;
4483 SilcHashTableList htl;
4484 SilcBuffer chidp, clidp, csidp;
4485 SilcBuffer tmp, fkey = NULL, chpklist;
4487 unsigned char mode[4];
4490 SILC_LOG_DEBUG(("Start"));
4492 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4493 csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4494 chpklist = silc_server_get_channel_pk_list(server, channel, TRUE, FALSE);
4497 SILC_PUT32_MSB(channel->mode, mode);
4498 hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
4499 if (channel->founder_key)
4500 fkey = silc_pkcs_public_key_payload_encode(channel->founder_key);
4502 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
4503 7, csidp->data, csidp->len,
4506 hmac, hmac ? strlen(hmac) : 0,
4507 channel->passphrase,
4508 channel->passphrase ?
4509 strlen(channel->passphrase) : 0,
4510 fkey ? fkey->data : NULL,
4511 fkey ? fkey->len : 0,
4512 chpklist ? chpklist->data : NULL,
4513 chpklist ? chpklist->len : 0);
4516 silc_buffer_realloc(*channel_modes,
4518 (*channel_modes)->truelen + len : len));
4519 silc_buffer_pull_tail(*channel_modes,
4520 ((*channel_modes)->end -
4521 (*channel_modes)->data));
4522 silc_buffer_put(*channel_modes, tmp->data, tmp->len);
4523 silc_buffer_pull(*channel_modes, len);
4524 silc_buffer_free(tmp);
4525 silc_buffer_free(fkey);
4528 /* Now find all users on the channel */
4529 silc_hash_table_list(channel->user_list, &htl);
4530 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4531 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4534 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
4535 clidp->data, clidp->len,
4536 chidp->data, chidp->len);
4539 silc_buffer_realloc(*channel_users,
4541 (*channel_users)->truelen + len : len));
4542 silc_buffer_pull_tail(*channel_users,
4543 ((*channel_users)->end -
4544 (*channel_users)->data));
4546 silc_buffer_put(*channel_users, tmp->data, tmp->len);
4547 silc_buffer_pull(*channel_users, len);
4548 silc_buffer_free(tmp);
4550 /* CUMODE notify for mode change on the channel */
4551 SILC_PUT32_MSB(chl->mode, mode);
4552 if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
4553 fkey = silc_pkcs_public_key_payload_encode(channel->founder_key);
4554 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
4555 4, csidp->data, csidp->len,
4557 clidp->data, clidp->len,
4558 fkey ? fkey->data : NULL,
4559 fkey ? fkey->len : 0);
4561 *channel_users_modes =
4562 silc_buffer_realloc(*channel_users_modes,
4563 (*channel_users_modes ?
4564 (*channel_users_modes)->truelen + len : len));
4565 silc_buffer_pull_tail(*channel_users_modes,
4566 ((*channel_users_modes)->end -
4567 (*channel_users_modes)->data));
4569 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
4570 silc_buffer_pull(*channel_users_modes, len);
4571 silc_buffer_free(tmp);
4572 silc_buffer_free(fkey);
4574 silc_buffer_free(clidp);
4576 silc_hash_table_list_reset(&htl);
4577 silc_buffer_free(chidp);
4578 silc_buffer_free(csidp);
4581 /* Returns assembled packets for all channels and users on those channels
4582 from the given ID List. The packets are in the form dictated by the
4583 New Channel and New Channel User payloads. */
4585 void silc_server_announce_get_channels(SilcServer server,
4587 SilcBuffer *channels,
4588 SilcBuffer **channel_modes,
4589 SilcBuffer *channel_users,
4590 SilcBuffer **channel_users_modes,
4591 SilcUInt32 *channel_users_modes_c,
4592 SilcBuffer **channel_topics,
4593 SilcBuffer **channel_invites,
4594 SilcBuffer **channel_bans,
4595 SilcChannelID ***channel_ids,
4596 unsigned long creation_time)
4598 SilcIDCacheList list;
4599 SilcIDCacheEntry id_cache;
4600 SilcChannelEntry channel;
4603 SilcUInt16 name_len;
4605 int i = *channel_users_modes_c;
4608 SILC_LOG_DEBUG(("Start"));
4610 /* Go through all channels in the list */
4611 if (silc_idcache_get_all(id_list->channels, &list)) {
4612 if (silc_idcache_list_first(list, &id_cache)) {
4614 channel = (SilcChannelEntry)id_cache->context;
4616 if (creation_time && channel->created < creation_time)
4621 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4622 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4623 name_len = strlen(channel->channel_name);
4626 len = 4 + name_len + id_len + 4;
4628 silc_buffer_realloc(*channels,
4629 (*channels ? (*channels)->truelen +
4631 silc_buffer_pull_tail(*channels,
4632 ((*channels)->end - (*channels)->data));
4633 silc_buffer_format(*channels,
4634 SILC_STR_UI_SHORT(name_len),
4635 SILC_STR_UI_XNSTRING(channel->channel_name,
4637 SILC_STR_UI_SHORT(id_len),
4638 SILC_STR_UI_XNSTRING(cid, id_len),
4639 SILC_STR_UI_INT(channel->mode),
4641 silc_buffer_pull(*channels, len);
4644 if (creation_time && channel->updated < creation_time)
4650 /* Channel user modes */
4651 *channel_users_modes = silc_realloc(*channel_users_modes,
4652 sizeof(**channel_users_modes) *
4654 (*channel_users_modes)[i] = NULL;
4655 *channel_modes = silc_realloc(*channel_modes,
4656 sizeof(**channel_modes) * (i + 1));
4657 (*channel_modes)[i] = NULL;
4658 *channel_ids = silc_realloc(*channel_ids,
4659 sizeof(**channel_ids) * (i + 1));
4660 (*channel_ids)[i] = NULL;
4661 silc_server_announce_get_channel_users(server, channel,
4662 &(*channel_modes)[i],
4664 &(*channel_users_modes)[i]);
4665 (*channel_ids)[i] = channel->id;
4667 /* Channel's topic */
4668 *channel_topics = silc_realloc(*channel_topics,
4669 sizeof(**channel_topics) * (i + 1));
4670 (*channel_topics)[i] = NULL;
4671 silc_server_announce_get_channel_topic(server, channel,
4672 &(*channel_topics)[i]);
4674 /* Channel's invite and ban list */
4675 *channel_invites = silc_realloc(*channel_invites,
4676 sizeof(**channel_invites) * (i + 1));
4677 (*channel_invites)[i] = NULL;
4678 *channel_bans = silc_realloc(*channel_bans,
4679 sizeof(**channel_bans) * (i + 1));
4680 (*channel_bans)[i] = NULL;
4681 silc_server_announce_get_inviteban(server, channel,
4682 &(*channel_invites)[i],
4683 &(*channel_bans)[i]);
4685 (*channel_users_modes_c)++;
4691 if (!silc_idcache_list_next(list, &id_cache))
4696 silc_idcache_list_free(list);
4700 /* This function is used to announce our existing channels to our router
4701 when we've connected to it. This also announces the users on the
4702 channels to the router. If the `creation_time' is non-zero only the
4703 channels that was created after the `creation_time' are announced.
4704 Note that the channel users are still announced even if the `creation_time'
4707 void silc_server_announce_channels(SilcServer server,
4708 unsigned long creation_time,
4709 SilcSocketConnection remote)
4711 SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
4712 SilcBuffer *channel_users_modes = NULL;
4713 SilcBuffer *channel_topics = NULL;
4714 SilcBuffer *channel_invites = NULL;
4715 SilcBuffer *channel_bans = NULL;
4716 SilcUInt32 channel_users_modes_c = 0;
4717 SilcChannelID **channel_ids = NULL;
4719 SILC_LOG_DEBUG(("Announcing channels and channel users"));
4721 /* Get channels and channel users in local list */
4722 silc_server_announce_get_channels(server, server->local_list,
4723 &channels, &channel_modes,
4725 &channel_users_modes,
4726 &channel_users_modes_c,
4730 &channel_ids, creation_time);
4732 /* Get channels and channel users in global list */
4733 if (server->server_type != SILC_SERVER)
4734 silc_server_announce_get_channels(server, server->global_list,
4735 &channels, &channel_modes,
4737 &channel_users_modes,
4738 &channel_users_modes_c,
4742 &channel_ids, creation_time);
4745 silc_buffer_push(channels, channels->data - channels->head);
4746 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
4748 /* Send the packet */
4749 silc_server_packet_send(server, remote,
4750 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
4751 channels->data, channels->len,
4754 silc_buffer_free(channels);
4757 if (channel_users) {
4758 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
4759 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
4760 channel_users->len);
4762 /* Send the packet */
4763 silc_server_packet_send(server, remote,
4764 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4765 channel_users->data, channel_users->len,
4768 silc_buffer_free(channel_users);
4771 if (channel_modes) {
4774 for (i = 0; i < channel_users_modes_c; i++) {
4775 if (!channel_modes[i])
4777 silc_buffer_push(channel_modes[i],
4778 channel_modes[i]->data -
4779 channel_modes[i]->head);
4780 SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
4781 channel_modes[i]->len);
4782 silc_server_packet_send_dest(server, remote,
4783 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4784 channel_ids[i], SILC_ID_CHANNEL,
4785 channel_modes[i]->data,
4786 channel_modes[i]->len,
4788 silc_buffer_free(channel_modes[i]);
4790 silc_free(channel_modes);
4793 if (channel_users_modes) {
4796 for (i = 0; i < channel_users_modes_c; i++) {
4797 if (!channel_users_modes[i])
4799 silc_buffer_push(channel_users_modes[i],
4800 channel_users_modes[i]->data -
4801 channel_users_modes[i]->head);
4802 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
4803 channel_users_modes[i]->len);
4804 silc_server_packet_send_dest(server, remote,
4805 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4806 channel_ids[i], SILC_ID_CHANNEL,
4807 channel_users_modes[i]->data,
4808 channel_users_modes[i]->len,
4810 silc_buffer_free(channel_users_modes[i]);
4812 silc_free(channel_users_modes);
4815 if (channel_topics) {
4818 for (i = 0; i < channel_users_modes_c; i++) {
4819 if (!channel_topics[i])
4822 silc_buffer_push(channel_topics[i],
4823 channel_topics[i]->data -
4824 channel_topics[i]->head);
4825 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
4826 channel_topics[i]->len);
4827 silc_server_packet_send_dest(server, remote,
4828 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4829 channel_ids[i], SILC_ID_CHANNEL,
4830 channel_topics[i]->data,
4831 channel_topics[i]->len,
4833 silc_buffer_free(channel_topics[i]);
4835 silc_free(channel_topics);
4838 if (channel_invites) {
4841 for (i = 0; i < channel_users_modes_c; i++) {
4842 if (!channel_invites[i])
4845 silc_buffer_push(channel_invites[i],
4846 channel_invites[i]->data -
4847 channel_invites[i]->head);
4848 SILC_LOG_HEXDUMP(("channel invite list"), channel_invites[i]->data,
4849 channel_invites[i]->len);
4850 silc_server_packet_send_dest(server, remote,
4851 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4852 channel_ids[i], SILC_ID_CHANNEL,
4853 channel_invites[i]->data,
4854 channel_invites[i]->len,
4856 silc_buffer_free(channel_invites[i]);
4858 silc_free(channel_invites);
4864 for (i = 0; i < channel_users_modes_c; i++) {
4865 if (!channel_bans[i])
4868 silc_buffer_push(channel_bans[i],
4869 channel_bans[i]->data -
4870 channel_bans[i]->head);
4871 SILC_LOG_HEXDUMP(("channel ban list"), channel_bans[i]->data,
4872 channel_bans[i]->len);
4873 silc_server_packet_send_dest(server, remote,
4874 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4875 channel_ids[i], SILC_ID_CHANNEL,
4876 channel_bans[i]->data,
4877 channel_bans[i]->len,
4879 silc_buffer_free(channel_bans[i]);
4881 silc_free(channel_bans);
4884 silc_free(channel_ids);
4887 /* Assembles user list and users mode list from the `channel'. */
4889 bool silc_server_get_users_on_channel(SilcServer server,
4890 SilcChannelEntry channel,
4891 SilcBuffer *user_list,
4892 SilcBuffer *mode_list,
4893 SilcUInt32 *user_count)
4895 SilcChannelClientEntry chl;
4896 SilcHashTableList htl;
4897 SilcBuffer client_id_list;
4898 SilcBuffer client_mode_list;
4900 SilcUInt32 list_count = 0, len = 0;
4902 if (!silc_hash_table_count(channel->user_list))
4905 silc_hash_table_list(channel->user_list, &htl);
4906 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4907 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
4908 silc_hash_table_list_reset(&htl);
4910 client_id_list = silc_buffer_alloc(len);
4912 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
4913 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
4914 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
4916 silc_hash_table_list(channel->user_list, &htl);
4917 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4919 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4920 silc_buffer_put(client_id_list, idp->data, idp->len);
4921 silc_buffer_pull(client_id_list, idp->len);
4922 silc_buffer_free(idp);
4924 /* Client's mode on channel */
4925 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
4926 silc_buffer_pull(client_mode_list, 4);
4930 silc_hash_table_list_reset(&htl);
4931 silc_buffer_push(client_id_list,
4932 client_id_list->data - client_id_list->head);
4933 silc_buffer_push(client_mode_list,
4934 client_mode_list->data - client_mode_list->head);
4936 *user_list = client_id_list;
4937 *mode_list = client_mode_list;
4938 *user_count = list_count;
4942 /* Saves users and their modes to the `channel'. */
4944 void silc_server_save_users_on_channel(SilcServer server,
4945 SilcSocketConnection sock,
4946 SilcChannelEntry channel,
4947 SilcClientID *noadd,
4948 SilcBuffer user_list,
4949 SilcBuffer mode_list,
4950 SilcUInt32 user_count)
4955 SilcClientID *client_id;
4956 SilcClientEntry client;
4957 SilcIDCacheEntry cache;
4958 SilcChannelClientEntry chl;
4960 SILC_LOG_DEBUG(("Saving %d users on %s channel", user_count,
4961 channel->channel_name));
4963 for (i = 0; i < user_count; i++) {
4965 SILC_GET16_MSB(idp_len, user_list->data + 2);
4967 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
4968 silc_buffer_pull(user_list, idp_len);
4973 SILC_GET32_MSB(mode, mode_list->data);
4974 silc_buffer_pull(mode_list, 4);
4976 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
4977 silc_free(client_id);
4983 /* Check if we have this client cached already. */
4984 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4985 server->server_type, &cache);
4987 client = silc_idlist_find_client_by_id(server->global_list,
4988 client_id, server->server_type,
4991 /* If router did not find such Client ID in its lists then this must
4992 be bogus client or some router in the net is buggy. */
4993 if (server->server_type != SILC_SERVER) {
4994 silc_free(client_id);
4998 /* We don't have that client anywhere, add it. The client is added
4999 to global list since server didn't have it in the lists so it must be
5001 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
5002 silc_id_dup(client_id, SILC_ID_CLIENT),
5003 sock->user_data, NULL, 0);
5005 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
5006 silc_free(client_id);
5010 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
5015 silc_free(client_id);
5017 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
5018 SILC_LOG_ERROR(("Attempting to add unregistered client to channel ",
5019 "%s", channel->channel_name));
5023 if (!silc_server_client_on_channel(client, channel, &chl)) {
5024 /* Client was not on the channel, add it. */
5025 chl = silc_calloc(1, sizeof(*chl));
5026 chl->client = client;
5028 chl->channel = channel;
5029 silc_hash_table_add(channel->user_list, chl->client, chl);
5030 silc_hash_table_add(client->channels, chl->channel, chl);
5031 channel->user_count++;
5039 /* Saves channels and channels user modes to the `client'. Removes
5040 the client from those channels that are not sent in the list but
5043 void silc_server_save_user_channels(SilcServer server,
5044 SilcSocketConnection sock,
5045 SilcClientEntry client,
5046 SilcBuffer channels,
5047 SilcBuffer channels_user_modes)
5050 SilcUInt32 *chumodes;
5051 SilcChannelPayload entry;
5052 SilcChannelEntry channel;
5053 SilcChannelID *channel_id;
5054 SilcChannelClientEntry chl;
5055 SilcHashTable ht = NULL;
5056 SilcHashTableList htl;
5060 if (!channels || !channels_user_modes ||
5061 !(client->data.status & SILC_IDLIST_STATUS_REGISTERED))
5064 ch = silc_channel_payload_parse_list(channels->data, channels->len);
5065 if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
5067 ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL,
5068 NULL, NULL, NULL, TRUE);
5069 silc_dlist_start(ch);
5070 while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
5071 /* Check if we have this channel, and add it if we don't have it.
5072 Also add the client on the channel unless it is there already. */
5073 channel_id = silc_channel_get_id_parse(entry);
5074 channel = silc_idlist_find_channel_by_id(server->local_list,
5077 channel = silc_idlist_find_channel_by_id(server->global_list,
5080 if (server->server_type != SILC_SERVER) {
5081 silc_free(channel_id);
5086 /* We don't have that channel anywhere, add it. */
5087 name = silc_channel_get_name(entry, NULL);
5088 channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
5089 channel_id, server->router,
5092 silc_free(channel_id);
5099 channel->mode = silc_channel_get_mode(entry);
5101 /* Add the client on the channel */
5102 if (!silc_server_client_on_channel(client, channel, &chl)) {
5103 chl = silc_calloc(1, sizeof(*chl));
5104 chl->client = client;
5105 chl->mode = chumodes[i++];
5106 chl->channel = channel;
5107 silc_hash_table_add(channel->user_list, chl->client, chl);
5108 silc_hash_table_add(client->channels, chl->channel, chl);
5109 channel->user_count++;
5112 chl->mode = chumodes[i++];
5115 silc_hash_table_add(ht, channel, channel);
5116 silc_free(channel_id);
5118 silc_channel_payload_list_free(ch);
5119 silc_free(chumodes);
5123 /* Go through the list again and remove client from channels that
5124 are no part of the list. */
5126 silc_hash_table_list(client->channels, &htl);
5127 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
5128 if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
5129 silc_hash_table_del(chl->channel->user_list, chl->client);
5130 silc_hash_table_del(chl->client->channels, chl->channel);
5134 silc_hash_table_list_reset(&htl);
5135 silc_hash_table_free(ht);
5137 silc_hash_table_list(client->channels, &htl);
5138 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
5139 silc_hash_table_del(chl->channel->user_list, chl->client);
5140 silc_hash_table_del(chl->client->channels, chl->channel);
5143 silc_hash_table_list_reset(&htl);
5147 /* Lookups route to the client indicated by the `id_data'. The connection
5148 object and internal data object is returned. Returns NULL if route
5149 could not be found to the client. If the `client_id' is specified then
5150 it is used and the `id_data' is ignored. */
5152 SilcSocketConnection
5153 silc_server_get_client_route(SilcServer server,
5154 unsigned char *id_data,
5156 SilcClientID *client_id,
5157 SilcIDListData *idata,
5158 SilcClientEntry *client_entry)
5161 SilcClientEntry client;
5163 SILC_LOG_DEBUG(("Start"));
5166 *client_entry = NULL;
5168 /* Decode destination Client ID */
5170 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
5172 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
5176 id = silc_id_dup(client_id, SILC_ID_CLIENT);
5179 /* If the destination belongs to our server we don't have to route
5180 the packet anywhere but to send it to the local destination. */
5181 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
5185 /* If we are router and the client has router then the client is in
5186 our cell but not directly connected to us. */
5187 if (server->server_type == SILC_ROUTER && client->router) {
5188 /* We are of course in this case the client's router thus the route
5189 to the client is the server who owns the client. So, we will send
5190 the packet to that server. */
5192 *idata = (SilcIDListData)client->router;
5193 return client->router->connection;
5196 /* Seems that client really is directly connected to us */
5198 *idata = (SilcIDListData)client;
5200 *client_entry = client;
5201 return client->connection;
5204 /* Destination belongs to someone not in this server. If we are normal
5205 server our action is to send the packet to our router. */
5206 if (server->server_type != SILC_ROUTER && !server->standalone) {
5209 *idata = (SilcIDListData)server->router;
5210 return SILC_PRIMARY_ROUTE(server);
5213 /* We are router and we will perform route lookup for the destination
5214 and send the packet to fastest route. */
5215 if (server->server_type == SILC_ROUTER && !server->standalone) {
5216 /* Check first that the ID is valid */
5217 client = silc_idlist_find_client_by_id(server->global_list, id,
5220 SilcSocketConnection dst_sock;
5222 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
5226 *idata = (SilcIDListData)dst_sock->user_data;
5235 /* Encodes and returns channel list of channels the `client' has joined.
5236 Secret channels are not put to the list. */
5238 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
5239 SilcClientEntry client,
5242 SilcBuffer *user_mode_list)
5244 SilcBuffer buffer = NULL;
5245 SilcChannelEntry channel;
5246 SilcChannelClientEntry chl;
5247 SilcHashTableList htl;
5250 SilcUInt16 name_len;
5254 *user_mode_list = NULL;
5256 silc_hash_table_list(client->channels, &htl);
5257 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5258 channel = chl->channel;
5260 if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
5262 if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
5265 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
5266 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
5267 name_len = strlen(channel->channel_name);
5269 len = 4 + name_len + id_len + 4;
5270 buffer = silc_buffer_realloc(buffer,
5271 (buffer ? buffer->truelen + len : len));
5272 silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
5273 silc_buffer_format(buffer,
5274 SILC_STR_UI_SHORT(name_len),
5275 SILC_STR_UI_XNSTRING(channel->channel_name,
5277 SILC_STR_UI_SHORT(id_len),
5278 SILC_STR_UI_XNSTRING(cid, id_len),
5279 SILC_STR_UI_INT(chl->channel->mode),
5281 silc_buffer_pull(buffer, len);
5284 if (user_mode_list) {
5285 *user_mode_list = silc_buffer_realloc(*user_mode_list,
5287 (*user_mode_list)->truelen + 4 :
5289 silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
5290 (*user_mode_list)->data));
5291 SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
5292 silc_buffer_pull(*user_mode_list, 4);
5295 silc_hash_table_list_reset(&htl);
5298 silc_buffer_push(buffer, buffer->data - buffer->head);
5299 if (user_mode_list && *user_mode_list)
5300 silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
5301 (*user_mode_list)->head));
5306 /* Timeout callback for unsuccessful rekey. The rekey did not go through
5309 SILC_TASK_CALLBACK(silc_server_rekey_timeout)
5311 SilcServerRekeyInternalContext *ctx = context;
5312 SilcServer server = app_context;
5313 SilcSocketConnection sock = ctx->sock;
5315 SILC_LOG_DEBUG(("Timeout occurred in rekey protocol with %s:%d [%s]",
5316 sock->hostname, sock->port,
5317 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5318 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5319 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5322 SILC_LOG_WARNING(("Timeout occurred in rekey protocol with %s:%d [%s]",
5323 sock->hostname, sock->port,
5324 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5325 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5326 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5329 if (sock->protocol) {
5330 silc_protocol_cancel(sock->protocol, server->schedule);
5331 silc_protocol_free(sock->protocol);
5332 sock->protocol = NULL;
5335 silc_packet_context_free(ctx->packet);
5337 silc_ske_free(ctx->ske);
5338 silc_socket_free(sock);
5342 /* A timeout callback for the re-key. We will be the initiator of the
5345 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_callback)
5347 SilcServer server = app_context;
5348 SilcSocketConnection sock = (SilcSocketConnection)context;
5349 SilcIDListData idata = (SilcIDListData)sock->user_data;
5350 SilcProtocol protocol;
5351 SilcServerRekeyInternalContext *proto_ctx;
5353 /* Do not execute rekey with disabled connections, as it would not
5354 go through anyway. */
5355 if (idata->status & SILC_IDLIST_STATUS_DISABLED)
5358 /* If rekey protocol is active already wait for it to finish */
5359 if (sock->protocol && sock->protocol->protocol &&
5360 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)
5363 /* If any other protocol is active do not start this protocol yet. */
5364 if (sock->protocol) {
5365 SILC_LOG_DEBUG(("Waiting for other protocol to finish before rekeying"));
5366 silc_schedule_task_add(server->schedule, sock->sock,
5367 silc_server_rekey_callback,
5368 sock, 60, 0, SILC_TASK_TIMEOUT,
5369 SILC_TASK_PRI_NORMAL);
5373 SILC_LOG_DEBUG(("Executing rekey protocol with %s:%d [%s]",
5374 sock->hostname, sock->port,
5375 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5376 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5377 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5380 /* Allocate internal protocol context. This is sent as context
5382 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
5383 proto_ctx->server = (void *)server;
5384 proto_ctx->sock = silc_socket_dup(sock);
5385 proto_ctx->responder = FALSE;
5386 proto_ctx->pfs = idata->rekey->pfs;
5388 /* Perform rekey protocol. Will call the final callback after the
5389 protocol is over. */
5390 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
5391 &protocol, proto_ctx, silc_server_rekey_final);
5392 sock->protocol = protocol;
5394 /* Register timeout callback in case the rekey does not go through. */
5395 proto_ctx->timeout_task =
5396 silc_schedule_task_add(server->schedule, sock->sock,
5397 silc_server_rekey_timeout,
5399 server->config->key_exchange_timeout, 0,
5403 /* Run the protocol */
5404 silc_protocol_execute(protocol, server->schedule, 0, 0);
5407 /* The final callback for the REKEY protocol. This will actually take the
5408 new key material into use. */
5410 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
5412 SilcProtocol protocol = (SilcProtocol)context;
5413 SilcServerRekeyInternalContext *ctx =
5414 (SilcServerRekeyInternalContext *)protocol->context;
5415 SilcServer server = (SilcServer)ctx->server;
5416 SilcSocketConnection sock = ctx->sock;
5417 SilcIDListData idata = (SilcIDListData)sock->user_data;
5419 if (ctx->timeout_task)
5420 silc_schedule_task_del(server->schedule, ctx->timeout_task);
5422 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
5423 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
5424 /* Error occured during protocol */
5425 SILC_LOG_ERROR(("Error occurred during rekey protocol with "
5426 "%s (%s)", sock->hostname, sock->ip));
5427 silc_protocol_cancel(protocol, server->schedule);
5428 silc_protocol_free(protocol);
5429 sock->protocol = NULL;
5431 silc_packet_context_free(ctx->packet);
5433 silc_ske_free(ctx->ske);
5434 silc_socket_free(sock);
5436 silc_server_disconnect_remote(server, sock,
5437 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
5440 if (sock->type != SILC_SOCKET_TYPE_CLIENT)
5441 silc_server_create_connections(server);
5445 SILC_LOG_DEBUG(("Rekey protocol completed with %s:%d [%s]",
5446 sock->hostname, sock->port,
5447 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5448 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5449 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5452 /* Purge the outgoing data queue to assure that all rekey packets really
5453 go to the network before we quit the protocol. */
5454 silc_server_packet_queue_purge(server, sock);
5456 /* Re-register re-key timeout */
5457 if (ctx->responder == FALSE)
5458 silc_schedule_task_add(server->schedule, sock->sock,
5459 silc_server_rekey_callback,
5460 sock, idata->rekey->timeout, 0,
5461 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
5464 silc_protocol_free(protocol);
5465 sock->protocol = NULL;
5467 silc_packet_context_free(ctx->packet);
5469 silc_ske_free(ctx->ske);
5470 silc_socket_free(sock);
5474 /* Task callback used to retrieve network statistical information from
5475 router server once in a while. */
5477 SILC_TASK_CALLBACK(silc_server_get_stats)
5479 SilcServer server = (SilcServer)context;
5480 SilcBuffer idp, packet;
5482 if (!server->standalone) {
5483 SILC_LOG_DEBUG(("Retrieving stats from router"));
5484 idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
5485 packet = silc_command_payload_encode_va(SILC_COMMAND_STATS,
5486 ++server->cmd_ident, 1,
5487 1, idp->data, idp->len);
5488 silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
5489 SILC_PACKET_COMMAND, 0, packet->data,
5490 packet->len, FALSE);
5491 silc_buffer_free(packet);
5492 silc_buffer_free(idp);
5495 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
5496 server, 120, 0, SILC_TASK_TIMEOUT,