5 Author: Pekka Riikonen <priikone@poseidon.pspt.fi>
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);
42 /* Allocates a new SILC server object. This has to be done before the server
43 can be used. After allocation one must call silc_server_init to initialize
44 the server. The new allocated server object is returned to the new_server
47 int silc_server_alloc(SilcServer *new_server)
51 SILC_LOG_DEBUG(("Allocating new server object"));
53 server = silc_calloc(1, sizeof(*server));
54 server->server_type = SILC_SERVER;
55 server->standalone = TRUE;
56 server->local_list = silc_calloc(1, sizeof(*server->local_list));
57 server->global_list = silc_calloc(1, sizeof(*server->global_list));
58 server->pending_commands = silc_dlist_init();
60 server->sim = silc_dlist_init();
68 /* Free's the SILC server object. This is called at the very end before
71 void silc_server_free(SilcServer server)
78 if (server->local_list)
79 silc_free(server->local_list);
80 if (server->global_list)
81 silc_free(server->global_list);
83 silc_rng_free(server->rng);
86 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
87 silc_dlist_del(server->sim, sim);
90 silc_dlist_uninit(server->sim);
94 silc_free(server->params);
96 if (server->pending_commands)
97 silc_dlist_uninit(server->pending_commands);
99 silc_math_primegen_uninit(); /* XXX */
104 /* Initializes the entire SILC server. This is called always before running
105 the server. This is called only once at the initialization of the program.
106 This binds the server to its listenning port. After this function returns
107 one should call silc_server_run to start the server. This returns TRUE
108 when everything is ok to run the server. Configuration file must be
109 read and parsed before calling this. */
111 int silc_server_init(SilcServer server)
113 int *sock = NULL, sock_count = 0, i;
115 SilcServerEntry id_entry;
117 SILC_LOG_DEBUG(("Initializing server"));
119 assert(server->config);
121 /* XXX After server is made as Silc Server Library this can be given
122 as argument, for now this is hard coded */
123 server->params = silc_calloc(1, sizeof(*server->params));
124 server->params->retry_count = SILC_SERVER_RETRY_COUNT;
125 server->params->retry_interval_min = SILC_SERVER_RETRY_INTERVAL_MIN;
126 server->params->retry_interval_max = SILC_SERVER_RETRY_INTERVAL_MAX;
127 server->params->retry_keep_trying = FALSE;
128 server->params->protocol_timeout = 60;
129 server->params->require_reverse_mapping = FALSE;
131 /* Set log files where log message should be saved. */
132 server->config->server = server;
133 silc_config_server_setlogfiles(server->config);
135 /* Register all configured ciphers, PKCS and hash functions. */
136 silc_config_server_register_ciphers(server->config);
137 silc_config_server_register_pkcs(server->config);
138 silc_config_server_register_hashfuncs(server->config);
140 /* Initialize random number generator for the server. */
141 server->rng = silc_rng_alloc();
142 silc_rng_init(server->rng);
143 silc_math_primegen_init(); /* XXX */
145 /* Initialize hash functions for server to use */
146 silc_hash_alloc("md5", &server->md5hash);
147 silc_hash_alloc("sha1", &server->sha1hash);
149 /* Initialize none cipher */
150 silc_cipher_alloc("none", &server->none_cipher);
152 /* XXXXX Generate RSA key pair */
154 unsigned char *public_key;
155 unsigned char *private_key;
156 unsigned int pk_len, prv_len;
159 if (stat("pubkey.pub", &st) < 0 && stat("privkey.prv", &st) < 0) {
161 if (silc_pkcs_alloc("rsa", &server->pkcs) == FALSE) {
162 SILC_LOG_ERROR(("Could not create RSA key pair"));
166 if (server->pkcs->pkcs->init(server->pkcs->context,
167 1024, server->rng) == FALSE) {
168 SILC_LOG_ERROR(("Could not generate RSA key pair"));
172 public_key = server->pkcs->pkcs->get_public_key(server->pkcs->context,
174 private_key = server->pkcs->pkcs->get_private_key(server->pkcs->context,
177 SILC_LOG_HEXDUMP(("public key"), public_key, pk_len);
178 SILC_LOG_HEXDUMP(("private key"), private_key, prv_len);
181 silc_pkcs_public_key_alloc("rsa", "UN=root, HN=dummy",
183 server->private_key =
184 silc_pkcs_private_key_alloc("rsa", private_key, prv_len);
187 silc_pkcs_save_public_key("pubkey.pub", server->public_key,
189 silc_pkcs_save_private_key("privkey.prv", server->private_key, NULL,
192 memset(public_key, 0, pk_len);
193 memset(private_key, 0, prv_len);
194 silc_free(public_key);
195 silc_free(private_key);
197 silc_pkcs_load_public_key("pubkey.pub", &server->public_key,
199 silc_pkcs_load_private_key("privkey.prv", &server->private_key,
204 /* Create a listening server. Note that our server can listen on
205 multiple ports. All listeners are created here and now. */
206 /* XXX Still check this whether to use server_info or listen_port. */
208 while(server->config->listen_port) {
211 tmp = silc_net_create_server(server->config->listen_port->port,
212 server->config->listen_port->host);
216 sock = silc_realloc(sock, (sizeof(int *) * (sock_count + 1)));
217 sock[sock_count] = tmp;
218 server->config->listen_port = server->config->listen_port->next;
222 /* Initialize ID caches */
223 server->local_list->clients = silc_idcache_alloc(0);
224 server->local_list->servers = silc_idcache_alloc(0);
225 server->local_list->channels = silc_idcache_alloc(0);
227 /* These are allocated for normal server as well as these hold some
228 global information that the server has fetched from its router. For
229 router these are used as they are supposed to be used on router. */
230 server->global_list->clients = silc_idcache_alloc(0);
231 server->global_list->servers = silc_idcache_alloc(0);
232 server->global_list->channels = silc_idcache_alloc(0);
234 /* Allocate the entire socket list that is used in server. Eventually
235 all connections will have entry in this table (it is a table of
236 pointers to the actual object that is allocated individually
238 server->sockets = silc_calloc(SILC_SERVER_MAX_CONNECTIONS,
239 sizeof(*server->sockets));
241 for (i = 0; i < sock_count; i++) {
242 SilcSocketConnection newsocket = NULL;
244 /* Set socket to non-blocking mode */
245 silc_net_set_socket_nonblock(sock[i]);
246 server->sock = sock[i];
248 /* Create a Server ID for the server. */
249 silc_id_create_server_id(sock[i], server->rng, &id);
255 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
256 server->id_string_len = silc_id_get_len(SILC_ID_SERVER);
257 server->id_type = SILC_ID_SERVER;
258 server->server_name = server->config->server_info->server_name;
260 /* Add ourselves to the server list. We don't have a router yet
261 beacuse we haven't established a route yet. It will be done later.
262 For now, NULL is sent as router. This allocates new entry to
265 silc_idlist_add_server(server->local_list,
266 server->config->server_info->server_name,
267 server->server_type, server->id, NULL, NULL);
269 SILC_LOG_ERROR(("Could not add ourselves to cache"));
273 /* Add ourselves also to the socket table. The entry allocated above
274 is sent as argument for fast referencing in the future. */
275 silc_socket_alloc(sock[i], SILC_SOCKET_TYPE_SERVER, id_entry,
280 server->sockets[sock[i]] = newsocket;
282 /* Put the allocated socket pointer also to the entry allocated above
283 for fast back-referencing to the socket list. */
284 id_entry->connection = (void *)server->sockets[sock[i]];
285 server->id_entry = id_entry;
288 /* Register the task queues. In SILC we have by default three task queues.
289 One task queue for non-timeout tasks which perform different kind of
290 I/O on file descriptors, timeout task queue for timeout tasks, and,
291 generic non-timeout task queue whose tasks apply to all connections. */
292 silc_task_queue_alloc(&server->io_queue, TRUE);
293 if (!server->io_queue) {
296 silc_task_queue_alloc(&server->timeout_queue, TRUE);
297 if (!server->timeout_queue) {
300 silc_task_queue_alloc(&server->generic_queue, TRUE);
301 if (!server->generic_queue) {
305 /* Register protocols */
306 silc_server_protocols_register();
308 /* Initialize the scheduler */
309 silc_schedule_init(&server->io_queue, &server->timeout_queue,
310 &server->generic_queue,
311 SILC_SERVER_MAX_CONNECTIONS);
313 /* Add the first task to the queue. This is task that is executed by
314 timeout. It expires as soon as the caller calls silc_server_run. This
315 task performs authentication protocol and key exchange with our
317 silc_task_register(server->timeout_queue, sock[0],
318 silc_server_connect_to_router,
319 (void *)server, 0, 1,
321 SILC_TASK_PRI_NORMAL);
323 /* Add listener task to the queue. This task receives new connections to the
324 server. This task remains on the queue until the end of the program. */
325 silc_task_register(server->io_queue, sock[0],
326 silc_server_accept_new_connection,
327 (void *)server, 0, 0,
329 SILC_TASK_PRI_NORMAL);
330 server->listenning = TRUE;
332 /* If server connections has been configured then we must be router as
333 normal server cannot have server connections, only router connections. */
334 if (server->config->servers)
335 server->server_type = SILC_ROUTER;
337 SILC_LOG_DEBUG(("Server initialized"));
339 /* We are done here, return succesfully */
342 silc_task_queue_free(server->timeout_queue);
344 silc_task_queue_free(server->io_queue);
346 for (i = 0; i < sock_count; i++)
347 silc_net_close_server(sock[i]);
352 /* Fork server to background and set gid+uid to non-root.
353 Silcd will not run as root, so trying to set either user or group to
354 root will cause silcd to exit. */
356 void silc_server_daemonise(SilcServer server)
358 /* Are we executing silcd as root or a regular user? */
365 if (!server->config->identity || !server->config->identity->user ||
366 !server->config->identity->group) {
367 fprintf(stderr, "Error:"
368 "\tSILC server must not be run as root. For the security of your\n"
369 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
370 "\tuser account. Modify the [Identity] configuration section to run\n"
371 "\tthe server as non-root user.\n");
375 /* Get the values given for user and group in configuration file */
376 user=server->config->identity->user;
377 group=server->config->identity->group;
379 /* Check whether the user/group information is text */
380 if (atoi(user)!=0 || atoi(group)!=0) {
381 SILC_LOG_DEBUG(("Invalid user and/or group information"));
382 SILC_LOG_DEBUG(("User and/or group given as number"));
383 fprintf(stderr, "Invalid user and/or group information\n");
384 fprintf(stderr, "Please assign them as names, not numbers\n");
388 /* Catch the nasty incident of string "0" returning 0 from atoi */
389 if (strcmp("0", user)==0 || strcmp("0", group)==0) {
390 SILC_LOG_DEBUG(("User and/or group configured to 0. Unacceptable"));
391 fprintf(stderr, "User and/or group configured to 0. Exiting\n");
399 fprintf(stderr, "No such user %s found\n", user);
404 fprintf(stderr, "No such group %s found\n", group);
408 /* Check whether user and/or group is set to root. If yes, exit
409 immediately. Otherwise, setgid and setuid server to user.group */
410 if (gr->gr_gid==0 || pw->pw_uid==0) {
411 fprintf(stderr, "Error:"
412 "\tSILC server must not be run as root. For the security of your\n"
413 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
414 "\tuser account. Modify the [Identity] configuration section to run\n"
415 "\tthe server as non-root user.\n");
418 /* Fork server to background, making it a daemon */
420 SILC_LOG_DEBUG(("Server started as root. Dropping privileges."));
421 SILC_LOG_DEBUG(("Forking SILC server to background"));
426 SILC_LOG_DEBUG(("Changing to group %s", group));
427 if(setgid(gr->gr_gid)==0) {
428 SILC_LOG_DEBUG(("Setgid to %s", group));
430 SILC_LOG_DEBUG(("Setgid to %s failed", group));
431 fprintf(stderr, "Tried to setgid %s but no such group. Exiting\n",
435 SILC_LOG_DEBUG(("Changing to user nobody"));
436 if(setuid(pw->pw_uid)==0) {
437 SILC_LOG_DEBUG(("Setuid to %s", user));
439 SILC_LOG_DEBUG(("Setuid to %s failed", user));
440 fprintf(stderr, "Tried to setuid %s but no such user. Exiting\n",
446 /* Fork server to background, making it a daemon */
448 SILC_LOG_DEBUG(("Server started as user"));
449 SILC_LOG_DEBUG(("Forking SILC server to background"));
456 /* Stops the SILC server. This function is used to shutdown the server.
457 This is usually called after the scheduler has returned. After stopping
458 the server one should call silc_server_free. */
460 void silc_server_stop(SilcServer server)
462 SILC_LOG_DEBUG(("Stopping server"));
464 /* Stop the scheduler, although it might be already stopped. This
465 doesn't hurt anyone. This removes all the tasks and task queues,
467 silc_schedule_stop();
468 silc_schedule_uninit();
470 silc_server_protocols_unregister();
472 SILC_LOG_DEBUG(("Server stopped"));
475 /* The heart of the server. This runs the scheduler thus runs the server.
476 When this returns the server has been stopped and the program will
479 void silc_server_run(SilcServer server)
481 SILC_LOG_DEBUG(("Running server"));
483 /* Start the scheduler, the heart of the SILC server. When this returns
484 the program will be terminated. */
488 /* Timeout callback that will be called to retry connecting to remote
489 router. This is used by both normal and router server. This will wait
490 before retrying the connecting. The timeout is generated by exponential
491 backoff algorithm. */
493 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
495 SilcServerConnection sconn = (SilcServerConnection)context;
496 SilcServer server = sconn->server;
498 SILC_LOG_INFO(("Retrying connecting to a router"));
500 /* Calculate next timeout */
501 if (sconn->retry_count >= 1) {
502 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
503 if (sconn->retry_timeout > SILC_SERVER_RETRY_INTERVAL_MAX)
504 sconn->retry_timeout = SILC_SERVER_RETRY_INTERVAL_MAX;
506 sconn->retry_timeout = server->params->retry_interval_min;
508 sconn->retry_count++;
509 sconn->retry_timeout = sconn->retry_timeout +
510 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
512 /* If we've reached max retry count, give up. */
513 if (sconn->retry_count > server->params->retry_count &&
514 server->params->retry_keep_trying == FALSE) {
515 SILC_LOG_ERROR(("Could not connect to router, giving up"));
519 /* Wait one before retrying */
520 silc_task_register(server->timeout_queue, fd, silc_server_connect_router,
521 context, sconn->retry_timeout,
522 server->params->retry_interval_min_usec,
523 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
526 /* Generic routine to use connect to a router. */
528 SILC_TASK_CALLBACK(silc_server_connect_router)
530 SilcServerConnection sconn = (SilcServerConnection)context;
531 SilcServer server = sconn->server;
532 SilcSocketConnection newsocket;
533 SilcProtocol protocol;
534 SilcServerKEInternalContext *proto_ctx;
537 /* Connect to remote host */
538 sock = silc_net_create_connection(sconn->remote_port,
541 SILC_LOG_ERROR(("Could not connect to router"));
542 silc_task_register(server->timeout_queue, fd,
543 silc_server_connect_to_router_retry,
544 context, 0, 1, SILC_TASK_TIMEOUT,
545 SILC_TASK_PRI_NORMAL);
549 /* Set socket options */
550 silc_net_set_socket_nonblock(sock);
551 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
553 /* Create socket connection for the connection. Even though we
554 know that we are connecting to a router we will mark the socket
555 to be unknown connection until we have executed authentication
557 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
558 server->sockets[sock] = newsocket;
559 newsocket->hostname = strdup(sconn->remote_host);
560 newsocket->ip = strdup(sconn->remote_host);
561 newsocket->port = sconn->remote_port;
562 sconn->sock = newsocket;
564 /* Allocate internal protocol context. This is sent as context
566 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
567 proto_ctx->server = (void *)server;
568 proto_ctx->context = (void *)sconn;
569 proto_ctx->sock = newsocket;
570 proto_ctx->rng = server->rng;
571 proto_ctx->responder = FALSE;
573 /* Perform key exchange protocol. silc_server_connect_to_router_second
574 will be called after the protocol is finished. */
575 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
576 &protocol, proto_ctx,
577 silc_server_connect_to_router_second);
578 newsocket->protocol = protocol;
580 /* Register a timeout task that will be executed if the protocol
581 is not executed within set limit. */
582 proto_ctx->timeout_task =
583 silc_task_register(server->timeout_queue, sock,
584 silc_server_timeout_remote,
585 server, server->params->protocol_timeout,
586 server->params->protocol_timeout_usec,
590 /* Register the connection for network input and output. This sets
591 that scheduler will listen for incoming packets for this connection
592 and sets that outgoing packets may be sent to this connection as
593 well. However, this doesn't set the scheduler for outgoing traffic,
594 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
595 later when outgoing data is available. */
596 context = (void *)server;
597 SILC_REGISTER_CONNECTION_FOR_IO(sock);
599 /* Run the protocol */
600 protocol->execute(server->timeout_queue, 0, protocol, sock, 0, 0);
603 /* This function connects to our primary router or if we are a router this
604 establishes all our primary routes. This is called at the start of the
605 server to do authentication and key exchange with our router - called
608 SILC_TASK_CALLBACK(silc_server_connect_to_router)
610 SilcServer server = (SilcServer)context;
611 SilcServerConnection sconn;
613 SILC_LOG_DEBUG(("Connecting to router(s)"));
615 /* If we are normal SILC server we need to connect to our cell's
617 if (server->server_type == SILC_SERVER) {
618 SILC_LOG_DEBUG(("We are normal server"));
620 /* Create connection to the router, if configured. */
621 if (server->config->routers) {
623 /* Allocate connection object for hold connection specific stuff. */
624 sconn = silc_calloc(1, sizeof(*sconn));
625 sconn->server = server;
626 sconn->remote_host = server->config->routers->host;
627 sconn->remote_port = server->config->routers->port;
629 silc_task_register(server->timeout_queue, fd,
630 silc_server_connect_router,
631 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
632 SILC_TASK_PRI_NORMAL);
637 /* If we are a SILC router we need to establish all of our primary
639 if (server->server_type == SILC_ROUTER) {
640 SilcConfigServerSectionServerConnection *ptr;
642 SILC_LOG_DEBUG(("We are router"));
644 /* Create the connections to all our routes */
645 ptr = server->config->routers;
648 SILC_LOG_DEBUG(("Router connection [%s] %s:%d",
649 ptr->initiator ? "Initiator" : "Responder",
650 ptr->host, ptr->port));
652 if (ptr->initiator) {
653 /* Allocate connection object for hold connection specific stuff. */
654 sconn = silc_calloc(1, sizeof(*sconn));
655 sconn->server = server;
656 sconn->remote_host = ptr->host;
657 sconn->remote_port = ptr->port;
659 silc_task_register(server->timeout_queue, fd,
660 silc_server_connect_router,
661 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
662 SILC_TASK_PRI_NORMAL);
672 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
674 /* There wasn't a configured router, we will continue but we don't
675 have a connection to outside world. We will be standalone server. */
676 server->standalone = TRUE;
679 /* Second part of connecting to router(s). Key exchange protocol has been
680 executed and now we will execute authentication protocol. */
682 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
684 SilcProtocol protocol = (SilcProtocol)context;
685 SilcServerKEInternalContext *ctx =
686 (SilcServerKEInternalContext *)protocol->context;
687 SilcServer server = (SilcServer)ctx->server;
688 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
689 SilcSocketConnection sock = NULL;
690 SilcServerConnAuthInternalContext *proto_ctx;
692 SILC_LOG_DEBUG(("Start"));
694 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
695 /* Error occured during protocol */
696 silc_protocol_free(protocol);
698 silc_packet_context_free(ctx->packet);
700 silc_ske_free(ctx->ske);
702 silc_free(ctx->dest_id);
704 sock->protocol = NULL;
705 silc_server_disconnect_remote(server, sock, "Server closed connection: "
706 "Key exchange failed");
710 /* Allocate internal context for the authentication protocol. This
711 is sent as context for the protocol. */
712 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
713 proto_ctx->server = (void *)server;
714 proto_ctx->context = (void *)sconn;
715 proto_ctx->sock = sock = server->sockets[fd];
716 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
717 proto_ctx->dest_id_type = ctx->dest_id_type;
718 proto_ctx->dest_id = ctx->dest_id;
720 /* Resolve the authentication method used in this connection */
721 proto_ctx->auth_meth = SILC_PROTOCOL_CONN_AUTH_PASSWORD;
722 if (server->config->routers) {
723 SilcConfigServerSectionServerConnection *conn = NULL;
725 /* Check if we find a match from user configured connections */
726 conn = silc_config_server_find_router_conn(server->config,
730 /* Match found. Use the configured authentication method */
731 proto_ctx->auth_meth = conn->auth_meth;
732 if (conn->auth_data) {
733 proto_ctx->auth_data = strdup(conn->auth_data);
734 proto_ctx->auth_data_len = strlen(conn->auth_data);
737 /* No match found. */
744 /* Free old protocol as it is finished now */
745 silc_protocol_free(protocol);
747 silc_packet_context_free(ctx->packet);
749 sock->protocol = NULL;
751 /* Allocate the authentication protocol. This is allocated here
752 but we won't start it yet. We will be receiving party of this
753 protocol thus we will wait that connecting party will make
755 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
756 &sock->protocol, proto_ctx,
757 silc_server_connect_to_router_final);
759 /* Register timeout task. If the protocol is not executed inside
760 this timelimit the connection will be terminated. Currently
761 this is 15 seconds and is hard coded limit (XXX). */
762 proto_ctx->timeout_task =
763 silc_task_register(server->timeout_queue, sock->sock,
764 silc_server_timeout_remote,
765 (void *)server, 15, 0,
769 /* Run the protocol */
770 sock->protocol->execute(server->timeout_queue, 0,
771 sock->protocol, sock->sock, 0, 0);
774 /* Finalizes the connection to router. Registers a server task to the
775 queue so that we can accept new connections. */
777 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
779 SilcProtocol protocol = (SilcProtocol)context;
780 SilcServerConnAuthInternalContext *ctx =
781 (SilcServerConnAuthInternalContext *)protocol->context;
782 SilcServer server = (SilcServer)ctx->server;
783 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
784 SilcSocketConnection sock = ctx->sock;
785 SilcServerEntry id_entry;
787 SilcServerHBContext hb_context;
788 unsigned char *id_string;
790 SILC_LOG_DEBUG(("Start"));
792 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
793 /* Error occured during protocol */
795 silc_free(ctx->dest_id);
796 silc_server_disconnect_remote(server, sock, "Server closed connection: "
797 "Authentication failed");
801 /* Add a task to the queue. This task receives new connections to the
802 server. This task remains on the queue until the end of the program. */
803 if (!server->listenning) {
804 silc_task_register(server->io_queue, server->sock,
805 silc_server_accept_new_connection,
806 (void *)server, 0, 0,
808 SILC_TASK_PRI_NORMAL);
809 server->listenning = TRUE;
812 /* Send NEW_SERVER packet to the router. We will become registered
813 to the SILC network after sending this packet. */
814 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
815 packet = silc_buffer_alloc(2 + 2 + SILC_ID_SERVER_LEN +
816 strlen(server->server_name));
817 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
818 silc_buffer_format(packet,
819 SILC_STR_UI_SHORT(SILC_ID_SERVER_LEN),
820 SILC_STR_UI_XNSTRING(id_string, SILC_ID_SERVER_LEN),
821 SILC_STR_UI_SHORT(strlen(server->server_name)),
822 SILC_STR_UI_XNSTRING(server->server_name,
823 strlen(server->server_name)),
826 /* Send the packet */
827 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
828 packet->data, packet->len, TRUE);
829 silc_buffer_free(packet);
830 silc_free(id_string);
832 SILC_LOG_DEBUG(("Connected to router %s", sock->hostname));
834 /* Add the connected router to local server list */
835 server->standalone = FALSE;
836 id_entry = silc_idlist_add_server(server->local_list, sock->hostname,
837 SILC_ROUTER, ctx->dest_id, NULL, sock);
840 silc_free(ctx->dest_id);
841 silc_server_disconnect_remote(server, sock, "Server closed connection: "
842 "Authentication failed");
846 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
847 silc_free(sock->user_data);
848 sock->user_data = (void *)id_entry;
849 sock->type = SILC_SOCKET_TYPE_ROUTER;
850 server->id_entry->router = id_entry;
851 server->router = id_entry;
852 server->router->data.registered = TRUE;
854 /* Perform keepalive. The `hb_context' will be freed automatically
855 when finally calling the silc_socket_free function. XXX hardcoded
857 hb_context = silc_calloc(1, sizeof(*hb_context));
858 hb_context->server = server;
859 silc_socket_set_heartbeat(sock, 600, hb_context,
860 silc_server_perform_heartbeat,
861 server->timeout_queue);
863 /* If we are router then announce our possible servers. */
864 if (server->server_type == SILC_ROUTER)
865 silc_server_announce_servers(server);
867 /* Announce our clients and channels to the router */
868 silc_server_announce_clients(server);
869 silc_server_announce_channels(server);
872 /* Free the temporary connection data context */
876 /* Free the protocol object */
877 silc_protocol_free(protocol);
879 silc_packet_context_free(ctx->packet);
881 silc_ske_free(ctx->ske);
883 sock->protocol = NULL;
886 /* Accepts new connections to the server. Accepting new connections are
887 done in three parts to make it async. */
889 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
891 SilcServer server = (SilcServer)context;
892 SilcSocketConnection newsocket;
893 SilcServerKEInternalContext *proto_ctx;
896 SILC_LOG_DEBUG(("Accepting new connection"));
898 server->stat.conn_attempts++;
900 sock = silc_net_accept_connection(server->sock);
902 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
903 server->stat.conn_failures++;
907 /* Check max connections */
908 if (sock > SILC_SERVER_MAX_CONNECTIONS) {
909 if (server->config->redirect) {
910 /* XXX Redirecting connection to somewhere else now?? */
911 /*silc_server_send_notify("Server is full, trying to redirect..."); */
913 SILC_LOG_ERROR(("Refusing connection, server is full"));
914 server->stat.conn_failures++;
919 /* Set socket options */
920 silc_net_set_socket_nonblock(sock);
921 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
923 /* We don't create a ID yet, since we don't know what type of connection
924 this is yet. But, we do add the connection to the socket table. */
925 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
926 server->sockets[sock] = newsocket;
928 /* XXX This MUST be done async as this will block the entire server
929 process. Either we have to do our own resolver stuff or in the future
930 we can use threads. */
931 /* Perform name and address lookups for the remote host. */
932 silc_net_check_host_by_sock(sock, &newsocket->hostname, &newsocket->ip);
933 if ((server->params->require_reverse_mapping && !newsocket->hostname) ||
935 SILC_LOG_ERROR(("IP/DNS lookup failed"));
936 server->stat.conn_failures++;
939 if (!newsocket->hostname)
940 newsocket->hostname = strdup(newsocket->ip);
942 SILC_LOG_INFO(("Incoming connection from %s (%s)", newsocket->hostname,
945 /* Allocate internal context for key exchange protocol. This is
946 sent as context for the protocol. */
947 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
948 proto_ctx->server = context;
949 proto_ctx->sock = newsocket;
950 proto_ctx->rng = server->rng;
951 proto_ctx->responder = TRUE;
953 /* Prepare the connection for key exchange protocol. We allocate the
954 protocol but will not start it yet. The connector will be the
955 initiator of the protocol thus we will wait for initiation from
956 there before we start the protocol. */
957 server->stat.auth_attempts++;
958 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
959 &newsocket->protocol, proto_ctx,
960 silc_server_accept_new_connection_second);
962 /* Register a timeout task that will be executed if the connector
963 will not start the key exchange protocol within 60 seconds. For
964 now, this is a hard coded limit. After 60 secs the connection will
965 be closed if the key exchange protocol has not been started. */
966 proto_ctx->timeout_task =
967 silc_task_register(server->timeout_queue, newsocket->sock,
968 silc_server_timeout_remote,
973 /* Register the connection for network input and output. This sets
974 that scheduler will listen for incoming packets for this connection
975 and sets that outgoing packets may be sent to this connection as well.
976 However, this doesn't set the scheduler for outgoing traffic, it
977 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
978 later when outgoing data is available. */
979 SILC_REGISTER_CONNECTION_FOR_IO(sock);
982 /* Second part of accepting new connection. Key exchange protocol has been
983 performed and now it is time to do little connection authentication
984 protocol to figure out whether this connection is client or server
985 and whether it has right to access this server (especially server
986 connections needs to be authenticated). */
988 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
990 SilcProtocol protocol = (SilcProtocol)context;
991 SilcServerKEInternalContext *ctx =
992 (SilcServerKEInternalContext *)protocol->context;
993 SilcServer server = (SilcServer)ctx->server;
994 SilcSocketConnection sock = NULL;
995 SilcServerConnAuthInternalContext *proto_ctx;
997 SILC_LOG_DEBUG(("Start"));
999 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
1000 /* Error occured during protocol */
1001 silc_protocol_free(protocol);
1003 silc_packet_context_free(ctx->packet);
1005 silc_ske_free(ctx->ske);
1007 silc_free(ctx->dest_id);
1010 sock->protocol = NULL;
1011 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1012 "Key exchange failed");
1013 server->stat.auth_failures++;
1017 /* Allocate internal context for the authentication protocol. This
1018 is sent as context for the protocol. */
1019 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1020 proto_ctx->server = (void *)server;
1021 proto_ctx->sock = sock = server->sockets[fd];
1022 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1023 proto_ctx->responder = TRUE;
1024 proto_ctx->dest_id_type = ctx->dest_id_type;
1025 proto_ctx->dest_id = ctx->dest_id;
1027 /* Free old protocol as it is finished now */
1028 silc_protocol_free(protocol);
1030 silc_packet_context_free(ctx->packet);
1032 sock->protocol = NULL;
1034 /* Allocate the authentication protocol. This is allocated here
1035 but we won't start it yet. We will be receiving party of this
1036 protocol thus we will wait that connecting party will make
1037 their first move. */
1038 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1039 &sock->protocol, proto_ctx,
1040 silc_server_accept_new_connection_final);
1042 /* Register timeout task. If the protocol is not executed inside
1043 this timelimit the connection will be terminated. Currently
1044 this is 60 seconds and is hard coded limit (XXX). */
1045 proto_ctx->timeout_task =
1046 silc_task_register(server->timeout_queue, sock->sock,
1047 silc_server_timeout_remote,
1048 (void *)server, 60, 0,
1053 /* Final part of accepting new connection. The connection has now
1054 been authenticated and keys has been exchanged. We also know whether
1055 this is client or server connection. */
1057 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1059 SilcProtocol protocol = (SilcProtocol)context;
1060 SilcServerConnAuthInternalContext *ctx =
1061 (SilcServerConnAuthInternalContext *)protocol->context;
1062 SilcServer server = (SilcServer)ctx->server;
1063 SilcSocketConnection sock = ctx->sock;
1064 SilcServerHBContext hb_context;
1065 void *id_entry = NULL;
1067 SILC_LOG_DEBUG(("Start"));
1069 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
1070 /* Error occured during protocol */
1071 silc_protocol_free(protocol);
1073 silc_packet_context_free(ctx->packet);
1075 silc_ske_free(ctx->ske);
1077 silc_free(ctx->dest_id);
1080 sock->protocol = NULL;
1081 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1082 "Authentication failed");
1083 server->stat.auth_failures++;
1087 sock->type = ctx->conn_type;
1088 switch(sock->type) {
1089 case SILC_SOCKET_TYPE_CLIENT:
1091 SilcClientEntry client;
1093 SILC_LOG_DEBUG(("Remote host is client"));
1094 SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
1097 /* Add the client to the client ID cache. The nickname and Client ID
1098 and other information is created after we have received NEW_CLIENT
1099 packet from client. */
1100 client = silc_idlist_add_client(server->local_list,
1101 NULL, NULL, NULL, NULL, NULL, sock);
1103 SILC_LOG_ERROR(("Could not add new client to cache"));
1104 silc_free(sock->user_data);
1109 server->stat.my_clients++;
1110 server->stat.clients++;
1111 if (server->server_type == SILC_ROUTER)
1112 server->stat.cell_clients++;
1114 id_entry = (void *)client;
1117 case SILC_SOCKET_TYPE_SERVER:
1118 case SILC_SOCKET_TYPE_ROUTER:
1120 SilcServerEntry new_server;
1122 SILC_LOG_DEBUG(("Remote host is %s",
1123 sock->type == SILC_SOCKET_TYPE_SERVER ?
1124 "server" : "router"));
1125 SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
1126 sock->ip, sock->type == SILC_SOCKET_TYPE_SERVER ?
1127 "server" : "router"));
1129 /* Add the server into server cache. The server name and Server ID
1130 is updated after we have received NEW_SERVER packet from the
1131 server. We mark ourselves as router for this server if we really
1134 silc_idlist_add_server(server->local_list, NULL,
1135 sock->type == SILC_SOCKET_TYPE_SERVER ?
1136 SILC_SERVER : SILC_ROUTER, NULL,
1137 sock->type == SILC_SOCKET_TYPE_SERVER ?
1138 server->id_entry : NULL, sock);
1140 SILC_LOG_ERROR(("Could not add new server to cache"));
1141 silc_free(sock->user_data);
1146 if (sock->type == SILC_SOCKET_TYPE_SERVER)
1147 server->stat.my_servers++;
1149 server->stat.my_routers++;
1150 server->stat.servers++;
1152 id_entry = (void *)new_server;
1154 /* There is connection to other server now, if it is router then
1155 we will have connection to outside world. If we are router but
1156 normal server connected to us then we will remain standalone,
1157 if we are standlone. */
1158 if (server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER) {
1159 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1160 server->standalone = FALSE;
1161 if (!server->id_entry->router) {
1162 server->id_entry->router = id_entry;
1163 server->router = id_entry;
1172 /* Add the common data structure to the ID entry. */
1174 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1176 /* Add to sockets internal pointer for fast referencing */
1177 silc_free(sock->user_data);
1178 sock->user_data = id_entry;
1180 /* Connection has been fully established now. Everything is ok. */
1181 SILC_LOG_DEBUG(("New connection authenticated"));
1183 /* Perform keepalive. The `hb_context' will be freed automatically
1184 when finally calling the silc_socket_free function. XXX hardcoded
1186 hb_context = silc_calloc(1, sizeof(*hb_context));
1187 hb_context->server = server;
1188 silc_socket_set_heartbeat(sock, 600, hb_context,
1189 silc_server_perform_heartbeat,
1190 server->timeout_queue);
1192 silc_protocol_free(protocol);
1194 silc_packet_context_free(ctx->packet);
1196 silc_ske_free(ctx->ske);
1198 silc_free(ctx->dest_id);
1200 sock->protocol = NULL;
1203 /* This function is used to read packets from network and send packets to
1204 network. This is usually a generic task. */
1206 SILC_TASK_CALLBACK(silc_server_packet_process)
1208 SilcServer server = (SilcServer)context;
1209 SilcSocketConnection sock = server->sockets[fd];
1210 SilcIDListData idata;
1211 SilcCipher cipher = NULL;
1212 SilcHmac hmac = NULL;
1218 SILC_LOG_DEBUG(("Processing packet"));
1220 /* Packet sending */
1222 if (type == SILC_TASK_WRITE) {
1223 /* Do not send data to disconnected connection */
1224 if (SILC_IS_DISCONNECTED(sock))
1227 server->stat.packets_sent++;
1229 if (sock->outbuf->data - sock->outbuf->head)
1230 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1232 ret = silc_server_packet_send_real(server, sock, TRUE);
1234 /* If returned -2 could not write to connection now, will do
1242 /* The packet has been sent and now it is time to set the connection
1243 back to only for input. When there is again some outgoing data
1244 available for this connection it will be set for output as well.
1245 This call clears the output setting and sets it only for input. */
1246 SILC_SET_CONNECTION_FOR_INPUT(fd);
1247 SILC_UNSET_OUTBUF_PENDING(sock);
1249 silc_buffer_clear(sock->outbuf);
1253 /* Packet receiving */
1255 /* Read some data from connection */
1256 ret = silc_packet_receive(sock);
1262 SILC_LOG_DEBUG(("Read EOF"));
1264 /* If connection is disconnecting already we will finally
1265 close the connection */
1266 if (SILC_IS_DISCONNECTING(sock)) {
1267 if (sock->user_data)
1268 silc_server_free_sock_user_data(server, sock);
1269 silc_server_close_connection(server, sock);
1273 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1274 SILC_SET_DISCONNECTING(sock);
1276 /* If the closed connection was our primary router connection the
1277 start re-connecting phase. */
1278 if (!server->standalone && server->server_type == SILC_SERVER &&
1279 sock == server->router->connection)
1280 silc_task_register(server->timeout_queue, 0,
1281 silc_server_connect_to_router,
1284 SILC_TASK_PRI_NORMAL);
1286 if (sock->user_data)
1287 silc_server_free_sock_user_data(server, sock);
1288 silc_server_close_connection(server, sock);
1292 /* If connection is disconnecting or disconnected we will ignore
1294 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1295 SILC_LOG_DEBUG(("Ignoring read data from disonnected connection"));
1299 server->stat.packets_received++;
1301 /* Get keys and stuff from ID entry */
1302 idata = (SilcIDListData)sock->user_data;
1304 idata->last_receive = time(NULL);
1305 cipher = idata->receive_key;
1309 /* Process the packet. This will call the parser that will then
1310 decrypt and parse the packet. */
1311 silc_packet_receive_process(sock, cipher, hmac, silc_server_packet_parse,
1315 /* Parses whole packet, received earlier. */
1317 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1319 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1320 SilcServer server = (SilcServer)parse_ctx->context;
1321 SilcSocketConnection sock = parse_ctx->sock;
1322 SilcPacketContext *packet = parse_ctx->packet;
1325 SILC_LOG_DEBUG(("Start"));
1327 /* Decrypt the received packet */
1328 ret = silc_packet_decrypt(parse_ctx->cipher, parse_ctx->hmac,
1329 packet->buffer, packet);
1334 /* Parse the packet. Packet type is returned. */
1335 ret = silc_packet_parse(packet);
1337 /* Parse the packet header in special way as this is "special"
1339 ret = silc_packet_parse_special(packet);
1342 if (ret == SILC_PACKET_NONE)
1345 if (server->server_type == SILC_ROUTER) {
1346 /* Route the packet if it is not destined to us. Other ID types but
1347 server are handled separately after processing them. */
1348 if (packet->dst_id_type == SILC_ID_SERVER &&
1349 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1350 SILC_ID_SERVER_COMPARE(packet->dst_id, server->id_string)) {
1352 /* Route the packet to fastest route for the destination ID */
1353 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1354 packet->dst_id_type);
1357 silc_server_packet_route(server,
1358 silc_server_route_get(server, id,
1359 packet->dst_id_type),
1365 /* Broadcast packet if it is marked as broadcast packet and it is
1366 originated from router and we are router. */
1367 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1368 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
1369 silc_server_packet_broadcast(server, server->router->connection, packet);
1373 /* Parse the incoming packet type */
1374 silc_server_packet_parse_type(server, sock, packet);
1377 silc_buffer_clear(sock->inbuf);
1378 silc_packet_context_free(packet);
1379 silc_free(parse_ctx);
1382 /* Parser callback called by silc_packet_receive_process. This merely
1383 registers timeout that will handle the actual parsing when appropriate. */
1385 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1387 SilcServer server = (SilcServer)parser_context->context;
1388 SilcSocketConnection sock = parser_context->sock;
1390 switch (sock->type) {
1391 case SILC_SOCKET_TYPE_CLIENT:
1392 case SILC_SOCKET_TYPE_UNKNOWN:
1393 /* Parse the packet with timeout */
1394 silc_task_register(server->timeout_queue, sock->sock,
1395 silc_server_packet_parse_real,
1396 (void *)parser_context, 0, 100000,
1398 SILC_TASK_PRI_NORMAL);
1400 case SILC_SOCKET_TYPE_SERVER:
1401 case SILC_SOCKET_TYPE_ROUTER:
1402 /* Packets from servers are parsed as soon as possible */
1403 silc_task_register(server->timeout_queue, sock->sock,
1404 silc_server_packet_parse_real,
1405 (void *)parser_context, 0, 1,
1407 SILC_TASK_PRI_NORMAL);
1414 /* Parses the packet type and calls what ever routines the packet type
1415 requires. This is done for all incoming packets. */
1417 void silc_server_packet_parse_type(SilcServer server,
1418 SilcSocketConnection sock,
1419 SilcPacketContext *packet)
1421 SilcPacketType type = packet->type;
1423 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1425 /* Parse the packet type */
1427 case SILC_PACKET_DISCONNECT:
1428 SILC_LOG_DEBUG(("Disconnect packet"));
1431 case SILC_PACKET_SUCCESS:
1433 * Success received for something. For now we can have only
1434 * one protocol for connection executing at once hence this
1435 * success message is for whatever protocol is executing currently.
1437 SILC_LOG_DEBUG(("Success packet"));
1438 if (sock->protocol) {
1439 sock->protocol->execute(server->timeout_queue, 0,
1440 sock->protocol, sock->sock, 0, 0);
1444 case SILC_PACKET_FAILURE:
1446 * Failure received for something. For now we can have only
1447 * one protocol for connection executing at once hence this
1448 * failure message is for whatever protocol is executing currently.
1450 SILC_LOG_DEBUG(("Failure packet"));
1451 if (sock->protocol) {
1452 /* XXX Audit the failure type */
1453 sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
1454 sock->protocol->execute(server->timeout_queue, 0,
1455 sock->protocol, sock->sock, 0, 0);
1459 case SILC_PACKET_REJECT:
1460 SILC_LOG_DEBUG(("Reject packet"));
1464 case SILC_PACKET_NOTIFY:
1466 * Received notify packet. Server can receive notify packets from
1467 * router. Server then relays the notify messages to clients if needed.
1469 SILC_LOG_DEBUG(("Notify packet"));
1470 silc_server_notify(server, sock, packet);
1476 case SILC_PACKET_CHANNEL_MESSAGE:
1478 * Received channel message. Channel messages are special packets
1479 * (although probably most common ones) thus they are handled
1482 SILC_LOG_DEBUG(("Channel Message packet"));
1483 silc_server_channel_message(server, sock, packet);
1486 case SILC_PACKET_CHANNEL_KEY:
1488 * Received key for channel. As channels are created by the router
1489 * the keys are as well. We will distribute the key to all of our
1490 * locally connected clients on the particular channel. Router
1491 * never receives this channel and thus is ignored.
1493 SILC_LOG_DEBUG(("Channel Key packet"));
1494 silc_server_channel_key(server, sock, packet);
1500 case SILC_PACKET_COMMAND:
1502 * Recived command. Processes the command request and allocates the
1503 * command context and calls the command.
1505 SILC_LOG_DEBUG(("Command packet"));
1506 silc_server_command_process(server, sock, packet);
1509 case SILC_PACKET_COMMAND_REPLY:
1511 * Received command reply packet. Received command reply to command. It
1512 * may be reply to command sent by us or reply to command sent by client
1513 * that we've routed further.
1515 SILC_LOG_DEBUG(("Command Reply packet"));
1516 silc_server_command_reply(server, sock, packet);
1520 * Private Message packets
1522 case SILC_PACKET_PRIVATE_MESSAGE:
1524 * Received private message packet. The packet is coming from either
1527 SILC_LOG_DEBUG(("Private Message packet"));
1528 silc_server_private_message(server, sock, packet);
1531 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1533 * Private message key packet.
1538 * Key Exchange protocol packets
1540 case SILC_PACKET_KEY_EXCHANGE:
1541 SILC_LOG_DEBUG(("KE packet"));
1542 if (sock->protocol && sock->protocol->protocol->type
1543 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1545 SilcServerKEInternalContext *proto_ctx =
1546 (SilcServerKEInternalContext *)sock->protocol->context;
1548 proto_ctx->packet = silc_packet_context_dup(packet);
1550 /* Let the protocol handle the packet */
1551 sock->protocol->execute(server->timeout_queue, 0,
1552 sock->protocol, sock->sock, 0, 100000);
1554 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1555 "protocol active, packet dropped."));
1557 /* XXX Trigger KE protocol?? Rekey actually, maybe. */
1561 case SILC_PACKET_KEY_EXCHANGE_1:
1562 SILC_LOG_DEBUG(("KE 1 packet"));
1563 if (sock->protocol && sock->protocol->protocol->type
1564 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1566 SilcServerKEInternalContext *proto_ctx =
1567 (SilcServerKEInternalContext *)sock->protocol->context;
1569 if (proto_ctx->packet)
1570 silc_packet_context_free(proto_ctx->packet);
1572 proto_ctx->packet = silc_packet_context_dup(packet);
1573 proto_ctx->dest_id_type = packet->src_id_type;
1574 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1575 packet->src_id_type);
1576 if (!proto_ctx->dest_id)
1579 /* Let the protocol handle the packet */
1580 sock->protocol->execute(server->timeout_queue, 0,
1581 sock->protocol, sock->sock,
1584 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1585 "protocol active, packet dropped."));
1589 case SILC_PACKET_KEY_EXCHANGE_2:
1590 SILC_LOG_DEBUG(("KE 2 packet"));
1591 if (sock->protocol && sock->protocol->protocol->type
1592 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1594 SilcServerKEInternalContext *proto_ctx =
1595 (SilcServerKEInternalContext *)sock->protocol->context;
1597 if (proto_ctx->packet)
1598 silc_packet_context_free(proto_ctx->packet);
1600 proto_ctx->packet = silc_packet_context_dup(packet);
1601 proto_ctx->dest_id_type = packet->src_id_type;
1602 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1603 packet->src_id_type);
1604 if (!proto_ctx->dest_id)
1607 /* Let the protocol handle the packet */
1608 sock->protocol->execute(server->timeout_queue, 0,
1609 sock->protocol, sock->sock,
1612 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1613 "protocol active, packet dropped."));
1617 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1619 * Connection authentication request packet. When we receive this packet
1620 * we will send to the other end information about our mandatory
1621 * authentication method for the connection. This packet maybe received
1624 SILC_LOG_DEBUG(("Connection authentication request packet"));
1628 * Connection Authentication protocol packets
1630 case SILC_PACKET_CONNECTION_AUTH:
1631 /* Start of the authentication protocol. We receive here the
1632 authentication data and will verify it. */
1633 SILC_LOG_DEBUG(("Connection auth packet"));
1634 if (sock->protocol && sock->protocol->protocol->type
1635 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1637 SilcServerConnAuthInternalContext *proto_ctx =
1638 (SilcServerConnAuthInternalContext *)sock->protocol->context;
1640 proto_ctx->packet = silc_packet_context_dup(packet);
1642 /* Let the protocol handle the packet */
1643 sock->protocol->execute(server->timeout_queue, 0,
1644 sock->protocol, sock->sock, 0, 0);
1646 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1647 "protocol active, packet dropped."));
1651 case SILC_PACKET_NEW_ID:
1653 * Received New ID packet. This includes some new ID that has been
1654 * created. It may be for client, server or channel. This is the way
1655 * to distribute information about new registered entities in the
1658 SILC_LOG_DEBUG(("New ID packet"));
1659 silc_server_new_id(server, sock, packet);
1662 case SILC_PACKET_NEW_ID_LIST:
1664 * Received list of ID's. This packet is used by servers and routers
1665 * to notify their primary router about clients and servers they have.
1667 SILC_LOG_DEBUG(("New ID List packet"));
1668 silc_server_new_id_list(server, sock, packet);
1671 case SILC_PACKET_NEW_CLIENT:
1673 * Received new client packet. This includes client information that
1674 * we will use to create initial client ID. After creating new
1675 * ID we will send it to the client.
1677 SILC_LOG_DEBUG(("New Client packet"));
1678 silc_server_new_client(server, sock, packet);
1681 case SILC_PACKET_NEW_SERVER:
1683 * Received new server packet. This includes Server ID and some other
1684 * information that we may save. This is received after server has
1687 SILC_LOG_DEBUG(("New Server packet"));
1688 silc_server_new_server(server, sock, packet);
1691 case SILC_PACKET_NEW_CHANNEL:
1693 * Received new channel packet. Information about new channel in the
1694 * network are distributed using this packet.
1696 SILC_LOG_DEBUG(("New Channel packet"));
1697 silc_server_new_channel(server, sock, packet);
1700 case SILC_PACKET_NEW_CHANNEL_USER:
1702 * Received new channel user packet. Information about new users on a
1703 * channel are distributed between routers using this packet. The
1704 * router receiving this will redistribute it and also sent JOIN notify
1705 * to local clients on the same channel. Normal server sends JOIN notify
1706 * to its local clients on the channel.
1708 SILC_LOG_DEBUG(("New Channel User packet"));
1709 silc_server_new_channel_user(server, sock, packet);
1712 case SILC_PACKET_NEW_CHANNEL_LIST:
1714 * List of new channel packets received. This is usually received when
1715 * existing server or router connects to us and distributes information
1716 * of all channels it has.
1718 SILC_LOG_DEBUG(("New Channel List packet"));
1719 silc_server_new_channel_list(server, sock, packet);
1722 case SILC_PACKET_NEW_CHANNEL_USER_LIST:
1724 * List of new channel user packets received. This is usually received
1725 * when existing server or router connects to us and distributes
1726 * information of all channel users it has.
1728 SILC_LOG_DEBUG(("New Channel User List packet"));
1729 silc_server_new_channel_user_list(server, sock, packet);
1732 case SILC_PACKET_REPLACE_ID:
1734 * Received replace ID packet. This sends the old ID that is to be
1735 * replaced with the new one included into the packet. Client must not
1738 SILC_LOG_DEBUG(("Replace ID packet"));
1739 silc_server_replace_id(server, sock, packet);
1742 case SILC_PACKET_REMOVE_ID:
1744 * Received remove ID Packet.
1746 SILC_LOG_DEBUG(("Remove ID packet"));
1747 silc_server_remove_id(server, sock, packet);
1750 case SILC_PACKET_REMOVE_CHANNEL_USER:
1752 * Received packet to remove user from a channel. Routers notify other
1753 * routers about a user leaving a channel.
1755 SILC_LOG_DEBUG(("Remove Channel User packet"));
1756 silc_server_remove_channel_user(server, sock, packet);
1759 case SILC_PACKET_SET_MODE:
1761 * Received packet to set the mode of channel or client's channel mode.
1763 SILC_LOG_DEBUG(("Set Mode packet"));
1764 silc_server_set_mode(server, sock, packet);
1767 case SILC_PACKET_HEARTBEAT:
1769 * Received heartbeat.
1771 SILC_LOG_DEBUG(("Heartbeat packet"));
1775 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
1781 /* Closes connection to socket connection */
1783 void silc_server_close_connection(SilcServer server,
1784 SilcSocketConnection sock)
1786 SILC_LOG_DEBUG(("Closing connection %d", sock->sock));
1788 /* We won't listen for this connection anymore */
1789 silc_schedule_unset_listen_fd(sock->sock);
1791 /* Unregister all tasks */
1792 silc_task_unregister_by_fd(server->io_queue, sock->sock);
1793 silc_task_unregister_by_fd(server->timeout_queue, sock->sock);
1795 /* Close the actual connection */
1796 silc_net_close_connection(sock->sock);
1797 server->sockets[sock->sock] = NULL;
1798 silc_socket_free(sock);
1801 /* Sends disconnect message to remote connection and disconnects the
1804 void silc_server_disconnect_remote(SilcServer server,
1805 SilcSocketConnection sock,
1806 const char *fmt, ...)
1809 unsigned char buf[4096];
1814 memset(buf, 0, sizeof(buf));
1816 vsprintf(buf, fmt, ap);
1819 SILC_LOG_DEBUG(("Disconnecting remote host"));
1821 /* Notify remote end that the conversation is over. The notify message
1822 is tried to be sent immediately. */
1823 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
1824 buf, strlen(buf), TRUE);
1826 /* Mark the connection to be disconnected */
1827 SILC_SET_DISCONNECTED(sock);
1828 silc_server_close_connection(server, sock);
1831 /* Free's user_data pointer from socket connection object. This also sends
1832 appropriate notify packets to the network to inform about leaving
1835 void silc_server_free_sock_user_data(SilcServer server,
1836 SilcSocketConnection sock)
1838 SILC_LOG_DEBUG(("Start"));
1840 switch(sock->type) {
1841 case SILC_SOCKET_TYPE_CLIENT:
1843 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
1845 /* Remove client from all channels */
1846 silc_server_remove_from_channels(server, sock, user_data);
1848 /* XXX must take some info to history before freeing */
1850 /* Send REMOVE_ID packet to routers. */
1851 if (!server->standalone && server->router)
1852 silc_server_send_remove_id(server, server->router->connection,
1853 server->server_type == SILC_SERVER ?
1854 FALSE : TRUE, user_data->id,
1855 SILC_ID_CLIENT_LEN, SILC_ID_CLIENT);
1857 /* Free the client entry and everything in it */
1858 silc_idlist_del_data(user_data);
1859 silc_idlist_del_client(server->local_list, user_data);
1860 server->stat.my_clients--;
1861 server->stat.clients--;
1862 if (server->server_type == SILC_ROUTER)
1863 server->stat.cell_clients--;
1866 case SILC_SOCKET_TYPE_SERVER:
1867 case SILC_SOCKET_TYPE_ROUTER:
1869 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
1871 /* Send REMOVE_ID packet to routers. */
1872 if (!server->standalone && server->router)
1873 silc_server_send_remove_id(server, server->router->connection,
1874 server->server_type == SILC_SERVER ?
1875 FALSE : TRUE, user_data->id,
1876 SILC_ID_SERVER_LEN, SILC_ID_SERVER);
1878 /* Then also free all client entries that this server owns as
1879 they will become invalid now as well. */
1880 silc_server_remove_clients_by_server(server, user_data);
1882 /* If this was our primary router connection then we're lost to
1883 the outside world. */
1884 if (server->server_type == SILC_SERVER && server->router == user_data) {
1885 server->id_entry->router = NULL;
1886 server->router = NULL;
1887 server->standalone = TRUE;
1890 /* Free the server entry */
1891 silc_idlist_del_data(user_data);
1892 silc_idlist_del_server(server->local_list, user_data);
1893 server->stat.my_servers--;
1894 server->stat.servers--;
1895 if (server->server_type == SILC_ROUTER)
1896 server->stat.cell_servers--;
1901 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
1903 silc_idlist_del_data(user_data);
1904 silc_free(user_data);
1909 sock->user_data = NULL;
1912 /* This function is used to remove all client entries by the server `entry'.
1913 This is called when the connection is lost to the server. In this case
1914 we must invalidate all the client entries owned by the server `entry'. */
1916 int silc_server_remove_clients_by_server(SilcServer server,
1917 SilcServerEntry entry)
1919 SilcIDCacheList list = NULL;
1920 SilcIDCacheEntry id_cache = NULL;
1921 SilcClientEntry client = NULL;
1923 if (silc_idcache_find_by_id(server->local_list->clients,
1924 SILC_ID_CACHE_ANY, SILC_ID_CLIENT, &list)) {
1926 if (silc_idcache_list_first(list, &id_cache)) {
1928 client = (SilcClientEntry)id_cache->context;
1930 if (client->router != entry) {
1931 if (!silc_idcache_list_next(list, &id_cache))
1937 /* Remove the client entry */
1938 silc_server_remove_from_channels(server, NULL, client);
1939 silc_idlist_del_client(server->local_list, client);
1941 if (!silc_idcache_list_next(list, &id_cache))
1945 silc_idcache_list_free(list);
1948 if (silc_idcache_find_by_id(server->global_list->clients,
1949 SILC_ID_CACHE_ANY, SILC_ID_CLIENT, &list)) {
1951 if (silc_idcache_list_first(list, &id_cache)) {
1953 client = (SilcClientEntry)id_cache->context;
1955 if (client->router != entry) {
1956 if (!silc_idcache_list_next(list, &id_cache))
1962 /* Remove the client entry */
1963 silc_server_remove_from_channels(server, NULL, client);
1964 silc_idlist_del_client(server->global_list, client);
1966 if (!silc_idcache_list_next(list, &id_cache))
1970 silc_idcache_list_free(list);
1976 /* Checks whether given channel has global users. If it does this returns
1977 TRUE and FALSE if there is only locally connected clients on the channel. */
1979 int silc_server_channel_has_global(SilcChannelEntry channel)
1981 SilcChannelClientEntry chl;
1983 silc_list_start(channel->user_list);
1984 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
1985 if (chl->client->router)
1992 /* Checks whether given channel has locally connected users. If it does this
1993 returns TRUE and FALSE if there is not one locally connected client. */
1995 int silc_server_channel_has_local(SilcChannelEntry channel)
1997 SilcChannelClientEntry chl;
1999 silc_list_start(channel->user_list);
2000 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2001 if (!chl->client->router)
2008 /* Removes client from all channels it has joined. This is used when client
2009 connection is disconnected. If the client on a channel is last, the
2010 channel is removed as well. This sends the SIGNOFF notify types. */
2012 void silc_server_remove_from_channels(SilcServer server,
2013 SilcSocketConnection sock,
2014 SilcClientEntry client)
2016 SilcChannelEntry channel;
2017 SilcChannelClientEntry chl;
2020 SILC_LOG_DEBUG(("Start"));
2022 if (!client || !client->id)
2025 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2027 /* Remove the client from all channels. The client is removed from
2028 the channels' user list. */
2029 silc_list_start(client->channels);
2030 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2031 channel = chl->channel;
2033 /* Remove channel from client's channel list */
2034 silc_list_del(client->channels, chl);
2036 /* Remove channel if there is no users anymore */
2037 if (server->server_type == SILC_ROUTER &&
2038 silc_list_count(channel->user_list) < 2) {
2039 if (!silc_idlist_del_channel(server->local_list, channel))
2040 silc_idlist_del_channel(server->global_list, channel);
2041 server->stat.my_channels--;
2045 /* Remove client from channel's client list */
2046 silc_list_del(channel->user_list, chl);
2048 server->stat.my_chanclients--;
2050 /* If there is not at least one local user on the channel then we don't
2051 need the channel entry anymore, we can remove it safely. */
2052 if (server->server_type == SILC_SERVER &&
2053 !silc_server_channel_has_local(channel)) {
2054 /* Notify about leaving client if this channel has global users. */
2055 if (channel->global_users)
2056 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2057 SILC_NOTIFY_TYPE_SIGNOFF, 1,
2058 clidp->data, clidp->len);
2060 if (!silc_idlist_del_channel(server->local_list, channel))
2061 silc_idlist_del_channel(server->global_list, channel);
2062 server->stat.my_channels--;
2066 /* Send notify to channel about client leaving SILC and thus
2067 the entire channel. */
2068 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2069 SILC_NOTIFY_TYPE_SIGNOFF, 1,
2070 clidp->data, clidp->len);
2073 silc_buffer_free(clidp);
2076 /* Removes client from one channel. This is used for example when client
2077 calls LEAVE command to remove itself from the channel. Returns TRUE
2078 if channel still exists and FALSE if the channel is removed when
2079 last client leaves the channel. If `notify' is FALSE notify messages
2082 int silc_server_remove_from_one_channel(SilcServer server,
2083 SilcSocketConnection sock,
2084 SilcChannelEntry channel,
2085 SilcClientEntry client,
2088 SilcChannelEntry ch;
2089 SilcChannelClientEntry chl;
2092 SILC_LOG_DEBUG(("Start"));
2094 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2096 /* Remove the client from the channel. The client is removed from
2097 the channel's user list. */
2098 silc_list_start(client->channels);
2099 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2100 if (chl->channel != channel)
2105 /* Remove channel from client's channel list */
2106 silc_list_del(client->channels, chl);
2108 /* Remove channel if there is no users anymore */
2109 if (server->server_type == SILC_ROUTER &&
2110 silc_list_count(channel->user_list) < 2) {
2111 if (!silc_idlist_del_channel(server->local_list, channel))
2112 silc_idlist_del_channel(server->global_list, channel);
2113 silc_buffer_free(clidp);
2114 server->stat.my_channels--;
2118 /* Remove client from channel's client list */
2119 silc_list_del(channel->user_list, chl);
2121 server->stat.my_chanclients--;
2123 /* If there is no global users on the channel anymore mark the channel
2124 as local channel. */
2125 if (server->server_type == SILC_SERVER &&
2126 !silc_server_channel_has_global(channel))
2127 channel->global_users = FALSE;
2129 /* If there is not at least one local user on the channel then we don't
2130 need the channel entry anymore, we can remove it safely. */
2131 if (server->server_type == SILC_SERVER &&
2132 !silc_server_channel_has_local(channel)) {
2133 /* Notify about leaving client if this channel has global users. */
2134 if (notify && channel->global_users)
2135 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2136 SILC_NOTIFY_TYPE_LEAVE, 1,
2137 clidp->data, clidp->len);
2139 if (!silc_idlist_del_channel(server->local_list, channel))
2140 silc_idlist_del_channel(server->global_list, channel);
2141 silc_buffer_free(clidp);
2142 server->stat.my_channels--;
2146 /* Send notify to channel about client leaving the channel */
2148 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2149 SILC_NOTIFY_TYPE_LEAVE, 1,
2150 clidp->data, clidp->len);
2154 silc_buffer_free(clidp);
2158 /* Returns TRUE if the given client is on the channel. FALSE if not.
2159 This works because we assure that the user list on the channel is
2160 always in up to date thus we can only check the channel list from
2161 `client' which is faster than checking the user list from `channel'. */
2163 int silc_server_client_on_channel(SilcClientEntry client,
2164 SilcChannelEntry channel)
2166 SilcChannelClientEntry chl;
2168 if (!client || !channel)
2171 silc_list_start(client->channels);
2172 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END)
2173 if (chl->channel == channel)
2179 /* Timeout callback. This is called if connection is idle or for some
2180 other reason is not responding within some period of time. This
2181 disconnects the remote end. */
2183 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2185 SilcServer server = (SilcServer)context;
2186 SilcSocketConnection sock = server->sockets[fd];
2191 if (sock->user_data)
2192 silc_server_free_sock_user_data(server, sock);
2194 silc_server_disconnect_remote(server, sock,
2195 "Server closed connection: "
2196 "Connection timeout");
2199 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2200 function may be used only by router. In real SILC network all channels
2201 are created by routers thus this function is never used by normal
2204 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2205 SilcServerID *router_id,
2210 SilcChannelID *channel_id;
2211 SilcChannelEntry entry;
2214 SILC_LOG_DEBUG(("Creating new channel"));
2219 /* Allocate cipher */
2220 silc_cipher_alloc(cipher, &key);
2222 channel_name = strdup(channel_name);
2224 /* Create the channel */
2225 silc_id_create_channel_id(router_id, server->rng, &channel_id);
2226 entry = silc_idlist_add_channel(server->local_list, channel_name,
2227 SILC_CHANNEL_MODE_NONE, channel_id,
2230 silc_free(channel_name);
2234 /* Now create the actual key material */
2235 silc_server_create_channel_key(server, entry, 16);
2237 /* Notify other routers about the new channel. We send the packet
2238 to our primary route. */
2239 if (broadcast && server->standalone == FALSE) {
2240 silc_server_send_new_channel(server, server->router->connection, TRUE,
2241 channel_name, entry->id, SILC_ID_CHANNEL_LEN);
2244 server->stat.my_channels++;
2249 /* Same as above but creates the channel with Channel ID `channel_id. */
2252 silc_server_create_new_channel_with_id(SilcServer server,
2255 SilcChannelID *channel_id,
2258 SilcChannelEntry entry;
2261 SILC_LOG_DEBUG(("Creating new channel"));
2266 /* Allocate cipher */
2267 silc_cipher_alloc(cipher, &key);
2269 channel_name = strdup(channel_name);
2271 /* Create the channel */
2272 entry = silc_idlist_add_channel(server->local_list, channel_name,
2273 SILC_CHANNEL_MODE_NONE, channel_id,
2276 silc_free(channel_name);
2280 /* Now create the actual key material */
2281 silc_server_create_channel_key(server, entry, 16);
2283 /* Notify other routers about the new channel. We send the packet
2284 to our primary route. */
2285 if (broadcast && server->standalone == FALSE) {
2286 silc_server_send_new_channel(server, server->router->connection, TRUE,
2287 channel_name, entry->id, SILC_ID_CHANNEL_LEN);
2290 server->stat.my_channels++;
2295 /* Generates new channel key. This is used to create the initial channel key
2296 but also to re-generate new key for channel. If `key_len' is provided
2297 it is the bytes of the key length. */
2299 void silc_server_create_channel_key(SilcServer server,
2300 SilcChannelEntry channel,
2301 unsigned int key_len)
2304 unsigned char channel_key[32];
2307 if (!channel->channel_key)
2308 silc_cipher_alloc("twofish", &channel->channel_key);
2312 else if (channel->key_len)
2313 len = channel->key_len / 8;
2315 len = sizeof(channel_key);
2317 /* Create channel key */
2318 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
2321 channel->channel_key->cipher->set_key(channel->channel_key->context,
2324 /* Remove old key if exists */
2326 memset(channel->key, 0, channel->key_len / 8);
2327 silc_free(channel->key);
2331 channel->key_len = len * 8;
2332 channel->key = silc_calloc(len, sizeof(*channel->key));
2333 memcpy(channel->key, channel_key, len);
2334 memset(channel_key, 0, sizeof(channel_key));
2337 /* Saves the channel key found in the encoded `key_payload' buffer. This
2338 function is used when we receive Channel Key Payload and also when we're
2339 processing JOIN command reply. Returns entry to the channel. */
2341 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
2342 SilcBuffer key_payload,
2343 SilcChannelEntry channel)
2345 SilcChannelKeyPayload payload = NULL;
2346 SilcChannelID *id = NULL;
2348 unsigned int tmp_len;
2351 /* Decode channel key payload */
2352 payload = silc_channel_key_payload_parse(key_payload);
2354 SILC_LOG_ERROR(("Bad channel key payload, dropped"));
2359 /* Get the channel entry */
2362 /* Get channel ID */
2363 tmp = silc_channel_key_get_id(payload, &tmp_len);
2364 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
2370 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
2372 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
2374 SILC_LOG_ERROR(("Received key for non-existent channel"));
2380 tmp = silc_channel_key_get_key(payload, &tmp_len);
2386 cipher = silc_channel_key_get_cipher(payload, NULL);;
2392 /* Remove old key if exists */
2394 memset(channel->key, 0, channel->key_len / 8);
2395 silc_free(channel->key);
2396 silc_cipher_free(channel->channel_key);
2399 /* Create new cipher */
2400 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
2406 channel->key_len = tmp_len * 8;
2407 channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
2408 memcpy(channel->key, tmp, tmp_len);
2409 channel->channel_key->cipher->set_key(channel->channel_key->context,
2416 silc_channel_key_payload_free(payload);
2421 /* Heartbeat callback. This function is set as argument for the
2422 silc_socket_set_heartbeat function. The library will call this function
2423 at the set time interval. */
2425 void silc_server_perform_heartbeat(SilcSocketConnection sock,
2428 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
2430 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname,
2433 /* Send the heartbeat */
2434 silc_server_send_heartbeat(hb->server, sock);
2437 /* Returns assembled of all servers in the given ID list. The packet's
2438 form is dictated by the New ID payload. */
2440 static void silc_server_announce_get_servers(SilcServer server,
2442 SilcBuffer *servers)
2444 SilcIDCacheList list;
2445 SilcIDCacheEntry id_cache;
2446 SilcServerEntry entry;
2449 /* Go through all clients in the list */
2450 if (silc_idcache_find_by_id(id_list->clients, SILC_ID_CACHE_ANY,
2451 SILC_ID_SERVER, &list)) {
2452 if (silc_idcache_list_first(list, &id_cache)) {
2454 entry = (SilcServerEntry)id_cache->context;
2456 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
2458 *servers = silc_buffer_realloc(*servers,
2460 (*servers)->truelen + idp->len :
2462 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
2463 silc_buffer_put(*servers, idp->data, idp->len);
2464 silc_buffer_pull(*servers, idp->len);
2465 silc_buffer_free(idp);
2467 if (!silc_idcache_list_next(list, &id_cache))
2472 silc_idcache_list_free(list);
2476 /* This function is used by router to announce existing servers to our
2477 primary router when we've connected to it. */
2479 void silc_server_announce_servers(SilcServer server)
2481 SilcBuffer servers = NULL;
2483 SILC_LOG_DEBUG(("Announcing servers"));
2485 /* Get servers in local list */
2486 silc_server_announce_get_servers(server, server->local_list, &servers);
2488 /* Get servers in global list */
2489 silc_server_announce_get_servers(server, server->global_list, &servers);
2492 silc_buffer_push(servers, servers->data - servers->head);
2493 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
2495 /* Send the packet */
2496 silc_server_packet_send(server, server->router->connection,
2497 SILC_PACKET_NEW_ID_LIST, 0,
2498 servers->data, servers->len, TRUE);
2500 silc_buffer_free(servers);
2504 /* Returns assembled packet of all clients in the given ID list. The
2505 packet's form is dictated by the New ID Payload. */
2507 static void silc_server_announce_get_clients(SilcServer server,
2509 SilcBuffer *clients)
2511 SilcIDCacheList list;
2512 SilcIDCacheEntry id_cache;
2513 SilcClientEntry client;
2516 /* Go through all clients in the list */
2517 if (silc_idcache_find_by_id(id_list->clients, SILC_ID_CACHE_ANY,
2518 SILC_ID_CLIENT, &list)) {
2519 if (silc_idcache_list_first(list, &id_cache)) {
2521 client = (SilcClientEntry)id_cache->context;
2523 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2525 *clients = silc_buffer_realloc(*clients,
2527 (*clients)->truelen + idp->len :
2529 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
2530 silc_buffer_put(*clients, idp->data, idp->len);
2531 silc_buffer_pull(*clients, idp->len);
2532 silc_buffer_free(idp);
2534 if (!silc_idcache_list_next(list, &id_cache))
2539 silc_idcache_list_free(list);
2543 /* This function is used to announce our existing clients to our router
2544 when we've connected to it. */
2546 void silc_server_announce_clients(SilcServer server)
2548 SilcBuffer clients = NULL;
2550 SILC_LOG_DEBUG(("Announcing clients"));
2552 /* Get clients in local list */
2553 silc_server_announce_get_clients(server, server->local_list,
2556 /* As router we announce our global list as well */
2557 if (server->server_type == SILC_ROUTER)
2558 silc_server_announce_get_clients(server, server->global_list,
2562 silc_buffer_push(clients, clients->data - clients->head);
2563 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
2565 /* Send the packet */
2566 silc_server_packet_send(server, server->router->connection,
2567 SILC_PACKET_NEW_ID_LIST, 0,
2568 clients->data, clients->len, TRUE);
2570 silc_buffer_free(clients);
2574 /* Returns assembled packets for all channels and users on those channels
2575 from the given ID List. The packets are in the form dictated by the
2576 New Channel and New Channel User payloads. */
2578 static void silc_server_announce_get_channels(SilcServer server,
2580 SilcBuffer *channels,
2581 SilcBuffer *channel_users)
2583 SilcIDCacheList list;
2584 SilcIDCacheEntry id_cache;
2585 SilcChannelEntry channel;
2586 SilcChannelClientEntry chl;
2588 unsigned short name_len;
2591 /* Go through all channels in the list */
2592 if (silc_idcache_find_by_id(id_list->channels, SILC_ID_CACHE_ANY,
2593 SILC_ID_CHANNEL, &list)) {
2594 if (silc_idcache_list_first(list, &id_cache)) {
2596 channel = (SilcChannelEntry)id_cache->context;
2598 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
2599 name_len = strlen(channel->channel_name);
2601 len = 4 + name_len + SILC_ID_CHANNEL_LEN;
2603 silc_buffer_realloc(*channels,
2604 (*channels ? (*channels)->truelen + len : len));
2605 silc_buffer_pull_tail(*channels,
2606 ((*channels)->end - (*channels)->data));
2607 silc_buffer_format(*channels,
2608 SILC_STR_UI_SHORT(name_len),
2609 SILC_STR_UI_XNSTRING(channel->channel_name,
2611 SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
2612 SILC_STR_UI_XNSTRING(cid, SILC_ID_CHANNEL_LEN),
2614 silc_buffer_pull(*channels, len);
2616 /* Now find all users on the channel */
2617 silc_list_start(channel->user_list);
2618 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2619 unsigned char *clid;
2621 clid = silc_id_id2str(chl->client->id, SILC_ID_CLIENT);
2623 len = 4 + SILC_ID_CHANNEL_LEN + SILC_ID_CLIENT_LEN;
2625 silc_buffer_realloc(*channel_users,
2627 (*channel_users)->truelen + len : len));
2628 silc_buffer_pull_tail(*channel_users,
2629 ((*channel_users)->end -
2630 (*channel_users)->data));
2631 silc_buffer_format(*channel_users,
2632 SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
2633 SILC_STR_UI_XNSTRING(cid, SILC_ID_CHANNEL_LEN),
2634 SILC_STR_UI_SHORT(SILC_ID_CLIENT_LEN),
2635 SILC_STR_UI_XNSTRING(clid, SILC_ID_CLIENT_LEN),
2637 silc_buffer_pull(*channel_users, len);
2643 if (!silc_idcache_list_next(list, &id_cache))
2648 silc_idcache_list_free(list);
2652 /* This function is used to announce our existing channels to our router
2653 when we've connected to it. This also announces the users on the
2654 channels to the router. */
2656 void silc_server_announce_channels(SilcServer server)
2658 SilcBuffer channels = NULL, channel_users = NULL;
2660 SILC_LOG_DEBUG(("Announcing channels and channel users"));
2662 /* Get channels and channel users in local list */
2663 silc_server_announce_get_channels(server, server->local_list,
2664 &channels, &channel_users);
2666 /* Get channels and channel users in global list */
2667 silc_server_announce_get_channels(server, server->global_list,
2668 &channels, &channel_users);
2671 silc_buffer_push(channels, channels->data - channels->head);
2672 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
2674 /* Send the packet */
2675 silc_server_packet_send(server, server->router->connection,
2676 SILC_PACKET_NEW_CHANNEL_LIST, 0,
2677 channels->data, channels->len,
2680 silc_buffer_free(channels);
2683 if (channel_users) {
2684 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
2685 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
2686 channel_users->len);
2688 /* Send the packet */
2689 silc_server_packet_send(server, server->router->connection,
2690 SILC_PACKET_NEW_CHANNEL_USER_LIST, 0,
2691 channel_users->data, channel_users->len,
2694 silc_buffer_free(channel_users);