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; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
21 * This is the actual SILC server than handles everything relating to
22 * servicing the SILC connections. This is also a SILC router as a router
23 * is also normal server.
27 #include "serverincludes.h"
28 #include "server_internal.h"
30 /* Static prototypes */
31 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry);
32 SILC_TASK_CALLBACK(silc_server_connect_router);
33 SILC_TASK_CALLBACK(silc_server_connect_to_router);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
35 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
38 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
39 SILC_TASK_CALLBACK(silc_server_packet_process);
40 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
41 SILC_TASK_CALLBACK(silc_server_close_connection_final);
42 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout);
43 SILC_TASK_CALLBACK(silc_server_timeout_remote);
44 SILC_TASK_CALLBACK(silc_server_channel_key_rekey);
45 SILC_TASK_CALLBACK(silc_server_failure_callback);
46 SILC_TASK_CALLBACK(silc_server_rekey_callback);
47 SILC_TASK_CALLBACK(silc_server_get_stats);
49 /* Allocates a new SILC server object. This has to be done before the server
50 can be used. After allocation one must call silc_server_init to initialize
51 the server. The new allocated server object is returned to the new_server
54 int silc_server_alloc(SilcServer *new_server)
58 SILC_LOG_DEBUG(("Allocating new server object"));
60 server = silc_calloc(1, sizeof(*server));
61 server->server_type = SILC_SERVER;
62 server->standalone = TRUE;
63 server->local_list = silc_calloc(1, sizeof(*server->local_list));
64 server->global_list = silc_calloc(1, sizeof(*server->global_list));
65 server->pending_commands = silc_dlist_init();
67 server->sim = silc_dlist_init();
75 /* Free's the SILC server object. This is called at the very end before
78 void silc_server_free(SilcServer server)
84 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
85 silc_dlist_del(server->sim, sim);
88 silc_dlist_uninit(server->sim);
91 silc_server_config_unref(&server->config_ref);
93 silc_rng_free(server->rng);
95 silc_pkcs_free(server->pkcs);
96 if (server->public_key)
97 silc_pkcs_public_key_free(server->public_key);
98 if (server->private_key)
99 silc_pkcs_private_key_free(server->private_key);
100 if (server->pending_commands)
101 silc_dlist_uninit(server->pending_commands);
102 if (server->id_entry)
103 silc_idlist_del_server(server->local_list, server->id_entry);
105 silc_idcache_free(server->local_list->clients);
106 silc_idcache_free(server->local_list->servers);
107 silc_idcache_free(server->local_list->channels);
108 silc_idcache_free(server->global_list->clients);
109 silc_idcache_free(server->global_list->servers);
110 silc_idcache_free(server->global_list->channels);
111 silc_hash_table_free(server->watcher_list);
113 silc_free(server->sockets);
118 /* Opens a listening port.
119 XXX This function will become more general and will support multiple
122 static bool silc_server_listen(SilcServer server, const char *server_ip,
123 SilcUInt16 port, int *sock)
125 *sock = silc_net_create_server(port, server_ip);
127 SILC_LOG_ERROR(("Could not create server listener: %s on %hu",
134 /* Adds a secondary listener. */
135 bool silc_server_init_secondary(SilcServer server)
137 int sock=0, sock_list[server->config->param.connections_max];
138 SilcSocketConnection newsocket = NULL;
139 SilcServerConfigServerInfoInterface *interface;
141 for (interface = server->config->server_info->secondary; interface;
142 interface = interface->next, sock++) {
144 if (!silc_server_listen(server,
145 interface->server_ip, interface->port, &sock_list[sock]))
148 /* Set socket to non-blocking mode */
149 silc_net_set_socket_nonblock(sock_list[sock]);
151 /* Add ourselves also to the socket table. The entry allocated above
152 is sent as argument for fast referencing in the future. */
153 silc_socket_alloc(sock_list[sock],
154 SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
155 server->sockets[sock_list[sock]] = newsocket;
157 /* Perform name and address lookups to resolve the listenning address
159 if (!silc_net_check_local_by_sock(sock_list[sock], &newsocket->hostname,
161 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
163 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
164 newsocket->hostname ? newsocket->hostname :
165 newsocket->ip ? newsocket->ip : ""));
166 server->stat.conn_failures++;
169 if (!newsocket->hostname)
170 newsocket->hostname = strdup(newsocket->ip);
172 newsocket->port = silc_net_get_local_port(sock);
174 newsocket->user_data = (void *)server->id_entry;
175 silc_schedule_task_add(server->schedule, sock_list[sock],
176 silc_server_accept_new_connection,
177 (void *)server, 0, 0,
179 SILC_TASK_PRI_NORMAL);
187 do silc_net_close_server(sock_list[sock--]); while (sock >= 0);
192 /* Initializes the entire SILC server. This is called always before running
193 the server. This is called only once at the initialization of the program.
194 This binds the server to its listenning port. After this function returns
195 one should call silc_server_run to start the server. This returns TRUE
196 when everything is ok to run the server. Configuration file must be
197 read and parsed before calling this. */
199 bool silc_server_init(SilcServer server)
203 SilcServerEntry id_entry;
204 SilcIDListPurge purge;
205 SilcSocketConnection newsocket = NULL;
207 SILC_LOG_DEBUG(("Initializing server"));
209 server->starttime = time(NULL);
211 /* Take config object for us */
212 silc_server_config_ref(&server->config_ref, server->config,
215 /* Steal public and private key from the config object */
216 server->public_key = server->config->server_info->public_key;
217 server->private_key = server->config->server_info->private_key;
218 server->config->server_info->public_key = NULL;
219 server->config->server_info->private_key = NULL;
221 /* Register all configured ciphers, PKCS and hash functions. */
222 if (!silc_server_config_register_ciphers(server))
223 silc_cipher_register_default();
224 if (!silc_server_config_register_pkcs(server))
225 silc_pkcs_register_default();
226 if (!silc_server_config_register_hashfuncs(server))
227 silc_hash_register_default();
228 if (!silc_server_config_register_hmacs(server))
229 silc_hmac_register_default();
231 /* Initialize random number generator for the server. */
232 server->rng = silc_rng_alloc();
233 silc_rng_init(server->rng);
234 silc_rng_global_init(server->rng);
236 /* Initialize hash functions for server to use */
237 silc_hash_alloc("md5", &server->md5hash);
238 silc_hash_alloc("sha1", &server->sha1hash);
240 /* Allocate PKCS context for local public and private keys */
241 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
243 silc_pkcs_public_key_set(server->pkcs, server->public_key);
244 silc_pkcs_private_key_set(server->pkcs, server->private_key);
246 /* Initialize the scheduler */
247 server->schedule = silc_schedule_init(server->config->param.connections_max);
248 if (!server->schedule)
251 /* First, register log files configuration for error output */
252 silc_server_config_setlogfiles(server);
254 /* Initialize ID caches */
255 server->local_list->clients =
256 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
257 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
258 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
260 /* These are allocated for normal server as well as these hold some
261 global information that the server has fetched from its router. For
262 router these are used as they are supposed to be used on router. */
263 server->global_list->clients =
264 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
265 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
266 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
268 /* Init watcher list */
269 server->watcher_list =
270 silc_hash_table_alloc(1, silc_hash_client_id_hash, NULL,
271 silc_hash_data_compare, (void *)CLIENTID_HASH_LEN,
273 if (!server->watcher_list)
276 /* Create a listening server */
277 if (!silc_server_listen(server,
278 server->config->server_info->primary == NULL ? NULL :
279 server->config->server_info->primary->server_ip,
280 server->config->server_info->primary == NULL ? 0 :
281 server->config->server_info->primary->port,
285 /* Set socket to non-blocking mode */
286 silc_net_set_socket_nonblock(sock);
289 /* Allocate the entire socket list that is used in server. Eventually
290 all connections will have entry in this table (it is a table of
291 pointers to the actual object that is allocated individually
293 server->sockets = silc_calloc(server->config->param.connections_max,
294 sizeof(*server->sockets));
295 if (!server->sockets)
298 /* Add ourselves also to the socket table. The entry allocated above
299 is sent as argument for fast referencing in the future. */
300 silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
301 server->sockets[sock] = newsocket;
303 /* Perform name and address lookups to resolve the listenning address
305 if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
307 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
309 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
310 newsocket->hostname ? newsocket->hostname :
311 newsocket->ip ? newsocket->ip : ""));
312 server->stat.conn_failures++;
315 if (!newsocket->hostname)
316 newsocket->hostname = strdup(newsocket->ip);
318 newsocket->port = silc_net_get_local_port(sock);
320 /* Create a Server ID for the server. */
321 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
326 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
327 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
328 server->id_type = SILC_ID_SERVER;
329 server->server_name = server->config->server_info->server_name;
330 server->config->server_info->server_name = NULL;
332 /* Add ourselves to the server list. We don't have a router yet
333 beacuse we haven't established a route yet. It will be done later.
334 For now, NULL is sent as router. This allocates new entry to
337 silc_idlist_add_server(server->local_list, strdup(server->server_name),
338 server->server_type, server->id, NULL, NULL);
340 SILC_LOG_ERROR(("Could not add ourselves to cache"));
343 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
345 /* Put the allocated socket pointer also to the entry allocated above
346 for fast back-referencing to the socket list. */
347 newsocket->user_data = (void *)id_entry;
348 id_entry->connection = (void *)newsocket;
349 server->id_entry = id_entry;
351 /* Register protocols */
352 silc_server_protocols_register();
354 /* Add the first task to the scheduler. This is task that is executed by
355 timeout. It expires as soon as the caller calls silc_server_run. This
356 task performs authentication protocol and key exchange with our
358 silc_schedule_task_add(server->schedule, 0,
359 silc_server_connect_to_router,
360 (void *)server, 0, 1,
362 SILC_TASK_PRI_NORMAL);
364 /* Add listener task to the scheduler. This task receives new connections
365 to the server. This task remains on the queue until the end of the
367 silc_schedule_task_add(server->schedule, sock,
368 silc_server_accept_new_connection,
369 (void *)server, 0, 0,
371 SILC_TASK_PRI_NORMAL);
373 if (silc_server_init_secondary(server) == FALSE)
376 server->listenning = TRUE;
378 /* If server connections has been configured then we must be router as
379 normal server cannot have server connections, only router connections. */
380 if (server->config->servers) {
381 SilcServerConfigServer *ptr = server->config->servers;
383 server->server_type = SILC_ROUTER;
385 if (ptr->backup_router) {
386 server->server_type = SILC_BACKUP_ROUTER;
387 server->backup_router = TRUE;
388 server->id_entry->server_type = SILC_BACKUP_ROUTER;
395 /* Register the ID Cache purge task. This periodically purges the ID cache
396 and removes the expired cache entries. */
398 /* Clients local list */
399 purge = silc_calloc(1, sizeof(*purge));
400 purge->cache = server->local_list->clients;
401 purge->schedule = server->schedule;
402 purge->timeout = 600;
403 silc_schedule_task_add(purge->schedule, 0,
405 (void *)purge, purge->timeout, 0,
406 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
408 /* Clients global list */
409 purge = silc_calloc(1, sizeof(*purge));
410 purge->cache = server->global_list->clients;
411 purge->schedule = server->schedule;
412 purge->timeout = 300;
413 silc_schedule_task_add(purge->schedule, 0,
415 (void *)purge, purge->timeout, 0,
416 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
418 /* If we are normal server we'll retrieve network statisticial information
419 once in a while from the router. */
420 if (server->server_type == SILC_SERVER)
421 silc_schedule_task_add(purge->schedule, 0, silc_server_get_stats,
422 server, 10, 0, SILC_TASK_TIMEOUT,
425 if (server->server_type == SILC_ROUTER)
426 server->stat.routers++;
428 SILC_LOG_DEBUG(("Server initialized"));
430 /* We are done here, return succesfully */
434 silc_server_config_unref(&server->config_ref);
435 silc_net_close_server(sock);
439 /* This function basically reads the config file again and switches the config
440 object pointed by the server object. After that, we have to fix various
441 things such as the server_name and the listening ports.
442 Keep in mind that we no longer have the root privileges at this point. */
444 bool silc_server_rehash(SilcServer server)
446 SilcServerConfig newconfig;
448 SILC_LOG_INFO(("Rehashing server"));
450 /* Reset the logging system */
451 silc_log_quick = TRUE;
452 silc_log_flush_all();
454 /* Start the main rehash phase (read again the config file) */
455 newconfig = silc_server_config_alloc(server->config_file);
457 SILC_LOG_ERROR(("Rehash FAILED."));
461 /* Reinit scheduler if necessary */
462 if (newconfig->param.connections_max > server->config->param.connections_max)
463 if (!silc_schedule_reinit(server->schedule,
464 newconfig->param.connections_max))
467 /* Fix the server_name field */
468 if (strcmp(server->server_name, newconfig->server_info->server_name)) {
469 silc_free(server->server_name);
470 server->server_name = newconfig->server_info->server_name;
471 newconfig->server_info->server_name = NULL;
473 /* Update the idcache list with a fresh pointer */
474 silc_free(server->id_entry->server_name);
475 server->id_entry->server_name = strdup(server->server_name);
476 if (!silc_idcache_del_by_context(server->local_list->servers,
479 if (!silc_idcache_add(server->local_list->servers,
480 server->id_entry->server_name,
481 server->id_entry->id, server->id_entry, 0, NULL))
486 silc_server_config_setlogfiles(server);
488 /* Change new key pair if necessary */
489 if (newconfig->server_info->public_key &&
490 !silc_pkcs_public_key_compare(server->public_key,
491 newconfig->server_info->public_key)) {
492 silc_pkcs_public_key_free(server->public_key);
493 silc_pkcs_private_key_free(server->private_key);
494 server->public_key = newconfig->server_info->public_key;
495 server->private_key = newconfig->server_info->private_key;
496 newconfig->server_info->public_key = NULL;
497 newconfig->server_info->private_key = NULL;
499 /* Allocate PKCS context for local public and private keys */
500 silc_pkcs_free(server->pkcs);
501 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
503 silc_pkcs_public_key_set(server->pkcs, server->public_key);
504 silc_pkcs_private_key_set(server->pkcs, server->private_key);
507 /* Go through all configured routers after rehash */
508 silc_schedule_task_add(server->schedule, 0,
509 silc_server_connect_to_router,
510 (void *)server, 0, 1,
512 SILC_TASK_PRI_NORMAL);
514 /* Check whether our router status has changed */
515 if (newconfig->servers) {
516 SilcServerConfigServer *ptr = newconfig->servers;
518 server->server_type = SILC_ROUTER;
520 if (ptr->backup_router) {
521 server->server_type = SILC_BACKUP_ROUTER;
522 server->backup_router = TRUE;
523 server->id_entry->server_type = SILC_BACKUP_ROUTER;
530 /* Our old config is gone now. We'll unreference our reference made in
531 silc_server_init and then destroy it since we are destroying it
532 underneath the application (layer which called silc_server_init). */
533 silc_server_config_unref(&server->config_ref);
534 silc_server_config_destroy(server->config);
536 /* Take new config context */
537 server->config = newconfig;
538 silc_server_config_ref(&server->config_ref, server->config, server->config);
540 SILC_LOG_DEBUG(("Server rehashed"));
545 /* The heart of the server. This runs the scheduler thus runs the server.
546 When this returns the server has been stopped and the program will
549 void silc_server_run(SilcServer server)
551 SILC_LOG_INFO(("SILC Server started"));
553 /* Start the scheduler, the heart of the SILC server. When this returns
554 the program will be terminated. */
555 silc_schedule(server->schedule);
558 /* Stops the SILC server. This function is used to shutdown the server.
559 This is usually called after the scheduler has returned. After stopping
560 the server one should call silc_server_free. */
562 void silc_server_stop(SilcServer server)
564 SILC_LOG_DEBUG(("Stopping server"));
566 if (server->schedule) {
567 silc_schedule_stop(server->schedule);
568 silc_schedule_uninit(server->schedule);
569 server->schedule = NULL;
572 silc_server_protocols_unregister();
574 SILC_LOG_DEBUG(("Server stopped"));
577 /* Function that is called when the network connection to a router has
578 been established. This will continue with the key exchange protocol
579 with the remote router. */
581 void silc_server_start_key_exchange(SilcServer server,
582 SilcServerConnection sconn,
585 SilcSocketConnection newsocket;
586 SilcProtocol protocol;
587 SilcServerKEInternalContext *proto_ctx;
588 SilcServerConfigRouter *conn =
589 (SilcServerConfigRouter *) sconn->conn.ref_ptr;
592 /* Cancel any possible retry timeouts */
593 silc_schedule_task_del_by_callback(server->schedule,
594 silc_server_connect_to_router_retry);
596 /* Set socket options */
597 silc_net_set_socket_nonblock(sock);
598 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
600 /* Create socket connection for the connection. Even though we
601 know that we are connecting to a router we will mark the socket
602 to be unknown connection until we have executed authentication
604 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
605 server->sockets[sock] = newsocket;
606 newsocket->hostname = strdup(sconn->remote_host);
607 newsocket->ip = strdup(sconn->remote_host);
608 newsocket->port = sconn->remote_port;
609 sconn->sock = newsocket;
611 /* Allocate internal protocol context. This is sent as context
613 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
614 proto_ctx->server = (void *)server;
615 proto_ctx->context = (void *)sconn;
616 proto_ctx->sock = newsocket;
617 proto_ctx->rng = server->rng;
618 proto_ctx->responder = FALSE;
620 /* Set Key Exchange flags from configuration, but fall back to global
622 SILC_GET_SKE_FLAGS(conn, proto_ctx);
623 if (server->config->param.key_exchange_pfs)
624 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
626 /* Perform key exchange protocol. silc_server_connect_to_router_second
627 will be called after the protocol is finished. */
628 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
629 &protocol, proto_ctx,
630 silc_server_connect_to_router_second);
631 newsocket->protocol = protocol;
633 /* Register a timeout task that will be executed if the protocol
634 is not executed within set limit. */
635 proto_ctx->timeout_task =
636 silc_schedule_task_add(server->schedule, sock,
637 silc_server_timeout_remote,
638 server, server->config->key_exchange_timeout, 0,
642 /* Register the connection for network input and output. This sets
643 that scheduler will listen for incoming packets for this connection
644 and sets that outgoing packets may be sent to this connection as
645 well. However, this doesn't set the scheduler for outgoing traffic,
646 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
647 later when outgoing data is available. */
648 context = (void *)server;
649 SILC_REGISTER_CONNECTION_FOR_IO(sock);
651 /* Run the protocol */
652 silc_protocol_execute(protocol, server->schedule, 0, 0);
655 /* Timeout callback that will be called to retry connecting to remote
656 router. This is used by both normal and router server. This will wait
657 before retrying the connecting. The timeout is generated by exponential
658 backoff algorithm. */
660 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
662 SilcServerConnection sconn = (SilcServerConnection)context;
663 SilcServer server = sconn->server;
664 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
665 SilcServerConfigConnParams *param =
666 (conn->param ? conn->param : &server->config->param);
668 SILC_LOG_INFO(("Retrying connecting to a router"));
670 /* Calculate next timeout */
671 if (sconn->retry_count >= 1) {
672 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
673 if (sconn->retry_timeout > param->reconnect_interval_max)
674 sconn->retry_timeout = param->reconnect_interval_max;
676 sconn->retry_timeout = param->reconnect_interval;
678 sconn->retry_count++;
679 sconn->retry_timeout = sconn->retry_timeout +
680 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
682 /* If we've reached max retry count, give up. */
683 if ((sconn->retry_count > param->reconnect_count) &&
684 !param->reconnect_keep_trying) {
685 SILC_LOG_ERROR(("Could not connect to router, giving up"));
686 silc_server_config_unref(&sconn->conn);
687 silc_free(sconn->remote_host);
688 silc_free(sconn->backup_replace_ip);
693 /* We will lookup a fresh pointer later */
694 silc_server_config_unref(&sconn->conn);
696 /* Wait one before retrying */
697 silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
698 context, sconn->retry_timeout, 0,
699 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
702 /* Generic routine to use connect to a router. */
704 SILC_TASK_CALLBACK(silc_server_connect_router)
706 SilcServerConnection sconn = (SilcServerConnection)context;
707 SilcServer server = sconn->server;
708 SilcServerConfigRouter *rconn;
711 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
712 (sconn->backup ? "backup router" : "router"),
713 sconn->remote_host, sconn->remote_port));
715 server->router_connect = time(NULL);
716 rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
719 SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
720 (sconn->backup ? "backup router" : "router"),
721 sconn->remote_host, sconn->remote_port));
722 silc_free(sconn->remote_host);
723 silc_free(sconn->backup_replace_ip);
727 silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
729 /* Connect to remote host */
730 sock = silc_net_create_connection(
731 (!server->config->server_info->primary ? NULL :
732 server->config->server_info->primary->server_ip),
733 sconn->remote_port, sconn->remote_host);
735 SILC_LOG_ERROR(("Could not connect to router %s:%d",
736 sconn->remote_host, sconn->remote_port));
737 if (!sconn->no_reconnect)
738 silc_schedule_task_add(server->schedule, 0,
739 silc_server_connect_to_router_retry,
740 context, 0, 1, SILC_TASK_TIMEOUT,
741 SILC_TASK_PRI_NORMAL);
743 silc_server_config_unref(&sconn->conn);
747 /* Continue with key exchange protocol */
748 silc_server_start_key_exchange(server, sconn, sock);
751 /* This function connects to our primary router or if we are a router this
752 establishes all our primary routes. This is called at the start of the
753 server to do authentication and key exchange with our router - called
756 SILC_TASK_CALLBACK(silc_server_connect_to_router)
758 SilcServer server = (SilcServer)context;
759 SilcServerConnection sconn;
760 SilcServerConfigRouter *ptr;
762 SILC_LOG_DEBUG(("Connecting to router(s)"));
764 if (server->server_type == SILC_SERVER) {
765 SILC_LOG_DEBUG(("We are normal server"));
766 } else if (server->server_type == SILC_ROUTER) {
767 SILC_LOG_DEBUG(("We are router"));
769 SILC_LOG_DEBUG(("We are backup router/normal server"));
772 if (!server->config->routers) {
773 /* There wasn't a configured router, we will continue but we don't
774 have a connection to outside world. We will be standalone server. */
775 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
776 server->standalone = TRUE;
780 /* Cancel any possible retry timeouts */
781 silc_schedule_task_del_by_callback(server->schedule,
782 silc_server_connect_router);
783 silc_schedule_task_del_by_callback(server->schedule,
784 silc_server_connect_to_router_retry);
786 /* Create the connections to all our routes */
787 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
789 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
790 ptr->backup_router ? "Backup router" : "Router",
791 ptr->initiator ? "Initiator" : "Responder",
792 ptr->host, ptr->port));
794 if (ptr->initiator) {
795 /* Check whether we are connected to this host already */
796 if (silc_server_num_sockets_by_remote(server,
797 silc_net_is_ip(ptr->host) ?
799 silc_net_is_ip(ptr->host) ?
800 NULL : ptr->host, ptr->port,
801 SILC_SOCKET_TYPE_ROUTER)) {
802 SILC_LOG_DEBUG(("We are already connected to this router"));
806 /* Allocate connection object for hold connection specific stuff. */
807 sconn = silc_calloc(1, sizeof(*sconn));
808 sconn->server = server;
809 sconn->remote_host = strdup(ptr->host);
810 sconn->remote_port = ptr->port;
811 sconn->backup = ptr->backup_router;
813 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
814 sconn->backup_replace_port = ptr->backup_replace_port;
817 if (!server->router_conn && !sconn->backup)
818 server->router_conn = sconn;
820 silc_schedule_task_add(server->schedule, 0,
821 silc_server_connect_router,
822 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
823 SILC_TASK_PRI_NORMAL);
828 /* Second part of connecting to router(s). Key exchange protocol has been
829 executed and now we will execute authentication protocol. */
831 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
833 SilcProtocol protocol = (SilcProtocol)context;
834 SilcServerKEInternalContext *ctx =
835 (SilcServerKEInternalContext *)protocol->context;
836 SilcServer server = (SilcServer)ctx->server;
837 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
838 SilcSocketConnection sock = ctx->sock;
839 SilcServerConnAuthInternalContext *proto_ctx;
840 SilcServerConfigRouter *conn = NULL;
842 SILC_LOG_DEBUG(("Start"));
844 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
845 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
846 /* Error occured during protocol */
847 silc_protocol_free(protocol);
848 sock->protocol = NULL;
849 silc_ske_free_key_material(ctx->keymat);
851 silc_packet_context_free(ctx->packet);
853 silc_ske_free(ctx->ske);
854 silc_free(ctx->dest_id);
856 silc_server_config_unref(&sconn->conn);
857 silc_free(sconn->remote_host);
858 silc_free(sconn->backup_replace_ip);
860 silc_schedule_task_del_by_callback(server->schedule,
861 silc_server_failure_callback);
862 silc_server_disconnect_remote(server, sock,
863 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
867 /* We now have the key material as the result of the key exchange
868 protocol. Take the key material into use. Free the raw key material
869 as soon as we've set them into use. */
870 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
871 ctx->sock, ctx->keymat,
872 ctx->ske->prop->cipher,
873 ctx->ske->prop->pkcs,
874 ctx->ske->prop->hash,
875 ctx->ske->prop->hmac,
876 ctx->ske->prop->group,
878 silc_protocol_free(protocol);
879 sock->protocol = NULL;
880 silc_ske_free_key_material(ctx->keymat);
882 silc_packet_context_free(ctx->packet);
884 silc_ske_free(ctx->ske);
885 silc_free(ctx->dest_id);
887 silc_server_config_unref(&sconn->conn);
888 silc_free(sconn->remote_host);
889 silc_free(sconn->backup_replace_ip);
891 silc_schedule_task_del_by_callback(server->schedule,
892 silc_server_failure_callback);
893 silc_server_disconnect_remote(server, sock,
894 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
897 silc_ske_free_key_material(ctx->keymat);
899 /* Allocate internal context for the authentication protocol. This
900 is sent as context for the protocol. */
901 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
902 proto_ctx->server = (void *)server;
903 proto_ctx->context = (void *)sconn;
904 proto_ctx->sock = sock;
905 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
906 proto_ctx->dest_id_type = ctx->dest_id_type;
907 proto_ctx->dest_id = ctx->dest_id;
909 /* Resolve the authentication method used in this connection. Check if
910 we find a match from user configured connections */
911 if (!sconn->conn.ref_ptr)
912 conn = silc_server_config_find_router_conn(server, sock->hostname,
915 conn = sconn->conn.ref_ptr;
918 /* Match found. Use the configured authentication method. Take only
919 the passphrase, since for public key auth we automatically use
920 our local key pair. */
921 if (conn->passphrase) {
922 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
923 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
925 proto_ctx->auth_data = strdup(conn->passphrase);
926 proto_ctx->auth_data_len = strlen(conn->passphrase);
927 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
929 } else if (conn->publickeys) {
930 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
932 proto_ctx->auth_meth = SILC_AUTH_NONE;
935 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
936 sock->hostname, sock->ip, sock->port));
937 silc_protocol_free(protocol);
938 sock->protocol = NULL;
940 silc_packet_context_free(ctx->packet);
942 silc_ske_free(ctx->ske);
943 silc_free(ctx->dest_id);
945 silc_server_config_unref(&sconn->conn);
946 silc_free(sconn->remote_host);
947 silc_free(sconn->backup_replace_ip);
949 silc_schedule_task_del_by_callback(server->schedule,
950 silc_server_failure_callback);
951 silc_server_disconnect_remote(server, sock,
952 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
956 /* Free old protocol as it is finished now */
957 silc_protocol_free(protocol);
959 silc_packet_context_free(ctx->packet);
961 sock->protocol = NULL;
963 /* Allocate the authentication protocol. This is allocated here
964 but we won't start it yet. We will be receiving party of this
965 protocol thus we will wait that connecting party will make
967 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
968 &sock->protocol, proto_ctx,
969 silc_server_connect_to_router_final);
971 /* Register timeout task. If the protocol is not executed inside
972 this timelimit the connection will be terminated. */
973 proto_ctx->timeout_task =
974 silc_schedule_task_add(server->schedule, sock->sock,
975 silc_server_timeout_remote,
977 server->config->conn_auth_timeout, 0,
981 /* Run the protocol */
982 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
985 /* Finalizes the connection to router. Registers a server task to the
986 queue so that we can accept new connections. */
988 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
990 SilcProtocol protocol = (SilcProtocol)context;
991 SilcServerConnAuthInternalContext *ctx =
992 (SilcServerConnAuthInternalContext *)protocol->context;
993 SilcServer server = (SilcServer)ctx->server;
994 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
995 SilcSocketConnection sock = ctx->sock;
996 SilcServerEntry id_entry;
998 SilcServerHBContext hb_context;
999 unsigned char *id_string;
1001 SilcIDListData idata;
1002 SilcServerConfigRouter *conn = NULL;
1003 SilcServerConfigConnParams *param = NULL;
1005 SILC_LOG_DEBUG(("Start"));
1007 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1008 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1009 /* Error occured during protocol */
1010 silc_free(ctx->dest_id);
1011 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1016 /* Add a task to the queue. This task receives new connections to the
1017 server. This task remains on the queue until the end of the program. */
1018 if (!server->listenning && !sconn->backup) {
1019 silc_schedule_task_add(server->schedule, server->sock,
1020 silc_server_accept_new_connection,
1021 (void *)server, 0, 0,
1023 SILC_TASK_PRI_NORMAL);
1024 server->listenning = TRUE;
1027 /* Send NEW_SERVER packet to the router. We will become registered
1028 to the SILC network after sending this packet. */
1029 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
1030 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1031 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
1032 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1033 silc_buffer_format(packet,
1034 SILC_STR_UI_SHORT(id_len),
1035 SILC_STR_UI_XNSTRING(id_string, id_len),
1036 SILC_STR_UI_SHORT(strlen(server->server_name)),
1037 SILC_STR_UI_XNSTRING(server->server_name,
1038 strlen(server->server_name)),
1041 /* Send the packet */
1042 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
1043 packet->data, packet->len, TRUE);
1044 silc_buffer_free(packet);
1045 silc_free(id_string);
1047 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
1049 /* Check that we do not have this ID already */
1050 id_entry = silc_idlist_find_server_by_id(server->local_list,
1051 ctx->dest_id, TRUE, NULL);
1053 silc_idcache_del_by_context(server->local_list->servers, id_entry);
1055 id_entry = silc_idlist_find_server_by_id(server->global_list,
1056 ctx->dest_id, TRUE, NULL);
1058 silc_idcache_del_by_context(server->global_list->servers, id_entry);
1061 SILC_LOG_DEBUG(("New server id(%s)",
1062 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1064 /* Add the connected router to global server list */
1065 id_entry = silc_idlist_add_server(server->global_list,
1066 strdup(sock->hostname),
1067 SILC_ROUTER, ctx->dest_id, NULL, sock);
1069 silc_free(ctx->dest_id);
1070 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1071 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1076 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1077 silc_free(sock->user_data);
1078 sock->user_data = (void *)id_entry;
1079 sock->type = SILC_SOCKET_TYPE_ROUTER;
1080 idata = (SilcIDListData)sock->user_data;
1081 idata->status |= SILC_IDLIST_STATUS_REGISTERED;
1083 conn = sconn->conn.ref_ptr;
1084 param = &server->config->param;
1085 if (conn && conn->param)
1086 param = conn->param;
1088 /* Perform keepalive. The `hb_context' will be freed automatically
1089 when finally calling the silc_socket_free function. */
1090 hb_context = silc_calloc(1, sizeof(*hb_context));
1091 hb_context->server = server;
1092 silc_socket_set_heartbeat(sock, param->keepalive_secs, hb_context,
1093 silc_server_perform_heartbeat,
1096 /* Register re-key timeout */
1097 idata->rekey->timeout = param->key_exchange_rekey;
1098 idata->rekey->context = (void *)server;
1099 silc_schedule_task_add(server->schedule, sock->sock,
1100 silc_server_rekey_callback,
1101 (void *)sock, idata->rekey->timeout, 0,
1102 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1104 if (!sconn->backup) {
1105 /* Mark this router our primary router if we're still standalone */
1106 if (server->standalone) {
1107 server->id_entry->router = id_entry;
1108 server->router = id_entry;
1109 server->standalone = FALSE;
1111 /* If we are router then announce our possible servers. */
1112 if (server->server_type == SILC_ROUTER)
1113 silc_server_announce_servers(server, FALSE, 0,
1114 server->router->connection);
1116 /* Announce our clients and channels to the router */
1117 silc_server_announce_clients(server, 0, server->router->connection);
1118 silc_server_announce_channels(server, 0, server->router->connection);
1120 #ifdef BACKUP_SINGLE_ROUTER
1121 /* If we are backup router then this primary router is whom we are
1123 if (server->server_type == SILC_BACKUP_ROUTER)
1124 silc_server_backup_add(server, server->id_entry, sock->ip, 0, TRUE);
1125 #endif /* BACKUP_SINGLE_ROUTER */
1128 /* Add this server to be our backup router */
1129 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1130 sconn->backup_replace_port, FALSE);
1133 sock->protocol = NULL;
1135 /* Call the completion callback to indicate that we've connected to
1137 if (sconn->callback)
1138 (*sconn->callback)(server, id_entry, sconn->callback_context);
1141 /* Free the temporary connection data context */
1143 silc_server_config_unref(&sconn->conn);
1144 silc_free(sconn->remote_host);
1145 silc_free(sconn->backup_replace_ip);
1148 if (sconn == server->router_conn)
1149 server->router_conn = NULL;
1151 /* Free the protocol object */
1152 if (sock->protocol == protocol)
1153 sock->protocol = NULL;
1154 silc_protocol_free(protocol);
1156 silc_packet_context_free(ctx->packet);
1158 silc_ske_free(ctx->ske);
1159 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1160 silc_free(ctx->auth_data);
1164 /* Host lookup callback that is called after the incoming connection's
1165 IP and FQDN lookup is performed. This will actually check the acceptance
1166 of the incoming connection and will register the key exchange protocol
1167 for this connection. */
1170 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1173 SilcServerKEInternalContext *proto_ctx =
1174 (SilcServerKEInternalContext *)context;
1175 SilcServer server = (SilcServer)proto_ctx->server;
1176 SilcServerConfigClient *cconfig = NULL;
1177 SilcServerConfigServer *sconfig = NULL;
1178 SilcServerConfigRouter *rconfig = NULL;
1179 SilcServerConfigDeny *deny;
1182 context = (void *)server;
1184 SILC_LOG_DEBUG(("Start"));
1186 /* Check whether we could resolve both IP and FQDN. */
1187 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1188 server->config->require_reverse_lookup)) {
1189 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1190 sock->hostname ? sock->hostname :
1191 sock->ip ? sock->ip : ""));
1192 server->stat.conn_failures++;
1193 silc_server_disconnect_remote(server, sock,
1194 SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
1195 "Unknown host or IP");
1196 silc_free(proto_ctx);
1200 /* Register the connection for network input and output. This sets
1201 that scheduler will listen for incoming packets for this connection
1202 and sets that outgoing packets may be sent to this connection as well.
1203 However, this doesn't set the scheduler for outgoing traffic, it
1204 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1205 later when outgoing data is available. */
1206 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1208 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1211 /* Listenning port */
1212 port = server->sockets[(SilcUInt32)proto_ctx->context]->port;
1214 /* Check whether this connection is denied to connect to us. */
1215 deny = silc_server_config_find_denied(server, sock->ip);
1217 deny = silc_server_config_find_denied(server, sock->hostname);
1219 /* The connection is denied */
1220 SILC_LOG_INFO(("Connection %s (%s) is denied",
1221 sock->hostname, sock->ip));
1222 silc_server_disconnect_remote(server, sock,
1223 SILC_STATUS_ERR_BANNED_FROM_SERVER,
1225 server->stat.conn_failures++;
1226 silc_free(proto_ctx);
1230 /* Check whether we have configured this sort of connection at all. We
1231 have to check all configurations since we don't know what type of
1232 connection this is. */
1233 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1234 cconfig = silc_server_config_find_client(server, sock->hostname);
1235 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1236 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1237 if (server->server_type == SILC_ROUTER) {
1238 if (!(rconfig = silc_server_config_find_router_conn(server,
1239 sock->ip, sock->port)))
1240 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1243 if (!cconfig && !sconfig && !rconfig) {
1244 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1246 silc_server_disconnect_remote(server, sock,
1247 SILC_STATUS_ERR_BANNED_FROM_SERVER, NULL);
1248 server->stat.conn_failures++;
1249 silc_free(proto_ctx);
1253 /* The connection is allowed */
1255 /* Set internal context for key exchange protocol. This is
1256 sent as context for the protocol. */
1257 proto_ctx->sock = sock;
1258 proto_ctx->rng = server->rng;
1259 proto_ctx->responder = TRUE;
1260 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1261 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1262 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1264 /* Take flags for key exchange. Since we do not know what type of connection
1265 this is, we go through all found configurations and use the global ones
1266 as well. This will result always into strictest key exchange flags. */
1267 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1268 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1269 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1270 if (server->config->param.key_exchange_pfs)
1271 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1273 /* Prepare the connection for key exchange protocol. We allocate the
1274 protocol but will not start it yet. The connector will be the
1275 initiator of the protocol thus we will wait for initiation from
1276 there before we start the protocol. */
1277 server->stat.auth_attempts++;
1278 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1279 &sock->protocol, proto_ctx,
1280 silc_server_accept_new_connection_second);
1282 /* Register a timeout task that will be executed if the connector
1283 will not start the key exchange protocol within specified timeout
1284 and the connection will be closed. */
1285 proto_ctx->timeout_task =
1286 silc_schedule_task_add(server->schedule, sock->sock,
1287 silc_server_timeout_remote,
1289 server->config->key_exchange_timeout, 0,
1294 /* Accepts new connections to the server. Accepting new connections are
1295 done in three parts to make it async. */
1297 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1299 SilcServer server = (SilcServer)context;
1300 SilcSocketConnection newsocket;
1301 SilcServerKEInternalContext *proto_ctx;
1304 SILC_LOG_DEBUG(("Accepting new connection"));
1306 server->stat.conn_attempts++;
1308 sock = silc_net_accept_connection(fd);
1310 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1311 server->stat.conn_failures++;
1315 /* Check for maximum allowed connections */
1316 if (sock > server->config->param.connections_max) {
1317 SILC_LOG_ERROR(("Refusing connection, server is full"));
1318 server->stat.conn_failures++;
1319 silc_net_close_connection(sock);
1323 /* Set socket options */
1324 silc_net_set_socket_nonblock(sock);
1325 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1327 /* We don't create a ID yet, since we don't know what type of connection
1328 this is yet. But, we do add the connection to the socket table. */
1329 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1330 server->sockets[sock] = newsocket;
1332 /* Perform asynchronous host lookup. This will lookup the IP and the
1333 FQDN of the remote connection. After the lookup is done the connection
1334 is accepted further. */
1335 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1336 proto_ctx->server = server;
1337 proto_ctx->context = (void *)fd;
1338 silc_socket_host_lookup(newsocket, TRUE,
1339 silc_server_accept_new_connection_lookup,
1340 (void *)proto_ctx, server->schedule);
1343 /* Second part of accepting new connection. Key exchange protocol has been
1344 performed and now it is time to do little connection authentication
1345 protocol to figure out whether this connection is client or server
1346 and whether it has right to access this server (especially server
1347 connections needs to be authenticated). */
1349 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1351 SilcProtocol protocol = (SilcProtocol)context;
1352 SilcServerKEInternalContext *ctx =
1353 (SilcServerKEInternalContext *)protocol->context;
1354 SilcServer server = (SilcServer)ctx->server;
1355 SilcSocketConnection sock = ctx->sock;
1356 SilcServerConnAuthInternalContext *proto_ctx;
1358 SILC_LOG_DEBUG(("Start"));
1360 if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1361 (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1362 /* Error occured during protocol */
1363 silc_protocol_free(protocol);
1364 sock->protocol = NULL;
1365 silc_ske_free_key_material(ctx->keymat);
1367 silc_packet_context_free(ctx->packet);
1369 silc_ske_free(ctx->ske);
1370 silc_free(ctx->dest_id);
1371 silc_server_config_unref(&ctx->cconfig);
1372 silc_server_config_unref(&ctx->sconfig);
1373 silc_server_config_unref(&ctx->rconfig);
1375 silc_schedule_task_del_by_callback(server->schedule,
1376 silc_server_failure_callback);
1377 silc_server_disconnect_remote(server, sock,
1378 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
1380 server->stat.auth_failures++;
1384 /* We now have the key material as the result of the key exchange
1385 protocol. Take the key material into use. Free the raw key material
1386 as soon as we've set them into use. */
1387 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1388 ctx->sock, ctx->keymat,
1389 ctx->ske->prop->cipher,
1390 ctx->ske->prop->pkcs,
1391 ctx->ske->prop->hash,
1392 ctx->ske->prop->hmac,
1393 ctx->ske->prop->group,
1395 silc_protocol_free(protocol);
1396 sock->protocol = NULL;
1397 silc_ske_free_key_material(ctx->keymat);
1399 silc_packet_context_free(ctx->packet);
1401 silc_ske_free(ctx->ske);
1402 silc_free(ctx->dest_id);
1403 silc_server_config_unref(&ctx->cconfig);
1404 silc_server_config_unref(&ctx->sconfig);
1405 silc_server_config_unref(&ctx->rconfig);
1407 silc_schedule_task_del_by_callback(server->schedule,
1408 silc_server_failure_callback);
1409 silc_server_disconnect_remote(server, sock,
1410 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1411 server->stat.auth_failures++;
1414 silc_ske_free_key_material(ctx->keymat);
1416 /* Allocate internal context for the authentication protocol. This
1417 is sent as context for the protocol. */
1418 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1419 proto_ctx->server = (void *)server;
1420 proto_ctx->sock = sock;
1421 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1422 proto_ctx->responder = TRUE;
1423 proto_ctx->dest_id_type = ctx->dest_id_type;
1424 proto_ctx->dest_id = ctx->dest_id;
1425 proto_ctx->cconfig = ctx->cconfig;
1426 proto_ctx->sconfig = ctx->sconfig;
1427 proto_ctx->rconfig = ctx->rconfig;
1429 /* Free old protocol as it is finished now */
1430 silc_protocol_free(protocol);
1432 silc_packet_context_free(ctx->packet);
1434 sock->protocol = NULL;
1436 /* Allocate the authentication protocol. This is allocated here
1437 but we won't start it yet. We will be receiving party of this
1438 protocol thus we will wait that connecting party will make
1439 their first move. */
1440 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1441 &sock->protocol, proto_ctx,
1442 silc_server_accept_new_connection_final);
1444 /* Register timeout task. If the protocol is not executed inside
1445 this timelimit the connection will be terminated. */
1446 proto_ctx->timeout_task =
1447 silc_schedule_task_add(server->schedule, sock->sock,
1448 silc_server_timeout_remote,
1450 server->config->conn_auth_timeout, 0,
1455 /* Final part of accepting new connection. The connection has now
1456 been authenticated and keys has been exchanged. We also know whether
1457 this is client or server connection. */
1459 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1461 SilcProtocol protocol = (SilcProtocol)context;
1462 SilcServerConnAuthInternalContext *ctx =
1463 (SilcServerConnAuthInternalContext *)protocol->context;
1464 SilcServer server = (SilcServer)ctx->server;
1465 SilcSocketConnection sock = ctx->sock;
1466 SilcServerHBContext hb_context;
1467 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1469 SilcUInt32 hearbeat_timeout = server->config->param.keepalive_secs;
1471 SILC_LOG_DEBUG(("Start"));
1473 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1474 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1475 /* Error occured during protocol */
1476 silc_protocol_free(protocol);
1477 sock->protocol = NULL;
1479 silc_packet_context_free(ctx->packet);
1481 silc_ske_free(ctx->ske);
1482 silc_free(ctx->dest_id);
1483 silc_server_config_unref(&ctx->cconfig);
1484 silc_server_config_unref(&ctx->sconfig);
1485 silc_server_config_unref(&ctx->rconfig);
1487 silc_schedule_task_del_by_callback(server->schedule,
1488 silc_server_failure_callback);
1489 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1491 server->stat.auth_failures++;
1495 entry->data.last_receive = time(NULL);
1497 switch (ctx->conn_type) {
1498 case SILC_SOCKET_TYPE_CLIENT:
1500 SilcClientEntry client;
1501 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1503 /* Verify whether this connection is after all allowed to connect */
1504 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1505 &server->config->param,
1506 conn->param, ctx->ske)) {
1507 server->stat.auth_failures++;
1511 SILC_LOG_DEBUG(("Remote host is client"));
1512 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1515 /* Add the client to the client ID cache. The nickname and Client ID
1516 and other information is created after we have received NEW_CLIENT
1517 packet from client. */
1518 client = silc_idlist_add_client(server->local_list,
1519 NULL, NULL, NULL, NULL, NULL, sock, 0);
1521 SILC_LOG_ERROR(("Could not add new client to cache"));
1522 silc_free(sock->user_data);
1523 silc_server_disconnect_remote(server, sock,
1524 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1525 server->stat.auth_failures++;
1530 server->stat.my_clients++;
1531 server->stat.clients++;
1532 server->stat.cell_clients++;
1534 /* Get connection parameters */
1536 if (conn->param->keepalive_secs)
1537 hearbeat_timeout = conn->param->keepalive_secs;
1540 id_entry = (void *)client;
1543 case SILC_SOCKET_TYPE_SERVER:
1544 case SILC_SOCKET_TYPE_ROUTER:
1546 SilcServerEntry new_server;
1547 bool initiator = FALSE;
1548 bool backup_local = FALSE;
1549 bool backup_router = FALSE;
1550 char *backup_replace_ip = NULL;
1551 SilcUInt16 backup_replace_port = 0;
1552 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1553 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1555 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1556 /* Verify whether this connection is after all allowed to connect */
1557 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1558 &server->config->param,
1559 rconn ? rconn->param : NULL,
1561 server->stat.auth_failures++;
1567 if (rconn->param->keepalive_secs)
1568 hearbeat_timeout = rconn->param->keepalive_secs;
1571 initiator = rconn->initiator;
1572 backup_local = rconn->backup_local;
1573 backup_router = rconn->backup_router;
1574 backup_replace_ip = rconn->backup_replace_ip;
1575 backup_replace_port = rconn->backup_replace_port;
1579 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1580 /* Verify whether this connection is after all allowed to connect */
1581 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1582 &server->config->param,
1583 sconn ? sconn->param : NULL,
1585 server->stat.auth_failures++;
1590 if (sconn->param->keepalive_secs)
1591 hearbeat_timeout = sconn->param->keepalive_secs;
1594 backup_router = sconn->backup_router;
1598 SILC_LOG_DEBUG(("Remote host is %s",
1599 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1600 "server" : (backup_router ?
1601 "backup router" : "router")));
1602 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
1603 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1604 "server" : (backup_router ?
1605 "backup router" : "router")));
1607 /* Add the server into server cache. The server name and Server ID
1608 is updated after we have received NEW_SERVER packet from the
1609 server. We mark ourselves as router for this server if we really
1612 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1613 server->local_list : (backup_router ?
1614 server->local_list :
1615 server->global_list)),
1617 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1618 SILC_SERVER : SILC_ROUTER),
1620 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1621 server->id_entry : (backup_router ?
1622 server->id_entry : NULL)),
1625 SILC_LOG_ERROR(("Could not add new server to cache"));
1626 silc_free(sock->user_data);
1627 silc_server_disconnect_remote(server, sock,
1628 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1629 server->stat.auth_failures++;
1634 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1635 server->stat.my_servers++;
1637 server->stat.my_routers++;
1638 server->stat.routers++;
1640 server->stat.servers++;
1642 id_entry = (void *)new_server;
1644 /* If the incoming connection is router and marked as backup router
1645 then add it to be one of our backups */
1646 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
1647 silc_server_backup_add(server, new_server, backup_replace_ip,
1648 backup_replace_port, backup_local);
1650 /* Change it back to SERVER type since that's what it really is. */
1652 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1654 new_server->server_type = SILC_BACKUP_ROUTER;
1657 /* Check whether this connection is to be our primary router connection
1658 if we do not already have the primary route. */
1659 if (!backup_router &&
1660 server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1661 if (silc_server_config_is_primary_route(server) && !initiator)
1664 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1665 server->standalone = FALSE;
1666 if (!server->id_entry->router) {
1667 server->id_entry->router = id_entry;
1668 server->router = id_entry;
1679 sock->type = ctx->conn_type;
1681 /* Add the common data structure to the ID entry. */
1682 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1684 /* Add to sockets internal pointer for fast referencing */
1685 silc_free(sock->user_data);
1686 sock->user_data = id_entry;
1688 /* Connection has been fully established now. Everything is ok. */
1689 SILC_LOG_DEBUG(("New connection authenticated"));
1691 /* Perform keepalive. The `hb_context' will be freed automatically
1692 when finally calling the silc_socket_free function. */
1693 hb_context = silc_calloc(1, sizeof(*hb_context));
1694 hb_context->server = server;
1695 silc_socket_set_heartbeat(sock, hearbeat_timeout, hb_context,
1696 silc_server_perform_heartbeat,
1700 silc_schedule_task_del_by_callback(server->schedule,
1701 silc_server_failure_callback);
1702 silc_protocol_free(protocol);
1704 silc_packet_context_free(ctx->packet);
1706 silc_ske_free(ctx->ske);
1707 silc_free(ctx->dest_id);
1708 silc_server_config_unref(&ctx->cconfig);
1709 silc_server_config_unref(&ctx->sconfig);
1710 silc_server_config_unref(&ctx->rconfig);
1712 sock->protocol = NULL;
1715 /* This function is used to read packets from network and send packets to
1716 network. This is usually a generic task. */
1718 SILC_TASK_CALLBACK(silc_server_packet_process)
1720 SilcServer server = (SilcServer)context;
1721 SilcSocketConnection sock = server->sockets[fd];
1722 SilcIDListData idata;
1723 SilcCipher cipher = NULL;
1724 SilcHmac hmac = NULL;
1725 SilcUInt32 sequence = 0;
1731 SILC_LOG_DEBUG(("Processing packet"));
1733 /* Packet sending */
1735 if (type == SILC_TASK_WRITE) {
1736 /* Do not send data to disconnected connection */
1737 if (SILC_IS_DISCONNECTED(sock))
1740 server->stat.packets_sent++;
1742 /* Send the packet */
1743 ret = silc_packet_send(sock, TRUE);
1745 /* If returned -2 could not write to connection now, will do
1751 SILC_LOG_ERROR(("Error sending packet to connection "
1752 "%s:%d [%s]", sock->hostname, sock->port,
1753 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1754 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1755 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1760 /* The packet has been sent and now it is time to set the connection
1761 back to only for input. When there is again some outgoing data
1762 available for this connection it will be set for output as well.
1763 This call clears the output setting and sets it only for input. */
1764 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1765 SILC_UNSET_OUTBUF_PENDING(sock);
1767 silc_buffer_clear(sock->outbuf);
1771 /* Packet receiving */
1773 /* Read some data from connection */
1774 ret = silc_packet_receive(sock);
1778 SILC_LOG_ERROR(("Error receiving packet from connection "
1779 "%s:%d [%s] %s", sock->hostname, sock->port,
1780 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1781 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1782 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1783 "Router"), strerror(errno)));
1789 SILC_LOG_DEBUG(("Read EOF"));
1791 /* If connection is disconnecting already we will finally
1792 close the connection */
1793 if (SILC_IS_DISCONNECTING(sock)) {
1794 if (sock->user_data)
1795 silc_server_free_sock_user_data(server, sock, NULL);
1796 silc_server_close_connection(server, sock);
1800 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1801 SILC_SET_DISCONNECTING(sock);
1803 if (sock->user_data) {
1805 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
1806 silc_server_free_sock_user_data(server, sock, tmp);
1808 silc_server_free_sock_user_data(server, sock, NULL);
1809 } else if (server->router_conn && server->router_conn->sock == sock &&
1810 !server->router && server->standalone)
1811 silc_schedule_task_add(server->schedule, 0,
1812 silc_server_connect_to_router,
1815 SILC_TASK_PRI_NORMAL);
1817 silc_server_close_connection(server, sock);
1821 /* If connection is disconnecting or disconnected we will ignore
1823 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1824 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
1828 server->stat.packets_received++;
1830 /* Get keys and stuff from ID entry */
1831 idata = (SilcIDListData)sock->user_data;
1833 cipher = idata->receive_key;
1834 hmac = idata->hmac_receive;
1835 sequence = idata->psn_receive;
1838 /* Process the packet. This will call the parser that will then
1839 decrypt and parse the packet. */
1840 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1841 TRUE : FALSE, cipher, hmac, sequence,
1842 silc_server_packet_parse, server);
1844 /* If this socket connection is not authenticated yet and the packet
1845 processing failed we will drop the connection since it can be
1846 a malicious flooder. */
1847 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
1848 (!sock->protocol || sock->protocol->protocol->type ==
1849 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
1850 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
1851 SILC_SET_DISCONNECTING(sock);
1853 if (sock->user_data)
1854 silc_server_free_sock_user_data(server, sock, NULL);
1855 silc_server_close_connection(server, sock);
1859 /* Parses whole packet, received earlier. */
1861 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1863 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1864 SilcServer server = (SilcServer)parse_ctx->context;
1865 SilcSocketConnection sock = parse_ctx->sock;
1866 SilcPacketContext *packet = parse_ctx->packet;
1867 SilcIDListData idata = (SilcIDListData)sock->user_data;
1870 SILC_LOG_DEBUG(("Start"));
1872 /* Parse the packet */
1873 if (parse_ctx->normal)
1874 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
1876 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
1878 /* If entry is disabled ignore what we got. */
1879 if (ret != SILC_PACKET_RESUME_ROUTER &&
1880 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1881 SILC_LOG_DEBUG(("Connection is disabled"));
1885 if (ret == SILC_PACKET_NONE)
1888 /* Check that the the current client ID is same as in the client's packet. */
1889 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1890 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1891 if (client && client->id) {
1892 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1893 packet->src_id_type);
1894 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1902 if (server->server_type == SILC_ROUTER) {
1903 /* Route the packet if it is not destined to us. Other ID types but
1904 server are handled separately after processing them. */
1905 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1906 packet->dst_id_type == SILC_ID_SERVER &&
1907 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1908 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1910 /* Route the packet to fastest route for the destination ID */
1911 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1912 packet->dst_id_type);
1915 silc_server_packet_route(server,
1916 silc_server_route_get(server, id,
1917 packet->dst_id_type),
1924 /* Parse the incoming packet type */
1925 silc_server_packet_parse_type(server, sock, packet);
1927 if (server->server_type == SILC_ROUTER) {
1928 /* Broadcast packet if it is marked as broadcast packet and it is
1929 originated from router and we are router. */
1930 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1931 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1932 !server->standalone) {
1933 /* Broadcast to our primary route */
1934 silc_server_packet_broadcast(server, server->router->connection, packet);
1936 /* If we have backup routers then we need to feed all broadcast
1937 data to those servers. */
1938 silc_server_backup_broadcast(server, sock, packet);
1943 silc_packet_context_free(packet);
1944 silc_free(parse_ctx);
1947 /* Parser callback called by silc_packet_receive_process. This merely
1948 registers timeout that will handle the actual parsing when appropriate. */
1950 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
1953 SilcServer server = (SilcServer)context;
1954 SilcSocketConnection sock = parser_context->sock;
1955 SilcIDListData idata = (SilcIDListData)sock->user_data;
1958 idata->psn_receive = parser_context->packet->sequence + 1;
1960 /* If protocol for this connection is key exchange or rekey then we'll
1961 process all packets synchronously, since there might be packets in
1962 queue that we are not able to decrypt without first processing the
1963 packets before them. */
1964 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
1965 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
1966 (sock->protocol && sock->protocol->protocol &&
1967 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1968 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
1969 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1972 /* Reprocess data since we'll return FALSE here. This is because
1973 the idata->receive_key might have become valid in the last packet
1974 and we want to call this processor with valid cipher. */
1976 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1977 TRUE : FALSE, idata->receive_key,
1978 idata->hmac_receive, idata->psn_receive,
1979 silc_server_packet_parse, server);
1981 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1982 TRUE : FALSE, NULL, NULL, 0,
1983 silc_server_packet_parse, server);
1987 switch (sock->type) {
1988 case SILC_SOCKET_TYPE_UNKNOWN:
1989 case SILC_SOCKET_TYPE_CLIENT:
1990 /* Parse the packet with timeout */
1991 silc_schedule_task_add(server->schedule, sock->sock,
1992 silc_server_packet_parse_real,
1993 (void *)parser_context, 0, 100000,
1995 SILC_TASK_PRI_NORMAL);
1997 case SILC_SOCKET_TYPE_SERVER:
1998 case SILC_SOCKET_TYPE_ROUTER:
1999 /* Packets from servers are parsed immediately */
2000 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
2010 /* Parses the packet type and calls what ever routines the packet type
2011 requires. This is done for all incoming packets. */
2013 void silc_server_packet_parse_type(SilcServer server,
2014 SilcSocketConnection sock,
2015 SilcPacketContext *packet)
2017 SilcPacketType type = packet->type;
2018 SilcIDListData idata = (SilcIDListData)sock->user_data;
2020 SILC_LOG_DEBUG(("Parsing packet type %d", type));
2022 /* Parse the packet type */
2024 case SILC_PACKET_DISCONNECT:
2027 char *message = NULL;
2029 SILC_LOG_DEBUG(("Disconnect packet"));
2031 if (packet->flags & SILC_PACKET_FLAG_LIST)
2033 if (packet->buffer->len < 1)
2036 status = (SilcStatus)packet->buffer->data[0];
2037 if (packet->buffer->len > 1 &&
2038 silc_utf8_valid(packet->buffer->data + 1, packet->buffer->len - 1))
2039 message = silc_memdup(packet->buffer->data, packet->buffer->len);
2041 SILC_LOG_ERROR(("Disconnected by %s (%s): %s (%d) %s",
2042 sock->ip, sock->hostname,
2043 silc_get_status_message(status), status,
2044 message ? message : ""));
2049 case SILC_PACKET_SUCCESS:
2051 * Success received for something. For now we can have only
2052 * one protocol for connection executing at once hence this
2053 * success message is for whatever protocol is executing currently.
2055 SILC_LOG_DEBUG(("Success packet"));
2056 if (packet->flags & SILC_PACKET_FLAG_LIST)
2059 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2062 case SILC_PACKET_FAILURE:
2064 * Failure received for something. For now we can have only
2065 * one protocol for connection executing at once hence this
2066 * failure message is for whatever protocol is executing currently.
2068 SILC_LOG_DEBUG(("Failure packet"));
2069 if (packet->flags & SILC_PACKET_FLAG_LIST)
2071 if (sock->protocol) {
2072 SilcServerFailureContext f;
2073 f = silc_calloc(1, sizeof(*f));
2077 /* We will wait 5 seconds to process this failure packet */
2078 silc_schedule_task_add(server->schedule, sock->sock,
2079 silc_server_failure_callback, (void *)f, 5, 0,
2080 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2084 case SILC_PACKET_REJECT:
2085 SILC_LOG_DEBUG(("Reject packet"));
2086 if (packet->flags & SILC_PACKET_FLAG_LIST)
2091 case SILC_PACKET_NOTIFY:
2093 * Received notify packet. Server can receive notify packets from
2094 * router. Server then relays the notify messages to clients if needed.
2096 SILC_LOG_DEBUG(("Notify packet"));
2097 if (packet->flags & SILC_PACKET_FLAG_LIST)
2098 silc_server_notify_list(server, sock, packet);
2100 silc_server_notify(server, sock, packet);
2106 case SILC_PACKET_CHANNEL_MESSAGE:
2108 * Received channel message. Channel messages are special packets
2109 * (although probably most common ones) thus they are handled
2112 SILC_LOG_DEBUG(("Channel Message packet"));
2113 if (packet->flags & SILC_PACKET_FLAG_LIST)
2115 idata->last_receive = time(NULL);
2116 silc_server_channel_message(server, sock, packet);
2119 case SILC_PACKET_CHANNEL_KEY:
2121 * Received key for channel. As channels are created by the router
2122 * the keys are as well. We will distribute the key to all of our
2123 * locally connected clients on the particular channel. Router
2124 * never receives this channel and thus is ignored.
2126 SILC_LOG_DEBUG(("Channel Key packet"));
2127 if (packet->flags & SILC_PACKET_FLAG_LIST)
2129 silc_server_channel_key(server, sock, packet);
2135 case SILC_PACKET_COMMAND:
2137 * Recived command. Processes the command request and allocates the
2138 * command context and calls the command.
2140 SILC_LOG_DEBUG(("Command packet"));
2141 if (packet->flags & SILC_PACKET_FLAG_LIST)
2143 silc_server_command_process(server, sock, packet);
2146 case SILC_PACKET_COMMAND_REPLY:
2148 * Received command reply packet. Received command reply to command. It
2149 * may be reply to command sent by us or reply to command sent by client
2150 * that we've routed further.
2152 SILC_LOG_DEBUG(("Command Reply packet"));
2153 if (packet->flags & SILC_PACKET_FLAG_LIST)
2155 silc_server_command_reply(server, sock, packet);
2159 * Private Message packets
2161 case SILC_PACKET_PRIVATE_MESSAGE:
2163 * Received private message packet. The packet is coming from either
2166 SILC_LOG_DEBUG(("Private Message packet"));
2167 if (packet->flags & SILC_PACKET_FLAG_LIST)
2169 idata->last_receive = time(NULL);
2170 silc_server_private_message(server, sock, packet);
2173 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2175 * Private message key packet.
2177 if (packet->flags & SILC_PACKET_FLAG_LIST)
2179 silc_server_private_message_key(server, sock, packet);
2183 * Key Exchange protocol packets
2185 case SILC_PACKET_KEY_EXCHANGE:
2186 SILC_LOG_DEBUG(("KE packet"));
2187 if (packet->flags & SILC_PACKET_FLAG_LIST)
2190 if (sock->protocol && sock->protocol->protocol &&
2191 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2192 SilcServerKEInternalContext *proto_ctx =
2193 (SilcServerKEInternalContext *)sock->protocol->context;
2195 proto_ctx->packet = silc_packet_context_dup(packet);
2197 /* Let the protocol handle the packet */
2198 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2200 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2201 "protocol active, packet dropped."));
2205 case SILC_PACKET_KEY_EXCHANGE_1:
2206 SILC_LOG_DEBUG(("KE 1 packet"));
2207 if (packet->flags & SILC_PACKET_FLAG_LIST)
2210 if (sock->protocol && sock->protocol->protocol &&
2211 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2212 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2214 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2215 SilcServerRekeyInternalContext *proto_ctx =
2216 (SilcServerRekeyInternalContext *)sock->protocol->context;
2218 if (proto_ctx->packet)
2219 silc_packet_context_free(proto_ctx->packet);
2221 proto_ctx->packet = silc_packet_context_dup(packet);
2223 /* Let the protocol handle the packet */
2224 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2226 SilcServerKEInternalContext *proto_ctx =
2227 (SilcServerKEInternalContext *)sock->protocol->context;
2229 if (proto_ctx->packet)
2230 silc_packet_context_free(proto_ctx->packet);
2232 proto_ctx->packet = silc_packet_context_dup(packet);
2233 proto_ctx->dest_id_type = packet->src_id_type;
2234 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2235 packet->src_id_type);
2236 if (!proto_ctx->dest_id)
2239 /* Let the protocol handle the packet */
2240 silc_protocol_execute(sock->protocol, server->schedule,
2244 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2245 "protocol active, packet dropped."));
2249 case SILC_PACKET_KEY_EXCHANGE_2:
2250 SILC_LOG_DEBUG(("KE 2 packet"));
2251 if (packet->flags & SILC_PACKET_FLAG_LIST)
2254 if (sock->protocol && sock->protocol->protocol &&
2255 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2256 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2258 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2259 SilcServerRekeyInternalContext *proto_ctx =
2260 (SilcServerRekeyInternalContext *)sock->protocol->context;
2262 if (proto_ctx->packet)
2263 silc_packet_context_free(proto_ctx->packet);
2265 proto_ctx->packet = silc_packet_context_dup(packet);
2267 /* Let the protocol handle the packet */
2268 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2270 SilcServerKEInternalContext *proto_ctx =
2271 (SilcServerKEInternalContext *)sock->protocol->context;
2273 if (proto_ctx->packet)
2274 silc_packet_context_free(proto_ctx->packet);
2276 proto_ctx->packet = silc_packet_context_dup(packet);
2277 proto_ctx->dest_id_type = packet->src_id_type;
2278 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2279 packet->src_id_type);
2280 if (!proto_ctx->dest_id)
2283 /* Let the protocol handle the packet */
2284 silc_protocol_execute(sock->protocol, server->schedule,
2288 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2289 "protocol active, packet dropped."));
2293 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2295 * Connection authentication request packet. When we receive this packet
2296 * we will send to the other end information about our mandatory
2297 * authentication method for the connection. This packet maybe received
2300 SILC_LOG_DEBUG(("Connection authentication request packet"));
2301 if (packet->flags & SILC_PACKET_FLAG_LIST)
2303 silc_server_connection_auth_request(server, sock, packet);
2307 * Connection Authentication protocol packets
2309 case SILC_PACKET_CONNECTION_AUTH:
2310 /* Start of the authentication protocol. We receive here the
2311 authentication data and will verify it. */
2312 SILC_LOG_DEBUG(("Connection auth packet"));
2313 if (packet->flags & SILC_PACKET_FLAG_LIST)
2316 if (sock->protocol && sock->protocol->protocol->type
2317 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2319 SilcServerConnAuthInternalContext *proto_ctx =
2320 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2322 proto_ctx->packet = silc_packet_context_dup(packet);
2324 /* Let the protocol handle the packet */
2325 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2327 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2328 "protocol active, packet dropped."));
2332 case SILC_PACKET_NEW_ID:
2334 * Received New ID packet. This includes some new ID that has been
2335 * created. It may be for client, server or channel. This is the way
2336 * to distribute information about new registered entities in the
2339 SILC_LOG_DEBUG(("New ID packet"));
2340 if (packet->flags & SILC_PACKET_FLAG_LIST)
2341 silc_server_new_id_list(server, sock, packet);
2343 silc_server_new_id(server, sock, packet);
2346 case SILC_PACKET_NEW_CLIENT:
2348 * Received new client packet. This includes client information that
2349 * we will use to create initial client ID. After creating new
2350 * ID we will send it to the client.
2352 SILC_LOG_DEBUG(("New Client packet"));
2353 if (packet->flags & SILC_PACKET_FLAG_LIST)
2355 silc_server_new_client(server, sock, packet);
2358 case SILC_PACKET_NEW_SERVER:
2360 * Received new server packet. This includes Server ID and some other
2361 * information that we may save. This is received after server has
2364 SILC_LOG_DEBUG(("New Server packet"));
2365 if (packet->flags & SILC_PACKET_FLAG_LIST)
2367 silc_server_new_server(server, sock, packet);
2370 case SILC_PACKET_NEW_CHANNEL:
2372 * Received new channel packet. Information about new channel in the
2373 * network are distributed using this packet.
2375 SILC_LOG_DEBUG(("New Channel packet"));
2376 if (packet->flags & SILC_PACKET_FLAG_LIST)
2377 silc_server_new_channel_list(server, sock, packet);
2379 silc_server_new_channel(server, sock, packet);
2382 case SILC_PACKET_HEARTBEAT:
2384 * Received heartbeat.
2386 SILC_LOG_DEBUG(("Heartbeat packet"));
2387 if (packet->flags & SILC_PACKET_FLAG_LIST)
2391 case SILC_PACKET_KEY_AGREEMENT:
2393 * Received heartbeat.
2395 SILC_LOG_DEBUG(("Key agreement packet"));
2396 if (packet->flags & SILC_PACKET_FLAG_LIST)
2398 silc_server_key_agreement(server, sock, packet);
2401 case SILC_PACKET_REKEY:
2403 * Received re-key packet. The sender wants to regenerate the session
2406 SILC_LOG_DEBUG(("Re-key packet"));
2407 if (packet->flags & SILC_PACKET_FLAG_LIST)
2409 silc_server_rekey(server, sock, packet);
2412 case SILC_PACKET_REKEY_DONE:
2414 * The re-key is done.
2416 SILC_LOG_DEBUG(("Re-key done packet"));
2417 if (packet->flags & SILC_PACKET_FLAG_LIST)
2420 if (sock->protocol && sock->protocol->protocol &&
2421 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2423 SilcServerRekeyInternalContext *proto_ctx =
2424 (SilcServerRekeyInternalContext *)sock->protocol->context;
2426 if (proto_ctx->packet)
2427 silc_packet_context_free(proto_ctx->packet);
2429 proto_ctx->packet = silc_packet_context_dup(packet);
2431 /* Let the protocol handle the packet */
2432 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2434 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2435 "protocol active, packet dropped."));
2439 case SILC_PACKET_FTP:
2441 SILC_LOG_DEBUG(("FTP packet"));
2442 if (packet->flags & SILC_PACKET_FLAG_LIST)
2444 silc_server_ftp(server, sock, packet);
2447 case SILC_PACKET_RESUME_CLIENT:
2449 SILC_LOG_DEBUG(("Resume Client packet"));
2450 if (packet->flags & SILC_PACKET_FLAG_LIST)
2452 silc_server_resume_client(server, sock, packet);
2455 case SILC_PACKET_RESUME_ROUTER:
2456 /* Resume router packet received. This packet is received for backup
2457 router resuming protocol. */
2458 SILC_LOG_DEBUG(("Resume router packet"));
2459 if (packet->flags & SILC_PACKET_FLAG_LIST)
2461 silc_server_backup_resume_router(server, sock, packet);
2465 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2471 /* Creates connection to a remote router. */
2473 void silc_server_create_connection(SilcServer server,
2474 const char *remote_host, SilcUInt32 port)
2476 SilcServerConnection sconn;
2478 /* Allocate connection object for hold connection specific stuff. */
2479 sconn = silc_calloc(1, sizeof(*sconn));
2480 sconn->server = server;
2481 sconn->remote_host = strdup(remote_host);
2482 sconn->remote_port = port;
2483 sconn->no_reconnect = TRUE;
2485 silc_schedule_task_add(server->schedule, 0,
2486 silc_server_connect_router,
2487 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2488 SILC_TASK_PRI_NORMAL);
2491 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2493 silc_socket_free((SilcSocketConnection)context);
2496 /* Closes connection to socket connection */
2498 void silc_server_close_connection(SilcServer server,
2499 SilcSocketConnection sock)
2501 if (!server->sockets[sock->sock])
2504 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2506 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2507 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2508 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2511 /* We won't listen for this connection anymore */
2512 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2514 /* Unregister all tasks */
2515 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2517 /* Close the actual connection */
2518 silc_net_close_connection(sock->sock);
2519 server->sockets[sock->sock] = NULL;
2521 /* If sock->user_data is NULL then we'll check for active protocols
2522 here since the silc_server_free_sock_user_data has not been called
2523 for this connection. */
2524 if (!sock->user_data) {
2525 /* If any protocol is active cancel its execution. It will call
2526 the final callback which will finalize the disconnection. */
2527 if (sock->protocol) {
2528 silc_protocol_cancel(sock->protocol, server->schedule);
2529 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2530 silc_protocol_execute_final(sock->protocol, server->schedule);
2531 sock->protocol = NULL;
2536 silc_schedule_task_add(server->schedule, 0,
2537 silc_server_close_connection_final,
2538 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2539 SILC_TASK_PRI_NORMAL);
2542 /* Sends disconnect message to remote connection and disconnects the
2545 void silc_server_disconnect_remote(SilcServer server,
2546 SilcSocketConnection sock,
2547 SilcStatus status, ...)
2550 unsigned char buf[512];
2558 memset(buf, 0, sizeof(buf));
2559 va_start(ap, status);
2560 cp = va_arg(ap, char *);
2562 vsnprintf(buf, sizeof(buf) - 1, cp, ap);
2567 SILC_LOG_DEBUG(("Disconnecting remote host"));
2569 /* Notify remote end that the conversation is over. The notify message
2570 is tried to be sent immediately. */
2574 len += silc_utf8_encoded_len(buf, strlen(buf), SILC_STRING_ASCII);
2576 buffer = silc_buffer_alloc_size(len);
2580 buffer->data[0] = status;
2582 silc_utf8_encode(buf, strlen(buf), SILC_STRING_ASCII, buffer->data + 1,
2584 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2585 buffer->data, buffer->len, TRUE);
2586 silc_buffer_free(buffer);
2589 silc_server_packet_queue_purge(server, sock);
2591 /* Mark the connection to be disconnected */
2592 SILC_SET_DISCONNECTED(sock);
2593 silc_server_close_connection(server, sock);
2598 SilcClientEntry client;
2599 } *FreeClientInternal;
2601 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2603 FreeClientInternal i = (FreeClientInternal)context;
2605 silc_idlist_del_data(i->client);
2606 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2610 /* Frees client data and notifies about client's signoff. */
2612 void silc_server_free_client_data(SilcServer server,
2613 SilcSocketConnection sock,
2614 SilcClientEntry client,
2616 const char *signoff)
2618 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2620 /* If there is pending outgoing data for the client then purge it
2621 to the network before removing the client entry. */
2622 silc_server_packet_queue_purge(server, sock);
2625 /* Check if anyone is watching this nickname */
2626 if (server->server_type == SILC_ROUTER)
2627 silc_server_check_watcher_list(server, client, NULL,
2628 SILC_NOTIFY_TYPE_SIGNOFF);
2630 /* Send SIGNOFF notify to routers. */
2631 if (notify && !server->standalone && server->router)
2632 silc_server_send_notify_signoff(server, server->router->connection,
2633 server->server_type == SILC_SERVER ?
2634 FALSE : TRUE, client->id, signoff);
2636 /* Remove client from all channels */
2638 silc_server_remove_from_channels(server, NULL, client,
2639 TRUE, (char *)signoff, TRUE);
2641 silc_server_remove_from_channels(server, NULL, client,
2642 FALSE, NULL, FALSE);
2644 /* Remove this client from watcher list if it is */
2645 silc_server_del_from_watcher_list(server, client);
2648 /* Update statistics */
2649 server->stat.my_clients--;
2650 server->stat.clients--;
2651 if (server->stat.cell_clients)
2652 server->stat.cell_clients--;
2653 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2654 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2655 silc_schedule_task_del_by_context(server->schedule, client);
2657 /* We will not delete the client entry right away. We will take it
2658 into history (for WHOWAS command) for 5 minutes */
2661 silc_schedule_task_add(server->schedule, 0,
2662 silc_server_free_client_data_timeout,
2664 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2665 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2667 client->router = NULL;
2668 client->connection = NULL;
2671 /* Frees user_data pointer from socket connection object. This also sends
2672 appropriate notify packets to the network to inform about leaving
2675 void silc_server_free_sock_user_data(SilcServer server,
2676 SilcSocketConnection sock,
2677 const char *signoff_message)
2679 SILC_LOG_DEBUG(("Start"));
2681 switch (sock->type) {
2682 case SILC_SOCKET_TYPE_CLIENT:
2684 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2685 silc_server_free_client_data(server, sock, user_data, TRUE,
2689 case SILC_SOCKET_TYPE_SERVER:
2690 case SILC_SOCKET_TYPE_ROUTER:
2692 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2693 SilcServerEntry backup_router = NULL;
2696 backup_router = silc_server_backup_get(server, user_data->id);
2698 /* If this was our primary router connection then we're lost to
2699 the outside world. */
2700 if (server->router == user_data) {
2701 /* Check whether we have a backup router connection */
2702 if (!backup_router || backup_router == user_data) {
2703 silc_schedule_task_add(server->schedule, 0,
2704 silc_server_connect_to_router,
2707 SILC_TASK_PRI_NORMAL);
2709 server->id_entry->router = NULL;
2710 server->router = NULL;
2711 server->standalone = TRUE;
2712 backup_router = NULL;
2714 SILC_LOG_INFO(("New primary router is backup router %s",
2715 backup_router->server_name));
2716 SILC_LOG_DEBUG(("New primary router is backup router %s",
2717 backup_router->server_name));
2718 #ifdef BACKUP_SINGLE_ROUTER
2719 if (server->id_entry != backup_router) {
2720 #endif /* BACKUP_SINGLE_ROUTER */
2721 server->id_entry->router = backup_router;
2722 server->router = backup_router;
2723 server->router_connect = time(0);
2724 server->backup_primary = TRUE;
2725 #ifdef BACKUP_SINGLE_ROUTER
2727 server->id_entry->router = NULL;
2728 server->router = NULL;
2729 server->standalone = TRUE;
2731 #endif /* BACKUP_SINGLE_ROUTER */
2733 if (server->server_type == SILC_BACKUP_ROUTER) {
2734 server->server_type = SILC_ROUTER;
2736 /* We'll need to constantly try to reconnect to the primary
2737 router so that we'll see when it comes back online. */
2738 silc_server_backup_reconnect(server, sock->ip, sock->port,
2739 silc_server_backup_connected,
2743 /* Mark this connection as replaced */
2744 silc_server_backup_replaced_add(server, user_data->id,
2747 } else if (backup_router) {
2748 SILC_LOG_INFO(("Enabling the use of backup router %s",
2749 backup_router->server_name));
2750 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2751 backup_router->server_name));
2753 /* Mark this connection as replaced */
2754 silc_server_backup_replaced_add(server, user_data->id,
2758 if (!backup_router) {
2759 /* Free all client entries that this server owns as they will
2760 become invalid now as well. */
2762 silc_server_remove_clients_by_server(server, user_data, TRUE);
2763 if (server->server_type == SILC_SERVER)
2764 silc_server_remove_channels_by_server(server, user_data);
2766 /* Update the client entries of this server to the new backup
2767 router. This also removes the clients that *really* was owned
2768 by the primary router and went down with the router. */
2769 silc_server_update_clients_by_server(server, user_data, backup_router,
2771 silc_server_update_servers_by_server(server, user_data, backup_router);
2772 if (server->server_type == SILC_SERVER)
2773 silc_server_update_channels_by_server(server, user_data,
2777 /* Free the server entry */
2778 silc_server_backup_del(server, user_data);
2779 silc_server_backup_replaced_del(server, user_data);
2780 silc_idlist_del_data(user_data);
2781 if (!silc_idlist_del_server(server->local_list, user_data))
2782 silc_idlist_del_server(server->global_list, user_data);
2783 if (sock->type == SILC_SOCKET_TYPE_SERVER) {
2784 server->stat.my_servers--;
2786 server->stat.my_routers--;
2787 server->stat.routers--;
2789 server->stat.servers--;
2790 if (server->server_type == SILC_ROUTER)
2791 server->stat.cell_servers--;
2793 if (backup_router) {
2794 /* Announce all of our stuff that was created about 5 minutes ago.
2795 The backup router knows all the other stuff already. */
2796 if (server->server_type == SILC_ROUTER)
2797 silc_server_announce_servers(server, FALSE, time(0) - 300,
2798 backup_router->connection);
2800 /* Announce our clients and channels to the router */
2801 silc_server_announce_clients(server, time(0) - 300,
2802 backup_router->connection);
2803 silc_server_announce_channels(server, time(0) - 300,
2804 backup_router->connection);
2810 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2812 silc_idlist_del_data(user_data);
2813 silc_free(user_data);
2818 /* If any protocol is active cancel its execution */
2819 if (sock->protocol) {
2820 silc_protocol_cancel(sock->protocol, server->schedule);
2821 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2822 silc_protocol_execute_final(sock->protocol, server->schedule);
2823 sock->protocol = NULL;
2826 sock->user_data = NULL;
2829 /* Removes client from all channels it has joined. This is used when client
2830 connection is disconnected. If the client on a channel is last, the
2831 channel is removed as well. This sends the SIGNOFF notify types. */
2833 void silc_server_remove_from_channels(SilcServer server,
2834 SilcSocketConnection sock,
2835 SilcClientEntry client,
2837 const char *signoff_message,
2840 SilcChannelEntry channel;
2841 SilcChannelClientEntry chl;
2842 SilcHashTableList htl;
2845 SILC_LOG_DEBUG(("Start"));
2847 if (!client || !client->id)
2850 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2854 /* Remove the client from all channels. The client is removed from
2855 the channels' user list. */
2856 silc_hash_table_list(client->channels, &htl);
2857 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2858 channel = chl->channel;
2860 /* Remove channel if this is last client leaving the channel, unless
2861 the channel is permanent. */
2862 if (server->server_type == SILC_ROUTER &&
2863 silc_hash_table_count(channel->user_list) < 2) {
2864 silc_server_channel_delete(server, channel);
2868 silc_hash_table_del(client->channels, channel);
2869 silc_hash_table_del(channel->user_list, chl->client);
2870 channel->user_count--;
2872 /* If there is no global users on the channel anymore mark the channel
2873 as local channel. Do not check if the removed client is local client. */
2874 if (server->server_type != SILC_ROUTER && channel->global_users &&
2875 chl->client->router && !silc_server_channel_has_global(channel))
2876 channel->global_users = FALSE;
2879 server->stat.my_chanclients--;
2881 /* If there is not at least one local user on the channel then we don't
2882 need the channel entry anymore, we can remove it safely, unless the
2883 channel is permanent channel */
2884 if (server->server_type != SILC_ROUTER &&
2885 !silc_server_channel_has_local(channel)) {
2886 /* Notify about leaving client if this channel has global users. */
2887 if (notify && channel->global_users)
2888 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2889 SILC_NOTIFY_TYPE_SIGNOFF,
2890 signoff_message ? 2 : 1,
2891 clidp->data, clidp->len,
2892 signoff_message, signoff_message ?
2893 strlen(signoff_message) : 0);
2895 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2896 silc_server_channel_delete(server, channel);
2900 /* Send notify to channel about client leaving SILC and channel too */
2902 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2903 SILC_NOTIFY_TYPE_SIGNOFF,
2904 signoff_message ? 2 : 1,
2905 clidp->data, clidp->len,
2906 signoff_message, signoff_message ?
2907 strlen(signoff_message) : 0);
2909 /* Re-generate channel key if needed */
2910 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2911 if (!silc_server_create_channel_key(server, channel, 0))
2914 /* Send the channel key to the channel. The key of course is not sent
2915 to the client who was removed from the channel. */
2916 silc_server_send_channel_key(server, client->connection, channel,
2917 server->server_type == SILC_ROUTER ?
2918 FALSE : !server->standalone);
2922 silc_hash_table_list_reset(&htl);
2923 silc_buffer_free(clidp);
2926 /* Removes client from one channel. This is used for example when client
2927 calls LEAVE command to remove itself from the channel. Returns TRUE
2928 if channel still exists and FALSE if the channel is removed when
2929 last client leaves the channel. If `notify' is FALSE notify messages
2932 bool silc_server_remove_from_one_channel(SilcServer server,
2933 SilcSocketConnection sock,
2934 SilcChannelEntry channel,
2935 SilcClientEntry client,
2938 SilcChannelClientEntry chl;
2941 SILC_LOG_DEBUG(("Removing %s from channel %s",
2942 silc_id_render(client->id, SILC_ID_CLIENT),
2943 channel->channel_name));
2945 /* Get the entry to the channel, if this client is not on the channel
2947 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2950 /* Remove channel if this is last client leaving the channel, unless
2951 the channel is permanent. */
2952 if (server->server_type == SILC_ROUTER &&
2953 silc_hash_table_count(channel->user_list) < 2) {
2954 silc_server_channel_delete(server, channel);
2958 silc_hash_table_del(client->channels, chl->channel);
2959 silc_hash_table_del(channel->user_list, chl->client);
2960 channel->user_count--;
2962 /* If there is no global users on the channel anymore mark the channel
2963 as local channel. Do not check if the client is local client. */
2964 if (server->server_type != SILC_ROUTER && channel->global_users &&
2965 chl->client->router && !silc_server_channel_has_global(channel))
2966 channel->global_users = FALSE;
2969 server->stat.my_chanclients--;
2971 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2975 /* If there is not at least one local user on the channel then we don't
2976 need the channel entry anymore, we can remove it safely, unless the
2977 channel is permanent channel */
2978 if (server->server_type != SILC_ROUTER &&
2979 !silc_server_channel_has_local(channel)) {
2980 /* Notify about leaving client if this channel has global users. */
2981 if (notify && channel->global_users)
2982 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2983 SILC_NOTIFY_TYPE_LEAVE, 1,
2984 clidp->data, clidp->len);
2986 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2987 silc_server_channel_delete(server, channel);
2988 silc_buffer_free(clidp);
2992 /* Send notify to channel about client leaving the channel */
2994 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2995 SILC_NOTIFY_TYPE_LEAVE, 1,
2996 clidp->data, clidp->len);
2998 silc_buffer_free(clidp);
3002 /* Timeout callback. This is called if connection is idle or for some
3003 other reason is not responding within some period of time. This
3004 disconnects the remote end. */
3006 SILC_TASK_CALLBACK(silc_server_timeout_remote)
3008 SilcServer server = (SilcServer)context;
3009 SilcSocketConnection sock = server->sockets[fd];
3010 SilcProtocolType protocol = 0;
3012 SILC_LOG_DEBUG(("Start"));
3017 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
3018 sock->hostname, sock->ip));
3020 /* If we have protocol active we must assure that we call the protocol's
3021 final callback so that all the memory is freed. */
3022 if (sock->protocol) {
3023 protocol = sock->protocol->protocol->type;
3024 silc_protocol_cancel(sock->protocol, server->schedule);
3025 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3026 silc_protocol_execute_final(sock->protocol, server->schedule);
3027 sock->protocol = NULL;
3031 if (sock->user_data)
3032 silc_server_free_sock_user_data(server, sock, NULL);
3034 silc_server_disconnect_remote(server, sock,
3036 SILC_PROTOCOL_SERVER_CONNECTION_AUTH ?
3037 SILC_STATUS_ERR_AUTH_FAILED :
3038 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
3039 "Connection timeout");
3042 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
3043 function may be used only by router. In real SILC network all channels
3044 are created by routers thus this function is never used by normal
3047 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3048 SilcServerID *router_id,
3054 SilcChannelID *channel_id;
3055 SilcChannelEntry entry;
3059 SILC_LOG_DEBUG(("Creating new channel"));
3062 cipher = SILC_DEFAULT_CIPHER;
3064 hmac = SILC_DEFAULT_HMAC;
3066 /* Allocate cipher */
3067 if (!silc_cipher_alloc(cipher, &key))
3071 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3072 silc_cipher_free(key);
3076 channel_name = strdup(channel_name);
3078 /* Create the channel ID */
3079 if (!silc_id_create_channel_id(server, router_id, server->rng,
3081 silc_free(channel_name);
3082 silc_cipher_free(key);
3083 silc_hmac_free(newhmac);
3087 /* Create the channel */
3088 entry = silc_idlist_add_channel(server->local_list, channel_name,
3089 SILC_CHANNEL_MODE_NONE, channel_id,
3090 NULL, key, newhmac, 0);
3092 silc_free(channel_name);
3093 silc_cipher_free(key);
3094 silc_hmac_free(newhmac);
3095 silc_free(channel_id);
3099 entry->cipher = strdup(cipher);
3100 entry->hmac_name = strdup(hmac);
3102 /* Now create the actual key material */
3103 if (!silc_server_create_channel_key(server, entry,
3104 silc_cipher_get_key_len(key) / 8)) {
3105 silc_idlist_del_channel(server->local_list, entry);
3109 /* Notify other routers about the new channel. We send the packet
3110 to our primary route. */
3111 if (broadcast && server->standalone == FALSE)
3112 silc_server_send_new_channel(server, server->router->connection, TRUE,
3113 channel_name, entry->id,
3114 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3117 /* Distribute to backup routers */
3118 if (broadcast && server->server_type == SILC_ROUTER) {
3121 SilcUInt32 name_len = strlen(channel_name);
3122 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3123 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3125 packet = silc_channel_payload_encode(channel_name, name_len,
3126 cid, channel_id_len, entry->mode);
3127 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3128 packet->data, packet->len, FALSE, TRUE);
3130 silc_buffer_free(packet);
3133 server->stat.my_channels++;
3135 if (server->server_type == SILC_ROUTER)
3136 entry->users_resolved = TRUE;
3141 /* Same as above but creates the channel with Channel ID `channel_id. */
3144 silc_server_create_new_channel_with_id(SilcServer server,
3148 SilcChannelID *channel_id,
3151 SilcChannelEntry entry;
3155 SILC_LOG_DEBUG(("Creating new channel"));
3158 cipher = SILC_DEFAULT_CIPHER;
3160 hmac = SILC_DEFAULT_HMAC;
3162 /* Allocate cipher */
3163 if (!silc_cipher_alloc(cipher, &key))
3167 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3168 silc_cipher_free(key);
3172 channel_name = strdup(channel_name);
3174 /* Create the channel */
3175 entry = silc_idlist_add_channel(server->local_list, channel_name,
3176 SILC_CHANNEL_MODE_NONE, channel_id,
3177 NULL, key, newhmac, 0);
3179 silc_cipher_free(key);
3180 silc_hmac_free(newhmac);
3181 silc_free(channel_name);
3185 /* Now create the actual key material */
3186 if (!silc_server_create_channel_key(server, entry,
3187 silc_cipher_get_key_len(key) / 8)) {
3188 silc_idlist_del_channel(server->local_list, entry);
3192 /* Notify other routers about the new channel. We send the packet
3193 to our primary route. */
3194 if (broadcast && server->standalone == FALSE)
3195 silc_server_send_new_channel(server, server->router->connection, TRUE,
3196 channel_name, entry->id,
3197 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3200 /* Distribute to backup routers */
3201 if (broadcast && server->server_type == SILC_ROUTER) {
3204 SilcUInt32 name_len = strlen(channel_name);
3205 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3206 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3208 packet = silc_channel_payload_encode(channel_name, name_len,
3209 cid, channel_id_len, entry->mode);
3210 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3211 packet->data, packet->len, FALSE, TRUE);
3213 silc_buffer_free(packet);
3216 server->stat.my_channels++;
3218 if (server->server_type == SILC_ROUTER)
3219 entry->users_resolved = TRUE;
3224 /* Channel's key re-key timeout callback. */
3226 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3228 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3229 SilcServer server = (SilcServer)rekey->context;
3233 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3236 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3239 /* Generates new channel key. This is used to create the initial channel key
3240 but also to re-generate new key for channel. If `key_len' is provided
3241 it is the bytes of the key length. */
3243 bool silc_server_create_channel_key(SilcServer server,
3244 SilcChannelEntry channel,
3248 unsigned char channel_key[32], hash[32];
3251 SILC_LOG_DEBUG(("Generating channel key"));
3253 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3254 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3258 if (!channel->channel_key)
3259 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3260 channel->channel_key = NULL;
3266 else if (channel->key_len)
3267 len = channel->key_len / 8;
3269 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3271 /* Create channel key */
3272 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3275 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3277 /* Remove old key if exists */
3279 memset(channel->key, 0, channel->key_len / 8);
3280 silc_free(channel->key);
3284 channel->key_len = len * 8;
3285 channel->key = silc_memdup(channel_key, len);
3286 memset(channel_key, 0, sizeof(channel_key));
3288 /* Generate HMAC key from the channel key data and set it */
3290 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3291 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3292 silc_hmac_set_key(channel->hmac, hash,
3293 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3294 memset(hash, 0, sizeof(hash));
3296 if (server->server_type == SILC_ROUTER) {
3297 if (!channel->rekey)
3298 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3299 channel->rekey->context = (void *)server;
3300 channel->rekey->channel = channel;
3301 channel->rekey->key_len = key_len;
3302 if (channel->rekey->task)
3303 silc_schedule_task_del(server->schedule, channel->rekey->task);
3305 channel->rekey->task =
3306 silc_schedule_task_add(server->schedule, 0,
3307 silc_server_channel_key_rekey,
3308 (void *)channel->rekey,
3309 server->config->channel_rekey_secs, 0,
3311 SILC_TASK_PRI_NORMAL);
3317 /* Saves the channel key found in the encoded `key_payload' buffer. This
3318 function is used when we receive Channel Key Payload and also when we're
3319 processing JOIN command reply. Returns entry to the channel. */
3321 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3322 SilcBuffer key_payload,
3323 SilcChannelEntry channel)
3325 SilcChannelKeyPayload payload = NULL;
3326 SilcChannelID *id = NULL;
3327 unsigned char *tmp, hash[32];
3331 SILC_LOG_DEBUG(("Start"));
3333 /* Decode channel key payload */
3334 payload = silc_channel_key_payload_parse(key_payload->data,
3337 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3342 /* Get the channel entry */
3345 /* Get channel ID */
3346 tmp = silc_channel_key_get_id(payload, &tmp_len);
3347 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3353 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3355 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3357 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3358 silc_id_render(id, SILC_ID_CHANNEL)));
3364 tmp = silc_channel_key_get_key(payload, &tmp_len);
3370 cipher = silc_channel_key_get_cipher(payload, NULL);
3376 /* Remove old key if exists */
3378 memset(channel->key, 0, channel->key_len / 8);
3379 silc_free(channel->key);
3380 silc_cipher_free(channel->channel_key);
3383 /* Create new cipher */
3384 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3385 channel->channel_key = NULL;
3390 if (channel->cipher)
3391 silc_free(channel->cipher);
3392 channel->cipher = strdup(cipher);
3395 channel->key_len = tmp_len * 8;
3396 channel->key = silc_memdup(tmp, tmp_len);
3397 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3399 /* Generate HMAC key from the channel key data and set it */
3401 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3402 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3403 silc_hmac_set_key(channel->hmac, hash,
3404 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3406 memset(hash, 0, sizeof(hash));
3407 memset(tmp, 0, tmp_len);
3409 if (server->server_type == SILC_ROUTER) {
3410 if (!channel->rekey)
3411 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3412 channel->rekey->context = (void *)server;
3413 channel->rekey->channel = channel;
3414 if (channel->rekey->task)
3415 silc_schedule_task_del(server->schedule, channel->rekey->task);
3417 channel->rekey->task =
3418 silc_schedule_task_add(server->schedule, 0,
3419 silc_server_channel_key_rekey,
3420 (void *)channel->rekey,
3421 server->config->channel_rekey_secs, 0,
3423 SILC_TASK_PRI_NORMAL);
3429 silc_channel_key_payload_free(payload);
3434 /* Heartbeat callback. This function is set as argument for the
3435 silc_socket_set_heartbeat function. The library will call this function
3436 at the set time interval. */
3438 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3441 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3443 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3445 /* Send the heartbeat */
3446 silc_server_send_heartbeat(hb->server, sock);
3449 /* Returns assembled of all servers in the given ID list. The packet's
3450 form is dictated by the New ID payload. */
3452 static void silc_server_announce_get_servers(SilcServer server,
3453 SilcServerEntry remote,
3455 SilcBuffer *servers,
3456 unsigned long creation_time)
3458 SilcIDCacheList list;
3459 SilcIDCacheEntry id_cache;
3460 SilcServerEntry entry;
3463 /* Go through all clients in the list */
3464 if (silc_idcache_get_all(id_list->servers, &list)) {
3465 if (silc_idcache_list_first(list, &id_cache)) {
3467 entry = (SilcServerEntry)id_cache->context;
3469 /* Do not announce the one we've sending our announcements and
3470 do not announce ourself. Also check the creation time if it's
3472 if ((entry == remote) || (entry == server->id_entry) ||
3473 (creation_time && entry->data.created < creation_time)) {
3474 if (!silc_idcache_list_next(list, &id_cache))
3479 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3481 *servers = silc_buffer_realloc(*servers,
3483 (*servers)->truelen + idp->len :
3485 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3486 silc_buffer_put(*servers, idp->data, idp->len);
3487 silc_buffer_pull(*servers, idp->len);
3488 silc_buffer_free(idp);
3490 if (!silc_idcache_list_next(list, &id_cache))
3495 silc_idcache_list_free(list);
3500 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3506 p = silc_notify_payload_encode(notify, argc, ap);
3512 /* This function is used by router to announce existing servers to our
3513 primary router when we've connected to it. If `creation_time' is non-zero
3514 then only the servers that has been created after the `creation_time'
3515 will be announced. */
3517 void silc_server_announce_servers(SilcServer server, bool global,
3518 unsigned long creation_time,
3519 SilcSocketConnection remote)
3521 SilcBuffer servers = NULL;
3523 SILC_LOG_DEBUG(("Announcing servers"));
3525 /* Get servers in local list */
3526 silc_server_announce_get_servers(server, remote->user_data,
3527 server->local_list, &servers,
3531 /* Get servers in global list */
3532 silc_server_announce_get_servers(server, remote->user_data,
3533 server->global_list, &servers,
3537 silc_buffer_push(servers, servers->data - servers->head);
3538 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3540 /* Send the packet */
3541 silc_server_packet_send(server, remote,
3542 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3543 servers->data, servers->len, TRUE);
3545 silc_buffer_free(servers);
3549 /* Returns assembled packet of all clients in the given ID list. The
3550 packet's form is dictated by the New ID Payload. */
3552 static void silc_server_announce_get_clients(SilcServer server,
3554 SilcBuffer *clients,
3556 unsigned long creation_time)
3558 SilcIDCacheList list;
3559 SilcIDCacheEntry id_cache;
3560 SilcClientEntry client;
3563 unsigned char mode[4];
3565 /* Go through all clients in the list */
3566 if (silc_idcache_get_all(id_list->clients, &list)) {
3567 if (silc_idcache_list_first(list, &id_cache)) {
3569 client = (SilcClientEntry)id_cache->context;
3571 if (creation_time && client->data.created < creation_time) {
3572 if (!silc_idcache_list_next(list, &id_cache))
3577 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3579 *clients = silc_buffer_realloc(*clients,
3581 (*clients)->truelen + idp->len :
3583 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3584 silc_buffer_put(*clients, idp->data, idp->len);
3585 silc_buffer_pull(*clients, idp->len);
3587 SILC_PUT32_MSB(client->mode, mode);
3588 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3589 2, idp->data, idp->len,
3591 *umodes = silc_buffer_realloc(*umodes,
3593 (*umodes)->truelen + tmp->len :
3595 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3596 silc_buffer_put(*umodes, tmp->data, tmp->len);
3597 silc_buffer_pull(*umodes, tmp->len);
3598 silc_buffer_free(tmp);
3600 silc_buffer_free(idp);
3602 if (!silc_idcache_list_next(list, &id_cache))
3607 silc_idcache_list_free(list);
3611 /* This function is used to announce our existing clients to our router
3612 when we've connected to it. If `creation_time' is non-zero then only
3613 the clients that has been created after the `creation_time' will be
3616 void silc_server_announce_clients(SilcServer server,
3617 unsigned long creation_time,
3618 SilcSocketConnection remote)
3620 SilcBuffer clients = NULL;
3621 SilcBuffer umodes = NULL;
3623 SILC_LOG_DEBUG(("Announcing clients"));
3625 /* Get clients in local list */
3626 silc_server_announce_get_clients(server, server->local_list,
3627 &clients, &umodes, creation_time);
3629 /* As router we announce our global list as well */
3630 if (server->server_type == SILC_ROUTER)
3631 silc_server_announce_get_clients(server, server->global_list,
3632 &clients, &umodes, creation_time);
3635 silc_buffer_push(clients, clients->data - clients->head);
3636 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3638 /* Send the packet */
3639 silc_server_packet_send(server, remote,
3640 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3641 clients->data, clients->len, TRUE);
3643 silc_buffer_free(clients);
3647 silc_buffer_push(umodes, umodes->data - umodes->head);
3648 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3650 /* Send the packet */
3651 silc_server_packet_send(server, remote,
3652 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3653 umodes->data, umodes->len, TRUE);
3655 silc_buffer_free(umodes);
3659 /* Returns channel's topic for announcing it */
3661 void silc_server_announce_get_channel_topic(SilcServer server,
3662 SilcChannelEntry channel,
3667 if (channel->topic) {
3668 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3669 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3670 chidp->data, chidp->len,
3672 strlen(channel->topic));
3673 silc_buffer_free(chidp);
3677 /* Returns assembled packets for channel users of the `channel'. */
3679 void silc_server_announce_get_channel_users(SilcServer server,
3680 SilcChannelEntry channel,
3681 SilcBuffer *channel_modes,
3682 SilcBuffer *channel_users,
3683 SilcBuffer *channel_users_modes)
3685 SilcChannelClientEntry chl;
3686 SilcHashTableList htl;
3687 SilcBuffer chidp, clidp, csidp;
3690 unsigned char mode[4], *fkey = NULL;
3691 SilcUInt32 fkey_len = 0;
3694 SILC_LOG_DEBUG(("Start"));
3696 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3697 csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
3700 SILC_PUT32_MSB(channel->mode, mode);
3701 hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
3702 if (channel->founder_key)
3703 fkey = silc_pkcs_public_key_encode(channel->founder_key, &fkey_len);
3705 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
3706 6, csidp->data, csidp->len,
3709 hmac, hmac ? strlen(hmac) : 0,
3710 channel->passphrase,
3711 channel->passphrase ?
3712 strlen(channel->passphrase) : 0,
3716 silc_buffer_realloc(*channel_modes,
3718 (*channel_modes)->truelen + len : len));
3719 silc_buffer_pull_tail(*channel_modes,
3720 ((*channel_modes)->end -
3721 (*channel_modes)->data));
3722 silc_buffer_put(*channel_modes, tmp->data, tmp->len);
3723 silc_buffer_pull(*channel_modes, len);
3724 silc_buffer_free(tmp);
3729 /* Now find all users on the channel */
3730 silc_hash_table_list(channel->user_list, &htl);
3731 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3732 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3735 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3736 clidp->data, clidp->len,
3737 chidp->data, chidp->len);
3740 silc_buffer_realloc(*channel_users,
3742 (*channel_users)->truelen + len : len));
3743 silc_buffer_pull_tail(*channel_users,
3744 ((*channel_users)->end -
3745 (*channel_users)->data));
3747 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3748 silc_buffer_pull(*channel_users, len);
3749 silc_buffer_free(tmp);
3751 /* CUMODE notify for mode change on the channel */
3752 SILC_PUT32_MSB(chl->mode, mode);
3753 if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
3754 fkey = silc_pkcs_public_key_encode(channel->founder_key, &fkey_len);
3755 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3756 4, csidp->data, csidp->len,
3758 clidp->data, clidp->len,
3761 *channel_users_modes =
3762 silc_buffer_realloc(*channel_users_modes,
3763 (*channel_users_modes ?
3764 (*channel_users_modes)->truelen + len : len));
3765 silc_buffer_pull_tail(*channel_users_modes,
3766 ((*channel_users_modes)->end -
3767 (*channel_users_modes)->data));
3769 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3770 silc_buffer_pull(*channel_users_modes, len);
3771 silc_buffer_free(tmp);
3775 silc_buffer_free(clidp);
3777 silc_hash_table_list_reset(&htl);
3778 silc_buffer_free(chidp);
3779 silc_buffer_free(csidp);
3782 /* Returns assembled packets for all channels and users on those channels
3783 from the given ID List. The packets are in the form dictated by the
3784 New Channel and New Channel User payloads. */
3786 void silc_server_announce_get_channels(SilcServer server,
3788 SilcBuffer *channels,
3789 SilcBuffer **channel_modes,
3790 SilcBuffer *channel_users,
3791 SilcBuffer **channel_users_modes,
3792 SilcUInt32 *channel_users_modes_c,
3793 SilcBuffer **channel_topics,
3794 SilcChannelID ***channel_ids,
3795 unsigned long creation_time)
3797 SilcIDCacheList list;
3798 SilcIDCacheEntry id_cache;
3799 SilcChannelEntry channel;
3802 SilcUInt16 name_len;
3804 int i = *channel_users_modes_c;
3807 SILC_LOG_DEBUG(("Start"));
3809 /* Go through all channels in the list */
3810 if (silc_idcache_get_all(id_list->channels, &list)) {
3811 if (silc_idcache_list_first(list, &id_cache)) {
3813 channel = (SilcChannelEntry)id_cache->context;
3815 if (creation_time && channel->created < creation_time)
3820 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3821 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3822 name_len = strlen(channel->channel_name);
3825 len = 4 + name_len + id_len + 4;
3827 silc_buffer_realloc(*channels,
3828 (*channels ? (*channels)->truelen +
3830 silc_buffer_pull_tail(*channels,
3831 ((*channels)->end - (*channels)->data));
3832 silc_buffer_format(*channels,
3833 SILC_STR_UI_SHORT(name_len),
3834 SILC_STR_UI_XNSTRING(channel->channel_name,
3836 SILC_STR_UI_SHORT(id_len),
3837 SILC_STR_UI_XNSTRING(cid, id_len),
3838 SILC_STR_UI_INT(channel->mode),
3840 silc_buffer_pull(*channels, len);
3843 /* Channel user modes */
3844 *channel_users_modes = silc_realloc(*channel_users_modes,
3845 sizeof(**channel_users_modes) *
3847 (*channel_users_modes)[i] = NULL;
3848 *channel_modes = silc_realloc(*channel_modes,
3849 sizeof(**channel_modes) * (i + 1));
3850 (*channel_modes)[i] = NULL;
3851 *channel_ids = silc_realloc(*channel_ids,
3852 sizeof(**channel_ids) * (i + 1));
3853 (*channel_ids)[i] = NULL;
3854 silc_server_announce_get_channel_users(server, channel,
3855 &(*channel_modes)[i],
3857 &(*channel_users_modes)[i]);
3858 (*channel_ids)[i] = channel->id;
3860 /* Channel's topic */
3861 *channel_topics = silc_realloc(*channel_topics,
3862 sizeof(**channel_topics) * (i + 1));
3863 (*channel_topics)[i] = NULL;
3864 silc_server_announce_get_channel_topic(server, channel,
3865 &(*channel_topics)[i]);
3868 if (!silc_idcache_list_next(list, &id_cache))
3872 *channel_users_modes_c += i;
3875 silc_idcache_list_free(list);
3879 /* This function is used to announce our existing channels to our router
3880 when we've connected to it. This also announces the users on the
3881 channels to the router. If the `creation_time' is non-zero only the
3882 channels that was created after the `creation_time' are announced.
3883 Note that the channel users are still announced even if the `creation_time'
3886 void silc_server_announce_channels(SilcServer server,
3887 unsigned long creation_time,
3888 SilcSocketConnection remote)
3890 SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
3891 SilcBuffer *channel_users_modes = NULL;
3892 SilcBuffer *channel_topics = NULL;
3893 SilcUInt32 channel_users_modes_c = 0;
3894 SilcChannelID **channel_ids = NULL;
3896 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3898 /* Get channels and channel users in local list */
3899 silc_server_announce_get_channels(server, server->local_list,
3900 &channels, &channel_modes,
3902 &channel_users_modes,
3903 &channel_users_modes_c,
3905 &channel_ids, creation_time);
3907 /* Get channels and channel users in global list */
3908 if (server->server_type != SILC_SERVER)
3909 silc_server_announce_get_channels(server, server->global_list,
3910 &channels, &channel_modes,
3912 &channel_users_modes,
3913 &channel_users_modes_c,
3915 &channel_ids, creation_time);
3918 silc_buffer_push(channels, channels->data - channels->head);
3919 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3921 /* Send the packet */
3922 silc_server_packet_send(server, remote,
3923 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3924 channels->data, channels->len,
3927 silc_buffer_free(channels);
3930 if (channel_modes) {
3933 for (i = 0; i < channel_users_modes_c; i++) {
3934 if (!channel_modes[i])
3936 silc_buffer_push(channel_modes[i],
3937 channel_modes[i]->data -
3938 channel_modes[i]->head);
3939 SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
3940 channel_modes[i]->len);
3941 silc_server_packet_send_dest(server, remote,
3942 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3943 channel_ids[i], SILC_ID_CHANNEL,
3944 channel_modes[i]->data,
3945 channel_modes[i]->len,
3947 silc_buffer_free(channel_modes[i]);
3949 silc_free(channel_modes);
3952 if (channel_users) {
3953 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3954 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3955 channel_users->len);
3957 /* Send the packet */
3958 silc_server_packet_send(server, remote,
3959 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3960 channel_users->data, channel_users->len,
3963 silc_buffer_free(channel_users);
3966 if (channel_users_modes) {
3969 for (i = 0; i < channel_users_modes_c; i++) {
3970 if (!channel_users_modes[i])
3972 silc_buffer_push(channel_users_modes[i],
3973 channel_users_modes[i]->data -
3974 channel_users_modes[i]->head);
3975 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3976 channel_users_modes[i]->len);
3977 silc_server_packet_send_dest(server, remote,
3978 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3979 channel_ids[i], SILC_ID_CHANNEL,
3980 channel_users_modes[i]->data,
3981 channel_users_modes[i]->len,
3983 silc_buffer_free(channel_users_modes[i]);
3985 silc_free(channel_users_modes);
3988 if (channel_topics) {
3991 for (i = 0; i < channel_users_modes_c; i++) {
3992 if (!channel_topics[i])
3995 silc_buffer_push(channel_topics[i],
3996 channel_topics[i]->data -
3997 channel_topics[i]->head);
3998 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
3999 channel_topics[i]->len);
4000 silc_server_packet_send_dest(server, remote,
4001 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4002 channel_ids[i], SILC_ID_CHANNEL,
4003 channel_topics[i]->data,
4004 channel_topics[i]->len,
4006 silc_buffer_free(channel_topics[i]);
4008 silc_free(channel_topics);
4011 silc_free(channel_ids);
4014 /* Failure timeout callback. If this is called then we will immediately
4015 process the received failure. We always process the failure with timeout
4016 since we do not want to blindly trust to received failure packets.
4017 This won't be called (the timeout is cancelled) if the failure was
4018 bogus (it is bogus if remote does not close the connection after sending
4021 SILC_TASK_CALLBACK(silc_server_failure_callback)
4023 SilcServerFailureContext f = (SilcServerFailureContext)context;
4025 if (f->sock->protocol) {
4026 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
4027 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
4033 /* Assembles user list and users mode list from the `channel'. */
4035 bool silc_server_get_users_on_channel(SilcServer server,
4036 SilcChannelEntry channel,
4037 SilcBuffer *user_list,
4038 SilcBuffer *mode_list,
4039 SilcUInt32 *user_count)
4041 SilcChannelClientEntry chl;
4042 SilcHashTableList htl;
4043 SilcBuffer client_id_list;
4044 SilcBuffer client_mode_list;
4046 SilcUInt32 list_count = 0, len = 0;
4048 if (!silc_hash_table_count(channel->user_list))
4051 silc_hash_table_list(channel->user_list, &htl);
4052 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4053 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
4054 silc_hash_table_list_reset(&htl);
4056 client_id_list = silc_buffer_alloc(len);
4058 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
4059 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
4060 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
4062 silc_hash_table_list(channel->user_list, &htl);
4063 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4065 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4066 silc_buffer_put(client_id_list, idp->data, idp->len);
4067 silc_buffer_pull(client_id_list, idp->len);
4068 silc_buffer_free(idp);
4070 /* Client's mode on channel */
4071 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
4072 silc_buffer_pull(client_mode_list, 4);
4076 silc_hash_table_list_reset(&htl);
4077 silc_buffer_push(client_id_list,
4078 client_id_list->data - client_id_list->head);
4079 silc_buffer_push(client_mode_list,
4080 client_mode_list->data - client_mode_list->head);
4082 *user_list = client_id_list;
4083 *mode_list = client_mode_list;
4084 *user_count = list_count;
4088 /* Saves users and their modes to the `channel'. */
4090 void silc_server_save_users_on_channel(SilcServer server,
4091 SilcSocketConnection sock,
4092 SilcChannelEntry channel,
4093 SilcClientID *noadd,
4094 SilcBuffer user_list,
4095 SilcBuffer mode_list,
4096 SilcUInt32 user_count)
4101 SilcClientID *client_id;
4102 SilcClientEntry client;
4103 SilcIDCacheEntry cache;
4104 SilcChannelClientEntry chl;
4107 SILC_LOG_DEBUG(("Start"));
4109 for (i = 0; i < user_count; i++) {
4111 SILC_GET16_MSB(idp_len, user_list->data + 2);
4113 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
4114 silc_buffer_pull(user_list, idp_len);
4119 SILC_GET32_MSB(mode, mode_list->data);
4120 silc_buffer_pull(mode_list, 4);
4122 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
4123 silc_free(client_id);
4129 /* Check if we have this client cached already. */
4130 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4131 server->server_type, &cache);
4133 client = silc_idlist_find_client_by_id(server->global_list,
4134 client_id, server->server_type,
4139 /* If router did not find such Client ID in its lists then this must
4140 be bogus client or some router in the net is buggy. */
4141 if (server->server_type == SILC_ROUTER) {
4142 silc_free(client_id);
4146 /* We don't have that client anywhere, add it. The client is added
4147 to global list since server didn't have it in the lists so it must be
4149 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
4150 silc_id_dup(client_id, SILC_ID_CLIENT),
4151 sock->user_data, NULL, 0);
4153 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
4154 silc_free(client_id);
4158 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
4160 /* Found, if it is from global list we'll assure that we won't
4161 expire it now that the entry is on channel. */
4166 silc_free(client_id);
4168 if (!silc_server_client_on_channel(client, channel, &chl)) {
4169 /* Client was not on the channel, add it. */
4170 chl = silc_calloc(1, sizeof(*chl));
4171 chl->client = client;
4173 chl->channel = channel;
4174 silc_hash_table_add(channel->user_list, chl->client, chl);
4175 silc_hash_table_add(client->channels, chl->channel, chl);
4176 channel->user_count++;
4184 /* Saves channels and channels user modes to the `client'. Removes
4185 the client from those channels that are not sent in the list but
4188 void silc_server_save_user_channels(SilcServer server,
4189 SilcSocketConnection sock,
4190 SilcClientEntry client,
4191 SilcBuffer channels,
4192 SilcBuffer channels_user_modes)
4195 SilcUInt32 *chumodes;
4196 SilcChannelPayload entry;
4197 SilcChannelEntry channel;
4198 SilcChannelID *channel_id;
4199 SilcChannelClientEntry chl;
4200 SilcHashTable ht = NULL;
4201 SilcHashTableList htl;
4205 if (!channels ||!channels_user_modes)
4208 ch = silc_channel_payload_parse_list(channels->data, channels->len);
4209 if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
4211 ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL,
4212 NULL, NULL, NULL, TRUE);
4213 silc_dlist_start(ch);
4214 while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
4215 /* Check if we have this channel, and add it if we don't have it.
4216 Also add the client on the channel unless it is there already. */
4217 channel_id = silc_channel_get_id_parse(entry);
4218 channel = silc_idlist_find_channel_by_id(server->local_list,
4221 channel = silc_idlist_find_channel_by_id(server->global_list,
4224 if (server->server_type != SILC_SERVER) {
4225 silc_free(channel_id);
4230 /* We don't have that channel anywhere, add it. */
4231 name = silc_channel_get_name(entry, NULL);
4232 channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
4233 channel_id, server->router,
4236 silc_free(channel_id);
4243 channel->mode = silc_channel_get_mode(entry);
4245 /* Add the client on the channel */
4246 if (!silc_server_client_on_channel(client, channel, &chl)) {
4247 chl = silc_calloc(1, sizeof(*chl));
4248 chl->client = client;
4249 chl->mode = chumodes[i++];
4250 chl->channel = channel;
4251 silc_hash_table_add(channel->user_list, chl->client, chl);
4252 silc_hash_table_add(client->channels, chl->channel, chl);
4253 channel->user_count++;
4256 chl->mode = chumodes[i++];
4259 silc_hash_table_add(ht, channel, channel);
4260 silc_free(channel_id);
4262 silc_channel_payload_list_free(ch);
4263 silc_free(chumodes);
4267 /* Go through the list again and remove client from channels that
4268 are no part of the list. */
4270 silc_hash_table_list(client->channels, &htl);
4271 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4272 if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
4273 silc_hash_table_del(chl->channel->user_list, chl->client);
4274 silc_hash_table_del(chl->client->channels, chl->channel);
4278 silc_hash_table_list_reset(&htl);
4279 silc_hash_table_free(ht);
4281 silc_hash_table_list(client->channels, &htl);
4282 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4283 silc_hash_table_del(chl->channel->user_list, chl->client);
4284 silc_hash_table_del(chl->client->channels, chl->channel);
4287 silc_hash_table_list_reset(&htl);
4291 /* Lookups route to the client indicated by the `id_data'. The connection
4292 object and internal data object is returned. Returns NULL if route
4293 could not be found to the client. If the `client_id' is specified then
4294 it is used and the `id_data' is ignored. */
4296 SilcSocketConnection
4297 silc_server_get_client_route(SilcServer server,
4298 unsigned char *id_data,
4300 SilcClientID *client_id,
4301 SilcIDListData *idata,
4302 SilcClientEntry *client_entry)
4305 SilcClientEntry client;
4307 SILC_LOG_DEBUG(("Start"));
4310 *client_entry = NULL;
4312 /* Decode destination Client ID */
4314 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
4316 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
4320 id = silc_id_dup(client_id, SILC_ID_CLIENT);
4323 /* If the destination belongs to our server we don't have to route
4324 the packet anywhere but to send it to the local destination. */
4325 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
4329 /* If we are router and the client has router then the client is in
4330 our cell but not directly connected to us. */
4331 if (server->server_type == SILC_ROUTER && client->router) {
4332 /* We are of course in this case the client's router thus the route
4333 to the client is the server who owns the client. So, we will send
4334 the packet to that server. */
4336 *idata = (SilcIDListData)client->router;
4337 return client->router->connection;
4340 /* Seems that client really is directly connected to us */
4342 *idata = (SilcIDListData)client;
4344 *client_entry = client;
4345 return client->connection;
4348 /* Destination belongs to someone not in this server. If we are normal
4349 server our action is to send the packet to our router. */
4350 if (server->server_type != SILC_ROUTER && !server->standalone) {
4353 *idata = (SilcIDListData)server->router;
4354 return server->router->connection;
4357 /* We are router and we will perform route lookup for the destination
4358 and send the packet to fastest route. */
4359 if (server->server_type == SILC_ROUTER && !server->standalone) {
4360 /* Check first that the ID is valid */
4361 client = silc_idlist_find_client_by_id(server->global_list, id,
4364 SilcSocketConnection dst_sock;
4366 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
4370 *idata = (SilcIDListData)dst_sock->user_data;
4379 /* Encodes and returns channel list of channels the `client' has joined.
4380 Secret channels are not put to the list. */
4382 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
4383 SilcClientEntry client,
4386 SilcBuffer *user_mode_list)
4388 SilcBuffer buffer = NULL;
4389 SilcChannelEntry channel;
4390 SilcChannelClientEntry chl;
4391 SilcHashTableList htl;
4394 SilcUInt16 name_len;
4398 *user_mode_list = NULL;
4400 silc_hash_table_list(client->channels, &htl);
4401 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4402 channel = chl->channel;
4404 if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
4406 if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
4409 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4410 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4411 name_len = strlen(channel->channel_name);
4413 len = 4 + name_len + id_len + 4;
4414 buffer = silc_buffer_realloc(buffer,
4415 (buffer ? buffer->truelen + len : len));
4416 silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
4417 silc_buffer_format(buffer,
4418 SILC_STR_UI_SHORT(name_len),
4419 SILC_STR_UI_XNSTRING(channel->channel_name,
4421 SILC_STR_UI_SHORT(id_len),
4422 SILC_STR_UI_XNSTRING(cid, id_len),
4423 SILC_STR_UI_INT(chl->channel->mode),
4425 silc_buffer_pull(buffer, len);
4428 if (user_mode_list) {
4429 *user_mode_list = silc_buffer_realloc(*user_mode_list,
4431 (*user_mode_list)->truelen + 4 :
4433 silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
4434 (*user_mode_list)->data));
4435 SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
4436 silc_buffer_pull(*user_mode_list, 4);
4439 silc_hash_table_list_reset(&htl);
4442 silc_buffer_push(buffer, buffer->data - buffer->head);
4443 if (user_mode_list && *user_mode_list)
4444 silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
4445 (*user_mode_list)->head));
4450 /* Finds client entry by Client ID and if it is not found then resolves
4451 it using WHOIS command. */
4453 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4454 SilcClientID *client_id,
4455 bool always_resolve,
4458 SilcClientEntry client;
4463 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4466 client = silc_idlist_find_client_by_id(server->global_list,
4467 client_id, TRUE, NULL);
4468 if (!client && server->server_type == SILC_ROUTER)
4472 if (!client && server->standalone)
4475 if (!client || !client->nickname || !client->username ||
4477 SilcBuffer buffer, idp;
4480 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4481 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4482 client->resolve_cmd_ident = ++server->cmd_ident;
4485 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4486 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4487 server->cmd_ident, 1,
4488 4, idp->data, idp->len);
4489 silc_server_packet_send(server, client ? client->router->connection :
4490 server->router->connection,
4491 SILC_PACKET_COMMAND, 0,
4492 buffer->data, buffer->len, FALSE);
4493 silc_buffer_free(idp);
4494 silc_buffer_free(buffer);
4505 /* A timeout callback for the re-key. We will be the initiator of the
4508 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4510 SilcSocketConnection sock = (SilcSocketConnection)context;
4511 SilcIDListData idata = (SilcIDListData)sock->user_data;
4512 SilcServer server = (SilcServer)idata->rekey->context;
4513 SilcProtocol protocol;
4514 SilcServerRekeyInternalContext *proto_ctx;
4516 SILC_LOG_DEBUG(("Start"));
4518 /* Allocate internal protocol context. This is sent as context
4520 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4521 proto_ctx->server = (void *)server;
4522 proto_ctx->sock = sock;
4523 proto_ctx->responder = FALSE;
4524 proto_ctx->pfs = idata->rekey->pfs;
4526 /* Perform rekey protocol. Will call the final callback after the
4527 protocol is over. */
4528 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4529 &protocol, proto_ctx, silc_server_rekey_final);
4530 sock->protocol = protocol;
4532 /* Run the protocol */
4533 silc_protocol_execute(protocol, server->schedule, 0, 0);
4535 /* Re-register re-key timeout */
4536 silc_schedule_task_add(server->schedule, sock->sock,
4537 silc_server_rekey_callback,
4538 context, idata->rekey->timeout, 0,
4539 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4542 /* The final callback for the REKEY protocol. This will actually take the
4543 new key material into use. */
4545 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4547 SilcProtocol protocol = (SilcProtocol)context;
4548 SilcServerRekeyInternalContext *ctx =
4549 (SilcServerRekeyInternalContext *)protocol->context;
4550 SilcServer server = (SilcServer)ctx->server;
4551 SilcSocketConnection sock = ctx->sock;
4553 SILC_LOG_DEBUG(("Start"));
4555 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4556 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4557 /* Error occured during protocol */
4558 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4559 silc_protocol_cancel(protocol, server->schedule);
4560 silc_protocol_free(protocol);
4561 sock->protocol = NULL;
4563 silc_packet_context_free(ctx->packet);
4565 silc_ske_free(ctx->ske);
4570 /* Purge the outgoing data queue to assure that all rekey packets really
4571 go to the network before we quit the protocol. */
4572 silc_server_packet_queue_purge(server, sock);
4575 silc_protocol_free(protocol);
4576 sock->protocol = NULL;
4578 silc_packet_context_free(ctx->packet);
4580 silc_ske_free(ctx->ske);
4584 /* Task callback used to retrieve network statistical information from
4585 router server once in a while. */
4587 SILC_TASK_CALLBACK(silc_server_get_stats)
4589 SilcServer server = (SilcServer)context;
4590 SilcBuffer idp, packet;
4592 SILC_LOG_DEBUG(("Retrieving stats from router"));
4594 if (!server->standalone) {
4595 idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
4596 packet = silc_command_payload_encode_va(SILC_COMMAND_STATS,
4597 ++server->cmd_ident, 1,
4598 1, idp->data, idp->len);
4599 silc_server_packet_send(server, server->router->connection,
4600 SILC_PACKET_COMMAND, 0, packet->data,
4601 packet->len, FALSE);
4602 silc_buffer_free(packet);
4603 silc_buffer_free(idp);
4606 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
4607 server, 120, 0, SILC_TASK_TIMEOUT,