5 Author: Pekka Riikonen <priikone@silcnet.org>
7 Copyright (C) 1997 - 2002 Pekka Riikonen
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; version 2 of the License.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
20 * This is the actual SILC server than handles everything relating to
21 * servicing the SILC connections. This is also a SILC router as a router
22 * is also normal server.
26 #include "serverincludes.h"
27 #include "server_internal.h"
29 /* Static prototypes */
30 SILC_TASK_CALLBACK(silc_server_rehash_close_connection);
31 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry);
32 SILC_TASK_CALLBACK(silc_server_connect_router);
33 SILC_TASK_CALLBACK(silc_server_connect_to_router);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
35 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
38 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
39 SILC_TASK_CALLBACK(silc_server_packet_process);
40 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
41 SILC_TASK_CALLBACK(silc_server_close_connection_final);
42 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout);
43 SILC_TASK_CALLBACK(silc_server_timeout_remote);
44 SILC_TASK_CALLBACK(silc_server_channel_key_rekey);
45 SILC_TASK_CALLBACK(silc_server_failure_callback);
46 SILC_TASK_CALLBACK(silc_server_get_stats);
48 /* Allocates a new SILC server object. This has to be done before the server
49 can be used. After allocation one must call silc_server_init to initialize
50 the server. The new allocated server object is returned to the new_server
53 int silc_server_alloc(SilcServer *new_server)
57 SILC_LOG_DEBUG(("Allocating new server object"));
59 server = silc_calloc(1, sizeof(*server));
60 server->server_type = SILC_SERVER;
61 server->standalone = TRUE;
62 server->local_list = silc_calloc(1, sizeof(*server->local_list));
63 server->global_list = silc_calloc(1, sizeof(*server->global_list));
64 server->pending_commands = silc_dlist_init();
66 server->sim = silc_dlist_init();
74 /* Free's the SILC server object. This is called at the very end before
77 void silc_server_free(SilcServer server)
80 SilcIDCacheEntry cache;
89 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
90 silc_dlist_del(server->sim, sim);
93 silc_dlist_uninit(server->sim);
97 silc_server_backup_free(server);
98 silc_server_config_unref(&server->config_ref);
100 silc_rng_free(server->rng);
102 silc_pkcs_free(server->pkcs);
103 if (server->public_key)
104 silc_pkcs_public_key_free(server->public_key);
105 if (server->private_key)
106 silc_pkcs_private_key_free(server->private_key);
107 if (server->pending_commands)
108 silc_dlist_uninit(server->pending_commands);
109 if (server->id_entry)
110 silc_idlist_del_server(server->local_list, server->id_entry);
112 /* Delete all channels */
114 if (silc_idcache_get_all(server->local_list->channels, &list) &&
115 silc_idcache_list_first(list, &cache)) {
116 silc_idlist_del_channel(server->local_list, cache->context);
117 while (silc_idcache_list_next(list, &cache))
118 silc_idlist_del_channel(server->local_list, cache->context);
121 silc_idcache_list_free(list);
123 if (silc_idcache_get_all(server->global_list->channels, &list) &&
124 silc_idcache_list_first(list, &cache)) {
125 silc_idlist_del_channel(server->global_list, cache->context);
126 while (silc_idcache_list_next(list, &cache))
127 silc_idlist_del_channel(server->global_list, cache->context);
130 silc_idcache_list_free(list);
132 /* Delete all clients */
134 if (silc_idcache_get_all(server->local_list->clients, &list) &&
135 silc_idcache_list_first(list, &cache)) {
136 silc_idlist_del_client(server->local_list, cache->context);
137 while (silc_idcache_list_next(list, &cache))
138 silc_idlist_del_client(server->local_list, cache->context);
141 silc_idcache_list_free(list);
143 if (silc_idcache_get_all(server->global_list->clients, &list) &&
144 silc_idcache_list_first(list, &cache)) {
145 silc_idlist_del_client(server->global_list, cache->context);
146 while (silc_idcache_list_next(list, &cache))
147 silc_idlist_del_client(server->global_list, cache->context);
150 silc_idcache_list_free(list);
152 /* Delete all servers */
154 if (silc_idcache_get_all(server->local_list->servers, &list) &&
155 silc_idcache_list_first(list, &cache)) {
156 silc_idlist_del_server(server->local_list, cache->context);
157 while (silc_idcache_list_next(list, &cache))
158 silc_idlist_del_server(server->local_list, cache->context);
161 silc_idcache_list_free(list);
163 if (silc_idcache_get_all(server->global_list->servers, &list) &&
164 silc_idcache_list_first(list, &cache)) {
165 silc_idlist_del_server(server->global_list, cache->context);
166 while (silc_idcache_list_next(list, &cache))
167 silc_idlist_del_server(server->global_list, cache->context);
170 silc_idcache_list_free(list);
172 silc_idcache_free(server->local_list->clients);
173 silc_idcache_free(server->local_list->servers);
174 silc_idcache_free(server->local_list->channels);
175 silc_idcache_free(server->global_list->clients);
176 silc_idcache_free(server->global_list->servers);
177 silc_idcache_free(server->global_list->channels);
178 silc_hash_table_free(server->watcher_list);
180 silc_hash_free(server->md5hash);
181 silc_hash_free(server->sha1hash);
182 silc_hmac_unregister_all();
183 silc_hash_unregister_all();
184 silc_cipher_unregister_all();
185 silc_pkcs_unregister_all();
187 silc_free(server->local_list);
188 silc_free(server->global_list);
189 silc_free(server->server_name);
190 silc_free(server->id_string);
191 silc_free(server->purge_i);
192 silc_free(server->purge_g);
196 /* Creates a new server listener. */
198 static bool silc_server_listen(SilcServer server, const char *server_ip,
199 SilcUInt16 port, int *sock)
201 *sock = silc_net_create_server(port, server_ip);
203 SILC_SERVER_LOG_ERROR(("Could not create server listener: %s on %hu",
210 /* Adds a secondary listener. */
212 bool silc_server_init_secondary(SilcServer server)
214 int sock = 0, sock_list[server->config->param.connections_max];
215 SilcSocketConnection newsocket = NULL;
216 SilcServerConfigServerInfoInterface *interface;
218 for (interface = server->config->server_info->secondary; interface;
219 interface = interface->next, sock++) {
221 if (!silc_server_listen(server,
222 interface->server_ip, interface->port, &sock_list[sock]))
225 /* Set socket to non-blocking mode */
226 silc_net_set_socket_nonblock(sock_list[sock]);
228 /* Add ourselves also to the socket table. The entry allocated above
229 is sent as argument for fast referencing in the future. */
230 silc_socket_alloc(sock_list[sock],
231 SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
232 server->sockets[sock_list[sock]] = newsocket;
233 SILC_SET_LISTENER(newsocket);
235 /* Perform name and address lookups to resolve the listenning address
237 if (!silc_net_check_local_by_sock(sock_list[sock], &newsocket->hostname,
239 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
241 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
242 newsocket->hostname ? newsocket->hostname :
243 newsocket->ip ? newsocket->ip : ""));
244 server->stat.conn_failures++;
247 if (!newsocket->hostname)
248 newsocket->hostname = strdup(newsocket->ip);
250 newsocket->port = silc_net_get_local_port(sock);
252 newsocket->user_data = (void *)server->id_entry;
253 silc_schedule_task_add(server->schedule, sock_list[sock],
254 silc_server_accept_new_connection,
255 (void *)server, 0, 0,
257 SILC_TASK_PRI_NORMAL);
263 do silc_net_close_server(sock_list[sock--]); while (sock >= 0);
267 /* Initializes the entire SILC server. This is called always before running
268 the server. This is called only once at the initialization of the program.
269 This binds the server to its listenning port. After this function returns
270 one should call silc_server_run to start the server. This returns TRUE
271 when everything is ok to run the server. Configuration file must be
272 read and parsed before calling this. */
274 bool silc_server_init(SilcServer server)
278 SilcServerEntry id_entry;
279 SilcIDListPurge purge;
280 SilcSocketConnection newsocket = NULL;
282 SILC_LOG_DEBUG(("Initializing server"));
284 server->starttime = time(NULL);
286 /* Take config object for us */
287 silc_server_config_ref(&server->config_ref, server->config,
290 /* Steal public and private key from the config object */
291 server->public_key = server->config->server_info->public_key;
292 server->private_key = server->config->server_info->private_key;
293 server->config->server_info->public_key = NULL;
294 server->config->server_info->private_key = NULL;
296 /* Register all configured ciphers, PKCS and hash functions. */
297 if (!silc_server_config_register_ciphers(server))
298 silc_cipher_register_default();
299 if (!silc_server_config_register_pkcs(server))
300 silc_pkcs_register_default();
301 if (!silc_server_config_register_hashfuncs(server))
302 silc_hash_register_default();
303 if (!silc_server_config_register_hmacs(server))
304 silc_hmac_register_default();
306 /* Initialize random number generator for the server. */
307 server->rng = silc_rng_alloc();
308 silc_rng_init(server->rng);
309 silc_rng_global_init(server->rng);
311 /* Initialize hash functions for server to use */
312 silc_hash_alloc("md5", &server->md5hash);
313 silc_hash_alloc("sha1", &server->sha1hash);
315 /* Allocate PKCS context for local public and private keys */
316 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
318 silc_pkcs_public_key_set(server->pkcs, server->public_key);
319 silc_pkcs_private_key_set(server->pkcs, server->private_key);
321 /* Initialize the scheduler */
322 server->schedule = silc_schedule_init(server->config->param.connections_max,
324 if (!server->schedule)
327 /* First, register log files configuration for error output */
328 silc_server_config_setlogfiles(server);
330 /* Initialize ID caches */
331 server->local_list->clients =
332 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
333 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
334 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
336 /* These are allocated for normal server as well as these hold some
337 global information that the server has fetched from its router. For
338 router these are used as they are supposed to be used on router. */
339 server->global_list->clients =
340 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
341 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
342 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
344 /* Init watcher list */
345 server->watcher_list =
346 silc_hash_table_alloc(1, silc_hash_client_id_hash, NULL,
347 silc_hash_data_compare, (void *)CLIENTID_HASH_LEN,
349 if (!server->watcher_list)
352 /* Create a listening server */
353 if (!silc_server_listen(server,
354 server->config->server_info->primary == NULL ? NULL :
355 server->config->server_info->primary->server_ip,
356 server->config->server_info->primary == NULL ? 0 :
357 server->config->server_info->primary->port,
361 /* Set socket to non-blocking mode */
362 silc_net_set_socket_nonblock(sock);
365 /* Allocate the entire socket list that is used in server. Eventually
366 all connections will have entry in this table (it is a table of
367 pointers to the actual object that is allocated individually
369 server->sockets = silc_calloc(server->config->param.connections_max,
370 sizeof(*server->sockets));
371 if (!server->sockets)
374 /* Add ourselves also to the socket table. The entry allocated above
375 is sent as argument for fast referencing in the future. */
376 silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
377 server->sockets[sock] = newsocket;
378 SILC_SET_LISTENER(newsocket);
380 /* Perform name and address lookups to resolve the listenning address
382 if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
384 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
386 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
387 newsocket->hostname ? newsocket->hostname :
388 newsocket->ip ? newsocket->ip : ""));
389 server->stat.conn_failures++;
392 if (!newsocket->hostname)
393 newsocket->hostname = strdup(newsocket->ip);
395 newsocket->port = silc_net_get_local_port(sock);
397 /* Create a Server ID for the server. */
398 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
403 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
404 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
405 server->server_name = server->config->server_info->server_name;
406 server->config->server_info->server_name = NULL;
408 /* Add ourselves to the server list. We don't have a router yet
409 beacuse we haven't established a route yet. It will be done later.
410 For now, NULL is sent as router. This allocates new entry to
413 silc_idlist_add_server(server->local_list, strdup(server->server_name),
414 server->server_type, server->id, NULL, NULL);
416 SILC_LOG_ERROR(("Could not add ourselves to cache"));
419 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
421 /* Put the allocated socket pointer also to the entry allocated above
422 for fast back-referencing to the socket list. */
423 newsocket->user_data = (void *)id_entry;
424 id_entry->connection = (void *)newsocket;
425 server->id_entry = id_entry;
427 /* Register protocols */
428 silc_server_protocols_register();
430 /* Add the first task to the scheduler. This is task that is executed by
431 timeout. It expires as soon as the caller calls silc_server_run. This
432 task performs authentication protocol and key exchange with our
434 silc_schedule_task_add(server->schedule, 0,
435 silc_server_connect_to_router,
436 (void *)server, 0, 1,
438 SILC_TASK_PRI_NORMAL);
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 /* Go through all configured routers after rehash */
700 silc_schedule_task_add(server->schedule, 0,
701 silc_server_connect_to_router,
702 (void *)server, 0, 1,
704 SILC_TASK_PRI_NORMAL);
706 /* Check whether our router status has changed */
707 if (newconfig->servers) {
708 SilcServerConfigServer *ptr = newconfig->servers;
710 server->server_type = SILC_ROUTER;
712 if (ptr->backup_router) {
713 server->server_type = SILC_BACKUP_ROUTER;
714 server->backup_router = TRUE;
715 server->id_entry->server_type = SILC_BACKUP_ROUTER;
722 /* Our old config is gone now. We'll unreference our reference made in
723 silc_server_init and then destroy it since we are destroying it
724 underneath the application (layer which called silc_server_init). */
725 silc_server_config_unref(&server->config_ref);
726 silc_server_config_destroy(server->config);
728 /* Take new config context */
729 server->config = newconfig;
730 silc_server_config_ref(&server->config_ref, server->config, server->config);
732 SILC_LOG_DEBUG(("Server rehashed"));
737 /* The heart of the server. This runs the scheduler thus runs the server.
738 When this returns the server has been stopped and the program will
741 void silc_server_run(SilcServer server)
743 SILC_LOG_INFO(("SILC Server started"));
745 /* Start the scheduler, the heart of the SILC server. When this returns
746 the program will be terminated. */
747 silc_schedule(server->schedule);
750 /* Stops the SILC server. This function is used to shutdown the server.
751 This is usually called after the scheduler has returned. After stopping
752 the server one should call silc_server_free. */
754 void silc_server_stop(SilcServer server)
756 SILC_LOG_INFO(("SILC Server shutting down"));
758 if (server->schedule) {
761 server->server_shutdown = TRUE;
763 /* Close all connections */
764 for (i = 0; i < server->config->param.connections_max; i++) {
765 if (!server->sockets[i])
767 if (!SILC_IS_LISTENER(server->sockets[i])) {
768 SilcSocketConnection sock = server->sockets[i];
769 SilcIDListData idata = sock->user_data;
772 idata->status &= ~SILC_IDLIST_STATUS_DISABLED;
774 silc_schedule_task_del_by_context(server->schedule,
776 silc_server_disconnect_remote(server, server->sockets[i],
778 "Server is shutting down");
780 silc_server_free_sock_user_data(server, sock,
781 "Server is shutting down");
782 silc_socket_free(sock);
784 silc_socket_free(server->sockets[i]);
785 server->sockets[i] = NULL;
789 /* We are not connected to network anymore */
790 server->standalone = TRUE;
792 silc_schedule_stop(server->schedule);
793 silc_schedule_uninit(server->schedule);
794 server->schedule = NULL;
796 silc_free(server->sockets);
797 server->sockets = NULL;
800 silc_server_protocols_unregister();
802 SILC_LOG_DEBUG(("Server stopped"));
805 /* Function that is called when the network connection to a router has
806 been established. This will continue with the key exchange protocol
807 with the remote router. */
809 void silc_server_start_key_exchange(SilcServer server,
810 SilcServerConnection sconn,
813 SilcSocketConnection newsocket;
814 SilcProtocol protocol;
815 SilcServerKEInternalContext *proto_ctx;
816 SilcServerConfigRouter *conn =
817 (SilcServerConfigRouter *) sconn->conn.ref_ptr;
820 /* Cancel any possible retry timeouts */
821 silc_schedule_task_del_by_callback(server->schedule,
822 silc_server_connect_to_router_retry);
824 /* Set socket options */
825 silc_net_set_socket_nonblock(sock);
826 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
828 /* Create socket connection for the connection. Even though we
829 know that we are connecting to a router we will mark the socket
830 to be unknown connection until we have executed authentication
832 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
833 server->sockets[sock] = newsocket;
834 newsocket->hostname = strdup(sconn->remote_host);
835 newsocket->ip = strdup(sconn->remote_host);
836 newsocket->port = sconn->remote_port;
837 sconn->sock = newsocket;
839 /* Allocate internal protocol context. This is sent as context
841 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
842 proto_ctx->server = (void *)server;
843 proto_ctx->context = (void *)sconn;
844 proto_ctx->sock = newsocket;
845 proto_ctx->rng = server->rng;
846 proto_ctx->responder = FALSE;
848 /* Set Key Exchange flags from configuration, but fall back to global
850 SILC_GET_SKE_FLAGS(conn, proto_ctx);
851 if (server->config->param.key_exchange_pfs)
852 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
854 /* Perform key exchange protocol. silc_server_connect_to_router_second
855 will be called after the protocol is finished. */
856 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
857 &protocol, proto_ctx,
858 silc_server_connect_to_router_second);
859 newsocket->protocol = protocol;
861 /* Register a timeout task that will be executed if the protocol
862 is not executed within set limit. */
863 proto_ctx->timeout_task =
864 silc_schedule_task_add(server->schedule, sock,
865 silc_server_timeout_remote,
866 server, server->config->key_exchange_timeout, 0,
870 /* Register the connection for network input and output. This sets
871 that scheduler will listen for incoming packets for this connection
872 and sets that outgoing packets may be sent to this connection as
873 well. However, this doesn't set the scheduler for outgoing traffic,
874 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
875 later when outgoing data is available. */
876 context = (void *)server;
877 SILC_REGISTER_CONNECTION_FOR_IO(sock);
879 /* Run the protocol */
880 silc_protocol_execute(protocol, server->schedule, 0, 0);
883 /* Timeout callback that will be called to retry connecting to remote
884 router. This is used by both normal and router server. This will wait
885 before retrying the connecting. The timeout is generated by exponential
886 backoff algorithm. */
888 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
890 SilcServer server = app_context;
891 SilcServerConnection sconn = (SilcServerConnection)context;
892 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
893 SilcServerConfigConnParams *param =
894 (conn->param ? conn->param : &server->config->param);
896 /* Don't retry if we are shutting down. */
897 if (server->server_shutdown) {
898 silc_server_config_unref(&sconn->conn);
899 silc_free(sconn->remote_host);
900 silc_free(sconn->backup_replace_ip);
905 SILC_LOG_INFO(("Retrying connecting to a router"));
907 /* Calculate next timeout */
908 if (sconn->retry_count >= 1) {
909 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
910 if (sconn->retry_timeout > param->reconnect_interval_max)
911 sconn->retry_timeout = param->reconnect_interval_max;
913 sconn->retry_timeout = param->reconnect_interval;
915 sconn->retry_count++;
916 sconn->retry_timeout = sconn->retry_timeout +
917 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
919 /* If we've reached max retry count, give up. */
920 if ((sconn->retry_count > param->reconnect_count) &&
921 !param->reconnect_keep_trying) {
922 SILC_LOG_ERROR(("Could not connect to router, giving up"));
923 silc_server_config_unref(&sconn->conn);
924 silc_free(sconn->remote_host);
925 silc_free(sconn->backup_replace_ip);
930 SILC_LOG_DEBUG(("Retrying connecting to a router in %d seconds",
931 sconn->retry_timeout));
933 /* We will lookup a fresh pointer later */
934 silc_server_config_unref(&sconn->conn);
936 /* Wait one before retrying */
937 silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
938 context, sconn->retry_timeout, 0,
939 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
942 /* Generic routine to use connect to a router. */
944 SILC_TASK_CALLBACK(silc_server_connect_router)
946 SilcServer server = app_context;
947 SilcServerConnection sconn = (SilcServerConnection)context;
948 SilcServerConfigRouter *rconn;
951 /* Don't connect if we are shutting down. */
952 if (server->server_shutdown) {
953 silc_free(sconn->remote_host);
954 silc_free(sconn->backup_replace_ip);
959 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
960 (sconn->backup ? "backup router" : "router"),
961 sconn->remote_host, sconn->remote_port));
963 server->router_connect = time(NULL);
964 rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
967 SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
968 (sconn->backup ? "backup router" : "router"),
969 sconn->remote_host, sconn->remote_port));
970 silc_free(sconn->remote_host);
971 silc_free(sconn->backup_replace_ip);
975 silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
977 /* Connect to remote host */
978 sock = silc_net_create_connection(
979 (!server->config->server_info->primary ? NULL :
980 server->config->server_info->primary->server_ip),
981 sconn->remote_port, sconn->remote_host);
983 SILC_LOG_ERROR(("Could not connect to router %s:%d",
984 sconn->remote_host, sconn->remote_port));
985 if (!sconn->no_reconnect)
986 silc_schedule_task_add(server->schedule, 0,
987 silc_server_connect_to_router_retry,
988 context, 0, 1, SILC_TASK_TIMEOUT,
989 SILC_TASK_PRI_NORMAL);
991 silc_server_config_unref(&sconn->conn);
992 silc_free(sconn->remote_host);
993 silc_free(sconn->backup_replace_ip);
999 /* Continue with key exchange protocol */
1000 silc_server_start_key_exchange(server, sconn, sock);
1003 /* This function connects to our primary router or if we are a router this
1004 establishes all our primary routes. This is called at the start of the
1005 server to do authentication and key exchange with our router - called
1008 SILC_TASK_CALLBACK(silc_server_connect_to_router)
1010 SilcServer server = (SilcServer)context;
1011 SilcServerConnection sconn;
1012 SilcServerConfigRouter *ptr;
1014 /* Don't connect if we are shutting down. */
1015 if (server->server_shutdown)
1018 SILC_LOG_DEBUG(("We are %s",
1019 (server->server_type == SILC_SERVER ?
1020 "normal server" : server->server_type == SILC_ROUTER ?
1021 "router" : "backup router/normal server")));
1023 if (!server->config->routers) {
1024 /* There wasn't a configured router, we will continue but we don't
1025 have a connection to outside world. We will be standalone server. */
1026 SILC_LOG_DEBUG(("No router(s), we are standalone"));
1027 server->standalone = TRUE;
1031 /* Cancel any possible retry timeouts */
1032 silc_schedule_task_del_by_callback(server->schedule,
1033 silc_server_connect_router);
1034 silc_schedule_task_del_by_callback(server->schedule,
1035 silc_server_connect_to_router_retry);
1037 /* Create the connections to all our routes */
1038 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
1040 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
1041 ptr->backup_router ? "Backup router" : "Router",
1042 ptr->initiator ? "Initiator" : "Responder",
1043 ptr->host, ptr->port));
1045 if (server->server_type == SILC_ROUTER && ptr->backup_router &&
1046 ptr->initiator == FALSE && !server->backup_router &&
1047 !silc_server_config_get_backup_router(server))
1048 server->wait_backup = TRUE;
1050 if (ptr->initiator) {
1051 /* Check whether we are connected to this host already */
1052 if (silc_server_num_sockets_by_remote(server,
1053 silc_net_is_ip(ptr->host) ?
1055 silc_net_is_ip(ptr->host) ?
1056 NULL : ptr->host, ptr->port,
1057 SILC_SOCKET_TYPE_ROUTER)) {
1058 SILC_LOG_DEBUG(("We are already connected to this router"));
1062 /* Allocate connection object for hold connection specific stuff. */
1063 sconn = silc_calloc(1, sizeof(*sconn));
1064 sconn->remote_host = strdup(ptr->host);
1065 sconn->remote_port = ptr->port;
1066 sconn->backup = ptr->backup_router;
1067 if (sconn->backup) {
1068 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
1069 sconn->backup_replace_port = ptr->backup_replace_port;
1072 if (!server->router_conn && !sconn->backup)
1073 server->router_conn = sconn;
1075 silc_schedule_task_add(server->schedule, 0,
1076 silc_server_connect_router,
1077 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
1078 SILC_TASK_PRI_NORMAL);
1083 /* Second part of connecting to router(s). Key exchange protocol has been
1084 executed and now we will execute authentication protocol. */
1086 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
1088 SilcProtocol protocol = (SilcProtocol)context;
1089 SilcServerKEInternalContext *ctx =
1090 (SilcServerKEInternalContext *)protocol->context;
1091 SilcServer server = (SilcServer)ctx->server;
1092 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1093 SilcSocketConnection sock = ctx->sock;
1094 SilcServerConnAuthInternalContext *proto_ctx;
1095 SilcServerConfigRouter *conn = NULL;
1097 SILC_LOG_DEBUG(("Start"));
1099 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1100 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1101 /* Error occured during protocol */
1102 silc_protocol_free(protocol);
1103 sock->protocol = NULL;
1104 silc_ske_free_key_material(ctx->keymat);
1106 silc_packet_context_free(ctx->packet);
1108 silc_ske_free(ctx->ske);
1109 silc_free(ctx->dest_id);
1111 silc_schedule_task_del_by_callback(server->schedule,
1112 silc_server_failure_callback);
1113 silc_server_disconnect_remote(server, sock,
1114 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1116 /* Try reconnecting if configuration wants it */
1117 if (!sconn->no_reconnect) {
1118 silc_schedule_task_add(server->schedule, 0,
1119 silc_server_connect_to_router_retry,
1120 sconn, 0, 1, SILC_TASK_TIMEOUT,
1121 SILC_TASK_PRI_NORMAL);
1125 /* Call completion to indicate error */
1126 if (sconn->callback)
1127 (*sconn->callback)(server, NULL, sconn->callback_context);
1129 silc_server_config_unref(&sconn->conn);
1130 silc_free(sconn->remote_host);
1131 silc_free(sconn->backup_replace_ip);
1136 /* We now have the key material as the result of the key exchange
1137 protocol. Take the key material into use. Free the raw key material
1138 as soon as we've set them into use. */
1139 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1140 ctx->sock, ctx->keymat,
1141 ctx->ske->prop->cipher,
1142 ctx->ske->prop->pkcs,
1143 ctx->ske->prop->hash,
1144 ctx->ske->prop->hmac,
1145 ctx->ske->prop->group,
1147 silc_protocol_free(protocol);
1148 sock->protocol = NULL;
1149 silc_ske_free_key_material(ctx->keymat);
1151 silc_packet_context_free(ctx->packet);
1153 silc_ske_free(ctx->ske);
1154 silc_free(ctx->dest_id);
1156 silc_schedule_task_del_by_callback(server->schedule,
1157 silc_server_failure_callback);
1158 silc_server_disconnect_remote(server, sock,
1159 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1161 /* Try reconnecting if configuration wants it */
1162 if (!sconn->no_reconnect) {
1163 silc_schedule_task_add(server->schedule, 0,
1164 silc_server_connect_to_router_retry,
1165 sconn, 0, 1, SILC_TASK_TIMEOUT,
1166 SILC_TASK_PRI_NORMAL);
1170 /* Call completion to indicate error */
1171 if (sconn->callback)
1172 (*sconn->callback)(server, NULL, sconn->callback_context);
1174 silc_server_config_unref(&sconn->conn);
1175 silc_free(sconn->remote_host);
1176 silc_free(sconn->backup_replace_ip);
1180 silc_ske_free_key_material(ctx->keymat);
1182 /* Allocate internal context for the authentication protocol. This
1183 is sent as context for the protocol. */
1184 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1185 proto_ctx->server = (void *)server;
1186 proto_ctx->context = (void *)sconn;
1187 proto_ctx->sock = sock;
1188 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1189 proto_ctx->dest_id_type = ctx->dest_id_type;
1190 proto_ctx->dest_id = ctx->dest_id;
1192 /* Resolve the authentication method used in this connection. Check if
1193 we find a match from user configured connections */
1194 if (!sconn->conn.ref_ptr)
1195 conn = silc_server_config_find_router_conn(server, sock->hostname,
1198 conn = sconn->conn.ref_ptr;
1201 /* Match found. Use the configured authentication method. Take only
1202 the passphrase, since for public key auth we automatically use
1203 our local key pair. */
1204 if (conn->passphrase) {
1205 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
1206 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1208 proto_ctx->auth_data = strdup(conn->passphrase);
1209 proto_ctx->auth_data_len = strlen(conn->passphrase);
1210 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
1212 } else if (conn->publickeys) {
1213 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1215 proto_ctx->auth_meth = SILC_AUTH_NONE;
1218 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
1219 sock->hostname, sock->ip, sock->port));
1220 silc_protocol_free(protocol);
1221 sock->protocol = NULL;
1223 silc_packet_context_free(ctx->packet);
1225 silc_ske_free(ctx->ske);
1226 silc_free(ctx->dest_id);
1228 silc_server_config_unref(&sconn->conn);
1229 silc_free(sconn->remote_host);
1230 silc_free(sconn->backup_replace_ip);
1232 silc_schedule_task_del_by_callback(server->schedule,
1233 silc_server_failure_callback);
1234 silc_server_disconnect_remote(server, sock,
1235 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1239 /* Free old protocol as it is finished now */
1240 silc_protocol_free(protocol);
1242 silc_packet_context_free(ctx->packet);
1244 sock->protocol = NULL;
1246 /* Allocate the authentication protocol. This is allocated here
1247 but we won't start it yet. We will be receiving party of this
1248 protocol thus we will wait that connecting party will make
1249 their first move. */
1250 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1251 &sock->protocol, proto_ctx,
1252 silc_server_connect_to_router_final);
1254 /* Register timeout task. If the protocol is not executed inside
1255 this timelimit the connection will be terminated. */
1256 proto_ctx->timeout_task =
1257 silc_schedule_task_add(server->schedule, sock->sock,
1258 silc_server_timeout_remote,
1260 server->config->conn_auth_timeout, 0,
1264 /* Run the protocol */
1265 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1268 /* Finalizes the connection to router. Registers a server task to the
1269 queue so that we can accept new connections. */
1271 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
1273 SilcProtocol protocol = (SilcProtocol)context;
1274 SilcServerConnAuthInternalContext *ctx =
1275 (SilcServerConnAuthInternalContext *)protocol->context;
1276 SilcServer server = (SilcServer)ctx->server;
1277 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1278 SilcSocketConnection sock = ctx->sock;
1279 SilcServerEntry id_entry = NULL;
1281 unsigned char *id_string;
1283 SilcIDListData idata;
1284 SilcServerConfigRouter *conn = NULL;
1285 SilcServerConfigConnParams *param = NULL;
1287 SILC_LOG_DEBUG(("Start"));
1289 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1290 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1291 /* Error occured during protocol */
1292 silc_free(ctx->dest_id);
1293 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1296 /* Try reconnecting if configuration wants it */
1297 if (!sconn->no_reconnect) {
1298 silc_schedule_task_add(server->schedule, 0,
1299 silc_server_connect_to_router_retry,
1300 sconn, 0, 1, SILC_TASK_TIMEOUT,
1301 SILC_TASK_PRI_NORMAL);
1308 /* Add a task to the queue. This task receives new connections to the
1309 server. This task remains on the queue until the end of the program. */
1310 if (!server->listenning && !sconn->backup) {
1311 silc_schedule_task_add(server->schedule, server->sock,
1312 silc_server_accept_new_connection,
1313 (void *)server, 0, 0,
1315 SILC_TASK_PRI_NORMAL);
1316 server->listenning = TRUE;
1319 /* Send NEW_SERVER packet to the router. We will become registered
1320 to the SILC network after sending this packet. */
1321 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
1322 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1323 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
1324 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1325 silc_buffer_format(packet,
1326 SILC_STR_UI_SHORT(id_len),
1327 SILC_STR_UI_XNSTRING(id_string, id_len),
1328 SILC_STR_UI_SHORT(strlen(server->server_name)),
1329 SILC_STR_UI_XNSTRING(server->server_name,
1330 strlen(server->server_name)),
1333 /* Send the packet */
1334 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
1335 packet->data, packet->len, TRUE);
1336 silc_buffer_free(packet);
1337 silc_free(id_string);
1339 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
1341 /* Check that we do not have this ID already */
1342 id_entry = silc_idlist_find_server_by_id(server->local_list,
1343 ctx->dest_id, TRUE, NULL);
1345 silc_idcache_del_by_context(server->local_list->servers, id_entry);
1347 id_entry = silc_idlist_find_server_by_id(server->global_list,
1348 ctx->dest_id, TRUE, NULL);
1350 silc_idcache_del_by_context(server->global_list->servers, id_entry);
1353 SILC_LOG_DEBUG(("New server id(%s)",
1354 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1356 /* Add the connected router to global server list. Router is sent
1357 as NULL since it's local to us. */
1358 id_entry = silc_idlist_add_server(server->global_list,
1359 strdup(sock->hostname),
1360 SILC_ROUTER, ctx->dest_id, NULL, sock);
1362 silc_free(ctx->dest_id);
1363 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1364 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1369 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1370 silc_free(sock->user_data);
1371 sock->user_data = (void *)id_entry;
1372 sock->type = SILC_SOCKET_TYPE_ROUTER;
1373 idata = (SilcIDListData)sock->user_data;
1374 idata->status |= (SILC_IDLIST_STATUS_REGISTERED |
1375 SILC_IDLIST_STATUS_LOCAL);
1377 conn = sconn->conn.ref_ptr;
1378 param = &server->config->param;
1379 if (conn && conn->param)
1380 param = conn->param;
1382 /* Perform keepalive. */
1383 silc_socket_set_heartbeat(sock, param->keepalive_secs, server,
1384 silc_server_perform_heartbeat,
1387 /* Register re-key timeout */
1388 idata->rekey->timeout = param->key_exchange_rekey;
1389 silc_schedule_task_add(server->schedule, sock->sock,
1390 silc_server_rekey_callback,
1391 (void *)sock, idata->rekey->timeout, 0,
1392 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1394 if (!sconn->backup) {
1395 /* Mark this router our primary router if we're still standalone */
1396 if (server->standalone) {
1397 SILC_LOG_DEBUG(("This connection is our primary router"));
1398 server->id_entry->router = id_entry;
1399 server->router = id_entry;
1400 server->standalone = FALSE;
1402 /* If we are router then announce our possible servers. Backup
1403 router announces also global servers. */
1404 if (server->server_type == SILC_ROUTER)
1405 silc_server_announce_servers(server,
1406 server->backup_router ? TRUE : FALSE,
1407 0, SILC_PRIMARY_ROUTE(server));
1409 /* Announce our clients and channels to the router */
1410 silc_server_announce_clients(server, 0, SILC_PRIMARY_ROUTE(server));
1411 silc_server_announce_channels(server, 0, SILC_PRIMARY_ROUTE(server));
1413 /* If we are backup router then this primary router is whom we are
1415 if (server->server_type == SILC_BACKUP_ROUTER)
1416 silc_server_backup_add(server, server->id_entry, sock->ip,
1417 sconn->remote_port, TRUE);
1420 /* Add this server to be our backup router */
1421 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1422 sconn->backup_replace_port, FALSE);
1425 sock->protocol = NULL;
1428 /* Call the completion callback to indicate that we've connected to
1430 if (sconn && sconn->callback)
1431 (*sconn->callback)(server, id_entry, sconn->callback_context);
1433 /* Free the temporary connection data context */
1435 silc_server_config_unref(&sconn->conn);
1436 silc_free(sconn->remote_host);
1437 silc_free(sconn->backup_replace_ip);
1440 if (sconn == server->router_conn)
1441 server->router_conn = NULL;
1444 /* Free the protocol object */
1445 if (sock->protocol == protocol)
1446 sock->protocol = NULL;
1447 silc_protocol_free(protocol);
1449 silc_packet_context_free(ctx->packet);
1451 silc_ske_free(ctx->ske);
1452 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1453 silc_free(ctx->auth_data);
1457 /* Host lookup callback that is called after the incoming connection's
1458 IP and FQDN lookup is performed. This will actually check the acceptance
1459 of the incoming connection and will register the key exchange protocol
1460 for this connection. */
1463 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1466 SilcServerKEInternalContext *proto_ctx =
1467 (SilcServerKEInternalContext *)context;
1468 SilcServer server = (SilcServer)proto_ctx->server;
1469 SilcServerConfigClient *cconfig = NULL;
1470 SilcServerConfigServer *sconfig = NULL;
1471 SilcServerConfigRouter *rconfig = NULL;
1472 SilcServerConfigDeny *deny;
1475 /* Check whether we could resolve both IP and FQDN. */
1476 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1477 server->config->require_reverse_lookup)) {
1478 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1479 sock->hostname ? sock->hostname :
1480 sock->ip ? sock->ip : ""));
1481 server->stat.conn_failures++;
1482 silc_server_disconnect_remote(server, sock,
1483 SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
1484 "Unknown host or IP");
1485 silc_free(proto_ctx);
1489 /* Register the connection for network input and output. This sets
1490 that scheduler will listen for incoming packets for this connection
1491 and sets that outgoing packets may be sent to this connection as well.
1492 However, this doesn't set the scheduler for outgoing traffic, it
1493 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1494 later when outgoing data is available. */
1495 context = (void *)server;
1496 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1498 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1501 /* Listenning port */
1502 if (!server->sockets[(SilcUInt32)proto_ctx->context]) {
1503 silc_server_disconnect_remote(server, sock,
1504 SILC_STATUS_ERR_RESOURCE_LIMIT,
1505 "Connection refused");
1506 server->stat.conn_failures++;
1507 silc_free(proto_ctx);
1510 port = server->sockets[(SilcUInt32)proto_ctx->context]->port;
1512 /* Check whether this connection is denied to connect to us. */
1513 deny = silc_server_config_find_denied(server, sock->ip);
1515 deny = silc_server_config_find_denied(server, sock->hostname);
1517 /* The connection is denied */
1518 SILC_LOG_INFO(("Connection %s (%s) is denied",
1519 sock->hostname, sock->ip));
1520 silc_server_disconnect_remote(server, sock,
1521 SILC_STATUS_ERR_BANNED_FROM_SERVER,
1523 server->stat.conn_failures++;
1524 silc_free(proto_ctx);
1528 /* Check whether we have configured this sort of connection at all. We
1529 have to check all configurations since we don't know what type of
1530 connection this is. */
1531 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1532 cconfig = silc_server_config_find_client(server, sock->hostname);
1533 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1534 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1535 if (server->server_type == SILC_ROUTER) {
1536 if (!(rconfig = silc_server_config_find_router_conn(server,
1537 sock->ip, sock->port)))
1538 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1541 if (!cconfig && !sconfig && !rconfig) {
1542 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1544 silc_server_disconnect_remote(server, sock,
1545 SILC_STATUS_ERR_BANNED_FROM_SERVER, NULL);
1546 server->stat.conn_failures++;
1547 silc_free(proto_ctx);
1551 /* The connection is allowed */
1553 /* Set internal context for key exchange protocol. This is
1554 sent as context for the protocol. */
1555 proto_ctx->sock = sock;
1556 proto_ctx->rng = server->rng;
1557 proto_ctx->responder = TRUE;
1558 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1559 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1560 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1562 /* Take flags for key exchange. Since we do not know what type of connection
1563 this is, we go through all found configurations and use the global ones
1564 as well. This will result always into strictest key exchange flags. */
1565 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1566 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1567 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1568 if (server->config->param.key_exchange_pfs)
1569 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1571 /* Prepare the connection for key exchange protocol. We allocate the
1572 protocol but will not start it yet. The connector will be the
1573 initiator of the protocol thus we will wait for initiation from
1574 there before we start the protocol. */
1575 server->stat.auth_attempts++;
1576 SILC_LOG_DEBUG(("Starting key exchange protocol"));
1577 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1578 &sock->protocol, proto_ctx,
1579 silc_server_accept_new_connection_second);
1581 /* Register a timeout task that will be executed if the connector
1582 will not start the key exchange protocol within specified timeout
1583 and the connection will be closed. */
1584 proto_ctx->timeout_task =
1585 silc_schedule_task_add(server->schedule, sock->sock,
1586 silc_server_timeout_remote,
1588 server->config->key_exchange_timeout, 0,
1593 /* Accepts new connections to the server. Accepting new connections are
1594 done in three parts to make it async. */
1596 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1598 SilcServer server = (SilcServer)context;
1599 SilcSocketConnection newsocket;
1600 SilcServerKEInternalContext *proto_ctx;
1603 SILC_LOG_DEBUG(("Accepting new connection"));
1605 server->stat.conn_attempts++;
1607 sock = silc_net_accept_connection(fd);
1609 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1610 server->stat.conn_failures++;
1614 /* Check for maximum allowed connections */
1615 if (sock > server->config->param.connections_max) {
1616 SILC_LOG_ERROR(("Refusing connection, server is full"));
1617 server->stat.conn_failures++;
1618 silc_net_close_connection(sock);
1622 /* Set socket options */
1623 silc_net_set_socket_nonblock(sock);
1624 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1626 /* We don't create a ID yet, since we don't know what type of connection
1627 this is yet. But, we do add the connection to the socket table. */
1628 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1629 server->sockets[sock] = newsocket;
1631 /* Perform asynchronous host lookup. This will lookup the IP and the
1632 FQDN of the remote connection. After the lookup is done the connection
1633 is accepted further. */
1634 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1635 proto_ctx->server = server;
1636 proto_ctx->context = (void *)fd;
1637 silc_socket_host_lookup(newsocket, TRUE,
1638 silc_server_accept_new_connection_lookup,
1639 (void *)proto_ctx, server->schedule);
1642 /* Second part of accepting new connection. Key exchange protocol has been
1643 performed and now it is time to do little connection authentication
1644 protocol to figure out whether this connection is client or server
1645 and whether it has right to access this server (especially server
1646 connections needs to be authenticated). */
1648 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1650 SilcProtocol protocol = (SilcProtocol)context;
1651 SilcServerKEInternalContext *ctx =
1652 (SilcServerKEInternalContext *)protocol->context;
1653 SilcServer server = (SilcServer)ctx->server;
1654 SilcSocketConnection sock = ctx->sock;
1655 SilcServerConnAuthInternalContext *proto_ctx;
1657 SILC_LOG_DEBUG(("Start"));
1659 if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1660 (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1661 /* Error occured during protocol */
1662 SILC_LOG_DEBUG(("Error key exchange protocol"));
1663 silc_protocol_free(protocol);
1664 sock->protocol = NULL;
1665 silc_ske_free_key_material(ctx->keymat);
1667 silc_packet_context_free(ctx->packet);
1669 silc_ske_free(ctx->ske);
1670 silc_free(ctx->dest_id);
1671 silc_server_config_unref(&ctx->cconfig);
1672 silc_server_config_unref(&ctx->sconfig);
1673 silc_server_config_unref(&ctx->rconfig);
1675 silc_schedule_task_del_by_callback(server->schedule,
1676 silc_server_failure_callback);
1677 silc_server_disconnect_remote(server, sock,
1678 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
1680 server->stat.auth_failures++;
1684 /* We now have the key material as the result of the key exchange
1685 protocol. Take the key material into use. Free the raw key material
1686 as soon as we've set them into use. */
1687 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1688 ctx->sock, ctx->keymat,
1689 ctx->ske->prop->cipher,
1690 ctx->ske->prop->pkcs,
1691 ctx->ske->prop->hash,
1692 ctx->ske->prop->hmac,
1693 ctx->ske->prop->group,
1695 SILC_LOG_ERROR(("Error setting key material in use"));
1696 silc_protocol_free(protocol);
1697 sock->protocol = NULL;
1698 silc_ske_free_key_material(ctx->keymat);
1700 silc_packet_context_free(ctx->packet);
1702 silc_ske_free(ctx->ske);
1703 silc_free(ctx->dest_id);
1704 silc_server_config_unref(&ctx->cconfig);
1705 silc_server_config_unref(&ctx->sconfig);
1706 silc_server_config_unref(&ctx->rconfig);
1708 silc_schedule_task_del_by_callback(server->schedule,
1709 silc_server_failure_callback);
1710 silc_server_disconnect_remote(server, sock,
1711 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1712 server->stat.auth_failures++;
1715 silc_ske_free_key_material(ctx->keymat);
1717 /* Allocate internal context for the authentication protocol. This
1718 is sent as context for the protocol. */
1719 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1720 proto_ctx->server = (void *)server;
1721 proto_ctx->sock = sock;
1722 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1723 proto_ctx->responder = TRUE;
1724 proto_ctx->dest_id_type = ctx->dest_id_type;
1725 proto_ctx->dest_id = ctx->dest_id;
1726 proto_ctx->cconfig = ctx->cconfig;
1727 proto_ctx->sconfig = ctx->sconfig;
1728 proto_ctx->rconfig = ctx->rconfig;
1730 /* Free old protocol as it is finished now */
1731 silc_protocol_free(protocol);
1733 silc_packet_context_free(ctx->packet);
1735 sock->protocol = NULL;
1737 /* Allocate the authentication protocol. This is allocated here
1738 but we won't start it yet. We will be receiving party of this
1739 protocol thus we will wait that connecting party will make
1740 their first move. */
1741 SILC_LOG_DEBUG(("Starting connection authentication protocol"));
1742 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1743 &sock->protocol, proto_ctx,
1744 silc_server_accept_new_connection_final);
1746 /* Register timeout task. If the protocol is not executed inside
1747 this timelimit the connection will be terminated. */
1748 proto_ctx->timeout_task =
1749 silc_schedule_task_add(server->schedule, sock->sock,
1750 silc_server_timeout_remote,
1752 server->config->conn_auth_timeout, 0,
1757 /* After this is called, server don't wait for backup router anymore.
1758 This gets called automatically even after we have backup router
1759 connection established. */
1761 SILC_TASK_CALLBACK(silc_server_backup_router_wait)
1763 SilcServer server = context;
1764 server->wait_backup = FALSE;
1767 /* Final part of accepting new connection. The connection has now
1768 been authenticated and keys has been exchanged. We also know whether
1769 this is client or server connection. */
1771 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1773 SilcProtocol protocol = (SilcProtocol)context;
1774 SilcServerConnAuthInternalContext *ctx =
1775 (SilcServerConnAuthInternalContext *)protocol->context;
1776 SilcServer server = (SilcServer)ctx->server;
1777 SilcSocketConnection sock = ctx->sock;
1778 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1780 SilcServerConfigConnParams *param = &server->config->param;
1782 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1783 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1784 /* Error occured during protocol */
1785 SILC_LOG_DEBUG(("Error during authentication protocol"));
1786 silc_protocol_free(protocol);
1787 sock->protocol = NULL;
1789 silc_packet_context_free(ctx->packet);
1791 silc_ske_free(ctx->ske);
1792 silc_free(ctx->dest_id);
1793 silc_server_config_unref(&ctx->cconfig);
1794 silc_server_config_unref(&ctx->sconfig);
1795 silc_server_config_unref(&ctx->rconfig);
1797 silc_schedule_task_del_by_callback(server->schedule,
1798 silc_server_failure_callback);
1799 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1801 server->stat.auth_failures++;
1805 entry->data.last_receive = time(NULL);
1807 switch (ctx->conn_type) {
1808 case SILC_SOCKET_TYPE_CLIENT:
1810 SilcClientEntry client;
1811 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1813 /* Verify whether this connection is after all allowed to connect */
1814 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1815 &server->config->param,
1816 conn->param, ctx->ske)) {
1817 server->stat.auth_failures++;
1821 /* If we are primary router and we have backup router configured
1822 but it has not connected to use yet, do not accept any other
1824 if (server->wait_backup && server->server_type == SILC_ROUTER &&
1825 !server->backup_router) {
1826 SilcServerConfigRouter *router;
1827 router = silc_server_config_get_backup_router(server);
1828 if (router && strcmp(server->config->server_info->primary->server_ip,
1830 silc_server_find_socket_by_host(server,
1831 SILC_SOCKET_TYPE_SERVER,
1832 router->backup_replace_ip, 0)) {
1833 SILC_LOG_INFO(("Will not accept connections because we do "
1834 "not have backup router connection established"));
1835 silc_server_disconnect_remote(server, sock,
1836 SILC_STATUS_ERR_PERM_DENIED,
1837 "We do not have connection to backup "
1838 "router established, try later");
1839 silc_free(sock->user_data);
1840 server->stat.auth_failures++;
1842 /* From here on, wait 10 seconds for the backup router to appear. */
1843 silc_schedule_task_add(server->schedule, 0,
1844 silc_server_backup_router_wait,
1845 (void *)server, 10, 0,
1846 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1851 SILC_LOG_DEBUG(("Remote host is client"));
1852 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1855 /* Add the client to the client ID cache. The nickname and Client ID
1856 and other information is created after we have received NEW_CLIENT
1857 packet from client. */
1858 client = silc_idlist_add_client(server->local_list,
1859 NULL, NULL, NULL, NULL, NULL, sock, 0);
1861 SILC_LOG_ERROR(("Could not add new client to cache"));
1862 silc_free(sock->user_data);
1863 silc_server_disconnect_remote(server, sock,
1864 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1865 server->stat.auth_failures++;
1868 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
1871 server->stat.my_clients++;
1872 server->stat.clients++;
1873 server->stat.cell_clients++;
1875 /* Get connection parameters */
1877 param = conn->param;
1879 if (!param->keepalive_secs)
1880 param->keepalive_secs = server->config->param.keepalive_secs;
1882 if (!param->qos && server->config->param.qos) {
1883 param->qos = server->config->param.qos;
1884 param->qos_rate_limit = server->config->param.qos_rate_limit;
1885 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
1886 param->qos_limit_sec = server->config->param.qos_limit_sec;
1887 param->qos_limit_usec = server->config->param.qos_limit_usec;
1890 /* Check if to be anonymous connection */
1891 if (param->anonymous)
1892 client->mode |= SILC_UMODE_ANONYMOUS;
1895 id_entry = (void *)client;
1898 case SILC_SOCKET_TYPE_SERVER:
1899 case SILC_SOCKET_TYPE_ROUTER:
1901 SilcServerEntry new_server;
1902 bool initiator = FALSE;
1903 bool backup_local = FALSE;
1904 bool backup_router = FALSE;
1905 char *backup_replace_ip = NULL;
1906 SilcUInt16 backup_replace_port = 0;
1907 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1908 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1910 /* If we are backup router and this is incoming server connection
1911 and we do not have connection to primary router, do not allow
1913 if (server->server_type == SILC_BACKUP_ROUTER &&
1914 ctx->conn_type == SILC_SOCKET_TYPE_SERVER &&
1915 !SILC_PRIMARY_ROUTE(server)) {
1916 SILC_LOG_INFO(("Will not accept server connection because we do "
1917 "not have primary router connection established"));
1918 silc_server_disconnect_remote(server, sock,
1919 SILC_STATUS_ERR_PERM_DENIED,
1920 "We do not have connection to primary "
1921 "router established, try later");
1922 silc_free(sock->user_data);
1923 server->stat.auth_failures++;
1927 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1928 /* Verify whether this connection is after all allowed to connect */
1929 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1930 &server->config->param,
1931 rconn ? rconn->param : NULL,
1933 silc_free(sock->user_data);
1934 server->stat.auth_failures++;
1940 param = rconn->param;
1942 if (!param->keepalive_secs)
1943 param->keepalive_secs = server->config->param.keepalive_secs;
1945 if (!param->qos && server->config->param.qos) {
1946 param->qos = server->config->param.qos;
1947 param->qos_rate_limit = server->config->param.qos_rate_limit;
1948 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
1949 param->qos_limit_sec = server->config->param.qos_limit_sec;
1950 param->qos_limit_usec = server->config->param.qos_limit_usec;
1954 initiator = rconn->initiator;
1955 backup_local = rconn->backup_local;
1956 backup_router = rconn->backup_router;
1957 backup_replace_ip = rconn->backup_replace_ip;
1958 backup_replace_port = rconn->backup_replace_port;
1962 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1963 /* Verify whether this connection is after all allowed to connect */
1964 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1965 &server->config->param,
1966 sconn ? sconn->param : NULL,
1968 silc_free(sock->user_data);
1969 server->stat.auth_failures++;
1974 param = sconn->param;
1976 if (!param->keepalive_secs)
1977 param->keepalive_secs = server->config->param.keepalive_secs;
1979 if (!param->qos && server->config->param.qos) {
1980 param->qos = server->config->param.qos;
1981 param->qos_rate_limit = server->config->param.qos_rate_limit;
1982 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
1983 param->qos_limit_sec = server->config->param.qos_limit_sec;
1984 param->qos_limit_usec = server->config->param.qos_limit_usec;
1988 backup_router = sconn->backup_router;
1992 /* If we are primary router and we have backup router configured
1993 but it has not connected to use yet, do not accept any other
1995 if (server->wait_backup && server->server_type == SILC_ROUTER &&
1996 !server->backup_router && !backup_router) {
1997 SilcServerConfigRouter *router;
1998 router = silc_server_config_get_backup_router(server);
1999 if (router && strcmp(server->config->server_info->primary->server_ip,
2001 silc_server_find_socket_by_host(server,
2002 SILC_SOCKET_TYPE_SERVER,
2003 router->backup_replace_ip, 0)) {
2004 SILC_LOG_INFO(("Will not accept connections because we do "
2005 "not have backup router connection established"));
2006 silc_server_disconnect_remote(server, sock,
2007 SILC_STATUS_ERR_PERM_DENIED,
2008 "We do not have connection to backup "
2009 "router established, try later");
2010 silc_free(sock->user_data);
2011 server->stat.auth_failures++;
2013 /* From here on, wait 10 seconds for the backup router to appear. */
2014 silc_schedule_task_add(server->schedule, 0,
2015 silc_server_backup_router_wait,
2016 (void *)server, 10, 0,
2017 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2022 SILC_LOG_DEBUG(("Remote host is %s",
2023 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2024 "server" : (backup_router ?
2025 "backup router" : "router")));
2026 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
2027 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2028 "server" : (backup_router ?
2029 "backup router" : "router")));
2031 /* Add the server into server cache. The server name and Server ID
2032 is updated after we have received NEW_SERVER packet from the
2033 server. We mark ourselves as router for this server if we really
2036 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2037 server->local_list : (backup_router ?
2038 server->local_list :
2039 server->global_list)),
2041 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2042 SILC_SERVER : SILC_ROUTER),
2044 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2045 server->id_entry : (backup_router ?
2046 server->id_entry : NULL)),
2049 SILC_LOG_ERROR(("Could not add new server to cache"));
2050 silc_free(sock->user_data);
2051 silc_server_disconnect_remote(server, sock,
2052 SILC_STATUS_ERR_AUTH_FAILED, NULL);
2053 server->stat.auth_failures++;
2056 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
2058 id_entry = (void *)new_server;
2060 /* If the incoming connection is router and marked as backup router
2061 then add it to be one of our backups */
2062 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
2063 /* Change it back to SERVER type since that's what it really is. */
2065 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
2066 new_server->server_type = SILC_BACKUP_ROUTER;
2068 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
2069 ("Backup router %s is now online",
2072 /* Remove the backup waiting with timeout */
2073 silc_schedule_task_add(server->schedule, 0,
2074 silc_server_backup_router_wait,
2075 (void *)server, 5, 0,
2076 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2080 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
2081 server->stat.my_servers++;
2083 server->stat.my_routers++;
2084 server->stat.routers++;
2086 server->stat.servers++;
2088 /* Check whether this connection is to be our primary router connection
2089 if we do not already have the primary route. */
2090 if (!backup_router &&
2091 server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
2092 if (silc_server_config_is_primary_route(server) && !initiator)
2095 SILC_LOG_DEBUG(("We are not standalone server anymore"));
2096 server->standalone = FALSE;
2097 if (!server->id_entry->router) {
2098 server->id_entry->router = id_entry;
2099 server->router = id_entry;
2110 sock->type = ctx->conn_type;
2112 /* Add the common data structure to the ID entry. */
2113 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
2115 /* Add to sockets internal pointer for fast referencing */
2116 silc_free(sock->user_data);
2117 sock->user_data = id_entry;
2119 /* Connection has been fully established now. Everything is ok. */
2120 SILC_LOG_DEBUG(("New connection authenticated"));
2122 /* Perform keepalive. */
2123 if (param->keepalive_secs)
2124 silc_socket_set_heartbeat(sock, param->keepalive_secs, server,
2125 silc_server_perform_heartbeat,
2128 /* Perform Quality of Service */
2130 silc_socket_set_qos(sock, param->qos_rate_limit, param->qos_bytes_limit,
2131 param->qos_limit_sec, param->qos_limit_usec,
2135 silc_schedule_task_del_by_callback(server->schedule,
2136 silc_server_failure_callback);
2137 silc_protocol_free(protocol);
2139 silc_packet_context_free(ctx->packet);
2141 silc_ske_free(ctx->ske);
2142 silc_free(ctx->dest_id);
2143 silc_server_config_unref(&ctx->cconfig);
2144 silc_server_config_unref(&ctx->sconfig);
2145 silc_server_config_unref(&ctx->rconfig);
2147 sock->protocol = NULL;
2150 /* This function is used to read packets from network and send packets to
2151 network. This is usually a generic task. */
2153 SILC_TASK_CALLBACK(silc_server_packet_process)
2155 SilcServer server = (SilcServer)context;
2156 SilcSocketConnection sock = server->sockets[fd];
2157 SilcIDListData idata;
2158 SilcCipher cipher = NULL;
2159 SilcHmac hmac = NULL;
2160 SilcUInt32 sequence = 0;
2164 SILC_LOG_DEBUG(("Unknown socket connection"));
2168 /* Packet sending */
2170 if (type == SILC_TASK_WRITE) {
2171 /* Do not send data to disconnected connection */
2172 if (SILC_IS_DISCONNECTED(sock)) {
2173 SILC_LOG_DEBUG(("Disconnected socket connection, cannot send"));
2177 server->stat.packets_sent++;
2179 /* Send the packet */
2180 ret = silc_packet_send(sock, TRUE);
2182 /* If returned -2 could not write to connection now, will do
2188 SILC_LOG_ERROR(("Error sending packet to connection "
2189 "%s:%d [%s]", sock->hostname, sock->port,
2190 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2191 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2192 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2197 /* The packet has been sent and now it is time to set the connection
2198 back to only for input. When there is again some outgoing data
2199 available for this connection it will be set for output as well.
2200 This call clears the output setting and sets it only for input. */
2201 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
2202 SILC_UNSET_OUTBUF_PENDING(sock);
2204 silc_buffer_clear(sock->outbuf);
2208 /* Packet receiving */
2210 /* Read some data from connection */
2211 ret = silc_packet_receive(sock);
2215 SILC_LOG_ERROR(("Error receiving packet from connection "
2216 "%s:%d [%s] %s", sock->hostname, sock->port,
2217 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2218 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2219 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2220 "Router"), strerror(errno)));
2226 SILC_LOG_DEBUG(("Read EOF"));
2228 /* If connection is disconnecting already we will finally
2229 close the connection */
2230 if (SILC_IS_DISCONNECTING(sock)) {
2231 if (sock->user_data)
2232 silc_server_free_sock_user_data(server, sock, NULL);
2233 silc_server_close_connection(server, sock);
2237 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
2238 SILC_SET_DISCONNECTING(sock);
2240 if (sock->user_data) {
2242 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
2243 silc_server_free_sock_user_data(server, sock, tmp);
2245 silc_server_free_sock_user_data(server, sock, NULL);
2246 } else if (server->router_conn && server->router_conn->sock == sock &&
2247 !server->router && server->standalone)
2248 silc_schedule_task_add(server->schedule, 0,
2249 silc_server_connect_to_router,
2252 SILC_TASK_PRI_NORMAL);
2254 silc_server_close_connection(server, sock);
2258 /* If connection is disconnecting or disconnected we will ignore
2260 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2261 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
2265 /* Get keys and stuff from ID entry */
2266 idata = (SilcIDListData)sock->user_data;
2268 cipher = idata->receive_key;
2269 hmac = idata->hmac_receive;
2270 sequence = idata->psn_receive;
2273 /* Process the packet. This will call the parser that will then
2274 decrypt and parse the packet. */
2275 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
2276 TRUE : FALSE, cipher, hmac, sequence,
2277 silc_server_packet_parse, server);
2279 /* If processing failed the connection is closed. */
2281 /* On packet processing errors we may close our primary router
2282 connection but won't become primary router if we are the backup
2283 since this is local error condition. */
2284 if (SILC_PRIMARY_ROUTE(server) == sock && server->backup_router)
2285 server->backup_noswitch = TRUE;
2287 if (sock->user_data)
2288 silc_server_free_sock_user_data(server, sock, NULL);
2289 silc_server_close_connection(server, sock);
2293 /* Parses whole packet, received earlier. */
2295 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
2297 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
2298 SilcServer server = (SilcServer)parse_ctx->context;
2299 SilcSocketConnection sock = parse_ctx->sock;
2300 SilcPacketContext *packet = parse_ctx->packet;
2301 SilcIDListData idata = (SilcIDListData)sock->user_data;
2304 server->stat.packets_received++;
2306 /* Parse the packet */
2307 if (parse_ctx->normal)
2308 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
2310 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
2312 /* If entry is disabled ignore what we got. */
2313 if (idata && idata->status & SILC_IDLIST_STATUS_DISABLED &&
2314 ret != SILC_PACKET_HEARTBEAT && ret != SILC_PACKET_RESUME_ROUTER &&
2315 ret != SILC_PACKET_REKEY && ret != SILC_PACKET_REKEY_DONE) {
2316 SILC_LOG_DEBUG(("Connection is disabled"));
2320 if (ret == SILC_PACKET_NONE) {
2321 SILC_LOG_DEBUG(("Error parsing packet"));
2325 /* Check that the the current client ID is same as in the client's packet. */
2326 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
2327 SilcClientEntry client = (SilcClientEntry)sock->user_data;
2328 if (client && client->id && packet->src_id) {
2329 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
2330 packet->src_id_type);
2331 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
2333 SILC_LOG_DEBUG(("Packet source is not same as sender"));
2340 if (server->server_type == SILC_ROUTER) {
2341 /* Route the packet if it is not destined to us. Other ID types but
2342 server are handled separately after processing them. */
2343 if (packet->dst_id && !(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
2344 packet->dst_id_type == SILC_ID_SERVER &&
2345 sock->type != SILC_SOCKET_TYPE_CLIENT &&
2346 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
2348 /* Route the packet to fastest route for the destination ID */
2349 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
2350 packet->dst_id_type);
2353 silc_server_packet_route(server,
2354 silc_server_route_get(server, id,
2355 packet->dst_id_type),
2362 /* Parse the incoming packet type */
2363 silc_server_packet_parse_type(server, sock, packet);
2365 /* Broadcast packet if it is marked as broadcast packet and it is
2366 originated from router and we are router. */
2367 if (server->server_type == SILC_ROUTER &&
2368 sock->type == SILC_SOCKET_TYPE_ROUTER &&
2369 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
2370 /* Broadcast to our primary route */
2371 silc_server_packet_broadcast(server, SILC_PRIMARY_ROUTE(server), packet);
2373 /* If we have backup routers then we need to feed all broadcast
2374 data to those servers. */
2375 silc_server_backup_broadcast(server, sock, packet);
2379 silc_packet_context_free(packet);
2380 silc_free(parse_ctx);
2383 /* Parser callback called by silc_packet_receive_process. This merely
2384 registers timeout that will handle the actual parsing when appropriate. */
2386 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
2389 SilcServer server = (SilcServer)context;
2390 SilcSocketConnection sock = parser_context->sock;
2391 SilcIDListData idata = (SilcIDListData)sock->user_data;
2395 idata->psn_receive = parser_context->packet->sequence + 1;
2397 /* If protocol for this connection is key exchange or rekey then we'll
2398 process all packets synchronously, since there might be packets in
2399 queue that we are not able to decrypt without first processing the
2400 packets before them. */
2401 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
2402 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
2403 (sock->protocol && sock->protocol->protocol &&
2404 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2405 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
2406 silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2409 /* Reprocess data since we'll return FALSE here. This is because
2410 the idata->receive_key might have become valid in the last packet
2411 and we want to call this processor with valid cipher. */
2413 ret = silc_packet_receive_process(
2414 sock, server->server_type == SILC_ROUTER ?
2415 TRUE : FALSE, idata->receive_key,
2416 idata->hmac_receive, idata->psn_receive,
2417 silc_server_packet_parse, server);
2419 ret = silc_packet_receive_process(
2420 sock, server->server_type == SILC_ROUTER ?
2421 TRUE : FALSE, NULL, NULL, 0,
2422 silc_server_packet_parse, server);
2425 /* On packet processing errors we may close our primary router
2426 connection but won't become primary router if we are the backup
2427 since this is local error condition. */
2428 if (SILC_PRIMARY_ROUTE(server) == sock && server->backup_router)
2429 server->backup_noswitch = TRUE;
2431 if (sock->user_data)
2432 silc_server_free_sock_user_data(server, sock, NULL);
2433 silc_server_close_connection(server, sock);
2439 switch (sock->type) {
2440 case SILC_SOCKET_TYPE_UNKNOWN:
2441 case SILC_SOCKET_TYPE_CLIENT:
2442 /* Parse the packet with timeout */
2443 silc_schedule_task_add(server->schedule, sock->sock,
2444 silc_server_packet_parse_real,
2445 (void *)parser_context, 0, 100000,
2447 SILC_TASK_PRI_NORMAL);
2449 case SILC_SOCKET_TYPE_SERVER:
2450 case SILC_SOCKET_TYPE_ROUTER:
2451 /* Packets from servers are parsed immediately */
2452 silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2462 /* Parses the packet type and calls what ever routines the packet type
2463 requires. This is done for all incoming packets. */
2465 void silc_server_packet_parse_type(SilcServer server,
2466 SilcSocketConnection sock,
2467 SilcPacketContext *packet)
2469 SilcPacketType type = packet->type;
2470 SilcIDListData idata = (SilcIDListData)sock->user_data;
2472 SILC_LOG_DEBUG(("Received %s packet [flags %d]",
2473 silc_get_packet_name(type), packet->flags));
2475 /* Parse the packet type */
2477 case SILC_PACKET_DISCONNECT:
2480 char *message = NULL;
2482 if (packet->flags & SILC_PACKET_FLAG_LIST)
2484 if (packet->buffer->len < 1)
2487 status = (SilcStatus)packet->buffer->data[0];
2488 if (packet->buffer->len > 1 &&
2489 silc_utf8_valid(packet->buffer->data + 1, packet->buffer->len - 1))
2490 message = silc_memdup(packet->buffer->data + 1,
2491 packet->buffer->len - 1);
2493 SILC_LOG_INFO(("Disconnected by %s (%s): %s (%d) %s",
2494 sock->ip, sock->hostname,
2495 silc_get_status_message(status), status,
2496 message ? message : ""));
2499 /* Handle the disconnection from our end too */
2500 if (sock->user_data && SILC_IS_LOCAL(sock->user_data))
2501 silc_server_free_sock_user_data(server, sock, NULL);
2502 silc_server_close_connection(server, sock);
2506 case SILC_PACKET_SUCCESS:
2508 * Success received for something. For now we can have only
2509 * one protocol for connection executing at once hence this
2510 * success message is for whatever protocol is executing currently.
2512 if (packet->flags & SILC_PACKET_FLAG_LIST)
2515 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2518 case SILC_PACKET_FAILURE:
2520 * Failure received for something. For now we can have only
2521 * one protocol for connection executing at once hence this
2522 * failure message is for whatever protocol is executing currently.
2524 if (packet->flags & SILC_PACKET_FLAG_LIST)
2526 if (sock->protocol) {
2527 SilcServerFailureContext f;
2528 f = silc_calloc(1, sizeof(*f));
2529 f->sock = silc_socket_dup(sock);
2531 /* We will wait 5 seconds to process this failure packet */
2532 silc_schedule_task_add(server->schedule, sock->sock,
2533 silc_server_failure_callback, (void *)f, 5, 0,
2534 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2538 case SILC_PACKET_REJECT:
2539 if (packet->flags & SILC_PACKET_FLAG_LIST)
2544 case SILC_PACKET_NOTIFY:
2546 * Received notify packet. Server can receive notify packets from
2547 * router. Server then relays the notify messages to clients if needed.
2549 if (packet->flags & SILC_PACKET_FLAG_LIST)
2550 silc_server_notify_list(server, sock, packet);
2552 silc_server_notify(server, sock, packet);
2558 case SILC_PACKET_CHANNEL_MESSAGE:
2560 * Received channel message. Channel messages are special packets
2561 * (although probably most common ones) thus they are handled
2564 if (packet->flags & SILC_PACKET_FLAG_LIST)
2566 idata->last_receive = time(NULL);
2567 silc_server_channel_message(server, sock, packet);
2570 case SILC_PACKET_CHANNEL_KEY:
2572 * Received key for channel. As channels are created by the router
2573 * the keys are as well. We will distribute the key to all of our
2574 * locally connected clients on the particular channel. Router
2575 * never receives this channel and thus is ignored.
2577 if (packet->flags & SILC_PACKET_FLAG_LIST)
2579 silc_server_channel_key(server, sock, packet);
2585 case SILC_PACKET_COMMAND:
2587 * Recived command. Processes the command request and allocates the
2588 * command context and calls the command.
2590 if (packet->flags & SILC_PACKET_FLAG_LIST)
2592 silc_server_command_process(server, sock, packet);
2595 case SILC_PACKET_COMMAND_REPLY:
2597 * Received command reply packet. Received command reply to command. It
2598 * may be reply to command sent by us or reply to command sent by client
2599 * that we've routed further.
2601 if (packet->flags & SILC_PACKET_FLAG_LIST)
2603 silc_server_command_reply(server, sock, packet);
2607 * Private Message packets
2609 case SILC_PACKET_PRIVATE_MESSAGE:
2611 * Received private message packet. The packet is coming from either
2614 if (packet->flags & SILC_PACKET_FLAG_LIST)
2616 idata->last_receive = time(NULL);
2617 silc_server_private_message(server, sock, packet);
2620 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2622 * Private message key packet.
2624 if (packet->flags & SILC_PACKET_FLAG_LIST)
2626 silc_server_private_message_key(server, sock, packet);
2630 * Key Exchange protocol packets
2632 case SILC_PACKET_KEY_EXCHANGE:
2633 if (packet->flags & SILC_PACKET_FLAG_LIST)
2636 if (sock->protocol && sock->protocol->protocol &&
2637 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2638 SilcServerKEInternalContext *proto_ctx =
2639 (SilcServerKEInternalContext *)sock->protocol->context;
2641 proto_ctx->packet = silc_packet_context_dup(packet);
2643 /* Let the protocol handle the packet */
2644 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2646 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2647 "protocol active, packet dropped."));
2651 case SILC_PACKET_KEY_EXCHANGE_1:
2652 if (packet->flags & SILC_PACKET_FLAG_LIST)
2655 if (sock->protocol && sock->protocol->protocol &&
2656 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2657 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2659 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2660 SilcServerRekeyInternalContext *proto_ctx =
2661 (SilcServerRekeyInternalContext *)sock->protocol->context;
2663 if (proto_ctx->packet)
2664 silc_packet_context_free(proto_ctx->packet);
2666 proto_ctx->packet = silc_packet_context_dup(packet);
2668 /* Let the protocol handle the packet */
2669 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2671 SilcServerKEInternalContext *proto_ctx =
2672 (SilcServerKEInternalContext *)sock->protocol->context;
2674 if (proto_ctx->packet)
2675 silc_packet_context_free(proto_ctx->packet);
2677 proto_ctx->packet = silc_packet_context_dup(packet);
2678 proto_ctx->dest_id_type = packet->src_id_type;
2679 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2680 packet->src_id_type);
2681 if (!proto_ctx->dest_id)
2684 /* Let the protocol handle the packet */
2685 silc_protocol_execute(sock->protocol, server->schedule,
2689 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2690 "protocol active, packet dropped."));
2694 case SILC_PACKET_KEY_EXCHANGE_2:
2695 if (packet->flags & SILC_PACKET_FLAG_LIST)
2698 if (sock->protocol && sock->protocol->protocol &&
2699 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2700 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2702 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2703 SilcServerRekeyInternalContext *proto_ctx =
2704 (SilcServerRekeyInternalContext *)sock->protocol->context;
2706 if (proto_ctx->packet)
2707 silc_packet_context_free(proto_ctx->packet);
2709 proto_ctx->packet = silc_packet_context_dup(packet);
2711 /* Let the protocol handle the packet */
2712 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2714 SilcServerKEInternalContext *proto_ctx =
2715 (SilcServerKEInternalContext *)sock->protocol->context;
2717 if (proto_ctx->packet)
2718 silc_packet_context_free(proto_ctx->packet);
2720 proto_ctx->packet = silc_packet_context_dup(packet);
2721 proto_ctx->dest_id_type = packet->src_id_type;
2722 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2723 packet->src_id_type);
2724 if (!proto_ctx->dest_id)
2727 /* Let the protocol handle the packet */
2728 silc_protocol_execute(sock->protocol, server->schedule,
2732 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2733 "protocol active, packet dropped."));
2737 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2739 * Connection authentication request packet. When we receive this packet
2740 * we will send to the other end information about our mandatory
2741 * authentication method for the connection. This packet maybe received
2744 if (packet->flags & SILC_PACKET_FLAG_LIST)
2746 silc_server_connection_auth_request(server, sock, packet);
2750 * Connection Authentication protocol packets
2752 case SILC_PACKET_CONNECTION_AUTH:
2753 /* Start of the authentication protocol. We receive here the
2754 authentication data and will verify it. */
2755 if (packet->flags & SILC_PACKET_FLAG_LIST)
2758 if (sock->protocol && sock->protocol->protocol->type
2759 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2761 SilcServerConnAuthInternalContext *proto_ctx =
2762 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2764 proto_ctx->packet = silc_packet_context_dup(packet);
2766 /* Let the protocol handle the packet */
2767 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2769 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2770 "protocol active, packet dropped."));
2774 case SILC_PACKET_NEW_ID:
2776 * Received New ID packet. This includes some new ID that has been
2777 * created. It may be for client, server or channel. This is the way
2778 * to distribute information about new registered entities in the
2781 if (packet->flags & SILC_PACKET_FLAG_LIST)
2782 silc_server_new_id_list(server, sock, packet);
2784 silc_server_new_id(server, sock, packet);
2787 case SILC_PACKET_NEW_CLIENT:
2789 * Received new client packet. This includes client information that
2790 * we will use to create initial client ID. After creating new
2791 * ID we will send it to the client.
2793 if (packet->flags & SILC_PACKET_FLAG_LIST)
2795 silc_server_new_client(server, sock, packet);
2798 case SILC_PACKET_NEW_SERVER:
2800 * Received new server packet. This includes Server ID and some other
2801 * information that we may save. This is received after server has
2804 if (packet->flags & SILC_PACKET_FLAG_LIST)
2806 silc_server_new_server(server, sock, packet);
2809 case SILC_PACKET_NEW_CHANNEL:
2811 * Received new channel packet. Information about new channel in the
2812 * network are distributed using this packet.
2814 if (packet->flags & SILC_PACKET_FLAG_LIST)
2815 silc_server_new_channel_list(server, sock, packet);
2817 silc_server_new_channel(server, sock, packet);
2820 case SILC_PACKET_HEARTBEAT:
2822 * Received heartbeat.
2824 if (packet->flags & SILC_PACKET_FLAG_LIST)
2828 case SILC_PACKET_KEY_AGREEMENT:
2830 * Received heartbeat.
2832 if (packet->flags & SILC_PACKET_FLAG_LIST)
2834 silc_server_key_agreement(server, sock, packet);
2837 case SILC_PACKET_REKEY:
2839 * Received re-key packet. The sender wants to regenerate the session
2842 if (packet->flags & SILC_PACKET_FLAG_LIST)
2844 silc_server_rekey(server, sock, packet);
2847 case SILC_PACKET_REKEY_DONE:
2849 * The re-key is done.
2851 if (packet->flags & SILC_PACKET_FLAG_LIST)
2854 if (sock->protocol && sock->protocol->protocol &&
2855 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2857 SilcServerRekeyInternalContext *proto_ctx =
2858 (SilcServerRekeyInternalContext *)sock->protocol->context;
2860 if (proto_ctx->packet)
2861 silc_packet_context_free(proto_ctx->packet);
2863 proto_ctx->packet = silc_packet_context_dup(packet);
2865 /* Let the protocol handle the packet */
2866 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2868 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2869 "protocol active, packet dropped."));
2873 case SILC_PACKET_FTP:
2875 if (packet->flags & SILC_PACKET_FLAG_LIST)
2877 silc_server_ftp(server, sock, packet);
2880 case SILC_PACKET_RESUME_CLIENT:
2882 if (packet->flags & SILC_PACKET_FLAG_LIST)
2884 silc_server_resume_client(server, sock, packet);
2887 case SILC_PACKET_RESUME_ROUTER:
2888 /* Resume router packet received. This packet is received for backup
2889 router resuming protocol. */
2890 if (packet->flags & SILC_PACKET_FLAG_LIST)
2892 silc_server_backup_resume_router(server, sock, packet);
2896 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2901 /* Creates connection to a remote router. */
2903 void silc_server_create_connection(SilcServer server,
2904 const char *remote_host, SilcUInt32 port)
2906 SilcServerConnection sconn;
2908 /* Allocate connection object for hold connection specific stuff. */
2909 sconn = silc_calloc(1, sizeof(*sconn));
2910 sconn->remote_host = strdup(remote_host);
2911 sconn->remote_port = port;
2912 sconn->no_reconnect = TRUE;
2914 silc_schedule_task_add(server->schedule, 0,
2915 silc_server_connect_router,
2916 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2917 SILC_TASK_PRI_NORMAL);
2920 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2922 silc_socket_free(context);
2925 /* Closes connection to socket connection */
2927 void silc_server_close_connection(SilcServer server,
2928 SilcSocketConnection sock)
2932 if (!server->sockets[sock->sock] && SILC_IS_DISCONNECTED(sock)) {
2933 silc_schedule_task_add(server->schedule, 0,
2934 silc_server_close_connection_final,
2935 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2936 SILC_TASK_PRI_NORMAL);
2940 memset(tmp, 0, sizeof(tmp));
2941 silc_socket_get_error(sock, tmp, sizeof(tmp));
2942 SILC_LOG_INFO(("Closing connection %s:%d [%s] %s", sock->hostname,
2944 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2945 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2946 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2947 "Router"), tmp[0] ? tmp : ""));
2949 /* We won't listen for this connection anymore */
2950 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2952 /* Unregister all tasks */
2953 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2955 /* Close the actual connection */
2956 silc_net_close_connection(sock->sock);
2957 server->sockets[sock->sock] = NULL;
2959 /* If sock->user_data is NULL then we'll check for active protocols
2960 here since the silc_server_free_sock_user_data has not been called
2961 for this connection. */
2962 if (!sock->user_data) {
2963 /* If any protocol is active cancel its execution. It will call
2964 the final callback which will finalize the disconnection. */
2965 if (sock->protocol) {
2966 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
2967 silc_protocol_cancel(sock->protocol, server->schedule);
2968 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2969 silc_protocol_execute_final(sock->protocol, server->schedule);
2970 sock->protocol = NULL;
2975 silc_schedule_task_add(server->schedule, 0,
2976 silc_server_close_connection_final,
2977 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2978 SILC_TASK_PRI_NORMAL);
2981 /* Sends disconnect message to remote connection and disconnects the
2984 void silc_server_disconnect_remote(SilcServer server,
2985 SilcSocketConnection sock,
2986 SilcStatus status, ...)
2989 unsigned char buf[512];
2994 if (!sock || SILC_IS_DISCONNECTED(sock))
2997 memset(buf, 0, sizeof(buf));
2998 va_start(ap, status);
2999 cp = va_arg(ap, char *);
3001 vsnprintf(buf, sizeof(buf) - 1, cp, ap);
3006 SILC_LOG_DEBUG(("Disconnecting remote host"));
3008 /* Notify remote end that the conversation is over. The notify message
3009 is tried to be sent immediately. */
3013 len += silc_utf8_encoded_len(buf, strlen(buf), SILC_STRING_ASCII);
3015 buffer = silc_buffer_alloc_size(len);
3019 buffer->data[0] = status;
3021 silc_utf8_encode(buf, strlen(buf), SILC_STRING_ASCII, buffer->data + 1,
3023 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
3024 buffer->data, buffer->len, TRUE);
3025 silc_buffer_free(buffer);
3028 silc_server_packet_queue_purge(server, sock);
3030 /* Mark the connection to be disconnected */
3031 SILC_SET_DISCONNECTED(sock);
3032 silc_server_close_connection(server, sock);
3035 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
3037 SilcServer server = app_context;
3038 SilcClientEntry client = context;
3040 assert(!silc_hash_table_count(client->channels));
3042 silc_idlist_del_data(client);
3043 silc_idcache_purge_by_context(server->local_list->clients, client);
3046 /* Frees client data and notifies about client's signoff. */
3048 void silc_server_free_client_data(SilcServer server,
3049 SilcSocketConnection sock,
3050 SilcClientEntry client,
3052 const char *signoff)
3054 SILC_LOG_DEBUG(("Freeing client data"));
3056 /* If there is pending outgoing data for the client then purge it
3057 to the network before removing the client entry. */
3058 silc_server_packet_queue_purge(server, sock);
3061 /* Check if anyone is watching this nickname */
3062 if (server->server_type == SILC_ROUTER)
3063 silc_server_check_watcher_list(server, client, NULL,
3064 SILC_NOTIFY_TYPE_SIGNOFF);
3066 /* Send SIGNOFF notify to routers. */
3068 silc_server_send_notify_signoff(server, SILC_PRIMARY_ROUTE(server),
3069 SILC_BROADCAST(server), client->id,
3073 /* Remove client from all channels */
3075 silc_server_remove_from_channels(server, NULL, client,
3076 TRUE, (char *)signoff, TRUE);
3078 silc_server_remove_from_channels(server, NULL, client,
3079 FALSE, NULL, FALSE);
3081 /* Remove this client from watcher list if it is */
3082 silc_server_del_from_watcher_list(server, client);
3084 /* Update statistics */
3085 server->stat.my_clients--;
3086 server->stat.clients--;
3087 if (server->stat.cell_clients)
3088 server->stat.cell_clients--;
3089 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
3090 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
3091 silc_schedule_task_del_by_context(server->schedule, client);
3093 /* We will not delete the client entry right away. We will take it
3094 into history (for WHOWAS command) for 5 minutes, unless we're
3095 shutting down server. */
3096 if (!server->server_shutdown) {
3097 silc_schedule_task_add(server->schedule, 0,
3098 silc_server_free_client_data_timeout,
3100 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
3101 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
3102 client->data.status &= ~SILC_IDLIST_STATUS_LOCAL;
3104 client->router = NULL;
3105 client->connection = NULL;
3107 /* Delete directly since we're shutting down server */
3108 silc_idlist_del_data(client);
3109 silc_idlist_del_client(server->local_list, client);
3113 /* Frees user_data pointer from socket connection object. This also sends
3114 appropriate notify packets to the network to inform about leaving
3117 void silc_server_free_sock_user_data(SilcServer server,
3118 SilcSocketConnection sock,
3119 const char *signoff_message)
3121 switch (sock->type) {
3122 case SILC_SOCKET_TYPE_CLIENT:
3124 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
3125 silc_server_free_client_data(server, sock, user_data, TRUE,
3129 case SILC_SOCKET_TYPE_SERVER:
3130 case SILC_SOCKET_TYPE_ROUTER:
3132 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
3133 SilcServerEntry backup_router = NULL;
3135 SILC_LOG_DEBUG(("Freeing server data"));
3138 backup_router = silc_server_backup_get(server, user_data->id);
3140 if (!server->backup_router && server->server_type == SILC_ROUTER &&
3141 backup_router == server->id_entry &&
3142 sock->type != SILC_SOCKET_TYPE_ROUTER)
3143 backup_router = NULL;
3145 if (server->server_shutdown || server->backup_noswitch)
3146 backup_router = NULL;
3148 /* If this was our primary router connection then we're lost to
3149 the outside world. */
3150 if (server->router == user_data) {
3151 /* Check whether we have a backup router connection */
3152 if (!backup_router || backup_router == user_data) {
3153 silc_schedule_task_add(server->schedule, 0,
3154 silc_server_connect_to_router,
3157 SILC_TASK_PRI_NORMAL);
3159 server->id_entry->router = NULL;
3160 server->router = NULL;
3161 server->standalone = TRUE;
3162 backup_router = NULL;
3164 if (server->id_entry != backup_router) {
3165 SILC_LOG_INFO(("New primary router is backup router %s",
3166 backup_router->server_name));
3167 server->id_entry->router = backup_router;
3168 server->router = backup_router;
3169 server->router_connect = time(0);
3170 server->backup_primary = TRUE;
3172 SILC_LOG_INFO(("We are now new primary router in this cell"));
3173 server->id_entry->router = NULL;
3174 server->router = NULL;
3175 server->standalone = TRUE;
3177 /* We stop here to take a breath */
3181 if (server->server_type == SILC_BACKUP_ROUTER) {
3182 server->server_type = SILC_ROUTER;
3184 /* We'll need to constantly try to reconnect to the primary
3185 router so that we'll see when it comes back online. */
3186 silc_server_backup_reconnect(server, sock->ip, sock->port,
3187 silc_server_backup_connected,
3191 /* Mark this connection as replaced */
3192 silc_server_backup_replaced_add(server, user_data->id,
3195 } else if (backup_router) {
3196 SILC_LOG_INFO(("Enabling the use of backup router %s",
3197 backup_router->server_name));
3198 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
3199 backup_router->server_name));
3201 /* Mark this connection as replaced */
3202 silc_server_backup_replaced_add(server, user_data->id,
3204 } else if (server->server_type == SILC_SERVER &&
3205 sock->type == SILC_SOCKET_TYPE_ROUTER) {
3206 /* Reconnect to the router (backup) */
3207 silc_schedule_task_add(server->schedule, 0,
3208 silc_server_connect_to_router,
3211 SILC_TASK_PRI_NORMAL);
3214 if (!backup_router) {
3215 /* Remove all servers that are originated from this server, and
3216 remove the clients of those servers too. */
3217 silc_server_remove_servers_by_server(server, user_data, TRUE);
3219 /* Remove the clients that this server owns as they will become
3220 invalid now too. For backup router the server is actually
3221 coming from the primary router, so mark that as the owner
3223 if (server->server_type == SILC_BACKUP_ROUTER &&
3224 sock->type == SILC_SOCKET_TYPE_SERVER)
3225 silc_server_remove_clients_by_server(server, server->router,
3228 silc_server_remove_clients_by_server(server, user_data,
3231 /* Remove channels owned by this server */
3232 if (server->server_type == SILC_SERVER)
3233 silc_server_remove_channels_by_server(server, user_data);
3235 /* Enable local server connections that may be disabled */
3236 silc_server_local_servers_toggle_enabled(server, TRUE);
3238 /* Update the client entries of this server to the new backup
3239 router. If we are the backup router we also resolve the real
3240 servers for the clients. After updating is over this also
3241 removes the clients that this server explicitly owns. */
3242 silc_server_update_clients_by_server(server, user_data,
3243 backup_router, TRUE);
3245 /* If we are router and just lost our primary router (now standlaone)
3246 we remove everything that was behind it, since we don't know
3248 if (server->server_type == SILC_ROUTER && server->standalone)
3249 /* Remove all servers that are originated from this server, and
3250 remove the clients of those servers too. */
3251 silc_server_remove_servers_by_server(server, user_data, TRUE);
3253 /* Finally remove the clients that are explicitly owned by this
3254 server. They go down with the server. */
3255 silc_server_remove_clients_by_server(server, user_data,
3258 /* Update our server cache to use the new backup router too. */
3259 silc_server_update_servers_by_server(server, user_data, backup_router);
3260 if (server->server_type == SILC_SERVER)
3261 silc_server_update_channels_by_server(server, user_data,
3264 /* Send notify about primary router going down to local operators */
3265 if (server->backup_router)
3266 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3267 SILC_NOTIFY_TYPE_NONE,
3268 ("%s switched to backup router %s "
3269 "(we are primary router now)",
3270 server->server_name, server->server_name));
3271 else if (server->router)
3272 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3273 SILC_NOTIFY_TYPE_NONE,
3274 ("%s switched to backup router %s",
3275 server->server_name,
3276 server->router->server_name));
3278 server->backup_noswitch = FALSE;
3280 /* Free the server entry */
3281 silc_server_backup_del(server, user_data);
3282 silc_server_backup_replaced_del(server, user_data);
3283 silc_idlist_del_data(user_data);
3284 if (!silc_idlist_del_server(server->local_list, user_data))
3285 silc_idlist_del_server(server->global_list, user_data);
3286 if (sock->type == SILC_SOCKET_TYPE_SERVER) {
3287 server->stat.my_servers--;
3289 server->stat.my_routers--;
3290 server->stat.routers--;
3292 server->stat.servers--;
3293 if (server->server_type == SILC_ROUTER)
3294 server->stat.cell_servers--;
3296 if (backup_router && backup_router != server->id_entry) {
3297 /* Announce all of our stuff that was created about 5 minutes ago.
3298 The backup router knows all the other stuff already. */
3299 if (server->server_type == SILC_ROUTER)
3300 silc_server_announce_servers(server, FALSE, time(0) - 300,
3301 backup_router->connection);
3303 /* Announce our clients and channels to the router */
3304 silc_server_announce_clients(server, time(0) - 300,
3305 backup_router->connection);
3306 silc_server_announce_channels(server, time(0) - 300,
3307 backup_router->connection);
3313 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
3315 SILC_LOG_DEBUG(("Freeing unknown connection data"));
3317 silc_idlist_del_data(user_data);
3318 silc_free(user_data);
3323 /* If any protocol is active cancel its execution */
3324 if (sock->protocol) {
3325 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3326 silc_protocol_cancel(sock->protocol, server->schedule);
3327 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3328 silc_protocol_execute_final(sock->protocol, server->schedule);
3329 sock->protocol = NULL;
3332 sock->user_data = NULL;
3335 /* Removes client from all channels it has joined. This is used when client
3336 connection is disconnected. If the client on a channel is last, the
3337 channel is removed as well. This sends the SIGNOFF notify types. */
3339 void silc_server_remove_from_channels(SilcServer server,
3340 SilcSocketConnection sock,
3341 SilcClientEntry client,
3343 const char *signoff_message,
3346 SilcChannelEntry channel;
3347 SilcChannelClientEntry chl;
3348 SilcHashTableList htl;
3349 SilcBuffer clidp = NULL;
3354 SILC_LOG_DEBUG(("Removing client from joined channels"));
3356 if (notify && !client->id)
3360 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3365 /* Remove the client from all channels. The client is removed from
3366 the channels' user list. */
3367 silc_hash_table_list(client->channels, &htl);
3368 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3369 channel = chl->channel;
3371 /* Remove channel if this is last client leaving the channel, unless
3372 the channel is permanent. */
3373 if (server->server_type != SILC_SERVER &&
3374 silc_hash_table_count(channel->user_list) < 2) {
3375 silc_server_channel_delete(server, channel);
3379 silc_hash_table_del(client->channels, channel);
3380 silc_hash_table_del(channel->user_list, client);
3381 channel->user_count--;
3383 /* If there is no global users on the channel anymore mark the channel
3384 as local channel. Do not check if the removed client is local client. */
3385 if (server->server_type == SILC_SERVER && channel->global_users &&
3386 chl->client->router && !silc_server_channel_has_global(channel))
3387 channel->global_users = FALSE;
3389 memset(chl, 'A', sizeof(*chl));
3392 /* Update statistics */
3393 if (SILC_IS_LOCAL(client))
3394 server->stat.my_chanclients--;
3395 if (server->server_type == SILC_ROUTER) {
3396 server->stat.cell_chanclients--;
3397 server->stat.chanclients--;
3400 /* If there is not at least one local user on the channel then we don't
3401 need the channel entry anymore, we can remove it safely, unless the
3402 channel is permanent channel */
3403 if (server->server_type == SILC_SERVER &&
3404 !silc_server_channel_has_local(channel)) {
3405 /* Notify about leaving client if this channel has global users. */
3406 if (notify && channel->global_users)
3407 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3408 SILC_NOTIFY_TYPE_SIGNOFF,
3409 signoff_message ? 2 : 1,
3410 clidp->data, clidp->len,
3411 signoff_message, signoff_message ?
3412 strlen(signoff_message) : 0);
3414 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3415 silc_server_channel_delete(server, channel);
3419 /* Send notify to channel about client leaving SILC and channel too */
3421 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3422 SILC_NOTIFY_TYPE_SIGNOFF,
3423 signoff_message ? 2 : 1,
3424 clidp->data, clidp->len,
3425 signoff_message, signoff_message ?
3426 strlen(signoff_message) : 0);
3428 /* Don't create keys if we are shutting down */
3429 if (server->server_shutdown)
3432 /* Re-generate channel key if needed */
3433 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3434 if (!silc_server_create_channel_key(server, channel, 0))
3437 /* Send the channel key to the channel. The key of course is not sent
3438 to the client who was removed from the channel. */
3439 silc_server_send_channel_key(server, client->connection, channel,
3440 server->server_type == SILC_ROUTER ?
3441 FALSE : !server->standalone);
3445 silc_hash_table_list_reset(&htl);
3447 silc_buffer_free(clidp);
3450 /* Removes client from one channel. This is used for example when client
3451 calls LEAVE command to remove itself from the channel. Returns TRUE
3452 if channel still exists and FALSE if the channel is removed when
3453 last client leaves the channel. If `notify' is FALSE notify messages
3456 bool silc_server_remove_from_one_channel(SilcServer server,
3457 SilcSocketConnection sock,
3458 SilcChannelEntry channel,
3459 SilcClientEntry client,
3462 SilcChannelClientEntry chl;
3465 SILC_LOG_DEBUG(("Removing %s from channel %s",
3466 silc_id_render(client->id, SILC_ID_CLIENT),
3467 channel->channel_name));
3469 /* Get the entry to the channel, if this client is not on the channel
3471 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
3474 /* Remove channel if this is last client leaving the channel, unless
3475 the channel is permanent. */
3476 if (server->server_type != SILC_SERVER &&
3477 silc_hash_table_count(channel->user_list) < 2) {
3478 silc_server_channel_delete(server, channel);
3482 silc_hash_table_del(client->channels, channel);
3483 silc_hash_table_del(channel->user_list, client);
3484 channel->user_count--;
3486 /* If there is no global users on the channel anymore mark the channel
3487 as local channel. Do not check if the client is local client. */
3488 if (server->server_type == SILC_SERVER && channel->global_users &&
3489 chl->client->router && !silc_server_channel_has_global(channel))
3490 channel->global_users = FALSE;
3492 memset(chl, 'O', sizeof(*chl));
3495 /* Update statistics */
3496 if (SILC_IS_LOCAL(client))
3497 server->stat.my_chanclients--;
3498 if (server->server_type == SILC_ROUTER) {
3499 server->stat.cell_chanclients--;
3500 server->stat.chanclients--;
3503 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3507 /* If there is not at least one local user on the channel then we don't
3508 need the channel entry anymore, we can remove it safely, unless the
3509 channel is permanent channel */
3510 if (server->server_type == SILC_SERVER &&
3511 !silc_server_channel_has_local(channel)) {
3512 /* Notify about leaving client if this channel has global users. */
3513 if (notify && channel->global_users)
3514 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3515 SILC_NOTIFY_TYPE_LEAVE, 1,
3516 clidp->data, clidp->len);
3518 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3519 silc_server_channel_delete(server, channel);
3520 silc_buffer_free(clidp);
3524 /* Send notify to channel about client leaving the channel */
3526 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3527 SILC_NOTIFY_TYPE_LEAVE, 1,
3528 clidp->data, clidp->len);
3530 silc_buffer_free(clidp);
3534 /* Timeout callback. This is called if connection is idle or for some
3535 other reason is not responding within some period of time. This
3536 disconnects the remote end. */
3538 SILC_TASK_CALLBACK(silc_server_timeout_remote)
3540 SilcServer server = (SilcServer)context;
3541 SilcSocketConnection sock = server->sockets[fd];
3542 SilcProtocolType protocol = 0;
3544 SILC_LOG_DEBUG(("Start"));
3549 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
3550 sock->hostname, sock->ip));
3552 /* If we have protocol active we must assure that we call the protocol's
3553 final callback so that all the memory is freed. */
3554 if (sock->protocol) {
3555 protocol = sock->protocol->protocol->type;
3556 silc_protocol_cancel(sock->protocol, server->schedule);
3557 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3558 silc_protocol_execute_final(sock->protocol, server->schedule);
3559 sock->protocol = NULL;
3563 silc_server_disconnect_remote(server, sock,
3565 SILC_PROTOCOL_SERVER_CONNECTION_AUTH ?
3566 SILC_STATUS_ERR_AUTH_FAILED :
3567 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
3568 "Connection timeout");
3570 if (sock->user_data)
3571 silc_server_free_sock_user_data(server, sock, NULL);
3574 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
3575 function may be used only by router. In real SILC network all channels
3576 are created by routers thus this function is never used by normal
3579 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3580 SilcServerID *router_id,
3586 SilcChannelID *channel_id;
3587 SilcChannelEntry entry;
3591 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3594 cipher = SILC_DEFAULT_CIPHER;
3596 hmac = SILC_DEFAULT_HMAC;
3598 /* Allocate cipher */
3599 if (!silc_cipher_alloc(cipher, &key))
3603 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3604 silc_cipher_free(key);
3608 channel_name = strdup(channel_name);
3610 /* Create the channel ID */
3611 if (!silc_id_create_channel_id(server, router_id, server->rng,
3613 silc_free(channel_name);
3614 silc_cipher_free(key);
3615 silc_hmac_free(newhmac);
3619 /* Create the channel */
3620 entry = silc_idlist_add_channel(server->local_list, channel_name,
3621 SILC_CHANNEL_MODE_NONE, channel_id,
3622 NULL, key, newhmac, 0);
3624 silc_free(channel_name);
3625 silc_cipher_free(key);
3626 silc_hmac_free(newhmac);
3627 silc_free(channel_id);
3631 entry->cipher = strdup(cipher);
3632 entry->hmac_name = strdup(hmac);
3634 /* Now create the actual key material */
3635 if (!silc_server_create_channel_key(server, entry,
3636 silc_cipher_get_key_len(key) / 8)) {
3637 silc_idlist_del_channel(server->local_list, entry);
3641 /* Notify other routers about the new channel. We send the packet
3642 to our primary route. */
3644 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3645 channel_name, entry->id,
3646 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3649 /* Distribute to backup routers */
3650 if (broadcast && server->server_type == SILC_ROUTER) {
3653 SilcUInt32 name_len = strlen(channel_name);
3654 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3655 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3657 packet = silc_channel_payload_encode(channel_name, name_len,
3658 cid, channel_id_len, entry->mode);
3659 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3660 packet->data, packet->len, FALSE, TRUE);
3662 silc_buffer_free(packet);
3665 server->stat.my_channels++;
3666 if (server->server_type == SILC_ROUTER) {
3667 server->stat.channels++;
3668 server->stat.cell_channels++;
3669 entry->users_resolved = TRUE;
3675 /* Same as above but creates the channel with Channel ID `channel_id. */
3678 silc_server_create_new_channel_with_id(SilcServer server,
3682 SilcChannelID *channel_id,
3685 SilcChannelEntry entry;
3689 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3692 cipher = SILC_DEFAULT_CIPHER;
3694 hmac = SILC_DEFAULT_HMAC;
3696 /* Allocate cipher */
3697 if (!silc_cipher_alloc(cipher, &key))
3701 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3702 silc_cipher_free(key);
3706 channel_name = strdup(channel_name);
3708 /* Create the channel */
3709 entry = silc_idlist_add_channel(server->local_list, channel_name,
3710 SILC_CHANNEL_MODE_NONE, channel_id,
3711 NULL, key, newhmac, 0);
3713 silc_cipher_free(key);
3714 silc_hmac_free(newhmac);
3715 silc_free(channel_name);
3719 /* Now create the actual key material */
3720 if (!silc_server_create_channel_key(server, entry,
3721 silc_cipher_get_key_len(key) / 8)) {
3722 silc_idlist_del_channel(server->local_list, entry);
3726 /* Notify other routers about the new channel. We send the packet
3727 to our primary route. */
3729 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3730 channel_name, entry->id,
3731 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3734 /* Distribute to backup routers */
3735 if (broadcast && server->server_type == SILC_ROUTER) {
3738 SilcUInt32 name_len = strlen(channel_name);
3739 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3740 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3742 packet = silc_channel_payload_encode(channel_name, name_len,
3743 cid, channel_id_len, entry->mode);
3744 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3745 packet->data, packet->len, FALSE, TRUE);
3747 silc_buffer_free(packet);
3750 server->stat.my_channels++;
3751 if (server->server_type == SILC_ROUTER) {
3752 server->stat.channels++;
3753 server->stat.cell_channels++;
3754 entry->users_resolved = TRUE;
3760 /* Channel's key re-key timeout callback. */
3762 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3764 SilcServer server = app_context;
3765 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3769 /* Return now if we are shutting down */
3770 if (server->server_shutdown)
3773 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3776 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3779 /* Generates new channel key. This is used to create the initial channel key
3780 but also to re-generate new key for channel. If `key_len' is provided
3781 it is the bytes of the key length. */
3783 bool silc_server_create_channel_key(SilcServer server,
3784 SilcChannelEntry channel,
3788 unsigned char channel_key[32], hash[32];
3791 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3792 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3796 SILC_LOG_DEBUG(("Generating channel %s key", channel->channel_name));
3798 if (!channel->channel_key)
3799 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3800 channel->channel_key = NULL;
3806 else if (channel->key_len)
3807 len = channel->key_len / 8;
3809 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3811 /* Create channel key */
3812 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3815 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3817 /* Remove old key if exists */
3819 memset(channel->key, 0, channel->key_len / 8);
3820 silc_free(channel->key);
3824 channel->key_len = len * 8;
3825 channel->key = silc_memdup(channel_key, len);
3826 memset(channel_key, 0, sizeof(channel_key));
3828 /* Generate HMAC key from the channel key data and set it */
3830 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3831 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3832 silc_hmac_set_key(channel->hmac, hash,
3833 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3834 memset(hash, 0, sizeof(hash));
3836 if (server->server_type == SILC_ROUTER) {
3837 if (!channel->rekey)
3838 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3839 channel->rekey->channel = channel;
3840 channel->rekey->key_len = key_len;
3841 if (channel->rekey->task)
3842 silc_schedule_task_del(server->schedule, channel->rekey->task);
3844 channel->rekey->task =
3845 silc_schedule_task_add(server->schedule, 0,
3846 silc_server_channel_key_rekey,
3847 (void *)channel->rekey,
3848 server->config->channel_rekey_secs, 0,
3850 SILC_TASK_PRI_NORMAL);
3856 /* Saves the channel key found in the encoded `key_payload' buffer. This
3857 function is used when we receive Channel Key Payload and also when we're
3858 processing JOIN command reply. Returns entry to the channel. */
3860 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3861 SilcBuffer key_payload,
3862 SilcChannelEntry channel)
3864 SilcChannelKeyPayload payload = NULL;
3865 SilcChannelID *id = NULL;
3866 unsigned char *tmp, hash[32];
3870 /* Decode channel key payload */
3871 payload = silc_channel_key_payload_parse(key_payload->data,
3874 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3879 /* Get the channel entry */
3882 /* Get channel ID */
3883 tmp = silc_channel_key_get_id(payload, &tmp_len);
3884 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3890 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3892 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3894 if (server->server_type == SILC_ROUTER)
3895 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3896 silc_id_render(id, SILC_ID_CHANNEL)));
3902 SILC_LOG_DEBUG(("Saving new channel %s key", channel->channel_name));
3904 tmp = silc_channel_key_get_key(payload, &tmp_len);
3910 cipher = silc_channel_key_get_cipher(payload, NULL);
3916 /* Remove old key if exists */
3918 memset(channel->key, 0, channel->key_len / 8);
3919 silc_free(channel->key);
3920 silc_cipher_free(channel->channel_key);
3923 /* Create new cipher */
3924 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3925 channel->channel_key = NULL;
3930 if (channel->cipher)
3931 silc_free(channel->cipher);
3932 channel->cipher = strdup(cipher);
3935 channel->key_len = tmp_len * 8;
3936 channel->key = silc_memdup(tmp, tmp_len);
3937 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3939 /* Generate HMAC key from the channel key data and set it */
3941 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3942 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3943 silc_hmac_set_key(channel->hmac, hash,
3944 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3946 memset(hash, 0, sizeof(hash));
3947 memset(tmp, 0, tmp_len);
3949 if (server->server_type == SILC_ROUTER) {
3950 if (!channel->rekey)
3951 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3952 channel->rekey->channel = channel;
3953 if (channel->rekey->task)
3954 silc_schedule_task_del(server->schedule, channel->rekey->task);
3956 channel->rekey->task =
3957 silc_schedule_task_add(server->schedule, 0,
3958 silc_server_channel_key_rekey,
3959 (void *)channel->rekey,
3960 server->config->channel_rekey_secs, 0,
3962 SILC_TASK_PRI_NORMAL);
3968 silc_channel_key_payload_free(payload);
3973 /* Heartbeat callback. This function is set as argument for the
3974 silc_socket_set_heartbeat function. The library will call this function
3975 at the set time interval. */
3977 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3980 SilcServer server = hb_context;
3982 SILC_LOG_DEBUG(("Sending heartbeat to %s:%d (%s)", sock->hostname,
3983 sock->port, sock->ip));
3985 /* Send the heartbeat */
3986 silc_server_send_heartbeat(server, sock);
3989 /* Returns assembled of all servers in the given ID list. The packet's
3990 form is dictated by the New ID payload. */
3992 static void silc_server_announce_get_servers(SilcServer server,
3993 SilcServerEntry remote,
3995 SilcBuffer *servers,
3996 unsigned long creation_time)
3998 SilcIDCacheList list;
3999 SilcIDCacheEntry id_cache;
4000 SilcServerEntry entry;
4003 /* Go through all clients in the list */
4004 if (silc_idcache_get_all(id_list->servers, &list)) {
4005 if (silc_idcache_list_first(list, &id_cache)) {
4007 entry = (SilcServerEntry)id_cache->context;
4009 /* Do not announce the one we've sending our announcements and
4010 do not announce ourself. Also check the creation time if it's
4012 if ((entry == remote) || (entry == server->id_entry) ||
4013 (creation_time && entry->data.created < creation_time)) {
4014 if (!silc_idcache_list_next(list, &id_cache))
4019 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
4021 *servers = silc_buffer_realloc(*servers,
4023 (*servers)->truelen + idp->len :
4025 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
4026 silc_buffer_put(*servers, idp->data, idp->len);
4027 silc_buffer_pull(*servers, idp->len);
4028 silc_buffer_free(idp);
4030 if (!silc_idcache_list_next(list, &id_cache))
4035 silc_idcache_list_free(list);
4040 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
4046 p = silc_notify_payload_encode(notify, argc, ap);
4052 /* This function is used by router to announce existing servers to our
4053 primary router when we've connected to it. If `creation_time' is non-zero
4054 then only the servers that has been created after the `creation_time'
4055 will be announced. */
4057 void silc_server_announce_servers(SilcServer server, bool global,
4058 unsigned long creation_time,
4059 SilcSocketConnection remote)
4061 SilcBuffer servers = NULL;
4063 SILC_LOG_DEBUG(("Announcing servers"));
4065 /* Get servers in local list */
4066 silc_server_announce_get_servers(server, remote->user_data,
4067 server->local_list, &servers,
4071 /* Get servers in global list */
4072 silc_server_announce_get_servers(server, remote->user_data,
4073 server->global_list, &servers,
4077 silc_buffer_push(servers, servers->data - servers->head);
4078 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
4080 /* Send the packet */
4081 silc_server_packet_send(server, remote,
4082 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4083 servers->data, servers->len, TRUE);
4085 silc_buffer_free(servers);
4089 /* Returns assembled packet of all clients in the given ID list. The
4090 packet's form is dictated by the New ID Payload. */
4092 static void silc_server_announce_get_clients(SilcServer server,
4094 SilcBuffer *clients,
4096 unsigned long creation_time)
4098 SilcIDCacheList list;
4099 SilcIDCacheEntry id_cache;
4100 SilcClientEntry client;
4103 unsigned char mode[4];
4105 /* Go through all clients in the list */
4106 if (silc_idcache_get_all(id_list->clients, &list)) {
4107 if (silc_idcache_list_first(list, &id_cache)) {
4109 client = (SilcClientEntry)id_cache->context;
4111 if (creation_time && client->data.created < creation_time) {
4112 if (!silc_idcache_list_next(list, &id_cache))
4116 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED) &&
4117 !client->connection && !client->router && !SILC_IS_LOCAL(client)) {
4118 if (!silc_idcache_list_next(list, &id_cache))
4123 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
4125 *clients = silc_buffer_realloc(*clients,
4127 (*clients)->truelen + idp->len :
4129 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
4130 silc_buffer_put(*clients, idp->data, idp->len);
4131 silc_buffer_pull(*clients, idp->len);
4133 SILC_PUT32_MSB(client->mode, mode);
4135 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
4136 2, idp->data, idp->len,
4138 *umodes = silc_buffer_realloc(*umodes,
4140 (*umodes)->truelen + tmp->len :
4142 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
4143 silc_buffer_put(*umodes, tmp->data, tmp->len);
4144 silc_buffer_pull(*umodes, tmp->len);
4145 silc_buffer_free(tmp);
4147 silc_buffer_free(idp);
4149 if (!silc_idcache_list_next(list, &id_cache))
4154 silc_idcache_list_free(list);
4158 /* This function is used to announce our existing clients to our router
4159 when we've connected to it. If `creation_time' is non-zero then only
4160 the clients that has been created after the `creation_time' will be
4163 void silc_server_announce_clients(SilcServer server,
4164 unsigned long creation_time,
4165 SilcSocketConnection remote)
4167 SilcBuffer clients = NULL;
4168 SilcBuffer umodes = NULL;
4170 SILC_LOG_DEBUG(("Announcing clients"));
4172 /* Get clients in local list */
4173 silc_server_announce_get_clients(server, server->local_list,
4174 &clients, &umodes, creation_time);
4176 /* As router we announce our global list as well */
4177 if (server->server_type == SILC_ROUTER)
4178 silc_server_announce_get_clients(server, server->global_list,
4179 &clients, &umodes, creation_time);
4182 silc_buffer_push(clients, clients->data - clients->head);
4183 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
4185 /* Send the packet */
4186 silc_server_packet_send(server, remote,
4187 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4188 clients->data, clients->len, TRUE);
4190 silc_buffer_free(clients);
4194 silc_buffer_push(umodes, umodes->data - umodes->head);
4195 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
4197 /* Send the packet */
4198 silc_server_packet_send(server, remote,
4199 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4200 umodes->data, umodes->len, TRUE);
4202 silc_buffer_free(umodes);
4206 /* Returns channel's topic for announcing it */
4208 void silc_server_announce_get_channel_topic(SilcServer server,
4209 SilcChannelEntry channel,
4214 if (channel->topic) {
4215 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4216 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
4217 chidp->data, chidp->len,
4219 strlen(channel->topic));
4220 silc_buffer_free(chidp);
4224 /* Returns assembled packets for channel users of the `channel'. */
4226 void silc_server_announce_get_channel_users(SilcServer server,
4227 SilcChannelEntry channel,
4228 SilcBuffer *channel_modes,
4229 SilcBuffer *channel_users,
4230 SilcBuffer *channel_users_modes)
4232 SilcChannelClientEntry chl;
4233 SilcHashTableList htl;
4234 SilcBuffer chidp, clidp, csidp;
4235 SilcBuffer tmp, fkey = NULL;
4237 unsigned char mode[4];
4240 SILC_LOG_DEBUG(("Start"));
4242 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4243 csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4246 SILC_PUT32_MSB(channel->mode, mode);
4247 hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
4248 if (channel->founder_key)
4249 fkey = silc_pkcs_public_key_payload_encode(channel->founder_key);
4251 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
4252 6, csidp->data, csidp->len,
4255 hmac, hmac ? strlen(hmac) : 0,
4256 channel->passphrase,
4257 channel->passphrase ?
4258 strlen(channel->passphrase) : 0,
4259 fkey ? fkey->data : NULL,
4260 fkey ? fkey->len : 0);
4263 silc_buffer_realloc(*channel_modes,
4265 (*channel_modes)->truelen + len : len));
4266 silc_buffer_pull_tail(*channel_modes,
4267 ((*channel_modes)->end -
4268 (*channel_modes)->data));
4269 silc_buffer_put(*channel_modes, tmp->data, tmp->len);
4270 silc_buffer_pull(*channel_modes, len);
4271 silc_buffer_free(tmp);
4272 silc_buffer_free(fkey);
4275 /* Now find all users on the channel */
4276 silc_hash_table_list(channel->user_list, &htl);
4277 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4278 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4281 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
4282 clidp->data, clidp->len,
4283 chidp->data, chidp->len);
4286 silc_buffer_realloc(*channel_users,
4288 (*channel_users)->truelen + len : len));
4289 silc_buffer_pull_tail(*channel_users,
4290 ((*channel_users)->end -
4291 (*channel_users)->data));
4293 silc_buffer_put(*channel_users, tmp->data, tmp->len);
4294 silc_buffer_pull(*channel_users, len);
4295 silc_buffer_free(tmp);
4297 /* CUMODE notify for mode change on the channel */
4298 SILC_PUT32_MSB(chl->mode, mode);
4299 if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
4300 fkey = silc_pkcs_public_key_payload_encode(channel->founder_key);
4301 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
4302 4, csidp->data, csidp->len,
4304 clidp->data, clidp->len,
4305 fkey ? fkey->data : NULL,
4306 fkey ? fkey->len : 0);
4308 *channel_users_modes =
4309 silc_buffer_realloc(*channel_users_modes,
4310 (*channel_users_modes ?
4311 (*channel_users_modes)->truelen + len : len));
4312 silc_buffer_pull_tail(*channel_users_modes,
4313 ((*channel_users_modes)->end -
4314 (*channel_users_modes)->data));
4316 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
4317 silc_buffer_pull(*channel_users_modes, len);
4318 silc_buffer_free(tmp);
4319 silc_buffer_free(fkey);
4321 silc_buffer_free(clidp);
4323 silc_hash_table_list_reset(&htl);
4324 silc_buffer_free(chidp);
4325 silc_buffer_free(csidp);
4328 /* Returns assembled packets for all channels and users on those channels
4329 from the given ID List. The packets are in the form dictated by the
4330 New Channel and New Channel User payloads. */
4332 void silc_server_announce_get_channels(SilcServer server,
4334 SilcBuffer *channels,
4335 SilcBuffer **channel_modes,
4336 SilcBuffer *channel_users,
4337 SilcBuffer **channel_users_modes,
4338 SilcUInt32 *channel_users_modes_c,
4339 SilcBuffer **channel_topics,
4340 SilcChannelID ***channel_ids,
4341 unsigned long creation_time)
4343 SilcIDCacheList list;
4344 SilcIDCacheEntry id_cache;
4345 SilcChannelEntry channel;
4348 SilcUInt16 name_len;
4350 int i = *channel_users_modes_c;
4353 SILC_LOG_DEBUG(("Start"));
4355 /* Go through all channels in the list */
4356 if (silc_idcache_get_all(id_list->channels, &list)) {
4357 if (silc_idcache_list_first(list, &id_cache)) {
4359 channel = (SilcChannelEntry)id_cache->context;
4361 if (creation_time && channel->created < creation_time)
4366 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4367 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4368 name_len = strlen(channel->channel_name);
4371 len = 4 + name_len + id_len + 4;
4373 silc_buffer_realloc(*channels,
4374 (*channels ? (*channels)->truelen +
4376 silc_buffer_pull_tail(*channels,
4377 ((*channels)->end - (*channels)->data));
4378 silc_buffer_format(*channels,
4379 SILC_STR_UI_SHORT(name_len),
4380 SILC_STR_UI_XNSTRING(channel->channel_name,
4382 SILC_STR_UI_SHORT(id_len),
4383 SILC_STR_UI_XNSTRING(cid, id_len),
4384 SILC_STR_UI_INT(channel->mode),
4386 silc_buffer_pull(*channels, len);
4389 if (creation_time && channel->updated < creation_time)
4395 /* Channel user modes */
4396 *channel_users_modes = silc_realloc(*channel_users_modes,
4397 sizeof(**channel_users_modes) *
4399 (*channel_users_modes)[i] = NULL;
4400 *channel_modes = silc_realloc(*channel_modes,
4401 sizeof(**channel_modes) * (i + 1));
4402 (*channel_modes)[i] = NULL;
4403 *channel_ids = silc_realloc(*channel_ids,
4404 sizeof(**channel_ids) * (i + 1));
4405 (*channel_ids)[i] = NULL;
4406 silc_server_announce_get_channel_users(server, channel,
4407 &(*channel_modes)[i],
4409 &(*channel_users_modes)[i]);
4410 (*channel_ids)[i] = channel->id;
4412 /* Channel's topic */
4413 *channel_topics = silc_realloc(*channel_topics,
4414 sizeof(**channel_topics) * (i + 1));
4415 (*channel_topics)[i] = NULL;
4416 silc_server_announce_get_channel_topic(server, channel,
4417 &(*channel_topics)[i]);
4418 (*channel_users_modes_c)++;
4425 if (!silc_idcache_list_next(list, &id_cache))
4430 silc_idcache_list_free(list);
4434 /* This function is used to announce our existing channels to our router
4435 when we've connected to it. This also announces the users on the
4436 channels to the router. If the `creation_time' is non-zero only the
4437 channels that was created after the `creation_time' are announced.
4438 Note that the channel users are still announced even if the `creation_time'
4441 void silc_server_announce_channels(SilcServer server,
4442 unsigned long creation_time,
4443 SilcSocketConnection remote)
4445 SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
4446 SilcBuffer *channel_users_modes = NULL;
4447 SilcBuffer *channel_topics = NULL;
4448 SilcUInt32 channel_users_modes_c = 0;
4449 SilcChannelID **channel_ids = NULL;
4451 SILC_LOG_DEBUG(("Announcing channels and channel users"));
4453 /* Get channels and channel users in local list */
4454 silc_server_announce_get_channels(server, server->local_list,
4455 &channels, &channel_modes,
4457 &channel_users_modes,
4458 &channel_users_modes_c,
4460 &channel_ids, creation_time);
4462 /* Get channels and channel users in global list */
4463 if (server->server_type != SILC_SERVER)
4464 silc_server_announce_get_channels(server, server->global_list,
4465 &channels, &channel_modes,
4467 &channel_users_modes,
4468 &channel_users_modes_c,
4470 &channel_ids, creation_time);
4473 silc_buffer_push(channels, channels->data - channels->head);
4474 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
4476 /* Send the packet */
4477 silc_server_packet_send(server, remote,
4478 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
4479 channels->data, channels->len,
4482 silc_buffer_free(channels);
4485 if (channel_users) {
4486 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
4487 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
4488 channel_users->len);
4490 /* Send the packet */
4491 silc_server_packet_send(server, remote,
4492 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4493 channel_users->data, channel_users->len,
4496 silc_buffer_free(channel_users);
4499 if (channel_modes) {
4502 for (i = 0; i < channel_users_modes_c; i++) {
4503 if (!channel_modes[i])
4505 silc_buffer_push(channel_modes[i],
4506 channel_modes[i]->data -
4507 channel_modes[i]->head);
4508 SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
4509 channel_modes[i]->len);
4510 silc_server_packet_send_dest(server, remote,
4511 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4512 channel_ids[i], SILC_ID_CHANNEL,
4513 channel_modes[i]->data,
4514 channel_modes[i]->len,
4516 silc_buffer_free(channel_modes[i]);
4518 silc_free(channel_modes);
4521 if (channel_users_modes) {
4524 for (i = 0; i < channel_users_modes_c; i++) {
4525 if (!channel_users_modes[i])
4527 silc_buffer_push(channel_users_modes[i],
4528 channel_users_modes[i]->data -
4529 channel_users_modes[i]->head);
4530 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
4531 channel_users_modes[i]->len);
4532 silc_server_packet_send_dest(server, remote,
4533 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4534 channel_ids[i], SILC_ID_CHANNEL,
4535 channel_users_modes[i]->data,
4536 channel_users_modes[i]->len,
4538 silc_buffer_free(channel_users_modes[i]);
4540 silc_free(channel_users_modes);
4543 if (channel_topics) {
4546 for (i = 0; i < channel_users_modes_c; i++) {
4547 if (!channel_topics[i])
4550 silc_buffer_push(channel_topics[i],
4551 channel_topics[i]->data -
4552 channel_topics[i]->head);
4553 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
4554 channel_topics[i]->len);
4555 silc_server_packet_send_dest(server, remote,
4556 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4557 channel_ids[i], SILC_ID_CHANNEL,
4558 channel_topics[i]->data,
4559 channel_topics[i]->len,
4561 silc_buffer_free(channel_topics[i]);
4563 silc_free(channel_topics);
4566 silc_free(channel_ids);
4569 /* Failure timeout callback. If this is called then we will immediately
4570 process the received failure. We always process the failure with timeout
4571 since we do not want to blindly trust to received failure packets.
4572 This won't be called (the timeout is cancelled) if the failure was
4573 bogus (it is bogus if remote does not close the connection after sending
4576 SILC_TASK_CALLBACK(silc_server_failure_callback)
4578 SilcServer server = app_context;
4579 SilcServerFailureContext f = (SilcServerFailureContext)context;
4581 if (f->sock->protocol) {
4582 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
4583 silc_protocol_execute(f->sock->protocol, server->schedule, 0, 0);
4586 silc_socket_free(f->sock);
4590 /* Assembles user list and users mode list from the `channel'. */
4592 bool silc_server_get_users_on_channel(SilcServer server,
4593 SilcChannelEntry channel,
4594 SilcBuffer *user_list,
4595 SilcBuffer *mode_list,
4596 SilcUInt32 *user_count)
4598 SilcChannelClientEntry chl;
4599 SilcHashTableList htl;
4600 SilcBuffer client_id_list;
4601 SilcBuffer client_mode_list;
4603 SilcUInt32 list_count = 0, len = 0;
4605 if (!silc_hash_table_count(channel->user_list))
4608 silc_hash_table_list(channel->user_list, &htl);
4609 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4610 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
4611 silc_hash_table_list_reset(&htl);
4613 client_id_list = silc_buffer_alloc(len);
4615 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
4616 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
4617 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
4619 silc_hash_table_list(channel->user_list, &htl);
4620 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4622 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4623 silc_buffer_put(client_id_list, idp->data, idp->len);
4624 silc_buffer_pull(client_id_list, idp->len);
4625 silc_buffer_free(idp);
4627 /* Client's mode on channel */
4628 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
4629 silc_buffer_pull(client_mode_list, 4);
4633 silc_hash_table_list_reset(&htl);
4634 silc_buffer_push(client_id_list,
4635 client_id_list->data - client_id_list->head);
4636 silc_buffer_push(client_mode_list,
4637 client_mode_list->data - client_mode_list->head);
4639 *user_list = client_id_list;
4640 *mode_list = client_mode_list;
4641 *user_count = list_count;
4645 /* Saves users and their modes to the `channel'. */
4647 void silc_server_save_users_on_channel(SilcServer server,
4648 SilcSocketConnection sock,
4649 SilcChannelEntry channel,
4650 SilcClientID *noadd,
4651 SilcBuffer user_list,
4652 SilcBuffer mode_list,
4653 SilcUInt32 user_count)
4658 SilcClientID *client_id;
4659 SilcClientEntry client;
4660 SilcIDCacheEntry cache;
4661 SilcChannelClientEntry chl;
4663 SILC_LOG_DEBUG(("Saving %d users on %s channel", user_count,
4664 channel->channel_name));
4666 for (i = 0; i < user_count; i++) {
4668 SILC_GET16_MSB(idp_len, user_list->data + 2);
4670 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
4671 silc_buffer_pull(user_list, idp_len);
4676 SILC_GET32_MSB(mode, mode_list->data);
4677 silc_buffer_pull(mode_list, 4);
4679 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
4680 silc_free(client_id);
4686 /* Check if we have this client cached already. */
4687 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4688 server->server_type, &cache);
4690 client = silc_idlist_find_client_by_id(server->global_list,
4691 client_id, server->server_type,
4694 /* If router did not find such Client ID in its lists then this must
4695 be bogus client or some router in the net is buggy. */
4696 if (server->server_type != SILC_SERVER) {
4697 silc_free(client_id);
4701 /* We don't have that client anywhere, add it. The client is added
4702 to global list since server didn't have it in the lists so it must be
4704 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
4705 silc_id_dup(client_id, SILC_ID_CLIENT),
4706 sock->user_data, NULL, 0);
4708 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
4709 silc_free(client_id);
4713 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
4718 silc_free(client_id);
4720 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
4721 SILC_LOG_ERROR(("Attempting to add unregistered client to channel ",
4722 "%s", channel->channel_name));
4726 if (!silc_server_client_on_channel(client, channel, &chl)) {
4727 /* Client was not on the channel, add it. */
4728 chl = silc_calloc(1, sizeof(*chl));
4729 chl->client = client;
4731 chl->channel = channel;
4732 silc_hash_table_add(channel->user_list, chl->client, chl);
4733 silc_hash_table_add(client->channels, chl->channel, chl);
4734 channel->user_count++;
4742 /* Saves channels and channels user modes to the `client'. Removes
4743 the client from those channels that are not sent in the list but
4746 void silc_server_save_user_channels(SilcServer server,
4747 SilcSocketConnection sock,
4748 SilcClientEntry client,
4749 SilcBuffer channels,
4750 SilcBuffer channels_user_modes)
4753 SilcUInt32 *chumodes;
4754 SilcChannelPayload entry;
4755 SilcChannelEntry channel;
4756 SilcChannelID *channel_id;
4757 SilcChannelClientEntry chl;
4758 SilcHashTable ht = NULL;
4759 SilcHashTableList htl;
4763 if (!channels || !channels_user_modes ||
4764 !(client->data.status & SILC_IDLIST_STATUS_REGISTERED))
4767 ch = silc_channel_payload_parse_list(channels->data, channels->len);
4768 if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
4770 ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL,
4771 NULL, NULL, NULL, TRUE);
4772 silc_dlist_start(ch);
4773 while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
4774 /* Check if we have this channel, and add it if we don't have it.
4775 Also add the client on the channel unless it is there already. */
4776 channel_id = silc_channel_get_id_parse(entry);
4777 channel = silc_idlist_find_channel_by_id(server->local_list,
4780 channel = silc_idlist_find_channel_by_id(server->global_list,
4783 if (server->server_type != SILC_SERVER) {
4784 silc_free(channel_id);
4789 /* We don't have that channel anywhere, add it. */
4790 name = silc_channel_get_name(entry, NULL);
4791 channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
4792 channel_id, server->router,
4795 silc_free(channel_id);
4802 channel->mode = silc_channel_get_mode(entry);
4804 /* Add the client on the channel */
4805 if (!silc_server_client_on_channel(client, channel, &chl)) {
4806 chl = silc_calloc(1, sizeof(*chl));
4807 chl->client = client;
4808 chl->mode = chumodes[i++];
4809 chl->channel = channel;
4810 silc_hash_table_add(channel->user_list, chl->client, chl);
4811 silc_hash_table_add(client->channels, chl->channel, chl);
4812 channel->user_count++;
4815 chl->mode = chumodes[i++];
4818 silc_hash_table_add(ht, channel, channel);
4819 silc_free(channel_id);
4821 silc_channel_payload_list_free(ch);
4822 silc_free(chumodes);
4826 /* Go through the list again and remove client from channels that
4827 are no part of the list. */
4829 silc_hash_table_list(client->channels, &htl);
4830 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4831 if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
4832 silc_hash_table_del(chl->channel->user_list, chl->client);
4833 silc_hash_table_del(chl->client->channels, chl->channel);
4837 silc_hash_table_list_reset(&htl);
4838 silc_hash_table_free(ht);
4840 silc_hash_table_list(client->channels, &htl);
4841 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4842 silc_hash_table_del(chl->channel->user_list, chl->client);
4843 silc_hash_table_del(chl->client->channels, chl->channel);
4846 silc_hash_table_list_reset(&htl);
4850 /* Lookups route to the client indicated by the `id_data'. The connection
4851 object and internal data object is returned. Returns NULL if route
4852 could not be found to the client. If the `client_id' is specified then
4853 it is used and the `id_data' is ignored. */
4855 SilcSocketConnection
4856 silc_server_get_client_route(SilcServer server,
4857 unsigned char *id_data,
4859 SilcClientID *client_id,
4860 SilcIDListData *idata,
4861 SilcClientEntry *client_entry)
4864 SilcClientEntry client;
4866 SILC_LOG_DEBUG(("Start"));
4869 *client_entry = NULL;
4871 /* Decode destination Client ID */
4873 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
4875 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
4879 id = silc_id_dup(client_id, SILC_ID_CLIENT);
4882 /* If the destination belongs to our server we don't have to route
4883 the packet anywhere but to send it to the local destination. */
4884 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
4888 /* If we are router and the client has router then the client is in
4889 our cell but not directly connected to us. */
4890 if (server->server_type == SILC_ROUTER && client->router) {
4891 /* We are of course in this case the client's router thus the route
4892 to the client is the server who owns the client. So, we will send
4893 the packet to that server. */
4895 *idata = (SilcIDListData)client->router;
4896 return client->router->connection;
4899 /* Seems that client really is directly connected to us */
4901 *idata = (SilcIDListData)client;
4903 *client_entry = client;
4904 return client->connection;
4907 /* Destination belongs to someone not in this server. If we are normal
4908 server our action is to send the packet to our router. */
4909 if (server->server_type != SILC_ROUTER && !server->standalone) {
4912 *idata = (SilcIDListData)server->router;
4913 return SILC_PRIMARY_ROUTE(server);
4916 /* We are router and we will perform route lookup for the destination
4917 and send the packet to fastest route. */
4918 if (server->server_type == SILC_ROUTER && !server->standalone) {
4919 /* Check first that the ID is valid */
4920 client = silc_idlist_find_client_by_id(server->global_list, id,
4923 SilcSocketConnection dst_sock;
4925 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
4929 *idata = (SilcIDListData)dst_sock->user_data;
4938 /* Encodes and returns channel list of channels the `client' has joined.
4939 Secret channels are not put to the list. */
4941 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
4942 SilcClientEntry client,
4945 SilcBuffer *user_mode_list)
4947 SilcBuffer buffer = NULL;
4948 SilcChannelEntry channel;
4949 SilcChannelClientEntry chl;
4950 SilcHashTableList htl;
4953 SilcUInt16 name_len;
4957 *user_mode_list = NULL;
4959 silc_hash_table_list(client->channels, &htl);
4960 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4961 channel = chl->channel;
4963 if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
4965 if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
4968 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4969 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4970 name_len = strlen(channel->channel_name);
4972 len = 4 + name_len + id_len + 4;
4973 buffer = silc_buffer_realloc(buffer,
4974 (buffer ? buffer->truelen + len : len));
4975 silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
4976 silc_buffer_format(buffer,
4977 SILC_STR_UI_SHORT(name_len),
4978 SILC_STR_UI_XNSTRING(channel->channel_name,
4980 SILC_STR_UI_SHORT(id_len),
4981 SILC_STR_UI_XNSTRING(cid, id_len),
4982 SILC_STR_UI_INT(chl->channel->mode),
4984 silc_buffer_pull(buffer, len);
4987 if (user_mode_list) {
4988 *user_mode_list = silc_buffer_realloc(*user_mode_list,
4990 (*user_mode_list)->truelen + 4 :
4992 silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
4993 (*user_mode_list)->data));
4994 SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
4995 silc_buffer_pull(*user_mode_list, 4);
4998 silc_hash_table_list_reset(&htl);
5001 silc_buffer_push(buffer, buffer->data - buffer->head);
5002 if (user_mode_list && *user_mode_list)
5003 silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
5004 (*user_mode_list)->head));
5009 /* A timeout callback for the re-key. We will be the initiator of the
5012 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_callback)
5014 SilcServer server = app_context;
5015 SilcSocketConnection sock = (SilcSocketConnection)context;
5016 SilcIDListData idata = (SilcIDListData)sock->user_data;
5017 SilcProtocol protocol;
5018 SilcServerRekeyInternalContext *proto_ctx;
5020 /* Allocate internal protocol context. This is sent as context
5022 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
5023 proto_ctx->server = (void *)server;
5024 proto_ctx->sock = sock;
5025 proto_ctx->responder = FALSE;
5026 proto_ctx->pfs = idata->rekey->pfs;
5028 /* Perform rekey protocol. Will call the final callback after the
5029 protocol is over. */
5030 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
5031 &protocol, proto_ctx, silc_server_rekey_final);
5032 sock->protocol = protocol;
5034 /* Run the protocol */
5035 silc_protocol_execute(protocol, server->schedule, 0, 0);
5037 SILC_LOG_DEBUG(("Rekey protocol completed"));
5039 /* Re-register re-key timeout */
5040 silc_schedule_task_add(server->schedule, sock->sock,
5041 silc_server_rekey_callback,
5042 context, idata->rekey->timeout, 0,
5043 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
5046 /* The final callback for the REKEY protocol. This will actually take the
5047 new key material into use. */
5049 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
5051 SilcProtocol protocol = (SilcProtocol)context;
5052 SilcServerRekeyInternalContext *ctx =
5053 (SilcServerRekeyInternalContext *)protocol->context;
5054 SilcServer server = (SilcServer)ctx->server;
5055 SilcSocketConnection sock = ctx->sock;
5057 SILC_LOG_DEBUG(("Start"));
5059 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
5060 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
5061 /* Error occured during protocol */
5062 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
5063 silc_protocol_cancel(protocol, server->schedule);
5064 silc_protocol_free(protocol);
5065 sock->protocol = NULL;
5067 silc_packet_context_free(ctx->packet);
5069 silc_ske_free(ctx->ske);
5074 /* Purge the outgoing data queue to assure that all rekey packets really
5075 go to the network before we quit the protocol. */
5076 silc_server_packet_queue_purge(server, sock);
5079 silc_protocol_free(protocol);
5080 sock->protocol = NULL;
5082 silc_packet_context_free(ctx->packet);
5084 silc_ske_free(ctx->ske);
5088 /* Task callback used to retrieve network statistical information from
5089 router server once in a while. */
5091 SILC_TASK_CALLBACK(silc_server_get_stats)
5093 SilcServer server = (SilcServer)context;
5094 SilcBuffer idp, packet;
5096 SILC_LOG_DEBUG(("Retrieving stats from router"));
5098 if (!server->standalone) {
5099 idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
5100 packet = silc_command_payload_encode_va(SILC_COMMAND_STATS,
5101 ++server->cmd_ident, 1,
5102 1, idp->data, idp->len);
5103 silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
5104 SILC_PACKET_COMMAND, 0, packet->data,
5105 packet->len, FALSE);
5106 silc_buffer_free(packet);
5107 silc_buffer_free(idp);
5110 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
5111 server, 120, 0, SILC_TASK_TIMEOUT,