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 = 0, 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;
146 silc_server_config_setlogfiles(server->config);
148 /* Register all configured ciphers, PKCS and hash functions. */
149 if (!silc_server_config_register_ciphers(server->config))
150 silc_cipher_register_default();
151 if (!silc_server_config_register_pkcs(server->config))
152 silc_pkcs_register_default();
153 if (!silc_server_config_register_hashfuncs(server->config))
154 silc_hash_register_default();
155 if (!silc_server_config_register_hmacs(server->config))
156 silc_hmac_register_default();
158 /* Initialize random number generator for the server. */
159 server->rng = silc_rng_alloc();
160 silc_rng_init(server->rng);
161 silc_rng_global_init(server->rng);
163 /* Initialize hash functions for server to use */
164 silc_hash_alloc("md5", &server->md5hash);
165 silc_hash_alloc("sha1", &server->sha1hash);
167 /* Initialize none cipher */
168 silc_cipher_alloc("none", &server->none_cipher);
170 /* Allocate PKCS context for local public and private keys */
171 silc_pkcs_alloc(server->public_key->name, &server->pkcs);
172 silc_pkcs_public_key_set(server->pkcs, server->public_key);
173 silc_pkcs_private_key_set(server->pkcs, server->private_key);
175 /* Create a listening server. Note that our server can listen on multiple
176 ports. All listeners are created here and now. */
178 listen = server->config->listen_port;
182 tmp = silc_net_create_server(server->config->listen_port->port,
183 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(int *) * (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 /* Create a Server ID for the server. */
226 silc_id_create_server_id(sock[i], server->rng, &id);
232 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
233 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
234 server->id_type = SILC_ID_SERVER;
235 server->server_name = server->config->server_info->server_name;
237 /* Add ourselves to the server list. We don't have a router yet
238 beacuse we haven't established a route yet. It will be done later.
239 For now, NULL is sent as router. This allocates new entry to
242 silc_idlist_add_server(server->local_list,
243 server->config->server_info->server_name,
244 server->server_type, server->id, NULL, NULL);
246 SILC_LOG_ERROR(("Could not add ourselves to cache"));
249 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
251 /* Add ourselves also to the socket table. The entry allocated above
252 is sent as argument for fast referencing in the future. */
253 silc_socket_alloc(sock[i], SILC_SOCKET_TYPE_SERVER, id_entry,
256 server->sockets[sock[i]] = newsocket;
258 /* Perform name and address lookups to resolve the listenning address
260 if (!silc_net_check_local_by_sock(sock[i], &newsocket->hostname,
262 if ((server->params->require_reverse_mapping && !newsocket->hostname) ||
264 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
265 newsocket->hostname ? newsocket->hostname :
266 newsocket->ip ? newsocket->ip : ""));
267 server->stat.conn_failures++;
270 if (!newsocket->hostname)
271 newsocket->hostname = strdup(newsocket->ip);
273 newsocket->port = silc_net_get_local_port(sock[i]);
275 /* Put the allocated socket pointer also to the entry allocated above
276 for fast back-referencing to the socket list. */
277 id_entry->connection = (void *)server->sockets[sock[i]];
278 server->id_entry = id_entry;
281 /* Register protocols */
282 silc_server_protocols_register();
284 /* Initialize the scheduler. */
285 server->schedule = silc_schedule_init(SILC_SERVER_MAX_CONNECTIONS);
286 if (!server->schedule)
289 /* Add the first task to the scheduler. This is task that is executed by
290 timeout. It expires as soon as the caller calls silc_server_run. This
291 task performs authentication protocol and key exchange with our
293 silc_schedule_task_add(server->schedule, sock[0],
294 silc_server_connect_to_router,
295 (void *)server, 0, 1,
297 SILC_TASK_PRI_NORMAL);
299 /* Add listener task to the scheduler. This task receives new connections
300 to the server. This task remains on the queue until the end of the
302 silc_schedule_task_add(server->schedule, sock[0],
303 silc_server_accept_new_connection,
304 (void *)server, 0, 0,
306 SILC_TASK_PRI_NORMAL);
307 server->listenning = TRUE;
309 /* If server connections has been configured then we must be router as
310 normal server cannot have server connections, only router connections. */
311 if (server->config->servers) {
312 SilcServerConfigSectionServerConnection *ptr = server->config->servers;
314 server->server_type = SILC_ROUTER;
316 if (ptr->backup_router) {
317 server->server_type = SILC_BACKUP_ROUTER;
318 server->backup_router = TRUE;
319 server->id_entry->server_type = SILC_BACKUP_ROUTER;
326 /* Register the ID Cache purge task. This periodically purges the ID cache
327 and removes the expired cache entries. */
329 /* Clients local list */
330 purge = silc_calloc(1, sizeof(*purge));
331 purge->cache = server->local_list->clients;
332 purge->schedule = server->schedule;
333 silc_schedule_task_add(purge->schedule, 0,
335 (void *)purge, 600, 0,
336 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
338 /* Clients global list */
339 purge = silc_calloc(1, sizeof(*purge));
340 purge->cache = server->global_list->clients;
341 purge->schedule = server->schedule;
342 silc_schedule_task_add(purge->schedule, 0,
344 (void *)purge, 300, 0,
345 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
347 SILC_LOG_DEBUG(("Server initialized"));
349 /* We are done here, return succesfully */
353 for (i = 0; i < sock_count; i++)
354 silc_net_close_server(sock[i]);
359 /* Fork server to background and set gid+uid to non-root */
361 void silc_server_daemonise(SilcServer server)
370 SILC_LOG_DEBUG(("Server started as user"));
372 SILC_LOG_DEBUG(("Server started as root. Dropping privileges."));
374 SILC_LOG_DEBUG(("Forking SILC server to background"));
377 SILC_LOG_DEBUG(("fork() failed, cannot proceed"));
384 /* Drop root privligies. If this cannot be done, die. */
386 void silc_server_drop(SilcServer server)
388 /* Are we executing silcd as root or a regular user? */
395 if (!server->config->identity || !server->config->identity->user ||
396 !server->config->identity->group) {
397 fprintf(stderr, "Error:"
398 "\tSILC server must not be run as root. For the security of your\n"
399 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
400 "\tuser account. Modify the [Identity] configuration section to run\n"
401 "\tthe server as non-root user.\n");
405 /* Get the values given for user and group in configuration file */
406 user=server->config->identity->user;
407 group=server->config->identity->group;
409 /* Check whether the user/group information is text */
410 if (atoi(user)!=0 || atoi(group)!=0) {
411 SILC_LOG_DEBUG(("Invalid user and/or group information"));
412 SILC_LOG_DEBUG(("User and/or group given as number"));
413 fprintf(stderr, "Invalid user and/or group information\n");
414 fprintf(stderr, "Please assign them as names, not numbers\n");
418 /* Catch the nasty incident of string "0" returning 0 from atoi */
419 if (strcmp("0", user)==0 || strcmp("0", group)==0) {
420 SILC_LOG_DEBUG(("User and/or group configured to 0. Unacceptable"));
421 fprintf(stderr, "User and/or group configured to 0. Exiting\n");
425 if (!(pw=getpwnam(user))) {
426 fprintf(stderr, "No such user %s found\n", user);
430 if (!(gr=getgrnam(group))) {
431 fprintf(stderr, "No such group %s found\n", group);
435 /* Check whether user and/or group is set to root. If yes, exit
436 immediately. Otherwise, setgid and setuid server to user.group */
437 if (gr->gr_gid==0 || pw->pw_uid==0) {
438 fprintf(stderr, "Error:"
439 "\tSILC server must not be run as root. For the security of your\n"
440 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
441 "\tuser account. Modify the [Identity] configuration section to run\n"
442 "\tthe server as non-root user.\n");
445 SILC_LOG_DEBUG(("Changing to group %s", group));
446 if (setgid(gr->gr_gid)==0) {
447 SILC_LOG_DEBUG(("Setgid to %s", group));
449 SILC_LOG_DEBUG(("Setgid to %s failed", group));
450 fprintf(stderr, "Tried to setgid %s but no such group. Exiting\n",
454 #if defined HAVE_SETGROUPS && defined HAVE_INITGROUPS
455 if (setgroups(0, NULL)!=0) {
456 SILC_LOG_DEBUG(("Setgroups to NULL failed"));
457 fprintf(stderr, "Tried to setgroups NULL but failed. Exiting\n");
460 if (initgroups(user, gr->gr_gid)!=0) {
461 SILC_LOG_DEBUG(("Initgroups to user %s (gid=%d) failed", user, gr->gr_gid));
462 fprintf(stderr, "Tried to initgroups %s (gid=%d) but no such user. Exiting\n",
467 SILC_LOG_DEBUG(("Changing to user %s", user));
468 if (setuid(pw->pw_uid)==0) {
469 SILC_LOG_DEBUG(("Setuid to %s", user));
471 SILC_LOG_DEBUG(("Setuid to %s failed", user));
472 fprintf(stderr, "Tried to setuid %s but no such user. Exiting\n",
480 /* The heart of the server. This runs the scheduler thus runs the server.
481 When this returns the server has been stopped and the program will
484 void silc_server_run(SilcServer server)
486 SILC_LOG_DEBUG(("Running server"));
488 SILC_LOG_INFO(("SILC Server started"));
490 /* Start the scheduler, the heart of the SILC server. When this returns
491 the program will be terminated. */
492 silc_schedule(server->schedule);
495 /* Stops the SILC server. This function is used to shutdown the server.
496 This is usually called after the scheduler has returned. After stopping
497 the server one should call silc_server_free. */
499 void silc_server_stop(SilcServer server)
501 SILC_LOG_DEBUG(("Stopping server"));
503 silc_schedule_stop(server->schedule);
504 silc_schedule_uninit(server->schedule);
506 silc_server_protocols_unregister();
508 SILC_LOG_DEBUG(("Server stopped"));
511 /* Function that is called when the network connection to a router has
512 been established. This will continue with the key exchange protocol
513 with the remote router. */
515 void silc_server_start_key_exchange(SilcServer server,
516 SilcServerConnection sconn,
519 SilcSocketConnection newsocket;
520 SilcProtocol protocol;
521 SilcServerKEInternalContext *proto_ctx;
524 /* Set socket options */
525 silc_net_set_socket_nonblock(sock);
526 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
528 /* Create socket connection for the connection. Even though we
529 know that we are connecting to a router we will mark the socket
530 to be unknown connection until we have executed authentication
532 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
533 server->sockets[sock] = newsocket;
534 newsocket->hostname = strdup(sconn->remote_host);
535 newsocket->ip = strdup(sconn->remote_host);
536 newsocket->port = sconn->remote_port;
537 sconn->sock = newsocket;
539 /* Allocate internal protocol context. This is sent as context
541 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
542 proto_ctx->server = (void *)server;
543 proto_ctx->context = (void *)sconn;
544 proto_ctx->sock = newsocket;
545 proto_ctx->rng = server->rng;
546 proto_ctx->responder = FALSE;
548 /* Perform key exchange protocol. silc_server_connect_to_router_second
549 will be called after the protocol is finished. */
550 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
551 &protocol, proto_ctx,
552 silc_server_connect_to_router_second);
553 newsocket->protocol = protocol;
555 /* Register a timeout task that will be executed if the protocol
556 is not executed within set limit. */
557 proto_ctx->timeout_task =
558 silc_schedule_task_add(server->schedule, sock,
559 silc_server_timeout_remote,
560 server, server->params->protocol_timeout,
561 server->params->protocol_timeout_usec,
565 /* Register the connection for network input and output. This sets
566 that scheduler will listen for incoming packets for this connection
567 and sets that outgoing packets may be sent to this connection as
568 well. However, this doesn't set the scheduler for outgoing traffic,
569 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
570 later when outgoing data is available. */
571 context = (void *)server;
572 SILC_REGISTER_CONNECTION_FOR_IO(sock);
574 /* Run the protocol */
575 silc_protocol_execute(protocol, server->schedule, 0, 0);
578 /* Timeout callback that will be called to retry connecting to remote
579 router. This is used by both normal and router server. This will wait
580 before retrying the connecting. The timeout is generated by exponential
581 backoff algorithm. */
583 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
585 SilcServerConnection sconn = (SilcServerConnection)context;
586 SilcServer server = sconn->server;
588 SILC_LOG_INFO(("Retrying connecting to a router"));
590 /* Calculate next timeout */
591 if (sconn->retry_count >= 1) {
592 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
593 if (sconn->retry_timeout > SILC_SERVER_RETRY_INTERVAL_MAX)
594 sconn->retry_timeout = SILC_SERVER_RETRY_INTERVAL_MAX;
596 sconn->retry_timeout = server->params->retry_interval_min;
598 sconn->retry_count++;
599 sconn->retry_timeout = sconn->retry_timeout +
600 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
602 /* If we've reached max retry count, give up. */
603 if (sconn->retry_count > server->params->retry_count &&
604 server->params->retry_keep_trying == FALSE) {
605 SILC_LOG_ERROR(("Could not connect to router, giving up"));
609 /* Wait one before retrying */
610 silc_schedule_task_add(server->schedule, fd, silc_server_connect_router,
611 context, sconn->retry_timeout,
612 server->params->retry_interval_min_usec,
613 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
616 /* Generic routine to use connect to a router. */
618 SILC_TASK_CALLBACK(silc_server_connect_router)
620 SilcServerConnection sconn = (SilcServerConnection)context;
621 SilcServer server = sconn->server;
624 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
625 (sconn->backup ? "backup router" : "router"),
626 sconn->remote_host, sconn->remote_port));
628 server->router_connect = time(0);
630 /* Connect to remote host */
631 sock = silc_net_create_connection(server->config->listen_port->local_ip,
635 SILC_LOG_ERROR(("Could not connect to router"));
636 silc_schedule_task_add(server->schedule, fd,
637 silc_server_connect_to_router_retry,
638 context, 0, 1, SILC_TASK_TIMEOUT,
639 SILC_TASK_PRI_NORMAL);
643 /* Continue with key exchange protocol */
644 silc_server_start_key_exchange(server, sconn, sock);
647 /* This function connects to our primary router or if we are a router this
648 establishes all our primary routes. This is called at the start of the
649 server to do authentication and key exchange with our router - called
652 SILC_TASK_CALLBACK(silc_server_connect_to_router)
654 SilcServer server = (SilcServer)context;
655 SilcServerConnection sconn;
656 SilcServerConfigSectionServerConnection *ptr;
658 SILC_LOG_DEBUG(("Connecting to router(s)"));
660 if (server->server_type == SILC_SERVER) {
661 SILC_LOG_DEBUG(("We are normal server"));
662 } else if (server->server_type == SILC_ROUTER) {
663 SILC_LOG_DEBUG(("We are router"));
665 SILC_LOG_DEBUG(("We are backup router/normal server"));
668 /* Create the connections to all our routes */
669 ptr = server->config->routers;
672 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
673 ptr->backup_router ? "Backup router" : "Router",
674 ptr->initiator ? "Initiator" : "Responder",
675 ptr->host, ptr->port));
677 if (ptr->initiator) {
678 /* Allocate connection object for hold connection specific stuff. */
679 sconn = silc_calloc(1, sizeof(*sconn));
680 sconn->server = server;
681 sconn->remote_host = strdup(ptr->host);
682 sconn->remote_port = ptr->port;
683 sconn->backup = ptr->backup_router;
685 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
686 sconn->backup_replace_port = ptr->backup_replace_port;
689 silc_schedule_task_add(server->schedule, fd,
690 silc_server_connect_router,
691 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
692 SILC_TASK_PRI_NORMAL);
701 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
703 /* There wasn't a configured router, we will continue but we don't
704 have a connection to outside world. We will be standalone server. */
705 server->standalone = TRUE;
708 /* Second part of connecting to router(s). Key exchange protocol has been
709 executed and now we will execute authentication protocol. */
711 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
713 SilcProtocol protocol = (SilcProtocol)context;
714 SilcServerKEInternalContext *ctx =
715 (SilcServerKEInternalContext *)protocol->context;
716 SilcServer server = (SilcServer)ctx->server;
717 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
718 SilcSocketConnection sock = ctx->sock;
719 SilcServerConnAuthInternalContext *proto_ctx;
720 SilcServerConfigSectionServerConnection *conn = NULL;
722 SILC_LOG_DEBUG(("Start"));
724 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
725 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
726 /* Error occured during protocol */
727 silc_protocol_free(protocol);
728 sock->protocol = NULL;
729 silc_ske_free_key_material(ctx->keymat);
731 silc_packet_context_free(ctx->packet);
733 silc_ske_free(ctx->ske);
734 silc_free(ctx->dest_id);
736 silc_schedule_task_del_by_callback(server->schedule,
737 silc_server_failure_callback);
738 silc_server_disconnect_remote(server, sock, "Server closed connection: "
739 "Key exchange failed");
743 /* We now have the key material as the result of the key exchange
744 protocol. Take the key material into use. Free the raw key material
745 as soon as we've set them into use. */
746 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
747 ctx->sock, ctx->keymat,
748 ctx->ske->prop->cipher,
749 ctx->ske->prop->pkcs,
750 ctx->ske->prop->hash,
751 ctx->ske->prop->hmac,
752 ctx->ske->prop->group,
754 silc_protocol_free(protocol);
755 sock->protocol = NULL;
756 silc_ske_free_key_material(ctx->keymat);
758 silc_packet_context_free(ctx->packet);
760 silc_ske_free(ctx->ske);
761 silc_free(ctx->dest_id);
763 silc_schedule_task_del_by_callback(server->schedule,
764 silc_server_failure_callback);
765 silc_server_disconnect_remote(server, sock, "Server closed connection: "
766 "Key exchange failed");
769 silc_ske_free_key_material(ctx->keymat);
771 /* Allocate internal context for the authentication protocol. This
772 is sent as context for the protocol. */
773 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
774 proto_ctx->server = (void *)server;
775 proto_ctx->context = (void *)sconn;
776 proto_ctx->sock = sock;
777 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
778 proto_ctx->dest_id_type = ctx->dest_id_type;
779 proto_ctx->dest_id = ctx->dest_id;
781 /* Resolve the authentication method used in this connection. Check if
782 we find a match from user configured connections */
783 conn = silc_server_config_find_router_conn(server->config,
787 /* Match found. Use the configured authentication method */
788 proto_ctx->auth_meth = conn->auth_meth;
789 if (conn->auth_data) {
790 proto_ctx->auth_data = strdup(conn->auth_data);
791 proto_ctx->auth_data_len = strlen(conn->auth_data);
794 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
795 sock->hostname, sock->ip, sock->port));
796 silc_protocol_free(protocol);
797 sock->protocol = NULL;
799 silc_packet_context_free(ctx->packet);
801 silc_ske_free(ctx->ske);
802 silc_free(ctx->dest_id);
804 silc_schedule_task_del_by_callback(server->schedule,
805 silc_server_failure_callback);
806 silc_server_disconnect_remote(server, sock, "Server closed connection: "
807 "Key exchange failed");
811 /* Free old protocol as it is finished now */
812 silc_protocol_free(protocol);
814 silc_packet_context_free(ctx->packet);
816 sock->protocol = NULL;
818 /* Allocate the authentication protocol. This is allocated here
819 but we won't start it yet. We will be receiving party of this
820 protocol thus we will wait that connecting party will make
822 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
823 &sock->protocol, proto_ctx,
824 silc_server_connect_to_router_final);
826 /* Register timeout task. If the protocol is not executed inside
827 this timelimit the connection will be terminated. Currently
828 this is 15 seconds and is hard coded limit (XXX). */
829 proto_ctx->timeout_task =
830 silc_schedule_task_add(server->schedule, sock->sock,
831 silc_server_timeout_remote,
832 (void *)server, 15, 0,
836 /* Run the protocol */
837 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
840 /* Finalizes the connection to router. Registers a server task to the
841 queue so that we can accept new connections. */
843 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
845 SilcProtocol protocol = (SilcProtocol)context;
846 SilcServerConnAuthInternalContext *ctx =
847 (SilcServerConnAuthInternalContext *)protocol->context;
848 SilcServer server = (SilcServer)ctx->server;
849 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
850 SilcSocketConnection sock = ctx->sock;
851 SilcServerEntry id_entry;
853 SilcServerHBContext hb_context;
854 unsigned char *id_string;
856 SilcIDListData idata;
858 SILC_LOG_DEBUG(("Start"));
860 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
861 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
862 /* Error occured during protocol */
863 silc_free(ctx->dest_id);
864 silc_server_disconnect_remote(server, sock, "Server closed connection: "
865 "Authentication failed");
869 /* Add a task to the queue. This task receives new connections to the
870 server. This task remains on the queue until the end of the program. */
871 if (!server->listenning && !sconn->backup) {
872 silc_schedule_task_add(server->schedule, server->sock,
873 silc_server_accept_new_connection,
874 (void *)server, 0, 0,
876 SILC_TASK_PRI_NORMAL);
877 server->listenning = TRUE;
880 /* Send NEW_SERVER packet to the router. We will become registered
881 to the SILC network after sending this packet. */
882 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
883 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
884 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
885 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
886 silc_buffer_format(packet,
887 SILC_STR_UI_SHORT(id_len),
888 SILC_STR_UI_XNSTRING(id_string, id_len),
889 SILC_STR_UI_SHORT(strlen(server->server_name)),
890 SILC_STR_UI_XNSTRING(server->server_name,
891 strlen(server->server_name)),
894 /* Send the packet */
895 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
896 packet->data, packet->len, TRUE);
897 silc_buffer_free(packet);
898 silc_free(id_string);
900 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
902 /* Check that we do not have this ID already */
903 id_entry = silc_idlist_find_server_by_id(server->local_list,
904 ctx->dest_id, TRUE, NULL);
906 silc_idcache_del_by_context(server->local_list->servers, id_entry);
908 id_entry = silc_idlist_find_server_by_id(server->global_list,
909 ctx->dest_id, TRUE, NULL);
911 silc_idcache_del_by_context(server->global_list->servers, id_entry);
914 SILC_LOG_DEBUG(("New server id(%s)",
915 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
917 /* Add the connected router to global server list */
918 id_entry = silc_idlist_add_server(server->global_list,
919 strdup(sock->hostname),
920 SILC_ROUTER, ctx->dest_id, NULL, sock);
922 silc_free(ctx->dest_id);
923 silc_server_disconnect_remote(server, sock, "Server closed connection: "
924 "Authentication failed");
928 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
929 silc_free(sock->user_data);
930 sock->user_data = (void *)id_entry;
931 sock->type = SILC_SOCKET_TYPE_ROUTER;
932 idata = (SilcIDListData)sock->user_data;
933 idata->status |= SILC_IDLIST_STATUS_REGISTERED;
935 /* Perform keepalive. The `hb_context' will be freed automatically
936 when finally calling the silc_socket_free function. XXX hardcoded
938 hb_context = silc_calloc(1, sizeof(*hb_context));
939 hb_context->server = server;
940 silc_socket_set_heartbeat(sock, 600, hb_context,
941 silc_server_perform_heartbeat,
944 /* Register re-key timeout */
945 idata->rekey->timeout = 3600; /* XXX hardcoded */
946 idata->rekey->context = (void *)server;
947 silc_schedule_task_add(server->schedule, sock->sock,
948 silc_server_rekey_callback,
949 (void *)sock, idata->rekey->timeout, 0,
950 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
952 if (!sconn->backup) {
953 /* Mark this router our primary router if we're still standalone */
954 if (server->standalone) {
955 server->id_entry->router = id_entry;
956 server->router = id_entry;
957 server->standalone = FALSE;
959 /* If we are router then announce our possible servers. */
960 if (server->server_type == SILC_ROUTER)
961 silc_server_announce_servers(server, FALSE, 0,
962 server->router->connection);
964 /* Announce our clients and channels to the router */
965 silc_server_announce_clients(server, 0, server->router->connection);
966 silc_server_announce_channels(server, 0, server->router->connection);
969 /* Add this server to be our backup router */
970 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
971 sconn->backup_replace_port, FALSE);
974 sock->protocol = NULL;
976 /* Call the completion callback to indicate that we've connected to
979 (*sconn->callback)(server, id_entry, sconn->callback_context);
982 /* Free the temporary connection data context */
984 silc_free(sconn->remote_host);
985 silc_free(sconn->backup_replace_ip);
989 /* Free the protocol object */
990 if (sock->protocol == protocol)
991 sock->protocol = NULL;
992 silc_protocol_free(protocol);
994 silc_packet_context_free(ctx->packet);
996 silc_ske_free(ctx->ske);
1000 /* Host lookup callbcak that is called after the incoming connection's
1001 IP and FQDN lookup is performed. This will actually check the acceptance
1002 of the incoming connection and will register the key exchange protocol
1003 for this connection. */
1006 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1009 SilcServer server = (SilcServer)context;
1010 SilcServerKEInternalContext *proto_ctx;
1011 void *cconfig, *sconfig, *rconfig;
1012 SilcServerConfigSectionDenyConnection *deny;
1015 SILC_LOG_DEBUG(("Start"));
1017 /* Check whether we could resolve both IP and FQDN. */
1018 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1019 server->params->require_reverse_mapping)) {
1020 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1021 sock->hostname ? sock->hostname :
1022 sock->ip ? sock->ip : ""));
1023 server->stat.conn_failures++;
1024 silc_server_disconnect_remote(server, sock,
1025 "Server closed connection: Unknown host");
1029 /* Register the connection for network input and output. This sets
1030 that scheduler will listen for incoming packets for this connection
1031 and sets that outgoing packets may be sent to this connection as well.
1032 However, this doesn't set the scheduler for outgoing traffic, it
1033 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1034 later when outgoing data is available. */
1035 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1037 SILC_LOG_INFO(("Incoming connection from %s (%s)", sock->hostname,
1040 port = server->sockets[server->sock]->port; /* Listenning port */
1042 /* Check whether this connection is denied to connect to us. */
1043 deny = silc_server_config_denied_conn(server->config, sock->ip, port);
1045 deny = silc_server_config_denied_conn(server->config, sock->hostname,
1048 /* The connection is denied */
1049 SILC_LOG_INFO(("Connection %s (%s) is denied",
1050 sock->hostname, sock->ip));
1051 silc_server_disconnect_remote(server, sock, deny->comment ?
1053 "Server closed connection: "
1054 "Connection refused");
1055 server->stat.conn_failures++;
1059 /* Check whether we have configred this sort of connection at all. We
1060 have to check all configurations since we don't know what type of
1061 connection this is. */
1062 if (!(cconfig = silc_server_config_find_client_conn(server->config,
1064 cconfig = silc_server_config_find_client_conn(server->config,
1067 if (!(sconfig = silc_server_config_find_server_conn(server->config,
1070 sconfig = silc_server_config_find_server_conn(server->config,
1073 if (!(rconfig = silc_server_config_find_router_conn(server->config,
1075 rconfig = silc_server_config_find_router_conn(server->config,
1078 if (!cconfig && !sconfig && !rconfig) {
1079 silc_server_disconnect_remote(server, sock,
1080 "Server closed connection: "
1081 "Connection refused");
1082 server->stat.conn_failures++;
1086 /* The connection is allowed */
1088 /* Allocate internal context for key exchange protocol. This is
1089 sent as context for the protocol. */
1090 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1091 proto_ctx->server = context;
1092 proto_ctx->sock = sock;
1093 proto_ctx->rng = server->rng;
1094 proto_ctx->responder = TRUE;
1095 proto_ctx->cconfig = cconfig;
1096 proto_ctx->sconfig = sconfig;
1097 proto_ctx->rconfig = rconfig;
1099 /* Prepare the connection for key exchange protocol. We allocate the
1100 protocol but will not start it yet. The connector will be the
1101 initiator of the protocol thus we will wait for initiation from
1102 there before we start the protocol. */
1103 server->stat.auth_attempts++;
1104 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1105 &sock->protocol, proto_ctx,
1106 silc_server_accept_new_connection_second);
1108 /* Register a timeout task that will be executed if the connector
1109 will not start the key exchange protocol within 60 seconds. For
1110 now, this is a hard coded limit. After 60 secs the connection will
1111 be closed if the key exchange protocol has not been started. */
1112 proto_ctx->timeout_task =
1113 silc_schedule_task_add(server->schedule, sock->sock,
1114 silc_server_timeout_remote,
1120 /* Accepts new connections to the server. Accepting new connections are
1121 done in three parts to make it async. */
1123 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1125 SilcServer server = (SilcServer)context;
1126 SilcSocketConnection newsocket;
1129 SILC_LOG_DEBUG(("Accepting new connection"));
1131 server->stat.conn_attempts++;
1133 sock = silc_net_accept_connection(server->sock);
1135 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1136 server->stat.conn_failures++;
1140 /* Check max connections */
1141 if (sock > SILC_SERVER_MAX_CONNECTIONS) {
1142 SILC_LOG_ERROR(("Refusing connection, server is full"));
1143 server->stat.conn_failures++;
1147 /* Set socket options */
1148 silc_net_set_socket_nonblock(sock);
1149 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1151 /* We don't create a ID yet, since we don't know what type of connection
1152 this is yet. But, we do add the connection to the socket table. */
1153 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1154 server->sockets[sock] = newsocket;
1156 /* Perform asynchronous host lookup. This will lookup the IP and the
1157 FQDN of the remote connection. After the lookup is done the connection
1158 is accepted further. */
1159 silc_socket_host_lookup(newsocket, TRUE,
1160 silc_server_accept_new_connection_lookup, context,
1164 /* Second part of accepting new connection. Key exchange protocol has been
1165 performed and now it is time to do little connection authentication
1166 protocol to figure out whether this connection is client or server
1167 and whether it has right to access this server (especially server
1168 connections needs to be authenticated). */
1170 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1172 SilcProtocol protocol = (SilcProtocol)context;
1173 SilcServerKEInternalContext *ctx =
1174 (SilcServerKEInternalContext *)protocol->context;
1175 SilcServer server = (SilcServer)ctx->server;
1176 SilcSocketConnection sock = ctx->sock;
1177 SilcServerConnAuthInternalContext *proto_ctx;
1179 SILC_LOG_DEBUG(("Start"));
1181 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1182 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1183 /* Error occured during protocol */
1184 silc_protocol_free(protocol);
1185 sock->protocol = NULL;
1186 silc_ske_free_key_material(ctx->keymat);
1188 silc_packet_context_free(ctx->packet);
1190 silc_ske_free(ctx->ske);
1191 silc_free(ctx->dest_id);
1193 silc_schedule_task_del_by_callback(server->schedule,
1194 silc_server_failure_callback);
1195 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1196 "Key exchange failed");
1197 server->stat.auth_failures++;
1201 /* We now have the key material as the result of the key exchange
1202 protocol. Take the key material into use. Free the raw key material
1203 as soon as we've set them into use. */
1204 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1205 ctx->sock, ctx->keymat,
1206 ctx->ske->prop->cipher,
1207 ctx->ske->prop->pkcs,
1208 ctx->ske->prop->hash,
1209 ctx->ske->prop->hmac,
1210 ctx->ske->prop->group,
1212 silc_protocol_free(protocol);
1213 sock->protocol = NULL;
1214 silc_ske_free_key_material(ctx->keymat);
1216 silc_packet_context_free(ctx->packet);
1218 silc_ske_free(ctx->ske);
1219 silc_free(ctx->dest_id);
1221 silc_schedule_task_del_by_callback(server->schedule,
1222 silc_server_failure_callback);
1223 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1224 "Key exchange failed");
1225 server->stat.auth_failures++;
1228 silc_ske_free_key_material(ctx->keymat);
1230 /* Allocate internal context for the authentication protocol. This
1231 is sent as context for the protocol. */
1232 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1233 proto_ctx->server = (void *)server;
1234 proto_ctx->sock = sock;
1235 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1236 proto_ctx->responder = TRUE;
1237 proto_ctx->dest_id_type = ctx->dest_id_type;
1238 proto_ctx->dest_id = ctx->dest_id;
1239 proto_ctx->cconfig = ctx->cconfig;
1240 proto_ctx->sconfig = ctx->sconfig;
1241 proto_ctx->rconfig = ctx->rconfig;
1243 /* Free old protocol as it is finished now */
1244 silc_protocol_free(protocol);
1246 silc_packet_context_free(ctx->packet);
1248 sock->protocol = NULL;
1250 /* Allocate the authentication protocol. This is allocated here
1251 but we won't start it yet. We will be receiving party of this
1252 protocol thus we will wait that connecting party will make
1253 their first move. */
1254 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1255 &sock->protocol, proto_ctx,
1256 silc_server_accept_new_connection_final);
1258 /* Register timeout task. If the protocol is not executed inside
1259 this timelimit the connection will be terminated. Currently
1260 this is 60 seconds and is hard coded limit (XXX). */
1261 proto_ctx->timeout_task =
1262 silc_schedule_task_add(server->schedule, sock->sock,
1263 silc_server_timeout_remote,
1264 (void *)server, 60, 0,
1269 /* Final part of accepting new connection. The connection has now
1270 been authenticated and keys has been exchanged. We also know whether
1271 this is client or server connection. */
1273 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1275 SilcProtocol protocol = (SilcProtocol)context;
1276 SilcServerConnAuthInternalContext *ctx =
1277 (SilcServerConnAuthInternalContext *)protocol->context;
1278 SilcServer server = (SilcServer)ctx->server;
1279 SilcSocketConnection sock = ctx->sock;
1280 SilcServerHBContext hb_context;
1281 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1282 void *id_entry = NULL;
1284 SILC_LOG_DEBUG(("Start"));
1286 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1287 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1288 /* Error occured during protocol */
1289 silc_protocol_free(protocol);
1290 sock->protocol = NULL;
1292 silc_packet_context_free(ctx->packet);
1294 silc_ske_free(ctx->ske);
1295 silc_free(ctx->dest_id);
1297 silc_schedule_task_del_by_callback(server->schedule,
1298 silc_server_failure_callback);
1299 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1300 "Authentication failed");
1301 server->stat.auth_failures++;
1305 entry->data.last_receive = time(NULL);
1307 switch (ctx->conn_type) {
1308 case SILC_SOCKET_TYPE_CLIENT:
1310 SilcClientEntry client;
1312 SILC_LOG_DEBUG(("Remote host is client"));
1313 SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
1316 /* Add the client to the client ID cache. The nickname and Client ID
1317 and other information is created after we have received NEW_CLIENT
1318 packet from client. */
1319 client = silc_idlist_add_client(server->local_list,
1320 NULL, NULL, NULL, NULL, NULL, sock);
1322 SILC_LOG_ERROR(("Could not add new client to cache"));
1323 silc_free(sock->user_data);
1324 silc_server_disconnect_remote(server, sock,
1325 "Server closed connection: "
1326 "Authentication failed");
1327 server->stat.auth_failures++;
1332 server->stat.my_clients++;
1333 server->stat.clients++;
1334 if (server->server_type == SILC_ROUTER)
1335 server->stat.cell_clients++;
1337 id_entry = (void *)client;
1340 case SILC_SOCKET_TYPE_SERVER:
1341 case SILC_SOCKET_TYPE_ROUTER:
1343 SilcServerEntry new_server;
1344 SilcServerConfigSectionServerConnection *conn =
1345 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1346 ctx->sconfig : ctx->rconfig;
1348 SILC_LOG_DEBUG(("Remote host is %s",
1349 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1350 "server" : (conn->backup_router ?
1351 "backup router" : "router")));
1352 SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
1353 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1354 "server" : (conn->backup_router ?
1355 "backup router" : "router")));
1357 /* Add the server into server cache. The server name and Server ID
1358 is updated after we have received NEW_SERVER packet from the
1359 server. We mark ourselves as router for this server if we really
1362 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1363 server->local_list : (conn->backup_router ?
1364 server->local_list :
1365 server->global_list)),
1367 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1368 SILC_SERVER : SILC_ROUTER),
1370 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1371 server->id_entry : (conn->backup_router ?
1372 server->id_entry : NULL)),
1375 SILC_LOG_ERROR(("Could not add new server to cache"));
1376 silc_free(sock->user_data);
1377 silc_server_disconnect_remote(server, sock,
1378 "Server closed connection: "
1379 "Authentication failed");
1380 server->stat.auth_failures++;
1385 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1386 server->stat.my_servers++;
1388 server->stat.my_routers++;
1389 server->stat.servers++;
1391 id_entry = (void *)new_server;
1393 /* If the incoming connection is router and marked as backup router
1394 then add it to be one of our backups */
1395 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && conn->backup_router) {
1396 silc_server_backup_add(server, new_server, conn->backup_replace_ip,
1397 conn->backup_replace_port, conn->backup_local);
1399 /* Change it back to SERVER type since that's what it really is. */
1400 if (conn->backup_local)
1401 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1403 new_server->server_type = SILC_BACKUP_ROUTER;
1406 /* Check whether this connection is to be our primary router connection
1407 if we do not already have the primary route. */
1408 if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1409 if (silc_server_config_is_primary_route(server->config) &&
1413 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1414 server->standalone = FALSE;
1415 if (!server->id_entry->router) {
1416 server->id_entry->router = id_entry;
1417 server->router = id_entry;
1427 sock->type = ctx->conn_type;
1429 /* Add the common data structure to the ID entry. */
1431 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1433 /* Add to sockets internal pointer for fast referencing */
1434 silc_free(sock->user_data);
1435 sock->user_data = id_entry;
1437 /* Connection has been fully established now. Everything is ok. */
1438 SILC_LOG_DEBUG(("New connection authenticated"));
1440 /* Perform keepalive. The `hb_context' will be freed automatically
1441 when finally calling the silc_socket_free function. XXX hardcoded
1443 hb_context = silc_calloc(1, sizeof(*hb_context));
1444 hb_context->server = server;
1445 silc_socket_set_heartbeat(sock, 600, hb_context,
1446 silc_server_perform_heartbeat,
1450 silc_schedule_task_del_by_callback(server->schedule,
1451 silc_server_failure_callback);
1452 silc_protocol_free(protocol);
1454 silc_packet_context_free(ctx->packet);
1456 silc_ske_free(ctx->ske);
1457 silc_free(ctx->dest_id);
1459 sock->protocol = NULL;
1462 /* This function is used to read packets from network and send packets to
1463 network. This is usually a generic task. */
1465 SILC_TASK_CALLBACK(silc_server_packet_process)
1467 SilcServer server = (SilcServer)context;
1468 SilcSocketConnection sock = server->sockets[fd];
1469 SilcIDListData idata;
1470 SilcCipher cipher = NULL;
1471 SilcHmac hmac = NULL;
1472 uint32 sequence = 0;
1478 SILC_LOG_DEBUG(("Processing packet"));
1480 /* Packet sending */
1482 if (type == SILC_TASK_WRITE) {
1483 /* Do not send data to disconnected connection */
1484 if (SILC_IS_DISCONNECTED(sock))
1487 server->stat.packets_sent++;
1489 if (sock->outbuf->data - sock->outbuf->head)
1490 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1492 /* Send the packet */
1493 ret = silc_packet_send(sock, TRUE);
1495 /* If returned -2 could not write to connection now, will do
1501 SILC_LOG_ERROR(("Error sending packet to connection "
1502 "%s:%d [%s]", sock->hostname, sock->port,
1503 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1504 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1505 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1510 /* The packet has been sent and now it is time to set the connection
1511 back to only for input. When there is again some outgoing data
1512 available for this connection it will be set for output as well.
1513 This call clears the output setting and sets it only for input. */
1514 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1515 SILC_UNSET_OUTBUF_PENDING(sock);
1517 silc_buffer_clear(sock->outbuf);
1521 /* Packet receiving */
1523 /* Read some data from connection */
1524 ret = silc_packet_receive(sock);
1528 SILC_LOG_ERROR(("Error receiving packet from connection "
1529 "%s:%d [%s] %s", sock->hostname, sock->port,
1530 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1531 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1532 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1533 "Router"), strerror(errno)));
1539 SILC_LOG_DEBUG(("Read EOF"));
1541 /* If connection is disconnecting already we will finally
1542 close the connection */
1543 if (SILC_IS_DISCONNECTING(sock)) {
1544 if (sock->user_data)
1545 silc_server_free_sock_user_data(server, sock);
1546 silc_server_close_connection(server, sock);
1550 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1551 SILC_SET_DISCONNECTING(sock);
1553 if (sock->user_data)
1554 silc_server_free_sock_user_data(server, sock);
1555 silc_server_close_connection(server, sock);
1559 /* If connection is disconnecting or disconnected we will ignore
1561 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1562 SILC_LOG_DEBUG(("Ignoring read data from disonnected connection"));
1566 server->stat.packets_received++;
1568 /* Get keys and stuff from ID entry */
1569 idata = (SilcIDListData)sock->user_data;
1571 cipher = idata->receive_key;
1572 hmac = idata->hmac_receive;
1573 sequence = idata->psn_receive;
1576 /* Process the packet. This will call the parser that will then
1577 decrypt and parse the packet. */
1578 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1579 TRUE : FALSE, cipher, hmac, sequence,
1580 silc_server_packet_parse, server);
1583 /* Parses whole packet, received earlier. */
1585 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1587 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1588 SilcServer server = (SilcServer)parse_ctx->context;
1589 SilcSocketConnection sock = parse_ctx->sock;
1590 SilcPacketContext *packet = parse_ctx->packet;
1591 SilcIDListData idata = (SilcIDListData)sock->user_data;
1594 SILC_LOG_DEBUG(("Start"));
1596 /* Parse the packet */
1597 if (parse_ctx->normal)
1598 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
1600 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
1602 /* If entry is disabled ignore what we got. */
1603 if (ret != SILC_PACKET_RESUME_ROUTER &&
1604 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1605 SILC_LOG_DEBUG(("Connection is disabled"));
1609 if (ret == SILC_PACKET_NONE)
1612 /* Check that the the current client ID is same as in the client's packet. */
1613 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1614 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1615 if (client && client->id) {
1616 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1617 packet->src_id_type);
1618 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1626 if (server->server_type == SILC_ROUTER) {
1627 /* Route the packet if it is not destined to us. Other ID types but
1628 server are handled separately after processing them. */
1629 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1630 packet->dst_id_type == SILC_ID_SERVER &&
1631 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1632 memcmp(packet->dst_id, server->id_string, packet->dst_id_len)) {
1634 /* Route the packet to fastest route for the destination ID */
1635 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1636 packet->dst_id_type);
1639 silc_server_packet_route(server,
1640 silc_server_route_get(server, id,
1641 packet->dst_id_type),
1648 /* Parse the incoming packet type */
1649 silc_server_packet_parse_type(server, sock, packet);
1651 if (server->server_type == SILC_ROUTER) {
1652 /* Broadcast packet if it is marked as broadcast packet and it is
1653 originated from router and we are router. */
1654 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1655 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1656 !server->standalone) {
1657 /* Broadcast to our primary route */
1658 silc_server_packet_broadcast(server, server->router->connection, packet);
1660 /* If we have backup routers then we need to feed all broadcast
1661 data to those servers. */
1662 silc_server_backup_broadcast(server, sock, packet);
1667 silc_packet_context_free(packet);
1668 silc_free(parse_ctx);
1671 /* Parser callback called by silc_packet_receive_process. This merely
1672 registers timeout that will handle the actual parsing when appropriate. */
1674 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
1677 SilcServer server = (SilcServer)context;
1678 SilcSocketConnection sock = parser_context->sock;
1679 SilcIDListData idata = (SilcIDListData)sock->user_data;
1682 idata->psn_receive = parser_context->packet->sequence + 1;
1684 /* If protocol for this connection is key exchange or rekey then we'll
1685 process all packets synchronously, since there might be packets in
1686 queue that we are not able to decrypt without first processing the
1687 packets before them. */
1688 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
1689 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
1690 (sock->protocol && sock->protocol->protocol &&
1691 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1692 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
1693 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1696 /* Reprocess data since we'll return FALSE here. This is because
1697 the idata->receive_key might have become valid in the last packet
1698 and we want to call this processor with valid cipher. */
1700 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1701 TRUE : FALSE, idata->receive_key,
1702 idata->hmac_receive, idata->psn_receive,
1703 silc_server_packet_parse, server);
1705 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1706 TRUE : FALSE, NULL, NULL, 0,
1707 silc_server_packet_parse, server);
1711 switch (sock->type) {
1712 case SILC_SOCKET_TYPE_UNKNOWN:
1713 case SILC_SOCKET_TYPE_CLIENT:
1714 /* Parse the packet with timeout */
1715 silc_schedule_task_add(server->schedule, sock->sock,
1716 silc_server_packet_parse_real,
1717 (void *)parser_context, 0, 100000,
1719 SILC_TASK_PRI_NORMAL);
1721 case SILC_SOCKET_TYPE_SERVER:
1722 case SILC_SOCKET_TYPE_ROUTER:
1723 /* Packets from servers are parsed immediately */
1724 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1734 /* Parses the packet type and calls what ever routines the packet type
1735 requires. This is done for all incoming packets. */
1737 void silc_server_packet_parse_type(SilcServer server,
1738 SilcSocketConnection sock,
1739 SilcPacketContext *packet)
1741 SilcPacketType type = packet->type;
1742 SilcIDListData idata = (SilcIDListData)sock->user_data;
1744 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1746 /* Parse the packet type */
1748 case SILC_PACKET_DISCONNECT:
1749 SILC_LOG_DEBUG(("Disconnect packet"));
1750 if (packet->flags & SILC_PACKET_FLAG_LIST)
1754 case SILC_PACKET_SUCCESS:
1756 * Success received for something. For now we can have only
1757 * one protocol for connection executing at once hence this
1758 * success message is for whatever protocol is executing currently.
1760 SILC_LOG_DEBUG(("Success packet"));
1761 if (packet->flags & SILC_PACKET_FLAG_LIST)
1764 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1767 case SILC_PACKET_FAILURE:
1769 * Failure received for something. For now we can have only
1770 * one protocol for connection executing at once hence this
1771 * failure message is for whatever protocol is executing currently.
1773 SILC_LOG_DEBUG(("Failure packet"));
1774 if (packet->flags & SILC_PACKET_FLAG_LIST)
1776 if (sock->protocol) {
1777 SilcServerFailureContext f;
1778 f = silc_calloc(1, sizeof(*f));
1782 /* We will wait 5 seconds to process this failure packet */
1783 silc_schedule_task_add(server->schedule, sock->sock,
1784 silc_server_failure_callback, (void *)f, 5, 0,
1785 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1789 case SILC_PACKET_REJECT:
1790 SILC_LOG_DEBUG(("Reject packet"));
1791 if (packet->flags & SILC_PACKET_FLAG_LIST)
1796 case SILC_PACKET_NOTIFY:
1798 * Received notify packet. Server can receive notify packets from
1799 * router. Server then relays the notify messages to clients if needed.
1801 SILC_LOG_DEBUG(("Notify packet"));
1802 if (packet->flags & SILC_PACKET_FLAG_LIST)
1803 silc_server_notify_list(server, sock, packet);
1805 silc_server_notify(server, sock, packet);
1811 case SILC_PACKET_CHANNEL_MESSAGE:
1813 * Received channel message. Channel messages are special packets
1814 * (although probably most common ones) thus they are handled
1817 SILC_LOG_DEBUG(("Channel Message packet"));
1818 if (packet->flags & SILC_PACKET_FLAG_LIST)
1820 idata->last_receive = time(NULL);
1821 silc_server_channel_message(server, sock, packet);
1824 case SILC_PACKET_CHANNEL_KEY:
1826 * Received key for channel. As channels are created by the router
1827 * the keys are as well. We will distribute the key to all of our
1828 * locally connected clients on the particular channel. Router
1829 * never receives this channel and thus is ignored.
1831 SILC_LOG_DEBUG(("Channel Key packet"));
1832 if (packet->flags & SILC_PACKET_FLAG_LIST)
1834 silc_server_channel_key(server, sock, packet);
1840 case SILC_PACKET_COMMAND:
1842 * Recived command. Processes the command request and allocates the
1843 * command context and calls the command.
1845 SILC_LOG_DEBUG(("Command packet"));
1846 if (packet->flags & SILC_PACKET_FLAG_LIST)
1848 silc_server_command_process(server, sock, packet);
1851 case SILC_PACKET_COMMAND_REPLY:
1853 * Received command reply packet. Received command reply to command. It
1854 * may be reply to command sent by us or reply to command sent by client
1855 * that we've routed further.
1857 SILC_LOG_DEBUG(("Command Reply packet"));
1858 if (packet->flags & SILC_PACKET_FLAG_LIST)
1860 silc_server_command_reply(server, sock, packet);
1864 * Private Message packets
1866 case SILC_PACKET_PRIVATE_MESSAGE:
1868 * Received private message packet. The packet is coming from either
1871 SILC_LOG_DEBUG(("Private Message packet"));
1872 if (packet->flags & SILC_PACKET_FLAG_LIST)
1874 idata->last_receive = time(NULL);
1875 silc_server_private_message(server, sock, packet);
1878 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1880 * Private message key packet.
1882 if (packet->flags & SILC_PACKET_FLAG_LIST)
1884 silc_server_private_message_key(server, sock, packet);
1888 * Key Exchange protocol packets
1890 case SILC_PACKET_KEY_EXCHANGE:
1891 SILC_LOG_DEBUG(("KE packet"));
1892 if (packet->flags & SILC_PACKET_FLAG_LIST)
1895 if (sock->protocol && sock->protocol->protocol &&
1896 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1898 SilcServerKEInternalContext *proto_ctx =
1899 (SilcServerKEInternalContext *)sock->protocol->context;
1901 proto_ctx->packet = silc_packet_context_dup(packet);
1903 /* Let the protocol handle the packet */
1904 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
1906 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1907 "protocol active, packet dropped."));
1911 case SILC_PACKET_KEY_EXCHANGE_1:
1912 SILC_LOG_DEBUG(("KE 1 packet"));
1913 if (packet->flags & SILC_PACKET_FLAG_LIST)
1916 if (sock->protocol && sock->protocol->protocol &&
1917 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1918 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
1920 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
1921 SilcServerRekeyInternalContext *proto_ctx =
1922 (SilcServerRekeyInternalContext *)sock->protocol->context;
1924 if (proto_ctx->packet)
1925 silc_packet_context_free(proto_ctx->packet);
1927 proto_ctx->packet = silc_packet_context_dup(packet);
1929 /* Let the protocol handle the packet */
1930 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1932 SilcServerKEInternalContext *proto_ctx =
1933 (SilcServerKEInternalContext *)sock->protocol->context;
1935 if (proto_ctx->packet)
1936 silc_packet_context_free(proto_ctx->packet);
1938 proto_ctx->packet = silc_packet_context_dup(packet);
1939 proto_ctx->dest_id_type = packet->src_id_type;
1940 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1941 packet->src_id_type);
1942 if (!proto_ctx->dest_id)
1945 /* Let the protocol handle the packet */
1946 silc_protocol_execute(sock->protocol, server->schedule,
1950 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1951 "protocol active, packet dropped."));
1955 case SILC_PACKET_KEY_EXCHANGE_2:
1956 SILC_LOG_DEBUG(("KE 2 packet"));
1957 if (packet->flags & SILC_PACKET_FLAG_LIST)
1960 if (sock->protocol && sock->protocol->protocol &&
1961 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1962 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
1964 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
1965 SilcServerRekeyInternalContext *proto_ctx =
1966 (SilcServerRekeyInternalContext *)sock->protocol->context;
1968 if (proto_ctx->packet)
1969 silc_packet_context_free(proto_ctx->packet);
1971 proto_ctx->packet = silc_packet_context_dup(packet);
1973 /* Let the protocol handle the packet */
1974 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1976 SilcServerKEInternalContext *proto_ctx =
1977 (SilcServerKEInternalContext *)sock->protocol->context;
1979 if (proto_ctx->packet)
1980 silc_packet_context_free(proto_ctx->packet);
1982 proto_ctx->packet = silc_packet_context_dup(packet);
1983 proto_ctx->dest_id_type = packet->src_id_type;
1984 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1985 packet->src_id_type);
1986 if (!proto_ctx->dest_id)
1989 /* Let the protocol handle the packet */
1990 silc_protocol_execute(sock->protocol, server->schedule,
1994 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1995 "protocol active, packet dropped."));
1999 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2001 * Connection authentication request packet. When we receive this packet
2002 * we will send to the other end information about our mandatory
2003 * authentication method for the connection. This packet maybe received
2006 SILC_LOG_DEBUG(("Connection authentication request packet"));
2007 if (packet->flags & SILC_PACKET_FLAG_LIST)
2009 silc_server_connection_auth_request(server, sock, packet);
2013 * Connection Authentication protocol packets
2015 case SILC_PACKET_CONNECTION_AUTH:
2016 /* Start of the authentication protocol. We receive here the
2017 authentication data and will verify it. */
2018 SILC_LOG_DEBUG(("Connection auth packet"));
2019 if (packet->flags & SILC_PACKET_FLAG_LIST)
2022 if (sock->protocol && sock->protocol->protocol->type
2023 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2025 SilcServerConnAuthInternalContext *proto_ctx =
2026 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2028 proto_ctx->packet = silc_packet_context_dup(packet);
2030 /* Let the protocol handle the packet */
2031 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2033 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2034 "protocol active, packet dropped."));
2038 case SILC_PACKET_NEW_ID:
2040 * Received New ID packet. This includes some new ID that has been
2041 * created. It may be for client, server or channel. This is the way
2042 * to distribute information about new registered entities in the
2045 SILC_LOG_DEBUG(("New ID packet"));
2046 if (packet->flags & SILC_PACKET_FLAG_LIST)
2047 silc_server_new_id_list(server, sock, packet);
2049 silc_server_new_id(server, sock, packet);
2052 case SILC_PACKET_NEW_CLIENT:
2054 * Received new client packet. This includes client information that
2055 * we will use to create initial client ID. After creating new
2056 * ID we will send it to the client.
2058 SILC_LOG_DEBUG(("New Client packet"));
2059 if (packet->flags & SILC_PACKET_FLAG_LIST)
2061 silc_server_new_client(server, sock, packet);
2064 case SILC_PACKET_NEW_SERVER:
2066 * Received new server packet. This includes Server ID and some other
2067 * information that we may save. This is received after server has
2070 SILC_LOG_DEBUG(("New Server packet"));
2071 if (packet->flags & SILC_PACKET_FLAG_LIST)
2073 silc_server_new_server(server, sock, packet);
2076 case SILC_PACKET_NEW_CHANNEL:
2078 * Received new channel packet. Information about new channel in the
2079 * network are distributed using this packet.
2081 SILC_LOG_DEBUG(("New Channel packet"));
2082 if (packet->flags & SILC_PACKET_FLAG_LIST)
2083 silc_server_new_channel_list(server, sock, packet);
2085 silc_server_new_channel(server, sock, packet);
2088 case SILC_PACKET_HEARTBEAT:
2090 * Received heartbeat.
2092 SILC_LOG_DEBUG(("Heartbeat packet"));
2093 if (packet->flags & SILC_PACKET_FLAG_LIST)
2097 case SILC_PACKET_KEY_AGREEMENT:
2099 * Received heartbeat.
2101 SILC_LOG_DEBUG(("Key agreement packet"));
2102 if (packet->flags & SILC_PACKET_FLAG_LIST)
2104 silc_server_key_agreement(server, sock, packet);
2107 case SILC_PACKET_REKEY:
2109 * Received re-key packet. The sender wants to regenerate the session
2112 SILC_LOG_DEBUG(("Re-key packet"));
2113 if (packet->flags & SILC_PACKET_FLAG_LIST)
2115 silc_server_rekey(server, sock, packet);
2118 case SILC_PACKET_REKEY_DONE:
2120 * The re-key is done.
2122 SILC_LOG_DEBUG(("Re-key done packet"));
2123 if (packet->flags & SILC_PACKET_FLAG_LIST)
2126 if (sock->protocol && sock->protocol->protocol &&
2127 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2129 SilcServerRekeyInternalContext *proto_ctx =
2130 (SilcServerRekeyInternalContext *)sock->protocol->context;
2132 if (proto_ctx->packet)
2133 silc_packet_context_free(proto_ctx->packet);
2135 proto_ctx->packet = silc_packet_context_dup(packet);
2137 /* Let the protocol handle the packet */
2138 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2140 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2141 "protocol active, packet dropped."));
2145 case SILC_PACKET_FTP:
2147 SILC_LOG_DEBUG(("FTP packet"));
2148 if (packet->flags & SILC_PACKET_FLAG_LIST)
2150 silc_server_ftp(server, sock, packet);
2153 case SILC_PACKET_RESUME_ROUTER:
2154 /* Resume router packet received. This packet is received for backup
2155 router resuming protocol. */
2156 SILC_LOG_DEBUG(("Resume router packet"));
2157 if (packet->flags & SILC_PACKET_FLAG_LIST)
2159 silc_server_backup_resume_router(server, sock, packet);
2163 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2169 /* Creates connection to a remote router. */
2171 void silc_server_create_connection(SilcServer server,
2172 char *remote_host, uint32 port)
2174 SilcServerConnection sconn;
2176 /* Allocate connection object for hold connection specific stuff. */
2177 sconn = silc_calloc(1, sizeof(*sconn));
2178 sconn->server = server;
2179 sconn->remote_host = strdup(remote_host);
2180 sconn->remote_port = port;
2182 silc_schedule_task_add(server->schedule, 0,
2183 silc_server_connect_router,
2184 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2185 SILC_TASK_PRI_NORMAL);
2188 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2190 silc_socket_free((SilcSocketConnection)context);
2193 /* Closes connection to socket connection */
2195 void silc_server_close_connection(SilcServer server,
2196 SilcSocketConnection sock)
2198 if (!server->sockets[sock->sock])
2201 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2203 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2204 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2205 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2208 /* We won't listen for this connection anymore */
2209 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2211 /* Unregister all tasks */
2212 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2214 /* Close the actual connection */
2215 silc_net_close_connection(sock->sock);
2216 server->sockets[sock->sock] = NULL;
2218 /* If sock->user_data is NULL then we'll check for active protocols
2219 here since the silc_server_free_sock_user_data has not been called
2220 for this connection. */
2221 if (!sock->user_data) {
2222 /* If any protocol is active cancel its execution. It will call
2223 the final callback which will finalize the disconnection. */
2224 if (sock->protocol) {
2225 silc_protocol_cancel(sock->protocol, server->schedule);
2226 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2227 silc_protocol_execute_final(sock->protocol, server->schedule);
2228 sock->protocol = NULL;
2233 silc_schedule_task_add(server->schedule, 0,
2234 silc_server_close_connection_final,
2235 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2236 SILC_TASK_PRI_NORMAL);
2239 /* Sends disconnect message to remote connection and disconnects the
2242 void silc_server_disconnect_remote(SilcServer server,
2243 SilcSocketConnection sock,
2244 const char *fmt, ...)
2247 unsigned char buf[4096];
2252 memset(buf, 0, sizeof(buf));
2254 vsprintf(buf, fmt, ap);
2257 SILC_LOG_DEBUG(("Disconnecting remote host"));
2259 /* Notify remote end that the conversation is over. The notify message
2260 is tried to be sent immediately. */
2261 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2262 buf, strlen(buf), TRUE);
2264 /* Mark the connection to be disconnected */
2265 SILC_SET_DISCONNECTED(sock);
2266 silc_server_close_connection(server, sock);
2271 SilcClientEntry client;
2272 } *FreeClientInternal;
2274 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2276 FreeClientInternal i = (FreeClientInternal)context;
2278 silc_idlist_del_data(i->client);
2279 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2283 /* Frees client data and notifies about client's signoff. */
2285 void silc_server_free_client_data(SilcServer server,
2286 SilcSocketConnection sock,
2287 SilcClientEntry client,
2291 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2293 /* If there is pending outgoing data for the client then purge it
2294 to the network before removing the client entry. */
2295 silc_server_packet_queue_purge(server, sock);
2300 /* Send SIGNOFF notify to routers. */
2301 if (notify && !server->standalone && server->router)
2302 silc_server_send_notify_signoff(server, server->router->connection,
2303 server->server_type == SILC_SERVER ?
2304 FALSE : TRUE, client->id, signoff);
2306 /* Remove client from all channels */
2308 silc_server_remove_from_channels(server, NULL, client,
2309 TRUE, signoff, TRUE);
2311 silc_server_remove_from_channels(server, NULL, client,
2312 FALSE, NULL, FALSE);
2314 /* We will not delete the client entry right away. We will take it
2315 into history (for WHOWAS command) for 5 minutes */
2318 silc_schedule_task_add(server->schedule, 0,
2319 silc_server_free_client_data_timeout,
2321 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2322 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2323 client->router = NULL;
2324 client->connection = NULL;
2326 /* Free the client entry and everything in it */
2327 server->stat.my_clients--;
2328 server->stat.clients--;
2329 if (server->server_type == SILC_ROUTER)
2330 server->stat.cell_clients--;
2333 /* Frees user_data pointer from socket connection object. This also sends
2334 appropriate notify packets to the network to inform about leaving
2337 void silc_server_free_sock_user_data(SilcServer server,
2338 SilcSocketConnection sock)
2340 SILC_LOG_DEBUG(("Start"));
2342 switch (sock->type) {
2343 case SILC_SOCKET_TYPE_CLIENT:
2345 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2346 silc_server_free_client_data(server, sock, user_data, TRUE, NULL);
2349 case SILC_SOCKET_TYPE_SERVER:
2350 case SILC_SOCKET_TYPE_ROUTER:
2352 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2353 SilcServerEntry backup_router = NULL;
2356 backup_router = silc_server_backup_get(server, user_data->id);
2358 /* If this was our primary router connection then we're lost to
2359 the outside world. */
2360 if (server->router == user_data) {
2361 /* Check whether we have a backup router connection */
2362 if (!backup_router || backup_router == user_data) {
2363 silc_schedule_task_add(server->schedule, 0,
2364 silc_server_connect_to_router,
2367 SILC_TASK_PRI_NORMAL);
2369 server->id_entry->router = NULL;
2370 server->router = NULL;
2371 server->standalone = TRUE;
2372 backup_router = NULL;
2374 SILC_LOG_INFO(("New primary router is backup router %s",
2375 backup_router->server_name));
2376 SILC_LOG_DEBUG(("New primary router is backup router %s",
2377 backup_router->server_name));
2378 server->id_entry->router = backup_router;
2379 server->router = backup_router;
2380 server->router_connect = time(0);
2381 server->backup_primary = TRUE;
2382 if (server->server_type == SILC_BACKUP_ROUTER) {
2383 server->server_type = SILC_ROUTER;
2385 /* We'll need to constantly try to reconnect to the primary
2386 router so that we'll see when it comes back online. */
2387 silc_server_backup_reconnect(server, sock->ip, sock->port,
2388 silc_server_backup_connected,
2392 /* Mark this connection as replaced */
2393 silc_server_backup_replaced_add(server, user_data->id,
2396 } else if (backup_router) {
2397 SILC_LOG_INFO(("Enabling the use of backup router %s",
2398 backup_router->server_name));
2399 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2400 backup_router->server_name));
2402 /* Mark this connection as replaced */
2403 silc_server_backup_replaced_add(server, user_data->id,
2407 if (!backup_router) {
2408 /* Free all client entries that this server owns as they will
2409 become invalid now as well. */
2411 silc_server_remove_clients_by_server(server, user_data, TRUE);
2412 if (server->server_type == SILC_SERVER)
2413 silc_server_remove_channels_by_server(server, user_data);
2415 /* Update the client entries of this server to the new backup
2416 router. This also removes the clients that *really* was owned
2417 by the primary router and went down with the router. */
2418 silc_server_update_clients_by_server(server, user_data, backup_router,
2420 silc_server_update_servers_by_server(server, user_data, backup_router);
2421 if (server->server_type == SILC_SERVER)
2422 silc_server_update_channels_by_server(server, user_data,
2426 /* Free the server entry */
2427 silc_server_backup_del(server, user_data);
2428 silc_server_backup_replaced_del(server, user_data);
2429 silc_idlist_del_data(user_data);
2430 if (!silc_idlist_del_server(server->local_list, user_data))
2431 silc_idlist_del_server(server->global_list, user_data);
2432 server->stat.my_servers--;
2433 server->stat.servers--;
2434 if (server->server_type == SILC_ROUTER)
2435 server->stat.cell_servers--;
2437 if (backup_router) {
2438 /* Announce all of our stuff that was created about 5 minutes ago.
2439 The backup router knows all the other stuff already. */
2440 if (server->server_type == SILC_ROUTER)
2441 silc_server_announce_servers(server, FALSE, time(0) - 300,
2442 backup_router->connection);
2444 /* Announce our clients and channels to the router */
2445 silc_server_announce_clients(server, time(0) - 300,
2446 backup_router->connection);
2447 silc_server_announce_channels(server, time(0) - 300,
2448 backup_router->connection);
2454 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2456 silc_idlist_del_data(user_data);
2457 silc_free(user_data);
2462 /* If any protocol is active cancel its execution */
2463 if (sock->protocol) {
2464 silc_protocol_cancel(sock->protocol, server->schedule);
2465 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2466 silc_protocol_execute_final(sock->protocol, server->schedule);
2467 sock->protocol = NULL;
2470 sock->user_data = NULL;
2473 /* Removes client from all channels it has joined. This is used when client
2474 connection is disconnected. If the client on a channel is last, the
2475 channel is removed as well. This sends the SIGNOFF notify types. */
2477 void silc_server_remove_from_channels(SilcServer server,
2478 SilcSocketConnection sock,
2479 SilcClientEntry client,
2481 char *signoff_message,
2484 SilcChannelEntry channel;
2485 SilcChannelClientEntry chl;
2486 SilcHashTableList htl;
2489 SILC_LOG_DEBUG(("Start"));
2491 if (!client || !client->id)
2494 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2496 /* Remove the client from all channels. The client is removed from
2497 the channels' user list. */
2498 silc_hash_table_list(client->channels, &htl);
2499 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2500 channel = chl->channel;
2502 /* Remove channel from client's channel list */
2503 silc_hash_table_del(client->channels, channel);
2505 /* Remove channel if there is no users anymore */
2506 if (server->server_type == SILC_ROUTER &&
2507 silc_hash_table_count(channel->user_list) < 2) {
2509 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2510 if (silc_idlist_del_channel(server->local_list, channel))
2511 server->stat.my_channels--;
2513 silc_idlist_del_channel(server->global_list, channel);
2517 /* Remove client from channel's client list */
2518 silc_hash_table_del(channel->user_list, chl->client);
2520 /* If there is no global users on the channel anymore mark the channel
2521 as local channel. Do not check if the removed client is local client. */
2522 if (server->server_type != SILC_ROUTER && channel->global_users &&
2523 chl->client->router && !silc_server_channel_has_global(channel))
2524 channel->global_users = FALSE;
2527 server->stat.my_chanclients--;
2529 /* If there is not at least one local user on the channel then we don't
2530 need the channel entry anymore, we can remove it safely. */
2531 if (server->server_type != SILC_ROUTER &&
2532 !silc_server_channel_has_local(channel)) {
2533 /* Notify about leaving client if this channel has global users. */
2534 if (notify && channel->global_users)
2535 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2536 SILC_NOTIFY_TYPE_SIGNOFF,
2537 signoff_message ? 2 : 1,
2538 clidp->data, clidp->len,
2539 signoff_message, signoff_message ?
2540 strlen(signoff_message) : 0);
2543 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2545 if (channel->founder_key) {
2546 /* The founder auth data exists, do not remove the channel entry */
2547 SilcChannelClientEntry chl2;
2548 SilcHashTableList htl2;
2550 channel->disabled = TRUE;
2552 silc_hash_table_list(channel->user_list, &htl2);
2553 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2554 silc_hash_table_del(chl2->client->channels, channel);
2555 silc_hash_table_del(channel->user_list, chl2->client);
2561 /* Remove the channel entry */
2562 if (silc_idlist_del_channel(server->local_list, channel))
2563 server->stat.my_channels--;
2565 silc_idlist_del_channel(server->global_list, channel);
2569 /* Send notify to channel about client leaving SILC and thus
2570 the entire channel. */
2572 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2573 SILC_NOTIFY_TYPE_SIGNOFF,
2574 signoff_message ? 2 : 1,
2575 clidp->data, clidp->len,
2576 signoff_message, signoff_message ?
2577 strlen(signoff_message) : 0);
2579 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2580 /* Re-generate channel key */
2581 if (!silc_server_create_channel_key(server, channel, 0))
2584 /* Send the channel key to the channel. The key of course is not sent
2585 to the client who was removed from the channel. */
2586 silc_server_send_channel_key(server, client->connection, channel,
2587 server->server_type == SILC_ROUTER ?
2588 FALSE : !server->standalone);
2592 silc_buffer_free(clidp);
2595 /* Removes client from one channel. This is used for example when client
2596 calls LEAVE command to remove itself from the channel. Returns TRUE
2597 if channel still exists and FALSE if the channel is removed when
2598 last client leaves the channel. If `notify' is FALSE notify messages
2601 int silc_server_remove_from_one_channel(SilcServer server,
2602 SilcSocketConnection sock,
2603 SilcChannelEntry channel,
2604 SilcClientEntry client,
2607 SilcChannelClientEntry chl;
2610 SILC_LOG_DEBUG(("Start"));
2612 /* Get the entry to the channel, if this client is not on the channel
2614 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2617 /* Remove the client from the channel. The client is removed from
2618 the channel's user list. */
2620 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2622 /* Remove channel from client's channel list */
2623 silc_hash_table_del(client->channels, chl->channel);
2625 /* Remove channel if there is no users anymore */
2626 if (server->server_type == SILC_ROUTER &&
2627 silc_hash_table_count(channel->user_list) < 2) {
2629 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2630 if (silc_idlist_del_channel(server->local_list, channel))
2631 server->stat.my_channels--;
2633 silc_idlist_del_channel(server->global_list, channel);
2634 silc_buffer_free(clidp);
2638 /* Remove client from channel's client list */
2639 silc_hash_table_del(channel->user_list, chl->client);
2641 /* If there is no global users on the channel anymore mark the channel
2642 as local channel. Do not check if the client is local client. */
2643 if (server->server_type != SILC_ROUTER && channel->global_users &&
2644 chl->client->router && !silc_server_channel_has_global(channel))
2645 channel->global_users = FALSE;
2648 server->stat.my_chanclients--;
2650 /* If there is not at least one local user on the channel then we don't
2651 need the channel entry anymore, we can remove it safely. */
2652 if (server->server_type != SILC_ROUTER &&
2653 !silc_server_channel_has_local(channel)) {
2654 /* Notify about leaving client if this channel has global users. */
2655 if (notify && channel->global_users)
2656 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2657 SILC_NOTIFY_TYPE_LEAVE, 1,
2658 clidp->data, clidp->len);
2660 silc_buffer_free(clidp);
2663 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2665 if (channel->founder_key) {
2666 /* The founder auth data exists, do not remove the channel entry */
2667 SilcChannelClientEntry chl2;
2668 SilcHashTableList htl2;
2670 channel->disabled = TRUE;
2672 silc_hash_table_list(channel->user_list, &htl2);
2673 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2674 silc_hash_table_del(chl2->client->channels, channel);
2675 silc_hash_table_del(channel->user_list, chl2->client);
2681 /* Remove the channel entry */
2682 if (silc_idlist_del_channel(server->local_list, channel))
2683 server->stat.my_channels--;
2685 silc_idlist_del_channel(server->global_list, channel);
2689 /* Send notify to channel about client leaving the channel */
2691 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2692 SILC_NOTIFY_TYPE_LEAVE, 1,
2693 clidp->data, clidp->len);
2695 silc_buffer_free(clidp);
2699 /* Timeout callback. This is called if connection is idle or for some
2700 other reason is not responding within some period of time. This
2701 disconnects the remote end. */
2703 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2705 SilcServer server = (SilcServer)context;
2706 SilcSocketConnection sock = server->sockets[fd];
2708 SILC_LOG_DEBUG(("Start"));
2713 /* If we have protocol active we must assure that we call the protocol's
2714 final callback so that all the memory is freed. */
2715 if (sock->protocol) {
2716 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2717 silc_protocol_execute_final(sock->protocol, server->schedule);
2721 if (sock->user_data)
2722 silc_server_free_sock_user_data(server, sock);
2724 silc_server_disconnect_remote(server, sock, "Server closed connection: "
2725 "Connection timeout");
2728 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2729 function may be used only by router. In real SILC network all channels
2730 are created by routers thus this function is never used by normal
2733 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2734 SilcServerID *router_id,
2740 SilcChannelID *channel_id;
2741 SilcChannelEntry entry;
2745 SILC_LOG_DEBUG(("Creating new channel"));
2748 cipher = SILC_DEFAULT_CIPHER;
2750 hmac = SILC_DEFAULT_HMAC;
2752 /* Allocate cipher */
2753 if (!silc_cipher_alloc(cipher, &key))
2757 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2758 silc_cipher_free(key);
2762 channel_name = strdup(channel_name);
2764 /* Create the channel */
2765 if (!silc_id_create_channel_id(server, router_id, server->rng,
2767 silc_free(channel_name);
2768 silc_cipher_free(key);
2769 silc_hmac_free(newhmac);
2772 entry = silc_idlist_add_channel(server->local_list, channel_name,
2773 SILC_CHANNEL_MODE_NONE, channel_id,
2774 NULL, key, newhmac);
2776 silc_free(channel_name);
2777 silc_cipher_free(key);
2778 silc_hmac_free(newhmac);
2782 entry->cipher = strdup(cipher);
2783 entry->hmac_name = strdup(hmac);
2785 /* Now create the actual key material */
2786 if (!silc_server_create_channel_key(server, entry,
2787 silc_cipher_get_key_len(key) / 8)) {
2788 silc_free(channel_name);
2789 silc_cipher_free(key);
2790 silc_hmac_free(newhmac);
2791 silc_free(entry->cipher);
2792 silc_free(entry->hmac_name);
2796 /* Notify other routers about the new channel. We send the packet
2797 to our primary route. */
2798 if (broadcast && server->standalone == FALSE)
2799 silc_server_send_new_channel(server, server->router->connection, TRUE,
2800 channel_name, entry->id,
2801 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2804 server->stat.my_channels++;
2809 /* Same as above but creates the channel with Channel ID `channel_id. */
2812 silc_server_create_new_channel_with_id(SilcServer server,
2816 SilcChannelID *channel_id,
2819 SilcChannelEntry entry;
2823 SILC_LOG_DEBUG(("Creating new channel"));
2826 cipher = SILC_DEFAULT_CIPHER;
2828 hmac = SILC_DEFAULT_HMAC;
2830 /* Allocate cipher */
2831 if (!silc_cipher_alloc(cipher, &key))
2835 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2836 silc_cipher_free(key);
2840 channel_name = strdup(channel_name);
2842 /* Create the channel */
2843 entry = silc_idlist_add_channel(server->local_list, channel_name,
2844 SILC_CHANNEL_MODE_NONE, channel_id,
2845 NULL, key, newhmac);
2847 silc_free(channel_name);
2851 /* Now create the actual key material */
2852 if (!silc_server_create_channel_key(server, entry,
2853 silc_cipher_get_key_len(key) / 8)) {
2854 silc_free(channel_name);
2858 /* Notify other routers about the new channel. We send the packet
2859 to our primary route. */
2860 if (broadcast && server->standalone == FALSE)
2861 silc_server_send_new_channel(server, server->router->connection, TRUE,
2862 channel_name, entry->id,
2863 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2866 server->stat.my_channels++;
2871 /* Channel's key re-key timeout callback. */
2873 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
2875 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
2876 SilcServer server = (SilcServer)rekey->context;
2880 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
2883 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
2886 /* Generates new channel key. This is used to create the initial channel key
2887 but also to re-generate new key for channel. If `key_len' is provided
2888 it is the bytes of the key length. */
2890 bool silc_server_create_channel_key(SilcServer server,
2891 SilcChannelEntry channel,
2895 unsigned char channel_key[32], hash[32];
2898 SILC_LOG_DEBUG(("Generating channel key"));
2900 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
2901 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
2905 if (!channel->channel_key)
2906 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
2907 channel->channel_key = NULL;
2913 else if (channel->key_len)
2914 len = channel->key_len / 8;
2916 len = silc_cipher_get_key_len(channel->channel_key) / 8;
2918 /* Create channel key */
2919 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
2922 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
2924 /* Remove old key if exists */
2926 memset(channel->key, 0, channel->key_len / 8);
2927 silc_free(channel->key);
2931 channel->key_len = len * 8;
2932 channel->key = silc_calloc(len, sizeof(*channel->key));
2933 memcpy(channel->key, channel_key, len);
2934 memset(channel_key, 0, sizeof(channel_key));
2936 /* Generate HMAC key from the channel key data and set it */
2938 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
2939 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
2940 silc_hmac_set_key(channel->hmac, hash,
2941 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
2942 memset(hash, 0, sizeof(hash));
2944 if (server->server_type == SILC_ROUTER) {
2945 if (!channel->rekey)
2946 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
2947 channel->rekey->context = (void *)server;
2948 channel->rekey->channel = channel;
2949 channel->rekey->key_len = key_len;
2950 if (channel->rekey->task)
2951 silc_schedule_task_del(server->schedule, channel->rekey->task);
2953 channel->rekey->task =
2954 silc_schedule_task_add(server->schedule, 0,
2955 silc_server_channel_key_rekey,
2956 (void *)channel->rekey, 3600, 0,
2958 SILC_TASK_PRI_NORMAL);
2964 /* Saves the channel key found in the encoded `key_payload' buffer. This
2965 function is used when we receive Channel Key Payload and also when we're
2966 processing JOIN command reply. Returns entry to the channel. */
2968 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
2969 SilcBuffer key_payload,
2970 SilcChannelEntry channel)
2972 SilcChannelKeyPayload payload = NULL;
2973 SilcChannelID *id = NULL;
2974 unsigned char *tmp, hash[32];
2978 SILC_LOG_DEBUG(("Start"));
2980 /* Decode channel key payload */
2981 payload = silc_channel_key_payload_parse(key_payload);
2983 SILC_LOG_ERROR(("Bad channel key payload, dropped"));
2988 /* Get the channel entry */
2991 /* Get channel ID */
2992 tmp = silc_channel_key_get_id(payload, &tmp_len);
2993 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
2999 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3001 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3003 SILC_LOG_ERROR(("Received key for non-existent channel"));
3009 tmp = silc_channel_key_get_key(payload, &tmp_len);
3015 cipher = silc_channel_key_get_cipher(payload, NULL);
3021 /* Remove old key if exists */
3023 memset(channel->key, 0, channel->key_len / 8);
3024 silc_free(channel->key);
3025 silc_cipher_free(channel->channel_key);
3028 /* Create new cipher */
3029 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3030 channel->channel_key = NULL;
3035 if (channel->cipher)
3036 silc_free(channel->cipher);
3037 channel->cipher = strdup(cipher);
3040 channel->key_len = tmp_len * 8;
3041 channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
3042 memcpy(channel->key, tmp, tmp_len);
3043 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3045 /* Generate HMAC key from the channel key data and set it */
3047 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3048 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3049 silc_hmac_set_key(channel->hmac, hash,
3050 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3052 memset(hash, 0, sizeof(hash));
3053 memset(tmp, 0, tmp_len);
3055 if (server->server_type == SILC_ROUTER) {
3056 if (!channel->rekey)
3057 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3058 channel->rekey->context = (void *)server;
3059 channel->rekey->channel = channel;
3060 if (channel->rekey->task)
3061 silc_schedule_task_del(server->schedule, channel->rekey->task);
3063 channel->rekey->task =
3064 silc_schedule_task_add(server->schedule, 0,
3065 silc_server_channel_key_rekey,
3066 (void *)channel->rekey, 3600, 0,
3068 SILC_TASK_PRI_NORMAL);
3074 silc_channel_key_payload_free(payload);
3079 /* Heartbeat callback. This function is set as argument for the
3080 silc_socket_set_heartbeat function. The library will call this function
3081 at the set time interval. */
3083 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3086 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3088 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname,
3091 /* Send the heartbeat */
3092 silc_server_send_heartbeat(hb->server, sock);
3095 /* Returns assembled of all servers in the given ID list. The packet's
3096 form is dictated by the New ID payload. */
3098 static void silc_server_announce_get_servers(SilcServer server,
3099 SilcServerEntry remote,
3101 SilcBuffer *servers,
3102 unsigned long creation_time)
3104 SilcIDCacheList list;
3105 SilcIDCacheEntry id_cache;
3106 SilcServerEntry entry;
3109 /* Go through all clients in the list */
3110 if (silc_idcache_get_all(id_list->servers, &list)) {
3111 if (silc_idcache_list_first(list, &id_cache)) {
3113 entry = (SilcServerEntry)id_cache->context;
3115 /* Do not announce the one we've sending our announcements and
3116 do not announce ourself. Also check the creation time if it's
3118 if ((entry == remote) || (entry == server->id_entry) ||
3119 (creation_time && entry->data.created < creation_time)) {
3120 if (!silc_idcache_list_next(list, &id_cache))
3125 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3127 *servers = silc_buffer_realloc(*servers,
3129 (*servers)->truelen + idp->len :
3131 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3132 silc_buffer_put(*servers, idp->data, idp->len);
3133 silc_buffer_pull(*servers, idp->len);
3134 silc_buffer_free(idp);
3136 if (!silc_idcache_list_next(list, &id_cache))
3141 silc_idcache_list_free(list);
3145 /* This function is used by router to announce existing servers to our
3146 primary router when we've connected to it. If `creation_time' is non-zero
3147 then only the servers that has been created after the `creation_time'
3148 will be announced. */
3150 void silc_server_announce_servers(SilcServer server, bool global,
3151 unsigned long creation_time,
3152 SilcSocketConnection remote)
3154 SilcBuffer servers = NULL;
3156 SILC_LOG_DEBUG(("Announcing servers"));
3158 /* Get servers in local list */
3159 silc_server_announce_get_servers(server, remote->user_data,
3160 server->local_list, &servers,
3164 /* Get servers in global list */
3165 silc_server_announce_get_servers(server, remote->user_data,
3166 server->global_list, &servers,
3170 silc_buffer_push(servers, servers->data - servers->head);
3171 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3173 /* Send the packet */
3174 silc_server_packet_send(server, remote,
3175 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3176 servers->data, servers->len, TRUE);
3178 silc_buffer_free(servers);
3182 /* Returns assembled packet of all clients in the given ID list. The
3183 packet's form is dictated by the New ID Payload. */
3185 static void silc_server_announce_get_clients(SilcServer server,
3187 SilcBuffer *clients,
3188 unsigned long creation_time)
3190 SilcIDCacheList list;
3191 SilcIDCacheEntry id_cache;
3192 SilcClientEntry client;
3195 /* Go through all clients in the list */
3196 if (silc_idcache_get_all(id_list->clients, &list)) {
3197 if (silc_idcache_list_first(list, &id_cache)) {
3199 client = (SilcClientEntry)id_cache->context;
3201 if (creation_time && client->data.created < creation_time) {
3202 if (!silc_idcache_list_next(list, &id_cache))
3207 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3209 *clients = silc_buffer_realloc(*clients,
3211 (*clients)->truelen + idp->len :
3213 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3214 silc_buffer_put(*clients, idp->data, idp->len);
3215 silc_buffer_pull(*clients, idp->len);
3216 silc_buffer_free(idp);
3218 if (!silc_idcache_list_next(list, &id_cache))
3223 silc_idcache_list_free(list);
3227 /* This function is used to announce our existing clients to our router
3228 when we've connected to it. If `creation_time' is non-zero then only
3229 the clients that has been created after the `creation_time' will be
3232 void silc_server_announce_clients(SilcServer server,
3233 unsigned long creation_time,
3234 SilcSocketConnection remote)
3236 SilcBuffer clients = NULL;
3238 SILC_LOG_DEBUG(("Announcing clients"));
3240 /* Get clients in local list */
3241 silc_server_announce_get_clients(server, server->local_list,
3242 &clients, creation_time);
3244 /* As router we announce our global list as well */
3245 if (server->server_type == SILC_ROUTER)
3246 silc_server_announce_get_clients(server, server->global_list,
3247 &clients, creation_time);
3250 silc_buffer_push(clients, clients->data - clients->head);
3251 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3253 /* Send the packet */
3254 silc_server_packet_send(server, remote,
3255 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3256 clients->data, clients->len, TRUE);
3258 silc_buffer_free(clients);
3263 silc_server_announce_encode_notify(SilcNotifyType notify, uint32 argc, ...)
3269 p = silc_notify_payload_encode(notify, argc, ap);
3275 /* Returns assembled packets for channel users of the `channel'. */
3277 void silc_server_announce_get_channel_users(SilcServer server,
3278 SilcChannelEntry channel,
3279 SilcBuffer *channel_users,
3280 SilcBuffer *channel_users_modes)
3282 SilcChannelClientEntry chl;
3283 SilcHashTableList htl;
3284 SilcBuffer chidp, clidp;
3287 unsigned char mode[4];
3289 SILC_LOG_DEBUG(("Start"));
3291 /* Now find all users on the channel */
3292 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3293 silc_hash_table_list(channel->user_list, &htl);
3294 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3295 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3298 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3299 clidp->data, clidp->len,
3300 chidp->data, chidp->len);
3303 silc_buffer_realloc(*channel_users,
3305 (*channel_users)->truelen + len : len));
3306 silc_buffer_pull_tail(*channel_users,
3307 ((*channel_users)->end -
3308 (*channel_users)->data));
3310 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3311 silc_buffer_pull(*channel_users, len);
3312 silc_buffer_free(tmp);
3314 /* CUMODE notify for mode change on the channel */
3315 SILC_PUT32_MSB(chl->mode, mode);
3316 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3317 3, clidp->data, clidp->len,
3319 clidp->data, clidp->len);
3321 *channel_users_modes =
3322 silc_buffer_realloc(*channel_users_modes,
3323 (*channel_users_modes ?
3324 (*channel_users_modes)->truelen + len : len));
3325 silc_buffer_pull_tail(*channel_users_modes,
3326 ((*channel_users_modes)->end -
3327 (*channel_users_modes)->data));
3329 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3330 silc_buffer_pull(*channel_users_modes, len);
3331 silc_buffer_free(tmp);
3333 silc_buffer_free(clidp);
3335 silc_buffer_free(chidp);
3338 /* Returns assembled packets for all channels and users on those channels
3339 from the given ID List. The packets are in the form dictated by the
3340 New Channel and New Channel User payloads. */
3342 void silc_server_announce_get_channels(SilcServer server,
3344 SilcBuffer *channels,
3345 SilcBuffer *channel_users,
3346 SilcBuffer **channel_users_modes,
3347 uint32 *channel_users_modes_c,
3348 SilcChannelID ***channel_ids,
3349 unsigned long creation_time)
3351 SilcIDCacheList list;
3352 SilcIDCacheEntry id_cache;
3353 SilcChannelEntry channel;
3358 int i = *channel_users_modes_c;
3361 SILC_LOG_DEBUG(("Start"));
3363 /* Go through all channels in the list */
3364 if (silc_idcache_get_all(id_list->channels, &list)) {
3365 if (silc_idcache_list_first(list, &id_cache)) {
3367 channel = (SilcChannelEntry)id_cache->context;
3369 if (creation_time && channel->created < creation_time)
3374 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3375 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3376 name_len = strlen(channel->channel_name);
3379 len = 4 + name_len + id_len + 4;
3381 silc_buffer_realloc(*channels,
3382 (*channels ? (*channels)->truelen +
3384 silc_buffer_pull_tail(*channels,
3385 ((*channels)->end - (*channels)->data));
3386 silc_buffer_format(*channels,
3387 SILC_STR_UI_SHORT(name_len),
3388 SILC_STR_UI_XNSTRING(channel->channel_name,
3390 SILC_STR_UI_SHORT(id_len),
3391 SILC_STR_UI_XNSTRING(cid, id_len),
3392 SILC_STR_UI_INT(channel->mode),
3394 silc_buffer_pull(*channels, len);
3397 *channel_users_modes = silc_realloc(*channel_users_modes,
3398 sizeof(**channel_users_modes) *
3400 (*channel_users_modes)[i] = NULL;
3401 *channel_ids = silc_realloc(*channel_ids,
3402 sizeof(**channel_ids) * (i + 1));
3403 (*channel_ids)[i] = NULL;
3404 silc_server_announce_get_channel_users(server, channel,
3406 &(*channel_users_modes)[i]);
3407 (*channel_ids)[i] = channel->id;
3410 if (!silc_idcache_list_next(list, &id_cache))
3414 *channel_users_modes_c += i;
3417 silc_idcache_list_free(list);
3421 /* This function is used to announce our existing channels to our router
3422 when we've connected to it. This also announces the users on the
3423 channels to the router. If the `creation_time' is non-zero only the
3424 channels that was created after the `creation_time' are announced.
3425 Note that the channel users are still announced even if the `creation_time'
3428 void silc_server_announce_channels(SilcServer server,
3429 unsigned long creation_time,
3430 SilcSocketConnection remote)
3432 SilcBuffer channels = NULL, channel_users = NULL;
3433 SilcBuffer *channel_users_modes = NULL;
3434 uint32 channel_users_modes_c = 0;
3435 SilcChannelID **channel_ids = NULL;
3437 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3439 /* Get channels and channel users in local list */
3440 silc_server_announce_get_channels(server, server->local_list,
3441 &channels, &channel_users,
3442 &channel_users_modes,
3443 &channel_users_modes_c,
3444 &channel_ids, creation_time);
3446 /* Get channels and channel users in global list */
3447 if (server->server_type != SILC_SERVER)
3448 silc_server_announce_get_channels(server, server->global_list,
3449 &channels, &channel_users,
3450 &channel_users_modes,
3451 &channel_users_modes_c,
3452 &channel_ids, creation_time);
3455 silc_buffer_push(channels, channels->data - channels->head);
3456 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3458 /* Send the packet */
3459 silc_server_packet_send(server, remote,
3460 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3461 channels->data, channels->len,
3464 silc_buffer_free(channels);
3467 if (channel_users) {
3468 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3469 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3470 channel_users->len);
3472 /* Send the packet */
3473 silc_server_packet_send(server, remote,
3474 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3475 channel_users->data, channel_users->len,
3478 silc_buffer_free(channel_users);
3481 if (channel_users_modes) {
3484 for (i = 0; i < channel_users_modes_c; i++) {
3485 silc_buffer_push(channel_users_modes[i],
3486 channel_users_modes[i]->data -
3487 channel_users_modes[i]->head);
3488 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3489 channel_users_modes[i]->len);
3490 silc_server_packet_send_dest(server, remote,
3491 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3492 channel_ids[i], SILC_ID_CHANNEL,
3493 channel_users_modes[i]->data,
3494 channel_users_modes[i]->len,
3496 silc_buffer_free(channel_users_modes[i]);
3498 silc_free(channel_users_modes);
3499 silc_free(channel_ids);
3503 /* Failure timeout callback. If this is called then we will immediately
3504 process the received failure. We always process the failure with timeout
3505 since we do not want to blindly trust to received failure packets.
3506 This won't be called (the timeout is cancelled) if the failure was
3507 bogus (it is bogus if remote does not close the connection after sending
3510 SILC_TASK_CALLBACK(silc_server_failure_callback)
3512 SilcServerFailureContext f = (SilcServerFailureContext)context;
3514 if (f->sock->protocol) {
3515 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3516 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3522 /* Assembles user list and users mode list from the `channel'. */
3524 void silc_server_get_users_on_channel(SilcServer server,
3525 SilcChannelEntry channel,
3526 SilcBuffer *user_list,
3527 SilcBuffer *mode_list,
3530 SilcChannelClientEntry chl;
3531 SilcHashTableList htl;
3532 SilcBuffer client_id_list;
3533 SilcBuffer client_mode_list;
3535 uint32 list_count = 0, len = 0;
3537 silc_hash_table_list(channel->user_list, &htl);
3538 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3539 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3541 client_id_list = silc_buffer_alloc(len);
3543 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3544 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3545 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3547 silc_hash_table_list(channel->user_list, &htl);
3548 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3550 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3551 silc_buffer_put(client_id_list, idp->data, idp->len);
3552 silc_buffer_pull(client_id_list, idp->len);
3553 silc_buffer_free(idp);
3555 /* Client's mode on channel */
3556 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3557 silc_buffer_pull(client_mode_list, 4);
3561 silc_buffer_push(client_id_list,
3562 client_id_list->data - client_id_list->head);
3563 silc_buffer_push(client_mode_list,
3564 client_mode_list->data - client_mode_list->head);
3566 *user_list = client_id_list;
3567 *mode_list = client_mode_list;
3568 *user_count = list_count;
3571 /* Saves users and their modes to the `channel'. */
3573 void silc_server_save_users_on_channel(SilcServer server,
3574 SilcSocketConnection sock,
3575 SilcChannelEntry channel,
3576 SilcClientID *noadd,
3577 SilcBuffer user_list,
3578 SilcBuffer mode_list,
3583 for (i = 0; i < user_count; i++) {
3586 SilcClientID *client_id;
3587 SilcClientEntry client;
3590 SILC_GET16_MSB(idp_len, user_list->data + 2);
3592 client_id = silc_id_payload_parse_id(user_list->data, idp_len);
3593 silc_buffer_pull(user_list, idp_len);
3598 SILC_GET32_MSB(mode, mode_list->data);
3599 silc_buffer_pull(mode_list, 4);
3601 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3602 silc_free(client_id);
3606 /* Check if we have this client cached already. */
3607 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3608 server->server_type, NULL);
3610 client = silc_idlist_find_client_by_id(server->global_list,
3611 client_id, server->server_type,
3614 /* If router did not find such Client ID in its lists then this must
3615 be bogus client or some router in the net is buggy. */
3616 if (server->server_type == SILC_ROUTER) {
3617 silc_free(client_id);
3621 /* We don't have that client anywhere, add it. The client is added
3622 to global list since server didn't have it in the lists so it must be
3624 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3625 silc_id_dup(client_id, SILC_ID_CLIENT),
3626 sock->user_data, NULL);
3628 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3629 silc_free(client_id);
3633 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3636 silc_free(client_id);
3638 if (!silc_server_client_on_channel(client, channel)) {
3639 /* Client was not on the channel, add it. */
3640 SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3641 chl->client = client;
3643 chl->channel = channel;
3644 silc_hash_table_add(channel->user_list, chl->client, chl);
3645 silc_hash_table_add(client->channels, chl->channel, chl);
3650 /* Lookups route to the client indicated by the `id_data'. The connection
3651 object and internal data object is returned. Returns NULL if route
3652 could not be found to the client. If the `client_id' is specified then
3653 it is used and the `id_data' is ignored. */
3655 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3656 unsigned char *id_data,
3658 SilcClientID *client_id,
3659 SilcIDListData *idata)
3662 SilcClientEntry client;
3664 SILC_LOG_DEBUG(("Start"));
3666 /* Decode destination Client ID */
3668 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3670 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3674 id = silc_id_dup(client_id, SILC_ID_CLIENT);
3677 /* If the destination belongs to our server we don't have to route
3678 the packet anywhere but to send it to the local destination. */
3679 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
3683 /* If we are router and the client has router then the client is in
3684 our cell but not directly connected to us. */
3685 if (server->server_type == SILC_ROUTER && client->router) {
3686 /* We are of course in this case the client's router thus the route
3687 to the client is the server who owns the client. So, we will send
3688 the packet to that server. */
3690 *idata = (SilcIDListData)client->router;
3691 return client->router->connection;
3694 /* Seems that client really is directly connected to us */
3696 *idata = (SilcIDListData)client;
3697 return client->connection;
3700 /* Destination belongs to someone not in this server. If we are normal
3701 server our action is to send the packet to our router. */
3702 if (server->server_type != SILC_ROUTER && !server->standalone) {
3705 *idata = (SilcIDListData)server->router;
3706 return server->router->connection;
3709 /* We are router and we will perform route lookup for the destination
3710 and send the packet to fastest route. */
3711 if (server->server_type == SILC_ROUTER && !server->standalone) {
3712 /* Check first that the ID is valid */
3713 client = silc_idlist_find_client_by_id(server->global_list, id,
3716 SilcSocketConnection dst_sock;
3718 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
3722 *idata = (SilcIDListData)dst_sock->user_data;
3731 /* Encodes and returns channel list of channels the `client' has joined.
3732 Secret channels are not put to the list. */
3734 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
3735 SilcClientEntry client)
3737 SilcBuffer buffer = NULL;
3738 SilcChannelEntry channel;
3739 SilcChannelClientEntry chl;
3740 SilcHashTableList htl;
3746 silc_hash_table_list(client->channels, &htl);
3747 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3748 channel = chl->channel;
3750 if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
3751 channel->mode & SILC_CHANNEL_MODE_PRIVATE)
3754 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3755 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3756 name_len = strlen(channel->channel_name);
3758 len = 4 + name_len + id_len + 4;
3759 buffer = silc_buffer_realloc(buffer,
3760 (buffer ? (buffer)->truelen + len : len));
3761 silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
3762 silc_buffer_format(buffer,
3763 SILC_STR_UI_SHORT(name_len),
3764 SILC_STR_UI_XNSTRING(channel->channel_name,
3766 SILC_STR_UI_SHORT(id_len),
3767 SILC_STR_UI_XNSTRING(cid, id_len),
3768 SILC_STR_UI_INT(chl->mode), /* Client's mode */
3770 silc_buffer_pull(buffer, len);
3775 silc_buffer_push(buffer, buffer->data - buffer->head);
3780 /* Finds client entry by Client ID and if it is not found then resolves
3781 it using WHOIS command. */
3783 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
3784 SilcClientID *client_id)
3786 SilcClientEntry client;
3788 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3791 client = silc_idlist_find_client_by_id(server->global_list,
3792 client_id, TRUE, NULL);
3793 if (!client && server->server_type == SILC_ROUTER)
3797 if (!client && server->standalone)
3800 if (!client || !client->nickname || !client->username) {
3801 SilcBuffer buffer, idp;
3803 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
3804 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
3805 client->resolve_cmd_ident = ++server->cmd_ident;
3807 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3808 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
3809 server->cmd_ident, 1,
3810 3, idp->data, idp->len);
3811 silc_server_packet_send(server, client ? client->router->connection :
3812 server->router->connection,
3813 SILC_PACKET_COMMAND, 0,
3814 buffer->data, buffer->len, FALSE);
3815 silc_buffer_free(idp);
3816 silc_buffer_free(buffer);
3823 /* A timeout callback for the re-key. We will be the initiator of the
3826 SILC_TASK_CALLBACK(silc_server_rekey_callback)
3828 SilcSocketConnection sock = (SilcSocketConnection)context;
3829 SilcIDListData idata = (SilcIDListData)sock->user_data;
3830 SilcServer server = (SilcServer)idata->rekey->context;
3831 SilcProtocol protocol;
3832 SilcServerRekeyInternalContext *proto_ctx;
3834 SILC_LOG_DEBUG(("Start"));
3836 /* Allocate internal protocol context. This is sent as context
3838 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
3839 proto_ctx->server = (void *)server;
3840 proto_ctx->sock = sock;
3841 proto_ctx->responder = FALSE;
3842 proto_ctx->pfs = idata->rekey->pfs;
3844 /* Perform rekey protocol. Will call the final callback after the
3845 protocol is over. */
3846 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
3847 &protocol, proto_ctx, silc_server_rekey_final);
3848 sock->protocol = protocol;
3850 /* Run the protocol */
3851 silc_protocol_execute(protocol, server->schedule, 0, 0);
3853 /* Re-register re-key timeout */
3854 silc_schedule_task_add(server->schedule, sock->sock,
3855 silc_server_rekey_callback,
3856 context, idata->rekey->timeout, 0,
3857 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
3860 /* The final callback for the REKEY protocol. This will actually take the
3861 new key material into use. */
3863 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
3865 SilcProtocol protocol = (SilcProtocol)context;
3866 SilcServerRekeyInternalContext *ctx =
3867 (SilcServerRekeyInternalContext *)protocol->context;
3868 SilcServer server = (SilcServer)ctx->server;
3869 SilcSocketConnection sock = ctx->sock;
3871 SILC_LOG_DEBUG(("Start"));
3873 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
3874 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
3875 /* Error occured during protocol */
3876 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
3877 silc_protocol_cancel(protocol, server->schedule);
3878 silc_protocol_free(protocol);
3879 sock->protocol = NULL;
3881 silc_packet_context_free(ctx->packet);
3883 silc_ske_free(ctx->ske);
3888 /* Purge the outgoing data queue to assure that all rekey packets really
3889 go to the network before we quit the protocol. */
3890 silc_server_packet_queue_purge(server, sock);
3893 silc_protocol_free(protocol);
3894 sock->protocol = NULL;
3896 silc_packet_context_free(ctx->packet);
3898 silc_ske_free(ctx->ske);