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 silc_free(server->local_list);
81 silc_free(server->global_list);
83 silc_rng_free(server->rng);
86 silc_pkcs_free(server->pkcs);
89 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
90 silc_dlist_del(server->sim, sim);
93 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, i;
116 SilcServerEntry id_entry;
117 SilcIDListPurge purge;
118 SilcServerConfigSectionListenPort *listen;
120 SILC_LOG_DEBUG(("Initializing server"));
122 assert(server->config);
124 /* Set public and private keys */
125 if (!server->config->server_keys ||
126 !server->config->server_keys->public_key ||
127 !server->config->server_keys->private_key) {
128 SILC_LOG_ERROR(("Server public key and/or private key does not exist"));
131 server->public_key = server->config->server_keys->public_key;
132 server->private_key = server->config->server_keys->private_key;
134 /* XXX After server is made as Silc Server Library this can be given
135 as argument, for now this is hard coded */
136 server->params = silc_calloc(1, sizeof(*server->params));
137 server->params->retry_count = SILC_SERVER_RETRY_COUNT;
138 server->params->retry_interval_min = SILC_SERVER_RETRY_INTERVAL_MIN;
139 server->params->retry_interval_max = SILC_SERVER_RETRY_INTERVAL_MAX;
140 server->params->retry_keep_trying = FALSE;
141 server->params->protocol_timeout = 60;
142 server->params->require_reverse_mapping = FALSE;
144 /* Set log files where log message should be saved. */
145 server->config->server = server;
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 /* Allocate PKCS context for local public and private keys */
170 silc_pkcs_alloc(server->public_key->name, &server->pkcs);
171 silc_pkcs_public_key_set(server->pkcs, server->public_key);
172 silc_pkcs_private_key_set(server->pkcs, server->private_key);
174 /* Create a listening server. Note that our server can listen on multiple
175 ports. All listeners are created here and now. */
177 listen = server->config->listen_port;
181 tmp = silc_net_create_server(server->config->listen_port->port,
182 server->config->listen_port->listener_ip);
185 SILC_LOG_ERROR(("Could not create server listener: %s on %d",
186 server->config->listen_port->listener_ip,
187 server->config->listen_port->port));
191 sock = silc_realloc(sock, sizeof(*sock) * (sock_count + 1));
192 sock[sock_count] = tmp;
194 listen = listen->next;
197 /* Initialize ID caches */
198 server->local_list->clients =
199 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
200 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
201 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
203 /* These are allocated for normal server as well as these hold some
204 global information that the server has fetched from its router. For
205 router these are used as they are supposed to be used on router. */
206 server->global_list->clients =
207 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
208 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
209 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
211 /* Allocate the entire socket list that is used in server. Eventually
212 all connections will have entry in this table (it is a table of
213 pointers to the actual object that is allocated individually
215 server->sockets = silc_calloc(SILC_SERVER_MAX_CONNECTIONS,
216 sizeof(*server->sockets));
218 for (i = 0; i < sock_count; i++) {
219 SilcSocketConnection newsocket = NULL;
221 /* Set socket to non-blocking mode */
222 silc_net_set_socket_nonblock(sock[i]);
223 server->sock = sock[i];
225 /* Add ourselves also to the socket table. The entry allocated above
226 is sent as argument for fast referencing in the future. */
227 silc_socket_alloc(sock[i], SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
228 server->sockets[sock[i]] = newsocket;
230 /* Perform name and address lookups to resolve the listenning address
232 if (!silc_net_check_local_by_sock(sock[i], &newsocket->hostname,
234 if ((server->params->require_reverse_mapping && !newsocket->hostname) ||
236 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
237 newsocket->hostname ? newsocket->hostname :
238 newsocket->ip ? newsocket->ip : ""));
239 server->stat.conn_failures++;
242 if (!newsocket->hostname)
243 newsocket->hostname = strdup(newsocket->ip);
245 newsocket->port = silc_net_get_local_port(sock[i]);
247 /* Create a Server ID for the server. */
248 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
253 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
254 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
255 server->id_type = SILC_ID_SERVER;
256 server->server_name = server->config->server_info->server_name;
258 /* Add ourselves to the server list. We don't have a router yet
259 beacuse we haven't established a route yet. It will be done later.
260 For now, NULL is sent as router. This allocates new entry to
263 silc_idlist_add_server(server->local_list,
264 server->config->server_info->server_name,
265 server->server_type, server->id, NULL, NULL);
267 SILC_LOG_ERROR(("Could not add ourselves to cache"));
270 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
272 /* Put the allocated socket pointer also to the entry allocated above
273 for fast back-referencing to the socket list. */
274 newsocket->user_data = (void *)id_entry;
275 id_entry->connection = (void *)newsocket;
276 server->id_entry = id_entry;
279 /* Register protocols */
280 silc_server_protocols_register();
282 /* Initialize the scheduler. */
283 server->schedule = silc_schedule_init(SILC_SERVER_MAX_CONNECTIONS);
284 if (!server->schedule)
287 /* Add the first task to the scheduler. This is task that is executed by
288 timeout. It expires as soon as the caller calls silc_server_run. This
289 task performs authentication protocol and key exchange with our
291 silc_schedule_task_add(server->schedule, sock[0],
292 silc_server_connect_to_router,
293 (void *)server, 0, 1,
295 SILC_TASK_PRI_NORMAL);
297 /* Add listener task to the scheduler. This task receives new connections
298 to the server. This task remains on the queue until the end of the
300 silc_schedule_task_add(server->schedule, sock[0],
301 silc_server_accept_new_connection,
302 (void *)server, 0, 0,
304 SILC_TASK_PRI_NORMAL);
305 server->listenning = TRUE;
307 /* Send log file configuration */
308 silc_server_config_setlogfiles(server->config, server->schedule);
310 /* If server connections has been configured then we must be router as
311 normal server cannot have server connections, only router connections. */
312 if (server->config->servers) {
313 SilcServerConfigSectionServerConnection *ptr = server->config->servers;
315 server->server_type = SILC_ROUTER;
317 if (ptr->backup_router) {
318 server->server_type = SILC_BACKUP_ROUTER;
319 server->backup_router = TRUE;
320 server->id_entry->server_type = SILC_BACKUP_ROUTER;
327 /* Register the ID Cache purge task. This periodically purges the ID cache
328 and removes the expired cache entries. */
330 /* Clients local list */
331 purge = silc_calloc(1, sizeof(*purge));
332 purge->cache = server->local_list->clients;
333 purge->schedule = server->schedule;
334 purge->timeout = 600;
335 silc_schedule_task_add(purge->schedule, 0,
337 (void *)purge, purge->timeout, 0,
338 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
340 /* Clients global list */
341 purge = silc_calloc(1, sizeof(*purge));
342 purge->cache = server->global_list->clients;
343 purge->schedule = server->schedule;
344 purge->timeout = 300;
345 silc_schedule_task_add(purge->schedule, 0,
347 (void *)purge, purge->timeout, 0,
348 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
350 SILC_LOG_DEBUG(("Server initialized"));
352 /* We are done here, return succesfully */
356 for (i = 0; i < sock_count; i++)
357 silc_net_close_server(sock[i]);
362 /* Fork server to background */
364 void silc_server_daemonise(SilcServer server)
368 SILC_LOG_DEBUG(("Forking SILC server to background"));
373 SILC_LOG_DEBUG(("fork() failed, cannot proceed"));
378 SILC_LOG_DEBUG(("Server started as user"));
380 SILC_LOG_DEBUG(("Server started as root. Dropping privileges."));
386 /* Drop root privligies. If this cannot be done, die. */
388 void silc_server_drop(SilcServer server)
390 /* Are we executing silcd as root or a regular user? */
396 if (!server->config->identity || !server->config->identity->user ||
397 !server->config->identity->group) {
398 fprintf(stderr, "Error:"
399 "\tSILC server must not be run as root. For the security of your\n"
400 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
401 "\tuser account. Modify the [Identity] configuration section to run\n"
402 "\tthe server as non-root user.\n");
406 /* Get the values given for user and group in configuration file */
407 user=server->config->identity->user;
408 group=server->config->identity->group;
410 /* Check whether the user/group information is text */
411 if (atoi(user)!=0 || atoi(group)!=0) {
412 SILC_LOG_DEBUG(("Invalid user and/or group information"));
413 SILC_LOG_DEBUG(("User and/or group given as number"));
414 fprintf(stderr, "Invalid user and/or group information\n");
415 fprintf(stderr, "Please assign them as names, not numbers\n");
419 /* Catch the nasty incident of string "0" returning 0 from atoi */
420 if (strcmp("0", user)==0 || strcmp("0", group)==0) {
421 SILC_LOG_DEBUG(("User and/or group configured to 0. Unacceptable"));
422 fprintf(stderr, "User and/or group configured to 0. Exiting\n");
426 if (!(pw=getpwnam(user))) {
427 fprintf(stderr, "No such user %s found\n", user);
431 if (!(gr=getgrnam(group))) {
432 fprintf(stderr, "No such group %s found\n", group);
436 /* Check whether user and/or group is set to root. If yes, exit
437 immediately. Otherwise, setgid and setuid server to user.group */
438 if (gr->gr_gid==0 || pw->pw_uid==0) {
439 fprintf(stderr, "Error:"
440 "\tSILC server must not be run as root. For the security of your\n"
441 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
442 "\tuser account. Modify the [Identity] configuration section to run\n"
443 "\tthe server as non-root user.\n");
446 SILC_LOG_DEBUG(("Changing to group %s", group));
447 if (setgid(gr->gr_gid)==0) {
448 SILC_LOG_DEBUG(("Setgid to %s", group));
450 SILC_LOG_DEBUG(("Setgid to %s failed", group));
451 fprintf(stderr, "Tried to setgid %s but no such group. Exiting\n",
455 #if defined HAVE_SETGROUPS && defined HAVE_INITGROUPS
456 if (setgroups(0, NULL)!=0) {
457 SILC_LOG_DEBUG(("Setgroups to NULL failed"));
458 fprintf(stderr, "Tried to setgroups NULL but failed. Exiting\n");
461 if (initgroups(user, gr->gr_gid)!=0) {
462 SILC_LOG_DEBUG(("Initgroups to user %s (gid=%d) failed", user, gr->gr_gid));
463 fprintf(stderr, "Tried to initgroups %s (gid=%d) but no such user. Exiting\n",
468 SILC_LOG_DEBUG(("Changing to user %s", user));
469 if (setuid(pw->pw_uid)==0) {
470 SILC_LOG_DEBUG(("Setuid to %s", user));
472 SILC_LOG_DEBUG(("Setuid to %s failed", user));
473 fprintf(stderr, "Tried to setuid %s but no such user. Exiting\n",
481 /* The heart of the server. This runs the scheduler thus runs the server.
482 When this returns the server has been stopped and the program will
485 void silc_server_run(SilcServer server)
487 SILC_LOG_DEBUG(("Running server"));
489 SILC_LOG_INFO(("SILC Server started"));
491 /* Start the scheduler, the heart of the SILC server. When this returns
492 the program will be terminated. */
493 silc_schedule(server->schedule);
496 /* Stops the SILC server. This function is used to shutdown the server.
497 This is usually called after the scheduler has returned. After stopping
498 the server one should call silc_server_free. */
500 void silc_server_stop(SilcServer server)
502 SILC_LOG_DEBUG(("Stopping server"));
504 if (server->schedule) {
505 silc_schedule_stop(server->schedule);
506 silc_schedule_uninit(server->schedule);
507 server->schedule = NULL;
510 silc_server_protocols_unregister();
512 SILC_LOG_DEBUG(("Server stopped"));
515 /* Function that is called when the network connection to a router has
516 been established. This will continue with the key exchange protocol
517 with the remote router. */
519 void silc_server_start_key_exchange(SilcServer server,
520 SilcServerConnection sconn,
523 SilcSocketConnection newsocket;
524 SilcProtocol protocol;
525 SilcServerKEInternalContext *proto_ctx;
528 /* Cancel any possible retry timeouts */
529 silc_schedule_task_del_by_callback(server->schedule,
530 silc_server_connect_router);
532 /* Set socket options */
533 silc_net_set_socket_nonblock(sock);
534 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
536 /* Create socket connection for the connection. Even though we
537 know that we are connecting to a router we will mark the socket
538 to be unknown connection until we have executed authentication
540 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
541 server->sockets[sock] = newsocket;
542 newsocket->hostname = strdup(sconn->remote_host);
543 newsocket->ip = strdup(sconn->remote_host);
544 newsocket->port = sconn->remote_port;
545 sconn->sock = newsocket;
547 /* Allocate internal protocol context. This is sent as context
549 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
550 proto_ctx->server = (void *)server;
551 proto_ctx->context = (void *)sconn;
552 proto_ctx->sock = newsocket;
553 proto_ctx->rng = server->rng;
554 proto_ctx->responder = FALSE;
556 /* Perform key exchange protocol. silc_server_connect_to_router_second
557 will be called after the protocol is finished. */
558 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
559 &protocol, proto_ctx,
560 silc_server_connect_to_router_second);
561 newsocket->protocol = protocol;
563 /* Register a timeout task that will be executed if the protocol
564 is not executed within set limit. */
565 proto_ctx->timeout_task =
566 silc_schedule_task_add(server->schedule, sock,
567 silc_server_timeout_remote,
568 server, server->params->protocol_timeout,
569 server->params->protocol_timeout_usec,
573 /* Register the connection for network input and output. This sets
574 that scheduler will listen for incoming packets for this connection
575 and sets that outgoing packets may be sent to this connection as
576 well. However, this doesn't set the scheduler for outgoing traffic,
577 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
578 later when outgoing data is available. */
579 context = (void *)server;
580 SILC_REGISTER_CONNECTION_FOR_IO(sock);
582 /* Run the protocol */
583 silc_protocol_execute(protocol, server->schedule, 0, 0);
586 /* Timeout callback that will be called to retry connecting to remote
587 router. This is used by both normal and router server. This will wait
588 before retrying the connecting. The timeout is generated by exponential
589 backoff algorithm. */
591 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
593 SilcServerConnection sconn = (SilcServerConnection)context;
594 SilcServer server = sconn->server;
596 SILC_LOG_INFO(("Retrying connecting to a router"));
598 /* Calculate next timeout */
599 if (sconn->retry_count >= 1) {
600 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
601 if (sconn->retry_timeout > SILC_SERVER_RETRY_INTERVAL_MAX)
602 sconn->retry_timeout = SILC_SERVER_RETRY_INTERVAL_MAX;
604 sconn->retry_timeout = server->params->retry_interval_min;
606 sconn->retry_count++;
607 sconn->retry_timeout = sconn->retry_timeout +
608 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
610 /* If we've reached max retry count, give up. */
611 if (sconn->retry_count > server->params->retry_count &&
612 server->params->retry_keep_trying == FALSE) {
613 SILC_LOG_ERROR(("Could not connect to router, giving up"));
614 silc_free(sconn->remote_host);
619 /* Wait one before retrying */
620 silc_schedule_task_add(server->schedule, fd, silc_server_connect_router,
621 context, sconn->retry_timeout,
622 server->params->retry_interval_min_usec,
623 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
626 /* Generic routine to use connect to a router. */
628 SILC_TASK_CALLBACK(silc_server_connect_router)
630 SilcServerConnection sconn = (SilcServerConnection)context;
631 SilcServer server = sconn->server;
634 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
635 (sconn->backup ? "backup router" : "router"),
636 sconn->remote_host, sconn->remote_port));
638 server->router_connect = time(0);
640 /* Connect to remote host */
641 sock = silc_net_create_connection(server->config->listen_port->local_ip,
645 SILC_LOG_ERROR(("Could not connect to router %s:%d",
646 sconn->remote_host, sconn->remote_port));
647 if (!sconn->no_reconnect)
648 silc_schedule_task_add(server->schedule, fd,
649 silc_server_connect_to_router_retry,
650 context, 0, 1, SILC_TASK_TIMEOUT,
651 SILC_TASK_PRI_NORMAL);
655 /* Continue with key exchange protocol */
656 silc_server_start_key_exchange(server, sconn, sock);
659 /* This function connects to our primary router or if we are a router this
660 establishes all our primary routes. This is called at the start of the
661 server to do authentication and key exchange with our router - called
664 SILC_TASK_CALLBACK(silc_server_connect_to_router)
666 SilcServer server = (SilcServer)context;
667 SilcServerConnection sconn;
668 SilcServerConfigSectionServerConnection *ptr;
670 SILC_LOG_DEBUG(("Connecting to router(s)"));
672 if (server->server_type == SILC_SERVER) {
673 SILC_LOG_DEBUG(("We are normal server"));
674 } else if (server->server_type == SILC_ROUTER) {
675 SILC_LOG_DEBUG(("We are router"));
677 SILC_LOG_DEBUG(("We are backup router/normal server"));
680 /* Create the connections to all our routes */
681 ptr = server->config->routers;
684 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
685 ptr->backup_router ? "Backup router" : "Router",
686 ptr->initiator ? "Initiator" : "Responder",
687 ptr->host, ptr->port));
689 if (ptr->initiator) {
690 /* Allocate connection object for hold connection specific stuff. */
691 sconn = silc_calloc(1, sizeof(*sconn));
692 sconn->server = server;
693 sconn->remote_host = strdup(ptr->host);
694 sconn->remote_port = ptr->port;
695 sconn->backup = ptr->backup_router;
697 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
698 sconn->backup_replace_port = ptr->backup_replace_port;
701 if (!server->router_conn && !sconn->backup)
702 server->router_conn = sconn;
704 silc_schedule_task_add(server->schedule, fd,
705 silc_server_connect_router,
706 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
707 SILC_TASK_PRI_NORMAL);
716 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
718 /* There wasn't a configured router, we will continue but we don't
719 have a connection to outside world. We will be standalone server. */
720 server->standalone = TRUE;
723 /* Second part of connecting to router(s). Key exchange protocol has been
724 executed and now we will execute authentication protocol. */
726 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
728 SilcProtocol protocol = (SilcProtocol)context;
729 SilcServerKEInternalContext *ctx =
730 (SilcServerKEInternalContext *)protocol->context;
731 SilcServer server = (SilcServer)ctx->server;
732 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
733 SilcSocketConnection sock = ctx->sock;
734 SilcServerConnAuthInternalContext *proto_ctx;
735 SilcServerConfigSectionServerConnection *conn = NULL;
737 SILC_LOG_DEBUG(("Start"));
739 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
740 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
741 /* Error occured during protocol */
742 silc_protocol_free(protocol);
743 sock->protocol = NULL;
744 silc_ske_free_key_material(ctx->keymat);
746 silc_packet_context_free(ctx->packet);
748 silc_ske_free(ctx->ske);
749 silc_free(ctx->dest_id);
751 silc_schedule_task_del_by_callback(server->schedule,
752 silc_server_failure_callback);
753 silc_server_disconnect_remote(server, sock, "Server closed connection: "
754 "Key exchange failed");
758 /* We now have the key material as the result of the key exchange
759 protocol. Take the key material into use. Free the raw key material
760 as soon as we've set them into use. */
761 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
762 ctx->sock, ctx->keymat,
763 ctx->ske->prop->cipher,
764 ctx->ske->prop->pkcs,
765 ctx->ske->prop->hash,
766 ctx->ske->prop->hmac,
767 ctx->ske->prop->group,
769 silc_protocol_free(protocol);
770 sock->protocol = NULL;
771 silc_ske_free_key_material(ctx->keymat);
773 silc_packet_context_free(ctx->packet);
775 silc_ske_free(ctx->ske);
776 silc_free(ctx->dest_id);
778 silc_schedule_task_del_by_callback(server->schedule,
779 silc_server_failure_callback);
780 silc_server_disconnect_remote(server, sock, "Server closed connection: "
781 "Key exchange failed");
784 silc_ske_free_key_material(ctx->keymat);
786 /* Allocate internal context for the authentication protocol. This
787 is sent as context for the protocol. */
788 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
789 proto_ctx->server = (void *)server;
790 proto_ctx->context = (void *)sconn;
791 proto_ctx->sock = sock;
792 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
793 proto_ctx->dest_id_type = ctx->dest_id_type;
794 proto_ctx->dest_id = ctx->dest_id;
796 /* Resolve the authentication method used in this connection. Check if
797 we find a match from user configured connections */
798 conn = silc_server_config_find_router_conn(server->config,
802 /* Match found. Use the configured authentication method */
803 proto_ctx->auth_meth = conn->auth_meth;
804 if (conn->auth_data) {
805 proto_ctx->auth_data = strdup(conn->auth_data);
806 proto_ctx->auth_data_len = strlen(conn->auth_data);
809 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
810 sock->hostname, sock->ip, sock->port));
811 silc_protocol_free(protocol);
812 sock->protocol = NULL;
814 silc_packet_context_free(ctx->packet);
816 silc_ske_free(ctx->ske);
817 silc_free(ctx->dest_id);
819 silc_schedule_task_del_by_callback(server->schedule,
820 silc_server_failure_callback);
821 silc_server_disconnect_remote(server, sock, "Server closed connection: "
822 "Key exchange failed");
826 /* Free old protocol as it is finished now */
827 silc_protocol_free(protocol);
829 silc_packet_context_free(ctx->packet);
831 sock->protocol = NULL;
833 /* Allocate the authentication protocol. This is allocated here
834 but we won't start it yet. We will be receiving party of this
835 protocol thus we will wait that connecting party will make
837 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
838 &sock->protocol, proto_ctx,
839 silc_server_connect_to_router_final);
841 /* Register timeout task. If the protocol is not executed inside
842 this timelimit the connection will be terminated. Currently
843 this is 15 seconds and is hard coded limit (XXX). */
844 proto_ctx->timeout_task =
845 silc_schedule_task_add(server->schedule, sock->sock,
846 silc_server_timeout_remote,
847 (void *)server, 15, 0,
851 /* Run the protocol */
852 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
855 /* Finalizes the connection to router. Registers a server task to the
856 queue so that we can accept new connections. */
858 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
860 SilcProtocol protocol = (SilcProtocol)context;
861 SilcServerConnAuthInternalContext *ctx =
862 (SilcServerConnAuthInternalContext *)protocol->context;
863 SilcServer server = (SilcServer)ctx->server;
864 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
865 SilcSocketConnection sock = ctx->sock;
866 SilcServerEntry id_entry;
868 SilcServerHBContext hb_context;
869 unsigned char *id_string;
871 SilcIDListData idata;
873 SILC_LOG_DEBUG(("Start"));
875 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
876 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
877 /* Error occured during protocol */
878 silc_free(ctx->dest_id);
879 silc_server_disconnect_remote(server, sock, "Server closed connection: "
880 "Authentication failed");
884 /* Add a task to the queue. This task receives new connections to the
885 server. This task remains on the queue until the end of the program. */
886 if (!server->listenning && !sconn->backup) {
887 silc_schedule_task_add(server->schedule, server->sock,
888 silc_server_accept_new_connection,
889 (void *)server, 0, 0,
891 SILC_TASK_PRI_NORMAL);
892 server->listenning = TRUE;
895 /* Send NEW_SERVER packet to the router. We will become registered
896 to the SILC network after sending this packet. */
897 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
898 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
899 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
900 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
901 silc_buffer_format(packet,
902 SILC_STR_UI_SHORT(id_len),
903 SILC_STR_UI_XNSTRING(id_string, id_len),
904 SILC_STR_UI_SHORT(strlen(server->server_name)),
905 SILC_STR_UI_XNSTRING(server->server_name,
906 strlen(server->server_name)),
909 /* Send the packet */
910 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
911 packet->data, packet->len, TRUE);
912 silc_buffer_free(packet);
913 silc_free(id_string);
915 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
917 /* Check that we do not have this ID already */
918 id_entry = silc_idlist_find_server_by_id(server->local_list,
919 ctx->dest_id, TRUE, NULL);
921 silc_idcache_del_by_context(server->local_list->servers, id_entry);
923 id_entry = silc_idlist_find_server_by_id(server->global_list,
924 ctx->dest_id, TRUE, NULL);
926 silc_idcache_del_by_context(server->global_list->servers, id_entry);
929 SILC_LOG_DEBUG(("New server id(%s)",
930 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
932 /* Add the connected router to global server list */
933 id_entry = silc_idlist_add_server(server->global_list,
934 strdup(sock->hostname),
935 SILC_ROUTER, ctx->dest_id, NULL, sock);
937 silc_free(ctx->dest_id);
938 silc_server_disconnect_remote(server, sock, "Server closed connection: "
939 "Authentication failed");
943 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
944 silc_free(sock->user_data);
945 sock->user_data = (void *)id_entry;
946 sock->type = SILC_SOCKET_TYPE_ROUTER;
947 idata = (SilcIDListData)sock->user_data;
948 idata->status |= SILC_IDLIST_STATUS_REGISTERED;
950 /* Perform keepalive. The `hb_context' will be freed automatically
951 when finally calling the silc_socket_free function. XXX hardcoded
953 hb_context = silc_calloc(1, sizeof(*hb_context));
954 hb_context->server = server;
955 silc_socket_set_heartbeat(sock, 300, hb_context,
956 silc_server_perform_heartbeat,
959 /* Register re-key timeout */
960 idata->rekey->timeout = 3600; /* XXX hardcoded */
961 idata->rekey->context = (void *)server;
962 silc_schedule_task_add(server->schedule, sock->sock,
963 silc_server_rekey_callback,
964 (void *)sock, idata->rekey->timeout, 0,
965 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
967 if (!sconn->backup) {
968 /* Mark this router our primary router if we're still standalone */
969 if (server->standalone) {
970 server->id_entry->router = id_entry;
971 server->router = id_entry;
972 server->standalone = FALSE;
974 /* If we are router then announce our possible servers. */
975 if (server->server_type == SILC_ROUTER)
976 silc_server_announce_servers(server, FALSE, 0,
977 server->router->connection);
979 /* Announce our clients and channels to the router */
980 silc_server_announce_clients(server, 0, server->router->connection);
981 silc_server_announce_channels(server, 0, server->router->connection);
984 /* Add this server to be our backup router */
985 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
986 sconn->backup_replace_port, FALSE);
989 sock->protocol = NULL;
991 /* Call the completion callback to indicate that we've connected to
994 (*sconn->callback)(server, id_entry, sconn->callback_context);
997 /* Free the temporary connection data context */
999 silc_free(sconn->remote_host);
1000 silc_free(sconn->backup_replace_ip);
1003 if (sconn == server->router_conn)
1004 server->router_conn = NULL;
1006 /* Free the protocol object */
1007 if (sock->protocol == protocol)
1008 sock->protocol = NULL;
1009 silc_protocol_free(protocol);
1011 silc_packet_context_free(ctx->packet);
1013 silc_ske_free(ctx->ske);
1014 silc_free(ctx->auth_data);
1018 /* Host lookup callbcak that is called after the incoming connection's
1019 IP and FQDN lookup is performed. This will actually check the acceptance
1020 of the incoming connection and will register the key exchange protocol
1021 for this connection. */
1024 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1027 SilcServer server = (SilcServer)context;
1028 SilcServerKEInternalContext *proto_ctx;
1029 void *cconfig, *sconfig, *rconfig;
1030 SilcServerConfigSectionDenyConnection *deny;
1033 SILC_LOG_DEBUG(("Start"));
1035 /* Check whether we could resolve both IP and FQDN. */
1036 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1037 server->params->require_reverse_mapping)) {
1038 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1039 sock->hostname ? sock->hostname :
1040 sock->ip ? sock->ip : ""));
1041 server->stat.conn_failures++;
1042 silc_server_disconnect_remote(server, sock,
1043 "Server closed connection: Unknown host");
1047 /* Register the connection for network input and output. This sets
1048 that scheduler will listen for incoming packets for this connection
1049 and sets that outgoing packets may be sent to this connection as well.
1050 However, this doesn't set the scheduler for outgoing traffic, it
1051 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1052 later when outgoing data is available. */
1053 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1055 SILC_LOG_INFO(("Incoming connection from %s (%s)", sock->hostname,
1058 port = server->sockets[server->sock]->port; /* Listenning port */
1060 /* Check whether this connection is denied to connect to us. */
1061 deny = silc_server_config_denied_conn(server->config, sock->ip, port);
1063 deny = silc_server_config_denied_conn(server->config, sock->hostname,
1066 /* The connection is denied */
1067 SILC_LOG_INFO(("Connection %s (%s) is denied",
1068 sock->hostname, sock->ip));
1069 silc_server_disconnect_remote(server, sock, deny->comment ?
1071 "Server closed connection: "
1072 "Connection refused");
1073 server->stat.conn_failures++;
1077 /* Check whether we have configred this sort of connection at all. We
1078 have to check all configurations since we don't know what type of
1079 connection this is. */
1080 if (!(cconfig = silc_server_config_find_client_conn(server->config,
1082 cconfig = silc_server_config_find_client_conn(server->config,
1085 if (!(sconfig = silc_server_config_find_server_conn(server->config,
1088 sconfig = silc_server_config_find_server_conn(server->config,
1091 if (!(rconfig = silc_server_config_find_router_conn(server->config,
1093 rconfig = silc_server_config_find_router_conn(server->config,
1096 if (!cconfig && !sconfig && !rconfig) {
1097 SILC_LOG_INFO(("Connection %s (%s) is not allowed",
1098 sock->hostname, sock->ip));
1099 silc_server_disconnect_remote(server, sock,
1100 "Server closed connection: "
1101 "Connection refused");
1102 server->stat.conn_failures++;
1106 /* The connection is allowed */
1108 /* Allocate internal context for key exchange protocol. This is
1109 sent as context for the protocol. */
1110 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1111 proto_ctx->server = context;
1112 proto_ctx->sock = sock;
1113 proto_ctx->rng = server->rng;
1114 proto_ctx->responder = TRUE;
1115 proto_ctx->cconfig = cconfig;
1116 proto_ctx->sconfig = sconfig;
1117 proto_ctx->rconfig = rconfig;
1119 /* Prepare the connection for key exchange protocol. We allocate the
1120 protocol but will not start it yet. The connector will be the
1121 initiator of the protocol thus we will wait for initiation from
1122 there before we start the protocol. */
1123 server->stat.auth_attempts++;
1124 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1125 &sock->protocol, proto_ctx,
1126 silc_server_accept_new_connection_second);
1128 /* Register a timeout task that will be executed if the connector
1129 will not start the key exchange protocol within 60 seconds. For
1130 now, this is a hard coded limit. After 60 secs the connection will
1131 be closed if the key exchange protocol has not been started. */
1132 proto_ctx->timeout_task =
1133 silc_schedule_task_add(server->schedule, sock->sock,
1134 silc_server_timeout_remote,
1140 /* Accepts new connections to the server. Accepting new connections are
1141 done in three parts to make it async. */
1143 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1145 SilcServer server = (SilcServer)context;
1146 SilcSocketConnection newsocket;
1149 SILC_LOG_DEBUG(("Accepting new connection"));
1151 server->stat.conn_attempts++;
1153 sock = silc_net_accept_connection(server->sock);
1155 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1156 server->stat.conn_failures++;
1160 /* Check max connections */
1161 if (sock > SILC_SERVER_MAX_CONNECTIONS) {
1162 SILC_LOG_ERROR(("Refusing connection, server is full"));
1163 server->stat.conn_failures++;
1167 /* Set socket options */
1168 silc_net_set_socket_nonblock(sock);
1169 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1171 /* We don't create a ID yet, since we don't know what type of connection
1172 this is yet. But, we do add the connection to the socket table. */
1173 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1174 server->sockets[sock] = newsocket;
1176 /* Perform asynchronous host lookup. This will lookup the IP and the
1177 FQDN of the remote connection. After the lookup is done the connection
1178 is accepted further. */
1179 silc_socket_host_lookup(newsocket, TRUE,
1180 silc_server_accept_new_connection_lookup, context,
1184 /* Second part of accepting new connection. Key exchange protocol has been
1185 performed and now it is time to do little connection authentication
1186 protocol to figure out whether this connection is client or server
1187 and whether it has right to access this server (especially server
1188 connections needs to be authenticated). */
1190 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1192 SilcProtocol protocol = (SilcProtocol)context;
1193 SilcServerKEInternalContext *ctx =
1194 (SilcServerKEInternalContext *)protocol->context;
1195 SilcServer server = (SilcServer)ctx->server;
1196 SilcSocketConnection sock = ctx->sock;
1197 SilcServerConnAuthInternalContext *proto_ctx;
1199 SILC_LOG_DEBUG(("Start"));
1201 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1202 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1203 /* Error occured during protocol */
1204 silc_protocol_free(protocol);
1205 sock->protocol = NULL;
1206 silc_ske_free_key_material(ctx->keymat);
1208 silc_packet_context_free(ctx->packet);
1210 silc_ske_free(ctx->ske);
1211 silc_free(ctx->dest_id);
1213 silc_schedule_task_del_by_callback(server->schedule,
1214 silc_server_failure_callback);
1215 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1216 "Key exchange failed");
1217 server->stat.auth_failures++;
1221 /* We now have the key material as the result of the key exchange
1222 protocol. Take the key material into use. Free the raw key material
1223 as soon as we've set them into use. */
1224 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1225 ctx->sock, ctx->keymat,
1226 ctx->ske->prop->cipher,
1227 ctx->ske->prop->pkcs,
1228 ctx->ske->prop->hash,
1229 ctx->ske->prop->hmac,
1230 ctx->ske->prop->group,
1232 silc_protocol_free(protocol);
1233 sock->protocol = NULL;
1234 silc_ske_free_key_material(ctx->keymat);
1236 silc_packet_context_free(ctx->packet);
1238 silc_ske_free(ctx->ske);
1239 silc_free(ctx->dest_id);
1241 silc_schedule_task_del_by_callback(server->schedule,
1242 silc_server_failure_callback);
1243 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1244 "Key exchange failed");
1245 server->stat.auth_failures++;
1248 silc_ske_free_key_material(ctx->keymat);
1250 /* Allocate internal context for the authentication protocol. This
1251 is sent as context for the protocol. */
1252 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1253 proto_ctx->server = (void *)server;
1254 proto_ctx->sock = sock;
1255 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1256 proto_ctx->responder = TRUE;
1257 proto_ctx->dest_id_type = ctx->dest_id_type;
1258 proto_ctx->dest_id = ctx->dest_id;
1259 proto_ctx->cconfig = ctx->cconfig;
1260 proto_ctx->sconfig = ctx->sconfig;
1261 proto_ctx->rconfig = ctx->rconfig;
1263 /* Free old protocol as it is finished now */
1264 silc_protocol_free(protocol);
1266 silc_packet_context_free(ctx->packet);
1268 sock->protocol = NULL;
1270 /* Allocate the authentication protocol. This is allocated here
1271 but we won't start it yet. We will be receiving party of this
1272 protocol thus we will wait that connecting party will make
1273 their first move. */
1274 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1275 &sock->protocol, proto_ctx,
1276 silc_server_accept_new_connection_final);
1278 /* Register timeout task. If the protocol is not executed inside
1279 this timelimit the connection will be terminated. Currently
1280 this is 60 seconds and is hard coded limit (XXX). */
1281 proto_ctx->timeout_task =
1282 silc_schedule_task_add(server->schedule, sock->sock,
1283 silc_server_timeout_remote,
1284 (void *)server, 60, 0,
1289 /* Final part of accepting new connection. The connection has now
1290 been authenticated and keys has been exchanged. We also know whether
1291 this is client or server connection. */
1293 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1295 SilcProtocol protocol = (SilcProtocol)context;
1296 SilcServerConnAuthInternalContext *ctx =
1297 (SilcServerConnAuthInternalContext *)protocol->context;
1298 SilcServer server = (SilcServer)ctx->server;
1299 SilcSocketConnection sock = ctx->sock;
1300 SilcServerHBContext hb_context;
1301 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1304 SILC_LOG_DEBUG(("Start"));
1306 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1307 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1308 /* Error occured during protocol */
1309 silc_protocol_free(protocol);
1310 sock->protocol = NULL;
1312 silc_packet_context_free(ctx->packet);
1314 silc_ske_free(ctx->ske);
1315 silc_free(ctx->dest_id);
1317 silc_schedule_task_del_by_callback(server->schedule,
1318 silc_server_failure_callback);
1319 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1320 "Authentication failed");
1321 server->stat.auth_failures++;
1325 entry->data.last_receive = time(NULL);
1327 switch (ctx->conn_type) {
1328 case SILC_SOCKET_TYPE_CLIENT:
1330 SilcClientEntry client;
1332 SILC_LOG_DEBUG(("Remote host is client"));
1333 SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
1336 /* Add the client to the client ID cache. The nickname and Client ID
1337 and other information is created after we have received NEW_CLIENT
1338 packet from client. */
1339 client = silc_idlist_add_client(server->local_list,
1340 NULL, NULL, NULL, NULL, NULL, sock, 0);
1342 SILC_LOG_ERROR(("Could not add new client to cache"));
1343 silc_free(sock->user_data);
1344 silc_server_disconnect_remote(server, sock,
1345 "Server closed connection: "
1346 "Authentication failed");
1347 server->stat.auth_failures++;
1352 server->stat.my_clients++;
1353 server->stat.clients++;
1354 if (server->server_type == SILC_ROUTER)
1355 server->stat.cell_clients++;
1357 id_entry = (void *)client;
1360 case SILC_SOCKET_TYPE_SERVER:
1361 case SILC_SOCKET_TYPE_ROUTER:
1363 SilcServerEntry new_server;
1364 SilcServerConfigSectionServerConnection *conn =
1365 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1366 ctx->sconfig : ctx->rconfig;
1368 SILC_LOG_DEBUG(("Remote host is %s",
1369 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1370 "server" : (conn->backup_router ?
1371 "backup router" : "router")));
1372 SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
1373 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1374 "server" : (conn->backup_router ?
1375 "backup router" : "router")));
1377 /* Add the server into server cache. The server name and Server ID
1378 is updated after we have received NEW_SERVER packet from the
1379 server. We mark ourselves as router for this server if we really
1382 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1383 server->local_list : (conn->backup_router ?
1384 server->local_list :
1385 server->global_list)),
1387 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1388 SILC_SERVER : SILC_ROUTER),
1390 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1391 server->id_entry : (conn->backup_router ?
1392 server->id_entry : NULL)),
1395 SILC_LOG_ERROR(("Could not add new server to cache"));
1396 silc_free(sock->user_data);
1397 silc_server_disconnect_remote(server, sock,
1398 "Server closed connection: "
1399 "Authentication failed");
1400 server->stat.auth_failures++;
1405 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1406 server->stat.my_servers++;
1408 server->stat.my_routers++;
1409 server->stat.servers++;
1411 id_entry = (void *)new_server;
1413 /* If the incoming connection is router and marked as backup router
1414 then add it to be one of our backups */
1415 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && conn->backup_router) {
1416 silc_server_backup_add(server, new_server, conn->backup_replace_ip,
1417 conn->backup_replace_port, conn->backup_local);
1419 /* Change it back to SERVER type since that's what it really is. */
1420 if (conn->backup_local)
1421 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1423 new_server->server_type = SILC_BACKUP_ROUTER;
1426 /* Check whether this connection is to be our primary router connection
1427 if we do not already have the primary route. */
1428 if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1429 if (silc_server_config_is_primary_route(server->config) &&
1433 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1434 server->standalone = FALSE;
1435 if (!server->id_entry->router) {
1436 server->id_entry->router = id_entry;
1437 server->router = id_entry;
1448 sock->type = ctx->conn_type;
1450 /* Add the common data structure to the ID entry. */
1451 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1453 /* Add to sockets internal pointer for fast referencing */
1454 silc_free(sock->user_data);
1455 sock->user_data = id_entry;
1457 /* Connection has been fully established now. Everything is ok. */
1458 SILC_LOG_DEBUG(("New connection authenticated"));
1460 /* Perform keepalive. The `hb_context' will be freed automatically
1461 when finally calling the silc_socket_free function. XXX hardcoded
1463 hb_context = silc_calloc(1, sizeof(*hb_context));
1464 hb_context->server = server;
1465 silc_socket_set_heartbeat(sock, 400, hb_context,
1466 silc_server_perform_heartbeat,
1470 silc_schedule_task_del_by_callback(server->schedule,
1471 silc_server_failure_callback);
1472 silc_protocol_free(protocol);
1474 silc_packet_context_free(ctx->packet);
1476 silc_ske_free(ctx->ske);
1477 silc_free(ctx->dest_id);
1479 sock->protocol = NULL;
1482 /* This function is used to read packets from network and send packets to
1483 network. This is usually a generic task. */
1485 SILC_TASK_CALLBACK(silc_server_packet_process)
1487 SilcServer server = (SilcServer)context;
1488 SilcSocketConnection sock = server->sockets[fd];
1489 SilcIDListData idata;
1490 SilcCipher cipher = NULL;
1491 SilcHmac hmac = NULL;
1492 uint32 sequence = 0;
1498 SILC_LOG_DEBUG(("Processing packet"));
1500 /* Packet sending */
1502 if (type == SILC_TASK_WRITE) {
1503 /* Do not send data to disconnected connection */
1504 if (SILC_IS_DISCONNECTED(sock))
1507 server->stat.packets_sent++;
1509 if (sock->outbuf->data - sock->outbuf->head)
1510 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1512 /* Send the packet */
1513 ret = silc_packet_send(sock, TRUE);
1515 /* If returned -2 could not write to connection now, will do
1521 SILC_LOG_ERROR(("Error sending packet to connection "
1522 "%s:%d [%s]", sock->hostname, sock->port,
1523 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1524 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1525 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1530 /* The packet has been sent and now it is time to set the connection
1531 back to only for input. When there is again some outgoing data
1532 available for this connection it will be set for output as well.
1533 This call clears the output setting and sets it only for input. */
1534 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1535 SILC_UNSET_OUTBUF_PENDING(sock);
1537 silc_buffer_clear(sock->outbuf);
1541 /* Packet receiving */
1543 /* Read some data from connection */
1544 ret = silc_packet_receive(sock);
1548 SILC_LOG_ERROR(("Error receiving packet from connection "
1549 "%s:%d [%s] %s", sock->hostname, sock->port,
1550 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1551 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1552 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1553 "Router"), strerror(errno)));
1559 SILC_LOG_DEBUG(("Read EOF"));
1561 /* If connection is disconnecting already we will finally
1562 close the connection */
1563 if (SILC_IS_DISCONNECTING(sock)) {
1564 if (sock->user_data)
1565 silc_server_free_sock_user_data(server, sock, NULL);
1566 silc_server_close_connection(server, sock);
1570 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1571 SILC_SET_DISCONNECTING(sock);
1573 if (sock->user_data) {
1575 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
1576 silc_server_free_sock_user_data(server, sock, tmp);
1578 silc_server_free_sock_user_data(server, sock, NULL);
1579 } else if (server->router_conn && server->router_conn->sock == sock &&
1580 !server->router && server->standalone)
1581 silc_schedule_task_add(server->schedule, 0,
1582 silc_server_connect_to_router,
1585 SILC_TASK_PRI_NORMAL);
1587 silc_server_close_connection(server, sock);
1591 /* If connection is disconnecting or disconnected we will ignore
1593 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1594 SILC_LOG_DEBUG(("Ignoring read data from disonnected connection"));
1598 server->stat.packets_received++;
1600 /* Get keys and stuff from ID entry */
1601 idata = (SilcIDListData)sock->user_data;
1603 cipher = idata->receive_key;
1604 hmac = idata->hmac_receive;
1605 sequence = idata->psn_receive;
1608 /* Process the packet. This will call the parser that will then
1609 decrypt and parse the packet. */
1610 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1611 TRUE : FALSE, cipher, hmac, sequence,
1612 silc_server_packet_parse, server);
1614 /* If this socket connection is not authenticated yet and the packet
1615 processing failed we will drop the connection since it can be
1616 a malicious flooder. */
1617 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
1618 (!sock->protocol || sock->protocol->protocol->type ==
1619 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
1620 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
1621 SILC_SET_DISCONNECTING(sock);
1623 if (sock->user_data)
1624 silc_server_free_sock_user_data(server, sock, NULL);
1625 silc_server_close_connection(server, sock);
1629 /* Parses whole packet, received earlier. */
1631 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1633 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1634 SilcServer server = (SilcServer)parse_ctx->context;
1635 SilcSocketConnection sock = parse_ctx->sock;
1636 SilcPacketContext *packet = parse_ctx->packet;
1637 SilcIDListData idata = (SilcIDListData)sock->user_data;
1640 SILC_LOG_DEBUG(("Start"));
1642 /* Parse the packet */
1643 if (parse_ctx->normal)
1644 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
1646 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
1648 /* If entry is disabled ignore what we got. */
1649 if (ret != SILC_PACKET_RESUME_ROUTER &&
1650 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1651 SILC_LOG_DEBUG(("Connection is disabled"));
1655 if (ret == SILC_PACKET_NONE)
1658 /* Check that the the current client ID is same as in the client's packet. */
1659 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1660 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1661 if (client && client->id) {
1662 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1663 packet->src_id_type);
1664 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1672 if (server->server_type == SILC_ROUTER) {
1673 /* Route the packet if it is not destined to us. Other ID types but
1674 server are handled separately after processing them. */
1675 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1676 packet->dst_id_type == SILC_ID_SERVER &&
1677 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1678 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1680 /* Route the packet to fastest route for the destination ID */
1681 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1682 packet->dst_id_type);
1685 silc_server_packet_route(server,
1686 silc_server_route_get(server, id,
1687 packet->dst_id_type),
1694 /* Parse the incoming packet type */
1695 silc_server_packet_parse_type(server, sock, packet);
1697 if (server->server_type == SILC_ROUTER) {
1698 /* Broadcast packet if it is marked as broadcast packet and it is
1699 originated from router and we are router. */
1700 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1701 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1702 !server->standalone) {
1703 /* Broadcast to our primary route */
1704 silc_server_packet_broadcast(server, server->router->connection, packet);
1706 /* If we have backup routers then we need to feed all broadcast
1707 data to those servers. */
1708 silc_server_backup_broadcast(server, sock, packet);
1713 silc_packet_context_free(packet);
1714 silc_free(parse_ctx);
1717 /* Parser callback called by silc_packet_receive_process. This merely
1718 registers timeout that will handle the actual parsing when appropriate. */
1720 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
1723 SilcServer server = (SilcServer)context;
1724 SilcSocketConnection sock = parser_context->sock;
1725 SilcIDListData idata = (SilcIDListData)sock->user_data;
1728 idata->psn_receive = parser_context->packet->sequence + 1;
1730 /* If protocol for this connection is key exchange or rekey then we'll
1731 process all packets synchronously, since there might be packets in
1732 queue that we are not able to decrypt without first processing the
1733 packets before them. */
1734 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
1735 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
1736 (sock->protocol && sock->protocol->protocol &&
1737 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1738 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
1739 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1742 /* Reprocess data since we'll return FALSE here. This is because
1743 the idata->receive_key might have become valid in the last packet
1744 and we want to call this processor with valid cipher. */
1746 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1747 TRUE : FALSE, idata->receive_key,
1748 idata->hmac_receive, idata->psn_receive,
1749 silc_server_packet_parse, server);
1751 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1752 TRUE : FALSE, NULL, NULL, 0,
1753 silc_server_packet_parse, server);
1757 switch (sock->type) {
1758 case SILC_SOCKET_TYPE_UNKNOWN:
1759 case SILC_SOCKET_TYPE_CLIENT:
1760 /* Parse the packet with timeout */
1761 silc_schedule_task_add(server->schedule, sock->sock,
1762 silc_server_packet_parse_real,
1763 (void *)parser_context, 0, 100000,
1765 SILC_TASK_PRI_NORMAL);
1767 case SILC_SOCKET_TYPE_SERVER:
1768 case SILC_SOCKET_TYPE_ROUTER:
1769 /* Packets from servers are parsed immediately */
1770 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1780 /* Parses the packet type and calls what ever routines the packet type
1781 requires. This is done for all incoming packets. */
1783 void silc_server_packet_parse_type(SilcServer server,
1784 SilcSocketConnection sock,
1785 SilcPacketContext *packet)
1787 SilcPacketType type = packet->type;
1788 SilcIDListData idata = (SilcIDListData)sock->user_data;
1790 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1792 /* Parse the packet type */
1794 case SILC_PACKET_DISCONNECT:
1795 SILC_LOG_DEBUG(("Disconnect packet"));
1796 if (packet->flags & SILC_PACKET_FLAG_LIST)
1800 case SILC_PACKET_SUCCESS:
1802 * Success received for something. For now we can have only
1803 * one protocol for connection executing at once hence this
1804 * success message is for whatever protocol is executing currently.
1806 SILC_LOG_DEBUG(("Success packet"));
1807 if (packet->flags & SILC_PACKET_FLAG_LIST)
1810 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1813 case SILC_PACKET_FAILURE:
1815 * Failure received for something. For now we can have only
1816 * one protocol for connection executing at once hence this
1817 * failure message is for whatever protocol is executing currently.
1819 SILC_LOG_DEBUG(("Failure packet"));
1820 if (packet->flags & SILC_PACKET_FLAG_LIST)
1822 if (sock->protocol) {
1823 SilcServerFailureContext f;
1824 f = silc_calloc(1, sizeof(*f));
1828 /* We will wait 5 seconds to process this failure packet */
1829 silc_schedule_task_add(server->schedule, sock->sock,
1830 silc_server_failure_callback, (void *)f, 5, 0,
1831 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1835 case SILC_PACKET_REJECT:
1836 SILC_LOG_DEBUG(("Reject packet"));
1837 if (packet->flags & SILC_PACKET_FLAG_LIST)
1842 case SILC_PACKET_NOTIFY:
1844 * Received notify packet. Server can receive notify packets from
1845 * router. Server then relays the notify messages to clients if needed.
1847 SILC_LOG_DEBUG(("Notify packet"));
1848 if (packet->flags & SILC_PACKET_FLAG_LIST)
1849 silc_server_notify_list(server, sock, packet);
1851 silc_server_notify(server, sock, packet);
1857 case SILC_PACKET_CHANNEL_MESSAGE:
1859 * Received channel message. Channel messages are special packets
1860 * (although probably most common ones) thus they are handled
1863 SILC_LOG_DEBUG(("Channel Message packet"));
1864 if (packet->flags & SILC_PACKET_FLAG_LIST)
1866 idata->last_receive = time(NULL);
1867 silc_server_channel_message(server, sock, packet);
1870 case SILC_PACKET_CHANNEL_KEY:
1872 * Received key for channel. As channels are created by the router
1873 * the keys are as well. We will distribute the key to all of our
1874 * locally connected clients on the particular channel. Router
1875 * never receives this channel and thus is ignored.
1877 SILC_LOG_DEBUG(("Channel Key packet"));
1878 if (packet->flags & SILC_PACKET_FLAG_LIST)
1880 silc_server_channel_key(server, sock, packet);
1886 case SILC_PACKET_COMMAND:
1888 * Recived command. Processes the command request and allocates the
1889 * command context and calls the command.
1891 SILC_LOG_DEBUG(("Command packet"));
1892 if (packet->flags & SILC_PACKET_FLAG_LIST)
1894 silc_server_command_process(server, sock, packet);
1897 case SILC_PACKET_COMMAND_REPLY:
1899 * Received command reply packet. Received command reply to command. It
1900 * may be reply to command sent by us or reply to command sent by client
1901 * that we've routed further.
1903 SILC_LOG_DEBUG(("Command Reply packet"));
1904 if (packet->flags & SILC_PACKET_FLAG_LIST)
1906 silc_server_command_reply(server, sock, packet);
1910 * Private Message packets
1912 case SILC_PACKET_PRIVATE_MESSAGE:
1914 * Received private message packet. The packet is coming from either
1917 SILC_LOG_DEBUG(("Private Message packet"));
1918 if (packet->flags & SILC_PACKET_FLAG_LIST)
1920 idata->last_receive = time(NULL);
1921 silc_server_private_message(server, sock, packet);
1924 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1926 * Private message key packet.
1928 if (packet->flags & SILC_PACKET_FLAG_LIST)
1930 silc_server_private_message_key(server, sock, packet);
1934 * Key Exchange protocol packets
1936 case SILC_PACKET_KEY_EXCHANGE:
1937 SILC_LOG_DEBUG(("KE packet"));
1938 if (packet->flags & SILC_PACKET_FLAG_LIST)
1941 if (sock->protocol && sock->protocol->protocol &&
1942 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1944 SilcServerKEInternalContext *proto_ctx =
1945 (SilcServerKEInternalContext *)sock->protocol->context;
1947 proto_ctx->packet = silc_packet_context_dup(packet);
1949 /* Let the protocol handle the packet */
1950 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
1952 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1953 "protocol active, packet dropped."));
1957 case SILC_PACKET_KEY_EXCHANGE_1:
1958 SILC_LOG_DEBUG(("KE 1 packet"));
1959 if (packet->flags & SILC_PACKET_FLAG_LIST)
1962 if (sock->protocol && sock->protocol->protocol &&
1963 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1964 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
1966 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
1967 SilcServerRekeyInternalContext *proto_ctx =
1968 (SilcServerRekeyInternalContext *)sock->protocol->context;
1970 if (proto_ctx->packet)
1971 silc_packet_context_free(proto_ctx->packet);
1973 proto_ctx->packet = silc_packet_context_dup(packet);
1975 /* Let the protocol handle the packet */
1976 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1978 SilcServerKEInternalContext *proto_ctx =
1979 (SilcServerKEInternalContext *)sock->protocol->context;
1981 if (proto_ctx->packet)
1982 silc_packet_context_free(proto_ctx->packet);
1984 proto_ctx->packet = silc_packet_context_dup(packet);
1985 proto_ctx->dest_id_type = packet->src_id_type;
1986 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1987 packet->src_id_type);
1988 if (!proto_ctx->dest_id)
1991 /* Let the protocol handle the packet */
1992 silc_protocol_execute(sock->protocol, server->schedule,
1996 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1997 "protocol active, packet dropped."));
2001 case SILC_PACKET_KEY_EXCHANGE_2:
2002 SILC_LOG_DEBUG(("KE 2 packet"));
2003 if (packet->flags & SILC_PACKET_FLAG_LIST)
2006 if (sock->protocol && sock->protocol->protocol &&
2007 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2008 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2010 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2011 SilcServerRekeyInternalContext *proto_ctx =
2012 (SilcServerRekeyInternalContext *)sock->protocol->context;
2014 if (proto_ctx->packet)
2015 silc_packet_context_free(proto_ctx->packet);
2017 proto_ctx->packet = silc_packet_context_dup(packet);
2019 /* Let the protocol handle the packet */
2020 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2022 SilcServerKEInternalContext *proto_ctx =
2023 (SilcServerKEInternalContext *)sock->protocol->context;
2025 if (proto_ctx->packet)
2026 silc_packet_context_free(proto_ctx->packet);
2028 proto_ctx->packet = silc_packet_context_dup(packet);
2029 proto_ctx->dest_id_type = packet->src_id_type;
2030 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2031 packet->src_id_type);
2032 if (!proto_ctx->dest_id)
2035 /* Let the protocol handle the packet */
2036 silc_protocol_execute(sock->protocol, server->schedule,
2040 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2041 "protocol active, packet dropped."));
2045 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2047 * Connection authentication request packet. When we receive this packet
2048 * we will send to the other end information about our mandatory
2049 * authentication method for the connection. This packet maybe received
2052 SILC_LOG_DEBUG(("Connection authentication request packet"));
2053 if (packet->flags & SILC_PACKET_FLAG_LIST)
2055 silc_server_connection_auth_request(server, sock, packet);
2059 * Connection Authentication protocol packets
2061 case SILC_PACKET_CONNECTION_AUTH:
2062 /* Start of the authentication protocol. We receive here the
2063 authentication data and will verify it. */
2064 SILC_LOG_DEBUG(("Connection auth packet"));
2065 if (packet->flags & SILC_PACKET_FLAG_LIST)
2068 if (sock->protocol && sock->protocol->protocol->type
2069 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2071 SilcServerConnAuthInternalContext *proto_ctx =
2072 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2074 proto_ctx->packet = silc_packet_context_dup(packet);
2076 /* Let the protocol handle the packet */
2077 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2079 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2080 "protocol active, packet dropped."));
2084 case SILC_PACKET_NEW_ID:
2086 * Received New ID packet. This includes some new ID that has been
2087 * created. It may be for client, server or channel. This is the way
2088 * to distribute information about new registered entities in the
2091 SILC_LOG_DEBUG(("New ID packet"));
2092 if (packet->flags & SILC_PACKET_FLAG_LIST)
2093 silc_server_new_id_list(server, sock, packet);
2095 silc_server_new_id(server, sock, packet);
2098 case SILC_PACKET_NEW_CLIENT:
2100 * Received new client packet. This includes client information that
2101 * we will use to create initial client ID. After creating new
2102 * ID we will send it to the client.
2104 SILC_LOG_DEBUG(("New Client packet"));
2105 if (packet->flags & SILC_PACKET_FLAG_LIST)
2107 silc_server_new_client(server, sock, packet);
2110 case SILC_PACKET_NEW_SERVER:
2112 * Received new server packet. This includes Server ID and some other
2113 * information that we may save. This is received after server has
2116 SILC_LOG_DEBUG(("New Server packet"));
2117 if (packet->flags & SILC_PACKET_FLAG_LIST)
2119 silc_server_new_server(server, sock, packet);
2122 case SILC_PACKET_NEW_CHANNEL:
2124 * Received new channel packet. Information about new channel in the
2125 * network are distributed using this packet.
2127 SILC_LOG_DEBUG(("New Channel packet"));
2128 if (packet->flags & SILC_PACKET_FLAG_LIST)
2129 silc_server_new_channel_list(server, sock, packet);
2131 silc_server_new_channel(server, sock, packet);
2134 case SILC_PACKET_HEARTBEAT:
2136 * Received heartbeat.
2138 SILC_LOG_DEBUG(("Heartbeat packet"));
2139 if (packet->flags & SILC_PACKET_FLAG_LIST)
2143 case SILC_PACKET_KEY_AGREEMENT:
2145 * Received heartbeat.
2147 SILC_LOG_DEBUG(("Key agreement packet"));
2148 if (packet->flags & SILC_PACKET_FLAG_LIST)
2150 silc_server_key_agreement(server, sock, packet);
2153 case SILC_PACKET_REKEY:
2155 * Received re-key packet. The sender wants to regenerate the session
2158 SILC_LOG_DEBUG(("Re-key packet"));
2159 if (packet->flags & SILC_PACKET_FLAG_LIST)
2161 silc_server_rekey(server, sock, packet);
2164 case SILC_PACKET_REKEY_DONE:
2166 * The re-key is done.
2168 SILC_LOG_DEBUG(("Re-key done packet"));
2169 if (packet->flags & SILC_PACKET_FLAG_LIST)
2172 if (sock->protocol && sock->protocol->protocol &&
2173 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2175 SilcServerRekeyInternalContext *proto_ctx =
2176 (SilcServerRekeyInternalContext *)sock->protocol->context;
2178 if (proto_ctx->packet)
2179 silc_packet_context_free(proto_ctx->packet);
2181 proto_ctx->packet = silc_packet_context_dup(packet);
2183 /* Let the protocol handle the packet */
2184 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2186 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2187 "protocol active, packet dropped."));
2191 case SILC_PACKET_FTP:
2193 SILC_LOG_DEBUG(("FTP packet"));
2194 if (packet->flags & SILC_PACKET_FLAG_LIST)
2196 silc_server_ftp(server, sock, packet);
2199 case SILC_PACKET_RESUME_ROUTER:
2200 /* Resume router packet received. This packet is received for backup
2201 router resuming protocol. */
2202 SILC_LOG_DEBUG(("Resume router packet"));
2203 if (packet->flags & SILC_PACKET_FLAG_LIST)
2205 silc_server_backup_resume_router(server, sock, packet);
2209 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2215 /* Creates connection to a remote router. */
2217 void silc_server_create_connection(SilcServer server,
2218 const char *remote_host, uint32 port)
2220 SilcServerConnection sconn;
2222 /* Allocate connection object for hold connection specific stuff. */
2223 sconn = silc_calloc(1, sizeof(*sconn));
2224 sconn->server = server;
2225 sconn->remote_host = strdup(remote_host);
2226 sconn->remote_port = port;
2227 sconn->no_reconnect = TRUE;
2229 silc_schedule_task_add(server->schedule, 0,
2230 silc_server_connect_router,
2231 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2232 SILC_TASK_PRI_NORMAL);
2235 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2237 silc_socket_free((SilcSocketConnection)context);
2240 /* Closes connection to socket connection */
2242 void silc_server_close_connection(SilcServer server,
2243 SilcSocketConnection sock)
2245 if (!server->sockets[sock->sock])
2248 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2250 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2251 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2252 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2255 /* We won't listen for this connection anymore */
2256 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2258 /* Unregister all tasks */
2259 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2261 /* Close the actual connection */
2262 silc_net_close_connection(sock->sock);
2263 server->sockets[sock->sock] = NULL;
2265 /* If sock->user_data is NULL then we'll check for active protocols
2266 here since the silc_server_free_sock_user_data has not been called
2267 for this connection. */
2268 if (!sock->user_data) {
2269 /* If any protocol is active cancel its execution. It will call
2270 the final callback which will finalize the disconnection. */
2271 if (sock->protocol) {
2272 silc_protocol_cancel(sock->protocol, server->schedule);
2273 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2274 silc_protocol_execute_final(sock->protocol, server->schedule);
2275 sock->protocol = NULL;
2280 silc_schedule_task_add(server->schedule, 0,
2281 silc_server_close_connection_final,
2282 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2283 SILC_TASK_PRI_NORMAL);
2286 /* Sends disconnect message to remote connection and disconnects the
2289 void silc_server_disconnect_remote(SilcServer server,
2290 SilcSocketConnection sock,
2291 const char *fmt, ...)
2294 unsigned char buf[4096];
2299 memset(buf, 0, sizeof(buf));
2301 vsprintf(buf, fmt, ap);
2304 SILC_LOG_DEBUG(("Disconnecting remote host"));
2306 /* Notify remote end that the conversation is over. The notify message
2307 is tried to be sent immediately. */
2308 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2309 buf, strlen(buf), TRUE);
2311 /* Mark the connection to be disconnected */
2312 SILC_SET_DISCONNECTED(sock);
2313 silc_server_close_connection(server, sock);
2318 SilcClientEntry client;
2319 } *FreeClientInternal;
2321 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2323 FreeClientInternal i = (FreeClientInternal)context;
2325 silc_idlist_del_data(i->client);
2326 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2330 /* Frees client data and notifies about client's signoff. */
2332 void silc_server_free_client_data(SilcServer server,
2333 SilcSocketConnection sock,
2334 SilcClientEntry client,
2336 const char *signoff)
2338 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2340 /* If there is pending outgoing data for the client then purge it
2341 to the network before removing the client entry. */
2342 silc_server_packet_queue_purge(server, sock);
2347 /* Send SIGNOFF notify to routers. */
2348 if (notify && !server->standalone && server->router)
2349 silc_server_send_notify_signoff(server, server->router->connection,
2350 server->server_type == SILC_SERVER ?
2351 FALSE : TRUE, client->id, signoff);
2353 /* Remove client from all channels */
2355 silc_server_remove_from_channels(server, NULL, client,
2356 TRUE, (char *)signoff, TRUE);
2358 silc_server_remove_from_channels(server, NULL, client,
2359 FALSE, NULL, FALSE);
2361 /* Update statistics */
2362 server->stat.my_clients--;
2363 server->stat.clients--;
2364 if (server->server_type == SILC_ROUTER)
2365 server->stat.cell_clients--;
2366 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2367 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2369 /* We will not delete the client entry right away. We will take it
2370 into history (for WHOWAS command) for 5 minutes */
2373 silc_schedule_task_add(server->schedule, 0,
2374 silc_server_free_client_data_timeout,
2376 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2377 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2378 client->router = NULL;
2379 client->connection = NULL;
2383 /* Frees user_data pointer from socket connection object. This also sends
2384 appropriate notify packets to the network to inform about leaving
2387 void silc_server_free_sock_user_data(SilcServer server,
2388 SilcSocketConnection sock,
2389 const char *signoff_message)
2391 SILC_LOG_DEBUG(("Start"));
2393 switch (sock->type) {
2394 case SILC_SOCKET_TYPE_CLIENT:
2396 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2397 silc_server_free_client_data(server, sock, user_data, TRUE,
2401 case SILC_SOCKET_TYPE_SERVER:
2402 case SILC_SOCKET_TYPE_ROUTER:
2404 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2405 SilcServerEntry backup_router = NULL;
2408 backup_router = silc_server_backup_get(server, user_data->id);
2410 /* If this was our primary router connection then we're lost to
2411 the outside world. */
2412 if (server->router == user_data) {
2413 /* Check whether we have a backup router connection */
2414 if (!backup_router || backup_router == user_data) {
2415 silc_schedule_task_add(server->schedule, 0,
2416 silc_server_connect_to_router,
2419 SILC_TASK_PRI_NORMAL);
2421 server->id_entry->router = NULL;
2422 server->router = NULL;
2423 server->standalone = TRUE;
2424 backup_router = NULL;
2426 SILC_LOG_INFO(("New primary router is backup router %s",
2427 backup_router->server_name));
2428 SILC_LOG_DEBUG(("New primary router is backup router %s",
2429 backup_router->server_name));
2430 server->id_entry->router = backup_router;
2431 server->router = backup_router;
2432 server->router_connect = time(0);
2433 server->backup_primary = TRUE;
2434 if (server->server_type == SILC_BACKUP_ROUTER) {
2435 server->server_type = SILC_ROUTER;
2437 /* We'll need to constantly try to reconnect to the primary
2438 router so that we'll see when it comes back online. */
2439 silc_server_backup_reconnect(server, sock->ip, sock->port,
2440 silc_server_backup_connected,
2444 /* Mark this connection as replaced */
2445 silc_server_backup_replaced_add(server, user_data->id,
2448 } else if (backup_router) {
2449 SILC_LOG_INFO(("Enabling the use of backup router %s",
2450 backup_router->server_name));
2451 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2452 backup_router->server_name));
2454 /* Mark this connection as replaced */
2455 silc_server_backup_replaced_add(server, user_data->id,
2459 if (!backup_router) {
2460 /* Free all client entries that this server owns as they will
2461 become invalid now as well. */
2463 silc_server_remove_clients_by_server(server, user_data, TRUE);
2464 if (server->server_type == SILC_SERVER)
2465 silc_server_remove_channels_by_server(server, user_data);
2467 /* Update the client entries of this server to the new backup
2468 router. This also removes the clients that *really* was owned
2469 by the primary router and went down with the router. */
2470 silc_server_update_clients_by_server(server, user_data, backup_router,
2472 silc_server_update_servers_by_server(server, user_data, backup_router);
2473 if (server->server_type == SILC_SERVER)
2474 silc_server_update_channels_by_server(server, user_data,
2478 /* Free the server entry */
2479 silc_server_backup_del(server, user_data);
2480 silc_server_backup_replaced_del(server, user_data);
2481 silc_idlist_del_data(user_data);
2482 if (!silc_idlist_del_server(server->local_list, user_data))
2483 silc_idlist_del_server(server->global_list, user_data);
2484 server->stat.my_servers--;
2485 server->stat.servers--;
2486 if (server->server_type == SILC_ROUTER)
2487 server->stat.cell_servers--;
2489 if (backup_router) {
2490 /* Announce all of our stuff that was created about 5 minutes ago.
2491 The backup router knows all the other stuff already. */
2492 if (server->server_type == SILC_ROUTER)
2493 silc_server_announce_servers(server, FALSE, time(0) - 300,
2494 backup_router->connection);
2496 /* Announce our clients and channels to the router */
2497 silc_server_announce_clients(server, time(0) - 300,
2498 backup_router->connection);
2499 silc_server_announce_channels(server, time(0) - 300,
2500 backup_router->connection);
2506 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2508 silc_idlist_del_data(user_data);
2509 silc_free(user_data);
2514 /* If any protocol is active cancel its execution */
2515 if (sock->protocol) {
2516 silc_protocol_cancel(sock->protocol, server->schedule);
2517 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2518 silc_protocol_execute_final(sock->protocol, server->schedule);
2519 sock->protocol = NULL;
2522 sock->user_data = NULL;
2525 /* Removes client from all channels it has joined. This is used when client
2526 connection is disconnected. If the client on a channel is last, the
2527 channel is removed as well. This sends the SIGNOFF notify types. */
2529 void silc_server_remove_from_channels(SilcServer server,
2530 SilcSocketConnection sock,
2531 SilcClientEntry client,
2533 char *signoff_message,
2536 SilcChannelEntry channel;
2537 SilcChannelClientEntry chl;
2538 SilcHashTableList htl;
2541 SILC_LOG_DEBUG(("Start"));
2543 if (!client || !client->id)
2546 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2548 /* Remove the client from all channels. The client is removed from
2549 the channels' user list. */
2550 silc_hash_table_list(client->channels, &htl);
2551 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2552 channel = chl->channel;
2554 /* Remove channel from client's channel list */
2555 silc_hash_table_del(client->channels, channel);
2557 /* Remove channel if there is no users anymore */
2558 if (server->server_type == SILC_ROUTER &&
2559 silc_hash_table_count(channel->user_list) < 2) {
2561 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2562 if (silc_idlist_del_channel(server->local_list, channel))
2563 server->stat.my_channels--;
2565 silc_idlist_del_channel(server->global_list, channel);
2569 /* Remove client from channel's client list */
2570 silc_hash_table_del(channel->user_list, chl->client);
2572 /* If there is no global users on the channel anymore mark the channel
2573 as local channel. Do not check if the removed client is local client. */
2574 if (server->server_type != SILC_ROUTER && channel->global_users &&
2575 chl->client->router && !silc_server_channel_has_global(channel))
2576 channel->global_users = FALSE;
2579 server->stat.my_chanclients--;
2581 /* If there is not at least one local user on the channel then we don't
2582 need the channel entry anymore, we can remove it safely. */
2583 if (server->server_type != SILC_ROUTER &&
2584 !silc_server_channel_has_local(channel)) {
2585 /* Notify about leaving client if this channel has global users. */
2586 if (notify && channel->global_users)
2587 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2588 SILC_NOTIFY_TYPE_SIGNOFF,
2589 signoff_message ? 2 : 1,
2590 clidp->data, clidp->len,
2591 signoff_message, signoff_message ?
2592 strlen(signoff_message) : 0);
2595 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2597 if (channel->founder_key) {
2598 /* The founder auth data exists, do not remove the channel entry */
2599 SilcChannelClientEntry chl2;
2600 SilcHashTableList htl2;
2602 channel->disabled = TRUE;
2604 silc_hash_table_list(channel->user_list, &htl2);
2605 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2606 silc_hash_table_del(chl2->client->channels, channel);
2607 silc_hash_table_del(channel->user_list, chl2->client);
2613 /* Remove the channel entry */
2614 if (silc_idlist_del_channel(server->local_list, channel))
2615 server->stat.my_channels--;
2617 silc_idlist_del_channel(server->global_list, channel);
2621 /* Send notify to channel about client leaving SILC and thus
2622 the entire channel. */
2624 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2625 SILC_NOTIFY_TYPE_SIGNOFF,
2626 signoff_message ? 2 : 1,
2627 clidp->data, clidp->len,
2628 signoff_message, signoff_message ?
2629 strlen(signoff_message) : 0);
2631 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2632 /* Re-generate channel key */
2633 if (!silc_server_create_channel_key(server, channel, 0))
2636 /* Send the channel key to the channel. The key of course is not sent
2637 to the client who was removed from the channel. */
2638 silc_server_send_channel_key(server, client->connection, channel,
2639 server->server_type == SILC_ROUTER ?
2640 FALSE : !server->standalone);
2644 silc_buffer_free(clidp);
2647 /* Removes client from one channel. This is used for example when client
2648 calls LEAVE command to remove itself from the channel. Returns TRUE
2649 if channel still exists and FALSE if the channel is removed when
2650 last client leaves the channel. If `notify' is FALSE notify messages
2653 int silc_server_remove_from_one_channel(SilcServer server,
2654 SilcSocketConnection sock,
2655 SilcChannelEntry channel,
2656 SilcClientEntry client,
2659 SilcChannelClientEntry chl;
2662 SILC_LOG_DEBUG(("Start"));
2664 /* Get the entry to the channel, if this client is not on the channel
2666 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2669 /* Remove the client from the channel. The client is removed from
2670 the channel's user list. */
2672 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2674 /* Remove channel from client's channel list */
2675 silc_hash_table_del(client->channels, chl->channel);
2677 /* Remove channel if there is no users anymore */
2678 if (server->server_type == SILC_ROUTER &&
2679 silc_hash_table_count(channel->user_list) < 2) {
2681 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2682 if (silc_idlist_del_channel(server->local_list, channel))
2683 server->stat.my_channels--;
2685 silc_idlist_del_channel(server->global_list, channel);
2686 silc_buffer_free(clidp);
2690 /* Remove client from channel's client list */
2691 silc_hash_table_del(channel->user_list, chl->client);
2693 /* If there is no global users on the channel anymore mark the channel
2694 as local channel. Do not check if the client is local client. */
2695 if (server->server_type != SILC_ROUTER && channel->global_users &&
2696 chl->client->router && !silc_server_channel_has_global(channel))
2697 channel->global_users = FALSE;
2700 server->stat.my_chanclients--;
2702 /* If there is not at least one local user on the channel then we don't
2703 need the channel entry anymore, we can remove it safely. */
2704 if (server->server_type != SILC_ROUTER &&
2705 !silc_server_channel_has_local(channel)) {
2706 /* Notify about leaving client if this channel has global users. */
2707 if (notify && channel->global_users)
2708 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2709 SILC_NOTIFY_TYPE_LEAVE, 1,
2710 clidp->data, clidp->len);
2712 silc_buffer_free(clidp);
2715 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2717 if (channel->founder_key) {
2718 /* The founder auth data exists, do not remove the channel entry */
2719 SilcChannelClientEntry chl2;
2720 SilcHashTableList htl2;
2722 channel->disabled = TRUE;
2724 silc_hash_table_list(channel->user_list, &htl2);
2725 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2726 silc_hash_table_del(chl2->client->channels, channel);
2727 silc_hash_table_del(channel->user_list, chl2->client);
2733 /* Remove the channel entry */
2734 if (silc_idlist_del_channel(server->local_list, channel))
2735 server->stat.my_channels--;
2737 silc_idlist_del_channel(server->global_list, channel);
2741 /* Send notify to channel about client leaving the channel */
2743 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2744 SILC_NOTIFY_TYPE_LEAVE, 1,
2745 clidp->data, clidp->len);
2747 silc_buffer_free(clidp);
2751 /* Timeout callback. This is called if connection is idle or for some
2752 other reason is not responding within some period of time. This
2753 disconnects the remote end. */
2755 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2757 SilcServer server = (SilcServer)context;
2758 SilcSocketConnection sock = server->sockets[fd];
2760 SILC_LOG_DEBUG(("Start"));
2765 /* If we have protocol active we must assure that we call the protocol's
2766 final callback so that all the memory is freed. */
2767 if (sock->protocol) {
2768 silc_protocol_cancel(sock->protocol, server->schedule);
2769 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2770 silc_protocol_execute_final(sock->protocol, server->schedule);
2771 sock->protocol = NULL;
2775 if (sock->user_data)
2776 silc_server_free_sock_user_data(server, sock, NULL);
2778 silc_server_disconnect_remote(server, sock, "Server closed connection: "
2779 "Connection timeout");
2782 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2783 function may be used only by router. In real SILC network all channels
2784 are created by routers thus this function is never used by normal
2787 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2788 SilcServerID *router_id,
2794 SilcChannelID *channel_id;
2795 SilcChannelEntry entry;
2799 SILC_LOG_DEBUG(("Creating new channel"));
2802 cipher = SILC_DEFAULT_CIPHER;
2804 hmac = SILC_DEFAULT_HMAC;
2806 /* Allocate cipher */
2807 if (!silc_cipher_alloc(cipher, &key))
2811 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2812 silc_cipher_free(key);
2816 channel_name = strdup(channel_name);
2818 /* Create the channel ID */
2819 if (!silc_id_create_channel_id(server, router_id, server->rng,
2821 silc_free(channel_name);
2822 silc_cipher_free(key);
2823 silc_hmac_free(newhmac);
2827 /* Create the channel */
2828 entry = silc_idlist_add_channel(server->local_list, channel_name,
2829 SILC_CHANNEL_MODE_NONE, channel_id,
2830 NULL, key, newhmac, 0);
2832 silc_free(channel_name);
2833 silc_cipher_free(key);
2834 silc_hmac_free(newhmac);
2835 silc_free(channel_id);
2839 entry->cipher = strdup(cipher);
2840 entry->hmac_name = strdup(hmac);
2842 /* Now create the actual key material */
2843 if (!silc_server_create_channel_key(server, entry,
2844 silc_cipher_get_key_len(key) / 8)) {
2845 silc_idlist_del_channel(server->local_list, entry);
2849 /* Notify other routers about the new channel. We send the packet
2850 to our primary route. */
2851 if (broadcast && server->standalone == FALSE)
2852 silc_server_send_new_channel(server, server->router->connection, TRUE,
2853 channel_name, entry->id,
2854 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2857 server->stat.my_channels++;
2862 /* Same as above but creates the channel with Channel ID `channel_id. */
2865 silc_server_create_new_channel_with_id(SilcServer server,
2869 SilcChannelID *channel_id,
2872 SilcChannelEntry entry;
2876 SILC_LOG_DEBUG(("Creating new channel"));
2879 cipher = SILC_DEFAULT_CIPHER;
2881 hmac = SILC_DEFAULT_HMAC;
2883 /* Allocate cipher */
2884 if (!silc_cipher_alloc(cipher, &key))
2888 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2889 silc_cipher_free(key);
2893 channel_name = strdup(channel_name);
2895 /* Create the channel */
2896 entry = silc_idlist_add_channel(server->local_list, channel_name,
2897 SILC_CHANNEL_MODE_NONE, channel_id,
2898 NULL, key, newhmac, 0);
2900 silc_cipher_free(key);
2901 silc_hmac_free(newhmac);
2902 silc_free(channel_name);
2906 /* Now create the actual key material */
2907 if (!silc_server_create_channel_key(server, entry,
2908 silc_cipher_get_key_len(key) / 8)) {
2909 silc_idlist_del_channel(server->local_list, entry);
2913 /* Notify other routers about the new channel. We send the packet
2914 to our primary route. */
2915 if (broadcast && server->standalone == FALSE)
2916 silc_server_send_new_channel(server, server->router->connection, TRUE,
2917 channel_name, entry->id,
2918 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2921 server->stat.my_channels++;
2926 /* Channel's key re-key timeout callback. */
2928 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
2930 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
2931 SilcServer server = (SilcServer)rekey->context;
2935 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
2938 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
2941 /* Generates new channel key. This is used to create the initial channel key
2942 but also to re-generate new key for channel. If `key_len' is provided
2943 it is the bytes of the key length. */
2945 bool silc_server_create_channel_key(SilcServer server,
2946 SilcChannelEntry channel,
2950 unsigned char channel_key[32], hash[32];
2953 SILC_LOG_DEBUG(("Generating channel key"));
2955 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
2956 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
2960 if (!channel->channel_key)
2961 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
2962 channel->channel_key = NULL;
2968 else if (channel->key_len)
2969 len = channel->key_len / 8;
2971 len = silc_cipher_get_key_len(channel->channel_key) / 8;
2973 /* Create channel key */
2974 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
2977 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
2979 /* Remove old key if exists */
2981 memset(channel->key, 0, channel->key_len / 8);
2982 silc_free(channel->key);
2986 channel->key_len = len * 8;
2987 channel->key = silc_calloc(len, sizeof(*channel->key));
2988 memcpy(channel->key, channel_key, len);
2989 memset(channel_key, 0, sizeof(channel_key));
2991 /* Generate HMAC key from the channel key data and set it */
2993 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
2994 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
2995 silc_hmac_set_key(channel->hmac, hash,
2996 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
2997 memset(hash, 0, sizeof(hash));
2999 if (server->server_type == SILC_ROUTER) {
3000 if (!channel->rekey)
3001 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3002 channel->rekey->context = (void *)server;
3003 channel->rekey->channel = channel;
3004 channel->rekey->key_len = key_len;
3005 if (channel->rekey->task)
3006 silc_schedule_task_del(server->schedule, channel->rekey->task);
3008 channel->rekey->task =
3009 silc_schedule_task_add(server->schedule, 0,
3010 silc_server_channel_key_rekey,
3011 (void *)channel->rekey, 3600, 0,
3013 SILC_TASK_PRI_NORMAL);
3019 /* Saves the channel key found in the encoded `key_payload' buffer. This
3020 function is used when we receive Channel Key Payload and also when we're
3021 processing JOIN command reply. Returns entry to the channel. */
3023 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3024 SilcBuffer key_payload,
3025 SilcChannelEntry channel)
3027 SilcChannelKeyPayload payload = NULL;
3028 SilcChannelID *id = NULL;
3029 unsigned char *tmp, hash[32];
3033 SILC_LOG_DEBUG(("Start"));
3035 /* Decode channel key payload */
3036 payload = silc_channel_key_payload_parse(key_payload->data,
3039 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3044 /* Get the channel entry */
3047 /* Get channel ID */
3048 tmp = silc_channel_key_get_id(payload, &tmp_len);
3049 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3055 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3057 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3059 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3060 silc_id_render(id, SILC_ID_CHANNEL)));
3066 tmp = silc_channel_key_get_key(payload, &tmp_len);
3072 cipher = silc_channel_key_get_cipher(payload, NULL);
3078 /* Remove old key if exists */
3080 memset(channel->key, 0, channel->key_len / 8);
3081 silc_free(channel->key);
3082 silc_cipher_free(channel->channel_key);
3085 /* Create new cipher */
3086 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3087 channel->channel_key = NULL;
3092 if (channel->cipher)
3093 silc_free(channel->cipher);
3094 channel->cipher = strdup(cipher);
3097 channel->key_len = tmp_len * 8;
3098 channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
3099 memcpy(channel->key, tmp, tmp_len);
3100 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3102 /* Generate HMAC key from the channel key data and set it */
3104 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3105 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3106 silc_hmac_set_key(channel->hmac, hash,
3107 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3109 memset(hash, 0, sizeof(hash));
3110 memset(tmp, 0, tmp_len);
3112 if (server->server_type == SILC_ROUTER) {
3113 if (!channel->rekey)
3114 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3115 channel->rekey->context = (void *)server;
3116 channel->rekey->channel = channel;
3117 if (channel->rekey->task)
3118 silc_schedule_task_del(server->schedule, channel->rekey->task);
3120 channel->rekey->task =
3121 silc_schedule_task_add(server->schedule, 0,
3122 silc_server_channel_key_rekey,
3123 (void *)channel->rekey, 3600, 0,
3125 SILC_TASK_PRI_NORMAL);
3131 silc_channel_key_payload_free(payload);
3136 /* Heartbeat callback. This function is set as argument for the
3137 silc_socket_set_heartbeat function. The library will call this function
3138 at the set time interval. */
3140 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3143 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3145 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3147 /* Send the heartbeat */
3148 silc_server_send_heartbeat(hb->server, sock);
3151 /* Returns assembled of all servers in the given ID list. The packet's
3152 form is dictated by the New ID payload. */
3154 static void silc_server_announce_get_servers(SilcServer server,
3155 SilcServerEntry remote,
3157 SilcBuffer *servers,
3158 unsigned long creation_time)
3160 SilcIDCacheList list;
3161 SilcIDCacheEntry id_cache;
3162 SilcServerEntry entry;
3165 /* Go through all clients in the list */
3166 if (silc_idcache_get_all(id_list->servers, &list)) {
3167 if (silc_idcache_list_first(list, &id_cache)) {
3169 entry = (SilcServerEntry)id_cache->context;
3171 /* Do not announce the one we've sending our announcements and
3172 do not announce ourself. Also check the creation time if it's
3174 if ((entry == remote) || (entry == server->id_entry) ||
3175 (creation_time && entry->data.created < creation_time)) {
3176 if (!silc_idcache_list_next(list, &id_cache))
3181 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3183 *servers = silc_buffer_realloc(*servers,
3185 (*servers)->truelen + idp->len :
3187 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3188 silc_buffer_put(*servers, idp->data, idp->len);
3189 silc_buffer_pull(*servers, idp->len);
3190 silc_buffer_free(idp);
3192 if (!silc_idcache_list_next(list, &id_cache))
3197 silc_idcache_list_free(list);
3202 silc_server_announce_encode_notify(SilcNotifyType notify, uint32 argc, ...)
3208 p = silc_notify_payload_encode(notify, argc, ap);
3214 /* This function is used by router to announce existing servers to our
3215 primary router when we've connected to it. If `creation_time' is non-zero
3216 then only the servers that has been created after the `creation_time'
3217 will be announced. */
3219 void silc_server_announce_servers(SilcServer server, bool global,
3220 unsigned long creation_time,
3221 SilcSocketConnection remote)
3223 SilcBuffer servers = NULL;
3225 SILC_LOG_DEBUG(("Announcing servers"));
3227 /* Get servers in local list */
3228 silc_server_announce_get_servers(server, remote->user_data,
3229 server->local_list, &servers,
3233 /* Get servers in global list */
3234 silc_server_announce_get_servers(server, remote->user_data,
3235 server->global_list, &servers,
3239 silc_buffer_push(servers, servers->data - servers->head);
3240 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3242 /* Send the packet */
3243 silc_server_packet_send(server, remote,
3244 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3245 servers->data, servers->len, TRUE);
3247 silc_buffer_free(servers);
3251 /* Returns assembled packet of all clients in the given ID list. The
3252 packet's form is dictated by the New ID Payload. */
3254 static void silc_server_announce_get_clients(SilcServer server,
3256 SilcBuffer *clients,
3258 unsigned long creation_time)
3260 SilcIDCacheList list;
3261 SilcIDCacheEntry id_cache;
3262 SilcClientEntry client;
3265 unsigned char mode[4];
3267 /* Go through all clients in the list */
3268 if (silc_idcache_get_all(id_list->clients, &list)) {
3269 if (silc_idcache_list_first(list, &id_cache)) {
3271 client = (SilcClientEntry)id_cache->context;
3273 if (creation_time && client->data.created < creation_time) {
3274 if (!silc_idcache_list_next(list, &id_cache))
3279 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3281 *clients = silc_buffer_realloc(*clients,
3283 (*clients)->truelen + idp->len :
3285 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3286 silc_buffer_put(*clients, idp->data, idp->len);
3287 silc_buffer_pull(*clients, idp->len);
3289 SILC_PUT32_MSB(client->mode, mode);
3290 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3291 2, idp->data, idp->len,
3293 *umodes = silc_buffer_realloc(*umodes,
3295 (*umodes)->truelen + tmp->len :
3297 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3298 silc_buffer_put(*umodes, tmp->data, tmp->len);
3299 silc_buffer_pull(*umodes, tmp->len);
3300 silc_buffer_free(tmp);
3302 silc_buffer_free(idp);
3304 if (!silc_idcache_list_next(list, &id_cache))
3309 silc_idcache_list_free(list);
3313 /* This function is used to announce our existing clients to our router
3314 when we've connected to it. If `creation_time' is non-zero then only
3315 the clients that has been created after the `creation_time' will be
3318 void silc_server_announce_clients(SilcServer server,
3319 unsigned long creation_time,
3320 SilcSocketConnection remote)
3322 SilcBuffer clients = NULL;
3323 SilcBuffer umodes = NULL;
3325 SILC_LOG_DEBUG(("Announcing clients"));
3327 /* Get clients in local list */
3328 silc_server_announce_get_clients(server, server->local_list,
3329 &clients, &umodes, creation_time);
3331 /* As router we announce our global list as well */
3332 if (server->server_type == SILC_ROUTER)
3333 silc_server_announce_get_clients(server, server->global_list,
3334 &clients, &umodes, creation_time);
3337 silc_buffer_push(clients, clients->data - clients->head);
3338 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3340 /* Send the packet */
3341 silc_server_packet_send(server, remote,
3342 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3343 clients->data, clients->len, TRUE);
3345 silc_buffer_free(clients);
3349 silc_buffer_push(umodes, umodes->data - umodes->head);
3350 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3352 /* Send the packet */
3353 silc_server_packet_send(server, remote,
3354 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3355 umodes->data, umodes->len, TRUE);
3357 silc_buffer_free(umodes);
3361 /* Returns channel's topic for announcing it */
3363 void silc_server_announce_get_channel_topic(SilcServer server,
3364 SilcChannelEntry channel,
3369 if (channel->topic) {
3370 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3371 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3372 chidp->data, chidp->len,
3374 strlen(channel->topic));
3375 silc_buffer_free(chidp);
3379 /* Returns assembled packets for channel users of the `channel'. */
3381 void silc_server_announce_get_channel_users(SilcServer server,
3382 SilcChannelEntry channel,
3383 SilcBuffer *channel_users,
3384 SilcBuffer *channel_users_modes)
3386 SilcChannelClientEntry chl;
3387 SilcHashTableList htl;
3388 SilcBuffer chidp, clidp;
3391 unsigned char mode[4];
3393 SILC_LOG_DEBUG(("Start"));
3395 /* Now find all users on the channel */
3396 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3397 silc_hash_table_list(channel->user_list, &htl);
3398 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3399 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3402 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3403 clidp->data, clidp->len,
3404 chidp->data, chidp->len);
3407 silc_buffer_realloc(*channel_users,
3409 (*channel_users)->truelen + len : len));
3410 silc_buffer_pull_tail(*channel_users,
3411 ((*channel_users)->end -
3412 (*channel_users)->data));
3414 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3415 silc_buffer_pull(*channel_users, len);
3416 silc_buffer_free(tmp);
3418 /* CUMODE notify for mode change on the channel */
3419 SILC_PUT32_MSB(chl->mode, mode);
3420 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3421 3, clidp->data, clidp->len,
3423 clidp->data, clidp->len);
3425 *channel_users_modes =
3426 silc_buffer_realloc(*channel_users_modes,
3427 (*channel_users_modes ?
3428 (*channel_users_modes)->truelen + len : len));
3429 silc_buffer_pull_tail(*channel_users_modes,
3430 ((*channel_users_modes)->end -
3431 (*channel_users_modes)->data));
3433 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3434 silc_buffer_pull(*channel_users_modes, len);
3435 silc_buffer_free(tmp);
3437 silc_buffer_free(clidp);
3439 silc_buffer_free(chidp);
3442 /* Returns assembled packets for all channels and users on those channels
3443 from the given ID List. The packets are in the form dictated by the
3444 New Channel and New Channel User payloads. */
3446 void silc_server_announce_get_channels(SilcServer server,
3448 SilcBuffer *channels,
3449 SilcBuffer *channel_users,
3450 SilcBuffer **channel_users_modes,
3451 uint32 *channel_users_modes_c,
3452 SilcBuffer **channel_topics,
3453 SilcChannelID ***channel_ids,
3454 unsigned long creation_time)
3456 SilcIDCacheList list;
3457 SilcIDCacheEntry id_cache;
3458 SilcChannelEntry channel;
3463 int i = *channel_users_modes_c;
3466 SILC_LOG_DEBUG(("Start"));
3468 /* Go through all channels in the list */
3469 if (silc_idcache_get_all(id_list->channels, &list)) {
3470 if (silc_idcache_list_first(list, &id_cache)) {
3472 channel = (SilcChannelEntry)id_cache->context;
3474 if (creation_time && channel->created < creation_time)
3479 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3480 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3481 name_len = strlen(channel->channel_name);
3484 len = 4 + name_len + id_len + 4;
3486 silc_buffer_realloc(*channels,
3487 (*channels ? (*channels)->truelen +
3489 silc_buffer_pull_tail(*channels,
3490 ((*channels)->end - (*channels)->data));
3491 silc_buffer_format(*channels,
3492 SILC_STR_UI_SHORT(name_len),
3493 SILC_STR_UI_XNSTRING(channel->channel_name,
3495 SILC_STR_UI_SHORT(id_len),
3496 SILC_STR_UI_XNSTRING(cid, id_len),
3497 SILC_STR_UI_INT(channel->mode),
3499 silc_buffer_pull(*channels, len);
3502 /* Channel user modes */
3503 *channel_users_modes = silc_realloc(*channel_users_modes,
3504 sizeof(**channel_users_modes) *
3506 (*channel_users_modes)[i] = NULL;
3507 *channel_ids = silc_realloc(*channel_ids,
3508 sizeof(**channel_ids) * (i + 1));
3509 (*channel_ids)[i] = NULL;
3510 silc_server_announce_get_channel_users(server, channel,
3512 &(*channel_users_modes)[i]);
3513 (*channel_ids)[i] = channel->id;
3515 /* Channel's topic */
3516 *channel_topics = silc_realloc(*channel_topics,
3517 sizeof(**channel_topics) * (i + 1));
3518 (*channel_topics)[i] = NULL;
3519 silc_server_announce_get_channel_topic(server, channel,
3520 &(*channel_topics)[i]);
3523 if (!silc_idcache_list_next(list, &id_cache))
3527 *channel_users_modes_c += i;
3530 silc_idcache_list_free(list);
3534 /* This function is used to announce our existing channels to our router
3535 when we've connected to it. This also announces the users on the
3536 channels to the router. If the `creation_time' is non-zero only the
3537 channels that was created after the `creation_time' are announced.
3538 Note that the channel users are still announced even if the `creation_time'
3541 void silc_server_announce_channels(SilcServer server,
3542 unsigned long creation_time,
3543 SilcSocketConnection remote)
3545 SilcBuffer channels = NULL, channel_users = NULL;
3546 SilcBuffer *channel_users_modes = NULL;
3547 SilcBuffer *channel_topics = NULL;
3548 uint32 channel_users_modes_c = 0;
3549 SilcChannelID **channel_ids = NULL;
3551 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3553 /* Get channels and channel users in local list */
3554 silc_server_announce_get_channels(server, server->local_list,
3555 &channels, &channel_users,
3556 &channel_users_modes,
3557 &channel_users_modes_c,
3559 &channel_ids, creation_time);
3561 /* Get channels and channel users in global list */
3562 if (server->server_type != SILC_SERVER)
3563 silc_server_announce_get_channels(server, server->global_list,
3564 &channels, &channel_users,
3565 &channel_users_modes,
3566 &channel_users_modes_c,
3568 &channel_ids, creation_time);
3571 silc_buffer_push(channels, channels->data - channels->head);
3572 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3574 /* Send the packet */
3575 silc_server_packet_send(server, remote,
3576 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3577 channels->data, channels->len,
3580 silc_buffer_free(channels);
3583 if (channel_users) {
3584 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3585 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3586 channel_users->len);
3588 /* Send the packet */
3589 silc_server_packet_send(server, remote,
3590 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3591 channel_users->data, channel_users->len,
3594 silc_buffer_free(channel_users);
3597 if (channel_users_modes) {
3600 for (i = 0; i < channel_users_modes_c; i++) {
3601 if (!channel_users_modes[i])
3603 silc_buffer_push(channel_users_modes[i],
3604 channel_users_modes[i]->data -
3605 channel_users_modes[i]->head);
3606 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3607 channel_users_modes[i]->len);
3608 silc_server_packet_send_dest(server, remote,
3609 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3610 channel_ids[i], SILC_ID_CHANNEL,
3611 channel_users_modes[i]->data,
3612 channel_users_modes[i]->len,
3614 silc_buffer_free(channel_users_modes[i]);
3616 silc_free(channel_users_modes);
3619 if (channel_topics) {
3622 for (i = 0; i < channel_users_modes_c; i++) {
3623 if (!channel_topics[i])
3626 silc_buffer_push(channel_topics[i],
3627 channel_topics[i]->data -
3628 channel_topics[i]->head);
3629 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
3630 channel_topics[i]->len);
3631 silc_server_packet_send_dest(server, remote,
3632 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3633 channel_ids[i], SILC_ID_CHANNEL,
3634 channel_topics[i]->data,
3635 channel_topics[i]->len,
3637 silc_buffer_free(channel_topics[i]);
3639 silc_free(channel_topics);
3642 silc_free(channel_ids);
3645 /* Failure timeout callback. If this is called then we will immediately
3646 process the received failure. We always process the failure with timeout
3647 since we do not want to blindly trust to received failure packets.
3648 This won't be called (the timeout is cancelled) if the failure was
3649 bogus (it is bogus if remote does not close the connection after sending
3652 SILC_TASK_CALLBACK(silc_server_failure_callback)
3654 SilcServerFailureContext f = (SilcServerFailureContext)context;
3656 if (f->sock->protocol) {
3657 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3658 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3664 /* Assembles user list and users mode list from the `channel'. */
3666 void silc_server_get_users_on_channel(SilcServer server,
3667 SilcChannelEntry channel,
3668 SilcBuffer *user_list,
3669 SilcBuffer *mode_list,
3672 SilcChannelClientEntry chl;
3673 SilcHashTableList htl;
3674 SilcBuffer client_id_list;
3675 SilcBuffer client_mode_list;
3677 uint32 list_count = 0, len = 0;
3679 silc_hash_table_list(channel->user_list, &htl);
3680 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3681 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3683 client_id_list = silc_buffer_alloc(len);
3685 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3686 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3687 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3689 silc_hash_table_list(channel->user_list, &htl);
3690 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3692 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3693 silc_buffer_put(client_id_list, idp->data, idp->len);
3694 silc_buffer_pull(client_id_list, idp->len);
3695 silc_buffer_free(idp);
3697 /* Client's mode on channel */
3698 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3699 silc_buffer_pull(client_mode_list, 4);
3703 silc_buffer_push(client_id_list,
3704 client_id_list->data - client_id_list->head);
3705 silc_buffer_push(client_mode_list,
3706 client_mode_list->data - client_mode_list->head);
3708 *user_list = client_id_list;
3709 *mode_list = client_mode_list;
3710 *user_count = list_count;
3713 /* Saves users and their modes to the `channel'. */
3715 void silc_server_save_users_on_channel(SilcServer server,
3716 SilcSocketConnection sock,
3717 SilcChannelEntry channel,
3718 SilcClientID *noadd,
3719 SilcBuffer user_list,
3720 SilcBuffer mode_list,
3726 SilcClientID *client_id;
3727 SilcClientEntry client;
3728 SilcIDCacheEntry cache;
3731 SILC_LOG_DEBUG(("Start"));
3733 for (i = 0; i < user_count; i++) {
3735 SILC_GET16_MSB(idp_len, user_list->data + 2);
3737 client_id = silc_id_payload_parse_id(user_list->data, idp_len);
3738 silc_buffer_pull(user_list, idp_len);
3743 SILC_GET32_MSB(mode, mode_list->data);
3744 silc_buffer_pull(mode_list, 4);
3746 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3747 silc_free(client_id);
3753 /* Check if we have this client cached already. */
3754 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3755 server->server_type, &cache);
3757 client = silc_idlist_find_client_by_id(server->global_list,
3758 client_id, server->server_type,
3763 /* If router did not find such Client ID in its lists then this must
3764 be bogus client or some router in the net is buggy. */
3765 if (server->server_type == SILC_ROUTER) {
3766 silc_free(client_id);
3770 /* We don't have that client anywhere, add it. The client is added
3771 to global list since server didn't have it in the lists so it must be
3773 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3774 silc_id_dup(client_id, SILC_ID_CLIENT),
3775 sock->user_data, NULL, 0);
3777 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3778 silc_free(client_id);
3782 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3784 /* Found, if it is from global list we'll assure that we won't
3785 expire it now that the entry is on channel. */
3790 silc_free(client_id);
3792 if (!silc_server_client_on_channel(client, channel)) {
3793 /* Client was not on the channel, add it. */
3794 SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3795 chl->client = client;
3797 chl->channel = channel;
3798 silc_hash_table_add(channel->user_list, chl->client, chl);
3799 silc_hash_table_add(client->channels, chl->channel, chl);
3804 /* Lookups route to the client indicated by the `id_data'. The connection
3805 object and internal data object is returned. Returns NULL if route
3806 could not be found to the client. If the `client_id' is specified then
3807 it is used and the `id_data' is ignored. */
3809 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3810 unsigned char *id_data,
3812 SilcClientID *client_id,
3813 SilcIDListData *idata)
3816 SilcClientEntry client;
3818 SILC_LOG_DEBUG(("Start"));
3820 /* Decode destination Client ID */
3822 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3824 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3828 id = silc_id_dup(client_id, SILC_ID_CLIENT);
3831 /* If the destination belongs to our server we don't have to route
3832 the packet anywhere but to send it to the local destination. */
3833 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
3837 /* If we are router and the client has router then the client is in
3838 our cell but not directly connected to us. */
3839 if (server->server_type == SILC_ROUTER && client->router) {
3840 /* We are of course in this case the client's router thus the route
3841 to the client is the server who owns the client. So, we will send
3842 the packet to that server. */
3844 *idata = (SilcIDListData)client->router;
3845 return client->router->connection;
3848 /* Seems that client really is directly connected to us */
3850 *idata = (SilcIDListData)client;
3851 return client->connection;
3854 /* Destination belongs to someone not in this server. If we are normal
3855 server our action is to send the packet to our router. */
3856 if (server->server_type != SILC_ROUTER && !server->standalone) {
3859 *idata = (SilcIDListData)server->router;
3860 return server->router->connection;
3863 /* We are router and we will perform route lookup for the destination
3864 and send the packet to fastest route. */
3865 if (server->server_type == SILC_ROUTER && !server->standalone) {
3866 /* Check first that the ID is valid */
3867 client = silc_idlist_find_client_by_id(server->global_list, id,
3870 SilcSocketConnection dst_sock;
3872 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
3876 *idata = (SilcIDListData)dst_sock->user_data;
3885 /* Encodes and returns channel list of channels the `client' has joined.
3886 Secret channels are not put to the list. */
3888 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
3889 SilcClientEntry client)
3891 SilcBuffer buffer = NULL;
3892 SilcChannelEntry channel;
3893 SilcChannelClientEntry chl;
3894 SilcHashTableList htl;
3900 silc_hash_table_list(client->channels, &htl);
3901 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3902 channel = chl->channel;
3904 if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
3905 channel->mode & SILC_CHANNEL_MODE_PRIVATE)
3908 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3909 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3910 name_len = strlen(channel->channel_name);
3912 len = 4 + name_len + id_len + 4;
3913 buffer = silc_buffer_realloc(buffer,
3914 (buffer ? (buffer)->truelen + len : len));
3915 silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
3916 silc_buffer_format(buffer,
3917 SILC_STR_UI_SHORT(name_len),
3918 SILC_STR_UI_XNSTRING(channel->channel_name,
3920 SILC_STR_UI_SHORT(id_len),
3921 SILC_STR_UI_XNSTRING(cid, id_len),
3922 SILC_STR_UI_INT(chl->mode), /* Client's mode */
3924 silc_buffer_pull(buffer, len);
3929 silc_buffer_push(buffer, buffer->data - buffer->head);
3934 /* Finds client entry by Client ID and if it is not found then resolves
3935 it using WHOIS command. */
3937 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
3938 SilcClientID *client_id,
3941 SilcClientEntry client;
3946 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3949 client = silc_idlist_find_client_by_id(server->global_list,
3950 client_id, TRUE, NULL);
3951 if (!client && server->server_type == SILC_ROUTER)
3955 if (!client && server->standalone)
3958 if (!client || !client->nickname || !client->username) {
3959 SilcBuffer buffer, idp;
3961 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
3962 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
3963 client->resolve_cmd_ident = ++server->cmd_ident;
3965 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3966 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
3967 server->cmd_ident, 1,
3968 3, idp->data, idp->len);
3969 silc_server_packet_send(server, client ? client->router->connection :
3970 server->router->connection,
3971 SILC_PACKET_COMMAND, 0,
3972 buffer->data, buffer->len, FALSE);
3973 silc_buffer_free(idp);
3974 silc_buffer_free(buffer);
3985 /* A timeout callback for the re-key. We will be the initiator of the
3988 SILC_TASK_CALLBACK(silc_server_rekey_callback)
3990 SilcSocketConnection sock = (SilcSocketConnection)context;
3991 SilcIDListData idata = (SilcIDListData)sock->user_data;
3992 SilcServer server = (SilcServer)idata->rekey->context;
3993 SilcProtocol protocol;
3994 SilcServerRekeyInternalContext *proto_ctx;
3996 SILC_LOG_DEBUG(("Start"));
3998 /* Allocate internal protocol context. This is sent as context
4000 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4001 proto_ctx->server = (void *)server;
4002 proto_ctx->sock = sock;
4003 proto_ctx->responder = FALSE;
4004 proto_ctx->pfs = idata->rekey->pfs;
4006 /* Perform rekey protocol. Will call the final callback after the
4007 protocol is over. */
4008 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4009 &protocol, proto_ctx, silc_server_rekey_final);
4010 sock->protocol = protocol;
4012 /* Run the protocol */
4013 silc_protocol_execute(protocol, server->schedule, 0, 0);
4015 /* Re-register re-key timeout */
4016 silc_schedule_task_add(server->schedule, sock->sock,
4017 silc_server_rekey_callback,
4018 context, idata->rekey->timeout, 0,
4019 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4022 /* The final callback for the REKEY protocol. This will actually take the
4023 new key material into use. */
4025 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4027 SilcProtocol protocol = (SilcProtocol)context;
4028 SilcServerRekeyInternalContext *ctx =
4029 (SilcServerRekeyInternalContext *)protocol->context;
4030 SilcServer server = (SilcServer)ctx->server;
4031 SilcSocketConnection sock = ctx->sock;
4033 SILC_LOG_DEBUG(("Start"));
4035 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4036 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4037 /* Error occured during protocol */
4038 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4039 silc_protocol_cancel(protocol, server->schedule);
4040 silc_protocol_free(protocol);
4041 sock->protocol = NULL;
4043 silc_packet_context_free(ctx->packet);
4045 silc_ske_free(ctx->ske);
4050 /* Purge the outgoing data queue to assure that all rekey packets really
4051 go to the network before we quit the protocol. */
4052 silc_server_packet_queue_purge(server, sock);
4055 silc_protocol_free(protocol);
4056 sock->protocol = NULL;
4058 silc_packet_context_free(ctx->packet);
4060 silc_ske_free(ctx->ske);