5 Author: Pekka Riikonen <priikone@poseidon.pspt.fi>
7 Copyright (C) 1997 - 2000 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);
42 /* Allocates a new SILC server object. This has to be done before the server
43 can be used. After allocation one must call silc_server_init to initialize
44 the server. The new allocated server object is returned to the new_server
47 int silc_server_alloc(SilcServer *new_server)
51 SILC_LOG_DEBUG(("Allocating new server object"));
53 server = silc_calloc(1, sizeof(*server));
54 server->server_type = SILC_SERVER;
55 server->standalone = TRUE;
56 server->local_list = silc_calloc(1, sizeof(*server->local_list));
57 server->global_list = silc_calloc(1, sizeof(*server->global_list));
58 server->pending_commands = silc_dlist_init();
60 server->sim = silc_dlist_init();
68 /* Free's the SILC server object. This is called at the very end before
71 void silc_server_free(SilcServer server)
78 if (server->local_list)
79 silc_free(server->local_list);
80 if (server->global_list)
81 silc_free(server->global_list);
83 silc_rng_free(server->rng);
86 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
87 silc_dlist_del(server->sim, sim);
90 silc_dlist_uninit(server->sim);
94 silc_free(server->params);
96 if (server->pending_commands)
97 silc_dlist_uninit(server->pending_commands);
99 silc_math_primegen_uninit(); /* XXX */
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_config_server_setlogfiles(server->config);
135 /* Register all configured ciphers, PKCS and hash functions. */
136 silc_config_server_register_ciphers(server->config);
137 silc_config_server_register_pkcs(server->config);
138 silc_config_server_register_hashfuncs(server->config);
140 /* Initialize random number generator for the server. */
141 server->rng = silc_rng_alloc();
142 silc_rng_init(server->rng);
143 silc_math_primegen_init(); /* XXX */
145 /* Initialize hash functions for server to use */
146 silc_hash_alloc("md5", &server->md5hash);
147 silc_hash_alloc("sha1", &server->sha1hash);
149 /* Initialize none cipher */
150 silc_cipher_alloc("none", &server->none_cipher);
152 /* XXXXX Generate RSA key pair */
154 unsigned char *public_key;
155 unsigned char *private_key;
156 unsigned int pk_len, prv_len;
159 if (stat("pubkey.pub", &st) < 0 && stat("privkey.prv", &st) < 0) {
161 if (silc_pkcs_alloc("rsa", &server->pkcs) == FALSE) {
162 SILC_LOG_ERROR(("Could not create RSA key pair"));
166 if (server->pkcs->pkcs->init(server->pkcs->context,
167 1024, server->rng) == FALSE) {
168 SILC_LOG_ERROR(("Could not generate RSA key pair"));
172 public_key = server->pkcs->pkcs->get_public_key(server->pkcs->context,
174 private_key = server->pkcs->pkcs->get_private_key(server->pkcs->context,
177 SILC_LOG_HEXDUMP(("public key"), public_key, pk_len);
178 SILC_LOG_HEXDUMP(("private key"), private_key, prv_len);
181 silc_pkcs_public_key_alloc("rsa", "UN=root, HN=dummy",
183 server->private_key =
184 silc_pkcs_private_key_alloc("rsa", private_key, prv_len);
187 silc_pkcs_save_public_key("pubkey.pub", server->public_key,
189 silc_pkcs_save_private_key("privkey.prv", server->private_key, NULL,
192 memset(public_key, 0, pk_len);
193 memset(private_key, 0, prv_len);
194 silc_free(public_key);
195 silc_free(private_key);
197 silc_pkcs_load_public_key("pubkey.pub", &server->public_key,
199 silc_pkcs_load_private_key("privkey.prv", &server->private_key,
204 /* Create a listening server. Note that our server can listen on
205 multiple ports. All listeners are created here and now. */
206 /* XXX Still check this whether to use server_info or listen_port. */
208 while(server->config->listen_port) {
211 tmp = silc_net_create_server(server->config->listen_port->port,
212 server->config->listen_port->host);
216 sock = silc_realloc(sock, (sizeof(int *) * (sock_count + 1)));
217 sock[sock_count] = tmp;
218 server->config->listen_port = server->config->listen_port->next;
222 /* Initialize ID caches */
223 server->local_list->clients = silc_idcache_alloc(0);
224 server->local_list->servers = silc_idcache_alloc(0);
225 server->local_list->channels = silc_idcache_alloc(0);
227 /* These are allocated for normal server as well as these hold some
228 global information that the server has fetched from its router. For
229 router these are used as they are supposed to be used on router. */
230 server->global_list->clients = silc_idcache_alloc(0);
231 server->global_list->servers = silc_idcache_alloc(0);
232 server->global_list->channels = silc_idcache_alloc(0);
234 /* Allocate the entire socket list that is used in server. Eventually
235 all connections will have entry in this table (it is a table of
236 pointers to the actual object that is allocated individually
238 server->sockets = silc_calloc(SILC_SERVER_MAX_CONNECTIONS,
239 sizeof(*server->sockets));
241 for (i = 0; i < sock_count; i++) {
242 SilcSocketConnection newsocket = NULL;
244 /* Set socket to non-blocking mode */
245 silc_net_set_socket_nonblock(sock[i]);
246 server->sock = sock[i];
248 /* Create a Server ID for the server. */
249 silc_id_create_server_id(sock[i], server->rng, &id);
255 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
256 server->id_string_len = silc_id_get_len(SILC_ID_SERVER);
257 server->id_type = SILC_ID_SERVER;
258 server->server_name = server->config->server_info->server_name;
260 /* Add ourselves to the server list. We don't have a router yet
261 beacuse we haven't established a route yet. It will be done later.
262 For now, NULL is sent as router. This allocates new entry to
265 silc_idlist_add_server(server->local_list,
266 server->config->server_info->server_name,
267 server->server_type, server->id, NULL, NULL);
269 SILC_LOG_ERROR(("Could not add ourselves to cache"));
273 /* Add ourselves also to the socket table. The entry allocated above
274 is sent as argument for fast referencing in the future. */
275 silc_socket_alloc(sock[i], SILC_SOCKET_TYPE_SERVER, id_entry,
280 server->sockets[sock[i]] = newsocket;
282 /* Put the allocated socket pointer also to the entry allocated above
283 for fast back-referencing to the socket list. */
284 id_entry->connection = (void *)server->sockets[sock[i]];
285 server->id_entry = id_entry;
288 /* Register the task queues. In SILC we have by default three task queues.
289 One task queue for non-timeout tasks which perform different kind of
290 I/O on file descriptors, timeout task queue for timeout tasks, and,
291 generic non-timeout task queue whose tasks apply to all connections. */
292 silc_task_queue_alloc(&server->io_queue, TRUE);
293 if (!server->io_queue) {
296 silc_task_queue_alloc(&server->timeout_queue, TRUE);
297 if (!server->timeout_queue) {
300 silc_task_queue_alloc(&server->generic_queue, TRUE);
301 if (!server->generic_queue) {
305 /* Register protocols */
306 silc_server_protocols_register();
308 /* Initialize the scheduler */
309 silc_schedule_init(&server->io_queue, &server->timeout_queue,
310 &server->generic_queue,
311 SILC_SERVER_MAX_CONNECTIONS);
313 /* Add the first task to the queue. This is task that is executed by
314 timeout. It expires as soon as the caller calls silc_server_run. This
315 task performs authentication protocol and key exchange with our
317 silc_task_register(server->timeout_queue, sock[0],
318 silc_server_connect_to_router,
319 (void *)server, 0, 1,
321 SILC_TASK_PRI_NORMAL);
323 /* Add listener task to the queue. This task receives new connections to the
324 server. This task remains on the queue until the end of the program. */
325 silc_task_register(server->io_queue, sock[0],
326 silc_server_accept_new_connection,
327 (void *)server, 0, 0,
329 SILC_TASK_PRI_NORMAL);
330 server->listenning = TRUE;
332 /* If server connections has been configured then we must be router as
333 normal server cannot have server connections, only router connections. */
334 if (server->config->servers)
335 server->server_type = SILC_ROUTER;
337 SILC_LOG_DEBUG(("Server initialized"));
339 /* We are done here, return succesfully */
342 silc_task_queue_free(server->timeout_queue);
344 silc_task_queue_free(server->io_queue);
346 for (i = 0; i < sock_count; i++)
347 silc_net_close_server(sock[i]);
352 /* Stops the SILC server. This function is used to shutdown the server.
353 This is usually called after the scheduler has returned. After stopping
354 the server one should call silc_server_free. */
356 void silc_server_stop(SilcServer server)
358 SILC_LOG_DEBUG(("Stopping server"));
360 /* Stop the scheduler, although it might be already stopped. This
361 doesn't hurt anyone. This removes all the tasks and task queues,
363 silc_schedule_stop();
364 silc_schedule_uninit();
366 silc_server_protocols_unregister();
368 SILC_LOG_DEBUG(("Server stopped"));
371 /* The heart of the server. This runs the scheduler thus runs the server.
372 When this returns the server has been stopped and the program will
375 void silc_server_run(SilcServer server)
377 SILC_LOG_DEBUG(("Running server"));
379 /* Start the scheduler, the heart of the SILC server. When this returns
380 the program will be terminated. */
384 /* Timeout callback that will be called to retry connecting to remote
385 router. This is used by both normal and router server. This will wait
386 before retrying the connecting. The timeout is generated by exponential
387 backoff algorithm. */
389 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
391 SilcServerConnection sconn = (SilcServerConnection)context;
392 SilcServer server = sconn->server;
394 SILC_LOG_INFO(("Retrying connecting to a router"));
396 /* Calculate next timeout */
397 if (sconn->retry_count >= 1) {
398 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
399 if (sconn->retry_timeout > SILC_SERVER_RETRY_INTERVAL_MAX)
400 sconn->retry_timeout = SILC_SERVER_RETRY_INTERVAL_MAX;
402 sconn->retry_timeout = server->params->retry_interval_min;
404 sconn->retry_count++;
405 sconn->retry_timeout = sconn->retry_timeout +
406 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
408 /* If we've reached max retry count, give up. */
409 if (sconn->retry_count > server->params->retry_count &&
410 server->params->retry_keep_trying == FALSE) {
411 SILC_LOG_ERROR(("Could not connect to router, giving up"));
415 /* Wait one before retrying */
416 silc_task_register(server->timeout_queue, fd, silc_server_connect_router,
417 context, sconn->retry_timeout,
418 server->params->retry_interval_min_usec,
419 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
422 /* Generic routine to use connect to a router. */
424 SILC_TASK_CALLBACK(silc_server_connect_router)
426 SilcServerConnection sconn = (SilcServerConnection)context;
427 SilcServer server = sconn->server;
428 SilcSocketConnection newsocket;
429 SilcProtocol protocol;
430 SilcServerKEInternalContext *proto_ctx;
433 /* Connect to remote host */
434 sock = silc_net_create_connection(sconn->remote_port,
437 SILC_LOG_ERROR(("Could not connect to router"));
438 silc_task_register(server->timeout_queue, fd,
439 silc_server_connect_to_router_retry,
440 context, 0, 1, SILC_TASK_TIMEOUT,
441 SILC_TASK_PRI_NORMAL);
445 /* Set socket options */
446 silc_net_set_socket_nonblock(sock);
447 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
449 /* Create socket connection for the connection. Even though we
450 know that we are connecting to a router we will mark the socket
451 to be unknown connection until we have executed authentication
453 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
454 server->sockets[sock] = newsocket;
455 newsocket->hostname = sconn->remote_host;
456 newsocket->port = sconn->remote_port;
457 sconn->sock = newsocket;
459 /* Allocate internal protocol context. This is sent as context
461 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
462 proto_ctx->server = (void *)server;
463 proto_ctx->context = (void *)sconn;
464 proto_ctx->sock = newsocket;
465 proto_ctx->rng = server->rng;
466 proto_ctx->responder = FALSE;
468 /* Perform key exchange protocol. silc_server_connect_to_router_second
469 will be called after the protocol is finished. */
470 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
471 &protocol, proto_ctx,
472 silc_server_connect_to_router_second);
473 newsocket->protocol = protocol;
475 /* Register a timeout task that will be executed if the protocol
476 is not executed within set limit. */
477 proto_ctx->timeout_task =
478 silc_task_register(server->timeout_queue, sock,
479 silc_server_timeout_remote,
480 server, server->params->protocol_timeout,
481 server->params->protocol_timeout_usec,
485 /* Register the connection for network input and output. This sets
486 that scheduler will listen for incoming packets for this connection
487 and sets that outgoing packets may be sent to this connection as
488 well. However, this doesn't set the scheduler for outgoing traffic,
489 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
490 later when outgoing data is available. */
491 context = (void *)server;
492 SILC_REGISTER_CONNECTION_FOR_IO(sock);
494 /* Run the protocol */
495 protocol->execute(server->timeout_queue, 0, protocol, sock, 0, 0);
498 /* This function connects to our primary router or if we are a router this
499 establishes all our primary routes. This is called at the start of the
500 server to do authentication and key exchange with our router - called
503 SILC_TASK_CALLBACK(silc_server_connect_to_router)
505 SilcServer server = (SilcServer)context;
506 SilcServerConnection sconn;
508 SILC_LOG_DEBUG(("Connecting to router(s)"));
510 /* If we are normal SILC server we need to connect to our cell's
512 if (server->server_type == SILC_SERVER) {
513 SILC_LOG_DEBUG(("We are normal server"));
515 /* Create connection to the router, if configured. */
516 if (server->config->routers) {
518 /* Allocate connection object for hold connection specific stuff. */
519 sconn = silc_calloc(1, sizeof(*sconn));
520 sconn->server = server;
521 sconn->remote_host = server->config->routers->host;
522 sconn->remote_port = server->config->routers->port;
524 silc_task_register(server->timeout_queue, fd,
525 silc_server_connect_router,
526 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
527 SILC_TASK_PRI_NORMAL);
532 /* If we are a SILC router we need to establish all of our primary
534 if (server->server_type == SILC_ROUTER) {
535 SilcConfigServerSectionServerConnection *ptr;
537 SILC_LOG_DEBUG(("We are router"));
539 /* Create the connections to all our routes */
540 ptr = server->config->routers;
543 SILC_LOG_DEBUG(("Router connection [%s] %s:%d",
544 ptr->initiator ? "Initiator" : "Responder",
545 ptr->host, ptr->port));
547 if (ptr->initiator) {
548 /* Allocate connection object for hold connection specific stuff. */
549 sconn = silc_calloc(1, sizeof(*sconn));
550 sconn->server = server;
551 sconn->remote_host = ptr->host;
552 sconn->remote_port = ptr->port;
554 silc_task_register(server->timeout_queue, fd,
555 silc_server_connect_router,
556 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
557 SILC_TASK_PRI_NORMAL);
567 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
569 /* There wasn't a configured router, we will continue but we don't
570 have a connection to outside world. We will be standalone server. */
571 server->standalone = TRUE;
574 /* Second part of connecting to router(s). Key exchange protocol has been
575 executed and now we will execute authentication protocol. */
577 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
579 SilcProtocol protocol = (SilcProtocol)context;
580 SilcServerKEInternalContext *ctx =
581 (SilcServerKEInternalContext *)protocol->context;
582 SilcServer server = (SilcServer)ctx->server;
583 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
584 SilcSocketConnection sock = NULL;
585 SilcServerConnAuthInternalContext *proto_ctx;
587 SILC_LOG_DEBUG(("Start"));
589 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
590 /* Error occured during protocol */
591 silc_protocol_free(protocol);
593 silc_packet_context_free(ctx->packet);
595 silc_ske_free(ctx->ske);
597 silc_free(ctx->dest_id);
599 sock->protocol = NULL;
600 silc_server_disconnect_remote(server, sock, "Server closed connection: "
601 "Key exchange failed");
605 /* Allocate internal context for the authentication protocol. This
606 is sent as context for the protocol. */
607 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
608 proto_ctx->server = (void *)server;
609 proto_ctx->context = (void *)sconn;
610 proto_ctx->sock = sock = server->sockets[fd];
611 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
612 proto_ctx->dest_id_type = ctx->dest_id_type;
613 proto_ctx->dest_id = ctx->dest_id;
615 /* Resolve the authentication method used in this connection */
616 proto_ctx->auth_meth = SILC_PROTOCOL_CONN_AUTH_PASSWORD;
617 if (server->config->routers) {
618 SilcConfigServerSectionServerConnection *conn = NULL;
620 /* Check if we find a match from user configured connections */
621 conn = silc_config_server_find_router_conn(server->config,
625 /* Match found. Use the configured authentication method */
626 proto_ctx->auth_meth = conn->auth_meth;
627 if (conn->auth_data) {
628 proto_ctx->auth_data = strdup(conn->auth_data);
629 proto_ctx->auth_data_len = strlen(conn->auth_data);
632 /* No match found. */
639 /* Free old protocol as it is finished now */
640 silc_protocol_free(protocol);
642 silc_packet_context_free(ctx->packet);
644 sock->protocol = NULL;
646 /* Allocate the authentication protocol. This is allocated here
647 but we won't start it yet. We will be receiving party of this
648 protocol thus we will wait that connecting party will make
650 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
651 &sock->protocol, proto_ctx,
652 silc_server_connect_to_router_final);
654 /* Register timeout task. If the protocol is not executed inside
655 this timelimit the connection will be terminated. Currently
656 this is 15 seconds and is hard coded limit (XXX). */
657 proto_ctx->timeout_task =
658 silc_task_register(server->timeout_queue, sock->sock,
659 silc_server_timeout_remote,
660 (void *)server, 15, 0,
664 /* Run the protocol */
665 sock->protocol->execute(server->timeout_queue, 0,
666 sock->protocol, sock->sock, 0, 0);
669 /* Finalizes the connection to router. Registers a server task to the
670 queue so that we can accept new connections. */
672 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
674 SilcProtocol protocol = (SilcProtocol)context;
675 SilcServerConnAuthInternalContext *ctx =
676 (SilcServerConnAuthInternalContext *)protocol->context;
677 SilcServer server = (SilcServer)ctx->server;
678 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
679 SilcSocketConnection sock = ctx->sock;
680 SilcServerEntry id_entry;
682 unsigned char *id_string;
684 SILC_LOG_DEBUG(("Start"));
686 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
687 /* Error occured during protocol */
689 silc_free(ctx->dest_id);
690 silc_server_disconnect_remote(server, sock, "Server closed connection: "
691 "Authentication failed");
695 /* Add a task to the queue. This task receives new connections to the
696 server. This task remains on the queue until the end of the program. */
697 if (!server->listenning) {
698 silc_task_register(server->io_queue, server->sock,
699 silc_server_accept_new_connection,
700 (void *)server, 0, 0,
702 SILC_TASK_PRI_NORMAL);
703 server->listenning = TRUE;
706 /* Send NEW_SERVER packet to the router. We will become registered
707 to the SILC network after sending this packet. */
708 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
709 packet = silc_buffer_alloc(2 + 2 + SILC_ID_SERVER_LEN +
710 strlen(server->server_name));
711 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
712 silc_buffer_format(packet,
713 SILC_STR_UI_SHORT(SILC_ID_SERVER_LEN),
714 SILC_STR_UI_XNSTRING(id_string, SILC_ID_SERVER_LEN),
715 SILC_STR_UI_SHORT(strlen(server->server_name)),
716 SILC_STR_UI_XNSTRING(server->server_name,
717 strlen(server->server_name)),
720 /* Send the packet */
721 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
722 packet->data, packet->len, TRUE);
723 silc_buffer_free(packet);
724 silc_free(id_string);
726 SILC_LOG_DEBUG(("Connected to router %s", sock->hostname));
728 /* Add the connected router to local server list */
729 server->standalone = FALSE;
730 id_entry = silc_idlist_add_server(server->local_list, sock->hostname,
731 SILC_ROUTER, ctx->dest_id, NULL, sock);
734 silc_free(ctx->dest_id);
735 silc_server_disconnect_remote(server, sock, "Server closed connection: "
736 "Authentication failed");
740 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
741 silc_free(sock->user_data);
742 sock->user_data = (void *)id_entry;
743 sock->type = SILC_SOCKET_TYPE_ROUTER;
744 server->id_entry->router = id_entry;
745 server->router = id_entry;
746 server->router->data.registered = TRUE;
749 /* Free the temporary connection data context */
753 /* Free the protocol object */
754 silc_protocol_free(protocol);
756 silc_packet_context_free(ctx->packet);
758 silc_ske_free(ctx->ske);
760 sock->protocol = NULL;
763 /* Accepts new connections to the server. Accepting new connections are
764 done in three parts to make it async. */
766 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
768 SilcServer server = (SilcServer)context;
769 SilcSocketConnection newsocket;
770 SilcServerKEInternalContext *proto_ctx;
773 SILC_LOG_DEBUG(("Accepting new connection"));
775 server->stat.conn_attempts++;
777 sock = silc_net_accept_connection(server->sock);
779 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
780 server->stat.conn_failures++;
784 /* Check max connections */
785 if (sock > SILC_SERVER_MAX_CONNECTIONS) {
786 if (server->config->redirect) {
787 /* XXX Redirecting connection to somewhere else now?? */
788 /*silc_server_send_notify("Server is full, trying to redirect..."); */
790 SILC_LOG_ERROR(("Refusing connection, server is full"));
791 server->stat.conn_failures++;
796 /* Set socket options */
797 silc_net_set_socket_nonblock(sock);
798 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
800 /* We don't create a ID yet, since we don't know what type of connection
801 this is yet. But, we do add the connection to the socket table. */
802 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
803 server->sockets[sock] = newsocket;
805 /* XXX This MUST be done async as this will block the entire server
806 process. Either we have to do our own resolver stuff or in the future
807 we can use threads. */
808 /* Perform name and address lookups for the remote host. */
809 silc_net_check_host_by_sock(sock, &newsocket->hostname, &newsocket->ip);
810 if ((server->params->require_reverse_mapping && !newsocket->hostname) ||
812 SILC_LOG_ERROR(("IP/DNS lookup failed"));
813 server->stat.conn_failures++;
816 if (!newsocket->hostname)
817 newsocket->hostname = strdup(newsocket->ip);
819 SILC_LOG_INFO(("Incoming connection from %s (%s)", newsocket->hostname,
822 /* Allocate internal context for key exchange protocol. This is
823 sent as context for the protocol. */
824 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
825 proto_ctx->server = context;
826 proto_ctx->sock = newsocket;
827 proto_ctx->rng = server->rng;
828 proto_ctx->responder = TRUE;
830 /* Prepare the connection for key exchange protocol. We allocate the
831 protocol but will not start it yet. The connector will be the
832 initiator of the protocol thus we will wait for initiation from
833 there before we start the protocol. */
834 server->stat.auth_attempts++;
835 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
836 &newsocket->protocol, proto_ctx,
837 silc_server_accept_new_connection_second);
839 /* Register a timeout task that will be executed if the connector
840 will not start the key exchange protocol within 60 seconds. For
841 now, this is a hard coded limit. After 60 secs the connection will
842 be closed if the key exchange protocol has not been started. */
843 proto_ctx->timeout_task =
844 silc_task_register(server->timeout_queue, newsocket->sock,
845 silc_server_timeout_remote,
850 /* Register the connection for network input and output. This sets
851 that scheduler will listen for incoming packets for this connection
852 and sets that outgoing packets may be sent to this connection as well.
853 However, this doesn't set the scheduler for outgoing traffic, it
854 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
855 later when outgoing data is available. */
856 SILC_REGISTER_CONNECTION_FOR_IO(sock);
859 /* Second part of accepting new connection. Key exchange protocol has been
860 performed and now it is time to do little connection authentication
861 protocol to figure out whether this connection is client or server
862 and whether it has right to access this server (especially server
863 connections needs to be authenticated). */
865 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
867 SilcProtocol protocol = (SilcProtocol)context;
868 SilcServerKEInternalContext *ctx =
869 (SilcServerKEInternalContext *)protocol->context;
870 SilcServer server = (SilcServer)ctx->server;
871 SilcSocketConnection sock = NULL;
872 SilcServerConnAuthInternalContext *proto_ctx;
874 SILC_LOG_DEBUG(("Start"));
876 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
877 /* Error occured during protocol */
878 silc_protocol_free(protocol);
880 silc_packet_context_free(ctx->packet);
882 silc_ske_free(ctx->ske);
884 silc_free(ctx->dest_id);
887 sock->protocol = NULL;
888 silc_server_disconnect_remote(server, sock, "Server closed connection: "
889 "Key exchange failed");
890 server->stat.auth_failures++;
894 /* Allocate internal context for the authentication protocol. This
895 is sent as context for the protocol. */
896 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
897 proto_ctx->server = (void *)server;
898 proto_ctx->sock = sock = server->sockets[fd];
899 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
900 proto_ctx->responder = TRUE;
901 proto_ctx->dest_id_type = ctx->dest_id_type;
902 proto_ctx->dest_id = ctx->dest_id;
904 /* Free old protocol as it is finished now */
905 silc_protocol_free(protocol);
907 silc_packet_context_free(ctx->packet);
909 sock->protocol = NULL;
911 /* Allocate the authentication protocol. This is allocated here
912 but we won't start it yet. We will be receiving party of this
913 protocol thus we will wait that connecting party will make
915 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
916 &sock->protocol, proto_ctx,
917 silc_server_accept_new_connection_final);
919 /* Register timeout task. If the protocol is not executed inside
920 this timelimit the connection will be terminated. Currently
921 this is 60 seconds and is hard coded limit (XXX). */
922 proto_ctx->timeout_task =
923 silc_task_register(server->timeout_queue, sock->sock,
924 silc_server_timeout_remote,
925 (void *)server, 60, 0,
930 /* Final part of accepting new connection. The connection has now
931 been authenticated and keys has been exchanged. We also know whether
932 this is client or server connection. */
934 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
936 SilcProtocol protocol = (SilcProtocol)context;
937 SilcServerConnAuthInternalContext *ctx =
938 (SilcServerConnAuthInternalContext *)protocol->context;
939 SilcServer server = (SilcServer)ctx->server;
940 SilcSocketConnection sock = ctx->sock;
941 void *id_entry = NULL;
943 SILC_LOG_DEBUG(("Start"));
945 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
946 /* Error occured during protocol */
947 silc_protocol_free(protocol);
949 silc_packet_context_free(ctx->packet);
951 silc_ske_free(ctx->ske);
953 silc_free(ctx->dest_id);
956 sock->protocol = NULL;
957 silc_server_disconnect_remote(server, sock, "Server closed connection: "
958 "Authentication failed");
959 server->stat.auth_failures++;
963 sock->type = ctx->conn_type;
965 case SILC_SOCKET_TYPE_CLIENT:
967 SilcClientEntry client;
969 SILC_LOG_DEBUG(("Remote host is client"));
970 SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
973 /* Add the client to the client ID cache. The nickname and Client ID
974 and other information is created after we have received NEW_CLIENT
975 packet from client. */
976 client = silc_idlist_add_client(server->local_list,
977 NULL, NULL, NULL, NULL, NULL, sock);
979 SILC_LOG_ERROR(("Could not add new client to cache"));
980 silc_free(sock->user_data);
984 server->stat.my_clients++;
986 id_entry = (void *)client;
989 case SILC_SOCKET_TYPE_SERVER:
990 case SILC_SOCKET_TYPE_ROUTER:
992 SilcServerEntry new_server;
994 SILC_LOG_DEBUG(("Remote host is %s",
995 sock->type == SILC_SOCKET_TYPE_SERVER ?
996 "server" : "router"));
997 SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
998 sock->ip, sock->type == SILC_SOCKET_TYPE_SERVER ?
999 "server" : "router"));
1001 /* Add the server into server cache. The server name and Server ID
1002 is updated after we have received NEW_SERVER packet from the
1003 server. We mark ourselves as router for this server if we really
1006 silc_idlist_add_server(server->local_list, NULL,
1007 sock->type == SILC_SOCKET_TYPE_SERVER ?
1008 SILC_SERVER : SILC_ROUTER, NULL,
1009 sock->type == SILC_SOCKET_TYPE_SERVER ?
1010 server->id_entry : NULL, sock);
1012 SILC_LOG_ERROR(("Could not add new server to cache"));
1013 silc_free(sock->user_data);
1017 if (sock->type == SILC_SOCKET_TYPE_SERVER)
1018 server->stat.my_servers++;
1020 server->stat.my_routers++;
1021 server->stat.servers++;
1023 id_entry = (void *)new_server;
1025 /* There is connection to other server now, if it is router then
1026 we will have connection to outside world. If we are router but
1027 normal server connected to us then we will remain standalone,
1028 if we are standlone. */
1029 if (server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER) {
1030 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1031 server->standalone = FALSE;
1032 if (!server->id_entry->router) {
1033 server->id_entry->router = id_entry;
1034 server->router = id_entry;
1043 /* Add the common data structure to the ID entry. */
1045 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1047 /* Add to sockets internal pointer for fast referencing */
1048 silc_free(sock->user_data);
1049 sock->user_data = id_entry;
1051 /* Connection has been fully established now. Everything is ok. */
1052 SILC_LOG_DEBUG(("New connection authenticated"));
1054 silc_protocol_free(protocol);
1056 silc_packet_context_free(ctx->packet);
1058 silc_ske_free(ctx->ske);
1060 silc_free(ctx->dest_id);
1062 sock->protocol = NULL;
1065 /* This function is used to read packets from network and send packets to
1066 network. This is usually a generic task. */
1068 SILC_TASK_CALLBACK(silc_server_packet_process)
1070 SilcServer server = (SilcServer)context;
1071 SilcSocketConnection sock = server->sockets[fd];
1072 SilcIDListData idata;
1073 SilcCipher cipher = NULL;
1074 SilcHmac hmac = NULL;
1080 SILC_LOG_DEBUG(("Processing packet"));
1082 /* Packet sending */
1084 if (type == SILC_TASK_WRITE) {
1085 server->stat.packets_sent++;
1087 if (sock->outbuf->data - sock->outbuf->head)
1088 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1090 ret = silc_server_packet_send_real(server, sock, TRUE);
1092 /* If returned -2 could not write to connection now, will do
1097 /* The packet has been sent and now it is time to set the connection
1098 back to only for input. When there is again some outgoing data
1099 available for this connection it will be set for output as well.
1100 This call clears the output setting and sets it only for input. */
1101 SILC_SET_CONNECTION_FOR_INPUT(fd);
1102 SILC_UNSET_OUTBUF_PENDING(sock);
1104 silc_buffer_clear(sock->outbuf);
1108 /* Packet receiving */
1110 /* Read some data from connection */
1111 ret = silc_packet_receive(sock);
1117 SILC_LOG_DEBUG(("Read EOF"));
1119 /* If connection is disconnecting already we will finally
1120 close the connection */
1121 if (SILC_IS_DISCONNECTING(sock)) {
1122 if (sock->user_data)
1123 silc_server_free_sock_user_data(server, sock);
1124 silc_server_close_connection(server, sock);
1128 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1130 if (sock->user_data)
1131 silc_server_free_sock_user_data(server, sock);
1132 silc_server_close_connection(server, sock);
1136 /* If connection is disconnecting or disconnected we will ignore
1138 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1139 SILC_LOG_DEBUG(("Ignoring read data from invalid connection"));
1143 server->stat.packets_received++;
1145 /* Get keys and stuff from ID entry */
1146 idata = (SilcIDListData)sock->user_data;
1148 idata->last_receive = time(NULL);
1149 cipher = idata->receive_key;
1153 /* Process the packet. This will call the parser that will then
1154 decrypt and parse the packet. */
1155 silc_packet_receive_process(sock, cipher, hmac, silc_server_packet_parse,
1159 /* Parses whole packet, received earlier. */
1161 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1163 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1164 SilcServer server = (SilcServer)parse_ctx->context;
1165 SilcSocketConnection sock = parse_ctx->sock;
1166 SilcPacketContext *packet = parse_ctx->packet;
1169 SILC_LOG_DEBUG(("Start"));
1171 /* Decrypt the received packet */
1172 ret = silc_packet_decrypt(parse_ctx->cipher, parse_ctx->hmac,
1173 packet->buffer, packet);
1178 /* Parse the packet. Packet type is returned. */
1179 ret = silc_packet_parse(packet);
1181 /* Parse the packet header in special way as this is "special"
1183 ret = silc_packet_parse_special(packet);
1186 if (ret == SILC_PACKET_NONE)
1189 if (server->server_type == SILC_ROUTER) {
1190 /* Route the packet if it is not destined to us. Other ID types but
1191 server are handled separately after processing them. */
1192 if (packet->dst_id_type == SILC_ID_SERVER &&
1193 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1194 SILC_ID_SERVER_COMPARE(packet->dst_id, server->id_string)) {
1196 /* Route the packet to fastest route for the destination ID */
1197 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_type);
1198 silc_server_packet_route(server,
1199 silc_server_route_get(server, id,
1200 packet->dst_id_type),
1206 /* Broadcast packet if it is marked as broadcast packet and it is
1207 originated from router and we are router. */
1208 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1209 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
1210 silc_server_packet_broadcast(server, server->router->connection, packet);
1214 /* Parse the incoming packet type */
1215 silc_server_packet_parse_type(server, sock, packet);
1218 silc_buffer_clear(sock->inbuf);
1219 silc_packet_context_free(packet);
1220 silc_free(parse_ctx);
1223 /* Parser callback called by silc_packet_receive_process. This merely
1224 registers timeout that will handle the actual parsing when appropriate. */
1226 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1228 SilcServer server = (SilcServer)parser_context->context;
1229 SilcSocketConnection sock = parser_context->sock;
1231 switch (sock->type) {
1232 case SILC_SOCKET_TYPE_CLIENT:
1233 case SILC_SOCKET_TYPE_UNKNOWN:
1234 /* Parse the packet with timeout */
1235 silc_task_register(server->timeout_queue, sock->sock,
1236 silc_server_packet_parse_real,
1237 (void *)parser_context, 0, 100000,
1239 SILC_TASK_PRI_NORMAL);
1241 case SILC_SOCKET_TYPE_SERVER:
1242 case SILC_SOCKET_TYPE_ROUTER:
1243 /* Packets from servers are parsed as soon as possible */
1244 silc_task_register(server->timeout_queue, sock->sock,
1245 silc_server_packet_parse_real,
1246 (void *)parser_context, 0, 1,
1248 SILC_TASK_PRI_NORMAL);
1255 /* Parses the packet type and calls what ever routines the packet type
1256 requires. This is done for all incoming packets. */
1258 void silc_server_packet_parse_type(SilcServer server,
1259 SilcSocketConnection sock,
1260 SilcPacketContext *packet)
1262 SilcPacketType type = packet->type;
1264 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1266 /* Parse the packet type */
1268 case SILC_PACKET_DISCONNECT:
1269 SILC_LOG_DEBUG(("Disconnect packet"));
1272 case SILC_PACKET_SUCCESS:
1274 * Success received for something. For now we can have only
1275 * one protocol for connection executing at once hence this
1276 * success message is for whatever protocol is executing currently.
1278 SILC_LOG_DEBUG(("Success packet"));
1279 if (sock->protocol) {
1280 sock->protocol->execute(server->timeout_queue, 0,
1281 sock->protocol, sock->sock, 0, 0);
1285 case SILC_PACKET_FAILURE:
1287 * Failure received for something. For now we can have only
1288 * one protocol for connection executing at once hence this
1289 * failure message is for whatever protocol is executing currently.
1291 SILC_LOG_DEBUG(("Failure packet"));
1292 if (sock->protocol) {
1293 /* XXX Audit the failure type */
1294 sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
1295 sock->protocol->execute(server->timeout_queue, 0,
1296 sock->protocol, sock->sock, 0, 0);
1300 case SILC_PACKET_REJECT:
1301 SILC_LOG_DEBUG(("Reject packet"));
1305 case SILC_PACKET_NOTIFY:
1307 * Received notify packet. Server can receive notify packets from
1308 * router. Server then relays the notify messages to clients if needed.
1310 SILC_LOG_DEBUG(("Notify packet"));
1311 silc_server_notify(server, sock, packet);
1317 case SILC_PACKET_CHANNEL_MESSAGE:
1319 * Received channel message. Channel messages are special packets
1320 * (although probably most common ones) thus they are handled
1323 SILC_LOG_DEBUG(("Channel Message packet"));
1324 silc_server_channel_message(server, sock, packet);
1327 case SILC_PACKET_CHANNEL_KEY:
1329 * Received key for channel. As channels are created by the router
1330 * the keys are as well. We will distribute the key to all of our
1331 * locally connected clients on the particular channel. Router
1332 * never receives this channel and thus is ignored.
1334 SILC_LOG_DEBUG(("Channel Key packet"));
1335 silc_server_channel_key(server, sock, packet);
1341 case SILC_PACKET_COMMAND:
1343 * Recived command. Processes the command request and allocates the
1344 * command context and calls the command.
1346 SILC_LOG_DEBUG(("Command packet"));
1347 silc_server_command_process(server, sock, packet);
1350 case SILC_PACKET_COMMAND_REPLY:
1352 * Received command reply packet. Received command reply to command. It
1353 * may be reply to command sent by us or reply to command sent by client
1354 * that we've routed further.
1356 SILC_LOG_DEBUG(("Command Reply packet"));
1357 silc_server_command_reply(server, sock, packet);
1361 * Private Message packets
1363 case SILC_PACKET_PRIVATE_MESSAGE:
1365 * Received private message packet. The packet is coming from either
1368 SILC_LOG_DEBUG(("Private Message packet"));
1369 silc_server_private_message(server, sock, packet);
1372 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1374 * Private message key packet.
1379 * Key Exchange protocol packets
1381 case SILC_PACKET_KEY_EXCHANGE:
1382 SILC_LOG_DEBUG(("KE packet"));
1383 if (sock->protocol && sock->protocol->protocol->type
1384 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1386 SilcServerKEInternalContext *proto_ctx =
1387 (SilcServerKEInternalContext *)sock->protocol->context;
1389 proto_ctx->packet = silc_packet_context_dup(packet);
1391 /* Let the protocol handle the packet */
1392 sock->protocol->execute(server->timeout_queue, 0,
1393 sock->protocol, sock->sock, 0, 100000);
1395 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1396 "protocol active, packet dropped."));
1398 /* XXX Trigger KE protocol?? Rekey actually, maybe. */
1402 case SILC_PACKET_KEY_EXCHANGE_1:
1403 SILC_LOG_DEBUG(("KE 1 packet"));
1404 if (sock->protocol && sock->protocol->protocol->type
1405 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1407 SilcServerKEInternalContext *proto_ctx =
1408 (SilcServerKEInternalContext *)sock->protocol->context;
1410 if (proto_ctx->packet)
1411 silc_packet_context_free(proto_ctx->packet);
1413 proto_ctx->packet = silc_packet_context_dup(packet);
1414 proto_ctx->dest_id_type = packet->src_id_type;
1415 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_type);
1417 /* Let the protocol handle the packet */
1418 sock->protocol->execute(server->timeout_queue, 0,
1419 sock->protocol, sock->sock,
1422 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1423 "protocol active, packet dropped."));
1427 case SILC_PACKET_KEY_EXCHANGE_2:
1428 SILC_LOG_DEBUG(("KE 2 packet"));
1429 if (sock->protocol && sock->protocol->protocol->type
1430 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1432 SilcServerKEInternalContext *proto_ctx =
1433 (SilcServerKEInternalContext *)sock->protocol->context;
1435 if (proto_ctx->packet)
1436 silc_packet_context_free(proto_ctx->packet);
1438 proto_ctx->packet = silc_packet_context_dup(packet);
1439 proto_ctx->dest_id_type = packet->src_id_type;
1440 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_type);
1442 /* Let the protocol handle the packet */
1443 sock->protocol->execute(server->timeout_queue, 0,
1444 sock->protocol, sock->sock,
1447 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1448 "protocol active, packet dropped."));
1452 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1454 * Connection authentication request packet. When we receive this packet
1455 * we will send to the other end information about our mandatory
1456 * authentication method for the connection. This packet maybe received
1459 SILC_LOG_DEBUG(("Connection authentication request packet"));
1463 * Connection Authentication protocol packets
1465 case SILC_PACKET_CONNECTION_AUTH:
1466 /* Start of the authentication protocol. We receive here the
1467 authentication data and will verify it. */
1468 SILC_LOG_DEBUG(("Connection auth packet"));
1469 if (sock->protocol && sock->protocol->protocol->type
1470 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1472 SilcServerConnAuthInternalContext *proto_ctx =
1473 (SilcServerConnAuthInternalContext *)sock->protocol->context;
1475 proto_ctx->packet = silc_packet_context_dup(packet);
1477 /* Let the protocol handle the packet */
1478 sock->protocol->execute(server->timeout_queue, 0,
1479 sock->protocol, sock->sock, 0, 0);
1481 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1482 "protocol active, packet dropped."));
1486 case SILC_PACKET_NEW_ID:
1488 * Received New ID packet. This includes some new ID that has been
1489 * created. It may be for client, server or channel. This is the way
1490 * to distribute information about new registered entities in the
1493 SILC_LOG_DEBUG(("New ID packet"));
1494 silc_server_new_id(server, sock, packet);
1497 case SILC_PACKET_NEW_CLIENT:
1499 * Received new client packet. This includes client information that
1500 * we will use to create initial client ID. After creating new
1501 * ID we will send it to the client.
1503 SILC_LOG_DEBUG(("New Client packet"));
1504 silc_server_new_client(server, sock, packet);
1507 case SILC_PACKET_NEW_SERVER:
1509 * Received new server packet. This includes Server ID and some other
1510 * information that we may save. This is received after server has
1513 SILC_LOG_DEBUG(("New Server packet"));
1514 silc_server_new_server(server, sock, packet);
1517 case SILC_PACKET_NEW_CHANNEL:
1519 * Received new channel packet. Information about new channel in the
1520 * network are distributed using this packet.
1522 SILC_LOG_DEBUG(("New Channel packet"));
1523 silc_server_new_channel(server, sock, packet);
1526 case SILC_PACKET_NEW_CHANNEL_USER:
1528 * Received new channel user packet. Information about new users on a
1529 * channel are distributed between routers using this packet. The
1530 * router receiving this will redistribute it and also sent JOIN notify
1531 * to local clients on the same channel. Normal server sends JOIN notify
1532 * to its local clients on the channel.
1534 SILC_LOG_DEBUG(("New Channel User packet"));
1535 silc_server_new_channel_user(server, sock, packet);
1538 case SILC_PACKET_NEW_CHANNEL_LIST:
1540 * List of new channel packets received. This is usually received when
1541 * existing server or router connects to us and distributes information
1542 * of all channels it has.
1546 case SILC_PACKET_NEW_CHANNEL_USER_LIST:
1548 * List of new channel user packets received. This is usually received
1549 * when existing server or router connects to us and distributes
1550 * information of all channel users it has.
1554 case SILC_PACKET_REPLACE_ID:
1556 * Received replace ID packet. This sends the old ID that is to be
1557 * replaced with the new one included into the packet. Client must not
1560 SILC_LOG_DEBUG(("Replace ID packet"));
1561 silc_server_replace_id(server, sock, packet);
1564 case SILC_PACKET_REMOVE_ID:
1566 * Received remove ID Packet.
1568 SILC_LOG_DEBUG(("Remove ID packet"));
1569 silc_server_remove_id(server, sock, packet);
1572 case SILC_PACKET_REMOVE_CHANNEL_USER:
1574 * Received packet to remove user from a channel. Routers notify other
1575 * routers about a user leaving a channel.
1577 SILC_LOG_DEBUG(("Remove Channel User packet"));
1578 silc_server_remove_channel_user(server, sock, packet);
1582 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
1588 /* Closes connection to socket connection */
1590 void silc_server_close_connection(SilcServer server,
1591 SilcSocketConnection sock)
1593 SILC_LOG_DEBUG(("Closing connection %d", sock->sock));
1595 /* We won't listen for this connection anymore */
1596 silc_schedule_unset_listen_fd(sock->sock);
1598 /* Unregister all tasks */
1599 silc_task_unregister_by_fd(server->io_queue, sock->sock);
1600 silc_task_unregister_by_fd(server->timeout_queue, sock->sock);
1602 /* Close the actual connection */
1603 silc_net_close_connection(sock->sock);
1604 server->sockets[sock->sock] = NULL;
1605 silc_socket_free(sock);
1608 /* Sends disconnect message to remote connection and disconnects the
1611 void silc_server_disconnect_remote(SilcServer server,
1612 SilcSocketConnection sock,
1613 const char *fmt, ...)
1616 unsigned char buf[4096];
1621 memset(buf, 0, sizeof(buf));
1623 vsprintf(buf, fmt, ap);
1626 SILC_LOG_DEBUG(("Disconnecting remote host"));
1628 /* Notify remote end that the conversation is over. The notify message
1629 is tried to be sent immediately. */
1630 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
1631 buf, strlen(buf), TRUE);
1633 /* Mark the connection to be disconnected */
1634 SILC_SET_DISCONNECTED(sock);
1635 silc_server_close_connection(server, sock);
1638 /* Free's user_data pointer from socket connection object. This also sends
1639 appropriate notify packets to the network to inform about leaving
1642 void silc_server_free_sock_user_data(SilcServer server,
1643 SilcSocketConnection sock)
1645 SILC_LOG_DEBUG(("Start"));
1647 switch(sock->type) {
1648 case SILC_SOCKET_TYPE_CLIENT:
1650 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
1652 /* Remove client from all channels */
1653 silc_server_remove_from_channels(server, sock, user_data);
1655 /* XXX must take some info to history before freeing */
1657 /* Send REMOVE_ID packet to routers. */
1658 if (!server->standalone && server->router)
1659 silc_server_send_remove_id(server, server->router->connection,
1660 server->server_type == SILC_SERVER ?
1661 FALSE : TRUE, user_data->id,
1662 SILC_ID_CLIENT_LEN, SILC_ID_CLIENT);
1664 /* Free the client entry and everything in it */
1665 silc_idlist_del_data(user_data);
1666 silc_idlist_del_client(server->local_list, user_data);
1667 server->stat.my_clients--;
1670 case SILC_SOCKET_TYPE_SERVER:
1671 case SILC_SOCKET_TYPE_ROUTER:
1673 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
1675 /* Send REMOVE_ID packet to routers. */
1676 if (!server->standalone && server->router)
1677 silc_server_send_remove_id(server, server->router->connection,
1678 server->server_type == SILC_SERVER ?
1679 FALSE : TRUE, user_data->id,
1680 SILC_ID_CLIENT_LEN, SILC_ID_CLIENT);
1682 /* Free the server entry */
1683 silc_idlist_del_data(user_data);
1684 silc_idlist_del_server(server->local_list, user_data);
1685 server->stat.my_servers--;
1690 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
1692 silc_idlist_del_data(user_data);
1693 silc_free(user_data);
1698 sock->user_data = NULL;
1701 /* Checks whether given channel has global users. If it does this returns
1702 TRUE and FALSE if there is only locally connected clients on the channel. */
1704 int silc_server_channel_has_global(SilcChannelEntry channel)
1706 SilcChannelClientEntry chl;
1708 silc_list_start(channel->user_list);
1709 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
1710 if (chl->client->router)
1717 /* Checks whether given channel has locally connected users. If it does this
1718 returns TRUE and FALSE if there is not one locally connected client. */
1720 int silc_server_channel_has_local(SilcChannelEntry channel)
1722 SilcChannelClientEntry chl;
1724 silc_list_start(channel->user_list);
1725 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
1726 if (!chl->client->router)
1733 /* Removes client from all channels it has joined. This is used when client
1734 connection is disconnected. If the client on a channel is last, the
1735 channel is removed as well. This sends the SIGNOFF notify types. */
1737 void silc_server_remove_from_channels(SilcServer server,
1738 SilcSocketConnection sock,
1739 SilcClientEntry client)
1741 SilcChannelEntry channel;
1742 SilcChannelClientEntry chl;
1743 SilcBuffer chidp, clidp;
1745 SILC_LOG_DEBUG(("Start"));
1747 if (!client || !client->id)
1750 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
1752 /* Remove the client from all channels. The client is removed from
1753 the channels' user list. */
1754 silc_list_start(client->channels);
1755 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
1756 channel = chl->channel;
1757 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
1759 /* Remove from list */
1760 silc_list_del(client->channels, chl);
1762 /* If this client is last one on the channel the channel
1763 is removed all together. */
1764 if (silc_list_count(channel->user_list) < 2) {
1766 /* However, if the channel has marked global users then the
1767 channel is not created locally, and this does not remove the
1768 channel globally from SILC network, in this case we will
1769 notify that this client has left the channel. */
1770 if (channel->global_users)
1771 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
1772 SILC_NOTIFY_TYPE_SIGNOFF, 1,
1773 clidp->data, clidp->len);
1775 silc_idlist_del_channel(server->local_list, channel);
1776 server->stat.my_channels--;
1780 /* Remove from list */
1781 silc_list_del(channel->user_list, chl);
1783 server->stat.my_chanclients--;
1785 /* Send notify to channel about client leaving SILC and thus
1786 the entire channel. */
1787 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
1788 SILC_NOTIFY_TYPE_SIGNOFF, 1,
1789 clidp->data, clidp->len);
1790 silc_buffer_free(chidp);
1793 silc_buffer_free(clidp);
1796 /* Removes client from one channel. This is used for example when client
1797 calls LEAVE command to remove itself from the channel. Returns TRUE
1798 if channel still exists and FALSE if the channel is removed when
1799 last client leaves the channel. If `notify' is FALSE notify messages
1802 int silc_server_remove_from_one_channel(SilcServer server,
1803 SilcSocketConnection sock,
1804 SilcChannelEntry channel,
1805 SilcClientEntry client,
1808 SilcChannelEntry ch;
1809 SilcChannelClientEntry chl;
1812 SILC_LOG_DEBUG(("Start"));
1814 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
1816 /* Remove the client from the channel. The client is removed from
1817 the channel's user list. */
1818 silc_list_start(client->channels);
1819 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
1820 if (chl->channel != channel)
1825 /* Remove from list */
1826 silc_list_del(client->channels, chl);
1828 /* If this client is last one on the channel the channel
1829 is removed all together. */
1830 if (silc_list_count(channel->user_list) < 2) {
1831 /* Notify about leaving client if this channel has global users. */
1832 if (notify && channel->global_users)
1833 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
1834 SILC_NOTIFY_TYPE_LEAVE, 1,
1835 clidp->data, clidp->len);
1837 silc_idlist_del_channel(server->local_list, channel);
1838 silc_buffer_free(clidp);
1839 server->stat.my_channels--;
1843 /* Remove from list */
1844 silc_list_del(channel->user_list, chl);
1846 server->stat.my_chanclients--;
1848 /* If there is no global users on the channel anymore mark the channel
1849 as local channel. */
1850 if (server->server_type == SILC_SERVER &&
1851 !silc_server_channel_has_global(channel))
1852 channel->global_users = FALSE;
1854 /* If tehre is not at least one local user on the channel then we don't
1855 need the channel entry anymore, we can remove it safely. */
1856 if (server->server_type == SILC_SERVER &&
1857 !silc_server_channel_has_local(channel)) {
1858 silc_idlist_del_channel(server->local_list, channel);
1859 silc_buffer_free(clidp);
1860 server->stat.my_channels--;
1864 /* Send notify to channel about client leaving the channel */
1866 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
1867 SILC_NOTIFY_TYPE_LEAVE, 1,
1868 clidp->data, clidp->len);
1872 silc_buffer_free(clidp);
1876 /* Returns TRUE if the given client is on the channel. FALSE if not.
1877 This works because we assure that the user list on the channel is
1878 always in up to date thus we can only check the channel list from
1879 `client' which is faster than checking the user list from `channel'. */
1881 int silc_server_client_on_channel(SilcClientEntry client,
1882 SilcChannelEntry channel)
1884 SilcChannelClientEntry chl;
1886 if (!client || !channel)
1889 silc_list_start(client->channels);
1890 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END)
1891 if (chl->channel == channel)
1897 /* Timeout callback. This is called if connection is idle or for some
1898 other reason is not responding within some period of time. This
1899 disconnects the remote end. */
1901 SILC_TASK_CALLBACK(silc_server_timeout_remote)
1903 SilcServerConnection sconn = (SilcServerConnection)context;
1904 SilcSocketConnection sock = sconn->server->sockets[fd];
1909 silc_server_disconnect_remote(sconn->server, sock,
1910 "Server closed connection: "
1911 "Connection timeout");
1914 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
1915 function may be used only by router. In real SILC network all channels
1916 are created by routers thus this function is never used by normal
1919 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
1920 SilcServerID *router_id,
1924 SilcChannelID *channel_id;
1925 SilcChannelEntry entry;
1928 SILC_LOG_DEBUG(("Creating new channel"));
1933 /* Allocate cipher */
1934 silc_cipher_alloc(cipher, &key);
1936 channel_name = strdup(channel_name);
1938 /* Create the channel */
1939 silc_id_create_channel_id(router_id, server->rng, &channel_id);
1940 entry = silc_idlist_add_channel(server->local_list, channel_name,
1941 SILC_CHANNEL_MODE_NONE, channel_id,
1944 silc_free(channel_name);
1948 /* Now create the actual key material */
1949 silc_server_create_channel_key(server, entry, 16);
1951 /* Notify other routers about the new channel. We send the packet
1952 to our primary route. */
1953 if (server->standalone == FALSE) {
1954 silc_server_send_new_channel(server, server->router->connection, TRUE,
1955 channel_name, entry->id, SILC_ID_CHANNEL_LEN);
1958 server->stat.my_channels++;
1963 /* Generates new channel key. This is used to create the initial channel key
1964 but also to re-generate new key for channel. If `key_len' is provided
1965 it is the bytes of the key length. */
1967 void silc_server_create_channel_key(SilcServer server,
1968 SilcChannelEntry channel,
1969 unsigned int key_len)
1972 unsigned char channel_key[32];
1975 if (!channel->channel_key)
1976 silc_cipher_alloc("twofish", &channel->channel_key);
1980 else if (channel->key_len)
1981 len = channel->key_len / 8;
1983 len = sizeof(channel_key);
1985 /* Create channel key */
1986 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
1989 channel->channel_key->cipher->set_key(channel->channel_key->context,
1992 /* Remove old key if exists */
1994 memset(channel->key, 0, channel->key_len / 8);
1995 silc_free(channel->key);
1999 channel->key_len = len * 8;
2000 channel->key = silc_calloc(len, sizeof(*channel->key));
2001 memcpy(channel->key, channel_key, len);
2002 memset(channel_key, 0, sizeof(channel_key));
2005 /* Saves the channel key found in the encoded `key_payload' buffer. This
2006 function is used when we receive Channel Key Payload and also when we're
2007 processing JOIN command reply. Returns entry to the channel. */
2009 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
2010 SilcBuffer key_payload,
2011 SilcChannelEntry channel)
2013 SilcChannelKeyPayload payload = NULL;
2014 SilcChannelID *id = NULL;
2016 unsigned int tmp_len;
2019 /* Decode channel key payload */
2020 payload = silc_channel_key_payload_parse(key_payload);
2022 SILC_LOG_ERROR(("Bad channel key payload, dropped"));
2027 /* Get the channel entry */
2030 /* Get channel ID */
2031 tmp = silc_channel_key_get_id(payload, &tmp_len);
2032 id = silc_id_str2id(tmp, SILC_ID_CHANNEL);
2038 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
2040 SILC_LOG_ERROR(("Received key for non-existent channel"));
2045 tmp = silc_channel_key_get_key(payload, &tmp_len);
2051 cipher = silc_channel_key_get_cipher(payload, NULL);;
2057 /* Remove old key if exists */
2059 memset(channel->key, 0, channel->key_len / 8);
2060 silc_free(channel->key);
2061 silc_cipher_free(channel->channel_key);
2064 /* Create new cipher */
2065 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
2071 channel->key_len = tmp_len * 8;
2072 channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
2073 memcpy(channel->key, tmp, tmp_len);
2074 channel->channel_key->cipher->set_key(channel->channel_key->context,
2081 silc_channel_key_payload_free(payload);