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);
2610 /* Remove the channel entry */
2611 if (silc_idlist_del_channel(server->local_list, channel))
2612 server->stat.my_channels--;
2614 silc_idlist_del_channel(server->global_list, channel);
2618 /* Send notify to channel about client leaving SILC and thus
2619 the entire channel. */
2621 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2622 SILC_NOTIFY_TYPE_SIGNOFF,
2623 signoff_message ? 2 : 1,
2624 clidp->data, clidp->len,
2625 signoff_message, signoff_message ?
2626 strlen(signoff_message) : 0);
2628 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2629 /* Re-generate channel key */
2630 if (!silc_server_create_channel_key(server, channel, 0))
2633 /* Send the channel key to the channel. The key of course is not sent
2634 to the client who was removed from the channel. */
2635 silc_server_send_channel_key(server, client->connection, channel,
2636 server->server_type == SILC_ROUTER ?
2637 FALSE : !server->standalone);
2641 silc_buffer_free(clidp);
2644 /* Removes client from one channel. This is used for example when client
2645 calls LEAVE command to remove itself from the channel. Returns TRUE
2646 if channel still exists and FALSE if the channel is removed when
2647 last client leaves the channel. If `notify' is FALSE notify messages
2650 int silc_server_remove_from_one_channel(SilcServer server,
2651 SilcSocketConnection sock,
2652 SilcChannelEntry channel,
2653 SilcClientEntry client,
2656 SilcChannelClientEntry chl;
2659 SILC_LOG_DEBUG(("Start"));
2661 /* Get the entry to the channel, if this client is not on the channel
2663 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2666 /* Remove the client from the channel. The client is removed from
2667 the channel's user list. */
2669 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2671 /* Remove channel from client's channel list */
2672 silc_hash_table_del(client->channels, chl->channel);
2674 /* Remove channel if there is no users anymore */
2675 if (server->server_type == SILC_ROUTER &&
2676 silc_hash_table_count(channel->user_list) < 2) {
2678 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2679 if (silc_idlist_del_channel(server->local_list, channel))
2680 server->stat.my_channels--;
2682 silc_idlist_del_channel(server->global_list, channel);
2683 silc_buffer_free(clidp);
2687 /* Remove client from channel's client list */
2688 silc_hash_table_del(channel->user_list, chl->client);
2690 /* If there is no global users on the channel anymore mark the channel
2691 as local channel. Do not check if the client is local client. */
2692 if (server->server_type != SILC_ROUTER && channel->global_users &&
2693 chl->client->router && !silc_server_channel_has_global(channel))
2694 channel->global_users = FALSE;
2697 server->stat.my_chanclients--;
2699 /* If there is not at least one local user on the channel then we don't
2700 need the channel entry anymore, we can remove it safely. */
2701 if (server->server_type != SILC_ROUTER &&
2702 !silc_server_channel_has_local(channel)) {
2703 /* Notify about leaving client if this channel has global users. */
2704 if (notify && channel->global_users)
2705 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2706 SILC_NOTIFY_TYPE_LEAVE, 1,
2707 clidp->data, clidp->len);
2709 silc_buffer_free(clidp);
2712 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2714 if (channel->founder_key) {
2715 /* The founder auth data exists, do not remove the channel entry */
2716 SilcChannelClientEntry chl2;
2717 SilcHashTableList htl2;
2719 channel->disabled = TRUE;
2721 silc_hash_table_list(channel->user_list, &htl2);
2722 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2723 silc_hash_table_del(chl2->client->channels, channel);
2724 silc_hash_table_del(channel->user_list, chl2->client);
2730 /* Remove the channel entry */
2731 if (silc_idlist_del_channel(server->local_list, channel))
2732 server->stat.my_channels--;
2734 silc_idlist_del_channel(server->global_list, channel);
2738 /* Send notify to channel about client leaving the channel */
2740 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2741 SILC_NOTIFY_TYPE_LEAVE, 1,
2742 clidp->data, clidp->len);
2744 silc_buffer_free(clidp);
2748 /* Timeout callback. This is called if connection is idle or for some
2749 other reason is not responding within some period of time. This
2750 disconnects the remote end. */
2752 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2754 SilcServer server = (SilcServer)context;
2755 SilcSocketConnection sock = server->sockets[fd];
2757 SILC_LOG_DEBUG(("Start"));
2762 /* If we have protocol active we must assure that we call the protocol's
2763 final callback so that all the memory is freed. */
2764 if (sock->protocol) {
2765 silc_protocol_cancel(sock->protocol, server->schedule);
2766 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2767 silc_protocol_execute_final(sock->protocol, server->schedule);
2768 sock->protocol = NULL;
2772 if (sock->user_data)
2773 silc_server_free_sock_user_data(server, sock, NULL);
2775 silc_server_disconnect_remote(server, sock, "Server closed connection: "
2776 "Connection timeout");
2779 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2780 function may be used only by router. In real SILC network all channels
2781 are created by routers thus this function is never used by normal
2784 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2785 SilcServerID *router_id,
2791 SilcChannelID *channel_id;
2792 SilcChannelEntry entry;
2796 SILC_LOG_DEBUG(("Creating new channel"));
2799 cipher = SILC_DEFAULT_CIPHER;
2801 hmac = SILC_DEFAULT_HMAC;
2803 /* Allocate cipher */
2804 if (!silc_cipher_alloc(cipher, &key))
2808 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2809 silc_cipher_free(key);
2813 channel_name = strdup(channel_name);
2815 /* Create the channel ID */
2816 if (!silc_id_create_channel_id(server, router_id, server->rng,
2818 silc_free(channel_name);
2819 silc_cipher_free(key);
2820 silc_hmac_free(newhmac);
2824 /* Create the channel */
2825 entry = silc_idlist_add_channel(server->local_list, channel_name,
2826 SILC_CHANNEL_MODE_NONE, channel_id,
2827 NULL, key, newhmac, 0);
2829 silc_free(channel_name);
2830 silc_cipher_free(key);
2831 silc_hmac_free(newhmac);
2832 silc_free(channel_id);
2836 entry->cipher = strdup(cipher);
2837 entry->hmac_name = strdup(hmac);
2839 /* Now create the actual key material */
2840 if (!silc_server_create_channel_key(server, entry,
2841 silc_cipher_get_key_len(key) / 8)) {
2842 silc_idlist_del_channel(server->local_list, entry);
2846 /* Notify other routers about the new channel. We send the packet
2847 to our primary route. */
2848 if (broadcast && server->standalone == FALSE)
2849 silc_server_send_new_channel(server, server->router->connection, TRUE,
2850 channel_name, entry->id,
2851 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2854 server->stat.my_channels++;
2859 /* Same as above but creates the channel with Channel ID `channel_id. */
2862 silc_server_create_new_channel_with_id(SilcServer server,
2866 SilcChannelID *channel_id,
2869 SilcChannelEntry entry;
2873 SILC_LOG_DEBUG(("Creating new channel"));
2876 cipher = SILC_DEFAULT_CIPHER;
2878 hmac = SILC_DEFAULT_HMAC;
2880 /* Allocate cipher */
2881 if (!silc_cipher_alloc(cipher, &key))
2885 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2886 silc_cipher_free(key);
2890 channel_name = strdup(channel_name);
2892 /* Create the channel */
2893 entry = silc_idlist_add_channel(server->local_list, channel_name,
2894 SILC_CHANNEL_MODE_NONE, channel_id,
2895 NULL, key, newhmac, 0);
2897 silc_cipher_free(key);
2898 silc_hmac_free(newhmac);
2899 silc_free(channel_name);
2903 /* Now create the actual key material */
2904 if (!silc_server_create_channel_key(server, entry,
2905 silc_cipher_get_key_len(key) / 8)) {
2906 silc_idlist_del_channel(server->local_list, entry);
2910 /* Notify other routers about the new channel. We send the packet
2911 to our primary route. */
2912 if (broadcast && server->standalone == FALSE)
2913 silc_server_send_new_channel(server, server->router->connection, TRUE,
2914 channel_name, entry->id,
2915 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2918 server->stat.my_channels++;
2923 /* Channel's key re-key timeout callback. */
2925 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
2927 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
2928 SilcServer server = (SilcServer)rekey->context;
2932 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
2935 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
2938 /* Generates new channel key. This is used to create the initial channel key
2939 but also to re-generate new key for channel. If `key_len' is provided
2940 it is the bytes of the key length. */
2942 bool silc_server_create_channel_key(SilcServer server,
2943 SilcChannelEntry channel,
2947 unsigned char channel_key[32], hash[32];
2950 SILC_LOG_DEBUG(("Generating channel key"));
2952 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
2953 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
2957 if (!channel->channel_key)
2958 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
2959 channel->channel_key = NULL;
2965 else if (channel->key_len)
2966 len = channel->key_len / 8;
2968 len = silc_cipher_get_key_len(channel->channel_key) / 8;
2970 /* Create channel key */
2971 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
2974 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
2976 /* Remove old key if exists */
2978 memset(channel->key, 0, channel->key_len / 8);
2979 silc_free(channel->key);
2983 channel->key_len = len * 8;
2984 channel->key = silc_calloc(len, sizeof(*channel->key));
2985 memcpy(channel->key, channel_key, len);
2986 memset(channel_key, 0, sizeof(channel_key));
2988 /* Generate HMAC key from the channel key data and set it */
2990 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
2991 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
2992 silc_hmac_set_key(channel->hmac, hash,
2993 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
2994 memset(hash, 0, sizeof(hash));
2996 if (server->server_type == SILC_ROUTER) {
2997 if (!channel->rekey)
2998 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
2999 channel->rekey->context = (void *)server;
3000 channel->rekey->channel = channel;
3001 channel->rekey->key_len = key_len;
3002 if (channel->rekey->task)
3003 silc_schedule_task_del(server->schedule, channel->rekey->task);
3005 channel->rekey->task =
3006 silc_schedule_task_add(server->schedule, 0,
3007 silc_server_channel_key_rekey,
3008 (void *)channel->rekey, 36, 0,
3010 SILC_TASK_PRI_NORMAL);
3016 /* Saves the channel key found in the encoded `key_payload' buffer. This
3017 function is used when we receive Channel Key Payload and also when we're
3018 processing JOIN command reply. Returns entry to the channel. */
3020 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3021 SilcBuffer key_payload,
3022 SilcChannelEntry channel)
3024 SilcChannelKeyPayload payload = NULL;
3025 SilcChannelID *id = NULL;
3026 unsigned char *tmp, hash[32];
3030 SILC_LOG_DEBUG(("Start"));
3032 /* Decode channel key payload */
3033 payload = silc_channel_key_payload_parse(key_payload->data,
3036 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3041 /* Get the channel entry */
3044 /* Get channel ID */
3045 tmp = silc_channel_key_get_id(payload, &tmp_len);
3046 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3052 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3054 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3056 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3057 silc_id_render(id, SILC_ID_CHANNEL)));
3063 tmp = silc_channel_key_get_key(payload, &tmp_len);
3069 cipher = silc_channel_key_get_cipher(payload, NULL);
3075 /* Remove old key if exists */
3077 memset(channel->key, 0, channel->key_len / 8);
3078 silc_free(channel->key);
3079 silc_cipher_free(channel->channel_key);
3082 /* Create new cipher */
3083 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3084 channel->channel_key = NULL;
3089 if (channel->cipher)
3090 silc_free(channel->cipher);
3091 channel->cipher = strdup(cipher);
3094 channel->key_len = tmp_len * 8;
3095 channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
3096 memcpy(channel->key, tmp, tmp_len);
3097 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3099 /* Generate HMAC key from the channel key data and set it */
3101 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3102 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3103 silc_hmac_set_key(channel->hmac, hash,
3104 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3106 memset(hash, 0, sizeof(hash));
3107 memset(tmp, 0, tmp_len);
3109 if (server->server_type == SILC_ROUTER) {
3110 if (!channel->rekey)
3111 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3112 channel->rekey->context = (void *)server;
3113 channel->rekey->channel = channel;
3114 if (channel->rekey->task)
3115 silc_schedule_task_del(server->schedule, channel->rekey->task);
3117 channel->rekey->task =
3118 silc_schedule_task_add(server->schedule, 0,
3119 silc_server_channel_key_rekey,
3120 (void *)channel->rekey, 36, 0,
3122 SILC_TASK_PRI_NORMAL);
3128 silc_channel_key_payload_free(payload);
3133 /* Heartbeat callback. This function is set as argument for the
3134 silc_socket_set_heartbeat function. The library will call this function
3135 at the set time interval. */
3137 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3140 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3142 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3144 /* Send the heartbeat */
3145 silc_server_send_heartbeat(hb->server, sock);
3148 /* Returns assembled of all servers in the given ID list. The packet's
3149 form is dictated by the New ID payload. */
3151 static void silc_server_announce_get_servers(SilcServer server,
3152 SilcServerEntry remote,
3154 SilcBuffer *servers,
3155 unsigned long creation_time)
3157 SilcIDCacheList list;
3158 SilcIDCacheEntry id_cache;
3159 SilcServerEntry entry;
3162 /* Go through all clients in the list */
3163 if (silc_idcache_get_all(id_list->servers, &list)) {
3164 if (silc_idcache_list_first(list, &id_cache)) {
3166 entry = (SilcServerEntry)id_cache->context;
3168 /* Do not announce the one we've sending our announcements and
3169 do not announce ourself. Also check the creation time if it's
3171 if ((entry == remote) || (entry == server->id_entry) ||
3172 (creation_time && entry->data.created < creation_time)) {
3173 if (!silc_idcache_list_next(list, &id_cache))
3178 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3180 *servers = silc_buffer_realloc(*servers,
3182 (*servers)->truelen + idp->len :
3184 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3185 silc_buffer_put(*servers, idp->data, idp->len);
3186 silc_buffer_pull(*servers, idp->len);
3187 silc_buffer_free(idp);
3189 if (!silc_idcache_list_next(list, &id_cache))
3194 silc_idcache_list_free(list);
3199 silc_server_announce_encode_notify(SilcNotifyType notify, uint32 argc, ...)
3205 p = silc_notify_payload_encode(notify, argc, ap);
3211 /* This function is used by router to announce existing servers to our
3212 primary router when we've connected to it. If `creation_time' is non-zero
3213 then only the servers that has been created after the `creation_time'
3214 will be announced. */
3216 void silc_server_announce_servers(SilcServer server, bool global,
3217 unsigned long creation_time,
3218 SilcSocketConnection remote)
3220 SilcBuffer servers = NULL;
3222 SILC_LOG_DEBUG(("Announcing servers"));
3224 /* Get servers in local list */
3225 silc_server_announce_get_servers(server, remote->user_data,
3226 server->local_list, &servers,
3230 /* Get servers in global list */
3231 silc_server_announce_get_servers(server, remote->user_data,
3232 server->global_list, &servers,
3236 silc_buffer_push(servers, servers->data - servers->head);
3237 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3239 /* Send the packet */
3240 silc_server_packet_send(server, remote,
3241 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3242 servers->data, servers->len, TRUE);
3244 silc_buffer_free(servers);
3248 /* Returns assembled packet of all clients in the given ID list. The
3249 packet's form is dictated by the New ID Payload. */
3251 static void silc_server_announce_get_clients(SilcServer server,
3253 SilcBuffer *clients,
3255 unsigned long creation_time)
3257 SilcIDCacheList list;
3258 SilcIDCacheEntry id_cache;
3259 SilcClientEntry client;
3262 unsigned char mode[4];
3264 /* Go through all clients in the list */
3265 if (silc_idcache_get_all(id_list->clients, &list)) {
3266 if (silc_idcache_list_first(list, &id_cache)) {
3268 client = (SilcClientEntry)id_cache->context;
3270 if (creation_time && client->data.created < creation_time) {
3271 if (!silc_idcache_list_next(list, &id_cache))
3276 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3278 *clients = silc_buffer_realloc(*clients,
3280 (*clients)->truelen + idp->len :
3282 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3283 silc_buffer_put(*clients, idp->data, idp->len);
3284 silc_buffer_pull(*clients, idp->len);
3286 SILC_PUT32_MSB(client->mode, mode);
3287 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3288 2, idp->data, idp->len,
3290 *umodes = silc_buffer_realloc(*umodes,
3292 (*umodes)->truelen + tmp->len :
3294 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3295 silc_buffer_put(*umodes, tmp->data, tmp->len);
3296 silc_buffer_pull(*umodes, tmp->len);
3297 silc_buffer_free(tmp);
3299 silc_buffer_free(idp);
3301 if (!silc_idcache_list_next(list, &id_cache))
3306 silc_idcache_list_free(list);
3310 /* This function is used to announce our existing clients to our router
3311 when we've connected to it. If `creation_time' is non-zero then only
3312 the clients that has been created after the `creation_time' will be
3315 void silc_server_announce_clients(SilcServer server,
3316 unsigned long creation_time,
3317 SilcSocketConnection remote)
3319 SilcBuffer clients = NULL;
3320 SilcBuffer umodes = NULL;
3322 SILC_LOG_DEBUG(("Announcing clients"));
3324 /* Get clients in local list */
3325 silc_server_announce_get_clients(server, server->local_list,
3326 &clients, &umodes, creation_time);
3328 /* As router we announce our global list as well */
3329 if (server->server_type == SILC_ROUTER)
3330 silc_server_announce_get_clients(server, server->global_list,
3331 &clients, &umodes, creation_time);
3334 silc_buffer_push(clients, clients->data - clients->head);
3335 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3337 /* Send the packet */
3338 silc_server_packet_send(server, remote,
3339 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3340 clients->data, clients->len, TRUE);
3342 silc_buffer_free(clients);
3346 silc_buffer_push(umodes, umodes->data - umodes->head);
3347 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3349 /* Send the packet */
3350 silc_server_packet_send(server, remote,
3351 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3352 umodes->data, umodes->len, TRUE);
3354 silc_buffer_free(umodes);
3358 /* Returns channel's topic for announcing it */
3360 void silc_server_announce_get_channel_topic(SilcServer server,
3361 SilcChannelEntry channel,
3366 if (channel->topic) {
3367 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3368 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3369 chidp->data, chidp->len,
3371 strlen(channel->topic));
3372 silc_buffer_free(chidp);
3376 /* Returns assembled packets for channel users of the `channel'. */
3378 void silc_server_announce_get_channel_users(SilcServer server,
3379 SilcChannelEntry channel,
3380 SilcBuffer *channel_users,
3381 SilcBuffer *channel_users_modes)
3383 SilcChannelClientEntry chl;
3384 SilcHashTableList htl;
3385 SilcBuffer chidp, clidp;
3388 unsigned char mode[4];
3390 SILC_LOG_DEBUG(("Start"));
3392 /* Now find all users on the channel */
3393 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3394 silc_hash_table_list(channel->user_list, &htl);
3395 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3396 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3399 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3400 clidp->data, clidp->len,
3401 chidp->data, chidp->len);
3404 silc_buffer_realloc(*channel_users,
3406 (*channel_users)->truelen + len : len));
3407 silc_buffer_pull_tail(*channel_users,
3408 ((*channel_users)->end -
3409 (*channel_users)->data));
3411 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3412 silc_buffer_pull(*channel_users, len);
3413 silc_buffer_free(tmp);
3415 /* CUMODE notify for mode change on the channel */
3416 SILC_PUT32_MSB(chl->mode, mode);
3417 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3418 3, clidp->data, clidp->len,
3420 clidp->data, clidp->len);
3422 *channel_users_modes =
3423 silc_buffer_realloc(*channel_users_modes,
3424 (*channel_users_modes ?
3425 (*channel_users_modes)->truelen + len : len));
3426 silc_buffer_pull_tail(*channel_users_modes,
3427 ((*channel_users_modes)->end -
3428 (*channel_users_modes)->data));
3430 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3431 silc_buffer_pull(*channel_users_modes, len);
3432 silc_buffer_free(tmp);
3434 silc_buffer_free(clidp);
3436 silc_buffer_free(chidp);
3439 /* Returns assembled packets for all channels and users on those channels
3440 from the given ID List. The packets are in the form dictated by the
3441 New Channel and New Channel User payloads. */
3443 void silc_server_announce_get_channels(SilcServer server,
3445 SilcBuffer *channels,
3446 SilcBuffer *channel_users,
3447 SilcBuffer **channel_users_modes,
3448 uint32 *channel_users_modes_c,
3449 SilcBuffer **channel_topics,
3450 SilcChannelID ***channel_ids,
3451 unsigned long creation_time)
3453 SilcIDCacheList list;
3454 SilcIDCacheEntry id_cache;
3455 SilcChannelEntry channel;
3460 int i = *channel_users_modes_c;
3463 SILC_LOG_DEBUG(("Start"));
3465 /* Go through all channels in the list */
3466 if (silc_idcache_get_all(id_list->channels, &list)) {
3467 if (silc_idcache_list_first(list, &id_cache)) {
3469 channel = (SilcChannelEntry)id_cache->context;
3471 if (creation_time && channel->created < creation_time)
3476 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3477 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3478 name_len = strlen(channel->channel_name);
3481 len = 4 + name_len + id_len + 4;
3483 silc_buffer_realloc(*channels,
3484 (*channels ? (*channels)->truelen +
3486 silc_buffer_pull_tail(*channels,
3487 ((*channels)->end - (*channels)->data));
3488 silc_buffer_format(*channels,
3489 SILC_STR_UI_SHORT(name_len),
3490 SILC_STR_UI_XNSTRING(channel->channel_name,
3492 SILC_STR_UI_SHORT(id_len),
3493 SILC_STR_UI_XNSTRING(cid, id_len),
3494 SILC_STR_UI_INT(channel->mode),
3496 silc_buffer_pull(*channels, len);
3499 /* Channel user modes */
3500 *channel_users_modes = silc_realloc(*channel_users_modes,
3501 sizeof(**channel_users_modes) *
3503 (*channel_users_modes)[i] = NULL;
3504 *channel_ids = silc_realloc(*channel_ids,
3505 sizeof(**channel_ids) * (i + 1));
3506 (*channel_ids)[i] = NULL;
3507 silc_server_announce_get_channel_users(server, channel,
3509 &(*channel_users_modes)[i]);
3510 (*channel_ids)[i] = channel->id;
3512 /* Channel's topic */
3513 *channel_topics = silc_realloc(*channel_topics,
3514 sizeof(**channel_topics) * (i + 1));
3515 (*channel_topics)[i] = NULL;
3516 silc_server_announce_get_channel_topic(server, channel,
3517 &(*channel_topics)[i]);
3520 if (!silc_idcache_list_next(list, &id_cache))
3524 *channel_users_modes_c += i;
3527 silc_idcache_list_free(list);
3531 /* This function is used to announce our existing channels to our router
3532 when we've connected to it. This also announces the users on the
3533 channels to the router. If the `creation_time' is non-zero only the
3534 channels that was created after the `creation_time' are announced.
3535 Note that the channel users are still announced even if the `creation_time'
3538 void silc_server_announce_channels(SilcServer server,
3539 unsigned long creation_time,
3540 SilcSocketConnection remote)
3542 SilcBuffer channels = NULL, channel_users = NULL;
3543 SilcBuffer *channel_users_modes = NULL;
3544 SilcBuffer *channel_topics = NULL;
3545 uint32 channel_users_modes_c = 0;
3546 SilcChannelID **channel_ids = NULL;
3548 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3550 /* Get channels and channel users in local list */
3551 silc_server_announce_get_channels(server, server->local_list,
3552 &channels, &channel_users,
3553 &channel_users_modes,
3554 &channel_users_modes_c,
3556 &channel_ids, creation_time);
3558 /* Get channels and channel users in global list */
3559 if (server->server_type != SILC_SERVER)
3560 silc_server_announce_get_channels(server, server->global_list,
3561 &channels, &channel_users,
3562 &channel_users_modes,
3563 &channel_users_modes_c,
3565 &channel_ids, creation_time);
3568 silc_buffer_push(channels, channels->data - channels->head);
3569 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3571 /* Send the packet */
3572 silc_server_packet_send(server, remote,
3573 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3574 channels->data, channels->len,
3577 silc_buffer_free(channels);
3580 if (channel_users) {
3581 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3582 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3583 channel_users->len);
3585 /* Send the packet */
3586 silc_server_packet_send(server, remote,
3587 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3588 channel_users->data, channel_users->len,
3591 silc_buffer_free(channel_users);
3594 if (channel_users_modes) {
3597 for (i = 0; i < channel_users_modes_c; i++) {
3598 if (!channel_users_modes[i])
3600 silc_buffer_push(channel_users_modes[i],
3601 channel_users_modes[i]->data -
3602 channel_users_modes[i]->head);
3603 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3604 channel_users_modes[i]->len);
3605 silc_server_packet_send_dest(server, remote,
3606 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3607 channel_ids[i], SILC_ID_CHANNEL,
3608 channel_users_modes[i]->data,
3609 channel_users_modes[i]->len,
3611 silc_buffer_free(channel_users_modes[i]);
3613 silc_free(channel_users_modes);
3616 if (channel_topics) {
3619 for (i = 0; i < channel_users_modes_c; i++) {
3620 if (!channel_topics[i])
3623 silc_buffer_push(channel_topics[i],
3624 channel_topics[i]->data -
3625 channel_topics[i]->head);
3626 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
3627 channel_topics[i]->len);
3628 silc_server_packet_send_dest(server, remote,
3629 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3630 channel_ids[i], SILC_ID_CHANNEL,
3631 channel_topics[i]->data,
3632 channel_topics[i]->len,
3634 silc_buffer_free(channel_topics[i]);
3636 silc_free(channel_topics);
3639 silc_free(channel_ids);
3642 /* Failure timeout callback. If this is called then we will immediately
3643 process the received failure. We always process the failure with timeout
3644 since we do not want to blindly trust to received failure packets.
3645 This won't be called (the timeout is cancelled) if the failure was
3646 bogus (it is bogus if remote does not close the connection after sending
3649 SILC_TASK_CALLBACK(silc_server_failure_callback)
3651 SilcServerFailureContext f = (SilcServerFailureContext)context;
3653 if (f->sock->protocol) {
3654 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3655 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3661 /* Assembles user list and users mode list from the `channel'. */
3663 void silc_server_get_users_on_channel(SilcServer server,
3664 SilcChannelEntry channel,
3665 SilcBuffer *user_list,
3666 SilcBuffer *mode_list,
3669 SilcChannelClientEntry chl;
3670 SilcHashTableList htl;
3671 SilcBuffer client_id_list;
3672 SilcBuffer client_mode_list;
3674 uint32 list_count = 0, len = 0;
3676 silc_hash_table_list(channel->user_list, &htl);
3677 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3678 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3680 client_id_list = silc_buffer_alloc(len);
3682 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3683 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3684 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3686 silc_hash_table_list(channel->user_list, &htl);
3687 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3689 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3690 silc_buffer_put(client_id_list, idp->data, idp->len);
3691 silc_buffer_pull(client_id_list, idp->len);
3692 silc_buffer_free(idp);
3694 /* Client's mode on channel */
3695 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3696 silc_buffer_pull(client_mode_list, 4);
3700 silc_buffer_push(client_id_list,
3701 client_id_list->data - client_id_list->head);
3702 silc_buffer_push(client_mode_list,
3703 client_mode_list->data - client_mode_list->head);
3705 *user_list = client_id_list;
3706 *mode_list = client_mode_list;
3707 *user_count = list_count;
3710 /* Saves users and their modes to the `channel'. */
3712 void silc_server_save_users_on_channel(SilcServer server,
3713 SilcSocketConnection sock,
3714 SilcChannelEntry channel,
3715 SilcClientID *noadd,
3716 SilcBuffer user_list,
3717 SilcBuffer mode_list,
3723 SilcClientID *client_id;
3724 SilcClientEntry client;
3725 SilcIDCacheEntry cache;
3728 SILC_LOG_DEBUG(("Start"));
3730 for (i = 0; i < user_count; i++) {
3732 SILC_GET16_MSB(idp_len, user_list->data + 2);
3734 client_id = silc_id_payload_parse_id(user_list->data, idp_len);
3735 silc_buffer_pull(user_list, idp_len);
3740 SILC_GET32_MSB(mode, mode_list->data);
3741 silc_buffer_pull(mode_list, 4);
3743 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3744 silc_free(client_id);
3750 /* Check if we have this client cached already. */
3751 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3752 server->server_type, &cache);
3754 client = silc_idlist_find_client_by_id(server->global_list,
3755 client_id, server->server_type,
3760 /* If router did not find such Client ID in its lists then this must
3761 be bogus client or some router in the net is buggy. */
3762 if (server->server_type == SILC_ROUTER) {
3763 silc_free(client_id);
3767 /* We don't have that client anywhere, add it. The client is added
3768 to global list since server didn't have it in the lists so it must be
3770 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3771 silc_id_dup(client_id, SILC_ID_CLIENT),
3772 sock->user_data, NULL, 0);
3774 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3775 silc_free(client_id);
3779 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3781 /* Found, if it is from global list we'll assure that we won't
3782 expire it now that the entry is on channel. */
3787 silc_free(client_id);
3789 if (!silc_server_client_on_channel(client, channel)) {
3790 /* Client was not on the channel, add it. */
3791 SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3792 chl->client = client;
3794 chl->channel = channel;
3795 silc_hash_table_add(channel->user_list, chl->client, chl);
3796 silc_hash_table_add(client->channels, chl->channel, chl);
3801 /* Lookups route to the client indicated by the `id_data'. The connection
3802 object and internal data object is returned. Returns NULL if route
3803 could not be found to the client. If the `client_id' is specified then
3804 it is used and the `id_data' is ignored. */
3806 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3807 unsigned char *id_data,
3809 SilcClientID *client_id,
3810 SilcIDListData *idata)
3813 SilcClientEntry client;
3815 SILC_LOG_DEBUG(("Start"));
3817 /* Decode destination Client ID */
3819 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3821 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3825 id = silc_id_dup(client_id, SILC_ID_CLIENT);
3828 /* If the destination belongs to our server we don't have to route
3829 the packet anywhere but to send it to the local destination. */
3830 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
3834 /* If we are router and the client has router then the client is in
3835 our cell but not directly connected to us. */
3836 if (server->server_type == SILC_ROUTER && client->router) {
3837 /* We are of course in this case the client's router thus the route
3838 to the client is the server who owns the client. So, we will send
3839 the packet to that server. */
3841 *idata = (SilcIDListData)client->router;
3842 return client->router->connection;
3845 /* Seems that client really is directly connected to us */
3847 *idata = (SilcIDListData)client;
3848 return client->connection;
3851 /* Destination belongs to someone not in this server. If we are normal
3852 server our action is to send the packet to our router. */
3853 if (server->server_type != SILC_ROUTER && !server->standalone) {
3856 *idata = (SilcIDListData)server->router;
3857 return server->router->connection;
3860 /* We are router and we will perform route lookup for the destination
3861 and send the packet to fastest route. */
3862 if (server->server_type == SILC_ROUTER && !server->standalone) {
3863 /* Check first that the ID is valid */
3864 client = silc_idlist_find_client_by_id(server->global_list, id,
3867 SilcSocketConnection dst_sock;
3869 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
3873 *idata = (SilcIDListData)dst_sock->user_data;
3882 /* Encodes and returns channel list of channels the `client' has joined.
3883 Secret channels are not put to the list. */
3885 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
3886 SilcClientEntry client)
3888 SilcBuffer buffer = NULL;
3889 SilcChannelEntry channel;
3890 SilcChannelClientEntry chl;
3891 SilcHashTableList htl;
3897 silc_hash_table_list(client->channels, &htl);
3898 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3899 channel = chl->channel;
3901 if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
3902 channel->mode & SILC_CHANNEL_MODE_PRIVATE)
3905 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3906 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3907 name_len = strlen(channel->channel_name);
3909 len = 4 + name_len + id_len + 4;
3910 buffer = silc_buffer_realloc(buffer,
3911 (buffer ? (buffer)->truelen + len : len));
3912 silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
3913 silc_buffer_format(buffer,
3914 SILC_STR_UI_SHORT(name_len),
3915 SILC_STR_UI_XNSTRING(channel->channel_name,
3917 SILC_STR_UI_SHORT(id_len),
3918 SILC_STR_UI_XNSTRING(cid, id_len),
3919 SILC_STR_UI_INT(chl->mode), /* Client's mode */
3921 silc_buffer_pull(buffer, len);
3926 silc_buffer_push(buffer, buffer->data - buffer->head);
3931 /* Finds client entry by Client ID and if it is not found then resolves
3932 it using WHOIS command. */
3934 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
3935 SilcClientID *client_id,
3938 SilcClientEntry client;
3943 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3946 client = silc_idlist_find_client_by_id(server->global_list,
3947 client_id, TRUE, NULL);
3948 if (!client && server->server_type == SILC_ROUTER)
3952 if (!client && server->standalone)
3955 if (!client || !client->nickname || !client->username) {
3956 SilcBuffer buffer, idp;
3958 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
3959 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
3960 client->resolve_cmd_ident = ++server->cmd_ident;
3962 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3963 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
3964 server->cmd_ident, 1,
3965 3, idp->data, idp->len);
3966 silc_server_packet_send(server, client ? client->router->connection :
3967 server->router->connection,
3968 SILC_PACKET_COMMAND, 0,
3969 buffer->data, buffer->len, FALSE);
3970 silc_buffer_free(idp);
3971 silc_buffer_free(buffer);
3982 /* A timeout callback for the re-key. We will be the initiator of the
3985 SILC_TASK_CALLBACK(silc_server_rekey_callback)
3987 SilcSocketConnection sock = (SilcSocketConnection)context;
3988 SilcIDListData idata = (SilcIDListData)sock->user_data;
3989 SilcServer server = (SilcServer)idata->rekey->context;
3990 SilcProtocol protocol;
3991 SilcServerRekeyInternalContext *proto_ctx;
3993 SILC_LOG_DEBUG(("Start"));
3995 /* Allocate internal protocol context. This is sent as context
3997 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
3998 proto_ctx->server = (void *)server;
3999 proto_ctx->sock = sock;
4000 proto_ctx->responder = FALSE;
4001 proto_ctx->pfs = idata->rekey->pfs;
4003 /* Perform rekey protocol. Will call the final callback after the
4004 protocol is over. */
4005 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4006 &protocol, proto_ctx, silc_server_rekey_final);
4007 sock->protocol = protocol;
4009 /* Run the protocol */
4010 silc_protocol_execute(protocol, server->schedule, 0, 0);
4012 /* Re-register re-key timeout */
4013 silc_schedule_task_add(server->schedule, sock->sock,
4014 silc_server_rekey_callback,
4015 context, idata->rekey->timeout, 0,
4016 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4019 /* The final callback for the REKEY protocol. This will actually take the
4020 new key material into use. */
4022 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4024 SilcProtocol protocol = (SilcProtocol)context;
4025 SilcServerRekeyInternalContext *ctx =
4026 (SilcServerRekeyInternalContext *)protocol->context;
4027 SilcServer server = (SilcServer)ctx->server;
4028 SilcSocketConnection sock = ctx->sock;
4030 SILC_LOG_DEBUG(("Start"));
4032 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4033 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4034 /* Error occured during protocol */
4035 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4036 silc_protocol_cancel(protocol, server->schedule);
4037 silc_protocol_free(protocol);
4038 sock->protocol = NULL;
4040 silc_packet_context_free(ctx->packet);
4042 silc_ske_free(ctx->ske);
4047 /* Purge the outgoing data queue to assure that all rekey packets really
4048 go to the network before we quit the protocol. */
4049 silc_server_packet_queue_purge(server, sock);
4052 silc_protocol_free(protocol);
4053 sock->protocol = NULL;
4055 silc_packet_context_free(ctx->packet);
4057 silc_ske_free(ctx->ske);