5 Author: Pekka Riikonen <priikone@poseidon.pspt.fi>
7 Copyright (C) 1997 - 2001 Pekka Riikonen
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
21 * This is the actual SILC server than handles everything relating to
22 * servicing the SILC connections. This is also a SILC router as a router
23 * is also normal server.
27 #include "serverincludes.h"
28 #include "server_internal.h"
30 /* Static prototypes */
31 SILC_TASK_CALLBACK(silc_server_connect_router);
32 SILC_TASK_CALLBACK(silc_server_connect_to_router);
33 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
35 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
38 SILC_TASK_CALLBACK(silc_server_packet_process);
39 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
40 SILC_TASK_CALLBACK(silc_server_timeout_remote);
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);
103 /* Initializes the entire SILC server. This is called always before running
104 the server. This is called only once at the initialization of the program.
105 This binds the server to its listenning port. After this function returns
106 one should call silc_server_run to start the server. This returns TRUE
107 when everything is ok to run the server. Configuration file must be
108 read and parsed before calling this. */
110 int silc_server_init(SilcServer server)
112 int *sock = NULL, sock_count = 0, i;
114 SilcServerEntry id_entry;
116 SILC_LOG_DEBUG(("Initializing server"));
118 assert(server->config);
120 /* XXX After server is made as Silc Server Library this can be given
121 as argument, for now this is hard coded */
122 server->params = silc_calloc(1, sizeof(*server->params));
123 server->params->retry_count = SILC_SERVER_RETRY_COUNT;
124 server->params->retry_interval_min = SILC_SERVER_RETRY_INTERVAL_MIN;
125 server->params->retry_interval_max = SILC_SERVER_RETRY_INTERVAL_MAX;
126 server->params->retry_keep_trying = FALSE;
127 server->params->protocol_timeout = 60;
128 server->params->require_reverse_mapping = FALSE;
130 /* Set log files where log message should be saved. */
131 server->config->server = server;
132 silc_server_config_setlogfiles(server->config);
134 /* Register all configured ciphers, PKCS and hash functions. */
135 silc_server_config_register_ciphers(server->config);
136 silc_server_config_register_pkcs(server->config);
137 silc_server_config_register_hashfuncs(server->config);
139 /* Initialize random number generator for the server. */
140 server->rng = silc_rng_alloc();
141 silc_rng_init(server->rng);
142 silc_rng_global_init(server->rng);
144 /* Initialize hash functions for server to use */
145 silc_hash_alloc("md5", &server->md5hash);
146 silc_hash_alloc("sha1", &server->sha1hash);
148 /* Initialize none cipher */
149 silc_cipher_alloc("none", &server->none_cipher);
151 /* XXXXX Generate RSA key pair */
153 unsigned char *public_key;
154 unsigned char *private_key;
155 unsigned int pk_len, prv_len;
158 if (stat("pubkey.pub", &st) < 0 && stat("privkey.prv", &st) < 0) {
160 if (silc_pkcs_alloc("rsa", &server->pkcs) == FALSE) {
161 SILC_LOG_ERROR(("Could not create RSA key pair"));
165 if (server->pkcs->pkcs->init(server->pkcs->context,
166 1024, server->rng) == FALSE) {
167 SILC_LOG_ERROR(("Could not generate RSA key pair"));
171 public_key = server->pkcs->pkcs->get_public_key(server->pkcs->context,
173 private_key = server->pkcs->pkcs->get_private_key(server->pkcs->context,
176 SILC_LOG_HEXDUMP(("public key"), public_key, pk_len);
177 SILC_LOG_HEXDUMP(("private key"), private_key, prv_len);
180 silc_pkcs_public_key_alloc("rsa", "UN=root, HN=dummy",
182 server->private_key =
183 silc_pkcs_private_key_alloc("rsa", private_key, prv_len);
186 silc_pkcs_save_public_key("pubkey.pub", server->public_key,
188 silc_pkcs_save_private_key("privkey.prv", server->private_key, NULL,
191 memset(public_key, 0, pk_len);
192 memset(private_key, 0, prv_len);
193 silc_free(public_key);
194 silc_free(private_key);
196 silc_pkcs_load_public_key("pubkey.pub", &server->public_key,
198 silc_pkcs_load_private_key("privkey.prv", &server->private_key,
203 /* Create a listening server. Note that our server can listen on
204 multiple ports. All listeners are created here and now. */
205 /* XXX Still check this whether to use server_info or listen_port. */
207 while(server->config->listen_port) {
210 tmp = silc_net_create_server(server->config->listen_port->port,
211 server->config->listen_port->host);
215 sock = silc_realloc(sock, (sizeof(int *) * (sock_count + 1)));
216 sock[sock_count] = tmp;
217 server->config->listen_port = server->config->listen_port->next;
221 /* Initialize ID caches */
222 server->local_list->clients = silc_idcache_alloc(0);
223 server->local_list->servers = silc_idcache_alloc(0);
224 server->local_list->channels = silc_idcache_alloc(0);
226 /* These are allocated for normal server as well as these hold some
227 global information that the server has fetched from its router. For
228 router these are used as they are supposed to be used on router. */
229 server->global_list->clients = silc_idcache_alloc(0);
230 server->global_list->servers = silc_idcache_alloc(0);
231 server->global_list->channels = silc_idcache_alloc(0);
233 /* Allocate the entire socket list that is used in server. Eventually
234 all connections will have entry in this table (it is a table of
235 pointers to the actual object that is allocated individually
237 server->sockets = silc_calloc(SILC_SERVER_MAX_CONNECTIONS,
238 sizeof(*server->sockets));
240 for (i = 0; i < sock_count; i++) {
241 SilcSocketConnection newsocket = NULL;
243 /* Set socket to non-blocking mode */
244 silc_net_set_socket_nonblock(sock[i]);
245 server->sock = sock[i];
247 /* Create a Server ID for the server. */
248 silc_id_create_server_id(sock[i], server->rng, &id);
254 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
255 server->id_string_len = silc_id_get_len(SILC_ID_SERVER);
256 server->id_type = SILC_ID_SERVER;
257 server->server_name = server->config->server_info->server_name;
259 /* Add ourselves to the server list. We don't have a router yet
260 beacuse we haven't established a route yet. It will be done later.
261 For now, NULL is sent as router. This allocates new entry to
264 silc_idlist_add_server(server->local_list,
265 server->config->server_info->server_name,
266 server->server_type, server->id, NULL, NULL);
268 SILC_LOG_ERROR(("Could not add ourselves to cache"));
272 /* Add ourselves also to the socket table. The entry allocated above
273 is sent as argument for fast referencing in the future. */
274 silc_socket_alloc(sock[i], SILC_SOCKET_TYPE_SERVER, id_entry,
279 server->sockets[sock[i]] = newsocket;
281 /* Put the allocated socket pointer also to the entry allocated above
282 for fast back-referencing to the socket list. */
283 id_entry->connection = (void *)server->sockets[sock[i]];
284 server->id_entry = id_entry;
287 /* Register the task queues. In SILC we have by default three task queues.
288 One task queue for non-timeout tasks which perform different kind of
289 I/O on file descriptors, timeout task queue for timeout tasks, and,
290 generic non-timeout task queue whose tasks apply to all connections. */
291 silc_task_queue_alloc(&server->io_queue, TRUE);
292 if (!server->io_queue) {
295 silc_task_queue_alloc(&server->timeout_queue, TRUE);
296 if (!server->timeout_queue) {
299 silc_task_queue_alloc(&server->generic_queue, TRUE);
300 if (!server->generic_queue) {
304 /* Register protocols */
305 silc_server_protocols_register();
307 /* Initialize the scheduler */
308 silc_schedule_init(&server->io_queue, &server->timeout_queue,
309 &server->generic_queue,
310 SILC_SERVER_MAX_CONNECTIONS);
312 /* Add the first task to the queue. This is task that is executed by
313 timeout. It expires as soon as the caller calls silc_server_run. This
314 task performs authentication protocol and key exchange with our
316 silc_task_register(server->timeout_queue, sock[0],
317 silc_server_connect_to_router,
318 (void *)server, 0, 1,
320 SILC_TASK_PRI_NORMAL);
322 /* Add listener task to the queue. This task receives new connections to the
323 server. This task remains on the queue until the end of the program. */
324 silc_task_register(server->io_queue, sock[0],
325 silc_server_accept_new_connection,
326 (void *)server, 0, 0,
328 SILC_TASK_PRI_NORMAL);
329 server->listenning = TRUE;
331 /* If server connections has been configured then we must be router as
332 normal server cannot have server connections, only router connections. */
333 if (server->config->servers)
334 server->server_type = SILC_ROUTER;
336 SILC_LOG_DEBUG(("Server initialized"));
338 /* We are done here, return succesfully */
341 silc_task_queue_free(server->timeout_queue);
343 silc_task_queue_free(server->io_queue);
345 for (i = 0; i < sock_count; i++)
346 silc_net_close_server(sock[i]);
351 /* Fork server to background and set gid+uid to non-root.
352 Silcd will not run as root, so trying to set either user or group to
353 root will cause silcd to exit. */
355 void silc_server_daemonise(SilcServer server)
357 /* Are we executing silcd as root or a regular user? */
364 if (!server->config->identity || !server->config->identity->user ||
365 !server->config->identity->group) {
366 fprintf(stderr, "Error:"
367 "\tSILC server must not be run as root. For the security of your\n"
368 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
369 "\tuser account. Modify the [Identity] configuration section to run\n"
370 "\tthe server as non-root user.\n");
374 /* Get the values given for user and group in configuration file */
375 user=server->config->identity->user;
376 group=server->config->identity->group;
378 /* Check whether the user/group information is text */
379 if (atoi(user)!=0 || atoi(group)!=0) {
380 SILC_LOG_DEBUG(("Invalid user and/or group information"));
381 SILC_LOG_DEBUG(("User and/or group given as number"));
382 fprintf(stderr, "Invalid user and/or group information\n");
383 fprintf(stderr, "Please assign them as names, not numbers\n");
387 /* Catch the nasty incident of string "0" returning 0 from atoi */
388 if (strcmp("0", user)==0 || strcmp("0", group)==0) {
389 SILC_LOG_DEBUG(("User and/or group configured to 0. Unacceptable"));
390 fprintf(stderr, "User and/or group configured to 0. Exiting\n");
398 fprintf(stderr, "No such user %s found\n", user);
403 fprintf(stderr, "No such group %s found\n", group);
407 /* Check whether user and/or group is set to root. If yes, exit
408 immediately. Otherwise, setgid and setuid server to user.group */
409 if (gr->gr_gid==0 || pw->pw_uid==0) {
410 fprintf(stderr, "Error:"
411 "\tSILC server must not be run as root. For the security of your\n"
412 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
413 "\tuser account. Modify the [Identity] configuration section to run\n"
414 "\tthe server as non-root user.\n");
417 /* Fork server to background, making it a daemon */
419 SILC_LOG_DEBUG(("Server started as root. Dropping privileges."));
420 SILC_LOG_DEBUG(("Forking SILC server to background"));
425 SILC_LOG_DEBUG(("Changing to group %s", group));
426 if(setgid(gr->gr_gid)==0) {
427 SILC_LOG_DEBUG(("Setgid to %s", group));
429 SILC_LOG_DEBUG(("Setgid to %s failed", group));
430 fprintf(stderr, "Tried to setgid %s but no such group. Exiting\n",
434 SILC_LOG_DEBUG(("Changing to user nobody"));
435 if(setuid(pw->pw_uid)==0) {
436 SILC_LOG_DEBUG(("Setuid to %s", user));
438 SILC_LOG_DEBUG(("Setuid to %s failed", user));
439 fprintf(stderr, "Tried to setuid %s but no such user. Exiting\n",
445 /* Fork server to background, making it a daemon */
447 SILC_LOG_DEBUG(("Server started as user"));
448 SILC_LOG_DEBUG(("Forking SILC server to background"));
455 /* Stops the SILC server. This function is used to shutdown the server.
456 This is usually called after the scheduler has returned. After stopping
457 the server one should call silc_server_free. */
459 void silc_server_stop(SilcServer server)
461 SILC_LOG_DEBUG(("Stopping server"));
463 /* Stop the scheduler, although it might be already stopped. This
464 doesn't hurt anyone. This removes all the tasks and task queues,
466 silc_schedule_stop();
467 silc_schedule_uninit();
469 silc_server_protocols_unregister();
471 SILC_LOG_DEBUG(("Server stopped"));
474 /* The heart of the server. This runs the scheduler thus runs the server.
475 When this returns the server has been stopped and the program will
478 void silc_server_run(SilcServer server)
480 SILC_LOG_DEBUG(("Running server"));
482 /* Start the scheduler, the heart of the SILC server. When this returns
483 the program will be terminated. */
487 /* Timeout callback that will be called to retry connecting to remote
488 router. This is used by both normal and router server. This will wait
489 before retrying the connecting. The timeout is generated by exponential
490 backoff algorithm. */
492 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
494 SilcServerConnection sconn = (SilcServerConnection)context;
495 SilcServer server = sconn->server;
497 SILC_LOG_INFO(("Retrying connecting to a router"));
499 /* Calculate next timeout */
500 if (sconn->retry_count >= 1) {
501 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
502 if (sconn->retry_timeout > SILC_SERVER_RETRY_INTERVAL_MAX)
503 sconn->retry_timeout = SILC_SERVER_RETRY_INTERVAL_MAX;
505 sconn->retry_timeout = server->params->retry_interval_min;
507 sconn->retry_count++;
508 sconn->retry_timeout = sconn->retry_timeout +
509 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
511 /* If we've reached max retry count, give up. */
512 if (sconn->retry_count > server->params->retry_count &&
513 server->params->retry_keep_trying == FALSE) {
514 SILC_LOG_ERROR(("Could not connect to router, giving up"));
518 /* Wait one before retrying */
519 silc_task_register(server->timeout_queue, fd, silc_server_connect_router,
520 context, sconn->retry_timeout,
521 server->params->retry_interval_min_usec,
522 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
525 /* Generic routine to use connect to a router. */
527 SILC_TASK_CALLBACK(silc_server_connect_router)
529 SilcServerConnection sconn = (SilcServerConnection)context;
530 SilcServer server = sconn->server;
531 SilcSocketConnection newsocket;
532 SilcProtocol protocol;
533 SilcServerKEInternalContext *proto_ctx;
536 /* Connect to remote host */
537 sock = silc_net_create_connection(sconn->remote_port,
540 SILC_LOG_ERROR(("Could not connect to router"));
541 silc_task_register(server->timeout_queue, fd,
542 silc_server_connect_to_router_retry,
543 context, 0, 1, SILC_TASK_TIMEOUT,
544 SILC_TASK_PRI_NORMAL);
548 /* Set socket options */
549 silc_net_set_socket_nonblock(sock);
550 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
552 /* Create socket connection for the connection. Even though we
553 know that we are connecting to a router we will mark the socket
554 to be unknown connection until we have executed authentication
556 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
557 server->sockets[sock] = newsocket;
558 newsocket->hostname = strdup(sconn->remote_host);
559 newsocket->ip = strdup(sconn->remote_host);
560 newsocket->port = sconn->remote_port;
561 sconn->sock = newsocket;
563 /* Allocate internal protocol context. This is sent as context
565 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
566 proto_ctx->server = (void *)server;
567 proto_ctx->context = (void *)sconn;
568 proto_ctx->sock = newsocket;
569 proto_ctx->rng = server->rng;
570 proto_ctx->responder = FALSE;
572 /* Perform key exchange protocol. silc_server_connect_to_router_second
573 will be called after the protocol is finished. */
574 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
575 &protocol, proto_ctx,
576 silc_server_connect_to_router_second);
577 newsocket->protocol = protocol;
579 /* Register a timeout task that will be executed if the protocol
580 is not executed within set limit. */
581 proto_ctx->timeout_task =
582 silc_task_register(server->timeout_queue, sock,
583 silc_server_timeout_remote,
584 server, server->params->protocol_timeout,
585 server->params->protocol_timeout_usec,
589 /* Register the connection for network input and output. This sets
590 that scheduler will listen for incoming packets for this connection
591 and sets that outgoing packets may be sent to this connection as
592 well. However, this doesn't set the scheduler for outgoing traffic,
593 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
594 later when outgoing data is available. */
595 context = (void *)server;
596 SILC_REGISTER_CONNECTION_FOR_IO(sock);
598 /* Run the protocol */
599 protocol->execute(server->timeout_queue, 0, protocol, sock, 0, 0);
602 /* This function connects to our primary router or if we are a router this
603 establishes all our primary routes. This is called at the start of the
604 server to do authentication and key exchange with our router - called
607 SILC_TASK_CALLBACK(silc_server_connect_to_router)
609 SilcServer server = (SilcServer)context;
610 SilcServerConnection sconn;
612 SILC_LOG_DEBUG(("Connecting to router(s)"));
614 /* If we are normal SILC server we need to connect to our cell's
616 if (server->server_type == SILC_SERVER) {
617 SILC_LOG_DEBUG(("We are normal server"));
619 /* Create connection to the router, if configured. */
620 if (server->config->routers) {
622 /* Allocate connection object for hold connection specific stuff. */
623 sconn = silc_calloc(1, sizeof(*sconn));
624 sconn->server = server;
625 sconn->remote_host = server->config->routers->host;
626 sconn->remote_port = server->config->routers->port;
628 silc_task_register(server->timeout_queue, fd,
629 silc_server_connect_router,
630 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
631 SILC_TASK_PRI_NORMAL);
636 /* If we are a SILC router we need to establish all of our primary
638 if (server->server_type == SILC_ROUTER) {
639 SilcServerConfigSectionServerConnection *ptr;
641 SILC_LOG_DEBUG(("We are router"));
643 /* Create the connections to all our routes */
644 ptr = server->config->routers;
647 SILC_LOG_DEBUG(("Router connection [%s] %s:%d",
648 ptr->initiator ? "Initiator" : "Responder",
649 ptr->host, ptr->port));
651 if (ptr->initiator) {
652 /* Allocate connection object for hold connection specific stuff. */
653 sconn = silc_calloc(1, sizeof(*sconn));
654 sconn->server = server;
655 sconn->remote_host = ptr->host;
656 sconn->remote_port = ptr->port;
658 silc_task_register(server->timeout_queue, fd,
659 silc_server_connect_router,
660 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
661 SILC_TASK_PRI_NORMAL);
671 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
673 /* There wasn't a configured router, we will continue but we don't
674 have a connection to outside world. We will be standalone server. */
675 server->standalone = TRUE;
678 /* Second part of connecting to router(s). Key exchange protocol has been
679 executed and now we will execute authentication protocol. */
681 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
683 SilcProtocol protocol = (SilcProtocol)context;
684 SilcServerKEInternalContext *ctx =
685 (SilcServerKEInternalContext *)protocol->context;
686 SilcServer server = (SilcServer)ctx->server;
687 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
688 SilcSocketConnection sock = NULL;
689 SilcServerConnAuthInternalContext *proto_ctx;
691 SILC_LOG_DEBUG(("Start"));
693 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
694 /* Error occured during protocol */
695 silc_protocol_free(protocol);
697 silc_packet_context_free(ctx->packet);
699 silc_ske_free(ctx->ske);
701 silc_free(ctx->dest_id);
704 sock->protocol = NULL;
705 silc_server_disconnect_remote(server, sock, "Server closed connection: "
706 "Key exchange failed");
710 /* Allocate internal context for the authentication protocol. This
711 is sent as context for the protocol. */
712 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
713 proto_ctx->server = (void *)server;
714 proto_ctx->context = (void *)sconn;
715 proto_ctx->sock = sock = server->sockets[fd];
716 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
717 proto_ctx->dest_id_type = ctx->dest_id_type;
718 proto_ctx->dest_id = ctx->dest_id;
720 /* Resolve the authentication method used in this connection */
721 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
722 if (server->config->routers) {
723 SilcServerConfigSectionServerConnection *conn = NULL;
725 /* Check if we find a match from user configured connections */
726 conn = silc_server_config_find_router_conn(server->config,
730 /* Match found. Use the configured authentication method */
731 proto_ctx->auth_meth = conn->auth_meth;
732 if (conn->auth_data) {
733 proto_ctx->auth_data = strdup(conn->auth_data);
734 proto_ctx->auth_data_len = strlen(conn->auth_data);
737 /* No match found. */
744 /* Free old protocol as it is finished now */
745 silc_protocol_free(protocol);
747 silc_packet_context_free(ctx->packet);
749 sock->protocol = NULL;
751 /* Allocate the authentication protocol. This is allocated here
752 but we won't start it yet. We will be receiving party of this
753 protocol thus we will wait that connecting party will make
755 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
756 &sock->protocol, proto_ctx,
757 silc_server_connect_to_router_final);
759 /* Register timeout task. If the protocol is not executed inside
760 this timelimit the connection will be terminated. Currently
761 this is 15 seconds and is hard coded limit (XXX). */
762 proto_ctx->timeout_task =
763 silc_task_register(server->timeout_queue, sock->sock,
764 silc_server_timeout_remote,
765 (void *)server, 15, 0,
769 /* Run the protocol */
770 sock->protocol->execute(server->timeout_queue, 0,
771 sock->protocol, sock->sock, 0, 0);
774 /* Finalizes the connection to router. Registers a server task to the
775 queue so that we can accept new connections. */
777 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
779 SilcProtocol protocol = (SilcProtocol)context;
780 SilcServerConnAuthInternalContext *ctx =
781 (SilcServerConnAuthInternalContext *)protocol->context;
782 SilcServer server = (SilcServer)ctx->server;
783 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
784 SilcSocketConnection sock = ctx->sock;
785 SilcServerEntry id_entry;
787 SilcServerHBContext hb_context;
788 unsigned char *id_string;
790 SILC_LOG_DEBUG(("Start"));
792 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
793 /* Error occured during protocol */
795 silc_free(ctx->dest_id);
796 silc_server_disconnect_remote(server, sock, "Server closed connection: "
797 "Authentication failed");
801 /* Add a task to the queue. This task receives new connections to the
802 server. This task remains on the queue until the end of the program. */
803 if (!server->listenning) {
804 silc_task_register(server->io_queue, server->sock,
805 silc_server_accept_new_connection,
806 (void *)server, 0, 0,
808 SILC_TASK_PRI_NORMAL);
809 server->listenning = TRUE;
812 /* Send NEW_SERVER packet to the router. We will become registered
813 to the SILC network after sending this packet. */
814 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
815 packet = silc_buffer_alloc(2 + 2 + SILC_ID_SERVER_LEN +
816 strlen(server->server_name));
817 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
818 silc_buffer_format(packet,
819 SILC_STR_UI_SHORT(SILC_ID_SERVER_LEN),
820 SILC_STR_UI_XNSTRING(id_string, SILC_ID_SERVER_LEN),
821 SILC_STR_UI_SHORT(strlen(server->server_name)),
822 SILC_STR_UI_XNSTRING(server->server_name,
823 strlen(server->server_name)),
826 /* Send the packet */
827 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
828 packet->data, packet->len, TRUE);
829 silc_buffer_free(packet);
830 silc_free(id_string);
832 SILC_LOG_DEBUG(("Connected to router %s", sock->hostname));
834 /* Add the connected router to local server list */
835 server->standalone = FALSE;
836 id_entry = silc_idlist_add_server(server->local_list, sock->hostname,
837 SILC_ROUTER, ctx->dest_id, NULL, sock);
840 silc_free(ctx->dest_id);
841 silc_server_disconnect_remote(server, sock, "Server closed connection: "
842 "Authentication failed");
846 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
847 silc_free(sock->user_data);
848 sock->user_data = (void *)id_entry;
849 sock->type = SILC_SOCKET_TYPE_ROUTER;
850 server->id_entry->router = id_entry;
851 server->router = id_entry;
852 server->router->data.registered = TRUE;
854 /* Perform keepalive. The `hb_context' will be freed automatically
855 when finally calling the silc_socket_free function. XXX hardcoded
857 hb_context = silc_calloc(1, sizeof(*hb_context));
858 hb_context->server = server;
859 silc_socket_set_heartbeat(sock, 600, hb_context,
860 silc_server_perform_heartbeat,
861 server->timeout_queue);
863 /* If we are router then announce our possible servers. */
864 if (server->server_type == SILC_ROUTER)
865 silc_server_announce_servers(server);
867 /* Announce our clients and channels to the router */
868 silc_server_announce_clients(server);
869 silc_server_announce_channels(server);
872 /* Free the temporary connection data context */
876 /* Free the protocol object */
877 silc_protocol_free(protocol);
879 silc_packet_context_free(ctx->packet);
881 silc_ske_free(ctx->ske);
883 sock->protocol = NULL;
886 /* Accepts new connections to the server. Accepting new connections are
887 done in three parts to make it async. */
889 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
891 SilcServer server = (SilcServer)context;
892 SilcSocketConnection newsocket;
893 SilcServerKEInternalContext *proto_ctx;
896 SILC_LOG_DEBUG(("Accepting new connection"));
898 server->stat.conn_attempts++;
900 sock = silc_net_accept_connection(server->sock);
902 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
903 server->stat.conn_failures++;
907 /* Check max connections */
908 if (sock > SILC_SERVER_MAX_CONNECTIONS) {
909 if (server->config->redirect) {
910 /* XXX Redirecting connection to somewhere else now?? */
911 /*silc_server_send_notify("Server is full, trying to redirect..."); */
913 SILC_LOG_ERROR(("Refusing connection, server is full"));
914 server->stat.conn_failures++;
919 /* Set socket options */
920 silc_net_set_socket_nonblock(sock);
921 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
923 /* We don't create a ID yet, since we don't know what type of connection
924 this is yet. But, we do add the connection to the socket table. */
925 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
926 server->sockets[sock] = newsocket;
928 /* XXX This MUST be done async as this will block the entire server
929 process. Either we have to do our own resolver stuff or in the future
930 we can use threads. */
931 /* Perform name and address lookups for the remote host. */
932 silc_net_check_host_by_sock(sock, &newsocket->hostname, &newsocket->ip);
933 if ((server->params->require_reverse_mapping && !newsocket->hostname) ||
935 SILC_LOG_ERROR(("IP/DNS lookup failed"));
936 server->stat.conn_failures++;
939 if (!newsocket->hostname)
940 newsocket->hostname = strdup(newsocket->ip);
941 newsocket->port = silc_net_get_remote_port(sock);
943 SILC_LOG_INFO(("Incoming connection from %s (%s)", newsocket->hostname,
946 /* Allocate internal context for key exchange protocol. This is
947 sent as context for the protocol. */
948 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
949 proto_ctx->server = context;
950 proto_ctx->sock = newsocket;
951 proto_ctx->rng = server->rng;
952 proto_ctx->responder = TRUE;
954 /* Prepare the connection for key exchange protocol. We allocate the
955 protocol but will not start it yet. The connector will be the
956 initiator of the protocol thus we will wait for initiation from
957 there before we start the protocol. */
958 server->stat.auth_attempts++;
959 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
960 &newsocket->protocol, proto_ctx,
961 silc_server_accept_new_connection_second);
963 /* Register a timeout task that will be executed if the connector
964 will not start the key exchange protocol within 60 seconds. For
965 now, this is a hard coded limit. After 60 secs the connection will
966 be closed if the key exchange protocol has not been started. */
967 proto_ctx->timeout_task =
968 silc_task_register(server->timeout_queue, newsocket->sock,
969 silc_server_timeout_remote,
974 /* Register the connection for network input and output. This sets
975 that scheduler will listen for incoming packets for this connection
976 and sets that outgoing packets may be sent to this connection as well.
977 However, this doesn't set the scheduler for outgoing traffic, it
978 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
979 later when outgoing data is available. */
980 SILC_REGISTER_CONNECTION_FOR_IO(sock);
983 /* Second part of accepting new connection. Key exchange protocol has been
984 performed and now it is time to do little connection authentication
985 protocol to figure out whether this connection is client or server
986 and whether it has right to access this server (especially server
987 connections needs to be authenticated). */
989 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
991 SilcProtocol protocol = (SilcProtocol)context;
992 SilcServerKEInternalContext *ctx =
993 (SilcServerKEInternalContext *)protocol->context;
994 SilcServer server = (SilcServer)ctx->server;
995 SilcSocketConnection sock = NULL;
996 SilcServerConnAuthInternalContext *proto_ctx;
998 SILC_LOG_DEBUG(("Start"));
1000 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
1001 /* Error occured during protocol */
1002 silc_protocol_free(protocol);
1004 silc_packet_context_free(ctx->packet);
1006 silc_ske_free(ctx->ske);
1008 silc_free(ctx->dest_id);
1011 sock->protocol = NULL;
1012 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1013 "Key exchange failed");
1014 server->stat.auth_failures++;
1018 /* Allocate internal context for the authentication protocol. This
1019 is sent as context for the protocol. */
1020 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1021 proto_ctx->server = (void *)server;
1022 proto_ctx->sock = sock = server->sockets[fd];
1023 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1024 proto_ctx->responder = TRUE;
1025 proto_ctx->dest_id_type = ctx->dest_id_type;
1026 proto_ctx->dest_id = ctx->dest_id;
1028 /* Free old protocol as it is finished now */
1029 silc_protocol_free(protocol);
1031 silc_packet_context_free(ctx->packet);
1033 sock->protocol = NULL;
1035 /* Allocate the authentication protocol. This is allocated here
1036 but we won't start it yet. We will be receiving party of this
1037 protocol thus we will wait that connecting party will make
1038 their first move. */
1039 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1040 &sock->protocol, proto_ctx,
1041 silc_server_accept_new_connection_final);
1043 /* Register timeout task. If the protocol is not executed inside
1044 this timelimit the connection will be terminated. Currently
1045 this is 60 seconds and is hard coded limit (XXX). */
1046 proto_ctx->timeout_task =
1047 silc_task_register(server->timeout_queue, sock->sock,
1048 silc_server_timeout_remote,
1049 (void *)server, 60, 0,
1054 /* Final part of accepting new connection. The connection has now
1055 been authenticated and keys has been exchanged. We also know whether
1056 this is client or server connection. */
1058 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1060 SilcProtocol protocol = (SilcProtocol)context;
1061 SilcServerConnAuthInternalContext *ctx =
1062 (SilcServerConnAuthInternalContext *)protocol->context;
1063 SilcServer server = (SilcServer)ctx->server;
1064 SilcSocketConnection sock = ctx->sock;
1065 SilcServerHBContext hb_context;
1066 void *id_entry = NULL;
1068 SILC_LOG_DEBUG(("Start"));
1070 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
1071 /* Error occured during protocol */
1072 silc_protocol_free(protocol);
1074 silc_packet_context_free(ctx->packet);
1076 silc_ske_free(ctx->ske);
1078 silc_free(ctx->dest_id);
1081 sock->protocol = NULL;
1082 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1083 "Authentication failed");
1084 server->stat.auth_failures++;
1088 sock->type = ctx->conn_type;
1089 switch(sock->type) {
1090 case SILC_SOCKET_TYPE_CLIENT:
1092 SilcClientEntry client;
1094 SILC_LOG_DEBUG(("Remote host is client"));
1095 SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
1098 /* Add the client to the client ID cache. The nickname and Client ID
1099 and other information is created after we have received NEW_CLIENT
1100 packet from client. */
1101 client = silc_idlist_add_client(server->local_list,
1102 NULL, NULL, NULL, NULL, NULL, sock);
1104 SILC_LOG_ERROR(("Could not add new client to cache"));
1105 silc_free(sock->user_data);
1110 server->stat.my_clients++;
1111 server->stat.clients++;
1112 if (server->server_type == SILC_ROUTER)
1113 server->stat.cell_clients++;
1115 id_entry = (void *)client;
1118 case SILC_SOCKET_TYPE_SERVER:
1119 case SILC_SOCKET_TYPE_ROUTER:
1121 SilcServerEntry new_server;
1123 SILC_LOG_DEBUG(("Remote host is %s",
1124 sock->type == SILC_SOCKET_TYPE_SERVER ?
1125 "server" : "router"));
1126 SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
1127 sock->ip, sock->type == SILC_SOCKET_TYPE_SERVER ?
1128 "server" : "router"));
1130 /* Add the server into server cache. The server name and Server ID
1131 is updated after we have received NEW_SERVER packet from the
1132 server. We mark ourselves as router for this server if we really
1135 silc_idlist_add_server(server->local_list, NULL,
1136 sock->type == SILC_SOCKET_TYPE_SERVER ?
1137 SILC_SERVER : SILC_ROUTER, NULL,
1138 sock->type == SILC_SOCKET_TYPE_SERVER ?
1139 server->id_entry : NULL, sock);
1141 SILC_LOG_ERROR(("Could not add new server to cache"));
1142 silc_free(sock->user_data);
1147 if (sock->type == SILC_SOCKET_TYPE_SERVER)
1148 server->stat.my_servers++;
1150 server->stat.my_routers++;
1151 server->stat.servers++;
1153 id_entry = (void *)new_server;
1155 /* There is connection to other server now, if it is router then
1156 we will have connection to outside world. If we are router but
1157 normal server connected to us then we will remain standalone,
1158 if we are standlone. */
1159 if (server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER) {
1160 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1161 server->standalone = FALSE;
1162 if (!server->id_entry->router) {
1163 server->id_entry->router = id_entry;
1164 server->router = id_entry;
1173 /* Add the common data structure to the ID entry. */
1175 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1177 /* Add to sockets internal pointer for fast referencing */
1178 silc_free(sock->user_data);
1179 sock->user_data = id_entry;
1181 /* Connection has been fully established now. Everything is ok. */
1182 SILC_LOG_DEBUG(("New connection authenticated"));
1184 /* Perform keepalive. The `hb_context' will be freed automatically
1185 when finally calling the silc_socket_free function. XXX hardcoded
1187 hb_context = silc_calloc(1, sizeof(*hb_context));
1188 hb_context->server = server;
1189 silc_socket_set_heartbeat(sock, 600, hb_context,
1190 silc_server_perform_heartbeat,
1191 server->timeout_queue);
1193 silc_protocol_free(protocol);
1195 silc_packet_context_free(ctx->packet);
1197 silc_ske_free(ctx->ske);
1199 silc_free(ctx->dest_id);
1201 sock->protocol = NULL;
1204 /* This function is used to read packets from network and send packets to
1205 network. This is usually a generic task. */
1207 SILC_TASK_CALLBACK(silc_server_packet_process)
1209 SilcServer server = (SilcServer)context;
1210 SilcSocketConnection sock = server->sockets[fd];
1211 SilcIDListData idata;
1212 SilcCipher cipher = NULL;
1213 SilcHmac hmac = NULL;
1219 SILC_LOG_DEBUG(("Processing packet"));
1221 /* Packet sending */
1223 if (type == SILC_TASK_WRITE) {
1224 /* Do not send data to disconnected connection */
1225 if (SILC_IS_DISCONNECTED(sock))
1228 server->stat.packets_sent++;
1230 if (sock->outbuf->data - sock->outbuf->head)
1231 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1233 ret = silc_server_packet_send_real(server, sock, TRUE);
1235 /* If returned -2 could not write to connection now, will do
1243 /* The packet has been sent and now it is time to set the connection
1244 back to only for input. When there is again some outgoing data
1245 available for this connection it will be set for output as well.
1246 This call clears the output setting and sets it only for input. */
1247 SILC_SET_CONNECTION_FOR_INPUT(fd);
1248 SILC_UNSET_OUTBUF_PENDING(sock);
1250 silc_buffer_clear(sock->outbuf);
1254 /* Packet receiving */
1256 /* Read some data from connection */
1257 ret = silc_packet_receive(sock);
1263 SILC_LOG_DEBUG(("Read EOF"));
1265 /* If connection is disconnecting already we will finally
1266 close the connection */
1267 if (SILC_IS_DISCONNECTING(sock)) {
1268 if (sock->user_data)
1269 silc_server_free_sock_user_data(server, sock);
1270 silc_server_close_connection(server, sock);
1274 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1275 SILC_SET_DISCONNECTING(sock);
1277 /* If the closed connection was our primary router connection the
1278 start re-connecting phase. */
1279 if (!server->standalone && server->server_type == SILC_SERVER &&
1280 sock == server->router->connection)
1281 silc_task_register(server->timeout_queue, 0,
1282 silc_server_connect_to_router,
1285 SILC_TASK_PRI_NORMAL);
1287 if (sock->user_data)
1288 silc_server_free_sock_user_data(server, sock);
1289 silc_server_close_connection(server, sock);
1293 /* If connection is disconnecting or disconnected we will ignore
1295 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1296 SILC_LOG_DEBUG(("Ignoring read data from disonnected connection"));
1300 server->stat.packets_received++;
1302 /* Get keys and stuff from ID entry */
1303 idata = (SilcIDListData)sock->user_data;
1305 idata->last_receive = time(NULL);
1306 cipher = idata->receive_key;
1310 /* Process the packet. This will call the parser that will then
1311 decrypt and parse the packet. */
1312 silc_packet_receive_process(sock, cipher, hmac, silc_server_packet_parse,
1316 /* Parses whole packet, received earlier. */
1318 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1320 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1321 SilcServer server = (SilcServer)parse_ctx->context;
1322 SilcSocketConnection sock = parse_ctx->sock;
1323 SilcPacketContext *packet = parse_ctx->packet;
1326 SILC_LOG_DEBUG(("Start"));
1328 /* Decrypt the received packet */
1329 ret = silc_packet_decrypt(parse_ctx->cipher, parse_ctx->hmac,
1330 packet->buffer, packet);
1335 /* Parse the packet. Packet type is returned. */
1336 ret = silc_packet_parse(packet);
1338 /* Parse the packet header in special way as this is "special"
1340 ret = silc_packet_parse_special(packet);
1343 if (ret == SILC_PACKET_NONE)
1346 if (server->server_type == SILC_ROUTER) {
1347 /* Route the packet if it is not destined to us. Other ID types but
1348 server are handled separately after processing them. */
1349 if (packet->dst_id_type == SILC_ID_SERVER &&
1350 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1351 SILC_ID_SERVER_COMPARE(packet->dst_id, server->id_string)) {
1353 /* Route the packet to fastest route for the destination ID */
1354 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1355 packet->dst_id_type);
1358 silc_server_packet_route(server,
1359 silc_server_route_get(server, id,
1360 packet->dst_id_type),
1366 /* Broadcast packet if it is marked as broadcast packet and it is
1367 originated from router and we are router. */
1368 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1369 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
1370 silc_server_packet_broadcast(server, server->router->connection, packet);
1374 /* Parse the incoming packet type */
1375 silc_server_packet_parse_type(server, sock, packet);
1378 silc_buffer_clear(sock->inbuf);
1379 silc_packet_context_free(packet);
1380 silc_free(parse_ctx);
1383 /* Parser callback called by silc_packet_receive_process. This merely
1384 registers timeout that will handle the actual parsing when appropriate. */
1386 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1388 SilcServer server = (SilcServer)parser_context->context;
1389 SilcSocketConnection sock = parser_context->sock;
1391 switch (sock->type) {
1392 case SILC_SOCKET_TYPE_CLIENT:
1393 case SILC_SOCKET_TYPE_UNKNOWN:
1394 /* Parse the packet with timeout */
1395 silc_task_register(server->timeout_queue, sock->sock,
1396 silc_server_packet_parse_real,
1397 (void *)parser_context, 0, 100000,
1399 SILC_TASK_PRI_NORMAL);
1401 case SILC_SOCKET_TYPE_SERVER:
1402 case SILC_SOCKET_TYPE_ROUTER:
1403 /* Packets from servers are parsed as soon as possible */
1404 silc_task_register(server->timeout_queue, sock->sock,
1405 silc_server_packet_parse_real,
1406 (void *)parser_context, 0, 1,
1408 SILC_TASK_PRI_NORMAL);
1415 /* Parses the packet type and calls what ever routines the packet type
1416 requires. This is done for all incoming packets. */
1418 void silc_server_packet_parse_type(SilcServer server,
1419 SilcSocketConnection sock,
1420 SilcPacketContext *packet)
1422 SilcPacketType type = packet->type;
1424 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1426 /* Parse the packet type */
1428 case SILC_PACKET_DISCONNECT:
1429 SILC_LOG_DEBUG(("Disconnect packet"));
1430 if (packet->flags & SILC_PACKET_FLAG_LIST)
1434 case SILC_PACKET_SUCCESS:
1436 * Success received for something. For now we can have only
1437 * one protocol for connection executing at once hence this
1438 * success message is for whatever protocol is executing currently.
1440 SILC_LOG_DEBUG(("Success packet"));
1441 if (packet->flags & SILC_PACKET_FLAG_LIST)
1443 if (sock->protocol) {
1444 sock->protocol->execute(server->timeout_queue, 0,
1445 sock->protocol, sock->sock, 0, 0);
1449 case SILC_PACKET_FAILURE:
1451 * Failure received for something. For now we can have only
1452 * one protocol for connection executing at once hence this
1453 * failure message is for whatever protocol is executing currently.
1455 SILC_LOG_DEBUG(("Failure packet"));
1456 if (packet->flags & SILC_PACKET_FLAG_LIST)
1458 if (sock->protocol) {
1459 /* XXX Audit the failure type */
1460 sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
1461 sock->protocol->execute(server->timeout_queue, 0,
1462 sock->protocol, sock->sock, 0, 0);
1466 case SILC_PACKET_REJECT:
1467 SILC_LOG_DEBUG(("Reject packet"));
1468 if (packet->flags & SILC_PACKET_FLAG_LIST)
1473 case SILC_PACKET_NOTIFY:
1475 * Received notify packet. Server can receive notify packets from
1476 * router. Server then relays the notify messages to clients if needed.
1478 SILC_LOG_DEBUG(("Notify packet"));
1479 if (packet->flags & SILC_PACKET_FLAG_LIST)
1480 silc_server_notify_list(server, sock, packet);
1482 silc_server_notify(server, sock, packet);
1488 case SILC_PACKET_CHANNEL_MESSAGE:
1490 * Received channel message. Channel messages are special packets
1491 * (although probably most common ones) thus they are handled
1494 SILC_LOG_DEBUG(("Channel Message packet"));
1495 if (packet->flags & SILC_PACKET_FLAG_LIST)
1497 silc_server_channel_message(server, sock, packet);
1500 case SILC_PACKET_CHANNEL_KEY:
1502 * Received key for channel. As channels are created by the router
1503 * the keys are as well. We will distribute the key to all of our
1504 * locally connected clients on the particular channel. Router
1505 * never receives this channel and thus is ignored.
1507 SILC_LOG_DEBUG(("Channel Key packet"));
1508 if (packet->flags & SILC_PACKET_FLAG_LIST)
1510 silc_server_channel_key(server, sock, packet);
1516 case SILC_PACKET_COMMAND:
1518 * Recived command. Processes the command request and allocates the
1519 * command context and calls the command.
1521 SILC_LOG_DEBUG(("Command packet"));
1522 if (packet->flags & SILC_PACKET_FLAG_LIST)
1524 silc_server_command_process(server, sock, packet);
1527 case SILC_PACKET_COMMAND_REPLY:
1529 * Received command reply packet. Received command reply to command. It
1530 * may be reply to command sent by us or reply to command sent by client
1531 * that we've routed further.
1533 SILC_LOG_DEBUG(("Command Reply packet"));
1534 if (packet->flags & SILC_PACKET_FLAG_LIST)
1536 silc_server_command_reply(server, sock, packet);
1540 * Private Message packets
1542 case SILC_PACKET_PRIVATE_MESSAGE:
1544 * Received private message packet. The packet is coming from either
1547 SILC_LOG_DEBUG(("Private Message packet"));
1548 if (packet->flags & SILC_PACKET_FLAG_LIST)
1550 silc_server_private_message(server, sock, packet);
1553 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1555 * Private message key packet.
1557 if (packet->flags & SILC_PACKET_FLAG_LIST)
1562 * Key Exchange protocol packets
1564 case SILC_PACKET_KEY_EXCHANGE:
1565 SILC_LOG_DEBUG(("KE packet"));
1566 if (packet->flags & SILC_PACKET_FLAG_LIST)
1569 if (sock->protocol && sock->protocol->protocol->type
1570 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1572 SilcServerKEInternalContext *proto_ctx =
1573 (SilcServerKEInternalContext *)sock->protocol->context;
1575 proto_ctx->packet = silc_packet_context_dup(packet);
1577 /* Let the protocol handle the packet */
1578 sock->protocol->execute(server->timeout_queue, 0,
1579 sock->protocol, sock->sock, 0, 100000);
1581 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1582 "protocol active, packet dropped."));
1584 /* XXX Trigger KE protocol?? Rekey actually, maybe. */
1588 case SILC_PACKET_KEY_EXCHANGE_1:
1589 SILC_LOG_DEBUG(("KE 1 packet"));
1590 if (packet->flags & SILC_PACKET_FLAG_LIST)
1593 if (sock->protocol && sock->protocol->protocol->type
1594 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1596 SilcServerKEInternalContext *proto_ctx =
1597 (SilcServerKEInternalContext *)sock->protocol->context;
1599 if (proto_ctx->packet)
1600 silc_packet_context_free(proto_ctx->packet);
1602 proto_ctx->packet = silc_packet_context_dup(packet);
1603 proto_ctx->dest_id_type = packet->src_id_type;
1604 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1605 packet->src_id_type);
1606 if (!proto_ctx->dest_id)
1609 /* Let the protocol handle the packet */
1610 sock->protocol->execute(server->timeout_queue, 0,
1611 sock->protocol, sock->sock,
1614 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1615 "protocol active, packet dropped."));
1619 case SILC_PACKET_KEY_EXCHANGE_2:
1620 SILC_LOG_DEBUG(("KE 2 packet"));
1621 if (packet->flags & SILC_PACKET_FLAG_LIST)
1624 if (sock->protocol && sock->protocol->protocol->type
1625 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1627 SilcServerKEInternalContext *proto_ctx =
1628 (SilcServerKEInternalContext *)sock->protocol->context;
1630 if (proto_ctx->packet)
1631 silc_packet_context_free(proto_ctx->packet);
1633 proto_ctx->packet = silc_packet_context_dup(packet);
1634 proto_ctx->dest_id_type = packet->src_id_type;
1635 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1636 packet->src_id_type);
1637 if (!proto_ctx->dest_id)
1640 /* Let the protocol handle the packet */
1641 sock->protocol->execute(server->timeout_queue, 0,
1642 sock->protocol, sock->sock,
1645 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1646 "protocol active, packet dropped."));
1650 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1652 * Connection authentication request packet. When we receive this packet
1653 * we will send to the other end information about our mandatory
1654 * authentication method for the connection. This packet maybe received
1657 SILC_LOG_DEBUG(("Connection authentication request packet"));
1658 if (packet->flags & SILC_PACKET_FLAG_LIST)
1663 * Connection Authentication protocol packets
1665 case SILC_PACKET_CONNECTION_AUTH:
1666 /* Start of the authentication protocol. We receive here the
1667 authentication data and will verify it. */
1668 SILC_LOG_DEBUG(("Connection auth packet"));
1669 if (packet->flags & SILC_PACKET_FLAG_LIST)
1672 if (sock->protocol && sock->protocol->protocol->type
1673 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1675 SilcServerConnAuthInternalContext *proto_ctx =
1676 (SilcServerConnAuthInternalContext *)sock->protocol->context;
1678 proto_ctx->packet = silc_packet_context_dup(packet);
1680 /* Let the protocol handle the packet */
1681 sock->protocol->execute(server->timeout_queue, 0,
1682 sock->protocol, sock->sock, 0, 0);
1684 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1685 "protocol active, packet dropped."));
1689 case SILC_PACKET_NEW_ID:
1691 * Received New ID packet. This includes some new ID that has been
1692 * created. It may be for client, server or channel. This is the way
1693 * to distribute information about new registered entities in the
1696 SILC_LOG_DEBUG(("New ID packet"));
1697 if (packet->flags & SILC_PACKET_FLAG_LIST)
1698 silc_server_new_id_list(server, sock, packet);
1700 silc_server_new_id(server, sock, packet);
1703 case SILC_PACKET_NEW_CLIENT:
1705 * Received new client packet. This includes client information that
1706 * we will use to create initial client ID. After creating new
1707 * ID we will send it to the client.
1709 SILC_LOG_DEBUG(("New Client packet"));
1710 if (packet->flags & SILC_PACKET_FLAG_LIST)
1712 silc_server_new_client(server, sock, packet);
1715 case SILC_PACKET_NEW_SERVER:
1717 * Received new server packet. This includes Server ID and some other
1718 * information that we may save. This is received after server has
1721 SILC_LOG_DEBUG(("New Server packet"));
1722 if (packet->flags & SILC_PACKET_FLAG_LIST)
1724 silc_server_new_server(server, sock, packet);
1727 case SILC_PACKET_NEW_CHANNEL:
1729 * Received new channel packet. Information about new channel in the
1730 * network are distributed using this packet.
1732 SILC_LOG_DEBUG(("New Channel packet"));
1733 if (packet->flags & SILC_PACKET_FLAG_LIST)
1734 silc_server_new_channel_list(server, sock, packet);
1736 silc_server_new_channel(server, sock, packet);
1739 case SILC_PACKET_HEARTBEAT:
1741 * Received heartbeat.
1743 SILC_LOG_DEBUG(("Heartbeat packet"));
1744 if (packet->flags & SILC_PACKET_FLAG_LIST)
1749 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
1755 /* Closes connection to socket connection */
1757 void silc_server_close_connection(SilcServer server,
1758 SilcSocketConnection sock)
1760 SILC_LOG_DEBUG(("Closing connection %d", sock->sock));
1762 /* We won't listen for this connection anymore */
1763 silc_schedule_unset_listen_fd(sock->sock);
1765 /* Unregister all tasks */
1766 silc_task_unregister_by_fd(server->io_queue, sock->sock);
1767 silc_task_unregister_by_fd(server->timeout_queue, sock->sock);
1769 /* Close the actual connection */
1770 silc_net_close_connection(sock->sock);
1771 server->sockets[sock->sock] = NULL;
1772 silc_socket_free(sock);
1775 /* Sends disconnect message to remote connection and disconnects the
1778 void silc_server_disconnect_remote(SilcServer server,
1779 SilcSocketConnection sock,
1780 const char *fmt, ...)
1783 unsigned char buf[4096];
1788 memset(buf, 0, sizeof(buf));
1790 vsprintf(buf, fmt, ap);
1793 SILC_LOG_DEBUG(("Disconnecting remote host"));
1795 SILC_LOG_INFO(("Disconnecting %s:%d (%s) [%s]", sock->hostname,
1797 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1798 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1799 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1802 /* Notify remote end that the conversation is over. The notify message
1803 is tried to be sent immediately. */
1804 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
1805 buf, strlen(buf), TRUE);
1807 /* Mark the connection to be disconnected */
1808 SILC_SET_DISCONNECTED(sock);
1809 silc_server_close_connection(server, sock);
1812 /* Frees client data and notifies about client's signoff. */
1814 void silc_server_free_client_data(SilcServer server,
1815 SilcSocketConnection sock,
1816 SilcClientEntry user_data, char *signoff)
1818 /* Send REMOVE_ID packet to routers. */
1819 if (!server->standalone && server->router)
1820 silc_server_send_notify_signoff(server, server->router->connection,
1821 server->server_type == SILC_SERVER ?
1822 FALSE : TRUE, user_data->id,
1823 SILC_ID_CLIENT_LEN, signoff);
1825 /* Remove client from all channels */
1826 silc_server_remove_from_channels(server, sock, user_data, signoff);
1828 /* XXX must take some info to history before freeing */
1830 /* Free the client entry and everything in it */
1831 silc_idlist_del_data(user_data);
1832 silc_idlist_del_client(server->local_list, user_data);
1833 server->stat.my_clients--;
1834 server->stat.clients--;
1835 if (server->server_type == SILC_ROUTER)
1836 server->stat.cell_clients--;
1839 /* Frees user_data pointer from socket connection object. This also sends
1840 appropriate notify packets to the network to inform about leaving
1843 void silc_server_free_sock_user_data(SilcServer server,
1844 SilcSocketConnection sock)
1846 SILC_LOG_DEBUG(("Start"));
1848 switch(sock->type) {
1849 case SILC_SOCKET_TYPE_CLIENT:
1851 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
1852 silc_server_free_client_data(server, sock, user_data, NULL);
1855 case SILC_SOCKET_TYPE_SERVER:
1856 case SILC_SOCKET_TYPE_ROUTER:
1858 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
1860 /* Send REMOVE_ID packet to routers. */
1861 if (!server->standalone && server->router)
1862 silc_server_send_notify_server_signoff(server,
1863 server->router->connection,
1864 server->server_type ==
1866 FALSE : TRUE, user_data->id,
1867 SILC_ID_SERVER_LEN);
1869 /* Then also free all client entries that this server owns as
1870 they will become invalid now as well. */
1871 silc_server_remove_clients_by_server(server, user_data);
1873 /* If this was our primary router connection then we're lost to
1874 the outside world. */
1875 if (server->server_type == SILC_SERVER && server->router == user_data) {
1876 server->id_entry->router = NULL;
1877 server->router = NULL;
1878 server->standalone = TRUE;
1881 /* Free the server entry */
1882 silc_idlist_del_data(user_data);
1883 silc_idlist_del_server(server->local_list, user_data);
1884 server->stat.my_servers--;
1885 server->stat.servers--;
1886 if (server->server_type == SILC_ROUTER)
1887 server->stat.cell_servers--;
1892 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
1894 silc_idlist_del_data(user_data);
1895 silc_free(user_data);
1900 sock->user_data = NULL;
1903 /* This function is used to remove all client entries by the server `entry'.
1904 This is called when the connection is lost to the server. In this case
1905 we must invalidate all the client entries owned by the server `entry'. */
1907 int silc_server_remove_clients_by_server(SilcServer server,
1908 SilcServerEntry entry)
1910 SilcIDCacheList list = NULL;
1911 SilcIDCacheEntry id_cache = NULL;
1912 SilcClientEntry client = NULL;
1914 if (silc_idcache_find_by_id(server->local_list->clients,
1915 SILC_ID_CACHE_ANY, SILC_ID_CLIENT, &list)) {
1917 if (silc_idcache_list_first(list, &id_cache)) {
1919 client = (SilcClientEntry)id_cache->context;
1921 if (client->router != entry) {
1922 if (!silc_idcache_list_next(list, &id_cache))
1928 /* Remove the client entry */
1929 silc_server_remove_from_channels(server, NULL, client, NULL);
1930 silc_idlist_del_client(server->local_list, client);
1932 if (!silc_idcache_list_next(list, &id_cache))
1936 silc_idcache_list_free(list);
1939 if (silc_idcache_find_by_id(server->global_list->clients,
1940 SILC_ID_CACHE_ANY, SILC_ID_CLIENT, &list)) {
1942 if (silc_idcache_list_first(list, &id_cache)) {
1944 client = (SilcClientEntry)id_cache->context;
1946 if (client->router != entry) {
1947 if (!silc_idcache_list_next(list, &id_cache))
1953 /* Remove the client entry */
1954 silc_server_remove_from_channels(server, NULL, client, NULL);
1955 silc_idlist_del_client(server->global_list, client);
1957 if (!silc_idcache_list_next(list, &id_cache))
1961 silc_idcache_list_free(list);
1967 /* Checks whether given channel has global users. If it does this returns
1968 TRUE and FALSE if there is only locally connected clients on the channel. */
1970 int silc_server_channel_has_global(SilcChannelEntry channel)
1972 SilcChannelClientEntry chl;
1974 silc_list_start(channel->user_list);
1975 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
1976 if (chl->client->router)
1983 /* Checks whether given channel has locally connected users. If it does this
1984 returns TRUE and FALSE if there is not one locally connected client. */
1986 int silc_server_channel_has_local(SilcChannelEntry channel)
1988 SilcChannelClientEntry chl;
1990 silc_list_start(channel->user_list);
1991 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
1992 if (!chl->client->router)
1999 /* Removes client from all channels it has joined. This is used when client
2000 connection is disconnected. If the client on a channel is last, the
2001 channel is removed as well. This sends the SIGNOFF notify types. */
2003 void silc_server_remove_from_channels(SilcServer server,
2004 SilcSocketConnection sock,
2005 SilcClientEntry client,
2006 char *signoff_message)
2008 SilcChannelEntry channel;
2009 SilcChannelClientEntry chl;
2012 SILC_LOG_DEBUG(("Start"));
2014 if (!client || !client->id)
2017 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2019 /* Remove the client from all channels. The client is removed from
2020 the channels' user list. */
2021 silc_list_start(client->channels);
2022 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2023 channel = chl->channel;
2025 /* Remove channel from client's channel list */
2026 silc_list_del(client->channels, chl);
2028 /* Remove channel if there is no users anymore */
2029 if (server->server_type == SILC_ROUTER &&
2030 silc_list_count(channel->user_list) < 2) {
2031 if (!silc_idlist_del_channel(server->local_list, channel))
2032 silc_idlist_del_channel(server->global_list, channel);
2033 server->stat.my_channels--;
2037 /* Remove client from channel's client list */
2038 silc_list_del(channel->user_list, chl);
2040 server->stat.my_chanclients--;
2042 /* If there is no global users on the channel anymore mark the channel
2043 as local channel. */
2044 if (server->server_type == SILC_SERVER &&
2045 !silc_server_channel_has_global(channel))
2046 channel->global_users = FALSE;
2048 /* If there is not at least one local user on the channel then we don't
2049 need the channel entry anymore, we can remove it safely. */
2050 if (server->server_type == SILC_SERVER &&
2051 !silc_server_channel_has_local(channel)) {
2052 /* Notify about leaving client if this channel has global users. */
2053 if (channel->global_users)
2054 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2055 SILC_NOTIFY_TYPE_SIGNOFF,
2056 signoff_message ? 2 : 1,
2057 clidp->data, clidp->len,
2058 signoff_message, signoff_message ?
2059 strlen(signoff_message) : 0);
2061 if (!silc_idlist_del_channel(server->local_list, channel))
2062 silc_idlist_del_channel(server->global_list, channel);
2063 server->stat.my_channels--;
2067 /* Send notify to channel about client leaving SILC and thus
2068 the entire channel. */
2069 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2070 SILC_NOTIFY_TYPE_SIGNOFF,
2071 signoff_message ? 2 : 1,
2072 clidp->data, clidp->len,
2073 signoff_message, signoff_message ?
2074 strlen(signoff_message) : 0);
2077 silc_buffer_free(clidp);
2080 /* Removes client from one channel. This is used for example when client
2081 calls LEAVE command to remove itself from the channel. Returns TRUE
2082 if channel still exists and FALSE if the channel is removed when
2083 last client leaves the channel. If `notify' is FALSE notify messages
2086 int silc_server_remove_from_one_channel(SilcServer server,
2087 SilcSocketConnection sock,
2088 SilcChannelEntry channel,
2089 SilcClientEntry client,
2092 SilcChannelEntry ch;
2093 SilcChannelClientEntry chl;
2096 SILC_LOG_DEBUG(("Start"));
2098 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2100 /* Remove the client from the channel. The client is removed from
2101 the channel's user list. */
2102 silc_list_start(client->channels);
2103 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2104 if (chl->channel != channel)
2109 /* Remove channel from client's channel list */
2110 silc_list_del(client->channels, chl);
2112 /* Remove channel if there is no users anymore */
2113 if (server->server_type == SILC_ROUTER &&
2114 silc_list_count(channel->user_list) < 2) {
2115 if (!silc_idlist_del_channel(server->local_list, channel))
2116 silc_idlist_del_channel(server->global_list, channel);
2117 silc_buffer_free(clidp);
2118 server->stat.my_channels--;
2122 /* Remove client from channel's client list */
2123 silc_list_del(channel->user_list, chl);
2125 server->stat.my_chanclients--;
2127 /* If there is no global users on the channel anymore mark the channel
2128 as local channel. */
2129 if (server->server_type == SILC_SERVER &&
2130 !silc_server_channel_has_global(channel))
2131 channel->global_users = FALSE;
2133 /* If there is not at least one local user on the channel then we don't
2134 need the channel entry anymore, we can remove it safely. */
2135 if (server->server_type == SILC_SERVER &&
2136 !silc_server_channel_has_local(channel)) {
2137 /* Notify about leaving client if this channel has global users. */
2138 if (notify && channel->global_users)
2139 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2140 SILC_NOTIFY_TYPE_LEAVE, 1,
2141 clidp->data, clidp->len);
2143 if (!silc_idlist_del_channel(server->local_list, channel))
2144 silc_idlist_del_channel(server->global_list, channel);
2145 silc_buffer_free(clidp);
2146 server->stat.my_channels--;
2150 /* Send notify to channel about client leaving the channel */
2152 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2153 SILC_NOTIFY_TYPE_LEAVE, 1,
2154 clidp->data, clidp->len);
2158 silc_buffer_free(clidp);
2162 /* Returns TRUE if the given client is on the channel. FALSE if not.
2163 This works because we assure that the user list on the channel is
2164 always in up to date thus we can only check the channel list from
2165 `client' which is faster than checking the user list from `channel'. */
2167 int silc_server_client_on_channel(SilcClientEntry client,
2168 SilcChannelEntry channel)
2170 SilcChannelClientEntry chl;
2172 if (!client || !channel)
2175 silc_list_start(client->channels);
2176 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END)
2177 if (chl->channel == channel)
2183 /* Timeout callback. This is called if connection is idle or for some
2184 other reason is not responding within some period of time. This
2185 disconnects the remote end. */
2187 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2189 SilcServer server = (SilcServer)context;
2190 SilcSocketConnection sock = server->sockets[fd];
2195 if (sock->user_data)
2196 silc_server_free_sock_user_data(server, sock);
2198 silc_server_disconnect_remote(server, sock,
2199 "Server closed connection: "
2200 "Connection timeout");
2203 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2204 function may be used only by router. In real SILC network all channels
2205 are created by routers thus this function is never used by normal
2208 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2209 SilcServerID *router_id,
2214 SilcChannelID *channel_id;
2215 SilcChannelEntry entry;
2218 SILC_LOG_DEBUG(("Creating new channel"));
2223 /* Allocate cipher */
2224 silc_cipher_alloc(cipher, &key);
2226 channel_name = strdup(channel_name);
2228 /* Create the channel */
2229 silc_id_create_channel_id(router_id, server->rng, &channel_id);
2230 entry = silc_idlist_add_channel(server->local_list, channel_name,
2231 SILC_CHANNEL_MODE_NONE, channel_id,
2234 silc_free(channel_name);
2238 /* Now create the actual key material */
2239 silc_server_create_channel_key(server, entry, 16);
2241 /* Notify other routers about the new channel. We send the packet
2242 to our primary route. */
2243 if (broadcast && server->standalone == FALSE) {
2244 silc_server_send_new_channel(server, server->router->connection, TRUE,
2245 channel_name, entry->id, SILC_ID_CHANNEL_LEN);
2248 server->stat.my_channels++;
2253 /* Same as above but creates the channel with Channel ID `channel_id. */
2256 silc_server_create_new_channel_with_id(SilcServer server,
2259 SilcChannelID *channel_id,
2262 SilcChannelEntry entry;
2265 SILC_LOG_DEBUG(("Creating new channel"));
2270 /* Allocate cipher */
2271 silc_cipher_alloc(cipher, &key);
2273 channel_name = strdup(channel_name);
2275 /* Create the channel */
2276 entry = silc_idlist_add_channel(server->local_list, channel_name,
2277 SILC_CHANNEL_MODE_NONE, channel_id,
2280 silc_free(channel_name);
2284 /* Now create the actual key material */
2285 silc_server_create_channel_key(server, entry, 16);
2287 /* Notify other routers about the new channel. We send the packet
2288 to our primary route. */
2289 if (broadcast && server->standalone == FALSE) {
2290 silc_server_send_new_channel(server, server->router->connection, TRUE,
2291 channel_name, entry->id, SILC_ID_CHANNEL_LEN);
2294 server->stat.my_channels++;
2299 /* Generates new channel key. This is used to create the initial channel key
2300 but also to re-generate new key for channel. If `key_len' is provided
2301 it is the bytes of the key length. */
2303 void silc_server_create_channel_key(SilcServer server,
2304 SilcChannelEntry channel,
2305 unsigned int key_len)
2308 unsigned char channel_key[32];
2311 if (!channel->channel_key)
2312 silc_cipher_alloc("twofish", &channel->channel_key);
2316 else if (channel->key_len)
2317 len = channel->key_len / 8;
2319 len = sizeof(channel_key);
2321 /* Create channel key */
2322 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
2325 channel->channel_key->cipher->set_key(channel->channel_key->context,
2328 /* Remove old key if exists */
2330 memset(channel->key, 0, channel->key_len / 8);
2331 silc_free(channel->key);
2335 channel->key_len = len * 8;
2336 channel->key = silc_calloc(len, sizeof(*channel->key));
2337 memcpy(channel->key, channel_key, len);
2338 memset(channel_key, 0, sizeof(channel_key));
2341 /* Saves the channel key found in the encoded `key_payload' buffer. This
2342 function is used when we receive Channel Key Payload and also when we're
2343 processing JOIN command reply. Returns entry to the channel. */
2345 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
2346 SilcBuffer key_payload,
2347 SilcChannelEntry channel)
2349 SilcChannelKeyPayload payload = NULL;
2350 SilcChannelID *id = NULL;
2352 unsigned int tmp_len;
2355 /* Decode channel key payload */
2356 payload = silc_channel_key_payload_parse(key_payload);
2358 SILC_LOG_ERROR(("Bad channel key payload, dropped"));
2363 /* Get the channel entry */
2366 /* Get channel ID */
2367 tmp = silc_channel_key_get_id(payload, &tmp_len);
2368 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
2374 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
2376 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
2378 SILC_LOG_ERROR(("Received key for non-existent channel"));
2384 tmp = silc_channel_key_get_key(payload, &tmp_len);
2390 cipher = silc_channel_key_get_cipher(payload, NULL);;
2396 /* Remove old key if exists */
2398 memset(channel->key, 0, channel->key_len / 8);
2399 silc_free(channel->key);
2400 silc_cipher_free(channel->channel_key);
2403 /* Create new cipher */
2404 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
2410 channel->key_len = tmp_len * 8;
2411 channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
2412 memcpy(channel->key, tmp, tmp_len);
2413 channel->channel_key->cipher->set_key(channel->channel_key->context,
2420 silc_channel_key_payload_free(payload);
2425 /* Heartbeat callback. This function is set as argument for the
2426 silc_socket_set_heartbeat function. The library will call this function
2427 at the set time interval. */
2429 void silc_server_perform_heartbeat(SilcSocketConnection sock,
2432 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
2434 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname,
2437 /* Send the heartbeat */
2438 silc_server_send_heartbeat(hb->server, sock);
2441 /* Returns assembled of all servers in the given ID list. The packet's
2442 form is dictated by the New ID payload. */
2444 static void silc_server_announce_get_servers(SilcServer server,
2446 SilcBuffer *servers)
2448 SilcIDCacheList list;
2449 SilcIDCacheEntry id_cache;
2450 SilcServerEntry entry;
2453 /* Go through all clients in the list */
2454 if (silc_idcache_find_by_id(id_list->clients, SILC_ID_CACHE_ANY,
2455 SILC_ID_SERVER, &list)) {
2456 if (silc_idcache_list_first(list, &id_cache)) {
2458 entry = (SilcServerEntry)id_cache->context;
2460 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
2462 *servers = silc_buffer_realloc(*servers,
2464 (*servers)->truelen + idp->len :
2466 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
2467 silc_buffer_put(*servers, idp->data, idp->len);
2468 silc_buffer_pull(*servers, idp->len);
2469 silc_buffer_free(idp);
2471 if (!silc_idcache_list_next(list, &id_cache))
2476 silc_idcache_list_free(list);
2480 /* This function is used by router to announce existing servers to our
2481 primary router when we've connected to it. */
2483 void silc_server_announce_servers(SilcServer server)
2485 SilcBuffer servers = NULL;
2487 SILC_LOG_DEBUG(("Announcing servers"));
2489 /* Get servers in local list */
2490 silc_server_announce_get_servers(server, server->local_list, &servers);
2492 /* Get servers in global list */
2493 silc_server_announce_get_servers(server, server->global_list, &servers);
2496 silc_buffer_push(servers, servers->data - servers->head);
2497 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
2499 /* Send the packet */
2500 silc_server_packet_send(server, server->router->connection,
2501 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
2502 servers->data, servers->len, TRUE);
2504 silc_buffer_free(servers);
2508 /* Returns assembled packet of all clients in the given ID list. The
2509 packet's form is dictated by the New ID Payload. */
2511 static void silc_server_announce_get_clients(SilcServer server,
2513 SilcBuffer *clients)
2515 SilcIDCacheList list;
2516 SilcIDCacheEntry id_cache;
2517 SilcClientEntry client;
2520 /* Go through all clients in the list */
2521 if (silc_idcache_find_by_id(id_list->clients, SILC_ID_CACHE_ANY,
2522 SILC_ID_CLIENT, &list)) {
2523 if (silc_idcache_list_first(list, &id_cache)) {
2525 client = (SilcClientEntry)id_cache->context;
2527 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2529 *clients = silc_buffer_realloc(*clients,
2531 (*clients)->truelen + idp->len :
2533 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
2534 silc_buffer_put(*clients, idp->data, idp->len);
2535 silc_buffer_pull(*clients, idp->len);
2536 silc_buffer_free(idp);
2538 if (!silc_idcache_list_next(list, &id_cache))
2543 silc_idcache_list_free(list);
2547 /* This function is used to announce our existing clients to our router
2548 when we've connected to it. */
2550 void silc_server_announce_clients(SilcServer server)
2552 SilcBuffer clients = NULL;
2554 SILC_LOG_DEBUG(("Announcing clients"));
2556 /* Get clients in local list */
2557 silc_server_announce_get_clients(server, server->local_list,
2560 /* As router we announce our global list as well */
2561 if (server->server_type == SILC_ROUTER)
2562 silc_server_announce_get_clients(server, server->global_list,
2566 silc_buffer_push(clients, clients->data - clients->head);
2567 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
2569 /* Send the packet */
2570 silc_server_packet_send(server, server->router->connection,
2571 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
2572 clients->data, clients->len, TRUE);
2574 silc_buffer_free(clients);
2579 silc_server_announce_encode_join(unsigned int argc, ...)
2584 return silc_notify_payload_encode(SILC_NOTIFY_TYPE_JOIN, argc, ap);
2587 /* Returns assembled packets for all channels and users on those channels
2588 from the given ID List. The packets are in the form dictated by the
2589 New Channel and New Channel User payloads. */
2591 static void silc_server_announce_get_channels(SilcServer server,
2593 SilcBuffer *channels,
2594 SilcBuffer *channel_users)
2596 SilcIDCacheList list;
2597 SilcIDCacheEntry id_cache;
2598 SilcChannelEntry channel;
2599 SilcChannelClientEntry chl;
2602 unsigned short name_len;
2605 /* Go through all channels in the list */
2606 if (silc_idcache_find_by_id(id_list->channels, SILC_ID_CACHE_ANY,
2607 SILC_ID_CHANNEL, &list)) {
2608 if (silc_idcache_list_first(list, &id_cache)) {
2610 channel = (SilcChannelEntry)id_cache->context;
2612 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
2613 name_len = strlen(channel->channel_name);
2615 len = 4 + name_len + SILC_ID_CHANNEL_LEN;
2617 silc_buffer_realloc(*channels,
2618 (*channels ? (*channels)->truelen + len : len));
2619 silc_buffer_pull_tail(*channels,
2620 ((*channels)->end - (*channels)->data));
2621 silc_buffer_format(*channels,
2622 SILC_STR_UI_SHORT(name_len),
2623 SILC_STR_UI_XNSTRING(channel->channel_name,
2625 SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
2626 SILC_STR_UI_XNSTRING(cid, SILC_ID_CHANNEL_LEN),
2628 silc_buffer_pull(*channels, len);
2630 /* Now find all users on the channel */
2631 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
2632 silc_list_start(channel->user_list);
2633 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2637 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
2639 tmp = silc_server_announce_encode_join(2, clidp->data, clidp->len,
2640 chidp->data, chidp->len);
2643 silc_buffer_realloc(*channel_users,
2645 (*channel_users)->truelen + len : len));
2646 silc_buffer_pull_tail(*channel_users,
2647 ((*channel_users)->end -
2648 (*channel_users)->data));
2650 silc_buffer_put(*channel_users, tmp->data, tmp->len);
2651 silc_buffer_pull(*channel_users, len);
2652 silc_buffer_free(clidp);
2653 silc_buffer_free(tmp);
2655 silc_buffer_free(chidp);
2659 if (!silc_idcache_list_next(list, &id_cache))
2664 silc_idcache_list_free(list);
2668 /* This function is used to announce our existing channels to our router
2669 when we've connected to it. This also announces the users on the
2670 channels to the router. */
2672 void silc_server_announce_channels(SilcServer server)
2674 SilcBuffer channels = NULL, channel_users = NULL;
2676 SILC_LOG_DEBUG(("Announcing channels and channel users"));
2678 /* Get channels and channel users in local list */
2679 silc_server_announce_get_channels(server, server->local_list,
2680 &channels, &channel_users);
2682 /* Get channels and channel users in global list */
2683 silc_server_announce_get_channels(server, server->global_list,
2684 &channels, &channel_users);
2687 silc_buffer_push(channels, channels->data - channels->head);
2688 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
2690 /* Send the packet */
2691 silc_server_packet_send(server, server->router->connection,
2692 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
2693 channels->data, channels->len,
2696 silc_buffer_free(channels);
2699 if (channel_users) {
2700 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
2701 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
2702 channel_users->len);
2704 /* Send the packet */
2705 silc_server_packet_send(server, server->router->connection,
2706 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
2707 channel_users->data, channel_users->len,
2710 silc_buffer_free(channel_users);