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 = 0, 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;
146 silc_server_config_setlogfiles(server->config);
148 /* Register all configured ciphers, PKCS and hash functions. */
149 if (!silc_server_config_register_ciphers(server->config))
150 silc_cipher_register_default();
151 if (!silc_server_config_register_pkcs(server->config))
152 silc_pkcs_register_default();
153 if (!silc_server_config_register_hashfuncs(server->config))
154 silc_hash_register_default();
155 if (!silc_server_config_register_hmacs(server->config))
156 silc_hmac_register_default();
158 /* Initialize random number generator for the server. */
159 server->rng = silc_rng_alloc();
160 silc_rng_init(server->rng);
161 silc_rng_global_init(server->rng);
163 /* Initialize hash functions for server to use */
164 silc_hash_alloc("md5", &server->md5hash);
165 silc_hash_alloc("sha1", &server->sha1hash);
167 /* Initialize none cipher */
168 silc_cipher_alloc("none", &server->none_cipher);
170 /* Allocate PKCS context for local public and private keys */
171 silc_pkcs_alloc(server->public_key->name, &server->pkcs);
172 silc_pkcs_public_key_set(server->pkcs, server->public_key);
173 silc_pkcs_private_key_set(server->pkcs, server->private_key);
175 /* Create a listening server. Note that our server can listen on multiple
176 ports. All listeners are created here and now. */
178 listen = server->config->listen_port;
182 tmp = silc_net_create_server(server->config->listen_port->port,
183 server->config->listen_port->listener_ip);
187 sock = silc_realloc(sock, (sizeof(int *) * (sock_count + 1)));
188 sock[sock_count] = tmp;
190 listen = listen->next;
193 /* Initialize ID caches */
194 server->local_list->clients =
195 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
196 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
197 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
199 /* These are allocated for normal server as well as these hold some
200 global information that the server has fetched from its router. For
201 router these are used as they are supposed to be used on router. */
202 server->global_list->clients =
203 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
204 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
205 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
207 /* Allocate the entire socket list that is used in server. Eventually
208 all connections will have entry in this table (it is a table of
209 pointers to the actual object that is allocated individually
211 server->sockets = silc_calloc(SILC_SERVER_MAX_CONNECTIONS,
212 sizeof(*server->sockets));
214 for (i = 0; i < sock_count; i++) {
215 SilcSocketConnection newsocket = NULL;
217 /* Set socket to non-blocking mode */
218 silc_net_set_socket_nonblock(sock[i]);
219 server->sock = sock[i];
221 /* Create a Server ID for the server. */
222 silc_id_create_server_id(sock[i], server->rng, &id);
228 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
229 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
230 server->id_type = SILC_ID_SERVER;
231 server->server_name = server->config->server_info->server_name;
233 /* Add ourselves to the server list. We don't have a router yet
234 beacuse we haven't established a route yet. It will be done later.
235 For now, NULL is sent as router. This allocates new entry to
238 silc_idlist_add_server(server->local_list,
239 server->config->server_info->server_name,
240 server->server_type, server->id, NULL, NULL);
242 SILC_LOG_ERROR(("Could not add ourselves to cache"));
245 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
247 /* Add ourselves also to the socket table. The entry allocated above
248 is sent as argument for fast referencing in the future. */
249 silc_socket_alloc(sock[i], SILC_SOCKET_TYPE_SERVER, id_entry,
252 server->sockets[sock[i]] = newsocket;
254 /* Perform name and address lookups to resolve the listenning address
256 if (!silc_net_check_local_by_sock(sock[i], &newsocket->hostname,
258 if ((server->params->require_reverse_mapping && !newsocket->hostname) ||
260 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
261 newsocket->hostname ? newsocket->hostname :
262 newsocket->ip ? newsocket->ip : ""));
263 server->stat.conn_failures++;
266 if (!newsocket->hostname)
267 newsocket->hostname = strdup(newsocket->ip);
269 newsocket->port = silc_net_get_local_port(sock[i]);
271 /* Put the allocated socket pointer also to the entry allocated above
272 for fast back-referencing to the socket list. */
273 id_entry->connection = (void *)server->sockets[sock[i]];
274 server->id_entry = id_entry;
277 /* Register protocols */
278 silc_server_protocols_register();
280 /* Initialize the scheduler. */
281 server->schedule = silc_schedule_init(SILC_SERVER_MAX_CONNECTIONS);
282 if (!server->schedule)
285 /* Add the first task to the scheduler. This is task that is executed by
286 timeout. It expires as soon as the caller calls silc_server_run. This
287 task performs authentication protocol and key exchange with our
289 silc_schedule_task_add(server->schedule, sock[0],
290 silc_server_connect_to_router,
291 (void *)server, 0, 1,
293 SILC_TASK_PRI_NORMAL);
295 /* Add listener task to the scheduler. This task receives new connections
296 to the server. This task remains on the queue until the end of the
298 silc_schedule_task_add(server->schedule, sock[0],
299 silc_server_accept_new_connection,
300 (void *)server, 0, 0,
302 SILC_TASK_PRI_NORMAL);
303 server->listenning = TRUE;
305 /* If server connections has been configured then we must be router as
306 normal server cannot have server connections, only router connections. */
307 if (server->config->servers) {
308 SilcServerConfigSectionServerConnection *ptr = server->config->servers;
310 server->server_type = SILC_ROUTER;
312 if (ptr->backup_router) {
313 server->server_type = SILC_BACKUP_ROUTER;
314 server->backup_router = TRUE;
321 /* Register the ID Cache purge task. This periodically purges the ID cache
322 and removes the expired cache entries. */
324 /* Clients local list */
325 purge = silc_calloc(1, sizeof(*purge));
326 purge->cache = server->local_list->clients;
327 purge->schedule = server->schedule;
328 silc_schedule_task_add(purge->schedule, 0,
330 (void *)purge, 600, 0,
331 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
333 /* Clients global list */
334 purge = silc_calloc(1, sizeof(*purge));
335 purge->cache = server->global_list->clients;
336 purge->schedule = server->schedule;
337 silc_schedule_task_add(purge->schedule, 0,
339 (void *)purge, 300, 0,
340 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
342 SILC_LOG_DEBUG(("Server initialized"));
344 /* We are done here, return succesfully */
348 for (i = 0; i < sock_count; i++)
349 silc_net_close_server(sock[i]);
354 /* Fork server to background and set gid+uid to non-root.
355 Silcd will not run as root, so trying to set either user or group to
356 root will cause silcd to exit. */
358 void silc_server_daemonise(SilcServer server)
360 /* Are we executing silcd as root or a regular user? */
367 if (!server->config->identity || !server->config->identity->user ||
368 !server->config->identity->group) {
369 fprintf(stderr, "Error:"
370 "\tSILC server must not be run as root. For the security of your\n"
371 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
372 "\tuser account. Modify the [Identity] configuration section to run\n"
373 "\tthe server as non-root user.\n");
377 /* Get the values given for user and group in configuration file */
378 user=server->config->identity->user;
379 group=server->config->identity->group;
381 /* Check whether the user/group information is text */
382 if (atoi(user)!=0 || atoi(group)!=0) {
383 SILC_LOG_DEBUG(("Invalid user and/or group information"));
384 SILC_LOG_DEBUG(("User and/or group given as number"));
385 fprintf(stderr, "Invalid user and/or group information\n");
386 fprintf(stderr, "Please assign them as names, not numbers\n");
390 /* Catch the nasty incident of string "0" returning 0 from atoi */
391 if (strcmp("0", user)==0 || strcmp("0", group)==0) {
392 SILC_LOG_DEBUG(("User and/or group configured to 0. Unacceptable"));
393 fprintf(stderr, "User and/or group configured to 0. Exiting\n");
401 fprintf(stderr, "No such user %s found\n", user);
406 fprintf(stderr, "No such group %s found\n", group);
410 /* Check whether user and/or group is set to root. If yes, exit
411 immediately. Otherwise, setgid and setuid server to user.group */
412 if (gr->gr_gid==0 || pw->pw_uid==0) {
413 fprintf(stderr, "Error:"
414 "\tSILC server must not be run as root. For the security of your\n"
415 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
416 "\tuser account. Modify the [Identity] configuration section to run\n"
417 "\tthe server as non-root user.\n");
420 /* Fork server to background, making it a daemon */
422 SILC_LOG_DEBUG(("Server started as root. Dropping privileges."));
423 SILC_LOG_DEBUG(("Forking SILC server to background"));
428 SILC_LOG_DEBUG(("Changing to group %s", group));
429 if(setgid(gr->gr_gid)==0) {
430 SILC_LOG_DEBUG(("Setgid to %s", group));
432 SILC_LOG_DEBUG(("Setgid to %s failed", group));
433 fprintf(stderr, "Tried to setgid %s but no such group. Exiting\n",
437 SILC_LOG_DEBUG(("Changing to user nobody"));
438 if(setuid(pw->pw_uid)==0) {
439 SILC_LOG_DEBUG(("Setuid to %s", user));
441 SILC_LOG_DEBUG(("Setuid to %s failed", user));
442 fprintf(stderr, "Tried to setuid %s but no such user. Exiting\n",
448 /* Fork server to background, making it a daemon */
450 SILC_LOG_DEBUG(("Server started as user"));
451 SILC_LOG_DEBUG(("Forking SILC server to background"));
458 /* The heart of the server. This runs the scheduler thus runs the server.
459 When this returns the server has been stopped and the program will
462 void silc_server_run(SilcServer server)
464 SILC_LOG_DEBUG(("Running server"));
466 SILC_LOG_INFO(("SILC Server started"));
468 /* Start the scheduler, the heart of the SILC server. When this returns
469 the program will be terminated. */
470 silc_schedule(server->schedule);
473 /* Stops the SILC server. This function is used to shutdown the server.
474 This is usually called after the scheduler has returned. After stopping
475 the server one should call silc_server_free. */
477 void silc_server_stop(SilcServer server)
479 SILC_LOG_DEBUG(("Stopping server"));
481 silc_schedule_stop(server->schedule);
482 silc_schedule_uninit(server->schedule);
484 silc_server_protocols_unregister();
486 SILC_LOG_DEBUG(("Server stopped"));
489 /* Function that is called when the network connection to a router has
490 been established. This will continue with the key exchange protocol
491 with the remote router. */
493 void silc_server_start_key_exchange(SilcServer server,
494 SilcServerConnection sconn,
497 SilcSocketConnection newsocket;
498 SilcProtocol protocol;
499 SilcServerKEInternalContext *proto_ctx;
502 /* Set socket options */
503 silc_net_set_socket_nonblock(sock);
504 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
506 /* Create socket connection for the connection. Even though we
507 know that we are connecting to a router we will mark the socket
508 to be unknown connection until we have executed authentication
510 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
511 server->sockets[sock] = newsocket;
512 newsocket->hostname = strdup(sconn->remote_host);
513 newsocket->ip = strdup(sconn->remote_host);
514 newsocket->port = sconn->remote_port;
515 sconn->sock = newsocket;
517 /* Allocate internal protocol context. This is sent as context
519 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
520 proto_ctx->server = (void *)server;
521 proto_ctx->context = (void *)sconn;
522 proto_ctx->sock = newsocket;
523 proto_ctx->rng = server->rng;
524 proto_ctx->responder = FALSE;
526 /* Perform key exchange protocol. silc_server_connect_to_router_second
527 will be called after the protocol is finished. */
528 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
529 &protocol, proto_ctx,
530 silc_server_connect_to_router_second);
531 newsocket->protocol = protocol;
533 /* Register a timeout task that will be executed if the protocol
534 is not executed within set limit. */
535 proto_ctx->timeout_task =
536 silc_schedule_task_add(server->schedule, sock,
537 silc_server_timeout_remote,
538 server, server->params->protocol_timeout,
539 server->params->protocol_timeout_usec,
543 /* Register the connection for network input and output. This sets
544 that scheduler will listen for incoming packets for this connection
545 and sets that outgoing packets may be sent to this connection as
546 well. However, this doesn't set the scheduler for outgoing traffic,
547 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
548 later when outgoing data is available. */
549 context = (void *)server;
550 SILC_REGISTER_CONNECTION_FOR_IO(sock);
552 /* Run the protocol */
553 silc_protocol_execute(protocol, server->schedule, 0, 0);
556 /* Timeout callback that will be called to retry connecting to remote
557 router. This is used by both normal and router server. This will wait
558 before retrying the connecting. The timeout is generated by exponential
559 backoff algorithm. */
561 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
563 SilcServerConnection sconn = (SilcServerConnection)context;
564 SilcServer server = sconn->server;
566 SILC_LOG_INFO(("Retrying connecting to a router"));
568 /* Calculate next timeout */
569 if (sconn->retry_count >= 1) {
570 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
571 if (sconn->retry_timeout > SILC_SERVER_RETRY_INTERVAL_MAX)
572 sconn->retry_timeout = SILC_SERVER_RETRY_INTERVAL_MAX;
574 sconn->retry_timeout = server->params->retry_interval_min;
576 sconn->retry_count++;
577 sconn->retry_timeout = sconn->retry_timeout +
578 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
580 /* If we've reached max retry count, give up. */
581 if (sconn->retry_count > server->params->retry_count &&
582 server->params->retry_keep_trying == FALSE) {
583 SILC_LOG_ERROR(("Could not connect to router, giving up"));
587 /* Wait one before retrying */
588 silc_schedule_task_add(server->schedule, fd, silc_server_connect_router,
589 context, sconn->retry_timeout,
590 server->params->retry_interval_min_usec,
591 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
594 /* Generic routine to use connect to a router. */
596 SILC_TASK_CALLBACK(silc_server_connect_router)
598 SilcServerConnection sconn = (SilcServerConnection)context;
599 SilcServer server = sconn->server;
602 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
603 (sconn->backup ? "backup router" : "router"),
604 sconn->remote_host, sconn->remote_port));
606 server->router_connect = time(0);
608 /* Connect to remote host */
609 sock = silc_net_create_connection(server->config->listen_port->local_ip,
613 SILC_LOG_ERROR(("Could not connect to router"));
614 silc_schedule_task_add(server->schedule, fd,
615 silc_server_connect_to_router_retry,
616 context, 0, 1, SILC_TASK_TIMEOUT,
617 SILC_TASK_PRI_NORMAL);
621 /* Continue with key exchange protocol */
622 silc_server_start_key_exchange(server, sconn, sock);
625 /* This function connects to our primary router or if we are a router this
626 establishes all our primary routes. This is called at the start of the
627 server to do authentication and key exchange with our router - called
630 SILC_TASK_CALLBACK(silc_server_connect_to_router)
632 SilcServer server = (SilcServer)context;
633 SilcServerConnection sconn;
634 SilcServerConfigSectionServerConnection *ptr;
636 SILC_LOG_DEBUG(("Connecting to router(s)"));
638 if (server->server_type == SILC_SERVER) {
639 SILC_LOG_DEBUG(("We are normal server"));
640 } else if (server->server_type == SILC_ROUTER) {
641 SILC_LOG_DEBUG(("We are router"));
643 SILC_LOG_DEBUG(("We are backup router/normal server"));
646 /* Create the connections to all our routes */
647 ptr = server->config->routers;
650 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
651 ptr->backup_router ? "Backup router" : "Router",
652 ptr->initiator ? "Initiator" : "Responder",
653 ptr->host, ptr->port));
655 if (ptr->initiator) {
656 /* Allocate connection object for hold connection specific stuff. */
657 sconn = silc_calloc(1, sizeof(*sconn));
658 sconn->server = server;
659 sconn->remote_host = strdup(ptr->host);
660 sconn->remote_port = ptr->port;
661 sconn->backup = ptr->backup_router;
663 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
664 sconn->backup_replace_port = ptr->backup_replace_port;
667 silc_schedule_task_add(server->schedule, fd,
668 silc_server_connect_router,
669 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
670 SILC_TASK_PRI_NORMAL);
679 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
681 /* There wasn't a configured router, we will continue but we don't
682 have a connection to outside world. We will be standalone server. */
683 server->standalone = TRUE;
686 /* Second part of connecting to router(s). Key exchange protocol has been
687 executed and now we will execute authentication protocol. */
689 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
691 SilcProtocol protocol = (SilcProtocol)context;
692 SilcServerKEInternalContext *ctx =
693 (SilcServerKEInternalContext *)protocol->context;
694 SilcServer server = (SilcServer)ctx->server;
695 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
696 SilcSocketConnection sock = ctx->sock;
697 SilcServerConnAuthInternalContext *proto_ctx;
698 SilcServerConfigSectionServerConnection *conn = NULL;
700 SILC_LOG_DEBUG(("Start"));
702 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
703 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
704 /* Error occured during protocol */
705 silc_protocol_free(protocol);
706 sock->protocol = NULL;
707 silc_ske_free_key_material(ctx->keymat);
709 silc_packet_context_free(ctx->packet);
711 silc_ske_free(ctx->ske);
712 silc_free(ctx->dest_id);
714 silc_schedule_task_del_by_callback(server->schedule,
715 silc_server_failure_callback);
716 silc_server_disconnect_remote(server, sock, "Server closed connection: "
717 "Key exchange failed");
721 /* We now have the key material as the result of the key exchange
722 protocol. Take the key material into use. Free the raw key material
723 as soon as we've set them into use. */
724 if (!silc_server_protocol_ke_set_keys(ctx->ske, ctx->sock, ctx->keymat,
725 ctx->ske->prop->cipher,
726 ctx->ske->prop->pkcs,
727 ctx->ske->prop->hash,
728 ctx->ske->prop->hmac,
729 ctx->ske->prop->group,
731 silc_protocol_free(protocol);
732 sock->protocol = NULL;
733 silc_ske_free_key_material(ctx->keymat);
735 silc_packet_context_free(ctx->packet);
737 silc_ske_free(ctx->ske);
738 silc_free(ctx->dest_id);
740 silc_schedule_task_del_by_callback(server->schedule,
741 silc_server_failure_callback);
742 silc_server_disconnect_remote(server, sock, "Server closed connection: "
743 "Key exchange failed");
746 silc_ske_free_key_material(ctx->keymat);
748 /* Allocate internal context for the authentication protocol. This
749 is sent as context for the protocol. */
750 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
751 proto_ctx->server = (void *)server;
752 proto_ctx->context = (void *)sconn;
753 proto_ctx->sock = sock;
754 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
755 proto_ctx->dest_id_type = ctx->dest_id_type;
756 proto_ctx->dest_id = ctx->dest_id;
758 /* Resolve the authentication method used in this connection. Check if
759 we find a match from user configured connections */
760 conn = silc_server_config_find_router_conn(server->config,
764 /* Match found. Use the configured authentication method */
765 proto_ctx->auth_meth = conn->auth_meth;
766 if (conn->auth_data) {
767 proto_ctx->auth_data = strdup(conn->auth_data);
768 proto_ctx->auth_data_len = strlen(conn->auth_data);
771 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
772 sock->hostname, sock->ip, sock->port));
773 silc_protocol_free(protocol);
774 sock->protocol = NULL;
776 silc_packet_context_free(ctx->packet);
778 silc_ske_free(ctx->ske);
779 silc_free(ctx->dest_id);
781 silc_schedule_task_del_by_callback(server->schedule,
782 silc_server_failure_callback);
783 silc_server_disconnect_remote(server, sock, "Server closed connection: "
784 "Key exchange failed");
788 /* Free old protocol as it is finished now */
789 silc_protocol_free(protocol);
791 silc_packet_context_free(ctx->packet);
793 sock->protocol = NULL;
795 /* Allocate the authentication protocol. This is allocated here
796 but we won't start it yet. We will be receiving party of this
797 protocol thus we will wait that connecting party will make
799 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
800 &sock->protocol, proto_ctx,
801 silc_server_connect_to_router_final);
803 /* Register timeout task. If the protocol is not executed inside
804 this timelimit the connection will be terminated. Currently
805 this is 15 seconds and is hard coded limit (XXX). */
806 proto_ctx->timeout_task =
807 silc_schedule_task_add(server->schedule, sock->sock,
808 silc_server_timeout_remote,
809 (void *)server, 15, 0,
813 /* Run the protocol */
814 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
817 /* Finalizes the connection to router. Registers a server task to the
818 queue so that we can accept new connections. */
820 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
822 SilcProtocol protocol = (SilcProtocol)context;
823 SilcServerConnAuthInternalContext *ctx =
824 (SilcServerConnAuthInternalContext *)protocol->context;
825 SilcServer server = (SilcServer)ctx->server;
826 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
827 SilcSocketConnection sock = ctx->sock;
828 SilcServerEntry id_entry;
830 SilcServerHBContext hb_context;
831 unsigned char *id_string;
833 SilcIDListData idata;
835 SILC_LOG_DEBUG(("Start"));
837 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
838 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
839 /* Error occured during protocol */
840 silc_free(ctx->dest_id);
841 silc_server_disconnect_remote(server, sock, "Server closed connection: "
842 "Authentication failed");
846 /* Add a task to the queue. This task receives new connections to the
847 server. This task remains on the queue until the end of the program. */
848 if (!server->listenning && !sconn->backup) {
849 silc_schedule_task_add(server->schedule, server->sock,
850 silc_server_accept_new_connection,
851 (void *)server, 0, 0,
853 SILC_TASK_PRI_NORMAL);
854 server->listenning = TRUE;
857 /* Send NEW_SERVER packet to the router. We will become registered
858 to the SILC network after sending this packet. */
859 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
860 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
861 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
862 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
863 silc_buffer_format(packet,
864 SILC_STR_UI_SHORT(id_len),
865 SILC_STR_UI_XNSTRING(id_string, id_len),
866 SILC_STR_UI_SHORT(strlen(server->server_name)),
867 SILC_STR_UI_XNSTRING(server->server_name,
868 strlen(server->server_name)),
871 /* Send the packet */
872 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
873 packet->data, packet->len, TRUE);
874 silc_buffer_free(packet);
875 silc_free(id_string);
877 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
879 /* Check that we do not have this ID already */
880 id_entry = silc_idlist_find_server_by_id(server->local_list,
881 ctx->dest_id, TRUE, NULL);
883 silc_idcache_del_by_context(server->local_list->servers, id_entry);
885 id_entry = silc_idlist_find_server_by_id(server->global_list,
886 ctx->dest_id, TRUE, NULL);
888 silc_idcache_del_by_context(server->global_list->servers, id_entry);
891 SILC_LOG_DEBUG(("New server id(%s)",
892 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
894 /* Add the connected router to global server list */
895 id_entry = silc_idlist_add_server(server->global_list,
896 strdup(sock->hostname),
897 SILC_ROUTER, ctx->dest_id, NULL, sock);
899 silc_free(ctx->dest_id);
900 silc_server_disconnect_remote(server, sock, "Server closed connection: "
901 "Authentication failed");
905 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
906 silc_free(sock->user_data);
907 sock->user_data = (void *)id_entry;
908 sock->type = SILC_SOCKET_TYPE_ROUTER;
909 idata = (SilcIDListData)sock->user_data;
910 idata->status |= SILC_IDLIST_STATUS_REGISTERED;
912 /* Perform keepalive. The `hb_context' will be freed automatically
913 when finally calling the silc_socket_free function. XXX hardcoded
915 hb_context = silc_calloc(1, sizeof(*hb_context));
916 hb_context->server = server;
917 silc_socket_set_heartbeat(sock, 600, hb_context,
918 silc_server_perform_heartbeat,
921 /* Register re-key timeout */
922 idata->rekey->timeout = 3600; /* XXX hardcoded */
923 idata->rekey->context = (void *)server;
924 silc_schedule_task_add(server->schedule, sock->sock,
925 silc_server_rekey_callback,
926 (void *)sock, idata->rekey->timeout, 0,
927 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
929 if (!sconn->backup) {
930 /* Mark this router our primary router if we're still standalone */
931 if (server->standalone) {
932 server->id_entry->router = id_entry;
933 server->router = id_entry;
934 server->standalone = FALSE;
936 /* If we are router then announce our possible servers. */
937 if (server->server_type == SILC_ROUTER)
938 silc_server_announce_servers(server, FALSE, 0,
939 server->router->connection);
941 /* Announce our clients and channels to the router */
942 silc_server_announce_clients(server, 0, server->router->connection);
943 silc_server_announce_channels(server, 0, server->router->connection);
946 /* Add this server to be our backup router */
947 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
948 sconn->backup_replace_port, FALSE);
951 sock->protocol = NULL;
953 /* Call the completion callback to indicate that we've connected to
956 (*sconn->callback)(server, id_entry, sconn->callback_context);
959 /* Free the temporary connection data context */
961 silc_free(sconn->remote_host);
962 silc_free(sconn->backup_replace_ip);
966 /* Free the protocol object */
967 if (sock->protocol == protocol)
968 sock->protocol = NULL;
969 silc_protocol_free(protocol);
971 silc_packet_context_free(ctx->packet);
973 silc_ske_free(ctx->ske);
977 /* Host lookup callbcak that is called after the incoming connection's
978 IP and FQDN lookup is performed. This will actually check the acceptance
979 of the incoming connection and will register the key exchange protocol
980 for this connection. */
983 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
986 SilcServer server = (SilcServer)context;
987 SilcServerKEInternalContext *proto_ctx;
988 void *cconfig, *sconfig, *rconfig;
989 SilcServerConfigSectionDenyConnection *deny;
992 SILC_LOG_DEBUG(("Start"));
994 /* Check whether we could resolve both IP and FQDN. */
995 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
996 server->params->require_reverse_mapping)) {
997 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
998 sock->hostname ? sock->hostname :
999 sock->ip ? sock->ip : ""));
1000 server->stat.conn_failures++;
1001 silc_server_disconnect_remote(server, sock,
1002 "Server closed connection: Unknown host");
1006 /* Register the connection for network input and output. This sets
1007 that scheduler will listen for incoming packets for this connection
1008 and sets that outgoing packets may be sent to this connection as well.
1009 However, this doesn't set the scheduler for outgoing traffic, it
1010 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1011 later when outgoing data is available. */
1012 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1014 SILC_LOG_INFO(("Incoming connection from %s (%s)", sock->hostname,
1017 port = server->sockets[server->sock]->port; /* Listenning port */
1019 /* Check whether this connection is denied to connect to us. */
1020 deny = silc_server_config_denied_conn(server->config, sock->ip, port);
1022 deny = silc_server_config_denied_conn(server->config, sock->hostname,
1025 /* The connection is denied */
1026 SILC_LOG_INFO(("Connection %s (%s) is denied",
1027 sock->hostname, sock->ip));
1028 silc_server_disconnect_remote(server, sock, deny->comment ?
1030 "Server closed connection: "
1031 "Connection refused");
1032 server->stat.conn_failures++;
1036 /* Check whether we have configred this sort of connection at all. We
1037 have to check all configurations since we don't know what type of
1038 connection this is. */
1039 if (!(cconfig = silc_server_config_find_client_conn(server->config,
1041 cconfig = silc_server_config_find_client_conn(server->config,
1044 if (!(sconfig = silc_server_config_find_server_conn(server->config,
1047 sconfig = silc_server_config_find_server_conn(server->config,
1050 if (!(rconfig = silc_server_config_find_router_conn(server->config,
1052 rconfig = silc_server_config_find_router_conn(server->config,
1055 if (!cconfig && !sconfig && !rconfig) {
1056 silc_server_disconnect_remote(server, sock,
1057 "Server closed connection: "
1058 "Connection refused");
1059 server->stat.conn_failures++;
1063 /* The connection is allowed */
1065 /* Allocate internal context for key exchange protocol. This is
1066 sent as context for the protocol. */
1067 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1068 proto_ctx->server = context;
1069 proto_ctx->sock = sock;
1070 proto_ctx->rng = server->rng;
1071 proto_ctx->responder = TRUE;
1072 proto_ctx->cconfig = cconfig;
1073 proto_ctx->sconfig = sconfig;
1074 proto_ctx->rconfig = rconfig;
1076 /* Prepare the connection for key exchange protocol. We allocate the
1077 protocol but will not start it yet. The connector will be the
1078 initiator of the protocol thus we will wait for initiation from
1079 there before we start the protocol. */
1080 server->stat.auth_attempts++;
1081 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1082 &sock->protocol, proto_ctx,
1083 silc_server_accept_new_connection_second);
1085 /* Register a timeout task that will be executed if the connector
1086 will not start the key exchange protocol within 60 seconds. For
1087 now, this is a hard coded limit. After 60 secs the connection will
1088 be closed if the key exchange protocol has not been started. */
1089 proto_ctx->timeout_task =
1090 silc_schedule_task_add(server->schedule, sock->sock,
1091 silc_server_timeout_remote,
1097 /* Accepts new connections to the server. Accepting new connections are
1098 done in three parts to make it async. */
1100 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1102 SilcServer server = (SilcServer)context;
1103 SilcSocketConnection newsocket;
1106 SILC_LOG_DEBUG(("Accepting new connection"));
1108 server->stat.conn_attempts++;
1110 sock = silc_net_accept_connection(server->sock);
1112 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1113 server->stat.conn_failures++;
1117 /* Check max connections */
1118 if (sock > SILC_SERVER_MAX_CONNECTIONS) {
1119 SILC_LOG_ERROR(("Refusing connection, server is full"));
1120 server->stat.conn_failures++;
1124 /* Set socket options */
1125 silc_net_set_socket_nonblock(sock);
1126 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1128 /* We don't create a ID yet, since we don't know what type of connection
1129 this is yet. But, we do add the connection to the socket table. */
1130 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1131 server->sockets[sock] = newsocket;
1133 /* Perform asynchronous host lookup. This will lookup the IP and the
1134 FQDN of the remote connection. After the lookup is done the connection
1135 is accepted further. */
1136 silc_socket_host_lookup(newsocket, TRUE,
1137 silc_server_accept_new_connection_lookup, context,
1141 /* Second part of accepting new connection. Key exchange protocol has been
1142 performed and now it is time to do little connection authentication
1143 protocol to figure out whether this connection is client or server
1144 and whether it has right to access this server (especially server
1145 connections needs to be authenticated). */
1147 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1149 SilcProtocol protocol = (SilcProtocol)context;
1150 SilcServerKEInternalContext *ctx =
1151 (SilcServerKEInternalContext *)protocol->context;
1152 SilcServer server = (SilcServer)ctx->server;
1153 SilcSocketConnection sock = ctx->sock;
1154 SilcServerConnAuthInternalContext *proto_ctx;
1156 SILC_LOG_DEBUG(("Start"));
1158 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1159 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1160 /* Error occured during protocol */
1161 silc_protocol_free(protocol);
1162 sock->protocol = NULL;
1163 silc_ske_free_key_material(ctx->keymat);
1165 silc_packet_context_free(ctx->packet);
1167 silc_ske_free(ctx->ske);
1168 silc_free(ctx->dest_id);
1170 silc_schedule_task_del_by_callback(server->schedule,
1171 silc_server_failure_callback);
1172 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1173 "Key exchange failed");
1174 server->stat.auth_failures++;
1178 /* We now have the key material as the result of the key exchange
1179 protocol. Take the key material into use. Free the raw key material
1180 as soon as we've set them into use. */
1181 if (!silc_server_protocol_ke_set_keys(ctx->ske, ctx->sock, ctx->keymat,
1182 ctx->ske->prop->cipher,
1183 ctx->ske->prop->pkcs,
1184 ctx->ske->prop->hash,
1185 ctx->ske->prop->hmac,
1186 ctx->ske->prop->group,
1188 silc_protocol_free(protocol);
1189 sock->protocol = NULL;
1190 silc_ske_free_key_material(ctx->keymat);
1192 silc_packet_context_free(ctx->packet);
1194 silc_ske_free(ctx->ske);
1195 silc_free(ctx->dest_id);
1197 silc_schedule_task_del_by_callback(server->schedule,
1198 silc_server_failure_callback);
1199 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1200 "Key exchange failed");
1201 server->stat.auth_failures++;
1204 silc_ske_free_key_material(ctx->keymat);
1206 /* Allocate internal context for the authentication protocol. This
1207 is sent as context for the protocol. */
1208 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1209 proto_ctx->server = (void *)server;
1210 proto_ctx->sock = sock;
1211 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1212 proto_ctx->responder = TRUE;
1213 proto_ctx->dest_id_type = ctx->dest_id_type;
1214 proto_ctx->dest_id = ctx->dest_id;
1215 proto_ctx->cconfig = ctx->cconfig;
1216 proto_ctx->sconfig = ctx->sconfig;
1217 proto_ctx->rconfig = ctx->rconfig;
1219 /* Free old protocol as it is finished now */
1220 silc_protocol_free(protocol);
1222 silc_packet_context_free(ctx->packet);
1224 sock->protocol = NULL;
1226 /* Allocate the authentication protocol. This is allocated here
1227 but we won't start it yet. We will be receiving party of this
1228 protocol thus we will wait that connecting party will make
1229 their first move. */
1230 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1231 &sock->protocol, proto_ctx,
1232 silc_server_accept_new_connection_final);
1234 /* Register timeout task. If the protocol is not executed inside
1235 this timelimit the connection will be terminated. Currently
1236 this is 60 seconds and is hard coded limit (XXX). */
1237 proto_ctx->timeout_task =
1238 silc_schedule_task_add(server->schedule, sock->sock,
1239 silc_server_timeout_remote,
1240 (void *)server, 60, 0,
1245 /* Final part of accepting new connection. The connection has now
1246 been authenticated and keys has been exchanged. We also know whether
1247 this is client or server connection. */
1249 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1251 SilcProtocol protocol = (SilcProtocol)context;
1252 SilcServerConnAuthInternalContext *ctx =
1253 (SilcServerConnAuthInternalContext *)protocol->context;
1254 SilcServer server = (SilcServer)ctx->server;
1255 SilcSocketConnection sock = ctx->sock;
1256 SilcServerHBContext hb_context;
1257 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1258 void *id_entry = NULL;
1260 SILC_LOG_DEBUG(("Start"));
1262 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1263 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1264 /* Error occured during protocol */
1265 silc_protocol_free(protocol);
1266 sock->protocol = NULL;
1268 silc_packet_context_free(ctx->packet);
1270 silc_ske_free(ctx->ske);
1271 silc_free(ctx->dest_id);
1274 sock->protocol = NULL;
1275 silc_schedule_task_del_by_callback(server->schedule,
1276 silc_server_failure_callback);
1277 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1278 "Authentication failed");
1279 server->stat.auth_failures++;
1283 entry->data.last_receive = time(NULL);
1285 switch (ctx->conn_type) {
1286 case SILC_SOCKET_TYPE_CLIENT:
1288 SilcClientEntry client;
1290 SILC_LOG_DEBUG(("Remote host is client"));
1291 SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
1294 /* Add the client to the client ID cache. The nickname and Client ID
1295 and other information is created after we have received NEW_CLIENT
1296 packet from client. */
1297 client = silc_idlist_add_client(server->local_list,
1298 NULL, NULL, NULL, NULL, NULL, sock);
1300 SILC_LOG_ERROR(("Could not add new client to cache"));
1301 silc_free(sock->user_data);
1302 silc_server_disconnect_remote(server, sock,
1303 "Server closed connection: "
1304 "Authentication failed");
1305 server->stat.auth_failures++;
1310 server->stat.my_clients++;
1311 server->stat.clients++;
1312 if (server->server_type == SILC_ROUTER)
1313 server->stat.cell_clients++;
1315 id_entry = (void *)client;
1318 case SILC_SOCKET_TYPE_SERVER:
1319 case SILC_SOCKET_TYPE_ROUTER:
1321 SilcServerEntry new_server;
1322 SilcServerConfigSectionServerConnection *conn =
1323 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1324 ctx->sconfig : ctx->rconfig;
1326 SILC_LOG_DEBUG(("Remote host is %s",
1327 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1328 "server" : (conn->backup_router ?
1329 "backup router" : "router")));
1330 SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
1331 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1332 "server" : (conn->backup_router ?
1333 "backup router" : "router")));
1335 /* Add the server into server cache. The server name and Server ID
1336 is updated after we have received NEW_SERVER packet from the
1337 server. We mark ourselves as router for this server if we really
1340 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1341 server->local_list : (conn->backup_router ?
1342 server->local_list :
1343 server->global_list)),
1345 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1346 SILC_SERVER : SILC_ROUTER),
1348 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1349 server->id_entry : (conn->backup_router ?
1350 server->id_entry : NULL)),
1353 SILC_LOG_ERROR(("Could not add new server to cache"));
1354 silc_free(sock->user_data);
1355 silc_server_disconnect_remote(server, sock,
1356 "Server closed connection: "
1357 "Authentication failed");
1358 server->stat.auth_failures++;
1363 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1364 server->stat.my_servers++;
1366 server->stat.my_routers++;
1367 server->stat.servers++;
1369 id_entry = (void *)new_server;
1371 /* If the incoming connection is router and marked as backup router
1372 then add it to be one of our backups */
1373 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && conn->backup_router) {
1374 silc_server_backup_add(server, new_server, conn->backup_replace_ip,
1375 conn->backup_replace_port, conn->backup_local);
1377 /* Change it back to SERVER type since that's what it really is. */
1378 if (conn->backup_local)
1379 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1381 new_server->server_type = SILC_BACKUP_ROUTER;
1384 /* Check whether this connection is to be our primary router connection
1385 if we do not already have the primary route. */
1386 if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1387 if (silc_server_config_is_primary_route(server->config) &&
1391 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1392 server->standalone = FALSE;
1393 if (!server->id_entry->router) {
1394 server->id_entry->router = id_entry;
1395 server->router = id_entry;
1405 sock->type = ctx->conn_type;
1407 /* Add the common data structure to the ID entry. */
1409 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1411 /* Add to sockets internal pointer for fast referencing */
1412 silc_free(sock->user_data);
1413 sock->user_data = id_entry;
1415 /* Connection has been fully established now. Everything is ok. */
1416 SILC_LOG_DEBUG(("New connection authenticated"));
1418 /* Perform keepalive. The `hb_context' will be freed automatically
1419 when finally calling the silc_socket_free function. XXX hardcoded
1421 hb_context = silc_calloc(1, sizeof(*hb_context));
1422 hb_context->server = server;
1423 silc_socket_set_heartbeat(sock, 600, hb_context,
1424 silc_server_perform_heartbeat,
1428 silc_schedule_task_del_by_callback(server->schedule,
1429 silc_server_failure_callback);
1430 silc_protocol_free(protocol);
1432 silc_packet_context_free(ctx->packet);
1434 silc_ske_free(ctx->ske);
1435 silc_free(ctx->dest_id);
1437 sock->protocol = NULL;
1440 /* This function is used to read packets from network and send packets to
1441 network. This is usually a generic task. */
1443 SILC_TASK_CALLBACK(silc_server_packet_process)
1445 SilcServer server = (SilcServer)context;
1446 SilcSocketConnection sock = server->sockets[fd];
1447 SilcIDListData idata;
1448 SilcCipher cipher = NULL;
1449 SilcHmac hmac = NULL;
1455 SILC_LOG_DEBUG(("Processing packet"));
1457 /* Packet sending */
1459 if (type == SILC_TASK_WRITE) {
1460 /* Do not send data to disconnected connection */
1461 if (SILC_IS_DISCONNECTED(sock))
1464 server->stat.packets_sent++;
1466 if (sock->outbuf->data - sock->outbuf->head)
1467 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1469 /* Send the packet */
1470 ret = silc_packet_send(sock, TRUE);
1472 /* If returned -2 could not write to connection now, will do
1478 SILC_LOG_ERROR(("Error sending packet to connection "
1479 "%s:%d [%s]", sock->hostname, sock->port,
1480 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1481 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1482 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1487 /* The packet has been sent and now it is time to set the connection
1488 back to only for input. When there is again some outgoing data
1489 available for this connection it will be set for output as well.
1490 This call clears the output setting and sets it only for input. */
1491 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1492 SILC_UNSET_OUTBUF_PENDING(sock);
1494 silc_buffer_clear(sock->outbuf);
1498 /* Packet receiving */
1500 /* Read some data from connection */
1501 ret = silc_packet_receive(sock);
1505 SILC_LOG_ERROR(("Error receiving packet from connection "
1506 "%s:%d [%s]", sock->hostname, sock->port,
1507 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1508 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1509 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1516 SILC_LOG_DEBUG(("Read EOF"));
1518 /* If connection is disconnecting already we will finally
1519 close the connection */
1520 if (SILC_IS_DISCONNECTING(sock)) {
1521 if (sock->user_data)
1522 silc_server_free_sock_user_data(server, sock);
1523 silc_server_close_connection(server, sock);
1527 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1528 SILC_SET_DISCONNECTING(sock);
1530 if (sock->user_data)
1531 silc_server_free_sock_user_data(server, sock);
1532 silc_server_close_connection(server, sock);
1536 /* If connection is disconnecting or disconnected we will ignore
1538 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1539 SILC_LOG_DEBUG(("Ignoring read data from disonnected connection"));
1543 server->stat.packets_received++;
1545 /* Get keys and stuff from ID entry */
1546 idata = (SilcIDListData)sock->user_data;
1548 cipher = idata->receive_key;
1549 hmac = idata->hmac_receive;
1552 /* Process the packet. This will call the parser that will then
1553 decrypt and parse the packet. */
1554 silc_packet_receive_process(sock, cipher, hmac, silc_server_packet_parse,
1558 /* Callback function that the silc_packet_decrypt will call to make the
1559 decision whether the packet is normal or special packet. We will
1560 return TRUE if it is normal and FALSE if it is special */
1562 static int silc_server_packet_decrypt_check(SilcPacketType packet_type,
1564 SilcPacketContext *packet,
1567 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1568 SilcServer server = (SilcServer)parse_ctx->context;
1570 /* Packet is normal packet, if:
1572 1) packet is private message packet and does not have private key set
1573 2) is other packet than channel message packet
1574 3) is channel message packet and remote is router and we are router
1576 all other packets are special packets
1579 if (packet_type == SILC_PACKET_PRIVATE_MESSAGE &&
1580 (buffer->data[2] & SILC_PACKET_FLAG_PRIVMSG_KEY))
1583 if (packet_type != SILC_PACKET_CHANNEL_MESSAGE ||
1584 (packet_type == SILC_PACKET_CHANNEL_MESSAGE &&
1585 parse_ctx->sock->type == SILC_SOCKET_TYPE_ROUTER &&
1586 server->server_type == SILC_ROUTER))
1592 /* Parses whole packet, received earlier. */
1594 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1596 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1597 SilcServer server = (SilcServer)parse_ctx->context;
1598 SilcSocketConnection sock = parse_ctx->sock;
1599 SilcPacketContext *packet = parse_ctx->packet;
1600 SilcIDListData idata = (SilcIDListData)sock->user_data;
1603 SILC_LOG_DEBUG(("Start"));
1605 /* Decrypt the received packet */
1606 ret = silc_packet_decrypt(idata ? idata->receive_key : NULL,
1607 idata ? idata->hmac_receive : NULL,
1608 packet->buffer, packet,
1609 silc_server_packet_decrypt_check, parse_ctx);
1611 SILC_LOG_WARNING(("Packet decryption failed for connection "
1612 "%s:%d [%s]", sock->hostname, sock->port,
1613 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1614 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1615 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1621 /* Parse the packet. Packet type is returned. */
1622 ret = silc_packet_parse(packet);
1624 /* Parse the packet header in special way as this is "special"
1626 ret = silc_packet_parse_special(packet);
1629 /* If entry is disabled ignore what we got. */
1630 if (ret != SILC_PACKET_RESUME_ROUTER &&
1631 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1632 SILC_LOG_DEBUG(("Connection is disabled"));
1636 if (ret == SILC_PACKET_NONE)
1639 /* Check that the the current client ID is same as in the client's packet. */
1640 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1641 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1642 if (client && client->id) {
1643 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1644 packet->src_id_type);
1645 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1653 if (server->server_type == SILC_ROUTER) {
1654 /* Route the packet if it is not destined to us. Other ID types but
1655 server are handled separately after processing them. */
1656 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1657 packet->dst_id_type == SILC_ID_SERVER &&
1658 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1659 memcmp(packet->dst_id, server->id_string, packet->dst_id_len)) {
1661 /* Route the packet to fastest route for the destination ID */
1662 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1663 packet->dst_id_type);
1666 silc_server_packet_route(server,
1667 silc_server_route_get(server, id,
1668 packet->dst_id_type),
1675 /* Parse the incoming packet type */
1676 silc_server_packet_parse_type(server, sock, packet);
1678 if (server->server_type == SILC_ROUTER) {
1679 /* Broadcast packet if it is marked as broadcast packet and it is
1680 originated from router and we are router. */
1681 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1682 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1683 !server->standalone) {
1684 /* Broadcast to our primary route */
1685 silc_server_packet_broadcast(server, server->router->connection, packet);
1687 /* If we have backup routers then we need to feed all broadcast
1688 data to those servers. */
1689 silc_server_backup_broadcast(server, sock, packet);
1694 silc_packet_context_free(packet);
1695 silc_free(parse_ctx);
1698 /* Parser callback called by silc_packet_receive_process. This merely
1699 registers timeout that will handle the actual parsing when appropriate. */
1701 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1703 SilcServer server = (SilcServer)parser_context->context;
1704 SilcSocketConnection sock = parser_context->sock;
1706 switch (sock->type) {
1707 case SILC_SOCKET_TYPE_UNKNOWN:
1708 case SILC_SOCKET_TYPE_CLIENT:
1709 /* Parse the packet with timeout */
1710 silc_schedule_task_add(server->schedule, sock->sock,
1711 silc_server_packet_parse_real,
1712 (void *)parser_context, 0, 100000,
1714 SILC_TASK_PRI_NORMAL);
1716 case SILC_SOCKET_TYPE_SERVER:
1717 case SILC_SOCKET_TYPE_ROUTER:
1718 /* Packets from servers are parsed as soon as possible */
1719 silc_schedule_task_add(server->schedule, sock->sock,
1720 silc_server_packet_parse_real,
1721 (void *)parser_context, 0, 1,
1723 SILC_TASK_PRI_NORMAL);
1730 /* Parses the packet type and calls what ever routines the packet type
1731 requires. This is done for all incoming packets. */
1733 void silc_server_packet_parse_type(SilcServer server,
1734 SilcSocketConnection sock,
1735 SilcPacketContext *packet)
1737 SilcPacketType type = packet->type;
1738 SilcIDListData idata = (SilcIDListData)sock->user_data;
1740 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1742 /* Parse the packet type */
1744 case SILC_PACKET_DISCONNECT:
1745 SILC_LOG_DEBUG(("Disconnect packet"));
1746 if (packet->flags & SILC_PACKET_FLAG_LIST)
1750 case SILC_PACKET_SUCCESS:
1752 * Success received for something. For now we can have only
1753 * one protocol for connection executing at once hence this
1754 * success message is for whatever protocol is executing currently.
1756 SILC_LOG_DEBUG(("Success packet"));
1757 if (packet->flags & SILC_PACKET_FLAG_LIST)
1760 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1763 case SILC_PACKET_FAILURE:
1765 * Failure received for something. For now we can have only
1766 * one protocol for connection executing at once hence this
1767 * failure message is for whatever protocol is executing currently.
1769 SILC_LOG_DEBUG(("Failure packet"));
1770 if (packet->flags & SILC_PACKET_FLAG_LIST)
1772 if (sock->protocol) {
1773 SilcServerFailureContext f;
1774 f = silc_calloc(1, sizeof(*f));
1778 /* We will wait 5 seconds to process this failure packet */
1779 silc_schedule_task_add(server->schedule, sock->sock,
1780 silc_server_failure_callback, (void *)f, 5, 0,
1781 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1785 case SILC_PACKET_REJECT:
1786 SILC_LOG_DEBUG(("Reject packet"));
1787 if (packet->flags & SILC_PACKET_FLAG_LIST)
1792 case SILC_PACKET_NOTIFY:
1794 * Received notify packet. Server can receive notify packets from
1795 * router. Server then relays the notify messages to clients if needed.
1797 SILC_LOG_DEBUG(("Notify packet"));
1798 if (packet->flags & SILC_PACKET_FLAG_LIST)
1799 silc_server_notify_list(server, sock, packet);
1801 silc_server_notify(server, sock, packet);
1807 case SILC_PACKET_CHANNEL_MESSAGE:
1809 * Received channel message. Channel messages are special packets
1810 * (although probably most common ones) thus they are handled
1813 SILC_LOG_DEBUG(("Channel Message packet"));
1814 if (packet->flags & SILC_PACKET_FLAG_LIST)
1816 idata->last_receive = time(NULL);
1817 silc_server_channel_message(server, sock, packet);
1820 case SILC_PACKET_CHANNEL_KEY:
1822 * Received key for channel. As channels are created by the router
1823 * the keys are as well. We will distribute the key to all of our
1824 * locally connected clients on the particular channel. Router
1825 * never receives this channel and thus is ignored.
1827 SILC_LOG_DEBUG(("Channel Key packet"));
1828 if (packet->flags & SILC_PACKET_FLAG_LIST)
1830 silc_server_channel_key(server, sock, packet);
1836 case SILC_PACKET_COMMAND:
1838 * Recived command. Processes the command request and allocates the
1839 * command context and calls the command.
1841 SILC_LOG_DEBUG(("Command packet"));
1842 if (packet->flags & SILC_PACKET_FLAG_LIST)
1844 silc_server_command_process(server, sock, packet);
1847 case SILC_PACKET_COMMAND_REPLY:
1849 * Received command reply packet. Received command reply to command. It
1850 * may be reply to command sent by us or reply to command sent by client
1851 * that we've routed further.
1853 SILC_LOG_DEBUG(("Command Reply packet"));
1854 if (packet->flags & SILC_PACKET_FLAG_LIST)
1856 silc_server_command_reply(server, sock, packet);
1860 * Private Message packets
1862 case SILC_PACKET_PRIVATE_MESSAGE:
1864 * Received private message packet. The packet is coming from either
1867 SILC_LOG_DEBUG(("Private Message packet"));
1868 if (packet->flags & SILC_PACKET_FLAG_LIST)
1870 idata->last_receive = time(NULL);
1871 silc_server_private_message(server, sock, packet);
1874 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1876 * Private message key packet.
1878 if (packet->flags & SILC_PACKET_FLAG_LIST)
1880 silc_server_private_message_key(server, sock, packet);
1884 * Key Exchange protocol packets
1886 case SILC_PACKET_KEY_EXCHANGE:
1887 SILC_LOG_DEBUG(("KE packet"));
1888 if (packet->flags & SILC_PACKET_FLAG_LIST)
1891 if (sock->protocol && sock->protocol->protocol &&
1892 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1894 SilcServerKEInternalContext *proto_ctx =
1895 (SilcServerKEInternalContext *)sock->protocol->context;
1897 proto_ctx->packet = silc_packet_context_dup(packet);
1899 /* Let the protocol handle the packet */
1900 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
1902 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1903 "protocol active, packet dropped."));
1907 case SILC_PACKET_KEY_EXCHANGE_1:
1908 SILC_LOG_DEBUG(("KE 1 packet"));
1909 if (packet->flags & SILC_PACKET_FLAG_LIST)
1912 if (sock->protocol && sock->protocol->protocol &&
1913 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1914 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
1916 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
1917 SilcServerRekeyInternalContext *proto_ctx =
1918 (SilcServerRekeyInternalContext *)sock->protocol->context;
1920 if (proto_ctx->packet)
1921 silc_packet_context_free(proto_ctx->packet);
1923 proto_ctx->packet = silc_packet_context_dup(packet);
1925 /* Let the protocol handle the packet */
1926 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1928 SilcServerKEInternalContext *proto_ctx =
1929 (SilcServerKEInternalContext *)sock->protocol->context;
1931 if (proto_ctx->packet)
1932 silc_packet_context_free(proto_ctx->packet);
1934 proto_ctx->packet = silc_packet_context_dup(packet);
1935 proto_ctx->dest_id_type = packet->src_id_type;
1936 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1937 packet->src_id_type);
1938 if (!proto_ctx->dest_id)
1941 /* Let the protocol handle the packet */
1942 silc_protocol_execute(sock->protocol, server->schedule,
1946 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1947 "protocol active, packet dropped."));
1951 case SILC_PACKET_KEY_EXCHANGE_2:
1952 SILC_LOG_DEBUG(("KE 2 packet"));
1953 if (packet->flags & SILC_PACKET_FLAG_LIST)
1956 if (sock->protocol && sock->protocol->protocol &&
1957 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1958 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
1960 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
1961 SilcServerRekeyInternalContext *proto_ctx =
1962 (SilcServerRekeyInternalContext *)sock->protocol->context;
1964 if (proto_ctx->packet)
1965 silc_packet_context_free(proto_ctx->packet);
1967 proto_ctx->packet = silc_packet_context_dup(packet);
1969 /* Let the protocol handle the packet */
1970 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1972 SilcServerKEInternalContext *proto_ctx =
1973 (SilcServerKEInternalContext *)sock->protocol->context;
1975 if (proto_ctx->packet)
1976 silc_packet_context_free(proto_ctx->packet);
1978 proto_ctx->packet = silc_packet_context_dup(packet);
1979 proto_ctx->dest_id_type = packet->src_id_type;
1980 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1981 packet->src_id_type);
1982 if (!proto_ctx->dest_id)
1985 /* Let the protocol handle the packet */
1986 silc_protocol_execute(sock->protocol, server->schedule,
1990 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1991 "protocol active, packet dropped."));
1995 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1997 * Connection authentication request packet. When we receive this packet
1998 * we will send to the other end information about our mandatory
1999 * authentication method for the connection. This packet maybe received
2002 SILC_LOG_DEBUG(("Connection authentication request packet"));
2003 if (packet->flags & SILC_PACKET_FLAG_LIST)
2005 silc_server_connection_auth_request(server, sock, packet);
2009 * Connection Authentication protocol packets
2011 case SILC_PACKET_CONNECTION_AUTH:
2012 /* Start of the authentication protocol. We receive here the
2013 authentication data and will verify it. */
2014 SILC_LOG_DEBUG(("Connection auth packet"));
2015 if (packet->flags & SILC_PACKET_FLAG_LIST)
2018 if (sock->protocol && sock->protocol->protocol->type
2019 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2021 SilcServerConnAuthInternalContext *proto_ctx =
2022 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2024 proto_ctx->packet = silc_packet_context_dup(packet);
2026 /* Let the protocol handle the packet */
2027 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2029 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2030 "protocol active, packet dropped."));
2034 case SILC_PACKET_NEW_ID:
2036 * Received New ID packet. This includes some new ID that has been
2037 * created. It may be for client, server or channel. This is the way
2038 * to distribute information about new registered entities in the
2041 SILC_LOG_DEBUG(("New ID packet"));
2042 if (packet->flags & SILC_PACKET_FLAG_LIST)
2043 silc_server_new_id_list(server, sock, packet);
2045 silc_server_new_id(server, sock, packet);
2048 case SILC_PACKET_NEW_CLIENT:
2050 * Received new client packet. This includes client information that
2051 * we will use to create initial client ID. After creating new
2052 * ID we will send it to the client.
2054 SILC_LOG_DEBUG(("New Client packet"));
2055 if (packet->flags & SILC_PACKET_FLAG_LIST)
2057 silc_server_new_client(server, sock, packet);
2060 case SILC_PACKET_NEW_SERVER:
2062 * Received new server packet. This includes Server ID and some other
2063 * information that we may save. This is received after server has
2066 SILC_LOG_DEBUG(("New Server packet"));
2067 if (packet->flags & SILC_PACKET_FLAG_LIST)
2069 silc_server_new_server(server, sock, packet);
2072 case SILC_PACKET_NEW_CHANNEL:
2074 * Received new channel packet. Information about new channel in the
2075 * network are distributed using this packet.
2077 SILC_LOG_DEBUG(("New Channel packet"));
2078 if (packet->flags & SILC_PACKET_FLAG_LIST)
2079 silc_server_new_channel_list(server, sock, packet);
2081 silc_server_new_channel(server, sock, packet);
2084 case SILC_PACKET_HEARTBEAT:
2086 * Received heartbeat.
2088 SILC_LOG_DEBUG(("Heartbeat packet"));
2089 if (packet->flags & SILC_PACKET_FLAG_LIST)
2093 case SILC_PACKET_KEY_AGREEMENT:
2095 * Received heartbeat.
2097 SILC_LOG_DEBUG(("Key agreement packet"));
2098 if (packet->flags & SILC_PACKET_FLAG_LIST)
2100 silc_server_key_agreement(server, sock, packet);
2103 case SILC_PACKET_REKEY:
2105 * Received re-key packet. The sender wants to regenerate the session
2108 SILC_LOG_DEBUG(("Re-key packet"));
2109 if (packet->flags & SILC_PACKET_FLAG_LIST)
2111 silc_server_rekey(server, sock, packet);
2114 case SILC_PACKET_REKEY_DONE:
2116 * The re-key is done.
2118 SILC_LOG_DEBUG(("Re-key done packet"));
2119 if (packet->flags & SILC_PACKET_FLAG_LIST)
2122 if (sock->protocol && sock->protocol->protocol &&
2123 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2125 SilcServerRekeyInternalContext *proto_ctx =
2126 (SilcServerRekeyInternalContext *)sock->protocol->context;
2128 if (proto_ctx->packet)
2129 silc_packet_context_free(proto_ctx->packet);
2131 proto_ctx->packet = silc_packet_context_dup(packet);
2133 /* Let the protocol handle the packet */
2134 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2136 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2137 "protocol active, packet dropped."));
2141 case SILC_PACKET_FTP:
2145 case SILC_PACKET_RESUME_ROUTER:
2146 /* Resume router packet received. This packet is received for backup
2147 router resuming protocol. */
2148 SILC_LOG_DEBUG(("Resume router packet"));
2149 if (packet->flags & SILC_PACKET_FLAG_LIST)
2151 silc_server_backup_resume_router(server, sock, packet);
2155 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2161 /* Creates connection to a remote router. */
2163 void silc_server_create_connection(SilcServer server,
2164 char *remote_host, uint32 port)
2166 SilcServerConnection sconn;
2168 /* Allocate connection object for hold connection specific stuff. */
2169 sconn = silc_calloc(1, sizeof(*sconn));
2170 sconn->server = server;
2171 sconn->remote_host = strdup(remote_host);
2172 sconn->remote_port = port;
2174 silc_schedule_task_add(server->schedule, 0,
2175 silc_server_connect_router,
2176 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2177 SILC_TASK_PRI_NORMAL);
2180 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2182 silc_socket_free((SilcSocketConnection)context);
2185 /* Closes connection to socket connection */
2187 void silc_server_close_connection(SilcServer server,
2188 SilcSocketConnection sock)
2190 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2192 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2193 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2194 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2197 /* We won't listen for this connection anymore */
2198 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2200 /* Unregister all tasks */
2201 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2203 /* Close the actual connection */
2204 silc_net_close_connection(sock->sock);
2205 server->sockets[sock->sock] = NULL;
2207 /* If sock->user_data is NULL then we'll check for active protocols
2208 here since the silc_server_free_sock_user_data has not been called
2209 for this connection. */
2210 if (!sock->user_data) {
2211 /* If any protocol is active cancel its execution. It will call
2212 the final callback which will finalize the disconnection. */
2213 if (sock->protocol) {
2214 silc_protocol_cancel(sock->protocol, server->schedule);
2215 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2216 silc_protocol_execute_final(sock->protocol, server->schedule);
2217 sock->protocol = NULL;
2222 silc_schedule_task_add(server->schedule, 0,
2223 silc_server_close_connection_final,
2224 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2225 SILC_TASK_PRI_NORMAL);
2228 /* Sends disconnect message to remote connection and disconnects the
2231 void silc_server_disconnect_remote(SilcServer server,
2232 SilcSocketConnection sock,
2233 const char *fmt, ...)
2236 unsigned char buf[4096];
2241 memset(buf, 0, sizeof(buf));
2243 vsprintf(buf, fmt, ap);
2246 SILC_LOG_DEBUG(("Disconnecting remote host"));
2248 /* Notify remote end that the conversation is over. The notify message
2249 is tried to be sent immediately. */
2250 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2251 buf, strlen(buf), TRUE);
2253 /* Mark the connection to be disconnected */
2254 SILC_SET_DISCONNECTED(sock);
2255 silc_server_close_connection(server, sock);
2260 SilcClientEntry client;
2261 } *FreeClientInternal;
2263 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2265 FreeClientInternal i = (FreeClientInternal)context;
2267 silc_idlist_del_data(i->client);
2268 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2272 /* Frees client data and notifies about client's signoff. */
2274 void silc_server_free_client_data(SilcServer server,
2275 SilcSocketConnection sock,
2276 SilcClientEntry client,
2280 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2282 /* If there is pending outgoing data for the client then purge it
2283 to the network before removing the client entry. */
2284 silc_server_packet_queue_purge(server, sock);
2286 /* Send SIGNOFF notify to routers. */
2287 if (notify && !server->standalone && server->router)
2288 silc_server_send_notify_signoff(server, server->router->connection,
2289 server->server_type == SILC_SERVER ?
2290 FALSE : TRUE, client->id, signoff);
2292 /* Remove client from all channels */
2294 silc_server_remove_from_channels(server, NULL, client,
2295 TRUE, signoff, TRUE);
2297 silc_server_remove_from_channels(server, NULL, client,
2298 FALSE, NULL, FALSE);
2300 /* We will not delete the client entry right away. We will take it
2301 into history (for WHOWAS command) for 5 minutes */
2304 silc_schedule_task_add(server->schedule, 0,
2305 silc_server_free_client_data_timeout,
2307 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2308 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2309 client->router = NULL;
2310 client->connection = NULL;
2312 /* Free the client entry and everything in it */
2313 server->stat.my_clients--;
2314 server->stat.clients--;
2315 if (server->server_type == SILC_ROUTER)
2316 server->stat.cell_clients--;
2319 /* Frees user_data pointer from socket connection object. This also sends
2320 appropriate notify packets to the network to inform about leaving
2323 void silc_server_free_sock_user_data(SilcServer server,
2324 SilcSocketConnection sock)
2326 SILC_LOG_DEBUG(("Start"));
2328 switch (sock->type) {
2329 case SILC_SOCKET_TYPE_CLIENT:
2331 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2332 silc_server_free_client_data(server, sock, user_data, TRUE, NULL);
2335 case SILC_SOCKET_TYPE_SERVER:
2336 case SILC_SOCKET_TYPE_ROUTER:
2338 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2339 SilcServerEntry backup_router = NULL;
2342 backup_router = silc_server_backup_get(server, user_data->id);
2344 /* If this was our primary router connection then we're lost to
2345 the outside world. */
2346 if (server->router == user_data) {
2347 /* Check whether we have a backup router connection */
2348 if (!backup_router || backup_router == user_data) {
2349 silc_schedule_task_add(server->schedule, 0,
2350 silc_server_connect_to_router,
2353 SILC_TASK_PRI_NORMAL);
2355 server->id_entry->router = NULL;
2356 server->router = NULL;
2357 server->standalone = TRUE;
2358 backup_router = NULL;
2360 SILC_LOG_INFO(("New primary router is backup router %s",
2361 backup_router->server_name));
2362 SILC_LOG_DEBUG(("New primary router is backup router %s",
2363 backup_router->server_name));
2364 server->id_entry->router = backup_router;
2365 server->router = backup_router;
2366 server->router_connect = time(0);
2367 server->backup_primary = TRUE;
2368 if (server->server_type == SILC_BACKUP_ROUTER) {
2369 server->server_type = SILC_ROUTER;
2371 /* We'll need to constantly try to reconnect to the primary
2372 router so that we'll see when it comes back online. */
2373 silc_server_backup_reconnect(server, sock->ip, sock->port,
2374 silc_server_backup_connected,
2378 /* Mark this connection as replaced */
2379 silc_server_backup_replaced_add(server, user_data->id,
2382 } else if (backup_router) {
2383 SILC_LOG_INFO(("Enabling the use of backup router %s",
2384 backup_router->server_name));
2385 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2386 backup_router->server_name));
2388 /* Mark this connection as replaced */
2389 silc_server_backup_replaced_add(server, user_data->id,
2393 if (!backup_router) {
2394 /* Free all client entries that this server owns as they will
2395 become invalid now as well. */
2397 silc_server_remove_clients_by_server(server, user_data, TRUE);
2399 /* Update the client entries of this server to the new backup
2400 router. This also removes the clients that *really* was owned
2401 by the primary router and went down with the router. */
2402 silc_server_update_clients_by_server(server, user_data, backup_router,
2406 /* Free the server entry */
2407 silc_server_backup_del(server, user_data);
2408 silc_server_backup_replaced_del(server, user_data);
2409 silc_idlist_del_data(user_data);
2410 if (!silc_idlist_del_server(server->local_list, user_data))
2411 silc_idlist_del_server(server->global_list, user_data);
2412 server->stat.my_servers--;
2413 server->stat.servers--;
2414 if (server->server_type == SILC_ROUTER)
2415 server->stat.cell_servers--;
2417 if (backup_router) {
2418 /* Announce all of our stuff that was created about 5 minutes ago.
2419 The backup router knows all the other stuff already. */
2420 if (server->server_type == SILC_ROUTER)
2421 silc_server_announce_servers(server, FALSE, time(0) - 300,
2422 backup_router->connection);
2424 /* Announce our clients and channels to the router */
2425 silc_server_announce_clients(server, time(0) - 300,
2426 backup_router->connection);
2427 silc_server_announce_channels(server, time(0) - 300,
2428 backup_router->connection);
2434 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2436 silc_idlist_del_data(user_data);
2437 silc_free(user_data);
2442 /* If any protocol is active cancel its execution */
2443 if (sock->protocol) {
2444 silc_protocol_cancel(sock->protocol, server->schedule);
2445 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2446 silc_protocol_execute_final(sock->protocol, server->schedule);
2447 sock->protocol = NULL;
2450 sock->user_data = NULL;
2453 /* Removes client from all channels it has joined. This is used when client
2454 connection is disconnected. If the client on a channel is last, the
2455 channel is removed as well. This sends the SIGNOFF notify types. */
2457 void silc_server_remove_from_channels(SilcServer server,
2458 SilcSocketConnection sock,
2459 SilcClientEntry client,
2461 char *signoff_message,
2464 SilcChannelEntry channel;
2465 SilcChannelClientEntry chl;
2466 SilcHashTableList htl;
2469 SILC_LOG_DEBUG(("Start"));
2471 if (!client || !client->id)
2474 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2476 /* Remove the client from all channels. The client is removed from
2477 the channels' user list. */
2478 silc_hash_table_list(client->channels, &htl);
2479 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2480 channel = chl->channel;
2482 /* Remove channel from client's channel list */
2483 silc_hash_table_del(client->channels, channel);
2485 /* Remove channel if there is no users anymore */
2486 if (server->server_type == SILC_ROUTER &&
2487 silc_hash_table_count(channel->user_list) < 2) {
2489 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2490 if (silc_idlist_del_channel(server->local_list, channel))
2491 server->stat.my_channels--;
2492 silc_idlist_del_channel(server->global_list, channel);
2496 /* Remove client from channel's client list */
2497 silc_hash_table_del(channel->user_list, chl->client);
2499 /* If there is no global users on the channel anymore mark the channel
2500 as local channel. Do not check if the removed client is local client. */
2501 if (server->server_type != SILC_ROUTER && channel->global_users &&
2502 chl->client->router && !silc_server_channel_has_global(channel))
2503 channel->global_users = FALSE;
2506 server->stat.my_chanclients--;
2508 /* If there is not at least one local user on the channel then we don't
2509 need the channel entry anymore, we can remove it safely. */
2510 if (server->server_type != SILC_ROUTER &&
2511 !silc_server_channel_has_local(channel)) {
2512 /* Notify about leaving client if this channel has global users. */
2513 if (notify && channel->global_users)
2514 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2515 SILC_NOTIFY_TYPE_SIGNOFF,
2516 signoff_message ? 2 : 1,
2517 clidp->data, clidp->len,
2518 signoff_message, signoff_message ?
2519 strlen(signoff_message) : 0);
2522 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2524 if (channel->founder_key) {
2525 /* The founder auth data exists, do not remove the channel entry */
2526 SilcChannelClientEntry chl2;
2527 SilcHashTableList htl2;
2531 silc_hash_table_list(channel->user_list, &htl2);
2532 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2533 silc_hash_table_del(chl2->client->channels, channel);
2534 silc_hash_table_del(channel->user_list, chl2->client);
2540 /* Remove the channel entry */
2541 if (!silc_idlist_del_channel(server->local_list, channel))
2542 silc_idlist_del_channel(server->global_list, channel);
2543 server->stat.my_channels--;
2547 /* Send notify to channel about client leaving SILC and thus
2548 the entire channel. */
2550 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2551 SILC_NOTIFY_TYPE_SIGNOFF,
2552 signoff_message ? 2 : 1,
2553 clidp->data, clidp->len,
2554 signoff_message, signoff_message ?
2555 strlen(signoff_message) : 0);
2557 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2558 /* Re-generate channel key */
2559 if (!silc_server_create_channel_key(server, channel, 0))
2562 /* Send the channel key to the channel. The key of course is not sent
2563 to the client who was removed from the channel. */
2564 silc_server_send_channel_key(server, client->connection, channel,
2565 server->server_type == SILC_ROUTER ?
2566 FALSE : !server->standalone);
2570 silc_buffer_free(clidp);
2573 /* Removes client from one channel. This is used for example when client
2574 calls LEAVE command to remove itself from the channel. Returns TRUE
2575 if channel still exists and FALSE if the channel is removed when
2576 last client leaves the channel. If `notify' is FALSE notify messages
2579 int silc_server_remove_from_one_channel(SilcServer server,
2580 SilcSocketConnection sock,
2581 SilcChannelEntry channel,
2582 SilcClientEntry client,
2585 SilcChannelClientEntry chl;
2588 SILC_LOG_DEBUG(("Start"));
2590 /* Get the entry to the channel, if this client is not on the channel
2592 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2595 /* Remove the client from the channel. The client is removed from
2596 the channel's user list. */
2598 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2600 /* Remove channel from client's channel list */
2601 silc_hash_table_del(client->channels, chl->channel);
2603 /* Remove channel if there is no users anymore */
2604 if (server->server_type == SILC_ROUTER &&
2605 silc_hash_table_count(channel->user_list) < 2) {
2607 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2608 if (!silc_idlist_del_channel(server->local_list, channel))
2609 silc_idlist_del_channel(server->global_list, channel);
2610 silc_buffer_free(clidp);
2611 server->stat.my_channels--;
2615 /* Remove client from channel's client list */
2616 silc_hash_table_del(channel->user_list, chl->client);
2618 /* If there is no global users on the channel anymore mark the channel
2619 as local channel. Do not check if the client is local client. */
2620 if (server->server_type != SILC_ROUTER && channel->global_users &&
2621 chl->client->router && !silc_server_channel_has_global(channel))
2622 channel->global_users = FALSE;
2625 server->stat.my_chanclients--;
2627 /* If there is not at least one local user on the channel then we don't
2628 need the channel entry anymore, we can remove it safely. */
2629 if (server->server_type != SILC_ROUTER &&
2630 !silc_server_channel_has_local(channel)) {
2631 /* Notify about leaving client if this channel has global users. */
2632 if (notify && channel->global_users)
2633 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2634 SILC_NOTIFY_TYPE_LEAVE, 1,
2635 clidp->data, clidp->len);
2637 silc_buffer_free(clidp);
2640 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2642 if (channel->founder_key) {
2643 /* The founder auth data exists, do not remove the channel entry */
2644 SilcChannelClientEntry chl2;
2645 SilcHashTableList htl2;
2649 silc_hash_table_list(channel->user_list, &htl2);
2650 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2651 silc_hash_table_del(chl2->client->channels, channel);
2652 silc_hash_table_del(channel->user_list, chl2->client);
2658 /* Remove the channel entry */
2659 if (!silc_idlist_del_channel(server->local_list, channel))
2660 silc_idlist_del_channel(server->global_list, channel);
2661 server->stat.my_channels--;
2665 /* Send notify to channel about client leaving the channel */
2667 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2668 SILC_NOTIFY_TYPE_LEAVE, 1,
2669 clidp->data, clidp->len);
2671 silc_buffer_free(clidp);
2675 /* Timeout callback. This is called if connection is idle or for some
2676 other reason is not responding within some period of time. This
2677 disconnects the remote end. */
2679 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2681 SilcServer server = (SilcServer)context;
2682 SilcSocketConnection sock = server->sockets[fd];
2684 SILC_LOG_DEBUG(("Start"));
2689 /* If we have protocol active we must assure that we call the protocol's
2690 final callback so that all the memory is freed. */
2691 if (sock->protocol) {
2692 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2693 silc_protocol_execute_final(sock->protocol, server->schedule);
2697 if (sock->user_data)
2698 silc_server_free_sock_user_data(server, sock);
2700 silc_server_disconnect_remote(server, sock, "Server closed connection: "
2701 "Connection timeout");
2704 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2705 function may be used only by router. In real SILC network all channels
2706 are created by routers thus this function is never used by normal
2709 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2710 SilcServerID *router_id,
2716 SilcChannelID *channel_id;
2717 SilcChannelEntry entry;
2721 SILC_LOG_DEBUG(("Creating new channel"));
2724 cipher = SILC_DEFAULT_CIPHER;
2726 hmac = SILC_DEFAULT_HMAC;
2728 /* Allocate cipher */
2729 if (!silc_cipher_alloc(cipher, &key))
2733 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2734 silc_cipher_free(key);
2738 channel_name = strdup(channel_name);
2740 /* Create the channel */
2741 if (!silc_id_create_channel_id(server, router_id, server->rng,
2743 silc_free(channel_name);
2744 silc_cipher_free(key);
2745 silc_hmac_free(newhmac);
2748 entry = silc_idlist_add_channel(server->local_list, channel_name,
2749 SILC_CHANNEL_MODE_NONE, channel_id,
2750 NULL, key, newhmac);
2752 silc_free(channel_name);
2753 silc_cipher_free(key);
2754 silc_hmac_free(newhmac);
2758 entry->cipher = strdup(cipher);
2759 entry->hmac_name = strdup(hmac);
2761 /* Now create the actual key material */
2762 if (!silc_server_create_channel_key(server, entry,
2763 silc_cipher_get_key_len(key) / 8)) {
2764 silc_free(channel_name);
2765 silc_cipher_free(key);
2766 silc_hmac_free(newhmac);
2767 silc_free(entry->cipher);
2768 silc_free(entry->hmac_name);
2772 /* Notify other routers about the new channel. We send the packet
2773 to our primary route. */
2774 if (broadcast && server->standalone == FALSE)
2775 silc_server_send_new_channel(server, server->router->connection, TRUE,
2776 channel_name, entry->id,
2777 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2780 server->stat.my_channels++;
2785 /* Same as above but creates the channel with Channel ID `channel_id. */
2788 silc_server_create_new_channel_with_id(SilcServer server,
2792 SilcChannelID *channel_id,
2795 SilcChannelEntry entry;
2799 SILC_LOG_DEBUG(("Creating new channel"));
2802 cipher = SILC_DEFAULT_CIPHER;
2804 hmac = SILC_DEFAULT_HMAC;
2806 /* Allocate cipher */
2807 if (!silc_cipher_alloc(cipher, &key))
2811 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2812 silc_cipher_free(key);
2816 channel_name = strdup(channel_name);
2818 /* Create the channel */
2819 entry = silc_idlist_add_channel(server->local_list, channel_name,
2820 SILC_CHANNEL_MODE_NONE, channel_id,
2821 NULL, key, newhmac);
2823 silc_free(channel_name);
2827 /* Now create the actual key material */
2828 if (!silc_server_create_channel_key(server, entry,
2829 silc_cipher_get_key_len(key) / 8)) {
2830 silc_free(channel_name);
2834 /* Notify other routers about the new channel. We send the packet
2835 to our primary route. */
2836 if (broadcast && server->standalone == FALSE)
2837 silc_server_send_new_channel(server, server->router->connection, TRUE,
2838 channel_name, entry->id,
2839 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2842 server->stat.my_channels++;
2847 /* Channel's key re-key timeout callback. */
2849 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
2851 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
2852 SilcServer server = (SilcServer)rekey->context;
2856 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
2859 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
2862 /* Generates new channel key. This is used to create the initial channel key
2863 but also to re-generate new key for channel. If `key_len' is provided
2864 it is the bytes of the key length. */
2866 bool silc_server_create_channel_key(SilcServer server,
2867 SilcChannelEntry channel,
2871 unsigned char channel_key[32], hash[32];
2874 SILC_LOG_DEBUG(("Generating channel key"));
2876 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
2877 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
2881 if (!channel->channel_key)
2882 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key))
2887 else if (channel->key_len)
2888 len = channel->key_len / 8;
2890 len = silc_cipher_get_key_len(channel->channel_key) / 8;
2892 /* Create channel key */
2893 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
2896 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
2898 /* Remove old key if exists */
2900 memset(channel->key, 0, channel->key_len / 8);
2901 silc_free(channel->key);
2905 channel->key_len = len * 8;
2906 channel->key = silc_calloc(len, sizeof(*channel->key));
2907 memcpy(channel->key, channel_key, len);
2908 memset(channel_key, 0, sizeof(channel_key));
2910 /* Generate HMAC key from the channel key data and set it */
2912 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
2913 silc_hash_make(channel->hmac->hash, channel->key, len, hash);
2914 silc_hmac_set_key(channel->hmac, hash, silc_hash_len(channel->hmac->hash));
2915 memset(hash, 0, sizeof(hash));
2917 if (server->server_type == SILC_ROUTER) {
2918 if (!channel->rekey)
2919 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
2920 channel->rekey->context = (void *)server;
2921 channel->rekey->channel = channel;
2922 channel->rekey->key_len = key_len;
2923 if (channel->rekey->task)
2924 silc_schedule_task_del(server->schedule, channel->rekey->task);
2926 channel->rekey->task =
2927 silc_schedule_task_add(server->schedule, 0,
2928 silc_server_channel_key_rekey,
2929 (void *)channel->rekey, 3600, 0,
2931 SILC_TASK_PRI_NORMAL);
2937 /* Saves the channel key found in the encoded `key_payload' buffer. This
2938 function is used when we receive Channel Key Payload and also when we're
2939 processing JOIN command reply. Returns entry to the channel. */
2941 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
2942 SilcBuffer key_payload,
2943 SilcChannelEntry channel)
2945 SilcChannelKeyPayload payload = NULL;
2946 SilcChannelID *id = NULL;
2947 unsigned char *tmp, hash[32];
2951 SILC_LOG_DEBUG(("Start"));
2953 /* Decode channel key payload */
2954 payload = silc_channel_key_payload_parse(key_payload);
2956 SILC_LOG_ERROR(("Bad channel key payload, dropped"));
2961 /* Get the channel entry */
2964 /* Get channel ID */
2965 tmp = silc_channel_key_get_id(payload, &tmp_len);
2966 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
2972 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
2974 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
2976 SILC_LOG_ERROR(("Received key for non-existent channel"));
2982 tmp = silc_channel_key_get_key(payload, &tmp_len);
2988 cipher = silc_channel_key_get_cipher(payload, NULL);
2994 /* Remove old key if exists */
2996 memset(channel->key, 0, channel->key_len / 8);
2997 silc_free(channel->key);
2998 silc_cipher_free(channel->channel_key);
3001 /* Create new cipher */
3002 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3007 if (channel->cipher)
3008 silc_free(channel->cipher);
3009 channel->cipher = strdup(cipher);
3012 channel->key_len = tmp_len * 8;
3013 channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
3014 memcpy(channel->key, tmp, tmp_len);
3015 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3017 /* Generate HMAC key from the channel key data and set it */
3019 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3020 silc_hash_make(channel->hmac->hash, tmp, tmp_len, hash);
3021 silc_hmac_set_key(channel->hmac, hash, silc_hash_len(channel->hmac->hash));
3023 memset(hash, 0, sizeof(hash));
3024 memset(tmp, 0, tmp_len);
3026 if (server->server_type == SILC_ROUTER) {
3027 if (!channel->rekey)
3028 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3029 channel->rekey->context = (void *)server;
3030 channel->rekey->channel = channel;
3031 if (channel->rekey->task)
3032 silc_schedule_task_del(server->schedule, channel->rekey->task);
3034 channel->rekey->task =
3035 silc_schedule_task_add(server->schedule, 0,
3036 silc_server_channel_key_rekey,
3037 (void *)channel->rekey, 3600, 0,
3039 SILC_TASK_PRI_NORMAL);
3045 silc_channel_key_payload_free(payload);
3050 /* Heartbeat callback. This function is set as argument for the
3051 silc_socket_set_heartbeat function. The library will call this function
3052 at the set time interval. */
3054 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3057 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3059 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname,
3062 /* Send the heartbeat */
3063 silc_server_send_heartbeat(hb->server, sock);
3066 /* Returns assembled of all servers in the given ID list. The packet's
3067 form is dictated by the New ID payload. */
3069 static void silc_server_announce_get_servers(SilcServer server,
3070 SilcServerEntry remote,
3072 SilcBuffer *servers,
3073 unsigned long creation_time)
3075 SilcIDCacheList list;
3076 SilcIDCacheEntry id_cache;
3077 SilcServerEntry entry;
3080 /* Go through all clients in the list */
3081 if (silc_idcache_get_all(id_list->servers, &list)) {
3082 if (silc_idcache_list_first(list, &id_cache)) {
3084 entry = (SilcServerEntry)id_cache->context;
3086 /* Do not announce the one we've sending our announcements and
3087 do not announce ourself. Also check the creation time if it's
3089 if ((entry == remote) || (entry == server->id_entry) ||
3090 (creation_time && entry->data.created < creation_time)) {
3091 if (!silc_idcache_list_next(list, &id_cache))
3096 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3098 *servers = silc_buffer_realloc(*servers,
3100 (*servers)->truelen + idp->len :
3102 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3103 silc_buffer_put(*servers, idp->data, idp->len);
3104 silc_buffer_pull(*servers, idp->len);
3105 silc_buffer_free(idp);
3107 if (!silc_idcache_list_next(list, &id_cache))
3112 silc_idcache_list_free(list);
3116 /* This function is used by router to announce existing servers to our
3117 primary router when we've connected to it. If `creation_time' is non-zero
3118 then only the servers that has been created after the `creation_time'
3119 will be announced. */
3121 void silc_server_announce_servers(SilcServer server, bool global,
3122 unsigned long creation_time,
3123 SilcSocketConnection remote)
3125 SilcBuffer servers = NULL;
3127 SILC_LOG_DEBUG(("Announcing servers"));
3129 /* Get servers in local list */
3130 silc_server_announce_get_servers(server, remote->user_data,
3131 server->local_list, &servers,
3135 /* Get servers in global list */
3136 silc_server_announce_get_servers(server, remote->user_data,
3137 server->global_list, &servers,
3141 silc_buffer_push(servers, servers->data - servers->head);
3142 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3144 /* Send the packet */
3145 silc_server_packet_send(server, remote,
3146 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3147 servers->data, servers->len, TRUE);
3149 silc_buffer_free(servers);
3153 /* Returns assembled packet of all clients in the given ID list. The
3154 packet's form is dictated by the New ID Payload. */
3156 static void silc_server_announce_get_clients(SilcServer server,
3158 SilcBuffer *clients,
3159 unsigned long creation_time)
3161 SilcIDCacheList list;
3162 SilcIDCacheEntry id_cache;
3163 SilcClientEntry client;
3166 /* Go through all clients in the list */
3167 if (silc_idcache_get_all(id_list->clients, &list)) {
3168 if (silc_idcache_list_first(list, &id_cache)) {
3170 client = (SilcClientEntry)id_cache->context;
3172 if (creation_time && client->data.created < creation_time) {
3173 if (!silc_idcache_list_next(list, &id_cache))
3178 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3180 *clients = silc_buffer_realloc(*clients,
3182 (*clients)->truelen + idp->len :
3184 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3185 silc_buffer_put(*clients, idp->data, idp->len);
3186 silc_buffer_pull(*clients, idp->len);
3187 silc_buffer_free(idp);
3189 if (!silc_idcache_list_next(list, &id_cache))
3194 silc_idcache_list_free(list);
3198 /* This function is used to announce our existing clients to our router
3199 when we've connected to it. If `creation_time' is non-zero then only
3200 the clients that has been created after the `creation_time' will be
3203 void silc_server_announce_clients(SilcServer server,
3204 unsigned long creation_time,
3205 SilcSocketConnection remote)
3207 SilcBuffer clients = NULL;
3209 SILC_LOG_DEBUG(("Announcing clients"));
3211 /* Get clients in local list */
3212 silc_server_announce_get_clients(server, server->local_list,
3213 &clients, creation_time);
3215 /* As router we announce our global list as well */
3216 if (server->server_type == SILC_ROUTER)
3217 silc_server_announce_get_clients(server, server->global_list,
3218 &clients, creation_time);
3221 silc_buffer_push(clients, clients->data - clients->head);
3222 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3224 /* Send the packet */
3225 silc_server_packet_send(server, remote,
3226 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3227 clients->data, clients->len, TRUE);
3229 silc_buffer_free(clients);
3234 silc_server_announce_encode_notify(SilcNotifyType notify, uint32 argc, ...)
3240 p = silc_notify_payload_encode(notify, argc, ap);
3246 /* Returns assembled packets for channel users of the `channel'. */
3248 void silc_server_announce_get_channel_users(SilcServer server,
3249 SilcChannelEntry channel,
3250 SilcBuffer *channel_users,
3251 SilcBuffer *channel_users_modes)
3253 SilcChannelClientEntry chl;
3254 SilcHashTableList htl;
3255 SilcBuffer chidp, clidp;
3258 unsigned char mode[4];
3260 SILC_LOG_DEBUG(("Start"));
3262 /* Now find all users on the channel */
3263 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3264 silc_hash_table_list(channel->user_list, &htl);
3265 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3266 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3269 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3270 clidp->data, clidp->len,
3271 chidp->data, chidp->len);
3274 silc_buffer_realloc(*channel_users,
3276 (*channel_users)->truelen + len : len));
3277 silc_buffer_pull_tail(*channel_users,
3278 ((*channel_users)->end -
3279 (*channel_users)->data));
3281 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3282 silc_buffer_pull(*channel_users, len);
3283 silc_buffer_free(tmp);
3285 /* CUMODE notify for mode change on the channel */
3286 SILC_PUT32_MSB(chl->mode, mode);
3287 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3288 3, clidp->data, clidp->len,
3290 clidp->data, clidp->len);
3292 *channel_users_modes =
3293 silc_buffer_realloc(*channel_users_modes,
3294 (*channel_users_modes ?
3295 (*channel_users_modes)->truelen + len : len));
3296 silc_buffer_pull_tail(*channel_users_modes,
3297 ((*channel_users_modes)->end -
3298 (*channel_users_modes)->data));
3300 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3301 silc_buffer_pull(*channel_users_modes, len);
3302 silc_buffer_free(tmp);
3304 silc_buffer_free(clidp);
3306 silc_buffer_free(chidp);
3309 /* Returns assembled packets for all channels and users on those channels
3310 from the given ID List. The packets are in the form dictated by the
3311 New Channel and New Channel User payloads. */
3313 void silc_server_announce_get_channels(SilcServer server,
3315 SilcBuffer *channels,
3316 SilcBuffer *channel_users,
3317 SilcBuffer **channel_users_modes,
3318 uint32 *channel_users_modes_c,
3319 SilcChannelID ***channel_ids,
3320 unsigned long creation_time)
3322 SilcIDCacheList list;
3323 SilcIDCacheEntry id_cache;
3324 SilcChannelEntry channel;
3329 int i = *channel_users_modes_c;
3332 SILC_LOG_DEBUG(("Start"));
3334 /* Go through all channels in the list */
3335 if (silc_idcache_get_all(id_list->channels, &list)) {
3336 if (silc_idcache_list_first(list, &id_cache)) {
3338 channel = (SilcChannelEntry)id_cache->context;
3340 if (creation_time && channel->created < creation_time)
3345 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3346 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3347 name_len = strlen(channel->channel_name);
3350 len = 4 + name_len + id_len + 4;
3352 silc_buffer_realloc(*channels,
3353 (*channels ? (*channels)->truelen +
3355 silc_buffer_pull_tail(*channels,
3356 ((*channels)->end - (*channels)->data));
3357 silc_buffer_format(*channels,
3358 SILC_STR_UI_SHORT(name_len),
3359 SILC_STR_UI_XNSTRING(channel->channel_name,
3361 SILC_STR_UI_SHORT(id_len),
3362 SILC_STR_UI_XNSTRING(cid, id_len),
3363 SILC_STR_UI_INT(channel->mode),
3365 silc_buffer_pull(*channels, len);
3368 *channel_users_modes = silc_realloc(*channel_users_modes,
3369 sizeof(**channel_users_modes) *
3371 (*channel_users_modes)[i] = NULL;
3372 *channel_ids = silc_realloc(*channel_ids,
3373 sizeof(**channel_ids) * (i + 1));
3374 (*channel_ids)[i] = NULL;
3375 silc_server_announce_get_channel_users(server, channel,
3377 channel_users_modes[i]);
3378 (*channel_ids)[i] = channel->id;
3381 if (!silc_idcache_list_next(list, &id_cache))
3385 *channel_users_modes_c += i;
3388 silc_idcache_list_free(list);
3392 /* This function is used to announce our existing channels to our router
3393 when we've connected to it. This also announces the users on the
3394 channels to the router. If the `creation_time' is non-zero only the
3395 channels that was created after the `creation_time' are announced.
3396 Note that the channel users are still announced even if the `creation_time'
3399 void silc_server_announce_channels(SilcServer server,
3400 unsigned long creation_time,
3401 SilcSocketConnection remote)
3403 SilcBuffer channels = NULL, channel_users = NULL;
3404 SilcBuffer *channel_users_modes = NULL;
3405 uint32 channel_users_modes_c = 0;
3406 SilcChannelID **channel_ids = NULL;
3408 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3410 /* Get channels and channel users in local list */
3411 silc_server_announce_get_channels(server, server->local_list,
3412 &channels, &channel_users,
3413 &channel_users_modes,
3414 &channel_users_modes_c,
3415 &channel_ids, creation_time);
3417 /* Get channels and channel users in global list */
3418 silc_server_announce_get_channels(server, server->global_list,
3419 &channels, &channel_users,
3420 &channel_users_modes,
3421 &channel_users_modes_c,
3422 &channel_ids, creation_time);
3425 silc_buffer_push(channels, channels->data - channels->head);
3426 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3428 /* Send the packet */
3429 silc_server_packet_send(server, remote,
3430 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3431 channels->data, channels->len,
3434 silc_buffer_free(channels);
3437 if (channel_users) {
3438 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3439 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3440 channel_users->len);
3442 /* Send the packet */
3443 silc_server_packet_send(server, remote,
3444 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3445 channel_users->data, channel_users->len,
3448 silc_buffer_free(channel_users);
3451 if (channel_users_modes) {
3454 for (i = 0; i < channel_users_modes_c; i++) {
3455 silc_buffer_push(channel_users_modes[i],
3456 channel_users_modes[i]->data -
3457 channel_users_modes[i]->head);
3458 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3459 channel_users_modes[i]->len);
3460 silc_server_packet_send_dest(server, remote,
3461 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3462 channel_ids[i], SILC_ID_CHANNEL,
3463 channel_users_modes[i]->data,
3464 channel_users_modes[i]->len,
3466 silc_buffer_free(channel_users_modes[i]);
3468 silc_free(channel_users_modes);
3469 silc_free(channel_ids);
3473 /* Failure timeout callback. If this is called then we will immediately
3474 process the received failure. We always process the failure with timeout
3475 since we do not want to blindly trust to received failure packets.
3476 This won't be called (the timeout is cancelled) if the failure was
3477 bogus (it is bogus if remote does not close the connection after sending
3480 SILC_TASK_CALLBACK(silc_server_failure_callback)
3482 SilcServerFailureContext f = (SilcServerFailureContext)context;
3484 if (f->sock->protocol) {
3485 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3486 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3492 /* Assembles user list and users mode list from the `channel'. */
3494 void silc_server_get_users_on_channel(SilcServer server,
3495 SilcChannelEntry channel,
3496 SilcBuffer *user_list,
3497 SilcBuffer *mode_list,
3500 SilcChannelClientEntry chl;
3501 SilcHashTableList htl;
3502 SilcBuffer client_id_list;
3503 SilcBuffer client_mode_list;
3505 uint32 list_count = 0, len = 0;
3507 silc_hash_table_list(channel->user_list, &htl);
3508 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3509 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3511 client_id_list = silc_buffer_alloc(len);
3513 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3514 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3515 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3517 silc_hash_table_list(channel->user_list, &htl);
3518 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3520 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3521 silc_buffer_put(client_id_list, idp->data, idp->len);
3522 silc_buffer_pull(client_id_list, idp->len);
3523 silc_buffer_free(idp);
3525 /* Client's mode on channel */
3526 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3527 silc_buffer_pull(client_mode_list, 4);
3531 silc_buffer_push(client_id_list,
3532 client_id_list->data - client_id_list->head);
3533 silc_buffer_push(client_mode_list,
3534 client_mode_list->data - client_mode_list->head);
3536 *user_list = client_id_list;
3537 *mode_list = client_mode_list;
3538 *user_count = list_count;
3541 /* Saves users and their modes to the `channel'. */
3543 void silc_server_save_users_on_channel(SilcServer server,
3544 SilcSocketConnection sock,
3545 SilcChannelEntry channel,
3546 SilcClientID *noadd,
3547 SilcBuffer user_list,
3548 SilcBuffer mode_list,
3553 for (i = 0; i < user_count; i++) {
3556 SilcClientID *client_id;
3557 SilcClientEntry client;
3560 SILC_GET16_MSB(idp_len, user_list->data + 2);
3562 client_id = silc_id_payload_parse_id(user_list->data, idp_len);
3563 silc_buffer_pull(user_list, idp_len);
3568 SILC_GET32_MSB(mode, mode_list->data);
3569 silc_buffer_pull(mode_list, 4);
3571 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3572 silc_free(client_id);
3576 /* Check if we have this client cached already. */
3577 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3578 server->server_type, NULL);
3580 client = silc_idlist_find_client_by_id(server->global_list,
3581 client_id, server->server_type,
3584 /* If router did not find such Client ID in its lists then this must
3585 be bogus client or some router in the net is buggy. */
3586 if (server->server_type == SILC_ROUTER) {
3587 silc_free(client_id);
3591 /* We don't have that client anywhere, add it. The client is added
3592 to global list since server didn't have it in the lists so it must be
3594 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3595 silc_id_dup(client_id, SILC_ID_CLIENT),
3596 sock->user_data, NULL);
3598 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3599 silc_free(client_id);
3603 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3606 silc_free(client_id);
3608 if (!silc_server_client_on_channel(client, channel)) {
3609 /* Client was not on the channel, add it. */
3610 SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3611 chl->client = client;
3613 chl->channel = channel;
3614 silc_hash_table_add(channel->user_list, chl->client, chl);
3615 silc_hash_table_add(client->channels, chl->channel, chl);
3620 /* Lookups route to the client indicated by the `id_data'. The connection
3621 object and internal data object is returned. Returns NULL if route
3622 could not be found to the client. If the `client_id' is specified then
3623 it is used and the `id_data' is ignored. */
3625 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3626 unsigned char *id_data,
3628 SilcClientID *client_id,
3629 SilcIDListData *idata)
3632 SilcClientEntry client;
3634 SILC_LOG_DEBUG(("Start"));
3636 /* Decode destination Client ID */
3638 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3640 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3644 id = silc_id_dup(client_id, SILC_ID_CLIENT);
3647 /* If the destination belongs to our server we don't have to route
3648 the packet anywhere but to send it to the local destination. */
3649 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
3653 /* If we are router and the client has router then the client is in
3654 our cell but not directly connected to us. */
3655 if (server->server_type == SILC_ROUTER && client->router) {
3656 /* We are of course in this case the client's router thus the route
3657 to the client is the server who owns the client. So, we will send
3658 the packet to that server. */
3660 *idata = (SilcIDListData)client->router;
3661 return client->router->connection;
3664 /* Seems that client really is directly connected to us */
3666 *idata = (SilcIDListData)client;
3667 return client->connection;
3670 /* Destination belongs to someone not in this server. If we are normal
3671 server our action is to send the packet to our router. */
3672 if (server->server_type != SILC_ROUTER && !server->standalone) {
3675 *idata = (SilcIDListData)server->router;
3676 return server->router->connection;
3679 /* We are router and we will perform route lookup for the destination
3680 and send the packet to fastest route. */
3681 if (server->server_type == SILC_ROUTER && !server->standalone) {
3682 /* Check first that the ID is valid */
3683 client = silc_idlist_find_client_by_id(server->global_list, id,
3686 SilcSocketConnection dst_sock;
3688 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
3692 *idata = (SilcIDListData)dst_sock->user_data;
3701 /* Encodes and returns channel list of channels the `client' has joined.
3702 Secret channels are not put to the list. */
3704 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
3705 SilcClientEntry client)
3707 SilcBuffer buffer = NULL;
3708 SilcChannelEntry channel;
3709 SilcChannelClientEntry chl;
3710 SilcHashTableList htl;
3716 silc_hash_table_list(client->channels, &htl);
3717 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3718 channel = chl->channel;
3720 if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
3721 channel->mode & SILC_CHANNEL_MODE_PRIVATE)
3724 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3725 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3726 name_len = strlen(channel->channel_name);
3728 len = 4 + name_len + id_len + 4;
3729 buffer = silc_buffer_realloc(buffer,
3730 (buffer ? (buffer)->truelen + len : len));
3731 silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
3732 silc_buffer_format(buffer,
3733 SILC_STR_UI_SHORT(name_len),
3734 SILC_STR_UI_XNSTRING(channel->channel_name,
3736 SILC_STR_UI_SHORT(id_len),
3737 SILC_STR_UI_XNSTRING(cid, id_len),
3738 SILC_STR_UI_INT(chl->mode), /* Client's mode */
3740 silc_buffer_pull(buffer, len);
3745 silc_buffer_push(buffer, buffer->data - buffer->head);
3750 /* Finds client entry by Client ID and if it is not found then resolves
3751 it using WHOIS command. */
3753 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
3754 SilcClientID *client_id)
3756 SilcClientEntry client;
3758 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3761 client = silc_idlist_find_client_by_id(server->global_list,
3762 client_id, TRUE, NULL);
3763 if (!client && server->server_type == SILC_ROUTER)
3767 if (!client && server->standalone)
3770 if (!client || !client->nickname || !client->username) {
3771 SilcBuffer buffer, idp;
3773 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
3774 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
3775 client->resolve_cmd_ident = ++server->cmd_ident;
3777 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3778 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
3779 server->cmd_ident, 1,
3780 3, idp->data, idp->len);
3781 silc_server_packet_send(server, client ? client->router->connection :
3782 server->router->connection,
3783 SILC_PACKET_COMMAND, 0,
3784 buffer->data, buffer->len, FALSE);
3785 silc_buffer_free(idp);
3786 silc_buffer_free(buffer);
3793 /* A timeout callback for the re-key. We will be the initiator of the
3796 SILC_TASK_CALLBACK(silc_server_rekey_callback)
3798 SilcSocketConnection sock = (SilcSocketConnection)context;
3799 SilcIDListData idata = (SilcIDListData)sock->user_data;
3800 SilcServer server = (SilcServer)idata->rekey->context;
3801 SilcProtocol protocol;
3802 SilcServerRekeyInternalContext *proto_ctx;
3804 SILC_LOG_DEBUG(("Start"));
3806 /* Allocate internal protocol context. This is sent as context
3808 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
3809 proto_ctx->server = (void *)server;
3810 proto_ctx->sock = sock;
3811 proto_ctx->responder = FALSE;
3812 proto_ctx->pfs = idata->rekey->pfs;
3814 /* Perform rekey protocol. Will call the final callback after the
3815 protocol is over. */
3816 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
3817 &protocol, proto_ctx, silc_server_rekey_final);
3818 sock->protocol = protocol;
3820 /* Run the protocol */
3821 silc_protocol_execute(protocol, server->schedule, 0, 0);
3823 /* Re-register re-key timeout */
3824 silc_schedule_task_add(server->schedule, sock->sock,
3825 silc_server_rekey_callback,
3826 context, idata->rekey->timeout, 0,
3827 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
3830 /* The final callback for the REKEY protocol. This will actually take the
3831 new key material into use. */
3833 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
3835 SilcProtocol protocol = (SilcProtocol)context;
3836 SilcServerRekeyInternalContext *ctx =
3837 (SilcServerRekeyInternalContext *)protocol->context;
3838 SilcServer server = (SilcServer)ctx->server;
3839 SilcSocketConnection sock = ctx->sock;
3841 SILC_LOG_DEBUG(("Start"));
3843 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
3844 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
3845 /* Error occured during protocol */
3846 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
3847 silc_protocol_cancel(protocol, server->schedule);
3848 silc_protocol_free(protocol);
3849 sock->protocol = NULL;
3851 silc_packet_context_free(ctx->packet);
3853 silc_ske_free(ctx->ske);
3858 /* Purge the outgoing data queue to assure that all rekey packets really
3859 go to the network before we quit the protocol. */
3860 silc_server_packet_queue_purge(server, sock);
3863 silc_protocol_free(protocol);
3864 sock->protocol = NULL;
3866 silc_packet_context_free(ctx->packet);
3868 silc_ske_free(ctx->ske);