5 Author: Pekka Riikonen <priikone@silcnet.org>
7 Copyright (C) 1997 - 2001 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_router);
32 SILC_TASK_CALLBACK(silc_server_connect_to_router);
33 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
35 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
38 SILC_TASK_CALLBACK(silc_server_packet_process);
39 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
40 SILC_TASK_CALLBACK(silc_server_timeout_remote);
41 SILC_TASK_CALLBACK(silc_server_failure_callback);
42 SILC_TASK_CALLBACK(silc_server_rekey_callback);
44 /* Allocates a new SILC server object. This has to be done before the server
45 can be used. After allocation one must call silc_server_init to initialize
46 the server. The new allocated server object is returned to the new_server
49 int silc_server_alloc(SilcServer *new_server)
53 SILC_LOG_DEBUG(("Allocating new server object"));
55 server = silc_calloc(1, sizeof(*server));
56 server->server_type = SILC_SERVER;
57 server->standalone = TRUE;
58 server->local_list = silc_calloc(1, sizeof(*server->local_list));
59 server->global_list = silc_calloc(1, sizeof(*server->global_list));
60 server->pending_commands = silc_dlist_init();
62 server->sim = silc_dlist_init();
70 /* Free's the SILC server object. This is called at the very end before
73 void silc_server_free(SilcServer server)
80 silc_free(server->local_list);
81 silc_free(server->global_list);
83 silc_rng_free(server->rng);
86 silc_pkcs_free(server->pkcs);
89 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
90 silc_dlist_del(server->sim, sim);
93 silc_dlist_uninit(server->sim);
96 silc_free(server->params);
98 if (server->pending_commands)
99 silc_dlist_uninit(server->pending_commands);
105 /* Initializes the entire SILC server. This is called always before running
106 the server. This is called only once at the initialization of the program.
107 This binds the server to its listenning port. After this function returns
108 one should call silc_server_run to start the server. This returns TRUE
109 when everything is ok to run the server. Configuration file must be
110 read and parsed before calling this. */
112 int silc_server_init(SilcServer server)
114 int *sock = NULL, sock_count, i;
116 SilcServerEntry id_entry;
117 SilcIDListPurge purge;
118 SilcServerConfigSectionListenPort *listen;
120 SILC_LOG_DEBUG(("Initializing server"));
122 assert(server->config);
124 /* Set public and private keys */
125 if (!server->config->server_keys ||
126 !server->config->server_keys->public_key ||
127 !server->config->server_keys->private_key) {
128 SILC_LOG_ERROR(("Server public key and/or private key does not exist"));
131 server->public_key = server->config->server_keys->public_key;
132 server->private_key = server->config->server_keys->private_key;
134 /* XXX After server is made as Silc Server Library this can be given
135 as argument, for now this is hard coded */
136 server->params = silc_calloc(1, sizeof(*server->params));
137 server->params->retry_count = SILC_SERVER_RETRY_COUNT;
138 server->params->retry_interval_min = SILC_SERVER_RETRY_INTERVAL_MIN;
139 server->params->retry_interval_max = SILC_SERVER_RETRY_INTERVAL_MAX;
140 server->params->retry_keep_trying = FALSE;
141 server->params->protocol_timeout = 60;
142 server->params->require_reverse_mapping = FALSE;
144 /* Set log files where log message should be saved. */
145 server->config->server = server;
147 /* Register all configured ciphers, PKCS and hash functions. */
148 if (!silc_server_config_register_ciphers(server->config))
149 silc_cipher_register_default();
150 if (!silc_server_config_register_pkcs(server->config))
151 silc_pkcs_register_default();
152 if (!silc_server_config_register_hashfuncs(server->config))
153 silc_hash_register_default();
154 if (!silc_server_config_register_hmacs(server->config))
155 silc_hmac_register_default();
157 /* Initialize random number generator for the server. */
158 server->rng = silc_rng_alloc();
159 silc_rng_init(server->rng);
160 silc_rng_global_init(server->rng);
162 /* Initialize hash functions for server to use */
163 silc_hash_alloc("md5", &server->md5hash);
164 silc_hash_alloc("sha1", &server->sha1hash);
166 /* Initialize none cipher */
167 silc_cipher_alloc("none", &server->none_cipher);
169 /* Allocate PKCS context for local public and private keys */
170 silc_pkcs_alloc(server->public_key->name, &server->pkcs);
171 silc_pkcs_public_key_set(server->pkcs, server->public_key);
172 silc_pkcs_private_key_set(server->pkcs, server->private_key);
174 /* Create a listening server. Note that our server can listen on multiple
175 ports. All listeners are created here and now. */
177 listen = server->config->listen_port;
181 tmp = silc_net_create_server(server->config->listen_port->port,
182 server->config->listen_port->listener_ip);
185 SILC_LOG_ERROR(("Could not create server listener: %s on %d",
186 server->config->listen_port->listener_ip,
187 server->config->listen_port->port));
191 sock = silc_realloc(sock, sizeof(*sock) * (sock_count + 1));
192 sock[sock_count] = tmp;
194 listen = listen->next;
197 /* Initialize ID caches */
198 server->local_list->clients =
199 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
200 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
201 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
203 /* These are allocated for normal server as well as these hold some
204 global information that the server has fetched from its router. For
205 router these are used as they are supposed to be used on router. */
206 server->global_list->clients =
207 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
208 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
209 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
211 /* Allocate the entire socket list that is used in server. Eventually
212 all connections will have entry in this table (it is a table of
213 pointers to the actual object that is allocated individually
215 server->sockets = silc_calloc(SILC_SERVER_MAX_CONNECTIONS,
216 sizeof(*server->sockets));
218 for (i = 0; i < sock_count; i++) {
219 SilcSocketConnection newsocket = NULL;
221 /* Set socket to non-blocking mode */
222 silc_net_set_socket_nonblock(sock[i]);
223 server->sock = sock[i];
225 /* Add ourselves also to the socket table. The entry allocated above
226 is sent as argument for fast referencing in the future. */
227 silc_socket_alloc(sock[i], SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
228 server->sockets[sock[i]] = newsocket;
230 /* Perform name and address lookups to resolve the listenning address
232 if (!silc_net_check_local_by_sock(sock[i], &newsocket->hostname,
234 if ((server->params->require_reverse_mapping && !newsocket->hostname) ||
236 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
237 newsocket->hostname ? newsocket->hostname :
238 newsocket->ip ? newsocket->ip : ""));
239 server->stat.conn_failures++;
242 if (!newsocket->hostname)
243 newsocket->hostname = strdup(newsocket->ip);
245 newsocket->port = silc_net_get_local_port(sock[i]);
247 /* Create a Server ID for the server. */
248 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
253 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
254 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
255 server->id_type = SILC_ID_SERVER;
256 server->server_name = server->config->server_info->server_name;
258 /* Add ourselves to the server list. We don't have a router yet
259 beacuse we haven't established a route yet. It will be done later.
260 For now, NULL is sent as router. This allocates new entry to
263 silc_idlist_add_server(server->local_list,
264 server->config->server_info->server_name,
265 server->server_type, server->id, NULL, NULL);
267 SILC_LOG_ERROR(("Could not add ourselves to cache"));
270 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
272 /* Put the allocated socket pointer also to the entry allocated above
273 for fast back-referencing to the socket list. */
274 newsocket->user_data = (void *)id_entry;
275 id_entry->connection = (void *)newsocket;
276 server->id_entry = id_entry;
279 /* Register protocols */
280 silc_server_protocols_register();
282 /* Initialize the scheduler. */
283 server->schedule = silc_schedule_init(SILC_SERVER_MAX_CONNECTIONS);
284 if (!server->schedule)
287 /* Add the first task to the scheduler. This is task that is executed by
288 timeout. It expires as soon as the caller calls silc_server_run. This
289 task performs authentication protocol and key exchange with our
291 silc_schedule_task_add(server->schedule, sock[0],
292 silc_server_connect_to_router,
293 (void *)server, 0, 1,
295 SILC_TASK_PRI_NORMAL);
297 /* Add listener task to the scheduler. This task receives new connections
298 to the server. This task remains on the queue until the end of the
300 silc_schedule_task_add(server->schedule, sock[0],
301 silc_server_accept_new_connection,
302 (void *)server, 0, 0,
304 SILC_TASK_PRI_NORMAL);
305 server->listenning = TRUE;
307 /* Send log file configuration */
308 silc_server_config_setlogfiles(server->config, server->schedule);
310 /* If server connections has been configured then we must be router as
311 normal server cannot have server connections, only router connections. */
312 if (server->config->servers) {
313 SilcServerConfigSectionServerConnection *ptr = server->config->servers;
315 server->server_type = SILC_ROUTER;
317 if (ptr->backup_router) {
318 server->server_type = SILC_BACKUP_ROUTER;
319 server->backup_router = TRUE;
320 server->id_entry->server_type = SILC_BACKUP_ROUTER;
327 /* Register the ID Cache purge task. This periodically purges the ID cache
328 and removes the expired cache entries. */
330 /* Clients local list */
331 purge = silc_calloc(1, sizeof(*purge));
332 purge->cache = server->local_list->clients;
333 purge->schedule = server->schedule;
334 purge->timeout = 600;
335 silc_schedule_task_add(purge->schedule, 0,
337 (void *)purge, purge->timeout, 0,
338 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
340 /* Clients global list */
341 purge = silc_calloc(1, sizeof(*purge));
342 purge->cache = server->global_list->clients;
343 purge->schedule = server->schedule;
344 purge->timeout = 300;
345 silc_schedule_task_add(purge->schedule, 0,
347 (void *)purge, purge->timeout, 0,
348 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
350 SILC_LOG_DEBUG(("Server initialized"));
352 /* We are done here, return succesfully */
356 for (i = 0; i < sock_count; i++)
357 silc_net_close_server(sock[i]);
362 /* Fork server to background */
364 void silc_server_daemonise(SilcServer server)
368 SILC_LOG_DEBUG(("Forking SILC server to background"));
373 SILC_LOG_DEBUG(("fork() failed, cannot proceed"));
378 SILC_LOG_DEBUG(("Server started as user"));
380 SILC_LOG_DEBUG(("Server started as root. Dropping privileges."));
386 /* Drop root privligies. If this cannot be done, die. */
388 void silc_server_drop(SilcServer server)
390 /* Are we executing silcd as root or a regular user? */
396 if (!server->config->identity || !server->config->identity->user ||
397 !server->config->identity->group) {
398 fprintf(stderr, "Error:"
399 "\tSILC server must not be run as root. For the security of your\n"
400 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
401 "\tuser account. Modify the [Identity] configuration section to run\n"
402 "\tthe server as non-root user.\n");
406 /* Get the values given for user and group in configuration file */
407 user=server->config->identity->user;
408 group=server->config->identity->group;
410 /* Check whether the user/group information is text */
411 if (atoi(user)!=0 || atoi(group)!=0) {
412 SILC_LOG_DEBUG(("Invalid user and/or group information"));
413 SILC_LOG_DEBUG(("User and/or group given as number"));
414 fprintf(stderr, "Invalid user and/or group information\n");
415 fprintf(stderr, "Please assign them as names, not numbers\n");
419 /* Catch the nasty incident of string "0" returning 0 from atoi */
420 if (strcmp("0", user)==0 || strcmp("0", group)==0) {
421 SILC_LOG_DEBUG(("User and/or group configured to 0. Unacceptable"));
422 fprintf(stderr, "User and/or group configured to 0. Exiting\n");
426 if (!(pw=getpwnam(user))) {
427 fprintf(stderr, "No such user %s found\n", user);
431 if (!(gr=getgrnam(group))) {
432 fprintf(stderr, "No such group %s found\n", group);
436 /* Check whether user and/or group is set to root. If yes, exit
437 immediately. Otherwise, setgid and setuid server to user.group */
438 if (gr->gr_gid==0 || pw->pw_uid==0) {
439 fprintf(stderr, "Error:"
440 "\tSILC server must not be run as root. For the security of your\n"
441 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
442 "\tuser account. Modify the [Identity] configuration section to run\n"
443 "\tthe server as non-root user.\n");
446 SILC_LOG_DEBUG(("Changing to group %s", group));
447 if (setgid(gr->gr_gid)==0) {
448 SILC_LOG_DEBUG(("Setgid to %s", group));
450 SILC_LOG_DEBUG(("Setgid to %s failed", group));
451 fprintf(stderr, "Tried to setgid %s but no such group. Exiting\n",
455 #if defined HAVE_SETGROUPS && defined HAVE_INITGROUPS
456 if (setgroups(0, NULL)!=0) {
457 SILC_LOG_DEBUG(("Setgroups to NULL failed"));
458 fprintf(stderr, "Tried to setgroups NULL but failed. Exiting\n");
461 if (initgroups(user, gr->gr_gid)!=0) {
462 SILC_LOG_DEBUG(("Initgroups to user %s (gid=%d) failed", user, gr->gr_gid));
463 fprintf(stderr, "Tried to initgroups %s (gid=%d) but no such user. Exiting\n",
468 SILC_LOG_DEBUG(("Changing to user %s", user));
469 if (setuid(pw->pw_uid)==0) {
470 SILC_LOG_DEBUG(("Setuid to %s", user));
472 SILC_LOG_DEBUG(("Setuid to %s failed", user));
473 fprintf(stderr, "Tried to setuid %s but no such user. Exiting\n",
481 /* The heart of the server. This runs the scheduler thus runs the server.
482 When this returns the server has been stopped and the program will
485 void silc_server_run(SilcServer server)
487 SILC_LOG_DEBUG(("Running server"));
489 SILC_LOG_INFO(("SILC Server started"));
491 /* Start the scheduler, the heart of the SILC server. When this returns
492 the program will be terminated. */
493 silc_schedule(server->schedule);
496 /* Stops the SILC server. This function is used to shutdown the server.
497 This is usually called after the scheduler has returned. After stopping
498 the server one should call silc_server_free. */
500 void silc_server_stop(SilcServer server)
502 SILC_LOG_DEBUG(("Stopping server"));
504 if (server->schedule) {
505 silc_schedule_stop(server->schedule);
506 silc_schedule_uninit(server->schedule);
509 silc_server_protocols_unregister();
511 SILC_LOG_DEBUG(("Server stopped"));
514 /* Function that is called when the network connection to a router has
515 been established. This will continue with the key exchange protocol
516 with the remote router. */
518 void silc_server_start_key_exchange(SilcServer server,
519 SilcServerConnection sconn,
522 SilcSocketConnection newsocket;
523 SilcProtocol protocol;
524 SilcServerKEInternalContext *proto_ctx;
527 /* Set socket options */
528 silc_net_set_socket_nonblock(sock);
529 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
531 /* Create socket connection for the connection. Even though we
532 know that we are connecting to a router we will mark the socket
533 to be unknown connection until we have executed authentication
535 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
536 server->sockets[sock] = newsocket;
537 newsocket->hostname = strdup(sconn->remote_host);
538 newsocket->ip = strdup(sconn->remote_host);
539 newsocket->port = sconn->remote_port;
540 sconn->sock = newsocket;
542 /* Allocate internal protocol context. This is sent as context
544 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
545 proto_ctx->server = (void *)server;
546 proto_ctx->context = (void *)sconn;
547 proto_ctx->sock = newsocket;
548 proto_ctx->rng = server->rng;
549 proto_ctx->responder = FALSE;
551 /* Perform key exchange protocol. silc_server_connect_to_router_second
552 will be called after the protocol is finished. */
553 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
554 &protocol, proto_ctx,
555 silc_server_connect_to_router_second);
556 newsocket->protocol = protocol;
558 /* Register a timeout task that will be executed if the protocol
559 is not executed within set limit. */
560 proto_ctx->timeout_task =
561 silc_schedule_task_add(server->schedule, sock,
562 silc_server_timeout_remote,
563 server, server->params->protocol_timeout,
564 server->params->protocol_timeout_usec,
568 /* Register the connection for network input and output. This sets
569 that scheduler will listen for incoming packets for this connection
570 and sets that outgoing packets may be sent to this connection as
571 well. However, this doesn't set the scheduler for outgoing traffic,
572 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
573 later when outgoing data is available. */
574 context = (void *)server;
575 SILC_REGISTER_CONNECTION_FOR_IO(sock);
577 /* Run the protocol */
578 silc_protocol_execute(protocol, server->schedule, 0, 0);
581 /* Timeout callback that will be called to retry connecting to remote
582 router. This is used by both normal and router server. This will wait
583 before retrying the connecting. The timeout is generated by exponential
584 backoff algorithm. */
586 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
588 SilcServerConnection sconn = (SilcServerConnection)context;
589 SilcServer server = sconn->server;
591 SILC_LOG_INFO(("Retrying connecting to a router"));
593 /* Calculate next timeout */
594 if (sconn->retry_count >= 1) {
595 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
596 if (sconn->retry_timeout > SILC_SERVER_RETRY_INTERVAL_MAX)
597 sconn->retry_timeout = SILC_SERVER_RETRY_INTERVAL_MAX;
599 sconn->retry_timeout = server->params->retry_interval_min;
601 sconn->retry_count++;
602 sconn->retry_timeout = sconn->retry_timeout +
603 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
605 /* If we've reached max retry count, give up. */
606 if (sconn->retry_count > server->params->retry_count &&
607 server->params->retry_keep_trying == FALSE) {
608 SILC_LOG_ERROR(("Could not connect to router, giving up"));
609 silc_free(sconn->remote_host);
614 /* Wait one before retrying */
615 silc_schedule_task_add(server->schedule, fd, silc_server_connect_router,
616 context, sconn->retry_timeout,
617 server->params->retry_interval_min_usec,
618 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
621 /* Generic routine to use connect to a router. */
623 SILC_TASK_CALLBACK(silc_server_connect_router)
625 SilcServerConnection sconn = (SilcServerConnection)context;
626 SilcServer server = sconn->server;
629 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
630 (sconn->backup ? "backup router" : "router"),
631 sconn->remote_host, sconn->remote_port));
633 server->router_connect = time(0);
635 /* Connect to remote host */
636 sock = silc_net_create_connection(server->config->listen_port->local_ip,
640 SILC_LOG_ERROR(("Could not connect to router"));
641 silc_schedule_task_add(server->schedule, fd,
642 silc_server_connect_to_router_retry,
643 context, 0, 1, SILC_TASK_TIMEOUT,
644 SILC_TASK_PRI_NORMAL);
648 /* Continue with key exchange protocol */
649 silc_server_start_key_exchange(server, sconn, sock);
652 /* This function connects to our primary router or if we are a router this
653 establishes all our primary routes. This is called at the start of the
654 server to do authentication and key exchange with our router - called
657 SILC_TASK_CALLBACK(silc_server_connect_to_router)
659 SilcServer server = (SilcServer)context;
660 SilcServerConnection sconn;
661 SilcServerConfigSectionServerConnection *ptr;
663 SILC_LOG_DEBUG(("Connecting to router(s)"));
665 if (server->server_type == SILC_SERVER) {
666 SILC_LOG_DEBUG(("We are normal server"));
667 } else if (server->server_type == SILC_ROUTER) {
668 SILC_LOG_DEBUG(("We are router"));
670 SILC_LOG_DEBUG(("We are backup router/normal server"));
673 /* Create the connections to all our routes */
674 ptr = server->config->routers;
677 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
678 ptr->backup_router ? "Backup router" : "Router",
679 ptr->initiator ? "Initiator" : "Responder",
680 ptr->host, ptr->port));
682 if (ptr->initiator) {
683 /* Allocate connection object for hold connection specific stuff. */
684 sconn = silc_calloc(1, sizeof(*sconn));
685 sconn->server = server;
686 sconn->remote_host = strdup(ptr->host);
687 sconn->remote_port = ptr->port;
688 sconn->backup = ptr->backup_router;
690 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
691 sconn->backup_replace_port = ptr->backup_replace_port;
694 if (!server->router_conn && !sconn->backup)
695 server->router_conn = sconn;
697 silc_schedule_task_add(server->schedule, fd,
698 silc_server_connect_router,
699 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
700 SILC_TASK_PRI_NORMAL);
709 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
711 /* There wasn't a configured router, we will continue but we don't
712 have a connection to outside world. We will be standalone server. */
713 server->standalone = TRUE;
716 /* Second part of connecting to router(s). Key exchange protocol has been
717 executed and now we will execute authentication protocol. */
719 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
721 SilcProtocol protocol = (SilcProtocol)context;
722 SilcServerKEInternalContext *ctx =
723 (SilcServerKEInternalContext *)protocol->context;
724 SilcServer server = (SilcServer)ctx->server;
725 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
726 SilcSocketConnection sock = ctx->sock;
727 SilcServerConnAuthInternalContext *proto_ctx;
728 SilcServerConfigSectionServerConnection *conn = NULL;
730 SILC_LOG_DEBUG(("Start"));
732 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
733 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
734 /* Error occured during protocol */
735 silc_protocol_free(protocol);
736 sock->protocol = NULL;
737 silc_ske_free_key_material(ctx->keymat);
739 silc_packet_context_free(ctx->packet);
741 silc_ske_free(ctx->ske);
742 silc_free(ctx->dest_id);
744 silc_schedule_task_del_by_callback(server->schedule,
745 silc_server_failure_callback);
746 silc_server_disconnect_remote(server, sock, "Server closed connection: "
747 "Key exchange failed");
751 /* We now have the key material as the result of the key exchange
752 protocol. Take the key material into use. Free the raw key material
753 as soon as we've set them into use. */
754 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
755 ctx->sock, ctx->keymat,
756 ctx->ske->prop->cipher,
757 ctx->ske->prop->pkcs,
758 ctx->ske->prop->hash,
759 ctx->ske->prop->hmac,
760 ctx->ske->prop->group,
762 silc_protocol_free(protocol);
763 sock->protocol = NULL;
764 silc_ske_free_key_material(ctx->keymat);
766 silc_packet_context_free(ctx->packet);
768 silc_ske_free(ctx->ske);
769 silc_free(ctx->dest_id);
771 silc_schedule_task_del_by_callback(server->schedule,
772 silc_server_failure_callback);
773 silc_server_disconnect_remote(server, sock, "Server closed connection: "
774 "Key exchange failed");
777 silc_ske_free_key_material(ctx->keymat);
779 /* Allocate internal context for the authentication protocol. This
780 is sent as context for the protocol. */
781 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
782 proto_ctx->server = (void *)server;
783 proto_ctx->context = (void *)sconn;
784 proto_ctx->sock = sock;
785 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
786 proto_ctx->dest_id_type = ctx->dest_id_type;
787 proto_ctx->dest_id = ctx->dest_id;
789 /* Resolve the authentication method used in this connection. Check if
790 we find a match from user configured connections */
791 conn = silc_server_config_find_router_conn(server->config,
795 /* Match found. Use the configured authentication method */
796 proto_ctx->auth_meth = conn->auth_meth;
797 if (conn->auth_data) {
798 proto_ctx->auth_data = strdup(conn->auth_data);
799 proto_ctx->auth_data_len = strlen(conn->auth_data);
802 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
803 sock->hostname, sock->ip, sock->port));
804 silc_protocol_free(protocol);
805 sock->protocol = NULL;
807 silc_packet_context_free(ctx->packet);
809 silc_ske_free(ctx->ske);
810 silc_free(ctx->dest_id);
812 silc_schedule_task_del_by_callback(server->schedule,
813 silc_server_failure_callback);
814 silc_server_disconnect_remote(server, sock, "Server closed connection: "
815 "Key exchange failed");
819 /* Free old protocol as it is finished now */
820 silc_protocol_free(protocol);
822 silc_packet_context_free(ctx->packet);
824 sock->protocol = NULL;
826 /* Allocate the authentication protocol. This is allocated here
827 but we won't start it yet. We will be receiving party of this
828 protocol thus we will wait that connecting party will make
830 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
831 &sock->protocol, proto_ctx,
832 silc_server_connect_to_router_final);
834 /* Register timeout task. If the protocol is not executed inside
835 this timelimit the connection will be terminated. Currently
836 this is 15 seconds and is hard coded limit (XXX). */
837 proto_ctx->timeout_task =
838 silc_schedule_task_add(server->schedule, sock->sock,
839 silc_server_timeout_remote,
840 (void *)server, 15, 0,
844 /* Run the protocol */
845 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
848 /* Finalizes the connection to router. Registers a server task to the
849 queue so that we can accept new connections. */
851 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
853 SilcProtocol protocol = (SilcProtocol)context;
854 SilcServerConnAuthInternalContext *ctx =
855 (SilcServerConnAuthInternalContext *)protocol->context;
856 SilcServer server = (SilcServer)ctx->server;
857 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
858 SilcSocketConnection sock = ctx->sock;
859 SilcServerEntry id_entry;
861 SilcServerHBContext hb_context;
862 unsigned char *id_string;
864 SilcIDListData idata;
866 SILC_LOG_DEBUG(("Start"));
868 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
869 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
870 /* Error occured during protocol */
871 silc_free(ctx->dest_id);
872 silc_server_disconnect_remote(server, sock, "Server closed connection: "
873 "Authentication failed");
877 /* Add a task to the queue. This task receives new connections to the
878 server. This task remains on the queue until the end of the program. */
879 if (!server->listenning && !sconn->backup) {
880 silc_schedule_task_add(server->schedule, server->sock,
881 silc_server_accept_new_connection,
882 (void *)server, 0, 0,
884 SILC_TASK_PRI_NORMAL);
885 server->listenning = TRUE;
888 /* Send NEW_SERVER packet to the router. We will become registered
889 to the SILC network after sending this packet. */
890 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
891 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
892 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
893 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
894 silc_buffer_format(packet,
895 SILC_STR_UI_SHORT(id_len),
896 SILC_STR_UI_XNSTRING(id_string, id_len),
897 SILC_STR_UI_SHORT(strlen(server->server_name)),
898 SILC_STR_UI_XNSTRING(server->server_name,
899 strlen(server->server_name)),
902 /* Send the packet */
903 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
904 packet->data, packet->len, TRUE);
905 silc_buffer_free(packet);
906 silc_free(id_string);
908 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
910 /* Check that we do not have this ID already */
911 id_entry = silc_idlist_find_server_by_id(server->local_list,
912 ctx->dest_id, TRUE, NULL);
914 silc_idcache_del_by_context(server->local_list->servers, id_entry);
916 id_entry = silc_idlist_find_server_by_id(server->global_list,
917 ctx->dest_id, TRUE, NULL);
919 silc_idcache_del_by_context(server->global_list->servers, id_entry);
922 SILC_LOG_DEBUG(("New server id(%s)",
923 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
925 /* Add the connected router to global server list */
926 id_entry = silc_idlist_add_server(server->global_list,
927 strdup(sock->hostname),
928 SILC_ROUTER, ctx->dest_id, NULL, sock);
930 silc_free(ctx->dest_id);
931 silc_server_disconnect_remote(server, sock, "Server closed connection: "
932 "Authentication failed");
936 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
937 silc_free(sock->user_data);
938 sock->user_data = (void *)id_entry;
939 sock->type = SILC_SOCKET_TYPE_ROUTER;
940 idata = (SilcIDListData)sock->user_data;
941 idata->status |= SILC_IDLIST_STATUS_REGISTERED;
943 /* Perform keepalive. The `hb_context' will be freed automatically
944 when finally calling the silc_socket_free function. XXX hardcoded
946 hb_context = silc_calloc(1, sizeof(*hb_context));
947 hb_context->server = server;
948 silc_socket_set_heartbeat(sock, 600, hb_context,
949 silc_server_perform_heartbeat,
952 /* Register re-key timeout */
953 idata->rekey->timeout = 3600; /* XXX hardcoded */
954 idata->rekey->context = (void *)server;
955 silc_schedule_task_add(server->schedule, sock->sock,
956 silc_server_rekey_callback,
957 (void *)sock, idata->rekey->timeout, 0,
958 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
960 if (!sconn->backup) {
961 /* Mark this router our primary router if we're still standalone */
962 if (server->standalone) {
963 server->id_entry->router = id_entry;
964 server->router = id_entry;
965 server->standalone = FALSE;
967 /* If we are router then announce our possible servers. */
968 if (server->server_type == SILC_ROUTER)
969 silc_server_announce_servers(server, FALSE, 0,
970 server->router->connection);
972 /* Announce our clients and channels to the router */
973 silc_server_announce_clients(server, 0, server->router->connection);
974 silc_server_announce_channels(server, 0, server->router->connection);
977 /* Add this server to be our backup router */
978 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
979 sconn->backup_replace_port, FALSE);
982 sock->protocol = NULL;
984 /* Call the completion callback to indicate that we've connected to
987 (*sconn->callback)(server, id_entry, sconn->callback_context);
990 /* Free the temporary connection data context */
992 silc_free(sconn->remote_host);
993 silc_free(sconn->backup_replace_ip);
996 if (sconn == server->router_conn)
997 server->router_conn = NULL;
999 /* Free the protocol object */
1000 if (sock->protocol == protocol)
1001 sock->protocol = NULL;
1002 silc_protocol_free(protocol);
1004 silc_packet_context_free(ctx->packet);
1006 silc_ske_free(ctx->ske);
1007 silc_free(ctx->auth_data);
1011 /* Host lookup callbcak that is called after the incoming connection's
1012 IP and FQDN lookup is performed. This will actually check the acceptance
1013 of the incoming connection and will register the key exchange protocol
1014 for this connection. */
1017 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1020 SilcServer server = (SilcServer)context;
1021 SilcServerKEInternalContext *proto_ctx;
1022 void *cconfig, *sconfig, *rconfig;
1023 SilcServerConfigSectionDenyConnection *deny;
1026 SILC_LOG_DEBUG(("Start"));
1028 /* Check whether we could resolve both IP and FQDN. */
1029 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1030 server->params->require_reverse_mapping)) {
1031 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1032 sock->hostname ? sock->hostname :
1033 sock->ip ? sock->ip : ""));
1034 server->stat.conn_failures++;
1035 silc_server_disconnect_remote(server, sock,
1036 "Server closed connection: Unknown host");
1040 /* Register the connection for network input and output. This sets
1041 that scheduler will listen for incoming packets for this connection
1042 and sets that outgoing packets may be sent to this connection as well.
1043 However, this doesn't set the scheduler for outgoing traffic, it
1044 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1045 later when outgoing data is available. */
1046 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1048 SILC_LOG_INFO(("Incoming connection from %s (%s)", sock->hostname,
1051 port = server->sockets[server->sock]->port; /* Listenning port */
1053 /* Check whether this connection is denied to connect to us. */
1054 deny = silc_server_config_denied_conn(server->config, sock->ip, port);
1056 deny = silc_server_config_denied_conn(server->config, sock->hostname,
1059 /* The connection is denied */
1060 SILC_LOG_INFO(("Connection %s (%s) is denied",
1061 sock->hostname, sock->ip));
1062 silc_server_disconnect_remote(server, sock, deny->comment ?
1064 "Server closed connection: "
1065 "Connection refused");
1066 server->stat.conn_failures++;
1070 /* Check whether we have configred this sort of connection at all. We
1071 have to check all configurations since we don't know what type of
1072 connection this is. */
1073 if (!(cconfig = silc_server_config_find_client_conn(server->config,
1075 cconfig = silc_server_config_find_client_conn(server->config,
1078 if (!(sconfig = silc_server_config_find_server_conn(server->config,
1081 sconfig = silc_server_config_find_server_conn(server->config,
1084 if (!(rconfig = silc_server_config_find_router_conn(server->config,
1086 rconfig = silc_server_config_find_router_conn(server->config,
1089 if (!cconfig && !sconfig && !rconfig) {
1090 SILC_LOG_INFO(("Connection %s (%s) is not allowed",
1091 sock->hostname, sock->ip));
1092 silc_server_disconnect_remote(server, sock,
1093 "Server closed connection: "
1094 "Connection refused");
1095 server->stat.conn_failures++;
1099 /* The connection is allowed */
1101 /* Allocate internal context for key exchange protocol. This is
1102 sent as context for the protocol. */
1103 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1104 proto_ctx->server = context;
1105 proto_ctx->sock = sock;
1106 proto_ctx->rng = server->rng;
1107 proto_ctx->responder = TRUE;
1108 proto_ctx->cconfig = cconfig;
1109 proto_ctx->sconfig = sconfig;
1110 proto_ctx->rconfig = rconfig;
1112 /* Prepare the connection for key exchange protocol. We allocate the
1113 protocol but will not start it yet. The connector will be the
1114 initiator of the protocol thus we will wait for initiation from
1115 there before we start the protocol. */
1116 server->stat.auth_attempts++;
1117 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1118 &sock->protocol, proto_ctx,
1119 silc_server_accept_new_connection_second);
1121 /* Register a timeout task that will be executed if the connector
1122 will not start the key exchange protocol within 60 seconds. For
1123 now, this is a hard coded limit. After 60 secs the connection will
1124 be closed if the key exchange protocol has not been started. */
1125 proto_ctx->timeout_task =
1126 silc_schedule_task_add(server->schedule, sock->sock,
1127 silc_server_timeout_remote,
1133 /* Accepts new connections to the server. Accepting new connections are
1134 done in three parts to make it async. */
1136 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1138 SilcServer server = (SilcServer)context;
1139 SilcSocketConnection newsocket;
1142 SILC_LOG_DEBUG(("Accepting new connection"));
1144 server->stat.conn_attempts++;
1146 sock = silc_net_accept_connection(server->sock);
1148 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1149 server->stat.conn_failures++;
1153 /* Check max connections */
1154 if (sock > SILC_SERVER_MAX_CONNECTIONS) {
1155 SILC_LOG_ERROR(("Refusing connection, server is full"));
1156 server->stat.conn_failures++;
1160 /* Set socket options */
1161 silc_net_set_socket_nonblock(sock);
1162 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1164 /* We don't create a ID yet, since we don't know what type of connection
1165 this is yet. But, we do add the connection to the socket table. */
1166 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1167 server->sockets[sock] = newsocket;
1169 /* Perform asynchronous host lookup. This will lookup the IP and the
1170 FQDN of the remote connection. After the lookup is done the connection
1171 is accepted further. */
1172 silc_socket_host_lookup(newsocket, TRUE,
1173 silc_server_accept_new_connection_lookup, context,
1177 /* Second part of accepting new connection. Key exchange protocol has been
1178 performed and now it is time to do little connection authentication
1179 protocol to figure out whether this connection is client or server
1180 and whether it has right to access this server (especially server
1181 connections needs to be authenticated). */
1183 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1185 SilcProtocol protocol = (SilcProtocol)context;
1186 SilcServerKEInternalContext *ctx =
1187 (SilcServerKEInternalContext *)protocol->context;
1188 SilcServer server = (SilcServer)ctx->server;
1189 SilcSocketConnection sock = ctx->sock;
1190 SilcServerConnAuthInternalContext *proto_ctx;
1192 SILC_LOG_DEBUG(("Start"));
1194 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1195 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1196 /* Error occured during protocol */
1197 silc_protocol_free(protocol);
1198 sock->protocol = NULL;
1199 silc_ske_free_key_material(ctx->keymat);
1201 silc_packet_context_free(ctx->packet);
1203 silc_ske_free(ctx->ske);
1204 silc_free(ctx->dest_id);
1206 silc_schedule_task_del_by_callback(server->schedule,
1207 silc_server_failure_callback);
1208 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1209 "Key exchange failed");
1210 server->stat.auth_failures++;
1214 /* We now have the key material as the result of the key exchange
1215 protocol. Take the key material into use. Free the raw key material
1216 as soon as we've set them into use. */
1217 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1218 ctx->sock, ctx->keymat,
1219 ctx->ske->prop->cipher,
1220 ctx->ske->prop->pkcs,
1221 ctx->ske->prop->hash,
1222 ctx->ske->prop->hmac,
1223 ctx->ske->prop->group,
1225 silc_protocol_free(protocol);
1226 sock->protocol = NULL;
1227 silc_ske_free_key_material(ctx->keymat);
1229 silc_packet_context_free(ctx->packet);
1231 silc_ske_free(ctx->ske);
1232 silc_free(ctx->dest_id);
1234 silc_schedule_task_del_by_callback(server->schedule,
1235 silc_server_failure_callback);
1236 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1237 "Key exchange failed");
1238 server->stat.auth_failures++;
1241 silc_ske_free_key_material(ctx->keymat);
1243 /* Allocate internal context for the authentication protocol. This
1244 is sent as context for the protocol. */
1245 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1246 proto_ctx->server = (void *)server;
1247 proto_ctx->sock = sock;
1248 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1249 proto_ctx->responder = TRUE;
1250 proto_ctx->dest_id_type = ctx->dest_id_type;
1251 proto_ctx->dest_id = ctx->dest_id;
1252 proto_ctx->cconfig = ctx->cconfig;
1253 proto_ctx->sconfig = ctx->sconfig;
1254 proto_ctx->rconfig = ctx->rconfig;
1256 /* Free old protocol as it is finished now */
1257 silc_protocol_free(protocol);
1259 silc_packet_context_free(ctx->packet);
1261 sock->protocol = NULL;
1263 /* Allocate the authentication protocol. This is allocated here
1264 but we won't start it yet. We will be receiving party of this
1265 protocol thus we will wait that connecting party will make
1266 their first move. */
1267 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1268 &sock->protocol, proto_ctx,
1269 silc_server_accept_new_connection_final);
1271 /* Register timeout task. If the protocol is not executed inside
1272 this timelimit the connection will be terminated. Currently
1273 this is 60 seconds and is hard coded limit (XXX). */
1274 proto_ctx->timeout_task =
1275 silc_schedule_task_add(server->schedule, sock->sock,
1276 silc_server_timeout_remote,
1277 (void *)server, 60, 0,
1282 /* Final part of accepting new connection. The connection has now
1283 been authenticated and keys has been exchanged. We also know whether
1284 this is client or server connection. */
1286 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1288 SilcProtocol protocol = (SilcProtocol)context;
1289 SilcServerConnAuthInternalContext *ctx =
1290 (SilcServerConnAuthInternalContext *)protocol->context;
1291 SilcServer server = (SilcServer)ctx->server;
1292 SilcSocketConnection sock = ctx->sock;
1293 SilcServerHBContext hb_context;
1294 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1295 void *id_entry = NULL;
1297 SILC_LOG_DEBUG(("Start"));
1299 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1300 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1301 /* Error occured during protocol */
1302 silc_protocol_free(protocol);
1303 sock->protocol = NULL;
1305 silc_packet_context_free(ctx->packet);
1307 silc_ske_free(ctx->ske);
1308 silc_free(ctx->dest_id);
1310 silc_schedule_task_del_by_callback(server->schedule,
1311 silc_server_failure_callback);
1312 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1313 "Authentication failed");
1314 server->stat.auth_failures++;
1318 entry->data.last_receive = time(NULL);
1320 switch (ctx->conn_type) {
1321 case SILC_SOCKET_TYPE_CLIENT:
1323 SilcClientEntry client;
1325 SILC_LOG_DEBUG(("Remote host is client"));
1326 SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
1329 /* Add the client to the client ID cache. The nickname and Client ID
1330 and other information is created after we have received NEW_CLIENT
1331 packet from client. */
1332 client = silc_idlist_add_client(server->local_list,
1333 NULL, NULL, NULL, NULL, NULL, sock, 0);
1335 SILC_LOG_ERROR(("Could not add new client to cache"));
1336 silc_free(sock->user_data);
1337 silc_server_disconnect_remote(server, sock,
1338 "Server closed connection: "
1339 "Authentication failed");
1340 server->stat.auth_failures++;
1345 server->stat.my_clients++;
1346 server->stat.clients++;
1347 if (server->server_type == SILC_ROUTER)
1348 server->stat.cell_clients++;
1350 id_entry = (void *)client;
1353 case SILC_SOCKET_TYPE_SERVER:
1354 case SILC_SOCKET_TYPE_ROUTER:
1356 SilcServerEntry new_server;
1357 SilcServerConfigSectionServerConnection *conn =
1358 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1359 ctx->sconfig : ctx->rconfig;
1361 SILC_LOG_DEBUG(("Remote host is %s",
1362 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1363 "server" : (conn->backup_router ?
1364 "backup router" : "router")));
1365 SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
1366 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1367 "server" : (conn->backup_router ?
1368 "backup router" : "router")));
1370 /* Add the server into server cache. The server name and Server ID
1371 is updated after we have received NEW_SERVER packet from the
1372 server. We mark ourselves as router for this server if we really
1375 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1376 server->local_list : (conn->backup_router ?
1377 server->local_list :
1378 server->global_list)),
1380 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1381 SILC_SERVER : SILC_ROUTER),
1383 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1384 server->id_entry : (conn->backup_router ?
1385 server->id_entry : NULL)),
1388 SILC_LOG_ERROR(("Could not add new server to cache"));
1389 silc_free(sock->user_data);
1390 silc_server_disconnect_remote(server, sock,
1391 "Server closed connection: "
1392 "Authentication failed");
1393 server->stat.auth_failures++;
1398 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1399 server->stat.my_servers++;
1401 server->stat.my_routers++;
1402 server->stat.servers++;
1404 id_entry = (void *)new_server;
1406 /* If the incoming connection is router and marked as backup router
1407 then add it to be one of our backups */
1408 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && conn->backup_router) {
1409 silc_server_backup_add(server, new_server, conn->backup_replace_ip,
1410 conn->backup_replace_port, conn->backup_local);
1412 /* Change it back to SERVER type since that's what it really is. */
1413 if (conn->backup_local)
1414 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1416 new_server->server_type = SILC_BACKUP_ROUTER;
1419 /* Check whether this connection is to be our primary router connection
1420 if we do not already have the primary route. */
1421 if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1422 if (silc_server_config_is_primary_route(server->config) &&
1426 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1427 server->standalone = FALSE;
1428 if (!server->id_entry->router) {
1429 server->id_entry->router = id_entry;
1430 server->router = id_entry;
1440 sock->type = ctx->conn_type;
1442 /* Add the common data structure to the ID entry. */
1444 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1446 /* Add to sockets internal pointer for fast referencing */
1447 silc_free(sock->user_data);
1448 sock->user_data = id_entry;
1450 /* Connection has been fully established now. Everything is ok. */
1451 SILC_LOG_DEBUG(("New connection authenticated"));
1453 /* Perform keepalive. The `hb_context' will be freed automatically
1454 when finally calling the silc_socket_free function. XXX hardcoded
1456 hb_context = silc_calloc(1, sizeof(*hb_context));
1457 hb_context->server = server;
1458 silc_socket_set_heartbeat(sock, 600, hb_context,
1459 silc_server_perform_heartbeat,
1463 silc_schedule_task_del_by_callback(server->schedule,
1464 silc_server_failure_callback);
1465 silc_protocol_free(protocol);
1467 silc_packet_context_free(ctx->packet);
1469 silc_ske_free(ctx->ske);
1470 silc_free(ctx->dest_id);
1472 sock->protocol = NULL;
1475 /* This function is used to read packets from network and send packets to
1476 network. This is usually a generic task. */
1478 SILC_TASK_CALLBACK(silc_server_packet_process)
1480 SilcServer server = (SilcServer)context;
1481 SilcSocketConnection sock = server->sockets[fd];
1482 SilcIDListData idata;
1483 SilcCipher cipher = NULL;
1484 SilcHmac hmac = NULL;
1485 uint32 sequence = 0;
1491 SILC_LOG_DEBUG(("Processing packet"));
1493 /* Packet sending */
1495 if (type == SILC_TASK_WRITE) {
1496 /* Do not send data to disconnected connection */
1497 if (SILC_IS_DISCONNECTED(sock))
1500 server->stat.packets_sent++;
1502 if (sock->outbuf->data - sock->outbuf->head)
1503 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1505 /* Send the packet */
1506 ret = silc_packet_send(sock, TRUE);
1508 /* If returned -2 could not write to connection now, will do
1514 SILC_LOG_ERROR(("Error sending packet to connection "
1515 "%s:%d [%s]", sock->hostname, sock->port,
1516 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1517 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1518 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1523 /* The packet has been sent and now it is time to set the connection
1524 back to only for input. When there is again some outgoing data
1525 available for this connection it will be set for output as well.
1526 This call clears the output setting and sets it only for input. */
1527 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1528 SILC_UNSET_OUTBUF_PENDING(sock);
1530 silc_buffer_clear(sock->outbuf);
1534 /* Packet receiving */
1536 /* Read some data from connection */
1537 ret = silc_packet_receive(sock);
1541 SILC_LOG_ERROR(("Error receiving packet from connection "
1542 "%s:%d [%s] %s", sock->hostname, sock->port,
1543 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1544 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1545 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1546 "Router"), strerror(errno)));
1552 SILC_LOG_DEBUG(("Read EOF"));
1554 /* If connection is disconnecting already we will finally
1555 close the connection */
1556 if (SILC_IS_DISCONNECTING(sock)) {
1557 if (sock->user_data)
1558 silc_server_free_sock_user_data(server, sock, NULL);
1559 silc_server_close_connection(server, sock);
1563 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1564 SILC_SET_DISCONNECTING(sock);
1566 if (sock->user_data)
1567 silc_server_free_sock_user_data(server, sock, NULL);
1568 else if (server->router_conn && server->router_conn->sock == sock &&
1569 !server->router && server->standalone)
1570 silc_schedule_task_add(server->schedule, 0,
1571 silc_server_connect_to_router,
1574 SILC_TASK_PRI_NORMAL);
1576 silc_server_close_connection(server, sock);
1580 /* If connection is disconnecting or disconnected we will ignore
1582 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1583 SILC_LOG_DEBUG(("Ignoring read data from disonnected connection"));
1587 server->stat.packets_received++;
1589 /* Get keys and stuff from ID entry */
1590 idata = (SilcIDListData)sock->user_data;
1592 cipher = idata->receive_key;
1593 hmac = idata->hmac_receive;
1594 sequence = idata->psn_receive;
1597 /* Process the packet. This will call the parser that will then
1598 decrypt and parse the packet. */
1599 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1600 TRUE : FALSE, cipher, hmac, sequence,
1601 silc_server_packet_parse, server);
1603 /* If this socket connection is not authenticated yet and the packet
1604 processing failed we will drop the connection since it can be
1605 a malicious flooder. */
1606 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
1607 (!sock->protocol || sock->protocol->protocol->type ==
1608 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
1609 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
1610 SILC_SET_DISCONNECTING(sock);
1612 if (sock->user_data)
1613 silc_server_free_sock_user_data(server, sock, NULL);
1614 silc_server_close_connection(server, sock);
1618 /* Parses whole packet, received earlier. */
1620 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1622 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1623 SilcServer server = (SilcServer)parse_ctx->context;
1624 SilcSocketConnection sock = parse_ctx->sock;
1625 SilcPacketContext *packet = parse_ctx->packet;
1626 SilcIDListData idata = (SilcIDListData)sock->user_data;
1629 SILC_LOG_DEBUG(("Start"));
1631 /* Parse the packet */
1632 if (parse_ctx->normal)
1633 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
1635 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
1637 /* If entry is disabled ignore what we got. */
1638 if (ret != SILC_PACKET_RESUME_ROUTER &&
1639 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1640 SILC_LOG_DEBUG(("Connection is disabled"));
1644 if (ret == SILC_PACKET_NONE)
1647 /* Check that the the current client ID is same as in the client's packet. */
1648 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1649 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1650 if (client && client->id) {
1651 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1652 packet->src_id_type);
1653 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1661 if (server->server_type == SILC_ROUTER) {
1662 /* Route the packet if it is not destined to us. Other ID types but
1663 server are handled separately after processing them. */
1664 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1665 packet->dst_id_type == SILC_ID_SERVER &&
1666 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1667 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1669 /* Route the packet to fastest route for the destination ID */
1670 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1671 packet->dst_id_type);
1674 silc_server_packet_route(server,
1675 silc_server_route_get(server, id,
1676 packet->dst_id_type),
1683 /* Parse the incoming packet type */
1684 silc_server_packet_parse_type(server, sock, packet);
1686 if (server->server_type == SILC_ROUTER) {
1687 /* Broadcast packet if it is marked as broadcast packet and it is
1688 originated from router and we are router. */
1689 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1690 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1691 !server->standalone) {
1692 /* Broadcast to our primary route */
1693 silc_server_packet_broadcast(server, server->router->connection, packet);
1695 /* If we have backup routers then we need to feed all broadcast
1696 data to those servers. */
1697 silc_server_backup_broadcast(server, sock, packet);
1702 silc_packet_context_free(packet);
1703 silc_free(parse_ctx);
1706 /* Parser callback called by silc_packet_receive_process. This merely
1707 registers timeout that will handle the actual parsing when appropriate. */
1709 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
1712 SilcServer server = (SilcServer)context;
1713 SilcSocketConnection sock = parser_context->sock;
1714 SilcIDListData idata = (SilcIDListData)sock->user_data;
1717 idata->psn_receive = parser_context->packet->sequence + 1;
1719 /* If protocol for this connection is key exchange or rekey then we'll
1720 process all packets synchronously, since there might be packets in
1721 queue that we are not able to decrypt without first processing the
1722 packets before them. */
1723 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
1724 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
1725 (sock->protocol && sock->protocol->protocol &&
1726 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1727 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
1728 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1731 /* Reprocess data since we'll return FALSE here. This is because
1732 the idata->receive_key might have become valid in the last packet
1733 and we want to call this processor with valid cipher. */
1735 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1736 TRUE : FALSE, idata->receive_key,
1737 idata->hmac_receive, idata->psn_receive,
1738 silc_server_packet_parse, server);
1740 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1741 TRUE : FALSE, NULL, NULL, 0,
1742 silc_server_packet_parse, server);
1746 switch (sock->type) {
1747 case SILC_SOCKET_TYPE_UNKNOWN:
1748 case SILC_SOCKET_TYPE_CLIENT:
1749 /* Parse the packet with timeout */
1750 silc_schedule_task_add(server->schedule, sock->sock,
1751 silc_server_packet_parse_real,
1752 (void *)parser_context, 0, 100000,
1754 SILC_TASK_PRI_NORMAL);
1756 case SILC_SOCKET_TYPE_SERVER:
1757 case SILC_SOCKET_TYPE_ROUTER:
1758 /* Packets from servers are parsed immediately */
1759 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1769 /* Parses the packet type and calls what ever routines the packet type
1770 requires. This is done for all incoming packets. */
1772 void silc_server_packet_parse_type(SilcServer server,
1773 SilcSocketConnection sock,
1774 SilcPacketContext *packet)
1776 SilcPacketType type = packet->type;
1777 SilcIDListData idata = (SilcIDListData)sock->user_data;
1779 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1781 /* Parse the packet type */
1783 case SILC_PACKET_DISCONNECT:
1784 SILC_LOG_DEBUG(("Disconnect packet"));
1785 if (packet->flags & SILC_PACKET_FLAG_LIST)
1789 case SILC_PACKET_SUCCESS:
1791 * Success received for something. For now we can have only
1792 * one protocol for connection executing at once hence this
1793 * success message is for whatever protocol is executing currently.
1795 SILC_LOG_DEBUG(("Success packet"));
1796 if (packet->flags & SILC_PACKET_FLAG_LIST)
1799 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1802 case SILC_PACKET_FAILURE:
1804 * Failure received for something. For now we can have only
1805 * one protocol for connection executing at once hence this
1806 * failure message is for whatever protocol is executing currently.
1808 SILC_LOG_DEBUG(("Failure packet"));
1809 if (packet->flags & SILC_PACKET_FLAG_LIST)
1811 if (sock->protocol) {
1812 SilcServerFailureContext f;
1813 f = silc_calloc(1, sizeof(*f));
1817 /* We will wait 5 seconds to process this failure packet */
1818 silc_schedule_task_add(server->schedule, sock->sock,
1819 silc_server_failure_callback, (void *)f, 5, 0,
1820 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1824 case SILC_PACKET_REJECT:
1825 SILC_LOG_DEBUG(("Reject packet"));
1826 if (packet->flags & SILC_PACKET_FLAG_LIST)
1831 case SILC_PACKET_NOTIFY:
1833 * Received notify packet. Server can receive notify packets from
1834 * router. Server then relays the notify messages to clients if needed.
1836 SILC_LOG_DEBUG(("Notify packet"));
1837 if (packet->flags & SILC_PACKET_FLAG_LIST)
1838 silc_server_notify_list(server, sock, packet);
1840 silc_server_notify(server, sock, packet);
1846 case SILC_PACKET_CHANNEL_MESSAGE:
1848 * Received channel message. Channel messages are special packets
1849 * (although probably most common ones) thus they are handled
1852 SILC_LOG_DEBUG(("Channel Message packet"));
1853 if (packet->flags & SILC_PACKET_FLAG_LIST)
1855 idata->last_receive = time(NULL);
1856 silc_server_channel_message(server, sock, packet);
1859 case SILC_PACKET_CHANNEL_KEY:
1861 * Received key for channel. As channels are created by the router
1862 * the keys are as well. We will distribute the key to all of our
1863 * locally connected clients on the particular channel. Router
1864 * never receives this channel and thus is ignored.
1866 SILC_LOG_DEBUG(("Channel Key packet"));
1867 if (packet->flags & SILC_PACKET_FLAG_LIST)
1869 silc_server_channel_key(server, sock, packet);
1875 case SILC_PACKET_COMMAND:
1877 * Recived command. Processes the command request and allocates the
1878 * command context and calls the command.
1880 SILC_LOG_DEBUG(("Command packet"));
1881 if (packet->flags & SILC_PACKET_FLAG_LIST)
1883 silc_server_command_process(server, sock, packet);
1886 case SILC_PACKET_COMMAND_REPLY:
1888 * Received command reply packet. Received command reply to command. It
1889 * may be reply to command sent by us or reply to command sent by client
1890 * that we've routed further.
1892 SILC_LOG_DEBUG(("Command Reply packet"));
1893 if (packet->flags & SILC_PACKET_FLAG_LIST)
1895 silc_server_command_reply(server, sock, packet);
1899 * Private Message packets
1901 case SILC_PACKET_PRIVATE_MESSAGE:
1903 * Received private message packet. The packet is coming from either
1906 SILC_LOG_DEBUG(("Private Message packet"));
1907 if (packet->flags & SILC_PACKET_FLAG_LIST)
1909 idata->last_receive = time(NULL);
1910 silc_server_private_message(server, sock, packet);
1913 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1915 * Private message key packet.
1917 if (packet->flags & SILC_PACKET_FLAG_LIST)
1919 silc_server_private_message_key(server, sock, packet);
1923 * Key Exchange protocol packets
1925 case SILC_PACKET_KEY_EXCHANGE:
1926 SILC_LOG_DEBUG(("KE packet"));
1927 if (packet->flags & SILC_PACKET_FLAG_LIST)
1930 if (sock->protocol && sock->protocol->protocol &&
1931 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1933 SilcServerKEInternalContext *proto_ctx =
1934 (SilcServerKEInternalContext *)sock->protocol->context;
1936 proto_ctx->packet = silc_packet_context_dup(packet);
1938 /* Let the protocol handle the packet */
1939 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
1941 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1942 "protocol active, packet dropped."));
1946 case SILC_PACKET_KEY_EXCHANGE_1:
1947 SILC_LOG_DEBUG(("KE 1 packet"));
1948 if (packet->flags & SILC_PACKET_FLAG_LIST)
1951 if (sock->protocol && sock->protocol->protocol &&
1952 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1953 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
1955 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
1956 SilcServerRekeyInternalContext *proto_ctx =
1957 (SilcServerRekeyInternalContext *)sock->protocol->context;
1959 if (proto_ctx->packet)
1960 silc_packet_context_free(proto_ctx->packet);
1962 proto_ctx->packet = silc_packet_context_dup(packet);
1964 /* Let the protocol handle the packet */
1965 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1967 SilcServerKEInternalContext *proto_ctx =
1968 (SilcServerKEInternalContext *)sock->protocol->context;
1970 if (proto_ctx->packet)
1971 silc_packet_context_free(proto_ctx->packet);
1973 proto_ctx->packet = silc_packet_context_dup(packet);
1974 proto_ctx->dest_id_type = packet->src_id_type;
1975 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1976 packet->src_id_type);
1977 if (!proto_ctx->dest_id)
1980 /* Let the protocol handle the packet */
1981 silc_protocol_execute(sock->protocol, server->schedule,
1985 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1986 "protocol active, packet dropped."));
1990 case SILC_PACKET_KEY_EXCHANGE_2:
1991 SILC_LOG_DEBUG(("KE 2 packet"));
1992 if (packet->flags & SILC_PACKET_FLAG_LIST)
1995 if (sock->protocol && sock->protocol->protocol &&
1996 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1997 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
1999 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2000 SilcServerRekeyInternalContext *proto_ctx =
2001 (SilcServerRekeyInternalContext *)sock->protocol->context;
2003 if (proto_ctx->packet)
2004 silc_packet_context_free(proto_ctx->packet);
2006 proto_ctx->packet = silc_packet_context_dup(packet);
2008 /* Let the protocol handle the packet */
2009 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2011 SilcServerKEInternalContext *proto_ctx =
2012 (SilcServerKEInternalContext *)sock->protocol->context;
2014 if (proto_ctx->packet)
2015 silc_packet_context_free(proto_ctx->packet);
2017 proto_ctx->packet = silc_packet_context_dup(packet);
2018 proto_ctx->dest_id_type = packet->src_id_type;
2019 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2020 packet->src_id_type);
2021 if (!proto_ctx->dest_id)
2024 /* Let the protocol handle the packet */
2025 silc_protocol_execute(sock->protocol, server->schedule,
2029 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2030 "protocol active, packet dropped."));
2034 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2036 * Connection authentication request packet. When we receive this packet
2037 * we will send to the other end information about our mandatory
2038 * authentication method for the connection. This packet maybe received
2041 SILC_LOG_DEBUG(("Connection authentication request packet"));
2042 if (packet->flags & SILC_PACKET_FLAG_LIST)
2044 silc_server_connection_auth_request(server, sock, packet);
2048 * Connection Authentication protocol packets
2050 case SILC_PACKET_CONNECTION_AUTH:
2051 /* Start of the authentication protocol. We receive here the
2052 authentication data and will verify it. */
2053 SILC_LOG_DEBUG(("Connection auth packet"));
2054 if (packet->flags & SILC_PACKET_FLAG_LIST)
2057 if (sock->protocol && sock->protocol->protocol->type
2058 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2060 SilcServerConnAuthInternalContext *proto_ctx =
2061 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2063 proto_ctx->packet = silc_packet_context_dup(packet);
2065 /* Let the protocol handle the packet */
2066 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2068 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2069 "protocol active, packet dropped."));
2073 case SILC_PACKET_NEW_ID:
2075 * Received New ID packet. This includes some new ID that has been
2076 * created. It may be for client, server or channel. This is the way
2077 * to distribute information about new registered entities in the
2080 SILC_LOG_DEBUG(("New ID packet"));
2081 if (packet->flags & SILC_PACKET_FLAG_LIST)
2082 silc_server_new_id_list(server, sock, packet);
2084 silc_server_new_id(server, sock, packet);
2087 case SILC_PACKET_NEW_CLIENT:
2089 * Received new client packet. This includes client information that
2090 * we will use to create initial client ID. After creating new
2091 * ID we will send it to the client.
2093 SILC_LOG_DEBUG(("New Client packet"));
2094 if (packet->flags & SILC_PACKET_FLAG_LIST)
2096 silc_server_new_client(server, sock, packet);
2099 case SILC_PACKET_NEW_SERVER:
2101 * Received new server packet. This includes Server ID and some other
2102 * information that we may save. This is received after server has
2105 SILC_LOG_DEBUG(("New Server packet"));
2106 if (packet->flags & SILC_PACKET_FLAG_LIST)
2108 silc_server_new_server(server, sock, packet);
2111 case SILC_PACKET_NEW_CHANNEL:
2113 * Received new channel packet. Information about new channel in the
2114 * network are distributed using this packet.
2116 SILC_LOG_DEBUG(("New Channel packet"));
2117 if (packet->flags & SILC_PACKET_FLAG_LIST)
2118 silc_server_new_channel_list(server, sock, packet);
2120 silc_server_new_channel(server, sock, packet);
2123 case SILC_PACKET_HEARTBEAT:
2125 * Received heartbeat.
2127 SILC_LOG_DEBUG(("Heartbeat packet"));
2128 if (packet->flags & SILC_PACKET_FLAG_LIST)
2132 case SILC_PACKET_KEY_AGREEMENT:
2134 * Received heartbeat.
2136 SILC_LOG_DEBUG(("Key agreement packet"));
2137 if (packet->flags & SILC_PACKET_FLAG_LIST)
2139 silc_server_key_agreement(server, sock, packet);
2142 case SILC_PACKET_REKEY:
2144 * Received re-key packet. The sender wants to regenerate the session
2147 SILC_LOG_DEBUG(("Re-key packet"));
2148 if (packet->flags & SILC_PACKET_FLAG_LIST)
2150 silc_server_rekey(server, sock, packet);
2153 case SILC_PACKET_REKEY_DONE:
2155 * The re-key is done.
2157 SILC_LOG_DEBUG(("Re-key done packet"));
2158 if (packet->flags & SILC_PACKET_FLAG_LIST)
2161 if (sock->protocol && sock->protocol->protocol &&
2162 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2164 SilcServerRekeyInternalContext *proto_ctx =
2165 (SilcServerRekeyInternalContext *)sock->protocol->context;
2167 if (proto_ctx->packet)
2168 silc_packet_context_free(proto_ctx->packet);
2170 proto_ctx->packet = silc_packet_context_dup(packet);
2172 /* Let the protocol handle the packet */
2173 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2175 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2176 "protocol active, packet dropped."));
2180 case SILC_PACKET_FTP:
2182 SILC_LOG_DEBUG(("FTP packet"));
2183 if (packet->flags & SILC_PACKET_FLAG_LIST)
2185 silc_server_ftp(server, sock, packet);
2188 case SILC_PACKET_RESUME_ROUTER:
2189 /* Resume router packet received. This packet is received for backup
2190 router resuming protocol. */
2191 SILC_LOG_DEBUG(("Resume router packet"));
2192 if (packet->flags & SILC_PACKET_FLAG_LIST)
2194 silc_server_backup_resume_router(server, sock, packet);
2198 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2204 /* Creates connection to a remote router. */
2206 void silc_server_create_connection(SilcServer server,
2207 char *remote_host, uint32 port)
2209 SilcServerConnection sconn;
2211 /* Allocate connection object for hold connection specific stuff. */
2212 sconn = silc_calloc(1, sizeof(*sconn));
2213 sconn->server = server;
2214 sconn->remote_host = strdup(remote_host);
2215 sconn->remote_port = port;
2217 silc_schedule_task_add(server->schedule, 0,
2218 silc_server_connect_router,
2219 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2220 SILC_TASK_PRI_NORMAL);
2223 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2225 silc_socket_free((SilcSocketConnection)context);
2228 /* Closes connection to socket connection */
2230 void silc_server_close_connection(SilcServer server,
2231 SilcSocketConnection sock)
2233 if (!server->sockets[sock->sock])
2236 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2238 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2239 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2240 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2243 /* We won't listen for this connection anymore */
2244 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2246 /* Unregister all tasks */
2247 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2249 /* Close the actual connection */
2250 silc_net_close_connection(sock->sock);
2251 server->sockets[sock->sock] = NULL;
2253 /* If sock->user_data is NULL then we'll check for active protocols
2254 here since the silc_server_free_sock_user_data has not been called
2255 for this connection. */
2256 if (!sock->user_data) {
2257 /* If any protocol is active cancel its execution. It will call
2258 the final callback which will finalize the disconnection. */
2259 if (sock->protocol) {
2260 silc_protocol_cancel(sock->protocol, server->schedule);
2261 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2262 silc_protocol_execute_final(sock->protocol, server->schedule);
2263 sock->protocol = NULL;
2268 silc_schedule_task_add(server->schedule, 0,
2269 silc_server_close_connection_final,
2270 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2271 SILC_TASK_PRI_NORMAL);
2274 /* Sends disconnect message to remote connection and disconnects the
2277 void silc_server_disconnect_remote(SilcServer server,
2278 SilcSocketConnection sock,
2279 const char *fmt, ...)
2282 unsigned char buf[4096];
2287 memset(buf, 0, sizeof(buf));
2289 vsprintf(buf, fmt, ap);
2292 SILC_LOG_DEBUG(("Disconnecting remote host"));
2294 /* Notify remote end that the conversation is over. The notify message
2295 is tried to be sent immediately. */
2296 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2297 buf, strlen(buf), TRUE);
2299 /* Mark the connection to be disconnected */
2300 SILC_SET_DISCONNECTED(sock);
2301 silc_server_close_connection(server, sock);
2306 SilcClientEntry client;
2307 } *FreeClientInternal;
2309 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2311 FreeClientInternal i = (FreeClientInternal)context;
2313 silc_idlist_del_data(i->client);
2314 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2318 /* Frees client data and notifies about client's signoff. */
2320 void silc_server_free_client_data(SilcServer server,
2321 SilcSocketConnection sock,
2322 SilcClientEntry client,
2324 const char *signoff)
2326 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2328 /* If there is pending outgoing data for the client then purge it
2329 to the network before removing the client entry. */
2330 silc_server_packet_queue_purge(server, sock);
2335 /* Send SIGNOFF notify to routers. */
2336 if (notify && !server->standalone && server->router)
2337 silc_server_send_notify_signoff(server, server->router->connection,
2338 server->server_type == SILC_SERVER ?
2339 FALSE : TRUE, client->id, signoff);
2341 /* Remove client from all channels */
2343 silc_server_remove_from_channels(server, NULL, client,
2344 TRUE, (char *)signoff, TRUE);
2346 silc_server_remove_from_channels(server, NULL, client,
2347 FALSE, NULL, FALSE);
2349 /* We will not delete the client entry right away. We will take it
2350 into history (for WHOWAS command) for 5 minutes */
2353 silc_schedule_task_add(server->schedule, 0,
2354 silc_server_free_client_data_timeout,
2356 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2357 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2358 client->router = NULL;
2359 client->connection = NULL;
2361 /* Free the client entry and everything in it */
2362 server->stat.my_clients--;
2363 server->stat.clients--;
2364 if (server->server_type == SILC_ROUTER)
2365 server->stat.cell_clients--;
2368 /* Frees user_data pointer from socket connection object. This also sends
2369 appropriate notify packets to the network to inform about leaving
2372 void silc_server_free_sock_user_data(SilcServer server,
2373 SilcSocketConnection sock,
2374 const char *signoff_message)
2376 SILC_LOG_DEBUG(("Start"));
2378 switch (sock->type) {
2379 case SILC_SOCKET_TYPE_CLIENT:
2381 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2382 silc_server_free_client_data(server, sock, user_data, TRUE,
2386 case SILC_SOCKET_TYPE_SERVER:
2387 case SILC_SOCKET_TYPE_ROUTER:
2389 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2390 SilcServerEntry backup_router = NULL;
2393 backup_router = silc_server_backup_get(server, user_data->id);
2395 /* If this was our primary router connection then we're lost to
2396 the outside world. */
2397 if (server->router == user_data) {
2398 /* Check whether we have a backup router connection */
2399 if (!backup_router || backup_router == user_data) {
2400 silc_schedule_task_add(server->schedule, 0,
2401 silc_server_connect_to_router,
2404 SILC_TASK_PRI_NORMAL);
2406 server->id_entry->router = NULL;
2407 server->router = NULL;
2408 server->standalone = TRUE;
2409 backup_router = NULL;
2411 SILC_LOG_INFO(("New primary router is backup router %s",
2412 backup_router->server_name));
2413 SILC_LOG_DEBUG(("New primary router is backup router %s",
2414 backup_router->server_name));
2415 server->id_entry->router = backup_router;
2416 server->router = backup_router;
2417 server->router_connect = time(0);
2418 server->backup_primary = TRUE;
2419 if (server->server_type == SILC_BACKUP_ROUTER) {
2420 server->server_type = SILC_ROUTER;
2422 /* We'll need to constantly try to reconnect to the primary
2423 router so that we'll see when it comes back online. */
2424 silc_server_backup_reconnect(server, sock->ip, sock->port,
2425 silc_server_backup_connected,
2429 /* Mark this connection as replaced */
2430 silc_server_backup_replaced_add(server, user_data->id,
2433 } else if (backup_router) {
2434 SILC_LOG_INFO(("Enabling the use of backup router %s",
2435 backup_router->server_name));
2436 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2437 backup_router->server_name));
2439 /* Mark this connection as replaced */
2440 silc_server_backup_replaced_add(server, user_data->id,
2444 if (!backup_router) {
2445 /* Free all client entries that this server owns as they will
2446 become invalid now as well. */
2448 silc_server_remove_clients_by_server(server, user_data, TRUE);
2449 if (server->server_type == SILC_SERVER)
2450 silc_server_remove_channels_by_server(server, user_data);
2452 /* Update the client entries of this server to the new backup
2453 router. This also removes the clients that *really* was owned
2454 by the primary router and went down with the router. */
2455 silc_server_update_clients_by_server(server, user_data, backup_router,
2457 silc_server_update_servers_by_server(server, user_data, backup_router);
2458 if (server->server_type == SILC_SERVER)
2459 silc_server_update_channels_by_server(server, user_data,
2463 /* Free the server entry */
2464 silc_server_backup_del(server, user_data);
2465 silc_server_backup_replaced_del(server, user_data);
2466 silc_idlist_del_data(user_data);
2467 if (!silc_idlist_del_server(server->local_list, user_data))
2468 silc_idlist_del_server(server->global_list, user_data);
2469 server->stat.my_servers--;
2470 server->stat.servers--;
2471 if (server->server_type == SILC_ROUTER)
2472 server->stat.cell_servers--;
2474 if (backup_router) {
2475 /* Announce all of our stuff that was created about 5 minutes ago.
2476 The backup router knows all the other stuff already. */
2477 if (server->server_type == SILC_ROUTER)
2478 silc_server_announce_servers(server, FALSE, time(0) - 300,
2479 backup_router->connection);
2481 /* Announce our clients and channels to the router */
2482 silc_server_announce_clients(server, time(0) - 300,
2483 backup_router->connection);
2484 silc_server_announce_channels(server, time(0) - 300,
2485 backup_router->connection);
2491 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2493 silc_idlist_del_data(user_data);
2494 silc_free(user_data);
2499 /* If any protocol is active cancel its execution */
2500 if (sock->protocol) {
2501 silc_protocol_cancel(sock->protocol, server->schedule);
2502 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2503 silc_protocol_execute_final(sock->protocol, server->schedule);
2504 sock->protocol = NULL;
2507 sock->user_data = NULL;
2510 /* Removes client from all channels it has joined. This is used when client
2511 connection is disconnected. If the client on a channel is last, the
2512 channel is removed as well. This sends the SIGNOFF notify types. */
2514 void silc_server_remove_from_channels(SilcServer server,
2515 SilcSocketConnection sock,
2516 SilcClientEntry client,
2518 char *signoff_message,
2521 SilcChannelEntry channel;
2522 SilcChannelClientEntry chl;
2523 SilcHashTableList htl;
2526 SILC_LOG_DEBUG(("Start"));
2528 if (!client || !client->id)
2531 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2533 /* Remove the client from all channels. The client is removed from
2534 the channels' user list. */
2535 silc_hash_table_list(client->channels, &htl);
2536 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2537 channel = chl->channel;
2539 /* Remove channel from client's channel list */
2540 silc_hash_table_del(client->channels, channel);
2542 /* Remove channel if there is no users anymore */
2543 if (server->server_type == SILC_ROUTER &&
2544 silc_hash_table_count(channel->user_list) < 2) {
2546 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2547 if (silc_idlist_del_channel(server->local_list, channel))
2548 server->stat.my_channels--;
2550 silc_idlist_del_channel(server->global_list, channel);
2554 /* Remove client from channel's client list */
2555 silc_hash_table_del(channel->user_list, chl->client);
2557 /* If there is no global users on the channel anymore mark the channel
2558 as local channel. Do not check if the removed client is local client. */
2559 if (server->server_type != SILC_ROUTER && channel->global_users &&
2560 chl->client->router && !silc_server_channel_has_global(channel))
2561 channel->global_users = FALSE;
2564 server->stat.my_chanclients--;
2566 /* If there is not at least one local user on the channel then we don't
2567 need the channel entry anymore, we can remove it safely. */
2568 if (server->server_type != SILC_ROUTER &&
2569 !silc_server_channel_has_local(channel)) {
2570 /* Notify about leaving client if this channel has global users. */
2571 if (notify && channel->global_users)
2572 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2573 SILC_NOTIFY_TYPE_SIGNOFF,
2574 signoff_message ? 2 : 1,
2575 clidp->data, clidp->len,
2576 signoff_message, signoff_message ?
2577 strlen(signoff_message) : 0);
2580 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2582 if (channel->founder_key) {
2583 /* The founder auth data exists, do not remove the channel entry */
2584 SilcChannelClientEntry chl2;
2585 SilcHashTableList htl2;
2587 channel->disabled = TRUE;
2589 silc_hash_table_list(channel->user_list, &htl2);
2590 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2591 silc_hash_table_del(chl2->client->channels, channel);
2592 silc_hash_table_del(channel->user_list, chl2->client);
2598 /* Remove the channel entry */
2599 if (silc_idlist_del_channel(server->local_list, channel))
2600 server->stat.my_channels--;
2602 silc_idlist_del_channel(server->global_list, channel);
2606 /* Send notify to channel about client leaving SILC and thus
2607 the entire channel. */
2609 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2610 SILC_NOTIFY_TYPE_SIGNOFF,
2611 signoff_message ? 2 : 1,
2612 clidp->data, clidp->len,
2613 signoff_message, signoff_message ?
2614 strlen(signoff_message) : 0);
2616 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2617 /* Re-generate channel key */
2618 if (!silc_server_create_channel_key(server, channel, 0))
2621 /* Send the channel key to the channel. The key of course is not sent
2622 to the client who was removed from the channel. */
2623 silc_server_send_channel_key(server, client->connection, channel,
2624 server->server_type == SILC_ROUTER ?
2625 FALSE : !server->standalone);
2629 silc_buffer_free(clidp);
2632 /* Removes client from one channel. This is used for example when client
2633 calls LEAVE command to remove itself from the channel. Returns TRUE
2634 if channel still exists and FALSE if the channel is removed when
2635 last client leaves the channel. If `notify' is FALSE notify messages
2638 int silc_server_remove_from_one_channel(SilcServer server,
2639 SilcSocketConnection sock,
2640 SilcChannelEntry channel,
2641 SilcClientEntry client,
2644 SilcChannelClientEntry chl;
2647 SILC_LOG_DEBUG(("Start"));
2649 /* Get the entry to the channel, if this client is not on the channel
2651 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2654 /* Remove the client from the channel. The client is removed from
2655 the channel's user list. */
2657 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2659 /* Remove channel from client's channel list */
2660 silc_hash_table_del(client->channels, chl->channel);
2662 /* Remove channel if there is no users anymore */
2663 if (server->server_type == SILC_ROUTER &&
2664 silc_hash_table_count(channel->user_list) < 2) {
2666 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2667 if (silc_idlist_del_channel(server->local_list, channel))
2668 server->stat.my_channels--;
2670 silc_idlist_del_channel(server->global_list, channel);
2671 silc_buffer_free(clidp);
2675 /* Remove client from channel's client list */
2676 silc_hash_table_del(channel->user_list, chl->client);
2678 /* If there is no global users on the channel anymore mark the channel
2679 as local channel. Do not check if the client is local client. */
2680 if (server->server_type != SILC_ROUTER && channel->global_users &&
2681 chl->client->router && !silc_server_channel_has_global(channel))
2682 channel->global_users = FALSE;
2685 server->stat.my_chanclients--;
2687 /* If there is not at least one local user on the channel then we don't
2688 need the channel entry anymore, we can remove it safely. */
2689 if (server->server_type != SILC_ROUTER &&
2690 !silc_server_channel_has_local(channel)) {
2691 /* Notify about leaving client if this channel has global users. */
2692 if (notify && channel->global_users)
2693 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2694 SILC_NOTIFY_TYPE_LEAVE, 1,
2695 clidp->data, clidp->len);
2697 silc_buffer_free(clidp);
2700 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2702 if (channel->founder_key) {
2703 /* The founder auth data exists, do not remove the channel entry */
2704 SilcChannelClientEntry chl2;
2705 SilcHashTableList htl2;
2707 channel->disabled = TRUE;
2709 silc_hash_table_list(channel->user_list, &htl2);
2710 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2711 silc_hash_table_del(chl2->client->channels, channel);
2712 silc_hash_table_del(channel->user_list, chl2->client);
2718 /* Remove the channel entry */
2719 if (silc_idlist_del_channel(server->local_list, channel))
2720 server->stat.my_channels--;
2722 silc_idlist_del_channel(server->global_list, channel);
2726 /* Send notify to channel about client leaving the channel */
2728 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2729 SILC_NOTIFY_TYPE_LEAVE, 1,
2730 clidp->data, clidp->len);
2732 silc_buffer_free(clidp);
2736 /* Timeout callback. This is called if connection is idle or for some
2737 other reason is not responding within some period of time. This
2738 disconnects the remote end. */
2740 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2742 SilcServer server = (SilcServer)context;
2743 SilcSocketConnection sock = server->sockets[fd];
2745 SILC_LOG_DEBUG(("Start"));
2750 /* If we have protocol active we must assure that we call the protocol's
2751 final callback so that all the memory is freed. */
2752 if (sock->protocol) {
2753 silc_protocol_cancel(sock->protocol, server->schedule);
2754 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2755 silc_protocol_execute_final(sock->protocol, server->schedule);
2756 sock->protocol = NULL;
2760 if (sock->user_data)
2761 silc_server_free_sock_user_data(server, sock, NULL);
2763 silc_server_disconnect_remote(server, sock, "Server closed connection: "
2764 "Connection timeout");
2767 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2768 function may be used only by router. In real SILC network all channels
2769 are created by routers thus this function is never used by normal
2772 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2773 SilcServerID *router_id,
2779 SilcChannelID *channel_id;
2780 SilcChannelEntry entry;
2784 SILC_LOG_DEBUG(("Creating new channel"));
2787 cipher = SILC_DEFAULT_CIPHER;
2789 hmac = SILC_DEFAULT_HMAC;
2791 /* Allocate cipher */
2792 if (!silc_cipher_alloc(cipher, &key))
2796 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2797 silc_cipher_free(key);
2801 channel_name = strdup(channel_name);
2803 /* Create the channel */
2804 if (!silc_id_create_channel_id(server, router_id, server->rng,
2806 silc_free(channel_name);
2807 silc_cipher_free(key);
2808 silc_hmac_free(newhmac);
2811 entry = silc_idlist_add_channel(server->local_list, channel_name,
2812 SILC_CHANNEL_MODE_NONE, channel_id,
2813 NULL, key, newhmac, 0);
2815 silc_free(channel_name);
2816 silc_cipher_free(key);
2817 silc_hmac_free(newhmac);
2821 entry->cipher = strdup(cipher);
2822 entry->hmac_name = strdup(hmac);
2824 /* Now create the actual key material */
2825 if (!silc_server_create_channel_key(server, entry,
2826 silc_cipher_get_key_len(key) / 8)) {
2827 silc_free(channel_name);
2828 silc_cipher_free(key);
2829 silc_hmac_free(newhmac);
2830 silc_free(entry->cipher);
2831 silc_free(entry->hmac_name);
2835 /* Notify other routers about the new channel. We send the packet
2836 to our primary route. */
2837 if (broadcast && server->standalone == FALSE)
2838 silc_server_send_new_channel(server, server->router->connection, TRUE,
2839 channel_name, entry->id,
2840 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2843 server->stat.my_channels++;
2848 /* Same as above but creates the channel with Channel ID `channel_id. */
2851 silc_server_create_new_channel_with_id(SilcServer server,
2855 SilcChannelID *channel_id,
2858 SilcChannelEntry entry;
2862 SILC_LOG_DEBUG(("Creating new channel"));
2865 cipher = SILC_DEFAULT_CIPHER;
2867 hmac = SILC_DEFAULT_HMAC;
2869 /* Allocate cipher */
2870 if (!silc_cipher_alloc(cipher, &key))
2874 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2875 silc_cipher_free(key);
2879 channel_name = strdup(channel_name);
2881 /* Create the channel */
2882 entry = silc_idlist_add_channel(server->local_list, channel_name,
2883 SILC_CHANNEL_MODE_NONE, channel_id,
2884 NULL, key, newhmac, 0);
2886 silc_free(channel_name);
2890 /* Now create the actual key material */
2891 if (!silc_server_create_channel_key(server, entry,
2892 silc_cipher_get_key_len(key) / 8)) {
2893 silc_free(channel_name);
2897 /* Notify other routers about the new channel. We send the packet
2898 to our primary route. */
2899 if (broadcast && server->standalone == FALSE)
2900 silc_server_send_new_channel(server, server->router->connection, TRUE,
2901 channel_name, entry->id,
2902 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2905 server->stat.my_channels++;
2910 /* Channel's key re-key timeout callback. */
2912 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
2914 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
2915 SilcServer server = (SilcServer)rekey->context;
2919 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
2922 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
2925 /* Generates new channel key. This is used to create the initial channel key
2926 but also to re-generate new key for channel. If `key_len' is provided
2927 it is the bytes of the key length. */
2929 bool silc_server_create_channel_key(SilcServer server,
2930 SilcChannelEntry channel,
2934 unsigned char channel_key[32], hash[32];
2937 SILC_LOG_DEBUG(("Generating channel key"));
2939 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
2940 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
2944 if (!channel->channel_key)
2945 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
2946 channel->channel_key = NULL;
2952 else if (channel->key_len)
2953 len = channel->key_len / 8;
2955 len = silc_cipher_get_key_len(channel->channel_key) / 8;
2957 /* Create channel key */
2958 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
2961 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
2963 /* Remove old key if exists */
2965 memset(channel->key, 0, channel->key_len / 8);
2966 silc_free(channel->key);
2970 channel->key_len = len * 8;
2971 channel->key = silc_calloc(len, sizeof(*channel->key));
2972 memcpy(channel->key, channel_key, len);
2973 memset(channel_key, 0, sizeof(channel_key));
2975 /* Generate HMAC key from the channel key data and set it */
2977 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
2978 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
2979 silc_hmac_set_key(channel->hmac, hash,
2980 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
2981 memset(hash, 0, sizeof(hash));
2983 if (server->server_type == SILC_ROUTER) {
2984 if (!channel->rekey)
2985 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
2986 channel->rekey->context = (void *)server;
2987 channel->rekey->channel = channel;
2988 channel->rekey->key_len = key_len;
2989 if (channel->rekey->task)
2990 silc_schedule_task_del(server->schedule, channel->rekey->task);
2992 channel->rekey->task =
2993 silc_schedule_task_add(server->schedule, 0,
2994 silc_server_channel_key_rekey,
2995 (void *)channel->rekey, 3600, 0,
2997 SILC_TASK_PRI_NORMAL);
3003 /* Saves the channel key found in the encoded `key_payload' buffer. This
3004 function is used when we receive Channel Key Payload and also when we're
3005 processing JOIN command reply. Returns entry to the channel. */
3007 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3008 SilcBuffer key_payload,
3009 SilcChannelEntry channel)
3011 SilcChannelKeyPayload payload = NULL;
3012 SilcChannelID *id = NULL;
3013 unsigned char *tmp, hash[32];
3017 SILC_LOG_DEBUG(("Start"));
3019 /* Decode channel key payload */
3020 payload = silc_channel_key_payload_parse(key_payload->data,
3023 SILC_LOG_ERROR(("Bad channel key payload, dropped"));
3028 /* Get the channel entry */
3031 /* Get channel ID */
3032 tmp = silc_channel_key_get_id(payload, &tmp_len);
3033 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3039 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3041 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3043 SILC_LOG_ERROR(("Received key for non-existent channel"));
3049 tmp = silc_channel_key_get_key(payload, &tmp_len);
3055 cipher = silc_channel_key_get_cipher(payload, NULL);
3061 /* Remove old key if exists */
3063 memset(channel->key, 0, channel->key_len / 8);
3064 silc_free(channel->key);
3065 silc_cipher_free(channel->channel_key);
3068 /* Create new cipher */
3069 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3070 channel->channel_key = NULL;
3075 if (channel->cipher)
3076 silc_free(channel->cipher);
3077 channel->cipher = strdup(cipher);
3080 channel->key_len = tmp_len * 8;
3081 channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
3082 memcpy(channel->key, tmp, tmp_len);
3083 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3085 /* Generate HMAC key from the channel key data and set it */
3087 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3088 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3089 silc_hmac_set_key(channel->hmac, hash,
3090 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3092 memset(hash, 0, sizeof(hash));
3093 memset(tmp, 0, tmp_len);
3095 if (server->server_type == SILC_ROUTER) {
3096 if (!channel->rekey)
3097 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3098 channel->rekey->context = (void *)server;
3099 channel->rekey->channel = channel;
3100 if (channel->rekey->task)
3101 silc_schedule_task_del(server->schedule, channel->rekey->task);
3103 channel->rekey->task =
3104 silc_schedule_task_add(server->schedule, 0,
3105 silc_server_channel_key_rekey,
3106 (void *)channel->rekey, 3600, 0,
3108 SILC_TASK_PRI_NORMAL);
3114 silc_channel_key_payload_free(payload);
3119 /* Heartbeat callback. This function is set as argument for the
3120 silc_socket_set_heartbeat function. The library will call this function
3121 at the set time interval. */
3123 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3126 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3128 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname,
3131 /* Send the heartbeat */
3132 silc_server_send_heartbeat(hb->server, sock);
3135 /* Returns assembled of all servers in the given ID list. The packet's
3136 form is dictated by the New ID payload. */
3138 static void silc_server_announce_get_servers(SilcServer server,
3139 SilcServerEntry remote,
3141 SilcBuffer *servers,
3142 unsigned long creation_time)
3144 SilcIDCacheList list;
3145 SilcIDCacheEntry id_cache;
3146 SilcServerEntry entry;
3149 /* Go through all clients in the list */
3150 if (silc_idcache_get_all(id_list->servers, &list)) {
3151 if (silc_idcache_list_first(list, &id_cache)) {
3153 entry = (SilcServerEntry)id_cache->context;
3155 /* Do not announce the one we've sending our announcements and
3156 do not announce ourself. Also check the creation time if it's
3158 if ((entry == remote) || (entry == server->id_entry) ||
3159 (creation_time && entry->data.created < creation_time)) {
3160 if (!silc_idcache_list_next(list, &id_cache))
3165 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3167 *servers = silc_buffer_realloc(*servers,
3169 (*servers)->truelen + idp->len :
3171 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3172 silc_buffer_put(*servers, idp->data, idp->len);
3173 silc_buffer_pull(*servers, idp->len);
3174 silc_buffer_free(idp);
3176 if (!silc_idcache_list_next(list, &id_cache))
3181 silc_idcache_list_free(list);
3186 silc_server_announce_encode_notify(SilcNotifyType notify, uint32 argc, ...)
3192 p = silc_notify_payload_encode(notify, argc, ap);
3198 /* This function is used by router to announce existing servers to our
3199 primary router when we've connected to it. If `creation_time' is non-zero
3200 then only the servers that has been created after the `creation_time'
3201 will be announced. */
3203 void silc_server_announce_servers(SilcServer server, bool global,
3204 unsigned long creation_time,
3205 SilcSocketConnection remote)
3207 SilcBuffer servers = NULL;
3209 SILC_LOG_DEBUG(("Announcing servers"));
3211 /* Get servers in local list */
3212 silc_server_announce_get_servers(server, remote->user_data,
3213 server->local_list, &servers,
3217 /* Get servers in global list */
3218 silc_server_announce_get_servers(server, remote->user_data,
3219 server->global_list, &servers,
3223 silc_buffer_push(servers, servers->data - servers->head);
3224 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3226 /* Send the packet */
3227 silc_server_packet_send(server, remote,
3228 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3229 servers->data, servers->len, TRUE);
3231 silc_buffer_free(servers);
3235 /* Returns assembled packet of all clients in the given ID list. The
3236 packet's form is dictated by the New ID Payload. */
3238 static void silc_server_announce_get_clients(SilcServer server,
3240 SilcBuffer *clients,
3242 unsigned long creation_time)
3244 SilcIDCacheList list;
3245 SilcIDCacheEntry id_cache;
3246 SilcClientEntry client;
3249 unsigned char mode[4];
3251 /* Go through all clients in the list */
3252 if (silc_idcache_get_all(id_list->clients, &list)) {
3253 if (silc_idcache_list_first(list, &id_cache)) {
3255 client = (SilcClientEntry)id_cache->context;
3257 if (creation_time && client->data.created < creation_time) {
3258 if (!silc_idcache_list_next(list, &id_cache))
3263 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3265 *clients = silc_buffer_realloc(*clients,
3267 (*clients)->truelen + idp->len :
3269 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3270 silc_buffer_put(*clients, idp->data, idp->len);
3271 silc_buffer_pull(*clients, idp->len);
3273 SILC_PUT32_MSB(client->mode, mode);
3274 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3275 2, idp->data, idp->len,
3277 *umodes = silc_buffer_realloc(*umodes,
3279 (*umodes)->truelen + tmp->len :
3281 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3282 silc_buffer_put(*umodes, tmp->data, tmp->len);
3283 silc_buffer_pull(*umodes, tmp->len);
3284 silc_buffer_free(tmp);
3286 silc_buffer_free(idp);
3288 if (!silc_idcache_list_next(list, &id_cache))
3293 silc_idcache_list_free(list);
3297 /* This function is used to announce our existing clients to our router
3298 when we've connected to it. If `creation_time' is non-zero then only
3299 the clients that has been created after the `creation_time' will be
3302 void silc_server_announce_clients(SilcServer server,
3303 unsigned long creation_time,
3304 SilcSocketConnection remote)
3306 SilcBuffer clients = NULL;
3307 SilcBuffer umodes = NULL;
3309 SILC_LOG_DEBUG(("Announcing clients"));
3311 /* Get clients in local list */
3312 silc_server_announce_get_clients(server, server->local_list,
3313 &clients, &umodes, creation_time);
3315 /* As router we announce our global list as well */
3316 if (server->server_type == SILC_ROUTER)
3317 silc_server_announce_get_clients(server, server->global_list,
3318 &clients, &umodes, creation_time);
3321 silc_buffer_push(clients, clients->data - clients->head);
3322 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3324 /* Send the packet */
3325 silc_server_packet_send(server, remote,
3326 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3327 clients->data, clients->len, TRUE);
3329 silc_buffer_free(clients);
3333 silc_buffer_push(umodes, umodes->data - umodes->head);
3334 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3336 /* Send the packet */
3337 silc_server_packet_send(server, remote,
3338 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3339 umodes->data, umodes->len, TRUE);
3341 silc_buffer_free(umodes);
3345 /* Returns channel's topic for announcing it */
3347 void silc_server_announce_get_channel_topic(SilcServer server,
3348 SilcChannelEntry channel,
3353 if (channel->topic) {
3354 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3355 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3356 chidp->data, chidp->len,
3358 strlen(channel->topic));
3359 silc_buffer_free(chidp);
3363 /* Returns assembled packets for channel users of the `channel'. */
3365 void silc_server_announce_get_channel_users(SilcServer server,
3366 SilcChannelEntry channel,
3367 SilcBuffer *channel_users,
3368 SilcBuffer *channel_users_modes)
3370 SilcChannelClientEntry chl;
3371 SilcHashTableList htl;
3372 SilcBuffer chidp, clidp;
3375 unsigned char mode[4];
3377 SILC_LOG_DEBUG(("Start"));
3379 /* Now find all users on the channel */
3380 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3381 silc_hash_table_list(channel->user_list, &htl);
3382 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3383 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3386 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3387 clidp->data, clidp->len,
3388 chidp->data, chidp->len);
3391 silc_buffer_realloc(*channel_users,
3393 (*channel_users)->truelen + len : len));
3394 silc_buffer_pull_tail(*channel_users,
3395 ((*channel_users)->end -
3396 (*channel_users)->data));
3398 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3399 silc_buffer_pull(*channel_users, len);
3400 silc_buffer_free(tmp);
3402 /* CUMODE notify for mode change on the channel */
3403 SILC_PUT32_MSB(chl->mode, mode);
3404 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3405 3, clidp->data, clidp->len,
3407 clidp->data, clidp->len);
3409 *channel_users_modes =
3410 silc_buffer_realloc(*channel_users_modes,
3411 (*channel_users_modes ?
3412 (*channel_users_modes)->truelen + len : len));
3413 silc_buffer_pull_tail(*channel_users_modes,
3414 ((*channel_users_modes)->end -
3415 (*channel_users_modes)->data));
3417 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3418 silc_buffer_pull(*channel_users_modes, len);
3419 silc_buffer_free(tmp);
3421 silc_buffer_free(clidp);
3423 silc_buffer_free(chidp);
3426 /* Returns assembled packets for all channels and users on those channels
3427 from the given ID List. The packets are in the form dictated by the
3428 New Channel and New Channel User payloads. */
3430 void silc_server_announce_get_channels(SilcServer server,
3432 SilcBuffer *channels,
3433 SilcBuffer *channel_users,
3434 SilcBuffer **channel_users_modes,
3435 uint32 *channel_users_modes_c,
3436 SilcBuffer **channel_topics,
3437 SilcChannelID ***channel_ids,
3438 unsigned long creation_time)
3440 SilcIDCacheList list;
3441 SilcIDCacheEntry id_cache;
3442 SilcChannelEntry channel;
3447 int i = *channel_users_modes_c;
3450 SILC_LOG_DEBUG(("Start"));
3452 /* Go through all channels in the list */
3453 if (silc_idcache_get_all(id_list->channels, &list)) {
3454 if (silc_idcache_list_first(list, &id_cache)) {
3456 channel = (SilcChannelEntry)id_cache->context;
3458 if (creation_time && channel->created < creation_time)
3463 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3464 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3465 name_len = strlen(channel->channel_name);
3468 len = 4 + name_len + id_len + 4;
3470 silc_buffer_realloc(*channels,
3471 (*channels ? (*channels)->truelen +
3473 silc_buffer_pull_tail(*channels,
3474 ((*channels)->end - (*channels)->data));
3475 silc_buffer_format(*channels,
3476 SILC_STR_UI_SHORT(name_len),
3477 SILC_STR_UI_XNSTRING(channel->channel_name,
3479 SILC_STR_UI_SHORT(id_len),
3480 SILC_STR_UI_XNSTRING(cid, id_len),
3481 SILC_STR_UI_INT(channel->mode),
3483 silc_buffer_pull(*channels, len);
3486 /* Channel user modes */
3487 *channel_users_modes = silc_realloc(*channel_users_modes,
3488 sizeof(**channel_users_modes) *
3490 (*channel_users_modes)[i] = NULL;
3491 *channel_ids = silc_realloc(*channel_ids,
3492 sizeof(**channel_ids) * (i + 1));
3493 (*channel_ids)[i] = NULL;
3494 silc_server_announce_get_channel_users(server, channel,
3496 &(*channel_users_modes)[i]);
3497 (*channel_ids)[i] = channel->id;
3499 /* Channel's topic */
3500 *channel_topics = silc_realloc(*channel_topics,
3501 sizeof(**channel_topics) * (i + 1));
3502 (*channel_topics)[i] = NULL;
3503 silc_server_announce_get_channel_topic(server, channel,
3504 &(*channel_topics)[i]);
3507 if (!silc_idcache_list_next(list, &id_cache))
3511 *channel_users_modes_c += i;
3514 silc_idcache_list_free(list);
3518 /* This function is used to announce our existing channels to our router
3519 when we've connected to it. This also announces the users on the
3520 channels to the router. If the `creation_time' is non-zero only the
3521 channels that was created after the `creation_time' are announced.
3522 Note that the channel users are still announced even if the `creation_time'
3525 void silc_server_announce_channels(SilcServer server,
3526 unsigned long creation_time,
3527 SilcSocketConnection remote)
3529 SilcBuffer channels = NULL, channel_users = NULL;
3530 SilcBuffer *channel_users_modes = NULL;
3531 SilcBuffer *channel_topics = NULL;
3532 uint32 channel_users_modes_c = 0;
3533 SilcChannelID **channel_ids = NULL;
3535 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3537 /* Get channels and channel users in local list */
3538 silc_server_announce_get_channels(server, server->local_list,
3539 &channels, &channel_users,
3540 &channel_users_modes,
3541 &channel_users_modes_c,
3543 &channel_ids, creation_time);
3545 /* Get channels and channel users in global list */
3546 if (server->server_type != SILC_SERVER)
3547 silc_server_announce_get_channels(server, server->global_list,
3548 &channels, &channel_users,
3549 &channel_users_modes,
3550 &channel_users_modes_c,
3552 &channel_ids, creation_time);
3555 silc_buffer_push(channels, channels->data - channels->head);
3556 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3558 /* Send the packet */
3559 silc_server_packet_send(server, remote,
3560 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3561 channels->data, channels->len,
3564 silc_buffer_free(channels);
3567 if (channel_users) {
3568 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3569 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3570 channel_users->len);
3572 /* Send the packet */
3573 silc_server_packet_send(server, remote,
3574 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3575 channel_users->data, channel_users->len,
3578 silc_buffer_free(channel_users);
3581 if (channel_users_modes) {
3584 for (i = 0; i < channel_users_modes_c; i++) {
3585 silc_buffer_push(channel_users_modes[i],
3586 channel_users_modes[i]->data -
3587 channel_users_modes[i]->head);
3588 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3589 channel_users_modes[i]->len);
3590 silc_server_packet_send_dest(server, remote,
3591 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3592 channel_ids[i], SILC_ID_CHANNEL,
3593 channel_users_modes[i]->data,
3594 channel_users_modes[i]->len,
3596 silc_buffer_free(channel_users_modes[i]);
3598 silc_free(channel_users_modes);
3601 if (channel_topics) {
3604 for (i = 0; i < channel_users_modes_c; i++) {
3605 if (!channel_topics[i])
3608 silc_buffer_push(channel_topics[i],
3609 channel_topics[i]->data -
3610 channel_topics[i]->head);
3611 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
3612 channel_topics[i]->len);
3613 silc_server_packet_send_dest(server, remote,
3614 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3615 channel_ids[i], SILC_ID_CHANNEL,
3616 channel_topics[i]->data,
3617 channel_topics[i]->len,
3619 silc_buffer_free(channel_topics[i]);
3621 silc_free(channel_topics);
3624 silc_free(channel_ids);
3627 /* Failure timeout callback. If this is called then we will immediately
3628 process the received failure. We always process the failure with timeout
3629 since we do not want to blindly trust to received failure packets.
3630 This won't be called (the timeout is cancelled) if the failure was
3631 bogus (it is bogus if remote does not close the connection after sending
3634 SILC_TASK_CALLBACK(silc_server_failure_callback)
3636 SilcServerFailureContext f = (SilcServerFailureContext)context;
3638 if (f->sock->protocol) {
3639 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3640 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3646 /* Assembles user list and users mode list from the `channel'. */
3648 void silc_server_get_users_on_channel(SilcServer server,
3649 SilcChannelEntry channel,
3650 SilcBuffer *user_list,
3651 SilcBuffer *mode_list,
3654 SilcChannelClientEntry chl;
3655 SilcHashTableList htl;
3656 SilcBuffer client_id_list;
3657 SilcBuffer client_mode_list;
3659 uint32 list_count = 0, len = 0;
3661 silc_hash_table_list(channel->user_list, &htl);
3662 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3663 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3665 client_id_list = silc_buffer_alloc(len);
3667 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3668 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3669 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3671 silc_hash_table_list(channel->user_list, &htl);
3672 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3674 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3675 silc_buffer_put(client_id_list, idp->data, idp->len);
3676 silc_buffer_pull(client_id_list, idp->len);
3677 silc_buffer_free(idp);
3679 /* Client's mode on channel */
3680 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3681 silc_buffer_pull(client_mode_list, 4);
3685 silc_buffer_push(client_id_list,
3686 client_id_list->data - client_id_list->head);
3687 silc_buffer_push(client_mode_list,
3688 client_mode_list->data - client_mode_list->head);
3690 *user_list = client_id_list;
3691 *mode_list = client_mode_list;
3692 *user_count = list_count;
3695 /* Saves users and their modes to the `channel'. */
3697 void silc_server_save_users_on_channel(SilcServer server,
3698 SilcSocketConnection sock,
3699 SilcChannelEntry channel,
3700 SilcClientID *noadd,
3701 SilcBuffer user_list,
3702 SilcBuffer mode_list,
3708 SilcClientID *client_id;
3709 SilcClientEntry client;
3710 SilcIDCacheEntry cache;
3713 for (i = 0; i < user_count; i++) {
3715 SILC_GET16_MSB(idp_len, user_list->data + 2);
3717 client_id = silc_id_payload_parse_id(user_list->data, idp_len);
3718 silc_buffer_pull(user_list, idp_len);
3723 SILC_GET32_MSB(mode, mode_list->data);
3724 silc_buffer_pull(mode_list, 4);
3726 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3727 silc_free(client_id);
3733 /* Check if we have this client cached already. */
3734 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3735 server->server_type, &cache);
3737 client = silc_idlist_find_client_by_id(server->global_list,
3738 client_id, server->server_type,
3743 /* If router did not find such Client ID in its lists then this must
3744 be bogus client or some router in the net is buggy. */
3745 if (server->server_type == SILC_ROUTER) {
3746 silc_free(client_id);
3750 /* We don't have that client anywhere, add it. The client is added
3751 to global list since server didn't have it in the lists so it must be
3753 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3754 silc_id_dup(client_id, SILC_ID_CLIENT),
3755 sock->user_data, NULL, 0);
3757 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3758 silc_free(client_id);
3762 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3764 /* Found, if it is from global list we'll assure that we won't
3765 expire it now that the entry is on channel. */
3770 silc_free(client_id);
3772 if (!silc_server_client_on_channel(client, channel)) {
3773 /* Client was not on the channel, add it. */
3774 SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3775 chl->client = client;
3777 chl->channel = channel;
3778 silc_hash_table_add(channel->user_list, chl->client, chl);
3779 silc_hash_table_add(client->channels, chl->channel, chl);
3784 /* Lookups route to the client indicated by the `id_data'. The connection
3785 object and internal data object is returned. Returns NULL if route
3786 could not be found to the client. If the `client_id' is specified then
3787 it is used and the `id_data' is ignored. */
3789 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3790 unsigned char *id_data,
3792 SilcClientID *client_id,
3793 SilcIDListData *idata)
3796 SilcClientEntry client;
3798 SILC_LOG_DEBUG(("Start"));
3800 /* Decode destination Client ID */
3802 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3804 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3808 id = silc_id_dup(client_id, SILC_ID_CLIENT);
3811 /* If the destination belongs to our server we don't have to route
3812 the packet anywhere but to send it to the local destination. */
3813 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
3817 /* If we are router and the client has router then the client is in
3818 our cell but not directly connected to us. */
3819 if (server->server_type == SILC_ROUTER && client->router) {
3820 /* We are of course in this case the client's router thus the route
3821 to the client is the server who owns the client. So, we will send
3822 the packet to that server. */
3824 *idata = (SilcIDListData)client->router;
3825 return client->router->connection;
3828 /* Seems that client really is directly connected to us */
3830 *idata = (SilcIDListData)client;
3831 return client->connection;
3834 /* Destination belongs to someone not in this server. If we are normal
3835 server our action is to send the packet to our router. */
3836 if (server->server_type != SILC_ROUTER && !server->standalone) {
3839 *idata = (SilcIDListData)server->router;
3840 return server->router->connection;
3843 /* We are router and we will perform route lookup for the destination
3844 and send the packet to fastest route. */
3845 if (server->server_type == SILC_ROUTER && !server->standalone) {
3846 /* Check first that the ID is valid */
3847 client = silc_idlist_find_client_by_id(server->global_list, id,
3850 SilcSocketConnection dst_sock;
3852 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
3856 *idata = (SilcIDListData)dst_sock->user_data;
3865 /* Encodes and returns channel list of channels the `client' has joined.
3866 Secret channels are not put to the list. */
3868 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
3869 SilcClientEntry client)
3871 SilcBuffer buffer = NULL;
3872 SilcChannelEntry channel;
3873 SilcChannelClientEntry chl;
3874 SilcHashTableList htl;
3880 silc_hash_table_list(client->channels, &htl);
3881 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3882 channel = chl->channel;
3884 if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
3885 channel->mode & SILC_CHANNEL_MODE_PRIVATE)
3888 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3889 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3890 name_len = strlen(channel->channel_name);
3892 len = 4 + name_len + id_len + 4;
3893 buffer = silc_buffer_realloc(buffer,
3894 (buffer ? (buffer)->truelen + len : len));
3895 silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
3896 silc_buffer_format(buffer,
3897 SILC_STR_UI_SHORT(name_len),
3898 SILC_STR_UI_XNSTRING(channel->channel_name,
3900 SILC_STR_UI_SHORT(id_len),
3901 SILC_STR_UI_XNSTRING(cid, id_len),
3902 SILC_STR_UI_INT(chl->mode), /* Client's mode */
3904 silc_buffer_pull(buffer, len);
3909 silc_buffer_push(buffer, buffer->data - buffer->head);
3914 /* Finds client entry by Client ID and if it is not found then resolves
3915 it using WHOIS command. */
3917 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
3918 SilcClientID *client_id)
3920 SilcClientEntry client;
3922 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3925 client = silc_idlist_find_client_by_id(server->global_list,
3926 client_id, TRUE, NULL);
3927 if (!client && server->server_type == SILC_ROUTER)
3931 if (!client && server->standalone)
3934 if (!client || !client->nickname || !client->username) {
3935 SilcBuffer buffer, idp;
3937 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
3938 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
3939 client->resolve_cmd_ident = ++server->cmd_ident;
3941 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3942 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
3943 server->cmd_ident, 1,
3944 3, idp->data, idp->len);
3945 silc_server_packet_send(server, client ? client->router->connection :
3946 server->router->connection,
3947 SILC_PACKET_COMMAND, 0,
3948 buffer->data, buffer->len, FALSE);
3949 silc_buffer_free(idp);
3950 silc_buffer_free(buffer);
3957 /* A timeout callback for the re-key. We will be the initiator of the
3960 SILC_TASK_CALLBACK(silc_server_rekey_callback)
3962 SilcSocketConnection sock = (SilcSocketConnection)context;
3963 SilcIDListData idata = (SilcIDListData)sock->user_data;
3964 SilcServer server = (SilcServer)idata->rekey->context;
3965 SilcProtocol protocol;
3966 SilcServerRekeyInternalContext *proto_ctx;
3968 SILC_LOG_DEBUG(("Start"));
3970 /* Allocate internal protocol context. This is sent as context
3972 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
3973 proto_ctx->server = (void *)server;
3974 proto_ctx->sock = sock;
3975 proto_ctx->responder = FALSE;
3976 proto_ctx->pfs = idata->rekey->pfs;
3978 /* Perform rekey protocol. Will call the final callback after the
3979 protocol is over. */
3980 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
3981 &protocol, proto_ctx, silc_server_rekey_final);
3982 sock->protocol = protocol;
3984 /* Run the protocol */
3985 silc_protocol_execute(protocol, server->schedule, 0, 0);
3987 /* Re-register re-key timeout */
3988 silc_schedule_task_add(server->schedule, sock->sock,
3989 silc_server_rekey_callback,
3990 context, idata->rekey->timeout, 0,
3991 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
3994 /* The final callback for the REKEY protocol. This will actually take the
3995 new key material into use. */
3997 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
3999 SilcProtocol protocol = (SilcProtocol)context;
4000 SilcServerRekeyInternalContext *ctx =
4001 (SilcServerRekeyInternalContext *)protocol->context;
4002 SilcServer server = (SilcServer)ctx->server;
4003 SilcSocketConnection sock = ctx->sock;
4005 SILC_LOG_DEBUG(("Start"));
4007 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4008 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4009 /* Error occured during protocol */
4010 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4011 silc_protocol_cancel(protocol, server->schedule);
4012 silc_protocol_free(protocol);
4013 sock->protocol = NULL;
4015 silc_packet_context_free(ctx->packet);
4017 silc_ske_free(ctx->ske);
4022 /* Purge the outgoing data queue to assure that all rekey packets really
4023 go to the network before we quit the protocol. */
4024 silc_server_packet_queue_purge(server, sock);
4027 silc_protocol_free(protocol);
4028 sock->protocol = NULL;
4030 silc_packet_context_free(ctx->packet);
4032 silc_ske_free(ctx->ske);