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 /* Allocate PKCS context for local public and private keys */
167 silc_pkcs_alloc(server->public_key->name, &server->pkcs);
168 silc_pkcs_public_key_set(server->pkcs, server->public_key);
169 silc_pkcs_private_key_set(server->pkcs, server->private_key);
171 /* Create a listening server. Note that our server can listen on multiple
172 ports. All listeners are created here and now. */
174 listen = server->config->listen_port;
178 tmp = silc_net_create_server(server->config->listen_port->port,
179 server->config->listen_port->listener_ip);
182 SILC_LOG_ERROR(("Could not create server listener: %s on %d",
183 server->config->listen_port->listener_ip,
184 server->config->listen_port->port));
188 sock = silc_realloc(sock, sizeof(*sock) * (sock_count + 1));
189 sock[sock_count] = tmp;
191 listen = listen->next;
194 /* Initialize ID caches */
195 server->local_list->clients =
196 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
197 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
198 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
200 /* These are allocated for normal server as well as these hold some
201 global information that the server has fetched from its router. For
202 router these are used as they are supposed to be used on router. */
203 server->global_list->clients =
204 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
205 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
206 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
208 /* Allocate the entire socket list that is used in server. Eventually
209 all connections will have entry in this table (it is a table of
210 pointers to the actual object that is allocated individually
212 server->sockets = silc_calloc(SILC_SERVER_MAX_CONNECTIONS,
213 sizeof(*server->sockets));
215 for (i = 0; i < sock_count; i++) {
216 SilcSocketConnection newsocket = NULL;
218 /* Set socket to non-blocking mode */
219 silc_net_set_socket_nonblock(sock[i]);
220 server->sock = sock[i];
222 /* Add ourselves also to the socket table. The entry allocated above
223 is sent as argument for fast referencing in the future. */
224 silc_socket_alloc(sock[i], SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
225 server->sockets[sock[i]] = newsocket;
227 /* Perform name and address lookups to resolve the listenning address
229 if (!silc_net_check_local_by_sock(sock[i], &newsocket->hostname,
231 if ((server->params->require_reverse_mapping && !newsocket->hostname) ||
233 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
234 newsocket->hostname ? newsocket->hostname :
235 newsocket->ip ? newsocket->ip : ""));
236 server->stat.conn_failures++;
239 if (!newsocket->hostname)
240 newsocket->hostname = strdup(newsocket->ip);
242 newsocket->port = silc_net_get_local_port(sock[i]);
244 /* Create a Server ID for the server. */
245 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
250 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
251 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
252 server->id_type = SILC_ID_SERVER;
253 server->server_name = server->config->server_info->server_name;
255 /* Add ourselves to the server list. We don't have a router yet
256 beacuse we haven't established a route yet. It will be done later.
257 For now, NULL is sent as router. This allocates new entry to
260 silc_idlist_add_server(server->local_list,
261 server->config->server_info->server_name,
262 server->server_type, server->id, NULL, NULL);
264 SILC_LOG_ERROR(("Could not add ourselves to cache"));
267 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
269 /* Put the allocated socket pointer also to the entry allocated above
270 for fast back-referencing to the socket list. */
271 newsocket->user_data = (void *)id_entry;
272 id_entry->connection = (void *)newsocket;
273 server->id_entry = id_entry;
276 /* Register protocols */
277 silc_server_protocols_register();
279 /* Initialize the scheduler. */
280 server->schedule = silc_schedule_init(SILC_SERVER_MAX_CONNECTIONS);
281 if (!server->schedule)
284 /* Add the first task to the scheduler. This is task that is executed by
285 timeout. It expires as soon as the caller calls silc_server_run. This
286 task performs authentication protocol and key exchange with our
288 silc_schedule_task_add(server->schedule, sock[0],
289 silc_server_connect_to_router,
290 (void *)server, 0, 1,
292 SILC_TASK_PRI_NORMAL);
294 /* Add listener task to the scheduler. This task receives new connections
295 to the server. This task remains on the queue until the end of the
297 silc_schedule_task_add(server->schedule, sock[0],
298 silc_server_accept_new_connection,
299 (void *)server, 0, 0,
301 SILC_TASK_PRI_NORMAL);
302 server->listenning = TRUE;
304 /* Send log file configuration */
305 silc_server_config_setlogfiles(server->config, server->schedule);
307 /* If server connections has been configured then we must be router as
308 normal server cannot have server connections, only router connections. */
309 if (server->config->servers) {
310 SilcServerConfigSectionServerConnection *ptr = server->config->servers;
312 server->server_type = SILC_ROUTER;
314 if (ptr->backup_router) {
315 server->server_type = SILC_BACKUP_ROUTER;
316 server->backup_router = TRUE;
317 server->id_entry->server_type = SILC_BACKUP_ROUTER;
324 /* Register the ID Cache purge task. This periodically purges the ID cache
325 and removes the expired cache entries. */
327 /* Clients local list */
328 purge = silc_calloc(1, sizeof(*purge));
329 purge->cache = server->local_list->clients;
330 purge->schedule = server->schedule;
331 purge->timeout = 600;
332 silc_schedule_task_add(purge->schedule, 0,
334 (void *)purge, purge->timeout, 0,
335 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
337 /* Clients global list */
338 purge = silc_calloc(1, sizeof(*purge));
339 purge->cache = server->global_list->clients;
340 purge->schedule = server->schedule;
341 purge->timeout = 300;
342 silc_schedule_task_add(purge->schedule, 0,
344 (void *)purge, purge->timeout, 0,
345 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
347 SILC_LOG_DEBUG(("Server initialized"));
349 /* We are done here, return succesfully */
353 for (i = 0; i < sock_count; i++)
354 silc_net_close_server(sock[i]);
359 /* Fork server to background */
361 void silc_server_daemonise(SilcServer server)
365 SILC_LOG_DEBUG(("Forking SILC server to background"));
370 SILC_LOG_DEBUG(("fork() failed, cannot proceed"));
375 SILC_LOG_DEBUG(("Server started as user"));
377 SILC_LOG_DEBUG(("Server started as root. Dropping privileges."));
383 /* Drop root privligies. If this cannot be done, die. */
385 void silc_server_drop(SilcServer server)
387 /* Are we executing silcd as root or a regular user? */
393 if (!server->config->identity || !server->config->identity->user ||
394 !server->config->identity->group) {
395 fprintf(stderr, "Error:"
396 "\tSILC server must not be run as root. For the security of your\n"
397 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
398 "\tuser account. Modify the [Identity] configuration section to run\n"
399 "\tthe server as non-root user.\n");
403 /* Get the values given for user and group in configuration file */
404 user=server->config->identity->user;
405 group=server->config->identity->group;
407 /* Check whether the user/group information is text */
408 if (atoi(user)!=0 || atoi(group)!=0) {
409 SILC_LOG_DEBUG(("Invalid user and/or group information"));
410 SILC_LOG_DEBUG(("User and/or group given as number"));
411 fprintf(stderr, "Invalid user and/or group information\n");
412 fprintf(stderr, "Please assign them as names, not numbers\n");
416 /* Catch the nasty incident of string "0" returning 0 from atoi */
417 if (strcmp("0", user)==0 || strcmp("0", group)==0) {
418 SILC_LOG_DEBUG(("User and/or group configured to 0. Unacceptable"));
419 fprintf(stderr, "User and/or group configured to 0. Exiting\n");
423 if (!(pw=getpwnam(user))) {
424 fprintf(stderr, "No such user %s found\n", user);
428 if (!(gr=getgrnam(group))) {
429 fprintf(stderr, "No such group %s found\n", group);
433 /* Check whether user and/or group is set to root. If yes, exit
434 immediately. Otherwise, setgid and setuid server to user.group */
435 if (gr->gr_gid==0 || pw->pw_uid==0) {
436 fprintf(stderr, "Error:"
437 "\tSILC server must not be run as root. For the security of your\n"
438 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
439 "\tuser account. Modify the [Identity] configuration section to run\n"
440 "\tthe server as non-root user.\n");
443 SILC_LOG_DEBUG(("Changing to group %s", group));
444 if (setgid(gr->gr_gid)==0) {
445 SILC_LOG_DEBUG(("Setgid to %s", group));
447 SILC_LOG_DEBUG(("Setgid to %s failed", group));
448 fprintf(stderr, "Tried to setgid %s but no such group. Exiting\n",
452 #if defined HAVE_SETGROUPS && defined HAVE_INITGROUPS
453 if (setgroups(0, NULL)!=0) {
454 SILC_LOG_DEBUG(("Setgroups to NULL failed"));
455 fprintf(stderr, "Tried to setgroups NULL but failed. Exiting\n");
458 if (initgroups(user, gr->gr_gid)!=0) {
459 SILC_LOG_DEBUG(("Initgroups to user %s (gid=%d) failed", user, gr->gr_gid));
460 fprintf(stderr, "Tried to initgroups %s (gid=%d) but no such user. Exiting\n",
465 SILC_LOG_DEBUG(("Changing to user %s", user));
466 if (setuid(pw->pw_uid)==0) {
467 SILC_LOG_DEBUG(("Setuid to %s", user));
469 SILC_LOG_DEBUG(("Setuid to %s failed", user));
470 fprintf(stderr, "Tried to setuid %s but no such user. Exiting\n",
478 /* The heart of the server. This runs the scheduler thus runs the server.
479 When this returns the server has been stopped and the program will
482 void silc_server_run(SilcServer server)
484 SILC_LOG_DEBUG(("Running server"));
486 SILC_LOG_INFO(("SILC Server started"));
488 /* Start the scheduler, the heart of the SILC server. When this returns
489 the program will be terminated. */
490 silc_schedule(server->schedule);
493 /* Stops the SILC server. This function is used to shutdown the server.
494 This is usually called after the scheduler has returned. After stopping
495 the server one should call silc_server_free. */
497 void silc_server_stop(SilcServer server)
499 SILC_LOG_DEBUG(("Stopping server"));
501 if (server->schedule) {
502 silc_schedule_stop(server->schedule);
503 silc_schedule_uninit(server->schedule);
504 server->schedule = NULL;
507 silc_server_protocols_unregister();
509 SILC_LOG_DEBUG(("Server stopped"));
512 /* Function that is called when the network connection to a router has
513 been established. This will continue with the key exchange protocol
514 with the remote router. */
516 void silc_server_start_key_exchange(SilcServer server,
517 SilcServerConnection sconn,
520 SilcSocketConnection newsocket;
521 SilcProtocol protocol;
522 SilcServerKEInternalContext *proto_ctx;
525 /* Cancel any possible retry timeouts */
526 silc_schedule_task_del_by_callback(server->schedule,
527 silc_server_connect_router);
529 /* Set socket options */
530 silc_net_set_socket_nonblock(sock);
531 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
533 /* Create socket connection for the connection. Even though we
534 know that we are connecting to a router we will mark the socket
535 to be unknown connection until we have executed authentication
537 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
538 server->sockets[sock] = newsocket;
539 newsocket->hostname = strdup(sconn->remote_host);
540 newsocket->ip = strdup(sconn->remote_host);
541 newsocket->port = sconn->remote_port;
542 sconn->sock = newsocket;
544 /* Allocate internal protocol context. This is sent as context
546 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
547 proto_ctx->server = (void *)server;
548 proto_ctx->context = (void *)sconn;
549 proto_ctx->sock = newsocket;
550 proto_ctx->rng = server->rng;
551 proto_ctx->responder = FALSE;
553 /* Perform key exchange protocol. silc_server_connect_to_router_second
554 will be called after the protocol is finished. */
555 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
556 &protocol, proto_ctx,
557 silc_server_connect_to_router_second);
558 newsocket->protocol = protocol;
560 /* Register a timeout task that will be executed if the protocol
561 is not executed within set limit. */
562 proto_ctx->timeout_task =
563 silc_schedule_task_add(server->schedule, sock,
564 silc_server_timeout_remote,
565 server, server->params->protocol_timeout,
566 server->params->protocol_timeout_usec,
570 /* Register the connection for network input and output. This sets
571 that scheduler will listen for incoming packets for this connection
572 and sets that outgoing packets may be sent to this connection as
573 well. However, this doesn't set the scheduler for outgoing traffic,
574 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
575 later when outgoing data is available. */
576 context = (void *)server;
577 SILC_REGISTER_CONNECTION_FOR_IO(sock);
579 /* Run the protocol */
580 silc_protocol_execute(protocol, server->schedule, 0, 0);
583 /* Timeout callback that will be called to retry connecting to remote
584 router. This is used by both normal and router server. This will wait
585 before retrying the connecting. The timeout is generated by exponential
586 backoff algorithm. */
588 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
590 SilcServerConnection sconn = (SilcServerConnection)context;
591 SilcServer server = sconn->server;
593 SILC_LOG_INFO(("Retrying connecting to a router"));
595 /* Calculate next timeout */
596 if (sconn->retry_count >= 1) {
597 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
598 if (sconn->retry_timeout > SILC_SERVER_RETRY_INTERVAL_MAX)
599 sconn->retry_timeout = SILC_SERVER_RETRY_INTERVAL_MAX;
601 sconn->retry_timeout = server->params->retry_interval_min;
603 sconn->retry_count++;
604 sconn->retry_timeout = sconn->retry_timeout +
605 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
607 /* If we've reached max retry count, give up. */
608 if (sconn->retry_count > server->params->retry_count &&
609 server->params->retry_keep_trying == FALSE) {
610 SILC_LOG_ERROR(("Could not connect to router, giving up"));
611 silc_free(sconn->remote_host);
616 /* Wait one before retrying */
617 silc_schedule_task_add(server->schedule, fd, silc_server_connect_router,
618 context, sconn->retry_timeout,
619 server->params->retry_interval_min_usec,
620 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
623 /* Generic routine to use connect to a router. */
625 SILC_TASK_CALLBACK(silc_server_connect_router)
627 SilcServerConnection sconn = (SilcServerConnection)context;
628 SilcServer server = sconn->server;
631 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
632 (sconn->backup ? "backup router" : "router"),
633 sconn->remote_host, sconn->remote_port));
635 server->router_connect = time(0);
637 /* Connect to remote host */
638 sock = silc_net_create_connection(server->config->listen_port->local_ip,
642 SILC_LOG_ERROR(("Could not connect to router %s:%d",
643 sconn->remote_host, sconn->remote_port));
644 if (!sconn->no_reconnect)
645 silc_schedule_task_add(server->schedule, fd,
646 silc_server_connect_to_router_retry,
647 context, 0, 1, SILC_TASK_TIMEOUT,
648 SILC_TASK_PRI_NORMAL);
652 /* Continue with key exchange protocol */
653 silc_server_start_key_exchange(server, sconn, sock);
656 /* This function connects to our primary router or if we are a router this
657 establishes all our primary routes. This is called at the start of the
658 server to do authentication and key exchange with our router - called
661 SILC_TASK_CALLBACK(silc_server_connect_to_router)
663 SilcServer server = (SilcServer)context;
664 SilcServerConnection sconn;
665 SilcServerConfigSectionServerConnection *ptr;
667 SILC_LOG_DEBUG(("Connecting to router(s)"));
669 if (server->server_type == SILC_SERVER) {
670 SILC_LOG_DEBUG(("We are normal server"));
671 } else if (server->server_type == SILC_ROUTER) {
672 SILC_LOG_DEBUG(("We are router"));
674 SILC_LOG_DEBUG(("We are backup router/normal server"));
677 /* Create the connections to all our routes */
678 ptr = server->config->routers;
681 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
682 ptr->backup_router ? "Backup router" : "Router",
683 ptr->initiator ? "Initiator" : "Responder",
684 ptr->host, ptr->port));
686 if (ptr->initiator) {
687 /* Allocate connection object for hold connection specific stuff. */
688 sconn = silc_calloc(1, sizeof(*sconn));
689 sconn->server = server;
690 sconn->remote_host = strdup(ptr->host);
691 sconn->remote_port = ptr->port;
692 sconn->backup = ptr->backup_router;
694 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
695 sconn->backup_replace_port = ptr->backup_replace_port;
698 if (!server->router_conn && !sconn->backup)
699 server->router_conn = sconn;
701 silc_schedule_task_add(server->schedule, fd,
702 silc_server_connect_router,
703 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
704 SILC_TASK_PRI_NORMAL);
713 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
715 /* There wasn't a configured router, we will continue but we don't
716 have a connection to outside world. We will be standalone server. */
717 server->standalone = TRUE;
720 /* Second part of connecting to router(s). Key exchange protocol has been
721 executed and now we will execute authentication protocol. */
723 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
725 SilcProtocol protocol = (SilcProtocol)context;
726 SilcServerKEInternalContext *ctx =
727 (SilcServerKEInternalContext *)protocol->context;
728 SilcServer server = (SilcServer)ctx->server;
729 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
730 SilcSocketConnection sock = ctx->sock;
731 SilcServerConnAuthInternalContext *proto_ctx;
732 SilcServerConfigSectionServerConnection *conn = NULL;
734 SILC_LOG_DEBUG(("Start"));
736 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
737 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
738 /* Error occured during protocol */
739 silc_protocol_free(protocol);
740 sock->protocol = NULL;
741 silc_ske_free_key_material(ctx->keymat);
743 silc_packet_context_free(ctx->packet);
745 silc_ske_free(ctx->ske);
746 silc_free(ctx->dest_id);
748 silc_schedule_task_del_by_callback(server->schedule,
749 silc_server_failure_callback);
750 silc_server_disconnect_remote(server, sock, "Server closed connection: "
751 "Key exchange failed");
755 /* We now have the key material as the result of the key exchange
756 protocol. Take the key material into use. Free the raw key material
757 as soon as we've set them into use. */
758 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
759 ctx->sock, ctx->keymat,
760 ctx->ske->prop->cipher,
761 ctx->ske->prop->pkcs,
762 ctx->ske->prop->hash,
763 ctx->ske->prop->hmac,
764 ctx->ske->prop->group,
766 silc_protocol_free(protocol);
767 sock->protocol = NULL;
768 silc_ske_free_key_material(ctx->keymat);
770 silc_packet_context_free(ctx->packet);
772 silc_ske_free(ctx->ske);
773 silc_free(ctx->dest_id);
775 silc_schedule_task_del_by_callback(server->schedule,
776 silc_server_failure_callback);
777 silc_server_disconnect_remote(server, sock, "Server closed connection: "
778 "Key exchange failed");
781 silc_ske_free_key_material(ctx->keymat);
783 /* Allocate internal context for the authentication protocol. This
784 is sent as context for the protocol. */
785 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
786 proto_ctx->server = (void *)server;
787 proto_ctx->context = (void *)sconn;
788 proto_ctx->sock = sock;
789 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
790 proto_ctx->dest_id_type = ctx->dest_id_type;
791 proto_ctx->dest_id = ctx->dest_id;
793 /* Resolve the authentication method used in this connection. Check if
794 we find a match from user configured connections */
795 conn = silc_server_config_find_router_conn(server->config,
799 /* Match found. Use the configured authentication method */
800 proto_ctx->auth_meth = conn->auth_meth;
801 if (conn->auth_data) {
802 proto_ctx->auth_data = strdup(conn->auth_data);
803 proto_ctx->auth_data_len = strlen(conn->auth_data);
806 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
807 sock->hostname, sock->ip, sock->port));
808 silc_protocol_free(protocol);
809 sock->protocol = NULL;
811 silc_packet_context_free(ctx->packet);
813 silc_ske_free(ctx->ske);
814 silc_free(ctx->dest_id);
816 silc_schedule_task_del_by_callback(server->schedule,
817 silc_server_failure_callback);
818 silc_server_disconnect_remote(server, sock, "Server closed connection: "
819 "Key exchange failed");
823 /* Free old protocol as it is finished now */
824 silc_protocol_free(protocol);
826 silc_packet_context_free(ctx->packet);
828 sock->protocol = NULL;
830 /* Allocate the authentication protocol. This is allocated here
831 but we won't start it yet. We will be receiving party of this
832 protocol thus we will wait that connecting party will make
834 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
835 &sock->protocol, proto_ctx,
836 silc_server_connect_to_router_final);
838 /* Register timeout task. If the protocol is not executed inside
839 this timelimit the connection will be terminated. Currently
840 this is 15 seconds and is hard coded limit (XXX). */
841 proto_ctx->timeout_task =
842 silc_schedule_task_add(server->schedule, sock->sock,
843 silc_server_timeout_remote,
844 (void *)server, 15, 0,
848 /* Run the protocol */
849 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
852 /* Finalizes the connection to router. Registers a server task to the
853 queue so that we can accept new connections. */
855 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
857 SilcProtocol protocol = (SilcProtocol)context;
858 SilcServerConnAuthInternalContext *ctx =
859 (SilcServerConnAuthInternalContext *)protocol->context;
860 SilcServer server = (SilcServer)ctx->server;
861 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
862 SilcSocketConnection sock = ctx->sock;
863 SilcServerEntry id_entry;
865 SilcServerHBContext hb_context;
866 unsigned char *id_string;
868 SilcIDListData idata;
870 SILC_LOG_DEBUG(("Start"));
872 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
873 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
874 /* Error occured during protocol */
875 silc_free(ctx->dest_id);
876 silc_server_disconnect_remote(server, sock, "Server closed connection: "
877 "Authentication failed");
881 /* Add a task to the queue. This task receives new connections to the
882 server. This task remains on the queue until the end of the program. */
883 if (!server->listenning && !sconn->backup) {
884 silc_schedule_task_add(server->schedule, server->sock,
885 silc_server_accept_new_connection,
886 (void *)server, 0, 0,
888 SILC_TASK_PRI_NORMAL);
889 server->listenning = TRUE;
892 /* Send NEW_SERVER packet to the router. We will become registered
893 to the SILC network after sending this packet. */
894 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
895 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
896 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
897 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
898 silc_buffer_format(packet,
899 SILC_STR_UI_SHORT(id_len),
900 SILC_STR_UI_XNSTRING(id_string, id_len),
901 SILC_STR_UI_SHORT(strlen(server->server_name)),
902 SILC_STR_UI_XNSTRING(server->server_name,
903 strlen(server->server_name)),
906 /* Send the packet */
907 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
908 packet->data, packet->len, TRUE);
909 silc_buffer_free(packet);
910 silc_free(id_string);
912 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
914 /* Check that we do not have this ID already */
915 id_entry = silc_idlist_find_server_by_id(server->local_list,
916 ctx->dest_id, TRUE, NULL);
918 silc_idcache_del_by_context(server->local_list->servers, id_entry);
920 id_entry = silc_idlist_find_server_by_id(server->global_list,
921 ctx->dest_id, TRUE, NULL);
923 silc_idcache_del_by_context(server->global_list->servers, id_entry);
926 SILC_LOG_DEBUG(("New server id(%s)",
927 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
929 /* Add the connected router to global server list */
930 id_entry = silc_idlist_add_server(server->global_list,
931 strdup(sock->hostname),
932 SILC_ROUTER, ctx->dest_id, NULL, sock);
934 silc_free(ctx->dest_id);
935 silc_server_disconnect_remote(server, sock, "Server closed connection: "
936 "Authentication failed");
940 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
941 silc_free(sock->user_data);
942 sock->user_data = (void *)id_entry;
943 sock->type = SILC_SOCKET_TYPE_ROUTER;
944 idata = (SilcIDListData)sock->user_data;
945 idata->status |= SILC_IDLIST_STATUS_REGISTERED;
947 /* Perform keepalive. The `hb_context' will be freed automatically
948 when finally calling the silc_socket_free function. XXX hardcoded
950 hb_context = silc_calloc(1, sizeof(*hb_context));
951 hb_context->server = server;
952 silc_socket_set_heartbeat(sock, 300, hb_context,
953 silc_server_perform_heartbeat,
956 /* Register re-key timeout */
957 idata->rekey->timeout = 3600; /* XXX hardcoded */
958 idata->rekey->context = (void *)server;
959 silc_schedule_task_add(server->schedule, sock->sock,
960 silc_server_rekey_callback,
961 (void *)sock, idata->rekey->timeout, 0,
962 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
964 if (!sconn->backup) {
965 /* Mark this router our primary router if we're still standalone */
966 if (server->standalone) {
967 server->id_entry->router = id_entry;
968 server->router = id_entry;
969 server->standalone = FALSE;
971 /* If we are router then announce our possible servers. */
972 if (server->server_type == SILC_ROUTER)
973 silc_server_announce_servers(server, FALSE, 0,
974 server->router->connection);
976 /* Announce our clients and channels to the router */
977 silc_server_announce_clients(server, 0, server->router->connection);
978 silc_server_announce_channels(server, 0, server->router->connection);
981 /* Add this server to be our backup router */
982 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
983 sconn->backup_replace_port, FALSE);
986 sock->protocol = NULL;
988 /* Call the completion callback to indicate that we've connected to
991 (*sconn->callback)(server, id_entry, sconn->callback_context);
994 /* Free the temporary connection data context */
996 silc_free(sconn->remote_host);
997 silc_free(sconn->backup_replace_ip);
1000 if (sconn == server->router_conn)
1001 server->router_conn = NULL;
1003 /* Free the protocol object */
1004 if (sock->protocol == protocol)
1005 sock->protocol = NULL;
1006 silc_protocol_free(protocol);
1008 silc_packet_context_free(ctx->packet);
1010 silc_ske_free(ctx->ske);
1011 silc_free(ctx->auth_data);
1015 /* Host lookup callbcak that is called after the incoming connection's
1016 IP and FQDN lookup is performed. This will actually check the acceptance
1017 of the incoming connection and will register the key exchange protocol
1018 for this connection. */
1021 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1024 SilcServer server = (SilcServer)context;
1025 SilcServerKEInternalContext *proto_ctx;
1026 void *cconfig, *sconfig, *rconfig;
1027 SilcServerConfigSectionDenyConnection *deny;
1030 SILC_LOG_DEBUG(("Start"));
1032 /* Check whether we could resolve both IP and FQDN. */
1033 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1034 server->params->require_reverse_mapping)) {
1035 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1036 sock->hostname ? sock->hostname :
1037 sock->ip ? sock->ip : ""));
1038 server->stat.conn_failures++;
1039 silc_server_disconnect_remote(server, sock,
1040 "Server closed connection: Unknown host");
1044 /* Register the connection for network input and output. This sets
1045 that scheduler will listen for incoming packets for this connection
1046 and sets that outgoing packets may be sent to this connection as well.
1047 However, this doesn't set the scheduler for outgoing traffic, it
1048 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1049 later when outgoing data is available. */
1050 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1052 SILC_LOG_INFO(("Incoming connection from %s (%s)", sock->hostname,
1055 port = server->sockets[server->sock]->port; /* Listenning port */
1057 /* Check whether this connection is denied to connect to us. */
1058 deny = silc_server_config_denied_conn(server->config, sock->ip, port);
1060 deny = silc_server_config_denied_conn(server->config, sock->hostname,
1063 /* The connection is denied */
1064 SILC_LOG_INFO(("Connection %s (%s) is denied",
1065 sock->hostname, sock->ip));
1066 silc_server_disconnect_remote(server, sock, deny->comment ?
1068 "Server closed connection: "
1069 "Connection refused");
1070 server->stat.conn_failures++;
1074 /* Check whether we have configred this sort of connection at all. We
1075 have to check all configurations since we don't know what type of
1076 connection this is. */
1077 if (!(cconfig = silc_server_config_find_client_conn(server->config,
1079 cconfig = silc_server_config_find_client_conn(server->config,
1082 if (!(sconfig = silc_server_config_find_server_conn(server->config,
1085 sconfig = silc_server_config_find_server_conn(server->config,
1088 if (!(rconfig = silc_server_config_find_router_conn(server->config,
1090 rconfig = silc_server_config_find_router_conn(server->config,
1093 if (!cconfig && !sconfig && !rconfig) {
1094 SILC_LOG_INFO(("Connection %s (%s) is not allowed",
1095 sock->hostname, sock->ip));
1096 silc_server_disconnect_remote(server, sock,
1097 "Server closed connection: "
1098 "Connection refused");
1099 server->stat.conn_failures++;
1103 /* The connection is allowed */
1105 /* Allocate internal context for key exchange protocol. This is
1106 sent as context for the protocol. */
1107 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1108 proto_ctx->server = context;
1109 proto_ctx->sock = sock;
1110 proto_ctx->rng = server->rng;
1111 proto_ctx->responder = TRUE;
1112 proto_ctx->cconfig = cconfig;
1113 proto_ctx->sconfig = sconfig;
1114 proto_ctx->rconfig = rconfig;
1116 /* Prepare the connection for key exchange protocol. We allocate the
1117 protocol but will not start it yet. The connector will be the
1118 initiator of the protocol thus we will wait for initiation from
1119 there before we start the protocol. */
1120 server->stat.auth_attempts++;
1121 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1122 &sock->protocol, proto_ctx,
1123 silc_server_accept_new_connection_second);
1125 /* Register a timeout task that will be executed if the connector
1126 will not start the key exchange protocol within 60 seconds. For
1127 now, this is a hard coded limit. After 60 secs the connection will
1128 be closed if the key exchange protocol has not been started. */
1129 proto_ctx->timeout_task =
1130 silc_schedule_task_add(server->schedule, sock->sock,
1131 silc_server_timeout_remote,
1137 /* Accepts new connections to the server. Accepting new connections are
1138 done in three parts to make it async. */
1140 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1142 SilcServer server = (SilcServer)context;
1143 SilcSocketConnection newsocket;
1146 SILC_LOG_DEBUG(("Accepting new connection"));
1148 server->stat.conn_attempts++;
1150 sock = silc_net_accept_connection(server->sock);
1152 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1153 server->stat.conn_failures++;
1157 /* Check max connections */
1158 if (sock > SILC_SERVER_MAX_CONNECTIONS) {
1159 SILC_LOG_ERROR(("Refusing connection, server is full"));
1160 server->stat.conn_failures++;
1164 /* Set socket options */
1165 silc_net_set_socket_nonblock(sock);
1166 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1168 /* We don't create a ID yet, since we don't know what type of connection
1169 this is yet. But, we do add the connection to the socket table. */
1170 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1171 server->sockets[sock] = newsocket;
1173 /* Perform asynchronous host lookup. This will lookup the IP and the
1174 FQDN of the remote connection. After the lookup is done the connection
1175 is accepted further. */
1176 silc_socket_host_lookup(newsocket, TRUE,
1177 silc_server_accept_new_connection_lookup, context,
1181 /* Second part of accepting new connection. Key exchange protocol has been
1182 performed and now it is time to do little connection authentication
1183 protocol to figure out whether this connection is client or server
1184 and whether it has right to access this server (especially server
1185 connections needs to be authenticated). */
1187 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1189 SilcProtocol protocol = (SilcProtocol)context;
1190 SilcServerKEInternalContext *ctx =
1191 (SilcServerKEInternalContext *)protocol->context;
1192 SilcServer server = (SilcServer)ctx->server;
1193 SilcSocketConnection sock = ctx->sock;
1194 SilcServerConnAuthInternalContext *proto_ctx;
1196 SILC_LOG_DEBUG(("Start"));
1198 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1199 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1200 /* Error occured during protocol */
1201 silc_protocol_free(protocol);
1202 sock->protocol = NULL;
1203 silc_ske_free_key_material(ctx->keymat);
1205 silc_packet_context_free(ctx->packet);
1207 silc_ske_free(ctx->ske);
1208 silc_free(ctx->dest_id);
1210 silc_schedule_task_del_by_callback(server->schedule,
1211 silc_server_failure_callback);
1212 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1213 "Key exchange failed");
1214 server->stat.auth_failures++;
1218 /* We now have the key material as the result of the key exchange
1219 protocol. Take the key material into use. Free the raw key material
1220 as soon as we've set them into use. */
1221 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1222 ctx->sock, ctx->keymat,
1223 ctx->ske->prop->cipher,
1224 ctx->ske->prop->pkcs,
1225 ctx->ske->prop->hash,
1226 ctx->ske->prop->hmac,
1227 ctx->ske->prop->group,
1229 silc_protocol_free(protocol);
1230 sock->protocol = NULL;
1231 silc_ske_free_key_material(ctx->keymat);
1233 silc_packet_context_free(ctx->packet);
1235 silc_ske_free(ctx->ske);
1236 silc_free(ctx->dest_id);
1238 silc_schedule_task_del_by_callback(server->schedule,
1239 silc_server_failure_callback);
1240 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1241 "Key exchange failed");
1242 server->stat.auth_failures++;
1245 silc_ske_free_key_material(ctx->keymat);
1247 /* Allocate internal context for the authentication protocol. This
1248 is sent as context for the protocol. */
1249 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1250 proto_ctx->server = (void *)server;
1251 proto_ctx->sock = sock;
1252 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1253 proto_ctx->responder = TRUE;
1254 proto_ctx->dest_id_type = ctx->dest_id_type;
1255 proto_ctx->dest_id = ctx->dest_id;
1256 proto_ctx->cconfig = ctx->cconfig;
1257 proto_ctx->sconfig = ctx->sconfig;
1258 proto_ctx->rconfig = ctx->rconfig;
1260 /* Free old protocol as it is finished now */
1261 silc_protocol_free(protocol);
1263 silc_packet_context_free(ctx->packet);
1265 sock->protocol = NULL;
1267 /* Allocate the authentication protocol. This is allocated here
1268 but we won't start it yet. We will be receiving party of this
1269 protocol thus we will wait that connecting party will make
1270 their first move. */
1271 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1272 &sock->protocol, proto_ctx,
1273 silc_server_accept_new_connection_final);
1275 /* Register timeout task. If the protocol is not executed inside
1276 this timelimit the connection will be terminated. Currently
1277 this is 60 seconds and is hard coded limit (XXX). */
1278 proto_ctx->timeout_task =
1279 silc_schedule_task_add(server->schedule, sock->sock,
1280 silc_server_timeout_remote,
1281 (void *)server, 60, 0,
1286 /* Final part of accepting new connection. The connection has now
1287 been authenticated and keys has been exchanged. We also know whether
1288 this is client or server connection. */
1290 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1292 SilcProtocol protocol = (SilcProtocol)context;
1293 SilcServerConnAuthInternalContext *ctx =
1294 (SilcServerConnAuthInternalContext *)protocol->context;
1295 SilcServer server = (SilcServer)ctx->server;
1296 SilcSocketConnection sock = ctx->sock;
1297 SilcServerHBContext hb_context;
1298 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1301 SILC_LOG_DEBUG(("Start"));
1303 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1304 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1305 /* Error occured during protocol */
1306 silc_protocol_free(protocol);
1307 sock->protocol = NULL;
1309 silc_packet_context_free(ctx->packet);
1311 silc_ske_free(ctx->ske);
1312 silc_free(ctx->dest_id);
1314 silc_schedule_task_del_by_callback(server->schedule,
1315 silc_server_failure_callback);
1316 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1317 "Authentication failed");
1318 server->stat.auth_failures++;
1322 entry->data.last_receive = time(NULL);
1324 switch (ctx->conn_type) {
1325 case SILC_SOCKET_TYPE_CLIENT:
1327 SilcClientEntry client;
1329 SILC_LOG_DEBUG(("Remote host is client"));
1330 SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
1333 /* Add the client to the client ID cache. The nickname and Client ID
1334 and other information is created after we have received NEW_CLIENT
1335 packet from client. */
1336 client = silc_idlist_add_client(server->local_list,
1337 NULL, NULL, NULL, NULL, NULL, sock, 0);
1339 SILC_LOG_ERROR(("Could not add new client to cache"));
1340 silc_free(sock->user_data);
1341 silc_server_disconnect_remote(server, sock,
1342 "Server closed connection: "
1343 "Authentication failed");
1344 server->stat.auth_failures++;
1349 server->stat.my_clients++;
1350 server->stat.clients++;
1351 if (server->server_type == SILC_ROUTER)
1352 server->stat.cell_clients++;
1354 id_entry = (void *)client;
1357 case SILC_SOCKET_TYPE_SERVER:
1358 case SILC_SOCKET_TYPE_ROUTER:
1360 SilcServerEntry new_server;
1361 SilcServerConfigSectionServerConnection *conn =
1362 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1363 ctx->sconfig : ctx->rconfig;
1365 SILC_LOG_DEBUG(("Remote host is %s",
1366 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1367 "server" : (conn->backup_router ?
1368 "backup router" : "router")));
1369 SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
1370 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1371 "server" : (conn->backup_router ?
1372 "backup router" : "router")));
1374 /* Add the server into server cache. The server name and Server ID
1375 is updated after we have received NEW_SERVER packet from the
1376 server. We mark ourselves as router for this server if we really
1379 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1380 server->local_list : (conn->backup_router ?
1381 server->local_list :
1382 server->global_list)),
1384 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1385 SILC_SERVER : SILC_ROUTER),
1387 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1388 server->id_entry : (conn->backup_router ?
1389 server->id_entry : NULL)),
1392 SILC_LOG_ERROR(("Could not add new server to cache"));
1393 silc_free(sock->user_data);
1394 silc_server_disconnect_remote(server, sock,
1395 "Server closed connection: "
1396 "Authentication failed");
1397 server->stat.auth_failures++;
1402 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1403 server->stat.my_servers++;
1405 server->stat.my_routers++;
1406 server->stat.servers++;
1408 id_entry = (void *)new_server;
1410 /* If the incoming connection is router and marked as backup router
1411 then add it to be one of our backups */
1412 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && conn->backup_router) {
1413 silc_server_backup_add(server, new_server, conn->backup_replace_ip,
1414 conn->backup_replace_port, conn->backup_local);
1416 /* Change it back to SERVER type since that's what it really is. */
1417 if (conn->backup_local)
1418 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1420 new_server->server_type = SILC_BACKUP_ROUTER;
1423 /* Check whether this connection is to be our primary router connection
1424 if we do not already have the primary route. */
1425 if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1426 if (silc_server_config_is_primary_route(server->config) &&
1430 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1431 server->standalone = FALSE;
1432 if (!server->id_entry->router) {
1433 server->id_entry->router = id_entry;
1434 server->router = id_entry;
1445 sock->type = ctx->conn_type;
1447 /* Add the common data structure to the ID entry. */
1448 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1450 /* Add to sockets internal pointer for fast referencing */
1451 silc_free(sock->user_data);
1452 sock->user_data = id_entry;
1454 /* Connection has been fully established now. Everything is ok. */
1455 SILC_LOG_DEBUG(("New connection authenticated"));
1457 /* Perform keepalive. The `hb_context' will be freed automatically
1458 when finally calling the silc_socket_free function. XXX hardcoded
1460 hb_context = silc_calloc(1, sizeof(*hb_context));
1461 hb_context->server = server;
1462 silc_socket_set_heartbeat(sock, 400, hb_context,
1463 silc_server_perform_heartbeat,
1467 silc_schedule_task_del_by_callback(server->schedule,
1468 silc_server_failure_callback);
1469 silc_protocol_free(protocol);
1471 silc_packet_context_free(ctx->packet);
1473 silc_ske_free(ctx->ske);
1474 silc_free(ctx->dest_id);
1476 sock->protocol = NULL;
1479 /* This function is used to read packets from network and send packets to
1480 network. This is usually a generic task. */
1482 SILC_TASK_CALLBACK(silc_server_packet_process)
1484 SilcServer server = (SilcServer)context;
1485 SilcSocketConnection sock = server->sockets[fd];
1486 SilcIDListData idata;
1487 SilcCipher cipher = NULL;
1488 SilcHmac hmac = NULL;
1489 uint32 sequence = 0;
1495 SILC_LOG_DEBUG(("Processing packet"));
1497 /* Packet sending */
1499 if (type == SILC_TASK_WRITE) {
1500 /* Do not send data to disconnected connection */
1501 if (SILC_IS_DISCONNECTED(sock))
1504 server->stat.packets_sent++;
1506 if (sock->outbuf->data - sock->outbuf->head)
1507 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1509 /* Send the packet */
1510 ret = silc_packet_send(sock, TRUE);
1512 /* If returned -2 could not write to connection now, will do
1518 SILC_LOG_ERROR(("Error sending packet to connection "
1519 "%s:%d [%s]", sock->hostname, sock->port,
1520 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1521 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1522 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1527 /* The packet has been sent and now it is time to set the connection
1528 back to only for input. When there is again some outgoing data
1529 available for this connection it will be set for output as well.
1530 This call clears the output setting and sets it only for input. */
1531 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1532 SILC_UNSET_OUTBUF_PENDING(sock);
1534 silc_buffer_clear(sock->outbuf);
1538 /* Packet receiving */
1540 /* Read some data from connection */
1541 ret = silc_packet_receive(sock);
1545 SILC_LOG_ERROR(("Error receiving packet from connection "
1546 "%s:%d [%s] %s", sock->hostname, sock->port,
1547 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1548 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1549 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1550 "Router"), strerror(errno)));
1556 SILC_LOG_DEBUG(("Read EOF"));
1558 /* If connection is disconnecting already we will finally
1559 close the connection */
1560 if (SILC_IS_DISCONNECTING(sock)) {
1561 if (sock->user_data)
1562 silc_server_free_sock_user_data(server, sock, NULL);
1563 silc_server_close_connection(server, sock);
1567 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1568 SILC_SET_DISCONNECTING(sock);
1570 if (sock->user_data) {
1572 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
1573 silc_server_free_sock_user_data(server, sock, tmp);
1575 silc_server_free_sock_user_data(server, sock, NULL);
1576 } else if (server->router_conn && server->router_conn->sock == sock &&
1577 !server->router && server->standalone)
1578 silc_schedule_task_add(server->schedule, 0,
1579 silc_server_connect_to_router,
1582 SILC_TASK_PRI_NORMAL);
1584 silc_server_close_connection(server, sock);
1588 /* If connection is disconnecting or disconnected we will ignore
1590 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1591 SILC_LOG_DEBUG(("Ignoring read data from disonnected connection"));
1595 server->stat.packets_received++;
1597 /* Get keys and stuff from ID entry */
1598 idata = (SilcIDListData)sock->user_data;
1600 cipher = idata->receive_key;
1601 hmac = idata->hmac_receive;
1602 sequence = idata->psn_receive;
1605 /* Process the packet. This will call the parser that will then
1606 decrypt and parse the packet. */
1607 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1608 TRUE : FALSE, cipher, hmac, sequence,
1609 silc_server_packet_parse, server);
1611 /* If this socket connection is not authenticated yet and the packet
1612 processing failed we will drop the connection since it can be
1613 a malicious flooder. */
1614 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
1615 (!sock->protocol || sock->protocol->protocol->type ==
1616 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
1617 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
1618 SILC_SET_DISCONNECTING(sock);
1620 if (sock->user_data)
1621 silc_server_free_sock_user_data(server, sock, NULL);
1622 silc_server_close_connection(server, sock);
1626 /* Parses whole packet, received earlier. */
1628 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1630 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1631 SilcServer server = (SilcServer)parse_ctx->context;
1632 SilcSocketConnection sock = parse_ctx->sock;
1633 SilcPacketContext *packet = parse_ctx->packet;
1634 SilcIDListData idata = (SilcIDListData)sock->user_data;
1637 SILC_LOG_DEBUG(("Start"));
1639 /* Parse the packet */
1640 if (parse_ctx->normal)
1641 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
1643 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
1645 /* If entry is disabled ignore what we got. */
1646 if (ret != SILC_PACKET_RESUME_ROUTER &&
1647 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1648 SILC_LOG_DEBUG(("Connection is disabled"));
1652 if (ret == SILC_PACKET_NONE)
1655 /* Check that the the current client ID is same as in the client's packet. */
1656 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1657 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1658 if (client && client->id) {
1659 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1660 packet->src_id_type);
1661 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1669 if (server->server_type == SILC_ROUTER) {
1670 /* Route the packet if it is not destined to us. Other ID types but
1671 server are handled separately after processing them. */
1672 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1673 packet->dst_id_type == SILC_ID_SERVER &&
1674 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1675 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1677 /* Route the packet to fastest route for the destination ID */
1678 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1679 packet->dst_id_type);
1682 silc_server_packet_route(server,
1683 silc_server_route_get(server, id,
1684 packet->dst_id_type),
1691 /* Parse the incoming packet type */
1692 silc_server_packet_parse_type(server, sock, packet);
1694 if (server->server_type == SILC_ROUTER) {
1695 /* Broadcast packet if it is marked as broadcast packet and it is
1696 originated from router and we are router. */
1697 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1698 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1699 !server->standalone) {
1700 /* Broadcast to our primary route */
1701 silc_server_packet_broadcast(server, server->router->connection, packet);
1703 /* If we have backup routers then we need to feed all broadcast
1704 data to those servers. */
1705 silc_server_backup_broadcast(server, sock, packet);
1710 silc_packet_context_free(packet);
1711 silc_free(parse_ctx);
1714 /* Parser callback called by silc_packet_receive_process. This merely
1715 registers timeout that will handle the actual parsing when appropriate. */
1717 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
1720 SilcServer server = (SilcServer)context;
1721 SilcSocketConnection sock = parser_context->sock;
1722 SilcIDListData idata = (SilcIDListData)sock->user_data;
1725 idata->psn_receive = parser_context->packet->sequence + 1;
1727 /* If protocol for this connection is key exchange or rekey then we'll
1728 process all packets synchronously, since there might be packets in
1729 queue that we are not able to decrypt without first processing the
1730 packets before them. */
1731 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
1732 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
1733 (sock->protocol && sock->protocol->protocol &&
1734 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1735 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
1736 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1739 /* Reprocess data since we'll return FALSE here. This is because
1740 the idata->receive_key might have become valid in the last packet
1741 and we want to call this processor with valid cipher. */
1743 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1744 TRUE : FALSE, idata->receive_key,
1745 idata->hmac_receive, idata->psn_receive,
1746 silc_server_packet_parse, server);
1748 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1749 TRUE : FALSE, NULL, NULL, 0,
1750 silc_server_packet_parse, server);
1754 switch (sock->type) {
1755 case SILC_SOCKET_TYPE_UNKNOWN:
1756 case SILC_SOCKET_TYPE_CLIENT:
1757 /* Parse the packet with timeout */
1758 silc_schedule_task_add(server->schedule, sock->sock,
1759 silc_server_packet_parse_real,
1760 (void *)parser_context, 0, 100000,
1762 SILC_TASK_PRI_NORMAL);
1764 case SILC_SOCKET_TYPE_SERVER:
1765 case SILC_SOCKET_TYPE_ROUTER:
1766 /* Packets from servers are parsed immediately */
1767 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1777 /* Parses the packet type and calls what ever routines the packet type
1778 requires. This is done for all incoming packets. */
1780 void silc_server_packet_parse_type(SilcServer server,
1781 SilcSocketConnection sock,
1782 SilcPacketContext *packet)
1784 SilcPacketType type = packet->type;
1785 SilcIDListData idata = (SilcIDListData)sock->user_data;
1787 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1789 /* Parse the packet type */
1791 case SILC_PACKET_DISCONNECT:
1792 SILC_LOG_DEBUG(("Disconnect packet"));
1793 if (packet->flags & SILC_PACKET_FLAG_LIST)
1797 case SILC_PACKET_SUCCESS:
1799 * Success received for something. For now we can have only
1800 * one protocol for connection executing at once hence this
1801 * success message is for whatever protocol is executing currently.
1803 SILC_LOG_DEBUG(("Success packet"));
1804 if (packet->flags & SILC_PACKET_FLAG_LIST)
1807 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1810 case SILC_PACKET_FAILURE:
1812 * Failure received for something. For now we can have only
1813 * one protocol for connection executing at once hence this
1814 * failure message is for whatever protocol is executing currently.
1816 SILC_LOG_DEBUG(("Failure packet"));
1817 if (packet->flags & SILC_PACKET_FLAG_LIST)
1819 if (sock->protocol) {
1820 SilcServerFailureContext f;
1821 f = silc_calloc(1, sizeof(*f));
1825 /* We will wait 5 seconds to process this failure packet */
1826 silc_schedule_task_add(server->schedule, sock->sock,
1827 silc_server_failure_callback, (void *)f, 5, 0,
1828 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1832 case SILC_PACKET_REJECT:
1833 SILC_LOG_DEBUG(("Reject packet"));
1834 if (packet->flags & SILC_PACKET_FLAG_LIST)
1839 case SILC_PACKET_NOTIFY:
1841 * Received notify packet. Server can receive notify packets from
1842 * router. Server then relays the notify messages to clients if needed.
1844 SILC_LOG_DEBUG(("Notify packet"));
1845 if (packet->flags & SILC_PACKET_FLAG_LIST)
1846 silc_server_notify_list(server, sock, packet);
1848 silc_server_notify(server, sock, packet);
1854 case SILC_PACKET_CHANNEL_MESSAGE:
1856 * Received channel message. Channel messages are special packets
1857 * (although probably most common ones) thus they are handled
1860 SILC_LOG_DEBUG(("Channel Message packet"));
1861 if (packet->flags & SILC_PACKET_FLAG_LIST)
1863 idata->last_receive = time(NULL);
1864 silc_server_channel_message(server, sock, packet);
1867 case SILC_PACKET_CHANNEL_KEY:
1869 * Received key for channel. As channels are created by the router
1870 * the keys are as well. We will distribute the key to all of our
1871 * locally connected clients on the particular channel. Router
1872 * never receives this channel and thus is ignored.
1874 SILC_LOG_DEBUG(("Channel Key packet"));
1875 if (packet->flags & SILC_PACKET_FLAG_LIST)
1877 silc_server_channel_key(server, sock, packet);
1883 case SILC_PACKET_COMMAND:
1885 * Recived command. Processes the command request and allocates the
1886 * command context and calls the command.
1888 SILC_LOG_DEBUG(("Command packet"));
1889 if (packet->flags & SILC_PACKET_FLAG_LIST)
1891 silc_server_command_process(server, sock, packet);
1894 case SILC_PACKET_COMMAND_REPLY:
1896 * Received command reply packet. Received command reply to command. It
1897 * may be reply to command sent by us or reply to command sent by client
1898 * that we've routed further.
1900 SILC_LOG_DEBUG(("Command Reply packet"));
1901 if (packet->flags & SILC_PACKET_FLAG_LIST)
1903 silc_server_command_reply(server, sock, packet);
1907 * Private Message packets
1909 case SILC_PACKET_PRIVATE_MESSAGE:
1911 * Received private message packet. The packet is coming from either
1914 SILC_LOG_DEBUG(("Private Message packet"));
1915 if (packet->flags & SILC_PACKET_FLAG_LIST)
1917 idata->last_receive = time(NULL);
1918 silc_server_private_message(server, sock, packet);
1921 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1923 * Private message key packet.
1925 if (packet->flags & SILC_PACKET_FLAG_LIST)
1927 silc_server_private_message_key(server, sock, packet);
1931 * Key Exchange protocol packets
1933 case SILC_PACKET_KEY_EXCHANGE:
1934 SILC_LOG_DEBUG(("KE packet"));
1935 if (packet->flags & SILC_PACKET_FLAG_LIST)
1938 if (sock->protocol && sock->protocol->protocol &&
1939 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1941 SilcServerKEInternalContext *proto_ctx =
1942 (SilcServerKEInternalContext *)sock->protocol->context;
1944 proto_ctx->packet = silc_packet_context_dup(packet);
1946 /* Let the protocol handle the packet */
1947 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
1949 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1950 "protocol active, packet dropped."));
1954 case SILC_PACKET_KEY_EXCHANGE_1:
1955 SILC_LOG_DEBUG(("KE 1 packet"));
1956 if (packet->flags & SILC_PACKET_FLAG_LIST)
1959 if (sock->protocol && sock->protocol->protocol &&
1960 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1961 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
1963 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
1964 SilcServerRekeyInternalContext *proto_ctx =
1965 (SilcServerRekeyInternalContext *)sock->protocol->context;
1967 if (proto_ctx->packet)
1968 silc_packet_context_free(proto_ctx->packet);
1970 proto_ctx->packet = silc_packet_context_dup(packet);
1972 /* Let the protocol handle the packet */
1973 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1975 SilcServerKEInternalContext *proto_ctx =
1976 (SilcServerKEInternalContext *)sock->protocol->context;
1978 if (proto_ctx->packet)
1979 silc_packet_context_free(proto_ctx->packet);
1981 proto_ctx->packet = silc_packet_context_dup(packet);
1982 proto_ctx->dest_id_type = packet->src_id_type;
1983 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1984 packet->src_id_type);
1985 if (!proto_ctx->dest_id)
1988 /* Let the protocol handle the packet */
1989 silc_protocol_execute(sock->protocol, server->schedule,
1993 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1994 "protocol active, packet dropped."));
1998 case SILC_PACKET_KEY_EXCHANGE_2:
1999 SILC_LOG_DEBUG(("KE 2 packet"));
2000 if (packet->flags & SILC_PACKET_FLAG_LIST)
2003 if (sock->protocol && sock->protocol->protocol &&
2004 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2005 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2007 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2008 SilcServerRekeyInternalContext *proto_ctx =
2009 (SilcServerRekeyInternalContext *)sock->protocol->context;
2011 if (proto_ctx->packet)
2012 silc_packet_context_free(proto_ctx->packet);
2014 proto_ctx->packet = silc_packet_context_dup(packet);
2016 /* Let the protocol handle the packet */
2017 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2019 SilcServerKEInternalContext *proto_ctx =
2020 (SilcServerKEInternalContext *)sock->protocol->context;
2022 if (proto_ctx->packet)
2023 silc_packet_context_free(proto_ctx->packet);
2025 proto_ctx->packet = silc_packet_context_dup(packet);
2026 proto_ctx->dest_id_type = packet->src_id_type;
2027 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2028 packet->src_id_type);
2029 if (!proto_ctx->dest_id)
2032 /* Let the protocol handle the packet */
2033 silc_protocol_execute(sock->protocol, server->schedule,
2037 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2038 "protocol active, packet dropped."));
2042 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2044 * Connection authentication request packet. When we receive this packet
2045 * we will send to the other end information about our mandatory
2046 * authentication method for the connection. This packet maybe received
2049 SILC_LOG_DEBUG(("Connection authentication request packet"));
2050 if (packet->flags & SILC_PACKET_FLAG_LIST)
2052 silc_server_connection_auth_request(server, sock, packet);
2056 * Connection Authentication protocol packets
2058 case SILC_PACKET_CONNECTION_AUTH:
2059 /* Start of the authentication protocol. We receive here the
2060 authentication data and will verify it. */
2061 SILC_LOG_DEBUG(("Connection auth packet"));
2062 if (packet->flags & SILC_PACKET_FLAG_LIST)
2065 if (sock->protocol && sock->protocol->protocol->type
2066 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2068 SilcServerConnAuthInternalContext *proto_ctx =
2069 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2071 proto_ctx->packet = silc_packet_context_dup(packet);
2073 /* Let the protocol handle the packet */
2074 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2076 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2077 "protocol active, packet dropped."));
2081 case SILC_PACKET_NEW_ID:
2083 * Received New ID packet. This includes some new ID that has been
2084 * created. It may be for client, server or channel. This is the way
2085 * to distribute information about new registered entities in the
2088 SILC_LOG_DEBUG(("New ID packet"));
2089 if (packet->flags & SILC_PACKET_FLAG_LIST)
2090 silc_server_new_id_list(server, sock, packet);
2092 silc_server_new_id(server, sock, packet);
2095 case SILC_PACKET_NEW_CLIENT:
2097 * Received new client packet. This includes client information that
2098 * we will use to create initial client ID. After creating new
2099 * ID we will send it to the client.
2101 SILC_LOG_DEBUG(("New Client packet"));
2102 if (packet->flags & SILC_PACKET_FLAG_LIST)
2104 silc_server_new_client(server, sock, packet);
2107 case SILC_PACKET_NEW_SERVER:
2109 * Received new server packet. This includes Server ID and some other
2110 * information that we may save. This is received after server has
2113 SILC_LOG_DEBUG(("New Server packet"));
2114 if (packet->flags & SILC_PACKET_FLAG_LIST)
2116 silc_server_new_server(server, sock, packet);
2119 case SILC_PACKET_NEW_CHANNEL:
2121 * Received new channel packet. Information about new channel in the
2122 * network are distributed using this packet.
2124 SILC_LOG_DEBUG(("New Channel packet"));
2125 if (packet->flags & SILC_PACKET_FLAG_LIST)
2126 silc_server_new_channel_list(server, sock, packet);
2128 silc_server_new_channel(server, sock, packet);
2131 case SILC_PACKET_HEARTBEAT:
2133 * Received heartbeat.
2135 SILC_LOG_DEBUG(("Heartbeat packet"));
2136 if (packet->flags & SILC_PACKET_FLAG_LIST)
2140 case SILC_PACKET_KEY_AGREEMENT:
2142 * Received heartbeat.
2144 SILC_LOG_DEBUG(("Key agreement packet"));
2145 if (packet->flags & SILC_PACKET_FLAG_LIST)
2147 silc_server_key_agreement(server, sock, packet);
2150 case SILC_PACKET_REKEY:
2152 * Received re-key packet. The sender wants to regenerate the session
2155 SILC_LOG_DEBUG(("Re-key packet"));
2156 if (packet->flags & SILC_PACKET_FLAG_LIST)
2158 silc_server_rekey(server, sock, packet);
2161 case SILC_PACKET_REKEY_DONE:
2163 * The re-key is done.
2165 SILC_LOG_DEBUG(("Re-key done packet"));
2166 if (packet->flags & SILC_PACKET_FLAG_LIST)
2169 if (sock->protocol && sock->protocol->protocol &&
2170 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2172 SilcServerRekeyInternalContext *proto_ctx =
2173 (SilcServerRekeyInternalContext *)sock->protocol->context;
2175 if (proto_ctx->packet)
2176 silc_packet_context_free(proto_ctx->packet);
2178 proto_ctx->packet = silc_packet_context_dup(packet);
2180 /* Let the protocol handle the packet */
2181 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2183 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2184 "protocol active, packet dropped."));
2188 case SILC_PACKET_FTP:
2190 SILC_LOG_DEBUG(("FTP packet"));
2191 if (packet->flags & SILC_PACKET_FLAG_LIST)
2193 silc_server_ftp(server, sock, packet);
2196 case SILC_PACKET_RESUME_ROUTER:
2197 /* Resume router packet received. This packet is received for backup
2198 router resuming protocol. */
2199 SILC_LOG_DEBUG(("Resume router packet"));
2200 if (packet->flags & SILC_PACKET_FLAG_LIST)
2202 silc_server_backup_resume_router(server, sock, packet);
2206 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2212 /* Creates connection to a remote router. */
2214 void silc_server_create_connection(SilcServer server,
2215 const char *remote_host, uint32 port)
2217 SilcServerConnection sconn;
2219 /* Allocate connection object for hold connection specific stuff. */
2220 sconn = silc_calloc(1, sizeof(*sconn));
2221 sconn->server = server;
2222 sconn->remote_host = strdup(remote_host);
2223 sconn->remote_port = port;
2224 sconn->no_reconnect = TRUE;
2226 silc_schedule_task_add(server->schedule, 0,
2227 silc_server_connect_router,
2228 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2229 SILC_TASK_PRI_NORMAL);
2232 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2234 silc_socket_free((SilcSocketConnection)context);
2237 /* Closes connection to socket connection */
2239 void silc_server_close_connection(SilcServer server,
2240 SilcSocketConnection sock)
2242 if (!server->sockets[sock->sock])
2245 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2247 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2248 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2249 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2252 /* We won't listen for this connection anymore */
2253 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2255 /* Unregister all tasks */
2256 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2258 /* Close the actual connection */
2259 silc_net_close_connection(sock->sock);
2260 server->sockets[sock->sock] = NULL;
2262 /* If sock->user_data is NULL then we'll check for active protocols
2263 here since the silc_server_free_sock_user_data has not been called
2264 for this connection. */
2265 if (!sock->user_data) {
2266 /* If any protocol is active cancel its execution. It will call
2267 the final callback which will finalize the disconnection. */
2268 if (sock->protocol) {
2269 silc_protocol_cancel(sock->protocol, server->schedule);
2270 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2271 silc_protocol_execute_final(sock->protocol, server->schedule);
2272 sock->protocol = NULL;
2277 silc_schedule_task_add(server->schedule, 0,
2278 silc_server_close_connection_final,
2279 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2280 SILC_TASK_PRI_NORMAL);
2283 /* Sends disconnect message to remote connection and disconnects the
2286 void silc_server_disconnect_remote(SilcServer server,
2287 SilcSocketConnection sock,
2288 const char *fmt, ...)
2291 unsigned char buf[4096];
2296 memset(buf, 0, sizeof(buf));
2298 vsprintf(buf, fmt, ap);
2301 SILC_LOG_DEBUG(("Disconnecting remote host"));
2303 /* Notify remote end that the conversation is over. The notify message
2304 is tried to be sent immediately. */
2305 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2306 buf, strlen(buf), TRUE);
2308 /* Mark the connection to be disconnected */
2309 SILC_SET_DISCONNECTED(sock);
2310 silc_server_close_connection(server, sock);
2315 SilcClientEntry client;
2316 } *FreeClientInternal;
2318 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2320 FreeClientInternal i = (FreeClientInternal)context;
2322 silc_idlist_del_data(i->client);
2323 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2327 /* Frees client data and notifies about client's signoff. */
2329 void silc_server_free_client_data(SilcServer server,
2330 SilcSocketConnection sock,
2331 SilcClientEntry client,
2333 const char *signoff)
2335 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2337 /* If there is pending outgoing data for the client then purge it
2338 to the network before removing the client entry. */
2339 silc_server_packet_queue_purge(server, sock);
2344 /* Send SIGNOFF notify to routers. */
2345 if (notify && !server->standalone && server->router)
2346 silc_server_send_notify_signoff(server, server->router->connection,
2347 server->server_type == SILC_SERVER ?
2348 FALSE : TRUE, client->id, signoff);
2350 /* Remove client from all channels */
2352 silc_server_remove_from_channels(server, NULL, client,
2353 TRUE, (char *)signoff, TRUE);
2355 silc_server_remove_from_channels(server, NULL, client,
2356 FALSE, NULL, FALSE);
2358 /* Update statistics */
2359 server->stat.my_clients--;
2360 server->stat.clients--;
2361 if (server->server_type == SILC_ROUTER)
2362 server->stat.cell_clients--;
2363 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2364 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2366 /* We will not delete the client entry right away. We will take it
2367 into history (for WHOWAS command) for 5 minutes */
2370 silc_schedule_task_add(server->schedule, 0,
2371 silc_server_free_client_data_timeout,
2373 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2374 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2375 client->router = NULL;
2376 client->connection = NULL;
2380 /* Frees user_data pointer from socket connection object. This also sends
2381 appropriate notify packets to the network to inform about leaving
2384 void silc_server_free_sock_user_data(SilcServer server,
2385 SilcSocketConnection sock,
2386 const char *signoff_message)
2388 SILC_LOG_DEBUG(("Start"));
2390 switch (sock->type) {
2391 case SILC_SOCKET_TYPE_CLIENT:
2393 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2394 silc_server_free_client_data(server, sock, user_data, TRUE,
2398 case SILC_SOCKET_TYPE_SERVER:
2399 case SILC_SOCKET_TYPE_ROUTER:
2401 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2402 SilcServerEntry backup_router = NULL;
2405 backup_router = silc_server_backup_get(server, user_data->id);
2407 /* If this was our primary router connection then we're lost to
2408 the outside world. */
2409 if (server->router == user_data) {
2410 /* Check whether we have a backup router connection */
2411 if (!backup_router || backup_router == user_data) {
2412 silc_schedule_task_add(server->schedule, 0,
2413 silc_server_connect_to_router,
2416 SILC_TASK_PRI_NORMAL);
2418 server->id_entry->router = NULL;
2419 server->router = NULL;
2420 server->standalone = TRUE;
2421 backup_router = NULL;
2423 SILC_LOG_INFO(("New primary router is backup router %s",
2424 backup_router->server_name));
2425 SILC_LOG_DEBUG(("New primary router is backup router %s",
2426 backup_router->server_name));
2427 server->id_entry->router = backup_router;
2428 server->router = backup_router;
2429 server->router_connect = time(0);
2430 server->backup_primary = TRUE;
2431 if (server->server_type == SILC_BACKUP_ROUTER) {
2432 server->server_type = SILC_ROUTER;
2434 /* We'll need to constantly try to reconnect to the primary
2435 router so that we'll see when it comes back online. */
2436 silc_server_backup_reconnect(server, sock->ip, sock->port,
2437 silc_server_backup_connected,
2441 /* Mark this connection as replaced */
2442 silc_server_backup_replaced_add(server, user_data->id,
2445 } else if (backup_router) {
2446 SILC_LOG_INFO(("Enabling the use of backup router %s",
2447 backup_router->server_name));
2448 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2449 backup_router->server_name));
2451 /* Mark this connection as replaced */
2452 silc_server_backup_replaced_add(server, user_data->id,
2456 if (!backup_router) {
2457 /* Free all client entries that this server owns as they will
2458 become invalid now as well. */
2460 silc_server_remove_clients_by_server(server, user_data, TRUE);
2461 if (server->server_type == SILC_SERVER)
2462 silc_server_remove_channels_by_server(server, user_data);
2464 /* Update the client entries of this server to the new backup
2465 router. This also removes the clients that *really* was owned
2466 by the primary router and went down with the router. */
2467 silc_server_update_clients_by_server(server, user_data, backup_router,
2469 silc_server_update_servers_by_server(server, user_data, backup_router);
2470 if (server->server_type == SILC_SERVER)
2471 silc_server_update_channels_by_server(server, user_data,
2475 /* Free the server entry */
2476 silc_server_backup_del(server, user_data);
2477 silc_server_backup_replaced_del(server, user_data);
2478 silc_idlist_del_data(user_data);
2479 if (!silc_idlist_del_server(server->local_list, user_data))
2480 silc_idlist_del_server(server->global_list, user_data);
2481 server->stat.my_servers--;
2482 server->stat.servers--;
2483 if (server->server_type == SILC_ROUTER)
2484 server->stat.cell_servers--;
2486 if (backup_router) {
2487 /* Announce all of our stuff that was created about 5 minutes ago.
2488 The backup router knows all the other stuff already. */
2489 if (server->server_type == SILC_ROUTER)
2490 silc_server_announce_servers(server, FALSE, time(0) - 300,
2491 backup_router->connection);
2493 /* Announce our clients and channels to the router */
2494 silc_server_announce_clients(server, time(0) - 300,
2495 backup_router->connection);
2496 silc_server_announce_channels(server, time(0) - 300,
2497 backup_router->connection);
2503 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2505 silc_idlist_del_data(user_data);
2506 silc_free(user_data);
2511 /* If any protocol is active cancel its execution */
2512 if (sock->protocol) {
2513 silc_protocol_cancel(sock->protocol, server->schedule);
2514 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2515 silc_protocol_execute_final(sock->protocol, server->schedule);
2516 sock->protocol = NULL;
2519 sock->user_data = NULL;
2522 /* Removes client from all channels it has joined. This is used when client
2523 connection is disconnected. If the client on a channel is last, the
2524 channel is removed as well. This sends the SIGNOFF notify types. */
2526 void silc_server_remove_from_channels(SilcServer server,
2527 SilcSocketConnection sock,
2528 SilcClientEntry client,
2530 char *signoff_message,
2533 SilcChannelEntry channel;
2534 SilcChannelClientEntry chl;
2535 SilcHashTableList htl;
2538 SILC_LOG_DEBUG(("Start"));
2540 if (!client || !client->id)
2543 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2545 /* Remove the client from all channels. The client is removed from
2546 the channels' user list. */
2547 silc_hash_table_list(client->channels, &htl);
2548 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2549 channel = chl->channel;
2551 /* Remove channel from client's channel list */
2552 silc_hash_table_del(client->channels, channel);
2554 /* Remove channel if there is no users anymore */
2555 if (server->server_type == SILC_ROUTER &&
2556 silc_hash_table_count(channel->user_list) < 2) {
2558 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2559 if (silc_idlist_del_channel(server->local_list, channel))
2560 server->stat.my_channels--;
2562 silc_idlist_del_channel(server->global_list, channel);
2566 /* Remove client from channel's client list */
2567 silc_hash_table_del(channel->user_list, chl->client);
2569 /* If there is no global users on the channel anymore mark the channel
2570 as local channel. Do not check if the removed client is local client. */
2571 if (server->server_type != SILC_ROUTER && channel->global_users &&
2572 chl->client->router && !silc_server_channel_has_global(channel))
2573 channel->global_users = FALSE;
2576 server->stat.my_chanclients--;
2578 /* If there is not at least one local user on the channel then we don't
2579 need the channel entry anymore, we can remove it safely. */
2580 if (server->server_type != SILC_ROUTER &&
2581 !silc_server_channel_has_local(channel)) {
2582 /* Notify about leaving client if this channel has global users. */
2583 if (notify && channel->global_users)
2584 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2585 SILC_NOTIFY_TYPE_SIGNOFF,
2586 signoff_message ? 2 : 1,
2587 clidp->data, clidp->len,
2588 signoff_message, signoff_message ?
2589 strlen(signoff_message) : 0);
2592 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2594 if (channel->founder_key) {
2595 /* The founder auth data exists, do not remove the channel entry */
2596 SilcChannelClientEntry chl2;
2597 SilcHashTableList htl2;
2599 channel->disabled = TRUE;
2601 silc_hash_table_list(channel->user_list, &htl2);
2602 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2603 silc_hash_table_del(chl2->client->channels, channel);
2604 silc_hash_table_del(channel->user_list, chl2->client);
2607 silc_hash_table_list_reset(&htl2);
2611 /* Remove the channel entry */
2612 if (silc_idlist_del_channel(server->local_list, channel))
2613 server->stat.my_channels--;
2615 silc_idlist_del_channel(server->global_list, channel);
2619 /* Send notify to channel about client leaving SILC and thus
2620 the entire channel. */
2622 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2623 SILC_NOTIFY_TYPE_SIGNOFF,
2624 signoff_message ? 2 : 1,
2625 clidp->data, clidp->len,
2626 signoff_message, signoff_message ?
2627 strlen(signoff_message) : 0);
2629 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2630 /* Re-generate channel key */
2631 if (!silc_server_create_channel_key(server, channel, 0))
2634 /* Send the channel key to the channel. The key of course is not sent
2635 to the client who was removed from the channel. */
2636 silc_server_send_channel_key(server, client->connection, channel,
2637 server->server_type == SILC_ROUTER ?
2638 FALSE : !server->standalone);
2643 silc_hash_table_list_reset(&htl);
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);
2730 silc_hash_table_list_reset(&htl2);
2734 /* Remove the channel entry */
2735 if (silc_idlist_del_channel(server->local_list, channel))
2736 server->stat.my_channels--;
2738 silc_idlist_del_channel(server->global_list, channel);
2742 /* Send notify to channel about client leaving the channel */
2744 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2745 SILC_NOTIFY_TYPE_LEAVE, 1,
2746 clidp->data, clidp->len);
2748 silc_buffer_free(clidp);
2752 /* Timeout callback. This is called if connection is idle or for some
2753 other reason is not responding within some period of time. This
2754 disconnects the remote end. */
2756 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2758 SilcServer server = (SilcServer)context;
2759 SilcSocketConnection sock = server->sockets[fd];
2761 SILC_LOG_DEBUG(("Start"));
2766 /* If we have protocol active we must assure that we call the protocol's
2767 final callback so that all the memory is freed. */
2768 if (sock->protocol) {
2769 silc_protocol_cancel(sock->protocol, server->schedule);
2770 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2771 silc_protocol_execute_final(sock->protocol, server->schedule);
2772 sock->protocol = NULL;
2776 if (sock->user_data)
2777 silc_server_free_sock_user_data(server, sock, NULL);
2779 silc_server_disconnect_remote(server, sock, "Server closed connection: "
2780 "Connection timeout");
2783 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2784 function may be used only by router. In real SILC network all channels
2785 are created by routers thus this function is never used by normal
2788 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2789 SilcServerID *router_id,
2795 SilcChannelID *channel_id;
2796 SilcChannelEntry entry;
2800 SILC_LOG_DEBUG(("Creating new channel"));
2803 cipher = SILC_DEFAULT_CIPHER;
2805 hmac = SILC_DEFAULT_HMAC;
2807 /* Allocate cipher */
2808 if (!silc_cipher_alloc(cipher, &key))
2812 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2813 silc_cipher_free(key);
2817 channel_name = strdup(channel_name);
2819 /* Create the channel ID */
2820 if (!silc_id_create_channel_id(server, router_id, server->rng,
2822 silc_free(channel_name);
2823 silc_cipher_free(key);
2824 silc_hmac_free(newhmac);
2828 /* Create the channel */
2829 entry = silc_idlist_add_channel(server->local_list, channel_name,
2830 SILC_CHANNEL_MODE_NONE, channel_id,
2831 NULL, key, newhmac, 0);
2833 silc_free(channel_name);
2834 silc_cipher_free(key);
2835 silc_hmac_free(newhmac);
2836 silc_free(channel_id);
2840 entry->cipher = strdup(cipher);
2841 entry->hmac_name = strdup(hmac);
2843 /* Now create the actual key material */
2844 if (!silc_server_create_channel_key(server, entry,
2845 silc_cipher_get_key_len(key) / 8)) {
2846 silc_idlist_del_channel(server->local_list, entry);
2850 /* Notify other routers about the new channel. We send the packet
2851 to our primary route. */
2852 if (broadcast && server->standalone == FALSE)
2853 silc_server_send_new_channel(server, server->router->connection, TRUE,
2854 channel_name, entry->id,
2855 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2858 server->stat.my_channels++;
2863 /* Same as above but creates the channel with Channel ID `channel_id. */
2866 silc_server_create_new_channel_with_id(SilcServer server,
2870 SilcChannelID *channel_id,
2873 SilcChannelEntry entry;
2877 SILC_LOG_DEBUG(("Creating new channel"));
2880 cipher = SILC_DEFAULT_CIPHER;
2882 hmac = SILC_DEFAULT_HMAC;
2884 /* Allocate cipher */
2885 if (!silc_cipher_alloc(cipher, &key))
2889 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2890 silc_cipher_free(key);
2894 channel_name = strdup(channel_name);
2896 /* Create the channel */
2897 entry = silc_idlist_add_channel(server->local_list, channel_name,
2898 SILC_CHANNEL_MODE_NONE, channel_id,
2899 NULL, key, newhmac, 0);
2901 silc_cipher_free(key);
2902 silc_hmac_free(newhmac);
2903 silc_free(channel_name);
2907 /* Now create the actual key material */
2908 if (!silc_server_create_channel_key(server, entry,
2909 silc_cipher_get_key_len(key) / 8)) {
2910 silc_idlist_del_channel(server->local_list, entry);
2914 /* Notify other routers about the new channel. We send the packet
2915 to our primary route. */
2916 if (broadcast && server->standalone == FALSE)
2917 silc_server_send_new_channel(server, server->router->connection, TRUE,
2918 channel_name, entry->id,
2919 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2922 server->stat.my_channels++;
2927 /* Channel's key re-key timeout callback. */
2929 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
2931 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
2932 SilcServer server = (SilcServer)rekey->context;
2936 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
2939 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
2942 /* Generates new channel key. This is used to create the initial channel key
2943 but also to re-generate new key for channel. If `key_len' is provided
2944 it is the bytes of the key length. */
2946 bool silc_server_create_channel_key(SilcServer server,
2947 SilcChannelEntry channel,
2951 unsigned char channel_key[32], hash[32];
2954 SILC_LOG_DEBUG(("Generating channel key"));
2956 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
2957 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
2961 if (!channel->channel_key)
2962 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
2963 channel->channel_key = NULL;
2969 else if (channel->key_len)
2970 len = channel->key_len / 8;
2972 len = silc_cipher_get_key_len(channel->channel_key) / 8;
2974 /* Create channel key */
2975 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
2978 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
2980 /* Remove old key if exists */
2982 memset(channel->key, 0, channel->key_len / 8);
2983 silc_free(channel->key);
2987 channel->key_len = len * 8;
2988 channel->key = silc_calloc(len, sizeof(*channel->key));
2989 memcpy(channel->key, channel_key, len);
2990 memset(channel_key, 0, sizeof(channel_key));
2992 /* Generate HMAC key from the channel key data and set it */
2994 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
2995 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
2996 silc_hmac_set_key(channel->hmac, hash,
2997 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
2998 memset(hash, 0, sizeof(hash));
3000 if (server->server_type == SILC_ROUTER) {
3001 if (!channel->rekey)
3002 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3003 channel->rekey->context = (void *)server;
3004 channel->rekey->channel = channel;
3005 channel->rekey->key_len = key_len;
3006 if (channel->rekey->task)
3007 silc_schedule_task_del(server->schedule, channel->rekey->task);
3009 channel->rekey->task =
3010 silc_schedule_task_add(server->schedule, 0,
3011 silc_server_channel_key_rekey,
3012 (void *)channel->rekey, 3600, 0,
3014 SILC_TASK_PRI_NORMAL);
3020 /* Saves the channel key found in the encoded `key_payload' buffer. This
3021 function is used when we receive Channel Key Payload and also when we're
3022 processing JOIN command reply. Returns entry to the channel. */
3024 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3025 SilcBuffer key_payload,
3026 SilcChannelEntry channel)
3028 SilcChannelKeyPayload payload = NULL;
3029 SilcChannelID *id = NULL;
3030 unsigned char *tmp, hash[32];
3034 SILC_LOG_DEBUG(("Start"));
3036 /* Decode channel key payload */
3037 payload = silc_channel_key_payload_parse(key_payload->data,
3040 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3045 /* Get the channel entry */
3048 /* Get channel ID */
3049 tmp = silc_channel_key_get_id(payload, &tmp_len);
3050 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3056 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3058 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3060 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3061 silc_id_render(id, SILC_ID_CHANNEL)));
3067 tmp = silc_channel_key_get_key(payload, &tmp_len);
3073 cipher = silc_channel_key_get_cipher(payload, NULL);
3079 /* Remove old key if exists */
3081 memset(channel->key, 0, channel->key_len / 8);
3082 silc_free(channel->key);
3083 silc_cipher_free(channel->channel_key);
3086 /* Create new cipher */
3087 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3088 channel->channel_key = NULL;
3093 if (channel->cipher)
3094 silc_free(channel->cipher);
3095 channel->cipher = strdup(cipher);
3098 channel->key_len = tmp_len * 8;
3099 channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
3100 memcpy(channel->key, tmp, tmp_len);
3101 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3103 /* Generate HMAC key from the channel key data and set it */
3105 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3106 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3107 silc_hmac_set_key(channel->hmac, hash,
3108 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3110 memset(hash, 0, sizeof(hash));
3111 memset(tmp, 0, tmp_len);
3113 if (server->server_type == SILC_ROUTER) {
3114 if (!channel->rekey)
3115 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3116 channel->rekey->context = (void *)server;
3117 channel->rekey->channel = channel;
3118 if (channel->rekey->task)
3119 silc_schedule_task_del(server->schedule, channel->rekey->task);
3121 channel->rekey->task =
3122 silc_schedule_task_add(server->schedule, 0,
3123 silc_server_channel_key_rekey,
3124 (void *)channel->rekey, 3600, 0,
3126 SILC_TASK_PRI_NORMAL);
3132 silc_channel_key_payload_free(payload);
3137 /* Heartbeat callback. This function is set as argument for the
3138 silc_socket_set_heartbeat function. The library will call this function
3139 at the set time interval. */
3141 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3144 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3146 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3148 /* Send the heartbeat */
3149 silc_server_send_heartbeat(hb->server, sock);
3152 /* Returns assembled of all servers in the given ID list. The packet's
3153 form is dictated by the New ID payload. */
3155 static void silc_server_announce_get_servers(SilcServer server,
3156 SilcServerEntry remote,
3158 SilcBuffer *servers,
3159 unsigned long creation_time)
3161 SilcIDCacheList list;
3162 SilcIDCacheEntry id_cache;
3163 SilcServerEntry entry;
3166 /* Go through all clients in the list */
3167 if (silc_idcache_get_all(id_list->servers, &list)) {
3168 if (silc_idcache_list_first(list, &id_cache)) {
3170 entry = (SilcServerEntry)id_cache->context;
3172 /* Do not announce the one we've sending our announcements and
3173 do not announce ourself. Also check the creation time if it's
3175 if ((entry == remote) || (entry == server->id_entry) ||
3176 (creation_time && entry->data.created < creation_time)) {
3177 if (!silc_idcache_list_next(list, &id_cache))
3182 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3184 *servers = silc_buffer_realloc(*servers,
3186 (*servers)->truelen + idp->len :
3188 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3189 silc_buffer_put(*servers, idp->data, idp->len);
3190 silc_buffer_pull(*servers, idp->len);
3191 silc_buffer_free(idp);
3193 if (!silc_idcache_list_next(list, &id_cache))
3198 silc_idcache_list_free(list);
3203 silc_server_announce_encode_notify(SilcNotifyType notify, uint32 argc, ...)
3209 p = silc_notify_payload_encode(notify, argc, ap);
3215 /* This function is used by router to announce existing servers to our
3216 primary router when we've connected to it. If `creation_time' is non-zero
3217 then only the servers that has been created after the `creation_time'
3218 will be announced. */
3220 void silc_server_announce_servers(SilcServer server, bool global,
3221 unsigned long creation_time,
3222 SilcSocketConnection remote)
3224 SilcBuffer servers = NULL;
3226 SILC_LOG_DEBUG(("Announcing servers"));
3228 /* Get servers in local list */
3229 silc_server_announce_get_servers(server, remote->user_data,
3230 server->local_list, &servers,
3234 /* Get servers in global list */
3235 silc_server_announce_get_servers(server, remote->user_data,
3236 server->global_list, &servers,
3240 silc_buffer_push(servers, servers->data - servers->head);
3241 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3243 /* Send the packet */
3244 silc_server_packet_send(server, remote,
3245 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3246 servers->data, servers->len, TRUE);
3248 silc_buffer_free(servers);
3252 /* Returns assembled packet of all clients in the given ID list. The
3253 packet's form is dictated by the New ID Payload. */
3255 static void silc_server_announce_get_clients(SilcServer server,
3257 SilcBuffer *clients,
3259 unsigned long creation_time)
3261 SilcIDCacheList list;
3262 SilcIDCacheEntry id_cache;
3263 SilcClientEntry client;
3266 unsigned char mode[4];
3268 /* Go through all clients in the list */
3269 if (silc_idcache_get_all(id_list->clients, &list)) {
3270 if (silc_idcache_list_first(list, &id_cache)) {
3272 client = (SilcClientEntry)id_cache->context;
3274 if (creation_time && client->data.created < creation_time) {
3275 if (!silc_idcache_list_next(list, &id_cache))
3280 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3282 *clients = silc_buffer_realloc(*clients,
3284 (*clients)->truelen + idp->len :
3286 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3287 silc_buffer_put(*clients, idp->data, idp->len);
3288 silc_buffer_pull(*clients, idp->len);
3290 SILC_PUT32_MSB(client->mode, mode);
3291 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3292 2, idp->data, idp->len,
3294 *umodes = silc_buffer_realloc(*umodes,
3296 (*umodes)->truelen + tmp->len :
3298 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3299 silc_buffer_put(*umodes, tmp->data, tmp->len);
3300 silc_buffer_pull(*umodes, tmp->len);
3301 silc_buffer_free(tmp);
3303 silc_buffer_free(idp);
3305 if (!silc_idcache_list_next(list, &id_cache))
3310 silc_idcache_list_free(list);
3314 /* This function is used to announce our existing clients to our router
3315 when we've connected to it. If `creation_time' is non-zero then only
3316 the clients that has been created after the `creation_time' will be
3319 void silc_server_announce_clients(SilcServer server,
3320 unsigned long creation_time,
3321 SilcSocketConnection remote)
3323 SilcBuffer clients = NULL;
3324 SilcBuffer umodes = NULL;
3326 SILC_LOG_DEBUG(("Announcing clients"));
3328 /* Get clients in local list */
3329 silc_server_announce_get_clients(server, server->local_list,
3330 &clients, &umodes, creation_time);
3332 /* As router we announce our global list as well */
3333 if (server->server_type == SILC_ROUTER)
3334 silc_server_announce_get_clients(server, server->global_list,
3335 &clients, &umodes, creation_time);
3338 silc_buffer_push(clients, clients->data - clients->head);
3339 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3341 /* Send the packet */
3342 silc_server_packet_send(server, remote,
3343 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3344 clients->data, clients->len, TRUE);
3346 silc_buffer_free(clients);
3350 silc_buffer_push(umodes, umodes->data - umodes->head);
3351 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3353 /* Send the packet */
3354 silc_server_packet_send(server, remote,
3355 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3356 umodes->data, umodes->len, TRUE);
3358 silc_buffer_free(umodes);
3362 /* Returns channel's topic for announcing it */
3364 void silc_server_announce_get_channel_topic(SilcServer server,
3365 SilcChannelEntry channel,
3370 if (channel->topic) {
3371 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3372 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3373 chidp->data, chidp->len,
3375 strlen(channel->topic));
3376 silc_buffer_free(chidp);
3380 /* Returns assembled packets for channel users of the `channel'. */
3382 void silc_server_announce_get_channel_users(SilcServer server,
3383 SilcChannelEntry channel,
3384 SilcBuffer *channel_users,
3385 SilcBuffer *channel_users_modes)
3387 SilcChannelClientEntry chl;
3388 SilcHashTableList htl;
3389 SilcBuffer chidp, clidp;
3392 unsigned char mode[4];
3394 SILC_LOG_DEBUG(("Start"));
3396 /* Now find all users on the channel */
3397 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3398 silc_hash_table_list(channel->user_list, &htl);
3399 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3400 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3403 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3404 clidp->data, clidp->len,
3405 chidp->data, chidp->len);
3408 silc_buffer_realloc(*channel_users,
3410 (*channel_users)->truelen + len : len));
3411 silc_buffer_pull_tail(*channel_users,
3412 ((*channel_users)->end -
3413 (*channel_users)->data));
3415 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3416 silc_buffer_pull(*channel_users, len);
3417 silc_buffer_free(tmp);
3419 /* CUMODE notify for mode change on the channel */
3420 SILC_PUT32_MSB(chl->mode, mode);
3421 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3422 3, clidp->data, clidp->len,
3424 clidp->data, clidp->len);
3426 *channel_users_modes =
3427 silc_buffer_realloc(*channel_users_modes,
3428 (*channel_users_modes ?
3429 (*channel_users_modes)->truelen + len : len));
3430 silc_buffer_pull_tail(*channel_users_modes,
3431 ((*channel_users_modes)->end -
3432 (*channel_users_modes)->data));
3434 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3435 silc_buffer_pull(*channel_users_modes, len);
3436 silc_buffer_free(tmp);
3438 silc_buffer_free(clidp);
3440 silc_hash_table_list_reset(&htl);
3441 silc_buffer_free(chidp);
3444 /* Returns assembled packets for all channels and users on those channels
3445 from the given ID List. The packets are in the form dictated by the
3446 New Channel and New Channel User payloads. */
3448 void silc_server_announce_get_channels(SilcServer server,
3450 SilcBuffer *channels,
3451 SilcBuffer *channel_users,
3452 SilcBuffer **channel_users_modes,
3453 uint32 *channel_users_modes_c,
3454 SilcBuffer **channel_topics,
3455 SilcChannelID ***channel_ids,
3456 unsigned long creation_time)
3458 SilcIDCacheList list;
3459 SilcIDCacheEntry id_cache;
3460 SilcChannelEntry channel;
3465 int i = *channel_users_modes_c;
3468 SILC_LOG_DEBUG(("Start"));
3470 /* Go through all channels in the list */
3471 if (silc_idcache_get_all(id_list->channels, &list)) {
3472 if (silc_idcache_list_first(list, &id_cache)) {
3474 channel = (SilcChannelEntry)id_cache->context;
3476 if (creation_time && channel->created < creation_time)
3481 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3482 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3483 name_len = strlen(channel->channel_name);
3486 len = 4 + name_len + id_len + 4;
3488 silc_buffer_realloc(*channels,
3489 (*channels ? (*channels)->truelen +
3491 silc_buffer_pull_tail(*channels,
3492 ((*channels)->end - (*channels)->data));
3493 silc_buffer_format(*channels,
3494 SILC_STR_UI_SHORT(name_len),
3495 SILC_STR_UI_XNSTRING(channel->channel_name,
3497 SILC_STR_UI_SHORT(id_len),
3498 SILC_STR_UI_XNSTRING(cid, id_len),
3499 SILC_STR_UI_INT(channel->mode),
3501 silc_buffer_pull(*channels, len);
3504 /* Channel user modes */
3505 *channel_users_modes = silc_realloc(*channel_users_modes,
3506 sizeof(**channel_users_modes) *
3508 (*channel_users_modes)[i] = NULL;
3509 *channel_ids = silc_realloc(*channel_ids,
3510 sizeof(**channel_ids) * (i + 1));
3511 (*channel_ids)[i] = NULL;
3512 silc_server_announce_get_channel_users(server, channel,
3514 &(*channel_users_modes)[i]);
3515 (*channel_ids)[i] = channel->id;
3517 /* Channel's topic */
3518 *channel_topics = silc_realloc(*channel_topics,
3519 sizeof(**channel_topics) * (i + 1));
3520 (*channel_topics)[i] = NULL;
3521 silc_server_announce_get_channel_topic(server, channel,
3522 &(*channel_topics)[i]);
3525 if (!silc_idcache_list_next(list, &id_cache))
3529 *channel_users_modes_c += i;
3532 silc_idcache_list_free(list);
3536 /* This function is used to announce our existing channels to our router
3537 when we've connected to it. This also announces the users on the
3538 channels to the router. If the `creation_time' is non-zero only the
3539 channels that was created after the `creation_time' are announced.
3540 Note that the channel users are still announced even if the `creation_time'
3543 void silc_server_announce_channels(SilcServer server,
3544 unsigned long creation_time,
3545 SilcSocketConnection remote)
3547 SilcBuffer channels = NULL, channel_users = NULL;
3548 SilcBuffer *channel_users_modes = NULL;
3549 SilcBuffer *channel_topics = NULL;
3550 uint32 channel_users_modes_c = 0;
3551 SilcChannelID **channel_ids = NULL;
3553 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3555 /* Get channels and channel users in local list */
3556 silc_server_announce_get_channels(server, server->local_list,
3557 &channels, &channel_users,
3558 &channel_users_modes,
3559 &channel_users_modes_c,
3561 &channel_ids, creation_time);
3563 /* Get channels and channel users in global list */
3564 if (server->server_type != SILC_SERVER)
3565 silc_server_announce_get_channels(server, server->global_list,
3566 &channels, &channel_users,
3567 &channel_users_modes,
3568 &channel_users_modes_c,
3570 &channel_ids, creation_time);
3573 silc_buffer_push(channels, channels->data - channels->head);
3574 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3576 /* Send the packet */
3577 silc_server_packet_send(server, remote,
3578 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3579 channels->data, channels->len,
3582 silc_buffer_free(channels);
3585 if (channel_users) {
3586 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3587 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3588 channel_users->len);
3590 /* Send the packet */
3591 silc_server_packet_send(server, remote,
3592 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3593 channel_users->data, channel_users->len,
3596 silc_buffer_free(channel_users);
3599 if (channel_users_modes) {
3602 for (i = 0; i < channel_users_modes_c; i++) {
3603 if (!channel_users_modes[i])
3605 silc_buffer_push(channel_users_modes[i],
3606 channel_users_modes[i]->data -
3607 channel_users_modes[i]->head);
3608 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3609 channel_users_modes[i]->len);
3610 silc_server_packet_send_dest(server, remote,
3611 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3612 channel_ids[i], SILC_ID_CHANNEL,
3613 channel_users_modes[i]->data,
3614 channel_users_modes[i]->len,
3616 silc_buffer_free(channel_users_modes[i]);
3618 silc_free(channel_users_modes);
3621 if (channel_topics) {
3624 for (i = 0; i < channel_users_modes_c; i++) {
3625 if (!channel_topics[i])
3628 silc_buffer_push(channel_topics[i],
3629 channel_topics[i]->data -
3630 channel_topics[i]->head);
3631 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
3632 channel_topics[i]->len);
3633 silc_server_packet_send_dest(server, remote,
3634 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3635 channel_ids[i], SILC_ID_CHANNEL,
3636 channel_topics[i]->data,
3637 channel_topics[i]->len,
3639 silc_buffer_free(channel_topics[i]);
3641 silc_free(channel_topics);
3644 silc_free(channel_ids);
3647 /* Failure timeout callback. If this is called then we will immediately
3648 process the received failure. We always process the failure with timeout
3649 since we do not want to blindly trust to received failure packets.
3650 This won't be called (the timeout is cancelled) if the failure was
3651 bogus (it is bogus if remote does not close the connection after sending
3654 SILC_TASK_CALLBACK(silc_server_failure_callback)
3656 SilcServerFailureContext f = (SilcServerFailureContext)context;
3658 if (f->sock->protocol) {
3659 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3660 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3666 /* Assembles user list and users mode list from the `channel'. */
3668 void silc_server_get_users_on_channel(SilcServer server,
3669 SilcChannelEntry channel,
3670 SilcBuffer *user_list,
3671 SilcBuffer *mode_list,
3674 SilcChannelClientEntry chl;
3675 SilcHashTableList htl;
3676 SilcBuffer client_id_list;
3677 SilcBuffer client_mode_list;
3679 uint32 list_count = 0, len = 0;
3681 silc_hash_table_list(channel->user_list, &htl);
3682 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3683 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3684 silc_hash_table_list_reset(&htl);
3686 client_id_list = silc_buffer_alloc(len);
3688 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3689 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3690 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3692 silc_hash_table_list(channel->user_list, &htl);
3693 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3695 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3696 silc_buffer_put(client_id_list, idp->data, idp->len);
3697 silc_buffer_pull(client_id_list, idp->len);
3698 silc_buffer_free(idp);
3700 /* Client's mode on channel */
3701 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3702 silc_buffer_pull(client_mode_list, 4);
3706 silc_hash_table_list_reset(&htl);
3707 silc_buffer_push(client_id_list,
3708 client_id_list->data - client_id_list->head);
3709 silc_buffer_push(client_mode_list,
3710 client_mode_list->data - client_mode_list->head);
3712 *user_list = client_id_list;
3713 *mode_list = client_mode_list;
3714 *user_count = list_count;
3717 /* Saves users and their modes to the `channel'. */
3719 void silc_server_save_users_on_channel(SilcServer server,
3720 SilcSocketConnection sock,
3721 SilcChannelEntry channel,
3722 SilcClientID *noadd,
3723 SilcBuffer user_list,
3724 SilcBuffer mode_list,
3730 SilcClientID *client_id;
3731 SilcClientEntry client;
3732 SilcIDCacheEntry cache;
3735 SILC_LOG_DEBUG(("Start"));
3737 for (i = 0; i < user_count; i++) {
3739 SILC_GET16_MSB(idp_len, user_list->data + 2);
3741 client_id = silc_id_payload_parse_id(user_list->data, idp_len);
3742 silc_buffer_pull(user_list, idp_len);
3747 SILC_GET32_MSB(mode, mode_list->data);
3748 silc_buffer_pull(mode_list, 4);
3750 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3751 silc_free(client_id);
3757 /* Check if we have this client cached already. */
3758 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3759 server->server_type, &cache);
3761 client = silc_idlist_find_client_by_id(server->global_list,
3762 client_id, server->server_type,
3767 /* If router did not find such Client ID in its lists then this must
3768 be bogus client or some router in the net is buggy. */
3769 if (server->server_type == SILC_ROUTER) {
3770 silc_free(client_id);
3774 /* We don't have that client anywhere, add it. The client is added
3775 to global list since server didn't have it in the lists so it must be
3777 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3778 silc_id_dup(client_id, SILC_ID_CLIENT),
3779 sock->user_data, NULL, 0);
3781 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3782 silc_free(client_id);
3786 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3788 /* Found, if it is from global list we'll assure that we won't
3789 expire it now that the entry is on channel. */
3794 silc_free(client_id);
3796 if (!silc_server_client_on_channel(client, channel)) {
3797 /* Client was not on the channel, add it. */
3798 SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3799 chl->client = client;
3801 chl->channel = channel;
3802 silc_hash_table_add(channel->user_list, chl->client, chl);
3803 silc_hash_table_add(client->channels, chl->channel, chl);
3808 /* Lookups route to the client indicated by the `id_data'. The connection
3809 object and internal data object is returned. Returns NULL if route
3810 could not be found to the client. If the `client_id' is specified then
3811 it is used and the `id_data' is ignored. */
3813 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3814 unsigned char *id_data,
3816 SilcClientID *client_id,
3817 SilcIDListData *idata)
3820 SilcClientEntry client;
3822 SILC_LOG_DEBUG(("Start"));
3824 /* Decode destination Client ID */
3826 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3828 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3832 id = silc_id_dup(client_id, SILC_ID_CLIENT);
3835 /* If the destination belongs to our server we don't have to route
3836 the packet anywhere but to send it to the local destination. */
3837 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
3841 /* If we are router and the client has router then the client is in
3842 our cell but not directly connected to us. */
3843 if (server->server_type == SILC_ROUTER && client->router) {
3844 /* We are of course in this case the client's router thus the route
3845 to the client is the server who owns the client. So, we will send
3846 the packet to that server. */
3848 *idata = (SilcIDListData)client->router;
3849 return client->router->connection;
3852 /* Seems that client really is directly connected to us */
3854 *idata = (SilcIDListData)client;
3855 return client->connection;
3858 /* Destination belongs to someone not in this server. If we are normal
3859 server our action is to send the packet to our router. */
3860 if (server->server_type != SILC_ROUTER && !server->standalone) {
3863 *idata = (SilcIDListData)server->router;
3864 return server->router->connection;
3867 /* We are router and we will perform route lookup for the destination
3868 and send the packet to fastest route. */
3869 if (server->server_type == SILC_ROUTER && !server->standalone) {
3870 /* Check first that the ID is valid */
3871 client = silc_idlist_find_client_by_id(server->global_list, id,
3874 SilcSocketConnection dst_sock;
3876 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
3880 *idata = (SilcIDListData)dst_sock->user_data;
3889 /* Encodes and returns channel list of channels the `client' has joined.
3890 Secret channels are not put to the list. */
3892 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
3893 SilcClientEntry client)
3895 SilcBuffer buffer = NULL;
3896 SilcChannelEntry channel;
3897 SilcChannelClientEntry chl;
3898 SilcHashTableList htl;
3904 silc_hash_table_list(client->channels, &htl);
3905 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3906 channel = chl->channel;
3908 if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
3909 channel->mode & SILC_CHANNEL_MODE_PRIVATE)
3912 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3913 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3914 name_len = strlen(channel->channel_name);
3916 len = 4 + name_len + id_len + 4;
3917 buffer = silc_buffer_realloc(buffer,
3918 (buffer ? (buffer)->truelen + len : len));
3919 silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
3920 silc_buffer_format(buffer,
3921 SILC_STR_UI_SHORT(name_len),
3922 SILC_STR_UI_XNSTRING(channel->channel_name,
3924 SILC_STR_UI_SHORT(id_len),
3925 SILC_STR_UI_XNSTRING(cid, id_len),
3926 SILC_STR_UI_INT(chl->mode), /* Client's mode */
3928 silc_buffer_pull(buffer, len);
3931 silc_hash_table_list_reset(&htl);
3934 silc_buffer_push(buffer, buffer->data - buffer->head);
3939 /* Finds client entry by Client ID and if it is not found then resolves
3940 it using WHOIS command. */
3942 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
3943 SilcClientID *client_id,
3946 SilcClientEntry client;
3951 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3954 client = silc_idlist_find_client_by_id(server->global_list,
3955 client_id, TRUE, NULL);
3956 if (!client && server->server_type == SILC_ROUTER)
3960 if (!client && server->standalone)
3963 if (!client || !client->nickname || !client->username) {
3964 SilcBuffer buffer, idp;
3966 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
3967 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
3968 client->resolve_cmd_ident = ++server->cmd_ident;
3970 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3971 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
3972 server->cmd_ident, 1,
3973 3, idp->data, idp->len);
3974 silc_server_packet_send(server, client ? client->router->connection :
3975 server->router->connection,
3976 SILC_PACKET_COMMAND, 0,
3977 buffer->data, buffer->len, FALSE);
3978 silc_buffer_free(idp);
3979 silc_buffer_free(buffer);
3990 /* A timeout callback for the re-key. We will be the initiator of the
3993 SILC_TASK_CALLBACK(silc_server_rekey_callback)
3995 SilcSocketConnection sock = (SilcSocketConnection)context;
3996 SilcIDListData idata = (SilcIDListData)sock->user_data;
3997 SilcServer server = (SilcServer)idata->rekey->context;
3998 SilcProtocol protocol;
3999 SilcServerRekeyInternalContext *proto_ctx;
4001 SILC_LOG_DEBUG(("Start"));
4003 /* Allocate internal protocol context. This is sent as context
4005 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4006 proto_ctx->server = (void *)server;
4007 proto_ctx->sock = sock;
4008 proto_ctx->responder = FALSE;
4009 proto_ctx->pfs = idata->rekey->pfs;
4011 /* Perform rekey protocol. Will call the final callback after the
4012 protocol is over. */
4013 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4014 &protocol, proto_ctx, silc_server_rekey_final);
4015 sock->protocol = protocol;
4017 /* Run the protocol */
4018 silc_protocol_execute(protocol, server->schedule, 0, 0);
4020 /* Re-register re-key timeout */
4021 silc_schedule_task_add(server->schedule, sock->sock,
4022 silc_server_rekey_callback,
4023 context, idata->rekey->timeout, 0,
4024 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4027 /* The final callback for the REKEY protocol. This will actually take the
4028 new key material into use. */
4030 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4032 SilcProtocol protocol = (SilcProtocol)context;
4033 SilcServerRekeyInternalContext *ctx =
4034 (SilcServerRekeyInternalContext *)protocol->context;
4035 SilcServer server = (SilcServer)ctx->server;
4036 SilcSocketConnection sock = ctx->sock;
4038 SILC_LOG_DEBUG(("Start"));
4040 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4041 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4042 /* Error occured during protocol */
4043 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4044 silc_protocol_cancel(protocol, server->schedule);
4045 silc_protocol_free(protocol);
4046 sock->protocol = NULL;
4048 silc_packet_context_free(ctx->packet);
4050 silc_ske_free(ctx->ske);
4055 /* Purge the outgoing data queue to assure that all rekey packets really
4056 go to the network before we quit the protocol. */
4057 silc_server_packet_queue_purge(server, sock);
4060 silc_protocol_free(protocol);
4061 sock->protocol = NULL;
4063 silc_packet_context_free(ctx->packet);
4065 silc_ske_free(ctx->ske);