5 Author: Pekka Riikonen <priikone@poseidon.pspt.fi>
7 Copyright (C) 1997 - 2000 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 extern char *server_version;
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 = FALSE;
58 server->local_list = silc_calloc(1, sizeof(*server->local_list));
59 server->global_list = silc_calloc(1, sizeof(*server->global_list));
61 server->sim = silc_dlist_init();
69 /* Free's the SILC server object. This is called at the very end before
72 void silc_server_free(SilcServer server)
77 if (server->local_list)
78 silc_free(server->local_list);
79 if (server->global_list)
80 silc_free(server->global_list);
82 silc_rng_free(server->rng);
84 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
85 silc_dlist_del(server->sim, sim);
88 silc_dlist_uninit(server->sim);
91 silc_free(server->params);
93 silc_math_primegen_uninit(); /* XXX */
98 /* Initializes the entire SILC server. This is called always before running
99 the server. This is called only once at the initialization of the program.
100 This binds the server to its listenning port. After this function returns
101 one should call silc_server_run to start the server. This returns TRUE
102 when everything is ok to run the server. Configuration file must be
103 read and parsed before calling this. */
105 int silc_server_init(SilcServer server)
107 int *sock = NULL, sock_count = 0, i;
109 SilcServerEntry id_entry;
111 SILC_LOG_DEBUG(("Initializing server"));
113 assert(server->config);
115 /* XXX After server is made as Silc Server Library this can be given
116 as argument, for now this is hard coded */
117 server->params = silc_calloc(1, sizeof(*server->params));
118 server->params->retry_count = SILC_SERVER_RETRY_COUNT;
119 server->params->retry_interval_min = SILC_SERVER_RETRY_INTERVAL_MIN;
120 server->params->retry_interval_max = SILC_SERVER_RETRY_INTERVAL_MAX;
121 server->params->retry_keep_trying = FALSE;
122 server->params->protocol_timeout = 60;
124 /* Set log files where log message should be saved. */
125 server->config->server = server;
126 silc_config_server_setlogfiles(server->config);
128 /* Register all configured ciphers, PKCS and hash functions. */
129 silc_config_server_register_ciphers(server->config);
130 silc_config_server_register_pkcs(server->config);
131 silc_config_server_register_hashfuncs(server->config);
133 /* Initialize random number generator for the server. */
134 server->rng = silc_rng_alloc();
135 silc_rng_init(server->rng);
136 silc_math_primegen_init(); /* XXX */
138 /* Initialize hash functions for server to use */
139 silc_hash_alloc("md5", &server->md5hash);
140 silc_hash_alloc("sha1", &server->sha1hash);
142 /* Initialize none cipher */
143 silc_cipher_alloc("none", &server->none_cipher);
145 /* XXXXX Generate RSA key pair */
147 unsigned char *public_key;
148 unsigned char *private_key;
149 unsigned int pk_len, prv_len;
152 if (stat("pubkey.pub", &st) < 0 && stat("privkey.prv", &st) < 0) {
154 if (silc_pkcs_alloc("rsa", &server->pkcs) == FALSE) {
155 SILC_LOG_ERROR(("Could not create RSA key pair"));
159 if (server->pkcs->pkcs->init(server->pkcs->context,
160 1024, server->rng) == FALSE) {
161 SILC_LOG_ERROR(("Could not generate RSA key pair"));
165 public_key = server->pkcs->pkcs->get_public_key(server->pkcs->context,
167 private_key = server->pkcs->pkcs->get_private_key(server->pkcs->context,
170 SILC_LOG_HEXDUMP(("public key"), public_key, pk_len);
171 SILC_LOG_HEXDUMP(("private key"), private_key, prv_len);
174 silc_pkcs_public_key_alloc("rsa", "UN=root, HN=dummy",
176 server->private_key =
177 silc_pkcs_private_key_alloc("rsa", private_key, prv_len);
180 silc_pkcs_save_public_key("pubkey.pub", server->public_key,
182 silc_pkcs_save_private_key("privkey.prv", server->private_key, NULL,
185 memset(public_key, 0, pk_len);
186 memset(private_key, 0, prv_len);
187 silc_free(public_key);
188 silc_free(private_key);
190 silc_pkcs_load_public_key("pubkey.pub", &server->public_key,
192 silc_pkcs_load_private_key("privkey.prv", &server->private_key,
197 /* Create a listening server. Note that our server can listen on
198 multiple ports. All listeners are created here and now. */
199 /* XXX Still check this whether to use server_info or listen_port. */
201 while(server->config->listen_port) {
204 tmp = silc_net_create_server(server->config->listen_port->port,
205 server->config->listen_port->host);
209 sock = silc_realloc(sock, (sizeof(int *) * (sock_count + 1)));
210 sock[sock_count] = tmp;
211 server->config->listen_port = server->config->listen_port->next;
215 /* Initialize ID caches */
216 server->local_list->clients = silc_idcache_alloc(0);
217 server->local_list->servers = silc_idcache_alloc(0);
218 server->local_list->channels = silc_idcache_alloc(0);
220 /* XXX for now these are allocated for normal server as well as these
221 hold some global information that the server has fetched from its
222 router. For router these are used as they are supposed to be used
223 on router. The XXX can be remoevd later if this is the way we are
224 going to do this in the normal server as well. */
225 server->global_list->clients = silc_idcache_alloc(0);
226 server->global_list->servers = silc_idcache_alloc(0);
227 server->global_list->channels = silc_idcache_alloc(0);
229 /* Allocate the entire socket list that is used in server. Eventually
230 all connections will have entry in this table (it is a table of
231 pointers to the actual object that is allocated individually
233 server->sockets = silc_calloc(SILC_SERVER_MAX_CONNECTIONS,
234 sizeof(*server->sockets));
236 for (i = 0; i < sock_count; i++) {
237 SilcSocketConnection newsocket = NULL;
239 /* Set socket to non-blocking mode */
240 silc_net_set_socket_nonblock(sock[i]);
241 server->sock = sock[i];
243 /* Create a Server ID for the server. */
244 silc_id_create_server_id(sock[i], server->rng, &id);
250 server->id_type = SILC_ID_SERVER;
251 server->server_name = server->config->server_info->server_name;
253 /* Add ourselves to the server list. We don't have a router yet
254 beacuse we haven't established a route yet. It will be done later.
255 For now, NULL is sent as router. This allocates new entry to
258 silc_idlist_add_server(server->local_list,
259 server->config->server_info->server_name,
260 server->server_type, server->id, NULL,
261 server->send_key, server->receive_key,
262 NULL, NULL, NULL, NULL);
264 SILC_LOG_ERROR(("Could not add ourselves to cache"));
268 /* Add ourselves also to the socket table. The entry allocated above
269 is sent as argument for fast referencing in the future. */
270 silc_socket_alloc(sock[i], SILC_SOCKET_TYPE_SERVER, id_entry,
275 server->sockets[sock[i]] = newsocket;
277 /* Put the allocated socket pointer also to the entry allocated above
278 for fast back-referencing to the socket list. */
279 id_entry->connection = (void *)server->sockets[sock[i]];
280 server->id_entry = id_entry;
283 /* Register the task queues. In SILC we have by default three task queues.
284 One task queue for non-timeout tasks which perform different kind of
285 I/O on file descriptors, timeout task queue for timeout tasks, and,
286 generic non-timeout task queue whose tasks apply to all connections. */
287 silc_task_queue_alloc(&server->io_queue, TRUE);
288 if (!server->io_queue) {
291 silc_task_queue_alloc(&server->timeout_queue, TRUE);
292 if (!server->timeout_queue) {
295 silc_task_queue_alloc(&server->generic_queue, TRUE);
296 if (!server->generic_queue) {
300 /* Register protocols */
301 silc_server_protocols_register();
303 /* Initialize the scheduler */
304 silc_schedule_init(&server->io_queue, &server->timeout_queue,
305 &server->generic_queue,
306 SILC_SERVER_MAX_CONNECTIONS);
308 /* Add the first task to the queue. This is task that is executed by
309 timeout. It expires as soon as the caller calls silc_server_run. This
310 task performs authentication protocol and key exchange with our
312 if (silc_task_register(server->timeout_queue, sock[0],
313 silc_server_connect_to_router,
314 (void *)server, 0, 1,
316 SILC_TASK_PRI_NORMAL) == NULL) {
320 /* If server connections has been configured then we must be router as
321 normal server cannot have server connections, only router connections. */
322 if (server->config->servers)
323 server->server_type = SILC_ROUTER;
325 SILC_LOG_DEBUG(("Server initialized"));
327 /* We are done here, return succesfully */
331 silc_task_queue_free(server->timeout_queue);
333 silc_task_queue_free(server->io_queue);
335 for (i = 0; i < sock_count; i++)
336 silc_net_close_server(sock[i]);
341 /* Stops the SILC server. This function is used to shutdown the server.
342 This is usually called after the scheduler has returned. After stopping
343 the server one should call silc_server_free. */
345 void silc_server_stop(SilcServer server)
347 SILC_LOG_DEBUG(("Stopping server"));
349 /* Stop the scheduler, although it might be already stopped. This
350 doesn't hurt anyone. This removes all the tasks and task queues,
352 silc_schedule_stop();
353 silc_schedule_uninit();
355 silc_server_protocols_unregister();
357 SILC_LOG_DEBUG(("Server stopped"));
360 /* The heart of the server. This runs the scheduler thus runs the server. */
362 void silc_server_run(SilcServer server)
364 SILC_LOG_DEBUG(("Running server"));
366 /* Start the scheduler, the heart of the SILC server. When this returns
367 the program will be terminated. */
371 /* Timeout callback that will be called to retry connecting to remote
372 router. This is used by both normal and router server. This will wait
373 before retrying the connecting. The timeout is generated by exponential
374 backoff algorithm. */
376 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
378 SilcServerConnection sconn = (SilcServerConnection)context;
379 SilcServer server = sconn->server;
381 SILC_LOG_INFO(("Retrying connecting to a router"));
383 /* Calculate next timeout */
384 if (sconn->retry_count >= 1) {
385 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
386 if (sconn->retry_timeout > SILC_SERVER_RETRY_INTERVAL_MAX)
387 sconn->retry_timeout = SILC_SERVER_RETRY_INTERVAL_MAX;
389 sconn->retry_timeout = server->params->retry_interval_min;
391 sconn->retry_count++;
392 sconn->retry_timeout = sconn->retry_timeout +
393 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
395 /* If we've reached max retry count, give up. */
396 if (sconn->retry_count > server->params->retry_count &&
397 server->params->retry_keep_trying == FALSE) {
398 SILC_LOG_ERROR(("Could not connect to router, giving up"));
402 /* Wait one before retrying */
403 silc_task_register(server->timeout_queue, fd, silc_server_connect_router,
404 context, sconn->retry_timeout,
405 server->params->retry_interval_min_usec,
406 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
409 /* Generic routine to use connect to a router. */
411 SILC_TASK_CALLBACK(silc_server_connect_router)
413 SilcServerConnection sconn = (SilcServerConnection)context;
414 SilcServer server = sconn->server;
415 SilcSocketConnection newsocket;
416 SilcProtocol protocol;
417 SilcServerKEInternalContext *proto_ctx;
420 /* Connect to remote host */
421 sock = silc_net_create_connection(sconn->remote_port,
424 SILC_LOG_ERROR(("Could not connect to router"));
425 silc_task_register(server->timeout_queue, fd,
426 silc_server_connect_to_router_retry,
427 context, 0, 1, SILC_TASK_TIMEOUT,
428 SILC_TASK_PRI_NORMAL);
432 /* Set socket options */
433 silc_net_set_socket_nonblock(sock);
434 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
436 /* Create socket connection for the connection. Even though we
437 know that we are connecting to a router we will mark the socket
438 to be unknown connection until we have executed authentication
440 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
441 server->sockets[sock] = newsocket;
442 newsocket->hostname = sconn->remote_host;
443 newsocket->port = sconn->remote_port;
444 sconn->sock = newsocket;
446 /* Allocate internal protocol context. This is sent as context
448 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
449 proto_ctx->server = (void *)server;
450 proto_ctx->context = (void *)sconn;
451 proto_ctx->sock = newsocket;
452 proto_ctx->rng = server->rng;
453 proto_ctx->responder = FALSE;
455 /* Perform key exchange protocol. silc_server_connect_to_router_second
456 will be called after the protocol is finished. */
457 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
458 &protocol, proto_ctx,
459 silc_server_connect_to_router_second);
460 newsocket->protocol = protocol;
462 /* Register a timeout task that will be executed if the protocol
463 is not executed within set limit. */
464 proto_ctx->timeout_task =
465 silc_task_register(server->timeout_queue, sock,
466 silc_server_timeout_remote,
467 server, server->params->protocol_timeout,
468 server->params->protocol_timeout_usec,
472 /* Register the connection for network input and output. This sets
473 that scheduler will listen for incoming packets for this connection
474 and sets that outgoing packets may be sent to this connection as
475 well. However, this doesn't set the scheduler for outgoing traffic,
476 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
477 later when outgoing data is available. */
478 context = (void *)server;
479 SILC_REGISTER_CONNECTION_FOR_IO(sock);
481 /* Run the protocol */
482 protocol->execute(server->timeout_queue, 0, protocol, sock, 0, 0);
485 /* This function connects to our primary router or if we are a router this
486 establishes all our primary routes. This is called at the start of the
487 server to do authentication and key exchange with our router - called
490 SILC_TASK_CALLBACK(silc_server_connect_to_router)
492 SilcServer server = (SilcServer)context;
493 SilcServerConnection sconn;
495 SILC_LOG_DEBUG(("Connecting to router(s)"));
497 /* If we are normal SILC server we need to connect to our cell's
499 if (server->server_type == SILC_SERVER) {
500 SILC_LOG_DEBUG(("We are normal server"));
502 /* Create connection to the router, if configured. */
503 if (server->config->routers) {
505 /* Allocate connection object for hold connection specific stuff. */
506 sconn = silc_calloc(1, sizeof(*sconn));
507 sconn->server = server;
508 sconn->remote_host = server->config->routers->host;
509 sconn->remote_port = server->config->routers->port;
511 silc_task_register(server->timeout_queue, fd,
512 silc_server_connect_router,
513 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
514 SILC_TASK_PRI_NORMAL);
519 /* If we are a SILC router we need to establish all of our primary
521 if (server->server_type == SILC_ROUTER) {
522 SilcConfigServerSectionServerConnection *ptr;
524 SILC_LOG_DEBUG(("We are router"));
526 /* Create the connections to all our routes */
527 ptr = server->config->routers;
530 /* Allocate connection object for hold connection specific stuff. */
531 sconn = silc_calloc(1, sizeof(*sconn));
532 sconn->server = server;
533 sconn->remote_host = ptr->host;
534 sconn->remote_port = ptr->port;
536 silc_task_register(server->timeout_queue, fd,
537 silc_server_connect_router,
538 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
539 SILC_TASK_PRI_NORMAL);
548 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
550 /* There wasn't a configured router, we will continue but we don't
551 have a connection to outside world. We will be standalone server. */
552 server->standalone = TRUE;
554 /* Add a task to the queue. This task receives new connections to the
555 server. This task remains on the queue until the end of the program. */
556 silc_task_register(server->io_queue, fd,
557 silc_server_accept_new_connection,
558 (void *)server, 0, 0,
560 SILC_TASK_PRI_NORMAL);
563 /* Second part of connecting to router(s). Key exchange protocol has been
564 executed and now we will execute authentication protocol. */
566 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
568 SilcProtocol protocol = (SilcProtocol)context;
569 SilcServerKEInternalContext *ctx =
570 (SilcServerKEInternalContext *)protocol->context;
571 SilcServer server = (SilcServer)ctx->server;
572 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
573 SilcSocketConnection sock = NULL;
574 SilcServerConnAuthInternalContext *proto_ctx;
576 SILC_LOG_DEBUG(("Start"));
578 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
579 /* Error occured during protocol */
580 silc_protocol_free(protocol);
582 silc_buffer_free(ctx->packet);
584 silc_ske_free(ctx->ske);
586 silc_free(ctx->dest_id);
588 sock->protocol = NULL;
589 silc_server_disconnect_remote(server, sock, "Server closed connection: "
590 "Key exchange failed");
594 /* Allocate internal context for the authentication protocol. This
595 is sent as context for the protocol. */
596 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
597 proto_ctx->server = (void *)server;
598 proto_ctx->context = (void *)sconn;
599 proto_ctx->sock = sock = server->sockets[fd];
600 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
601 proto_ctx->dest_id_type = ctx->dest_id_type;
602 proto_ctx->dest_id = ctx->dest_id;
604 /* Resolve the authentication method used in this connection */
605 proto_ctx->auth_meth = SILC_PROTOCOL_CONN_AUTH_PASSWORD;
606 if (server->config->routers) {
607 SilcConfigServerSectionServerConnection *conn = NULL;
609 /* Check if we find a match from user configured connections */
610 conn = silc_config_server_find_router_conn(server->config,
614 /* Match found. Use the configured authentication method */
615 proto_ctx->auth_meth = conn->auth_meth;
616 if (conn->auth_data) {
617 proto_ctx->auth_data = strdup(conn->auth_data);
618 proto_ctx->auth_data_len = strlen(conn->auth_data);
621 /* No match found. */
628 /* Free old protocol as it is finished now */
629 silc_protocol_free(protocol);
631 silc_buffer_free(ctx->packet);
633 sock->protocol = NULL;
635 /* Allocate the authentication protocol. This is allocated here
636 but we won't start it yet. We will be receiving party of this
637 protocol thus we will wait that connecting party will make
639 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
640 &sock->protocol, proto_ctx,
641 silc_server_connect_to_router_final);
643 /* Register timeout task. If the protocol is not executed inside
644 this timelimit the connection will be terminated. Currently
645 this is 15 seconds and is hard coded limit (XXX). */
646 proto_ctx->timeout_task =
647 silc_task_register(server->timeout_queue, sock->sock,
648 silc_server_timeout_remote,
649 (void *)server, 15, 0,
653 /* Run the protocol */
654 sock->protocol->execute(server->timeout_queue, 0,
655 sock->protocol, sock->sock, 0, 0);
658 /* Finalizes the connection to router. Registers a server task to the
659 queue so that we can accept new connections. */
661 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
663 SilcProtocol protocol = (SilcProtocol)context;
664 SilcServerConnAuthInternalContext *ctx =
665 (SilcServerConnAuthInternalContext *)protocol->context;
666 SilcServer server = (SilcServer)ctx->server;
667 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
668 SilcSocketConnection sock = ctx->sock;
669 SilcServerEntry id_entry;
670 SilcUnknownEntry conn_data;
672 unsigned char *id_string;
674 SILC_LOG_DEBUG(("Start"));
676 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
677 /* Error occured during protocol */
678 silc_protocol_free(protocol);
680 silc_buffer_free(ctx->packet);
682 silc_ske_free(ctx->ske);
684 silc_free(ctx->dest_id);
686 sock->protocol = NULL;
687 silc_server_disconnect_remote(server, sock, "Server closed connection: "
688 "Authentication failed");
692 /* Add a task to the queue. This task receives new connections to the
693 server. This task remains on the queue until the end of the program. */
694 if (!server->listenning) {
695 silc_task_register(server->io_queue, server->sock,
696 silc_server_accept_new_connection,
697 (void *)server, 0, 0,
699 SILC_TASK_PRI_NORMAL);
700 server->listenning = TRUE;
703 /* Send NEW_SERVER packet to the router. We will become registered
704 to the SILC network after sending this packet. */
705 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
706 packet = silc_buffer_alloc(2 + 2 + SILC_ID_SERVER_LEN +
707 strlen(server->server_name));
708 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
709 silc_buffer_format(packet,
710 SILC_STR_UI_SHORT(SILC_ID_SERVER_LEN),
711 SILC_STR_UI_XNSTRING(id_string, SILC_ID_SERVER_LEN),
712 SILC_STR_UI_SHORT(strlen(server->server_name)),
713 SILC_STR_UI_XNSTRING(server->server_name,
714 strlen(server->server_name)),
717 /* Send the packet */
718 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
719 packet->data, packet->len, TRUE);
720 silc_buffer_free(packet);
721 silc_free(id_string);
723 SILC_LOG_DEBUG(("Connected to router %s", sock->hostname));
725 /* Add the connected router to local server list */
726 server->standalone = FALSE;
727 conn_data = (SilcUnknownEntry)sock->user_data;
729 silc_idlist_add_server(server->local_list,
730 sock->hostname ? sock->hostname : sock->ip,
731 SILC_ROUTER, ctx->dest_id, NULL,
732 conn_data->send_key, conn_data->receive_key,
733 conn_data->pkcs, conn_data->hmac, NULL, sock);
735 id_entry->hmac_key = conn_data->hmac_key;
736 id_entry->hmac_key_len = conn_data->hmac_key_len;
737 sock->user_data = (void *)id_entry;
738 sock->type = SILC_SOCKET_TYPE_ROUTER;
739 server->id_entry->router = id_entry;
742 /* Free the temporary connection data context from key exchange */
743 silc_free(conn_data);
747 /* Free the protocol object */
748 silc_protocol_free(protocol);
750 silc_buffer_free(ctx->packet);
752 silc_ske_free(ctx->ske);
754 sock->protocol = NULL;
757 /* Accepts new connections to the server. Accepting new connections are
758 done in three parts to make it async. */
760 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
762 SilcServer server = (SilcServer)context;
763 SilcSocketConnection newsocket;
764 SilcServerKEInternalContext *proto_ctx;
767 SILC_LOG_DEBUG(("Accepting new connection"));
769 sock = silc_net_accept_connection(server->sock);
771 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
775 /* Check max connections */
776 if (sock > SILC_SERVER_MAX_CONNECTIONS) {
777 if (server->config->redirect) {
778 /* XXX Redirecting connection to somewhere else now?? */
779 /*silc_server_send_notify("Server is full, trying to redirect..."); */
781 SILC_LOG_ERROR(("Refusing connection, server is full"));
786 /* Set socket options */
787 silc_net_set_socket_nonblock(sock);
788 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
790 /* We don't create a ID yet, since we don't know what type of connection
791 this is yet. But, we do add the connection to the socket table. */
792 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
793 server->sockets[sock] = newsocket;
795 /* XXX This MUST be done async as this will block the entire server
796 process. Either we have to do our own resolver stuff or in the future
797 we can use threads. */
798 /* Perform mandatory name and address lookups for the remote host. */
799 silc_net_check_host_by_sock(sock, &newsocket->hostname, &newsocket->ip);
800 if (!newsocket->ip || !newsocket->hostname) {
801 SILC_LOG_DEBUG(("IP lookup/DNS lookup failed"));
802 SILC_LOG_ERROR(("IP lookup/DNS lookup failed"));
806 SILC_LOG_INFO(("Incoming connection from %s (%s)", newsocket->hostname,
809 /* Allocate internal context for key exchange protocol. This is
810 sent as context for the protocol. */
811 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
812 proto_ctx->server = context;
813 proto_ctx->sock = newsocket;
814 proto_ctx->rng = server->rng;
815 proto_ctx->responder = TRUE;
817 /* Prepare the connection for key exchange protocol. We allocate the
818 protocol but will not start it yet. The connector will be the
819 initiator of the protocol thus we will wait for initiation from
820 there before we start the protocol. */
821 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
822 &newsocket->protocol, proto_ctx,
823 silc_server_accept_new_connection_second);
825 /* Register a timeout task that will be executed if the connector
826 will not start the key exchange protocol within 60 seconds. For
827 now, this is a hard coded limit. After 60 secs the connection will
828 be closed if the key exchange protocol has not been started. */
829 proto_ctx->timeout_task =
830 silc_task_register(server->timeout_queue, newsocket->sock,
831 silc_server_timeout_remote,
836 /* Register the connection for network input and output. This sets
837 that scheduler will listen for incoming packets for this connection
838 and sets that outgoing packets may be sent to this connection as well.
839 However, this doesn't set the scheduler for outgoing traffic, it
840 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
841 later when outgoing data is available. */
842 SILC_REGISTER_CONNECTION_FOR_IO(sock);
845 /* Second part of accepting new connection. Key exchange protocol has been
846 performed and now it is time to do little connection authentication
847 protocol to figure out whether this connection is client or server
848 and whether it has right to access this server (especially server
849 connections needs to be authenticated). */
851 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
853 SilcProtocol protocol = (SilcProtocol)context;
854 SilcServerKEInternalContext *ctx =
855 (SilcServerKEInternalContext *)protocol->context;
856 SilcServer server = (SilcServer)ctx->server;
857 SilcSocketConnection sock = NULL;
858 SilcServerConnAuthInternalContext *proto_ctx;
860 SILC_LOG_DEBUG(("Start"));
862 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
863 /* Error occured during protocol */
864 silc_protocol_free(protocol);
866 silc_buffer_free(ctx->packet);
868 silc_ske_free(ctx->ske);
870 silc_free(ctx->dest_id);
873 sock->protocol = NULL;
874 silc_server_disconnect_remote(server, sock, "Server closed connection: "
875 "Key exchange failed");
879 /* Allocate internal context for the authentication protocol. This
880 is sent as context for the protocol. */
881 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
882 proto_ctx->server = (void *)server;
883 proto_ctx->sock = sock = server->sockets[fd];
884 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
885 proto_ctx->responder = TRUE;
886 proto_ctx->dest_id_type = ctx->dest_id_type;
887 proto_ctx->dest_id = ctx->dest_id;
889 /* Free old protocol as it is finished now */
890 silc_protocol_free(protocol);
892 silc_buffer_free(ctx->packet);
894 sock->protocol = NULL;
896 /* Allocate the authentication protocol. This is allocated here
897 but we won't start it yet. We will be receiving party of this
898 protocol thus we will wait that connecting party will make
900 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
901 &sock->protocol, proto_ctx,
902 silc_server_accept_new_connection_final);
904 /* Register timeout task. If the protocol is not executed inside
905 this timelimit the connection will be terminated. Currently
906 this is 60 seconds and is hard coded limit (XXX). */
907 proto_ctx->timeout_task =
908 silc_task_register(server->timeout_queue, sock->sock,
909 silc_server_timeout_remote,
910 (void *)server, 60, 0,
915 /* Final part of accepting new connection. The connection has now
916 been authenticated and keys has been exchanged. We also know whether
917 this is client or server connection. */
919 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
921 SilcProtocol protocol = (SilcProtocol)context;
922 SilcServerConnAuthInternalContext *ctx =
923 (SilcServerConnAuthInternalContext *)protocol->context;
924 SilcServer server = (SilcServer)ctx->server;
925 SilcSocketConnection sock = ctx->sock;
927 SILC_LOG_DEBUG(("Start"));
929 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
930 /* Error occured during protocol */
931 silc_protocol_free(protocol);
933 silc_buffer_free(ctx->packet);
935 silc_ske_free(ctx->ske);
937 silc_free(ctx->dest_id);
940 sock->protocol = NULL;
941 silc_server_disconnect_remote(server, sock, "Server closed connection: "
942 "Authentication failed");
946 sock->type = ctx->conn_type;
948 case SILC_SOCKET_TYPE_CLIENT:
950 SilcClientEntry client;
951 SilcUnknownEntry conn_data = (SilcUnknownEntry)sock->user_data;
953 SILC_LOG_DEBUG(("Remote host is client"));
954 SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
957 /* Add the client to the client ID cache. The nickname and Client ID
958 and other information is created after we have received NEW_CLIENT
959 packet from client. */
961 silc_idlist_add_client(server->local_list, NULL, NULL, NULL, NULL,
962 NULL, conn_data->send_key,
963 conn_data->receive_key, conn_data->pkcs,
964 conn_data->hmac, NULL, sock);
966 SILC_LOG_ERROR(("Could not add new client to cache"));
967 silc_free(conn_data);
971 /* Free the temporary connection data context from key exchange */
972 silc_free(conn_data);
974 /* Add to sockets internal pointer for fast referencing */
975 sock->user_data = (void *)client;
978 case SILC_SOCKET_TYPE_SERVER:
979 case SILC_SOCKET_TYPE_ROUTER:
981 SilcServerEntry new_server;
982 SilcUnknownEntry conn_data = (SilcUnknownEntry)sock->user_data;
984 SILC_LOG_DEBUG(("Remote host is %s",
985 sock->type == SILC_SOCKET_TYPE_SERVER ?
986 "server" : "router"));
987 SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
988 sock->ip, sock->type == SILC_SOCKET_TYPE_SERVER ?
989 "server" : "router"));
991 /* Add the server into server cache. The server name and Server ID
992 is updated after we have received NEW_SERVER packet from the
995 silc_idlist_add_server(server->local_list, NULL,
996 sock->type == SILC_SOCKET_TYPE_SERVER ?
997 SILC_SERVER : SILC_ROUTER, NULL, NULL,
998 conn_data->send_key, conn_data->receive_key,
999 conn_data->pkcs, conn_data->hmac, NULL, sock);
1001 SILC_LOG_ERROR(("Could not add new server to cache"));
1002 silc_free(conn_data);
1006 new_server->registered = TRUE;
1007 new_server->hmac_key = conn_data->hmac_key;
1008 new_server->hmac_key_len = conn_data->hmac_key_len;
1010 /* Free the temporary connection data context from protocols */
1011 silc_free(conn_data);
1013 /* Add to sockets internal pointer for fast referencing */
1014 sock->user_data = (void *)new_server;
1016 /* There is connection to other server now, if it is router then
1017 we will have connection to outside world. If we are router but
1018 normal server connected to us then we will remain standalone,
1019 if we are standlone. */
1020 if (server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER) {
1021 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1022 server->standalone = FALSE;
1030 /* Connection has been fully established now. Everything is ok. */
1031 SILC_LOG_DEBUG(("New connection authenticated"));
1033 silc_protocol_free(protocol);
1035 silc_buffer_free(ctx->packet);
1037 silc_ske_free(ctx->ske);
1039 silc_free(ctx->dest_id);
1041 sock->protocol = NULL;
1044 /* Internal routine that sends packet or marks packet to be sent. This
1045 is used directly only in special cases. Normal cases should use
1046 silc_server_packet_send. Returns < 0 error. */
1048 static int silc_server_packet_send_real(SilcServer server,
1049 SilcSocketConnection sock,
1054 /* Send the packet */
1055 ret = silc_packet_send(sock, force_send);
1059 /* Mark that there is some outgoing data available for this connection.
1060 This call sets the connection both for input and output (the input
1061 is set always and this call keeps the input setting, actually).
1062 Actual data sending is performed by silc_server_packet_process. */
1063 SILC_SET_CONNECTION_FOR_OUTPUT(sock->sock);
1065 /* Mark to socket that data is pending in outgoing buffer. This flag
1066 is needed if new data is added to the buffer before the earlier
1067 put data is sent to the network. */
1068 SILC_SET_OUTBUF_PENDING(sock);
1074 SilcPacketContext *packetdata;
1076 SilcSocketConnection sock;
1079 } SilcServerInternalPacket;
1081 /* This function is used to read packets from network and send packets to
1082 network. This is usually a generic task. */
1084 SILC_TASK_CALLBACK(silc_server_packet_process)
1086 SilcServer server = (SilcServer)context;
1087 SilcSocketConnection sock = server->sockets[fd];
1088 SilcCipher cipher = NULL;
1089 SilcHmac hmac = NULL;
1092 SILC_LOG_DEBUG(("Processing packet"));
1094 /* Packet sending */
1095 if (type == SILC_TASK_WRITE) {
1096 SILC_LOG_DEBUG(("Writing data to connection"));
1098 if (sock->outbuf->data - sock->outbuf->head)
1099 silc_buffer_push(sock->outbuf,
1100 sock->outbuf->data - sock->outbuf->head);
1102 ret = silc_server_packet_send_real(server, sock, TRUE);
1104 /* If returned -2 could not write to connection now, will do
1109 /* The packet has been sent and now it is time to set the connection
1110 back to only for input. When there is again some outgoing data
1111 available for this connection it will be set for output as well.
1112 This call clears the output setting and sets it only for input. */
1113 SILC_SET_CONNECTION_FOR_INPUT(fd);
1114 SILC_UNSET_OUTBUF_PENDING(sock);
1116 silc_buffer_clear(sock->outbuf);
1120 /* Packet receiving */
1121 if (type == SILC_TASK_READ) {
1122 SILC_LOG_DEBUG(("Reading data from connection"));
1124 /* Read some data from connection */
1125 ret = silc_packet_receive(sock);
1131 SILC_LOG_DEBUG(("Read EOF"));
1133 /* If connection is disconnecting already we will finally
1134 close the connection */
1135 if (SILC_IS_DISCONNECTING(sock)) {
1136 if (sock->user_data)
1137 silc_server_free_sock_user_data(server, sock);
1138 silc_server_close_connection(server, sock);
1142 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1144 if (sock->user_data)
1145 silc_server_free_sock_user_data(server, sock);
1146 silc_server_close_connection(server, sock);
1150 /* If connection is disconnecting or disconnected we will ignore
1152 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1153 SILC_LOG_DEBUG(("Ignoring read data from invalid connection"));
1157 switch (sock->type) {
1158 case SILC_SOCKET_TYPE_CLIENT:
1160 SilcClientEntry clnt = (SilcClientEntry)sock->user_data;
1164 clnt->last_receive = time(NULL);
1166 cipher = clnt->receive_key;
1170 case SILC_SOCKET_TYPE_SERVER:
1171 case SILC_SOCKET_TYPE_ROUTER:
1173 SilcServerEntry srvr = (SilcServerEntry)sock->user_data;
1177 srvr->last_receive = time(NULL);
1179 cipher = srvr->receive_key;
1183 case SILC_SOCKET_TYPE_UNKNOWN:
1185 SilcUnknownEntry conn_data = (SilcUnknownEntry)sock->user_data;
1189 cipher = conn_data->receive_key;
1190 hmac = conn_data->hmac;
1197 /* Process the packet. This will call the parser that will then
1198 decrypt and parse the packet. */
1199 silc_packet_receive_process(sock, cipher, hmac,
1200 silc_server_packet_parse, server);
1204 /* Parses whole packet, received earlier. */
1206 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1208 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1209 SilcServer server = (SilcServer)parse_ctx->context;
1210 SilcSocketConnection sock = parse_ctx->sock;
1211 SilcPacketContext *packet = parse_ctx->packet;
1212 SilcBuffer buffer = packet->buffer;
1215 SILC_LOG_DEBUG(("Start"));
1217 /* Decrypt the received packet */
1218 ret = silc_packet_decrypt(parse_ctx->cipher, parse_ctx->hmac,
1224 /* Parse the packet. Packet type is returned. */
1225 ret = silc_packet_parse(packet);
1227 /* Parse the packet header in special way as this is "special"
1229 ret = silc_packet_parse_special(packet);
1232 if (ret == SILC_PACKET_NONE)
1235 /* Parse the incoming packet type */
1236 silc_server_packet_parse_type(server, sock, packet);
1239 silc_buffer_clear(sock->inbuf);
1241 silc_free(packet->src_id);
1243 silc_free(packet->dst_id);
1245 silc_free(parse_ctx);
1248 /* Parser callback called by silc_packet_receive_process. This merely
1249 registers timeout that will handle the actual parsing whem appropriate. */
1251 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1253 SilcServer server = (SilcServer)parser_context->context;
1254 SilcSocketConnection sock = parser_context->sock;
1256 switch (sock->type) {
1257 case SILC_SOCKET_TYPE_CLIENT:
1258 case SILC_SOCKET_TYPE_UNKNOWN:
1259 /* Parse the packet with timeout */
1260 silc_task_register(server->timeout_queue, sock->sock,
1261 silc_server_packet_parse_real,
1262 (void *)parser_context, 0, 100000,
1264 SILC_TASK_PRI_NORMAL);
1266 case SILC_SOCKET_TYPE_SERVER:
1267 case SILC_SOCKET_TYPE_ROUTER:
1268 /* Packets from servers are parsed as soon as possible */
1269 silc_task_register(server->timeout_queue, sock->sock,
1270 silc_server_packet_parse_real,
1271 (void *)parser_context, 0, 1,
1273 SILC_TASK_PRI_NORMAL);
1280 /* Parses the packet type and calls what ever routines the packet type
1281 requires. This is done for all incoming packets. */
1283 void silc_server_packet_parse_type(SilcServer server,
1284 SilcSocketConnection sock,
1285 SilcPacketContext *packet)
1287 SilcBuffer buffer = packet->buffer;
1288 SilcPacketType type = packet->type;
1290 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1292 /* Parse the packet type */
1294 case SILC_PACKET_DISCONNECT:
1295 SILC_LOG_DEBUG(("Disconnect packet"));
1297 case SILC_PACKET_SUCCESS:
1299 * Success received for something. For now we can have only
1300 * one protocol for connection executing at once hence this
1301 * success message is for whatever protocol is executing currently.
1303 SILC_LOG_DEBUG(("Success packet"));
1304 if (sock->protocol) {
1305 sock->protocol->execute(server->timeout_queue, 0,
1306 sock->protocol, sock->sock, 0, 0);
1309 case SILC_PACKET_FAILURE:
1311 * Failure received for something. For now we can have only
1312 * one protocol for connection executing at once hence this
1313 * failure message is for whatever protocol is executing currently.
1315 SILC_LOG_DEBUG(("Failure packet"));
1316 if (sock->protocol) {
1317 /* XXX Audit the failure type */
1318 sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
1319 sock->protocol->execute(server->timeout_queue, 0,
1320 sock->protocol, sock->sock, 0, 0);
1323 case SILC_PACKET_REJECT:
1324 SILC_LOG_DEBUG(("Reject packet"));
1331 case SILC_PACKET_CHANNEL_MESSAGE:
1333 * Received channel message. Channel messages are special packets
1334 * (although probably most common ones) hence they are handled
1337 SILC_LOG_DEBUG(("Channel Message packet"));
1338 silc_server_channel_message(server, sock, packet);
1341 case SILC_PACKET_CHANNEL_KEY:
1343 * Received key for channel. As channels are created by the router
1344 * the keys are as well. We will distribute the key to all of our
1345 * locally connected clients on the particular channel. Router
1346 * never receives this channel and thus is ignored.
1348 SILC_LOG_DEBUG(("Channel Key packet"));
1349 silc_server_channel_key(server, sock, packet);
1355 case SILC_PACKET_COMMAND:
1357 * Recived command. Allocate command context and execute the command.
1359 SILC_LOG_DEBUG(("Command packet"));
1360 silc_server_command_process(server, sock, packet);
1363 case SILC_PACKET_COMMAND_REPLY:
1365 * Received command reply packet. Servers never send commands thus
1366 * they don't receive command reply packets either, except in cases
1367 * where server has forwarded command packet coming from client.
1368 * This must be the case here or we will ignore the packet.
1370 SILC_LOG_DEBUG(("Command Reply packet"));
1371 silc_server_packet_relay_command_reply(server, sock, packet);
1375 * Private Message packets
1377 case SILC_PACKET_PRIVATE_MESSAGE:
1379 * Received private message packet. The packet is coming from either
1382 SILC_LOG_DEBUG(("Private Message packet"));
1383 silc_server_private_message(server, sock, packet);
1386 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1390 * Key Exchange protocol packets
1392 case SILC_PACKET_KEY_EXCHANGE:
1393 SILC_LOG_DEBUG(("KE packet"));
1394 if (sock->protocol && sock->protocol->protocol->type
1395 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1397 SilcServerKEInternalContext *proto_ctx =
1398 (SilcServerKEInternalContext *)sock->protocol->context;
1400 proto_ctx->packet = buffer;
1402 /* Let the protocol handle the packet */
1403 sock->protocol->execute(server->timeout_queue, 0,
1404 sock->protocol, sock->sock, 0, 100000);
1406 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1407 "protocol active, packet dropped."));
1409 /* XXX Trigger KE protocol?? Rekey actually, maybe. */
1413 case SILC_PACKET_KEY_EXCHANGE_1:
1414 SILC_LOG_DEBUG(("KE 1 packet"));
1415 if (sock->protocol && sock->protocol->protocol->type
1416 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1418 SilcServerKEInternalContext *proto_ctx =
1419 (SilcServerKEInternalContext *)sock->protocol->context;
1421 if (proto_ctx->packet)
1422 silc_buffer_free(proto_ctx->packet);
1424 proto_ctx->packet = buffer;
1425 proto_ctx->dest_id_type = packet->src_id_type;
1426 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_type);
1428 /* Let the protocol handle the packet */
1429 sock->protocol->execute(server->timeout_queue, 0,
1430 sock->protocol, sock->sock,
1433 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1434 "protocol active, packet dropped."));
1438 case SILC_PACKET_KEY_EXCHANGE_2:
1439 SILC_LOG_DEBUG(("KE 2 packet"));
1440 if (sock->protocol && sock->protocol->protocol->type
1441 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1443 SilcServerKEInternalContext *proto_ctx =
1444 (SilcServerKEInternalContext *)sock->protocol->context;
1446 if (proto_ctx->packet)
1447 silc_buffer_free(proto_ctx->packet);
1449 proto_ctx->packet = buffer;
1450 proto_ctx->dest_id_type = packet->src_id_type;
1451 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_type);
1453 /* Let the protocol handle the packet */
1454 sock->protocol->execute(server->timeout_queue, 0,
1455 sock->protocol, sock->sock,
1458 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1459 "protocol active, packet dropped."));
1463 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1464 /* If we receive this packet we will send to the other end information
1465 about our mandatory authentication method for the connection.
1466 This packet maybe received at any time. */
1469 * Connection Authentication protocol packets
1471 case SILC_PACKET_CONNECTION_AUTH:
1472 /* Start of the authentication protocol. We receive here the
1473 authentication data and will verify it. */
1474 SILC_LOG_DEBUG(("Connection auth packet"));
1475 if (sock->protocol && sock->protocol->protocol->type
1476 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1478 SilcServerConnAuthInternalContext *proto_ctx =
1479 (SilcServerConnAuthInternalContext *)sock->protocol->context;
1481 proto_ctx->packet = buffer;
1483 /* Let the protocol handle the packet */
1484 sock->protocol->execute(server->timeout_queue, 0,
1485 sock->protocol, sock->sock, 0, 0);
1487 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1488 "protocol active, packet dropped."));
1492 case SILC_PACKET_NEW_ID:
1494 * Received New ID packet. This includes some new ID that has been
1495 * created. It may be for client, server or channel. This is the way
1496 * to distribute information about new registered entities in the
1499 SILC_LOG_DEBUG(("New ID packet"));
1500 silc_server_new_id(server, sock, packet);
1503 case SILC_PACKET_NEW_CLIENT:
1505 * Received new client packet. This includes client information that
1506 * we will use to create initial client ID. After creating new
1507 * ID we will send it to the client.
1509 SILC_LOG_DEBUG(("New Client packet"));
1510 silc_server_new_client(server, sock, packet);
1513 case SILC_PACKET_NEW_SERVER:
1515 * Received new server packet. This includes Server ID and some other
1516 * information that we may save. This is received after server has
1519 SILC_LOG_DEBUG(("New Server packet"));
1520 silc_server_new_server(server, sock, packet);
1523 case SILC_PACKET_NEW_CHANNEL:
1526 case SILC_PACKET_NEW_CHANNEL_USER:
1529 case SILC_PACKET_NEW_CHANNEL_LIST:
1532 case SILC_PACKET_NEW_CHANNEL_USER_LIST:
1535 case SILC_PACKET_REPLACE_ID:
1537 * Received replace ID packet. This sends the old ID that is to be
1538 * replaced with the new one included into the packet. Client must not
1541 SILC_LOG_DEBUG(("Replace ID packet"));
1542 silc_server_replace_id(server, sock, packet);
1545 case SILC_PACKET_REMOVE_ID:
1548 case SILC_PACKET_REMOVE_CHANNEL_USER:
1550 * Received packet to remove user from a channel. Routers notify other
1551 * routers about a user leaving a channel.
1553 SILC_LOG_DEBUG(("Remove Channel User packet"));
1554 silc_server_remove_channel_user(server, sock, packet);
1558 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
1564 /* Assembles a new packet to be sent out to network. This doesn't actually
1565 send the packet but creates the packet and fills the outgoing data
1566 buffer and marks the packet ready to be sent to network. However, If
1567 argument force_send is TRUE the packet is sent immediately and not put
1568 to queue. Normal case is that the packet is not sent immediately. */
1570 void silc_server_packet_send(SilcServer server,
1571 SilcSocketConnection sock,
1572 SilcPacketType type,
1573 SilcPacketFlags flags,
1574 unsigned char *data,
1575 unsigned int data_len,
1578 void *dst_id = NULL;
1579 SilcIdType dst_id_type = SILC_ID_NONE;
1584 /* Get data used in the packet sending, keys and stuff */
1585 switch(sock->type) {
1586 case SILC_SOCKET_TYPE_CLIENT:
1587 if (((SilcClientEntry)sock->user_data)->id) {
1588 dst_id = ((SilcClientEntry)sock->user_data)->id;
1589 dst_id_type = SILC_ID_CLIENT;
1592 case SILC_SOCKET_TYPE_SERVER:
1593 case SILC_SOCKET_TYPE_ROUTER:
1594 if (((SilcServerEntry)sock->user_data)->id) {
1595 dst_id = ((SilcServerEntry)sock->user_data)->id;
1596 dst_id_type = SILC_ID_SERVER;
1603 silc_server_packet_send_dest(server, sock, type, flags, dst_id,
1604 dst_id_type, data, data_len, force_send);
1607 /* Assembles a new packet to be sent out to network. This doesn't actually
1608 send the packet but creates the packet and fills the outgoing data
1609 buffer and marks the packet ready to be sent to network. However, If
1610 argument force_send is TRUE the packet is sent immediately and not put
1611 to queue. Normal case is that the packet is not sent immediately.
1612 Destination information is sent as argument for this function. */
1614 void silc_server_packet_send_dest(SilcServer server,
1615 SilcSocketConnection sock,
1616 SilcPacketType type,
1617 SilcPacketFlags flags,
1619 SilcIdType dst_id_type,
1620 unsigned char *data,
1621 unsigned int data_len,
1624 SilcPacketContext packetdata;
1625 SilcCipher cipher = NULL;
1626 SilcHmac hmac = NULL;
1627 unsigned char *dst_id_data = NULL;
1628 unsigned int dst_id_len = 0;
1630 SILC_LOG_DEBUG(("Sending packet, type %d", type));
1632 /* Get data used in the packet sending, keys and stuff */
1633 switch(sock->type) {
1634 case SILC_SOCKET_TYPE_CLIENT:
1635 if (sock->user_data) {
1636 cipher = ((SilcClientEntry)sock->user_data)->send_key;
1637 hmac = ((SilcClientEntry)sock->user_data)->hmac;
1640 case SILC_SOCKET_TYPE_SERVER:
1641 case SILC_SOCKET_TYPE_ROUTER:
1642 if (sock->user_data) {
1643 cipher = ((SilcServerEntry)sock->user_data)->send_key;
1644 hmac = ((SilcServerEntry)sock->user_data)->hmac;
1648 if (sock->user_data) {
1649 /* We don't know what type of connection this is thus it must
1650 be in authentication phase. */
1651 cipher = ((SilcUnknownEntry)sock->user_data)->send_key;
1652 hmac = ((SilcUnknownEntry)sock->user_data)->hmac;
1658 dst_id_data = silc_id_id2str(dst_id, dst_id_type);
1659 dst_id_len = silc_id_get_len(dst_id_type);
1662 /* Set the packet context pointers */
1663 packetdata.type = type;
1664 packetdata.flags = flags;
1665 packetdata.src_id = silc_id_id2str(server->id, server->id_type);
1666 packetdata.src_id_len = SILC_ID_SERVER_LEN;
1667 packetdata.src_id_type = server->id_type;
1668 packetdata.dst_id = dst_id_data;
1669 packetdata.dst_id_len = dst_id_len;
1670 packetdata.dst_id_type = dst_id_type;
1671 packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
1672 packetdata.src_id_len + dst_id_len;
1673 packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
1674 packetdata.rng = server->rng;
1676 /* Prepare outgoing data buffer for packet sending */
1677 silc_packet_send_prepare(sock,
1678 SILC_PACKET_HEADER_LEN +
1679 packetdata.src_id_len +
1680 packetdata.dst_id_len,
1684 SILC_LOG_DEBUG(("Putting data to outgoing buffer, len %d", data_len));
1686 packetdata.buffer = sock->outbuf;
1688 /* Put the data to the buffer */
1689 if (data && data_len)
1690 silc_buffer_put(sock->outbuf, data, data_len);
1692 /* Create the outgoing packet */
1693 silc_packet_assemble(&packetdata);
1695 /* Encrypt the packet */
1697 silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
1699 SILC_LOG_HEXDUMP(("Outgoing packet, len %d", sock->outbuf->len),
1700 sock->outbuf->data, sock->outbuf->len);
1702 /* Now actually send the packet */
1703 silc_server_packet_send_real(server, sock, force_send);
1705 if (packetdata.src_id)
1706 silc_free(packetdata.src_id);
1707 if (packetdata.dst_id)
1708 silc_free(packetdata.dst_id);
1711 /* Forwards packet. Packets sent with this function will be marked as
1712 forwarded (in the SILC header flags) so that the receiver knows that
1713 we have forwarded the packet to it. Forwarded packets are handled
1714 specially by the receiver as they are not destined to the receiver
1715 originally. However, the receiver knows this because the forwarded
1716 flag has been set (and the flag is authenticated). */
1718 void silc_server_packet_forward(SilcServer server,
1719 SilcSocketConnection sock,
1720 unsigned char *data, unsigned int data_len,
1723 SilcCipher cipher = NULL;
1724 SilcHmac hmac = NULL;
1726 SILC_LOG_DEBUG(("Forwarding packet"));
1728 /* Get data used in the packet sending, keys and stuff */
1729 switch(sock->type) {
1730 case SILC_SOCKET_TYPE_CLIENT:
1731 if (sock->user_data) {
1732 cipher = ((SilcClientEntry )sock->user_data)->send_key;
1733 hmac = ((SilcClientEntry )sock->user_data)->hmac;
1736 case SILC_SOCKET_TYPE_SERVER:
1737 case SILC_SOCKET_TYPE_ROUTER:
1738 if (sock->user_data) {
1739 cipher = ((SilcServerEntry )sock->user_data)->send_key;
1740 hmac = ((SilcServerEntry )sock->user_data)->hmac;
1744 /* We won't forward to unknown destination - keys must exist with
1745 the destination before forwarding. */
1749 /* Prepare outgoing data buffer for packet sending */
1750 silc_packet_send_prepare(sock, 0, 0, data_len);
1752 /* Mungle the packet flags and add the FORWARDED flag */
1754 data[2] |= (unsigned char)SILC_PACKET_FLAG_FORWARDED;
1756 /* Put the data to the buffer */
1757 if (data && data_len)
1758 silc_buffer_put(sock->outbuf, data, data_len);
1760 /* Encrypt the packet */
1762 silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
1764 SILC_LOG_HEXDUMP(("Forwarded packet, len %d", sock->outbuf->len),
1765 sock->outbuf->data, sock->outbuf->len);
1767 /* Now actually send the packet */
1768 silc_server_packet_send_real(server, sock, force_send);
1771 /* Internal routine to actually create the channel packet and send it
1772 to network. This is common function in channel message sending. If
1773 `channel_message' is TRUE this encrypts the message as it is strictly
1774 a channel message. If FALSE normal encryption process is used. */
1777 silc_server_packet_send_to_channel_real(SilcServer server,
1778 SilcSocketConnection sock,
1779 SilcPacketContext *packet,
1782 unsigned char *data,
1783 unsigned int data_len,
1784 int channel_message,
1787 packet->truelen = data_len + SILC_PACKET_HEADER_LEN +
1788 packet->src_id_len + packet->dst_id_len;
1790 /* Prepare outgoing data buffer for packet sending */
1791 silc_packet_send_prepare(sock,
1792 SILC_PACKET_HEADER_LEN +
1793 packet->src_id_len +
1798 packet->buffer = sock->outbuf;
1800 /* Put the data to buffer, assemble and encrypt the packet. The packet
1801 is encrypted with normal session key shared with the client. */
1802 silc_buffer_put(sock->outbuf, data, data_len);
1803 silc_packet_assemble(packet);
1804 if (channel_message)
1805 silc_packet_encrypt(cipher, hmac, sock->outbuf, SILC_PACKET_HEADER_LEN +
1806 packet->src_id_len + packet->dst_id_len +
1809 silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
1811 SILC_LOG_HEXDUMP(("Channel packet, len %d", sock->outbuf->len),
1812 sock->outbuf->data, sock->outbuf->len);
1814 /* Now actually send the packet */
1815 silc_server_packet_send_real(server, sock, force_send);
1818 /* This routine is used by the server to send packets to channel. The
1819 packet sent with this function is distributed to all clients on
1820 the channel. Usually this is used to send notify messages to the
1821 channel, things like notify about new user joining to the channel. */
1823 void silc_server_packet_send_to_channel(SilcServer server,
1824 SilcChannelEntry channel,
1825 SilcPacketType type,
1826 unsigned char *data,
1827 unsigned int data_len,
1830 SilcSocketConnection sock = NULL;
1831 SilcPacketContext packetdata;
1832 SilcClientEntry client = NULL;
1833 SilcServerEntry *routed = NULL;
1834 SilcChannelClientEntry chl;
1835 unsigned int routed_count = 0;
1839 /* This doesn't send channel message packets */
1840 if (type == SILC_PACKET_CHANNEL_MESSAGE)
1843 SILC_LOG_DEBUG(("Sending packet to channel"));
1845 /* Set the packet context pointers. */
1846 packetdata.flags = 0;
1847 packetdata.type = type;
1848 packetdata.src_id = silc_id_id2str(server->id, SILC_ID_SERVER);
1849 packetdata.src_id_len = SILC_ID_SERVER_LEN;
1850 packetdata.src_id_type = SILC_ID_SERVER;
1851 packetdata.dst_id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
1852 packetdata.dst_id_len = SILC_ID_CHANNEL_LEN;
1853 packetdata.dst_id_type = SILC_ID_CHANNEL;
1854 packetdata.rng = server->rng;
1855 packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
1856 packetdata.src_id_len + packetdata.dst_id_len;
1857 packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
1859 /* If there are global users in the channel we will send the message
1860 first to our router for further routing. */
1861 if (server->server_type == SILC_SERVER && !server->standalone &&
1862 channel->global_users) {
1863 SilcServerEntry router;
1865 /* Get data used in packet header encryption, keys and stuff. */
1866 router = server->id_entry->router;
1867 sock = (SilcSocketConnection)router->connection;
1868 cipher = router->send_key;
1869 hmac = router->hmac;
1871 SILC_LOG_DEBUG(("Sending channel message to router for routing"));
1873 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1875 data_len, FALSE, force_send);
1878 /* Send the message to clients on the channel's client list. */
1879 silc_list_start(channel->user_list);
1880 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
1881 client = chl->client;
1883 /* If client has router set it is not locally connected client and
1884 we will route the message to the router set in the client. */
1885 if (client && client->router && server->server_type == SILC_ROUTER) {
1888 /* Check if we have sent the packet to this route already */
1889 for (k = 0; k < routed_count; k++)
1890 if (routed[k] == client->router)
1892 if (k < routed_count)
1895 /* Get data used in packet header encryption, keys and stuff. */
1896 sock = (SilcSocketConnection)client->router->connection;
1897 cipher = client->router->send_key;
1898 hmac = client->router->hmac;
1900 /* Send the packet */
1901 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1903 data_len, FALSE, force_send);
1905 /* We want to make sure that the packet is routed to same router
1906 only once. Mark this route as sent route. */
1908 routed = silc_realloc(routed, sizeof(*routed) * (k + 1));
1909 routed[k] = client->router;
1915 /* Send to locally connected client */
1918 /* Get data used in packet header encryption, keys and stuff. */
1919 sock = (SilcSocketConnection)client->connection;
1920 cipher = client->send_key;
1921 hmac = client->hmac;
1923 /* Send the packet */
1924 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1926 data_len, FALSE, force_send);
1932 silc_free(packetdata.src_id);
1933 silc_free(packetdata.dst_id);
1936 /* This routine is explicitly used to relay messages to some channel.
1937 Packets sent with this function we have received earlier and are
1938 totally encrypted. This just sends the packet to all clients on
1939 the channel. If the sender of the packet is someone on the channel
1940 the message will not be sent to that client. The SILC Packet header
1941 is encrypted with the session key shared between us and the client.
1942 MAC is also computed before encrypting the header. Rest of the
1943 packet will be untouched. */
1945 void silc_server_packet_relay_to_channel(SilcServer server,
1946 SilcSocketConnection sender_sock,
1947 SilcChannelEntry channel,
1949 SilcIdType sender_type,
1950 unsigned char *data,
1951 unsigned int data_len,
1955 SilcSocketConnection sock = NULL;
1956 SilcPacketContext packetdata;
1957 SilcClientEntry client = NULL;
1958 SilcServerEntry *routed = NULL;
1959 SilcChannelClientEntry chl;
1960 unsigned int routed_count = 0;
1964 SILC_LOG_DEBUG(("Relaying packet to channel"));
1966 /* Set the packet context pointers. */
1967 packetdata.flags = 0;
1968 packetdata.type = SILC_PACKET_CHANNEL_MESSAGE;
1969 packetdata.src_id = silc_id_id2str(sender, sender_type);
1970 packetdata.src_id_len = silc_id_get_len(sender_type);
1971 packetdata.src_id_type = sender_type;
1972 packetdata.dst_id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
1973 packetdata.dst_id_len = SILC_ID_CHANNEL_LEN;
1974 packetdata.dst_id_type = SILC_ID_CHANNEL;
1975 packetdata.rng = server->rng;
1976 packetdata.padlen = SILC_PACKET_PADLEN((SILC_PACKET_HEADER_LEN +
1977 packetdata.src_id_len +
1978 packetdata.dst_id_len));
1980 /* If there are global users in the channel we will send the message
1981 first to our router for further routing. */
1982 if (server->server_type == SILC_SERVER && !server->standalone &&
1983 channel->global_users) {
1984 SilcServerEntry router;
1986 router = server->id_entry->router;
1988 /* Check that the sender is not our router. */
1989 if (sender_sock != (SilcSocketConnection)router->connection) {
1991 /* Get data used in packet header encryption, keys and stuff. */
1992 sock = (SilcSocketConnection)router->connection;
1993 cipher = router->send_key;
1994 hmac = router->hmac;
1996 SILC_LOG_DEBUG(("Sending channel message to router for routing"));
1998 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
2000 data_len, TRUE, force_send);
2004 /* Send the message to clients on the channel's client list. */
2005 silc_list_start(channel->user_list);
2006 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2007 client = chl->client;
2011 /* If sender is one on the channel do not send it the packet. */
2012 if (!found && !SILC_ID_CLIENT_COMPARE(client->id, sender)) {
2017 /* If the client has set router it means that it is not locally
2018 connected client and we will route the packet further. */
2019 if (server->server_type == SILC_ROUTER && client->router) {
2022 /* Sender maybe server as well so we want to make sure that
2023 we won't send the message to the server it came from. */
2024 if (!found && !SILC_ID_SERVER_COMPARE(client->router->id, sender)) {
2029 /* Check if we have sent the packet to this route already */
2030 for (k = 0; k < routed_count; k++)
2031 if (routed[k] == client->router)
2033 if (k < routed_count)
2036 /* Get data used in packet header encryption, keys and stuff. */
2037 sock = (SilcSocketConnection)client->router->connection;
2038 cipher = client->router->send_key;
2039 hmac = client->router->hmac;
2041 /* Send the packet */
2042 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
2044 data_len, TRUE, force_send);
2046 /* We want to make sure that the packet is routed to same router
2047 only once. Mark this route as sent route. */
2049 routed = silc_realloc(routed, sizeof(*routed) * (k + 1));
2050 routed[k] = client->router;
2056 /* XXX Check client's mode on the channel. */
2058 /* Get data used in packet header encryption, keys and stuff. */
2059 sock = (SilcSocketConnection)client->connection;
2060 cipher = client->send_key;
2061 hmac = client->hmac;
2063 SILC_LOG_DEBUG(("Sending packet to client %s",
2064 sock->hostname ? sock->hostname : sock->ip));
2066 /* Send the packet */
2067 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
2069 data_len, TRUE, force_send);
2073 silc_free(packetdata.src_id);
2074 silc_free(packetdata.dst_id);
2077 /* This function is used to send packets strictly to all local clients
2078 on a particular channel. This is used for example to distribute new
2079 channel key to all our locally connected clients on the channel.
2080 The packets are always encrypted with the session key shared between
2081 the client, this means these are not _to the channel_ but _to the client_
2084 void silc_server_packet_send_local_channel(SilcServer server,
2085 SilcChannelEntry channel,
2086 SilcPacketType type,
2087 SilcPacketFlags flags,
2088 unsigned char *data,
2089 unsigned int data_len,
2092 SilcClientEntry client;
2093 SilcChannelClientEntry chl;
2094 SilcSocketConnection sock = NULL;
2096 SILC_LOG_DEBUG(("Start"));
2098 /* Send the message to clients on the channel's client list. */
2099 silc_list_start(channel->user_list);
2100 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2101 client = chl->client;
2104 sock = (SilcSocketConnection)client->connection;
2106 /* Send the packet to the client */
2107 silc_server_packet_send_dest(server, sock, type, flags, client->id,
2108 SILC_ID_CLIENT, data, data_len,
2114 /* Relays received command reply packet to the correct destination. The
2115 destination must be one of our locally connected client or the packet
2116 will be ignored. This is called when server has forwarded one of
2117 client's command request to router and router has now replied to the
2120 void silc_server_packet_relay_command_reply(SilcServer server,
2121 SilcSocketConnection sock,
2122 SilcPacketContext *packet)
2124 SilcBuffer buffer = packet->buffer;
2125 SilcClientEntry client;
2127 SilcSocketConnection dst_sock;
2129 SILC_LOG_DEBUG(("Start"));
2131 /* Source must be server or router */
2132 if (packet->src_id_type != SILC_ID_SERVER &&
2133 sock->type != SILC_SOCKET_TYPE_ROUTER)
2136 /* Destination must be client */
2137 if (packet->dst_id_type != SILC_ID_CLIENT)
2140 /* Execute command reply locally for the command */
2141 silc_server_command_reply_process(server, sock, buffer);
2143 id = silc_id_str2id(packet->dst_id, SILC_ID_CLIENT);
2145 /* Destination must be one of ours */
2146 client = silc_idlist_find_client_by_id(server->local_list, id);
2152 /* Relay the packet to the client */
2154 dst_sock = (SilcSocketConnection)client->connection;
2155 silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len
2156 + packet->dst_id_len + packet->padlen);
2158 silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
2159 silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
2161 /* Encrypt packet */
2162 if (client && client->send_key)
2163 silc_packet_encrypt(client->send_key, client->hmac,
2164 dst_sock->outbuf, buffer->len);
2166 /* Send the packet */
2167 silc_server_packet_send_real(server, dst_sock, FALSE);
2172 silc_buffer_free(buffer);
2175 /* Closes connection to socket connection */
2177 void silc_server_close_connection(SilcServer server,
2178 SilcSocketConnection sock)
2181 SILC_LOG_DEBUG(("Closing connection %d", sock->sock));
2183 /* We won't listen for this connection anymore */
2184 silc_schedule_unset_listen_fd(sock->sock);
2186 /* Unregister all tasks */
2187 silc_task_unregister_by_fd(server->io_queue, sock->sock);
2188 silc_task_unregister_by_fd(server->timeout_queue, sock->sock);
2190 /* Close the actual connection */
2191 silc_net_close_connection(sock->sock);
2192 server->sockets[sock->sock] = NULL;
2193 silc_socket_free(sock);
2196 /* Sends disconnect message to remote connection and disconnects the
2199 void silc_server_disconnect_remote(SilcServer server,
2200 SilcSocketConnection sock,
2201 const char *fmt, ...)
2204 unsigned char buf[4096];
2206 memset(buf, 0, sizeof(buf));
2208 vsprintf(buf, fmt, ap);
2211 SILC_LOG_DEBUG(("Disconnecting remote host"));
2213 /* Notify remote end that the conversation is over. The notify message
2214 is tried to be sent immediately. */
2215 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2216 buf, strlen(buf), TRUE);
2218 /* Mark the connection to be disconnected */
2219 SILC_SET_DISCONNECTED(sock);
2220 silc_server_close_connection(server, sock);
2223 /* Free's user_data pointer from socket connection object. As this
2224 pointer maybe anything we wil switch here to find the correct
2225 data type and free it the way it needs to be free'd. */
2227 void silc_server_free_sock_user_data(SilcServer server,
2228 SilcSocketConnection sock)
2230 SILC_LOG_DEBUG(("Start"));
2232 switch(sock->type) {
2233 case SILC_SOCKET_TYPE_CLIENT:
2235 SilcClientEntry user_data = (SilcClientEntry )sock->user_data;
2237 /* Remove client from all channels */
2238 silc_server_remove_from_channels(server, sock, user_data);
2240 /* Free the client entry and everything in it */
2241 /* XXX must take some info to history before freeing */
2242 silc_idlist_del_client(server->local_list, user_data);
2245 case SILC_SOCKET_TYPE_SERVER:
2246 case SILC_SOCKET_TYPE_ROUTER:
2254 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2256 if (user_data->send_key)
2257 silc_cipher_free(user_data->send_key);
2258 if (user_data->receive_key)
2259 silc_cipher_free(user_data->receive_key);
2260 if (user_data->pkcs)
2261 silc_pkcs_free(user_data->pkcs);
2262 if (user_data->hmac) {
2263 silc_hmac_free(user_data->hmac);
2264 memset(user_data->hmac_key, 0, user_data->hmac_key_len);
2265 silc_free(user_data->hmac_key);
2267 silc_free(user_data);
2272 sock->user_data = NULL;
2277 /* Removes client from all channels it has joined. This is used when
2278 client connection is disconnected. If the client on a channel
2279 is last, the channel is removed as well. */
2281 void silc_server_remove_from_channels(SilcServer server,
2282 SilcSocketConnection sock,
2283 SilcClientEntry client)
2285 SilcChannelEntry channel;
2286 SilcChannelClientEntry chl;
2287 SilcBuffer chidp, clidp;
2289 SILC_LOG_DEBUG(("Start"));
2291 if (!client || !client->id)
2294 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2296 /* Remove the client from all channels. The client is removed from
2297 the channels' user list. */
2298 silc_list_start(client->channels);
2299 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2300 channel = chl->channel;
2301 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
2303 /* Remove from list */
2304 silc_list_del(client->channels, chl);
2306 /* If this client is last one on the channel the channel
2307 is removed all together. */
2308 if (silc_list_count(channel->user_list) < 2) {
2310 /* However, if the channel has marked global users then the
2311 channel is not created locally, and this does not remove the
2312 channel globally from SILC network, in this case we will
2313 notify that this client has left the channel. */
2314 if (channel->global_users)
2315 silc_server_send_notify_to_channel(server, channel,
2316 SILC_NOTIFY_TYPE_SIGNOFF, 1,
2317 clidp->data, clidp->len);
2319 silc_idlist_del_channel(server->local_list, channel);
2323 /* Remove from list */
2324 silc_list_del(channel->user_list, chl);
2327 /* Send notify to channel about client leaving SILC and thus
2328 the entire channel. */
2329 silc_server_send_notify_to_channel(server, channel,
2330 SILC_NOTIFY_TYPE_SIGNOFF, 1,
2331 clidp->data, clidp->len);
2332 silc_buffer_free(chidp);
2335 silc_buffer_free(clidp);
2338 /* Removes client from one channel. This is used for example when client
2339 calls LEAVE command to remove itself from the channel. Returns TRUE
2340 if channel still exists and FALSE if the channel is removed when
2341 last client leaves the channel. If `notify' is FALSE notify messages
2344 int silc_server_remove_from_one_channel(SilcServer server,
2345 SilcSocketConnection sock,
2346 SilcChannelEntry channel,
2347 SilcClientEntry client,
2350 SilcChannelEntry ch;
2351 SilcChannelClientEntry chl;
2354 SILC_LOG_DEBUG(("Start"));
2356 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2358 /* Remove the client from the channel. The client is removed from
2359 the channel's user list. */
2360 silc_list_start(client->channels);
2361 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2362 if (chl->channel != channel)
2367 /* Remove from list */
2368 silc_list_del(client->channels, chl);
2370 /* If this client is last one on the channel the channel
2371 is removed all together. */
2372 if (silc_list_count(channel->user_list) < 2) {
2373 /* Notify about leaving client if this channel has global users,
2374 ie. the channel is not created locally. */
2375 if (notify && channel->global_users)
2376 silc_server_send_notify_to_channel(server, channel,
2377 SILC_NOTIFY_TYPE_LEAVE, 1,
2378 clidp->data, clidp->len);
2380 silc_idlist_del_channel(server->local_list, channel);
2381 silc_buffer_free(clidp);
2385 /* Remove from list */
2386 silc_list_del(channel->user_list, chl);
2389 /* Send notify to channel about client leaving the channel */
2391 silc_server_send_notify_to_channel(server, channel,
2392 SILC_NOTIFY_TYPE_LEAVE, 1,
2393 clidp->data, clidp->len);
2397 silc_buffer_free(clidp);
2401 /* Returns TRUE if the given client is on the channel. FALSE if not.
2402 This works because we assure that the user list on the channel is
2403 always in up to date thus we can only check the channel list from
2404 `client' which is faster than checking the user list from `channel'. */
2406 int silc_server_client_on_channel(SilcClientEntry client,
2407 SilcChannelEntry channel)
2409 SilcChannelClientEntry chl;
2411 if (!client || !channel)
2414 silc_list_start(client->channels);
2415 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END)
2416 if (chl->channel == channel)
2422 /* Timeout callback. This is called if connection is idle or for some
2423 other reason is not responding within some period of time. This
2424 disconnects the remote end. */
2426 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2428 SilcServerConnection sconn = (SilcServerConnection)context;
2429 SilcSocketConnection sock = sconn->server->sockets[fd];
2431 silc_server_disconnect_remote(sconn->server, sock,
2432 "Server closed connection: "
2433 "Connection timeout");
2436 /* Internal routine used to send (relay, route) private messages to some
2437 destination. If the private message key does not exist then the message
2438 is re-encrypted, otherwise we just pass it along. */
2441 silc_server_private_message_send_internal(SilcServer server,
2442 SilcSocketConnection dst_sock,
2445 SilcPacketContext *packet)
2447 SilcBuffer buffer = packet->buffer;
2449 /* Send and re-encrypt if private messge key does not exist */
2450 if ((packet->flags & SILC_PACKET_FLAG_PRIVMSG_KEY) == FALSE) {
2452 silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len
2453 + packet->dst_id_len + packet->padlen);
2454 silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
2455 silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
2457 /* Re-encrypt packet */
2458 silc_packet_encrypt(cipher, hmac, dst_sock->outbuf, buffer->len);
2460 /* Send the packet */
2461 silc_server_packet_send_real(server, dst_sock, FALSE);
2464 /* Key exist so just send it */
2465 silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len
2466 + packet->dst_id_len + packet->padlen);
2467 silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
2468 silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
2469 silc_server_packet_send_real(server, dst_sock, FALSE);
2473 /* Received private message. This resolves the destination of the message
2474 and sends the packet. This is used by both server and router. If the
2475 destination is our locally connected client this sends the packet to
2476 the client. This may also send the message for further routing if
2477 the destination is not in our server (or router). */
2479 void silc_server_private_message(SilcServer server,
2480 SilcSocketConnection sock,
2481 SilcPacketContext *packet)
2483 SilcBuffer buffer = packet->buffer;
2485 SilcServerEntry router;
2486 SilcSocketConnection dst_sock;
2487 SilcClientEntry client;
2489 SILC_LOG_DEBUG(("Start"));
2491 if (!packet->dst_id) {
2492 SILC_LOG_ERROR(("Bad Client ID in private message packet, dropped"));
2496 /* Decode destination Client ID */
2497 id = silc_id_str2id(packet->dst_id, SILC_ID_CLIENT);
2499 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
2503 /* If the destination belongs to our server we don't have to route
2504 the message anywhere but to send it to the local destination. */
2505 client = silc_idlist_find_client_by_id(server->local_list, id);
2507 /* It exists, now deliver the message to the destination */
2508 dst_sock = (SilcSocketConnection)client->connection;
2510 /* If we are router and the client has router then the client is in
2511 our cell but not directly connected to us. */
2512 if (server->server_type == SILC_ROUTER && client->router) {
2513 /* We are of course in this case the client's router thus the real
2514 "router" of the client is the server who owns the client. Thus
2515 we will send the packet to that server. */
2516 router = (SilcServerEntry)dst_sock->user_data;
2517 // assert(client->router == server->id_entry);
2519 silc_server_private_message_send_internal(server, dst_sock,
2526 /* Seems that client really is directly connected to us */
2527 silc_server_private_message_send_internal(server, dst_sock,
2529 client->hmac, packet);
2533 /* Destination belongs to someone not in this server. If we are normal
2534 server our action is to send the packet to our router. */
2535 if (server->server_type == SILC_SERVER && !server->standalone) {
2536 router = server->id_entry->router;
2538 /* Send to primary route */
2540 dst_sock = (SilcSocketConnection)router->connection;
2541 silc_server_private_message_send_internal(server, dst_sock,
2543 router->hmac, packet);
2548 /* We are router and we will perform route lookup for the destination
2549 and send the message to fastest route. */
2550 if (server->server_type == SILC_ROUTER && !server->standalone) {
2551 dst_sock = silc_server_get_route(server, id, SILC_ID_CLIENT);
2552 router = (SilcServerEntry)dst_sock->user_data;
2554 /* Get fastest route and send packet. */
2556 silc_server_private_message_send_internal(server, dst_sock,
2558 router->hmac, packet);
2564 silc_server_send_error(server, sock,
2565 "No such nickname: Private message not sent");
2567 silc_buffer_free(buffer);
2570 /* Process received channel message. The message can be originated from
2571 client or server. */
2573 void silc_server_channel_message(SilcServer server,
2574 SilcSocketConnection sock,
2575 SilcPacketContext *packet)
2577 SilcChannelEntry channel = NULL;
2578 SilcChannelClientEntry chl;
2579 SilcChannelID *id = NULL;
2580 void *sender = NULL;
2581 SilcBuffer buffer = packet->buffer;
2583 SILC_LOG_DEBUG(("Processing channel message"));
2586 if (packet->dst_id_type != SILC_ID_CHANNEL) {
2587 SILC_LOG_ERROR(("Received bad message for channel, dropped"));
2588 SILC_LOG_DEBUG(("Received bad message for channel, dropped"));
2592 /* Find channel entry */
2593 id = silc_id_str2id(packet->dst_id, SILC_ID_CHANNEL);
2594 channel = silc_idlist_find_channel_by_id(server->local_list, id);
2596 SILC_LOG_DEBUG(("Could not find channel"));
2600 /* See that this client is on the channel. If the message is coming
2601 from router we won't do the check as the message is from client that
2602 we don't know about. Also, if the original sender is not client
2603 (as it can be server as well) we don't do the check. */
2604 sender = silc_id_str2id(packet->src_id, packet->src_id_type);
2605 if (sock->type != SILC_SOCKET_TYPE_ROUTER &&
2606 packet->src_id_type == SILC_ID_CLIENT) {
2607 silc_list_start(channel->user_list);
2608 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2609 if (chl->client && !SILC_ID_CLIENT_COMPARE(chl->client->id, sender))
2612 if (chl == SILC_LIST_END)
2616 /* Distribute the packet to our local clients. This will send the
2617 packet for further routing as well, if needed. */
2618 silc_server_packet_relay_to_channel(server, sock, channel, sender,
2619 packet->src_id_type,
2620 packet->buffer->data,
2621 packet->buffer->len, FALSE);
2628 silc_buffer_free(buffer);
2631 /* Received channel key packet. We distribute the key to all of our locally
2632 connected clients on the channel. */
2633 /* XXX Router must accept this packet and distribute the key to all its
2634 server that has clients on the channel */
2636 void silc_server_channel_key(SilcServer server,
2637 SilcSocketConnection sock,
2638 SilcPacketContext *packet)
2640 SilcBuffer buffer = packet->buffer;
2641 SilcChannelKeyPayload payload = NULL;
2642 SilcChannelID *id = NULL;
2643 SilcChannelEntry channel;
2644 SilcChannelClientEntry chl;
2645 SilcClientEntry client;
2647 unsigned int tmp_len;
2650 if (packet->src_id_type != SILC_ID_SERVER &&
2651 sock->type != SILC_SOCKET_TYPE_ROUTER)
2654 /* Decode channel key payload */
2655 payload = silc_channel_key_payload_parse(buffer);
2657 SILC_LOG_ERROR(("Bad channel key payload, dropped"));
2661 /* Get channel ID */
2662 tmp = silc_channel_key_get_id(payload, &tmp_len);
2663 id = silc_id_payload_parse_id(tmp, tmp_len);
2667 /* Get the channel entry */
2668 channel = silc_idlist_find_channel_by_id(server->local_list, id);
2670 SILC_LOG_ERROR(("Received key for non-existent channel"));
2674 /* Save the key for us as well */
2675 tmp = silc_channel_key_get_key(payload, &tmp_len);
2678 cipher = silc_channel_key_get_cipher(payload, NULL);;
2681 if (!silc_cipher_alloc(cipher, &channel->channel_key))
2684 channel->key_len = tmp_len * 8;
2685 channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
2686 memcpy(channel->key, tmp, tmp_len);
2687 channel->channel_key->cipher->set_key(channel->channel_key->context,
2690 /* Distribute the key to all clients on the channel */
2691 /* XXX Some other sender should be used, I think this is not correct */
2692 silc_list_start(channel->user_list);
2693 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2694 client = chl->client;
2697 silc_server_packet_send_dest(server, client->connection,
2698 SILC_PACKET_CHANNEL_KEY, 0,
2699 client->id, SILC_ID_CLIENT,
2700 buffer->data, buffer->len, FALSE);
2707 silc_channel_key_payload_free(payload);
2708 silc_buffer_free(buffer);
2711 /* Sends current motd to client */
2713 void silc_server_send_motd(SilcServer server,
2714 SilcSocketConnection sock)
2719 if (server->config && server->config->motd &&
2720 server->config->motd->motd_file) {
2722 motd = silc_file_read(server->config->motd->motd_file, &motd_len);
2726 silc_server_send_notify(server, sock, SILC_NOTIFY_TYPE_MOTD, 1,
2732 /* Sends error message. Error messages may or may not have any
2735 void silc_server_send_error(SilcServer server,
2736 SilcSocketConnection sock,
2737 const char *fmt, ...)
2740 unsigned char buf[4096];
2742 memset(buf, 0, sizeof(buf));
2744 vsprintf(buf, fmt, ap);
2747 silc_server_packet_send(server, sock, SILC_PACKET_ERROR, 0,
2748 buf, strlen(buf), FALSE);
2751 /* Sends notify message. If format is TRUE the variable arguments are
2752 formatted and the formatted string is sent as argument payload. If it is
2753 FALSE then each argument is sent as separate argument and their format
2754 in the argument list must be { argument data, argument length }. */
2756 void silc_server_send_notify(SilcServer server,
2757 SilcSocketConnection sock,
2758 SilcNotifyType type,
2759 unsigned int argc, ...)
2766 packet = silc_notify_payload_encode(type, argc, ap);
2767 silc_server_packet_send(server, sock, SILC_PACKET_NOTIFY, 0,
2768 packet->data, packet->len, FALSE);
2769 silc_buffer_free(packet);
2772 /* Sends notify message destined to specific entity. */
2774 void silc_server_send_notify_dest(SilcServer server,
2775 SilcSocketConnection sock,
2777 SilcIdType dest_id_type,
2778 SilcNotifyType type,
2779 unsigned int argc, ...)
2786 packet = silc_notify_payload_encode(type, argc, ap);
2787 silc_server_packet_send_dest(server, sock, SILC_PACKET_NOTIFY, 0,
2788 dest_id, dest_id_type,
2789 packet->data, packet->len, FALSE);
2790 silc_buffer_free(packet);
2793 /* Sends notify message to a channel. The notify message sent is
2794 distributed to all clients on the channel. */
2796 void silc_server_send_notify_to_channel(SilcServer server,
2797 SilcChannelEntry channel,
2798 SilcNotifyType type,
2799 unsigned int argc, ...)
2806 packet = silc_notify_payload_encode(type, argc, ap);
2807 silc_server_packet_send_to_channel(server, channel,
2809 packet->data, packet->len, FALSE);
2810 silc_buffer_free(packet);
2813 /* Send notify message to all clients the client has joined. It is quaranteed
2814 that the message is sent only once to a client (ie. if a client is joined
2815 on two same channel it will receive only one notify message). Also, this
2816 sends only to local clients (locally connected if we are server, and to
2817 local servers if we are router). */
2819 void silc_server_send_notify_on_channels(SilcServer server,
2820 SilcClientEntry client,
2821 SilcNotifyType type,
2822 unsigned int argc, ...)
2825 SilcSocketConnection sock = NULL;
2826 SilcPacketContext packetdata;
2828 SilcClientEntry *sent_clients = NULL;
2829 unsigned int sent_clients_count = 0;
2830 SilcServerEntry *routed = NULL;
2831 unsigned int routed_count = 0;
2832 SilcChannelEntry channel;
2833 SilcChannelClientEntry chl, chl2;
2837 unsigned char *data;
2838 unsigned int data_len;
2839 int force_send = FALSE;
2842 if (!silc_list_count(client->channels))
2846 packet = silc_notify_payload_encode(type, argc, ap);
2847 data = packet->data;
2848 data_len = packet->len;
2850 /* Set the packet context pointers. */
2851 packetdata.flags = 0;
2852 packetdata.type = SILC_PACKET_NOTIFY;
2853 packetdata.src_id = silc_id_id2str(server->id, SILC_ID_SERVER);
2854 packetdata.src_id_len = SILC_ID_SERVER_LEN;
2855 packetdata.src_id_type = SILC_ID_SERVER;
2856 packetdata.rng = server->rng;
2858 silc_list_start(client->channels);
2859 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2860 channel = chl->channel;
2862 /* Send the message to all clients on the channel's client list. */
2863 silc_list_start(channel->user_list);
2864 while ((chl2 = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2867 /* Check if we have sent the packet to this client already */
2868 for (k = 0; k < sent_clients_count; k++)
2869 if (sent_clients[k] == c)
2871 if (k < sent_clients_count)
2874 /* If we are router and if this client has router set it is not
2875 locally connected client and we will route the message to the
2876 router set in the client. */
2877 if (c && c->router && server->server_type == SILC_ROUTER) {
2878 /* Check if we have sent the packet to this route already */
2879 for (k = 0; k < routed_count; k++)
2880 if (routed[k] == c->router)
2882 if (k < routed_count)
2885 /* Get data used in packet header encryption, keys and stuff. */
2886 sock = (SilcSocketConnection)c->router->connection;
2887 cipher = c->router->send_key;
2888 hmac = c->router->hmac;
2890 packetdata.dst_id = silc_id_id2str(c->router->id, SILC_ID_SERVER);
2891 packetdata.dst_id_len = SILC_ID_SERVER_LEN;
2892 packetdata.dst_id_type = SILC_ID_SERVER;
2893 packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
2894 packetdata.src_id_len + packetdata.dst_id_len;
2895 packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
2897 /* Send the packet */
2898 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
2900 data_len, FALSE, force_send);
2902 silc_free(packetdata.dst_id);
2904 /* We want to make sure that the packet is routed to same router
2905 only once. Mark this route as sent route. */
2907 routed = silc_realloc(routed, sizeof(*routed) * (k + 1));
2908 routed[k] = c->router;
2914 /* Send to locally connected client */
2917 /* Get data used in packet header encryption, keys and stuff. */
2918 sock = (SilcSocketConnection)c->connection;
2919 cipher = c->send_key;
2922 packetdata.dst_id = silc_id_id2str(c->id, SILC_ID_CLIENT);
2923 packetdata.dst_id_len = SILC_ID_CLIENT_LEN;
2924 packetdata.dst_id_type = SILC_ID_CLIENT;
2925 packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
2926 packetdata.src_id_len + packetdata.dst_id_len;
2927 packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
2929 /* Send the packet */
2930 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
2932 data_len, FALSE, force_send);
2934 silc_free(packetdata.dst_id);
2936 /* Make sure that we send the notify only once per client. */
2937 sent_clients = silc_realloc(sent_clients, sizeof(*sent_clients) *
2938 (sent_clients_count + 1));
2939 sent_clients[sent_clients_count] = c;
2940 sent_clients_count++;
2947 if (sent_clients_count)
2948 silc_free(sent_clients);
2949 silc_free(packetdata.src_id);
2952 /* Sends New ID Payload to remote end. The packet is used to distribute
2953 information about new registered clients, servers, channel etc. usually
2954 to routers so that they can keep these information up to date.
2955 If the argument `broadcast' is TRUE then the packet is sent as
2956 broadcast packet. */
2958 void silc_server_send_new_id(SilcServer server,
2959 SilcSocketConnection sock,
2961 void *id, SilcIdType id_type,
2962 unsigned int id_len)
2966 idp = silc_id_payload_encode(id, id_type);
2967 silc_server_packet_send(server, sock, SILC_PACKET_NEW_ID,
2968 broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
2969 idp->data, idp->len, FALSE);
2970 silc_buffer_free(idp);
2973 /* Sends Replace ID payload to remote end. This is used to replace old
2974 ID with new ID sent in the packet. This is called for example when
2975 user changes nickname and we create new ID for the user. If the
2976 argument `broadcast' is TRUE then the packet is sent as
2977 broadcast packet. */
2978 /* XXX It would be expected that the new id is same type as the old
2981 void silc_server_send_replace_id(SilcServer server,
2982 SilcSocketConnection sock,
2984 void *old_id, SilcIdType old_id_type,
2985 unsigned int old_id_len,
2986 void *new_id, SilcIdType new_id_type,
2987 unsigned int new_id_len)
2993 oid = silc_id_id2str(old_id, old_id_type);
2997 nid = silc_id_id2str(new_id, new_id_type);
3001 packet = silc_buffer_alloc(2 + 2 + 2 + 2 + old_id_len + new_id_len);
3002 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
3003 silc_buffer_format(packet,
3004 SILC_STR_UI_SHORT(old_id_type),
3005 SILC_STR_UI_SHORT(old_id_len),
3006 SILC_STR_UI_XNSTRING(oid, old_id_len),
3007 SILC_STR_UI_SHORT(new_id_type),
3008 SILC_STR_UI_SHORT(new_id_len),
3009 SILC_STR_UI_XNSTRING(nid, new_id_len),
3012 silc_server_packet_send(server, sock, SILC_PACKET_REPLACE_ID,
3013 broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
3014 packet->data, packet->len, FALSE);
3017 silc_buffer_free(packet);
3020 /* This function is used to send Remove Channel User payload. This may sent
3021 by server but is usually used only by router to notify other routers that
3022 user has left a channel. Normal server sends this packet to its router
3023 to notify that the router should not hold a record about this client
3024 on a channel anymore. Router distributes it further to other routers. */
3026 void silc_server_send_remove_channel_user(SilcServer server,
3027 SilcSocketConnection sock,
3029 void *client_id, void *channel_id)
3032 unsigned char *clid, *chid;
3034 clid = silc_id_id2str(client_id, SILC_ID_CLIENT);
3038 chid = silc_id_id2str(channel_id, SILC_ID_CHANNEL);
3042 packet = silc_buffer_alloc(2 + 2 + SILC_ID_CLIENT_LEN + SILC_ID_CHANNEL_LEN);
3043 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
3044 silc_buffer_format(packet,
3045 SILC_STR_UI_SHORT(SILC_ID_CLIENT_LEN),
3046 SILC_STR_UI_XNSTRING(clid, SILC_ID_CLIENT_LEN),
3047 SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
3048 SILC_STR_UI_XNSTRING(chid, SILC_ID_CHANNEL_LEN),
3051 silc_server_packet_send(server, sock, SILC_PACKET_REMOVE_CHANNEL_USER,
3052 broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
3053 packet->data, packet->len, FALSE);
3056 silc_buffer_free(packet);
3059 /* Received packet to replace a ID. This checks that the requested ID
3060 exists and replaces it with the new one. */
3062 void silc_server_replace_id(SilcServer server,
3063 SilcSocketConnection sock,
3064 SilcPacketContext *packet)
3066 SilcBuffer buffer = packet->buffer;
3067 unsigned char *old_id = NULL, *new_id = NULL;
3068 SilcIdType old_id_type, new_id_type;
3069 unsigned short old_id_len, new_id_len;
3070 void *id = NULL, *id2 = NULL;
3072 if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3073 packet->src_id_type == SILC_ID_CLIENT)
3076 SILC_LOG_DEBUG(("Replacing ID"));
3078 silc_buffer_unformat(buffer,
3079 SILC_STR_UI_SHORT(&old_id_type),
3080 SILC_STR_UI16_NSTRING_ALLOC(&old_id, &old_id_len),
3081 SILC_STR_UI_SHORT(&new_id_type),
3082 SILC_STR_UI16_NSTRING_ALLOC(&new_id, &new_id_len),
3085 if (old_id_type != new_id_type)
3088 if (old_id_len != silc_id_get_len(old_id_type) ||
3089 new_id_len != silc_id_get_len(new_id_type))
3092 id = silc_id_str2id(old_id, old_id_type);
3096 id2 = silc_id_str2id(new_id, new_id_type);
3100 /* Replace the old ID */
3101 switch(old_id_type) {
3102 case SILC_ID_CLIENT:
3103 if (silc_idlist_replace_client_id(server->local_list, id, id2) == NULL)
3104 if (server->server_type == SILC_ROUTER)
3105 silc_idlist_replace_client_id(server->global_list, id, id2);
3108 case SILC_ID_SERVER:
3109 if (silc_idlist_replace_server_id(server->local_list, id, id2) == NULL)
3110 if (server->server_type == SILC_ROUTER)
3111 silc_idlist_replace_server_id(server->global_list, id, id2);
3114 case SILC_ID_CHANNEL:
3115 /* XXX Hmm... Basically this cannot occur. Channel ID's cannot be
3134 /* Creates new channel. */
3136 SilcChannelEntry silc_server_new_channel(SilcServer server,
3137 SilcServerID *router_id,
3138 char *cipher, char *channel_name)
3140 int i, channel_len, key_len;
3141 SilcChannelID *channel_id;
3142 SilcChannelEntry entry;
3144 unsigned char channel_key[32], *id_string;
3147 SILC_LOG_DEBUG(("Creating new channel"));
3149 /* Create channel key */
3150 for (i = 0; i < 32; i++)
3151 channel_key[i] = silc_rng_get_byte(server->rng);
3158 silc_cipher_alloc(cipher, &key);
3159 key->cipher->set_key(key->context, channel_key, key_len);
3161 channel_name = strdup(channel_name);
3163 /* Create the channel */
3164 silc_id_create_channel_id(router_id, server->rng, &channel_id);
3165 entry = silc_idlist_add_channel(server->local_list, channel_name,
3166 SILC_CHANNEL_MODE_NONE, channel_id,
3169 silc_free(channel_name);
3173 entry->key = silc_calloc(key_len, sizeof(*entry->key));
3174 entry->key_len = key_len * 8;
3175 memcpy(entry->key, channel_key, key_len);
3176 memset(channel_key, 0, sizeof(channel_key));
3178 /* Notify other routers about the new channel. We send the packet
3179 to our primary route. */
3180 if (server->standalone == FALSE) {
3181 channel_len = strlen(channel_name);
3182 id_string = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3183 packet = silc_buffer_alloc(2 + SILC_ID_CHANNEL_LEN);
3185 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
3186 silc_buffer_format(packet,
3187 SILC_STR_UI_SHORT(channel_len),
3188 SILC_STR_UI_XNSTRING(channel_name, channel_len),
3189 SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
3190 SILC_STR_UI_XNSTRING(id_string, SILC_ID_CHANNEL_LEN),
3193 /* Send the packet to our router. */
3194 silc_server_packet_send(server, (SilcSocketConnection)
3195 server->id_entry->router->connection,
3196 SILC_PACKET_NEW_CHANNEL_USER, 0,
3197 packet->data, packet->len, TRUE);
3199 silc_free(id_string);
3200 silc_buffer_free(packet);
3206 /* Create new client. This processes incoming NEW_CLIENT packet and creates
3207 Client ID for the client. Client becomes registered after calling this
3210 SilcClientEntry silc_server_new_client(SilcServer server,
3211 SilcSocketConnection sock,
3212 SilcPacketContext *packet)
3214 SilcBuffer buffer = packet->buffer;
3215 SilcClientEntry client;
3216 SilcIDCacheEntry cache;
3217 SilcClientID *client_id;
3219 char *username = NULL, *realname = NULL, *id_string;
3221 SILC_LOG_DEBUG(("Creating new client"));
3223 if (sock->type != SILC_SOCKET_TYPE_CLIENT)
3226 /* Take client entry */
3227 client = (SilcClientEntry)sock->user_data;
3229 /* Fetch the old client cache entry so that we can update it. */
3230 if (!silc_idcache_find_by_context(server->local_list->clients,
3231 sock->user_data, &cache)) {
3232 SILC_LOG_ERROR(("Lost client's cache entry - bad thing"));
3236 /* Parse incoming packet */
3237 silc_buffer_unformat(buffer,
3238 SILC_STR_UI16_STRING_ALLOC(&username),
3239 SILC_STR_UI16_STRING_ALLOC(&realname),
3242 /* Create Client ID */
3243 silc_id_create_client_id(server->id, server->rng, server->md5hash,
3244 username, &client_id);
3246 /* Update client entry */
3247 client->registered = TRUE;
3248 client->nickname = strdup(username);
3249 client->username = username;
3250 client->userinfo = realname;
3251 client->id = client_id;
3253 /* Update the cache entry */
3254 cache->id = (void *)client_id;
3255 cache->type = SILC_ID_CLIENT;
3256 cache->data = username;
3257 silc_idcache_sort_by_data(server->local_list->clients);
3259 /* Notify our router about new client on the SILC network */
3260 if (!server->standalone)
3261 silc_server_send_new_id(server, (SilcSocketConnection)
3262 server->id_entry->router->connection,
3263 server->server_type == SILC_SERVER ? TRUE : FALSE,
3264 client->id, SILC_ID_CLIENT, SILC_ID_CLIENT_LEN);
3266 /* Send the new client ID to the client. */
3267 id_string = silc_id_id2str(client->id, SILC_ID_CLIENT);
3268 reply = silc_buffer_alloc(2 + 2 + SILC_ID_CLIENT_LEN);
3269 silc_buffer_pull_tail(reply, SILC_BUFFER_END(reply));
3270 silc_buffer_format(reply,
3271 SILC_STR_UI_SHORT(SILC_ID_CLIENT),
3272 SILC_STR_UI_SHORT(SILC_ID_CLIENT_LEN),
3273 SILC_STR_UI_XNSTRING(id_string, SILC_ID_CLIENT_LEN),
3275 silc_server_packet_send(server, sock, SILC_PACKET_NEW_ID, 0,
3276 reply->data, reply->len, FALSE);
3277 silc_free(id_string);
3278 silc_buffer_free(reply);
3280 /* Send some nice info to the client */
3281 SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3282 ("Welcome to the SILC Network %s@%s",
3283 username, sock->hostname));
3284 SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3285 ("Your host is %s, running version %s",
3286 server->config->server_info->server_name,
3288 SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3289 ("Your connection is secured with %s cipher, "
3290 "key length %d bits",
3291 client->send_key->cipher->name,
3292 client->send_key->cipher->key_len));
3293 SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3294 ("Your current nickname is %s",
3298 silc_server_send_motd(server, sock);
3303 /* Create new server. This processes incoming NEW_SERVER packet and
3304 saves the received Server ID. The server is our locally connected
3305 server thus we save all the information and save it to local list.
3306 This funtion can be used by both normal server and router server.
3307 If normal server uses this it means that its router has connected
3308 to the server. If router uses this it means that one of the cell's
3309 servers is connected to the router. */
3311 SilcServerEntry silc_server_new_server(SilcServer server,
3312 SilcSocketConnection sock,
3313 SilcPacketContext *packet)
3315 SilcBuffer buffer = packet->buffer;
3316 SilcServerEntry new_server;
3317 SilcIDCacheEntry cache;
3318 SilcServerID *server_id;
3319 unsigned char *server_name, *id_string;
3320 unsigned short id_len;
3322 SILC_LOG_DEBUG(("Creating new server"));
3324 if (sock->type != SILC_SOCKET_TYPE_SERVER &&
3325 sock->type != SILC_SOCKET_TYPE_ROUTER)
3328 /* Take server entry */
3329 new_server = (SilcServerEntry)sock->user_data;
3331 /* Fetch the old server cache entry so that we can update it. */
3332 if (!silc_idcache_find_by_context(server->local_list->servers,
3333 sock->user_data, &cache)) {
3334 SILC_LOG_ERROR(("Lost server's cache entry - bad thing"));
3338 /* Parse the incoming packet */
3339 silc_buffer_unformat(buffer,
3340 SILC_STR_UI16_NSTRING_ALLOC(&id_string, &id_len),
3341 SILC_STR_UI16_STRING_ALLOC(&server_name),
3344 if (id_len > buffer->len) {
3345 silc_free(id_string);
3346 silc_free(server_name);
3351 server_id = silc_id_payload_parse_id(id_string, id_len);
3352 silc_free(id_string);
3354 /* Update client entry */
3355 new_server->registered = TRUE;
3356 new_server->server_name = server_name;
3357 new_server->id = server_id;
3359 /* Update the cache entry */
3360 cache->id = (void *)server_id;
3361 cache->type = SILC_ID_SERVER;
3362 cache->data = server_name;
3363 silc_idcache_sort_by_data(server->local_list->servers);
3365 /* Distribute the information about new server in the SILC network
3366 to our router. If we are normal server we won't send anything
3367 since this connection must be our router connection. */
3368 if (server->server_type == SILC_ROUTER && !server->standalone)
3369 silc_server_send_new_id(server, server->id_entry->router->connection,
3370 TRUE, new_server->id, SILC_ID_SERVER,
3371 SILC_ID_SERVER_LEN);
3376 /* Processes incoming New ID Payload. New ID Payload is used to distribute
3377 information about newly registered clients, servers and created
3380 void silc_server_new_id(SilcServer server, SilcSocketConnection sock,
3381 SilcPacketContext *packet)
3383 SilcBuffer buffer = packet->buffer;
3385 SilcServerEntry tmpserver, router;
3386 SilcSocketConnection router_sock;
3391 SILC_LOG_DEBUG(("Processing new ID"));
3393 if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3394 server->server_type == SILC_SERVER ||
3395 packet->src_id_type != SILC_ID_SERVER)
3398 idp = silc_id_payload_parse(buffer);
3402 id_type = silc_id_payload_get_type(idp);
3404 /* Normal server cannot have other normal server connections */
3405 if (id_type == SILC_ID_SERVER && sock->type == SILC_SOCKET_TYPE_SERVER)
3408 id = silc_id_payload_get_id(idp);
3412 /* If the packet is originated from the one who sent it to us we know
3413 that the ID belongs to our cell, unless the sender was router. */
3414 tmpid = silc_id_str2id(packet->src_id, SILC_ID_SERVER);
3415 tmpserver = (SilcServerEntry)sock->user_data;
3417 if (!SILC_ID_SERVER_COMPARE(tmpid, tmpserver->id) &&
3418 sock->type == SILC_SOCKET_TYPE_SERVER) {
3419 id_list = server->local_list;
3421 router = sock->user_data;
3422 /* router = server->id_entry; */
3424 id_list = server->global_list;
3425 router_sock = (SilcSocketConnection)server->id_entry->router->connection;
3426 router = server->id_entry->router;
3432 case SILC_ID_CLIENT:
3434 SilcClientEntry idlist;
3436 /* Add the client to our local list. We are router and we keep
3437 cell specific local database of all clients in the cell. */
3438 idlist = silc_idlist_add_client(id_list, NULL, NULL, NULL,
3439 id, router, NULL, NULL,
3440 NULL, NULL, NULL, router_sock);
3444 case SILC_ID_SERVER:
3446 SilcServerEntry idlist;
3448 /* Add the server to our local list. We are router and we keep
3449 cell specific local database of all servers in the cell. */
3450 idlist = silc_idlist_add_server(id_list, NULL, 0,
3451 id, router, NULL, NULL,
3452 NULL, NULL, NULL, router_sock);
3456 case SILC_ID_CHANNEL:
3457 /* Add the channel to our local list. We are router and we keep
3458 cell specific local database of all channels in the cell. */
3459 silc_idlist_add_channel(id_list, NULL, 0, id, router, NULL);
3467 silc_id_payload_free(idp);
3470 /* Received packet to remove a user from a channel. Routers notify other
3471 routers that user has left a channel. Client must not send this packet.
3472 Normal server may send this packet but ignores if it receives one. */
3474 void silc_server_remove_channel_user(SilcServer server,
3475 SilcSocketConnection sock,
3476 SilcPacketContext *packet)
3478 SilcBuffer buffer = packet->buffer;
3479 unsigned char *tmp1 = NULL, *tmp2 = NULL;
3480 SilcClientID *client_id = NULL;
3481 SilcChannelID *channel_id = NULL;
3482 SilcChannelEntry channel;
3483 SilcClientEntry client;
3485 SILC_LOG_DEBUG(("Removing user from channel"));
3487 if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3488 server->server_type == SILC_SERVER)
3491 silc_buffer_unformat(buffer,
3492 SILC_STR_UI16_STRING_ALLOC(&tmp1),
3493 SILC_STR_UI16_STRING_ALLOC(&tmp2),
3499 client_id = silc_id_str2id(tmp1, SILC_ID_CLIENT);
3500 channel_id = silc_id_str2id(tmp2, SILC_ID_CHANNEL);
3501 if (!client_id || !channel_id)
3504 /* XXX routers should check server->global_list as well */
3505 /* Get channel entry */
3506 channel = silc_idlist_find_channel_by_id(server->local_list, channel_id);
3510 /* XXX routers should check server->global_list as well */
3511 /* Get client entry */
3512 client = silc_idlist_find_client_by_id(server->local_list, client_id);
3516 /* Remove from channel */
3517 silc_server_remove_from_one_channel(server, sock, channel, client, FALSE);
3525 silc_free(client_id);
3527 silc_free(channel_id);