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)
76 if (server->local_list)
77 silc_free(server->local_list);
78 if (server->global_list)
79 silc_free(server->global_list);
81 silc_rng_free(server->rng);
83 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
84 silc_dlist_del(server->sim, sim);
87 silc_dlist_uninit(server->sim);
90 silc_free(server->params);
92 if (server->pending_commands)
93 silc_dlist_uninit(server->pending_commands);
95 silc_math_primegen_uninit(); /* XXX */
100 /* Initializes the entire SILC server. This is called always before running
101 the server. This is called only once at the initialization of the program.
102 This binds the server to its listenning port. After this function returns
103 one should call silc_server_run to start the server. This returns TRUE
104 when everything is ok to run the server. Configuration file must be
105 read and parsed before calling this. */
107 int silc_server_init(SilcServer server)
109 int *sock = NULL, sock_count = 0, i;
111 SilcServerEntry id_entry;
113 SILC_LOG_DEBUG(("Initializing server"));
115 assert(server->config);
117 /* XXX After server is made as Silc Server Library this can be given
118 as argument, for now this is hard coded */
119 server->params = silc_calloc(1, sizeof(*server->params));
120 server->params->retry_count = SILC_SERVER_RETRY_COUNT;
121 server->params->retry_interval_min = SILC_SERVER_RETRY_INTERVAL_MIN;
122 server->params->retry_interval_max = SILC_SERVER_RETRY_INTERVAL_MAX;
123 server->params->retry_keep_trying = FALSE;
124 server->params->protocol_timeout = 60;
126 /* Set log files where log message should be saved. */
127 server->config->server = server;
128 silc_config_server_setlogfiles(server->config);
130 /* Register all configured ciphers, PKCS and hash functions. */
131 silc_config_server_register_ciphers(server->config);
132 silc_config_server_register_pkcs(server->config);
133 silc_config_server_register_hashfuncs(server->config);
135 /* Initialize random number generator for the server. */
136 server->rng = silc_rng_alloc();
137 silc_rng_init(server->rng);
138 silc_math_primegen_init(); /* XXX */
140 /* Initialize hash functions for server to use */
141 silc_hash_alloc("md5", &server->md5hash);
142 silc_hash_alloc("sha1", &server->sha1hash);
144 /* Initialize none cipher */
145 silc_cipher_alloc("none", &server->none_cipher);
147 /* XXXXX Generate RSA key pair */
149 unsigned char *public_key;
150 unsigned char *private_key;
151 unsigned int pk_len, prv_len;
154 if (stat("pubkey.pub", &st) < 0 && stat("privkey.prv", &st) < 0) {
156 if (silc_pkcs_alloc("rsa", &server->pkcs) == FALSE) {
157 SILC_LOG_ERROR(("Could not create RSA key pair"));
161 if (server->pkcs->pkcs->init(server->pkcs->context,
162 1024, server->rng) == FALSE) {
163 SILC_LOG_ERROR(("Could not generate RSA key pair"));
167 public_key = server->pkcs->pkcs->get_public_key(server->pkcs->context,
169 private_key = server->pkcs->pkcs->get_private_key(server->pkcs->context,
172 SILC_LOG_HEXDUMP(("public key"), public_key, pk_len);
173 SILC_LOG_HEXDUMP(("private key"), private_key, prv_len);
176 silc_pkcs_public_key_alloc("rsa", "UN=root, HN=dummy",
178 server->private_key =
179 silc_pkcs_private_key_alloc("rsa", private_key, prv_len);
182 silc_pkcs_save_public_key("pubkey.pub", server->public_key,
184 silc_pkcs_save_private_key("privkey.prv", server->private_key, NULL,
187 memset(public_key, 0, pk_len);
188 memset(private_key, 0, prv_len);
189 silc_free(public_key);
190 silc_free(private_key);
192 silc_pkcs_load_public_key("pubkey.pub", &server->public_key,
194 silc_pkcs_load_private_key("privkey.prv", &server->private_key,
199 /* Create a listening server. Note that our server can listen on
200 multiple ports. All listeners are created here and now. */
201 /* XXX Still check this whether to use server_info or listen_port. */
203 while(server->config->listen_port) {
206 tmp = silc_net_create_server(server->config->listen_port->port,
207 server->config->listen_port->host);
211 sock = silc_realloc(sock, (sizeof(int *) * (sock_count + 1)));
212 sock[sock_count] = tmp;
213 server->config->listen_port = server->config->listen_port->next;
217 /* Initialize ID caches */
218 server->local_list->clients = silc_idcache_alloc(0);
219 server->local_list->servers = silc_idcache_alloc(0);
220 server->local_list->channels = silc_idcache_alloc(0);
222 /* XXX for now these are allocated for normal server as well as these
223 hold some global information that the server has fetched from its
224 router. For router these are used as they are supposed to be used
225 on router. The XXX can be remoevd later if this is the way we are
226 going to do this in the normal server as well. */
227 server->global_list->clients = silc_idcache_alloc(0);
228 server->global_list->servers = silc_idcache_alloc(0);
229 server->global_list->channels = silc_idcache_alloc(0);
231 /* Allocate the entire socket list that is used in server. Eventually
232 all connections will have entry in this table (it is a table of
233 pointers to the actual object that is allocated individually
235 server->sockets = silc_calloc(SILC_SERVER_MAX_CONNECTIONS,
236 sizeof(*server->sockets));
238 for (i = 0; i < sock_count; i++) {
239 SilcSocketConnection newsocket = NULL;
241 /* Set socket to non-blocking mode */
242 silc_net_set_socket_nonblock(sock[i]);
243 server->sock = sock[i];
245 /* Create a Server ID for the server. */
246 silc_id_create_server_id(sock[i], server->rng, &id);
252 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
253 server->id_string_len = silc_id_get_len(SILC_ID_SERVER);
254 server->id_type = SILC_ID_SERVER;
255 server->server_name = server->config->server_info->server_name;
257 /* Add ourselves to the server list. We don't have a router yet
258 beacuse we haven't established a route yet. It will be done later.
259 For now, NULL is sent as router. This allocates new entry to
262 silc_idlist_add_server(server->local_list,
263 server->config->server_info->server_name,
264 server->server_type, server->id, NULL, NULL);
266 SILC_LOG_ERROR(("Could not add ourselves to cache"));
270 /* Add ourselves also to the socket table. The entry allocated above
271 is sent as argument for fast referencing in the future. */
272 silc_socket_alloc(sock[i], SILC_SOCKET_TYPE_SERVER, id_entry,
277 server->sockets[sock[i]] = newsocket;
279 /* Put the allocated socket pointer also to the entry allocated above
280 for fast back-referencing to the socket list. */
281 id_entry->connection = (void *)server->sockets[sock[i]];
282 server->id_entry = id_entry;
285 /* Register the task queues. In SILC we have by default three task queues.
286 One task queue for non-timeout tasks which perform different kind of
287 I/O on file descriptors, timeout task queue for timeout tasks, and,
288 generic non-timeout task queue whose tasks apply to all connections. */
289 silc_task_queue_alloc(&server->io_queue, TRUE);
290 if (!server->io_queue) {
293 silc_task_queue_alloc(&server->timeout_queue, TRUE);
294 if (!server->timeout_queue) {
297 silc_task_queue_alloc(&server->generic_queue, TRUE);
298 if (!server->generic_queue) {
302 /* Register protocols */
303 silc_server_protocols_register();
305 /* Initialize the scheduler */
306 silc_schedule_init(&server->io_queue, &server->timeout_queue,
307 &server->generic_queue,
308 SILC_SERVER_MAX_CONNECTIONS);
310 /* Add the first task to the queue. This is task that is executed by
311 timeout. It expires as soon as the caller calls silc_server_run. This
312 task performs authentication protocol and key exchange with our
314 silc_task_register(server->timeout_queue, sock[0],
315 silc_server_connect_to_router,
316 (void *)server, 0, 1,
318 SILC_TASK_PRI_NORMAL);
320 /* Add listener task to the queue. This task receives new connections to the
321 server. This task remains on the queue until the end of the program. */
322 silc_task_register(server->io_queue, sock[0],
323 silc_server_accept_new_connection,
324 (void *)server, 0, 0,
326 SILC_TASK_PRI_NORMAL);
327 server->listenning = TRUE;
329 /* If server connections has been configured then we must be router as
330 normal server cannot have server connections, only router connections. */
331 if (server->config->servers)
332 server->server_type = SILC_ROUTER;
334 SILC_LOG_DEBUG(("Server initialized"));
336 /* We are done here, return succesfully */
339 silc_task_queue_free(server->timeout_queue);
341 silc_task_queue_free(server->io_queue);
343 for (i = 0; i < sock_count; i++)
344 silc_net_close_server(sock[i]);
349 /* Stops the SILC server. This function is used to shutdown the server.
350 This is usually called after the scheduler has returned. After stopping
351 the server one should call silc_server_free. */
353 void silc_server_stop(SilcServer server)
355 SILC_LOG_DEBUG(("Stopping server"));
357 /* Stop the scheduler, although it might be already stopped. This
358 doesn't hurt anyone. This removes all the tasks and task queues,
360 silc_schedule_stop();
361 silc_schedule_uninit();
363 silc_server_protocols_unregister();
365 SILC_LOG_DEBUG(("Server stopped"));
368 /* The heart of the server. This runs the scheduler thus runs the server. */
370 void silc_server_run(SilcServer server)
372 SILC_LOG_DEBUG(("Running server"));
374 /* Start the scheduler, the heart of the SILC server. When this returns
375 the program will be terminated. */
379 /* Timeout callback that will be called to retry connecting to remote
380 router. This is used by both normal and router server. This will wait
381 before retrying the connecting. The timeout is generated by exponential
382 backoff algorithm. */
384 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
386 SilcServerConnection sconn = (SilcServerConnection)context;
387 SilcServer server = sconn->server;
389 SILC_LOG_INFO(("Retrying connecting to a router"));
391 /* Calculate next timeout */
392 if (sconn->retry_count >= 1) {
393 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
394 if (sconn->retry_timeout > SILC_SERVER_RETRY_INTERVAL_MAX)
395 sconn->retry_timeout = SILC_SERVER_RETRY_INTERVAL_MAX;
397 sconn->retry_timeout = server->params->retry_interval_min;
399 sconn->retry_count++;
400 sconn->retry_timeout = sconn->retry_timeout +
401 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
403 /* If we've reached max retry count, give up. */
404 if (sconn->retry_count > server->params->retry_count &&
405 server->params->retry_keep_trying == FALSE) {
406 SILC_LOG_ERROR(("Could not connect to router, giving up"));
410 /* Wait one before retrying */
411 silc_task_register(server->timeout_queue, fd, silc_server_connect_router,
412 context, sconn->retry_timeout,
413 server->params->retry_interval_min_usec,
414 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
417 /* Generic routine to use connect to a router. */
419 SILC_TASK_CALLBACK(silc_server_connect_router)
421 SilcServerConnection sconn = (SilcServerConnection)context;
422 SilcServer server = sconn->server;
423 SilcSocketConnection newsocket;
424 SilcProtocol protocol;
425 SilcServerKEInternalContext *proto_ctx;
428 /* Connect to remote host */
429 sock = silc_net_create_connection(sconn->remote_port,
432 SILC_LOG_ERROR(("Could not connect to router"));
433 silc_task_register(server->timeout_queue, fd,
434 silc_server_connect_to_router_retry,
435 context, 0, 1, SILC_TASK_TIMEOUT,
436 SILC_TASK_PRI_NORMAL);
440 /* Set socket options */
441 silc_net_set_socket_nonblock(sock);
442 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
444 /* Create socket connection for the connection. Even though we
445 know that we are connecting to a router we will mark the socket
446 to be unknown connection until we have executed authentication
448 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
449 server->sockets[sock] = newsocket;
450 newsocket->hostname = sconn->remote_host;
451 newsocket->port = sconn->remote_port;
452 sconn->sock = newsocket;
454 /* Allocate internal protocol context. This is sent as context
456 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
457 proto_ctx->server = (void *)server;
458 proto_ctx->context = (void *)sconn;
459 proto_ctx->sock = newsocket;
460 proto_ctx->rng = server->rng;
461 proto_ctx->responder = FALSE;
463 /* Perform key exchange protocol. silc_server_connect_to_router_second
464 will be called after the protocol is finished. */
465 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
466 &protocol, proto_ctx,
467 silc_server_connect_to_router_second);
468 newsocket->protocol = protocol;
470 /* Register a timeout task that will be executed if the protocol
471 is not executed within set limit. */
472 proto_ctx->timeout_task =
473 silc_task_register(server->timeout_queue, sock,
474 silc_server_timeout_remote,
475 server, server->params->protocol_timeout,
476 server->params->protocol_timeout_usec,
480 /* Register the connection for network input and output. This sets
481 that scheduler will listen for incoming packets for this connection
482 and sets that outgoing packets may be sent to this connection as
483 well. However, this doesn't set the scheduler for outgoing traffic,
484 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
485 later when outgoing data is available. */
486 context = (void *)server;
487 SILC_REGISTER_CONNECTION_FOR_IO(sock);
489 /* Run the protocol */
490 protocol->execute(server->timeout_queue, 0, protocol, sock, 0, 0);
493 /* This function connects to our primary router or if we are a router this
494 establishes all our primary routes. This is called at the start of the
495 server to do authentication and key exchange with our router - called
498 SILC_TASK_CALLBACK(silc_server_connect_to_router)
500 SilcServer server = (SilcServer)context;
501 SilcServerConnection sconn;
503 SILC_LOG_DEBUG(("Connecting to router(s)"));
505 /* If we are normal SILC server we need to connect to our cell's
507 if (server->server_type == SILC_SERVER) {
508 SILC_LOG_DEBUG(("We are normal server"));
510 /* Create connection to the router, if configured. */
511 if (server->config->routers) {
513 /* Allocate connection object for hold connection specific stuff. */
514 sconn = silc_calloc(1, sizeof(*sconn));
515 sconn->server = server;
516 sconn->remote_host = server->config->routers->host;
517 sconn->remote_port = server->config->routers->port;
519 silc_task_register(server->timeout_queue, fd,
520 silc_server_connect_router,
521 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
522 SILC_TASK_PRI_NORMAL);
527 /* If we are a SILC router we need to establish all of our primary
529 if (server->server_type == SILC_ROUTER) {
530 SilcConfigServerSectionServerConnection *ptr;
532 SILC_LOG_DEBUG(("We are router"));
534 /* Create the connections to all our routes */
535 ptr = server->config->routers;
538 SILC_LOG_DEBUG(("Router connection [%s] %s:%d",
539 ptr->initiator ? "Initiator" : "Responder",
540 ptr->host, ptr->port));
542 if (ptr->initiator) {
543 /* Allocate connection object for hold connection specific stuff. */
544 sconn = silc_calloc(1, sizeof(*sconn));
545 sconn->server = server;
546 sconn->remote_host = ptr->host;
547 sconn->remote_port = ptr->port;
549 silc_task_register(server->timeout_queue, fd,
550 silc_server_connect_router,
551 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
552 SILC_TASK_PRI_NORMAL);
562 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
564 /* There wasn't a configured router, we will continue but we don't
565 have a connection to outside world. We will be standalone server. */
566 server->standalone = TRUE;
569 /* Second part of connecting to router(s). Key exchange protocol has been
570 executed and now we will execute authentication protocol. */
572 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
574 SilcProtocol protocol = (SilcProtocol)context;
575 SilcServerKEInternalContext *ctx =
576 (SilcServerKEInternalContext *)protocol->context;
577 SilcServer server = (SilcServer)ctx->server;
578 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
579 SilcSocketConnection sock = NULL;
580 SilcServerConnAuthInternalContext *proto_ctx;
582 SILC_LOG_DEBUG(("Start"));
584 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
585 /* Error occured during protocol */
586 silc_protocol_free(protocol);
588 silc_packet_context_free(ctx->packet);
590 silc_ske_free(ctx->ske);
592 silc_free(ctx->dest_id);
594 sock->protocol = NULL;
595 silc_server_disconnect_remote(server, sock, "Server closed connection: "
596 "Key exchange failed");
600 /* Allocate internal context for the authentication protocol. This
601 is sent as context for the protocol. */
602 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
603 proto_ctx->server = (void *)server;
604 proto_ctx->context = (void *)sconn;
605 proto_ctx->sock = sock = server->sockets[fd];
606 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
607 proto_ctx->dest_id_type = ctx->dest_id_type;
608 proto_ctx->dest_id = ctx->dest_id;
610 /* Resolve the authentication method used in this connection */
611 proto_ctx->auth_meth = SILC_PROTOCOL_CONN_AUTH_PASSWORD;
612 if (server->config->routers) {
613 SilcConfigServerSectionServerConnection *conn = NULL;
615 /* Check if we find a match from user configured connections */
616 conn = silc_config_server_find_router_conn(server->config,
620 /* Match found. Use the configured authentication method */
621 proto_ctx->auth_meth = conn->auth_meth;
622 if (conn->auth_data) {
623 proto_ctx->auth_data = strdup(conn->auth_data);
624 proto_ctx->auth_data_len = strlen(conn->auth_data);
627 /* No match found. */
634 /* Free old protocol as it is finished now */
635 silc_protocol_free(protocol);
637 silc_packet_context_free(ctx->packet);
639 sock->protocol = NULL;
641 /* Allocate the authentication protocol. This is allocated here
642 but we won't start it yet. We will be receiving party of this
643 protocol thus we will wait that connecting party will make
645 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
646 &sock->protocol, proto_ctx,
647 silc_server_connect_to_router_final);
649 /* Register timeout task. If the protocol is not executed inside
650 this timelimit the connection will be terminated. Currently
651 this is 15 seconds and is hard coded limit (XXX). */
652 proto_ctx->timeout_task =
653 silc_task_register(server->timeout_queue, sock->sock,
654 silc_server_timeout_remote,
655 (void *)server, 15, 0,
659 /* Run the protocol */
660 sock->protocol->execute(server->timeout_queue, 0,
661 sock->protocol, sock->sock, 0, 0);
664 /* Finalizes the connection to router. Registers a server task to the
665 queue so that we can accept new connections. */
667 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
669 SilcProtocol protocol = (SilcProtocol)context;
670 SilcServerConnAuthInternalContext *ctx =
671 (SilcServerConnAuthInternalContext *)protocol->context;
672 SilcServer server = (SilcServer)ctx->server;
673 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
674 SilcSocketConnection sock = ctx->sock;
675 SilcServerEntry id_entry;
677 unsigned char *id_string;
679 SILC_LOG_DEBUG(("Start"));
681 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
682 /* Error occured during protocol */
684 silc_free(ctx->dest_id);
685 silc_server_disconnect_remote(server, sock, "Server closed connection: "
686 "Authentication failed");
690 /* Add a task to the queue. This task receives new connections to the
691 server. This task remains on the queue until the end of the program. */
692 if (!server->listenning) {
693 silc_task_register(server->io_queue, server->sock,
694 silc_server_accept_new_connection,
695 (void *)server, 0, 0,
697 SILC_TASK_PRI_NORMAL);
698 server->listenning = TRUE;
701 /* Send NEW_SERVER packet to the router. We will become registered
702 to the SILC network after sending this packet. */
703 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
704 packet = silc_buffer_alloc(2 + 2 + SILC_ID_SERVER_LEN +
705 strlen(server->server_name));
706 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
707 silc_buffer_format(packet,
708 SILC_STR_UI_SHORT(SILC_ID_SERVER_LEN),
709 SILC_STR_UI_XNSTRING(id_string, SILC_ID_SERVER_LEN),
710 SILC_STR_UI_SHORT(strlen(server->server_name)),
711 SILC_STR_UI_XNSTRING(server->server_name,
712 strlen(server->server_name)),
715 /* Send the packet */
716 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
717 packet->data, packet->len, TRUE);
718 silc_buffer_free(packet);
719 silc_free(id_string);
721 SILC_LOG_DEBUG(("Connected to router %s", sock->hostname));
723 /* Add the connected router to local server list */
724 server->standalone = FALSE;
725 id_entry = silc_idlist_add_server(server->local_list,
726 sock->hostname ? sock->hostname : sock->ip,
727 SILC_ROUTER, ctx->dest_id, NULL, sock);
730 silc_free(ctx->dest_id);
731 silc_server_disconnect_remote(server, sock, "Server closed connection: "
732 "Authentication failed");
736 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
737 silc_free(sock->user_data);
738 sock->user_data = (void *)id_entry;
739 sock->type = SILC_SOCKET_TYPE_ROUTER;
740 server->id_entry->router = id_entry;
741 server->router = id_entry;
742 server->router->data.registered = TRUE;
745 /* Free the temporary connection data context */
749 /* Free the protocol object */
750 silc_protocol_free(protocol);
752 silc_packet_context_free(ctx->packet);
754 silc_ske_free(ctx->ske);
756 sock->protocol = NULL;
759 /* Accepts new connections to the server. Accepting new connections are
760 done in three parts to make it async. */
762 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
764 SilcServer server = (SilcServer)context;
765 SilcSocketConnection newsocket;
766 SilcServerKEInternalContext *proto_ctx;
769 SILC_LOG_DEBUG(("Accepting new connection"));
771 sock = silc_net_accept_connection(server->sock);
773 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
777 /* Check max connections */
778 if (sock > SILC_SERVER_MAX_CONNECTIONS) {
779 if (server->config->redirect) {
780 /* XXX Redirecting connection to somewhere else now?? */
781 /*silc_server_send_notify("Server is full, trying to redirect..."); */
783 SILC_LOG_ERROR(("Refusing connection, server is full"));
788 /* Set socket options */
789 silc_net_set_socket_nonblock(sock);
790 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
792 /* We don't create a ID yet, since we don't know what type of connection
793 this is yet. But, we do add the connection to the socket table. */
794 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
795 server->sockets[sock] = newsocket;
797 /* XXX This MUST be done async as this will block the entire server
798 process. Either we have to do our own resolver stuff or in the future
799 we can use threads. */
800 /* Perform mandatory name and address lookups for the remote host. */
801 silc_net_check_host_by_sock(sock, &newsocket->hostname, &newsocket->ip);
802 if (!newsocket->ip || !newsocket->hostname) {
803 SILC_LOG_DEBUG(("IP lookup/DNS lookup failed"));
804 SILC_LOG_ERROR(("IP lookup/DNS lookup failed"));
808 SILC_LOG_INFO(("Incoming connection from %s (%s)", newsocket->hostname,
811 /* Allocate internal context for key exchange protocol. This is
812 sent as context for the protocol. */
813 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
814 proto_ctx->server = context;
815 proto_ctx->sock = newsocket;
816 proto_ctx->rng = server->rng;
817 proto_ctx->responder = TRUE;
819 /* Prepare the connection for key exchange protocol. We allocate the
820 protocol but will not start it yet. The connector will be the
821 initiator of the protocol thus we will wait for initiation from
822 there before we start the protocol. */
823 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
824 &newsocket->protocol, proto_ctx,
825 silc_server_accept_new_connection_second);
827 /* Register a timeout task that will be executed if the connector
828 will not start the key exchange protocol within 60 seconds. For
829 now, this is a hard coded limit. After 60 secs the connection will
830 be closed if the key exchange protocol has not been started. */
831 proto_ctx->timeout_task =
832 silc_task_register(server->timeout_queue, newsocket->sock,
833 silc_server_timeout_remote,
838 /* Register the connection for network input and output. This sets
839 that scheduler will listen for incoming packets for this connection
840 and sets that outgoing packets may be sent to this connection as well.
841 However, this doesn't set the scheduler for outgoing traffic, it
842 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
843 later when outgoing data is available. */
844 SILC_REGISTER_CONNECTION_FOR_IO(sock);
847 /* Second part of accepting new connection. Key exchange protocol has been
848 performed and now it is time to do little connection authentication
849 protocol to figure out whether this connection is client or server
850 and whether it has right to access this server (especially server
851 connections needs to be authenticated). */
853 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
855 SilcProtocol protocol = (SilcProtocol)context;
856 SilcServerKEInternalContext *ctx =
857 (SilcServerKEInternalContext *)protocol->context;
858 SilcServer server = (SilcServer)ctx->server;
859 SilcSocketConnection sock = NULL;
860 SilcServerConnAuthInternalContext *proto_ctx;
862 SILC_LOG_DEBUG(("Start"));
864 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
865 /* Error occured during protocol */
866 silc_protocol_free(protocol);
868 silc_packet_context_free(ctx->packet);
870 silc_ske_free(ctx->ske);
872 silc_free(ctx->dest_id);
875 sock->protocol = NULL;
876 silc_server_disconnect_remote(server, sock, "Server closed connection: "
877 "Key exchange failed");
881 /* Allocate internal context for the authentication protocol. This
882 is sent as context for the protocol. */
883 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
884 proto_ctx->server = (void *)server;
885 proto_ctx->sock = sock = server->sockets[fd];
886 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
887 proto_ctx->responder = TRUE;
888 proto_ctx->dest_id_type = ctx->dest_id_type;
889 proto_ctx->dest_id = ctx->dest_id;
891 /* Free old protocol as it is finished now */
892 silc_protocol_free(protocol);
894 silc_packet_context_free(ctx->packet);
896 sock->protocol = NULL;
898 /* Allocate the authentication protocol. This is allocated here
899 but we won't start it yet. We will be receiving party of this
900 protocol thus we will wait that connecting party will make
902 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
903 &sock->protocol, proto_ctx,
904 silc_server_accept_new_connection_final);
906 /* Register timeout task. If the protocol is not executed inside
907 this timelimit the connection will be terminated. Currently
908 this is 60 seconds and is hard coded limit (XXX). */
909 proto_ctx->timeout_task =
910 silc_task_register(server->timeout_queue, sock->sock,
911 silc_server_timeout_remote,
912 (void *)server, 60, 0,
917 /* Final part of accepting new connection. The connection has now
918 been authenticated and keys has been exchanged. We also know whether
919 this is client or server connection. */
921 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
923 SilcProtocol protocol = (SilcProtocol)context;
924 SilcServerConnAuthInternalContext *ctx =
925 (SilcServerConnAuthInternalContext *)protocol->context;
926 SilcServer server = (SilcServer)ctx->server;
927 SilcSocketConnection sock = ctx->sock;
928 void *id_entry = NULL;
930 SILC_LOG_DEBUG(("Start"));
932 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
933 /* Error occured during protocol */
934 silc_protocol_free(protocol);
936 silc_packet_context_free(ctx->packet);
938 silc_ske_free(ctx->ske);
940 silc_free(ctx->dest_id);
943 sock->protocol = NULL;
944 silc_server_disconnect_remote(server, sock, "Server closed connection: "
945 "Authentication failed");
949 sock->type = ctx->conn_type;
951 case SILC_SOCKET_TYPE_CLIENT:
953 SilcClientEntry client;
955 SILC_LOG_DEBUG(("Remote host is client"));
956 SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
959 /* Add the client to the client ID cache. The nickname and Client ID
960 and other information is created after we have received NEW_CLIENT
961 packet from client. */
962 client = silc_idlist_add_client(server->local_list,
963 NULL, NULL, NULL, NULL, NULL, sock);
965 SILC_LOG_ERROR(("Could not add new client to cache"));
966 silc_free(sock->user_data);
970 id_entry = (void *)client;
973 case SILC_SOCKET_TYPE_SERVER:
974 case SILC_SOCKET_TYPE_ROUTER:
976 SilcServerEntry new_server;
978 SILC_LOG_DEBUG(("Remote host is %s",
979 sock->type == SILC_SOCKET_TYPE_SERVER ?
980 "server" : "router"));
981 SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
982 sock->ip, sock->type == SILC_SOCKET_TYPE_SERVER ?
983 "server" : "router"));
985 /* Add the server into server cache. The server name and Server ID
986 is updated after we have received NEW_SERVER packet from the
987 server. We mark ourselves as router for this server if we really
990 silc_idlist_add_server(server->local_list, NULL,
991 sock->type == SILC_SOCKET_TYPE_SERVER ?
992 SILC_SERVER : SILC_ROUTER, NULL,
993 sock->type == SILC_SOCKET_TYPE_SERVER ?
994 server->id_entry : NULL, sock);
996 SILC_LOG_ERROR(("Could not add new server to cache"));
997 silc_free(sock->user_data);
1001 id_entry = (void *)new_server;
1003 /* There is connection to other server now, if it is router then
1004 we will have connection to outside world. If we are router but
1005 normal server connected to us then we will remain standalone,
1006 if we are standlone. */
1007 if (server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER) {
1008 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1009 server->standalone = FALSE;
1010 if (!server->id_entry->router) {
1011 server->id_entry->router = id_entry;
1012 server->router = id_entry;
1021 /* Add the common data structure to the ID entry. */
1023 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1025 /* Add to sockets internal pointer for fast referencing */
1026 silc_free(sock->user_data);
1027 sock->user_data = id_entry;
1029 /* Connection has been fully established now. Everything is ok. */
1030 SILC_LOG_DEBUG(("New connection authenticated"));
1032 silc_protocol_free(protocol);
1034 silc_packet_context_free(ctx->packet);
1036 silc_ske_free(ctx->ske);
1038 silc_free(ctx->dest_id);
1040 sock->protocol = NULL;
1043 /* This function is used to read packets from network and send packets to
1044 network. This is usually a generic task. */
1046 SILC_TASK_CALLBACK(silc_server_packet_process)
1048 SilcServer server = (SilcServer)context;
1049 SilcSocketConnection sock = server->sockets[fd];
1050 SilcIDListData idata;
1051 SilcCipher cipher = NULL;
1052 SilcHmac hmac = NULL;
1055 SILC_LOG_DEBUG(("Processing packet"));
1057 /* Packet sending */
1058 if (type == SILC_TASK_WRITE) {
1059 SILC_LOG_DEBUG(("Writing data to connection"));
1061 if (sock->outbuf->data - sock->outbuf->head)
1062 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1064 ret = silc_server_packet_send_real(server, sock, TRUE);
1066 /* If returned -2 could not write to connection now, will do
1071 /* The packet has been sent and now it is time to set the connection
1072 back to only for input. When there is again some outgoing data
1073 available for this connection it will be set for output as well.
1074 This call clears the output setting and sets it only for input. */
1075 SILC_SET_CONNECTION_FOR_INPUT(fd);
1076 SILC_UNSET_OUTBUF_PENDING(sock);
1078 silc_buffer_clear(sock->outbuf);
1082 /* Packet receiving */
1083 SILC_LOG_DEBUG(("Reading data from connection"));
1085 /* Read some data from connection */
1086 ret = silc_packet_receive(sock);
1092 SILC_LOG_DEBUG(("Read EOF"));
1094 /* If connection is disconnecting already we will finally
1095 close the connection */
1096 if (SILC_IS_DISCONNECTING(sock)) {
1097 if (sock->user_data)
1098 silc_server_free_sock_user_data(server, sock);
1099 silc_server_close_connection(server, sock);
1103 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1105 if (sock->user_data)
1106 silc_server_free_sock_user_data(server, sock);
1107 silc_server_close_connection(server, sock);
1111 /* If connection is disconnecting or disconnected we will ignore
1113 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1114 SILC_LOG_DEBUG(("Ignoring read data from invalid connection"));
1118 /* Get keys and stuff from ID entry */
1119 idata = (SilcIDListData)sock->user_data;
1121 idata->last_receive = time(NULL);
1122 cipher = idata->receive_key;
1126 /* Process the packet. This will call the parser that will then
1127 decrypt and parse the packet. */
1128 silc_packet_receive_process(sock, cipher, hmac, silc_server_packet_parse,
1132 /* Parses whole packet, received earlier. */
1134 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1136 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1137 SilcServer server = (SilcServer)parse_ctx->context;
1138 SilcSocketConnection sock = parse_ctx->sock;
1139 SilcPacketContext *packet = parse_ctx->packet;
1142 SILC_LOG_DEBUG(("Start"));
1144 /* Decrypt the received packet */
1145 ret = silc_packet_decrypt(parse_ctx->cipher, parse_ctx->hmac,
1146 packet->buffer, packet);
1151 /* Parse the packet. Packet type is returned. */
1152 ret = silc_packet_parse(packet);
1154 /* Parse the packet header in special way as this is "special"
1156 ret = silc_packet_parse_special(packet);
1159 if (ret == SILC_PACKET_NONE)
1162 if (server->server_type == SILC_ROUTER) {
1163 /* Route the packet if it is not destined to us. Other ID types but
1164 server are handled separately after processing them. */
1165 if (packet->dst_id_type == SILC_ID_SERVER &&
1166 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1167 SILC_ID_SERVER_COMPARE(packet->dst_id, server->id_string)) {
1169 /* Route the packet to fastest route for the destination ID */
1170 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_type);
1171 silc_server_packet_route(server,
1172 silc_server_route_get(server, id,
1173 packet->dst_id_type),
1179 /* Broadcast packet if it is marked as broadcast packet and it is
1180 originated from router and we are router. */
1181 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1182 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
1183 silc_server_packet_broadcast(server, server->router->connection, packet);
1187 /* Parse the incoming packet type */
1188 silc_server_packet_parse_type(server, sock, packet);
1191 silc_buffer_clear(sock->inbuf);
1192 silc_packet_context_free(packet);
1193 silc_free(parse_ctx);
1196 /* Parser callback called by silc_packet_receive_process. This merely
1197 registers timeout that will handle the actual parsing when appropriate. */
1199 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1201 SilcServer server = (SilcServer)parser_context->context;
1202 SilcSocketConnection sock = parser_context->sock;
1204 switch (sock->type) {
1205 case SILC_SOCKET_TYPE_CLIENT:
1206 case SILC_SOCKET_TYPE_UNKNOWN:
1207 /* Parse the packet with timeout */
1208 silc_task_register(server->timeout_queue, sock->sock,
1209 silc_server_packet_parse_real,
1210 (void *)parser_context, 0, 100000,
1212 SILC_TASK_PRI_NORMAL);
1214 case SILC_SOCKET_TYPE_SERVER:
1215 case SILC_SOCKET_TYPE_ROUTER:
1216 /* Packets from servers are parsed as soon as possible */
1217 silc_task_register(server->timeout_queue, sock->sock,
1218 silc_server_packet_parse_real,
1219 (void *)parser_context, 0, 1,
1221 SILC_TASK_PRI_NORMAL);
1228 /* Parses the packet type and calls what ever routines the packet type
1229 requires. This is done for all incoming packets. */
1231 void silc_server_packet_parse_type(SilcServer server,
1232 SilcSocketConnection sock,
1233 SilcPacketContext *packet)
1235 SilcPacketType type = packet->type;
1237 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1239 /* Parse the packet type */
1241 case SILC_PACKET_DISCONNECT:
1242 SILC_LOG_DEBUG(("Disconnect packet"));
1245 case SILC_PACKET_SUCCESS:
1247 * Success received for something. For now we can have only
1248 * one protocol for connection executing at once hence this
1249 * success message is for whatever protocol is executing currently.
1251 SILC_LOG_DEBUG(("Success packet"));
1252 if (sock->protocol) {
1253 sock->protocol->execute(server->timeout_queue, 0,
1254 sock->protocol, sock->sock, 0, 0);
1258 case SILC_PACKET_FAILURE:
1260 * Failure received for something. For now we can have only
1261 * one protocol for connection executing at once hence this
1262 * failure message is for whatever protocol is executing currently.
1264 SILC_LOG_DEBUG(("Failure packet"));
1265 if (sock->protocol) {
1266 /* XXX Audit the failure type */
1267 sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
1268 sock->protocol->execute(server->timeout_queue, 0,
1269 sock->protocol, sock->sock, 0, 0);
1273 case SILC_PACKET_REJECT:
1274 SILC_LOG_DEBUG(("Reject packet"));
1278 case SILC_PACKET_NOTIFY:
1280 * Received notify packet. Server can receive notify packets from
1281 * router. Server then relays the notify messages to clients if needed.
1283 SILC_LOG_DEBUG(("Notify packet"));
1284 silc_server_notify(server, sock, packet);
1290 case SILC_PACKET_CHANNEL_MESSAGE:
1292 * Received channel message. Channel messages are special packets
1293 * (although probably most common ones) hence they are handled
1296 SILC_LOG_DEBUG(("Channel Message packet"));
1297 silc_server_channel_message(server, sock, packet);
1300 case SILC_PACKET_CHANNEL_KEY:
1302 * Received key for channel. As channels are created by the router
1303 * the keys are as well. We will distribute the key to all of our
1304 * locally connected clients on the particular channel. Router
1305 * never receives this channel and thus is ignored.
1307 SILC_LOG_DEBUG(("Channel Key packet"));
1308 silc_server_channel_key(server, sock, packet);
1314 case SILC_PACKET_COMMAND:
1316 * Recived command. Allocate command context and execute the command.
1318 SILC_LOG_DEBUG(("Command packet"));
1319 silc_server_command_process(server, sock, packet);
1322 case SILC_PACKET_COMMAND_REPLY:
1324 * Received command reply packet. Servers never send commands thus
1325 * they don't receive command reply packets either, except in cases
1326 * where server has forwarded command packet coming from client.
1327 * This must be the case here or we will ignore the packet.
1329 SILC_LOG_DEBUG(("Command Reply packet"));
1330 silc_server_command_reply(server, sock, packet);
1334 * Private Message packets
1336 case SILC_PACKET_PRIVATE_MESSAGE:
1338 * Received private message packet. The packet is coming from either
1341 SILC_LOG_DEBUG(("Private Message packet"));
1342 silc_server_private_message(server, sock, packet);
1345 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1352 * Key Exchange protocol packets
1354 case SILC_PACKET_KEY_EXCHANGE:
1355 SILC_LOG_DEBUG(("KE packet"));
1356 if (sock->protocol && sock->protocol->protocol->type
1357 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1359 SilcServerKEInternalContext *proto_ctx =
1360 (SilcServerKEInternalContext *)sock->protocol->context;
1362 proto_ctx->packet = silc_packet_context_dup(packet);
1364 /* Let the protocol handle the packet */
1365 sock->protocol->execute(server->timeout_queue, 0,
1366 sock->protocol, sock->sock, 0, 100000);
1368 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1369 "protocol active, packet dropped."));
1371 /* XXX Trigger KE protocol?? Rekey actually, maybe. */
1375 case SILC_PACKET_KEY_EXCHANGE_1:
1376 SILC_LOG_DEBUG(("KE 1 packet"));
1377 if (sock->protocol && sock->protocol->protocol->type
1378 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1380 SilcServerKEInternalContext *proto_ctx =
1381 (SilcServerKEInternalContext *)sock->protocol->context;
1383 if (proto_ctx->packet)
1384 silc_packet_context_free(proto_ctx->packet);
1386 proto_ctx->packet = silc_packet_context_dup(packet);
1387 proto_ctx->dest_id_type = packet->src_id_type;
1388 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_type);
1390 /* Let the protocol handle the packet */
1391 sock->protocol->execute(server->timeout_queue, 0,
1392 sock->protocol, sock->sock,
1395 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1396 "protocol active, packet dropped."));
1400 case SILC_PACKET_KEY_EXCHANGE_2:
1401 SILC_LOG_DEBUG(("KE 2 packet"));
1402 if (sock->protocol && sock->protocol->protocol->type
1403 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1405 SilcServerKEInternalContext *proto_ctx =
1406 (SilcServerKEInternalContext *)sock->protocol->context;
1408 if (proto_ctx->packet)
1409 silc_packet_context_free(proto_ctx->packet);
1411 proto_ctx->packet = silc_packet_context_dup(packet);
1412 proto_ctx->dest_id_type = packet->src_id_type;
1413 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_type);
1415 /* Let the protocol handle the packet */
1416 sock->protocol->execute(server->timeout_queue, 0,
1417 sock->protocol, sock->sock,
1420 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1421 "protocol active, packet dropped."));
1425 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1426 /* If we receive this packet we will send to the other end information
1427 about our mandatory authentication method for the connection.
1428 This packet maybe received at any time. */
1429 SILC_LOG_DEBUG(("Connection authentication request packet"));
1433 * Connection Authentication protocol packets
1435 case SILC_PACKET_CONNECTION_AUTH:
1436 /* Start of the authentication protocol. We receive here the
1437 authentication data and will verify it. */
1438 SILC_LOG_DEBUG(("Connection auth packet"));
1439 if (sock->protocol && sock->protocol->protocol->type
1440 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1442 SilcServerConnAuthInternalContext *proto_ctx =
1443 (SilcServerConnAuthInternalContext *)sock->protocol->context;
1445 proto_ctx->packet = silc_packet_context_dup(packet);
1447 /* Let the protocol handle the packet */
1448 sock->protocol->execute(server->timeout_queue, 0,
1449 sock->protocol, sock->sock, 0, 0);
1451 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1452 "protocol active, packet dropped."));
1456 case SILC_PACKET_NEW_ID:
1458 * Received New ID packet. This includes some new ID that has been
1459 * created. It may be for client, server or channel. This is the way
1460 * to distribute information about new registered entities in the
1463 SILC_LOG_DEBUG(("New ID packet"));
1464 silc_server_new_id(server, sock, packet);
1467 case SILC_PACKET_NEW_CLIENT:
1469 * Received new client packet. This includes client information that
1470 * we will use to create initial client ID. After creating new
1471 * ID we will send it to the client.
1473 SILC_LOG_DEBUG(("New Client packet"));
1474 silc_server_new_client(server, sock, packet);
1477 case SILC_PACKET_NEW_SERVER:
1479 * Received new server packet. This includes Server ID and some other
1480 * information that we may save. This is received after server has
1483 SILC_LOG_DEBUG(("New Server packet"));
1484 silc_server_new_server(server, sock, packet);
1487 case SILC_PACKET_NEW_CHANNEL:
1489 * Received new channel packet. Information about new channel in the
1490 * network are distributed using this packet.
1492 SILC_LOG_DEBUG(("New Channel packet"));
1493 silc_server_new_channel(server, sock, packet);
1496 case SILC_PACKET_NEW_CHANNEL_USER:
1498 * Received new channel user packet. Information about new users on a
1499 * channel are distributed between routers using this packet. The
1500 * router receiving this will redistribute it and also sent JOIN notify
1501 * to local clients on the same channel. Normal server sends JOIN notify
1502 * to its local clients on the channel.
1504 SILC_LOG_DEBUG(("New Channel User packet"));
1505 silc_server_new_channel_user(server, sock, packet);
1508 case SILC_PACKET_NEW_CHANNEL_LIST:
1510 * List of new channel packets received. This is usually received when
1511 * existing server or router connects to us and distributes information
1512 * of all channels it has.
1516 case SILC_PACKET_NEW_CHANNEL_USER_LIST:
1518 * List of new channel user packets received. This is usually received
1519 * when existing server or router connects to us and distributes
1520 * information of all channel users it has.
1524 case SILC_PACKET_REPLACE_ID:
1526 * Received replace ID packet. This sends the old ID that is to be
1527 * replaced with the new one included into the packet. Client must not
1530 SILC_LOG_DEBUG(("Replace ID packet"));
1531 silc_server_replace_id(server, sock, packet);
1534 case SILC_PACKET_REMOVE_ID:
1536 * Received remove ID Packet.
1538 SILC_LOG_DEBUG(("Remove ID packet"));
1541 case SILC_PACKET_REMOVE_CHANNEL_USER:
1543 * Received packet to remove user from a channel. Routers notify other
1544 * routers about a user leaving a channel.
1546 SILC_LOG_DEBUG(("Remove Channel User packet"));
1547 silc_server_remove_channel_user(server, sock, packet);
1551 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
1557 /* Closes connection to socket connection */
1559 void silc_server_close_connection(SilcServer server,
1560 SilcSocketConnection sock)
1563 SILC_LOG_DEBUG(("Closing connection %d", sock->sock));
1565 /* We won't listen for this connection anymore */
1566 silc_schedule_unset_listen_fd(sock->sock);
1568 /* Unregister all tasks */
1569 silc_task_unregister_by_fd(server->io_queue, sock->sock);
1570 silc_task_unregister_by_fd(server->timeout_queue, sock->sock);
1572 /* Close the actual connection */
1573 silc_net_close_connection(sock->sock);
1574 server->sockets[sock->sock] = NULL;
1575 silc_socket_free(sock);
1578 /* Sends disconnect message to remote connection and disconnects the
1581 void silc_server_disconnect_remote(SilcServer server,
1582 SilcSocketConnection sock,
1583 const char *fmt, ...)
1586 unsigned char buf[4096];
1588 memset(buf, 0, sizeof(buf));
1590 vsprintf(buf, fmt, ap);
1593 SILC_LOG_DEBUG(("Disconnecting remote host"));
1595 /* Notify remote end that the conversation is over. The notify message
1596 is tried to be sent immediately. */
1597 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
1598 buf, strlen(buf), TRUE);
1600 /* Mark the connection to be disconnected */
1601 SILC_SET_DISCONNECTED(sock);
1602 silc_server_close_connection(server, sock);
1605 /* Free's user_data pointer from socket connection object. As this
1606 pointer maybe anything we wil switch here to find the correct
1607 data type and free it the way it needs to be free'd. */
1609 void silc_server_free_sock_user_data(SilcServer server,
1610 SilcSocketConnection sock)
1612 SILC_LOG_DEBUG(("Start"));
1614 switch(sock->type) {
1615 case SILC_SOCKET_TYPE_CLIENT:
1617 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
1619 /* Remove client from all channels */
1620 silc_server_remove_from_channels(server, sock, user_data);
1622 /* XXX must take some info to history before freeing */
1624 /* Free the client entry and everything in it */
1625 silc_idlist_del_data(user_data);
1626 silc_idlist_del_client(server->local_list, user_data);
1629 case SILC_SOCKET_TYPE_SERVER:
1630 case SILC_SOCKET_TYPE_ROUTER:
1638 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
1640 silc_idlist_del_data(user_data);
1641 silc_free(user_data);
1646 sock->user_data = NULL;
1649 /* Removes client from all channels it has joined. This is used when
1650 client connection is disconnected. If the client on a channel
1651 is last, the channel is removed as well. */
1653 void silc_server_remove_from_channels(SilcServer server,
1654 SilcSocketConnection sock,
1655 SilcClientEntry client)
1657 SilcChannelEntry channel;
1658 SilcChannelClientEntry chl;
1659 SilcBuffer chidp, clidp;
1661 SILC_LOG_DEBUG(("Start"));
1663 if (!client || !client->id)
1666 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
1668 /* Remove the client from all channels. The client is removed from
1669 the channels' user list. */
1670 silc_list_start(client->channels);
1671 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
1672 channel = chl->channel;
1673 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
1675 /* Remove from list */
1676 silc_list_del(client->channels, chl);
1678 /* If this client is last one on the channel the channel
1679 is removed all together. */
1680 if (silc_list_count(channel->user_list) < 2) {
1682 /* However, if the channel has marked global users then the
1683 channel is not created locally, and this does not remove the
1684 channel globally from SILC network, in this case we will
1685 notify that this client has left the channel. */
1686 if (channel->global_users)
1687 silc_server_send_notify_to_channel(server, channel, TRUE,
1688 SILC_NOTIFY_TYPE_SIGNOFF, 1,
1689 clidp->data, clidp->len);
1691 silc_idlist_del_channel(server->local_list, channel);
1695 /* Remove from list */
1696 silc_list_del(channel->user_list, chl);
1699 /* Send notify to channel about client leaving SILC and thus
1700 the entire channel. */
1701 silc_server_send_notify_to_channel(server, channel, TRUE,
1702 SILC_NOTIFY_TYPE_SIGNOFF, 1,
1703 clidp->data, clidp->len);
1704 silc_buffer_free(chidp);
1707 silc_buffer_free(clidp);
1710 /* Removes client from one channel. This is used for example when client
1711 calls LEAVE command to remove itself from the channel. Returns TRUE
1712 if channel still exists and FALSE if the channel is removed when
1713 last client leaves the channel. If `notify' is FALSE notify messages
1716 int silc_server_remove_from_one_channel(SilcServer server,
1717 SilcSocketConnection sock,
1718 SilcChannelEntry channel,
1719 SilcClientEntry client,
1722 SilcChannelEntry ch;
1723 SilcChannelClientEntry chl;
1726 SILC_LOG_DEBUG(("Start"));
1728 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
1730 /* Remove the client from the channel. The client is removed from
1731 the channel's user list. */
1732 silc_list_start(client->channels);
1733 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
1734 if (chl->channel != channel)
1739 /* Remove from list */
1740 silc_list_del(client->channels, chl);
1742 /* If this client is last one on the channel the channel
1743 is removed all together. */
1744 if (silc_list_count(channel->user_list) < 2) {
1745 /* Notify about leaving client if this channel has global users,
1746 ie. the channel is not created locally. */
1747 if (notify && channel->global_users)
1748 silc_server_send_notify_to_channel(server, channel, TRUE,
1749 SILC_NOTIFY_TYPE_LEAVE, 1,
1750 clidp->data, clidp->len);
1752 silc_idlist_del_channel(server->local_list, channel);
1753 silc_buffer_free(clidp);
1757 /* Remove from list */
1758 silc_list_del(channel->user_list, chl);
1761 /* Send notify to channel about client leaving the channel */
1763 silc_server_send_notify_to_channel(server, channel, TRUE,
1764 SILC_NOTIFY_TYPE_LEAVE, 1,
1765 clidp->data, clidp->len);
1769 silc_buffer_free(clidp);
1773 /* Returns TRUE if the given client is on the channel. FALSE if not.
1774 This works because we assure that the user list on the channel is
1775 always in up to date thus we can only check the channel list from
1776 `client' which is faster than checking the user list from `channel'. */
1778 int silc_server_client_on_channel(SilcClientEntry client,
1779 SilcChannelEntry channel)
1781 SilcChannelClientEntry chl;
1783 if (!client || !channel)
1786 silc_list_start(client->channels);
1787 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END)
1788 if (chl->channel == channel)
1794 /* Timeout callback. This is called if connection is idle or for some
1795 other reason is not responding within some period of time. This
1796 disconnects the remote end. */
1798 SILC_TASK_CALLBACK(silc_server_timeout_remote)
1800 SilcServerConnection sconn = (SilcServerConnection)context;
1801 SilcSocketConnection sock = sconn->server->sockets[fd];
1803 silc_server_disconnect_remote(sconn->server, sock,
1804 "Server closed connection: "
1805 "Connection timeout");
1808 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
1809 function may be used only by router. In real SILC network all channels
1810 are created by routers thus this function is never used by normal
1813 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
1814 SilcServerID *router_id,
1818 SilcChannelID *channel_id;
1819 SilcChannelEntry entry;
1822 SILC_LOG_DEBUG(("Creating new channel"));
1827 /* Allocate cipher */
1828 silc_cipher_alloc(cipher, &key);
1830 channel_name = strdup(channel_name);
1832 /* Create the channel */
1833 silc_id_create_channel_id(router_id, server->rng, &channel_id);
1834 entry = silc_idlist_add_channel(server->local_list, channel_name,
1835 SILC_CHANNEL_MODE_NONE, channel_id,
1838 silc_free(channel_name);
1842 /* Now create the actual key material */
1843 silc_server_create_channel_key(server, entry, 16);
1845 /* Notify other routers about the new channel. We send the packet
1846 to our primary route. */
1847 if (server->standalone == FALSE) {
1848 silc_server_send_new_channel(server, server->router->connection, TRUE,
1849 channel_name, entry->id, SILC_ID_CHANNEL_LEN);
1855 /* Generates new channel key. This is used to create the initial channel key
1856 but also to re-generate new key for channel. If `key_len' is provided
1857 it is the bytes of the key length. */
1859 void silc_server_create_channel_key(SilcServer server,
1860 SilcChannelEntry channel,
1861 unsigned int key_len)
1864 unsigned char channel_key[32];
1869 else if (channel->key_len)
1870 len = channel->key_len / 8;
1874 /* Create channel key */
1875 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
1878 channel->channel_key->cipher->set_key(channel->channel_key->context,
1881 /* Remove old key if exists */
1883 memset(channel->key, 0, channel->key_len / 8);
1884 silc_free(channel->key);
1888 channel->key_len = len * 8;
1889 channel->key = silc_calloc(len, sizeof(*channel->key));
1890 memcpy(channel->key, channel_key, len);
1891 memset(channel_key, 0, sizeof(channel_key));