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"));
240 /* Add ourselves also to the socket table. The entry allocated above
241 is sent as argument for fast referencing in the future. */
242 silc_socket_alloc(sock[i], SILC_SOCKET_TYPE_SERVER, id_entry,
245 server->sockets[sock[i]] = newsocket;
247 /* Perform name and address lookups to resolve the listenning address
249 if (!silc_net_check_local_by_sock(sock[i], &newsocket->hostname,
251 if ((server->params->require_reverse_mapping && !newsocket->hostname) ||
253 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
254 newsocket->hostname ? newsocket->hostname :
255 newsocket->ip ? newsocket->ip : ""));
256 server->stat.conn_failures++;
259 if (!newsocket->hostname)
260 newsocket->hostname = strdup(newsocket->ip);
262 newsocket->port = silc_net_get_local_port(sock[i]);
264 /* Put the allocated socket pointer also to the entry allocated above
265 for fast back-referencing to the socket list. */
266 id_entry->connection = (void *)server->sockets[sock[i]];
267 server->id_entry = id_entry;
270 /* Register protocols */
271 silc_server_protocols_register();
273 /* Initialize the scheduler. */
274 server->schedule = silc_schedule_init(SILC_SERVER_MAX_CONNECTIONS);
275 if (!server->schedule)
278 /* Add the first task to the scheduler. This is task that is executed by
279 timeout. It expires as soon as the caller calls silc_server_run. This
280 task performs authentication protocol and key exchange with our
282 silc_schedule_task_add(server->schedule, sock[0],
283 silc_server_connect_to_router,
284 (void *)server, 0, 1,
286 SILC_TASK_PRI_NORMAL);
288 /* Add listener task to the scheduler. This task receives new connections
289 to the server. This task remains on the queue until the end of the
291 silc_schedule_task_add(server->schedule, sock[0],
292 silc_server_accept_new_connection,
293 (void *)server, 0, 0,
295 SILC_TASK_PRI_NORMAL);
296 server->listenning = TRUE;
298 /* If server connections has been configured then we must be router as
299 normal server cannot have server connections, only router connections. */
300 if (server->config->servers)
301 server->server_type = SILC_ROUTER;
303 /* Register the ID Cache purge task. This periodically purges the ID cache
304 and removes the expired cache entries. */
306 /* Clients local list */
307 purge = silc_calloc(1, sizeof(*purge));
308 purge->cache = server->local_list->clients;
309 purge->schedule = server->schedule;
310 silc_schedule_task_add(purge->schedule, 0,
312 (void *)purge, 600, 0,
313 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
315 /* Clients global list */
316 purge = silc_calloc(1, sizeof(*purge));
317 purge->cache = server->global_list->clients;
318 purge->schedule = server->schedule;
319 silc_schedule_task_add(purge->schedule, 0,
321 (void *)purge, 300, 0,
322 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
324 SILC_LOG_DEBUG(("Server initialized"));
326 /* We are done here, return succesfully */
330 for (i = 0; i < sock_count; i++)
331 silc_net_close_server(sock[i]);
336 /* Fork server to background and set gid+uid to non-root.
337 Silcd will not run as root, so trying to set either user or group to
338 root will cause silcd to exit. */
340 void silc_server_daemonise(SilcServer server)
342 /* Are we executing silcd as root or a regular user? */
349 if (!server->config->identity || !server->config->identity->user ||
350 !server->config->identity->group) {
351 fprintf(stderr, "Error:"
352 "\tSILC server must not be run as root. For the security of your\n"
353 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
354 "\tuser account. Modify the [Identity] configuration section to run\n"
355 "\tthe server as non-root user.\n");
359 /* Get the values given for user and group in configuration file */
360 user=server->config->identity->user;
361 group=server->config->identity->group;
363 /* Check whether the user/group information is text */
364 if (atoi(user)!=0 || atoi(group)!=0) {
365 SILC_LOG_DEBUG(("Invalid user and/or group information"));
366 SILC_LOG_DEBUG(("User and/or group given as number"));
367 fprintf(stderr, "Invalid user and/or group information\n");
368 fprintf(stderr, "Please assign them as names, not numbers\n");
372 /* Catch the nasty incident of string "0" returning 0 from atoi */
373 if (strcmp("0", user)==0 || strcmp("0", group)==0) {
374 SILC_LOG_DEBUG(("User and/or group configured to 0. Unacceptable"));
375 fprintf(stderr, "User and/or group configured to 0. Exiting\n");
383 fprintf(stderr, "No such user %s found\n", user);
388 fprintf(stderr, "No such group %s found\n", group);
392 /* Check whether user and/or group is set to root. If yes, exit
393 immediately. Otherwise, setgid and setuid server to user.group */
394 if (gr->gr_gid==0 || pw->pw_uid==0) {
395 fprintf(stderr, "Error:"
396 "\tSILC server must not be run as root. For the security of your\n"
397 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
398 "\tuser account. Modify the [Identity] configuration section to run\n"
399 "\tthe server as non-root user.\n");
402 /* Fork server to background, making it a daemon */
404 SILC_LOG_DEBUG(("Server started as root. Dropping privileges."));
405 SILC_LOG_DEBUG(("Forking SILC server to background"));
410 SILC_LOG_DEBUG(("Changing to group %s", group));
411 if(setgid(gr->gr_gid)==0) {
412 SILC_LOG_DEBUG(("Setgid to %s", group));
414 SILC_LOG_DEBUG(("Setgid to %s failed", group));
415 fprintf(stderr, "Tried to setgid %s but no such group. Exiting\n",
419 SILC_LOG_DEBUG(("Changing to user nobody"));
420 if(setuid(pw->pw_uid)==0) {
421 SILC_LOG_DEBUG(("Setuid to %s", user));
423 SILC_LOG_DEBUG(("Setuid to %s failed", user));
424 fprintf(stderr, "Tried to setuid %s but no such user. Exiting\n",
430 /* Fork server to background, making it a daemon */
432 SILC_LOG_DEBUG(("Server started as user"));
433 SILC_LOG_DEBUG(("Forking SILC server to background"));
440 /* Stops the SILC server. This function is used to shutdown the server.
441 This is usually called after the scheduler has returned. After stopping
442 the server one should call silc_server_free. */
444 void silc_server_stop(SilcServer server)
446 SILC_LOG_DEBUG(("Stopping server"));
448 silc_schedule_stop(server->schedule);
449 silc_schedule_uninit(server->schedule);
451 silc_server_protocols_unregister();
453 SILC_LOG_DEBUG(("Server stopped"));
456 /* The heart of the server. This runs the scheduler thus runs the server.
457 When this returns the server has been stopped and the program will
460 void silc_server_run(SilcServer server)
462 SILC_LOG_DEBUG(("Running server"));
464 SILC_LOG_INFO(("SILC Server started"));
466 /* Start the scheduler, the heart of the SILC server. When this returns
467 the program will be terminated. */
468 silc_schedule(server->schedule);
471 /* Timeout callback that will be called to retry connecting to remote
472 router. This is used by both normal and router server. This will wait
473 before retrying the connecting. The timeout is generated by exponential
474 backoff algorithm. */
476 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
478 SilcServerConnection sconn = (SilcServerConnection)context;
479 SilcServer server = sconn->server;
481 SILC_LOG_INFO(("Retrying connecting to a router"));
483 /* Calculate next timeout */
484 if (sconn->retry_count >= 1) {
485 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
486 if (sconn->retry_timeout > SILC_SERVER_RETRY_INTERVAL_MAX)
487 sconn->retry_timeout = SILC_SERVER_RETRY_INTERVAL_MAX;
489 sconn->retry_timeout = server->params->retry_interval_min;
491 sconn->retry_count++;
492 sconn->retry_timeout = sconn->retry_timeout +
493 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
495 /* If we've reached max retry count, give up. */
496 if (sconn->retry_count > server->params->retry_count &&
497 server->params->retry_keep_trying == FALSE) {
498 SILC_LOG_ERROR(("Could not connect to router, giving up"));
502 /* Wait one before retrying */
503 silc_schedule_task_add(server->schedule, fd, silc_server_connect_router,
504 context, sconn->retry_timeout,
505 server->params->retry_interval_min_usec,
506 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
509 /* Generic routine to use connect to a router. */
511 SILC_TASK_CALLBACK(silc_server_connect_router)
513 SilcServerConnection sconn = (SilcServerConnection)context;
514 SilcServer server = sconn->server;
515 SilcSocketConnection newsocket;
516 SilcProtocol protocol;
517 SilcServerKEInternalContext *proto_ctx;
520 SILC_LOG_INFO(("Connecting to the router %s on port %d",
521 sconn->remote_host, sconn->remote_port));
523 /* Connect to remote host */
524 sock = silc_net_create_connection(sconn->remote_port,
527 SILC_LOG_ERROR(("Could not connect to router"));
528 silc_schedule_task_add(server->schedule, fd,
529 silc_server_connect_to_router_retry,
530 context, 0, 1, SILC_TASK_TIMEOUT,
531 SILC_TASK_PRI_NORMAL);
535 /* Set socket options */
536 silc_net_set_socket_nonblock(sock);
537 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
539 /* Create socket connection for the connection. Even though we
540 know that we are connecting to a router we will mark the socket
541 to be unknown connection until we have executed authentication
543 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
544 server->sockets[sock] = newsocket;
545 newsocket->hostname = strdup(sconn->remote_host);
546 newsocket->ip = strdup(sconn->remote_host);
547 newsocket->port = sconn->remote_port;
548 sconn->sock = newsocket;
550 /* Allocate internal protocol context. This is sent as context
552 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
553 proto_ctx->server = (void *)server;
554 proto_ctx->context = (void *)sconn;
555 proto_ctx->sock = newsocket;
556 proto_ctx->rng = server->rng;
557 proto_ctx->responder = FALSE;
559 /* Perform key exchange protocol. silc_server_connect_to_router_second
560 will be called after the protocol is finished. */
561 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
562 &protocol, proto_ctx,
563 silc_server_connect_to_router_second);
564 newsocket->protocol = protocol;
566 /* Register a timeout task that will be executed if the protocol
567 is not executed within set limit. */
568 proto_ctx->timeout_task =
569 silc_schedule_task_add(server->schedule, sock,
570 silc_server_timeout_remote,
571 server, server->params->protocol_timeout,
572 server->params->protocol_timeout_usec,
576 /* Register the connection for network input and output. This sets
577 that scheduler will listen for incoming packets for this connection
578 and sets that outgoing packets may be sent to this connection as
579 well. However, this doesn't set the scheduler for outgoing traffic,
580 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
581 later when outgoing data is available. */
582 context = (void *)server;
583 SILC_REGISTER_CONNECTION_FOR_IO(sock);
585 /* Run the protocol */
586 silc_protocol_execute(protocol, server->schedule, 0, 0);
589 /* This function connects to our primary router or if we are a router this
590 establishes all our primary routes. This is called at the start of the
591 server to do authentication and key exchange with our router - called
594 SILC_TASK_CALLBACK(silc_server_connect_to_router)
596 SilcServer server = (SilcServer)context;
597 SilcServerConnection sconn;
599 SILC_LOG_DEBUG(("Connecting to router(s)"));
601 /* If we are normal SILC server we need to connect to our cell's
603 if (server->server_type == SILC_SERVER) {
604 SILC_LOG_DEBUG(("We are normal server"));
606 /* Create connection to the router, if configured. */
607 if (server->config->routers) {
609 /* Allocate connection object for hold connection specific stuff. */
610 sconn = silc_calloc(1, sizeof(*sconn));
611 sconn->server = server;
612 sconn->remote_host = strdup(server->config->routers->host);
613 sconn->remote_port = server->config->routers->port;
615 silc_schedule_task_add(server->schedule, fd,
616 silc_server_connect_router,
617 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
618 SILC_TASK_PRI_NORMAL);
623 /* If we are a SILC router we need to establish all of our primary
625 if (server->server_type == SILC_ROUTER) {
626 SilcServerConfigSectionServerConnection *ptr;
628 SILC_LOG_DEBUG(("We are router"));
630 /* Create the connections to all our routes */
631 ptr = server->config->routers;
634 SILC_LOG_DEBUG(("Router connection [%s] %s:%d",
635 ptr->initiator ? "Initiator" : "Responder",
636 ptr->host, ptr->port));
638 if (ptr->initiator) {
639 /* Allocate connection object for hold connection specific stuff. */
640 sconn = silc_calloc(1, sizeof(*sconn));
641 sconn->server = server;
642 sconn->remote_host = strdup(ptr->host);
643 sconn->remote_port = ptr->port;
645 silc_schedule_task_add(server->schedule, fd,
646 silc_server_connect_router,
647 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
648 SILC_TASK_PRI_NORMAL);
658 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
660 /* There wasn't a configured router, we will continue but we don't
661 have a connection to outside world. We will be standalone server. */
662 server->standalone = TRUE;
665 /* Second part of connecting to router(s). Key exchange protocol has been
666 executed and now we will execute authentication protocol. */
668 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
670 SilcProtocol protocol = (SilcProtocol)context;
671 SilcServerKEInternalContext *ctx =
672 (SilcServerKEInternalContext *)protocol->context;
673 SilcServer server = (SilcServer)ctx->server;
674 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
675 SilcSocketConnection sock = ctx->sock;
676 SilcServerConnAuthInternalContext *proto_ctx;
677 SilcServerConfigSectionServerConnection *conn = NULL;
679 SILC_LOG_DEBUG(("Start"));
681 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
682 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
683 /* Error occured during protocol */
684 silc_protocol_free(protocol);
685 sock->protocol = NULL;
686 silc_ske_free_key_material(ctx->keymat);
688 silc_packet_context_free(ctx->packet);
690 silc_ske_free(ctx->ske);
692 silc_free(ctx->dest_id);
694 silc_schedule_task_del_by_callback(server->schedule,
695 silc_server_failure_callback);
696 silc_server_disconnect_remote(server, sock, "Server closed connection: "
697 "Key exchange failed");
701 /* We now have the key material as the result of the key exchange
702 protocol. Take the key material into use. Free the raw key material
703 as soon as we've set them into use. */
704 if (!silc_server_protocol_ke_set_keys(ctx->ske, ctx->sock, ctx->keymat,
705 ctx->ske->prop->cipher,
706 ctx->ske->prop->pkcs,
707 ctx->ske->prop->hash,
708 ctx->ske->prop->hmac,
709 ctx->ske->prop->group,
711 silc_protocol_free(protocol);
712 sock->protocol = NULL;
713 silc_ske_free_key_material(ctx->keymat);
715 silc_packet_context_free(ctx->packet);
717 silc_ske_free(ctx->ske);
719 silc_free(ctx->dest_id);
721 silc_schedule_task_del_by_callback(server->schedule,
722 silc_server_failure_callback);
723 silc_server_disconnect_remote(server, sock, "Server closed connection: "
724 "Key exchange failed");
727 silc_ske_free_key_material(ctx->keymat);
729 /* Allocate internal context for the authentication protocol. This
730 is sent as context for the protocol. */
731 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
732 proto_ctx->server = (void *)server;
733 proto_ctx->context = (void *)sconn;
734 proto_ctx->sock = sock;
735 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
736 proto_ctx->dest_id_type = ctx->dest_id_type;
737 proto_ctx->dest_id = ctx->dest_id;
739 /* Resolve the authentication method used in this connection. Check if
740 we find a match from user configured connections */
741 conn = silc_server_config_find_router_conn(server->config,
745 /* Match found. Use the configured authentication method */
746 proto_ctx->auth_meth = conn->auth_meth;
747 if (conn->auth_data) {
748 proto_ctx->auth_data = strdup(conn->auth_data);
749 proto_ctx->auth_data_len = strlen(conn->auth_data);
752 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
753 sock->hostname, sock->ip, sock->port));
754 silc_protocol_free(protocol);
755 sock->protocol = NULL;
757 silc_packet_context_free(ctx->packet);
759 silc_ske_free(ctx->ske);
761 silc_free(ctx->dest_id);
763 silc_schedule_task_del_by_callback(server->schedule,
764 silc_server_failure_callback);
765 silc_server_disconnect_remote(server, sock, "Server closed connection: "
766 "Key exchange failed");
770 /* Free old protocol as it is finished now */
771 silc_protocol_free(protocol);
773 silc_packet_context_free(ctx->packet);
775 sock->protocol = NULL;
777 /* Allocate the authentication protocol. This is allocated here
778 but we won't start it yet. We will be receiving party of this
779 protocol thus we will wait that connecting party will make
781 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
782 &sock->protocol, proto_ctx,
783 silc_server_connect_to_router_final);
785 /* Register timeout task. If the protocol is not executed inside
786 this timelimit the connection will be terminated. Currently
787 this is 15 seconds and is hard coded limit (XXX). */
788 proto_ctx->timeout_task =
789 silc_schedule_task_add(server->schedule, sock->sock,
790 silc_server_timeout_remote,
791 (void *)server, 15, 0,
795 /* Run the protocol */
796 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
799 /* Finalizes the connection to router. Registers a server task to the
800 queue so that we can accept new connections. */
802 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
804 SilcProtocol protocol = (SilcProtocol)context;
805 SilcServerConnAuthInternalContext *ctx =
806 (SilcServerConnAuthInternalContext *)protocol->context;
807 SilcServer server = (SilcServer)ctx->server;
808 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
809 SilcSocketConnection sock = ctx->sock;
810 SilcServerEntry id_entry;
812 SilcServerHBContext hb_context;
813 unsigned char *id_string;
815 SilcIDListData idata;
817 SILC_LOG_DEBUG(("Start"));
819 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
820 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
821 /* Error occured during protocol */
823 silc_free(ctx->dest_id);
824 silc_server_disconnect_remote(server, sock, "Server closed connection: "
825 "Authentication failed");
829 /* Add a task to the queue. This task receives new connections to the
830 server. This task remains on the queue until the end of the program. */
831 if (!server->listenning) {
832 silc_schedule_task_add(server->schedule, server->sock,
833 silc_server_accept_new_connection,
834 (void *)server, 0, 0,
836 SILC_TASK_PRI_NORMAL);
837 server->listenning = TRUE;
840 /* Send NEW_SERVER packet to the router. We will become registered
841 to the SILC network after sending this packet. */
842 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
843 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
844 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
845 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
846 silc_buffer_format(packet,
847 SILC_STR_UI_SHORT(id_len),
848 SILC_STR_UI_XNSTRING(id_string, id_len),
849 SILC_STR_UI_SHORT(strlen(server->server_name)),
850 SILC_STR_UI_XNSTRING(server->server_name,
851 strlen(server->server_name)),
854 /* Send the packet */
855 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
856 packet->data, packet->len, TRUE);
857 silc_buffer_free(packet);
858 silc_free(id_string);
860 SILC_LOG_DEBUG(("Connected to router %s", sock->hostname));
862 /* Add the connected router to local server list */
863 server->standalone = FALSE;
864 id_entry = silc_idlist_add_server(server->local_list, strdup(sock->hostname),
865 SILC_ROUTER, ctx->dest_id, NULL, sock);
868 silc_free(ctx->dest_id);
869 silc_server_disconnect_remote(server, sock, "Server closed connection: "
870 "Authentication failed");
874 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
875 silc_free(sock->user_data);
876 sock->user_data = (void *)id_entry;
877 sock->type = SILC_SOCKET_TYPE_ROUTER;
878 server->id_entry->router = id_entry;
879 server->router = id_entry;
880 idata = (SilcIDListData)sock->user_data;
881 idata->registered = TRUE;
883 /* Perform keepalive. The `hb_context' will be freed automatically
884 when finally calling the silc_socket_free function. XXX hardcoded
886 hb_context = silc_calloc(1, sizeof(*hb_context));
887 hb_context->server = server;
888 silc_socket_set_heartbeat(sock, 600, hb_context,
889 silc_server_perform_heartbeat,
892 /* Register re-key timeout */
893 idata->rekey->timeout = 3600; /* XXX hardcoded */
894 idata->rekey->context = (void *)server;
895 silc_schedule_task_add(server->schedule, sock->sock,
896 silc_server_rekey_callback,
897 (void *)sock, idata->rekey->timeout, 0,
898 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
900 /* If we are router then announce our possible servers. */
901 if (server->server_type == SILC_ROUTER)
902 silc_server_announce_servers(server);
904 /* Announce our clients and channels to the router */
905 silc_server_announce_clients(server);
906 silc_server_announce_channels(server);
909 /* Free the temporary connection data context */
911 silc_free(sconn->remote_host);
915 /* Free the protocol object */
916 silc_protocol_free(protocol);
918 silc_packet_context_free(ctx->packet);
920 silc_ske_free(ctx->ske);
922 sock->protocol = NULL;
925 /* Host lookup callbcak that is called after the incoming connection's
926 IP and FQDN lookup is performed. This will actually check the acceptance
927 of the incoming connection and will register the key exchange protocol
928 for this connection. */
931 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
934 SilcServer server = (SilcServer)context;
935 SilcServerKEInternalContext *proto_ctx;
936 void *cconfig, *sconfig, *rconfig;
937 SilcServerConfigSectionDenyConnection *deny;
940 SILC_LOG_DEBUG(("Start"));
942 /* Check whether we could resolve both IP and FQDN. */
943 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
944 server->params->require_reverse_mapping)) {
945 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
946 sock->hostname ? sock->hostname :
947 sock->ip ? sock->ip : ""));
948 server->stat.conn_failures++;
949 silc_server_disconnect_remote(server, sock,
950 "Server closed connection: Unknown host");
954 /* Register the connection for network input and output. This sets
955 that scheduler will listen for incoming packets for this connection
956 and sets that outgoing packets may be sent to this connection as well.
957 However, this doesn't set the scheduler for outgoing traffic, it
958 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
959 later when outgoing data is available. */
960 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
962 SILC_LOG_INFO(("Incoming connection from %s (%s)", sock->hostname,
965 port = server->sockets[server->sock]->port; /* Listenning port */
967 /* Check whether this connection is denied to connect to us. */
968 deny = silc_server_config_denied_conn(server->config, sock->ip, port);
970 deny = silc_server_config_denied_conn(server->config, sock->hostname,
973 /* The connection is denied */
974 SILC_LOG_INFO(("Connection %s (%s) is denied",
975 sock->hostname, sock->ip));
976 silc_server_disconnect_remote(server, sock, deny->comment ?
978 "Server closed connection: "
979 "Connection refused");
980 server->stat.conn_failures++;
984 /* Check whether we have configred this sort of connection at all. We
985 have to check all configurations since we don't know what type of
986 connection this is. */
987 if (!(cconfig = silc_server_config_find_client_conn(server->config,
989 cconfig = silc_server_config_find_client_conn(server->config,
992 if (!(sconfig = silc_server_config_find_server_conn(server->config,
995 sconfig = silc_server_config_find_server_conn(server->config,
998 if (!(rconfig = silc_server_config_find_router_conn(server->config,
1000 rconfig = silc_server_config_find_router_conn(server->config,
1003 if (!cconfig && !sconfig && !rconfig) {
1004 silc_server_disconnect_remote(server, sock,
1005 "Server closed connection: "
1006 "Connection refused");
1007 server->stat.conn_failures++;
1011 /* The connection is allowed */
1013 /* Allocate internal context for key exchange protocol. This is
1014 sent as context for the protocol. */
1015 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1016 proto_ctx->server = context;
1017 proto_ctx->sock = sock;
1018 proto_ctx->rng = server->rng;
1019 proto_ctx->responder = TRUE;
1020 proto_ctx->cconfig = cconfig;
1021 proto_ctx->sconfig = sconfig;
1022 proto_ctx->rconfig = rconfig;
1024 /* Prepare the connection for key exchange protocol. We allocate the
1025 protocol but will not start it yet. The connector will be the
1026 initiator of the protocol thus we will wait for initiation from
1027 there before we start the protocol. */
1028 server->stat.auth_attempts++;
1029 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1030 &sock->protocol, proto_ctx,
1031 silc_server_accept_new_connection_second);
1033 /* Register a timeout task that will be executed if the connector
1034 will not start the key exchange protocol within 60 seconds. For
1035 now, this is a hard coded limit. After 60 secs the connection will
1036 be closed if the key exchange protocol has not been started. */
1037 proto_ctx->timeout_task =
1038 silc_schedule_task_add(server->schedule, sock->sock,
1039 silc_server_timeout_remote,
1045 /* Accepts new connections to the server. Accepting new connections are
1046 done in three parts to make it async. */
1048 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1050 SilcServer server = (SilcServer)context;
1051 SilcSocketConnection newsocket;
1054 SILC_LOG_DEBUG(("Accepting new connection"));
1056 server->stat.conn_attempts++;
1058 sock = silc_net_accept_connection(server->sock);
1060 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1061 server->stat.conn_failures++;
1065 /* Check max connections */
1066 if (sock > SILC_SERVER_MAX_CONNECTIONS) {
1067 SILC_LOG_ERROR(("Refusing connection, server is full"));
1068 server->stat.conn_failures++;
1072 /* Set socket options */
1073 silc_net_set_socket_nonblock(sock);
1074 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1076 /* We don't create a ID yet, since we don't know what type of connection
1077 this is yet. But, we do add the connection to the socket table. */
1078 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1079 server->sockets[sock] = newsocket;
1081 /* Perform asynchronous host lookup. This will lookup the IP and the
1082 FQDN of the remote connection. After the lookup is done the connection
1083 is accepted further. */
1084 silc_socket_host_lookup(newsocket, TRUE,
1085 silc_server_accept_new_connection_lookup, context,
1089 /* Second part of accepting new connection. Key exchange protocol has been
1090 performed and now it is time to do little connection authentication
1091 protocol to figure out whether this connection is client or server
1092 and whether it has right to access this server (especially server
1093 connections needs to be authenticated). */
1095 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1097 SilcProtocol protocol = (SilcProtocol)context;
1098 SilcServerKEInternalContext *ctx =
1099 (SilcServerKEInternalContext *)protocol->context;
1100 SilcServer server = (SilcServer)ctx->server;
1101 SilcSocketConnection sock = ctx->sock;
1102 SilcServerConnAuthInternalContext *proto_ctx;
1104 SILC_LOG_DEBUG(("Start"));
1106 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1107 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1108 /* Error occured during protocol */
1109 silc_protocol_free(protocol);
1110 sock->protocol = NULL;
1111 silc_ske_free_key_material(ctx->keymat);
1113 silc_packet_context_free(ctx->packet);
1115 silc_ske_free(ctx->ske);
1117 silc_free(ctx->dest_id);
1119 silc_schedule_task_del_by_callback(server->schedule,
1120 silc_server_failure_callback);
1121 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1122 "Key exchange failed");
1123 server->stat.auth_failures++;
1127 /* We now have the key material as the result of the key exchange
1128 protocol. Take the key material into use. Free the raw key material
1129 as soon as we've set them into use. */
1130 if (!silc_server_protocol_ke_set_keys(ctx->ske, ctx->sock, ctx->keymat,
1131 ctx->ske->prop->cipher,
1132 ctx->ske->prop->pkcs,
1133 ctx->ske->prop->hash,
1134 ctx->ske->prop->hmac,
1135 ctx->ske->prop->group,
1137 silc_protocol_free(protocol);
1138 sock->protocol = NULL;
1139 silc_ske_free_key_material(ctx->keymat);
1141 silc_packet_context_free(ctx->packet);
1143 silc_ske_free(ctx->ske);
1145 silc_free(ctx->dest_id);
1147 silc_schedule_task_del_by_callback(server->schedule,
1148 silc_server_failure_callback);
1149 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1150 "Key exchange failed");
1151 server->stat.auth_failures++;
1154 silc_ske_free_key_material(ctx->keymat);
1156 /* Allocate internal context for the authentication protocol. This
1157 is sent as context for the protocol. */
1158 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1159 proto_ctx->server = (void *)server;
1160 proto_ctx->sock = sock;
1161 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1162 proto_ctx->responder = TRUE;
1163 proto_ctx->dest_id_type = ctx->dest_id_type;
1164 proto_ctx->dest_id = ctx->dest_id;
1165 proto_ctx->cconfig = ctx->cconfig;
1166 proto_ctx->sconfig = ctx->sconfig;
1167 proto_ctx->rconfig = ctx->rconfig;
1169 /* Free old protocol as it is finished now */
1170 silc_protocol_free(protocol);
1172 silc_packet_context_free(ctx->packet);
1174 sock->protocol = NULL;
1176 /* Allocate the authentication protocol. This is allocated here
1177 but we won't start it yet. We will be receiving party of this
1178 protocol thus we will wait that connecting party will make
1179 their first move. */
1180 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1181 &sock->protocol, proto_ctx,
1182 silc_server_accept_new_connection_final);
1184 /* Register timeout task. If the protocol is not executed inside
1185 this timelimit the connection will be terminated. Currently
1186 this is 60 seconds and is hard coded limit (XXX). */
1187 proto_ctx->timeout_task =
1188 silc_schedule_task_add(server->schedule, sock->sock,
1189 silc_server_timeout_remote,
1190 (void *)server, 60, 0,
1195 /* Final part of accepting new connection. The connection has now
1196 been authenticated and keys has been exchanged. We also know whether
1197 this is client or server connection. */
1199 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1201 SilcProtocol protocol = (SilcProtocol)context;
1202 SilcServerConnAuthInternalContext *ctx =
1203 (SilcServerConnAuthInternalContext *)protocol->context;
1204 SilcServer server = (SilcServer)ctx->server;
1205 SilcSocketConnection sock = ctx->sock;
1206 SilcServerHBContext hb_context;
1207 void *id_entry = NULL;
1209 SILC_LOG_DEBUG(("Start"));
1211 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1212 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1213 /* Error occured during protocol */
1214 silc_protocol_free(protocol);
1215 sock->protocol = NULL;
1217 silc_packet_context_free(ctx->packet);
1219 silc_ske_free(ctx->ske);
1221 silc_free(ctx->dest_id);
1224 sock->protocol = NULL;
1225 silc_schedule_task_del_by_callback(server->schedule,
1226 silc_server_failure_callback);
1227 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1228 "Authentication failed");
1229 server->stat.auth_failures++;
1233 switch(ctx->conn_type) {
1234 case SILC_SOCKET_TYPE_CLIENT:
1236 SilcClientEntry client;
1238 SILC_LOG_DEBUG(("Remote host is client"));
1239 SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
1242 /* Add the client to the client ID cache. The nickname and Client ID
1243 and other information is created after we have received NEW_CLIENT
1244 packet from client. */
1245 client = silc_idlist_add_client(server->local_list,
1246 NULL, NULL, NULL, NULL, NULL, sock);
1248 SILC_LOG_ERROR(("Could not add new client to cache"));
1249 silc_free(sock->user_data);
1250 silc_server_disconnect_remote(server, sock,
1251 "Server closed connection: "
1252 "Authentication failed");
1253 server->stat.auth_failures++;
1258 server->stat.my_clients++;
1259 server->stat.clients++;
1260 if (server->server_type == SILC_ROUTER)
1261 server->stat.cell_clients++;
1263 id_entry = (void *)client;
1266 case SILC_SOCKET_TYPE_SERVER:
1267 case SILC_SOCKET_TYPE_ROUTER:
1269 SilcServerEntry new_server;
1270 SilcServerConfigSectionServerConnection *conn =
1271 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1272 ctx->sconfig : ctx->rconfig;
1274 SILC_LOG_DEBUG(("Remote host is %s",
1275 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1276 "server" : "router"));
1277 SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
1278 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1279 "server" : "router"));
1281 /* Add the server into server cache. The server name and Server ID
1282 is updated after we have received NEW_SERVER packet from the
1283 server. We mark ourselves as router for this server if we really
1286 silc_idlist_add_server(server->local_list, NULL,
1287 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1288 SILC_SERVER : SILC_ROUTER, NULL,
1289 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1290 server->id_entry : NULL, sock);
1292 SILC_LOG_ERROR(("Could not add new server to cache"));
1293 silc_free(sock->user_data);
1294 silc_server_disconnect_remote(server, sock,
1295 "Server closed connection: "
1296 "Authentication failed");
1297 server->stat.auth_failures++;
1302 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1303 server->stat.my_servers++;
1305 server->stat.my_routers++;
1306 server->stat.servers++;
1308 id_entry = (void *)new_server;
1310 /* Check whether this connection is to be our primary router connection
1311 if we dont' already have the primary route. */
1312 if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1313 if (silc_server_config_is_primary_route(server->config) &&
1317 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1318 server->standalone = FALSE;
1319 if (!server->id_entry->router) {
1320 server->id_entry->router = id_entry;
1321 server->router = id_entry;
1331 sock->type = ctx->conn_type;
1333 /* Add the common data structure to the ID entry. */
1335 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1337 /* Add to sockets internal pointer for fast referencing */
1338 silc_free(sock->user_data);
1339 sock->user_data = id_entry;
1341 /* Connection has been fully established now. Everything is ok. */
1342 SILC_LOG_DEBUG(("New connection authenticated"));
1344 /* Perform keepalive. The `hb_context' will be freed automatically
1345 when finally calling the silc_socket_free function. XXX hardcoded
1347 hb_context = silc_calloc(1, sizeof(*hb_context));
1348 hb_context->server = server;
1349 silc_socket_set_heartbeat(sock, 600, hb_context,
1350 silc_server_perform_heartbeat,
1354 silc_schedule_task_del_by_callback(server->schedule,
1355 silc_server_failure_callback);
1356 silc_protocol_free(protocol);
1358 silc_packet_context_free(ctx->packet);
1360 silc_ske_free(ctx->ske);
1362 silc_free(ctx->dest_id);
1364 sock->protocol = NULL;
1367 /* This function is used to read packets from network and send packets to
1368 network. This is usually a generic task. */
1370 SILC_TASK_CALLBACK(silc_server_packet_process)
1372 SilcServer server = (SilcServer)context;
1373 SilcSocketConnection sock = server->sockets[fd];
1374 SilcIDListData idata;
1375 SilcCipher cipher = NULL;
1376 SilcHmac hmac = NULL;
1382 SILC_LOG_DEBUG(("Processing packet"));
1384 /* Packet sending */
1386 if (type == SILC_TASK_WRITE) {
1387 /* Do not send data to disconnected connection */
1388 if (SILC_IS_DISCONNECTED(sock))
1391 server->stat.packets_sent++;
1393 if (sock->outbuf->data - sock->outbuf->head)
1394 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1396 /* Send the packet */
1397 ret = silc_packet_send(sock, TRUE);
1399 /* If returned -2 could not write to connection now, will do
1405 SILC_LOG_ERROR(("Error sending packet to connection "
1406 "%s:%d [%s]", sock->hostname, sock->port,
1407 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1408 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1409 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1414 /* The packet has been sent and now it is time to set the connection
1415 back to only for input. When there is again some outgoing data
1416 available for this connection it will be set for output as well.
1417 This call clears the output setting and sets it only for input. */
1418 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1419 SILC_UNSET_OUTBUF_PENDING(sock);
1421 silc_buffer_clear(sock->outbuf);
1425 /* Packet receiving */
1427 /* Read some data from connection */
1428 ret = silc_packet_receive(sock);
1432 SILC_LOG_ERROR(("Error receiving packet from connection "
1433 "%s:%d [%s]", sock->hostname, sock->port,
1434 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1435 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1436 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1443 SILC_LOG_DEBUG(("Read EOF"));
1445 /* If connection is disconnecting already we will finally
1446 close the connection */
1447 if (SILC_IS_DISCONNECTING(sock)) {
1448 if (sock->user_data)
1449 silc_server_free_sock_user_data(server, sock);
1450 silc_server_close_connection(server, sock);
1454 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1455 SILC_SET_DISCONNECTING(sock);
1457 /* If the closed connection was our primary router connection the
1458 start re-connecting phase. */
1459 if (!server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER &&
1460 sock == server->router->connection)
1461 silc_schedule_task_add(server->schedule, 0,
1462 silc_server_connect_to_router,
1465 SILC_TASK_PRI_NORMAL);
1467 if (sock->user_data)
1468 silc_server_free_sock_user_data(server, sock);
1469 silc_server_close_connection(server, sock);
1473 /* If connection is disconnecting or disconnected we will ignore
1475 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1476 SILC_LOG_DEBUG(("Ignoring read data from disonnected connection"));
1480 server->stat.packets_received++;
1482 /* Get keys and stuff from ID entry */
1483 idata = (SilcIDListData)sock->user_data;
1485 idata->last_receive = time(NULL);
1486 cipher = idata->receive_key;
1487 hmac = idata->hmac_receive;
1490 /* Process the packet. This will call the parser that will then
1491 decrypt and parse the packet. */
1492 silc_packet_receive_process(sock, cipher, hmac, silc_server_packet_parse,
1496 /* Callback function that the silc_packet_decrypt will call to make the
1497 decision whether the packet is normal or special packet. We will
1498 return TRUE if it is normal and FALSE if it is special */
1500 static int silc_server_packet_decrypt_check(SilcPacketType packet_type,
1502 SilcPacketContext *packet,
1505 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1506 SilcServer server = (SilcServer)parse_ctx->context;
1508 /* Packet is normal packet, if:
1510 1) packet is private message packet and does not have private key set
1511 2) is other packet than channel message packet
1512 3) is channel message packet and remote is router and we are router
1514 all other packets are special packets
1517 if (packet_type == SILC_PACKET_PRIVATE_MESSAGE &&
1518 (buffer->data[2] & SILC_PACKET_FLAG_PRIVMSG_KEY))
1521 if (packet_type != SILC_PACKET_CHANNEL_MESSAGE ||
1522 (packet_type == SILC_PACKET_CHANNEL_MESSAGE &&
1523 parse_ctx->sock->type == SILC_SOCKET_TYPE_ROUTER &&
1524 server->server_type == SILC_ROUTER))
1530 /* Parses whole packet, received earlier. */
1532 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1534 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1535 SilcServer server = (SilcServer)parse_ctx->context;
1536 SilcSocketConnection sock = parse_ctx->sock;
1537 SilcPacketContext *packet = parse_ctx->packet;
1538 SilcIDListData idata = (SilcIDListData)sock->user_data;
1541 SILC_LOG_DEBUG(("Start"));
1543 /* Decrypt the received packet */
1544 ret = silc_packet_decrypt(idata ? idata->receive_key : NULL,
1545 idata ? idata->hmac_receive : NULL,
1546 packet->buffer, packet,
1547 silc_server_packet_decrypt_check, parse_ctx);
1549 SILC_LOG_WARNING(("Packet decryption failed for connection "
1550 "%s:%d [%s]", sock->hostname, sock->port,
1551 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1552 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1553 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1559 /* Parse the packet. Packet type is returned. */
1560 ret = silc_packet_parse(packet);
1562 /* Parse the packet header in special way as this is "special"
1564 ret = silc_packet_parse_special(packet);
1567 if (ret == SILC_PACKET_NONE)
1570 /* Check that the the current client ID is same as in the client's packet. */
1571 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1572 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1573 if (client && client->id) {
1574 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1575 packet->src_id_type);
1576 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1584 if (server->server_type == SILC_ROUTER) {
1585 /* Route the packet if it is not destined to us. Other ID types but
1586 server are handled separately after processing them. */
1587 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1588 packet->dst_id_type == SILC_ID_SERVER &&
1589 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1590 memcmp(packet->dst_id, server->id_string, packet->dst_id_len)) {
1592 /* Route the packet to fastest route for the destination ID */
1593 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1594 packet->dst_id_type);
1597 silc_server_packet_route(server,
1598 silc_server_route_get(server, id,
1599 packet->dst_id_type),
1606 /* Parse the incoming packet type */
1607 silc_server_packet_parse_type(server, sock, packet);
1609 if (server->server_type == SILC_ROUTER) {
1610 /* Broadcast packet if it is marked as broadcast packet and it is
1611 originated from router and we are router. */
1612 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1613 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1614 !server->standalone) {
1615 silc_server_packet_broadcast(server, server->router->connection, packet);
1620 /* silc_buffer_clear(sock->inbuf); */
1621 silc_packet_context_free(packet);
1622 silc_free(parse_ctx);
1625 /* Parser callback called by silc_packet_receive_process. This merely
1626 registers timeout that will handle the actual parsing when appropriate. */
1628 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1630 SilcServer server = (SilcServer)parser_context->context;
1631 SilcSocketConnection sock = parser_context->sock;
1633 switch (sock->type) {
1634 case SILC_SOCKET_TYPE_UNKNOWN:
1635 case SILC_SOCKET_TYPE_CLIENT:
1636 /* Parse the packet with timeout */
1637 silc_schedule_task_add(server->schedule, sock->sock,
1638 silc_server_packet_parse_real,
1639 (void *)parser_context, 0, 100000,
1641 SILC_TASK_PRI_NORMAL);
1643 case SILC_SOCKET_TYPE_SERVER:
1644 case SILC_SOCKET_TYPE_ROUTER:
1645 /* Packets from servers are parsed as soon as possible */
1646 silc_schedule_task_add(server->schedule, sock->sock,
1647 silc_server_packet_parse_real,
1648 (void *)parser_context, 0, 1,
1650 SILC_TASK_PRI_NORMAL);
1657 /* Parses the packet type and calls what ever routines the packet type
1658 requires. This is done for all incoming packets. */
1660 void silc_server_packet_parse_type(SilcServer server,
1661 SilcSocketConnection sock,
1662 SilcPacketContext *packet)
1664 SilcPacketType type = packet->type;
1666 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1668 /* Parse the packet type */
1670 case SILC_PACKET_DISCONNECT:
1671 SILC_LOG_DEBUG(("Disconnect packet"));
1672 if (packet->flags & SILC_PACKET_FLAG_LIST)
1676 case SILC_PACKET_SUCCESS:
1678 * Success received for something. For now we can have only
1679 * one protocol for connection executing at once hence this
1680 * success message is for whatever protocol is executing currently.
1682 SILC_LOG_DEBUG(("Success packet"));
1683 if (packet->flags & SILC_PACKET_FLAG_LIST)
1686 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1689 case SILC_PACKET_FAILURE:
1691 * Failure received for something. For now we can have only
1692 * one protocol for connection executing at once hence this
1693 * failure message is for whatever protocol is executing currently.
1695 SILC_LOG_DEBUG(("Failure packet"));
1696 if (packet->flags & SILC_PACKET_FLAG_LIST)
1698 if (sock->protocol) {
1699 SilcServerFailureContext f;
1700 f = silc_calloc(1, sizeof(*f));
1704 /* We will wait 5 seconds to process this failure packet */
1705 silc_schedule_task_add(server->schedule, sock->sock,
1706 silc_server_failure_callback, (void *)f, 5, 0,
1707 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1711 case SILC_PACKET_REJECT:
1712 SILC_LOG_DEBUG(("Reject packet"));
1713 if (packet->flags & SILC_PACKET_FLAG_LIST)
1718 case SILC_PACKET_NOTIFY:
1720 * Received notify packet. Server can receive notify packets from
1721 * router. Server then relays the notify messages to clients if needed.
1723 SILC_LOG_DEBUG(("Notify packet"));
1724 if (packet->flags & SILC_PACKET_FLAG_LIST)
1725 silc_server_notify_list(server, sock, packet);
1727 silc_server_notify(server, sock, packet);
1733 case SILC_PACKET_CHANNEL_MESSAGE:
1735 * Received channel message. Channel messages are special packets
1736 * (although probably most common ones) thus they are handled
1739 SILC_LOG_DEBUG(("Channel Message packet"));
1740 if (packet->flags & SILC_PACKET_FLAG_LIST)
1742 silc_server_channel_message(server, sock, packet);
1745 case SILC_PACKET_CHANNEL_KEY:
1747 * Received key for channel. As channels are created by the router
1748 * the keys are as well. We will distribute the key to all of our
1749 * locally connected clients on the particular channel. Router
1750 * never receives this channel and thus is ignored.
1752 SILC_LOG_DEBUG(("Channel Key packet"));
1753 if (packet->flags & SILC_PACKET_FLAG_LIST)
1755 silc_server_channel_key(server, sock, packet);
1761 case SILC_PACKET_COMMAND:
1763 * Recived command. Processes the command request and allocates the
1764 * command context and calls the command.
1766 SILC_LOG_DEBUG(("Command packet"));
1767 if (packet->flags & SILC_PACKET_FLAG_LIST)
1769 silc_server_command_process(server, sock, packet);
1772 case SILC_PACKET_COMMAND_REPLY:
1774 * Received command reply packet. Received command reply to command. It
1775 * may be reply to command sent by us or reply to command sent by client
1776 * that we've routed further.
1778 SILC_LOG_DEBUG(("Command Reply packet"));
1779 if (packet->flags & SILC_PACKET_FLAG_LIST)
1781 silc_server_command_reply(server, sock, packet);
1785 * Private Message packets
1787 case SILC_PACKET_PRIVATE_MESSAGE:
1789 * Received private message packet. The packet is coming from either
1792 SILC_LOG_DEBUG(("Private Message packet"));
1793 if (packet->flags & SILC_PACKET_FLAG_LIST)
1795 silc_server_private_message(server, sock, packet);
1798 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1800 * Private message key packet.
1802 if (packet->flags & SILC_PACKET_FLAG_LIST)
1804 silc_server_private_message_key(server, sock, packet);
1808 * Key Exchange protocol packets
1810 case SILC_PACKET_KEY_EXCHANGE:
1811 SILC_LOG_DEBUG(("KE packet"));
1812 if (packet->flags & SILC_PACKET_FLAG_LIST)
1815 if (sock->protocol && sock->protocol->protocol &&
1816 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1818 SilcServerKEInternalContext *proto_ctx =
1819 (SilcServerKEInternalContext *)sock->protocol->context;
1821 proto_ctx->packet = silc_packet_context_dup(packet);
1823 /* Let the protocol handle the packet */
1824 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
1826 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1827 "protocol active, packet dropped."));
1831 case SILC_PACKET_KEY_EXCHANGE_1:
1832 SILC_LOG_DEBUG(("KE 1 packet"));
1833 if (packet->flags & SILC_PACKET_FLAG_LIST)
1836 if (sock->protocol && sock->protocol->protocol &&
1837 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1838 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
1840 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
1841 SilcServerRekeyInternalContext *proto_ctx =
1842 (SilcServerRekeyInternalContext *)sock->protocol->context;
1844 if (proto_ctx->packet)
1845 silc_packet_context_free(proto_ctx->packet);
1847 proto_ctx->packet = silc_packet_context_dup(packet);
1849 /* Let the protocol handle the packet */
1850 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1852 SilcServerKEInternalContext *proto_ctx =
1853 (SilcServerKEInternalContext *)sock->protocol->context;
1855 if (proto_ctx->packet)
1856 silc_packet_context_free(proto_ctx->packet);
1858 proto_ctx->packet = silc_packet_context_dup(packet);
1859 proto_ctx->dest_id_type = packet->src_id_type;
1860 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1861 packet->src_id_type);
1862 if (!proto_ctx->dest_id)
1865 /* Let the protocol handle the packet */
1866 silc_protocol_execute(sock->protocol, server->schedule,
1870 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1871 "protocol active, packet dropped."));
1875 case SILC_PACKET_KEY_EXCHANGE_2:
1876 SILC_LOG_DEBUG(("KE 2 packet"));
1877 if (packet->flags & SILC_PACKET_FLAG_LIST)
1880 if (sock->protocol && sock->protocol->protocol &&
1881 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1882 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
1884 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
1885 SilcServerRekeyInternalContext *proto_ctx =
1886 (SilcServerRekeyInternalContext *)sock->protocol->context;
1888 if (proto_ctx->packet)
1889 silc_packet_context_free(proto_ctx->packet);
1891 proto_ctx->packet = silc_packet_context_dup(packet);
1893 /* Let the protocol handle the packet */
1894 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1896 SilcServerKEInternalContext *proto_ctx =
1897 (SilcServerKEInternalContext *)sock->protocol->context;
1899 if (proto_ctx->packet)
1900 silc_packet_context_free(proto_ctx->packet);
1902 proto_ctx->packet = silc_packet_context_dup(packet);
1903 proto_ctx->dest_id_type = packet->src_id_type;
1904 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1905 packet->src_id_type);
1906 if (!proto_ctx->dest_id)
1909 /* Let the protocol handle the packet */
1910 silc_protocol_execute(sock->protocol, server->schedule,
1914 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1915 "protocol active, packet dropped."));
1919 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1921 * Connection authentication request packet. When we receive this packet
1922 * we will send to the other end information about our mandatory
1923 * authentication method for the connection. This packet maybe received
1926 SILC_LOG_DEBUG(("Connection authentication request packet"));
1927 if (packet->flags & SILC_PACKET_FLAG_LIST)
1929 silc_server_connection_auth_request(server, sock, packet);
1933 * Connection Authentication protocol packets
1935 case SILC_PACKET_CONNECTION_AUTH:
1936 /* Start of the authentication protocol. We receive here the
1937 authentication data and will verify it. */
1938 SILC_LOG_DEBUG(("Connection auth packet"));
1939 if (packet->flags & SILC_PACKET_FLAG_LIST)
1942 if (sock->protocol && sock->protocol->protocol->type
1943 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1945 SilcServerConnAuthInternalContext *proto_ctx =
1946 (SilcServerConnAuthInternalContext *)sock->protocol->context;
1948 proto_ctx->packet = silc_packet_context_dup(packet);
1950 /* Let the protocol handle the packet */
1951 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1953 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1954 "protocol active, packet dropped."));
1958 case SILC_PACKET_NEW_ID:
1960 * Received New ID packet. This includes some new ID that has been
1961 * created. It may be for client, server or channel. This is the way
1962 * to distribute information about new registered entities in the
1965 SILC_LOG_DEBUG(("New ID packet"));
1966 if (packet->flags & SILC_PACKET_FLAG_LIST)
1967 silc_server_new_id_list(server, sock, packet);
1969 silc_server_new_id(server, sock, packet);
1972 case SILC_PACKET_NEW_CLIENT:
1974 * Received new client packet. This includes client information that
1975 * we will use to create initial client ID. After creating new
1976 * ID we will send it to the client.
1978 SILC_LOG_DEBUG(("New Client packet"));
1979 if (packet->flags & SILC_PACKET_FLAG_LIST)
1981 silc_server_new_client(server, sock, packet);
1984 case SILC_PACKET_NEW_SERVER:
1986 * Received new server packet. This includes Server ID and some other
1987 * information that we may save. This is received after server has
1990 SILC_LOG_DEBUG(("New Server packet"));
1991 if (packet->flags & SILC_PACKET_FLAG_LIST)
1993 silc_server_new_server(server, sock, packet);
1996 case SILC_PACKET_NEW_CHANNEL:
1998 * Received new channel packet. Information about new channel in the
1999 * network are distributed using this packet.
2001 SILC_LOG_DEBUG(("New Channel packet"));
2002 if (packet->flags & SILC_PACKET_FLAG_LIST)
2003 silc_server_new_channel_list(server, sock, packet);
2005 silc_server_new_channel(server, sock, packet);
2008 case SILC_PACKET_HEARTBEAT:
2010 * Received heartbeat.
2012 SILC_LOG_DEBUG(("Heartbeat packet"));
2013 if (packet->flags & SILC_PACKET_FLAG_LIST)
2017 case SILC_PACKET_KEY_AGREEMENT:
2019 * Received heartbeat.
2021 SILC_LOG_DEBUG(("Key agreement packet"));
2022 if (packet->flags & SILC_PACKET_FLAG_LIST)
2024 silc_server_key_agreement(server, sock, packet);
2027 case SILC_PACKET_REKEY:
2029 * Received re-key packet. The sender wants to regenerate the session
2032 SILC_LOG_DEBUG(("Re-key packet"));
2033 if (packet->flags & SILC_PACKET_FLAG_LIST)
2035 silc_server_rekey(server, sock, packet);
2038 case SILC_PACKET_REKEY_DONE:
2040 * The re-key is done.
2042 SILC_LOG_DEBUG(("Re-key done packet"));
2043 if (packet->flags & SILC_PACKET_FLAG_LIST)
2046 if (sock->protocol && sock->protocol->protocol &&
2047 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2049 SilcServerRekeyInternalContext *proto_ctx =
2050 (SilcServerRekeyInternalContext *)sock->protocol->context;
2052 if (proto_ctx->packet)
2053 silc_packet_context_free(proto_ctx->packet);
2055 proto_ctx->packet = silc_packet_context_dup(packet);
2057 /* Let the protocol handle the packet */
2058 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2060 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2061 "protocol active, packet dropped."));
2066 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2072 /* Creates connection to a remote router. */
2074 void silc_server_create_connection(SilcServer server,
2075 char *remote_host, uint32 port)
2077 SilcServerConnection sconn;
2079 /* Allocate connection object for hold connection specific stuff. */
2080 sconn = silc_calloc(1, sizeof(*sconn));
2081 sconn->server = server;
2082 sconn->remote_host = strdup(remote_host);
2083 sconn->remote_port = port;
2085 silc_schedule_task_add(server->schedule, 0,
2086 silc_server_connect_router,
2087 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2088 SILC_TASK_PRI_NORMAL);
2091 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2093 silc_socket_free((SilcSocketConnection)context);
2096 /* Closes connection to socket connection */
2098 void silc_server_close_connection(SilcServer server,
2099 SilcSocketConnection sock)
2101 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2103 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2104 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2105 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2108 /* We won't listen for this connection anymore */
2109 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2111 /* Unregister all tasks */
2112 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
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;
2234 /* Free the client entry and everything in it */
2235 server->stat.my_clients--;
2236 server->stat.clients--;
2237 if (server->server_type == SILC_ROUTER)
2238 server->stat.cell_clients--;
2241 /* Frees user_data pointer from socket connection object. This also sends
2242 appropriate notify packets to the network to inform about leaving
2245 void silc_server_free_sock_user_data(SilcServer server,
2246 SilcSocketConnection sock)
2248 SILC_LOG_DEBUG(("Start"));
2250 switch(sock->type) {
2251 case SILC_SOCKET_TYPE_CLIENT:
2253 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2254 silc_server_free_client_data(server, sock, user_data, TRUE, NULL);
2257 case SILC_SOCKET_TYPE_SERVER:
2258 case SILC_SOCKET_TYPE_ROUTER:
2260 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2262 /* Free all client entries that this server owns as they will
2263 become invalid now as well. */
2265 silc_server_remove_clients_by_server(server, user_data, TRUE);
2267 /* If this was our primary router connection then we're lost to
2268 the outside world. */
2269 if (server->router == user_data) {
2270 server->id_entry->router = NULL;
2271 server->router = NULL;
2272 server->standalone = TRUE;
2275 /* Free the server entry */
2276 silc_idlist_del_data(user_data);
2277 silc_idlist_del_server(server->local_list, user_data);
2278 server->stat.my_servers--;
2279 server->stat.servers--;
2280 if (server->server_type == SILC_ROUTER)
2281 server->stat.cell_servers--;
2286 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2288 silc_idlist_del_data(user_data);
2289 silc_free(user_data);
2294 /* If any protocol is active cancel its execution */
2295 if (sock->protocol) {
2296 silc_protocol_cancel(sock->protocol, server->schedule);
2297 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2298 silc_protocol_execute_final(sock->protocol, server->schedule);
2299 sock->protocol = NULL;
2302 sock->user_data = NULL;
2305 /* Removes the client from channels and possibly removes the channels
2306 as well. After removing those channels that exist, their channel
2307 keys are regnerated. This is called only by the function
2308 silc_server_remove_clients_by_server. */
2310 static void silc_server_remove_clients_channels(SilcServer server,
2311 SilcSocketConnection sock,
2312 SilcClientEntry client,
2313 SilcHashTable channels)
2315 SilcChannelEntry channel;
2316 SilcChannelClientEntry chl;
2317 SilcHashTableList htl;
2320 SILC_LOG_DEBUG(("Start"));
2322 if (!client || !client->id)
2325 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2327 /* Remove the client from all channels. The client is removed from
2328 the channels' user list. */
2329 silc_hash_table_list(client->channels, &htl);
2330 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2331 channel = chl->channel;
2333 /* Remove channel from client's channel list */
2334 silc_hash_table_del(client->channels, channel);
2336 /* Remove channel if there is no users anymore */
2337 if (server->server_type == SILC_ROUTER &&
2338 silc_hash_table_count(channel->user_list) < 2) {
2340 if (silc_hash_table_find(channels, channel, NULL, NULL))
2341 silc_hash_table_del(channels, channel);
2344 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2346 if (!silc_idlist_del_channel(server->local_list, channel))
2347 silc_idlist_del_channel(server->global_list, channel);
2348 server->stat.my_channels--;
2352 /* Remove client from channel's client list */
2353 silc_hash_table_del(channel->user_list, chl->client);
2355 server->stat.my_chanclients--;
2357 /* If there is no global users on the channel anymore mark the channel
2358 as local channel. Do not check if the removed client is local client. */
2359 if (server->server_type == SILC_SERVER && channel->global_users &&
2360 chl->client->router && !silc_server_channel_has_global(channel))
2361 channel->global_users = FALSE;
2363 /* If there is not at least one local user on the channel then we don't
2364 need the channel entry anymore, we can remove it safely. */
2365 if (server->server_type == SILC_SERVER &&
2366 !silc_server_channel_has_local(channel)) {
2368 if (silc_hash_table_find(channels, channel, NULL, NULL))
2369 silc_hash_table_del(channels, channel);
2372 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2374 if (channel->founder_key) {
2375 /* The founder auth data exists, do not remove the channel entry */
2376 SilcChannelClientEntry chl2;
2377 SilcHashTableList htl2;
2381 silc_hash_table_list(channel->user_list, &htl2);
2382 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2383 silc_hash_table_del(chl2->client->channels, channel);
2384 silc_hash_table_del(channel->user_list, chl2->client);
2390 /* Remove the channel entry */
2391 if (!silc_idlist_del_channel(server->local_list, channel))
2392 silc_idlist_del_channel(server->global_list, channel);
2393 server->stat.my_channels--;
2397 /* Add the channel to the the channels list to regenerate the
2399 if (!silc_hash_table_find(channels, channel, NULL, NULL))
2400 silc_hash_table_add(channels, channel, channel);
2403 silc_buffer_free(clidp);
2406 /* This function is used to remove all client entries by the server `entry'.
2407 This is called when the connection is lost to the server. In this case
2408 we must invalidate all the client entries owned by the server `entry'.
2409 If the `server_signoff' is TRUE then the SERVER_SIGNOFF notify is
2410 distributed to our local clients. */
2412 int silc_server_remove_clients_by_server(SilcServer server,
2413 SilcServerEntry entry,
2416 SilcIDCacheList list = NULL;
2417 SilcIDCacheEntry id_cache = NULL;
2418 SilcClientEntry client = NULL;
2420 SilcClientEntry *clients = NULL;
2421 uint32 clients_c = 0;
2422 unsigned char **argv = NULL;
2423 uint32 *argv_lens = NULL, *argv_types = NULL, argc = 0;
2424 SilcHashTableList htl;
2425 SilcChannelEntry channel;
2426 SilcHashTable channels;
2429 SILC_LOG_DEBUG(("Start"));
2431 /* Allocate the hash table that holds the channels that require
2432 channel key re-generation after we've removed this server's clients
2433 from the channels. */
2434 channels = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL, NULL,
2437 if (server_signoff) {
2438 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
2439 argv = silc_realloc(argv, sizeof(*argv) * (argc + 1));
2440 argv_lens = silc_realloc(argv_lens, sizeof(*argv_lens) * (argc + 1));
2441 argv_types = silc_realloc(argv_types, sizeof(*argv_types) * (argc + 1));
2442 argv[argc] = silc_calloc(idp->len, sizeof(*argv[0]));
2443 memcpy(argv[argc], idp->data, idp->len);
2444 argv_lens[argc] = idp->len;
2445 argv_types[argc] = argc + 1;
2447 silc_buffer_free(idp);
2450 if (silc_idcache_get_all(server->local_list->clients, &list)) {
2452 if (silc_idcache_list_first(list, &id_cache)) {
2454 client = (SilcClientEntry)id_cache->context;
2455 if (client->data.registered == FALSE) {
2456 if (!silc_idcache_list_next(list, &id_cache))
2462 if (client->router != entry) {
2463 if (server_signoff && client->connection) {
2464 clients = silc_realloc(clients,
2465 sizeof(*clients) * (clients_c + 1));
2466 clients[clients_c] = client;
2470 if (!silc_idcache_list_next(list, &id_cache))
2476 if (server_signoff) {
2477 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2478 argv = silc_realloc(argv, sizeof(*argv) * (argc + 1));
2479 argv_lens = silc_realloc(argv_lens, sizeof(*argv_lens) *
2481 argv_types = silc_realloc(argv_types, sizeof(*argv_types) *
2483 argv[argc] = silc_calloc(idp->len, sizeof(*argv[0]));
2484 memcpy(argv[argc], idp->data, idp->len);
2485 argv_lens[argc] = idp->len;
2486 argv_types[argc] = argc + 1;
2488 silc_buffer_free(idp);
2491 /* Remove the client entry */
2492 silc_server_remove_clients_channels(server, NULL, client, channels);
2493 silc_idlist_del_client(server->local_list, client);
2495 if (!silc_idcache_list_next(list, &id_cache))
2499 silc_idcache_list_free(list);
2502 if (silc_idcache_get_all(server->global_list->clients, &list)) {
2504 if (silc_idcache_list_first(list, &id_cache)) {
2506 client = (SilcClientEntry)id_cache->context;
2507 if (client->data.registered == FALSE) {
2508 if (!silc_idcache_list_next(list, &id_cache))
2514 if (client->router != entry) {
2515 if (server_signoff && client->connection) {
2516 clients = silc_realloc(clients,
2517 sizeof(*clients) * (clients_c + 1));
2518 clients[clients_c] = client;
2522 if (!silc_idcache_list_next(list, &id_cache))
2528 if (server_signoff) {
2529 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2530 argv = silc_realloc(argv, sizeof(*argv) * (argc + 1));
2531 argv_lens = silc_realloc(argv_lens, sizeof(*argv_lens) *
2533 argv_types = silc_realloc(argv_types, sizeof(*argv_types) *
2535 argv[argc] = silc_calloc(idp->len, sizeof(*argv[0]));
2536 memcpy(argv[argc], idp->data, idp->len);
2537 argv_lens[argc] = idp->len;
2538 argv_types[argc] = argc + 1;
2540 silc_buffer_free(idp);
2543 /* Remove the client entry */
2544 silc_server_remove_clients_channels(server, NULL, client, channels);
2545 silc_idlist_del_client(server->global_list, client);
2547 if (!silc_idcache_list_next(list, &id_cache))
2551 silc_idcache_list_free(list);
2554 /* Send the SERVER_SIGNOFF notify */
2555 if (server_signoff) {
2558 /* Send SERVER_SIGNOFF notify to our primary router */
2559 if (!server->standalone && server->router &&
2560 server->router != entry) {
2561 args = silc_argument_payload_encode(1, argv, argv_lens,
2563 silc_server_send_notify_args(server,
2564 server->router->connection,
2565 server->server_type == SILC_SERVER ?
2567 SILC_NOTIFY_TYPE_SERVER_SIGNOFF,
2569 silc_buffer_free(args);
2572 args = silc_argument_payload_encode(argc, argv, argv_lens,
2574 /* Send to local clients */
2575 for (i = 0; i < clients_c; i++) {
2576 silc_server_send_notify_args(server, clients[i]->connection,
2577 FALSE, SILC_NOTIFY_TYPE_SERVER_SIGNOFF,
2582 silc_buffer_free(args);
2583 for (i = 0; i < argc; i++)
2586 silc_free(argv_lens);
2587 silc_free(argv_types);
2590 /* We must now re-generate the channel key for all channels that had
2591 this server's client(s) on the channel. As they left the channel we
2592 must re-generate the channel key. */
2593 silc_hash_table_list(channels, &htl);
2594 while (silc_hash_table_get(&htl, NULL, (void *)&channel)) {
2595 if (!silc_server_create_channel_key(server, channel, 0))
2597 silc_server_send_channel_key(server, NULL, channel,
2598 server->server_type == SILC_ROUTER ?
2599 FALSE : !server->standalone);
2601 silc_hash_table_free(channels);
2606 /* Checks whether given channel has global users. If it does this returns
2607 TRUE and FALSE if there is only locally connected clients on the channel. */
2609 int silc_server_channel_has_global(SilcChannelEntry channel)
2611 SilcChannelClientEntry chl;
2612 SilcHashTableList htl;
2614 silc_hash_table_list(channel->user_list, &htl);
2615 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2616 if (chl->client->router)
2623 /* Checks whether given channel has locally connected users. If it does this
2624 returns TRUE and FALSE if there is not one locally connected client. */
2626 int silc_server_channel_has_local(SilcChannelEntry channel)
2628 SilcChannelClientEntry chl;
2629 SilcHashTableList htl;
2631 silc_hash_table_list(channel->user_list, &htl);
2632 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2633 if (!chl->client->router)
2640 /* Removes client from all channels it has joined. This is used when client
2641 connection is disconnected. If the client on a channel is last, the
2642 channel is removed as well. This sends the SIGNOFF notify types. */
2644 void silc_server_remove_from_channels(SilcServer server,
2645 SilcSocketConnection sock,
2646 SilcClientEntry client,
2648 char *signoff_message,
2651 SilcChannelEntry channel;
2652 SilcChannelClientEntry chl;
2653 SilcHashTableList htl;
2656 SILC_LOG_DEBUG(("Start"));
2658 if (!client || !client->id)
2661 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2663 /* Remove the client from all channels. The client is removed from
2664 the channels' user list. */
2665 silc_hash_table_list(client->channels, &htl);
2666 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2667 channel = chl->channel;
2669 /* Remove channel from client's channel list */
2670 silc_hash_table_del(client->channels, channel);
2672 /* Remove channel if there is no users anymore */
2673 if (server->server_type == SILC_ROUTER &&
2674 silc_hash_table_count(channel->user_list) < 2) {
2676 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2677 if (!silc_idlist_del_channel(server->local_list, channel))
2678 silc_idlist_del_channel(server->global_list, channel);
2679 server->stat.my_channels--;
2683 /* Remove client from channel's client list */
2684 silc_hash_table_del(channel->user_list, chl->client);
2686 server->stat.my_chanclients--;
2688 /* If there is no global users on the channel anymore mark the channel
2689 as local channel. Do not check if the removed client is local client. */
2690 if (server->server_type == SILC_SERVER && channel->global_users &&
2691 chl->client->router && !silc_server_channel_has_global(channel))
2692 channel->global_users = FALSE;
2694 /* If there is not at least one local user on the channel then we don't
2695 need the channel entry anymore, we can remove it safely. */
2696 if (server->server_type == SILC_SERVER &&
2697 !silc_server_channel_has_local(channel)) {
2698 /* Notify about leaving client if this channel has global users. */
2699 if (notify && channel->global_users)
2700 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2701 SILC_NOTIFY_TYPE_SIGNOFF,
2702 signoff_message ? 2 : 1,
2703 clidp->data, clidp->len,
2704 signoff_message, signoff_message ?
2705 strlen(signoff_message) : 0);
2708 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2710 if (channel->founder_key) {
2711 /* The founder auth data exists, do not remove the channel entry */
2712 SilcChannelClientEntry chl2;
2713 SilcHashTableList htl2;
2717 silc_hash_table_list(channel->user_list, &htl2);
2718 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2719 silc_hash_table_del(chl2->client->channels, channel);
2720 silc_hash_table_del(channel->user_list, chl2->client);
2726 /* Remove the channel entry */
2727 if (!silc_idlist_del_channel(server->local_list, channel))
2728 silc_idlist_del_channel(server->global_list, channel);
2729 server->stat.my_channels--;
2733 /* Send notify to channel about client leaving SILC and thus
2734 the entire channel. */
2736 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2737 SILC_NOTIFY_TYPE_SIGNOFF,
2738 signoff_message ? 2 : 1,
2739 clidp->data, clidp->len,
2740 signoff_message, signoff_message ?
2741 strlen(signoff_message) : 0);
2743 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2744 /* Re-generate channel key */
2745 if (!silc_server_create_channel_key(server, channel, 0))
2748 /* Send the channel key to the channel. The key of course is not sent
2749 to the client who was removed from the channel. */
2750 silc_server_send_channel_key(server, client->connection, channel,
2751 server->server_type == SILC_ROUTER ?
2752 FALSE : !server->standalone);
2756 silc_buffer_free(clidp);
2759 /* Removes client from one channel. This is used for example when client
2760 calls LEAVE command to remove itself from the channel. Returns TRUE
2761 if channel still exists and FALSE if the channel is removed when
2762 last client leaves the channel. If `notify' is FALSE notify messages
2765 int silc_server_remove_from_one_channel(SilcServer server,
2766 SilcSocketConnection sock,
2767 SilcChannelEntry channel,
2768 SilcClientEntry client,
2771 SilcChannelClientEntry chl;
2774 SILC_LOG_DEBUG(("Start"));
2776 /* Get the entry to the channel, if this client is not on the channel
2778 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2781 /* Remove the client from the channel. The client is removed from
2782 the channel's user list. */
2784 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2786 /* Remove channel from client's channel list */
2787 silc_hash_table_del(client->channels, chl->channel);
2789 /* Remove channel if there is no users anymore */
2790 if (server->server_type == SILC_ROUTER &&
2791 silc_hash_table_count(channel->user_list) < 2) {
2793 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2794 if (!silc_idlist_del_channel(server->local_list, channel))
2795 silc_idlist_del_channel(server->global_list, channel);
2796 silc_buffer_free(clidp);
2797 server->stat.my_channels--;
2801 /* Remove client from channel's client list */
2802 silc_hash_table_del(channel->user_list, chl->client);
2804 server->stat.my_chanclients--;
2806 /* If there is no global users on the channel anymore mark the channel
2807 as local channel. Do not check if the client is local client. */
2808 if (server->server_type == SILC_SERVER && channel->global_users &&
2809 chl->client->router && !silc_server_channel_has_global(channel))
2810 channel->global_users = FALSE;
2812 /* If there is not at least one local user on the channel then we don't
2813 need the channel entry anymore, we can remove it safely. */
2814 if (server->server_type == SILC_SERVER &&
2815 !silc_server_channel_has_local(channel)) {
2816 /* Notify about leaving client if this channel has global users. */
2817 if (notify && channel->global_users)
2818 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2819 SILC_NOTIFY_TYPE_LEAVE, 1,
2820 clidp->data, clidp->len);
2822 silc_buffer_free(clidp);
2825 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2827 if (channel->founder_key) {
2828 /* The founder auth data exists, do not remove the channel entry */
2829 SilcChannelClientEntry chl2;
2830 SilcHashTableList htl2;
2834 silc_hash_table_list(channel->user_list, &htl2);
2835 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2836 silc_hash_table_del(chl2->client->channels, channel);
2837 silc_hash_table_del(channel->user_list, chl2->client);
2843 /* Remove the channel entry */
2844 if (!silc_idlist_del_channel(server->local_list, channel))
2845 silc_idlist_del_channel(server->global_list, channel);
2846 server->stat.my_channels--;
2850 /* Send notify to channel about client leaving the channel */
2852 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2853 SILC_NOTIFY_TYPE_LEAVE, 1,
2854 clidp->data, clidp->len);
2856 silc_buffer_free(clidp);
2860 /* Returns TRUE if the given client is on the channel. FALSE if not.
2861 This works because we assure that the user list on the channel is
2862 always in up to date thus we can only check the channel list from
2863 `client' which is faster than checking the user list from `channel'. */
2865 int silc_server_client_on_channel(SilcClientEntry client,
2866 SilcChannelEntry channel)
2868 if (!client || !channel)
2871 if (silc_hash_table_find(client->channels, channel, NULL, NULL))
2877 /* Timeout callback. This is called if connection is idle or for some
2878 other reason is not responding within some period of time. This
2879 disconnects the remote end. */
2881 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2883 SilcServer server = (SilcServer)context;
2884 SilcSocketConnection sock = server->sockets[fd];
2886 SILC_LOG_DEBUG(("Start"));
2891 /* If we have protocol active we must assure that we call the protocol's
2892 final callback so that all the memory is freed. */
2893 if (sock->protocol) {
2894 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2895 silc_protocol_execute_final(sock->protocol, server->schedule);
2899 if (sock->user_data)
2900 silc_server_free_sock_user_data(server, sock);
2902 silc_server_disconnect_remote(server, sock, "Server closed connection: "
2903 "Connection timeout");
2906 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2907 function may be used only by router. In real SILC network all channels
2908 are created by routers thus this function is never used by normal
2911 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2912 SilcServerID *router_id,
2918 SilcChannelID *channel_id;
2919 SilcChannelEntry entry;
2923 SILC_LOG_DEBUG(("Creating new channel"));
2926 cipher = "aes-256-cbc";
2928 hmac = "hmac-sha1-96";
2930 /* Allocate cipher */
2931 if (!silc_cipher_alloc(cipher, &key))
2935 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2936 silc_cipher_free(key);
2940 channel_name = strdup(channel_name);
2942 /* Create the channel */
2943 silc_id_create_channel_id(router_id, server->rng, &channel_id);
2944 entry = silc_idlist_add_channel(server->local_list, channel_name,
2945 SILC_CHANNEL_MODE_NONE, channel_id,
2946 NULL, key, newhmac);
2948 silc_free(channel_name);
2949 silc_cipher_free(key);
2950 silc_hmac_free(newhmac);
2954 entry->cipher = strdup(cipher);
2955 entry->hmac_name = strdup(hmac);
2957 /* Now create the actual key material */
2958 if (!silc_server_create_channel_key(server, entry,
2959 silc_cipher_get_key_len(key) / 8)) {
2960 silc_free(channel_name);
2961 silc_cipher_free(key);
2962 silc_hmac_free(newhmac);
2963 silc_free(entry->cipher);
2964 silc_free(entry->hmac_name);
2968 /* Notify other routers about the new channel. We send the packet
2969 to our primary route. */
2970 if (broadcast && server->standalone == FALSE)
2971 silc_server_send_new_channel(server, server->router->connection, TRUE,
2972 channel_name, entry->id,
2973 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2976 server->stat.my_channels++;
2981 /* Same as above but creates the channel with Channel ID `channel_id. */
2984 silc_server_create_new_channel_with_id(SilcServer server,
2988 SilcChannelID *channel_id,
2991 SilcChannelEntry entry;
2995 SILC_LOG_DEBUG(("Creating new channel"));
2998 cipher = "aes-256-cbc";
3000 hmac = "hmac-sha1-96";
3002 /* Allocate cipher */
3003 if (!silc_cipher_alloc(cipher, &key))
3007 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3008 silc_cipher_free(key);
3012 channel_name = strdup(channel_name);
3014 /* Create the channel */
3015 entry = silc_idlist_add_channel(server->local_list, channel_name,
3016 SILC_CHANNEL_MODE_NONE, channel_id,
3017 NULL, key, newhmac);
3019 silc_free(channel_name);
3023 /* Now create the actual key material */
3024 if (!silc_server_create_channel_key(server, entry,
3025 silc_cipher_get_key_len(key) / 8)) {
3026 silc_free(channel_name);
3030 /* Notify other routers about the new channel. We send the packet
3031 to our primary route. */
3032 if (broadcast && server->standalone == FALSE)
3033 silc_server_send_new_channel(server, server->router->connection, TRUE,
3034 channel_name, entry->id,
3035 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3038 server->stat.my_channels++;
3043 /* Channel's key re-key timeout callback. */
3045 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3047 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3048 SilcServer server = (SilcServer)rekey->context;
3050 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3052 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3054 silc_schedule_task_add(server->schedule, 0,
3055 silc_server_channel_key_rekey,
3056 (void *)rekey, 3600, 0,
3058 SILC_TASK_PRI_NORMAL);
3061 /* Generates new channel key. This is used to create the initial channel key
3062 but also to re-generate new key for channel. If `key_len' is provided
3063 it is the bytes of the key length. */
3065 bool silc_server_create_channel_key(SilcServer server,
3066 SilcChannelEntry channel,
3070 unsigned char channel_key[32], hash[32];
3073 SILC_LOG_DEBUG(("Generating channel key"));
3075 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3076 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3080 if (!channel->channel_key)
3081 if (!silc_cipher_alloc("aes-256-cbc", &channel->channel_key))
3086 else if (channel->key_len)
3087 len = channel->key_len / 8;
3089 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3091 /* Create channel key */
3092 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3095 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3097 /* Remove old key if exists */
3099 memset(channel->key, 0, channel->key_len / 8);
3100 silc_free(channel->key);
3104 channel->key_len = len * 8;
3105 channel->key = silc_calloc(len, sizeof(*channel->key));
3106 memcpy(channel->key, channel_key, len);
3107 memset(channel_key, 0, sizeof(channel_key));
3109 /* Generate HMAC key from the channel key data and set it */
3111 silc_hmac_alloc("hmac-sha1-96", NULL, &channel->hmac);
3112 silc_hash_make(channel->hmac->hash, channel->key, len, hash);
3113 silc_hmac_set_key(channel->hmac, hash, silc_hash_len(channel->hmac->hash));
3114 memset(hash, 0, sizeof(hash));
3116 if (server->server_type == SILC_ROUTER) {
3117 if (!channel->rekey)
3118 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3119 channel->rekey->context = (void *)server;
3120 channel->rekey->channel = channel;
3121 channel->rekey->key_len = key_len;
3124 /* XXX Now this cannot be a good thing */
3125 silc_schedule_task_del_by_callback(server->schedule,
3126 silc_server_channel_key_rekey);
3128 silc_schedule_task_add(server->schedule, 0,
3129 silc_server_channel_key_rekey,
3130 (void *)channel->rekey, 3600, 0,
3132 SILC_TASK_PRI_NORMAL);
3138 /* Saves the channel key found in the encoded `key_payload' buffer. This
3139 function is used when we receive Channel Key Payload and also when we're
3140 processing JOIN command reply. Returns entry to the channel. */
3142 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3143 SilcBuffer key_payload,
3144 SilcChannelEntry channel)
3146 SilcChannelKeyPayload payload = NULL;
3147 SilcChannelID *id = NULL;
3148 unsigned char *tmp, hash[32];
3152 SILC_LOG_DEBUG(("Start"));
3154 /* Decode channel key payload */
3155 payload = silc_channel_key_payload_parse(key_payload);
3157 SILC_LOG_ERROR(("Bad channel key payload, dropped"));
3162 /* Get the channel entry */
3165 /* Get channel ID */
3166 tmp = silc_channel_key_get_id(payload, &tmp_len);
3167 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3173 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3175 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3177 SILC_LOG_ERROR(("Received key for non-existent channel"));
3183 tmp = silc_channel_key_get_key(payload, &tmp_len);
3189 cipher = silc_channel_key_get_cipher(payload, NULL);
3195 /* Remove old key if exists */
3197 memset(channel->key, 0, channel->key_len / 8);
3198 silc_free(channel->key);
3199 silc_cipher_free(channel->channel_key);
3202 /* Create new cipher */
3203 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3208 if (channel->cipher)
3209 silc_free(channel->cipher);
3210 channel->cipher = strdup(cipher);
3213 channel->key_len = tmp_len * 8;
3214 channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
3215 memcpy(channel->key, tmp, tmp_len);
3216 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3218 /* Generate HMAC key from the channel key data and set it */
3220 silc_hmac_alloc("hmac-sha1-96", NULL, &channel->hmac);
3221 silc_hash_make(channel->hmac->hash, tmp, tmp_len, hash);
3222 silc_hmac_set_key(channel->hmac, hash, silc_hash_len(channel->hmac->hash));
3224 memset(hash, 0, sizeof(hash));
3225 memset(tmp, 0, tmp_len);
3227 if (server->server_type == SILC_ROUTER) {
3228 if (!channel->rekey)
3229 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3230 channel->rekey->context = (void *)server;
3231 channel->rekey->channel = channel;
3233 silc_schedule_task_del_by_callback(server->schedule,
3234 silc_server_channel_key_rekey);
3235 silc_schedule_task_add(server->schedule, 0,
3236 silc_server_channel_key_rekey,
3237 (void *)channel->rekey, 3600, 0,
3239 SILC_TASK_PRI_NORMAL);
3246 silc_channel_key_payload_free(payload);
3251 /* Heartbeat callback. This function is set as argument for the
3252 silc_socket_set_heartbeat function. The library will call this function
3253 at the set time interval. */
3255 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3258 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3260 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname,
3263 /* Send the heartbeat */
3264 silc_server_send_heartbeat(hb->server, sock);
3267 /* Returns assembled of all servers in the given ID list. The packet's
3268 form is dictated by the New ID payload. */
3270 static void silc_server_announce_get_servers(SilcServer server,
3272 SilcBuffer *servers)
3274 SilcIDCacheList list;
3275 SilcIDCacheEntry id_cache;
3276 SilcServerEntry entry;
3279 /* Go through all clients in the list */
3280 if (silc_idcache_get_all(id_list->servers, &list)) {
3281 if (silc_idcache_list_first(list, &id_cache)) {
3283 entry = (SilcServerEntry)id_cache->context;
3285 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3287 *servers = silc_buffer_realloc(*servers,
3289 (*servers)->truelen + idp->len :
3291 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3292 silc_buffer_put(*servers, idp->data, idp->len);
3293 silc_buffer_pull(*servers, idp->len);
3294 silc_buffer_free(idp);
3296 if (!silc_idcache_list_next(list, &id_cache))
3301 silc_idcache_list_free(list);
3305 /* This function is used by router to announce existing servers to our
3306 primary router when we've connected to it. */
3308 void silc_server_announce_servers(SilcServer server)
3310 SilcBuffer servers = NULL;
3312 SILC_LOG_DEBUG(("Announcing servers"));
3314 /* Get servers in local list */
3315 silc_server_announce_get_servers(server, server->local_list, &servers);
3317 /* Get servers in global list */
3318 silc_server_announce_get_servers(server, server->global_list, &servers);
3321 silc_buffer_push(servers, servers->data - servers->head);
3322 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3324 /* Send the packet */
3325 silc_server_packet_send(server, server->router->connection,
3326 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3327 servers->data, servers->len, TRUE);
3329 silc_buffer_free(servers);
3333 /* Returns assembled packet of all clients in the given ID list. The
3334 packet's form is dictated by the New ID Payload. */
3336 static void silc_server_announce_get_clients(SilcServer server,
3338 SilcBuffer *clients)
3340 SilcIDCacheList list;
3341 SilcIDCacheEntry id_cache;
3342 SilcClientEntry client;
3345 /* Go through all clients in the list */
3346 if (silc_idcache_get_all(id_list->clients, &list)) {
3347 if (silc_idcache_list_first(list, &id_cache)) {
3349 client = (SilcClientEntry)id_cache->context;
3351 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3353 *clients = silc_buffer_realloc(*clients,
3355 (*clients)->truelen + idp->len :
3357 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3358 silc_buffer_put(*clients, idp->data, idp->len);
3359 silc_buffer_pull(*clients, idp->len);
3360 silc_buffer_free(idp);
3362 if (!silc_idcache_list_next(list, &id_cache))
3367 silc_idcache_list_free(list);
3371 /* This function is used to announce our existing clients to our router
3372 when we've connected to it. */
3374 void silc_server_announce_clients(SilcServer server)
3376 SilcBuffer clients = NULL;
3378 SILC_LOG_DEBUG(("Announcing clients"));
3380 /* Get clients in local list */
3381 silc_server_announce_get_clients(server, server->local_list,
3384 /* As router we announce our global list as well */
3385 if (server->server_type == SILC_ROUTER)
3386 silc_server_announce_get_clients(server, server->global_list,
3390 silc_buffer_push(clients, clients->data - clients->head);
3391 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3393 /* Send the packet */
3394 silc_server_packet_send(server, server->router->connection,
3395 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3396 clients->data, clients->len, TRUE);
3398 silc_buffer_free(clients);
3403 silc_server_announce_encode_notify(SilcNotifyType notify, uint32 argc, ...)
3409 p = silc_notify_payload_encode(notify, argc, ap);
3415 /* Returns assembled packets for channel users of the `channel'. */
3417 void silc_server_announce_get_channel_users(SilcServer server,
3418 SilcChannelEntry channel,
3419 SilcBuffer *channel_users,
3420 SilcBuffer *channel_users_modes)
3422 SilcChannelClientEntry chl;
3423 SilcHashTableList htl;
3424 SilcBuffer chidp, clidp;
3427 unsigned char mode[4];
3429 SILC_LOG_DEBUG(("Start"));
3431 /* Now find all users on the channel */
3432 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3433 silc_hash_table_list(channel->user_list, &htl);
3434 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3435 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3438 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3439 clidp->data, clidp->len,
3440 chidp->data, chidp->len);
3443 silc_buffer_realloc(*channel_users,
3445 (*channel_users)->truelen + len : len));
3446 silc_buffer_pull_tail(*channel_users,
3447 ((*channel_users)->end -
3448 (*channel_users)->data));
3450 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3451 silc_buffer_pull(*channel_users, len);
3452 silc_buffer_free(tmp);
3454 /* CUMODE notify for mode change on the channel */
3455 SILC_PUT32_MSB(chl->mode, mode);
3456 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3457 3, clidp->data, clidp->len,
3459 clidp->data, clidp->len);
3461 *channel_users_modes =
3462 silc_buffer_realloc(*channel_users_modes,
3463 (*channel_users_modes ?
3464 (*channel_users_modes)->truelen + len : len));
3465 silc_buffer_pull_tail(*channel_users_modes,
3466 ((*channel_users_modes)->end -
3467 (*channel_users_modes)->data));
3469 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3470 silc_buffer_pull(*channel_users_modes, len);
3471 silc_buffer_free(tmp);
3473 silc_buffer_free(clidp);
3475 silc_buffer_free(chidp);
3478 /* Returns assembled packets for all channels and users on those channels
3479 from the given ID List. The packets are in the form dictated by the
3480 New Channel and New Channel User payloads. */
3482 void silc_server_announce_get_channels(SilcServer server,
3484 SilcBuffer *channels,
3485 SilcBuffer *channel_users,
3486 SilcBuffer **channel_users_modes,
3487 uint32 *channel_users_modes_c,
3488 SilcChannelID ***channel_ids)
3490 SilcIDCacheList list;
3491 SilcIDCacheEntry id_cache;
3492 SilcChannelEntry channel;
3497 int i = *channel_users_modes_c;
3499 SILC_LOG_DEBUG(("Start"));
3501 /* Go through all channels in the list */
3502 if (silc_idcache_get_all(id_list->channels, &list)) {
3503 if (silc_idcache_list_first(list, &id_cache)) {
3505 channel = (SilcChannelEntry)id_cache->context;
3507 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3508 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3509 name_len = strlen(channel->channel_name);
3511 len = 4 + name_len + id_len + 4;
3513 silc_buffer_realloc(*channels,
3514 (*channels ? (*channels)->truelen + len : len));
3515 silc_buffer_pull_tail(*channels,
3516 ((*channels)->end - (*channels)->data));
3517 silc_buffer_format(*channels,
3518 SILC_STR_UI_SHORT(name_len),
3519 SILC_STR_UI_XNSTRING(channel->channel_name,
3521 SILC_STR_UI_SHORT(id_len),
3522 SILC_STR_UI_XNSTRING(cid, id_len),
3523 SILC_STR_UI_INT(channel->mode),
3525 silc_buffer_pull(*channels, len);
3527 *channel_users_modes = silc_realloc(*channel_users_modes,
3528 sizeof(**channel_users_modes) *
3530 (*channel_users_modes)[i] = NULL;
3531 *channel_ids = silc_realloc(*channel_ids,
3532 sizeof(**channel_ids) * (i + 1));
3533 (*channel_ids)[i] = NULL;
3534 silc_server_announce_get_channel_users(server, channel,
3536 channel_users_modes[i]);
3537 (*channel_ids)[i] = channel->id;
3540 if (!silc_idcache_list_next(list, &id_cache))
3544 *channel_users_modes_c += i;
3547 silc_idcache_list_free(list);
3551 /* This function is used to announce our existing channels to our router
3552 when we've connected to it. This also announces the users on the
3553 channels to the router. */
3555 void silc_server_announce_channels(SilcServer server)
3557 SilcBuffer channels = NULL, channel_users = NULL;
3558 SilcBuffer *channel_users_modes = NULL;
3559 uint32 channel_users_modes_c = 0;
3560 SilcChannelID **channel_ids = NULL;
3562 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3564 /* Get channels and channel users in local list */
3565 silc_server_announce_get_channels(server, server->local_list,
3566 &channels, &channel_users,
3567 &channel_users_modes,
3568 &channel_users_modes_c,
3571 /* Get channels and channel users in global list */
3572 silc_server_announce_get_channels(server, server->global_list,
3573 &channels, &channel_users,
3574 &channel_users_modes,
3575 &channel_users_modes_c,
3579 silc_buffer_push(channels, channels->data - channels->head);
3580 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3582 /* Send the packet */
3583 silc_server_packet_send(server, server->router->connection,
3584 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3585 channels->data, channels->len,
3588 silc_buffer_free(channels);
3591 if (channel_users) {
3592 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3593 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3594 channel_users->len);
3596 /* Send the packet */
3597 silc_server_packet_send(server, server->router->connection,
3598 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3599 channel_users->data, channel_users->len,
3602 silc_buffer_free(channel_users);
3605 if (channel_users_modes) {
3608 for (i = 0; i < channel_users_modes_c; i++) {
3609 silc_buffer_push(channel_users_modes[i],
3610 channel_users_modes[i]->data -
3611 channel_users_modes[i]->head);
3612 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3613 channel_users_modes[i]->len);
3614 silc_server_packet_send_dest(server, server->router->connection,
3615 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3616 channel_ids[i], SILC_ID_CHANNEL,
3617 channel_users_modes[i]->data,
3618 channel_users_modes[i]->len,
3620 silc_buffer_free(channel_users_modes[i]);
3622 silc_free(channel_users_modes);
3623 silc_free(channel_ids);
3627 /* Failure timeout callback. If this is called then we will immediately
3628 process the received failure. We always process the failure with timeout
3629 since we do not want to blindly trust to received failure packets.
3630 This won't be called (the timeout is cancelled) if the failure was
3631 bogus (it is bogus if remote does not close the connection after sending
3634 SILC_TASK_CALLBACK(silc_server_failure_callback)
3636 SilcServerFailureContext f = (SilcServerFailureContext)context;
3638 if (f->sock->protocol) {
3639 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3640 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3646 /* Assembles user list and users mode list from the `channel'. */
3648 void silc_server_get_users_on_channel(SilcServer server,
3649 SilcChannelEntry channel,
3650 SilcBuffer *user_list,
3651 SilcBuffer *mode_list,
3654 SilcChannelClientEntry chl;
3655 SilcHashTableList htl;
3656 SilcBuffer client_id_list;
3657 SilcBuffer client_mode_list;
3659 uint32 list_count = 0, len = 0;
3661 silc_hash_table_list(channel->user_list, &htl);
3662 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3663 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3665 client_id_list = silc_buffer_alloc(len);
3667 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3668 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3669 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3671 silc_hash_table_list(channel->user_list, &htl);
3672 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3674 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3675 silc_buffer_put(client_id_list, idp->data, idp->len);
3676 silc_buffer_pull(client_id_list, idp->len);
3677 silc_buffer_free(idp);
3679 /* Client's mode on channel */
3680 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3681 silc_buffer_pull(client_mode_list, 4);
3685 silc_buffer_push(client_id_list,
3686 client_id_list->data - client_id_list->head);
3687 silc_buffer_push(client_mode_list,
3688 client_mode_list->data - client_mode_list->head);
3690 *user_list = client_id_list;
3691 *mode_list = client_mode_list;
3692 *user_count = list_count;
3695 /* Saves users and their modes to the `channel'. */
3697 void silc_server_save_users_on_channel(SilcServer server,
3698 SilcSocketConnection sock,
3699 SilcChannelEntry channel,
3700 SilcClientID *noadd,
3701 SilcBuffer user_list,
3702 SilcBuffer mode_list,
3707 /* Cache the received Client ID's and modes. This cache expires
3708 whenever server sends notify message to channel. It means two things;
3709 some user has joined or leaved the channel. XXX TODO! */
3710 for (i = 0; i < user_count; i++) {
3713 SilcClientID *client_id;
3714 SilcClientEntry client;
3717 SILC_GET16_MSB(idp_len, user_list->data + 2);
3719 client_id = silc_id_payload_parse_id(user_list->data, idp_len);
3720 silc_buffer_pull(user_list, idp_len);
3725 SILC_GET32_MSB(mode, mode_list->data);
3726 silc_buffer_pull(mode_list, 4);
3728 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3729 silc_free(client_id);
3733 /* Check if we have this client cached already. */
3734 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3737 client = silc_idlist_find_client_by_id(server->global_list,
3740 /* If router did not find such Client ID in its lists then this must
3741 be bogus client or some router in the net is buggy. */
3742 if (server->server_type == SILC_ROUTER) {
3743 silc_free(client_id);
3747 /* We don't have that client anywhere, add it. The client is added
3748 to global list since server didn't have it in the lists so it must be
3750 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3751 silc_id_dup(client_id, SILC_ID_CLIENT),
3752 sock->user_data, NULL);
3754 silc_free(client_id);
3758 client->data.registered = TRUE;
3761 silc_free(client_id);
3763 if (!silc_server_client_on_channel(client, channel)) {
3764 /* Client was not on the channel, add it. */
3765 SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3766 chl->client = client;
3768 chl->channel = channel;
3769 silc_hash_table_add(channel->user_list, chl->client, chl);
3770 silc_hash_table_add(client->channels, chl->channel, chl);
3775 /* Lookups route to the client indicated by the `id_data'. The connection
3776 object and internal data object is returned. Returns NULL if route
3777 could not be found to the client. If the `client_id' is specified then
3778 it is used and the `id_data' is ignored. */
3780 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3781 unsigned char *id_data,
3783 SilcClientID *client_id,
3784 SilcIDListData *idata)
3787 SilcClientEntry client;
3789 SILC_LOG_DEBUG(("Start"));
3791 /* Decode destination Client ID */
3793 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3795 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3799 id = silc_id_dup(client_id, SILC_ID_CLIENT);
3802 /* If the destination belongs to our server we don't have to route
3803 the packet anywhere but to send it to the local destination. */
3804 client = silc_idlist_find_client_by_id(server->local_list, id, NULL);
3808 if (client->data.registered == FALSE)
3811 /* If we are router and the client has router then the client is in
3812 our cell but not directly connected to us. */
3813 if (server->server_type == SILC_ROUTER && client->router) {
3814 /* We are of course in this case the client's router thus the route
3815 to the client is the server who owns the client. So, we will send
3816 the packet to that server. */
3818 *idata = (SilcIDListData)client->router;
3819 return client->router->connection;
3822 /* Seems that client really is directly connected to us */
3824 *idata = (SilcIDListData)client;
3825 return client->connection;
3828 /* Destination belongs to someone not in this server. If we are normal
3829 server our action is to send the packet to our router. */
3830 if (server->server_type == SILC_SERVER && !server->standalone) {
3833 *idata = (SilcIDListData)server->router;
3834 return server->router->connection;
3837 /* We are router and we will perform route lookup for the destination
3838 and send the packet to fastest route. */
3839 if (server->server_type == SILC_ROUTER && !server->standalone) {
3840 /* Check first that the ID is valid */
3841 client = silc_idlist_find_client_by_id(server->global_list, id, NULL);
3843 SilcSocketConnection dst_sock;
3845 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
3849 *idata = (SilcIDListData)dst_sock->user_data;
3858 /* Encodes and returns channel list of channels the `client' has joined.
3859 Secret channels are not put to the list. */
3861 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
3862 SilcClientEntry client)
3864 SilcBuffer buffer = NULL;
3865 SilcChannelEntry channel;
3866 SilcChannelClientEntry chl;
3867 SilcHashTableList htl;
3873 silc_hash_table_list(client->channels, &htl);
3874 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3875 channel = chl->channel;
3877 if (channel->mode & SILC_CHANNEL_MODE_SECRET)
3880 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3881 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3882 name_len = strlen(channel->channel_name);
3884 len = 4 + name_len + id_len + 4;
3885 buffer = silc_buffer_realloc(buffer,
3886 (buffer ? (buffer)->truelen + len : len));
3887 silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
3888 silc_buffer_format(buffer,
3889 SILC_STR_UI_SHORT(name_len),
3890 SILC_STR_UI_XNSTRING(channel->channel_name,
3892 SILC_STR_UI_SHORT(id_len),
3893 SILC_STR_UI_XNSTRING(cid, id_len),
3894 SILC_STR_UI_INT(chl->mode), /* Client's mode */
3896 silc_buffer_pull(buffer, len);
3901 silc_buffer_push(buffer, buffer->data - buffer->head);
3906 /* Finds client entry by Client ID and if it is not found then resolves
3907 it using WHOIS command. */
3909 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
3910 SilcClientID *client_id)
3912 SilcClientEntry client;
3914 client = silc_idlist_find_client_by_id(server->local_list, client_id, NULL);
3916 client = silc_idlist_find_client_by_id(server->global_list,
3918 if (!client && server->server_type == SILC_ROUTER)
3922 if (!client && server->standalone)
3925 if (!client->data.registered)
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);