5 Author: Pekka Riikonen <priikone@poseidon.pspt.fi>
7 Copyright (C) 1997 - 2001 Pekka Riikonen
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
21 * This is the actual SILC server than handles everything relating to
22 * servicing the SILC connections. This is also a SILC router as a router
23 * is also normal server.
27 #include "serverincludes.h"
28 #include "server_internal.h"
30 /* Static prototypes */
31 SILC_TASK_CALLBACK(silc_server_connect_router);
32 SILC_TASK_CALLBACK(silc_server_connect_to_router);
33 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
35 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
38 SILC_TASK_CALLBACK(silc_server_packet_process);
39 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
40 SILC_TASK_CALLBACK(silc_server_timeout_remote);
41 SILC_TASK_CALLBACK(silc_server_failure_callback);
42 SILC_TASK_CALLBACK(silc_server_rekey_callback);
44 /* Allocates a new SILC server object. This has to be done before the server
45 can be used. After allocation one must call silc_server_init to initialize
46 the server. The new allocated server object is returned to the new_server
49 int silc_server_alloc(SilcServer *new_server)
53 SILC_LOG_DEBUG(("Allocating new server object"));
55 server = silc_calloc(1, sizeof(*server));
56 server->server_type = SILC_SERVER;
57 server->standalone = TRUE;
58 server->local_list = silc_calloc(1, sizeof(*server->local_list));
59 server->global_list = silc_calloc(1, sizeof(*server->global_list));
60 server->pending_commands = silc_dlist_init();
62 server->sim = silc_dlist_init();
70 /* Free's the SILC server object. This is called at the very end before
73 void silc_server_free(SilcServer server)
80 if (server->local_list)
81 silc_free(server->local_list);
82 if (server->global_list)
83 silc_free(server->global_list);
85 silc_rng_free(server->rng);
88 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
89 silc_dlist_del(server->sim, sim);
92 silc_dlist_uninit(server->sim);
96 silc_free(server->params);
98 if (server->pending_commands)
99 silc_dlist_uninit(server->pending_commands);
105 /* Initializes the entire SILC server. This is called always before running
106 the server. This is called only once at the initialization of the program.
107 This binds the server to its listenning port. After this function returns
108 one should call silc_server_run to start the server. This returns TRUE
109 when everything is ok to run the server. Configuration file must be
110 read and parsed before calling this. */
112 int silc_server_init(SilcServer server)
114 int *sock = NULL, sock_count = 0, i;
116 SilcServerEntry id_entry;
117 SilcIDListPurge purge;
119 SILC_LOG_DEBUG(("Initializing server"));
121 assert(server->config);
123 /* Set public and private keys */
124 if (!server->config->server_keys ||
125 !server->config->server_keys->public_key ||
126 !server->config->server_keys->private_key) {
127 SILC_LOG_ERROR(("Server public key and/or private key does not exist"));
130 server->public_key = server->config->server_keys->public_key;
131 server->private_key = server->config->server_keys->private_key;
133 /* XXX After server is made as Silc Server Library this can be given
134 as argument, for now this is hard coded */
135 server->params = silc_calloc(1, sizeof(*server->params));
136 server->params->retry_count = SILC_SERVER_RETRY_COUNT;
137 server->params->retry_interval_min = SILC_SERVER_RETRY_INTERVAL_MIN;
138 server->params->retry_interval_max = SILC_SERVER_RETRY_INTERVAL_MAX;
139 server->params->retry_keep_trying = FALSE;
140 server->params->protocol_timeout = 60;
141 server->params->require_reverse_mapping = FALSE;
143 /* Set log files where log message should be saved. */
144 server->config->server = server;
145 silc_server_config_setlogfiles(server->config);
147 /* Register all configured ciphers, PKCS and hash functions. */
148 silc_server_config_register_ciphers(server->config);
149 silc_server_config_register_pkcs(server->config);
150 silc_server_config_register_hashfuncs(server->config);
151 silc_server_config_register_hmacs(server->config);
153 /* Initialize random number generator for the server. */
154 server->rng = silc_rng_alloc();
155 silc_rng_init(server->rng);
156 silc_rng_global_init(server->rng);
158 /* Initialize hash functions for server to use */
159 silc_hash_alloc("md5", &server->md5hash);
160 silc_hash_alloc("sha1", &server->sha1hash);
162 /* Initialize none cipher */
163 silc_cipher_alloc("none", &server->none_cipher);
165 /* Create a listening server. Note that our server can listen on
166 multiple ports. All listeners are created here and now. */
167 /* XXX Still check this whether to use server_info or listen_port. */
169 while(server->config->listen_port) {
172 tmp = silc_net_create_server(server->config->listen_port->port,
173 server->config->listen_port->host);
177 sock = silc_realloc(sock, (sizeof(int *) * (sock_count + 1)));
178 sock[sock_count] = tmp;
179 server->config->listen_port = server->config->listen_port->next;
183 /* Initialize ID caches */
184 server->local_list->clients =
185 silc_idcache_alloc(0, silc_idlist_client_destructor);
186 server->local_list->servers = silc_idcache_alloc(0, NULL);
187 server->local_list->channels = silc_idcache_alloc(0, NULL);
189 /* These are allocated for normal server as well as these hold some
190 global information that the server has fetched from its router. For
191 router these are used as they are supposed to be used on router. */
192 server->global_list->clients =
193 silc_idcache_alloc(0, silc_idlist_client_destructor);
194 server->global_list->servers = silc_idcache_alloc(0, NULL);
195 server->global_list->channels = silc_idcache_alloc(0, NULL);
197 /* Allocate the entire socket list that is used in server. Eventually
198 all connections will have entry in this table (it is a table of
199 pointers to the actual object that is allocated individually
201 server->sockets = silc_calloc(SILC_SERVER_MAX_CONNECTIONS,
202 sizeof(*server->sockets));
204 for (i = 0; i < sock_count; i++) {
205 SilcSocketConnection newsocket = NULL;
207 /* Set socket to non-blocking mode */
208 silc_net_set_socket_nonblock(sock[i]);
209 server->sock = sock[i];
211 /* Create a Server ID for the server. */
212 silc_id_create_server_id(sock[i], server->rng, &id);
218 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
219 server->id_string_len = silc_id_get_len(SILC_ID_SERVER);
220 server->id_type = SILC_ID_SERVER;
221 server->server_name = server->config->server_info->server_name;
223 /* Add ourselves to the server list. We don't have a router yet
224 beacuse we haven't established a route yet. It will be done later.
225 For now, NULL is sent as router. This allocates new entry to
228 silc_idlist_add_server(server->local_list,
229 server->config->server_info->server_name,
230 server->server_type, server->id, NULL, NULL);
232 SILC_LOG_ERROR(("Could not add ourselves to cache"));
236 /* Add ourselves also to the socket table. The entry allocated above
237 is sent as argument for fast referencing in the future. */
238 silc_socket_alloc(sock[i], SILC_SOCKET_TYPE_SERVER, id_entry,
241 server->sockets[sock[i]] = newsocket;
243 /* Put the allocated socket pointer also to the entry allocated above
244 for fast back-referencing to the socket list. */
245 id_entry->connection = (void *)server->sockets[sock[i]];
246 server->id_entry = id_entry;
249 /* Register the task queues. In SILC we have by default three task queues.
250 One task queue for non-timeout tasks which perform different kind of
251 I/O on file descriptors, timeout task queue for timeout tasks, and,
252 generic non-timeout task queue whose tasks apply to all connections. */
253 silc_task_queue_alloc(&server->io_queue, TRUE);
254 if (!server->io_queue) {
257 silc_task_queue_alloc(&server->timeout_queue, TRUE);
258 if (!server->timeout_queue) {
261 silc_task_queue_alloc(&server->generic_queue, TRUE);
262 if (!server->generic_queue) {
266 /* Register protocols */
267 silc_server_protocols_register();
269 /* Initialize the scheduler */
270 silc_schedule_init(&server->io_queue, &server->timeout_queue,
271 &server->generic_queue,
272 SILC_SERVER_MAX_CONNECTIONS);
274 /* Add the first task to the queue. This is task that is executed by
275 timeout. It expires as soon as the caller calls silc_server_run. This
276 task performs authentication protocol and key exchange with our
278 silc_task_register(server->timeout_queue, sock[0],
279 silc_server_connect_to_router,
280 (void *)server, 0, 1,
282 SILC_TASK_PRI_NORMAL);
284 /* Add listener task to the queue. This task receives new connections to the
285 server. This task remains on the queue until the end of the program. */
286 silc_task_register(server->io_queue, sock[0],
287 silc_server_accept_new_connection,
288 (void *)server, 0, 0,
290 SILC_TASK_PRI_NORMAL);
291 server->listenning = TRUE;
293 /* If server connections has been configured then we must be router as
294 normal server cannot have server connections, only router connections. */
295 if (server->config->servers)
296 server->server_type = SILC_ROUTER;
298 /* Register the ID Cache purge task. This periodically purges the ID cache
299 and removes the expired cache entries. */
301 /* Clients local list */
302 purge = silc_calloc(1, sizeof(*purge));
303 purge->cache = server->local_list->clients;
304 purge->timeout_queue = server->timeout_queue;
305 silc_task_register(purge->timeout_queue, 0,
307 (void *)purge, 600, 0,
308 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
310 /* Clients global list */
311 purge = silc_calloc(1, sizeof(*purge));
312 purge->cache = server->global_list->clients;
313 purge->timeout_queue = server->timeout_queue;
314 silc_task_register(purge->timeout_queue, 0,
316 (void *)purge, 300, 0,
317 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
319 SILC_LOG_DEBUG(("Server initialized"));
321 /* We are done here, return succesfully */
324 silc_task_queue_free(server->timeout_queue);
326 silc_task_queue_free(server->io_queue);
328 for (i = 0; i < sock_count; i++)
329 silc_net_close_server(sock[i]);
334 /* Fork server to background and set gid+uid to non-root.
335 Silcd will not run as root, so trying to set either user or group to
336 root will cause silcd to exit. */
338 void silc_server_daemonise(SilcServer server)
340 /* Are we executing silcd as root or a regular user? */
347 if (!server->config->identity || !server->config->identity->user ||
348 !server->config->identity->group) {
349 fprintf(stderr, "Error:"
350 "\tSILC server must not be run as root. For the security of your\n"
351 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
352 "\tuser account. Modify the [Identity] configuration section to run\n"
353 "\tthe server as non-root user.\n");
357 /* Get the values given for user and group in configuration file */
358 user=server->config->identity->user;
359 group=server->config->identity->group;
361 /* Check whether the user/group information is text */
362 if (atoi(user)!=0 || atoi(group)!=0) {
363 SILC_LOG_DEBUG(("Invalid user and/or group information"));
364 SILC_LOG_DEBUG(("User and/or group given as number"));
365 fprintf(stderr, "Invalid user and/or group information\n");
366 fprintf(stderr, "Please assign them as names, not numbers\n");
370 /* Catch the nasty incident of string "0" returning 0 from atoi */
371 if (strcmp("0", user)==0 || strcmp("0", group)==0) {
372 SILC_LOG_DEBUG(("User and/or group configured to 0. Unacceptable"));
373 fprintf(stderr, "User and/or group configured to 0. Exiting\n");
381 fprintf(stderr, "No such user %s found\n", user);
386 fprintf(stderr, "No such group %s found\n", group);
390 /* Check whether user and/or group is set to root. If yes, exit
391 immediately. Otherwise, setgid and setuid server to user.group */
392 if (gr->gr_gid==0 || pw->pw_uid==0) {
393 fprintf(stderr, "Error:"
394 "\tSILC server must not be run as root. For the security of your\n"
395 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
396 "\tuser account. Modify the [Identity] configuration section to run\n"
397 "\tthe server as non-root user.\n");
400 /* Fork server to background, making it a daemon */
402 SILC_LOG_DEBUG(("Server started as root. Dropping privileges."));
403 SILC_LOG_DEBUG(("Forking SILC server to background"));
408 SILC_LOG_DEBUG(("Changing to group %s", group));
409 if(setgid(gr->gr_gid)==0) {
410 SILC_LOG_DEBUG(("Setgid to %s", group));
412 SILC_LOG_DEBUG(("Setgid to %s failed", group));
413 fprintf(stderr, "Tried to setgid %s but no such group. Exiting\n",
417 SILC_LOG_DEBUG(("Changing to user nobody"));
418 if(setuid(pw->pw_uid)==0) {
419 SILC_LOG_DEBUG(("Setuid to %s", user));
421 SILC_LOG_DEBUG(("Setuid to %s failed", user));
422 fprintf(stderr, "Tried to setuid %s but no such user. Exiting\n",
428 /* Fork server to background, making it a daemon */
430 SILC_LOG_DEBUG(("Server started as user"));
431 SILC_LOG_DEBUG(("Forking SILC server to background"));
438 /* Stops the SILC server. This function is used to shutdown the server.
439 This is usually called after the scheduler has returned. After stopping
440 the server one should call silc_server_free. */
442 void silc_server_stop(SilcServer server)
444 SILC_LOG_DEBUG(("Stopping server"));
446 /* Stop the scheduler, although it might be already stopped. This
447 doesn't hurt anyone. This removes all the tasks and task queues,
449 silc_schedule_stop();
450 silc_schedule_uninit();
452 silc_server_protocols_unregister();
454 SILC_LOG_DEBUG(("Server stopped"));
457 /* The heart of the server. This runs the scheduler thus runs the server.
458 When this returns the server has been stopped and the program will
461 void silc_server_run(SilcServer server)
463 SILC_LOG_DEBUG(("Running server"));
465 /* Start the scheduler, the heart of the SILC server. When this returns
466 the program will be terminated. */
470 /* Timeout callback that will be called to retry connecting to remote
471 router. This is used by both normal and router server. This will wait
472 before retrying the connecting. The timeout is generated by exponential
473 backoff algorithm. */
475 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
477 SilcServerConnection sconn = (SilcServerConnection)context;
478 SilcServer server = sconn->server;
480 SILC_LOG_INFO(("Retrying connecting to a router"));
482 /* Calculate next timeout */
483 if (sconn->retry_count >= 1) {
484 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
485 if (sconn->retry_timeout > SILC_SERVER_RETRY_INTERVAL_MAX)
486 sconn->retry_timeout = SILC_SERVER_RETRY_INTERVAL_MAX;
488 sconn->retry_timeout = server->params->retry_interval_min;
490 sconn->retry_count++;
491 sconn->retry_timeout = sconn->retry_timeout +
492 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
494 /* If we've reached max retry count, give up. */
495 if (sconn->retry_count > server->params->retry_count &&
496 server->params->retry_keep_trying == FALSE) {
497 SILC_LOG_ERROR(("Could not connect to router, giving up"));
501 /* Wait one before retrying */
502 silc_task_register(server->timeout_queue, fd, silc_server_connect_router,
503 context, sconn->retry_timeout,
504 server->params->retry_interval_min_usec,
505 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
508 /* Generic routine to use connect to a router. */
510 SILC_TASK_CALLBACK(silc_server_connect_router)
512 SilcServerConnection sconn = (SilcServerConnection)context;
513 SilcServer server = sconn->server;
514 SilcSocketConnection newsocket;
515 SilcProtocol protocol;
516 SilcServerKEInternalContext *proto_ctx;
519 SILC_LOG_INFO(("Connecting to the router %s on port %d",
520 sconn->remote_host, sconn->remote_port));
522 /* Connect to remote host */
523 sock = silc_net_create_connection(sconn->remote_port,
526 SILC_LOG_ERROR(("Could not connect to router"));
527 silc_task_register(server->timeout_queue, fd,
528 silc_server_connect_to_router_retry,
529 context, 0, 1, SILC_TASK_TIMEOUT,
530 SILC_TASK_PRI_NORMAL);
534 /* Set socket options */
535 silc_net_set_socket_nonblock(sock);
536 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
538 /* Create socket connection for the connection. Even though we
539 know that we are connecting to a router we will mark the socket
540 to be unknown connection until we have executed authentication
542 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
543 server->sockets[sock] = newsocket;
544 newsocket->hostname = strdup(sconn->remote_host);
545 newsocket->ip = strdup(sconn->remote_host);
546 newsocket->port = sconn->remote_port;
547 sconn->sock = newsocket;
549 /* Allocate internal protocol context. This is sent as context
551 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
552 proto_ctx->server = (void *)server;
553 proto_ctx->context = (void *)sconn;
554 proto_ctx->sock = newsocket;
555 proto_ctx->rng = server->rng;
556 proto_ctx->responder = FALSE;
558 /* Perform key exchange protocol. silc_server_connect_to_router_second
559 will be called after the protocol is finished. */
560 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
561 &protocol, proto_ctx,
562 silc_server_connect_to_router_second);
563 newsocket->protocol = protocol;
565 /* Register a timeout task that will be executed if the protocol
566 is not executed within set limit. */
567 proto_ctx->timeout_task =
568 silc_task_register(server->timeout_queue, sock,
569 silc_server_timeout_remote,
570 server, server->params->protocol_timeout,
571 server->params->protocol_timeout_usec,
575 /* Register the connection for network input and output. This sets
576 that scheduler will listen for incoming packets for this connection
577 and sets that outgoing packets may be sent to this connection as
578 well. However, this doesn't set the scheduler for outgoing traffic,
579 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
580 later when outgoing data is available. */
581 context = (void *)server;
582 SILC_REGISTER_CONNECTION_FOR_IO(sock);
584 /* Run the protocol */
585 protocol->execute(server->timeout_queue, 0, protocol, sock, 0, 0);
588 /* This function connects to our primary router or if we are a router this
589 establishes all our primary routes. This is called at the start of the
590 server to do authentication and key exchange with our router - called
593 SILC_TASK_CALLBACK(silc_server_connect_to_router)
595 SilcServer server = (SilcServer)context;
596 SilcServerConnection sconn;
598 SILC_LOG_DEBUG(("Connecting to router(s)"));
600 /* If we are normal SILC server we need to connect to our cell's
602 if (server->server_type == SILC_SERVER) {
603 SILC_LOG_DEBUG(("We are normal server"));
605 /* Create connection to the router, if configured. */
606 if (server->config->routers) {
608 /* Allocate connection object for hold connection specific stuff. */
609 sconn = silc_calloc(1, sizeof(*sconn));
610 sconn->server = server;
611 sconn->remote_host = strdup(server->config->routers->host);
612 sconn->remote_port = server->config->routers->port;
614 silc_task_register(server->timeout_queue, fd,
615 silc_server_connect_router,
616 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
617 SILC_TASK_PRI_NORMAL);
622 /* If we are a SILC router we need to establish all of our primary
624 if (server->server_type == SILC_ROUTER) {
625 SilcServerConfigSectionServerConnection *ptr;
627 SILC_LOG_DEBUG(("We are router"));
629 /* Create the connections to all our routes */
630 ptr = server->config->routers;
633 SILC_LOG_DEBUG(("Router connection [%s] %s:%d",
634 ptr->initiator ? "Initiator" : "Responder",
635 ptr->host, ptr->port));
637 if (ptr->initiator) {
638 /* Allocate connection object for hold connection specific stuff. */
639 sconn = silc_calloc(1, sizeof(*sconn));
640 sconn->server = server;
641 sconn->remote_host = strdup(ptr->host);
642 sconn->remote_port = ptr->port;
644 silc_task_register(server->timeout_queue, fd,
645 silc_server_connect_router,
646 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
647 SILC_TASK_PRI_NORMAL);
657 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
659 /* There wasn't a configured router, we will continue but we don't
660 have a connection to outside world. We will be standalone server. */
661 server->standalone = TRUE;
664 /* Second part of connecting to router(s). Key exchange protocol has been
665 executed and now we will execute authentication protocol. */
667 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
669 SilcProtocol protocol = (SilcProtocol)context;
670 SilcServerKEInternalContext *ctx =
671 (SilcServerKEInternalContext *)protocol->context;
672 SilcServer server = (SilcServer)ctx->server;
673 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
674 SilcSocketConnection sock = server->sockets[fd];
675 SilcServerConnAuthInternalContext *proto_ctx;
676 SilcServerConfigSectionServerConnection *conn = NULL;
678 SILC_LOG_DEBUG(("Start"));
680 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
681 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
682 /* Error occured during protocol */
683 silc_protocol_free(protocol);
684 sock->protocol = NULL;
685 silc_ske_free_key_material(ctx->keymat);
687 silc_packet_context_free(ctx->packet);
689 silc_ske_free(ctx->ske);
691 silc_free(ctx->dest_id);
693 silc_task_unregister_by_callback(server->timeout_queue,
694 silc_server_failure_callback);
695 silc_server_disconnect_remote(server, sock, "Server closed connection: "
696 "Key exchange failed");
700 /* We now have the key material as the result of the key exchange
701 protocol. Take the key material into use. Free the raw key material
702 as soon as we've set them into use. */
703 if (!silc_server_protocol_ke_set_keys(ctx->ske, ctx->sock, ctx->keymat,
704 ctx->ske->prop->cipher,
705 ctx->ske->prop->pkcs,
706 ctx->ske->prop->hash,
707 ctx->ske->prop->hmac,
708 ctx->ske->prop->group,
710 silc_protocol_free(protocol);
711 sock->protocol = NULL;
712 silc_ske_free_key_material(ctx->keymat);
714 silc_packet_context_free(ctx->packet);
716 silc_ske_free(ctx->ske);
718 silc_free(ctx->dest_id);
720 silc_task_unregister_by_callback(server->timeout_queue,
721 silc_server_failure_callback);
722 silc_server_disconnect_remote(server, sock, "Server closed connection: "
723 "Key exchange failed");
726 silc_ske_free_key_material(ctx->keymat);
728 /* Allocate internal context for the authentication protocol. This
729 is sent as context for the protocol. */
730 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
731 proto_ctx->server = (void *)server;
732 proto_ctx->context = (void *)sconn;
733 proto_ctx->sock = sock;
734 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
735 proto_ctx->dest_id_type = ctx->dest_id_type;
736 proto_ctx->dest_id = ctx->dest_id;
738 /* Resolve the authentication method used in this connection. Check if
739 we find a match from user configured connections */
740 conn = silc_server_config_find_router_conn(server->config,
744 /* Match found. Use the configured authentication method */
745 proto_ctx->auth_meth = conn->auth_meth;
746 if (conn->auth_data) {
747 proto_ctx->auth_data = strdup(conn->auth_data);
748 proto_ctx->auth_data_len = strlen(conn->auth_data);
751 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
752 sock->hostname, sock->ip, sock->port));
753 silc_protocol_free(protocol);
754 sock->protocol = NULL;
756 silc_packet_context_free(ctx->packet);
758 silc_ske_free(ctx->ske);
760 silc_free(ctx->dest_id);
762 silc_task_unregister_by_callback(server->timeout_queue,
763 silc_server_failure_callback);
764 silc_server_disconnect_remote(server, sock, "Server closed connection: "
765 "Key exchange failed");
769 /* Free old protocol as it is finished now */
770 silc_protocol_free(protocol);
772 silc_packet_context_free(ctx->packet);
774 sock->protocol = NULL;
776 /* Allocate the authentication protocol. This is allocated here
777 but we won't start it yet. We will be receiving party of this
778 protocol thus we will wait that connecting party will make
780 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
781 &sock->protocol, proto_ctx,
782 silc_server_connect_to_router_final);
784 /* Register timeout task. If the protocol is not executed inside
785 this timelimit the connection will be terminated. Currently
786 this is 15 seconds and is hard coded limit (XXX). */
787 proto_ctx->timeout_task =
788 silc_task_register(server->timeout_queue, sock->sock,
789 silc_server_timeout_remote,
790 (void *)server, 15, 0,
794 /* Run the protocol */
795 sock->protocol->execute(server->timeout_queue, 0,
796 sock->protocol, sock->sock, 0, 0);
799 /* Finalizes the connection to router. Registers a server task to the
800 queue so that we can accept new connections. */
802 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
804 SilcProtocol protocol = (SilcProtocol)context;
805 SilcServerConnAuthInternalContext *ctx =
806 (SilcServerConnAuthInternalContext *)protocol->context;
807 SilcServer server = (SilcServer)ctx->server;
808 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
809 SilcSocketConnection sock = ctx->sock;
810 SilcServerEntry id_entry;
812 SilcServerHBContext hb_context;
813 unsigned char *id_string;
814 SilcIDListData idata;
816 SILC_LOG_DEBUG(("Start"));
818 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
819 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
820 /* Error occured during protocol */
822 silc_free(ctx->dest_id);
823 silc_server_disconnect_remote(server, sock, "Server closed connection: "
824 "Authentication failed");
828 /* Add a task to the queue. This task receives new connections to the
829 server. This task remains on the queue until the end of the program. */
830 if (!server->listenning) {
831 silc_task_register(server->io_queue, server->sock,
832 silc_server_accept_new_connection,
833 (void *)server, 0, 0,
835 SILC_TASK_PRI_NORMAL);
836 server->listenning = TRUE;
839 /* Send NEW_SERVER packet to the router. We will become registered
840 to the SILC network after sending this packet. */
841 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
842 packet = silc_buffer_alloc(2 + 2 + SILC_ID_SERVER_LEN +
843 strlen(server->server_name));
844 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
845 silc_buffer_format(packet,
846 SILC_STR_UI_SHORT(SILC_ID_SERVER_LEN),
847 SILC_STR_UI_XNSTRING(id_string, SILC_ID_SERVER_LEN),
848 SILC_STR_UI_SHORT(strlen(server->server_name)),
849 SILC_STR_UI_XNSTRING(server->server_name,
850 strlen(server->server_name)),
853 /* Send the packet */
854 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
855 packet->data, packet->len, TRUE);
856 silc_buffer_free(packet);
857 silc_free(id_string);
859 SILC_LOG_DEBUG(("Connected to router %s", sock->hostname));
861 /* Add the connected router to local server list */
862 server->standalone = FALSE;
863 id_entry = silc_idlist_add_server(server->local_list, strdup(sock->hostname),
864 SILC_ROUTER, ctx->dest_id, NULL, sock);
867 silc_free(ctx->dest_id);
868 silc_server_disconnect_remote(server, sock, "Server closed connection: "
869 "Authentication failed");
873 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
874 silc_free(sock->user_data);
875 sock->user_data = (void *)id_entry;
876 sock->type = SILC_SOCKET_TYPE_ROUTER;
877 server->id_entry->router = id_entry;
878 server->router = id_entry;
879 idata = (SilcIDListData)sock->user_data;
880 idata->registered = TRUE;
882 /* Perform keepalive. The `hb_context' will be freed automatically
883 when finally calling the silc_socket_free function. XXX hardcoded
885 hb_context = silc_calloc(1, sizeof(*hb_context));
886 hb_context->server = server;
887 silc_socket_set_heartbeat(sock, 600, hb_context,
888 silc_server_perform_heartbeat,
889 server->timeout_queue);
891 /* Register re-key timeout */
892 idata->rekey->timeout = 3600; /* XXX hardcoded */
893 idata->rekey->context = (void *)server;
894 silc_task_register(server->timeout_queue, sock->sock,
895 silc_server_rekey_callback,
896 (void *)sock, idata->rekey->timeout, 0,
897 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
899 /* If we are router then announce our possible servers. */
900 if (server->server_type == SILC_ROUTER)
901 silc_server_announce_servers(server);
903 /* Announce our clients and channels to the router */
904 silc_server_announce_clients(server);
905 silc_server_announce_channels(server);
908 /* Free the temporary connection data context */
910 silc_free(sconn->remote_host);
914 /* Free the protocol object */
915 silc_protocol_free(protocol);
917 silc_packet_context_free(ctx->packet);
919 silc_ske_free(ctx->ske);
921 sock->protocol = NULL;
924 /* Accepts new connections to the server. Accepting new connections are
925 done in three parts to make it async. */
927 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
929 SilcServer server = (SilcServer)context;
930 SilcSocketConnection newsocket;
931 SilcServerKEInternalContext *proto_ctx;
934 SILC_LOG_DEBUG(("Accepting new connection"));
936 server->stat.conn_attempts++;
938 sock = silc_net_accept_connection(server->sock);
940 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
941 server->stat.conn_failures++;
945 /* Check max connections */
946 if (sock > SILC_SERVER_MAX_CONNECTIONS) {
947 SILC_LOG_ERROR(("Refusing connection, server is full"));
948 server->stat.conn_failures++;
952 /* Set socket options */
953 silc_net_set_socket_nonblock(sock);
954 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
956 /* We don't create a ID yet, since we don't know what type of connection
957 this is yet. But, we do add the connection to the socket table. */
958 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
959 server->sockets[sock] = newsocket;
961 /* XXX This MUST be done async as this will block the entire server
962 process. Either we have to do our own resolver stuff or in the future
963 we can use threads. */
964 /* Perform name and address lookups for the remote host. */
965 if (!silc_net_check_host_by_sock(sock, &newsocket->hostname,
967 if ((server->params->require_reverse_mapping && !newsocket->hostname) ||
969 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
970 newsocket->hostname ? newsocket->hostname :
971 newsocket->ip ? newsocket->ip : ""));
972 server->stat.conn_failures++;
975 if (!newsocket->hostname)
976 newsocket->hostname = strdup(newsocket->ip);
978 newsocket->port = silc_net_get_remote_port(sock);
980 SILC_LOG_INFO(("Incoming connection from %s (%s)", newsocket->hostname,
983 /* Allocate internal context for key exchange protocol. This is
984 sent as context for the protocol. */
985 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
986 proto_ctx->server = context;
987 proto_ctx->sock = newsocket;
988 proto_ctx->rng = server->rng;
989 proto_ctx->responder = TRUE;
991 /* Prepare the connection for key exchange protocol. We allocate the
992 protocol but will not start it yet. The connector will be the
993 initiator of the protocol thus we will wait for initiation from
994 there before we start the protocol. */
995 server->stat.auth_attempts++;
996 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
997 &newsocket->protocol, proto_ctx,
998 silc_server_accept_new_connection_second);
1000 /* Register a timeout task that will be executed if the connector
1001 will not start the key exchange protocol within 60 seconds. For
1002 now, this is a hard coded limit. After 60 secs the connection will
1003 be closed if the key exchange protocol has not been started. */
1004 proto_ctx->timeout_task =
1005 silc_task_register(server->timeout_queue, newsocket->sock,
1006 silc_server_timeout_remote,
1011 /* Register the connection for network input and output. This sets
1012 that scheduler will listen for incoming packets for this connection
1013 and sets that outgoing packets may be sent to this connection as well.
1014 However, this doesn't set the scheduler for outgoing traffic, it
1015 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1016 later when outgoing data is available. */
1017 SILC_REGISTER_CONNECTION_FOR_IO(sock);
1020 /* Second part of accepting new connection. Key exchange protocol has been
1021 performed and now it is time to do little connection authentication
1022 protocol to figure out whether this connection is client or server
1023 and whether it has right to access this server (especially server
1024 connections needs to be authenticated). */
1026 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1028 SilcProtocol protocol = (SilcProtocol)context;
1029 SilcServerKEInternalContext *ctx =
1030 (SilcServerKEInternalContext *)protocol->context;
1031 SilcServer server = (SilcServer)ctx->server;
1032 SilcSocketConnection sock = server->sockets[fd];
1033 SilcServerConnAuthInternalContext *proto_ctx;
1035 SILC_LOG_DEBUG(("Start"));
1037 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1038 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1039 /* Error occured during protocol */
1040 silc_protocol_free(protocol);
1041 sock->protocol = NULL;
1042 silc_ske_free_key_material(ctx->keymat);
1044 silc_packet_context_free(ctx->packet);
1046 silc_ske_free(ctx->ske);
1048 silc_free(ctx->dest_id);
1050 silc_task_unregister_by_callback(server->timeout_queue,
1051 silc_server_failure_callback);
1052 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1053 "Key exchange failed");
1054 server->stat.auth_failures++;
1058 /* We now have the key material as the result of the key exchange
1059 protocol. Take the key material into use. Free the raw key material
1060 as soon as we've set them into use. */
1061 if (!silc_server_protocol_ke_set_keys(ctx->ske, ctx->sock, ctx->keymat,
1062 ctx->ske->prop->cipher,
1063 ctx->ske->prop->pkcs,
1064 ctx->ske->prop->hash,
1065 ctx->ske->prop->hmac,
1066 ctx->ske->prop->group,
1068 silc_protocol_free(protocol);
1069 sock->protocol = NULL;
1070 silc_ske_free_key_material(ctx->keymat);
1072 silc_packet_context_free(ctx->packet);
1074 silc_ske_free(ctx->ske);
1076 silc_free(ctx->dest_id);
1078 silc_task_unregister_by_callback(server->timeout_queue,
1079 silc_server_failure_callback);
1080 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1081 "Key exchange failed");
1082 server->stat.auth_failures++;
1085 silc_ske_free_key_material(ctx->keymat);
1087 /* Allocate internal context for the authentication protocol. This
1088 is sent as context for the protocol. */
1089 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1090 proto_ctx->server = (void *)server;
1091 proto_ctx->sock = sock;
1092 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1093 proto_ctx->responder = TRUE;
1094 proto_ctx->dest_id_type = ctx->dest_id_type;
1095 proto_ctx->dest_id = ctx->dest_id;
1097 /* Free old protocol as it is finished now */
1098 silc_protocol_free(protocol);
1100 silc_packet_context_free(ctx->packet);
1102 sock->protocol = NULL;
1104 /* Allocate the authentication protocol. This is allocated here
1105 but we won't start it yet. We will be receiving party of this
1106 protocol thus we will wait that connecting party will make
1107 their first move. */
1108 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1109 &sock->protocol, proto_ctx,
1110 silc_server_accept_new_connection_final);
1112 /* Register timeout task. If the protocol is not executed inside
1113 this timelimit the connection will be terminated. Currently
1114 this is 60 seconds and is hard coded limit (XXX). */
1115 proto_ctx->timeout_task =
1116 silc_task_register(server->timeout_queue, sock->sock,
1117 silc_server_timeout_remote,
1118 (void *)server, 60, 0,
1123 /* Final part of accepting new connection. The connection has now
1124 been authenticated and keys has been exchanged. We also know whether
1125 this is client or server connection. */
1127 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1129 SilcProtocol protocol = (SilcProtocol)context;
1130 SilcServerConnAuthInternalContext *ctx =
1131 (SilcServerConnAuthInternalContext *)protocol->context;
1132 SilcServer server = (SilcServer)ctx->server;
1133 SilcSocketConnection sock = ctx->sock;
1134 SilcServerHBContext hb_context;
1135 void *id_entry = NULL;
1137 SILC_LOG_DEBUG(("Start"));
1139 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1140 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1141 /* Error occured during protocol */
1142 silc_protocol_free(protocol);
1143 sock->protocol = NULL;
1145 silc_packet_context_free(ctx->packet);
1147 silc_ske_free(ctx->ske);
1149 silc_free(ctx->dest_id);
1152 sock->protocol = NULL;
1153 silc_task_unregister_by_callback(server->timeout_queue,
1154 silc_server_failure_callback);
1155 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1156 "Authentication failed");
1157 server->stat.auth_failures++;
1161 sock->type = ctx->conn_type;
1162 switch(sock->type) {
1163 case SILC_SOCKET_TYPE_CLIENT:
1165 SilcClientEntry client;
1167 SILC_LOG_DEBUG(("Remote host is client"));
1168 SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
1171 /* Add the client to the client ID cache. The nickname and Client ID
1172 and other information is created after we have received NEW_CLIENT
1173 packet from client. */
1174 client = silc_idlist_add_client(server->local_list,
1175 NULL, 0, NULL, NULL, NULL, NULL, sock);
1177 SILC_LOG_ERROR(("Could not add new client to cache"));
1178 silc_free(sock->user_data);
1183 server->stat.my_clients++;
1184 server->stat.clients++;
1185 if (server->server_type == SILC_ROUTER)
1186 server->stat.cell_clients++;
1188 id_entry = (void *)client;
1191 case SILC_SOCKET_TYPE_SERVER:
1192 case SILC_SOCKET_TYPE_ROUTER:
1194 SilcServerEntry new_server;
1196 SILC_LOG_DEBUG(("Remote host is %s",
1197 sock->type == SILC_SOCKET_TYPE_SERVER ?
1198 "server" : "router"));
1199 SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
1200 sock->ip, sock->type == SILC_SOCKET_TYPE_SERVER ?
1201 "server" : "router"));
1203 /* Add the server into server cache. The server name and Server ID
1204 is updated after we have received NEW_SERVER packet from the
1205 server. We mark ourselves as router for this server if we really
1208 silc_idlist_add_server(server->local_list, NULL,
1209 sock->type == SILC_SOCKET_TYPE_SERVER ?
1210 SILC_SERVER : SILC_ROUTER, NULL,
1211 sock->type == SILC_SOCKET_TYPE_SERVER ?
1212 server->id_entry : NULL, sock);
1214 SILC_LOG_ERROR(("Could not add new server to cache"));
1215 silc_free(sock->user_data);
1220 if (sock->type == SILC_SOCKET_TYPE_SERVER)
1221 server->stat.my_servers++;
1223 server->stat.my_routers++;
1224 server->stat.servers++;
1226 id_entry = (void *)new_server;
1228 /* There is connection to other server now, if it is router then
1229 we will have connection to outside world. If we are router but
1230 normal server connected to us then we will remain standalone,
1231 if we are standlone. */
1232 if (server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER) {
1233 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1234 server->standalone = FALSE;
1235 if (!server->id_entry->router) {
1236 server->id_entry->router = id_entry;
1237 server->router = id_entry;
1246 /* Add the common data structure to the ID entry. */
1248 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1250 /* Add to sockets internal pointer for fast referencing */
1251 silc_free(sock->user_data);
1252 sock->user_data = id_entry;
1254 /* Connection has been fully established now. Everything is ok. */
1255 SILC_LOG_DEBUG(("New connection authenticated"));
1257 /* Perform keepalive. The `hb_context' will be freed automatically
1258 when finally calling the silc_socket_free function. XXX hardcoded
1260 hb_context = silc_calloc(1, sizeof(*hb_context));
1261 hb_context->server = server;
1262 silc_socket_set_heartbeat(sock, 600, hb_context,
1263 silc_server_perform_heartbeat,
1264 server->timeout_queue);
1266 silc_task_unregister_by_callback(server->timeout_queue,
1267 silc_server_failure_callback);
1268 silc_protocol_free(protocol);
1270 silc_packet_context_free(ctx->packet);
1272 silc_ske_free(ctx->ske);
1274 silc_free(ctx->dest_id);
1276 sock->protocol = NULL;
1279 /* This function is used to read packets from network and send packets to
1280 network. This is usually a generic task. */
1282 SILC_TASK_CALLBACK(silc_server_packet_process)
1284 SilcServer server = (SilcServer)context;
1285 SilcSocketConnection sock = server->sockets[fd];
1286 SilcIDListData idata;
1287 SilcCipher cipher = NULL;
1288 SilcHmac hmac = NULL;
1294 SILC_LOG_DEBUG(("Processing packet"));
1296 /* Packet sending */
1298 if (type == SILC_TASK_WRITE) {
1299 /* Do not send data to disconnected connection */
1300 if (SILC_IS_DISCONNECTED(sock))
1303 server->stat.packets_sent++;
1305 if (sock->outbuf->data - sock->outbuf->head)
1306 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1308 /* Send the packet */
1309 ret = silc_packet_send(sock, TRUE);
1311 /* If returned -2 could not write to connection now, will do
1319 /* The packet has been sent and now it is time to set the connection
1320 back to only for input. When there is again some outgoing data
1321 available for this connection it will be set for output as well.
1322 This call clears the output setting and sets it only for input. */
1323 SILC_SET_CONNECTION_FOR_INPUT(fd);
1324 SILC_UNSET_OUTBUF_PENDING(sock);
1326 silc_buffer_clear(sock->outbuf);
1330 /* Packet receiving */
1332 /* Read some data from connection */
1333 ret = silc_packet_receive(sock);
1339 SILC_LOG_DEBUG(("Read EOF"));
1341 /* If connection is disconnecting already we will finally
1342 close the connection */
1343 if (SILC_IS_DISCONNECTING(sock)) {
1344 if (sock->user_data)
1345 silc_server_free_sock_user_data(server, sock);
1346 silc_server_close_connection(server, sock);
1350 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1351 SILC_SET_DISCONNECTING(sock);
1353 /* If the closed connection was our primary router connection the
1354 start re-connecting phase. */
1355 if (!server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER &&
1356 sock == server->router->connection)
1357 silc_task_register(server->timeout_queue, 0,
1358 silc_server_connect_to_router,
1361 SILC_TASK_PRI_NORMAL);
1363 if (sock->user_data)
1364 silc_server_free_sock_user_data(server, sock);
1365 silc_server_close_connection(server, sock);
1369 /* If connection is disconnecting or disconnected we will ignore
1371 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1372 SILC_LOG_DEBUG(("Ignoring read data from disonnected connection"));
1376 server->stat.packets_received++;
1378 /* Get keys and stuff from ID entry */
1379 idata = (SilcIDListData)sock->user_data;
1381 idata->last_receive = time(NULL);
1382 cipher = idata->receive_key;
1383 hmac = idata->hmac_receive;
1386 /* Process the packet. This will call the parser that will then
1387 decrypt and parse the packet. */
1388 silc_packet_receive_process(sock, cipher, hmac, silc_server_packet_parse,
1392 /* Callback function that the silc_packet_decrypt will call to make the
1393 decision whether the packet is normal or special packet. We will
1394 return TRUE if it is normal and FALSE if it is special */
1396 static int silc_server_packet_decrypt_check(SilcPacketType packet_type,
1398 SilcPacketContext *packet,
1401 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1402 SilcServer server = (SilcServer)parse_ctx->context;
1404 /* Packet is normal packet, if:
1406 1) packet is private message packet and does not have private key set
1407 2) is other packet than channel message packet
1408 3) is channel message packet and remote is router and we are router
1410 all other packets are special packets
1413 if (packet_type == SILC_PACKET_PRIVATE_MESSAGE &&
1414 (buffer->data[2] & SILC_PACKET_FLAG_PRIVMSG_KEY))
1417 if (packet_type != SILC_PACKET_CHANNEL_MESSAGE ||
1418 (packet_type == SILC_PACKET_CHANNEL_MESSAGE &&
1419 parse_ctx->sock->type == SILC_SOCKET_TYPE_ROUTER &&
1420 server->server_type == SILC_ROUTER))
1426 /* Parses whole packet, received earlier. */
1428 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1430 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1431 SilcServer server = (SilcServer)parse_ctx->context;
1432 SilcSocketConnection sock = parse_ctx->sock;
1433 SilcPacketContext *packet = parse_ctx->packet;
1434 SilcIDListData idata = (SilcIDListData)sock->user_data;
1437 SILC_LOG_DEBUG(("Start"));
1439 /* Decrypt the received packet */
1440 ret = silc_packet_decrypt(idata ? idata->receive_key : NULL,
1441 idata ? idata->hmac_receive : NULL,
1442 packet->buffer, packet,
1443 silc_server_packet_decrypt_check, parse_ctx);
1448 /* Parse the packet. Packet type is returned. */
1449 ret = silc_packet_parse(packet);
1451 /* Parse the packet header in special way as this is "special"
1453 ret = silc_packet_parse_special(packet);
1456 if (ret == SILC_PACKET_NONE)
1459 /* Check that the the current client ID is same as in the client's packet. */
1460 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1461 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1462 if (client && client->id) {
1463 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1464 packet->src_id_type);
1465 if (SILC_ID_CLIENT_COMPARE(client->id, id)) {
1473 if (server->server_type == SILC_ROUTER) {
1474 /* Route the packet if it is not destined to us. Other ID types but
1475 server are handled separately after processing them. */
1476 if (packet->dst_id_type == SILC_ID_SERVER &&
1477 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1478 SILC_ID_SERVER_COMPARE(packet->dst_id, server->id_string)) {
1480 /* Route the packet to fastest route for the destination ID */
1481 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1482 packet->dst_id_type);
1485 silc_server_packet_route(server,
1486 silc_server_route_get(server, id,
1487 packet->dst_id_type),
1493 /* Broadcast packet if it is marked as broadcast packet and it is
1494 originated from router and we are router. */
1495 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1496 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
1497 silc_server_packet_broadcast(server, server->router->connection, packet);
1501 /* Parse the incoming packet type */
1502 silc_server_packet_parse_type(server, sock, packet);
1505 /* silc_buffer_clear(sock->inbuf); */
1506 silc_packet_context_free(packet);
1507 silc_free(parse_ctx);
1510 /* Parser callback called by silc_packet_receive_process. This merely
1511 registers timeout that will handle the actual parsing when appropriate. */
1513 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1515 SilcServer server = (SilcServer)parser_context->context;
1516 SilcSocketConnection sock = parser_context->sock;
1518 switch (sock->type) {
1519 case SILC_SOCKET_TYPE_UNKNOWN:
1520 /* Parse the packet with timeout */
1521 silc_task_register(server->timeout_queue, sock->sock,
1522 silc_server_packet_parse_real,
1523 (void *)parser_context, 0, 100000,
1525 SILC_TASK_PRI_NORMAL);
1527 case SILC_SOCKET_TYPE_CLIENT:
1528 /* Parse the packet with timeout (unless protocol is active) */
1530 /* If REKEY protocol is active we must proccess the packets synchronously
1531 since we must assure that incoming packets that are encrypted with
1532 the old key is processed before the new keys is set to use. */
1533 if (SILC_SERVER_IS_REKEY(sock))
1534 silc_server_packet_parse_real(server->timeout_queue, SILC_TASK_READ,
1535 (void *)parser_context, sock->sock);
1537 silc_task_register(server->timeout_queue, sock->sock,
1538 silc_server_packet_parse_real,
1539 (void *)parser_context, 0,
1540 (sock->protocol ? 1 : 100000),
1542 SILC_TASK_PRI_NORMAL);
1544 case SILC_SOCKET_TYPE_SERVER:
1545 case SILC_SOCKET_TYPE_ROUTER:
1546 /* Packets from servers are parsed as soon as possible */
1548 /* If REKEY protocol is active we must proccess the packets synchronously
1549 since we must assure that incoming packets that are encrypted with
1550 the old key is processed before the new keys is set to use. */
1551 if (SILC_SERVER_IS_REKEY(sock))
1552 silc_server_packet_parse_real(server->timeout_queue, SILC_TASK_READ,
1553 (void *)parser_context, sock->sock);
1555 silc_task_register(server->timeout_queue, sock->sock,
1556 silc_server_packet_parse_real,
1557 (void *)parser_context, 0, 1,
1559 SILC_TASK_PRI_NORMAL);
1566 /* Parses the packet type and calls what ever routines the packet type
1567 requires. This is done for all incoming packets. */
1569 void silc_server_packet_parse_type(SilcServer server,
1570 SilcSocketConnection sock,
1571 SilcPacketContext *packet)
1573 SilcPacketType type = packet->type;
1575 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1577 /* Parse the packet type */
1579 case SILC_PACKET_DISCONNECT:
1580 SILC_LOG_DEBUG(("Disconnect packet"));
1581 if (packet->flags & SILC_PACKET_FLAG_LIST)
1585 case SILC_PACKET_SUCCESS:
1587 * Success received for something. For now we can have only
1588 * one protocol for connection executing at once hence this
1589 * success message is for whatever protocol is executing currently.
1591 SILC_LOG_DEBUG(("Success packet"));
1592 if (packet->flags & SILC_PACKET_FLAG_LIST)
1594 if (sock->protocol) {
1595 sock->protocol->execute(server->timeout_queue, 0,
1596 sock->protocol, sock->sock, 0, 0);
1600 case SILC_PACKET_FAILURE:
1602 * Failure received for something. For now we can have only
1603 * one protocol for connection executing at once hence this
1604 * failure message is for whatever protocol is executing currently.
1606 SILC_LOG_DEBUG(("Failure packet"));
1607 if (packet->flags & SILC_PACKET_FLAG_LIST)
1609 if (sock->protocol) {
1610 SilcServerFailureContext f;
1611 f = silc_calloc(1, sizeof(*f));
1615 /* We will wait 5 seconds to process this failure packet */
1616 silc_task_register(server->timeout_queue, sock->sock,
1617 silc_server_failure_callback, (void *)f, 5, 0,
1618 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1622 case SILC_PACKET_REJECT:
1623 SILC_LOG_DEBUG(("Reject packet"));
1624 if (packet->flags & SILC_PACKET_FLAG_LIST)
1629 case SILC_PACKET_NOTIFY:
1631 * Received notify packet. Server can receive notify packets from
1632 * router. Server then relays the notify messages to clients if needed.
1634 SILC_LOG_DEBUG(("Notify packet"));
1635 if (packet->flags & SILC_PACKET_FLAG_LIST)
1636 silc_server_notify_list(server, sock, packet);
1638 silc_server_notify(server, sock, packet);
1644 case SILC_PACKET_CHANNEL_MESSAGE:
1646 * Received channel message. Channel messages are special packets
1647 * (although probably most common ones) thus they are handled
1650 SILC_LOG_DEBUG(("Channel Message packet"));
1651 if (packet->flags & SILC_PACKET_FLAG_LIST)
1653 silc_server_channel_message(server, sock, packet);
1656 case SILC_PACKET_CHANNEL_KEY:
1658 * Received key for channel. As channels are created by the router
1659 * the keys are as well. We will distribute the key to all of our
1660 * locally connected clients on the particular channel. Router
1661 * never receives this channel and thus is ignored.
1663 SILC_LOG_DEBUG(("Channel Key packet"));
1664 if (packet->flags & SILC_PACKET_FLAG_LIST)
1666 silc_server_channel_key(server, sock, packet);
1672 case SILC_PACKET_COMMAND:
1674 * Recived command. Processes the command request and allocates the
1675 * command context and calls the command.
1677 SILC_LOG_DEBUG(("Command packet"));
1678 if (packet->flags & SILC_PACKET_FLAG_LIST)
1680 silc_server_command_process(server, sock, packet);
1683 case SILC_PACKET_COMMAND_REPLY:
1685 * Received command reply packet. Received command reply to command. It
1686 * may be reply to command sent by us or reply to command sent by client
1687 * that we've routed further.
1689 SILC_LOG_DEBUG(("Command Reply packet"));
1690 if (packet->flags & SILC_PACKET_FLAG_LIST)
1692 silc_server_command_reply(server, sock, packet);
1696 * Private Message packets
1698 case SILC_PACKET_PRIVATE_MESSAGE:
1700 * Received private message packet. The packet is coming from either
1703 SILC_LOG_DEBUG(("Private Message packet"));
1704 if (packet->flags & SILC_PACKET_FLAG_LIST)
1706 silc_server_private_message(server, sock, packet);
1709 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1711 * Private message key packet.
1713 if (packet->flags & SILC_PACKET_FLAG_LIST)
1715 silc_server_private_message_key(server, sock, packet);
1719 * Key Exchange protocol packets
1721 case SILC_PACKET_KEY_EXCHANGE:
1722 SILC_LOG_DEBUG(("KE packet"));
1723 if (packet->flags & SILC_PACKET_FLAG_LIST)
1726 if (sock->protocol && sock->protocol->protocol &&
1727 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1729 SilcServerKEInternalContext *proto_ctx =
1730 (SilcServerKEInternalContext *)sock->protocol->context;
1732 proto_ctx->packet = silc_packet_context_dup(packet);
1734 /* Let the protocol handle the packet */
1735 sock->protocol->execute(server->timeout_queue, 0,
1736 sock->protocol, sock->sock, 0, 100000);
1738 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1739 "protocol active, packet dropped."));
1741 /* XXX Trigger KE protocol?? Rekey actually, maybe. */
1745 case SILC_PACKET_KEY_EXCHANGE_1:
1746 SILC_LOG_DEBUG(("KE 1 packet"));
1747 if (packet->flags & SILC_PACKET_FLAG_LIST)
1750 if (sock->protocol && sock->protocol->protocol &&
1751 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1752 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
1754 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
1755 SilcServerRekeyInternalContext *proto_ctx =
1756 (SilcServerRekeyInternalContext *)sock->protocol->context;
1758 if (proto_ctx->packet)
1759 silc_packet_context_free(proto_ctx->packet);
1761 proto_ctx->packet = silc_packet_context_dup(packet);
1763 /* Let the protocol handle the packet */
1764 sock->protocol->execute(server->timeout_queue, 0,
1765 sock->protocol, sock->sock, 0, 0);
1767 SilcServerKEInternalContext *proto_ctx =
1768 (SilcServerKEInternalContext *)sock->protocol->context;
1770 if (proto_ctx->packet)
1771 silc_packet_context_free(proto_ctx->packet);
1773 proto_ctx->packet = silc_packet_context_dup(packet);
1774 proto_ctx->dest_id_type = packet->src_id_type;
1775 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1776 packet->src_id_type);
1777 if (!proto_ctx->dest_id)
1780 /* Let the protocol handle the packet */
1781 sock->protocol->execute(server->timeout_queue, 0,
1782 sock->protocol, sock->sock,
1786 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1787 "protocol active, packet dropped."));
1791 case SILC_PACKET_KEY_EXCHANGE_2:
1792 SILC_LOG_DEBUG(("KE 2 packet"));
1793 if (packet->flags & SILC_PACKET_FLAG_LIST)
1796 if (sock->protocol && sock->protocol->protocol &&
1797 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1798 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
1800 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
1801 SilcServerRekeyInternalContext *proto_ctx =
1802 (SilcServerRekeyInternalContext *)sock->protocol->context;
1804 if (proto_ctx->packet)
1805 silc_packet_context_free(proto_ctx->packet);
1807 proto_ctx->packet = silc_packet_context_dup(packet);
1809 /* Let the protocol handle the packet */
1810 sock->protocol->execute(server->timeout_queue, 0,
1811 sock->protocol, sock->sock, 0, 0);
1813 SilcServerKEInternalContext *proto_ctx =
1814 (SilcServerKEInternalContext *)sock->protocol->context;
1816 if (proto_ctx->packet)
1817 silc_packet_context_free(proto_ctx->packet);
1819 proto_ctx->packet = silc_packet_context_dup(packet);
1820 proto_ctx->dest_id_type = packet->src_id_type;
1821 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1822 packet->src_id_type);
1823 if (!proto_ctx->dest_id)
1826 /* Let the protocol handle the packet */
1827 sock->protocol->execute(server->timeout_queue, 0,
1828 sock->protocol, sock->sock,
1832 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1833 "protocol active, packet dropped."));
1837 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1839 * Connection authentication request packet. When we receive this packet
1840 * we will send to the other end information about our mandatory
1841 * authentication method for the connection. This packet maybe received
1844 SILC_LOG_DEBUG(("Connection authentication request packet"));
1845 if (packet->flags & SILC_PACKET_FLAG_LIST)
1847 silc_server_connection_auth_request(server, sock, packet);
1851 * Connection Authentication protocol packets
1853 case SILC_PACKET_CONNECTION_AUTH:
1854 /* Start of the authentication protocol. We receive here the
1855 authentication data and will verify it. */
1856 SILC_LOG_DEBUG(("Connection auth packet"));
1857 if (packet->flags & SILC_PACKET_FLAG_LIST)
1860 if (sock->protocol && sock->protocol->protocol->type
1861 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1863 SilcServerConnAuthInternalContext *proto_ctx =
1864 (SilcServerConnAuthInternalContext *)sock->protocol->context;
1866 proto_ctx->packet = silc_packet_context_dup(packet);
1868 /* Let the protocol handle the packet */
1869 sock->protocol->execute(server->timeout_queue, 0,
1870 sock->protocol, sock->sock, 0, 0);
1872 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1873 "protocol active, packet dropped."));
1877 case SILC_PACKET_NEW_ID:
1879 * Received New ID packet. This includes some new ID that has been
1880 * created. It may be for client, server or channel. This is the way
1881 * to distribute information about new registered entities in the
1884 SILC_LOG_DEBUG(("New ID packet"));
1885 if (packet->flags & SILC_PACKET_FLAG_LIST)
1886 silc_server_new_id_list(server, sock, packet);
1888 silc_server_new_id(server, sock, packet);
1891 case SILC_PACKET_NEW_CLIENT:
1893 * Received new client packet. This includes client information that
1894 * we will use to create initial client ID. After creating new
1895 * ID we will send it to the client.
1897 SILC_LOG_DEBUG(("New Client packet"));
1898 if (packet->flags & SILC_PACKET_FLAG_LIST)
1900 silc_server_new_client(server, sock, packet);
1903 case SILC_PACKET_NEW_SERVER:
1905 * Received new server packet. This includes Server ID and some other
1906 * information that we may save. This is received after server has
1909 SILC_LOG_DEBUG(("New Server packet"));
1910 if (packet->flags & SILC_PACKET_FLAG_LIST)
1912 silc_server_new_server(server, sock, packet);
1915 case SILC_PACKET_NEW_CHANNEL:
1917 * Received new channel packet. Information about new channel in the
1918 * network are distributed using this packet.
1920 SILC_LOG_DEBUG(("New Channel packet"));
1921 if (packet->flags & SILC_PACKET_FLAG_LIST)
1922 silc_server_new_channel_list(server, sock, packet);
1924 silc_server_new_channel(server, sock, packet);
1927 case SILC_PACKET_HEARTBEAT:
1929 * Received heartbeat.
1931 SILC_LOG_DEBUG(("Heartbeat packet"));
1932 if (packet->flags & SILC_PACKET_FLAG_LIST)
1936 case SILC_PACKET_KEY_AGREEMENT:
1938 * Received heartbeat.
1940 SILC_LOG_DEBUG(("Key agreement packet"));
1941 if (packet->flags & SILC_PACKET_FLAG_LIST)
1943 silc_server_key_agreement(server, sock, packet);
1946 case SILC_PACKET_REKEY:
1948 * Received re-key packet. The sender wants to regenerate the session
1951 SILC_LOG_DEBUG(("Re-key packet"));
1952 if (packet->flags & SILC_PACKET_FLAG_LIST)
1954 silc_server_rekey(server, sock, packet);
1957 case SILC_PACKET_REKEY_DONE:
1959 * The re-key is done.
1961 SILC_LOG_DEBUG(("Re-key done packet"));
1962 if (packet->flags & SILC_PACKET_FLAG_LIST)
1965 if (sock->protocol && sock->protocol->protocol &&
1966 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
1968 SilcServerRekeyInternalContext *proto_ctx =
1969 (SilcServerRekeyInternalContext *)sock->protocol->context;
1971 if (proto_ctx->packet)
1972 silc_packet_context_free(proto_ctx->packet);
1974 proto_ctx->packet = silc_packet_context_dup(packet);
1976 /* Let the protocol handle the packet */
1977 sock->protocol->execute(server->timeout_queue, 0,
1978 sock->protocol, sock->sock, 0, 0);
1980 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
1981 "protocol active, packet dropped."));
1986 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
1992 /* Creates connection to a remote router. */
1994 void silc_server_create_connection(SilcServer server,
1995 char *remote_host, uint32 port)
1997 SilcServerConnection sconn;
1999 /* Allocate connection object for hold connection specific stuff. */
2000 sconn = silc_calloc(1, sizeof(*sconn));
2001 sconn->server = server;
2002 sconn->remote_host = strdup(remote_host);
2003 sconn->remote_port = port;
2005 silc_task_register(server->timeout_queue, 0,
2006 silc_server_connect_router,
2007 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2008 SILC_TASK_PRI_NORMAL);
2011 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2013 silc_socket_free((SilcSocketConnection)context);
2016 /* Closes connection to socket connection */
2018 void silc_server_close_connection(SilcServer server,
2019 SilcSocketConnection sock)
2021 SILC_LOG_INFO(("Closing connection %s:%d [%s] (%d)", sock->hostname,
2023 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2024 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2025 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2026 "Router"), sock->sock));
2028 /* We won't listen for this connection anymore */
2029 silc_schedule_unset_listen_fd(sock->sock);
2031 /* Unregister all tasks */
2032 silc_task_unregister_by_fd(server->io_queue, sock->sock);
2033 silc_task_unregister_by_fd(server->timeout_queue, sock->sock);
2035 /* Close the actual connection */
2036 silc_net_close_connection(sock->sock);
2037 server->sockets[sock->sock] = NULL;
2039 silc_task_register(server->timeout_queue, 0,
2040 silc_server_close_connection_final,
2041 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2042 SILC_TASK_PRI_NORMAL);
2045 /* Sends disconnect message to remote connection and disconnects the
2048 void silc_server_disconnect_remote(SilcServer server,
2049 SilcSocketConnection sock,
2050 const char *fmt, ...)
2053 unsigned char buf[4096];
2058 memset(buf, 0, sizeof(buf));
2060 vsprintf(buf, fmt, ap);
2063 SILC_LOG_DEBUG(("Disconnecting remote host"));
2065 SILC_LOG_INFO(("Disconnecting %s:%d [%s]", sock->hostname,
2067 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2068 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2069 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2072 /* Notify remote end that the conversation is over. The notify message
2073 is tried to be sent immediately. */
2074 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2075 buf, strlen(buf), TRUE);
2077 /* Mark the connection to be disconnected */
2078 SILC_SET_DISCONNECTED(sock);
2079 silc_server_close_connection(server, sock);
2084 SilcClientEntry client;
2085 } *FreeClientInternal;
2087 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2089 FreeClientInternal i = (FreeClientInternal)context;
2091 silc_idlist_del_data(i->client);
2092 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2096 /* Frees client data and notifies about client's signoff. */
2098 void silc_server_free_client_data(SilcServer server,
2099 SilcSocketConnection sock,
2100 SilcClientEntry client,
2104 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2106 /* If there is pending outgoing data for the client then purge it
2107 to the network before removing the client entry. */
2108 if (sock && SILC_IS_OUTBUF_PENDING(sock) &&
2109 (SILC_IS_DISCONNECTED(sock) == FALSE)) {
2110 server->stat.packets_sent++;
2112 if (sock->outbuf->data - sock->outbuf->head)
2113 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
2115 silc_packet_send(sock, TRUE);
2117 SILC_SET_CONNECTION_FOR_INPUT(sock->sock);
2118 SILC_UNSET_OUTBUF_PENDING(sock);
2119 silc_buffer_clear(sock->outbuf);
2122 /* Send SIGNOFF notify to routers. */
2123 if (notify && !server->standalone && server->router)
2124 silc_server_send_notify_signoff(server, server->router->connection,
2125 server->server_type == SILC_SERVER ?
2126 FALSE : TRUE, client->id,
2127 SILC_ID_CLIENT_LEN, signoff);
2129 /* Remove client from all channels */
2131 silc_server_remove_from_channels(server, NULL, client,
2132 TRUE, signoff, TRUE);
2134 silc_server_remove_from_channels(server, NULL, client,
2135 FALSE, NULL, FALSE);
2137 /* We will not delete the client entry right away. We will take it
2138 into history (for WHOWAS command) for 5 minutes */
2141 silc_task_register(server->timeout_queue, 0,
2142 silc_server_free_client_data_timeout,
2144 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2145 client->data.registered = FALSE;
2147 /* Free the client entry and everything in it */
2148 server->stat.my_clients--;
2149 server->stat.clients--;
2150 if (server->server_type == SILC_ROUTER)
2151 server->stat.cell_clients--;
2154 /* Frees user_data pointer from socket connection object. This also sends
2155 appropriate notify packets to the network to inform about leaving
2158 void silc_server_free_sock_user_data(SilcServer server,
2159 SilcSocketConnection sock)
2161 SILC_LOG_DEBUG(("Start"));
2163 switch(sock->type) {
2164 case SILC_SOCKET_TYPE_CLIENT:
2166 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2167 silc_server_free_client_data(server, sock, user_data, TRUE, NULL);
2170 case SILC_SOCKET_TYPE_SERVER:
2171 case SILC_SOCKET_TYPE_ROUTER:
2173 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2175 /* Free all client entries that this server owns as they will
2176 become invalid now as well. */
2177 silc_server_remove_clients_by_server(server, user_data, TRUE);
2179 /* If this was our primary router connection then we're lost to
2180 the outside world. */
2181 if (server->router == user_data) {
2182 server->id_entry->router = NULL;
2183 server->router = NULL;
2184 server->standalone = TRUE;
2187 /* Free the server entry */
2188 silc_idlist_del_data(user_data);
2189 silc_idlist_del_server(server->local_list, user_data);
2190 server->stat.my_servers--;
2191 server->stat.servers--;
2192 if (server->server_type == SILC_ROUTER)
2193 server->stat.cell_servers--;
2198 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2200 silc_idlist_del_data(user_data);
2201 silc_free(user_data);
2206 sock->user_data = NULL;
2209 /* This function is used to remove all client entries by the server `entry'.
2210 This is called when the connection is lost to the server. In this case
2211 we must invalidate all the client entries owned by the server `entry'.
2212 If the `server_signoff' is TRUE then the SERVER_SIGNOFF notify is
2213 distributed to our local clients. */
2215 int silc_server_remove_clients_by_server(SilcServer server,
2216 SilcServerEntry entry,
2219 SilcIDCacheList list = NULL;
2220 SilcIDCacheEntry id_cache = NULL;
2221 SilcClientEntry client = NULL;
2223 SilcClientEntry *clients = NULL;
2224 uint32 clients_c = 0;
2225 unsigned char **argv = NULL;
2226 uint32 *argv_lens = NULL, *argv_types = NULL, argc = 0;
2229 SILC_LOG_DEBUG(("Start"));
2231 if (server_signoff) {
2232 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
2233 argv = silc_realloc(argv, sizeof(*argv) * (argc + 1));
2234 argv_lens = silc_realloc(argv_lens, sizeof(*argv_lens) * (argc + 1));
2235 argv_types = silc_realloc(argv_types, sizeof(*argv_types) * (argc + 1));
2236 argv[argc] = idp->data;
2237 argv_lens[argc] = idp->len;
2238 argv_types[argc] = argc + 1;
2240 silc_buffer_free(idp);
2243 if (silc_idcache_find_by_id(server->local_list->clients,
2244 SILC_ID_CACHE_ANY, SILC_ID_CLIENT, &list)) {
2246 if (silc_idcache_list_first(list, &id_cache)) {
2248 client = (SilcClientEntry)id_cache->context;
2249 if (client->data.registered == FALSE) {
2250 if (!silc_idcache_list_next(list, &id_cache))
2256 if (client->router != entry) {
2257 if (server_signoff && client->connection) {
2258 clients = silc_realloc(clients,
2259 sizeof(*clients) * (clients_c + 1));
2260 clients[clients_c] = client;
2264 if (!silc_idcache_list_next(list, &id_cache))
2270 if (server_signoff) {
2271 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2272 argv = silc_realloc(argv, sizeof(*argv) * (argc + 1));
2273 argv_lens = silc_realloc(argv_lens, sizeof(*argv_lens) *
2275 argv_types = silc_realloc(argv_types, sizeof(*argv_types) *
2277 argv[argc] = silc_calloc(idp->len, sizeof(*argv[0]));
2278 memcpy(argv[argc], idp->data, idp->len);
2279 argv_lens[argc] = idp->len;
2280 argv_types[argc] = argc + 1;
2282 silc_buffer_free(idp);
2285 /* Remove the client entry */
2286 silc_server_remove_from_channels(server, NULL, client, FALSE,
2288 silc_idlist_del_client(server->local_list, client);
2290 if (!silc_idcache_list_next(list, &id_cache))
2294 silc_idcache_list_free(list);
2297 if (silc_idcache_find_by_id(server->global_list->clients,
2298 SILC_ID_CACHE_ANY, SILC_ID_CLIENT, &list)) {
2300 if (silc_idcache_list_first(list, &id_cache)) {
2302 client = (SilcClientEntry)id_cache->context;
2303 if (client->data.registered == FALSE) {
2304 if (!silc_idcache_list_next(list, &id_cache))
2310 if (client->router != entry) {
2311 if (server_signoff && client->connection) {
2312 clients = silc_realloc(clients,
2313 sizeof(*clients) * (clients_c + 1));
2314 clients[clients_c] = client;
2318 if (!silc_idcache_list_next(list, &id_cache))
2324 if (server_signoff) {
2325 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2326 argv = silc_realloc(argv, sizeof(*argv) * (argc + 1));
2327 argv_lens = silc_realloc(argv_lens, sizeof(*argv_lens) *
2329 argv_types = silc_realloc(argv_types, sizeof(*argv_types) *
2331 argv[argc] = silc_calloc(idp->len, sizeof(*argv[0]));
2332 memcpy(argv[argc], idp->data, idp->len);
2333 argv_lens[argc] = idp->len;
2334 argv_types[argc] = argc + 1;
2336 silc_buffer_free(idp);
2339 /* Remove the client entry */
2340 silc_server_remove_from_channels(server, NULL, client, FALSE,
2342 silc_idlist_del_client(server->global_list, client);
2344 if (!silc_idcache_list_next(list, &id_cache))
2348 silc_idcache_list_free(list);
2351 /* Send the SERVER_SIGNOFF notify */
2352 if (server_signoff) {
2355 /* Send SERVER_SIGNOFF notify to our primary router */
2356 if (!server->standalone && server->router) {
2357 args = silc_argument_payload_encode(1, argv, argv_lens,
2359 silc_server_send_notify_args(server,
2360 server->router->connection,
2361 server->server_type ==
2362 SILC_SERVER ? FALSE : TRUE,
2363 SILC_NOTIFY_TYPE_SERVER_SIGNOFF,
2365 silc_buffer_free(args);
2368 args = silc_argument_payload_encode(argc, argv, argv_lens,
2370 /* Send to local clients */
2371 for (i = 0; i < clients_c; i++) {
2372 silc_server_send_notify_args(server, clients[i]->connection,
2373 FALSE, SILC_NOTIFY_TYPE_SERVER_SIGNOFF,
2378 silc_buffer_free(args);
2380 silc_free(argv_lens);
2381 silc_free(argv_types);
2387 /* Checks whether given channel has global users. If it does this returns
2388 TRUE and FALSE if there is only locally connected clients on the channel. */
2390 int silc_server_channel_has_global(SilcChannelEntry channel)
2392 SilcChannelClientEntry chl;
2394 silc_list_start(channel->user_list);
2395 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2396 if (chl->client->router)
2403 /* Checks whether given channel has locally connected users. If it does this
2404 returns TRUE and FALSE if there is not one locally connected client. */
2406 int silc_server_channel_has_local(SilcChannelEntry channel)
2408 SilcChannelClientEntry chl;
2410 silc_list_start(channel->user_list);
2411 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2412 if (!chl->client->router)
2419 /* Removes client from all channels it has joined. This is used when client
2420 connection is disconnected. If the client on a channel is last, the
2421 channel is removed as well. This sends the SIGNOFF notify types. */
2423 void silc_server_remove_from_channels(SilcServer server,
2424 SilcSocketConnection sock,
2425 SilcClientEntry client,
2427 char *signoff_message,
2430 SilcChannelEntry channel;
2431 SilcChannelClientEntry chl;
2434 SILC_LOG_DEBUG(("Start"));
2436 if (!client || !client->id)
2439 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2441 /* Remove the client from all channels. The client is removed from
2442 the channels' user list. */
2443 silc_list_start(client->channels);
2444 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2445 channel = chl->channel;
2447 /* Remove channel from client's channel list */
2448 silc_list_del(client->channels, chl);
2450 /* Remove channel if there is no users anymore */
2451 if (server->server_type == SILC_ROUTER &&
2452 silc_list_count(channel->user_list) < 2) {
2453 server->stat.my_channels--;
2456 silc_task_unregister_by_context(server->timeout_queue, channel->rekey);
2458 if (channel->founder_key) {
2459 /* The founder auth data exists, do not remove the channel entry */
2460 SilcChannelClientEntry chl2;
2464 silc_list_start(channel->user_list);
2465 while ((chl2 = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2466 silc_list_del(chl2->client->channels, chl2);
2467 silc_list_del(channel->user_list, chl2);
2473 if (!silc_idlist_del_channel(server->local_list, channel))
2474 silc_idlist_del_channel(server->global_list, channel);
2478 /* Remove client from channel's client list */
2479 silc_list_del(channel->user_list, chl);
2481 server->stat.my_chanclients--;
2483 /* If there is no global users on the channel anymore mark the channel
2484 as local channel. */
2485 if (server->server_type == SILC_SERVER &&
2486 !silc_server_channel_has_global(channel))
2487 channel->global_users = FALSE;
2489 /* If there is not at least one local user on the channel then we don't
2490 need the channel entry anymore, we can remove it safely. */
2491 if (server->server_type == SILC_SERVER &&
2492 !silc_server_channel_has_local(channel)) {
2493 /* Notify about leaving client if this channel has global users. */
2494 if (notify && channel->global_users)
2495 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2496 SILC_NOTIFY_TYPE_SIGNOFF,
2497 signoff_message ? 2 : 1,
2498 clidp->data, clidp->len,
2499 signoff_message, signoff_message ?
2500 strlen(signoff_message) : 0);
2502 server->stat.my_channels--;
2505 silc_task_unregister_by_context(server->timeout_queue, channel->rekey);
2507 if (channel->founder_key) {
2508 /* The founder auth data exists, do not remove the channel entry */
2509 SilcChannelClientEntry chl2;
2513 silc_list_start(channel->user_list);
2514 while ((chl2 = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2515 silc_list_del(chl2->client->channels, chl2);
2516 silc_list_del(channel->user_list, chl2);
2522 if (!silc_idlist_del_channel(server->local_list, channel))
2523 silc_idlist_del_channel(server->global_list, channel);
2527 /* Send notify to channel about client leaving SILC and thus
2528 the entire channel. */
2530 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2531 SILC_NOTIFY_TYPE_SIGNOFF,
2532 signoff_message ? 2 : 1,
2533 clidp->data, clidp->len,
2534 signoff_message, signoff_message ?
2535 strlen(signoff_message) : 0);
2537 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2538 /* Re-generate channel key */
2539 silc_server_create_channel_key(server, channel, 0);
2541 /* Send the channel key to the channel. The key of course is not sent
2542 to the client who was removed from the channel. */
2543 silc_server_send_channel_key(server, client->connection, channel,
2544 server->server_type == SILC_ROUTER ?
2545 FALSE : !server->standalone);
2549 silc_buffer_free(clidp);
2552 /* Removes client from one channel. This is used for example when client
2553 calls LEAVE command to remove itself from the channel. Returns TRUE
2554 if channel still exists and FALSE if the channel is removed when
2555 last client leaves the channel. If `notify' is FALSE notify messages
2558 int silc_server_remove_from_one_channel(SilcServer server,
2559 SilcSocketConnection sock,
2560 SilcChannelEntry channel,
2561 SilcClientEntry client,
2564 SilcChannelEntry ch;
2565 SilcChannelClientEntry chl;
2568 SILC_LOG_DEBUG(("Start"));
2570 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2572 /* Remove the client from the channel. The client is removed from
2573 the channel's user list. */
2574 silc_list_start(client->channels);
2575 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2576 if (chl->channel != channel)
2581 /* Remove channel from client's channel list */
2582 silc_list_del(client->channels, chl);
2584 /* Remove channel if there is no users anymore */
2585 if (server->server_type == SILC_ROUTER &&
2586 silc_list_count(channel->user_list) < 2) {
2588 silc_task_unregister_by_context(server->timeout_queue, channel->rekey);
2589 if (!silc_idlist_del_channel(server->local_list, channel))
2590 silc_idlist_del_channel(server->global_list, channel);
2591 silc_buffer_free(clidp);
2592 server->stat.my_channels--;
2596 /* Remove client from channel's client list */
2597 silc_list_del(channel->user_list, chl);
2599 server->stat.my_chanclients--;
2601 /* If there is no global users on the channel anymore mark the channel
2602 as local channel. */
2603 if (server->server_type == SILC_SERVER &&
2604 !silc_server_channel_has_global(channel))
2605 channel->global_users = FALSE;
2607 /* If there is not at least one local user on the channel then we don't
2608 need the channel entry anymore, we can remove it safely. */
2609 if (server->server_type == SILC_SERVER &&
2610 !silc_server_channel_has_local(channel)) {
2611 /* Notify about leaving client if this channel has global users. */
2612 if (notify && channel->global_users)
2613 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2614 SILC_NOTIFY_TYPE_LEAVE, 1,
2615 clidp->data, clidp->len);
2617 server->stat.my_channels--;
2618 silc_buffer_free(clidp);
2621 silc_task_unregister_by_context(server->timeout_queue, channel->rekey);
2623 if (channel->founder_key) {
2624 /* The founder auth data exists, do not remove the channel entry */
2625 SilcChannelClientEntry chl2;
2629 silc_list_start(channel->user_list);
2630 while ((chl2 = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2631 silc_list_del(chl2->client->channels, chl2);
2632 silc_list_del(channel->user_list, chl2);
2638 if (!silc_idlist_del_channel(server->local_list, channel))
2639 silc_idlist_del_channel(server->global_list, channel);
2643 /* Send notify to channel about client leaving the channel */
2645 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2646 SILC_NOTIFY_TYPE_LEAVE, 1,
2647 clidp->data, clidp->len);
2651 silc_buffer_free(clidp);
2655 /* Returns TRUE if the given client is on the channel. FALSE if not.
2656 This works because we assure that the user list on the channel is
2657 always in up to date thus we can only check the channel list from
2658 `client' which is faster than checking the user list from `channel'. */
2660 int silc_server_client_on_channel(SilcClientEntry client,
2661 SilcChannelEntry channel)
2663 SilcChannelClientEntry chl;
2665 if (!client || !channel)
2668 silc_list_start(client->channels);
2669 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END)
2670 if (chl->channel == channel)
2676 /* Timeout callback. This is called if connection is idle or for some
2677 other reason is not responding within some period of time. This
2678 disconnects the remote end. */
2680 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2682 SilcServer server = (SilcServer)context;
2683 SilcSocketConnection sock = server->sockets[fd];
2688 if (sock->user_data)
2689 silc_server_free_sock_user_data(server, sock);
2691 silc_server_disconnect_remote(server, sock,
2692 "Server closed connection: "
2693 "Connection timeout");
2696 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2697 function may be used only by router. In real SILC network all channels
2698 are created by routers thus this function is never used by normal
2701 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2702 SilcServerID *router_id,
2708 SilcChannelID *channel_id;
2709 SilcChannelEntry entry;
2713 SILC_LOG_DEBUG(("Creating new channel"));
2716 cipher = "aes-256-cbc";
2718 hmac = "hmac-sha1-96";
2720 /* Allocate cipher */
2721 if (!silc_cipher_alloc(cipher, &key))
2725 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2726 silc_cipher_free(key);
2730 channel_name = strdup(channel_name);
2732 /* Create the channel */
2733 silc_id_create_channel_id(router_id, server->rng, &channel_id);
2734 entry = silc_idlist_add_channel(server->local_list, channel_name,
2735 SILC_CHANNEL_MODE_NONE, channel_id,
2736 NULL, key, newhmac);
2738 silc_free(channel_name);
2742 entry->cipher = strdup(cipher);
2743 entry->hmac_name = strdup(hmac);
2745 /* Now create the actual key material */
2746 silc_server_create_channel_key(server, entry,
2747 silc_cipher_get_key_len(key) / 8);
2749 /* Notify other routers about the new channel. We send the packet
2750 to our primary route. */
2751 if (broadcast && server->standalone == FALSE)
2752 silc_server_send_new_channel(server, server->router->connection, TRUE,
2753 channel_name, entry->id, SILC_ID_CHANNEL_LEN,
2756 server->stat.my_channels++;
2761 /* Same as above but creates the channel with Channel ID `channel_id. */
2764 silc_server_create_new_channel_with_id(SilcServer server,
2768 SilcChannelID *channel_id,
2771 SilcChannelEntry entry;
2775 SILC_LOG_DEBUG(("Creating new channel"));
2778 cipher = "aes-256-cbc";
2780 hmac = "hmac-sha1-96";
2782 /* Allocate cipher */
2783 if (!silc_cipher_alloc(cipher, &key))
2787 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2788 silc_cipher_free(key);
2792 channel_name = strdup(channel_name);
2794 /* Create the channel */
2795 entry = silc_idlist_add_channel(server->local_list, channel_name,
2796 SILC_CHANNEL_MODE_NONE, channel_id,
2797 NULL, key, newhmac);
2799 silc_free(channel_name);
2803 /* Now create the actual key material */
2804 silc_server_create_channel_key(server, entry,
2805 silc_cipher_get_key_len(key) / 8);
2807 /* Notify other routers about the new channel. We send the packet
2808 to our primary route. */
2809 if (broadcast && server->standalone == FALSE)
2810 silc_server_send_new_channel(server, server->router->connection, TRUE,
2811 channel_name, entry->id, SILC_ID_CHANNEL_LEN,
2814 server->stat.my_channels++;
2819 /* Channel's key re-key timeout callback. */
2821 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
2823 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
2824 SilcServer server = (SilcServer)rekey->context;
2826 silc_server_create_channel_key(server, rekey->channel, rekey->key_len);
2827 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
2829 silc_task_register(server->timeout_queue, 0,
2830 silc_server_channel_key_rekey,
2831 (void *)rekey, 3600, 0,
2833 SILC_TASK_PRI_NORMAL);
2836 /* Generates new channel key. This is used to create the initial channel key
2837 but also to re-generate new key for channel. If `key_len' is provided
2838 it is the bytes of the key length. */
2840 void silc_server_create_channel_key(SilcServer server,
2841 SilcChannelEntry channel,
2845 unsigned char channel_key[32], hash[32];
2848 SILC_LOG_DEBUG(("Generating channel key"));
2850 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
2851 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
2855 if (!channel->channel_key)
2856 if (!silc_cipher_alloc("aes-256-cbc", &channel->channel_key))
2861 else if (channel->key_len)
2862 len = channel->key_len / 8;
2864 len = silc_cipher_get_key_len(channel->channel_key) / 8;
2866 /* Create channel key */
2867 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
2870 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
2872 /* Remove old key if exists */
2874 memset(channel->key, 0, channel->key_len / 8);
2875 silc_free(channel->key);
2879 channel->key_len = len * 8;
2880 channel->key = silc_calloc(len, sizeof(*channel->key));
2881 memcpy(channel->key, channel_key, len);
2882 memset(channel_key, 0, sizeof(channel_key));
2884 /* Generate HMAC key from the channel key data and set it */
2886 silc_hmac_alloc("hmac-sha1-96", NULL, &channel->hmac);
2887 silc_hash_make(channel->hmac->hash, channel->key, len, hash);
2888 silc_hmac_set_key(channel->hmac, hash, silc_hash_len(channel->hmac->hash));
2889 memset(hash, 0, sizeof(hash));
2891 if (server->server_type == SILC_ROUTER) {
2892 if (!channel->rekey)
2893 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
2894 channel->rekey->context = (void *)server;
2895 channel->rekey->channel = channel;
2896 channel->rekey->key_len = key_len;
2898 silc_task_unregister_by_callback(server->timeout_queue,
2899 silc_server_channel_key_rekey);
2900 silc_task_register(server->timeout_queue, 0,
2901 silc_server_channel_key_rekey,
2902 (void *)channel->rekey, 3600, 0,
2904 SILC_TASK_PRI_NORMAL);
2908 /* Saves the channel key found in the encoded `key_payload' buffer. This
2909 function is used when we receive Channel Key Payload and also when we're
2910 processing JOIN command reply. Returns entry to the channel. */
2912 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
2913 SilcBuffer key_payload,
2914 SilcChannelEntry channel)
2916 SilcChannelKeyPayload payload = NULL;
2917 SilcChannelID *id = NULL;
2918 unsigned char *tmp, hash[32];
2922 SILC_LOG_DEBUG(("Start"));
2924 /* Decode channel key payload */
2925 payload = silc_channel_key_payload_parse(key_payload);
2927 SILC_LOG_ERROR(("Bad channel key payload, dropped"));
2932 /* Get the channel entry */
2935 /* Get channel ID */
2936 tmp = silc_channel_key_get_id(payload, &tmp_len);
2937 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
2943 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
2945 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
2947 SILC_LOG_ERROR(("Received key for non-existent channel"));
2953 tmp = silc_channel_key_get_key(payload, &tmp_len);
2959 cipher = silc_channel_key_get_cipher(payload, NULL);
2965 /* Remove old key if exists */
2967 memset(channel->key, 0, channel->key_len / 8);
2968 silc_free(channel->key);
2969 silc_cipher_free(channel->channel_key);
2972 /* Create new cipher */
2973 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
2978 if (channel->cipher)
2979 silc_free(channel->cipher);
2980 channel->cipher = strdup(cipher);
2983 channel->key_len = tmp_len * 8;
2984 channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
2985 memcpy(channel->key, tmp, tmp_len);
2986 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
2988 /* Generate HMAC key from the channel key data and set it */
2990 silc_hmac_alloc("hmac-sha1-96", NULL, &channel->hmac);
2991 silc_hash_make(channel->hmac->hash, tmp, tmp_len, hash);
2992 silc_hmac_set_key(channel->hmac, hash, silc_hash_len(channel->hmac->hash));
2994 memset(hash, 0, sizeof(hash));
2995 memset(tmp, 0, tmp_len);
2997 if (server->server_type == SILC_ROUTER) {
2998 if (!channel->rekey)
2999 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3000 channel->rekey->context = (void *)server;
3001 channel->rekey->channel = channel;
3003 silc_task_unregister_by_callback(server->timeout_queue,
3004 silc_server_channel_key_rekey);
3005 silc_task_register(server->timeout_queue, 0,
3006 silc_server_channel_key_rekey,
3007 (void *)channel->rekey, 3600, 0,
3009 SILC_TASK_PRI_NORMAL);
3016 silc_channel_key_payload_free(payload);
3021 /* Heartbeat callback. This function is set as argument for the
3022 silc_socket_set_heartbeat function. The library will call this function
3023 at the set time interval. */
3025 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3028 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3030 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname,
3033 /* Send the heartbeat */
3034 silc_server_send_heartbeat(hb->server, sock);
3037 /* Returns assembled of all servers in the given ID list. The packet's
3038 form is dictated by the New ID payload. */
3040 static void silc_server_announce_get_servers(SilcServer server,
3042 SilcBuffer *servers)
3044 SilcIDCacheList list;
3045 SilcIDCacheEntry id_cache;
3046 SilcServerEntry entry;
3049 /* Go through all clients in the list */
3050 if (silc_idcache_find_by_id(id_list->clients, SILC_ID_CACHE_ANY,
3051 SILC_ID_SERVER, &list)) {
3052 if (silc_idcache_list_first(list, &id_cache)) {
3054 entry = (SilcServerEntry)id_cache->context;
3056 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3058 *servers = silc_buffer_realloc(*servers,
3060 (*servers)->truelen + idp->len :
3062 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3063 silc_buffer_put(*servers, idp->data, idp->len);
3064 silc_buffer_pull(*servers, idp->len);
3065 silc_buffer_free(idp);
3067 if (!silc_idcache_list_next(list, &id_cache))
3072 silc_idcache_list_free(list);
3076 /* This function is used by router to announce existing servers to our
3077 primary router when we've connected to it. */
3079 void silc_server_announce_servers(SilcServer server)
3081 SilcBuffer servers = NULL;
3083 SILC_LOG_DEBUG(("Announcing servers"));
3085 /* Get servers in local list */
3086 silc_server_announce_get_servers(server, server->local_list, &servers);
3088 /* Get servers in global list */
3089 silc_server_announce_get_servers(server, server->global_list, &servers);
3092 silc_buffer_push(servers, servers->data - servers->head);
3093 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3095 /* Send the packet */
3096 silc_server_packet_send(server, server->router->connection,
3097 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3098 servers->data, servers->len, TRUE);
3100 silc_buffer_free(servers);
3104 /* Returns assembled packet of all clients in the given ID list. The
3105 packet's form is dictated by the New ID Payload. */
3107 static void silc_server_announce_get_clients(SilcServer server,
3109 SilcBuffer *clients)
3111 SilcIDCacheList list;
3112 SilcIDCacheEntry id_cache;
3113 SilcClientEntry client;
3116 /* Go through all clients in the list */
3117 if (silc_idcache_find_by_id(id_list->clients, SILC_ID_CACHE_ANY,
3118 SILC_ID_CLIENT, &list)) {
3119 if (silc_idcache_list_first(list, &id_cache)) {
3121 client = (SilcClientEntry)id_cache->context;
3123 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3125 *clients = silc_buffer_realloc(*clients,
3127 (*clients)->truelen + idp->len :
3129 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3130 silc_buffer_put(*clients, idp->data, idp->len);
3131 silc_buffer_pull(*clients, idp->len);
3132 silc_buffer_free(idp);
3134 if (!silc_idcache_list_next(list, &id_cache))
3139 silc_idcache_list_free(list);
3143 /* This function is used to announce our existing clients to our router
3144 when we've connected to it. */
3146 void silc_server_announce_clients(SilcServer server)
3148 SilcBuffer clients = NULL;
3150 SILC_LOG_DEBUG(("Announcing clients"));
3152 /* Get clients in local list */
3153 silc_server_announce_get_clients(server, server->local_list,
3156 /* As router we announce our global list as well */
3157 if (server->server_type == SILC_ROUTER)
3158 silc_server_announce_get_clients(server, server->global_list,
3162 silc_buffer_push(clients, clients->data - clients->head);
3163 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3165 /* Send the packet */
3166 silc_server_packet_send(server, server->router->connection,
3167 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3168 clients->data, clients->len, TRUE);
3170 silc_buffer_free(clients);
3175 silc_server_announce_encode_join(uint32 argc, ...)
3180 return silc_notify_payload_encode(SILC_NOTIFY_TYPE_JOIN, argc, ap);
3183 /* Returns assembled packets for channel users of the `channel'. */
3185 void silc_server_announce_get_channel_users(SilcServer server,
3186 SilcChannelEntry channel,
3187 SilcBuffer *channel_users)
3189 SilcChannelClientEntry chl;
3190 SilcBuffer chidp, clidp;
3194 SILC_LOG_DEBUG(("Start"));
3196 /* Now find all users on the channel */
3197 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3198 silc_list_start(channel->user_list);
3199 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
3200 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3201 tmp = silc_server_announce_encode_join(2, clidp->data, clidp->len,
3202 chidp->data, chidp->len);
3205 silc_buffer_realloc(*channel_users,
3207 (*channel_users)->truelen + len : len));
3208 silc_buffer_pull_tail(*channel_users,
3209 ((*channel_users)->end -
3210 (*channel_users)->data));
3212 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3213 silc_buffer_pull(*channel_users, len);
3214 silc_buffer_free(clidp);
3215 silc_buffer_free(tmp);
3217 silc_buffer_free(chidp);
3220 /* Returns assembled packets for all channels and users on those channels
3221 from the given ID List. The packets are in the form dictated by the
3222 New Channel and New Channel User payloads. */
3224 void silc_server_announce_get_channels(SilcServer server,
3226 SilcBuffer *channels,
3227 SilcBuffer *channel_users)
3229 SilcIDCacheList list;
3230 SilcIDCacheEntry id_cache;
3231 SilcChannelEntry channel;
3236 SILC_LOG_DEBUG(("Start"));
3238 /* Go through all channels in the list */
3239 if (silc_idcache_find_by_id(id_list->channels, SILC_ID_CACHE_ANY,
3240 SILC_ID_CHANNEL, &list)) {
3241 if (silc_idcache_list_first(list, &id_cache)) {
3243 channel = (SilcChannelEntry)id_cache->context;
3245 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3246 name_len = strlen(channel->channel_name);
3248 len = 4 + name_len + SILC_ID_CHANNEL_LEN + 4;
3250 silc_buffer_realloc(*channels,
3251 (*channels ? (*channels)->truelen + len : len));
3252 silc_buffer_pull_tail(*channels,
3253 ((*channels)->end - (*channels)->data));
3254 silc_buffer_format(*channels,
3255 SILC_STR_UI_SHORT(name_len),
3256 SILC_STR_UI_XNSTRING(channel->channel_name,
3258 SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
3259 SILC_STR_UI_XNSTRING(cid, SILC_ID_CHANNEL_LEN),
3260 SILC_STR_UI_INT(channel->mode),
3262 silc_buffer_pull(*channels, len);
3264 silc_server_announce_get_channel_users(server, channel,
3269 if (!silc_idcache_list_next(list, &id_cache))
3274 silc_idcache_list_free(list);
3278 /* This function is used to announce our existing channels to our router
3279 when we've connected to it. This also announces the users on the
3280 channels to the router. */
3282 void silc_server_announce_channels(SilcServer server)
3284 SilcBuffer channels = NULL, channel_users = NULL;
3286 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3288 /* Get channels and channel users in local list */
3289 silc_server_announce_get_channels(server, server->local_list,
3290 &channels, &channel_users);
3292 /* Get channels and channel users in global list */
3293 silc_server_announce_get_channels(server, server->global_list,
3294 &channels, &channel_users);
3297 silc_buffer_push(channels, channels->data - channels->head);
3298 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3300 /* Send the packet */
3301 silc_server_packet_send(server, server->router->connection,
3302 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3303 channels->data, channels->len,
3306 silc_buffer_free(channels);
3309 if (channel_users) {
3310 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3311 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3312 channel_users->len);
3314 /* Send the packet */
3315 silc_server_packet_send(server, server->router->connection,
3316 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3317 channel_users->data, channel_users->len,
3320 silc_buffer_free(channel_users);
3324 /* Failure timeout callback. If this is called then we will immediately
3325 process the received failure. We always process the failure with timeout
3326 since we do not want to blindly trust to received failure packets.
3327 This won't be called (the timeout is cancelled) if the failure was
3328 bogus (it is bogus if remote does not close the connection after sending
3331 SILC_TASK_CALLBACK(silc_server_failure_callback)
3333 SilcServerFailureContext f = (SilcServerFailureContext)context;
3335 if (f->sock->protocol) {
3336 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3337 f->sock->protocol->execute(f->server->timeout_queue, 0,
3338 f->sock->protocol, f->sock->sock, 0, 0);
3344 /* Assembles user list and users mode list from the `channel'. */
3346 void silc_server_get_users_on_channel(SilcServer server,
3347 SilcChannelEntry channel,
3348 SilcBuffer *user_list,
3349 SilcBuffer *mode_list,
3352 SilcChannelClientEntry chl;
3353 SilcBuffer client_id_list;
3354 SilcBuffer client_mode_list;
3356 uint32 list_count = 0;
3358 client_id_list = silc_buffer_alloc((SILC_ID_CLIENT_LEN + 4) *
3359 silc_list_count(channel->user_list));
3360 client_mode_list = silc_buffer_alloc(4 *
3361 silc_list_count(channel->user_list));
3362 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3363 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3364 silc_list_start(channel->user_list);
3365 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
3367 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3368 silc_buffer_put(client_id_list, idp->data, idp->len);
3369 silc_buffer_pull(client_id_list, idp->len);
3370 silc_buffer_free(idp);
3372 /* Client's mode on channel */
3373 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3374 silc_buffer_pull(client_mode_list, 4);
3378 silc_buffer_push(client_id_list,
3379 client_id_list->data - client_id_list->head);
3380 silc_buffer_push(client_mode_list,
3381 client_mode_list->data - client_mode_list->head);
3383 *user_list = client_id_list;
3384 *mode_list = client_mode_list;
3385 *user_count = list_count;
3388 /* Saves users and their modes to the `channel'. */
3390 void silc_server_save_users_on_channel(SilcServer server,
3391 SilcSocketConnection sock,
3392 SilcChannelEntry channel,
3393 SilcClientID *noadd,
3394 SilcBuffer user_list,
3395 SilcBuffer mode_list,
3400 /* Cache the received Client ID's and modes. This cache expires
3401 whenever server sends notify message to channel. It means two things;
3402 some user has joined or leaved the channel. XXX TODO! */
3403 for (i = 0; i < user_count; i++) {
3406 SilcClientID *client_id;
3407 SilcClientEntry client;
3410 SILC_GET16_MSB(idp_len, user_list->data + 2);
3412 client_id = silc_id_payload_parse_id(user_list->data, idp_len);
3413 silc_buffer_pull(user_list, idp_len);
3418 SILC_GET32_MSB(mode, mode_list->data);
3419 silc_buffer_pull(mode_list, 4);
3421 if (noadd && !SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3422 silc_free(client_id);
3426 /* Check if we have this client cached already. */
3427 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3430 client = silc_idlist_find_client_by_id(server->global_list,
3433 /* If router did not find such Client ID in its lists then this must
3434 be bogus client or some router in the net is buggy. */
3435 if (server->server_type == SILC_ROUTER) {
3436 silc_free(client_id);
3440 /* We don't have that client anywhere, add it. The client is added
3441 to global list since server didn't have it in the lists so it must be
3443 client = silc_idlist_add_client(server->global_list, NULL, 0, NULL,
3445 silc_id_dup(client_id, SILC_ID_CLIENT),
3446 sock->user_data, NULL);
3448 silc_free(client_id);
3452 client->data.registered = TRUE;
3455 silc_free(client_id);
3457 if (!silc_server_client_on_channel(client, channel)) {
3458 /* Client was not on the channel, add it. */
3459 SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3460 chl->client = client;
3462 chl->channel = channel;
3463 silc_list_add(channel->user_list, chl);
3464 silc_list_add(client->channels, chl);
3469 /* Lookups route to the client indicated by the `id_data'. The connection
3470 object and internal data object is returned. Returns NULL if route
3471 could not be found to the client. If the `client_id' is specified then
3472 it is used and the `id_data' is ignored. */
3474 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3475 unsigned char *id_data,
3477 SilcClientID *client_id,
3478 SilcIDListData *idata)
3481 SilcClientEntry client;
3483 SILC_LOG_DEBUG(("Start"));
3485 /* Decode destination Client ID */
3487 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3489 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3493 id = silc_id_dup(client_id, SILC_ID_CLIENT);
3496 /* If the destination belongs to our server we don't have to route
3497 the packet anywhere but to send it to the local destination. */
3498 client = silc_idlist_find_client_by_id(server->local_list, id, NULL);
3502 if (client && client->data.registered == FALSE)
3505 /* If we are router and the client has router then the client is in
3506 our cell but not directly connected to us. */
3507 if (server->server_type == SILC_ROUTER && client->router) {
3508 /* We are of course in this case the client's router thus the real
3509 "router" of the client is the server who owns the client. Thus
3510 we will send the packet to that server. */
3512 *idata = (SilcIDListData)client->router;
3513 return client->router->connection;
3516 /* Seems that client really is directly connected to us */
3518 *idata = (SilcIDListData)client;
3519 return client->connection;
3522 /* Destination belongs to someone not in this server. If we are normal
3523 server our action is to send the packet to our router. */
3524 if (server->server_type == SILC_SERVER && !server->standalone) {
3527 *idata = (SilcIDListData)server->router;
3528 return server->router->connection;
3531 /* We are router and we will perform route lookup for the destination
3532 and send the packet to fastest route. */
3533 if (server->server_type == SILC_ROUTER && !server->standalone) {
3534 /* Check first that the ID is valid */
3535 client = silc_idlist_find_client_by_id(server->global_list, id, NULL);
3537 SilcSocketConnection dst_sock;
3539 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
3543 *idata = (SilcIDListData)dst_sock->user_data;
3552 /* Encodes and returns channel list of channels the `client' has joined.
3553 Secret channels are not put to the list. */
3555 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
3556 SilcClientEntry client)
3558 SilcBuffer buffer = NULL;
3559 SilcChannelEntry channel;
3560 SilcChannelClientEntry chl;
3565 silc_list_start(client->channels);
3566 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
3567 channel = chl->channel;
3569 if (channel->mode & SILC_CHANNEL_MODE_SECRET)
3572 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3573 name_len = strlen(channel->channel_name);
3575 len = 4 + name_len + SILC_ID_CHANNEL_LEN + 4;
3576 buffer = silc_buffer_realloc(buffer,
3577 (buffer ? (buffer)->truelen + len : len));
3578 silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
3579 silc_buffer_format(buffer,
3580 SILC_STR_UI_SHORT(name_len),
3581 SILC_STR_UI_XNSTRING(channel->channel_name,
3583 SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
3584 SILC_STR_UI_XNSTRING(cid, SILC_ID_CHANNEL_LEN),
3585 SILC_STR_UI_INT(chl->mode), /* Client's mode */
3587 silc_buffer_pull(buffer, len);
3592 silc_buffer_push(buffer, buffer->data - buffer->head);
3597 /* Finds client entry by Client ID and if it is not found then resolves
3598 it using WHOIS command. */
3600 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
3601 SilcClientID *client_id)
3603 SilcClientEntry client;
3605 client = silc_idlist_find_client_by_id(server->local_list, client_id, NULL);
3607 client = silc_idlist_find_client_by_id(server->global_list,
3609 if (!client && server->server_type == SILC_ROUTER)
3613 if (!client && server->standalone)
3616 if (!client || !client->nickname || !client->username) {
3617 SilcBuffer buffer, idp;
3619 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3620 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
3621 ++server->cmd_ident, 1,
3622 3, idp->data, idp->len);
3623 silc_server_packet_send(server, client ? client->router->connection :
3624 server->router->connection,
3625 SILC_PACKET_COMMAND, 0,
3626 buffer->data, buffer->len, FALSE);
3627 silc_buffer_free(idp);
3628 silc_buffer_free(buffer);
3634 /* A timeout callback for the re-key. We will be the initiator of the
3637 SILC_TASK_CALLBACK(silc_server_rekey_callback)
3639 SilcSocketConnection sock = (SilcSocketConnection)context;
3640 SilcIDListData idata = (SilcIDListData)sock->user_data;
3641 SilcServer server = (SilcServer)idata->rekey->context;
3642 SilcProtocol protocol;
3643 SilcServerRekeyInternalContext *proto_ctx;
3645 SILC_LOG_DEBUG(("Start"));
3647 /* Allocate internal protocol context. This is sent as context
3649 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
3650 proto_ctx->server = (void *)server;
3651 proto_ctx->sock = sock;
3652 proto_ctx->responder = FALSE;
3653 proto_ctx->pfs = idata->rekey->pfs;
3655 /* Perform rekey protocol. Will call the final callback after the
3656 protocol is over. */
3657 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
3658 &protocol, proto_ctx, silc_server_rekey_final);
3659 sock->protocol = protocol;
3661 /* Run the protocol */
3662 protocol->execute(server->timeout_queue, 0, protocol,
3665 /* Re-register re-key timeout */
3666 silc_task_register(server->timeout_queue, sock->sock,
3667 silc_server_rekey_callback,
3668 context, idata->rekey->timeout, 0,
3669 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
3672 /* The final callback for the REKEY protocol. This will actually take the
3673 new key material into use. */
3675 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
3677 SilcProtocol protocol = (SilcProtocol)context;
3678 SilcServerRekeyInternalContext *ctx =
3679 (SilcServerRekeyInternalContext *)protocol->context;
3680 SilcServer server = (SilcServer)ctx->server;
3681 SilcSocketConnection sock = ctx->sock;
3683 SILC_LOG_DEBUG(("Start"));
3685 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
3686 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
3687 /* Error occured during protocol */
3688 silc_protocol_cancel(server->timeout_queue, protocol);
3689 silc_protocol_free(protocol);
3690 sock->protocol = NULL;
3692 silc_packet_context_free(ctx->packet);
3694 silc_ske_free(ctx->ske);
3700 /* Take the keys into use */
3701 if (ctx->pfs == TRUE)
3702 silc_server_protocol_rekey_generate_pfs(server, ctx);
3704 silc_server_protocol_rekey_generate(server, ctx);
3708 silc_protocol_free(protocol);
3709 sock->protocol = NULL;
3711 silc_packet_context_free(ctx->packet);
3713 silc_ske_free(ctx->ske);