5 Author: Pekka Riikonen <priikone@silcnet.org>
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 if (!silc_server_config_register_ciphers(server->config))
149 silc_cipher_register_default();
150 if (!silc_server_config_register_pkcs(server->config))
151 silc_pkcs_register_default();
152 if (!silc_server_config_register_hashfuncs(server->config))
153 silc_hash_register_default();
154 if (!silc_server_config_register_hmacs(server->config))
155 silc_hmac_register_default();
157 /* Initialize random number generator for the server. */
158 server->rng = silc_rng_alloc();
159 silc_rng_init(server->rng);
160 silc_rng_global_init(server->rng);
162 /* Initialize hash functions for server to use */
163 silc_hash_alloc("md5", &server->md5hash);
164 silc_hash_alloc("sha1", &server->sha1hash);
166 /* Initialize none cipher */
167 silc_cipher_alloc("none", &server->none_cipher);
169 /* Create a listening server. Note that our server can listen on
170 multiple ports. All listeners are created here and now. */
171 /* XXX Still check this whether to use server_info or listen_port. */
173 while(server->config->listen_port) {
176 tmp = silc_net_create_server(server->config->listen_port->port,
177 server->config->listen_port->host);
181 sock = silc_realloc(sock, (sizeof(int *) * (sock_count + 1)));
182 sock[sock_count] = tmp;
183 server->config->listen_port = server->config->listen_port->next;
187 /* Initialize ID caches */
188 server->local_list->clients =
189 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
190 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
191 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
193 /* These are allocated for normal server as well as these hold some
194 global information that the server has fetched from its router. For
195 router these are used as they are supposed to be used on router. */
196 server->global_list->clients =
197 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
198 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
199 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
201 /* Allocate the entire socket list that is used in server. Eventually
202 all connections will have entry in this table (it is a table of
203 pointers to the actual object that is allocated individually
205 server->sockets = silc_calloc(SILC_SERVER_MAX_CONNECTIONS,
206 sizeof(*server->sockets));
208 for (i = 0; i < sock_count; i++) {
209 SilcSocketConnection newsocket = NULL;
211 /* Set socket to non-blocking mode */
212 silc_net_set_socket_nonblock(sock[i]);
213 server->sock = sock[i];
215 /* Create a Server ID for the server. */
216 silc_id_create_server_id(sock[i], server->rng, &id);
222 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
223 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
224 server->id_type = SILC_ID_SERVER;
225 server->server_name = server->config->server_info->server_name;
227 /* Add ourselves to the server list. We don't have a router yet
228 beacuse we haven't established a route yet. It will be done later.
229 For now, NULL is sent as router. This allocates new entry to
232 silc_idlist_add_server(server->local_list,
233 server->config->server_info->server_name,
234 server->server_type, server->id, NULL, NULL);
236 SILC_LOG_ERROR(("Could not add ourselves to cache"));
239 id_entry->data.registered = TRUE;
241 /* Add ourselves also to the socket table. The entry allocated above
242 is sent as argument for fast referencing in the future. */
243 silc_socket_alloc(sock[i], SILC_SOCKET_TYPE_SERVER, id_entry,
246 server->sockets[sock[i]] = newsocket;
248 /* Perform name and address lookups to resolve the listenning address
250 if (!silc_net_check_local_by_sock(sock[i], &newsocket->hostname,
252 if ((server->params->require_reverse_mapping && !newsocket->hostname) ||
254 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
255 newsocket->hostname ? newsocket->hostname :
256 newsocket->ip ? newsocket->ip : ""));
257 server->stat.conn_failures++;
260 if (!newsocket->hostname)
261 newsocket->hostname = strdup(newsocket->ip);
263 newsocket->port = silc_net_get_local_port(sock[i]);
265 /* Put the allocated socket pointer also to the entry allocated above
266 for fast back-referencing to the socket list. */
267 id_entry->connection = (void *)server->sockets[sock[i]];
268 server->id_entry = id_entry;
271 /* Register protocols */
272 silc_server_protocols_register();
274 /* Initialize the scheduler. */
275 server->schedule = silc_schedule_init(SILC_SERVER_MAX_CONNECTIONS);
276 if (!server->schedule)
279 /* Add the first task to the scheduler. This is task that is executed by
280 timeout. It expires as soon as the caller calls silc_server_run. This
281 task performs authentication protocol and key exchange with our
283 silc_schedule_task_add(server->schedule, sock[0],
284 silc_server_connect_to_router,
285 (void *)server, 0, 1,
287 SILC_TASK_PRI_NORMAL);
289 /* Add listener task to the scheduler. This task receives new connections
290 to the server. This task remains on the queue until the end of the
292 silc_schedule_task_add(server->schedule, sock[0],
293 silc_server_accept_new_connection,
294 (void *)server, 0, 0,
296 SILC_TASK_PRI_NORMAL);
297 server->listenning = TRUE;
299 /* If server connections has been configured then we must be router as
300 normal server cannot have server connections, only router connections. */
301 if (server->config->servers)
302 server->server_type = SILC_ROUTER;
304 /* Register the ID Cache purge task. This periodically purges the ID cache
305 and removes the expired cache entries. */
307 /* Clients local list */
308 purge = silc_calloc(1, sizeof(*purge));
309 purge->cache = server->local_list->clients;
310 purge->schedule = server->schedule;
311 silc_schedule_task_add(purge->schedule, 0,
313 (void *)purge, 600, 0,
314 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
316 /* Clients global list */
317 purge = silc_calloc(1, sizeof(*purge));
318 purge->cache = server->global_list->clients;
319 purge->schedule = server->schedule;
320 silc_schedule_task_add(purge->schedule, 0,
322 (void *)purge, 300, 0,
323 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
325 SILC_LOG_DEBUG(("Server initialized"));
327 /* We are done here, return succesfully */
331 for (i = 0; i < sock_count; i++)
332 silc_net_close_server(sock[i]);
337 /* Fork server to background and set gid+uid to non-root.
338 Silcd will not run as root, so trying to set either user or group to
339 root will cause silcd to exit. */
341 void silc_server_daemonise(SilcServer server)
343 /* Are we executing silcd as root or a regular user? */
350 if (!server->config->identity || !server->config->identity->user ||
351 !server->config->identity->group) {
352 fprintf(stderr, "Error:"
353 "\tSILC server must not be run as root. For the security of your\n"
354 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
355 "\tuser account. Modify the [Identity] configuration section to run\n"
356 "\tthe server as non-root user.\n");
360 /* Get the values given for user and group in configuration file */
361 user=server->config->identity->user;
362 group=server->config->identity->group;
364 /* Check whether the user/group information is text */
365 if (atoi(user)!=0 || atoi(group)!=0) {
366 SILC_LOG_DEBUG(("Invalid user and/or group information"));
367 SILC_LOG_DEBUG(("User and/or group given as number"));
368 fprintf(stderr, "Invalid user and/or group information\n");
369 fprintf(stderr, "Please assign them as names, not numbers\n");
373 /* Catch the nasty incident of string "0" returning 0 from atoi */
374 if (strcmp("0", user)==0 || strcmp("0", group)==0) {
375 SILC_LOG_DEBUG(("User and/or group configured to 0. Unacceptable"));
376 fprintf(stderr, "User and/or group configured to 0. Exiting\n");
384 fprintf(stderr, "No such user %s found\n", user);
389 fprintf(stderr, "No such group %s found\n", group);
393 /* Check whether user and/or group is set to root. If yes, exit
394 immediately. Otherwise, setgid and setuid server to user.group */
395 if (gr->gr_gid==0 || pw->pw_uid==0) {
396 fprintf(stderr, "Error:"
397 "\tSILC server must not be run as root. For the security of your\n"
398 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
399 "\tuser account. Modify the [Identity] configuration section to run\n"
400 "\tthe server as non-root user.\n");
403 /* Fork server to background, making it a daemon */
405 SILC_LOG_DEBUG(("Server started as root. Dropping privileges."));
406 SILC_LOG_DEBUG(("Forking SILC server to background"));
411 SILC_LOG_DEBUG(("Changing to group %s", group));
412 if(setgid(gr->gr_gid)==0) {
413 SILC_LOG_DEBUG(("Setgid to %s", group));
415 SILC_LOG_DEBUG(("Setgid to %s failed", group));
416 fprintf(stderr, "Tried to setgid %s but no such group. Exiting\n",
420 SILC_LOG_DEBUG(("Changing to user nobody"));
421 if(setuid(pw->pw_uid)==0) {
422 SILC_LOG_DEBUG(("Setuid to %s", user));
424 SILC_LOG_DEBUG(("Setuid to %s failed", user));
425 fprintf(stderr, "Tried to setuid %s but no such user. Exiting\n",
431 /* Fork server to background, making it a daemon */
433 SILC_LOG_DEBUG(("Server started as user"));
434 SILC_LOG_DEBUG(("Forking SILC server to background"));
441 /* Stops the SILC server. This function is used to shutdown the server.
442 This is usually called after the scheduler has returned. After stopping
443 the server one should call silc_server_free. */
445 void silc_server_stop(SilcServer server)
447 SILC_LOG_DEBUG(("Stopping server"));
449 silc_schedule_stop(server->schedule);
450 silc_schedule_uninit(server->schedule);
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 SILC_LOG_INFO(("SILC Server started"));
467 /* Start the scheduler, the heart of the SILC server. When this returns
468 the program will be terminated. */
469 silc_schedule(server->schedule);
472 /* Timeout callback that will be called to retry connecting to remote
473 router. This is used by both normal and router server. This will wait
474 before retrying the connecting. The timeout is generated by exponential
475 backoff algorithm. */
477 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
479 SilcServerConnection sconn = (SilcServerConnection)context;
480 SilcServer server = sconn->server;
482 SILC_LOG_INFO(("Retrying connecting to a router"));
484 /* Calculate next timeout */
485 if (sconn->retry_count >= 1) {
486 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
487 if (sconn->retry_timeout > SILC_SERVER_RETRY_INTERVAL_MAX)
488 sconn->retry_timeout = SILC_SERVER_RETRY_INTERVAL_MAX;
490 sconn->retry_timeout = server->params->retry_interval_min;
492 sconn->retry_count++;
493 sconn->retry_timeout = sconn->retry_timeout +
494 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
496 /* If we've reached max retry count, give up. */
497 if (sconn->retry_count > server->params->retry_count &&
498 server->params->retry_keep_trying == FALSE) {
499 SILC_LOG_ERROR(("Could not connect to router, giving up"));
503 /* Wait one before retrying */
504 silc_schedule_task_add(server->schedule, fd, silc_server_connect_router,
505 context, sconn->retry_timeout,
506 server->params->retry_interval_min_usec,
507 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
510 /* Generic routine to use connect to a router. */
512 SILC_TASK_CALLBACK(silc_server_connect_router)
514 SilcServerConnection sconn = (SilcServerConnection)context;
515 SilcServer server = sconn->server;
516 SilcSocketConnection newsocket;
517 SilcProtocol protocol;
518 SilcServerKEInternalContext *proto_ctx;
521 SILC_LOG_INFO(("Connecting to the router %s on port %d",
522 sconn->remote_host, sconn->remote_port));
524 /* Connect to remote host */
525 sock = silc_net_create_connection(sconn->remote_port,
528 SILC_LOG_ERROR(("Could not connect to router"));
529 silc_schedule_task_add(server->schedule, fd,
530 silc_server_connect_to_router_retry,
531 context, 0, 1, SILC_TASK_TIMEOUT,
532 SILC_TASK_PRI_NORMAL);
536 /* Set socket options */
537 silc_net_set_socket_nonblock(sock);
538 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
540 /* Create socket connection for the connection. Even though we
541 know that we are connecting to a router we will mark the socket
542 to be unknown connection until we have executed authentication
544 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
545 server->sockets[sock] = newsocket;
546 newsocket->hostname = strdup(sconn->remote_host);
547 newsocket->ip = strdup(sconn->remote_host);
548 newsocket->port = sconn->remote_port;
549 sconn->sock = newsocket;
551 /* Allocate internal protocol context. This is sent as context
553 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
554 proto_ctx->server = (void *)server;
555 proto_ctx->context = (void *)sconn;
556 proto_ctx->sock = newsocket;
557 proto_ctx->rng = server->rng;
558 proto_ctx->responder = FALSE;
560 /* Perform key exchange protocol. silc_server_connect_to_router_second
561 will be called after the protocol is finished. */
562 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
563 &protocol, proto_ctx,
564 silc_server_connect_to_router_second);
565 newsocket->protocol = protocol;
567 /* Register a timeout task that will be executed if the protocol
568 is not executed within set limit. */
569 proto_ctx->timeout_task =
570 silc_schedule_task_add(server->schedule, sock,
571 silc_server_timeout_remote,
572 server, server->params->protocol_timeout,
573 server->params->protocol_timeout_usec,
577 /* Register the connection for network input and output. This sets
578 that scheduler will listen for incoming packets for this connection
579 and sets that outgoing packets may be sent to this connection as
580 well. However, this doesn't set the scheduler for outgoing traffic,
581 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
582 later when outgoing data is available. */
583 context = (void *)server;
584 SILC_REGISTER_CONNECTION_FOR_IO(sock);
586 /* Run the protocol */
587 silc_protocol_execute(protocol, server->schedule, 0, 0);
590 /* This function connects to our primary router or if we are a router this
591 establishes all our primary routes. This is called at the start of the
592 server to do authentication and key exchange with our router - called
595 SILC_TASK_CALLBACK(silc_server_connect_to_router)
597 SilcServer server = (SilcServer)context;
598 SilcServerConnection sconn;
600 SILC_LOG_DEBUG(("Connecting to router(s)"));
602 /* If we are normal SILC server we need to connect to our cell's
604 if (server->server_type == SILC_SERVER) {
605 SILC_LOG_DEBUG(("We are normal server"));
607 /* Create connection to the router, if configured. */
608 if (server->config->routers) {
610 /* Allocate connection object for hold connection specific stuff. */
611 sconn = silc_calloc(1, sizeof(*sconn));
612 sconn->server = server;
613 sconn->remote_host = strdup(server->config->routers->host);
614 sconn->remote_port = server->config->routers->port;
616 silc_schedule_task_add(server->schedule, fd,
617 silc_server_connect_router,
618 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
619 SILC_TASK_PRI_NORMAL);
624 /* If we are a SILC router we need to establish all of our primary
626 if (server->server_type == SILC_ROUTER) {
627 SilcServerConfigSectionServerConnection *ptr;
629 SILC_LOG_DEBUG(("We are router"));
631 /* Create the connections to all our routes */
632 ptr = server->config->routers;
635 SILC_LOG_DEBUG(("Router connection [%s] %s:%d",
636 ptr->initiator ? "Initiator" : "Responder",
637 ptr->host, ptr->port));
639 if (ptr->initiator) {
640 /* Allocate connection object for hold connection specific stuff. */
641 sconn = silc_calloc(1, sizeof(*sconn));
642 sconn->server = server;
643 sconn->remote_host = strdup(ptr->host);
644 sconn->remote_port = ptr->port;
646 silc_schedule_task_add(server->schedule, fd,
647 silc_server_connect_router,
648 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
649 SILC_TASK_PRI_NORMAL);
659 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
661 /* There wasn't a configured router, we will continue but we don't
662 have a connection to outside world. We will be standalone server. */
663 server->standalone = TRUE;
666 /* Second part of connecting to router(s). Key exchange protocol has been
667 executed and now we will execute authentication protocol. */
669 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
671 SilcProtocol protocol = (SilcProtocol)context;
672 SilcServerKEInternalContext *ctx =
673 (SilcServerKEInternalContext *)protocol->context;
674 SilcServer server = (SilcServer)ctx->server;
675 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
676 SilcSocketConnection sock = ctx->sock;
677 SilcServerConnAuthInternalContext *proto_ctx;
678 SilcServerConfigSectionServerConnection *conn = NULL;
680 SILC_LOG_DEBUG(("Start"));
682 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
683 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
684 /* Error occured during protocol */
685 silc_protocol_free(protocol);
686 sock->protocol = NULL;
687 silc_ske_free_key_material(ctx->keymat);
689 silc_packet_context_free(ctx->packet);
691 silc_ske_free(ctx->ske);
693 silc_free(ctx->dest_id);
695 silc_schedule_task_del_by_callback(server->schedule,
696 silc_server_failure_callback);
697 silc_server_disconnect_remote(server, sock, "Server closed connection: "
698 "Key exchange failed");
702 /* We now have the key material as the result of the key exchange
703 protocol. Take the key material into use. Free the raw key material
704 as soon as we've set them into use. */
705 if (!silc_server_protocol_ke_set_keys(ctx->ske, ctx->sock, ctx->keymat,
706 ctx->ske->prop->cipher,
707 ctx->ske->prop->pkcs,
708 ctx->ske->prop->hash,
709 ctx->ske->prop->hmac,
710 ctx->ske->prop->group,
712 silc_protocol_free(protocol);
713 sock->protocol = NULL;
714 silc_ske_free_key_material(ctx->keymat);
716 silc_packet_context_free(ctx->packet);
718 silc_ske_free(ctx->ske);
720 silc_free(ctx->dest_id);
722 silc_schedule_task_del_by_callback(server->schedule,
723 silc_server_failure_callback);
724 silc_server_disconnect_remote(server, sock, "Server closed connection: "
725 "Key exchange failed");
728 silc_ske_free_key_material(ctx->keymat);
730 /* Allocate internal context for the authentication protocol. This
731 is sent as context for the protocol. */
732 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
733 proto_ctx->server = (void *)server;
734 proto_ctx->context = (void *)sconn;
735 proto_ctx->sock = sock;
736 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
737 proto_ctx->dest_id_type = ctx->dest_id_type;
738 proto_ctx->dest_id = ctx->dest_id;
740 /* Resolve the authentication method used in this connection. Check if
741 we find a match from user configured connections */
742 conn = silc_server_config_find_router_conn(server->config,
746 /* Match found. Use the configured authentication method */
747 proto_ctx->auth_meth = conn->auth_meth;
748 if (conn->auth_data) {
749 proto_ctx->auth_data = strdup(conn->auth_data);
750 proto_ctx->auth_data_len = strlen(conn->auth_data);
753 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
754 sock->hostname, sock->ip, sock->port));
755 silc_protocol_free(protocol);
756 sock->protocol = NULL;
758 silc_packet_context_free(ctx->packet);
760 silc_ske_free(ctx->ske);
762 silc_free(ctx->dest_id);
764 silc_schedule_task_del_by_callback(server->schedule,
765 silc_server_failure_callback);
766 silc_server_disconnect_remote(server, sock, "Server closed connection: "
767 "Key exchange failed");
771 /* Free old protocol as it is finished now */
772 silc_protocol_free(protocol);
774 silc_packet_context_free(ctx->packet);
776 sock->protocol = NULL;
778 /* Allocate the authentication protocol. This is allocated here
779 but we won't start it yet. We will be receiving party of this
780 protocol thus we will wait that connecting party will make
782 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
783 &sock->protocol, proto_ctx,
784 silc_server_connect_to_router_final);
786 /* Register timeout task. If the protocol is not executed inside
787 this timelimit the connection will be terminated. Currently
788 this is 15 seconds and is hard coded limit (XXX). */
789 proto_ctx->timeout_task =
790 silc_schedule_task_add(server->schedule, sock->sock,
791 silc_server_timeout_remote,
792 (void *)server, 15, 0,
796 /* Run the protocol */
797 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
800 /* Finalizes the connection to router. Registers a server task to the
801 queue so that we can accept new connections. */
803 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
805 SilcProtocol protocol = (SilcProtocol)context;
806 SilcServerConnAuthInternalContext *ctx =
807 (SilcServerConnAuthInternalContext *)protocol->context;
808 SilcServer server = (SilcServer)ctx->server;
809 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
810 SilcSocketConnection sock = ctx->sock;
811 SilcServerEntry id_entry;
813 SilcServerHBContext hb_context;
814 unsigned char *id_string;
816 SilcIDListData idata;
818 SILC_LOG_DEBUG(("Start"));
820 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
821 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
822 /* Error occured during protocol */
824 silc_free(ctx->dest_id);
825 silc_server_disconnect_remote(server, sock, "Server closed connection: "
826 "Authentication failed");
830 /* Add a task to the queue. This task receives new connections to the
831 server. This task remains on the queue until the end of the program. */
832 if (!server->listenning) {
833 silc_schedule_task_add(server->schedule, server->sock,
834 silc_server_accept_new_connection,
835 (void *)server, 0, 0,
837 SILC_TASK_PRI_NORMAL);
838 server->listenning = TRUE;
841 /* Send NEW_SERVER packet to the router. We will become registered
842 to the SILC network after sending this packet. */
843 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
844 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
845 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
846 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
847 silc_buffer_format(packet,
848 SILC_STR_UI_SHORT(id_len),
849 SILC_STR_UI_XNSTRING(id_string, id_len),
850 SILC_STR_UI_SHORT(strlen(server->server_name)),
851 SILC_STR_UI_XNSTRING(server->server_name,
852 strlen(server->server_name)),
855 /* Send the packet */
856 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
857 packet->data, packet->len, TRUE);
858 silc_buffer_free(packet);
859 silc_free(id_string);
861 SILC_LOG_DEBUG(("Connected to router %s", sock->hostname));
863 /* Add the connected router to local server list */
864 server->standalone = FALSE;
865 id_entry = silc_idlist_add_server(server->local_list, strdup(sock->hostname),
866 SILC_ROUTER, ctx->dest_id, NULL, sock);
869 silc_free(ctx->dest_id);
870 silc_server_disconnect_remote(server, sock, "Server closed connection: "
871 "Authentication failed");
875 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
876 silc_free(sock->user_data);
877 sock->user_data = (void *)id_entry;
878 sock->type = SILC_SOCKET_TYPE_ROUTER;
879 server->id_entry->router = id_entry;
880 server->router = id_entry;
881 idata = (SilcIDListData)sock->user_data;
882 idata->registered = TRUE;
884 /* Perform keepalive. The `hb_context' will be freed automatically
885 when finally calling the silc_socket_free function. XXX hardcoded
887 hb_context = silc_calloc(1, sizeof(*hb_context));
888 hb_context->server = server;
889 silc_socket_set_heartbeat(sock, 600, hb_context,
890 silc_server_perform_heartbeat,
893 /* Register re-key timeout */
894 idata->rekey->timeout = 3600; /* XXX hardcoded */
895 idata->rekey->context = (void *)server;
896 silc_schedule_task_add(server->schedule, sock->sock,
897 silc_server_rekey_callback,
898 (void *)sock, idata->rekey->timeout, 0,
899 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
901 /* If we are router then announce our possible servers. */
902 if (server->server_type == SILC_ROUTER)
903 silc_server_announce_servers(server);
905 /* Announce our clients and channels to the router */
906 silc_server_announce_clients(server);
907 silc_server_announce_channels(server);
910 /* Free the temporary connection data context */
912 silc_free(sconn->remote_host);
916 /* Free the protocol object */
917 silc_protocol_free(protocol);
919 silc_packet_context_free(ctx->packet);
921 silc_ske_free(ctx->ske);
923 sock->protocol = NULL;
926 /* Host lookup callbcak that is called after the incoming connection's
927 IP and FQDN lookup is performed. This will actually check the acceptance
928 of the incoming connection and will register the key exchange protocol
929 for this connection. */
932 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
935 SilcServer server = (SilcServer)context;
936 SilcServerKEInternalContext *proto_ctx;
937 void *cconfig, *sconfig, *rconfig;
938 SilcServerConfigSectionDenyConnection *deny;
941 SILC_LOG_DEBUG(("Start"));
943 /* Check whether we could resolve both IP and FQDN. */
944 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
945 server->params->require_reverse_mapping)) {
946 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
947 sock->hostname ? sock->hostname :
948 sock->ip ? sock->ip : ""));
949 server->stat.conn_failures++;
950 silc_server_disconnect_remote(server, sock,
951 "Server closed connection: Unknown host");
955 /* Register the connection for network input and output. This sets
956 that scheduler will listen for incoming packets for this connection
957 and sets that outgoing packets may be sent to this connection as well.
958 However, this doesn't set the scheduler for outgoing traffic, it
959 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
960 later when outgoing data is available. */
961 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
963 SILC_LOG_INFO(("Incoming connection from %s (%s)", sock->hostname,
966 port = server->sockets[server->sock]->port; /* Listenning port */
968 /* Check whether this connection is denied to connect to us. */
969 deny = silc_server_config_denied_conn(server->config, sock->ip, port);
971 deny = silc_server_config_denied_conn(server->config, sock->hostname,
974 /* The connection is denied */
975 SILC_LOG_INFO(("Connection %s (%s) is denied",
976 sock->hostname, sock->ip));
977 silc_server_disconnect_remote(server, sock, deny->comment ?
979 "Server closed connection: "
980 "Connection refused");
981 server->stat.conn_failures++;
985 /* Check whether we have configred this sort of connection at all. We
986 have to check all configurations since we don't know what type of
987 connection this is. */
988 if (!(cconfig = silc_server_config_find_client_conn(server->config,
990 cconfig = silc_server_config_find_client_conn(server->config,
993 if (!(sconfig = silc_server_config_find_server_conn(server->config,
996 sconfig = silc_server_config_find_server_conn(server->config,
999 if (!(rconfig = silc_server_config_find_router_conn(server->config,
1001 rconfig = silc_server_config_find_router_conn(server->config,
1004 if (!cconfig && !sconfig && !rconfig) {
1005 silc_server_disconnect_remote(server, sock,
1006 "Server closed connection: "
1007 "Connection refused");
1008 server->stat.conn_failures++;
1012 /* The connection is allowed */
1014 /* Allocate internal context for key exchange protocol. This is
1015 sent as context for the protocol. */
1016 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1017 proto_ctx->server = context;
1018 proto_ctx->sock = sock;
1019 proto_ctx->rng = server->rng;
1020 proto_ctx->responder = TRUE;
1021 proto_ctx->cconfig = cconfig;
1022 proto_ctx->sconfig = sconfig;
1023 proto_ctx->rconfig = rconfig;
1025 /* Prepare the connection for key exchange protocol. We allocate the
1026 protocol but will not start it yet. The connector will be the
1027 initiator of the protocol thus we will wait for initiation from
1028 there before we start the protocol. */
1029 server->stat.auth_attempts++;
1030 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1031 &sock->protocol, proto_ctx,
1032 silc_server_accept_new_connection_second);
1034 /* Register a timeout task that will be executed if the connector
1035 will not start the key exchange protocol within 60 seconds. For
1036 now, this is a hard coded limit. After 60 secs the connection will
1037 be closed if the key exchange protocol has not been started. */
1038 proto_ctx->timeout_task =
1039 silc_schedule_task_add(server->schedule, sock->sock,
1040 silc_server_timeout_remote,
1046 /* Accepts new connections to the server. Accepting new connections are
1047 done in three parts to make it async. */
1049 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1051 SilcServer server = (SilcServer)context;
1052 SilcSocketConnection newsocket;
1055 SILC_LOG_DEBUG(("Accepting new connection"));
1057 server->stat.conn_attempts++;
1059 sock = silc_net_accept_connection(server->sock);
1061 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1062 server->stat.conn_failures++;
1066 /* Check max connections */
1067 if (sock > SILC_SERVER_MAX_CONNECTIONS) {
1068 SILC_LOG_ERROR(("Refusing connection, server is full"));
1069 server->stat.conn_failures++;
1073 /* Set socket options */
1074 silc_net_set_socket_nonblock(sock);
1075 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1077 /* We don't create a ID yet, since we don't know what type of connection
1078 this is yet. But, we do add the connection to the socket table. */
1079 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1080 server->sockets[sock] = newsocket;
1082 /* Perform asynchronous host lookup. This will lookup the IP and the
1083 FQDN of the remote connection. After the lookup is done the connection
1084 is accepted further. */
1085 silc_socket_host_lookup(newsocket, TRUE,
1086 silc_server_accept_new_connection_lookup, context,
1090 /* Second part of accepting new connection. Key exchange protocol has been
1091 performed and now it is time to do little connection authentication
1092 protocol to figure out whether this connection is client or server
1093 and whether it has right to access this server (especially server
1094 connections needs to be authenticated). */
1096 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1098 SilcProtocol protocol = (SilcProtocol)context;
1099 SilcServerKEInternalContext *ctx =
1100 (SilcServerKEInternalContext *)protocol->context;
1101 SilcServer server = (SilcServer)ctx->server;
1102 SilcSocketConnection sock = ctx->sock;
1103 SilcServerConnAuthInternalContext *proto_ctx;
1105 SILC_LOG_DEBUG(("Start"));
1107 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1108 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1109 /* Error occured during protocol */
1110 silc_protocol_free(protocol);
1111 sock->protocol = NULL;
1112 silc_ske_free_key_material(ctx->keymat);
1114 silc_packet_context_free(ctx->packet);
1116 silc_ske_free(ctx->ske);
1118 silc_free(ctx->dest_id);
1120 silc_schedule_task_del_by_callback(server->schedule,
1121 silc_server_failure_callback);
1122 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1123 "Key exchange failed");
1124 server->stat.auth_failures++;
1128 /* We now have the key material as the result of the key exchange
1129 protocol. Take the key material into use. Free the raw key material
1130 as soon as we've set them into use. */
1131 if (!silc_server_protocol_ke_set_keys(ctx->ske, ctx->sock, ctx->keymat,
1132 ctx->ske->prop->cipher,
1133 ctx->ske->prop->pkcs,
1134 ctx->ske->prop->hash,
1135 ctx->ske->prop->hmac,
1136 ctx->ske->prop->group,
1138 silc_protocol_free(protocol);
1139 sock->protocol = NULL;
1140 silc_ske_free_key_material(ctx->keymat);
1142 silc_packet_context_free(ctx->packet);
1144 silc_ske_free(ctx->ske);
1146 silc_free(ctx->dest_id);
1148 silc_schedule_task_del_by_callback(server->schedule,
1149 silc_server_failure_callback);
1150 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1151 "Key exchange failed");
1152 server->stat.auth_failures++;
1155 silc_ske_free_key_material(ctx->keymat);
1157 /* Allocate internal context for the authentication protocol. This
1158 is sent as context for the protocol. */
1159 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1160 proto_ctx->server = (void *)server;
1161 proto_ctx->sock = sock;
1162 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1163 proto_ctx->responder = TRUE;
1164 proto_ctx->dest_id_type = ctx->dest_id_type;
1165 proto_ctx->dest_id = ctx->dest_id;
1166 proto_ctx->cconfig = ctx->cconfig;
1167 proto_ctx->sconfig = ctx->sconfig;
1168 proto_ctx->rconfig = ctx->rconfig;
1170 /* Free old protocol as it is finished now */
1171 silc_protocol_free(protocol);
1173 silc_packet_context_free(ctx->packet);
1175 sock->protocol = NULL;
1177 /* Allocate the authentication protocol. This is allocated here
1178 but we won't start it yet. We will be receiving party of this
1179 protocol thus we will wait that connecting party will make
1180 their first move. */
1181 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1182 &sock->protocol, proto_ctx,
1183 silc_server_accept_new_connection_final);
1185 /* Register timeout task. If the protocol is not executed inside
1186 this timelimit the connection will be terminated. Currently
1187 this is 60 seconds and is hard coded limit (XXX). */
1188 proto_ctx->timeout_task =
1189 silc_schedule_task_add(server->schedule, sock->sock,
1190 silc_server_timeout_remote,
1191 (void *)server, 60, 0,
1196 /* Final part of accepting new connection. The connection has now
1197 been authenticated and keys has been exchanged. We also know whether
1198 this is client or server connection. */
1200 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1202 SilcProtocol protocol = (SilcProtocol)context;
1203 SilcServerConnAuthInternalContext *ctx =
1204 (SilcServerConnAuthInternalContext *)protocol->context;
1205 SilcServer server = (SilcServer)ctx->server;
1206 SilcSocketConnection sock = ctx->sock;
1207 SilcServerHBContext hb_context;
1208 void *id_entry = NULL;
1210 SILC_LOG_DEBUG(("Start"));
1212 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1213 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1214 /* Error occured during protocol */
1215 silc_protocol_free(protocol);
1216 sock->protocol = NULL;
1218 silc_packet_context_free(ctx->packet);
1220 silc_ske_free(ctx->ske);
1222 silc_free(ctx->dest_id);
1225 sock->protocol = NULL;
1226 silc_schedule_task_del_by_callback(server->schedule,
1227 silc_server_failure_callback);
1228 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1229 "Authentication failed");
1230 server->stat.auth_failures++;
1234 switch(ctx->conn_type) {
1235 case SILC_SOCKET_TYPE_CLIENT:
1237 SilcClientEntry client;
1239 SILC_LOG_DEBUG(("Remote host is client"));
1240 SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
1243 /* Add the client to the client ID cache. The nickname and Client ID
1244 and other information is created after we have received NEW_CLIENT
1245 packet from client. */
1246 client = silc_idlist_add_client(server->local_list,
1247 NULL, NULL, NULL, NULL, NULL, sock);
1249 SILC_LOG_ERROR(("Could not add new client to cache"));
1250 silc_free(sock->user_data);
1251 silc_server_disconnect_remote(server, sock,
1252 "Server closed connection: "
1253 "Authentication failed");
1254 server->stat.auth_failures++;
1259 server->stat.my_clients++;
1260 server->stat.clients++;
1261 if (server->server_type == SILC_ROUTER)
1262 server->stat.cell_clients++;
1264 id_entry = (void *)client;
1267 case SILC_SOCKET_TYPE_SERVER:
1268 case SILC_SOCKET_TYPE_ROUTER:
1270 SilcServerEntry new_server;
1271 SilcServerConfigSectionServerConnection *conn =
1272 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1273 ctx->sconfig : ctx->rconfig;
1275 SILC_LOG_DEBUG(("Remote host is %s",
1276 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1277 "server" : "router"));
1278 SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
1279 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1280 "server" : "router"));
1282 /* Add the server into server cache. The server name and Server ID
1283 is updated after we have received NEW_SERVER packet from the
1284 server. We mark ourselves as router for this server if we really
1287 silc_idlist_add_server(server->local_list, NULL,
1288 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1289 SILC_SERVER : SILC_ROUTER, NULL,
1290 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1291 server->id_entry : NULL, sock);
1293 SILC_LOG_ERROR(("Could not add new server to cache"));
1294 silc_free(sock->user_data);
1295 silc_server_disconnect_remote(server, sock,
1296 "Server closed connection: "
1297 "Authentication failed");
1298 server->stat.auth_failures++;
1303 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1304 server->stat.my_servers++;
1306 server->stat.my_routers++;
1307 server->stat.servers++;
1309 id_entry = (void *)new_server;
1311 /* Check whether this connection is to be our primary router connection
1312 if we dont' already have the primary route. */
1313 if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1314 if (silc_server_config_is_primary_route(server->config) &&
1318 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1319 server->standalone = FALSE;
1320 if (!server->id_entry->router) {
1321 server->id_entry->router = id_entry;
1322 server->router = id_entry;
1332 sock->type = ctx->conn_type;
1334 /* Add the common data structure to the ID entry. */
1336 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1338 /* Add to sockets internal pointer for fast referencing */
1339 silc_free(sock->user_data);
1340 sock->user_data = id_entry;
1342 /* Connection has been fully established now. Everything is ok. */
1343 SILC_LOG_DEBUG(("New connection authenticated"));
1345 /* Perform keepalive. The `hb_context' will be freed automatically
1346 when finally calling the silc_socket_free function. XXX hardcoded
1348 hb_context = silc_calloc(1, sizeof(*hb_context));
1349 hb_context->server = server;
1350 silc_socket_set_heartbeat(sock, 600, hb_context,
1351 silc_server_perform_heartbeat,
1355 silc_schedule_task_del_by_callback(server->schedule,
1356 silc_server_failure_callback);
1357 silc_protocol_free(protocol);
1359 silc_packet_context_free(ctx->packet);
1361 silc_ske_free(ctx->ske);
1363 silc_free(ctx->dest_id);
1365 sock->protocol = NULL;
1368 /* This function is used to read packets from network and send packets to
1369 network. This is usually a generic task. */
1371 SILC_TASK_CALLBACK(silc_server_packet_process)
1373 SilcServer server = (SilcServer)context;
1374 SilcSocketConnection sock = server->sockets[fd];
1375 SilcIDListData idata;
1376 SilcCipher cipher = NULL;
1377 SilcHmac hmac = NULL;
1383 SILC_LOG_DEBUG(("Processing packet"));
1385 /* Packet sending */
1387 if (type == SILC_TASK_WRITE) {
1388 /* Do not send data to disconnected connection */
1389 if (SILC_IS_DISCONNECTED(sock))
1392 server->stat.packets_sent++;
1394 if (sock->outbuf->data - sock->outbuf->head)
1395 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1397 /* Send the packet */
1398 ret = silc_packet_send(sock, TRUE);
1400 /* If returned -2 could not write to connection now, will do
1406 SILC_LOG_ERROR(("Error sending packet to connection "
1407 "%s:%d [%s]", sock->hostname, sock->port,
1408 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1409 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1410 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1415 /* The packet has been sent and now it is time to set the connection
1416 back to only for input. When there is again some outgoing data
1417 available for this connection it will be set for output as well.
1418 This call clears the output setting and sets it only for input. */
1419 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1420 SILC_UNSET_OUTBUF_PENDING(sock);
1422 silc_buffer_clear(sock->outbuf);
1426 /* Packet receiving */
1428 /* Read some data from connection */
1429 ret = silc_packet_receive(sock);
1433 SILC_LOG_ERROR(("Error receiving packet from connection "
1434 "%s:%d [%s]", sock->hostname, sock->port,
1435 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1436 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1437 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1444 SILC_LOG_DEBUG(("Read EOF"));
1446 /* If connection is disconnecting already we will finally
1447 close the connection */
1448 if (SILC_IS_DISCONNECTING(sock)) {
1449 if (sock->user_data)
1450 silc_server_free_sock_user_data(server, sock);
1451 silc_server_close_connection(server, sock);
1455 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1456 SILC_SET_DISCONNECTING(sock);
1458 /* If the closed connection was our primary router connection the
1459 start re-connecting phase. */
1460 if (!server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER &&
1461 sock == server->router->connection)
1462 silc_schedule_task_add(server->schedule, 0,
1463 silc_server_connect_to_router,
1466 SILC_TASK_PRI_NORMAL);
1468 if (sock->user_data)
1469 silc_server_free_sock_user_data(server, sock);
1470 silc_server_close_connection(server, sock);
1474 /* If connection is disconnecting or disconnected we will ignore
1476 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1477 SILC_LOG_DEBUG(("Ignoring read data from disonnected connection"));
1481 server->stat.packets_received++;
1483 /* Get keys and stuff from ID entry */
1484 idata = (SilcIDListData)sock->user_data;
1486 idata->last_receive = time(NULL);
1487 cipher = idata->receive_key;
1488 hmac = idata->hmac_receive;
1491 /* Process the packet. This will call the parser that will then
1492 decrypt and parse the packet. */
1493 silc_packet_receive_process(sock, cipher, hmac, silc_server_packet_parse,
1497 /* Callback function that the silc_packet_decrypt will call to make the
1498 decision whether the packet is normal or special packet. We will
1499 return TRUE if it is normal and FALSE if it is special */
1501 static int silc_server_packet_decrypt_check(SilcPacketType packet_type,
1503 SilcPacketContext *packet,
1506 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1507 SilcServer server = (SilcServer)parse_ctx->context;
1509 /* Packet is normal packet, if:
1511 1) packet is private message packet and does not have private key set
1512 2) is other packet than channel message packet
1513 3) is channel message packet and remote is router and we are router
1515 all other packets are special packets
1518 if (packet_type == SILC_PACKET_PRIVATE_MESSAGE &&
1519 (buffer->data[2] & SILC_PACKET_FLAG_PRIVMSG_KEY))
1522 if (packet_type != SILC_PACKET_CHANNEL_MESSAGE ||
1523 (packet_type == SILC_PACKET_CHANNEL_MESSAGE &&
1524 parse_ctx->sock->type == SILC_SOCKET_TYPE_ROUTER &&
1525 server->server_type == SILC_ROUTER))
1531 /* Parses whole packet, received earlier. */
1533 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1535 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1536 SilcServer server = (SilcServer)parse_ctx->context;
1537 SilcSocketConnection sock = parse_ctx->sock;
1538 SilcPacketContext *packet = parse_ctx->packet;
1539 SilcIDListData idata = (SilcIDListData)sock->user_data;
1542 SILC_LOG_DEBUG(("Start"));
1544 /* Decrypt the received packet */
1545 ret = silc_packet_decrypt(idata ? idata->receive_key : NULL,
1546 idata ? idata->hmac_receive : NULL,
1547 packet->buffer, packet,
1548 silc_server_packet_decrypt_check, parse_ctx);
1550 SILC_LOG_WARNING(("Packet decryption failed for connection "
1551 "%s:%d [%s]", sock->hostname, sock->port,
1552 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1553 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1554 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1560 /* Parse the packet. Packet type is returned. */
1561 ret = silc_packet_parse(packet);
1563 /* Parse the packet header in special way as this is "special"
1565 ret = silc_packet_parse_special(packet);
1568 if (ret == SILC_PACKET_NONE)
1571 /* Check that the the current client ID is same as in the client's packet. */
1572 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1573 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1574 if (client && client->id) {
1575 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1576 packet->src_id_type);
1577 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1585 if (server->server_type == SILC_ROUTER) {
1586 /* Route the packet if it is not destined to us. Other ID types but
1587 server are handled separately after processing them. */
1588 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1589 packet->dst_id_type == SILC_ID_SERVER &&
1590 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1591 memcmp(packet->dst_id, server->id_string, packet->dst_id_len)) {
1593 /* Route the packet to fastest route for the destination ID */
1594 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1595 packet->dst_id_type);
1598 silc_server_packet_route(server,
1599 silc_server_route_get(server, id,
1600 packet->dst_id_type),
1607 /* Parse the incoming packet type */
1608 silc_server_packet_parse_type(server, sock, packet);
1610 if (server->server_type == SILC_ROUTER) {
1611 /* Broadcast packet if it is marked as broadcast packet and it is
1612 originated from router and we are router. */
1613 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1614 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1615 !server->standalone) {
1616 silc_server_packet_broadcast(server, server->router->connection, packet);
1621 /* silc_buffer_clear(sock->inbuf); */
1622 silc_packet_context_free(packet);
1623 silc_free(parse_ctx);
1626 /* Parser callback called by silc_packet_receive_process. This merely
1627 registers timeout that will handle the actual parsing when appropriate. */
1629 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1631 SilcServer server = (SilcServer)parser_context->context;
1632 SilcSocketConnection sock = parser_context->sock;
1634 switch (sock->type) {
1635 case SILC_SOCKET_TYPE_UNKNOWN:
1636 case SILC_SOCKET_TYPE_CLIENT:
1637 /* Parse the packet with timeout */
1638 silc_schedule_task_add(server->schedule, sock->sock,
1639 silc_server_packet_parse_real,
1640 (void *)parser_context, 0, 100000,
1642 SILC_TASK_PRI_NORMAL);
1644 case SILC_SOCKET_TYPE_SERVER:
1645 case SILC_SOCKET_TYPE_ROUTER:
1646 /* Packets from servers are parsed as soon as possible */
1647 silc_schedule_task_add(server->schedule, sock->sock,
1648 silc_server_packet_parse_real,
1649 (void *)parser_context, 0, 1,
1651 SILC_TASK_PRI_NORMAL);
1658 /* Parses the packet type and calls what ever routines the packet type
1659 requires. This is done for all incoming packets. */
1661 void silc_server_packet_parse_type(SilcServer server,
1662 SilcSocketConnection sock,
1663 SilcPacketContext *packet)
1665 SilcPacketType type = packet->type;
1667 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1669 /* Parse the packet type */
1671 case SILC_PACKET_DISCONNECT:
1672 SILC_LOG_DEBUG(("Disconnect packet"));
1673 if (packet->flags & SILC_PACKET_FLAG_LIST)
1677 case SILC_PACKET_SUCCESS:
1679 * Success received for something. For now we can have only
1680 * one protocol for connection executing at once hence this
1681 * success message is for whatever protocol is executing currently.
1683 SILC_LOG_DEBUG(("Success packet"));
1684 if (packet->flags & SILC_PACKET_FLAG_LIST)
1687 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1690 case SILC_PACKET_FAILURE:
1692 * Failure received for something. For now we can have only
1693 * one protocol for connection executing at once hence this
1694 * failure message is for whatever protocol is executing currently.
1696 SILC_LOG_DEBUG(("Failure packet"));
1697 if (packet->flags & SILC_PACKET_FLAG_LIST)
1699 if (sock->protocol) {
1700 SilcServerFailureContext f;
1701 f = silc_calloc(1, sizeof(*f));
1705 /* We will wait 5 seconds to process this failure packet */
1706 silc_schedule_task_add(server->schedule, sock->sock,
1707 silc_server_failure_callback, (void *)f, 5, 0,
1708 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1712 case SILC_PACKET_REJECT:
1713 SILC_LOG_DEBUG(("Reject packet"));
1714 if (packet->flags & SILC_PACKET_FLAG_LIST)
1719 case SILC_PACKET_NOTIFY:
1721 * Received notify packet. Server can receive notify packets from
1722 * router. Server then relays the notify messages to clients if needed.
1724 SILC_LOG_DEBUG(("Notify packet"));
1725 if (packet->flags & SILC_PACKET_FLAG_LIST)
1726 silc_server_notify_list(server, sock, packet);
1728 silc_server_notify(server, sock, packet);
1734 case SILC_PACKET_CHANNEL_MESSAGE:
1736 * Received channel message. Channel messages are special packets
1737 * (although probably most common ones) thus they are handled
1740 SILC_LOG_DEBUG(("Channel Message packet"));
1741 if (packet->flags & SILC_PACKET_FLAG_LIST)
1743 silc_server_channel_message(server, sock, packet);
1746 case SILC_PACKET_CHANNEL_KEY:
1748 * Received key for channel. As channels are created by the router
1749 * the keys are as well. We will distribute the key to all of our
1750 * locally connected clients on the particular channel. Router
1751 * never receives this channel and thus is ignored.
1753 SILC_LOG_DEBUG(("Channel Key packet"));
1754 if (packet->flags & SILC_PACKET_FLAG_LIST)
1756 silc_server_channel_key(server, sock, packet);
1762 case SILC_PACKET_COMMAND:
1764 * Recived command. Processes the command request and allocates the
1765 * command context and calls the command.
1767 SILC_LOG_DEBUG(("Command packet"));
1768 if (packet->flags & SILC_PACKET_FLAG_LIST)
1770 silc_server_command_process(server, sock, packet);
1773 case SILC_PACKET_COMMAND_REPLY:
1775 * Received command reply packet. Received command reply to command. It
1776 * may be reply to command sent by us or reply to command sent by client
1777 * that we've routed further.
1779 SILC_LOG_DEBUG(("Command Reply packet"));
1780 if (packet->flags & SILC_PACKET_FLAG_LIST)
1782 silc_server_command_reply(server, sock, packet);
1786 * Private Message packets
1788 case SILC_PACKET_PRIVATE_MESSAGE:
1790 * Received private message packet. The packet is coming from either
1793 SILC_LOG_DEBUG(("Private Message packet"));
1794 if (packet->flags & SILC_PACKET_FLAG_LIST)
1796 silc_server_private_message(server, sock, packet);
1799 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1801 * Private message key packet.
1803 if (packet->flags & SILC_PACKET_FLAG_LIST)
1805 silc_server_private_message_key(server, sock, packet);
1809 * Key Exchange protocol packets
1811 case SILC_PACKET_KEY_EXCHANGE:
1812 SILC_LOG_DEBUG(("KE packet"));
1813 if (packet->flags & SILC_PACKET_FLAG_LIST)
1816 if (sock->protocol && sock->protocol->protocol &&
1817 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1819 SilcServerKEInternalContext *proto_ctx =
1820 (SilcServerKEInternalContext *)sock->protocol->context;
1822 proto_ctx->packet = silc_packet_context_dup(packet);
1824 /* Let the protocol handle the packet */
1825 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
1827 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1828 "protocol active, packet dropped."));
1832 case SILC_PACKET_KEY_EXCHANGE_1:
1833 SILC_LOG_DEBUG(("KE 1 packet"));
1834 if (packet->flags & SILC_PACKET_FLAG_LIST)
1837 if (sock->protocol && sock->protocol->protocol &&
1838 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1839 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
1841 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
1842 SilcServerRekeyInternalContext *proto_ctx =
1843 (SilcServerRekeyInternalContext *)sock->protocol->context;
1845 if (proto_ctx->packet)
1846 silc_packet_context_free(proto_ctx->packet);
1848 proto_ctx->packet = silc_packet_context_dup(packet);
1850 /* Let the protocol handle the packet */
1851 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1853 SilcServerKEInternalContext *proto_ctx =
1854 (SilcServerKEInternalContext *)sock->protocol->context;
1856 if (proto_ctx->packet)
1857 silc_packet_context_free(proto_ctx->packet);
1859 proto_ctx->packet = silc_packet_context_dup(packet);
1860 proto_ctx->dest_id_type = packet->src_id_type;
1861 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1862 packet->src_id_type);
1863 if (!proto_ctx->dest_id)
1866 /* Let the protocol handle the packet */
1867 silc_protocol_execute(sock->protocol, server->schedule,
1871 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1872 "protocol active, packet dropped."));
1876 case SILC_PACKET_KEY_EXCHANGE_2:
1877 SILC_LOG_DEBUG(("KE 2 packet"));
1878 if (packet->flags & SILC_PACKET_FLAG_LIST)
1881 if (sock->protocol && sock->protocol->protocol &&
1882 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1883 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
1885 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
1886 SilcServerRekeyInternalContext *proto_ctx =
1887 (SilcServerRekeyInternalContext *)sock->protocol->context;
1889 if (proto_ctx->packet)
1890 silc_packet_context_free(proto_ctx->packet);
1892 proto_ctx->packet = silc_packet_context_dup(packet);
1894 /* Let the protocol handle the packet */
1895 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1897 SilcServerKEInternalContext *proto_ctx =
1898 (SilcServerKEInternalContext *)sock->protocol->context;
1900 if (proto_ctx->packet)
1901 silc_packet_context_free(proto_ctx->packet);
1903 proto_ctx->packet = silc_packet_context_dup(packet);
1904 proto_ctx->dest_id_type = packet->src_id_type;
1905 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1906 packet->src_id_type);
1907 if (!proto_ctx->dest_id)
1910 /* Let the protocol handle the packet */
1911 silc_protocol_execute(sock->protocol, server->schedule,
1915 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1916 "protocol active, packet dropped."));
1920 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1922 * Connection authentication request packet. When we receive this packet
1923 * we will send to the other end information about our mandatory
1924 * authentication method for the connection. This packet maybe received
1927 SILC_LOG_DEBUG(("Connection authentication request packet"));
1928 if (packet->flags & SILC_PACKET_FLAG_LIST)
1930 silc_server_connection_auth_request(server, sock, packet);
1934 * Connection Authentication protocol packets
1936 case SILC_PACKET_CONNECTION_AUTH:
1937 /* Start of the authentication protocol. We receive here the
1938 authentication data and will verify it. */
1939 SILC_LOG_DEBUG(("Connection auth packet"));
1940 if (packet->flags & SILC_PACKET_FLAG_LIST)
1943 if (sock->protocol && sock->protocol->protocol->type
1944 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1946 SilcServerConnAuthInternalContext *proto_ctx =
1947 (SilcServerConnAuthInternalContext *)sock->protocol->context;
1949 proto_ctx->packet = silc_packet_context_dup(packet);
1951 /* Let the protocol handle the packet */
1952 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1954 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1955 "protocol active, packet dropped."));
1959 case SILC_PACKET_NEW_ID:
1961 * Received New ID packet. This includes some new ID that has been
1962 * created. It may be for client, server or channel. This is the way
1963 * to distribute information about new registered entities in the
1966 SILC_LOG_DEBUG(("New ID packet"));
1967 if (packet->flags & SILC_PACKET_FLAG_LIST)
1968 silc_server_new_id_list(server, sock, packet);
1970 silc_server_new_id(server, sock, packet);
1973 case SILC_PACKET_NEW_CLIENT:
1975 * Received new client packet. This includes client information that
1976 * we will use to create initial client ID. After creating new
1977 * ID we will send it to the client.
1979 SILC_LOG_DEBUG(("New Client packet"));
1980 if (packet->flags & SILC_PACKET_FLAG_LIST)
1982 silc_server_new_client(server, sock, packet);
1985 case SILC_PACKET_NEW_SERVER:
1987 * Received new server packet. This includes Server ID and some other
1988 * information that we may save. This is received after server has
1991 SILC_LOG_DEBUG(("New Server packet"));
1992 if (packet->flags & SILC_PACKET_FLAG_LIST)
1994 silc_server_new_server(server, sock, packet);
1997 case SILC_PACKET_NEW_CHANNEL:
1999 * Received new channel packet. Information about new channel in the
2000 * network are distributed using this packet.
2002 SILC_LOG_DEBUG(("New Channel packet"));
2003 if (packet->flags & SILC_PACKET_FLAG_LIST)
2004 silc_server_new_channel_list(server, sock, packet);
2006 silc_server_new_channel(server, sock, packet);
2009 case SILC_PACKET_HEARTBEAT:
2011 * Received heartbeat.
2013 SILC_LOG_DEBUG(("Heartbeat packet"));
2014 if (packet->flags & SILC_PACKET_FLAG_LIST)
2018 case SILC_PACKET_KEY_AGREEMENT:
2020 * Received heartbeat.
2022 SILC_LOG_DEBUG(("Key agreement packet"));
2023 if (packet->flags & SILC_PACKET_FLAG_LIST)
2025 silc_server_key_agreement(server, sock, packet);
2028 case SILC_PACKET_REKEY:
2030 * Received re-key packet. The sender wants to regenerate the session
2033 SILC_LOG_DEBUG(("Re-key packet"));
2034 if (packet->flags & SILC_PACKET_FLAG_LIST)
2036 silc_server_rekey(server, sock, packet);
2039 case SILC_PACKET_REKEY_DONE:
2041 * The re-key is done.
2043 SILC_LOG_DEBUG(("Re-key done packet"));
2044 if (packet->flags & SILC_PACKET_FLAG_LIST)
2047 if (sock->protocol && sock->protocol->protocol &&
2048 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2050 SilcServerRekeyInternalContext *proto_ctx =
2051 (SilcServerRekeyInternalContext *)sock->protocol->context;
2053 if (proto_ctx->packet)
2054 silc_packet_context_free(proto_ctx->packet);
2056 proto_ctx->packet = silc_packet_context_dup(packet);
2058 /* Let the protocol handle the packet */
2059 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2061 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2062 "protocol active, packet dropped."));
2067 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2073 /* Creates connection to a remote router. */
2075 void silc_server_create_connection(SilcServer server,
2076 char *remote_host, uint32 port)
2078 SilcServerConnection sconn;
2080 /* Allocate connection object for hold connection specific stuff. */
2081 sconn = silc_calloc(1, sizeof(*sconn));
2082 sconn->server = server;
2083 sconn->remote_host = strdup(remote_host);
2084 sconn->remote_port = port;
2086 silc_schedule_task_add(server->schedule, 0,
2087 silc_server_connect_router,
2088 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2089 SILC_TASK_PRI_NORMAL);
2092 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2094 silc_socket_free((SilcSocketConnection)context);
2097 /* Closes connection to socket connection */
2099 void silc_server_close_connection(SilcServer server,
2100 SilcSocketConnection sock)
2102 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2104 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2105 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2106 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2109 /* We won't listen for this connection anymore */
2110 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2112 /* Unregister all tasks */
2113 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2115 /* Close the actual connection */
2116 silc_net_close_connection(sock->sock);
2117 server->sockets[sock->sock] = NULL;
2119 /* If sock->user_data is NULL then we'll check for active protocols
2120 here since the silc_server_free_sock_user_data has not been called
2121 for this connection. */
2122 if (!sock->user_data) {
2123 /* If any protocol is active cancel its execution. It will call
2124 the final callback which will finalize the disconnection. */
2125 if (sock->protocol) {
2126 silc_protocol_cancel(sock->protocol, server->schedule);
2127 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2128 silc_protocol_execute_final(sock->protocol, server->schedule);
2129 sock->protocol = NULL;
2134 silc_schedule_task_add(server->schedule, 0,
2135 silc_server_close_connection_final,
2136 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2137 SILC_TASK_PRI_NORMAL);
2140 /* Sends disconnect message to remote connection and disconnects the
2143 void silc_server_disconnect_remote(SilcServer server,
2144 SilcSocketConnection sock,
2145 const char *fmt, ...)
2148 unsigned char buf[4096];
2153 memset(buf, 0, sizeof(buf));
2155 vsprintf(buf, fmt, ap);
2158 SILC_LOG_DEBUG(("Disconnecting remote host"));
2160 /* Notify remote end that the conversation is over. The notify message
2161 is tried to be sent immediately. */
2162 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2163 buf, strlen(buf), TRUE);
2165 /* Mark the connection to be disconnected */
2166 SILC_SET_DISCONNECTED(sock);
2167 silc_server_close_connection(server, sock);
2172 SilcClientEntry client;
2173 } *FreeClientInternal;
2175 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2177 FreeClientInternal i = (FreeClientInternal)context;
2179 silc_idlist_del_data(i->client);
2180 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2184 /* Frees client data and notifies about client's signoff. */
2186 void silc_server_free_client_data(SilcServer server,
2187 SilcSocketConnection sock,
2188 SilcClientEntry client,
2192 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2194 /* If there is pending outgoing data for the client then purge it
2195 to the network before removing the client entry. */
2196 if (sock && SILC_IS_OUTBUF_PENDING(sock) &&
2197 (SILC_IS_DISCONNECTED(sock) == FALSE)) {
2198 server->stat.packets_sent++;
2200 if (sock->outbuf->data - sock->outbuf->head)
2201 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
2203 silc_packet_send(sock, TRUE);
2205 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, sock->sock);
2206 SILC_UNSET_OUTBUF_PENDING(sock);
2207 silc_buffer_clear(sock->outbuf);
2210 /* Send SIGNOFF notify to routers. */
2211 if (notify && !server->standalone && server->router)
2212 silc_server_send_notify_signoff(server, server->router->connection,
2213 server->server_type == SILC_SERVER ?
2214 FALSE : TRUE, client->id, signoff);
2216 /* Remove client from all channels */
2218 silc_server_remove_from_channels(server, NULL, client,
2219 TRUE, signoff, TRUE);
2221 silc_server_remove_from_channels(server, NULL, client,
2222 FALSE, NULL, FALSE);
2224 /* We will not delete the client entry right away. We will take it
2225 into history (for WHOWAS command) for 5 minutes */
2228 silc_schedule_task_add(server->schedule, 0,
2229 silc_server_free_client_data_timeout,
2231 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2232 client->data.registered = FALSE;
2233 client->router = NULL;
2234 client->connection = NULL;
2236 /* Free the client entry and everything in it */
2237 server->stat.my_clients--;
2238 server->stat.clients--;
2239 if (server->server_type == SILC_ROUTER)
2240 server->stat.cell_clients--;
2243 /* Frees user_data pointer from socket connection object. This also sends
2244 appropriate notify packets to the network to inform about leaving
2247 void silc_server_free_sock_user_data(SilcServer server,
2248 SilcSocketConnection sock)
2250 SILC_LOG_DEBUG(("Start"));
2252 switch(sock->type) {
2253 case SILC_SOCKET_TYPE_CLIENT:
2255 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2256 silc_server_free_client_data(server, sock, user_data, TRUE, NULL);
2259 case SILC_SOCKET_TYPE_SERVER:
2260 case SILC_SOCKET_TYPE_ROUTER:
2262 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2264 /* Free all client entries that this server owns as they will
2265 become invalid now as well. */
2267 silc_server_remove_clients_by_server(server, user_data, TRUE);
2269 /* If this was our primary router connection then we're lost to
2270 the outside world. */
2271 if (server->router == user_data) {
2272 server->id_entry->router = NULL;
2273 server->router = NULL;
2274 server->standalone = TRUE;
2277 /* Free the server entry */
2278 silc_idlist_del_data(user_data);
2279 silc_idlist_del_server(server->local_list, user_data);
2280 server->stat.my_servers--;
2281 server->stat.servers--;
2282 if (server->server_type == SILC_ROUTER)
2283 server->stat.cell_servers--;
2288 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2290 silc_idlist_del_data(user_data);
2291 silc_free(user_data);
2296 /* If any protocol is active cancel its execution */
2297 if (sock->protocol) {
2298 silc_protocol_cancel(sock->protocol, server->schedule);
2299 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2300 silc_protocol_execute_final(sock->protocol, server->schedule);
2301 sock->protocol = NULL;
2304 sock->user_data = NULL;
2307 /* Removes the client from channels and possibly removes the channels
2308 as well. After removing those channels that exist, their channel
2309 keys are regnerated. This is called only by the function
2310 silc_server_remove_clients_by_server. */
2312 static void silc_server_remove_clients_channels(SilcServer server,
2313 SilcSocketConnection sock,
2314 SilcClientEntry client,
2315 SilcHashTable channels)
2317 SilcChannelEntry channel;
2318 SilcChannelClientEntry chl;
2319 SilcHashTableList htl;
2322 SILC_LOG_DEBUG(("Start"));
2324 if (!client || !client->id)
2327 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2329 /* Remove the client from all channels. The client is removed from
2330 the channels' user list. */
2331 silc_hash_table_list(client->channels, &htl);
2332 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2333 channel = chl->channel;
2335 /* Remove channel from client's channel list */
2336 silc_hash_table_del(client->channels, channel);
2338 /* Remove channel if there is no users anymore */
2339 if (server->server_type == SILC_ROUTER &&
2340 silc_hash_table_count(channel->user_list) < 2) {
2342 if (silc_hash_table_find(channels, channel, NULL, NULL))
2343 silc_hash_table_del(channels, channel);
2346 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2348 if (!silc_idlist_del_channel(server->local_list, channel))
2349 silc_idlist_del_channel(server->global_list, channel);
2350 server->stat.my_channels--;
2354 /* Remove client from channel's client list */
2355 silc_hash_table_del(channel->user_list, chl->client);
2357 server->stat.my_chanclients--;
2359 /* If there is no global users on the channel anymore mark the channel
2360 as local channel. Do not check if the removed client is local client. */
2361 if (server->server_type == SILC_SERVER && channel->global_users &&
2362 chl->client->router && !silc_server_channel_has_global(channel))
2363 channel->global_users = FALSE;
2365 /* If there is not at least one local user on the channel then we don't
2366 need the channel entry anymore, we can remove it safely. */
2367 if (server->server_type == SILC_SERVER &&
2368 !silc_server_channel_has_local(channel)) {
2370 if (silc_hash_table_find(channels, channel, NULL, NULL))
2371 silc_hash_table_del(channels, channel);
2374 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2376 if (channel->founder_key) {
2377 /* The founder auth data exists, do not remove the channel entry */
2378 SilcChannelClientEntry chl2;
2379 SilcHashTableList htl2;
2383 silc_hash_table_list(channel->user_list, &htl2);
2384 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2385 silc_hash_table_del(chl2->client->channels, channel);
2386 silc_hash_table_del(channel->user_list, chl2->client);
2392 /* Remove the channel entry */
2393 if (!silc_idlist_del_channel(server->local_list, channel))
2394 silc_idlist_del_channel(server->global_list, channel);
2395 server->stat.my_channels--;
2399 /* Add the channel to the the channels list to regenerate the
2401 if (!silc_hash_table_find(channels, channel, NULL, NULL))
2402 silc_hash_table_add(channels, channel, channel);
2405 silc_buffer_free(clidp);
2408 /* This function is used to remove all client entries by the server `entry'.
2409 This is called when the connection is lost to the server. In this case
2410 we must invalidate all the client entries owned by the server `entry'.
2411 If the `server_signoff' is TRUE then the SERVER_SIGNOFF notify is
2412 distributed to our local clients. */
2414 int silc_server_remove_clients_by_server(SilcServer server,
2415 SilcServerEntry entry,
2418 SilcIDCacheList list = NULL;
2419 SilcIDCacheEntry id_cache = NULL;
2420 SilcClientEntry client = NULL;
2422 SilcClientEntry *clients = NULL;
2423 uint32 clients_c = 0;
2424 unsigned char **argv = NULL;
2425 uint32 *argv_lens = NULL, *argv_types = NULL, argc = 0;
2426 SilcHashTableList htl;
2427 SilcChannelEntry channel;
2428 SilcHashTable channels;
2431 SILC_LOG_DEBUG(("Start"));
2433 /* Allocate the hash table that holds the channels that require
2434 channel key re-generation after we've removed this server's clients
2435 from the channels. */
2436 channels = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL, NULL,
2439 if (server_signoff) {
2440 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
2441 argv = silc_realloc(argv, sizeof(*argv) * (argc + 1));
2442 argv_lens = silc_realloc(argv_lens, sizeof(*argv_lens) * (argc + 1));
2443 argv_types = silc_realloc(argv_types, sizeof(*argv_types) * (argc + 1));
2444 argv[argc] = silc_calloc(idp->len, sizeof(*argv[0]));
2445 memcpy(argv[argc], idp->data, idp->len);
2446 argv_lens[argc] = idp->len;
2447 argv_types[argc] = argc + 1;
2449 silc_buffer_free(idp);
2452 if (silc_idcache_get_all(server->local_list->clients, &list)) {
2454 if (silc_idcache_list_first(list, &id_cache)) {
2456 client = (SilcClientEntry)id_cache->context;
2457 if (client->data.registered == FALSE) {
2458 if (!silc_idcache_list_next(list, &id_cache))
2464 if (client->router != entry) {
2465 if (server_signoff && client->connection) {
2466 clients = silc_realloc(clients,
2467 sizeof(*clients) * (clients_c + 1));
2468 clients[clients_c] = client;
2472 if (!silc_idcache_list_next(list, &id_cache))
2478 if (server_signoff) {
2479 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2480 argv = silc_realloc(argv, sizeof(*argv) * (argc + 1));
2481 argv_lens = silc_realloc(argv_lens, sizeof(*argv_lens) *
2483 argv_types = silc_realloc(argv_types, sizeof(*argv_types) *
2485 argv[argc] = silc_calloc(idp->len, sizeof(*argv[0]));
2486 memcpy(argv[argc], idp->data, idp->len);
2487 argv_lens[argc] = idp->len;
2488 argv_types[argc] = argc + 1;
2490 silc_buffer_free(idp);
2493 /* Remove the client entry */
2494 silc_server_remove_clients_channels(server, NULL, client, channels);
2495 silc_idlist_del_client(server->local_list, client);
2497 if (!silc_idcache_list_next(list, &id_cache))
2501 silc_idcache_list_free(list);
2504 if (silc_idcache_get_all(server->global_list->clients, &list)) {
2506 if (silc_idcache_list_first(list, &id_cache)) {
2508 client = (SilcClientEntry)id_cache->context;
2509 if (client->data.registered == FALSE) {
2510 if (!silc_idcache_list_next(list, &id_cache))
2516 if (client->router != entry) {
2517 if (server_signoff && client->connection) {
2518 clients = silc_realloc(clients,
2519 sizeof(*clients) * (clients_c + 1));
2520 clients[clients_c] = client;
2524 if (!silc_idcache_list_next(list, &id_cache))
2530 if (server_signoff) {
2531 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2532 argv = silc_realloc(argv, sizeof(*argv) * (argc + 1));
2533 argv_lens = silc_realloc(argv_lens, sizeof(*argv_lens) *
2535 argv_types = silc_realloc(argv_types, sizeof(*argv_types) *
2537 argv[argc] = silc_calloc(idp->len, sizeof(*argv[0]));
2538 memcpy(argv[argc], idp->data, idp->len);
2539 argv_lens[argc] = idp->len;
2540 argv_types[argc] = argc + 1;
2542 silc_buffer_free(idp);
2545 /* Remove the client entry */
2546 silc_server_remove_clients_channels(server, NULL, client, channels);
2547 silc_idlist_del_client(server->global_list, client);
2549 if (!silc_idcache_list_next(list, &id_cache))
2553 silc_idcache_list_free(list);
2556 /* Send the SERVER_SIGNOFF notify */
2557 if (server_signoff) {
2560 /* Send SERVER_SIGNOFF notify to our primary router */
2561 if (!server->standalone && server->router &&
2562 server->router != entry) {
2563 args = silc_argument_payload_encode(1, argv, argv_lens,
2565 silc_server_send_notify_args(server,
2566 server->router->connection,
2567 server->server_type == SILC_SERVER ?
2569 SILC_NOTIFY_TYPE_SERVER_SIGNOFF,
2571 silc_buffer_free(args);
2574 args = silc_argument_payload_encode(argc, argv, argv_lens,
2576 /* Send to local clients */
2577 for (i = 0; i < clients_c; i++) {
2578 silc_server_send_notify_args(server, clients[i]->connection,
2579 FALSE, SILC_NOTIFY_TYPE_SERVER_SIGNOFF,
2584 silc_buffer_free(args);
2585 for (i = 0; i < argc; i++)
2588 silc_free(argv_lens);
2589 silc_free(argv_types);
2592 /* We must now re-generate the channel key for all channels that had
2593 this server's client(s) on the channel. As they left the channel we
2594 must re-generate the channel key. */
2595 silc_hash_table_list(channels, &htl);
2596 while (silc_hash_table_get(&htl, NULL, (void *)&channel)) {
2597 if (!silc_server_create_channel_key(server, channel, 0))
2599 silc_server_send_channel_key(server, NULL, channel,
2600 server->server_type == SILC_ROUTER ?
2601 FALSE : !server->standalone);
2603 silc_hash_table_free(channels);
2608 /* Checks whether given channel has global users. If it does this returns
2609 TRUE and FALSE if there is only locally connected clients on the channel. */
2611 int silc_server_channel_has_global(SilcChannelEntry channel)
2613 SilcChannelClientEntry chl;
2614 SilcHashTableList htl;
2616 silc_hash_table_list(channel->user_list, &htl);
2617 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2618 if (chl->client->router)
2625 /* Checks whether given channel has locally connected users. If it does this
2626 returns TRUE and FALSE if there is not one locally connected client. */
2628 int silc_server_channel_has_local(SilcChannelEntry channel)
2630 SilcChannelClientEntry chl;
2631 SilcHashTableList htl;
2633 silc_hash_table_list(channel->user_list, &htl);
2634 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2635 if (!chl->client->router)
2642 /* Removes client from all channels it has joined. This is used when client
2643 connection is disconnected. If the client on a channel is last, the
2644 channel is removed as well. This sends the SIGNOFF notify types. */
2646 void silc_server_remove_from_channels(SilcServer server,
2647 SilcSocketConnection sock,
2648 SilcClientEntry client,
2650 char *signoff_message,
2653 SilcChannelEntry channel;
2654 SilcChannelClientEntry chl;
2655 SilcHashTableList htl;
2658 SILC_LOG_DEBUG(("Start"));
2660 if (!client || !client->id)
2663 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2665 /* Remove the client from all channels. The client is removed from
2666 the channels' user list. */
2667 silc_hash_table_list(client->channels, &htl);
2668 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2669 channel = chl->channel;
2671 /* Remove channel from client's channel list */
2672 silc_hash_table_del(client->channels, channel);
2674 /* Remove channel if there is no users anymore */
2675 if (server->server_type == SILC_ROUTER &&
2676 silc_hash_table_count(channel->user_list) < 2) {
2678 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2679 if (!silc_idlist_del_channel(server->local_list, channel))
2680 silc_idlist_del_channel(server->global_list, channel);
2681 server->stat.my_channels--;
2685 /* Remove client from channel's client list */
2686 silc_hash_table_del(channel->user_list, chl->client);
2688 server->stat.my_chanclients--;
2690 /* If there is no global users on the channel anymore mark the channel
2691 as local channel. Do not check if the removed client is local client. */
2692 if (server->server_type == SILC_SERVER && channel->global_users &&
2693 chl->client->router && !silc_server_channel_has_global(channel))
2694 channel->global_users = FALSE;
2696 /* If there is not at least one local user on the channel then we don't
2697 need the channel entry anymore, we can remove it safely. */
2698 if (server->server_type == SILC_SERVER &&
2699 !silc_server_channel_has_local(channel)) {
2700 /* Notify about leaving client if this channel has global users. */
2701 if (notify && channel->global_users)
2702 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2703 SILC_NOTIFY_TYPE_SIGNOFF,
2704 signoff_message ? 2 : 1,
2705 clidp->data, clidp->len,
2706 signoff_message, signoff_message ?
2707 strlen(signoff_message) : 0);
2710 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2712 if (channel->founder_key) {
2713 /* The founder auth data exists, do not remove the channel entry */
2714 SilcChannelClientEntry chl2;
2715 SilcHashTableList htl2;
2719 silc_hash_table_list(channel->user_list, &htl2);
2720 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2721 silc_hash_table_del(chl2->client->channels, channel);
2722 silc_hash_table_del(channel->user_list, chl2->client);
2728 /* Remove the channel entry */
2729 if (!silc_idlist_del_channel(server->local_list, channel))
2730 silc_idlist_del_channel(server->global_list, channel);
2731 server->stat.my_channels--;
2735 /* Send notify to channel about client leaving SILC and thus
2736 the entire channel. */
2738 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2739 SILC_NOTIFY_TYPE_SIGNOFF,
2740 signoff_message ? 2 : 1,
2741 clidp->data, clidp->len,
2742 signoff_message, signoff_message ?
2743 strlen(signoff_message) : 0);
2745 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2746 /* Re-generate channel key */
2747 if (!silc_server_create_channel_key(server, channel, 0))
2750 /* Send the channel key to the channel. The key of course is not sent
2751 to the client who was removed from the channel. */
2752 silc_server_send_channel_key(server, client->connection, channel,
2753 server->server_type == SILC_ROUTER ?
2754 FALSE : !server->standalone);
2758 silc_buffer_free(clidp);
2761 /* Removes client from one channel. This is used for example when client
2762 calls LEAVE command to remove itself from the channel. Returns TRUE
2763 if channel still exists and FALSE if the channel is removed when
2764 last client leaves the channel. If `notify' is FALSE notify messages
2767 int silc_server_remove_from_one_channel(SilcServer server,
2768 SilcSocketConnection sock,
2769 SilcChannelEntry channel,
2770 SilcClientEntry client,
2773 SilcChannelClientEntry chl;
2776 SILC_LOG_DEBUG(("Start"));
2778 /* Get the entry to the channel, if this client is not on the channel
2780 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2783 /* Remove the client from the channel. The client is removed from
2784 the channel's user list. */
2786 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2788 /* Remove channel from client's channel list */
2789 silc_hash_table_del(client->channels, chl->channel);
2791 /* Remove channel if there is no users anymore */
2792 if (server->server_type == SILC_ROUTER &&
2793 silc_hash_table_count(channel->user_list) < 2) {
2795 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2796 if (!silc_idlist_del_channel(server->local_list, channel))
2797 silc_idlist_del_channel(server->global_list, channel);
2798 silc_buffer_free(clidp);
2799 server->stat.my_channels--;
2803 /* Remove client from channel's client list */
2804 silc_hash_table_del(channel->user_list, chl->client);
2806 server->stat.my_chanclients--;
2808 /* If there is no global users on the channel anymore mark the channel
2809 as local channel. Do not check if the client is local client. */
2810 if (server->server_type == SILC_SERVER && channel->global_users &&
2811 chl->client->router && !silc_server_channel_has_global(channel))
2812 channel->global_users = FALSE;
2814 /* If there is not at least one local user on the channel then we don't
2815 need the channel entry anymore, we can remove it safely. */
2816 if (server->server_type == SILC_SERVER &&
2817 !silc_server_channel_has_local(channel)) {
2818 /* Notify about leaving client if this channel has global users. */
2819 if (notify && channel->global_users)
2820 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2821 SILC_NOTIFY_TYPE_LEAVE, 1,
2822 clidp->data, clidp->len);
2824 silc_buffer_free(clidp);
2827 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2829 if (channel->founder_key) {
2830 /* The founder auth data exists, do not remove the channel entry */
2831 SilcChannelClientEntry chl2;
2832 SilcHashTableList htl2;
2836 silc_hash_table_list(channel->user_list, &htl2);
2837 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2838 silc_hash_table_del(chl2->client->channels, channel);
2839 silc_hash_table_del(channel->user_list, chl2->client);
2845 /* Remove the channel entry */
2846 if (!silc_idlist_del_channel(server->local_list, channel))
2847 silc_idlist_del_channel(server->global_list, channel);
2848 server->stat.my_channels--;
2852 /* Send notify to channel about client leaving the channel */
2854 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2855 SILC_NOTIFY_TYPE_LEAVE, 1,
2856 clidp->data, clidp->len);
2858 silc_buffer_free(clidp);
2862 /* Returns TRUE if the given client is on the channel. FALSE if not.
2863 This works because we assure that the user list on the channel is
2864 always in up to date thus we can only check the channel list from
2865 `client' which is faster than checking the user list from `channel'. */
2867 int silc_server_client_on_channel(SilcClientEntry client,
2868 SilcChannelEntry channel)
2870 if (!client || !channel)
2873 if (silc_hash_table_find(client->channels, channel, NULL, NULL))
2879 /* Timeout callback. This is called if connection is idle or for some
2880 other reason is not responding within some period of time. This
2881 disconnects the remote end. */
2883 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2885 SilcServer server = (SilcServer)context;
2886 SilcSocketConnection sock = server->sockets[fd];
2888 SILC_LOG_DEBUG(("Start"));
2893 /* If we have protocol active we must assure that we call the protocol's
2894 final callback so that all the memory is freed. */
2895 if (sock->protocol) {
2896 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2897 silc_protocol_execute_final(sock->protocol, server->schedule);
2901 if (sock->user_data)
2902 silc_server_free_sock_user_data(server, sock);
2904 silc_server_disconnect_remote(server, sock, "Server closed connection: "
2905 "Connection timeout");
2908 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2909 function may be used only by router. In real SILC network all channels
2910 are created by routers thus this function is never used by normal
2913 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2914 SilcServerID *router_id,
2920 SilcChannelID *channel_id;
2921 SilcChannelEntry entry;
2925 SILC_LOG_DEBUG(("Creating new channel"));
2928 cipher = "aes-256-cbc";
2930 hmac = "hmac-sha1-96";
2932 /* Allocate cipher */
2933 if (!silc_cipher_alloc(cipher, &key))
2937 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2938 silc_cipher_free(key);
2942 channel_name = strdup(channel_name);
2944 /* Create the channel */
2945 silc_id_create_channel_id(router_id, server->rng, &channel_id);
2946 entry = silc_idlist_add_channel(server->local_list, channel_name,
2947 SILC_CHANNEL_MODE_NONE, channel_id,
2948 NULL, key, newhmac);
2950 silc_free(channel_name);
2951 silc_cipher_free(key);
2952 silc_hmac_free(newhmac);
2956 entry->cipher = strdup(cipher);
2957 entry->hmac_name = strdup(hmac);
2959 /* Now create the actual key material */
2960 if (!silc_server_create_channel_key(server, entry,
2961 silc_cipher_get_key_len(key) / 8)) {
2962 silc_free(channel_name);
2963 silc_cipher_free(key);
2964 silc_hmac_free(newhmac);
2965 silc_free(entry->cipher);
2966 silc_free(entry->hmac_name);
2970 /* Notify other routers about the new channel. We send the packet
2971 to our primary route. */
2972 if (broadcast && server->standalone == FALSE)
2973 silc_server_send_new_channel(server, server->router->connection, TRUE,
2974 channel_name, entry->id,
2975 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2978 server->stat.my_channels++;
2983 /* Same as above but creates the channel with Channel ID `channel_id. */
2986 silc_server_create_new_channel_with_id(SilcServer server,
2990 SilcChannelID *channel_id,
2993 SilcChannelEntry entry;
2997 SILC_LOG_DEBUG(("Creating new channel"));
3000 cipher = "aes-256-cbc";
3002 hmac = "hmac-sha1-96";
3004 /* Allocate cipher */
3005 if (!silc_cipher_alloc(cipher, &key))
3009 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3010 silc_cipher_free(key);
3014 channel_name = strdup(channel_name);
3016 /* Create the channel */
3017 entry = silc_idlist_add_channel(server->local_list, channel_name,
3018 SILC_CHANNEL_MODE_NONE, channel_id,
3019 NULL, key, newhmac);
3021 silc_free(channel_name);
3025 /* Now create the actual key material */
3026 if (!silc_server_create_channel_key(server, entry,
3027 silc_cipher_get_key_len(key) / 8)) {
3028 silc_free(channel_name);
3032 /* Notify other routers about the new channel. We send the packet
3033 to our primary route. */
3034 if (broadcast && server->standalone == FALSE)
3035 silc_server_send_new_channel(server, server->router->connection, TRUE,
3036 channel_name, entry->id,
3037 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3040 server->stat.my_channels++;
3045 /* Channel's key re-key timeout callback. */
3047 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3049 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3050 SilcServer server = (SilcServer)rekey->context;
3052 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3054 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3056 silc_schedule_task_add(server->schedule, 0,
3057 silc_server_channel_key_rekey,
3058 (void *)rekey, 3600, 0,
3060 SILC_TASK_PRI_NORMAL);
3063 /* Generates new channel key. This is used to create the initial channel key
3064 but also to re-generate new key for channel. If `key_len' is provided
3065 it is the bytes of the key length. */
3067 bool silc_server_create_channel_key(SilcServer server,
3068 SilcChannelEntry channel,
3072 unsigned char channel_key[32], hash[32];
3075 SILC_LOG_DEBUG(("Generating channel key"));
3077 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3078 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3082 if (!channel->channel_key)
3083 if (!silc_cipher_alloc("aes-256-cbc", &channel->channel_key))
3088 else if (channel->key_len)
3089 len = channel->key_len / 8;
3091 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3093 /* Create channel key */
3094 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3097 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3099 /* Remove old key if exists */
3101 memset(channel->key, 0, channel->key_len / 8);
3102 silc_free(channel->key);
3106 channel->key_len = len * 8;
3107 channel->key = silc_calloc(len, sizeof(*channel->key));
3108 memcpy(channel->key, channel_key, len);
3109 memset(channel_key, 0, sizeof(channel_key));
3111 /* Generate HMAC key from the channel key data and set it */
3113 silc_hmac_alloc("hmac-sha1-96", NULL, &channel->hmac);
3114 silc_hash_make(channel->hmac->hash, channel->key, len, hash);
3115 silc_hmac_set_key(channel->hmac, hash, silc_hash_len(channel->hmac->hash));
3116 memset(hash, 0, sizeof(hash));
3118 if (server->server_type == SILC_ROUTER) {
3119 if (!channel->rekey)
3120 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3121 channel->rekey->context = (void *)server;
3122 channel->rekey->channel = channel;
3123 channel->rekey->key_len = key_len;
3126 /* XXX Now this cannot be a good thing */
3127 silc_schedule_task_del_by_callback(server->schedule,
3128 silc_server_channel_key_rekey);
3130 silc_schedule_task_add(server->schedule, 0,
3131 silc_server_channel_key_rekey,
3132 (void *)channel->rekey, 3600, 0,
3134 SILC_TASK_PRI_NORMAL);
3140 /* Saves the channel key found in the encoded `key_payload' buffer. This
3141 function is used when we receive Channel Key Payload and also when we're
3142 processing JOIN command reply. Returns entry to the channel. */
3144 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3145 SilcBuffer key_payload,
3146 SilcChannelEntry channel)
3148 SilcChannelKeyPayload payload = NULL;
3149 SilcChannelID *id = NULL;
3150 unsigned char *tmp, hash[32];
3154 SILC_LOG_DEBUG(("Start"));
3156 /* Decode channel key payload */
3157 payload = silc_channel_key_payload_parse(key_payload);
3159 SILC_LOG_ERROR(("Bad channel key payload, dropped"));
3164 /* Get the channel entry */
3167 /* Get channel ID */
3168 tmp = silc_channel_key_get_id(payload, &tmp_len);
3169 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3175 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3177 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3179 SILC_LOG_ERROR(("Received key for non-existent channel"));
3185 tmp = silc_channel_key_get_key(payload, &tmp_len);
3191 cipher = silc_channel_key_get_cipher(payload, NULL);
3197 /* Remove old key if exists */
3199 memset(channel->key, 0, channel->key_len / 8);
3200 silc_free(channel->key);
3201 silc_cipher_free(channel->channel_key);
3204 /* Create new cipher */
3205 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3210 if (channel->cipher)
3211 silc_free(channel->cipher);
3212 channel->cipher = strdup(cipher);
3215 channel->key_len = tmp_len * 8;
3216 channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
3217 memcpy(channel->key, tmp, tmp_len);
3218 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3220 /* Generate HMAC key from the channel key data and set it */
3222 silc_hmac_alloc("hmac-sha1-96", NULL, &channel->hmac);
3223 silc_hash_make(channel->hmac->hash, tmp, tmp_len, hash);
3224 silc_hmac_set_key(channel->hmac, hash, silc_hash_len(channel->hmac->hash));
3226 memset(hash, 0, sizeof(hash));
3227 memset(tmp, 0, tmp_len);
3229 if (server->server_type == SILC_ROUTER) {
3230 if (!channel->rekey)
3231 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3232 channel->rekey->context = (void *)server;
3233 channel->rekey->channel = channel;
3235 silc_schedule_task_del_by_callback(server->schedule,
3236 silc_server_channel_key_rekey);
3237 silc_schedule_task_add(server->schedule, 0,
3238 silc_server_channel_key_rekey,
3239 (void *)channel->rekey, 3600, 0,
3241 SILC_TASK_PRI_NORMAL);
3248 silc_channel_key_payload_free(payload);
3253 /* Heartbeat callback. This function is set as argument for the
3254 silc_socket_set_heartbeat function. The library will call this function
3255 at the set time interval. */
3257 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3260 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3262 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname,
3265 /* Send the heartbeat */
3266 silc_server_send_heartbeat(hb->server, sock);
3269 /* Returns assembled of all servers in the given ID list. The packet's
3270 form is dictated by the New ID payload. */
3272 static void silc_server_announce_get_servers(SilcServer server,
3274 SilcBuffer *servers)
3276 SilcIDCacheList list;
3277 SilcIDCacheEntry id_cache;
3278 SilcServerEntry entry;
3281 /* Go through all clients in the list */
3282 if (silc_idcache_get_all(id_list->servers, &list)) {
3283 if (silc_idcache_list_first(list, &id_cache)) {
3285 entry = (SilcServerEntry)id_cache->context;
3287 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3289 *servers = silc_buffer_realloc(*servers,
3291 (*servers)->truelen + idp->len :
3293 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3294 silc_buffer_put(*servers, idp->data, idp->len);
3295 silc_buffer_pull(*servers, idp->len);
3296 silc_buffer_free(idp);
3298 if (!silc_idcache_list_next(list, &id_cache))
3303 silc_idcache_list_free(list);
3307 /* This function is used by router to announce existing servers to our
3308 primary router when we've connected to it. */
3310 void silc_server_announce_servers(SilcServer server)
3312 SilcBuffer servers = NULL;
3314 SILC_LOG_DEBUG(("Announcing servers"));
3316 /* Get servers in local list */
3317 silc_server_announce_get_servers(server, server->local_list, &servers);
3319 /* Get servers in global list */
3320 silc_server_announce_get_servers(server, server->global_list, &servers);
3323 silc_buffer_push(servers, servers->data - servers->head);
3324 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3326 /* Send the packet */
3327 silc_server_packet_send(server, server->router->connection,
3328 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3329 servers->data, servers->len, TRUE);
3331 silc_buffer_free(servers);
3335 /* Returns assembled packet of all clients in the given ID list. The
3336 packet's form is dictated by the New ID Payload. */
3338 static void silc_server_announce_get_clients(SilcServer server,
3340 SilcBuffer *clients)
3342 SilcIDCacheList list;
3343 SilcIDCacheEntry id_cache;
3344 SilcClientEntry client;
3347 /* Go through all clients in the list */
3348 if (silc_idcache_get_all(id_list->clients, &list)) {
3349 if (silc_idcache_list_first(list, &id_cache)) {
3351 client = (SilcClientEntry)id_cache->context;
3353 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3355 *clients = silc_buffer_realloc(*clients,
3357 (*clients)->truelen + idp->len :
3359 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3360 silc_buffer_put(*clients, idp->data, idp->len);
3361 silc_buffer_pull(*clients, idp->len);
3362 silc_buffer_free(idp);
3364 if (!silc_idcache_list_next(list, &id_cache))
3369 silc_idcache_list_free(list);
3373 /* This function is used to announce our existing clients to our router
3374 when we've connected to it. */
3376 void silc_server_announce_clients(SilcServer server)
3378 SilcBuffer clients = NULL;
3380 SILC_LOG_DEBUG(("Announcing clients"));
3382 /* Get clients in local list */
3383 silc_server_announce_get_clients(server, server->local_list,
3386 /* As router we announce our global list as well */
3387 if (server->server_type == SILC_ROUTER)
3388 silc_server_announce_get_clients(server, server->global_list,
3392 silc_buffer_push(clients, clients->data - clients->head);
3393 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3395 /* Send the packet */
3396 silc_server_packet_send(server, server->router->connection,
3397 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3398 clients->data, clients->len, TRUE);
3400 silc_buffer_free(clients);
3405 silc_server_announce_encode_notify(SilcNotifyType notify, uint32 argc, ...)
3411 p = silc_notify_payload_encode(notify, argc, ap);
3417 /* Returns assembled packets for channel users of the `channel'. */
3419 void silc_server_announce_get_channel_users(SilcServer server,
3420 SilcChannelEntry channel,
3421 SilcBuffer *channel_users,
3422 SilcBuffer *channel_users_modes)
3424 SilcChannelClientEntry chl;
3425 SilcHashTableList htl;
3426 SilcBuffer chidp, clidp;
3429 unsigned char mode[4];
3431 SILC_LOG_DEBUG(("Start"));
3433 /* Now find all users on the channel */
3434 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3435 silc_hash_table_list(channel->user_list, &htl);
3436 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3437 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3440 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3441 clidp->data, clidp->len,
3442 chidp->data, chidp->len);
3445 silc_buffer_realloc(*channel_users,
3447 (*channel_users)->truelen + len : len));
3448 silc_buffer_pull_tail(*channel_users,
3449 ((*channel_users)->end -
3450 (*channel_users)->data));
3452 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3453 silc_buffer_pull(*channel_users, len);
3454 silc_buffer_free(tmp);
3456 /* CUMODE notify for mode change on the channel */
3457 SILC_PUT32_MSB(chl->mode, mode);
3458 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3459 3, clidp->data, clidp->len,
3461 clidp->data, clidp->len);
3463 *channel_users_modes =
3464 silc_buffer_realloc(*channel_users_modes,
3465 (*channel_users_modes ?
3466 (*channel_users_modes)->truelen + len : len));
3467 silc_buffer_pull_tail(*channel_users_modes,
3468 ((*channel_users_modes)->end -
3469 (*channel_users_modes)->data));
3471 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3472 silc_buffer_pull(*channel_users_modes, len);
3473 silc_buffer_free(tmp);
3475 silc_buffer_free(clidp);
3477 silc_buffer_free(chidp);
3480 /* Returns assembled packets for all channels and users on those channels
3481 from the given ID List. The packets are in the form dictated by the
3482 New Channel and New Channel User payloads. */
3484 void silc_server_announce_get_channels(SilcServer server,
3486 SilcBuffer *channels,
3487 SilcBuffer *channel_users,
3488 SilcBuffer **channel_users_modes,
3489 uint32 *channel_users_modes_c,
3490 SilcChannelID ***channel_ids)
3492 SilcIDCacheList list;
3493 SilcIDCacheEntry id_cache;
3494 SilcChannelEntry channel;
3499 int i = *channel_users_modes_c;
3501 SILC_LOG_DEBUG(("Start"));
3503 /* Go through all channels in the list */
3504 if (silc_idcache_get_all(id_list->channels, &list)) {
3505 if (silc_idcache_list_first(list, &id_cache)) {
3507 channel = (SilcChannelEntry)id_cache->context;
3509 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3510 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3511 name_len = strlen(channel->channel_name);
3513 len = 4 + name_len + id_len + 4;
3515 silc_buffer_realloc(*channels,
3516 (*channels ? (*channels)->truelen + len : len));
3517 silc_buffer_pull_tail(*channels,
3518 ((*channels)->end - (*channels)->data));
3519 silc_buffer_format(*channels,
3520 SILC_STR_UI_SHORT(name_len),
3521 SILC_STR_UI_XNSTRING(channel->channel_name,
3523 SILC_STR_UI_SHORT(id_len),
3524 SILC_STR_UI_XNSTRING(cid, id_len),
3525 SILC_STR_UI_INT(channel->mode),
3527 silc_buffer_pull(*channels, len);
3529 *channel_users_modes = silc_realloc(*channel_users_modes,
3530 sizeof(**channel_users_modes) *
3532 (*channel_users_modes)[i] = NULL;
3533 *channel_ids = silc_realloc(*channel_ids,
3534 sizeof(**channel_ids) * (i + 1));
3535 (*channel_ids)[i] = NULL;
3536 silc_server_announce_get_channel_users(server, channel,
3538 channel_users_modes[i]);
3539 (*channel_ids)[i] = channel->id;
3542 if (!silc_idcache_list_next(list, &id_cache))
3546 *channel_users_modes_c += i;
3549 silc_idcache_list_free(list);
3553 /* This function is used to announce our existing channels to our router
3554 when we've connected to it. This also announces the users on the
3555 channels to the router. */
3557 void silc_server_announce_channels(SilcServer server)
3559 SilcBuffer channels = NULL, channel_users = NULL;
3560 SilcBuffer *channel_users_modes = NULL;
3561 uint32 channel_users_modes_c = 0;
3562 SilcChannelID **channel_ids = NULL;
3564 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3566 /* Get channels and channel users in local list */
3567 silc_server_announce_get_channels(server, server->local_list,
3568 &channels, &channel_users,
3569 &channel_users_modes,
3570 &channel_users_modes_c,
3573 /* Get channels and channel users in global list */
3574 silc_server_announce_get_channels(server, server->global_list,
3575 &channels, &channel_users,
3576 &channel_users_modes,
3577 &channel_users_modes_c,
3581 silc_buffer_push(channels, channels->data - channels->head);
3582 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3584 /* Send the packet */
3585 silc_server_packet_send(server, server->router->connection,
3586 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3587 channels->data, channels->len,
3590 silc_buffer_free(channels);
3593 if (channel_users) {
3594 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3595 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3596 channel_users->len);
3598 /* Send the packet */
3599 silc_server_packet_send(server, server->router->connection,
3600 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3601 channel_users->data, channel_users->len,
3604 silc_buffer_free(channel_users);
3607 if (channel_users_modes) {
3610 for (i = 0; i < channel_users_modes_c; i++) {
3611 silc_buffer_push(channel_users_modes[i],
3612 channel_users_modes[i]->data -
3613 channel_users_modes[i]->head);
3614 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3615 channel_users_modes[i]->len);
3616 silc_server_packet_send_dest(server, server->router->connection,
3617 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3618 channel_ids[i], SILC_ID_CHANNEL,
3619 channel_users_modes[i]->data,
3620 channel_users_modes[i]->len,
3622 silc_buffer_free(channel_users_modes[i]);
3624 silc_free(channel_users_modes);
3625 silc_free(channel_ids);
3629 /* Failure timeout callback. If this is called then we will immediately
3630 process the received failure. We always process the failure with timeout
3631 since we do not want to blindly trust to received failure packets.
3632 This won't be called (the timeout is cancelled) if the failure was
3633 bogus (it is bogus if remote does not close the connection after sending
3636 SILC_TASK_CALLBACK(silc_server_failure_callback)
3638 SilcServerFailureContext f = (SilcServerFailureContext)context;
3640 if (f->sock->protocol) {
3641 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3642 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3648 /* Assembles user list and users mode list from the `channel'. */
3650 void silc_server_get_users_on_channel(SilcServer server,
3651 SilcChannelEntry channel,
3652 SilcBuffer *user_list,
3653 SilcBuffer *mode_list,
3656 SilcChannelClientEntry chl;
3657 SilcHashTableList htl;
3658 SilcBuffer client_id_list;
3659 SilcBuffer client_mode_list;
3661 uint32 list_count = 0, len = 0;
3663 silc_hash_table_list(channel->user_list, &htl);
3664 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3665 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3667 client_id_list = silc_buffer_alloc(len);
3669 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3670 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3671 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3673 silc_hash_table_list(channel->user_list, &htl);
3674 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3676 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3677 silc_buffer_put(client_id_list, idp->data, idp->len);
3678 silc_buffer_pull(client_id_list, idp->len);
3679 silc_buffer_free(idp);
3681 /* Client's mode on channel */
3682 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3683 silc_buffer_pull(client_mode_list, 4);
3687 silc_buffer_push(client_id_list,
3688 client_id_list->data - client_id_list->head);
3689 silc_buffer_push(client_mode_list,
3690 client_mode_list->data - client_mode_list->head);
3692 *user_list = client_id_list;
3693 *mode_list = client_mode_list;
3694 *user_count = list_count;
3697 /* Saves users and their modes to the `channel'. */
3699 void silc_server_save_users_on_channel(SilcServer server,
3700 SilcSocketConnection sock,
3701 SilcChannelEntry channel,
3702 SilcClientID *noadd,
3703 SilcBuffer user_list,
3704 SilcBuffer mode_list,
3709 /* Cache the received Client ID's and modes. This cache expires
3710 whenever server sends notify message to channel. It means two things;
3711 some user has joined or leaved the channel. XXX TODO! */
3712 for (i = 0; i < user_count; i++) {
3715 SilcClientID *client_id;
3716 SilcClientEntry client;
3719 SILC_GET16_MSB(idp_len, user_list->data + 2);
3721 client_id = silc_id_payload_parse_id(user_list->data, idp_len);
3722 silc_buffer_pull(user_list, idp_len);
3727 SILC_GET32_MSB(mode, mode_list->data);
3728 silc_buffer_pull(mode_list, 4);
3730 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3731 silc_free(client_id);
3735 /* Check if we have this client cached already. */
3736 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3737 server->server_type, NULL);
3739 client = silc_idlist_find_client_by_id(server->global_list,
3740 client_id, server->server_type,
3743 /* If router did not find such Client ID in its lists then this must
3744 be bogus client or some router in the net is buggy. */
3745 if (server->server_type == SILC_ROUTER) {
3746 silc_free(client_id);
3750 /* We don't have that client anywhere, add it. The client is added
3751 to global list since server didn't have it in the lists so it must be
3753 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3754 silc_id_dup(client_id, SILC_ID_CLIENT),
3755 sock->user_data, NULL);
3757 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3758 silc_free(client_id);
3762 client->data.registered = TRUE;
3765 silc_free(client_id);
3767 if (!silc_server_client_on_channel(client, channel)) {
3768 /* Client was not on the channel, add it. */
3769 SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3770 chl->client = client;
3772 chl->channel = channel;
3773 silc_hash_table_add(channel->user_list, chl->client, chl);
3774 silc_hash_table_add(client->channels, chl->channel, chl);
3779 /* Lookups route to the client indicated by the `id_data'. The connection
3780 object and internal data object is returned. Returns NULL if route
3781 could not be found to the client. If the `client_id' is specified then
3782 it is used and the `id_data' is ignored. */
3784 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3785 unsigned char *id_data,
3787 SilcClientID *client_id,
3788 SilcIDListData *idata)
3791 SilcClientEntry client;
3793 SILC_LOG_DEBUG(("Start"));
3795 /* Decode destination Client ID */
3797 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3799 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3803 id = silc_id_dup(client_id, SILC_ID_CLIENT);
3806 /* If the destination belongs to our server we don't have to route
3807 the packet anywhere but to send it to the local destination. */
3808 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
3812 /* If we are router and the client has router then the client is in
3813 our cell but not directly connected to us. */
3814 if (server->server_type == SILC_ROUTER && client->router) {
3815 /* We are of course in this case the client's router thus the route
3816 to the client is the server who owns the client. So, we will send
3817 the packet to that server. */
3819 *idata = (SilcIDListData)client->router;
3820 return client->router->connection;
3823 /* Seems that client really is directly connected to us */
3825 *idata = (SilcIDListData)client;
3826 return client->connection;
3829 /* Destination belongs to someone not in this server. If we are normal
3830 server our action is to send the packet to our router. */
3831 if (server->server_type == SILC_SERVER && !server->standalone) {
3834 *idata = (SilcIDListData)server->router;
3835 return server->router->connection;
3838 /* We are router and we will perform route lookup for the destination
3839 and send the packet to fastest route. */
3840 if (server->server_type == SILC_ROUTER && !server->standalone) {
3841 /* Check first that the ID is valid */
3842 client = silc_idlist_find_client_by_id(server->global_list, id,
3845 SilcSocketConnection dst_sock;
3847 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
3851 *idata = (SilcIDListData)dst_sock->user_data;
3860 /* Encodes and returns channel list of channels the `client' has joined.
3861 Secret channels are not put to the list. */
3863 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
3864 SilcClientEntry client)
3866 SilcBuffer buffer = NULL;
3867 SilcChannelEntry channel;
3868 SilcChannelClientEntry chl;
3869 SilcHashTableList htl;
3875 silc_hash_table_list(client->channels, &htl);
3876 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3877 channel = chl->channel;
3879 if (channel->mode & SILC_CHANNEL_MODE_SECRET)
3882 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3883 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3884 name_len = strlen(channel->channel_name);
3886 len = 4 + name_len + id_len + 4;
3887 buffer = silc_buffer_realloc(buffer,
3888 (buffer ? (buffer)->truelen + len : len));
3889 silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
3890 silc_buffer_format(buffer,
3891 SILC_STR_UI_SHORT(name_len),
3892 SILC_STR_UI_XNSTRING(channel->channel_name,
3894 SILC_STR_UI_SHORT(id_len),
3895 SILC_STR_UI_XNSTRING(cid, id_len),
3896 SILC_STR_UI_INT(chl->mode), /* Client's mode */
3898 silc_buffer_pull(buffer, len);
3903 silc_buffer_push(buffer, buffer->data - buffer->head);
3908 /* Finds client entry by Client ID and if it is not found then resolves
3909 it using WHOIS command. */
3911 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
3912 SilcClientID *client_id)
3914 SilcClientEntry client;
3916 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3919 client = silc_idlist_find_client_by_id(server->global_list,
3920 client_id, TRUE, NULL);
3921 if (!client && server->server_type == SILC_ROUTER)
3925 if (!client && server->standalone)
3928 if (!client || !client->nickname || !client->username) {
3929 SilcBuffer buffer, idp;
3931 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3932 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
3933 ++server->cmd_ident, 1,
3934 3, idp->data, idp->len);
3935 silc_server_packet_send(server, client ? client->router->connection :
3936 server->router->connection,
3937 SILC_PACKET_COMMAND, 0,
3938 buffer->data, buffer->len, FALSE);
3939 silc_buffer_free(idp);
3940 silc_buffer_free(buffer);
3947 /* A timeout callback for the re-key. We will be the initiator of the
3950 SILC_TASK_CALLBACK(silc_server_rekey_callback)
3952 SilcSocketConnection sock = (SilcSocketConnection)context;
3953 SilcIDListData idata = (SilcIDListData)sock->user_data;
3954 SilcServer server = (SilcServer)idata->rekey->context;
3955 SilcProtocol protocol;
3956 SilcServerRekeyInternalContext *proto_ctx;
3958 SILC_LOG_DEBUG(("Start"));
3960 /* Allocate internal protocol context. This is sent as context
3962 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
3963 proto_ctx->server = (void *)server;
3964 proto_ctx->sock = sock;
3965 proto_ctx->responder = FALSE;
3966 proto_ctx->pfs = idata->rekey->pfs;
3968 /* Perform rekey protocol. Will call the final callback after the
3969 protocol is over. */
3970 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
3971 &protocol, proto_ctx, silc_server_rekey_final);
3972 sock->protocol = protocol;
3974 /* Run the protocol */
3975 silc_protocol_execute(protocol, server->schedule, 0, 0);
3977 /* Re-register re-key timeout */
3978 silc_schedule_task_add(server->schedule, sock->sock,
3979 silc_server_rekey_callback,
3980 context, idata->rekey->timeout, 0,
3981 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
3984 /* The final callback for the REKEY protocol. This will actually take the
3985 new key material into use. */
3987 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
3989 SilcProtocol protocol = (SilcProtocol)context;
3990 SilcServerRekeyInternalContext *ctx =
3991 (SilcServerRekeyInternalContext *)protocol->context;
3992 SilcServer server = (SilcServer)ctx->server;
3993 SilcSocketConnection sock = ctx->sock;
3995 SILC_LOG_DEBUG(("Start"));
3997 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
3998 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
3999 /* Error occured during protocol */
4000 silc_protocol_cancel(protocol, server->schedule);
4001 silc_protocol_free(protocol);
4002 sock->protocol = NULL;
4004 silc_packet_context_free(ctx->packet);
4006 silc_ske_free(ctx->ske);
4012 silc_protocol_free(protocol);
4013 sock->protocol = NULL;
4015 silc_packet_context_free(ctx->packet);
4017 silc_ske_free(ctx->ske);