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);
507 server->schedule = NULL;
510 silc_server_protocols_unregister();
512 SILC_LOG_DEBUG(("Server stopped"));
515 /* Function that is called when the network connection to a router has
516 been established. This will continue with the key exchange protocol
517 with the remote router. */
519 void silc_server_start_key_exchange(SilcServer server,
520 SilcServerConnection sconn,
523 SilcSocketConnection newsocket;
524 SilcProtocol protocol;
525 SilcServerKEInternalContext *proto_ctx;
528 /* Set socket options */
529 silc_net_set_socket_nonblock(sock);
530 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
532 /* Create socket connection for the connection. Even though we
533 know that we are connecting to a router we will mark the socket
534 to be unknown connection until we have executed authentication
536 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
537 server->sockets[sock] = newsocket;
538 newsocket->hostname = strdup(sconn->remote_host);
539 newsocket->ip = strdup(sconn->remote_host);
540 newsocket->port = sconn->remote_port;
541 sconn->sock = newsocket;
543 /* Allocate internal protocol context. This is sent as context
545 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
546 proto_ctx->server = (void *)server;
547 proto_ctx->context = (void *)sconn;
548 proto_ctx->sock = newsocket;
549 proto_ctx->rng = server->rng;
550 proto_ctx->responder = FALSE;
552 /* Perform key exchange protocol. silc_server_connect_to_router_second
553 will be called after the protocol is finished. */
554 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
555 &protocol, proto_ctx,
556 silc_server_connect_to_router_second);
557 newsocket->protocol = protocol;
559 /* Register a timeout task that will be executed if the protocol
560 is not executed within set limit. */
561 proto_ctx->timeout_task =
562 silc_schedule_task_add(server->schedule, sock,
563 silc_server_timeout_remote,
564 server, server->params->protocol_timeout,
565 server->params->protocol_timeout_usec,
569 /* Register the connection for network input and output. This sets
570 that scheduler will listen for incoming packets for this connection
571 and sets that outgoing packets may be sent to this connection as
572 well. However, this doesn't set the scheduler for outgoing traffic,
573 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
574 later when outgoing data is available. */
575 context = (void *)server;
576 SILC_REGISTER_CONNECTION_FOR_IO(sock);
578 /* Run the protocol */
579 silc_protocol_execute(protocol, server->schedule, 0, 0);
582 /* Timeout callback that will be called to retry connecting to remote
583 router. This is used by both normal and router server. This will wait
584 before retrying the connecting. The timeout is generated by exponential
585 backoff algorithm. */
587 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
589 SilcServerConnection sconn = (SilcServerConnection)context;
590 SilcServer server = sconn->server;
592 SILC_LOG_INFO(("Retrying connecting to a router"));
594 /* Calculate next timeout */
595 if (sconn->retry_count >= 1) {
596 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
597 if (sconn->retry_timeout > SILC_SERVER_RETRY_INTERVAL_MAX)
598 sconn->retry_timeout = SILC_SERVER_RETRY_INTERVAL_MAX;
600 sconn->retry_timeout = server->params->retry_interval_min;
602 sconn->retry_count++;
603 sconn->retry_timeout = sconn->retry_timeout +
604 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
606 /* If we've reached max retry count, give up. */
607 if (sconn->retry_count > server->params->retry_count &&
608 server->params->retry_keep_trying == FALSE) {
609 SILC_LOG_ERROR(("Could not connect to router, giving up"));
610 silc_free(sconn->remote_host);
615 /* Wait one before retrying */
616 silc_schedule_task_add(server->schedule, fd, silc_server_connect_router,
617 context, sconn->retry_timeout,
618 server->params->retry_interval_min_usec,
619 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
622 /* Generic routine to use connect to a router. */
624 SILC_TASK_CALLBACK(silc_server_connect_router)
626 SilcServerConnection sconn = (SilcServerConnection)context;
627 SilcServer server = sconn->server;
630 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
631 (sconn->backup ? "backup router" : "router"),
632 sconn->remote_host, sconn->remote_port));
634 server->router_connect = time(0);
636 /* Connect to remote host */
637 sock = silc_net_create_connection(server->config->listen_port->local_ip,
641 SILC_LOG_ERROR(("Could not connect to router"));
642 silc_schedule_task_add(server->schedule, fd,
643 silc_server_connect_to_router_retry,
644 context, 0, 1, SILC_TASK_TIMEOUT,
645 SILC_TASK_PRI_NORMAL);
649 /* Continue with key exchange protocol */
650 silc_server_start_key_exchange(server, sconn, sock);
653 /* This function connects to our primary router or if we are a router this
654 establishes all our primary routes. This is called at the start of the
655 server to do authentication and key exchange with our router - called
658 SILC_TASK_CALLBACK(silc_server_connect_to_router)
660 SilcServer server = (SilcServer)context;
661 SilcServerConnection sconn;
662 SilcServerConfigSectionServerConnection *ptr;
664 SILC_LOG_DEBUG(("Connecting to router(s)"));
666 if (server->server_type == SILC_SERVER) {
667 SILC_LOG_DEBUG(("We are normal server"));
668 } else if (server->server_type == SILC_ROUTER) {
669 SILC_LOG_DEBUG(("We are router"));
671 SILC_LOG_DEBUG(("We are backup router/normal server"));
674 /* Create the connections to all our routes */
675 ptr = server->config->routers;
678 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
679 ptr->backup_router ? "Backup router" : "Router",
680 ptr->initiator ? "Initiator" : "Responder",
681 ptr->host, ptr->port));
683 if (ptr->initiator) {
684 /* Allocate connection object for hold connection specific stuff. */
685 sconn = silc_calloc(1, sizeof(*sconn));
686 sconn->server = server;
687 sconn->remote_host = strdup(ptr->host);
688 sconn->remote_port = ptr->port;
689 sconn->backup = ptr->backup_router;
691 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
692 sconn->backup_replace_port = ptr->backup_replace_port;
695 if (!server->router_conn && !sconn->backup)
696 server->router_conn = sconn;
698 silc_schedule_task_add(server->schedule, fd,
699 silc_server_connect_router,
700 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
701 SILC_TASK_PRI_NORMAL);
710 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
712 /* There wasn't a configured router, we will continue but we don't
713 have a connection to outside world. We will be standalone server. */
714 server->standalone = TRUE;
717 /* Second part of connecting to router(s). Key exchange protocol has been
718 executed and now we will execute authentication protocol. */
720 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
722 SilcProtocol protocol = (SilcProtocol)context;
723 SilcServerKEInternalContext *ctx =
724 (SilcServerKEInternalContext *)protocol->context;
725 SilcServer server = (SilcServer)ctx->server;
726 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
727 SilcSocketConnection sock = ctx->sock;
728 SilcServerConnAuthInternalContext *proto_ctx;
729 SilcServerConfigSectionServerConnection *conn = NULL;
731 SILC_LOG_DEBUG(("Start"));
733 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
734 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
735 /* Error occured during protocol */
736 silc_protocol_free(protocol);
737 sock->protocol = NULL;
738 silc_ske_free_key_material(ctx->keymat);
740 silc_packet_context_free(ctx->packet);
742 silc_ske_free(ctx->ske);
743 silc_free(ctx->dest_id);
745 silc_schedule_task_del_by_callback(server->schedule,
746 silc_server_failure_callback);
747 silc_server_disconnect_remote(server, sock, "Server closed connection: "
748 "Key exchange failed");
752 /* We now have the key material as the result of the key exchange
753 protocol. Take the key material into use. Free the raw key material
754 as soon as we've set them into use. */
755 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
756 ctx->sock, ctx->keymat,
757 ctx->ske->prop->cipher,
758 ctx->ske->prop->pkcs,
759 ctx->ske->prop->hash,
760 ctx->ske->prop->hmac,
761 ctx->ske->prop->group,
763 silc_protocol_free(protocol);
764 sock->protocol = NULL;
765 silc_ske_free_key_material(ctx->keymat);
767 silc_packet_context_free(ctx->packet);
769 silc_ske_free(ctx->ske);
770 silc_free(ctx->dest_id);
772 silc_schedule_task_del_by_callback(server->schedule,
773 silc_server_failure_callback);
774 silc_server_disconnect_remote(server, sock, "Server closed connection: "
775 "Key exchange failed");
778 silc_ske_free_key_material(ctx->keymat);
780 /* Allocate internal context for the authentication protocol. This
781 is sent as context for the protocol. */
782 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
783 proto_ctx->server = (void *)server;
784 proto_ctx->context = (void *)sconn;
785 proto_ctx->sock = sock;
786 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
787 proto_ctx->dest_id_type = ctx->dest_id_type;
788 proto_ctx->dest_id = ctx->dest_id;
790 /* Resolve the authentication method used in this connection. Check if
791 we find a match from user configured connections */
792 conn = silc_server_config_find_router_conn(server->config,
796 /* Match found. Use the configured authentication method */
797 proto_ctx->auth_meth = conn->auth_meth;
798 if (conn->auth_data) {
799 proto_ctx->auth_data = strdup(conn->auth_data);
800 proto_ctx->auth_data_len = strlen(conn->auth_data);
803 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
804 sock->hostname, sock->ip, sock->port));
805 silc_protocol_free(protocol);
806 sock->protocol = NULL;
808 silc_packet_context_free(ctx->packet);
810 silc_ske_free(ctx->ske);
811 silc_free(ctx->dest_id);
813 silc_schedule_task_del_by_callback(server->schedule,
814 silc_server_failure_callback);
815 silc_server_disconnect_remote(server, sock, "Server closed connection: "
816 "Key exchange failed");
820 /* Free old protocol as it is finished now */
821 silc_protocol_free(protocol);
823 silc_packet_context_free(ctx->packet);
825 sock->protocol = NULL;
827 /* Allocate the authentication protocol. This is allocated here
828 but we won't start it yet. We will be receiving party of this
829 protocol thus we will wait that connecting party will make
831 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
832 &sock->protocol, proto_ctx,
833 silc_server_connect_to_router_final);
835 /* Register timeout task. If the protocol is not executed inside
836 this timelimit the connection will be terminated. Currently
837 this is 15 seconds and is hard coded limit (XXX). */
838 proto_ctx->timeout_task =
839 silc_schedule_task_add(server->schedule, sock->sock,
840 silc_server_timeout_remote,
841 (void *)server, 15, 0,
845 /* Run the protocol */
846 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
849 /* Finalizes the connection to router. Registers a server task to the
850 queue so that we can accept new connections. */
852 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
854 SilcProtocol protocol = (SilcProtocol)context;
855 SilcServerConnAuthInternalContext *ctx =
856 (SilcServerConnAuthInternalContext *)protocol->context;
857 SilcServer server = (SilcServer)ctx->server;
858 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
859 SilcSocketConnection sock = ctx->sock;
860 SilcServerEntry id_entry;
862 SilcServerHBContext hb_context;
863 unsigned char *id_string;
865 SilcIDListData idata;
867 SILC_LOG_DEBUG(("Start"));
869 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
870 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
871 /* Error occured during protocol */
872 silc_free(ctx->dest_id);
873 silc_server_disconnect_remote(server, sock, "Server closed connection: "
874 "Authentication failed");
878 /* Add a task to the queue. This task receives new connections to the
879 server. This task remains on the queue until the end of the program. */
880 if (!server->listenning && !sconn->backup) {
881 silc_schedule_task_add(server->schedule, server->sock,
882 silc_server_accept_new_connection,
883 (void *)server, 0, 0,
885 SILC_TASK_PRI_NORMAL);
886 server->listenning = TRUE;
889 /* Send NEW_SERVER packet to the router. We will become registered
890 to the SILC network after sending this packet. */
891 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
892 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
893 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
894 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
895 silc_buffer_format(packet,
896 SILC_STR_UI_SHORT(id_len),
897 SILC_STR_UI_XNSTRING(id_string, id_len),
898 SILC_STR_UI_SHORT(strlen(server->server_name)),
899 SILC_STR_UI_XNSTRING(server->server_name,
900 strlen(server->server_name)),
903 /* Send the packet */
904 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
905 packet->data, packet->len, TRUE);
906 silc_buffer_free(packet);
907 silc_free(id_string);
909 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
911 /* Check that we do not have this ID already */
912 id_entry = silc_idlist_find_server_by_id(server->local_list,
913 ctx->dest_id, TRUE, NULL);
915 silc_idcache_del_by_context(server->local_list->servers, id_entry);
917 id_entry = silc_idlist_find_server_by_id(server->global_list,
918 ctx->dest_id, TRUE, NULL);
920 silc_idcache_del_by_context(server->global_list->servers, id_entry);
923 SILC_LOG_DEBUG(("New server id(%s)",
924 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
926 /* Add the connected router to global server list */
927 id_entry = silc_idlist_add_server(server->global_list,
928 strdup(sock->hostname),
929 SILC_ROUTER, ctx->dest_id, NULL, sock);
931 silc_free(ctx->dest_id);
932 silc_server_disconnect_remote(server, sock, "Server closed connection: "
933 "Authentication failed");
937 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
938 silc_free(sock->user_data);
939 sock->user_data = (void *)id_entry;
940 sock->type = SILC_SOCKET_TYPE_ROUTER;
941 idata = (SilcIDListData)sock->user_data;
942 idata->status |= SILC_IDLIST_STATUS_REGISTERED;
944 /* Perform keepalive. The `hb_context' will be freed automatically
945 when finally calling the silc_socket_free function. XXX hardcoded
947 hb_context = silc_calloc(1, sizeof(*hb_context));
948 hb_context->server = server;
949 silc_socket_set_heartbeat(sock, 600, hb_context,
950 silc_server_perform_heartbeat,
953 /* Register re-key timeout */
954 idata->rekey->timeout = 3600; /* XXX hardcoded */
955 idata->rekey->context = (void *)server;
956 silc_schedule_task_add(server->schedule, sock->sock,
957 silc_server_rekey_callback,
958 (void *)sock, idata->rekey->timeout, 0,
959 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
961 if (!sconn->backup) {
962 /* Mark this router our primary router if we're still standalone */
963 if (server->standalone) {
964 server->id_entry->router = id_entry;
965 server->router = id_entry;
966 server->standalone = FALSE;
968 /* If we are router then announce our possible servers. */
969 if (server->server_type == SILC_ROUTER)
970 silc_server_announce_servers(server, FALSE, 0,
971 server->router->connection);
973 /* Announce our clients and channels to the router */
974 silc_server_announce_clients(server, 0, server->router->connection);
975 silc_server_announce_channels(server, 0, server->router->connection);
978 /* Add this server to be our backup router */
979 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
980 sconn->backup_replace_port, FALSE);
983 sock->protocol = NULL;
985 /* Call the completion callback to indicate that we've connected to
988 (*sconn->callback)(server, id_entry, sconn->callback_context);
991 /* Free the temporary connection data context */
993 silc_free(sconn->remote_host);
994 silc_free(sconn->backup_replace_ip);
997 if (sconn == server->router_conn)
998 server->router_conn = NULL;
1000 /* Free the protocol object */
1001 if (sock->protocol == protocol)
1002 sock->protocol = NULL;
1003 silc_protocol_free(protocol);
1005 silc_packet_context_free(ctx->packet);
1007 silc_ske_free(ctx->ske);
1008 silc_free(ctx->auth_data);
1012 /* Host lookup callbcak that is called after the incoming connection's
1013 IP and FQDN lookup is performed. This will actually check the acceptance
1014 of the incoming connection and will register the key exchange protocol
1015 for this connection. */
1018 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1021 SilcServer server = (SilcServer)context;
1022 SilcServerKEInternalContext *proto_ctx;
1023 void *cconfig, *sconfig, *rconfig;
1024 SilcServerConfigSectionDenyConnection *deny;
1027 SILC_LOG_DEBUG(("Start"));
1029 /* Check whether we could resolve both IP and FQDN. */
1030 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1031 server->params->require_reverse_mapping)) {
1032 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1033 sock->hostname ? sock->hostname :
1034 sock->ip ? sock->ip : ""));
1035 server->stat.conn_failures++;
1036 silc_server_disconnect_remote(server, sock,
1037 "Server closed connection: Unknown host");
1041 /* Register the connection for network input and output. This sets
1042 that scheduler will listen for incoming packets for this connection
1043 and sets that outgoing packets may be sent to this connection as well.
1044 However, this doesn't set the scheduler for outgoing traffic, it
1045 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1046 later when outgoing data is available. */
1047 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1049 SILC_LOG_INFO(("Incoming connection from %s (%s)", sock->hostname,
1052 port = server->sockets[server->sock]->port; /* Listenning port */
1054 /* Check whether this connection is denied to connect to us. */
1055 deny = silc_server_config_denied_conn(server->config, sock->ip, port);
1057 deny = silc_server_config_denied_conn(server->config, sock->hostname,
1060 /* The connection is denied */
1061 SILC_LOG_INFO(("Connection %s (%s) is denied",
1062 sock->hostname, sock->ip));
1063 silc_server_disconnect_remote(server, sock, deny->comment ?
1065 "Server closed connection: "
1066 "Connection refused");
1067 server->stat.conn_failures++;
1071 /* Check whether we have configred this sort of connection at all. We
1072 have to check all configurations since we don't know what type of
1073 connection this is. */
1074 if (!(cconfig = silc_server_config_find_client_conn(server->config,
1076 cconfig = silc_server_config_find_client_conn(server->config,
1079 if (!(sconfig = silc_server_config_find_server_conn(server->config,
1082 sconfig = silc_server_config_find_server_conn(server->config,
1085 if (!(rconfig = silc_server_config_find_router_conn(server->config,
1087 rconfig = silc_server_config_find_router_conn(server->config,
1090 if (!cconfig && !sconfig && !rconfig) {
1091 SILC_LOG_INFO(("Connection %s (%s) is not allowed",
1092 sock->hostname, sock->ip));
1093 silc_server_disconnect_remote(server, sock,
1094 "Server closed connection: "
1095 "Connection refused");
1096 server->stat.conn_failures++;
1100 /* The connection is allowed */
1102 /* Allocate internal context for key exchange protocol. This is
1103 sent as context for the protocol. */
1104 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1105 proto_ctx->server = context;
1106 proto_ctx->sock = sock;
1107 proto_ctx->rng = server->rng;
1108 proto_ctx->responder = TRUE;
1109 proto_ctx->cconfig = cconfig;
1110 proto_ctx->sconfig = sconfig;
1111 proto_ctx->rconfig = rconfig;
1113 /* Prepare the connection for key exchange protocol. We allocate the
1114 protocol but will not start it yet. The connector will be the
1115 initiator of the protocol thus we will wait for initiation from
1116 there before we start the protocol. */
1117 server->stat.auth_attempts++;
1118 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1119 &sock->protocol, proto_ctx,
1120 silc_server_accept_new_connection_second);
1122 /* Register a timeout task that will be executed if the connector
1123 will not start the key exchange protocol within 60 seconds. For
1124 now, this is a hard coded limit. After 60 secs the connection will
1125 be closed if the key exchange protocol has not been started. */
1126 proto_ctx->timeout_task =
1127 silc_schedule_task_add(server->schedule, sock->sock,
1128 silc_server_timeout_remote,
1134 /* Accepts new connections to the server. Accepting new connections are
1135 done in three parts to make it async. */
1137 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1139 SilcServer server = (SilcServer)context;
1140 SilcSocketConnection newsocket;
1143 SILC_LOG_DEBUG(("Accepting new connection"));
1145 server->stat.conn_attempts++;
1147 sock = silc_net_accept_connection(server->sock);
1149 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1150 server->stat.conn_failures++;
1154 /* Check max connections */
1155 if (sock > SILC_SERVER_MAX_CONNECTIONS) {
1156 SILC_LOG_ERROR(("Refusing connection, server is full"));
1157 server->stat.conn_failures++;
1161 /* Set socket options */
1162 silc_net_set_socket_nonblock(sock);
1163 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1165 /* We don't create a ID yet, since we don't know what type of connection
1166 this is yet. But, we do add the connection to the socket table. */
1167 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1168 server->sockets[sock] = newsocket;
1170 /* Perform asynchronous host lookup. This will lookup the IP and the
1171 FQDN of the remote connection. After the lookup is done the connection
1172 is accepted further. */
1173 silc_socket_host_lookup(newsocket, TRUE,
1174 silc_server_accept_new_connection_lookup, context,
1178 /* Second part of accepting new connection. Key exchange protocol has been
1179 performed and now it is time to do little connection authentication
1180 protocol to figure out whether this connection is client or server
1181 and whether it has right to access this server (especially server
1182 connections needs to be authenticated). */
1184 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1186 SilcProtocol protocol = (SilcProtocol)context;
1187 SilcServerKEInternalContext *ctx =
1188 (SilcServerKEInternalContext *)protocol->context;
1189 SilcServer server = (SilcServer)ctx->server;
1190 SilcSocketConnection sock = ctx->sock;
1191 SilcServerConnAuthInternalContext *proto_ctx;
1193 SILC_LOG_DEBUG(("Start"));
1195 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1196 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1197 /* Error occured during protocol */
1198 silc_protocol_free(protocol);
1199 sock->protocol = NULL;
1200 silc_ske_free_key_material(ctx->keymat);
1202 silc_packet_context_free(ctx->packet);
1204 silc_ske_free(ctx->ske);
1205 silc_free(ctx->dest_id);
1207 silc_schedule_task_del_by_callback(server->schedule,
1208 silc_server_failure_callback);
1209 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1210 "Key exchange failed");
1211 server->stat.auth_failures++;
1215 /* We now have the key material as the result of the key exchange
1216 protocol. Take the key material into use. Free the raw key material
1217 as soon as we've set them into use. */
1218 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1219 ctx->sock, ctx->keymat,
1220 ctx->ske->prop->cipher,
1221 ctx->ske->prop->pkcs,
1222 ctx->ske->prop->hash,
1223 ctx->ske->prop->hmac,
1224 ctx->ske->prop->group,
1226 silc_protocol_free(protocol);
1227 sock->protocol = NULL;
1228 silc_ske_free_key_material(ctx->keymat);
1230 silc_packet_context_free(ctx->packet);
1232 silc_ske_free(ctx->ske);
1233 silc_free(ctx->dest_id);
1235 silc_schedule_task_del_by_callback(server->schedule,
1236 silc_server_failure_callback);
1237 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1238 "Key exchange failed");
1239 server->stat.auth_failures++;
1242 silc_ske_free_key_material(ctx->keymat);
1244 /* Allocate internal context for the authentication protocol. This
1245 is sent as context for the protocol. */
1246 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1247 proto_ctx->server = (void *)server;
1248 proto_ctx->sock = sock;
1249 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1250 proto_ctx->responder = TRUE;
1251 proto_ctx->dest_id_type = ctx->dest_id_type;
1252 proto_ctx->dest_id = ctx->dest_id;
1253 proto_ctx->cconfig = ctx->cconfig;
1254 proto_ctx->sconfig = ctx->sconfig;
1255 proto_ctx->rconfig = ctx->rconfig;
1257 /* Free old protocol as it is finished now */
1258 silc_protocol_free(protocol);
1260 silc_packet_context_free(ctx->packet);
1262 sock->protocol = NULL;
1264 /* Allocate the authentication protocol. This is allocated here
1265 but we won't start it yet. We will be receiving party of this
1266 protocol thus we will wait that connecting party will make
1267 their first move. */
1268 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1269 &sock->protocol, proto_ctx,
1270 silc_server_accept_new_connection_final);
1272 /* Register timeout task. If the protocol is not executed inside
1273 this timelimit the connection will be terminated. Currently
1274 this is 60 seconds and is hard coded limit (XXX). */
1275 proto_ctx->timeout_task =
1276 silc_schedule_task_add(server->schedule, sock->sock,
1277 silc_server_timeout_remote,
1278 (void *)server, 60, 0,
1283 /* Final part of accepting new connection. The connection has now
1284 been authenticated and keys has been exchanged. We also know whether
1285 this is client or server connection. */
1287 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1289 SilcProtocol protocol = (SilcProtocol)context;
1290 SilcServerConnAuthInternalContext *ctx =
1291 (SilcServerConnAuthInternalContext *)protocol->context;
1292 SilcServer server = (SilcServer)ctx->server;
1293 SilcSocketConnection sock = ctx->sock;
1294 SilcServerHBContext hb_context;
1295 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1296 void *id_entry = NULL;
1298 SILC_LOG_DEBUG(("Start"));
1300 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1301 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1302 /* Error occured during protocol */
1303 silc_protocol_free(protocol);
1304 sock->protocol = NULL;
1306 silc_packet_context_free(ctx->packet);
1308 silc_ske_free(ctx->ske);
1309 silc_free(ctx->dest_id);
1311 silc_schedule_task_del_by_callback(server->schedule,
1312 silc_server_failure_callback);
1313 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1314 "Authentication failed");
1315 server->stat.auth_failures++;
1319 entry->data.last_receive = time(NULL);
1321 switch (ctx->conn_type) {
1322 case SILC_SOCKET_TYPE_CLIENT:
1324 SilcClientEntry client;
1326 SILC_LOG_DEBUG(("Remote host is client"));
1327 SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
1330 /* Add the client to the client ID cache. The nickname and Client ID
1331 and other information is created after we have received NEW_CLIENT
1332 packet from client. */
1333 client = silc_idlist_add_client(server->local_list,
1334 NULL, NULL, NULL, NULL, NULL, sock, 0);
1336 SILC_LOG_ERROR(("Could not add new client to cache"));
1337 silc_free(sock->user_data);
1338 silc_server_disconnect_remote(server, sock,
1339 "Server closed connection: "
1340 "Authentication failed");
1341 server->stat.auth_failures++;
1346 server->stat.my_clients++;
1347 server->stat.clients++;
1348 if (server->server_type == SILC_ROUTER)
1349 server->stat.cell_clients++;
1351 id_entry = (void *)client;
1354 case SILC_SOCKET_TYPE_SERVER:
1355 case SILC_SOCKET_TYPE_ROUTER:
1357 SilcServerEntry new_server;
1358 SilcServerConfigSectionServerConnection *conn =
1359 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1360 ctx->sconfig : ctx->rconfig;
1362 SILC_LOG_DEBUG(("Remote host is %s",
1363 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1364 "server" : (conn->backup_router ?
1365 "backup router" : "router")));
1366 SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
1367 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1368 "server" : (conn->backup_router ?
1369 "backup router" : "router")));
1371 /* Add the server into server cache. The server name and Server ID
1372 is updated after we have received NEW_SERVER packet from the
1373 server. We mark ourselves as router for this server if we really
1376 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1377 server->local_list : (conn->backup_router ?
1378 server->local_list :
1379 server->global_list)),
1381 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1382 SILC_SERVER : SILC_ROUTER),
1384 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1385 server->id_entry : (conn->backup_router ?
1386 server->id_entry : NULL)),
1389 SILC_LOG_ERROR(("Could not add new server to cache"));
1390 silc_free(sock->user_data);
1391 silc_server_disconnect_remote(server, sock,
1392 "Server closed connection: "
1393 "Authentication failed");
1394 server->stat.auth_failures++;
1399 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1400 server->stat.my_servers++;
1402 server->stat.my_routers++;
1403 server->stat.servers++;
1405 id_entry = (void *)new_server;
1407 /* If the incoming connection is router and marked as backup router
1408 then add it to be one of our backups */
1409 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && conn->backup_router) {
1410 silc_server_backup_add(server, new_server, conn->backup_replace_ip,
1411 conn->backup_replace_port, conn->backup_local);
1413 /* Change it back to SERVER type since that's what it really is. */
1414 if (conn->backup_local)
1415 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1417 new_server->server_type = SILC_BACKUP_ROUTER;
1420 /* Check whether this connection is to be our primary router connection
1421 if we do not already have the primary route. */
1422 if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1423 if (silc_server_config_is_primary_route(server->config) &&
1427 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1428 server->standalone = FALSE;
1429 if (!server->id_entry->router) {
1430 server->id_entry->router = id_entry;
1431 server->router = id_entry;
1441 sock->type = ctx->conn_type;
1443 /* Add the common data structure to the ID entry. */
1445 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1447 /* Add to sockets internal pointer for fast referencing */
1448 silc_free(sock->user_data);
1449 sock->user_data = id_entry;
1451 /* Connection has been fully established now. Everything is ok. */
1452 SILC_LOG_DEBUG(("New connection authenticated"));
1454 /* Perform keepalive. The `hb_context' will be freed automatically
1455 when finally calling the silc_socket_free function. XXX hardcoded
1457 hb_context = silc_calloc(1, sizeof(*hb_context));
1458 hb_context->server = server;
1459 silc_socket_set_heartbeat(sock, 600, hb_context,
1460 silc_server_perform_heartbeat,
1464 silc_schedule_task_del_by_callback(server->schedule,
1465 silc_server_failure_callback);
1466 silc_protocol_free(protocol);
1468 silc_packet_context_free(ctx->packet);
1470 silc_ske_free(ctx->ske);
1471 silc_free(ctx->dest_id);
1473 sock->protocol = NULL;
1476 /* This function is used to read packets from network and send packets to
1477 network. This is usually a generic task. */
1479 SILC_TASK_CALLBACK(silc_server_packet_process)
1481 SilcServer server = (SilcServer)context;
1482 SilcSocketConnection sock = server->sockets[fd];
1483 SilcIDListData idata;
1484 SilcCipher cipher = NULL;
1485 SilcHmac hmac = NULL;
1486 uint32 sequence = 0;
1492 SILC_LOG_DEBUG(("Processing packet"));
1494 /* Packet sending */
1496 if (type == SILC_TASK_WRITE) {
1497 /* Do not send data to disconnected connection */
1498 if (SILC_IS_DISCONNECTED(sock))
1501 server->stat.packets_sent++;
1503 if (sock->outbuf->data - sock->outbuf->head)
1504 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1506 /* Send the packet */
1507 ret = silc_packet_send(sock, TRUE);
1509 /* If returned -2 could not write to connection now, will do
1515 SILC_LOG_ERROR(("Error sending packet to connection "
1516 "%s:%d [%s]", sock->hostname, sock->port,
1517 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1518 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1519 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1524 /* The packet has been sent and now it is time to set the connection
1525 back to only for input. When there is again some outgoing data
1526 available for this connection it will be set for output as well.
1527 This call clears the output setting and sets it only for input. */
1528 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1529 SILC_UNSET_OUTBUF_PENDING(sock);
1531 silc_buffer_clear(sock->outbuf);
1535 /* Packet receiving */
1537 /* Read some data from connection */
1538 ret = silc_packet_receive(sock);
1542 SILC_LOG_ERROR(("Error receiving packet from connection "
1543 "%s:%d [%s] %s", sock->hostname, sock->port,
1544 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1545 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1546 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1547 "Router"), strerror(errno)));
1553 SILC_LOG_DEBUG(("Read EOF"));
1555 /* If connection is disconnecting already we will finally
1556 close the connection */
1557 if (SILC_IS_DISCONNECTING(sock)) {
1558 if (sock->user_data)
1559 silc_server_free_sock_user_data(server, sock, NULL);
1560 silc_server_close_connection(server, sock);
1564 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1565 SILC_SET_DISCONNECTING(sock);
1567 if (sock->user_data) {
1569 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
1570 silc_server_free_sock_user_data(server, sock, tmp);
1572 silc_server_free_sock_user_data(server, sock, NULL);
1573 } else if (server->router_conn && server->router_conn->sock == sock &&
1574 !server->router && server->standalone)
1575 silc_schedule_task_add(server->schedule, 0,
1576 silc_server_connect_to_router,
1579 SILC_TASK_PRI_NORMAL);
1581 silc_server_close_connection(server, sock);
1585 /* If connection is disconnecting or disconnected we will ignore
1587 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1588 SILC_LOG_DEBUG(("Ignoring read data from disonnected connection"));
1592 server->stat.packets_received++;
1594 /* Get keys and stuff from ID entry */
1595 idata = (SilcIDListData)sock->user_data;
1597 cipher = idata->receive_key;
1598 hmac = idata->hmac_receive;
1599 sequence = idata->psn_receive;
1602 /* Process the packet. This will call the parser that will then
1603 decrypt and parse the packet. */
1604 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1605 TRUE : FALSE, cipher, hmac, sequence,
1606 silc_server_packet_parse, server);
1608 /* If this socket connection is not authenticated yet and the packet
1609 processing failed we will drop the connection since it can be
1610 a malicious flooder. */
1611 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
1612 (!sock->protocol || sock->protocol->protocol->type ==
1613 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
1614 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
1615 SILC_SET_DISCONNECTING(sock);
1617 if (sock->user_data)
1618 silc_server_free_sock_user_data(server, sock, NULL);
1619 silc_server_close_connection(server, sock);
1623 /* Parses whole packet, received earlier. */
1625 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1627 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1628 SilcServer server = (SilcServer)parse_ctx->context;
1629 SilcSocketConnection sock = parse_ctx->sock;
1630 SilcPacketContext *packet = parse_ctx->packet;
1631 SilcIDListData idata = (SilcIDListData)sock->user_data;
1634 SILC_LOG_DEBUG(("Start"));
1636 /* Parse the packet */
1637 if (parse_ctx->normal)
1638 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
1640 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
1642 /* If entry is disabled ignore what we got. */
1643 if (ret != SILC_PACKET_RESUME_ROUTER &&
1644 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1645 SILC_LOG_DEBUG(("Connection is disabled"));
1649 if (ret == SILC_PACKET_NONE)
1652 /* Check that the the current client ID is same as in the client's packet. */
1653 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1654 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1655 if (client && client->id) {
1656 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1657 packet->src_id_type);
1658 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1666 if (server->server_type == SILC_ROUTER) {
1667 /* Route the packet if it is not destined to us. Other ID types but
1668 server are handled separately after processing them. */
1669 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1670 packet->dst_id_type == SILC_ID_SERVER &&
1671 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1672 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1674 /* Route the packet to fastest route for the destination ID */
1675 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1676 packet->dst_id_type);
1679 silc_server_packet_route(server,
1680 silc_server_route_get(server, id,
1681 packet->dst_id_type),
1688 /* Parse the incoming packet type */
1689 silc_server_packet_parse_type(server, sock, packet);
1691 if (server->server_type == SILC_ROUTER) {
1692 /* Broadcast packet if it is marked as broadcast packet and it is
1693 originated from router and we are router. */
1694 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1695 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1696 !server->standalone) {
1697 /* Broadcast to our primary route */
1698 silc_server_packet_broadcast(server, server->router->connection, packet);
1700 /* If we have backup routers then we need to feed all broadcast
1701 data to those servers. */
1702 silc_server_backup_broadcast(server, sock, packet);
1707 silc_packet_context_free(packet);
1708 silc_free(parse_ctx);
1711 /* Parser callback called by silc_packet_receive_process. This merely
1712 registers timeout that will handle the actual parsing when appropriate. */
1714 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
1717 SilcServer server = (SilcServer)context;
1718 SilcSocketConnection sock = parser_context->sock;
1719 SilcIDListData idata = (SilcIDListData)sock->user_data;
1722 idata->psn_receive = parser_context->packet->sequence + 1;
1724 /* If protocol for this connection is key exchange or rekey then we'll
1725 process all packets synchronously, since there might be packets in
1726 queue that we are not able to decrypt without first processing the
1727 packets before them. */
1728 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
1729 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
1730 (sock->protocol && sock->protocol->protocol &&
1731 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1732 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
1733 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1736 /* Reprocess data since we'll return FALSE here. This is because
1737 the idata->receive_key might have become valid in the last packet
1738 and we want to call this processor with valid cipher. */
1740 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1741 TRUE : FALSE, idata->receive_key,
1742 idata->hmac_receive, idata->psn_receive,
1743 silc_server_packet_parse, server);
1745 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1746 TRUE : FALSE, NULL, NULL, 0,
1747 silc_server_packet_parse, server);
1751 switch (sock->type) {
1752 case SILC_SOCKET_TYPE_UNKNOWN:
1753 case SILC_SOCKET_TYPE_CLIENT:
1754 /* Parse the packet with timeout */
1755 silc_schedule_task_add(server->schedule, sock->sock,
1756 silc_server_packet_parse_real,
1757 (void *)parser_context, 0, 100000,
1759 SILC_TASK_PRI_NORMAL);
1761 case SILC_SOCKET_TYPE_SERVER:
1762 case SILC_SOCKET_TYPE_ROUTER:
1763 /* Packets from servers are parsed immediately */
1764 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1774 /* Parses the packet type and calls what ever routines the packet type
1775 requires. This is done for all incoming packets. */
1777 void silc_server_packet_parse_type(SilcServer server,
1778 SilcSocketConnection sock,
1779 SilcPacketContext *packet)
1781 SilcPacketType type = packet->type;
1782 SilcIDListData idata = (SilcIDListData)sock->user_data;
1784 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1786 /* Parse the packet type */
1788 case SILC_PACKET_DISCONNECT:
1789 SILC_LOG_DEBUG(("Disconnect packet"));
1790 if (packet->flags & SILC_PACKET_FLAG_LIST)
1794 case SILC_PACKET_SUCCESS:
1796 * Success received for something. For now we can have only
1797 * one protocol for connection executing at once hence this
1798 * success message is for whatever protocol is executing currently.
1800 SILC_LOG_DEBUG(("Success packet"));
1801 if (packet->flags & SILC_PACKET_FLAG_LIST)
1804 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1807 case SILC_PACKET_FAILURE:
1809 * Failure received for something. For now we can have only
1810 * one protocol for connection executing at once hence this
1811 * failure message is for whatever protocol is executing currently.
1813 SILC_LOG_DEBUG(("Failure packet"));
1814 if (packet->flags & SILC_PACKET_FLAG_LIST)
1816 if (sock->protocol) {
1817 SilcServerFailureContext f;
1818 f = silc_calloc(1, sizeof(*f));
1822 /* We will wait 5 seconds to process this failure packet */
1823 silc_schedule_task_add(server->schedule, sock->sock,
1824 silc_server_failure_callback, (void *)f, 5, 0,
1825 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1829 case SILC_PACKET_REJECT:
1830 SILC_LOG_DEBUG(("Reject packet"));
1831 if (packet->flags & SILC_PACKET_FLAG_LIST)
1836 case SILC_PACKET_NOTIFY:
1838 * Received notify packet. Server can receive notify packets from
1839 * router. Server then relays the notify messages to clients if needed.
1841 SILC_LOG_DEBUG(("Notify packet"));
1842 if (packet->flags & SILC_PACKET_FLAG_LIST)
1843 silc_server_notify_list(server, sock, packet);
1845 silc_server_notify(server, sock, packet);
1851 case SILC_PACKET_CHANNEL_MESSAGE:
1853 * Received channel message. Channel messages are special packets
1854 * (although probably most common ones) thus they are handled
1857 SILC_LOG_DEBUG(("Channel Message packet"));
1858 if (packet->flags & SILC_PACKET_FLAG_LIST)
1860 idata->last_receive = time(NULL);
1861 silc_server_channel_message(server, sock, packet);
1864 case SILC_PACKET_CHANNEL_KEY:
1866 * Received key for channel. As channels are created by the router
1867 * the keys are as well. We will distribute the key to all of our
1868 * locally connected clients on the particular channel. Router
1869 * never receives this channel and thus is ignored.
1871 SILC_LOG_DEBUG(("Channel Key packet"));
1872 if (packet->flags & SILC_PACKET_FLAG_LIST)
1874 silc_server_channel_key(server, sock, packet);
1880 case SILC_PACKET_COMMAND:
1882 * Recived command. Processes the command request and allocates the
1883 * command context and calls the command.
1885 SILC_LOG_DEBUG(("Command packet"));
1886 if (packet->flags & SILC_PACKET_FLAG_LIST)
1888 silc_server_command_process(server, sock, packet);
1891 case SILC_PACKET_COMMAND_REPLY:
1893 * Received command reply packet. Received command reply to command. It
1894 * may be reply to command sent by us or reply to command sent by client
1895 * that we've routed further.
1897 SILC_LOG_DEBUG(("Command Reply packet"));
1898 if (packet->flags & SILC_PACKET_FLAG_LIST)
1900 silc_server_command_reply(server, sock, packet);
1904 * Private Message packets
1906 case SILC_PACKET_PRIVATE_MESSAGE:
1908 * Received private message packet. The packet is coming from either
1911 SILC_LOG_DEBUG(("Private Message packet"));
1912 if (packet->flags & SILC_PACKET_FLAG_LIST)
1914 idata->last_receive = time(NULL);
1915 silc_server_private_message(server, sock, packet);
1918 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1920 * Private message key packet.
1922 if (packet->flags & SILC_PACKET_FLAG_LIST)
1924 silc_server_private_message_key(server, sock, packet);
1928 * Key Exchange protocol packets
1930 case SILC_PACKET_KEY_EXCHANGE:
1931 SILC_LOG_DEBUG(("KE packet"));
1932 if (packet->flags & SILC_PACKET_FLAG_LIST)
1935 if (sock->protocol && sock->protocol->protocol &&
1936 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1938 SilcServerKEInternalContext *proto_ctx =
1939 (SilcServerKEInternalContext *)sock->protocol->context;
1941 proto_ctx->packet = silc_packet_context_dup(packet);
1943 /* Let the protocol handle the packet */
1944 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
1946 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1947 "protocol active, packet dropped."));
1951 case SILC_PACKET_KEY_EXCHANGE_1:
1952 SILC_LOG_DEBUG(("KE 1 packet"));
1953 if (packet->flags & SILC_PACKET_FLAG_LIST)
1956 if (sock->protocol && sock->protocol->protocol &&
1957 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1958 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
1960 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
1961 SilcServerRekeyInternalContext *proto_ctx =
1962 (SilcServerRekeyInternalContext *)sock->protocol->context;
1964 if (proto_ctx->packet)
1965 silc_packet_context_free(proto_ctx->packet);
1967 proto_ctx->packet = silc_packet_context_dup(packet);
1969 /* Let the protocol handle the packet */
1970 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1972 SilcServerKEInternalContext *proto_ctx =
1973 (SilcServerKEInternalContext *)sock->protocol->context;
1975 if (proto_ctx->packet)
1976 silc_packet_context_free(proto_ctx->packet);
1978 proto_ctx->packet = silc_packet_context_dup(packet);
1979 proto_ctx->dest_id_type = packet->src_id_type;
1980 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1981 packet->src_id_type);
1982 if (!proto_ctx->dest_id)
1985 /* Let the protocol handle the packet */
1986 silc_protocol_execute(sock->protocol, server->schedule,
1990 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1991 "protocol active, packet dropped."));
1995 case SILC_PACKET_KEY_EXCHANGE_2:
1996 SILC_LOG_DEBUG(("KE 2 packet"));
1997 if (packet->flags & SILC_PACKET_FLAG_LIST)
2000 if (sock->protocol && sock->protocol->protocol &&
2001 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2002 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2004 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2005 SilcServerRekeyInternalContext *proto_ctx =
2006 (SilcServerRekeyInternalContext *)sock->protocol->context;
2008 if (proto_ctx->packet)
2009 silc_packet_context_free(proto_ctx->packet);
2011 proto_ctx->packet = silc_packet_context_dup(packet);
2013 /* Let the protocol handle the packet */
2014 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2016 SilcServerKEInternalContext *proto_ctx =
2017 (SilcServerKEInternalContext *)sock->protocol->context;
2019 if (proto_ctx->packet)
2020 silc_packet_context_free(proto_ctx->packet);
2022 proto_ctx->packet = silc_packet_context_dup(packet);
2023 proto_ctx->dest_id_type = packet->src_id_type;
2024 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2025 packet->src_id_type);
2026 if (!proto_ctx->dest_id)
2029 /* Let the protocol handle the packet */
2030 silc_protocol_execute(sock->protocol, server->schedule,
2034 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2035 "protocol active, packet dropped."));
2039 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2041 * Connection authentication request packet. When we receive this packet
2042 * we will send to the other end information about our mandatory
2043 * authentication method for the connection. This packet maybe received
2046 SILC_LOG_DEBUG(("Connection authentication request packet"));
2047 if (packet->flags & SILC_PACKET_FLAG_LIST)
2049 silc_server_connection_auth_request(server, sock, packet);
2053 * Connection Authentication protocol packets
2055 case SILC_PACKET_CONNECTION_AUTH:
2056 /* Start of the authentication protocol. We receive here the
2057 authentication data and will verify it. */
2058 SILC_LOG_DEBUG(("Connection auth packet"));
2059 if (packet->flags & SILC_PACKET_FLAG_LIST)
2062 if (sock->protocol && sock->protocol->protocol->type
2063 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2065 SilcServerConnAuthInternalContext *proto_ctx =
2066 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2068 proto_ctx->packet = silc_packet_context_dup(packet);
2070 /* Let the protocol handle the packet */
2071 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2073 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2074 "protocol active, packet dropped."));
2078 case SILC_PACKET_NEW_ID:
2080 * Received New ID packet. This includes some new ID that has been
2081 * created. It may be for client, server or channel. This is the way
2082 * to distribute information about new registered entities in the
2085 SILC_LOG_DEBUG(("New ID packet"));
2086 if (packet->flags & SILC_PACKET_FLAG_LIST)
2087 silc_server_new_id_list(server, sock, packet);
2089 silc_server_new_id(server, sock, packet);
2092 case SILC_PACKET_NEW_CLIENT:
2094 * Received new client packet. This includes client information that
2095 * we will use to create initial client ID. After creating new
2096 * ID we will send it to the client.
2098 SILC_LOG_DEBUG(("New Client packet"));
2099 if (packet->flags & SILC_PACKET_FLAG_LIST)
2101 silc_server_new_client(server, sock, packet);
2104 case SILC_PACKET_NEW_SERVER:
2106 * Received new server packet. This includes Server ID and some other
2107 * information that we may save. This is received after server has
2110 SILC_LOG_DEBUG(("New Server packet"));
2111 if (packet->flags & SILC_PACKET_FLAG_LIST)
2113 silc_server_new_server(server, sock, packet);
2116 case SILC_PACKET_NEW_CHANNEL:
2118 * Received new channel packet. Information about new channel in the
2119 * network are distributed using this packet.
2121 SILC_LOG_DEBUG(("New Channel packet"));
2122 if (packet->flags & SILC_PACKET_FLAG_LIST)
2123 silc_server_new_channel_list(server, sock, packet);
2125 silc_server_new_channel(server, sock, packet);
2128 case SILC_PACKET_HEARTBEAT:
2130 * Received heartbeat.
2132 SILC_LOG_DEBUG(("Heartbeat packet"));
2133 if (packet->flags & SILC_PACKET_FLAG_LIST)
2137 case SILC_PACKET_KEY_AGREEMENT:
2139 * Received heartbeat.
2141 SILC_LOG_DEBUG(("Key agreement packet"));
2142 if (packet->flags & SILC_PACKET_FLAG_LIST)
2144 silc_server_key_agreement(server, sock, packet);
2147 case SILC_PACKET_REKEY:
2149 * Received re-key packet. The sender wants to regenerate the session
2152 SILC_LOG_DEBUG(("Re-key packet"));
2153 if (packet->flags & SILC_PACKET_FLAG_LIST)
2155 silc_server_rekey(server, sock, packet);
2158 case SILC_PACKET_REKEY_DONE:
2160 * The re-key is done.
2162 SILC_LOG_DEBUG(("Re-key done packet"));
2163 if (packet->flags & SILC_PACKET_FLAG_LIST)
2166 if (sock->protocol && sock->protocol->protocol &&
2167 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2169 SilcServerRekeyInternalContext *proto_ctx =
2170 (SilcServerRekeyInternalContext *)sock->protocol->context;
2172 if (proto_ctx->packet)
2173 silc_packet_context_free(proto_ctx->packet);
2175 proto_ctx->packet = silc_packet_context_dup(packet);
2177 /* Let the protocol handle the packet */
2178 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2180 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2181 "protocol active, packet dropped."));
2185 case SILC_PACKET_FTP:
2187 SILC_LOG_DEBUG(("FTP packet"));
2188 if (packet->flags & SILC_PACKET_FLAG_LIST)
2190 silc_server_ftp(server, sock, packet);
2193 case SILC_PACKET_RESUME_ROUTER:
2194 /* Resume router packet received. This packet is received for backup
2195 router resuming protocol. */
2196 SILC_LOG_DEBUG(("Resume router packet"));
2197 if (packet->flags & SILC_PACKET_FLAG_LIST)
2199 silc_server_backup_resume_router(server, sock, packet);
2203 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2209 /* Creates connection to a remote router. */
2211 void silc_server_create_connection(SilcServer server,
2212 char *remote_host, uint32 port)
2214 SilcServerConnection sconn;
2216 /* Allocate connection object for hold connection specific stuff. */
2217 sconn = silc_calloc(1, sizeof(*sconn));
2218 sconn->server = server;
2219 sconn->remote_host = strdup(remote_host);
2220 sconn->remote_port = port;
2222 silc_schedule_task_add(server->schedule, 0,
2223 silc_server_connect_router,
2224 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2225 SILC_TASK_PRI_NORMAL);
2228 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2230 silc_socket_free((SilcSocketConnection)context);
2233 /* Closes connection to socket connection */
2235 void silc_server_close_connection(SilcServer server,
2236 SilcSocketConnection sock)
2238 if (!server->sockets[sock->sock])
2241 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2243 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2244 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2245 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2248 /* We won't listen for this connection anymore */
2249 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2251 /* Unregister all tasks */
2252 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2254 /* Close the actual connection */
2255 silc_net_close_connection(sock->sock);
2256 server->sockets[sock->sock] = NULL;
2258 /* If sock->user_data is NULL then we'll check for active protocols
2259 here since the silc_server_free_sock_user_data has not been called
2260 for this connection. */
2261 if (!sock->user_data) {
2262 /* If any protocol is active cancel its execution. It will call
2263 the final callback which will finalize the disconnection. */
2264 if (sock->protocol) {
2265 silc_protocol_cancel(sock->protocol, server->schedule);
2266 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2267 silc_protocol_execute_final(sock->protocol, server->schedule);
2268 sock->protocol = NULL;
2273 silc_schedule_task_add(server->schedule, 0,
2274 silc_server_close_connection_final,
2275 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2276 SILC_TASK_PRI_NORMAL);
2279 /* Sends disconnect message to remote connection and disconnects the
2282 void silc_server_disconnect_remote(SilcServer server,
2283 SilcSocketConnection sock,
2284 const char *fmt, ...)
2287 unsigned char buf[4096];
2292 memset(buf, 0, sizeof(buf));
2294 vsprintf(buf, fmt, ap);
2297 SILC_LOG_DEBUG(("Disconnecting remote host"));
2299 /* Notify remote end that the conversation is over. The notify message
2300 is tried to be sent immediately. */
2301 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2302 buf, strlen(buf), TRUE);
2304 /* Mark the connection to be disconnected */
2305 SILC_SET_DISCONNECTED(sock);
2306 silc_server_close_connection(server, sock);
2311 SilcClientEntry client;
2312 } *FreeClientInternal;
2314 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2316 FreeClientInternal i = (FreeClientInternal)context;
2318 silc_idlist_del_data(i->client);
2319 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2323 /* Frees client data and notifies about client's signoff. */
2325 void silc_server_free_client_data(SilcServer server,
2326 SilcSocketConnection sock,
2327 SilcClientEntry client,
2329 const char *signoff)
2331 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2333 /* If there is pending outgoing data for the client then purge it
2334 to the network before removing the client entry. */
2335 silc_server_packet_queue_purge(server, sock);
2340 /* Send SIGNOFF notify to routers. */
2341 if (notify && !server->standalone && server->router)
2342 silc_server_send_notify_signoff(server, server->router->connection,
2343 server->server_type == SILC_SERVER ?
2344 FALSE : TRUE, client->id, signoff);
2346 /* Remove client from all channels */
2348 silc_server_remove_from_channels(server, NULL, client,
2349 TRUE, (char *)signoff, TRUE);
2351 silc_server_remove_from_channels(server, NULL, client,
2352 FALSE, NULL, FALSE);
2354 /* Update statistics */
2355 server->stat.my_clients--;
2356 server->stat.clients--;
2357 if (server->server_type == SILC_ROUTER)
2358 server->stat.cell_clients--;
2359 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2360 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2362 /* We will not delete the client entry right away. We will take it
2363 into history (for WHOWAS command) for 5 minutes */
2366 silc_schedule_task_add(server->schedule, 0,
2367 silc_server_free_client_data_timeout,
2369 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2370 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2371 client->router = NULL;
2372 client->connection = NULL;
2376 /* Frees user_data pointer from socket connection object. This also sends
2377 appropriate notify packets to the network to inform about leaving
2380 void silc_server_free_sock_user_data(SilcServer server,
2381 SilcSocketConnection sock,
2382 const char *signoff_message)
2384 SILC_LOG_DEBUG(("Start"));
2386 switch (sock->type) {
2387 case SILC_SOCKET_TYPE_CLIENT:
2389 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2390 silc_server_free_client_data(server, sock, user_data, TRUE,
2394 case SILC_SOCKET_TYPE_SERVER:
2395 case SILC_SOCKET_TYPE_ROUTER:
2397 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2398 SilcServerEntry backup_router = NULL;
2401 backup_router = silc_server_backup_get(server, user_data->id);
2403 /* If this was our primary router connection then we're lost to
2404 the outside world. */
2405 if (server->router == user_data) {
2406 /* Check whether we have a backup router connection */
2407 if (!backup_router || backup_router == user_data) {
2408 silc_schedule_task_add(server->schedule, 0,
2409 silc_server_connect_to_router,
2412 SILC_TASK_PRI_NORMAL);
2414 server->id_entry->router = NULL;
2415 server->router = NULL;
2416 server->standalone = TRUE;
2417 backup_router = NULL;
2419 SILC_LOG_INFO(("New primary router is backup router %s",
2420 backup_router->server_name));
2421 SILC_LOG_DEBUG(("New primary router is backup router %s",
2422 backup_router->server_name));
2423 server->id_entry->router = backup_router;
2424 server->router = backup_router;
2425 server->router_connect = time(0);
2426 server->backup_primary = TRUE;
2427 if (server->server_type == SILC_BACKUP_ROUTER) {
2428 server->server_type = SILC_ROUTER;
2430 /* We'll need to constantly try to reconnect to the primary
2431 router so that we'll see when it comes back online. */
2432 silc_server_backup_reconnect(server, sock->ip, sock->port,
2433 silc_server_backup_connected,
2437 /* Mark this connection as replaced */
2438 silc_server_backup_replaced_add(server, user_data->id,
2441 } else if (backup_router) {
2442 SILC_LOG_INFO(("Enabling the use of backup router %s",
2443 backup_router->server_name));
2444 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2445 backup_router->server_name));
2447 /* Mark this connection as replaced */
2448 silc_server_backup_replaced_add(server, user_data->id,
2452 if (!backup_router) {
2453 /* Free all client entries that this server owns as they will
2454 become invalid now as well. */
2456 silc_server_remove_clients_by_server(server, user_data, TRUE);
2457 if (server->server_type == SILC_SERVER)
2458 silc_server_remove_channels_by_server(server, user_data);
2460 /* Update the client entries of this server to the new backup
2461 router. This also removes the clients that *really* was owned
2462 by the primary router and went down with the router. */
2463 silc_server_update_clients_by_server(server, user_data, backup_router,
2465 silc_server_update_servers_by_server(server, user_data, backup_router);
2466 if (server->server_type == SILC_SERVER)
2467 silc_server_update_channels_by_server(server, user_data,
2471 /* Free the server entry */
2472 silc_server_backup_del(server, user_data);
2473 silc_server_backup_replaced_del(server, user_data);
2474 silc_idlist_del_data(user_data);
2475 if (!silc_idlist_del_server(server->local_list, user_data))
2476 silc_idlist_del_server(server->global_list, user_data);
2477 server->stat.my_servers--;
2478 server->stat.servers--;
2479 if (server->server_type == SILC_ROUTER)
2480 server->stat.cell_servers--;
2482 if (backup_router) {
2483 /* Announce all of our stuff that was created about 5 minutes ago.
2484 The backup router knows all the other stuff already. */
2485 if (server->server_type == SILC_ROUTER)
2486 silc_server_announce_servers(server, FALSE, time(0) - 300,
2487 backup_router->connection);
2489 /* Announce our clients and channels to the router */
2490 silc_server_announce_clients(server, time(0) - 300,
2491 backup_router->connection);
2492 silc_server_announce_channels(server, time(0) - 300,
2493 backup_router->connection);
2499 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2501 silc_idlist_del_data(user_data);
2502 silc_free(user_data);
2507 /* If any protocol is active cancel its execution */
2508 if (sock->protocol) {
2509 silc_protocol_cancel(sock->protocol, server->schedule);
2510 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2511 silc_protocol_execute_final(sock->protocol, server->schedule);
2512 sock->protocol = NULL;
2515 sock->user_data = NULL;
2518 /* Removes client from all channels it has joined. This is used when client
2519 connection is disconnected. If the client on a channel is last, the
2520 channel is removed as well. This sends the SIGNOFF notify types. */
2522 void silc_server_remove_from_channels(SilcServer server,
2523 SilcSocketConnection sock,
2524 SilcClientEntry client,
2526 char *signoff_message,
2529 SilcChannelEntry channel;
2530 SilcChannelClientEntry chl;
2531 SilcHashTableList htl;
2534 SILC_LOG_DEBUG(("Start"));
2536 if (!client || !client->id)
2539 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2541 /* Remove the client from all channels. The client is removed from
2542 the channels' user list. */
2543 silc_hash_table_list(client->channels, &htl);
2544 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2545 channel = chl->channel;
2547 /* Remove channel from client's channel list */
2548 silc_hash_table_del(client->channels, channel);
2550 /* Remove channel if there is no users anymore */
2551 if (server->server_type == SILC_ROUTER &&
2552 silc_hash_table_count(channel->user_list) < 2) {
2554 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2555 if (silc_idlist_del_channel(server->local_list, channel))
2556 server->stat.my_channels--;
2558 silc_idlist_del_channel(server->global_list, channel);
2562 /* Remove client from channel's client list */
2563 silc_hash_table_del(channel->user_list, chl->client);
2565 /* If there is no global users on the channel anymore mark the channel
2566 as local channel. Do not check if the removed client is local client. */
2567 if (server->server_type != SILC_ROUTER && channel->global_users &&
2568 chl->client->router && !silc_server_channel_has_global(channel))
2569 channel->global_users = FALSE;
2572 server->stat.my_chanclients--;
2574 /* If there is not at least one local user on the channel then we don't
2575 need the channel entry anymore, we can remove it safely. */
2576 if (server->server_type != SILC_ROUTER &&
2577 !silc_server_channel_has_local(channel)) {
2578 /* Notify about leaving client if this channel has global users. */
2579 if (notify && channel->global_users)
2580 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2581 SILC_NOTIFY_TYPE_SIGNOFF,
2582 signoff_message ? 2 : 1,
2583 clidp->data, clidp->len,
2584 signoff_message, signoff_message ?
2585 strlen(signoff_message) : 0);
2588 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2590 if (channel->founder_key) {
2591 /* The founder auth data exists, do not remove the channel entry */
2592 SilcChannelClientEntry chl2;
2593 SilcHashTableList htl2;
2595 channel->disabled = TRUE;
2597 silc_hash_table_list(channel->user_list, &htl2);
2598 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2599 silc_hash_table_del(chl2->client->channels, channel);
2600 silc_hash_table_del(channel->user_list, chl2->client);
2606 /* Remove the channel entry */
2607 if (silc_idlist_del_channel(server->local_list, channel))
2608 server->stat.my_channels--;
2610 silc_idlist_del_channel(server->global_list, channel);
2614 /* Send notify to channel about client leaving SILC and thus
2615 the entire channel. */
2617 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2618 SILC_NOTIFY_TYPE_SIGNOFF,
2619 signoff_message ? 2 : 1,
2620 clidp->data, clidp->len,
2621 signoff_message, signoff_message ?
2622 strlen(signoff_message) : 0);
2624 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2625 /* Re-generate channel key */
2626 if (!silc_server_create_channel_key(server, channel, 0))
2629 /* Send the channel key to the channel. The key of course is not sent
2630 to the client who was removed from the channel. */
2631 silc_server_send_channel_key(server, client->connection, channel,
2632 server->server_type == SILC_ROUTER ?
2633 FALSE : !server->standalone);
2637 silc_buffer_free(clidp);
2640 /* Removes client from one channel. This is used for example when client
2641 calls LEAVE command to remove itself from the channel. Returns TRUE
2642 if channel still exists and FALSE if the channel is removed when
2643 last client leaves the channel. If `notify' is FALSE notify messages
2646 int silc_server_remove_from_one_channel(SilcServer server,
2647 SilcSocketConnection sock,
2648 SilcChannelEntry channel,
2649 SilcClientEntry client,
2652 SilcChannelClientEntry chl;
2655 SILC_LOG_DEBUG(("Start"));
2657 /* Get the entry to the channel, if this client is not on the channel
2659 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2662 /* Remove the client from the channel. The client is removed from
2663 the channel's user list. */
2665 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2667 /* Remove channel from client's channel list */
2668 silc_hash_table_del(client->channels, chl->channel);
2670 /* Remove channel if there is no users anymore */
2671 if (server->server_type == SILC_ROUTER &&
2672 silc_hash_table_count(channel->user_list) < 2) {
2674 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2675 if (silc_idlist_del_channel(server->local_list, channel))
2676 server->stat.my_channels--;
2678 silc_idlist_del_channel(server->global_list, channel);
2679 silc_buffer_free(clidp);
2683 /* Remove client from channel's client list */
2684 silc_hash_table_del(channel->user_list, chl->client);
2686 /* If there is no global users on the channel anymore mark the channel
2687 as local channel. Do not check if the client is local client. */
2688 if (server->server_type != SILC_ROUTER && channel->global_users &&
2689 chl->client->router && !silc_server_channel_has_global(channel))
2690 channel->global_users = FALSE;
2693 server->stat.my_chanclients--;
2695 /* If there is not at least one local user on the channel then we don't
2696 need the channel entry anymore, we can remove it safely. */
2697 if (server->server_type != SILC_ROUTER &&
2698 !silc_server_channel_has_local(channel)) {
2699 /* Notify about leaving client if this channel has global users. */
2700 if (notify && channel->global_users)
2701 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2702 SILC_NOTIFY_TYPE_LEAVE, 1,
2703 clidp->data, clidp->len);
2705 silc_buffer_free(clidp);
2708 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2710 if (channel->founder_key) {
2711 /* The founder auth data exists, do not remove the channel entry */
2712 SilcChannelClientEntry chl2;
2713 SilcHashTableList htl2;
2715 channel->disabled = TRUE;
2717 silc_hash_table_list(channel->user_list, &htl2);
2718 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2719 silc_hash_table_del(chl2->client->channels, channel);
2720 silc_hash_table_del(channel->user_list, chl2->client);
2726 /* Remove the channel entry */
2727 if (silc_idlist_del_channel(server->local_list, channel))
2728 server->stat.my_channels--;
2730 silc_idlist_del_channel(server->global_list, channel);
2734 /* Send notify to channel about client leaving the channel */
2736 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2737 SILC_NOTIFY_TYPE_LEAVE, 1,
2738 clidp->data, clidp->len);
2740 silc_buffer_free(clidp);
2744 /* Timeout callback. This is called if connection is idle or for some
2745 other reason is not responding within some period of time. This
2746 disconnects the remote end. */
2748 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2750 SilcServer server = (SilcServer)context;
2751 SilcSocketConnection sock = server->sockets[fd];
2753 SILC_LOG_DEBUG(("Start"));
2758 /* If we have protocol active we must assure that we call the protocol's
2759 final callback so that all the memory is freed. */
2760 if (sock->protocol) {
2761 silc_protocol_cancel(sock->protocol, server->schedule);
2762 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2763 silc_protocol_execute_final(sock->protocol, server->schedule);
2764 sock->protocol = NULL;
2768 if (sock->user_data)
2769 silc_server_free_sock_user_data(server, sock, NULL);
2771 silc_server_disconnect_remote(server, sock, "Server closed connection: "
2772 "Connection timeout");
2775 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2776 function may be used only by router. In real SILC network all channels
2777 are created by routers thus this function is never used by normal
2780 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2781 SilcServerID *router_id,
2787 SilcChannelID *channel_id;
2788 SilcChannelEntry entry;
2792 SILC_LOG_DEBUG(("Creating new channel"));
2795 cipher = SILC_DEFAULT_CIPHER;
2797 hmac = SILC_DEFAULT_HMAC;
2799 /* Allocate cipher */
2800 if (!silc_cipher_alloc(cipher, &key))
2804 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2805 silc_cipher_free(key);
2809 channel_name = strdup(channel_name);
2811 /* Create the channel */
2812 if (!silc_id_create_channel_id(server, router_id, server->rng,
2814 silc_free(channel_name);
2815 silc_cipher_free(key);
2816 silc_hmac_free(newhmac);
2819 entry = silc_idlist_add_channel(server->local_list, channel_name,
2820 SILC_CHANNEL_MODE_NONE, channel_id,
2821 NULL, key, newhmac, 0);
2823 silc_free(channel_name);
2824 silc_cipher_free(key);
2825 silc_hmac_free(newhmac);
2829 entry->cipher = strdup(cipher);
2830 entry->hmac_name = strdup(hmac);
2832 /* Now create the actual key material */
2833 if (!silc_server_create_channel_key(server, entry,
2834 silc_cipher_get_key_len(key) / 8)) {
2835 silc_free(channel_name);
2836 silc_cipher_free(key);
2837 silc_hmac_free(newhmac);
2838 silc_free(entry->cipher);
2839 silc_free(entry->hmac_name);
2843 /* Notify other routers about the new channel. We send the packet
2844 to our primary route. */
2845 if (broadcast && server->standalone == FALSE)
2846 silc_server_send_new_channel(server, server->router->connection, TRUE,
2847 channel_name, entry->id,
2848 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2851 server->stat.my_channels++;
2856 /* Same as above but creates the channel with Channel ID `channel_id. */
2859 silc_server_create_new_channel_with_id(SilcServer server,
2863 SilcChannelID *channel_id,
2866 SilcChannelEntry entry;
2870 SILC_LOG_DEBUG(("Creating new channel"));
2873 cipher = SILC_DEFAULT_CIPHER;
2875 hmac = SILC_DEFAULT_HMAC;
2877 /* Allocate cipher */
2878 if (!silc_cipher_alloc(cipher, &key))
2882 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2883 silc_cipher_free(key);
2887 channel_name = strdup(channel_name);
2889 /* Create the channel */
2890 entry = silc_idlist_add_channel(server->local_list, channel_name,
2891 SILC_CHANNEL_MODE_NONE, channel_id,
2892 NULL, key, newhmac, 0);
2894 silc_free(channel_name);
2898 /* Now create the actual key material */
2899 if (!silc_server_create_channel_key(server, entry,
2900 silc_cipher_get_key_len(key) / 8)) {
2901 silc_free(channel_name);
2905 /* Notify other routers about the new channel. We send the packet
2906 to our primary route. */
2907 if (broadcast && server->standalone == FALSE)
2908 silc_server_send_new_channel(server, server->router->connection, TRUE,
2909 channel_name, entry->id,
2910 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2913 server->stat.my_channels++;
2918 /* Channel's key re-key timeout callback. */
2920 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
2922 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
2923 SilcServer server = (SilcServer)rekey->context;
2927 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
2930 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
2933 /* Generates new channel key. This is used to create the initial channel key
2934 but also to re-generate new key for channel. If `key_len' is provided
2935 it is the bytes of the key length. */
2937 bool silc_server_create_channel_key(SilcServer server,
2938 SilcChannelEntry channel,
2942 unsigned char channel_key[32], hash[32];
2945 SILC_LOG_DEBUG(("Generating channel key"));
2947 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
2948 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
2952 if (!channel->channel_key)
2953 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
2954 channel->channel_key = NULL;
2960 else if (channel->key_len)
2961 len = channel->key_len / 8;
2963 len = silc_cipher_get_key_len(channel->channel_key) / 8;
2965 /* Create channel key */
2966 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
2969 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
2971 /* Remove old key if exists */
2973 memset(channel->key, 0, channel->key_len / 8);
2974 silc_free(channel->key);
2978 channel->key_len = len * 8;
2979 channel->key = silc_calloc(len, sizeof(*channel->key));
2980 memcpy(channel->key, channel_key, len);
2981 memset(channel_key, 0, sizeof(channel_key));
2983 /* Generate HMAC key from the channel key data and set it */
2985 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
2986 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
2987 silc_hmac_set_key(channel->hmac, hash,
2988 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
2989 memset(hash, 0, sizeof(hash));
2991 if (server->server_type == SILC_ROUTER) {
2992 if (!channel->rekey)
2993 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
2994 channel->rekey->context = (void *)server;
2995 channel->rekey->channel = channel;
2996 channel->rekey->key_len = key_len;
2997 if (channel->rekey->task)
2998 silc_schedule_task_del(server->schedule, channel->rekey->task);
3000 channel->rekey->task =
3001 silc_schedule_task_add(server->schedule, 0,
3002 silc_server_channel_key_rekey,
3003 (void *)channel->rekey, 3600, 0,
3005 SILC_TASK_PRI_NORMAL);
3011 /* Saves the channel key found in the encoded `key_payload' buffer. This
3012 function is used when we receive Channel Key Payload and also when we're
3013 processing JOIN command reply. Returns entry to the channel. */
3015 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3016 SilcBuffer key_payload,
3017 SilcChannelEntry channel)
3019 SilcChannelKeyPayload payload = NULL;
3020 SilcChannelID *id = NULL;
3021 unsigned char *tmp, hash[32];
3025 SILC_LOG_DEBUG(("Start"));
3027 /* Decode channel key payload */
3028 payload = silc_channel_key_payload_parse(key_payload->data,
3031 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3036 /* Get the channel entry */
3039 /* Get channel ID */
3040 tmp = silc_channel_key_get_id(payload, &tmp_len);
3041 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3047 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3049 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3051 SILC_LOG_ERROR(("Received key for non-existent channel"));
3057 tmp = silc_channel_key_get_key(payload, &tmp_len);
3063 cipher = silc_channel_key_get_cipher(payload, NULL);
3069 /* Remove old key if exists */
3071 memset(channel->key, 0, channel->key_len / 8);
3072 silc_free(channel->key);
3073 silc_cipher_free(channel->channel_key);
3076 /* Create new cipher */
3077 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3078 channel->channel_key = NULL;
3083 if (channel->cipher)
3084 silc_free(channel->cipher);
3085 channel->cipher = strdup(cipher);
3088 channel->key_len = tmp_len * 8;
3089 channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
3090 memcpy(channel->key, tmp, tmp_len);
3091 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3093 /* Generate HMAC key from the channel key data and set it */
3095 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3096 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3097 silc_hmac_set_key(channel->hmac, hash,
3098 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3100 memset(hash, 0, sizeof(hash));
3101 memset(tmp, 0, tmp_len);
3103 if (server->server_type == SILC_ROUTER) {
3104 if (!channel->rekey)
3105 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3106 channel->rekey->context = (void *)server;
3107 channel->rekey->channel = channel;
3108 if (channel->rekey->task)
3109 silc_schedule_task_del(server->schedule, channel->rekey->task);
3111 channel->rekey->task =
3112 silc_schedule_task_add(server->schedule, 0,
3113 silc_server_channel_key_rekey,
3114 (void *)channel->rekey, 3600, 0,
3116 SILC_TASK_PRI_NORMAL);
3122 silc_channel_key_payload_free(payload);
3127 /* Heartbeat callback. This function is set as argument for the
3128 silc_socket_set_heartbeat function. The library will call this function
3129 at the set time interval. */
3131 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3134 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3136 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname,
3139 /* Send the heartbeat */
3140 silc_server_send_heartbeat(hb->server, sock);
3143 /* Returns assembled of all servers in the given ID list. The packet's
3144 form is dictated by the New ID payload. */
3146 static void silc_server_announce_get_servers(SilcServer server,
3147 SilcServerEntry remote,
3149 SilcBuffer *servers,
3150 unsigned long creation_time)
3152 SilcIDCacheList list;
3153 SilcIDCacheEntry id_cache;
3154 SilcServerEntry entry;
3157 /* Go through all clients in the list */
3158 if (silc_idcache_get_all(id_list->servers, &list)) {
3159 if (silc_idcache_list_first(list, &id_cache)) {
3161 entry = (SilcServerEntry)id_cache->context;
3163 /* Do not announce the one we've sending our announcements and
3164 do not announce ourself. Also check the creation time if it's
3166 if ((entry == remote) || (entry == server->id_entry) ||
3167 (creation_time && entry->data.created < creation_time)) {
3168 if (!silc_idcache_list_next(list, &id_cache))
3173 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3175 *servers = silc_buffer_realloc(*servers,
3177 (*servers)->truelen + idp->len :
3179 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3180 silc_buffer_put(*servers, idp->data, idp->len);
3181 silc_buffer_pull(*servers, idp->len);
3182 silc_buffer_free(idp);
3184 if (!silc_idcache_list_next(list, &id_cache))
3189 silc_idcache_list_free(list);
3194 silc_server_announce_encode_notify(SilcNotifyType notify, uint32 argc, ...)
3200 p = silc_notify_payload_encode(notify, argc, ap);
3206 /* This function is used by router to announce existing servers to our
3207 primary router when we've connected to it. If `creation_time' is non-zero
3208 then only the servers that has been created after the `creation_time'
3209 will be announced. */
3211 void silc_server_announce_servers(SilcServer server, bool global,
3212 unsigned long creation_time,
3213 SilcSocketConnection remote)
3215 SilcBuffer servers = NULL;
3217 SILC_LOG_DEBUG(("Announcing servers"));
3219 /* Get servers in local list */
3220 silc_server_announce_get_servers(server, remote->user_data,
3221 server->local_list, &servers,
3225 /* Get servers in global list */
3226 silc_server_announce_get_servers(server, remote->user_data,
3227 server->global_list, &servers,
3231 silc_buffer_push(servers, servers->data - servers->head);
3232 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3234 /* Send the packet */
3235 silc_server_packet_send(server, remote,
3236 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3237 servers->data, servers->len, TRUE);
3239 silc_buffer_free(servers);
3243 /* Returns assembled packet of all clients in the given ID list. The
3244 packet's form is dictated by the New ID Payload. */
3246 static void silc_server_announce_get_clients(SilcServer server,
3248 SilcBuffer *clients,
3250 unsigned long creation_time)
3252 SilcIDCacheList list;
3253 SilcIDCacheEntry id_cache;
3254 SilcClientEntry client;
3257 unsigned char mode[4];
3259 /* Go through all clients in the list */
3260 if (silc_idcache_get_all(id_list->clients, &list)) {
3261 if (silc_idcache_list_first(list, &id_cache)) {
3263 client = (SilcClientEntry)id_cache->context;
3265 if (creation_time && client->data.created < creation_time) {
3266 if (!silc_idcache_list_next(list, &id_cache))
3271 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3273 *clients = silc_buffer_realloc(*clients,
3275 (*clients)->truelen + idp->len :
3277 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3278 silc_buffer_put(*clients, idp->data, idp->len);
3279 silc_buffer_pull(*clients, idp->len);
3281 SILC_PUT32_MSB(client->mode, mode);
3282 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3283 2, idp->data, idp->len,
3285 *umodes = silc_buffer_realloc(*umodes,
3287 (*umodes)->truelen + tmp->len :
3289 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3290 silc_buffer_put(*umodes, tmp->data, tmp->len);
3291 silc_buffer_pull(*umodes, tmp->len);
3292 silc_buffer_free(tmp);
3294 silc_buffer_free(idp);
3296 if (!silc_idcache_list_next(list, &id_cache))
3301 silc_idcache_list_free(list);
3305 /* This function is used to announce our existing clients to our router
3306 when we've connected to it. If `creation_time' is non-zero then only
3307 the clients that has been created after the `creation_time' will be
3310 void silc_server_announce_clients(SilcServer server,
3311 unsigned long creation_time,
3312 SilcSocketConnection remote)
3314 SilcBuffer clients = NULL;
3315 SilcBuffer umodes = NULL;
3317 SILC_LOG_DEBUG(("Announcing clients"));
3319 /* Get clients in local list */
3320 silc_server_announce_get_clients(server, server->local_list,
3321 &clients, &umodes, creation_time);
3323 /* As router we announce our global list as well */
3324 if (server->server_type == SILC_ROUTER)
3325 silc_server_announce_get_clients(server, server->global_list,
3326 &clients, &umodes, creation_time);
3329 silc_buffer_push(clients, clients->data - clients->head);
3330 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3332 /* Send the packet */
3333 silc_server_packet_send(server, remote,
3334 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3335 clients->data, clients->len, TRUE);
3337 silc_buffer_free(clients);
3341 silc_buffer_push(umodes, umodes->data - umodes->head);
3342 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3344 /* Send the packet */
3345 silc_server_packet_send(server, remote,
3346 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3347 umodes->data, umodes->len, TRUE);
3349 silc_buffer_free(umodes);
3353 /* Returns channel's topic for announcing it */
3355 void silc_server_announce_get_channel_topic(SilcServer server,
3356 SilcChannelEntry channel,
3361 if (channel->topic) {
3362 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3363 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3364 chidp->data, chidp->len,
3366 strlen(channel->topic));
3367 silc_buffer_free(chidp);
3371 /* Returns assembled packets for channel users of the `channel'. */
3373 void silc_server_announce_get_channel_users(SilcServer server,
3374 SilcChannelEntry channel,
3375 SilcBuffer *channel_users,
3376 SilcBuffer *channel_users_modes)
3378 SilcChannelClientEntry chl;
3379 SilcHashTableList htl;
3380 SilcBuffer chidp, clidp;
3383 unsigned char mode[4];
3385 SILC_LOG_DEBUG(("Start"));
3387 /* Now find all users on the channel */
3388 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3389 silc_hash_table_list(channel->user_list, &htl);
3390 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3391 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3394 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3395 clidp->data, clidp->len,
3396 chidp->data, chidp->len);
3399 silc_buffer_realloc(*channel_users,
3401 (*channel_users)->truelen + len : len));
3402 silc_buffer_pull_tail(*channel_users,
3403 ((*channel_users)->end -
3404 (*channel_users)->data));
3406 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3407 silc_buffer_pull(*channel_users, len);
3408 silc_buffer_free(tmp);
3410 /* CUMODE notify for mode change on the channel */
3411 SILC_PUT32_MSB(chl->mode, mode);
3412 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3413 3, clidp->data, clidp->len,
3415 clidp->data, clidp->len);
3417 *channel_users_modes =
3418 silc_buffer_realloc(*channel_users_modes,
3419 (*channel_users_modes ?
3420 (*channel_users_modes)->truelen + len : len));
3421 silc_buffer_pull_tail(*channel_users_modes,
3422 ((*channel_users_modes)->end -
3423 (*channel_users_modes)->data));
3425 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3426 silc_buffer_pull(*channel_users_modes, len);
3427 silc_buffer_free(tmp);
3429 silc_buffer_free(clidp);
3431 silc_buffer_free(chidp);
3434 /* Returns assembled packets for all channels and users on those channels
3435 from the given ID List. The packets are in the form dictated by the
3436 New Channel and New Channel User payloads. */
3438 void silc_server_announce_get_channels(SilcServer server,
3440 SilcBuffer *channels,
3441 SilcBuffer *channel_users,
3442 SilcBuffer **channel_users_modes,
3443 uint32 *channel_users_modes_c,
3444 SilcBuffer **channel_topics,
3445 SilcChannelID ***channel_ids,
3446 unsigned long creation_time)
3448 SilcIDCacheList list;
3449 SilcIDCacheEntry id_cache;
3450 SilcChannelEntry channel;
3455 int i = *channel_users_modes_c;
3458 SILC_LOG_DEBUG(("Start"));
3460 /* Go through all channels in the list */
3461 if (silc_idcache_get_all(id_list->channels, &list)) {
3462 if (silc_idcache_list_first(list, &id_cache)) {
3464 channel = (SilcChannelEntry)id_cache->context;
3466 if (creation_time && channel->created < creation_time)
3471 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3472 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3473 name_len = strlen(channel->channel_name);
3476 len = 4 + name_len + id_len + 4;
3478 silc_buffer_realloc(*channels,
3479 (*channels ? (*channels)->truelen +
3481 silc_buffer_pull_tail(*channels,
3482 ((*channels)->end - (*channels)->data));
3483 silc_buffer_format(*channels,
3484 SILC_STR_UI_SHORT(name_len),
3485 SILC_STR_UI_XNSTRING(channel->channel_name,
3487 SILC_STR_UI_SHORT(id_len),
3488 SILC_STR_UI_XNSTRING(cid, id_len),
3489 SILC_STR_UI_INT(channel->mode),
3491 silc_buffer_pull(*channels, len);
3494 /* Channel user modes */
3495 *channel_users_modes = silc_realloc(*channel_users_modes,
3496 sizeof(**channel_users_modes) *
3498 (*channel_users_modes)[i] = NULL;
3499 *channel_ids = silc_realloc(*channel_ids,
3500 sizeof(**channel_ids) * (i + 1));
3501 (*channel_ids)[i] = NULL;
3502 silc_server_announce_get_channel_users(server, channel,
3504 &(*channel_users_modes)[i]);
3505 (*channel_ids)[i] = channel->id;
3507 /* Channel's topic */
3508 *channel_topics = silc_realloc(*channel_topics,
3509 sizeof(**channel_topics) * (i + 1));
3510 (*channel_topics)[i] = NULL;
3511 silc_server_announce_get_channel_topic(server, channel,
3512 &(*channel_topics)[i]);
3515 if (!silc_idcache_list_next(list, &id_cache))
3519 *channel_users_modes_c += i;
3522 silc_idcache_list_free(list);
3526 /* This function is used to announce our existing channels to our router
3527 when we've connected to it. This also announces the users on the
3528 channels to the router. If the `creation_time' is non-zero only the
3529 channels that was created after the `creation_time' are announced.
3530 Note that the channel users are still announced even if the `creation_time'
3533 void silc_server_announce_channels(SilcServer server,
3534 unsigned long creation_time,
3535 SilcSocketConnection remote)
3537 SilcBuffer channels = NULL, channel_users = NULL;
3538 SilcBuffer *channel_users_modes = NULL;
3539 SilcBuffer *channel_topics = NULL;
3540 uint32 channel_users_modes_c = 0;
3541 SilcChannelID **channel_ids = NULL;
3543 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3545 /* Get channels and channel users in local list */
3546 silc_server_announce_get_channels(server, server->local_list,
3547 &channels, &channel_users,
3548 &channel_users_modes,
3549 &channel_users_modes_c,
3551 &channel_ids, creation_time);
3553 /* Get channels and channel users in global list */
3554 if (server->server_type != SILC_SERVER)
3555 silc_server_announce_get_channels(server, server->global_list,
3556 &channels, &channel_users,
3557 &channel_users_modes,
3558 &channel_users_modes_c,
3560 &channel_ids, creation_time);
3563 silc_buffer_push(channels, channels->data - channels->head);
3564 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3566 /* Send the packet */
3567 silc_server_packet_send(server, remote,
3568 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3569 channels->data, channels->len,
3572 silc_buffer_free(channels);
3575 if (channel_users) {
3576 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3577 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3578 channel_users->len);
3580 /* Send the packet */
3581 silc_server_packet_send(server, remote,
3582 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3583 channel_users->data, channel_users->len,
3586 silc_buffer_free(channel_users);
3589 if (channel_users_modes) {
3592 for (i = 0; i < channel_users_modes_c; i++) {
3593 silc_buffer_push(channel_users_modes[i],
3594 channel_users_modes[i]->data -
3595 channel_users_modes[i]->head);
3596 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3597 channel_users_modes[i]->len);
3598 silc_server_packet_send_dest(server, remote,
3599 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3600 channel_ids[i], SILC_ID_CHANNEL,
3601 channel_users_modes[i]->data,
3602 channel_users_modes[i]->len,
3604 silc_buffer_free(channel_users_modes[i]);
3606 silc_free(channel_users_modes);
3609 if (channel_topics) {
3612 for (i = 0; i < channel_users_modes_c; i++) {
3613 if (!channel_topics[i])
3616 silc_buffer_push(channel_topics[i],
3617 channel_topics[i]->data -
3618 channel_topics[i]->head);
3619 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
3620 channel_topics[i]->len);
3621 silc_server_packet_send_dest(server, remote,
3622 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3623 channel_ids[i], SILC_ID_CHANNEL,
3624 channel_topics[i]->data,
3625 channel_topics[i]->len,
3627 silc_buffer_free(channel_topics[i]);
3629 silc_free(channel_topics);
3632 silc_free(channel_ids);
3635 /* Failure timeout callback. If this is called then we will immediately
3636 process the received failure. We always process the failure with timeout
3637 since we do not want to blindly trust to received failure packets.
3638 This won't be called (the timeout is cancelled) if the failure was
3639 bogus (it is bogus if remote does not close the connection after sending
3642 SILC_TASK_CALLBACK(silc_server_failure_callback)
3644 SilcServerFailureContext f = (SilcServerFailureContext)context;
3646 if (f->sock->protocol) {
3647 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3648 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3654 /* Assembles user list and users mode list from the `channel'. */
3656 void silc_server_get_users_on_channel(SilcServer server,
3657 SilcChannelEntry channel,
3658 SilcBuffer *user_list,
3659 SilcBuffer *mode_list,
3662 SilcChannelClientEntry chl;
3663 SilcHashTableList htl;
3664 SilcBuffer client_id_list;
3665 SilcBuffer client_mode_list;
3667 uint32 list_count = 0, len = 0;
3669 silc_hash_table_list(channel->user_list, &htl);
3670 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3671 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3673 client_id_list = silc_buffer_alloc(len);
3675 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3676 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3677 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3679 silc_hash_table_list(channel->user_list, &htl);
3680 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3682 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3683 silc_buffer_put(client_id_list, idp->data, idp->len);
3684 silc_buffer_pull(client_id_list, idp->len);
3685 silc_buffer_free(idp);
3687 /* Client's mode on channel */
3688 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3689 silc_buffer_pull(client_mode_list, 4);
3693 silc_buffer_push(client_id_list,
3694 client_id_list->data - client_id_list->head);
3695 silc_buffer_push(client_mode_list,
3696 client_mode_list->data - client_mode_list->head);
3698 *user_list = client_id_list;
3699 *mode_list = client_mode_list;
3700 *user_count = list_count;
3703 /* Saves users and their modes to the `channel'. */
3705 void silc_server_save_users_on_channel(SilcServer server,
3706 SilcSocketConnection sock,
3707 SilcChannelEntry channel,
3708 SilcClientID *noadd,
3709 SilcBuffer user_list,
3710 SilcBuffer mode_list,
3716 SilcClientID *client_id;
3717 SilcClientEntry client;
3718 SilcIDCacheEntry cache;
3721 SILC_LOG_DEBUG(("Start"));
3723 for (i = 0; i < user_count; i++) {
3725 SILC_GET16_MSB(idp_len, user_list->data + 2);
3727 client_id = silc_id_payload_parse_id(user_list->data, idp_len);
3728 silc_buffer_pull(user_list, idp_len);
3733 SILC_GET32_MSB(mode, mode_list->data);
3734 silc_buffer_pull(mode_list, 4);
3736 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3737 silc_free(client_id);
3743 /* Check if we have this client cached already. */
3744 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3745 server->server_type, &cache);
3747 client = silc_idlist_find_client_by_id(server->global_list,
3748 client_id, server->server_type,
3753 /* If router did not find such Client ID in its lists then this must
3754 be bogus client or some router in the net is buggy. */
3755 if (server->server_type == SILC_ROUTER) {
3756 silc_free(client_id);
3760 /* We don't have that client anywhere, add it. The client is added
3761 to global list since server didn't have it in the lists so it must be
3763 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3764 silc_id_dup(client_id, SILC_ID_CLIENT),
3765 sock->user_data, NULL, 0);
3767 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3768 silc_free(client_id);
3772 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3774 /* Found, if it is from global list we'll assure that we won't
3775 expire it now that the entry is on channel. */
3780 silc_free(client_id);
3782 if (!silc_server_client_on_channel(client, channel)) {
3783 /* Client was not on the channel, add it. */
3784 SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3785 chl->client = client;
3787 chl->channel = channel;
3788 silc_hash_table_add(channel->user_list, chl->client, chl);
3789 silc_hash_table_add(client->channels, chl->channel, chl);
3794 /* Lookups route to the client indicated by the `id_data'. The connection
3795 object and internal data object is returned. Returns NULL if route
3796 could not be found to the client. If the `client_id' is specified then
3797 it is used and the `id_data' is ignored. */
3799 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3800 unsigned char *id_data,
3802 SilcClientID *client_id,
3803 SilcIDListData *idata)
3806 SilcClientEntry client;
3808 SILC_LOG_DEBUG(("Start"));
3810 /* Decode destination Client ID */
3812 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3814 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3818 id = silc_id_dup(client_id, SILC_ID_CLIENT);
3821 /* If the destination belongs to our server we don't have to route
3822 the packet anywhere but to send it to the local destination. */
3823 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
3827 /* If we are router and the client has router then the client is in
3828 our cell but not directly connected to us. */
3829 if (server->server_type == SILC_ROUTER && client->router) {
3830 /* We are of course in this case the client's router thus the route
3831 to the client is the server who owns the client. So, we will send
3832 the packet to that server. */
3834 *idata = (SilcIDListData)client->router;
3835 return client->router->connection;
3838 /* Seems that client really is directly connected to us */
3840 *idata = (SilcIDListData)client;
3841 return client->connection;
3844 /* Destination belongs to someone not in this server. If we are normal
3845 server our action is to send the packet to our router. */
3846 if (server->server_type != SILC_ROUTER && !server->standalone) {
3849 *idata = (SilcIDListData)server->router;
3850 return server->router->connection;
3853 /* We are router and we will perform route lookup for the destination
3854 and send the packet to fastest route. */
3855 if (server->server_type == SILC_ROUTER && !server->standalone) {
3856 /* Check first that the ID is valid */
3857 client = silc_idlist_find_client_by_id(server->global_list, id,
3860 SilcSocketConnection dst_sock;
3862 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
3866 *idata = (SilcIDListData)dst_sock->user_data;
3875 /* Encodes and returns channel list of channels the `client' has joined.
3876 Secret channels are not put to the list. */
3878 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
3879 SilcClientEntry client)
3881 SilcBuffer buffer = NULL;
3882 SilcChannelEntry channel;
3883 SilcChannelClientEntry chl;
3884 SilcHashTableList htl;
3890 silc_hash_table_list(client->channels, &htl);
3891 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3892 channel = chl->channel;
3894 if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
3895 channel->mode & SILC_CHANNEL_MODE_PRIVATE)
3898 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3899 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3900 name_len = strlen(channel->channel_name);
3902 len = 4 + name_len + id_len + 4;
3903 buffer = silc_buffer_realloc(buffer,
3904 (buffer ? (buffer)->truelen + len : len));
3905 silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
3906 silc_buffer_format(buffer,
3907 SILC_STR_UI_SHORT(name_len),
3908 SILC_STR_UI_XNSTRING(channel->channel_name,
3910 SILC_STR_UI_SHORT(id_len),
3911 SILC_STR_UI_XNSTRING(cid, id_len),
3912 SILC_STR_UI_INT(chl->mode), /* Client's mode */
3914 silc_buffer_pull(buffer, len);
3919 silc_buffer_push(buffer, buffer->data - buffer->head);
3924 /* Finds client entry by Client ID and if it is not found then resolves
3925 it using WHOIS command. */
3927 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
3928 SilcClientID *client_id,
3931 SilcClientEntry client;
3936 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3939 client = silc_idlist_find_client_by_id(server->global_list,
3940 client_id, TRUE, NULL);
3941 if (!client && server->server_type == SILC_ROUTER)
3945 if (!client && server->standalone)
3948 if (!client || !client->nickname || !client->username) {
3949 SilcBuffer buffer, idp;
3951 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
3952 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
3953 client->resolve_cmd_ident = ++server->cmd_ident;
3955 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3956 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
3957 server->cmd_ident, 1,
3958 3, idp->data, idp->len);
3959 silc_server_packet_send(server, client ? client->router->connection :
3960 server->router->connection,
3961 SILC_PACKET_COMMAND, 0,
3962 buffer->data, buffer->len, FALSE);
3963 silc_buffer_free(idp);
3964 silc_buffer_free(buffer);
3975 /* A timeout callback for the re-key. We will be the initiator of the
3978 SILC_TASK_CALLBACK(silc_server_rekey_callback)
3980 SilcSocketConnection sock = (SilcSocketConnection)context;
3981 SilcIDListData idata = (SilcIDListData)sock->user_data;
3982 SilcServer server = (SilcServer)idata->rekey->context;
3983 SilcProtocol protocol;
3984 SilcServerRekeyInternalContext *proto_ctx;
3986 SILC_LOG_DEBUG(("Start"));
3988 /* Allocate internal protocol context. This is sent as context
3990 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
3991 proto_ctx->server = (void *)server;
3992 proto_ctx->sock = sock;
3993 proto_ctx->responder = FALSE;
3994 proto_ctx->pfs = idata->rekey->pfs;
3996 /* Perform rekey protocol. Will call the final callback after the
3997 protocol is over. */
3998 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
3999 &protocol, proto_ctx, silc_server_rekey_final);
4000 sock->protocol = protocol;
4002 /* Run the protocol */
4003 silc_protocol_execute(protocol, server->schedule, 0, 0);
4005 /* Re-register re-key timeout */
4006 silc_schedule_task_add(server->schedule, sock->sock,
4007 silc_server_rekey_callback,
4008 context, idata->rekey->timeout, 0,
4009 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4012 /* The final callback for the REKEY protocol. This will actually take the
4013 new key material into use. */
4015 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4017 SilcProtocol protocol = (SilcProtocol)context;
4018 SilcServerRekeyInternalContext *ctx =
4019 (SilcServerRekeyInternalContext *)protocol->context;
4020 SilcServer server = (SilcServer)ctx->server;
4021 SilcSocketConnection sock = ctx->sock;
4023 SILC_LOG_DEBUG(("Start"));
4025 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4026 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4027 /* Error occured during protocol */
4028 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4029 silc_protocol_cancel(protocol, server->schedule);
4030 silc_protocol_free(protocol);
4031 sock->protocol = NULL;
4033 silc_packet_context_free(ctx->packet);
4035 silc_ske_free(ctx->ske);
4040 /* Purge the outgoing data queue to assure that all rekey packets really
4041 go to the network before we quit the protocol. */
4042 silc_server_packet_queue_purge(server, sock);
4045 silc_protocol_free(protocol);
4046 sock->protocol = NULL;
4048 silc_packet_context_free(ctx->packet);
4050 silc_ske_free(ctx->ske);