5 Author: Pekka Riikonen <priikone@poseidon.pspt.fi>
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);
43 /* Allocates a new SILC server object. This has to be done before the server
44 can be used. After allocation one must call silc_server_init to initialize
45 the server. The new allocated server object is returned to the new_server
48 int silc_server_alloc(SilcServer *new_server)
52 SILC_LOG_DEBUG(("Allocating new server object"));
54 server = silc_calloc(1, sizeof(*server));
55 server->server_type = SILC_SERVER;
56 server->standalone = TRUE;
57 server->local_list = silc_calloc(1, sizeof(*server->local_list));
58 server->global_list = silc_calloc(1, sizeof(*server->global_list));
59 server->pending_commands = silc_dlist_init();
61 server->sim = silc_dlist_init();
69 /* Free's the SILC server object. This is called at the very end before
72 void silc_server_free(SilcServer server)
79 if (server->local_list)
80 silc_free(server->local_list);
81 if (server->global_list)
82 silc_free(server->global_list);
84 silc_rng_free(server->rng);
87 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
88 silc_dlist_del(server->sim, sim);
91 silc_dlist_uninit(server->sim);
95 silc_free(server->params);
97 if (server->pending_commands)
98 silc_dlist_uninit(server->pending_commands);
104 /* Initializes the entire SILC server. This is called always before running
105 the server. This is called only once at the initialization of the program.
106 This binds the server to its listenning port. After this function returns
107 one should call silc_server_run to start the server. This returns TRUE
108 when everything is ok to run the server. Configuration file must be
109 read and parsed before calling this. */
111 int silc_server_init(SilcServer server)
113 int *sock = NULL, sock_count = 0, i;
115 SilcServerEntry id_entry;
117 SILC_LOG_DEBUG(("Initializing server"));
119 assert(server->config);
121 /* XXX After server is made as Silc Server Library this can be given
122 as argument, for now this is hard coded */
123 server->params = silc_calloc(1, sizeof(*server->params));
124 server->params->retry_count = SILC_SERVER_RETRY_COUNT;
125 server->params->retry_interval_min = SILC_SERVER_RETRY_INTERVAL_MIN;
126 server->params->retry_interval_max = SILC_SERVER_RETRY_INTERVAL_MAX;
127 server->params->retry_keep_trying = FALSE;
128 server->params->protocol_timeout = 60;
129 server->params->require_reverse_mapping = FALSE;
131 /* Set log files where log message should be saved. */
132 server->config->server = server;
133 silc_server_config_setlogfiles(server->config);
135 /* Register all configured ciphers, PKCS and hash functions. */
136 silc_server_config_register_ciphers(server->config);
137 silc_server_config_register_pkcs(server->config);
138 silc_server_config_register_hashfuncs(server->config);
139 silc_server_config_register_hmacs(server->config);
141 /* Initialize random number generator for the server. */
142 server->rng = silc_rng_alloc();
143 silc_rng_init(server->rng);
144 silc_rng_global_init(server->rng);
146 /* Initialize hash functions for server to use */
147 silc_hash_alloc("md5", &server->md5hash);
148 silc_hash_alloc("sha1", &server->sha1hash);
150 /* Initialize none cipher */
151 silc_cipher_alloc("none", &server->none_cipher);
153 /* XXXXX Generate RSA key pair */
155 unsigned char *public_key;
156 unsigned char *private_key;
157 unsigned int pk_len, prv_len;
160 if (stat("pubkey.pub", &st) < 0 && stat("privkey.prv", &st) < 0) {
162 if (silc_pkcs_alloc("rsa", &server->pkcs) == FALSE) {
163 SILC_LOG_ERROR(("Could not create RSA key pair"));
167 if (server->pkcs->pkcs->init(server->pkcs->context,
168 1024, server->rng) == FALSE) {
169 SILC_LOG_ERROR(("Could not generate RSA key pair"));
173 public_key = server->pkcs->pkcs->get_public_key(server->pkcs->context,
175 private_key = server->pkcs->pkcs->get_private_key(server->pkcs->context,
178 SILC_LOG_HEXDUMP(("public key"), public_key, pk_len);
179 SILC_LOG_HEXDUMP(("private key"), private_key, prv_len);
182 silc_pkcs_public_key_alloc("rsa", "UN=root, HN=dummy",
184 server->private_key =
185 silc_pkcs_private_key_alloc("rsa", private_key, prv_len);
188 silc_pkcs_save_public_key("pubkey.pub", server->public_key,
190 silc_pkcs_save_private_key("privkey.prv", server->private_key, NULL,
193 memset(public_key, 0, pk_len);
194 memset(private_key, 0, prv_len);
195 silc_free(public_key);
196 silc_free(private_key);
198 silc_pkcs_load_public_key("pubkey.pub", &server->public_key,
200 silc_pkcs_load_private_key("privkey.prv", &server->private_key,
205 /* Create a listening server. Note that our server can listen on
206 multiple ports. All listeners are created here and now. */
207 /* XXX Still check this whether to use server_info or listen_port. */
209 while(server->config->listen_port) {
212 tmp = silc_net_create_server(server->config->listen_port->port,
213 server->config->listen_port->host);
217 sock = silc_realloc(sock, (sizeof(int *) * (sock_count + 1)));
218 sock[sock_count] = tmp;
219 server->config->listen_port = server->config->listen_port->next;
223 /* Initialize ID caches */
224 server->local_list->clients = silc_idcache_alloc(0);
225 server->local_list->servers = silc_idcache_alloc(0);
226 server->local_list->channels = silc_idcache_alloc(0);
228 /* These are allocated for normal server as well as these hold some
229 global information that the server has fetched from its router. For
230 router these are used as they are supposed to be used on router. */
231 server->global_list->clients = silc_idcache_alloc(0);
232 server->global_list->servers = silc_idcache_alloc(0);
233 server->global_list->channels = silc_idcache_alloc(0);
235 /* Allocate the entire socket list that is used in server. Eventually
236 all connections will have entry in this table (it is a table of
237 pointers to the actual object that is allocated individually
239 server->sockets = silc_calloc(SILC_SERVER_MAX_CONNECTIONS,
240 sizeof(*server->sockets));
242 for (i = 0; i < sock_count; i++) {
243 SilcSocketConnection newsocket = NULL;
245 /* Set socket to non-blocking mode */
246 silc_net_set_socket_nonblock(sock[i]);
247 server->sock = sock[i];
249 /* Create a Server ID for the server. */
250 silc_id_create_server_id(sock[i], server->rng, &id);
256 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
257 server->id_string_len = silc_id_get_len(SILC_ID_SERVER);
258 server->id_type = SILC_ID_SERVER;
259 server->server_name = server->config->server_info->server_name;
261 /* Add ourselves to the server list. We don't have a router yet
262 beacuse we haven't established a route yet. It will be done later.
263 For now, NULL is sent as router. This allocates new entry to
266 silc_idlist_add_server(server->local_list,
267 server->config->server_info->server_name,
268 server->server_type, server->id, NULL, NULL);
270 SILC_LOG_ERROR(("Could not add ourselves to cache"));
274 /* Add ourselves also to the socket table. The entry allocated above
275 is sent as argument for fast referencing in the future. */
276 silc_socket_alloc(sock[i], SILC_SOCKET_TYPE_SERVER, id_entry,
279 server->sockets[sock[i]] = newsocket;
281 /* Put the allocated socket pointer also to the entry allocated above
282 for fast back-referencing to the socket list. */
283 id_entry->connection = (void *)server->sockets[sock[i]];
284 server->id_entry = id_entry;
287 /* Register the task queues. In SILC we have by default three task queues.
288 One task queue for non-timeout tasks which perform different kind of
289 I/O on file descriptors, timeout task queue for timeout tasks, and,
290 generic non-timeout task queue whose tasks apply to all connections. */
291 silc_task_queue_alloc(&server->io_queue, TRUE);
292 if (!server->io_queue) {
295 silc_task_queue_alloc(&server->timeout_queue, TRUE);
296 if (!server->timeout_queue) {
299 silc_task_queue_alloc(&server->generic_queue, TRUE);
300 if (!server->generic_queue) {
304 /* Register protocols */
305 silc_server_protocols_register();
307 /* Initialize the scheduler */
308 silc_schedule_init(&server->io_queue, &server->timeout_queue,
309 &server->generic_queue,
310 SILC_SERVER_MAX_CONNECTIONS);
312 /* Add the first task to the queue. This is task that is executed by
313 timeout. It expires as soon as the caller calls silc_server_run. This
314 task performs authentication protocol and key exchange with our
316 silc_task_register(server->timeout_queue, sock[0],
317 silc_server_connect_to_router,
318 (void *)server, 0, 1,
320 SILC_TASK_PRI_NORMAL);
322 /* Add listener task to the queue. This task receives new connections to the
323 server. This task remains on the queue until the end of the program. */
324 silc_task_register(server->io_queue, sock[0],
325 silc_server_accept_new_connection,
326 (void *)server, 0, 0,
328 SILC_TASK_PRI_NORMAL);
329 server->listenning = TRUE;
331 /* If server connections has been configured then we must be router as
332 normal server cannot have server connections, only router connections. */
333 if (server->config->servers)
334 server->server_type = SILC_ROUTER;
336 SILC_LOG_DEBUG(("Server initialized"));
338 /* We are done here, return succesfully */
341 silc_task_queue_free(server->timeout_queue);
343 silc_task_queue_free(server->io_queue);
345 for (i = 0; i < sock_count; i++)
346 silc_net_close_server(sock[i]);
351 /* Fork server to background and set gid+uid to non-root.
352 Silcd will not run as root, so trying to set either user or group to
353 root will cause silcd to exit. */
355 void silc_server_daemonise(SilcServer server)
357 /* Are we executing silcd as root or a regular user? */
364 if (!server->config->identity || !server->config->identity->user ||
365 !server->config->identity->group) {
366 fprintf(stderr, "Error:"
367 "\tSILC server must not be run as root. For the security of your\n"
368 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
369 "\tuser account. Modify the [Identity] configuration section to run\n"
370 "\tthe server as non-root user.\n");
374 /* Get the values given for user and group in configuration file */
375 user=server->config->identity->user;
376 group=server->config->identity->group;
378 /* Check whether the user/group information is text */
379 if (atoi(user)!=0 || atoi(group)!=0) {
380 SILC_LOG_DEBUG(("Invalid user and/or group information"));
381 SILC_LOG_DEBUG(("User and/or group given as number"));
382 fprintf(stderr, "Invalid user and/or group information\n");
383 fprintf(stderr, "Please assign them as names, not numbers\n");
387 /* Catch the nasty incident of string "0" returning 0 from atoi */
388 if (strcmp("0", user)==0 || strcmp("0", group)==0) {
389 SILC_LOG_DEBUG(("User and/or group configured to 0. Unacceptable"));
390 fprintf(stderr, "User and/or group configured to 0. Exiting\n");
398 fprintf(stderr, "No such user %s found\n", user);
403 fprintf(stderr, "No such group %s found\n", group);
407 /* Check whether user and/or group is set to root. If yes, exit
408 immediately. Otherwise, setgid and setuid server to user.group */
409 if (gr->gr_gid==0 || pw->pw_uid==0) {
410 fprintf(stderr, "Error:"
411 "\tSILC server must not be run as root. For the security of your\n"
412 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
413 "\tuser account. Modify the [Identity] configuration section to run\n"
414 "\tthe server as non-root user.\n");
417 /* Fork server to background, making it a daemon */
419 SILC_LOG_DEBUG(("Server started as root. Dropping privileges."));
420 SILC_LOG_DEBUG(("Forking SILC server to background"));
425 SILC_LOG_DEBUG(("Changing to group %s", group));
426 if(setgid(gr->gr_gid)==0) {
427 SILC_LOG_DEBUG(("Setgid to %s", group));
429 SILC_LOG_DEBUG(("Setgid to %s failed", group));
430 fprintf(stderr, "Tried to setgid %s but no such group. Exiting\n",
434 SILC_LOG_DEBUG(("Changing to user nobody"));
435 if(setuid(pw->pw_uid)==0) {
436 SILC_LOG_DEBUG(("Setuid to %s", user));
438 SILC_LOG_DEBUG(("Setuid to %s failed", user));
439 fprintf(stderr, "Tried to setuid %s but no such user. Exiting\n",
445 /* Fork server to background, making it a daemon */
447 SILC_LOG_DEBUG(("Server started as user"));
448 SILC_LOG_DEBUG(("Forking SILC server to background"));
455 /* Stops the SILC server. This function is used to shutdown the server.
456 This is usually called after the scheduler has returned. After stopping
457 the server one should call silc_server_free. */
459 void silc_server_stop(SilcServer server)
461 SILC_LOG_DEBUG(("Stopping server"));
463 /* Stop the scheduler, although it might be already stopped. This
464 doesn't hurt anyone. This removes all the tasks and task queues,
466 silc_schedule_stop();
467 silc_schedule_uninit();
469 silc_server_protocols_unregister();
471 SILC_LOG_DEBUG(("Server stopped"));
474 /* The heart of the server. This runs the scheduler thus runs the server.
475 When this returns the server has been stopped and the program will
478 void silc_server_run(SilcServer server)
480 SILC_LOG_DEBUG(("Running server"));
482 /* Start the scheduler, the heart of the SILC server. When this returns
483 the program will be terminated. */
487 /* Timeout callback that will be called to retry connecting to remote
488 router. This is used by both normal and router server. This will wait
489 before retrying the connecting. The timeout is generated by exponential
490 backoff algorithm. */
492 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
494 SilcServerConnection sconn = (SilcServerConnection)context;
495 SilcServer server = sconn->server;
497 SILC_LOG_INFO(("Retrying connecting to a router"));
499 /* Calculate next timeout */
500 if (sconn->retry_count >= 1) {
501 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
502 if (sconn->retry_timeout > SILC_SERVER_RETRY_INTERVAL_MAX)
503 sconn->retry_timeout = SILC_SERVER_RETRY_INTERVAL_MAX;
505 sconn->retry_timeout = server->params->retry_interval_min;
507 sconn->retry_count++;
508 sconn->retry_timeout = sconn->retry_timeout +
509 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
511 /* If we've reached max retry count, give up. */
512 if (sconn->retry_count > server->params->retry_count &&
513 server->params->retry_keep_trying == FALSE) {
514 SILC_LOG_ERROR(("Could not connect to router, giving up"));
518 /* Wait one before retrying */
519 silc_task_register(server->timeout_queue, fd, silc_server_connect_router,
520 context, sconn->retry_timeout,
521 server->params->retry_interval_min_usec,
522 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
525 /* Generic routine to use connect to a router. */
527 SILC_TASK_CALLBACK(silc_server_connect_router)
529 SilcServerConnection sconn = (SilcServerConnection)context;
530 SilcServer server = sconn->server;
531 SilcSocketConnection newsocket;
532 SilcProtocol protocol;
533 SilcServerKEInternalContext *proto_ctx;
536 /* Connect to remote host */
537 sock = silc_net_create_connection(sconn->remote_port,
540 SILC_LOG_ERROR(("Could not connect to router"));
541 silc_task_register(server->timeout_queue, fd,
542 silc_server_connect_to_router_retry,
543 context, 0, 1, SILC_TASK_TIMEOUT,
544 SILC_TASK_PRI_NORMAL);
548 /* Set socket options */
549 silc_net_set_socket_nonblock(sock);
550 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
552 /* Create socket connection for the connection. Even though we
553 know that we are connecting to a router we will mark the socket
554 to be unknown connection until we have executed authentication
556 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
557 server->sockets[sock] = newsocket;
558 newsocket->hostname = strdup(sconn->remote_host);
559 newsocket->ip = strdup(sconn->remote_host);
560 newsocket->port = sconn->remote_port;
561 sconn->sock = newsocket;
563 /* Allocate internal protocol context. This is sent as context
565 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
566 proto_ctx->server = (void *)server;
567 proto_ctx->context = (void *)sconn;
568 proto_ctx->sock = newsocket;
569 proto_ctx->rng = server->rng;
570 proto_ctx->responder = FALSE;
572 /* Perform key exchange protocol. silc_server_connect_to_router_second
573 will be called after the protocol is finished. */
574 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
575 &protocol, proto_ctx,
576 silc_server_connect_to_router_second);
577 newsocket->protocol = protocol;
579 /* Register a timeout task that will be executed if the protocol
580 is not executed within set limit. */
581 proto_ctx->timeout_task =
582 silc_task_register(server->timeout_queue, sock,
583 silc_server_timeout_remote,
584 server, server->params->protocol_timeout,
585 server->params->protocol_timeout_usec,
589 /* Register the connection for network input and output. This sets
590 that scheduler will listen for incoming packets for this connection
591 and sets that outgoing packets may be sent to this connection as
592 well. However, this doesn't set the scheduler for outgoing traffic,
593 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
594 later when outgoing data is available. */
595 context = (void *)server;
596 SILC_REGISTER_CONNECTION_FOR_IO(sock);
598 /* Run the protocol */
599 protocol->execute(server->timeout_queue, 0, protocol, sock, 0, 0);
602 /* This function connects to our primary router or if we are a router this
603 establishes all our primary routes. This is called at the start of the
604 server to do authentication and key exchange with our router - called
607 SILC_TASK_CALLBACK(silc_server_connect_to_router)
609 SilcServer server = (SilcServer)context;
610 SilcServerConnection sconn;
612 SILC_LOG_DEBUG(("Connecting to router(s)"));
614 /* If we are normal SILC server we need to connect to our cell's
616 if (server->server_type == SILC_SERVER) {
617 SILC_LOG_DEBUG(("We are normal server"));
619 /* Create connection to the router, if configured. */
620 if (server->config->routers) {
622 /* Allocate connection object for hold connection specific stuff. */
623 sconn = silc_calloc(1, sizeof(*sconn));
624 sconn->server = server;
625 sconn->remote_host = strdup(server->config->routers->host);
626 sconn->remote_port = server->config->routers->port;
628 silc_task_register(server->timeout_queue, fd,
629 silc_server_connect_router,
630 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
631 SILC_TASK_PRI_NORMAL);
636 /* If we are a SILC router we need to establish all of our primary
638 if (server->server_type == SILC_ROUTER) {
639 SilcServerConfigSectionServerConnection *ptr;
641 SILC_LOG_DEBUG(("We are router"));
643 /* Create the connections to all our routes */
644 ptr = server->config->routers;
647 SILC_LOG_DEBUG(("Router connection [%s] %s:%d",
648 ptr->initiator ? "Initiator" : "Responder",
649 ptr->host, ptr->port));
651 if (ptr->initiator) {
652 /* Allocate connection object for hold connection specific stuff. */
653 sconn = silc_calloc(1, sizeof(*sconn));
654 sconn->server = server;
655 sconn->remote_host = strdup(ptr->host);
656 sconn->remote_port = ptr->port;
658 silc_task_register(server->timeout_queue, fd,
659 silc_server_connect_router,
660 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
661 SILC_TASK_PRI_NORMAL);
671 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
673 /* There wasn't a configured router, we will continue but we don't
674 have a connection to outside world. We will be standalone server. */
675 server->standalone = TRUE;
678 /* Second part of connecting to router(s). Key exchange protocol has been
679 executed and now we will execute authentication protocol. */
681 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
683 SilcProtocol protocol = (SilcProtocol)context;
684 SilcServerKEInternalContext *ctx =
685 (SilcServerKEInternalContext *)protocol->context;
686 SilcServer server = (SilcServer)ctx->server;
687 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
688 SilcSocketConnection sock = NULL;
689 SilcServerConnAuthInternalContext *proto_ctx;
691 SILC_LOG_DEBUG(("Start"));
693 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
694 /* Error occured during protocol */
695 silc_protocol_free(protocol);
696 silc_ske_free_key_material(ctx->keymat);
698 silc_packet_context_free(ctx->packet);
700 silc_ske_free(ctx->ske);
702 silc_free(ctx->dest_id);
704 silc_task_unregister_by_callback(server->timeout_queue,
705 silc_server_failure_callback);
706 silc_server_disconnect_remote(server, sock, "Server closed connection: "
707 "Key exchange failed");
711 /* We now have the key material as the result of the key exchange
712 protocol. Take the key material into use. Free the raw key material
713 as soon as we've set them into use. */
714 if (!silc_server_protocol_ke_set_keys(ctx->ske, ctx->sock, ctx->keymat,
715 ctx->ske->prop->cipher,
716 ctx->ske->prop->pkcs,
717 ctx->ske->prop->hash,
718 ctx->ske->prop->hmac,
720 silc_protocol_free(protocol);
721 silc_ske_free_key_material(ctx->keymat);
723 silc_packet_context_free(ctx->packet);
725 silc_ske_free(ctx->ske);
727 silc_free(ctx->dest_id);
729 silc_task_unregister_by_callback(server->timeout_queue,
730 silc_server_failure_callback);
731 silc_server_disconnect_remote(server, sock, "Server closed connection: "
732 "Key exchange failed");
735 silc_ske_free_key_material(ctx->keymat);
737 /* Allocate internal context for the authentication protocol. This
738 is sent as context for the protocol. */
739 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
740 proto_ctx->server = (void *)server;
741 proto_ctx->context = (void *)sconn;
742 proto_ctx->sock = sock = server->sockets[fd];
743 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
744 proto_ctx->dest_id_type = ctx->dest_id_type;
745 proto_ctx->dest_id = ctx->dest_id;
747 /* Resolve the authentication method used in this connection */
748 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
749 if (server->config->routers) {
750 SilcServerConfigSectionServerConnection *conn = NULL;
752 /* Check if we find a match from user configured connections */
753 conn = silc_server_config_find_router_conn(server->config,
757 /* Match found. Use the configured authentication method */
758 proto_ctx->auth_meth = conn->auth_meth;
759 if (conn->auth_data) {
760 proto_ctx->auth_data = strdup(conn->auth_data);
761 proto_ctx->auth_data_len = strlen(conn->auth_data);
764 /* No match found. */
771 /* Free old protocol as it is finished now */
772 silc_protocol_free(protocol);
774 silc_packet_context_free(ctx->packet);
776 sock->protocol = NULL;
778 /* Allocate the authentication protocol. This is allocated here
779 but we won't start it yet. We will be receiving party of this
780 protocol thus we will wait that connecting party will make
782 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
783 &sock->protocol, proto_ctx,
784 silc_server_connect_to_router_final);
786 /* Register timeout task. If the protocol is not executed inside
787 this timelimit the connection will be terminated. Currently
788 this is 15 seconds and is hard coded limit (XXX). */
789 proto_ctx->timeout_task =
790 silc_task_register(server->timeout_queue, sock->sock,
791 silc_server_timeout_remote,
792 (void *)server, 15, 0,
796 /* Run the protocol */
797 sock->protocol->execute(server->timeout_queue, 0,
798 sock->protocol, sock->sock, 0, 0);
801 /* Finalizes the connection to router. Registers a server task to the
802 queue so that we can accept new connections. */
804 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
806 SilcProtocol protocol = (SilcProtocol)context;
807 SilcServerConnAuthInternalContext *ctx =
808 (SilcServerConnAuthInternalContext *)protocol->context;
809 SilcServer server = (SilcServer)ctx->server;
810 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
811 SilcSocketConnection sock = ctx->sock;
812 SilcServerEntry id_entry;
814 SilcServerHBContext hb_context;
815 unsigned char *id_string;
817 SILC_LOG_DEBUG(("Start"));
819 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
820 /* Error occured during protocol */
822 silc_free(ctx->dest_id);
823 silc_server_disconnect_remote(server, sock, "Server closed connection: "
824 "Authentication failed");
828 /* Add a task to the queue. This task receives new connections to the
829 server. This task remains on the queue until the end of the program. */
830 if (!server->listenning) {
831 silc_task_register(server->io_queue, server->sock,
832 silc_server_accept_new_connection,
833 (void *)server, 0, 0,
835 SILC_TASK_PRI_NORMAL);
836 server->listenning = TRUE;
839 /* Send NEW_SERVER packet to the router. We will become registered
840 to the SILC network after sending this packet. */
841 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
842 packet = silc_buffer_alloc(2 + 2 + SILC_ID_SERVER_LEN +
843 strlen(server->server_name));
844 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
845 silc_buffer_format(packet,
846 SILC_STR_UI_SHORT(SILC_ID_SERVER_LEN),
847 SILC_STR_UI_XNSTRING(id_string, SILC_ID_SERVER_LEN),
848 SILC_STR_UI_SHORT(strlen(server->server_name)),
849 SILC_STR_UI_XNSTRING(server->server_name,
850 strlen(server->server_name)),
853 /* Send the packet */
854 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
855 packet->data, packet->len, TRUE);
856 silc_buffer_free(packet);
857 silc_free(id_string);
859 SILC_LOG_DEBUG(("Connected to router %s", sock->hostname));
861 /* Add the connected router to local server list */
862 server->standalone = FALSE;
863 id_entry = silc_idlist_add_server(server->local_list, sock->hostname,
864 SILC_ROUTER, ctx->dest_id, NULL, sock);
867 silc_free(ctx->dest_id);
868 silc_server_disconnect_remote(server, sock, "Server closed connection: "
869 "Authentication failed");
873 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
874 silc_free(sock->user_data);
875 sock->user_data = (void *)id_entry;
876 sock->type = SILC_SOCKET_TYPE_ROUTER;
877 server->id_entry->router = id_entry;
878 server->router = id_entry;
879 server->router->data.registered = TRUE;
881 /* Perform keepalive. The `hb_context' will be freed automatically
882 when finally calling the silc_socket_free function. XXX hardcoded
884 hb_context = silc_calloc(1, sizeof(*hb_context));
885 hb_context->server = server;
886 silc_socket_set_heartbeat(sock, 600, hb_context,
887 silc_server_perform_heartbeat,
888 server->timeout_queue);
890 /* If we are router then announce our possible servers. */
891 if (server->server_type == SILC_ROUTER)
892 silc_server_announce_servers(server);
894 /* Announce our clients and channels to the router */
895 silc_server_announce_clients(server);
896 silc_server_announce_channels(server);
899 /* Free the temporary connection data context */
901 silc_free(sconn->remote_host);
905 /* Free the protocol object */
906 silc_protocol_free(protocol);
908 silc_packet_context_free(ctx->packet);
910 silc_ske_free(ctx->ske);
912 sock->protocol = NULL;
915 /* Accepts new connections to the server. Accepting new connections are
916 done in three parts to make it async. */
918 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
920 SilcServer server = (SilcServer)context;
921 SilcSocketConnection newsocket;
922 SilcServerKEInternalContext *proto_ctx;
925 SILC_LOG_DEBUG(("Accepting new connection"));
927 server->stat.conn_attempts++;
929 sock = silc_net_accept_connection(server->sock);
931 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
932 server->stat.conn_failures++;
936 /* Check max connections */
937 if (sock > SILC_SERVER_MAX_CONNECTIONS) {
938 if (server->config->redirect) {
939 /* XXX Redirecting connection to somewhere else now?? */
940 /*silc_server_send_notify("Server is full, trying to redirect..."); */
942 SILC_LOG_ERROR(("Refusing connection, server is full"));
943 server->stat.conn_failures++;
948 /* Set socket options */
949 silc_net_set_socket_nonblock(sock);
950 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
952 /* We don't create a ID yet, since we don't know what type of connection
953 this is yet. But, we do add the connection to the socket table. */
954 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
955 server->sockets[sock] = newsocket;
957 /* XXX This MUST be done async as this will block the entire server
958 process. Either we have to do our own resolver stuff or in the future
959 we can use threads. */
960 /* Perform name and address lookups for the remote host. */
961 silc_net_check_host_by_sock(sock, &newsocket->hostname, &newsocket->ip);
962 if ((server->params->require_reverse_mapping && !newsocket->hostname) ||
964 SILC_LOG_ERROR(("IP/DNS lookup failed"));
965 server->stat.conn_failures++;
968 if (!newsocket->hostname)
969 newsocket->hostname = strdup(newsocket->ip);
970 newsocket->port = silc_net_get_remote_port(sock);
972 SILC_LOG_INFO(("Incoming connection from %s (%s)", newsocket->hostname,
975 /* Allocate internal context for key exchange protocol. This is
976 sent as context for the protocol. */
977 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
978 proto_ctx->server = context;
979 proto_ctx->sock = newsocket;
980 proto_ctx->rng = server->rng;
981 proto_ctx->responder = TRUE;
983 /* Prepare the connection for key exchange protocol. We allocate the
984 protocol but will not start it yet. The connector will be the
985 initiator of the protocol thus we will wait for initiation from
986 there before we start the protocol. */
987 server->stat.auth_attempts++;
988 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
989 &newsocket->protocol, proto_ctx,
990 silc_server_accept_new_connection_second);
992 /* Register a timeout task that will be executed if the connector
993 will not start the key exchange protocol within 60 seconds. For
994 now, this is a hard coded limit. After 60 secs the connection will
995 be closed if the key exchange protocol has not been started. */
996 proto_ctx->timeout_task =
997 silc_task_register(server->timeout_queue, newsocket->sock,
998 silc_server_timeout_remote,
1003 /* Register the connection for network input and output. This sets
1004 that scheduler will listen for incoming packets for this connection
1005 and sets that outgoing packets may be sent to this connection as well.
1006 However, this doesn't set the scheduler for outgoing traffic, it
1007 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1008 later when outgoing data is available. */
1009 SILC_REGISTER_CONNECTION_FOR_IO(sock);
1012 /* Second part of accepting new connection. Key exchange protocol has been
1013 performed and now it is time to do little connection authentication
1014 protocol to figure out whether this connection is client or server
1015 and whether it has right to access this server (especially server
1016 connections needs to be authenticated). */
1018 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1020 SilcProtocol protocol = (SilcProtocol)context;
1021 SilcServerKEInternalContext *ctx =
1022 (SilcServerKEInternalContext *)protocol->context;
1023 SilcServer server = (SilcServer)ctx->server;
1024 SilcSocketConnection sock = NULL;
1025 SilcServerConnAuthInternalContext *proto_ctx;
1027 SILC_LOG_DEBUG(("Start"));
1029 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
1030 /* Error occured during protocol */
1031 silc_protocol_free(protocol);
1032 silc_ske_free_key_material(ctx->keymat);
1034 silc_packet_context_free(ctx->packet);
1036 silc_ske_free(ctx->ske);
1038 silc_free(ctx->dest_id);
1040 silc_task_unregister_by_callback(server->timeout_queue,
1041 silc_server_failure_callback);
1042 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1043 "Key exchange failed");
1044 server->stat.auth_failures++;
1048 /* We now have the key material as the result of the key exchange
1049 protocol. Take the key material into use. Free the raw key material
1050 as soon as we've set them into use. */
1051 if (!silc_server_protocol_ke_set_keys(ctx->ske, ctx->sock, ctx->keymat,
1052 ctx->ske->prop->cipher,
1053 ctx->ske->prop->pkcs,
1054 ctx->ske->prop->hash,
1055 ctx->ske->prop->hmac,
1057 silc_protocol_free(protocol);
1058 silc_ske_free_key_material(ctx->keymat);
1060 silc_packet_context_free(ctx->packet);
1062 silc_ske_free(ctx->ske);
1064 silc_free(ctx->dest_id);
1066 silc_task_unregister_by_callback(server->timeout_queue,
1067 silc_server_failure_callback);
1068 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1069 "Key exchange failed");
1070 server->stat.auth_failures++;
1073 silc_ske_free_key_material(ctx->keymat);
1075 /* Allocate internal context for the authentication protocol. This
1076 is sent as context for the protocol. */
1077 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1078 proto_ctx->server = (void *)server;
1079 proto_ctx->sock = sock = server->sockets[fd];
1080 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1081 proto_ctx->responder = TRUE;
1082 proto_ctx->dest_id_type = ctx->dest_id_type;
1083 proto_ctx->dest_id = ctx->dest_id;
1085 /* Free old protocol as it is finished now */
1086 silc_protocol_free(protocol);
1088 silc_packet_context_free(ctx->packet);
1090 sock->protocol = NULL;
1092 /* Allocate the authentication protocol. This is allocated here
1093 but we won't start it yet. We will be receiving party of this
1094 protocol thus we will wait that connecting party will make
1095 their first move. */
1096 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1097 &sock->protocol, proto_ctx,
1098 silc_server_accept_new_connection_final);
1100 /* Register timeout task. If the protocol is not executed inside
1101 this timelimit the connection will be terminated. Currently
1102 this is 60 seconds and is hard coded limit (XXX). */
1103 proto_ctx->timeout_task =
1104 silc_task_register(server->timeout_queue, sock->sock,
1105 silc_server_timeout_remote,
1106 (void *)server, 60, 0,
1111 /* Final part of accepting new connection. The connection has now
1112 been authenticated and keys has been exchanged. We also know whether
1113 this is client or server connection. */
1115 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1117 SilcProtocol protocol = (SilcProtocol)context;
1118 SilcServerConnAuthInternalContext *ctx =
1119 (SilcServerConnAuthInternalContext *)protocol->context;
1120 SilcServer server = (SilcServer)ctx->server;
1121 SilcSocketConnection sock = ctx->sock;
1122 SilcServerHBContext hb_context;
1123 void *id_entry = NULL;
1125 SILC_LOG_DEBUG(("Start"));
1127 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
1128 /* Error occured during protocol */
1129 silc_protocol_free(protocol);
1131 silc_packet_context_free(ctx->packet);
1133 silc_ske_free(ctx->ske);
1135 silc_free(ctx->dest_id);
1138 sock->protocol = NULL;
1139 silc_task_unregister_by_callback(server->timeout_queue,
1140 silc_server_failure_callback);
1141 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1142 "Authentication failed");
1143 server->stat.auth_failures++;
1147 sock->type = ctx->conn_type;
1148 switch(sock->type) {
1149 case SILC_SOCKET_TYPE_CLIENT:
1151 SilcClientEntry client;
1153 SILC_LOG_DEBUG(("Remote host is client"));
1154 SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
1157 /* Add the client to the client ID cache. The nickname and Client ID
1158 and other information is created after we have received NEW_CLIENT
1159 packet from client. */
1160 client = silc_idlist_add_client(server->local_list,
1161 NULL, NULL, NULL, NULL, NULL, sock);
1163 SILC_LOG_ERROR(("Could not add new client to cache"));
1164 silc_free(sock->user_data);
1169 server->stat.my_clients++;
1170 server->stat.clients++;
1171 if (server->server_type == SILC_ROUTER)
1172 server->stat.cell_clients++;
1174 id_entry = (void *)client;
1177 case SILC_SOCKET_TYPE_SERVER:
1178 case SILC_SOCKET_TYPE_ROUTER:
1180 SilcServerEntry new_server;
1182 SILC_LOG_DEBUG(("Remote host is %s",
1183 sock->type == SILC_SOCKET_TYPE_SERVER ?
1184 "server" : "router"));
1185 SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
1186 sock->ip, sock->type == SILC_SOCKET_TYPE_SERVER ?
1187 "server" : "router"));
1189 /* Add the server into server cache. The server name and Server ID
1190 is updated after we have received NEW_SERVER packet from the
1191 server. We mark ourselves as router for this server if we really
1194 silc_idlist_add_server(server->local_list, NULL,
1195 sock->type == SILC_SOCKET_TYPE_SERVER ?
1196 SILC_SERVER : SILC_ROUTER, NULL,
1197 sock->type == SILC_SOCKET_TYPE_SERVER ?
1198 server->id_entry : NULL, sock);
1200 SILC_LOG_ERROR(("Could not add new server to cache"));
1201 silc_free(sock->user_data);
1206 if (sock->type == SILC_SOCKET_TYPE_SERVER)
1207 server->stat.my_servers++;
1209 server->stat.my_routers++;
1210 server->stat.servers++;
1212 id_entry = (void *)new_server;
1214 /* There is connection to other server now, if it is router then
1215 we will have connection to outside world. If we are router but
1216 normal server connected to us then we will remain standalone,
1217 if we are standlone. */
1218 if (server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER) {
1219 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1220 server->standalone = FALSE;
1221 if (!server->id_entry->router) {
1222 server->id_entry->router = id_entry;
1223 server->router = id_entry;
1232 /* Add the common data structure to the ID entry. */
1234 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1236 /* Add to sockets internal pointer for fast referencing */
1237 silc_free(sock->user_data);
1238 sock->user_data = id_entry;
1240 /* Connection has been fully established now. Everything is ok. */
1241 SILC_LOG_DEBUG(("New connection authenticated"));
1243 /* Perform keepalive. The `hb_context' will be freed automatically
1244 when finally calling the silc_socket_free function. XXX hardcoded
1246 hb_context = silc_calloc(1, sizeof(*hb_context));
1247 hb_context->server = server;
1248 silc_socket_set_heartbeat(sock, 600, hb_context,
1249 silc_server_perform_heartbeat,
1250 server->timeout_queue);
1252 silc_task_unregister_by_callback(server->timeout_queue,
1253 silc_server_failure_callback);
1254 silc_protocol_free(protocol);
1256 silc_packet_context_free(ctx->packet);
1258 silc_ske_free(ctx->ske);
1260 silc_free(ctx->dest_id);
1262 sock->protocol = NULL;
1265 /* This function is used to read packets from network and send packets to
1266 network. This is usually a generic task. */
1268 SILC_TASK_CALLBACK(silc_server_packet_process)
1270 SilcServer server = (SilcServer)context;
1271 SilcSocketConnection sock = server->sockets[fd];
1272 SilcIDListData idata;
1273 SilcCipher cipher = NULL;
1274 SilcHmac hmac = NULL;
1280 SILC_LOG_DEBUG(("Processing packet"));
1282 /* Packet sending */
1284 if (type == SILC_TASK_WRITE) {
1285 /* Do not send data to disconnected connection */
1286 if (SILC_IS_DISCONNECTED(sock))
1289 server->stat.packets_sent++;
1291 if (sock->outbuf->data - sock->outbuf->head)
1292 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1294 ret = silc_server_packet_send_real(server, sock, TRUE);
1296 /* If returned -2 could not write to connection now, will do
1304 /* The packet has been sent and now it is time to set the connection
1305 back to only for input. When there is again some outgoing data
1306 available for this connection it will be set for output as well.
1307 This call clears the output setting and sets it only for input. */
1308 SILC_SET_CONNECTION_FOR_INPUT(fd);
1309 SILC_UNSET_OUTBUF_PENDING(sock);
1311 silc_buffer_clear(sock->outbuf);
1315 /* Packet receiving */
1317 /* Read some data from connection */
1318 ret = silc_packet_receive(sock);
1324 SILC_LOG_DEBUG(("Read EOF"));
1326 /* If connection is disconnecting already we will finally
1327 close the connection */
1328 if (SILC_IS_DISCONNECTING(sock)) {
1329 if (sock->user_data)
1330 silc_server_free_sock_user_data(server, sock);
1331 silc_server_close_connection(server, sock);
1335 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1336 SILC_SET_DISCONNECTING(sock);
1338 /* If the closed connection was our primary router connection the
1339 start re-connecting phase. */
1340 if (!server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER &&
1341 sock == server->router->connection)
1342 silc_task_register(server->timeout_queue, 0,
1343 silc_server_connect_to_router,
1346 SILC_TASK_PRI_NORMAL);
1348 if (sock->user_data)
1349 silc_server_free_sock_user_data(server, sock);
1350 silc_server_close_connection(server, sock);
1354 /* If connection is disconnecting or disconnected we will ignore
1356 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1357 SILC_LOG_DEBUG(("Ignoring read data from disonnected connection"));
1361 server->stat.packets_received++;
1363 /* Get keys and stuff from ID entry */
1364 idata = (SilcIDListData)sock->user_data;
1366 idata->last_receive = time(NULL);
1367 cipher = idata->receive_key;
1371 /* Process the packet. This will call the parser that will then
1372 decrypt and parse the packet. */
1373 silc_packet_receive_process(sock, cipher, hmac, silc_server_packet_parse,
1377 /* Parses whole packet, received earlier. */
1379 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1381 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1382 SilcServer server = (SilcServer)parse_ctx->context;
1383 SilcSocketConnection sock = parse_ctx->sock;
1384 SilcPacketContext *packet = parse_ctx->packet;
1387 SILC_LOG_DEBUG(("Start"));
1389 /* Decrypt the received packet */
1390 ret = silc_packet_decrypt(parse_ctx->cipher, parse_ctx->hmac,
1391 packet->buffer, packet);
1396 /* Parse the packet. Packet type is returned. */
1397 ret = silc_packet_parse(packet);
1399 /* Parse the packet header in special way as this is "special"
1401 ret = silc_packet_parse_special(packet);
1404 if (ret == SILC_PACKET_NONE)
1407 if (server->server_type == SILC_ROUTER) {
1408 /* Route the packet if it is not destined to us. Other ID types but
1409 server are handled separately after processing them. */
1410 if (packet->dst_id_type == SILC_ID_SERVER &&
1411 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1412 SILC_ID_SERVER_COMPARE(packet->dst_id, server->id_string)) {
1414 /* Route the packet to fastest route for the destination ID */
1415 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1416 packet->dst_id_type);
1419 silc_server_packet_route(server,
1420 silc_server_route_get(server, id,
1421 packet->dst_id_type),
1427 /* Broadcast packet if it is marked as broadcast packet and it is
1428 originated from router and we are router. */
1429 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1430 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
1431 silc_server_packet_broadcast(server, server->router->connection, packet);
1435 /* Parse the incoming packet type */
1436 silc_server_packet_parse_type(server, sock, packet);
1439 silc_buffer_clear(sock->inbuf);
1440 silc_packet_context_free(packet);
1441 silc_free(parse_ctx);
1444 /* Parser callback called by silc_packet_receive_process. This merely
1445 registers timeout that will handle the actual parsing when appropriate. */
1447 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1449 SilcServer server = (SilcServer)parser_context->context;
1450 SilcSocketConnection sock = parser_context->sock;
1452 switch (sock->type) {
1453 case SILC_SOCKET_TYPE_CLIENT:
1454 case SILC_SOCKET_TYPE_UNKNOWN:
1455 /* Parse the packet with timeout */
1456 silc_task_register(server->timeout_queue, sock->sock,
1457 silc_server_packet_parse_real,
1458 (void *)parser_context, 0, 100000,
1460 SILC_TASK_PRI_NORMAL);
1462 case SILC_SOCKET_TYPE_SERVER:
1463 case SILC_SOCKET_TYPE_ROUTER:
1464 /* Packets from servers are parsed as soon as possible */
1465 silc_task_register(server->timeout_queue, sock->sock,
1466 silc_server_packet_parse_real,
1467 (void *)parser_context, 0, 1,
1469 SILC_TASK_PRI_NORMAL);
1476 /* Parses the packet type and calls what ever routines the packet type
1477 requires. This is done for all incoming packets. */
1479 void silc_server_packet_parse_type(SilcServer server,
1480 SilcSocketConnection sock,
1481 SilcPacketContext *packet)
1483 SilcPacketType type = packet->type;
1485 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1487 /* Parse the packet type */
1489 case SILC_PACKET_DISCONNECT:
1490 SILC_LOG_DEBUG(("Disconnect packet"));
1491 if (packet->flags & SILC_PACKET_FLAG_LIST)
1495 case SILC_PACKET_SUCCESS:
1497 * Success received for something. For now we can have only
1498 * one protocol for connection executing at once hence this
1499 * success message is for whatever protocol is executing currently.
1501 SILC_LOG_DEBUG(("Success packet"));
1502 if (packet->flags & SILC_PACKET_FLAG_LIST)
1504 if (sock->protocol) {
1505 sock->protocol->execute(server->timeout_queue, 0,
1506 sock->protocol, sock->sock, 0, 0);
1510 case SILC_PACKET_FAILURE:
1512 * Failure received for something. For now we can have only
1513 * one protocol for connection executing at once hence this
1514 * failure message is for whatever protocol is executing currently.
1516 SILC_LOG_DEBUG(("Failure packet"));
1517 if (packet->flags & SILC_PACKET_FLAG_LIST)
1519 if (sock->protocol) {
1520 SilcServerFailureContext f;
1521 f = silc_calloc(1, sizeof(*f));
1525 /* We will wait 5 seconds to process this failure packet */
1526 silc_task_register(server->timeout_queue, sock->sock,
1527 silc_server_failure_callback, (void *)f, 5, 0,
1528 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1532 case SILC_PACKET_REJECT:
1533 SILC_LOG_DEBUG(("Reject packet"));
1534 if (packet->flags & SILC_PACKET_FLAG_LIST)
1539 case SILC_PACKET_NOTIFY:
1541 * Received notify packet. Server can receive notify packets from
1542 * router. Server then relays the notify messages to clients if needed.
1544 SILC_LOG_DEBUG(("Notify packet"));
1545 if (packet->flags & SILC_PACKET_FLAG_LIST)
1546 silc_server_notify_list(server, sock, packet);
1548 silc_server_notify(server, sock, packet);
1554 case SILC_PACKET_CHANNEL_MESSAGE:
1556 * Received channel message. Channel messages are special packets
1557 * (although probably most common ones) thus they are handled
1560 SILC_LOG_DEBUG(("Channel Message packet"));
1561 if (packet->flags & SILC_PACKET_FLAG_LIST)
1563 silc_server_channel_message(server, sock, packet);
1566 case SILC_PACKET_CHANNEL_KEY:
1568 * Received key for channel. As channels are created by the router
1569 * the keys are as well. We will distribute the key to all of our
1570 * locally connected clients on the particular channel. Router
1571 * never receives this channel and thus is ignored.
1573 SILC_LOG_DEBUG(("Channel Key packet"));
1574 if (packet->flags & SILC_PACKET_FLAG_LIST)
1576 silc_server_channel_key(server, sock, packet);
1582 case SILC_PACKET_COMMAND:
1584 * Recived command. Processes the command request and allocates the
1585 * command context and calls the command.
1587 SILC_LOG_DEBUG(("Command packet"));
1588 if (packet->flags & SILC_PACKET_FLAG_LIST)
1590 silc_server_command_process(server, sock, packet);
1593 case SILC_PACKET_COMMAND_REPLY:
1595 * Received command reply packet. Received command reply to command. It
1596 * may be reply to command sent by us or reply to command sent by client
1597 * that we've routed further.
1599 SILC_LOG_DEBUG(("Command Reply packet"));
1600 if (packet->flags & SILC_PACKET_FLAG_LIST)
1602 silc_server_command_reply(server, sock, packet);
1606 * Private Message packets
1608 case SILC_PACKET_PRIVATE_MESSAGE:
1610 * Received private message packet. The packet is coming from either
1613 SILC_LOG_DEBUG(("Private Message packet"));
1614 if (packet->flags & SILC_PACKET_FLAG_LIST)
1616 silc_server_private_message(server, sock, packet);
1619 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1621 * Private message key packet.
1623 if (packet->flags & SILC_PACKET_FLAG_LIST)
1625 silc_server_private_message_key(server, sock, packet);
1629 * Key Exchange protocol packets
1631 case SILC_PACKET_KEY_EXCHANGE:
1632 SILC_LOG_DEBUG(("KE packet"));
1633 if (packet->flags & SILC_PACKET_FLAG_LIST)
1636 if (sock->protocol && sock->protocol->protocol->type
1637 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1639 SilcServerKEInternalContext *proto_ctx =
1640 (SilcServerKEInternalContext *)sock->protocol->context;
1642 proto_ctx->packet = silc_packet_context_dup(packet);
1644 /* Let the protocol handle the packet */
1645 sock->protocol->execute(server->timeout_queue, 0,
1646 sock->protocol, sock->sock, 0, 100000);
1648 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1649 "protocol active, packet dropped."));
1651 /* XXX Trigger KE protocol?? Rekey actually, maybe. */
1655 case SILC_PACKET_KEY_EXCHANGE_1:
1656 SILC_LOG_DEBUG(("KE 1 packet"));
1657 if (packet->flags & SILC_PACKET_FLAG_LIST)
1660 if (sock->protocol && sock->protocol->protocol->type
1661 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1663 SilcServerKEInternalContext *proto_ctx =
1664 (SilcServerKEInternalContext *)sock->protocol->context;
1666 if (proto_ctx->packet)
1667 silc_packet_context_free(proto_ctx->packet);
1669 proto_ctx->packet = silc_packet_context_dup(packet);
1670 proto_ctx->dest_id_type = packet->src_id_type;
1671 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1672 packet->src_id_type);
1673 if (!proto_ctx->dest_id)
1676 /* Let the protocol handle the packet */
1677 sock->protocol->execute(server->timeout_queue, 0,
1678 sock->protocol, sock->sock,
1681 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1682 "protocol active, packet dropped."));
1686 case SILC_PACKET_KEY_EXCHANGE_2:
1687 SILC_LOG_DEBUG(("KE 2 packet"));
1688 if (packet->flags & SILC_PACKET_FLAG_LIST)
1691 if (sock->protocol && sock->protocol->protocol->type
1692 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1694 SilcServerKEInternalContext *proto_ctx =
1695 (SilcServerKEInternalContext *)sock->protocol->context;
1697 if (proto_ctx->packet)
1698 silc_packet_context_free(proto_ctx->packet);
1700 proto_ctx->packet = silc_packet_context_dup(packet);
1701 proto_ctx->dest_id_type = packet->src_id_type;
1702 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1703 packet->src_id_type);
1704 if (!proto_ctx->dest_id)
1707 /* Let the protocol handle the packet */
1708 sock->protocol->execute(server->timeout_queue, 0,
1709 sock->protocol, sock->sock,
1712 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1713 "protocol active, packet dropped."));
1717 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1719 * Connection authentication request packet. When we receive this packet
1720 * we will send to the other end information about our mandatory
1721 * authentication method for the connection. This packet maybe received
1724 SILC_LOG_DEBUG(("Connection authentication request packet"));
1725 if (packet->flags & SILC_PACKET_FLAG_LIST)
1730 * Connection Authentication protocol packets
1732 case SILC_PACKET_CONNECTION_AUTH:
1733 /* Start of the authentication protocol. We receive here the
1734 authentication data and will verify it. */
1735 SILC_LOG_DEBUG(("Connection auth packet"));
1736 if (packet->flags & SILC_PACKET_FLAG_LIST)
1739 if (sock->protocol && sock->protocol->protocol->type
1740 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1742 SilcServerConnAuthInternalContext *proto_ctx =
1743 (SilcServerConnAuthInternalContext *)sock->protocol->context;
1745 proto_ctx->packet = silc_packet_context_dup(packet);
1747 /* Let the protocol handle the packet */
1748 sock->protocol->execute(server->timeout_queue, 0,
1749 sock->protocol, sock->sock, 0, 0);
1751 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1752 "protocol active, packet dropped."));
1756 case SILC_PACKET_NEW_ID:
1758 * Received New ID packet. This includes some new ID that has been
1759 * created. It may be for client, server or channel. This is the way
1760 * to distribute information about new registered entities in the
1763 SILC_LOG_DEBUG(("New ID packet"));
1764 if (packet->flags & SILC_PACKET_FLAG_LIST)
1765 silc_server_new_id_list(server, sock, packet);
1767 silc_server_new_id(server, sock, packet);
1770 case SILC_PACKET_NEW_CLIENT:
1772 * Received new client packet. This includes client information that
1773 * we will use to create initial client ID. After creating new
1774 * ID we will send it to the client.
1776 SILC_LOG_DEBUG(("New Client packet"));
1777 if (packet->flags & SILC_PACKET_FLAG_LIST)
1779 silc_server_new_client(server, sock, packet);
1782 case SILC_PACKET_NEW_SERVER:
1784 * Received new server packet. This includes Server ID and some other
1785 * information that we may save. This is received after server has
1788 SILC_LOG_DEBUG(("New Server packet"));
1789 if (packet->flags & SILC_PACKET_FLAG_LIST)
1791 silc_server_new_server(server, sock, packet);
1794 case SILC_PACKET_NEW_CHANNEL:
1796 * Received new channel packet. Information about new channel in the
1797 * network are distributed using this packet.
1799 SILC_LOG_DEBUG(("New Channel packet"));
1800 if (packet->flags & SILC_PACKET_FLAG_LIST)
1801 silc_server_new_channel_list(server, sock, packet);
1803 silc_server_new_channel(server, sock, packet);
1806 case SILC_PACKET_HEARTBEAT:
1808 * Received heartbeat.
1810 SILC_LOG_DEBUG(("Heartbeat packet"));
1811 if (packet->flags & SILC_PACKET_FLAG_LIST)
1815 case SILC_PACKET_KEY_AGREEMENT:
1817 * Received heartbeat.
1819 SILC_LOG_DEBUG(("Key agreement packet"));
1820 if (packet->flags & SILC_PACKET_FLAG_LIST)
1822 silc_server_key_agreement(server, sock, packet);
1826 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
1832 /* Creates connection to a remote router. */
1834 void silc_server_create_connection(SilcServer server,
1835 char *remote_host, unsigned int port)
1837 SilcServerConnection sconn;
1839 /* Allocate connection object for hold connection specific stuff. */
1840 sconn = silc_calloc(1, sizeof(*sconn));
1841 sconn->server = server;
1842 sconn->remote_host = strdup(remote_host);
1843 sconn->remote_port = port;
1845 silc_task_register(server->timeout_queue, 0,
1846 silc_server_connect_router,
1847 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
1848 SILC_TASK_PRI_NORMAL);
1851 /* Closes connection to socket connection */
1853 void silc_server_close_connection(SilcServer server,
1854 SilcSocketConnection sock)
1856 SILC_LOG_DEBUG(("Closing connection %d", sock->sock));
1858 /* We won't listen for this connection anymore */
1859 silc_schedule_unset_listen_fd(sock->sock);
1861 /* Unregister all tasks */
1862 silc_task_unregister_by_fd(server->io_queue, sock->sock);
1863 silc_task_unregister_by_fd(server->timeout_queue, sock->sock);
1865 /* Close the actual connection */
1866 silc_net_close_connection(sock->sock);
1867 server->sockets[sock->sock] = NULL;
1868 silc_socket_free(sock);
1871 /* Sends disconnect message to remote connection and disconnects the
1874 void silc_server_disconnect_remote(SilcServer server,
1875 SilcSocketConnection sock,
1876 const char *fmt, ...)
1879 unsigned char buf[4096];
1884 memset(buf, 0, sizeof(buf));
1886 vsprintf(buf, fmt, ap);
1889 SILC_LOG_DEBUG(("Disconnecting remote host"));
1891 SILC_LOG_INFO(("Disconnecting %s:%d [%s]", sock->hostname,
1893 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1894 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1895 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1898 /* Notify remote end that the conversation is over. The notify message
1899 is tried to be sent immediately. */
1900 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
1901 buf, strlen(buf), TRUE);
1903 /* Mark the connection to be disconnected */
1904 SILC_SET_DISCONNECTED(sock);
1905 silc_server_close_connection(server, sock);
1908 /* Frees client data and notifies about client's signoff. */
1910 void silc_server_free_client_data(SilcServer server,
1911 SilcSocketConnection sock,
1912 SilcClientEntry user_data, char *signoff)
1914 /* Send REMOVE_ID packet to routers. */
1915 if (!server->standalone && server->router)
1916 silc_server_send_notify_signoff(server, server->router->connection,
1917 server->server_type == SILC_SERVER ?
1918 FALSE : TRUE, user_data->id,
1919 SILC_ID_CLIENT_LEN, signoff);
1921 /* Remove client from all channels */
1922 silc_server_remove_from_channels(server, sock, user_data, signoff);
1924 /* XXX must take some info to history before freeing */
1926 /* Free the client entry and everything in it */
1927 silc_idlist_del_data(user_data);
1928 silc_idlist_del_client(server->local_list, user_data);
1929 server->stat.my_clients--;
1930 server->stat.clients--;
1931 if (server->server_type == SILC_ROUTER)
1932 server->stat.cell_clients--;
1935 /* Frees user_data pointer from socket connection object. This also sends
1936 appropriate notify packets to the network to inform about leaving
1939 void silc_server_free_sock_user_data(SilcServer server,
1940 SilcSocketConnection sock)
1942 SILC_LOG_DEBUG(("Start"));
1944 switch(sock->type) {
1945 case SILC_SOCKET_TYPE_CLIENT:
1947 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
1948 silc_server_free_client_data(server, sock, user_data, NULL);
1951 case SILC_SOCKET_TYPE_SERVER:
1952 case SILC_SOCKET_TYPE_ROUTER:
1954 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
1956 /* Send REMOVE_ID packet to routers. */
1957 if (!server->standalone && server->router)
1958 silc_server_send_notify_server_signoff(server,
1959 server->router->connection,
1960 server->server_type ==
1962 FALSE : TRUE, user_data->id,
1963 SILC_ID_SERVER_LEN);
1965 /* Then also free all client entries that this server owns as
1966 they will become invalid now as well. */
1967 silc_server_remove_clients_by_server(server, user_data);
1969 /* If this was our primary router connection then we're lost to
1970 the outside world. */
1971 if (server->server_type == SILC_SERVER && server->router == user_data) {
1972 server->id_entry->router = NULL;
1973 server->router = NULL;
1974 server->standalone = TRUE;
1977 /* Free the server entry */
1978 silc_idlist_del_data(user_data);
1979 silc_idlist_del_server(server->local_list, user_data);
1980 server->stat.my_servers--;
1981 server->stat.servers--;
1982 if (server->server_type == SILC_ROUTER)
1983 server->stat.cell_servers--;
1988 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
1990 silc_idlist_del_data(user_data);
1991 silc_free(user_data);
1996 sock->user_data = NULL;
1999 /* This function is used to remove all client entries by the server `entry'.
2000 This is called when the connection is lost to the server. In this case
2001 we must invalidate all the client entries owned by the server `entry'. */
2003 int silc_server_remove_clients_by_server(SilcServer server,
2004 SilcServerEntry entry)
2006 SilcIDCacheList list = NULL;
2007 SilcIDCacheEntry id_cache = NULL;
2008 SilcClientEntry client = NULL;
2010 SILC_LOG_DEBUG(("Start"));
2012 if (silc_idcache_find_by_id(server->local_list->clients,
2013 SILC_ID_CACHE_ANY, SILC_ID_CLIENT, &list)) {
2015 if (silc_idcache_list_first(list, &id_cache)) {
2017 client = (SilcClientEntry)id_cache->context;
2019 if (client->router != entry) {
2020 if (!silc_idcache_list_next(list, &id_cache))
2026 /* Remove the client entry */
2027 silc_server_remove_from_channels(server, NULL, client, NULL);
2028 silc_idlist_del_client(server->local_list, client);
2030 if (!silc_idcache_list_next(list, &id_cache))
2034 silc_idcache_list_free(list);
2037 if (silc_idcache_find_by_id(server->global_list->clients,
2038 SILC_ID_CACHE_ANY, SILC_ID_CLIENT, &list)) {
2040 if (silc_idcache_list_first(list, &id_cache)) {
2042 client = (SilcClientEntry)id_cache->context;
2044 if (client->router != entry) {
2045 if (!silc_idcache_list_next(list, &id_cache))
2051 /* Remove the client entry */
2052 silc_server_remove_from_channels(server, NULL, client, NULL);
2053 silc_idlist_del_client(server->global_list, client);
2055 if (!silc_idcache_list_next(list, &id_cache))
2059 silc_idcache_list_free(list);
2065 /* Checks whether given channel has global users. If it does this returns
2066 TRUE and FALSE if there is only locally connected clients on the channel. */
2068 int silc_server_channel_has_global(SilcChannelEntry channel)
2070 SilcChannelClientEntry chl;
2072 silc_list_start(channel->user_list);
2073 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2074 if (chl->client->router)
2081 /* Checks whether given channel has locally connected users. If it does this
2082 returns TRUE and FALSE if there is not one locally connected client. */
2084 int silc_server_channel_has_local(SilcChannelEntry channel)
2086 SilcChannelClientEntry chl;
2088 silc_list_start(channel->user_list);
2089 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2090 if (!chl->client->router)
2097 /* Removes client from all channels it has joined. This is used when client
2098 connection is disconnected. If the client on a channel is last, the
2099 channel is removed as well. This sends the SIGNOFF notify types. */
2101 void silc_server_remove_from_channels(SilcServer server,
2102 SilcSocketConnection sock,
2103 SilcClientEntry client,
2104 char *signoff_message)
2106 SilcChannelEntry channel;
2107 SilcChannelClientEntry chl;
2110 SILC_LOG_DEBUG(("Start"));
2112 if (!client || !client->id)
2115 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2117 /* Remove the client from all channels. The client is removed from
2118 the channels' user list. */
2119 silc_list_start(client->channels);
2120 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2121 channel = chl->channel;
2123 /* Remove channel from client's channel list */
2124 silc_list_del(client->channels, chl);
2126 /* Remove channel if there is no users anymore */
2127 if (server->server_type == SILC_ROUTER &&
2128 silc_list_count(channel->user_list) < 2) {
2129 if (!silc_idlist_del_channel(server->local_list, channel))
2130 silc_idlist_del_channel(server->global_list, channel);
2131 server->stat.my_channels--;
2135 /* Remove client from channel's client list */
2136 silc_list_del(channel->user_list, chl);
2138 server->stat.my_chanclients--;
2140 /* If there is no global users on the channel anymore mark the channel
2141 as local channel. */
2142 if (server->server_type == SILC_SERVER &&
2143 !silc_server_channel_has_global(channel))
2144 channel->global_users = FALSE;
2146 /* If there is not at least one local user on the channel then we don't
2147 need the channel entry anymore, we can remove it safely. */
2148 if (server->server_type == SILC_SERVER &&
2149 !silc_server_channel_has_local(channel)) {
2150 /* Notify about leaving client if this channel has global users. */
2151 if (channel->global_users)
2152 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2153 SILC_NOTIFY_TYPE_SIGNOFF,
2154 signoff_message ? 2 : 1,
2155 clidp->data, clidp->len,
2156 signoff_message, signoff_message ?
2157 strlen(signoff_message) : 0);
2159 if (!silc_idlist_del_channel(server->local_list, channel))
2160 silc_idlist_del_channel(server->global_list, channel);
2161 server->stat.my_channels--;
2165 /* Send notify to channel about client leaving SILC and thus
2166 the entire channel. */
2167 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2168 SILC_NOTIFY_TYPE_SIGNOFF,
2169 signoff_message ? 2 : 1,
2170 clidp->data, clidp->len,
2171 signoff_message, signoff_message ?
2172 strlen(signoff_message) : 0);
2175 silc_buffer_free(clidp);
2178 /* Removes client from one channel. This is used for example when client
2179 calls LEAVE command to remove itself from the channel. Returns TRUE
2180 if channel still exists and FALSE if the channel is removed when
2181 last client leaves the channel. If `notify' is FALSE notify messages
2184 int silc_server_remove_from_one_channel(SilcServer server,
2185 SilcSocketConnection sock,
2186 SilcChannelEntry channel,
2187 SilcClientEntry client,
2190 SilcChannelEntry ch;
2191 SilcChannelClientEntry chl;
2194 SILC_LOG_DEBUG(("Start"));
2196 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2198 /* Remove the client from the channel. The client is removed from
2199 the channel's user list. */
2200 silc_list_start(client->channels);
2201 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2202 if (chl->channel != channel)
2207 /* Remove channel from client's channel list */
2208 silc_list_del(client->channels, chl);
2210 /* Remove channel if there is no users anymore */
2211 if (server->server_type == SILC_ROUTER &&
2212 silc_list_count(channel->user_list) < 2) {
2213 if (!silc_idlist_del_channel(server->local_list, channel))
2214 silc_idlist_del_channel(server->global_list, channel);
2215 silc_buffer_free(clidp);
2216 server->stat.my_channels--;
2220 /* Remove client from channel's client list */
2221 silc_list_del(channel->user_list, chl);
2223 server->stat.my_chanclients--;
2225 /* If there is no global users on the channel anymore mark the channel
2226 as local channel. */
2227 if (server->server_type == SILC_SERVER &&
2228 !silc_server_channel_has_global(channel))
2229 channel->global_users = FALSE;
2231 /* If there is not at least one local user on the channel then we don't
2232 need the channel entry anymore, we can remove it safely. */
2233 if (server->server_type == SILC_SERVER &&
2234 !silc_server_channel_has_local(channel)) {
2235 /* Notify about leaving client if this channel has global users. */
2236 if (notify && channel->global_users)
2237 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2238 SILC_NOTIFY_TYPE_LEAVE, 1,
2239 clidp->data, clidp->len);
2241 if (!silc_idlist_del_channel(server->local_list, channel))
2242 silc_idlist_del_channel(server->global_list, channel);
2243 silc_buffer_free(clidp);
2244 server->stat.my_channels--;
2248 /* Send notify to channel about client leaving the channel */
2250 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2251 SILC_NOTIFY_TYPE_LEAVE, 1,
2252 clidp->data, clidp->len);
2256 silc_buffer_free(clidp);
2260 /* Returns TRUE if the given client is on the channel. FALSE if not.
2261 This works because we assure that the user list on the channel is
2262 always in up to date thus we can only check the channel list from
2263 `client' which is faster than checking the user list from `channel'. */
2265 int silc_server_client_on_channel(SilcClientEntry client,
2266 SilcChannelEntry channel)
2268 SilcChannelClientEntry chl;
2270 if (!client || !channel)
2273 silc_list_start(client->channels);
2274 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END)
2275 if (chl->channel == channel)
2281 /* Timeout callback. This is called if connection is idle or for some
2282 other reason is not responding within some period of time. This
2283 disconnects the remote end. */
2285 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2287 SilcServer server = (SilcServer)context;
2288 SilcSocketConnection sock = server->sockets[fd];
2293 if (sock->user_data)
2294 silc_server_free_sock_user_data(server, sock);
2296 silc_server_disconnect_remote(server, sock,
2297 "Server closed connection: "
2298 "Connection timeout");
2301 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2302 function may be used only by router. In real SILC network all channels
2303 are created by routers thus this function is never used by normal
2306 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2307 SilcServerID *router_id,
2313 SilcChannelID *channel_id;
2314 SilcChannelEntry entry;
2317 SILC_LOG_DEBUG(("Creating new channel"));
2320 cipher = "aes-256-cbc";
2322 hmac = "hmac-sha1-96";
2324 /* Allocate cipher */
2325 if (!silc_cipher_alloc(cipher, &key))
2328 channel_name = strdup(channel_name);
2330 /* Create the channel */
2331 silc_id_create_channel_id(router_id, server->rng, &channel_id);
2332 entry = silc_idlist_add_channel(server->local_list, channel_name,
2333 SILC_CHANNEL_MODE_NONE, channel_id,
2336 silc_free(channel_name);
2340 /* Now create the actual key material */
2341 silc_server_create_channel_key(server, entry,
2342 silc_cipher_get_key_len(key) / 8);
2344 /* Notify other routers about the new channel. We send the packet
2345 to our primary route. */
2346 if (broadcast && server->standalone == FALSE) {
2347 silc_server_send_new_channel(server, server->router->connection, TRUE,
2348 channel_name, entry->id, SILC_ID_CHANNEL_LEN);
2351 server->stat.my_channels++;
2356 /* Same as above but creates the channel with Channel ID `channel_id. */
2359 silc_server_create_new_channel_with_id(SilcServer server,
2363 SilcChannelID *channel_id,
2366 SilcChannelEntry entry;
2369 SILC_LOG_DEBUG(("Creating new channel"));
2372 cipher = "aes-256-cbc";
2374 hmac = "hmac-sha1-96";
2376 /* Allocate cipher */
2377 if (!silc_cipher_alloc(cipher, &key))
2380 channel_name = strdup(channel_name);
2382 /* Create the channel */
2383 entry = silc_idlist_add_channel(server->local_list, channel_name,
2384 SILC_CHANNEL_MODE_NONE, channel_id,
2387 silc_free(channel_name);
2391 /* Now create the actual key material */
2392 silc_server_create_channel_key(server, entry,
2393 silc_cipher_get_key_len(key) / 8);
2395 /* Notify other routers about the new channel. We send the packet
2396 to our primary route. */
2397 if (broadcast && server->standalone == FALSE) {
2398 silc_server_send_new_channel(server, server->router->connection, TRUE,
2399 channel_name, entry->id, SILC_ID_CHANNEL_LEN);
2402 server->stat.my_channels++;
2407 /* Generates new channel key. This is used to create the initial channel key
2408 but also to re-generate new key for channel. If `key_len' is provided
2409 it is the bytes of the key length. */
2411 void silc_server_create_channel_key(SilcServer server,
2412 SilcChannelEntry channel,
2413 unsigned int key_len)
2416 unsigned char channel_key[32];
2419 if (!channel->channel_key)
2420 if (!silc_cipher_alloc("aes-256-cbc", &channel->channel_key))
2425 else if (channel->key_len)
2426 len = channel->key_len / 8;
2428 len = silc_cipher_get_key_len(channel->channel_key) / 8;
2430 /* Create channel key */
2431 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
2434 channel->channel_key->cipher->set_key(channel->channel_key->context,
2437 /* Remove old key if exists */
2439 memset(channel->key, 0, channel->key_len / 8);
2440 silc_free(channel->key);
2444 channel->key_len = len * 8;
2445 channel->key = silc_calloc(len, sizeof(*channel->key));
2446 memcpy(channel->key, channel_key, len);
2447 memset(channel_key, 0, sizeof(channel_key));
2450 /* Saves the channel key found in the encoded `key_payload' buffer. This
2451 function is used when we receive Channel Key Payload and also when we're
2452 processing JOIN command reply. Returns entry to the channel. */
2454 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
2455 SilcBuffer key_payload,
2456 SilcChannelEntry channel)
2458 SilcChannelKeyPayload payload = NULL;
2459 SilcChannelID *id = NULL;
2461 unsigned int tmp_len;
2464 /* Decode channel key payload */
2465 payload = silc_channel_key_payload_parse(key_payload);
2467 SILC_LOG_ERROR(("Bad channel key payload, dropped"));
2472 /* Get the channel entry */
2475 /* Get channel ID */
2476 tmp = silc_channel_key_get_id(payload, &tmp_len);
2477 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
2483 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
2485 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
2487 SILC_LOG_ERROR(("Received key for non-existent channel"));
2493 tmp = silc_channel_key_get_key(payload, &tmp_len);
2499 cipher = silc_channel_key_get_cipher(payload, NULL);
2505 /* Remove old key if exists */
2507 memset(channel->key, 0, channel->key_len / 8);
2508 silc_free(channel->key);
2509 silc_cipher_free(channel->channel_key);
2512 /* Create new cipher */
2513 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
2519 channel->key_len = tmp_len * 8;
2520 channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
2521 memcpy(channel->key, tmp, tmp_len);
2522 channel->channel_key->cipher->set_key(channel->channel_key->context,
2529 silc_channel_key_payload_free(payload);
2534 /* Heartbeat callback. This function is set as argument for the
2535 silc_socket_set_heartbeat function. The library will call this function
2536 at the set time interval. */
2538 void silc_server_perform_heartbeat(SilcSocketConnection sock,
2541 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
2543 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname,
2546 /* Send the heartbeat */
2547 silc_server_send_heartbeat(hb->server, sock);
2550 /* Returns assembled of all servers in the given ID list. The packet's
2551 form is dictated by the New ID payload. */
2553 static void silc_server_announce_get_servers(SilcServer server,
2555 SilcBuffer *servers)
2557 SilcIDCacheList list;
2558 SilcIDCacheEntry id_cache;
2559 SilcServerEntry entry;
2562 /* Go through all clients in the list */
2563 if (silc_idcache_find_by_id(id_list->clients, SILC_ID_CACHE_ANY,
2564 SILC_ID_SERVER, &list)) {
2565 if (silc_idcache_list_first(list, &id_cache)) {
2567 entry = (SilcServerEntry)id_cache->context;
2569 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
2571 *servers = silc_buffer_realloc(*servers,
2573 (*servers)->truelen + idp->len :
2575 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
2576 silc_buffer_put(*servers, idp->data, idp->len);
2577 silc_buffer_pull(*servers, idp->len);
2578 silc_buffer_free(idp);
2580 if (!silc_idcache_list_next(list, &id_cache))
2585 silc_idcache_list_free(list);
2589 /* This function is used by router to announce existing servers to our
2590 primary router when we've connected to it. */
2592 void silc_server_announce_servers(SilcServer server)
2594 SilcBuffer servers = NULL;
2596 SILC_LOG_DEBUG(("Announcing servers"));
2598 /* Get servers in local list */
2599 silc_server_announce_get_servers(server, server->local_list, &servers);
2601 /* Get servers in global list */
2602 silc_server_announce_get_servers(server, server->global_list, &servers);
2605 silc_buffer_push(servers, servers->data - servers->head);
2606 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
2608 /* Send the packet */
2609 silc_server_packet_send(server, server->router->connection,
2610 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
2611 servers->data, servers->len, TRUE);
2613 silc_buffer_free(servers);
2617 /* Returns assembled packet of all clients in the given ID list. The
2618 packet's form is dictated by the New ID Payload. */
2620 static void silc_server_announce_get_clients(SilcServer server,
2622 SilcBuffer *clients)
2624 SilcIDCacheList list;
2625 SilcIDCacheEntry id_cache;
2626 SilcClientEntry client;
2629 /* Go through all clients in the list */
2630 if (silc_idcache_find_by_id(id_list->clients, SILC_ID_CACHE_ANY,
2631 SILC_ID_CLIENT, &list)) {
2632 if (silc_idcache_list_first(list, &id_cache)) {
2634 client = (SilcClientEntry)id_cache->context;
2636 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2638 *clients = silc_buffer_realloc(*clients,
2640 (*clients)->truelen + idp->len :
2642 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
2643 silc_buffer_put(*clients, idp->data, idp->len);
2644 silc_buffer_pull(*clients, idp->len);
2645 silc_buffer_free(idp);
2647 if (!silc_idcache_list_next(list, &id_cache))
2652 silc_idcache_list_free(list);
2656 /* This function is used to announce our existing clients to our router
2657 when we've connected to it. */
2659 void silc_server_announce_clients(SilcServer server)
2661 SilcBuffer clients = NULL;
2663 SILC_LOG_DEBUG(("Announcing clients"));
2665 /* Get clients in local list */
2666 silc_server_announce_get_clients(server, server->local_list,
2669 /* As router we announce our global list as well */
2670 if (server->server_type == SILC_ROUTER)
2671 silc_server_announce_get_clients(server, server->global_list,
2675 silc_buffer_push(clients, clients->data - clients->head);
2676 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
2678 /* Send the packet */
2679 silc_server_packet_send(server, server->router->connection,
2680 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
2681 clients->data, clients->len, TRUE);
2683 silc_buffer_free(clients);
2688 silc_server_announce_encode_join(unsigned int argc, ...)
2693 return silc_notify_payload_encode(SILC_NOTIFY_TYPE_JOIN, argc, ap);
2696 /* Returns assembled packets for all channels and users on those channels
2697 from the given ID List. The packets are in the form dictated by the
2698 New Channel and New Channel User payloads. */
2700 static void silc_server_announce_get_channels(SilcServer server,
2702 SilcBuffer *channels,
2703 SilcBuffer *channel_users)
2705 SilcIDCacheList list;
2706 SilcIDCacheEntry id_cache;
2707 SilcChannelEntry channel;
2708 SilcChannelClientEntry chl;
2711 unsigned short name_len;
2714 /* Go through all channels in the list */
2715 if (silc_idcache_find_by_id(id_list->channels, SILC_ID_CACHE_ANY,
2716 SILC_ID_CHANNEL, &list)) {
2717 if (silc_idcache_list_first(list, &id_cache)) {
2719 channel = (SilcChannelEntry)id_cache->context;
2721 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
2722 name_len = strlen(channel->channel_name);
2724 len = 4 + name_len + SILC_ID_CHANNEL_LEN;
2726 silc_buffer_realloc(*channels,
2727 (*channels ? (*channels)->truelen + len : len));
2728 silc_buffer_pull_tail(*channels,
2729 ((*channels)->end - (*channels)->data));
2730 silc_buffer_format(*channels,
2731 SILC_STR_UI_SHORT(name_len),
2732 SILC_STR_UI_XNSTRING(channel->channel_name,
2734 SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
2735 SILC_STR_UI_XNSTRING(cid, SILC_ID_CHANNEL_LEN),
2737 silc_buffer_pull(*channels, len);
2739 /* Now find all users on the channel */
2740 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
2741 silc_list_start(channel->user_list);
2742 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2746 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
2748 tmp = silc_server_announce_encode_join(2, clidp->data, clidp->len,
2749 chidp->data, chidp->len);
2752 silc_buffer_realloc(*channel_users,
2754 (*channel_users)->truelen + len : len));
2755 silc_buffer_pull_tail(*channel_users,
2756 ((*channel_users)->end -
2757 (*channel_users)->data));
2759 silc_buffer_put(*channel_users, tmp->data, tmp->len);
2760 silc_buffer_pull(*channel_users, len);
2761 silc_buffer_free(clidp);
2762 silc_buffer_free(tmp);
2764 silc_buffer_free(chidp);
2768 if (!silc_idcache_list_next(list, &id_cache))
2773 silc_idcache_list_free(list);
2777 /* This function is used to announce our existing channels to our router
2778 when we've connected to it. This also announces the users on the
2779 channels to the router. */
2781 void silc_server_announce_channels(SilcServer server)
2783 SilcBuffer channels = NULL, channel_users = NULL;
2785 SILC_LOG_DEBUG(("Announcing channels and channel users"));
2787 /* Get channels and channel users in local list */
2788 silc_server_announce_get_channels(server, server->local_list,
2789 &channels, &channel_users);
2791 /* Get channels and channel users in global list */
2792 silc_server_announce_get_channels(server, server->global_list,
2793 &channels, &channel_users);
2796 silc_buffer_push(channels, channels->data - channels->head);
2797 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
2799 /* Send the packet */
2800 silc_server_packet_send(server, server->router->connection,
2801 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
2802 channels->data, channels->len,
2805 silc_buffer_free(channels);
2808 if (channel_users) {
2809 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
2810 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
2811 channel_users->len);
2813 /* Send the packet */
2814 silc_server_packet_send(server, server->router->connection,
2815 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
2816 channel_users->data, channel_users->len,
2819 silc_buffer_free(channel_users);
2823 /* Failure timeout callback. If this is called then we will immediately
2824 process the received failure. We always process the failure with timeout
2825 since we do not want to blindly trust to received failure packets.
2826 This won't be called (the timeout is cancelled) if the failure was
2827 bogus (it is bogus if remote does not close the connection after sending
2830 SILC_TASK_CALLBACK(silc_server_failure_callback)
2832 SilcServerFailureContext f = (SilcServerFailureContext)context;
2834 if (f->sock->protocol) {
2835 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
2836 f->sock->protocol->execute(f->server->timeout_queue, 0,
2837 f->sock->protocol, f->sock->sock, 0, 0);