5 Author: Pekka Riikonen <priikone@silcnet.org>
7 Copyright (C) 1997 - 2001 Pekka Riikonen
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
21 * This is the actual SILC server than handles everything relating to
22 * servicing the SILC connections. This is also a SILC router as a router
23 * is also normal server.
27 #include "serverincludes.h"
28 #include "server_internal.h"
30 /* Static prototypes */
31 SILC_TASK_CALLBACK(silc_server_connect_router);
32 SILC_TASK_CALLBACK(silc_server_connect_to_router);
33 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
35 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
38 SILC_TASK_CALLBACK(silc_server_packet_process);
39 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
40 SILC_TASK_CALLBACK(silc_server_timeout_remote);
41 SILC_TASK_CALLBACK(silc_server_failure_callback);
42 SILC_TASK_CALLBACK(silc_server_rekey_callback);
44 /* Allocates a new SILC server object. This has to be done before the server
45 can be used. After allocation one must call silc_server_init to initialize
46 the server. The new allocated server object is returned to the new_server
49 int silc_server_alloc(SilcServer *new_server)
53 SILC_LOG_DEBUG(("Allocating new server object"));
55 server = silc_calloc(1, sizeof(*server));
56 server->server_type = SILC_SERVER;
57 server->standalone = TRUE;
58 server->local_list = silc_calloc(1, sizeof(*server->local_list));
59 server->global_list = silc_calloc(1, sizeof(*server->global_list));
60 server->pending_commands = silc_dlist_init();
62 server->sim = silc_dlist_init();
70 /* Free's the SILC server object. This is called at the very end before
73 void silc_server_free(SilcServer server)
80 if (server->local_list)
81 silc_free(server->local_list);
82 if (server->global_list)
83 silc_free(server->global_list);
85 silc_rng_free(server->rng);
88 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
89 silc_dlist_del(server->sim, sim);
92 silc_dlist_uninit(server->sim);
96 silc_free(server->params);
98 if (server->pending_commands)
99 silc_dlist_uninit(server->pending_commands);
105 /* Initializes the entire SILC server. This is called always before running
106 the server. This is called only once at the initialization of the program.
107 This binds the server to its listenning port. After this function returns
108 one should call silc_server_run to start the server. This returns TRUE
109 when everything is ok to run the server. Configuration file must be
110 read and parsed before calling this. */
112 int silc_server_init(SilcServer server)
114 int *sock = NULL, sock_count = 0, i;
116 SilcServerEntry id_entry;
117 SilcIDListPurge purge;
119 SILC_LOG_DEBUG(("Initializing server"));
121 assert(server->config);
123 /* Set public and private keys */
124 if (!server->config->server_keys ||
125 !server->config->server_keys->public_key ||
126 !server->config->server_keys->private_key) {
127 SILC_LOG_ERROR(("Server public key and/or private key does not exist"));
130 server->public_key = server->config->server_keys->public_key;
131 server->private_key = server->config->server_keys->private_key;
133 /* XXX After server is made as Silc Server Library this can be given
134 as argument, for now this is hard coded */
135 server->params = silc_calloc(1, sizeof(*server->params));
136 server->params->retry_count = SILC_SERVER_RETRY_COUNT;
137 server->params->retry_interval_min = SILC_SERVER_RETRY_INTERVAL_MIN;
138 server->params->retry_interval_max = SILC_SERVER_RETRY_INTERVAL_MAX;
139 server->params->retry_keep_trying = FALSE;
140 server->params->protocol_timeout = 60;
141 server->params->require_reverse_mapping = FALSE;
143 /* Set log files where log message should be saved. */
144 server->config->server = server;
145 silc_server_config_setlogfiles(server->config);
147 /* Register all configured ciphers, PKCS and hash functions. */
148 if (!silc_server_config_register_ciphers(server->config))
149 silc_cipher_register_default();
150 if (!silc_server_config_register_pkcs(server->config))
151 silc_pkcs_register_default();
152 if (!silc_server_config_register_hashfuncs(server->config))
153 silc_hash_register_default();
154 if (!silc_server_config_register_hmacs(server->config))
155 silc_hmac_register_default();
157 /* Initialize random number generator for the server. */
158 server->rng = silc_rng_alloc();
159 silc_rng_init(server->rng);
160 silc_rng_global_init(server->rng);
162 /* Initialize hash functions for server to use */
163 silc_hash_alloc("md5", &server->md5hash);
164 silc_hash_alloc("sha1", &server->sha1hash);
166 /* Initialize none cipher */
167 silc_cipher_alloc("none", &server->none_cipher);
169 /* Create a listening server. Note that our server can listen on
170 multiple ports. All listeners are created here and now. */
171 /* XXX Still check this whether to use server_info or listen_port. */
173 while(server->config->listen_port) {
176 tmp = silc_net_create_server(server->config->listen_port->port,
177 server->config->listen_port->host);
181 sock = silc_realloc(sock, (sizeof(int *) * (sock_count + 1)));
182 sock[sock_count] = tmp;
183 server->config->listen_port = server->config->listen_port->next;
187 /* Initialize ID caches */
188 server->local_list->clients =
189 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
190 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
191 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
193 /* These are allocated for normal server as well as these hold some
194 global information that the server has fetched from its router. For
195 router these are used as they are supposed to be used on router. */
196 server->global_list->clients =
197 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
198 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
199 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
201 /* Allocate the entire socket list that is used in server. Eventually
202 all connections will have entry in this table (it is a table of
203 pointers to the actual object that is allocated individually
205 server->sockets = silc_calloc(SILC_SERVER_MAX_CONNECTIONS,
206 sizeof(*server->sockets));
208 for (i = 0; i < sock_count; i++) {
209 SilcSocketConnection newsocket = NULL;
211 /* Set socket to non-blocking mode */
212 silc_net_set_socket_nonblock(sock[i]);
213 server->sock = sock[i];
215 /* Create a Server ID for the server. */
216 silc_id_create_server_id(sock[i], server->rng, &id);
222 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
223 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
224 server->id_type = SILC_ID_SERVER;
225 server->server_name = server->config->server_info->server_name;
227 /* Add ourselves to the server list. We don't have a router yet
228 beacuse we haven't established a route yet. It will be done later.
229 For now, NULL is sent as router. This allocates new entry to
232 silc_idlist_add_server(server->local_list,
233 server->config->server_info->server_name,
234 server->server_type, server->id, NULL, NULL);
236 SILC_LOG_ERROR(("Could not add ourselves to cache"));
239 id_entry->data.registered = TRUE;
241 /* Add ourselves also to the socket table. The entry allocated above
242 is sent as argument for fast referencing in the future. */
243 silc_socket_alloc(sock[i], SILC_SOCKET_TYPE_SERVER, id_entry,
246 server->sockets[sock[i]] = newsocket;
248 /* Perform name and address lookups to resolve the listenning address
250 if (!silc_net_check_local_by_sock(sock[i], &newsocket->hostname,
252 if ((server->params->require_reverse_mapping && !newsocket->hostname) ||
254 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
255 newsocket->hostname ? newsocket->hostname :
256 newsocket->ip ? newsocket->ip : ""));
257 server->stat.conn_failures++;
260 if (!newsocket->hostname)
261 newsocket->hostname = strdup(newsocket->ip);
263 newsocket->port = silc_net_get_local_port(sock[i]);
265 /* Put the allocated socket pointer also to the entry allocated above
266 for fast back-referencing to the socket list. */
267 id_entry->connection = (void *)server->sockets[sock[i]];
268 server->id_entry = id_entry;
271 /* Register protocols */
272 silc_server_protocols_register();
274 /* Initialize the scheduler. */
275 server->schedule = silc_schedule_init(SILC_SERVER_MAX_CONNECTIONS);
276 if (!server->schedule)
279 /* Add the first task to the scheduler. This is task that is executed by
280 timeout. It expires as soon as the caller calls silc_server_run. This
281 task performs authentication protocol and key exchange with our
283 silc_schedule_task_add(server->schedule, sock[0],
284 silc_server_connect_to_router,
285 (void *)server, 0, 1,
287 SILC_TASK_PRI_NORMAL);
289 /* Add listener task to the scheduler. This task receives new connections
290 to the server. This task remains on the queue until the end of the
292 silc_schedule_task_add(server->schedule, sock[0],
293 silc_server_accept_new_connection,
294 (void *)server, 0, 0,
296 SILC_TASK_PRI_NORMAL);
297 server->listenning = TRUE;
299 /* If server connections has been configured then we must be router as
300 normal server cannot have server connections, only router connections. */
301 if (server->config->servers)
302 server->server_type = SILC_ROUTER;
304 /* Register the ID Cache purge task. This periodically purges the ID cache
305 and removes the expired cache entries. */
307 /* Clients local list */
308 purge = silc_calloc(1, sizeof(*purge));
309 purge->cache = server->local_list->clients;
310 purge->schedule = server->schedule;
311 silc_schedule_task_add(purge->schedule, 0,
313 (void *)purge, 600, 0,
314 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
316 /* Clients global list */
317 purge = silc_calloc(1, sizeof(*purge));
318 purge->cache = server->global_list->clients;
319 purge->schedule = server->schedule;
320 silc_schedule_task_add(purge->schedule, 0,
322 (void *)purge, 300, 0,
323 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
325 SILC_LOG_DEBUG(("Server initialized"));
327 /* We are done here, return succesfully */
331 for (i = 0; i < sock_count; i++)
332 silc_net_close_server(sock[i]);
337 /* Fork server to background and set gid+uid to non-root.
338 Silcd will not run as root, so trying to set either user or group to
339 root will cause silcd to exit. */
341 void silc_server_daemonise(SilcServer server)
343 /* Are we executing silcd as root or a regular user? */
350 if (!server->config->identity || !server->config->identity->user ||
351 !server->config->identity->group) {
352 fprintf(stderr, "Error:"
353 "\tSILC server must not be run as root. For the security of your\n"
354 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
355 "\tuser account. Modify the [Identity] configuration section to run\n"
356 "\tthe server as non-root user.\n");
360 /* Get the values given for user and group in configuration file */
361 user=server->config->identity->user;
362 group=server->config->identity->group;
364 /* Check whether the user/group information is text */
365 if (atoi(user)!=0 || atoi(group)!=0) {
366 SILC_LOG_DEBUG(("Invalid user and/or group information"));
367 SILC_LOG_DEBUG(("User and/or group given as number"));
368 fprintf(stderr, "Invalid user and/or group information\n");
369 fprintf(stderr, "Please assign them as names, not numbers\n");
373 /* Catch the nasty incident of string "0" returning 0 from atoi */
374 if (strcmp("0", user)==0 || strcmp("0", group)==0) {
375 SILC_LOG_DEBUG(("User and/or group configured to 0. Unacceptable"));
376 fprintf(stderr, "User and/or group configured to 0. Exiting\n");
384 fprintf(stderr, "No such user %s found\n", user);
389 fprintf(stderr, "No such group %s found\n", group);
393 /* Check whether user and/or group is set to root. If yes, exit
394 immediately. Otherwise, setgid and setuid server to user.group */
395 if (gr->gr_gid==0 || pw->pw_uid==0) {
396 fprintf(stderr, "Error:"
397 "\tSILC server must not be run as root. For the security of your\n"
398 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
399 "\tuser account. Modify the [Identity] configuration section to run\n"
400 "\tthe server as non-root user.\n");
403 /* Fork server to background, making it a daemon */
405 SILC_LOG_DEBUG(("Server started as root. Dropping privileges."));
406 SILC_LOG_DEBUG(("Forking SILC server to background"));
411 SILC_LOG_DEBUG(("Changing to group %s", group));
412 if(setgid(gr->gr_gid)==0) {
413 SILC_LOG_DEBUG(("Setgid to %s", group));
415 SILC_LOG_DEBUG(("Setgid to %s failed", group));
416 fprintf(stderr, "Tried to setgid %s but no such group. Exiting\n",
420 SILC_LOG_DEBUG(("Changing to user nobody"));
421 if(setuid(pw->pw_uid)==0) {
422 SILC_LOG_DEBUG(("Setuid to %s", user));
424 SILC_LOG_DEBUG(("Setuid to %s failed", user));
425 fprintf(stderr, "Tried to setuid %s but no such user. Exiting\n",
431 /* Fork server to background, making it a daemon */
433 SILC_LOG_DEBUG(("Server started as user"));
434 SILC_LOG_DEBUG(("Forking SILC server to background"));
441 /* Stops the SILC server. This function is used to shutdown the server.
442 This is usually called after the scheduler has returned. After stopping
443 the server one should call silc_server_free. */
445 void silc_server_stop(SilcServer server)
447 SILC_LOG_DEBUG(("Stopping server"));
449 silc_schedule_stop(server->schedule);
450 silc_schedule_uninit(server->schedule);
452 silc_server_protocols_unregister();
454 SILC_LOG_DEBUG(("Server stopped"));
457 /* The heart of the server. This runs the scheduler thus runs the server.
458 When this returns the server has been stopped and the program will
461 void silc_server_run(SilcServer server)
463 SILC_LOG_DEBUG(("Running server"));
465 SILC_LOG_INFO(("SILC Server started"));
467 /* Start the scheduler, the heart of the SILC server. When this returns
468 the program will be terminated. */
469 silc_schedule(server->schedule);
472 /* Timeout callback that will be called to retry connecting to remote
473 router. This is used by both normal and router server. This will wait
474 before retrying the connecting. The timeout is generated by exponential
475 backoff algorithm. */
477 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
479 SilcServerConnection sconn = (SilcServerConnection)context;
480 SilcServer server = sconn->server;
482 SILC_LOG_INFO(("Retrying connecting to a router"));
484 /* Calculate next timeout */
485 if (sconn->retry_count >= 1) {
486 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
487 if (sconn->retry_timeout > SILC_SERVER_RETRY_INTERVAL_MAX)
488 sconn->retry_timeout = SILC_SERVER_RETRY_INTERVAL_MAX;
490 sconn->retry_timeout = server->params->retry_interval_min;
492 sconn->retry_count++;
493 sconn->retry_timeout = sconn->retry_timeout +
494 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
496 /* If we've reached max retry count, give up. */
497 if (sconn->retry_count > server->params->retry_count &&
498 server->params->retry_keep_trying == FALSE) {
499 SILC_LOG_ERROR(("Could not connect to router, giving up"));
503 /* Wait one before retrying */
504 silc_schedule_task_add(server->schedule, fd, silc_server_connect_router,
505 context, sconn->retry_timeout,
506 server->params->retry_interval_min_usec,
507 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
510 /* Generic routine to use connect to a router. */
512 SILC_TASK_CALLBACK(silc_server_connect_router)
514 SilcServerConnection sconn = (SilcServerConnection)context;
515 SilcServer server = sconn->server;
516 SilcSocketConnection newsocket;
517 SilcProtocol protocol;
518 SilcServerKEInternalContext *proto_ctx;
521 SILC_LOG_INFO(("Connecting to the router %s on port %d",
522 sconn->remote_host, sconn->remote_port));
524 /* Connect to remote host */
525 sock = silc_net_create_connection(sconn->remote_port,
528 SILC_LOG_ERROR(("Could not connect to router"));
529 silc_schedule_task_add(server->schedule, fd,
530 silc_server_connect_to_router_retry,
531 context, 0, 1, SILC_TASK_TIMEOUT,
532 SILC_TASK_PRI_NORMAL);
536 /* Set socket options */
537 silc_net_set_socket_nonblock(sock);
538 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
540 /* Create socket connection for the connection. Even though we
541 know that we are connecting to a router we will mark the socket
542 to be unknown connection until we have executed authentication
544 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
545 server->sockets[sock] = newsocket;
546 newsocket->hostname = strdup(sconn->remote_host);
547 newsocket->ip = strdup(sconn->remote_host);
548 newsocket->port = sconn->remote_port;
549 sconn->sock = newsocket;
551 /* Allocate internal protocol context. This is sent as context
553 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
554 proto_ctx->server = (void *)server;
555 proto_ctx->context = (void *)sconn;
556 proto_ctx->sock = newsocket;
557 proto_ctx->rng = server->rng;
558 proto_ctx->responder = FALSE;
560 /* Perform key exchange protocol. silc_server_connect_to_router_second
561 will be called after the protocol is finished. */
562 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
563 &protocol, proto_ctx,
564 silc_server_connect_to_router_second);
565 newsocket->protocol = protocol;
567 /* Register a timeout task that will be executed if the protocol
568 is not executed within set limit. */
569 proto_ctx->timeout_task =
570 silc_schedule_task_add(server->schedule, sock,
571 silc_server_timeout_remote,
572 server, server->params->protocol_timeout,
573 server->params->protocol_timeout_usec,
577 /* Register the connection for network input and output. This sets
578 that scheduler will listen for incoming packets for this connection
579 and sets that outgoing packets may be sent to this connection as
580 well. However, this doesn't set the scheduler for outgoing traffic,
581 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
582 later when outgoing data is available. */
583 context = (void *)server;
584 SILC_REGISTER_CONNECTION_FOR_IO(sock);
586 /* Run the protocol */
587 silc_protocol_execute(protocol, server->schedule, 0, 0);
590 /* This function connects to our primary router or if we are a router this
591 establishes all our primary routes. This is called at the start of the
592 server to do authentication and key exchange with our router - called
595 SILC_TASK_CALLBACK(silc_server_connect_to_router)
597 SilcServer server = (SilcServer)context;
598 SilcServerConnection sconn;
600 SILC_LOG_DEBUG(("Connecting to router(s)"));
602 /* If we are normal SILC server we need to connect to our cell's
604 if (server->server_type == SILC_SERVER) {
605 SILC_LOG_DEBUG(("We are normal server"));
607 /* Create connection to the router, if configured. */
608 if (server->config->routers) {
610 /* Allocate connection object for hold connection specific stuff. */
611 sconn = silc_calloc(1, sizeof(*sconn));
612 sconn->server = server;
613 sconn->remote_host = strdup(server->config->routers->host);
614 sconn->remote_port = server->config->routers->port;
616 silc_schedule_task_add(server->schedule, fd,
617 silc_server_connect_router,
618 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
619 SILC_TASK_PRI_NORMAL);
624 /* If we are a SILC router we need to establish all of our primary
626 if (server->server_type == SILC_ROUTER) {
627 SilcServerConfigSectionServerConnection *ptr;
629 SILC_LOG_DEBUG(("We are router"));
631 /* Create the connections to all our routes */
632 ptr = server->config->routers;
635 SILC_LOG_DEBUG(("Router connection [%s] %s:%d",
636 ptr->initiator ? "Initiator" : "Responder",
637 ptr->host, ptr->port));
639 if (ptr->initiator) {
640 /* Allocate connection object for hold connection specific stuff. */
641 sconn = silc_calloc(1, sizeof(*sconn));
642 sconn->server = server;
643 sconn->remote_host = strdup(ptr->host);
644 sconn->remote_port = ptr->port;
646 silc_schedule_task_add(server->schedule, fd,
647 silc_server_connect_router,
648 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
649 SILC_TASK_PRI_NORMAL);
659 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
661 /* There wasn't a configured router, we will continue but we don't
662 have a connection to outside world. We will be standalone server. */
663 server->standalone = TRUE;
666 /* Second part of connecting to router(s). Key exchange protocol has been
667 executed and now we will execute authentication protocol. */
669 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
671 SilcProtocol protocol = (SilcProtocol)context;
672 SilcServerKEInternalContext *ctx =
673 (SilcServerKEInternalContext *)protocol->context;
674 SilcServer server = (SilcServer)ctx->server;
675 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
676 SilcSocketConnection sock = ctx->sock;
677 SilcServerConnAuthInternalContext *proto_ctx;
678 SilcServerConfigSectionServerConnection *conn = NULL;
680 SILC_LOG_DEBUG(("Start"));
682 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
683 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
684 /* Error occured during protocol */
685 silc_protocol_free(protocol);
686 sock->protocol = NULL;
687 silc_ske_free_key_material(ctx->keymat);
689 silc_packet_context_free(ctx->packet);
691 silc_ske_free(ctx->ske);
693 silc_free(ctx->dest_id);
695 silc_schedule_task_del_by_callback(server->schedule,
696 silc_server_failure_callback);
697 silc_server_disconnect_remote(server, sock, "Server closed connection: "
698 "Key exchange failed");
702 /* We now have the key material as the result of the key exchange
703 protocol. Take the key material into use. Free the raw key material
704 as soon as we've set them into use. */
705 if (!silc_server_protocol_ke_set_keys(ctx->ske, ctx->sock, ctx->keymat,
706 ctx->ske->prop->cipher,
707 ctx->ske->prop->pkcs,
708 ctx->ske->prop->hash,
709 ctx->ske->prop->hmac,
710 ctx->ske->prop->group,
712 silc_protocol_free(protocol);
713 sock->protocol = NULL;
714 silc_ske_free_key_material(ctx->keymat);
716 silc_packet_context_free(ctx->packet);
718 silc_ske_free(ctx->ske);
720 silc_free(ctx->dest_id);
722 silc_schedule_task_del_by_callback(server->schedule,
723 silc_server_failure_callback);
724 silc_server_disconnect_remote(server, sock, "Server closed connection: "
725 "Key exchange failed");
728 silc_ske_free_key_material(ctx->keymat);
730 /* Allocate internal context for the authentication protocol. This
731 is sent as context for the protocol. */
732 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
733 proto_ctx->server = (void *)server;
734 proto_ctx->context = (void *)sconn;
735 proto_ctx->sock = sock;
736 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
737 proto_ctx->dest_id_type = ctx->dest_id_type;
738 proto_ctx->dest_id = ctx->dest_id;
740 /* Resolve the authentication method used in this connection. Check if
741 we find a match from user configured connections */
742 conn = silc_server_config_find_router_conn(server->config,
746 /* Match found. Use the configured authentication method */
747 proto_ctx->auth_meth = conn->auth_meth;
748 if (conn->auth_data) {
749 proto_ctx->auth_data = strdup(conn->auth_data);
750 proto_ctx->auth_data_len = strlen(conn->auth_data);
753 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
754 sock->hostname, sock->ip, sock->port));
755 silc_protocol_free(protocol);
756 sock->protocol = NULL;
758 silc_packet_context_free(ctx->packet);
760 silc_ske_free(ctx->ske);
762 silc_free(ctx->dest_id);
764 silc_schedule_task_del_by_callback(server->schedule,
765 silc_server_failure_callback);
766 silc_server_disconnect_remote(server, sock, "Server closed connection: "
767 "Key exchange failed");
771 /* Free old protocol as it is finished now */
772 silc_protocol_free(protocol);
774 silc_packet_context_free(ctx->packet);
776 sock->protocol = NULL;
778 /* Allocate the authentication protocol. This is allocated here
779 but we won't start it yet. We will be receiving party of this
780 protocol thus we will wait that connecting party will make
782 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
783 &sock->protocol, proto_ctx,
784 silc_server_connect_to_router_final);
786 /* Register timeout task. If the protocol is not executed inside
787 this timelimit the connection will be terminated. Currently
788 this is 15 seconds and is hard coded limit (XXX). */
789 proto_ctx->timeout_task =
790 silc_schedule_task_add(server->schedule, sock->sock,
791 silc_server_timeout_remote,
792 (void *)server, 15, 0,
796 /* Run the protocol */
797 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
800 /* Finalizes the connection to router. Registers a server task to the
801 queue so that we can accept new connections. */
803 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
805 SilcProtocol protocol = (SilcProtocol)context;
806 SilcServerConnAuthInternalContext *ctx =
807 (SilcServerConnAuthInternalContext *)protocol->context;
808 SilcServer server = (SilcServer)ctx->server;
809 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
810 SilcSocketConnection sock = ctx->sock;
811 SilcServerEntry id_entry;
813 SilcServerHBContext hb_context;
814 unsigned char *id_string;
816 SilcIDListData idata;
818 SILC_LOG_DEBUG(("Start"));
820 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
821 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
822 /* Error occured during protocol */
824 silc_free(ctx->dest_id);
825 silc_server_disconnect_remote(server, sock, "Server closed connection: "
826 "Authentication failed");
830 /* Add a task to the queue. This task receives new connections to the
831 server. This task remains on the queue until the end of the program. */
832 if (!server->listenning) {
833 silc_schedule_task_add(server->schedule, server->sock,
834 silc_server_accept_new_connection,
835 (void *)server, 0, 0,
837 SILC_TASK_PRI_NORMAL);
838 server->listenning = TRUE;
841 /* Send NEW_SERVER packet to the router. We will become registered
842 to the SILC network after sending this packet. */
843 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
844 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
845 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
846 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
847 silc_buffer_format(packet,
848 SILC_STR_UI_SHORT(id_len),
849 SILC_STR_UI_XNSTRING(id_string, id_len),
850 SILC_STR_UI_SHORT(strlen(server->server_name)),
851 SILC_STR_UI_XNSTRING(server->server_name,
852 strlen(server->server_name)),
855 /* Send the packet */
856 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
857 packet->data, packet->len, TRUE);
858 silc_buffer_free(packet);
859 silc_free(id_string);
861 SILC_LOG_DEBUG(("Connected to router %s", sock->hostname));
863 /* Add the connected router to local server list */
864 server->standalone = FALSE;
865 id_entry = silc_idlist_add_server(server->local_list, strdup(sock->hostname),
866 SILC_ROUTER, ctx->dest_id, NULL, sock);
869 silc_free(ctx->dest_id);
870 silc_server_disconnect_remote(server, sock, "Server closed connection: "
871 "Authentication failed");
875 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
876 silc_free(sock->user_data);
877 sock->user_data = (void *)id_entry;
878 sock->type = SILC_SOCKET_TYPE_ROUTER;
879 server->id_entry->router = id_entry;
880 server->router = id_entry;
881 idata = (SilcIDListData)sock->user_data;
882 idata->registered = TRUE;
884 /* Perform keepalive. The `hb_context' will be freed automatically
885 when finally calling the silc_socket_free function. XXX hardcoded
887 hb_context = silc_calloc(1, sizeof(*hb_context));
888 hb_context->server = server;
889 silc_socket_set_heartbeat(sock, 600, hb_context,
890 silc_server_perform_heartbeat,
893 /* Register re-key timeout */
894 idata->rekey->timeout = 3600; /* XXX hardcoded */
895 idata->rekey->context = (void *)server;
896 silc_schedule_task_add(server->schedule, sock->sock,
897 silc_server_rekey_callback,
898 (void *)sock, idata->rekey->timeout, 0,
899 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
901 /* If we are router then announce our possible servers. */
902 if (server->server_type == SILC_ROUTER)
903 silc_server_announce_servers(server);
905 /* Announce our clients and channels to the router */
906 silc_server_announce_clients(server);
907 silc_server_announce_channels(server);
910 /* Free the temporary connection data context */
912 silc_free(sconn->remote_host);
916 /* Free the protocol object */
917 silc_protocol_free(protocol);
919 silc_packet_context_free(ctx->packet);
921 silc_ske_free(ctx->ske);
923 sock->protocol = NULL;
926 /* Host lookup callbcak that is called after the incoming connection's
927 IP and FQDN lookup is performed. This will actually check the acceptance
928 of the incoming connection and will register the key exchange protocol
929 for this connection. */
932 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
935 SilcServer server = (SilcServer)context;
936 SilcServerKEInternalContext *proto_ctx;
937 void *cconfig, *sconfig, *rconfig;
938 SilcServerConfigSectionDenyConnection *deny;
941 SILC_LOG_DEBUG(("Start"));
943 /* Check whether we could resolve both IP and FQDN. */
944 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
945 server->params->require_reverse_mapping)) {
946 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
947 sock->hostname ? sock->hostname :
948 sock->ip ? sock->ip : ""));
949 server->stat.conn_failures++;
950 silc_server_disconnect_remote(server, sock,
951 "Server closed connection: Unknown host");
955 /* Register the connection for network input and output. This sets
956 that scheduler will listen for incoming packets for this connection
957 and sets that outgoing packets may be sent to this connection as well.
958 However, this doesn't set the scheduler for outgoing traffic, it
959 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
960 later when outgoing data is available. */
961 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
963 SILC_LOG_INFO(("Incoming connection from %s (%s)", sock->hostname,
966 port = server->sockets[server->sock]->port; /* Listenning port */
968 /* Check whether this connection is denied to connect to us. */
969 deny = silc_server_config_denied_conn(server->config, sock->ip, port);
971 deny = silc_server_config_denied_conn(server->config, sock->hostname,
974 /* The connection is denied */
975 SILC_LOG_INFO(("Connection %s (%s) is denied",
976 sock->hostname, sock->ip));
977 silc_server_disconnect_remote(server, sock, deny->comment ?
979 "Server closed connection: "
980 "Connection refused");
981 server->stat.conn_failures++;
985 /* Check whether we have configred this sort of connection at all. We
986 have to check all configurations since we don't know what type of
987 connection this is. */
988 if (!(cconfig = silc_server_config_find_client_conn(server->config,
990 cconfig = silc_server_config_find_client_conn(server->config,
993 if (!(sconfig = silc_server_config_find_server_conn(server->config,
996 sconfig = silc_server_config_find_server_conn(server->config,
999 if (!(rconfig = silc_server_config_find_router_conn(server->config,
1001 rconfig = silc_server_config_find_router_conn(server->config,
1004 if (!cconfig && !sconfig && !rconfig) {
1005 silc_server_disconnect_remote(server, sock,
1006 "Server closed connection: "
1007 "Connection refused");
1008 server->stat.conn_failures++;
1012 /* The connection is allowed */
1014 /* Allocate internal context for key exchange protocol. This is
1015 sent as context for the protocol. */
1016 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1017 proto_ctx->server = context;
1018 proto_ctx->sock = sock;
1019 proto_ctx->rng = server->rng;
1020 proto_ctx->responder = TRUE;
1021 proto_ctx->cconfig = cconfig;
1022 proto_ctx->sconfig = sconfig;
1023 proto_ctx->rconfig = rconfig;
1025 /* Prepare the connection for key exchange protocol. We allocate the
1026 protocol but will not start it yet. The connector will be the
1027 initiator of the protocol thus we will wait for initiation from
1028 there before we start the protocol. */
1029 server->stat.auth_attempts++;
1030 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1031 &sock->protocol, proto_ctx,
1032 silc_server_accept_new_connection_second);
1034 /* Register a timeout task that will be executed if the connector
1035 will not start the key exchange protocol within 60 seconds. For
1036 now, this is a hard coded limit. After 60 secs the connection will
1037 be closed if the key exchange protocol has not been started. */
1038 proto_ctx->timeout_task =
1039 silc_schedule_task_add(server->schedule, sock->sock,
1040 silc_server_timeout_remote,
1046 /* Accepts new connections to the server. Accepting new connections are
1047 done in three parts to make it async. */
1049 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1051 SilcServer server = (SilcServer)context;
1052 SilcSocketConnection newsocket;
1055 SILC_LOG_DEBUG(("Accepting new connection"));
1057 server->stat.conn_attempts++;
1059 sock = silc_net_accept_connection(server->sock);
1061 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1062 server->stat.conn_failures++;
1066 /* Check max connections */
1067 if (sock > SILC_SERVER_MAX_CONNECTIONS) {
1068 SILC_LOG_ERROR(("Refusing connection, server is full"));
1069 server->stat.conn_failures++;
1073 /* Set socket options */
1074 silc_net_set_socket_nonblock(sock);
1075 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1077 /* We don't create a ID yet, since we don't know what type of connection
1078 this is yet. But, we do add the connection to the socket table. */
1079 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1080 server->sockets[sock] = newsocket;
1082 /* Perform asynchronous host lookup. This will lookup the IP and the
1083 FQDN of the remote connection. After the lookup is done the connection
1084 is accepted further. */
1085 silc_socket_host_lookup(newsocket, TRUE,
1086 silc_server_accept_new_connection_lookup, context,
1090 /* Second part of accepting new connection. Key exchange protocol has been
1091 performed and now it is time to do little connection authentication
1092 protocol to figure out whether this connection is client or server
1093 and whether it has right to access this server (especially server
1094 connections needs to be authenticated). */
1096 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1098 SilcProtocol protocol = (SilcProtocol)context;
1099 SilcServerKEInternalContext *ctx =
1100 (SilcServerKEInternalContext *)protocol->context;
1101 SilcServer server = (SilcServer)ctx->server;
1102 SilcSocketConnection sock = ctx->sock;
1103 SilcServerConnAuthInternalContext *proto_ctx;
1105 SILC_LOG_DEBUG(("Start"));
1107 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1108 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1109 /* Error occured during protocol */
1110 silc_protocol_free(protocol);
1111 sock->protocol = NULL;
1112 silc_ske_free_key_material(ctx->keymat);
1114 silc_packet_context_free(ctx->packet);
1116 silc_ske_free(ctx->ske);
1118 silc_free(ctx->dest_id);
1120 silc_schedule_task_del_by_callback(server->schedule,
1121 silc_server_failure_callback);
1122 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1123 "Key exchange failed");
1124 server->stat.auth_failures++;
1128 /* We now have the key material as the result of the key exchange
1129 protocol. Take the key material into use. Free the raw key material
1130 as soon as we've set them into use. */
1131 if (!silc_server_protocol_ke_set_keys(ctx->ske, ctx->sock, ctx->keymat,
1132 ctx->ske->prop->cipher,
1133 ctx->ske->prop->pkcs,
1134 ctx->ske->prop->hash,
1135 ctx->ske->prop->hmac,
1136 ctx->ske->prop->group,
1138 silc_protocol_free(protocol);
1139 sock->protocol = NULL;
1140 silc_ske_free_key_material(ctx->keymat);
1142 silc_packet_context_free(ctx->packet);
1144 silc_ske_free(ctx->ske);
1146 silc_free(ctx->dest_id);
1148 silc_schedule_task_del_by_callback(server->schedule,
1149 silc_server_failure_callback);
1150 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1151 "Key exchange failed");
1152 server->stat.auth_failures++;
1155 silc_ske_free_key_material(ctx->keymat);
1157 /* Allocate internal context for the authentication protocol. This
1158 is sent as context for the protocol. */
1159 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1160 proto_ctx->server = (void *)server;
1161 proto_ctx->sock = sock;
1162 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1163 proto_ctx->responder = TRUE;
1164 proto_ctx->dest_id_type = ctx->dest_id_type;
1165 proto_ctx->dest_id = ctx->dest_id;
1166 proto_ctx->cconfig = ctx->cconfig;
1167 proto_ctx->sconfig = ctx->sconfig;
1168 proto_ctx->rconfig = ctx->rconfig;
1170 /* Free old protocol as it is finished now */
1171 silc_protocol_free(protocol);
1173 silc_packet_context_free(ctx->packet);
1175 sock->protocol = NULL;
1177 /* Allocate the authentication protocol. This is allocated here
1178 but we won't start it yet. We will be receiving party of this
1179 protocol thus we will wait that connecting party will make
1180 their first move. */
1181 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1182 &sock->protocol, proto_ctx,
1183 silc_server_accept_new_connection_final);
1185 /* Register timeout task. If the protocol is not executed inside
1186 this timelimit the connection will be terminated. Currently
1187 this is 60 seconds and is hard coded limit (XXX). */
1188 proto_ctx->timeout_task =
1189 silc_schedule_task_add(server->schedule, sock->sock,
1190 silc_server_timeout_remote,
1191 (void *)server, 60, 0,
1196 /* Final part of accepting new connection. The connection has now
1197 been authenticated and keys has been exchanged. We also know whether
1198 this is client or server connection. */
1200 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1202 SilcProtocol protocol = (SilcProtocol)context;
1203 SilcServerConnAuthInternalContext *ctx =
1204 (SilcServerConnAuthInternalContext *)protocol->context;
1205 SilcServer server = (SilcServer)ctx->server;
1206 SilcSocketConnection sock = ctx->sock;
1207 SilcServerHBContext hb_context;
1208 void *id_entry = NULL;
1210 SILC_LOG_DEBUG(("Start"));
1212 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1213 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1214 /* Error occured during protocol */
1215 silc_protocol_free(protocol);
1216 sock->protocol = NULL;
1218 silc_packet_context_free(ctx->packet);
1220 silc_ske_free(ctx->ske);
1222 silc_free(ctx->dest_id);
1225 sock->protocol = NULL;
1226 silc_schedule_task_del_by_callback(server->schedule,
1227 silc_server_failure_callback);
1228 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1229 "Authentication failed");
1230 server->stat.auth_failures++;
1234 switch(ctx->conn_type) {
1235 case SILC_SOCKET_TYPE_CLIENT:
1237 SilcClientEntry client;
1239 SILC_LOG_DEBUG(("Remote host is client"));
1240 SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
1243 /* Add the client to the client ID cache. The nickname and Client ID
1244 and other information is created after we have received NEW_CLIENT
1245 packet from client. */
1246 client = silc_idlist_add_client(server->local_list,
1247 NULL, NULL, NULL, NULL, NULL, sock);
1249 SILC_LOG_ERROR(("Could not add new client to cache"));
1250 silc_free(sock->user_data);
1251 silc_server_disconnect_remote(server, sock,
1252 "Server closed connection: "
1253 "Authentication failed");
1254 server->stat.auth_failures++;
1259 server->stat.my_clients++;
1260 server->stat.clients++;
1261 if (server->server_type == SILC_ROUTER)
1262 server->stat.cell_clients++;
1264 id_entry = (void *)client;
1267 case SILC_SOCKET_TYPE_SERVER:
1268 case SILC_SOCKET_TYPE_ROUTER:
1270 SilcServerEntry new_server;
1271 SilcServerConfigSectionServerConnection *conn =
1272 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1273 ctx->sconfig : ctx->rconfig;
1275 SILC_LOG_DEBUG(("Remote host is %s",
1276 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1277 "server" : "router"));
1278 SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
1279 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1280 "server" : "router"));
1282 /* Add the server into server cache. The server name and Server ID
1283 is updated after we have received NEW_SERVER packet from the
1284 server. We mark ourselves as router for this server if we really
1287 silc_idlist_add_server(server->local_list, NULL,
1288 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1289 SILC_SERVER : SILC_ROUTER, NULL,
1290 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1291 server->id_entry : NULL, sock);
1293 SILC_LOG_ERROR(("Could not add new server to cache"));
1294 silc_free(sock->user_data);
1295 silc_server_disconnect_remote(server, sock,
1296 "Server closed connection: "
1297 "Authentication failed");
1298 server->stat.auth_failures++;
1303 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1304 server->stat.my_servers++;
1306 server->stat.my_routers++;
1307 server->stat.servers++;
1309 id_entry = (void *)new_server;
1311 /* Check whether this connection is to be our primary router connection
1312 if we dont' already have the primary route. */
1313 if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1314 if (silc_server_config_is_primary_route(server->config) &&
1318 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1319 server->standalone = FALSE;
1320 if (!server->id_entry->router) {
1321 server->id_entry->router = id_entry;
1322 server->router = id_entry;
1332 sock->type = ctx->conn_type;
1334 /* Add the common data structure to the ID entry. */
1336 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1338 /* Add to sockets internal pointer for fast referencing */
1339 silc_free(sock->user_data);
1340 sock->user_data = id_entry;
1342 /* Connection has been fully established now. Everything is ok. */
1343 SILC_LOG_DEBUG(("New connection authenticated"));
1345 /* Perform keepalive. The `hb_context' will be freed automatically
1346 when finally calling the silc_socket_free function. XXX hardcoded
1348 hb_context = silc_calloc(1, sizeof(*hb_context));
1349 hb_context->server = server;
1350 silc_socket_set_heartbeat(sock, 600, hb_context,
1351 silc_server_perform_heartbeat,
1355 silc_schedule_task_del_by_callback(server->schedule,
1356 silc_server_failure_callback);
1357 silc_protocol_free(protocol);
1359 silc_packet_context_free(ctx->packet);
1361 silc_ske_free(ctx->ske);
1363 silc_free(ctx->dest_id);
1365 sock->protocol = NULL;
1368 /* This function is used to read packets from network and send packets to
1369 network. This is usually a generic task. */
1371 SILC_TASK_CALLBACK(silc_server_packet_process)
1373 SilcServer server = (SilcServer)context;
1374 SilcSocketConnection sock = server->sockets[fd];
1375 SilcIDListData idata;
1376 SilcCipher cipher = NULL;
1377 SilcHmac hmac = NULL;
1383 SILC_LOG_DEBUG(("Processing packet"));
1385 /* Packet sending */
1387 if (type == SILC_TASK_WRITE) {
1388 /* Do not send data to disconnected connection */
1389 if (SILC_IS_DISCONNECTED(sock))
1392 server->stat.packets_sent++;
1394 if (sock->outbuf->data - sock->outbuf->head)
1395 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1397 /* Send the packet */
1398 ret = silc_packet_send(sock, TRUE);
1400 /* If returned -2 could not write to connection now, will do
1406 SILC_LOG_ERROR(("Error sending packet to connection "
1407 "%s:%d [%s]", sock->hostname, sock->port,
1408 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1409 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1410 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1415 /* The packet has been sent and now it is time to set the connection
1416 back to only for input. When there is again some outgoing data
1417 available for this connection it will be set for output as well.
1418 This call clears the output setting and sets it only for input. */
1419 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1420 SILC_UNSET_OUTBUF_PENDING(sock);
1422 silc_buffer_clear(sock->outbuf);
1426 /* Packet receiving */
1428 /* Read some data from connection */
1429 ret = silc_packet_receive(sock);
1433 SILC_LOG_ERROR(("Error receiving packet from connection "
1434 "%s:%d [%s]", sock->hostname, sock->port,
1435 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1436 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1437 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1444 SILC_LOG_DEBUG(("Read EOF"));
1446 /* If connection is disconnecting already we will finally
1447 close the connection */
1448 if (SILC_IS_DISCONNECTING(sock)) {
1449 if (sock->user_data)
1450 silc_server_free_sock_user_data(server, sock);
1451 silc_server_close_connection(server, sock);
1455 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1456 SILC_SET_DISCONNECTING(sock);
1458 /* If the closed connection was our primary router connection the
1459 start re-connecting phase. */
1460 if (!server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER &&
1461 sock == server->router->connection)
1462 silc_schedule_task_add(server->schedule, 0,
1463 silc_server_connect_to_router,
1466 SILC_TASK_PRI_NORMAL);
1468 if (sock->user_data)
1469 silc_server_free_sock_user_data(server, sock);
1470 silc_server_close_connection(server, sock);
1474 /* If connection is disconnecting or disconnected we will ignore
1476 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1477 SILC_LOG_DEBUG(("Ignoring read data from disonnected connection"));
1481 server->stat.packets_received++;
1483 /* Get keys and stuff from ID entry */
1484 idata = (SilcIDListData)sock->user_data;
1486 idata->last_receive = time(NULL);
1487 cipher = idata->receive_key;
1488 hmac = idata->hmac_receive;
1491 /* Process the packet. This will call the parser that will then
1492 decrypt and parse the packet. */
1493 silc_packet_receive_process(sock, cipher, hmac, silc_server_packet_parse,
1497 /* Callback function that the silc_packet_decrypt will call to make the
1498 decision whether the packet is normal or special packet. We will
1499 return TRUE if it is normal and FALSE if it is special */
1501 static int silc_server_packet_decrypt_check(SilcPacketType packet_type,
1503 SilcPacketContext *packet,
1506 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1507 SilcServer server = (SilcServer)parse_ctx->context;
1509 /* Packet is normal packet, if:
1511 1) packet is private message packet and does not have private key set
1512 2) is other packet than channel message packet
1513 3) is channel message packet and remote is router and we are router
1515 all other packets are special packets
1518 if (packet_type == SILC_PACKET_PRIVATE_MESSAGE &&
1519 (buffer->data[2] & SILC_PACKET_FLAG_PRIVMSG_KEY))
1522 if (packet_type != SILC_PACKET_CHANNEL_MESSAGE ||
1523 (packet_type == SILC_PACKET_CHANNEL_MESSAGE &&
1524 parse_ctx->sock->type == SILC_SOCKET_TYPE_ROUTER &&
1525 server->server_type == SILC_ROUTER))
1531 /* Parses whole packet, received earlier. */
1533 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1535 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1536 SilcServer server = (SilcServer)parse_ctx->context;
1537 SilcSocketConnection sock = parse_ctx->sock;
1538 SilcPacketContext *packet = parse_ctx->packet;
1539 SilcIDListData idata = (SilcIDListData)sock->user_data;
1542 SILC_LOG_DEBUG(("Start"));
1544 /* Decrypt the received packet */
1545 ret = silc_packet_decrypt(idata ? idata->receive_key : NULL,
1546 idata ? idata->hmac_receive : NULL,
1547 packet->buffer, packet,
1548 silc_server_packet_decrypt_check, parse_ctx);
1550 SILC_LOG_WARNING(("Packet decryption failed for connection "
1551 "%s:%d [%s]", sock->hostname, sock->port,
1552 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1553 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1554 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1560 /* Parse the packet. Packet type is returned. */
1561 ret = silc_packet_parse(packet);
1563 /* Parse the packet header in special way as this is "special"
1565 ret = silc_packet_parse_special(packet);
1568 if (ret == SILC_PACKET_NONE)
1571 /* Check that the the current client ID is same as in the client's packet. */
1572 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1573 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1574 if (client && client->id) {
1575 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1576 packet->src_id_type);
1577 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1585 if (server->server_type == SILC_ROUTER) {
1586 /* Route the packet if it is not destined to us. Other ID types but
1587 server are handled separately after processing them. */
1588 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1589 packet->dst_id_type == SILC_ID_SERVER &&
1590 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1591 memcmp(packet->dst_id, server->id_string, packet->dst_id_len)) {
1593 /* Route the packet to fastest route for the destination ID */
1594 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1595 packet->dst_id_type);
1598 silc_server_packet_route(server,
1599 silc_server_route_get(server, id,
1600 packet->dst_id_type),
1607 /* Parse the incoming packet type */
1608 silc_server_packet_parse_type(server, sock, packet);
1610 if (server->server_type == SILC_ROUTER) {
1611 /* Broadcast packet if it is marked as broadcast packet and it is
1612 originated from router and we are router. */
1613 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1614 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1615 !server->standalone) {
1616 silc_server_packet_broadcast(server, server->router->connection, packet);
1621 /* silc_buffer_clear(sock->inbuf); */
1622 silc_packet_context_free(packet);
1623 silc_free(parse_ctx);
1626 /* Parser callback called by silc_packet_receive_process. This merely
1627 registers timeout that will handle the actual parsing when appropriate. */
1629 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1631 SilcServer server = (SilcServer)parser_context->context;
1632 SilcSocketConnection sock = parser_context->sock;
1634 switch (sock->type) {
1635 case SILC_SOCKET_TYPE_UNKNOWN:
1636 case SILC_SOCKET_TYPE_CLIENT:
1637 /* Parse the packet with timeout */
1638 silc_schedule_task_add(server->schedule, sock->sock,
1639 silc_server_packet_parse_real,
1640 (void *)parser_context, 0, 100000,
1642 SILC_TASK_PRI_NORMAL);
1644 case SILC_SOCKET_TYPE_SERVER:
1645 case SILC_SOCKET_TYPE_ROUTER:
1646 /* Packets from servers are parsed as soon as possible */
1647 silc_schedule_task_add(server->schedule, sock->sock,
1648 silc_server_packet_parse_real,
1649 (void *)parser_context, 0, 1,
1651 SILC_TASK_PRI_NORMAL);
1658 /* Parses the packet type and calls what ever routines the packet type
1659 requires. This is done for all incoming packets. */
1661 void silc_server_packet_parse_type(SilcServer server,
1662 SilcSocketConnection sock,
1663 SilcPacketContext *packet)
1665 SilcPacketType type = packet->type;
1667 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1669 /* Parse the packet type */
1671 case SILC_PACKET_DISCONNECT:
1672 SILC_LOG_DEBUG(("Disconnect packet"));
1673 if (packet->flags & SILC_PACKET_FLAG_LIST)
1677 case SILC_PACKET_SUCCESS:
1679 * Success received for something. For now we can have only
1680 * one protocol for connection executing at once hence this
1681 * success message is for whatever protocol is executing currently.
1683 SILC_LOG_DEBUG(("Success packet"));
1684 if (packet->flags & SILC_PACKET_FLAG_LIST)
1687 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1690 case SILC_PACKET_FAILURE:
1692 * Failure received for something. For now we can have only
1693 * one protocol for connection executing at once hence this
1694 * failure message is for whatever protocol is executing currently.
1696 SILC_LOG_DEBUG(("Failure packet"));
1697 if (packet->flags & SILC_PACKET_FLAG_LIST)
1699 if (sock->protocol) {
1700 SilcServerFailureContext f;
1701 f = silc_calloc(1, sizeof(*f));
1705 /* We will wait 5 seconds to process this failure packet */
1706 silc_schedule_task_add(server->schedule, sock->sock,
1707 silc_server_failure_callback, (void *)f, 5, 0,
1708 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1712 case SILC_PACKET_REJECT:
1713 SILC_LOG_DEBUG(("Reject packet"));
1714 if (packet->flags & SILC_PACKET_FLAG_LIST)
1719 case SILC_PACKET_NOTIFY:
1721 * Received notify packet. Server can receive notify packets from
1722 * router. Server then relays the notify messages to clients if needed.
1724 SILC_LOG_DEBUG(("Notify packet"));
1725 if (packet->flags & SILC_PACKET_FLAG_LIST)
1726 silc_server_notify_list(server, sock, packet);
1728 silc_server_notify(server, sock, packet);
1734 case SILC_PACKET_CHANNEL_MESSAGE:
1736 * Received channel message. Channel messages are special packets
1737 * (although probably most common ones) thus they are handled
1740 SILC_LOG_DEBUG(("Channel Message packet"));
1741 if (packet->flags & SILC_PACKET_FLAG_LIST)
1743 silc_server_channel_message(server, sock, packet);
1746 case SILC_PACKET_CHANNEL_KEY:
1748 * Received key for channel. As channels are created by the router
1749 * the keys are as well. We will distribute the key to all of our
1750 * locally connected clients on the particular channel. Router
1751 * never receives this channel and thus is ignored.
1753 SILC_LOG_DEBUG(("Channel Key packet"));
1754 if (packet->flags & SILC_PACKET_FLAG_LIST)
1756 silc_server_channel_key(server, sock, packet);
1762 case SILC_PACKET_COMMAND:
1764 * Recived command. Processes the command request and allocates the
1765 * command context and calls the command.
1767 SILC_LOG_DEBUG(("Command packet"));
1768 if (packet->flags & SILC_PACKET_FLAG_LIST)
1770 silc_server_command_process(server, sock, packet);
1773 case SILC_PACKET_COMMAND_REPLY:
1775 * Received command reply packet. Received command reply to command. It
1776 * may be reply to command sent by us or reply to command sent by client
1777 * that we've routed further.
1779 SILC_LOG_DEBUG(("Command Reply packet"));
1780 if (packet->flags & SILC_PACKET_FLAG_LIST)
1782 silc_server_command_reply(server, sock, packet);
1786 * Private Message packets
1788 case SILC_PACKET_PRIVATE_MESSAGE:
1790 * Received private message packet. The packet is coming from either
1793 SILC_LOG_DEBUG(("Private Message packet"));
1794 if (packet->flags & SILC_PACKET_FLAG_LIST)
1796 silc_server_private_message(server, sock, packet);
1799 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1801 * Private message key packet.
1803 if (packet->flags & SILC_PACKET_FLAG_LIST)
1805 silc_server_private_message_key(server, sock, packet);
1809 * Key Exchange protocol packets
1811 case SILC_PACKET_KEY_EXCHANGE:
1812 SILC_LOG_DEBUG(("KE packet"));
1813 if (packet->flags & SILC_PACKET_FLAG_LIST)
1816 if (sock->protocol && sock->protocol->protocol &&
1817 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1819 SilcServerKEInternalContext *proto_ctx =
1820 (SilcServerKEInternalContext *)sock->protocol->context;
1822 proto_ctx->packet = silc_packet_context_dup(packet);
1824 /* Let the protocol handle the packet */
1825 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
1827 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1828 "protocol active, packet dropped."));
1832 case SILC_PACKET_KEY_EXCHANGE_1:
1833 SILC_LOG_DEBUG(("KE 1 packet"));
1834 if (packet->flags & SILC_PACKET_FLAG_LIST)
1837 if (sock->protocol && sock->protocol->protocol &&
1838 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1839 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
1841 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
1842 SilcServerRekeyInternalContext *proto_ctx =
1843 (SilcServerRekeyInternalContext *)sock->protocol->context;
1845 if (proto_ctx->packet)
1846 silc_packet_context_free(proto_ctx->packet);
1848 proto_ctx->packet = silc_packet_context_dup(packet);
1850 /* Let the protocol handle the packet */
1851 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1853 SilcServerKEInternalContext *proto_ctx =
1854 (SilcServerKEInternalContext *)sock->protocol->context;
1856 if (proto_ctx->packet)
1857 silc_packet_context_free(proto_ctx->packet);
1859 proto_ctx->packet = silc_packet_context_dup(packet);
1860 proto_ctx->dest_id_type = packet->src_id_type;
1861 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1862 packet->src_id_type);
1863 if (!proto_ctx->dest_id)
1866 /* Let the protocol handle the packet */
1867 silc_protocol_execute(sock->protocol, server->schedule,
1871 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1872 "protocol active, packet dropped."));
1876 case SILC_PACKET_KEY_EXCHANGE_2:
1877 SILC_LOG_DEBUG(("KE 2 packet"));
1878 if (packet->flags & SILC_PACKET_FLAG_LIST)
1881 if (sock->protocol && sock->protocol->protocol &&
1882 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1883 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
1885 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
1886 SilcServerRekeyInternalContext *proto_ctx =
1887 (SilcServerRekeyInternalContext *)sock->protocol->context;
1889 if (proto_ctx->packet)
1890 silc_packet_context_free(proto_ctx->packet);
1892 proto_ctx->packet = silc_packet_context_dup(packet);
1894 /* Let the protocol handle the packet */
1895 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1897 SilcServerKEInternalContext *proto_ctx =
1898 (SilcServerKEInternalContext *)sock->protocol->context;
1900 if (proto_ctx->packet)
1901 silc_packet_context_free(proto_ctx->packet);
1903 proto_ctx->packet = silc_packet_context_dup(packet);
1904 proto_ctx->dest_id_type = packet->src_id_type;
1905 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1906 packet->src_id_type);
1907 if (!proto_ctx->dest_id)
1910 /* Let the protocol handle the packet */
1911 silc_protocol_execute(sock->protocol, server->schedule,
1915 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1916 "protocol active, packet dropped."));
1920 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1922 * Connection authentication request packet. When we receive this packet
1923 * we will send to the other end information about our mandatory
1924 * authentication method for the connection. This packet maybe received
1927 SILC_LOG_DEBUG(("Connection authentication request packet"));
1928 if (packet->flags & SILC_PACKET_FLAG_LIST)
1930 silc_server_connection_auth_request(server, sock, packet);
1934 * Connection Authentication protocol packets
1936 case SILC_PACKET_CONNECTION_AUTH:
1937 /* Start of the authentication protocol. We receive here the
1938 authentication data and will verify it. */
1939 SILC_LOG_DEBUG(("Connection auth packet"));
1940 if (packet->flags & SILC_PACKET_FLAG_LIST)
1943 if (sock->protocol && sock->protocol->protocol->type
1944 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1946 SilcServerConnAuthInternalContext *proto_ctx =
1947 (SilcServerConnAuthInternalContext *)sock->protocol->context;
1949 proto_ctx->packet = silc_packet_context_dup(packet);
1951 /* Let the protocol handle the packet */
1952 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1954 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1955 "protocol active, packet dropped."));
1959 case SILC_PACKET_NEW_ID:
1961 * Received New ID packet. This includes some new ID that has been
1962 * created. It may be for client, server or channel. This is the way
1963 * to distribute information about new registered entities in the
1966 SILC_LOG_DEBUG(("New ID packet"));
1967 if (packet->flags & SILC_PACKET_FLAG_LIST)
1968 silc_server_new_id_list(server, sock, packet);
1970 silc_server_new_id(server, sock, packet);
1973 case SILC_PACKET_NEW_CLIENT:
1975 * Received new client packet. This includes client information that
1976 * we will use to create initial client ID. After creating new
1977 * ID we will send it to the client.
1979 SILC_LOG_DEBUG(("New Client packet"));
1980 if (packet->flags & SILC_PACKET_FLAG_LIST)
1982 silc_server_new_client(server, sock, packet);
1985 case SILC_PACKET_NEW_SERVER:
1987 * Received new server packet. This includes Server ID and some other
1988 * information that we may save. This is received after server has
1991 SILC_LOG_DEBUG(("New Server packet"));
1992 if (packet->flags & SILC_PACKET_FLAG_LIST)
1994 silc_server_new_server(server, sock, packet);
1997 case SILC_PACKET_NEW_CHANNEL:
1999 * Received new channel packet. Information about new channel in the
2000 * network are distributed using this packet.
2002 SILC_LOG_DEBUG(("New Channel packet"));
2003 if (packet->flags & SILC_PACKET_FLAG_LIST)
2004 silc_server_new_channel_list(server, sock, packet);
2006 silc_server_new_channel(server, sock, packet);
2009 case SILC_PACKET_HEARTBEAT:
2011 * Received heartbeat.
2013 SILC_LOG_DEBUG(("Heartbeat packet"));
2014 if (packet->flags & SILC_PACKET_FLAG_LIST)
2018 case SILC_PACKET_KEY_AGREEMENT:
2020 * Received heartbeat.
2022 SILC_LOG_DEBUG(("Key agreement packet"));
2023 if (packet->flags & SILC_PACKET_FLAG_LIST)
2025 silc_server_key_agreement(server, sock, packet);
2028 case SILC_PACKET_REKEY:
2030 * Received re-key packet. The sender wants to regenerate the session
2033 SILC_LOG_DEBUG(("Re-key packet"));
2034 if (packet->flags & SILC_PACKET_FLAG_LIST)
2036 silc_server_rekey(server, sock, packet);
2039 case SILC_PACKET_REKEY_DONE:
2041 * The re-key is done.
2043 SILC_LOG_DEBUG(("Re-key done packet"));
2044 if (packet->flags & SILC_PACKET_FLAG_LIST)
2047 if (sock->protocol && sock->protocol->protocol &&
2048 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2050 SilcServerRekeyInternalContext *proto_ctx =
2051 (SilcServerRekeyInternalContext *)sock->protocol->context;
2053 if (proto_ctx->packet)
2054 silc_packet_context_free(proto_ctx->packet);
2056 proto_ctx->packet = silc_packet_context_dup(packet);
2058 /* Let the protocol handle the packet */
2059 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2061 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2062 "protocol active, packet dropped."));
2067 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2073 /* Creates connection to a remote router. */
2075 void silc_server_create_connection(SilcServer server,
2076 char *remote_host, uint32 port)
2078 SilcServerConnection sconn;
2080 /* Allocate connection object for hold connection specific stuff. */
2081 sconn = silc_calloc(1, sizeof(*sconn));
2082 sconn->server = server;
2083 sconn->remote_host = strdup(remote_host);
2084 sconn->remote_port = port;
2086 silc_schedule_task_add(server->schedule, 0,
2087 silc_server_connect_router,
2088 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2089 SILC_TASK_PRI_NORMAL);
2092 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2094 silc_socket_free((SilcSocketConnection)context);
2097 /* Closes connection to socket connection */
2099 void silc_server_close_connection(SilcServer server,
2100 SilcSocketConnection sock)
2102 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2104 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2105 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2106 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2109 /* We won't listen for this connection anymore */
2110 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2112 /* Unregister all tasks */
2113 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2114 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2116 /* Close the actual connection */
2117 silc_net_close_connection(sock->sock);
2118 server->sockets[sock->sock] = NULL;
2120 /* If sock->user_data is NULL then we'll check for active protocols
2121 here since the silc_server_free_sock_user_data has not been called
2122 for this connection. */
2123 if (!sock->user_data) {
2124 /* If any protocol is active cancel its execution. It will call
2125 the final callback which will finalize the disconnection. */
2126 if (sock->protocol) {
2127 silc_protocol_cancel(sock->protocol, server->schedule);
2128 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2129 silc_protocol_execute_final(sock->protocol, server->schedule);
2130 sock->protocol = NULL;
2135 silc_schedule_task_add(server->schedule, 0,
2136 silc_server_close_connection_final,
2137 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2138 SILC_TASK_PRI_NORMAL);
2141 /* Sends disconnect message to remote connection and disconnects the
2144 void silc_server_disconnect_remote(SilcServer server,
2145 SilcSocketConnection sock,
2146 const char *fmt, ...)
2149 unsigned char buf[4096];
2154 memset(buf, 0, sizeof(buf));
2156 vsprintf(buf, fmt, ap);
2159 SILC_LOG_DEBUG(("Disconnecting remote host"));
2161 /* Notify remote end that the conversation is over. The notify message
2162 is tried to be sent immediately. */
2163 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2164 buf, strlen(buf), TRUE);
2166 /* Mark the connection to be disconnected */
2167 SILC_SET_DISCONNECTED(sock);
2168 silc_server_close_connection(server, sock);
2173 SilcClientEntry client;
2174 } *FreeClientInternal;
2176 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2178 FreeClientInternal i = (FreeClientInternal)context;
2180 silc_idlist_del_data(i->client);
2181 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2185 /* Frees client data and notifies about client's signoff. */
2187 void silc_server_free_client_data(SilcServer server,
2188 SilcSocketConnection sock,
2189 SilcClientEntry client,
2193 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2195 /* If there is pending outgoing data for the client then purge it
2196 to the network before removing the client entry. */
2197 if (sock && SILC_IS_OUTBUF_PENDING(sock) &&
2198 (SILC_IS_DISCONNECTED(sock) == FALSE)) {
2199 server->stat.packets_sent++;
2201 if (sock->outbuf->data - sock->outbuf->head)
2202 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
2204 silc_packet_send(sock, TRUE);
2206 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, sock->sock);
2207 SILC_UNSET_OUTBUF_PENDING(sock);
2208 silc_buffer_clear(sock->outbuf);
2211 /* Send SIGNOFF notify to routers. */
2212 if (notify && !server->standalone && server->router)
2213 silc_server_send_notify_signoff(server, server->router->connection,
2214 server->server_type == SILC_SERVER ?
2215 FALSE : TRUE, client->id, signoff);
2217 /* Remove client from all channels */
2219 silc_server_remove_from_channels(server, NULL, client,
2220 TRUE, signoff, TRUE);
2222 silc_server_remove_from_channels(server, NULL, client,
2223 FALSE, NULL, FALSE);
2225 /* We will not delete the client entry right away. We will take it
2226 into history (for WHOWAS command) for 5 minutes */
2229 silc_schedule_task_add(server->schedule, 0,
2230 silc_server_free_client_data_timeout,
2232 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2233 client->data.registered = FALSE;
2234 client->router = NULL;
2235 client->connection = NULL;
2237 /* Free the client entry and everything in it */
2238 server->stat.my_clients--;
2239 server->stat.clients--;
2240 if (server->server_type == SILC_ROUTER)
2241 server->stat.cell_clients--;
2244 /* Frees user_data pointer from socket connection object. This also sends
2245 appropriate notify packets to the network to inform about leaving
2248 void silc_server_free_sock_user_data(SilcServer server,
2249 SilcSocketConnection sock)
2251 SILC_LOG_DEBUG(("Start"));
2253 switch(sock->type) {
2254 case SILC_SOCKET_TYPE_CLIENT:
2256 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2257 silc_server_free_client_data(server, sock, user_data, TRUE, NULL);
2260 case SILC_SOCKET_TYPE_SERVER:
2261 case SILC_SOCKET_TYPE_ROUTER:
2263 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2265 /* Free all client entries that this server owns as they will
2266 become invalid now as well. */
2268 silc_server_remove_clients_by_server(server, user_data, TRUE);
2270 /* If this was our primary router connection then we're lost to
2271 the outside world. */
2272 if (server->router == user_data) {
2273 server->id_entry->router = NULL;
2274 server->router = NULL;
2275 server->standalone = TRUE;
2278 /* Free the server entry */
2279 silc_idlist_del_data(user_data);
2280 silc_idlist_del_server(server->local_list, user_data);
2281 server->stat.my_servers--;
2282 server->stat.servers--;
2283 if (server->server_type == SILC_ROUTER)
2284 server->stat.cell_servers--;
2289 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2291 silc_idlist_del_data(user_data);
2292 silc_free(user_data);
2297 /* If any protocol is active cancel its execution */
2298 if (sock->protocol) {
2299 silc_protocol_cancel(sock->protocol, server->schedule);
2300 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2301 silc_protocol_execute_final(sock->protocol, server->schedule);
2302 sock->protocol = NULL;
2305 sock->user_data = NULL;
2308 /* Removes the client from channels and possibly removes the channels
2309 as well. After removing those channels that exist, their channel
2310 keys are regnerated. This is called only by the function
2311 silc_server_remove_clients_by_server. */
2313 static void silc_server_remove_clients_channels(SilcServer server,
2314 SilcSocketConnection sock,
2315 SilcClientEntry client,
2316 SilcHashTable channels)
2318 SilcChannelEntry channel;
2319 SilcChannelClientEntry chl;
2320 SilcHashTableList htl;
2323 SILC_LOG_DEBUG(("Start"));
2325 if (!client || !client->id)
2328 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2330 /* Remove the client from all channels. The client is removed from
2331 the channels' user list. */
2332 silc_hash_table_list(client->channels, &htl);
2333 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2334 channel = chl->channel;
2336 /* Remove channel from client's channel list */
2337 silc_hash_table_del(client->channels, channel);
2339 /* Remove channel if there is no users anymore */
2340 if (server->server_type == SILC_ROUTER &&
2341 silc_hash_table_count(channel->user_list) < 2) {
2343 if (silc_hash_table_find(channels, channel, NULL, NULL))
2344 silc_hash_table_del(channels, channel);
2347 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2349 if (!silc_idlist_del_channel(server->local_list, channel))
2350 silc_idlist_del_channel(server->global_list, channel);
2351 server->stat.my_channels--;
2355 /* Remove client from channel's client list */
2356 silc_hash_table_del(channel->user_list, chl->client);
2358 server->stat.my_chanclients--;
2360 /* If there is no global users on the channel anymore mark the channel
2361 as local channel. Do not check if the removed client is local client. */
2362 if (server->server_type == SILC_SERVER && channel->global_users &&
2363 chl->client->router && !silc_server_channel_has_global(channel))
2364 channel->global_users = FALSE;
2366 /* If there is not at least one local user on the channel then we don't
2367 need the channel entry anymore, we can remove it safely. */
2368 if (server->server_type == SILC_SERVER &&
2369 !silc_server_channel_has_local(channel)) {
2371 if (silc_hash_table_find(channels, channel, NULL, NULL))
2372 silc_hash_table_del(channels, channel);
2375 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2377 if (channel->founder_key) {
2378 /* The founder auth data exists, do not remove the channel entry */
2379 SilcChannelClientEntry chl2;
2380 SilcHashTableList htl2;
2384 silc_hash_table_list(channel->user_list, &htl2);
2385 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2386 silc_hash_table_del(chl2->client->channels, channel);
2387 silc_hash_table_del(channel->user_list, chl2->client);
2393 /* Remove the channel entry */
2394 if (!silc_idlist_del_channel(server->local_list, channel))
2395 silc_idlist_del_channel(server->global_list, channel);
2396 server->stat.my_channels--;
2400 /* Add the channel to the the channels list to regenerate the
2402 if (!silc_hash_table_find(channels, channel, NULL, NULL))
2403 silc_hash_table_add(channels, channel, channel);
2406 silc_buffer_free(clidp);
2409 /* This function is used to remove all client entries by the server `entry'.
2410 This is called when the connection is lost to the server. In this case
2411 we must invalidate all the client entries owned by the server `entry'.
2412 If the `server_signoff' is TRUE then the SERVER_SIGNOFF notify is
2413 distributed to our local clients. */
2415 int silc_server_remove_clients_by_server(SilcServer server,
2416 SilcServerEntry entry,
2419 SilcIDCacheList list = NULL;
2420 SilcIDCacheEntry id_cache = NULL;
2421 SilcClientEntry client = NULL;
2423 SilcClientEntry *clients = NULL;
2424 uint32 clients_c = 0;
2425 unsigned char **argv = NULL;
2426 uint32 *argv_lens = NULL, *argv_types = NULL, argc = 0;
2427 SilcHashTableList htl;
2428 SilcChannelEntry channel;
2429 SilcHashTable channels;
2432 SILC_LOG_DEBUG(("Start"));
2434 /* Allocate the hash table that holds the channels that require
2435 channel key re-generation after we've removed this server's clients
2436 from the channels. */
2437 channels = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL, NULL,
2440 if (server_signoff) {
2441 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
2442 argv = silc_realloc(argv, sizeof(*argv) * (argc + 1));
2443 argv_lens = silc_realloc(argv_lens, sizeof(*argv_lens) * (argc + 1));
2444 argv_types = silc_realloc(argv_types, sizeof(*argv_types) * (argc + 1));
2445 argv[argc] = silc_calloc(idp->len, sizeof(*argv[0]));
2446 memcpy(argv[argc], idp->data, idp->len);
2447 argv_lens[argc] = idp->len;
2448 argv_types[argc] = argc + 1;
2450 silc_buffer_free(idp);
2453 if (silc_idcache_get_all(server->local_list->clients, &list)) {
2455 if (silc_idcache_list_first(list, &id_cache)) {
2457 client = (SilcClientEntry)id_cache->context;
2458 if (client->data.registered == FALSE) {
2459 if (!silc_idcache_list_next(list, &id_cache))
2465 if (client->router != entry) {
2466 if (server_signoff && client->connection) {
2467 clients = silc_realloc(clients,
2468 sizeof(*clients) * (clients_c + 1));
2469 clients[clients_c] = client;
2473 if (!silc_idcache_list_next(list, &id_cache))
2479 if (server_signoff) {
2480 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2481 argv = silc_realloc(argv, sizeof(*argv) * (argc + 1));
2482 argv_lens = silc_realloc(argv_lens, sizeof(*argv_lens) *
2484 argv_types = silc_realloc(argv_types, sizeof(*argv_types) *
2486 argv[argc] = silc_calloc(idp->len, sizeof(*argv[0]));
2487 memcpy(argv[argc], idp->data, idp->len);
2488 argv_lens[argc] = idp->len;
2489 argv_types[argc] = argc + 1;
2491 silc_buffer_free(idp);
2494 /* Remove the client entry */
2495 silc_server_remove_clients_channels(server, NULL, client, channels);
2496 silc_idlist_del_client(server->local_list, client);
2498 if (!silc_idcache_list_next(list, &id_cache))
2502 silc_idcache_list_free(list);
2505 if (silc_idcache_get_all(server->global_list->clients, &list)) {
2507 if (silc_idcache_list_first(list, &id_cache)) {
2509 client = (SilcClientEntry)id_cache->context;
2510 if (client->data.registered == FALSE) {
2511 if (!silc_idcache_list_next(list, &id_cache))
2517 if (client->router != entry) {
2518 if (server_signoff && client->connection) {
2519 clients = silc_realloc(clients,
2520 sizeof(*clients) * (clients_c + 1));
2521 clients[clients_c] = client;
2525 if (!silc_idcache_list_next(list, &id_cache))
2531 if (server_signoff) {
2532 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2533 argv = silc_realloc(argv, sizeof(*argv) * (argc + 1));
2534 argv_lens = silc_realloc(argv_lens, sizeof(*argv_lens) *
2536 argv_types = silc_realloc(argv_types, sizeof(*argv_types) *
2538 argv[argc] = silc_calloc(idp->len, sizeof(*argv[0]));
2539 memcpy(argv[argc], idp->data, idp->len);
2540 argv_lens[argc] = idp->len;
2541 argv_types[argc] = argc + 1;
2543 silc_buffer_free(idp);
2546 /* Remove the client entry */
2547 silc_server_remove_clients_channels(server, NULL, client, channels);
2548 silc_idlist_del_client(server->global_list, client);
2550 if (!silc_idcache_list_next(list, &id_cache))
2554 silc_idcache_list_free(list);
2557 /* Send the SERVER_SIGNOFF notify */
2558 if (server_signoff) {
2561 /* Send SERVER_SIGNOFF notify to our primary router */
2562 if (!server->standalone && server->router &&
2563 server->router != entry) {
2564 args = silc_argument_payload_encode(1, argv, argv_lens,
2566 silc_server_send_notify_args(server,
2567 server->router->connection,
2568 server->server_type == SILC_SERVER ?
2570 SILC_NOTIFY_TYPE_SERVER_SIGNOFF,
2572 silc_buffer_free(args);
2575 args = silc_argument_payload_encode(argc, argv, argv_lens,
2577 /* Send to local clients */
2578 for (i = 0; i < clients_c; i++) {
2579 silc_server_send_notify_args(server, clients[i]->connection,
2580 FALSE, SILC_NOTIFY_TYPE_SERVER_SIGNOFF,
2585 silc_buffer_free(args);
2586 for (i = 0; i < argc; i++)
2589 silc_free(argv_lens);
2590 silc_free(argv_types);
2593 /* We must now re-generate the channel key for all channels that had
2594 this server's client(s) on the channel. As they left the channel we
2595 must re-generate the channel key. */
2596 silc_hash_table_list(channels, &htl);
2597 while (silc_hash_table_get(&htl, NULL, (void *)&channel)) {
2598 if (!silc_server_create_channel_key(server, channel, 0))
2600 silc_server_send_channel_key(server, NULL, channel,
2601 server->server_type == SILC_ROUTER ?
2602 FALSE : !server->standalone);
2604 silc_hash_table_free(channels);
2609 /* Checks whether given channel has global users. If it does this returns
2610 TRUE and FALSE if there is only locally connected clients on the channel. */
2612 int silc_server_channel_has_global(SilcChannelEntry channel)
2614 SilcChannelClientEntry chl;
2615 SilcHashTableList htl;
2617 silc_hash_table_list(channel->user_list, &htl);
2618 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2619 if (chl->client->router)
2626 /* Checks whether given channel has locally connected users. If it does this
2627 returns TRUE and FALSE if there is not one locally connected client. */
2629 int silc_server_channel_has_local(SilcChannelEntry channel)
2631 SilcChannelClientEntry chl;
2632 SilcHashTableList htl;
2634 silc_hash_table_list(channel->user_list, &htl);
2635 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2636 if (!chl->client->router)
2643 /* Removes client from all channels it has joined. This is used when client
2644 connection is disconnected. If the client on a channel is last, the
2645 channel is removed as well. This sends the SIGNOFF notify types. */
2647 void silc_server_remove_from_channels(SilcServer server,
2648 SilcSocketConnection sock,
2649 SilcClientEntry client,
2651 char *signoff_message,
2654 SilcChannelEntry channel;
2655 SilcChannelClientEntry chl;
2656 SilcHashTableList htl;
2659 SILC_LOG_DEBUG(("Start"));
2661 if (!client || !client->id)
2664 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2666 /* Remove the client from all channels. The client is removed from
2667 the channels' user list. */
2668 silc_hash_table_list(client->channels, &htl);
2669 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2670 channel = chl->channel;
2672 /* Remove channel from client's channel list */
2673 silc_hash_table_del(client->channels, channel);
2675 /* Remove channel if there is no users anymore */
2676 if (server->server_type == SILC_ROUTER &&
2677 silc_hash_table_count(channel->user_list) < 2) {
2679 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2680 if (!silc_idlist_del_channel(server->local_list, channel))
2681 silc_idlist_del_channel(server->global_list, channel);
2682 server->stat.my_channels--;
2686 /* Remove client from channel's client list */
2687 silc_hash_table_del(channel->user_list, chl->client);
2689 server->stat.my_chanclients--;
2691 /* If there is no global users on the channel anymore mark the channel
2692 as local channel. Do not check if the removed client is local client. */
2693 if (server->server_type == SILC_SERVER && channel->global_users &&
2694 chl->client->router && !silc_server_channel_has_global(channel))
2695 channel->global_users = FALSE;
2697 /* If there is not at least one local user on the channel then we don't
2698 need the channel entry anymore, we can remove it safely. */
2699 if (server->server_type == SILC_SERVER &&
2700 !silc_server_channel_has_local(channel)) {
2701 /* Notify about leaving client if this channel has global users. */
2702 if (notify && channel->global_users)
2703 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2704 SILC_NOTIFY_TYPE_SIGNOFF,
2705 signoff_message ? 2 : 1,
2706 clidp->data, clidp->len,
2707 signoff_message, signoff_message ?
2708 strlen(signoff_message) : 0);
2711 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2713 if (channel->founder_key) {
2714 /* The founder auth data exists, do not remove the channel entry */
2715 SilcChannelClientEntry chl2;
2716 SilcHashTableList htl2;
2720 silc_hash_table_list(channel->user_list, &htl2);
2721 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2722 silc_hash_table_del(chl2->client->channels, channel);
2723 silc_hash_table_del(channel->user_list, chl2->client);
2729 /* Remove the channel entry */
2730 if (!silc_idlist_del_channel(server->local_list, channel))
2731 silc_idlist_del_channel(server->global_list, channel);
2732 server->stat.my_channels--;
2736 /* Send notify to channel about client leaving SILC and thus
2737 the entire channel. */
2739 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2740 SILC_NOTIFY_TYPE_SIGNOFF,
2741 signoff_message ? 2 : 1,
2742 clidp->data, clidp->len,
2743 signoff_message, signoff_message ?
2744 strlen(signoff_message) : 0);
2746 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2747 /* Re-generate channel key */
2748 if (!silc_server_create_channel_key(server, channel, 0))
2751 /* Send the channel key to the channel. The key of course is not sent
2752 to the client who was removed from the channel. */
2753 silc_server_send_channel_key(server, client->connection, channel,
2754 server->server_type == SILC_ROUTER ?
2755 FALSE : !server->standalone);
2759 silc_buffer_free(clidp);
2762 /* Removes client from one channel. This is used for example when client
2763 calls LEAVE command to remove itself from the channel. Returns TRUE
2764 if channel still exists and FALSE if the channel is removed when
2765 last client leaves the channel. If `notify' is FALSE notify messages
2768 int silc_server_remove_from_one_channel(SilcServer server,
2769 SilcSocketConnection sock,
2770 SilcChannelEntry channel,
2771 SilcClientEntry client,
2774 SilcChannelClientEntry chl;
2777 SILC_LOG_DEBUG(("Start"));
2779 /* Get the entry to the channel, if this client is not on the channel
2781 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2784 /* Remove the client from the channel. The client is removed from
2785 the channel's user list. */
2787 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2789 /* Remove channel from client's channel list */
2790 silc_hash_table_del(client->channels, chl->channel);
2792 /* Remove channel if there is no users anymore */
2793 if (server->server_type == SILC_ROUTER &&
2794 silc_hash_table_count(channel->user_list) < 2) {
2796 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2797 if (!silc_idlist_del_channel(server->local_list, channel))
2798 silc_idlist_del_channel(server->global_list, channel);
2799 silc_buffer_free(clidp);
2800 server->stat.my_channels--;
2804 /* Remove client from channel's client list */
2805 silc_hash_table_del(channel->user_list, chl->client);
2807 server->stat.my_chanclients--;
2809 /* If there is no global users on the channel anymore mark the channel
2810 as local channel. Do not check if the client is local client. */
2811 if (server->server_type == SILC_SERVER && channel->global_users &&
2812 chl->client->router && !silc_server_channel_has_global(channel))
2813 channel->global_users = FALSE;
2815 /* If there is not at least one local user on the channel then we don't
2816 need the channel entry anymore, we can remove it safely. */
2817 if (server->server_type == SILC_SERVER &&
2818 !silc_server_channel_has_local(channel)) {
2819 /* Notify about leaving client if this channel has global users. */
2820 if (notify && channel->global_users)
2821 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2822 SILC_NOTIFY_TYPE_LEAVE, 1,
2823 clidp->data, clidp->len);
2825 silc_buffer_free(clidp);
2828 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2830 if (channel->founder_key) {
2831 /* The founder auth data exists, do not remove the channel entry */
2832 SilcChannelClientEntry chl2;
2833 SilcHashTableList htl2;
2837 silc_hash_table_list(channel->user_list, &htl2);
2838 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2839 silc_hash_table_del(chl2->client->channels, channel);
2840 silc_hash_table_del(channel->user_list, chl2->client);
2846 /* Remove the channel entry */
2847 if (!silc_idlist_del_channel(server->local_list, channel))
2848 silc_idlist_del_channel(server->global_list, channel);
2849 server->stat.my_channels--;
2853 /* Send notify to channel about client leaving the channel */
2855 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2856 SILC_NOTIFY_TYPE_LEAVE, 1,
2857 clidp->data, clidp->len);
2859 silc_buffer_free(clidp);
2863 /* Returns TRUE if the given client is on the channel. FALSE if not.
2864 This works because we assure that the user list on the channel is
2865 always in up to date thus we can only check the channel list from
2866 `client' which is faster than checking the user list from `channel'. */
2868 int silc_server_client_on_channel(SilcClientEntry client,
2869 SilcChannelEntry channel)
2871 if (!client || !channel)
2874 if (silc_hash_table_find(client->channels, channel, NULL, NULL))
2880 /* Timeout callback. This is called if connection is idle or for some
2881 other reason is not responding within some period of time. This
2882 disconnects the remote end. */
2884 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2886 SilcServer server = (SilcServer)context;
2887 SilcSocketConnection sock = server->sockets[fd];
2889 SILC_LOG_DEBUG(("Start"));
2894 /* If we have protocol active we must assure that we call the protocol's
2895 final callback so that all the memory is freed. */
2896 if (sock->protocol) {
2897 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2898 silc_protocol_execute_final(sock->protocol, server->schedule);
2902 if (sock->user_data)
2903 silc_server_free_sock_user_data(server, sock);
2905 silc_server_disconnect_remote(server, sock, "Server closed connection: "
2906 "Connection timeout");
2909 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2910 function may be used only by router. In real SILC network all channels
2911 are created by routers thus this function is never used by normal
2914 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2915 SilcServerID *router_id,
2921 SilcChannelID *channel_id;
2922 SilcChannelEntry entry;
2926 SILC_LOG_DEBUG(("Creating new channel"));
2929 cipher = "aes-256-cbc";
2931 hmac = "hmac-sha1-96";
2933 /* Allocate cipher */
2934 if (!silc_cipher_alloc(cipher, &key))
2938 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2939 silc_cipher_free(key);
2943 channel_name = strdup(channel_name);
2945 /* Create the channel */
2946 silc_id_create_channel_id(router_id, server->rng, &channel_id);
2947 entry = silc_idlist_add_channel(server->local_list, channel_name,
2948 SILC_CHANNEL_MODE_NONE, channel_id,
2949 NULL, key, newhmac);
2951 silc_free(channel_name);
2952 silc_cipher_free(key);
2953 silc_hmac_free(newhmac);
2957 entry->cipher = strdup(cipher);
2958 entry->hmac_name = strdup(hmac);
2960 /* Now create the actual key material */
2961 if (!silc_server_create_channel_key(server, entry,
2962 silc_cipher_get_key_len(key) / 8)) {
2963 silc_free(channel_name);
2964 silc_cipher_free(key);
2965 silc_hmac_free(newhmac);
2966 silc_free(entry->cipher);
2967 silc_free(entry->hmac_name);
2971 /* Notify other routers about the new channel. We send the packet
2972 to our primary route. */
2973 if (broadcast && server->standalone == FALSE)
2974 silc_server_send_new_channel(server, server->router->connection, TRUE,
2975 channel_name, entry->id,
2976 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2979 server->stat.my_channels++;
2984 /* Same as above but creates the channel with Channel ID `channel_id. */
2987 silc_server_create_new_channel_with_id(SilcServer server,
2991 SilcChannelID *channel_id,
2994 SilcChannelEntry entry;
2998 SILC_LOG_DEBUG(("Creating new channel"));
3001 cipher = "aes-256-cbc";
3003 hmac = "hmac-sha1-96";
3005 /* Allocate cipher */
3006 if (!silc_cipher_alloc(cipher, &key))
3010 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3011 silc_cipher_free(key);
3015 channel_name = strdup(channel_name);
3017 /* Create the channel */
3018 entry = silc_idlist_add_channel(server->local_list, channel_name,
3019 SILC_CHANNEL_MODE_NONE, channel_id,
3020 NULL, key, newhmac);
3022 silc_free(channel_name);
3026 /* Now create the actual key material */
3027 if (!silc_server_create_channel_key(server, entry,
3028 silc_cipher_get_key_len(key) / 8)) {
3029 silc_free(channel_name);
3033 /* Notify other routers about the new channel. We send the packet
3034 to our primary route. */
3035 if (broadcast && server->standalone == FALSE)
3036 silc_server_send_new_channel(server, server->router->connection, TRUE,
3037 channel_name, entry->id,
3038 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3041 server->stat.my_channels++;
3046 /* Channel's key re-key timeout callback. */
3048 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3050 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3051 SilcServer server = (SilcServer)rekey->context;
3053 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3055 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3057 silc_schedule_task_add(server->schedule, 0,
3058 silc_server_channel_key_rekey,
3059 (void *)rekey, 3600, 0,
3061 SILC_TASK_PRI_NORMAL);
3064 /* Generates new channel key. This is used to create the initial channel key
3065 but also to re-generate new key for channel. If `key_len' is provided
3066 it is the bytes of the key length. */
3068 bool silc_server_create_channel_key(SilcServer server,
3069 SilcChannelEntry channel,
3073 unsigned char channel_key[32], hash[32];
3076 SILC_LOG_DEBUG(("Generating channel key"));
3078 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3079 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3083 if (!channel->channel_key)
3084 if (!silc_cipher_alloc("aes-256-cbc", &channel->channel_key))
3089 else if (channel->key_len)
3090 len = channel->key_len / 8;
3092 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3094 /* Create channel key */
3095 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3098 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3100 /* Remove old key if exists */
3102 memset(channel->key, 0, channel->key_len / 8);
3103 silc_free(channel->key);
3107 channel->key_len = len * 8;
3108 channel->key = silc_calloc(len, sizeof(*channel->key));
3109 memcpy(channel->key, channel_key, len);
3110 memset(channel_key, 0, sizeof(channel_key));
3112 /* Generate HMAC key from the channel key data and set it */
3114 silc_hmac_alloc("hmac-sha1-96", NULL, &channel->hmac);
3115 silc_hash_make(channel->hmac->hash, channel->key, len, hash);
3116 silc_hmac_set_key(channel->hmac, hash, silc_hash_len(channel->hmac->hash));
3117 memset(hash, 0, sizeof(hash));
3119 if (server->server_type == SILC_ROUTER) {
3120 if (!channel->rekey)
3121 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3122 channel->rekey->context = (void *)server;
3123 channel->rekey->channel = channel;
3124 channel->rekey->key_len = key_len;
3127 /* XXX Now this cannot be a good thing */
3128 silc_schedule_task_del_by_callback(server->schedule,
3129 silc_server_channel_key_rekey);
3131 silc_schedule_task_add(server->schedule, 0,
3132 silc_server_channel_key_rekey,
3133 (void *)channel->rekey, 3600, 0,
3135 SILC_TASK_PRI_NORMAL);
3141 /* Saves the channel key found in the encoded `key_payload' buffer. This
3142 function is used when we receive Channel Key Payload and also when we're
3143 processing JOIN command reply. Returns entry to the channel. */
3145 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3146 SilcBuffer key_payload,
3147 SilcChannelEntry channel)
3149 SilcChannelKeyPayload payload = NULL;
3150 SilcChannelID *id = NULL;
3151 unsigned char *tmp, hash[32];
3155 SILC_LOG_DEBUG(("Start"));
3157 /* Decode channel key payload */
3158 payload = silc_channel_key_payload_parse(key_payload);
3160 SILC_LOG_ERROR(("Bad channel key payload, dropped"));
3165 /* Get the channel entry */
3168 /* Get channel ID */
3169 tmp = silc_channel_key_get_id(payload, &tmp_len);
3170 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3176 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3178 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3180 SILC_LOG_ERROR(("Received key for non-existent channel"));
3186 tmp = silc_channel_key_get_key(payload, &tmp_len);
3192 cipher = silc_channel_key_get_cipher(payload, NULL);
3198 /* Remove old key if exists */
3200 memset(channel->key, 0, channel->key_len / 8);
3201 silc_free(channel->key);
3202 silc_cipher_free(channel->channel_key);
3205 /* Create new cipher */
3206 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3211 if (channel->cipher)
3212 silc_free(channel->cipher);
3213 channel->cipher = strdup(cipher);
3216 channel->key_len = tmp_len * 8;
3217 channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
3218 memcpy(channel->key, tmp, tmp_len);
3219 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3221 /* Generate HMAC key from the channel key data and set it */
3223 silc_hmac_alloc("hmac-sha1-96", NULL, &channel->hmac);
3224 silc_hash_make(channel->hmac->hash, tmp, tmp_len, hash);
3225 silc_hmac_set_key(channel->hmac, hash, silc_hash_len(channel->hmac->hash));
3227 memset(hash, 0, sizeof(hash));
3228 memset(tmp, 0, tmp_len);
3230 if (server->server_type == SILC_ROUTER) {
3231 if (!channel->rekey)
3232 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3233 channel->rekey->context = (void *)server;
3234 channel->rekey->channel = channel;
3236 silc_schedule_task_del_by_callback(server->schedule,
3237 silc_server_channel_key_rekey);
3238 silc_schedule_task_add(server->schedule, 0,
3239 silc_server_channel_key_rekey,
3240 (void *)channel->rekey, 3600, 0,
3242 SILC_TASK_PRI_NORMAL);
3249 silc_channel_key_payload_free(payload);
3254 /* Heartbeat callback. This function is set as argument for the
3255 silc_socket_set_heartbeat function. The library will call this function
3256 at the set time interval. */
3258 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3261 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3263 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname,
3266 /* Send the heartbeat */
3267 silc_server_send_heartbeat(hb->server, sock);
3270 /* Returns assembled of all servers in the given ID list. The packet's
3271 form is dictated by the New ID payload. */
3273 static void silc_server_announce_get_servers(SilcServer server,
3275 SilcBuffer *servers)
3277 SilcIDCacheList list;
3278 SilcIDCacheEntry id_cache;
3279 SilcServerEntry entry;
3282 /* Go through all clients in the list */
3283 if (silc_idcache_get_all(id_list->servers, &list)) {
3284 if (silc_idcache_list_first(list, &id_cache)) {
3286 entry = (SilcServerEntry)id_cache->context;
3288 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3290 *servers = silc_buffer_realloc(*servers,
3292 (*servers)->truelen + idp->len :
3294 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3295 silc_buffer_put(*servers, idp->data, idp->len);
3296 silc_buffer_pull(*servers, idp->len);
3297 silc_buffer_free(idp);
3299 if (!silc_idcache_list_next(list, &id_cache))
3304 silc_idcache_list_free(list);
3308 /* This function is used by router to announce existing servers to our
3309 primary router when we've connected to it. */
3311 void silc_server_announce_servers(SilcServer server)
3313 SilcBuffer servers = NULL;
3315 SILC_LOG_DEBUG(("Announcing servers"));
3317 /* Get servers in local list */
3318 silc_server_announce_get_servers(server, server->local_list, &servers);
3320 /* Get servers in global list */
3321 silc_server_announce_get_servers(server, server->global_list, &servers);
3324 silc_buffer_push(servers, servers->data - servers->head);
3325 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3327 /* Send the packet */
3328 silc_server_packet_send(server, server->router->connection,
3329 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3330 servers->data, servers->len, TRUE);
3332 silc_buffer_free(servers);
3336 /* Returns assembled packet of all clients in the given ID list. The
3337 packet's form is dictated by the New ID Payload. */
3339 static void silc_server_announce_get_clients(SilcServer server,
3341 SilcBuffer *clients)
3343 SilcIDCacheList list;
3344 SilcIDCacheEntry id_cache;
3345 SilcClientEntry client;
3348 /* Go through all clients in the list */
3349 if (silc_idcache_get_all(id_list->clients, &list)) {
3350 if (silc_idcache_list_first(list, &id_cache)) {
3352 client = (SilcClientEntry)id_cache->context;
3354 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3356 *clients = silc_buffer_realloc(*clients,
3358 (*clients)->truelen + idp->len :
3360 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3361 silc_buffer_put(*clients, idp->data, idp->len);
3362 silc_buffer_pull(*clients, idp->len);
3363 silc_buffer_free(idp);
3365 if (!silc_idcache_list_next(list, &id_cache))
3370 silc_idcache_list_free(list);
3374 /* This function is used to announce our existing clients to our router
3375 when we've connected to it. */
3377 void silc_server_announce_clients(SilcServer server)
3379 SilcBuffer clients = NULL;
3381 SILC_LOG_DEBUG(("Announcing clients"));
3383 /* Get clients in local list */
3384 silc_server_announce_get_clients(server, server->local_list,
3387 /* As router we announce our global list as well */
3388 if (server->server_type == SILC_ROUTER)
3389 silc_server_announce_get_clients(server, server->global_list,
3393 silc_buffer_push(clients, clients->data - clients->head);
3394 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3396 /* Send the packet */
3397 silc_server_packet_send(server, server->router->connection,
3398 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3399 clients->data, clients->len, TRUE);
3401 silc_buffer_free(clients);
3406 silc_server_announce_encode_notify(SilcNotifyType notify, uint32 argc, ...)
3412 p = silc_notify_payload_encode(notify, argc, ap);
3418 /* Returns assembled packets for channel users of the `channel'. */
3420 void silc_server_announce_get_channel_users(SilcServer server,
3421 SilcChannelEntry channel,
3422 SilcBuffer *channel_users,
3423 SilcBuffer *channel_users_modes)
3425 SilcChannelClientEntry chl;
3426 SilcHashTableList htl;
3427 SilcBuffer chidp, clidp;
3430 unsigned char mode[4];
3432 SILC_LOG_DEBUG(("Start"));
3434 /* Now find all users on the channel */
3435 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3436 silc_hash_table_list(channel->user_list, &htl);
3437 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3438 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3441 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3442 clidp->data, clidp->len,
3443 chidp->data, chidp->len);
3446 silc_buffer_realloc(*channel_users,
3448 (*channel_users)->truelen + len : len));
3449 silc_buffer_pull_tail(*channel_users,
3450 ((*channel_users)->end -
3451 (*channel_users)->data));
3453 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3454 silc_buffer_pull(*channel_users, len);
3455 silc_buffer_free(tmp);
3457 /* CUMODE notify for mode change on the channel */
3458 SILC_PUT32_MSB(chl->mode, mode);
3459 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3460 3, clidp->data, clidp->len,
3462 clidp->data, clidp->len);
3464 *channel_users_modes =
3465 silc_buffer_realloc(*channel_users_modes,
3466 (*channel_users_modes ?
3467 (*channel_users_modes)->truelen + len : len));
3468 silc_buffer_pull_tail(*channel_users_modes,
3469 ((*channel_users_modes)->end -
3470 (*channel_users_modes)->data));
3472 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3473 silc_buffer_pull(*channel_users_modes, len);
3474 silc_buffer_free(tmp);
3476 silc_buffer_free(clidp);
3478 silc_buffer_free(chidp);
3481 /* Returns assembled packets for all channels and users on those channels
3482 from the given ID List. The packets are in the form dictated by the
3483 New Channel and New Channel User payloads. */
3485 void silc_server_announce_get_channels(SilcServer server,
3487 SilcBuffer *channels,
3488 SilcBuffer *channel_users,
3489 SilcBuffer **channel_users_modes,
3490 uint32 *channel_users_modes_c,
3491 SilcChannelID ***channel_ids)
3493 SilcIDCacheList list;
3494 SilcIDCacheEntry id_cache;
3495 SilcChannelEntry channel;
3500 int i = *channel_users_modes_c;
3502 SILC_LOG_DEBUG(("Start"));
3504 /* Go through all channels in the list */
3505 if (silc_idcache_get_all(id_list->channels, &list)) {
3506 if (silc_idcache_list_first(list, &id_cache)) {
3508 channel = (SilcChannelEntry)id_cache->context;
3510 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3511 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3512 name_len = strlen(channel->channel_name);
3514 len = 4 + name_len + id_len + 4;
3516 silc_buffer_realloc(*channels,
3517 (*channels ? (*channels)->truelen + len : len));
3518 silc_buffer_pull_tail(*channels,
3519 ((*channels)->end - (*channels)->data));
3520 silc_buffer_format(*channels,
3521 SILC_STR_UI_SHORT(name_len),
3522 SILC_STR_UI_XNSTRING(channel->channel_name,
3524 SILC_STR_UI_SHORT(id_len),
3525 SILC_STR_UI_XNSTRING(cid, id_len),
3526 SILC_STR_UI_INT(channel->mode),
3528 silc_buffer_pull(*channels, len);
3530 *channel_users_modes = silc_realloc(*channel_users_modes,
3531 sizeof(**channel_users_modes) *
3533 (*channel_users_modes)[i] = NULL;
3534 *channel_ids = silc_realloc(*channel_ids,
3535 sizeof(**channel_ids) * (i + 1));
3536 (*channel_ids)[i] = NULL;
3537 silc_server_announce_get_channel_users(server, channel,
3539 channel_users_modes[i]);
3540 (*channel_ids)[i] = channel->id;
3543 if (!silc_idcache_list_next(list, &id_cache))
3547 *channel_users_modes_c += i;
3550 silc_idcache_list_free(list);
3554 /* This function is used to announce our existing channels to our router
3555 when we've connected to it. This also announces the users on the
3556 channels to the router. */
3558 void silc_server_announce_channels(SilcServer server)
3560 SilcBuffer channels = NULL, channel_users = NULL;
3561 SilcBuffer *channel_users_modes = NULL;
3562 uint32 channel_users_modes_c = 0;
3563 SilcChannelID **channel_ids = NULL;
3565 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3567 /* Get channels and channel users in local list */
3568 silc_server_announce_get_channels(server, server->local_list,
3569 &channels, &channel_users,
3570 &channel_users_modes,
3571 &channel_users_modes_c,
3574 /* Get channels and channel users in global list */
3575 silc_server_announce_get_channels(server, server->global_list,
3576 &channels, &channel_users,
3577 &channel_users_modes,
3578 &channel_users_modes_c,
3582 silc_buffer_push(channels, channels->data - channels->head);
3583 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3585 /* Send the packet */
3586 silc_server_packet_send(server, server->router->connection,
3587 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3588 channels->data, channels->len,
3591 silc_buffer_free(channels);
3594 if (channel_users) {
3595 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3596 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3597 channel_users->len);
3599 /* Send the packet */
3600 silc_server_packet_send(server, server->router->connection,
3601 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3602 channel_users->data, channel_users->len,
3605 silc_buffer_free(channel_users);
3608 if (channel_users_modes) {
3611 for (i = 0; i < channel_users_modes_c; i++) {
3612 silc_buffer_push(channel_users_modes[i],
3613 channel_users_modes[i]->data -
3614 channel_users_modes[i]->head);
3615 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3616 channel_users_modes[i]->len);
3617 silc_server_packet_send_dest(server, server->router->connection,
3618 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3619 channel_ids[i], SILC_ID_CHANNEL,
3620 channel_users_modes[i]->data,
3621 channel_users_modes[i]->len,
3623 silc_buffer_free(channel_users_modes[i]);
3625 silc_free(channel_users_modes);
3626 silc_free(channel_ids);
3630 /* Failure timeout callback. If this is called then we will immediately
3631 process the received failure. We always process the failure with timeout
3632 since we do not want to blindly trust to received failure packets.
3633 This won't be called (the timeout is cancelled) if the failure was
3634 bogus (it is bogus if remote does not close the connection after sending
3637 SILC_TASK_CALLBACK(silc_server_failure_callback)
3639 SilcServerFailureContext f = (SilcServerFailureContext)context;
3641 if (f->sock->protocol) {
3642 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3643 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3649 /* Assembles user list and users mode list from the `channel'. */
3651 void silc_server_get_users_on_channel(SilcServer server,
3652 SilcChannelEntry channel,
3653 SilcBuffer *user_list,
3654 SilcBuffer *mode_list,
3657 SilcChannelClientEntry chl;
3658 SilcHashTableList htl;
3659 SilcBuffer client_id_list;
3660 SilcBuffer client_mode_list;
3662 uint32 list_count = 0, len = 0;
3664 silc_hash_table_list(channel->user_list, &htl);
3665 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3666 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3668 client_id_list = silc_buffer_alloc(len);
3670 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3671 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3672 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3674 silc_hash_table_list(channel->user_list, &htl);
3675 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3677 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3678 silc_buffer_put(client_id_list, idp->data, idp->len);
3679 silc_buffer_pull(client_id_list, idp->len);
3680 silc_buffer_free(idp);
3682 /* Client's mode on channel */
3683 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3684 silc_buffer_pull(client_mode_list, 4);
3688 silc_buffer_push(client_id_list,
3689 client_id_list->data - client_id_list->head);
3690 silc_buffer_push(client_mode_list,
3691 client_mode_list->data - client_mode_list->head);
3693 *user_list = client_id_list;
3694 *mode_list = client_mode_list;
3695 *user_count = list_count;
3698 /* Saves users and their modes to the `channel'. */
3700 void silc_server_save_users_on_channel(SilcServer server,
3701 SilcSocketConnection sock,
3702 SilcChannelEntry channel,
3703 SilcClientID *noadd,
3704 SilcBuffer user_list,
3705 SilcBuffer mode_list,
3710 /* Cache the received Client ID's and modes. This cache expires
3711 whenever server sends notify message to channel. It means two things;
3712 some user has joined or leaved the channel. XXX TODO! */
3713 for (i = 0; i < user_count; i++) {
3716 SilcClientID *client_id;
3717 SilcClientEntry client;
3720 SILC_GET16_MSB(idp_len, user_list->data + 2);
3722 client_id = silc_id_payload_parse_id(user_list->data, idp_len);
3723 silc_buffer_pull(user_list, idp_len);
3728 SILC_GET32_MSB(mode, mode_list->data);
3729 silc_buffer_pull(mode_list, 4);
3731 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3732 silc_free(client_id);
3736 /* Check if we have this client cached already. */
3737 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3738 server->server_type, NULL);
3740 client = silc_idlist_find_client_by_id(server->global_list,
3741 client_id, server->server_type,
3744 /* If router did not find such Client ID in its lists then this must
3745 be bogus client or some router in the net is buggy. */
3746 if (server->server_type == SILC_ROUTER) {
3747 silc_free(client_id);
3751 /* We don't have that client anywhere, add it. The client is added
3752 to global list since server didn't have it in the lists so it must be
3754 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3755 silc_id_dup(client_id, SILC_ID_CLIENT),
3756 sock->user_data, NULL);
3758 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3759 silc_free(client_id);
3763 client->data.registered = TRUE;
3766 silc_free(client_id);
3768 if (!silc_server_client_on_channel(client, channel)) {
3769 /* Client was not on the channel, add it. */
3770 SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3771 chl->client = client;
3773 chl->channel = channel;
3774 silc_hash_table_add(channel->user_list, chl->client, chl);
3775 silc_hash_table_add(client->channels, chl->channel, chl);
3780 /* Lookups route to the client indicated by the `id_data'. The connection
3781 object and internal data object is returned. Returns NULL if route
3782 could not be found to the client. If the `client_id' is specified then
3783 it is used and the `id_data' is ignored. */
3785 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3786 unsigned char *id_data,
3788 SilcClientID *client_id,
3789 SilcIDListData *idata)
3792 SilcClientEntry client;
3794 SILC_LOG_DEBUG(("Start"));
3796 /* Decode destination Client ID */
3798 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3800 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3804 id = silc_id_dup(client_id, SILC_ID_CLIENT);
3807 /* If the destination belongs to our server we don't have to route
3808 the packet anywhere but to send it to the local destination. */
3809 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
3813 /* If we are router and the client has router then the client is in
3814 our cell but not directly connected to us. */
3815 if (server->server_type == SILC_ROUTER && client->router) {
3816 /* We are of course in this case the client's router thus the route
3817 to the client is the server who owns the client. So, we will send
3818 the packet to that server. */
3820 *idata = (SilcIDListData)client->router;
3821 return client->router->connection;
3824 /* Seems that client really is directly connected to us */
3826 *idata = (SilcIDListData)client;
3827 return client->connection;
3830 /* Destination belongs to someone not in this server. If we are normal
3831 server our action is to send the packet to our router. */
3832 if (server->server_type == SILC_SERVER && !server->standalone) {
3835 *idata = (SilcIDListData)server->router;
3836 return server->router->connection;
3839 /* We are router and we will perform route lookup for the destination
3840 and send the packet to fastest route. */
3841 if (server->server_type == SILC_ROUTER && !server->standalone) {
3842 /* Check first that the ID is valid */
3843 client = silc_idlist_find_client_by_id(server->global_list, id,
3846 SilcSocketConnection dst_sock;
3848 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
3852 *idata = (SilcIDListData)dst_sock->user_data;
3861 /* Encodes and returns channel list of channels the `client' has joined.
3862 Secret channels are not put to the list. */
3864 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
3865 SilcClientEntry client)
3867 SilcBuffer buffer = NULL;
3868 SilcChannelEntry channel;
3869 SilcChannelClientEntry chl;
3870 SilcHashTableList htl;
3876 silc_hash_table_list(client->channels, &htl);
3877 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3878 channel = chl->channel;
3880 if (channel->mode & SILC_CHANNEL_MODE_SECRET)
3883 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3884 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3885 name_len = strlen(channel->channel_name);
3887 len = 4 + name_len + id_len + 4;
3888 buffer = silc_buffer_realloc(buffer,
3889 (buffer ? (buffer)->truelen + len : len));
3890 silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
3891 silc_buffer_format(buffer,
3892 SILC_STR_UI_SHORT(name_len),
3893 SILC_STR_UI_XNSTRING(channel->channel_name,
3895 SILC_STR_UI_SHORT(id_len),
3896 SILC_STR_UI_XNSTRING(cid, id_len),
3897 SILC_STR_UI_INT(chl->mode), /* Client's mode */
3899 silc_buffer_pull(buffer, len);
3904 silc_buffer_push(buffer, buffer->data - buffer->head);
3909 /* Finds client entry by Client ID and if it is not found then resolves
3910 it using WHOIS command. */
3912 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
3913 SilcClientID *client_id)
3915 SilcClientEntry client;
3917 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3920 client = silc_idlist_find_client_by_id(server->global_list,
3921 client_id, TRUE, NULL);
3922 if (!client && server->server_type == SILC_ROUTER)
3926 if (!client && server->standalone)
3929 if (!client || !client->nickname || !client->username) {
3930 SilcBuffer buffer, idp;
3932 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3933 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
3934 ++server->cmd_ident, 1,
3935 3, idp->data, idp->len);
3936 silc_server_packet_send(server, client ? client->router->connection :
3937 server->router->connection,
3938 SILC_PACKET_COMMAND, 0,
3939 buffer->data, buffer->len, FALSE);
3940 silc_buffer_free(idp);
3941 silc_buffer_free(buffer);
3948 /* A timeout callback for the re-key. We will be the initiator of the
3951 SILC_TASK_CALLBACK(silc_server_rekey_callback)
3953 SilcSocketConnection sock = (SilcSocketConnection)context;
3954 SilcIDListData idata = (SilcIDListData)sock->user_data;
3955 SilcServer server = (SilcServer)idata->rekey->context;
3956 SilcProtocol protocol;
3957 SilcServerRekeyInternalContext *proto_ctx;
3959 SILC_LOG_DEBUG(("Start"));
3961 /* Allocate internal protocol context. This is sent as context
3963 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
3964 proto_ctx->server = (void *)server;
3965 proto_ctx->sock = sock;
3966 proto_ctx->responder = FALSE;
3967 proto_ctx->pfs = idata->rekey->pfs;
3969 /* Perform rekey protocol. Will call the final callback after the
3970 protocol is over. */
3971 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
3972 &protocol, proto_ctx, silc_server_rekey_final);
3973 sock->protocol = protocol;
3975 /* Run the protocol */
3976 silc_protocol_execute(protocol, server->schedule, 0, 0);
3978 /* Re-register re-key timeout */
3979 silc_schedule_task_add(server->schedule, sock->sock,
3980 silc_server_rekey_callback,
3981 context, idata->rekey->timeout, 0,
3982 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
3985 /* The final callback for the REKEY protocol. This will actually take the
3986 new key material into use. */
3988 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
3990 SilcProtocol protocol = (SilcProtocol)context;
3991 SilcServerRekeyInternalContext *ctx =
3992 (SilcServerRekeyInternalContext *)protocol->context;
3993 SilcServer server = (SilcServer)ctx->server;
3994 SilcSocketConnection sock = ctx->sock;
3996 SILC_LOG_DEBUG(("Start"));
3998 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
3999 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4000 /* Error occured during protocol */
4001 silc_protocol_cancel(protocol, server->schedule);
4002 silc_protocol_free(protocol);
4003 sock->protocol = NULL;
4005 silc_packet_context_free(ctx->packet);
4007 silc_ske_free(ctx->ske);
4013 silc_protocol_free(protocol);
4014 sock->protocol = NULL;
4016 silc_packet_context_free(ctx->packet);
4018 silc_ske_free(ctx->ske);