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 = TRUE;
58 server->local_list = silc_calloc(1, sizeof(*server->local_list));
59 server->global_list = silc_calloc(1, sizeof(*server->global_list));
60 server->pending_commands = silc_dlist_init();
62 server->sim = silc_dlist_init();
70 /* Free's the SILC server object. This is called at the very end before
73 void silc_server_free(SilcServer server)
78 if (server->local_list)
79 silc_free(server->local_list);
80 if (server->global_list)
81 silc_free(server->global_list);
83 silc_rng_free(server->rng);
85 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
86 silc_dlist_del(server->sim, sim);
89 silc_dlist_uninit(server->sim);
92 silc_free(server->params);
94 if (server->pending_commands)
95 silc_dlist_uninit(server->pending_commands);
97 silc_math_primegen_uninit(); /* XXX */
102 /* Initializes the entire SILC server. This is called always before running
103 the server. This is called only once at the initialization of the program.
104 This binds the server to its listenning port. After this function returns
105 one should call silc_server_run to start the server. This returns TRUE
106 when everything is ok to run the server. Configuration file must be
107 read and parsed before calling this. */
109 int silc_server_init(SilcServer server)
111 int *sock = NULL, sock_count = 0, i;
113 SilcServerEntry id_entry;
115 SILC_LOG_DEBUG(("Initializing server"));
117 assert(server->config);
119 /* XXX After server is made as Silc Server Library this can be given
120 as argument, for now this is hard coded */
121 server->params = silc_calloc(1, sizeof(*server->params));
122 server->params->retry_count = SILC_SERVER_RETRY_COUNT;
123 server->params->retry_interval_min = SILC_SERVER_RETRY_INTERVAL_MIN;
124 server->params->retry_interval_max = SILC_SERVER_RETRY_INTERVAL_MAX;
125 server->params->retry_keep_trying = FALSE;
126 server->params->protocol_timeout = 60;
128 /* Set log files where log message should be saved. */
129 server->config->server = server;
130 silc_config_server_setlogfiles(server->config);
132 /* Register all configured ciphers, PKCS and hash functions. */
133 silc_config_server_register_ciphers(server->config);
134 silc_config_server_register_pkcs(server->config);
135 silc_config_server_register_hashfuncs(server->config);
137 /* Initialize random number generator for the server. */
138 server->rng = silc_rng_alloc();
139 silc_rng_init(server->rng);
140 silc_math_primegen_init(); /* XXX */
142 /* Initialize hash functions for server to use */
143 silc_hash_alloc("md5", &server->md5hash);
144 silc_hash_alloc("sha1", &server->sha1hash);
146 /* Initialize none cipher */
147 silc_cipher_alloc("none", &server->none_cipher);
149 /* XXXXX Generate RSA key pair */
151 unsigned char *public_key;
152 unsigned char *private_key;
153 unsigned int pk_len, prv_len;
156 if (stat("pubkey.pub", &st) < 0 && stat("privkey.prv", &st) < 0) {
158 if (silc_pkcs_alloc("rsa", &server->pkcs) == FALSE) {
159 SILC_LOG_ERROR(("Could not create RSA key pair"));
163 if (server->pkcs->pkcs->init(server->pkcs->context,
164 1024, server->rng) == FALSE) {
165 SILC_LOG_ERROR(("Could not generate RSA key pair"));
169 public_key = server->pkcs->pkcs->get_public_key(server->pkcs->context,
171 private_key = server->pkcs->pkcs->get_private_key(server->pkcs->context,
174 SILC_LOG_HEXDUMP(("public key"), public_key, pk_len);
175 SILC_LOG_HEXDUMP(("private key"), private_key, prv_len);
178 silc_pkcs_public_key_alloc("rsa", "UN=root, HN=dummy",
180 server->private_key =
181 silc_pkcs_private_key_alloc("rsa", private_key, prv_len);
184 silc_pkcs_save_public_key("pubkey.pub", server->public_key,
186 silc_pkcs_save_private_key("privkey.prv", server->private_key, NULL,
189 memset(public_key, 0, pk_len);
190 memset(private_key, 0, prv_len);
191 silc_free(public_key);
192 silc_free(private_key);
194 silc_pkcs_load_public_key("pubkey.pub", &server->public_key,
196 silc_pkcs_load_private_key("privkey.prv", &server->private_key,
201 /* Create a listening server. Note that our server can listen on
202 multiple ports. All listeners are created here and now. */
203 /* XXX Still check this whether to use server_info or listen_port. */
205 while(server->config->listen_port) {
208 tmp = silc_net_create_server(server->config->listen_port->port,
209 server->config->listen_port->host);
213 sock = silc_realloc(sock, (sizeof(int *) * (sock_count + 1)));
214 sock[sock_count] = tmp;
215 server->config->listen_port = server->config->listen_port->next;
219 /* Initialize ID caches */
220 server->local_list->clients = silc_idcache_alloc(0);
221 server->local_list->servers = silc_idcache_alloc(0);
222 server->local_list->channels = silc_idcache_alloc(0);
224 /* XXX for now these are allocated for normal server as well as these
225 hold some global information that the server has fetched from its
226 router. For router these are used as they are supposed to be used
227 on router. The XXX can be remoevd later if this is the way we are
228 going to do this in the normal server as well. */
229 server->global_list->clients = silc_idcache_alloc(0);
230 server->global_list->servers = silc_idcache_alloc(0);
231 server->global_list->channels = silc_idcache_alloc(0);
233 /* Allocate the entire socket list that is used in server. Eventually
234 all connections will have entry in this table (it is a table of
235 pointers to the actual object that is allocated individually
237 server->sockets = silc_calloc(SILC_SERVER_MAX_CONNECTIONS,
238 sizeof(*server->sockets));
240 for (i = 0; i < sock_count; i++) {
241 SilcSocketConnection newsocket = NULL;
243 /* Set socket to non-blocking mode */
244 silc_net_set_socket_nonblock(sock[i]);
245 server->sock = sock[i];
247 /* Create a Server ID for the server. */
248 silc_id_create_server_id(sock[i], server->rng, &id);
254 server->id_type = SILC_ID_SERVER;
255 server->server_name = server->config->server_info->server_name;
257 /* Add ourselves to the server list. We don't have a router yet
258 beacuse we haven't established a route yet. It will be done later.
259 For now, NULL is sent as router. This allocates new entry to
262 silc_idlist_add_server(server->local_list,
263 server->config->server_info->server_name,
264 server->server_type, server->id, NULL, NULL);
266 SILC_LOG_ERROR(("Could not add ourselves to cache"));
270 /* Add ourselves also to the socket table. The entry allocated above
271 is sent as argument for fast referencing in the future. */
272 silc_socket_alloc(sock[i], SILC_SOCKET_TYPE_SERVER, id_entry,
277 server->sockets[sock[i]] = newsocket;
279 /* Put the allocated socket pointer also to the entry allocated above
280 for fast back-referencing to the socket list. */
281 id_entry->connection = (void *)server->sockets[sock[i]];
282 server->id_entry = id_entry;
285 /* Register the task queues. In SILC we have by default three task queues.
286 One task queue for non-timeout tasks which perform different kind of
287 I/O on file descriptors, timeout task queue for timeout tasks, and,
288 generic non-timeout task queue whose tasks apply to all connections. */
289 silc_task_queue_alloc(&server->io_queue, TRUE);
290 if (!server->io_queue) {
293 silc_task_queue_alloc(&server->timeout_queue, TRUE);
294 if (!server->timeout_queue) {
297 silc_task_queue_alloc(&server->generic_queue, TRUE);
298 if (!server->generic_queue) {
302 /* Register protocols */
303 silc_server_protocols_register();
305 /* Initialize the scheduler */
306 silc_schedule_init(&server->io_queue, &server->timeout_queue,
307 &server->generic_queue,
308 SILC_SERVER_MAX_CONNECTIONS);
310 /* Add the first task to the queue. This is task that is executed by
311 timeout. It expires as soon as the caller calls silc_server_run. This
312 task performs authentication protocol and key exchange with our
314 silc_task_register(server->timeout_queue, sock[0],
315 silc_server_connect_to_router,
316 (void *)server, 0, 1,
318 SILC_TASK_PRI_NORMAL);
320 /* Add listener task to the queue. This task receives new connections to the
321 server. This task remains on the queue until the end of the program. */
322 silc_task_register(server->io_queue, sock[0],
323 silc_server_accept_new_connection,
324 (void *)server, 0, 0,
326 SILC_TASK_PRI_NORMAL);
327 server->listenning = TRUE;
329 /* If server connections has been configured then we must be router as
330 normal server cannot have server connections, only router connections. */
331 if (server->config->servers)
332 server->server_type = SILC_ROUTER;
334 SILC_LOG_DEBUG(("Server initialized"));
336 /* We are done here, return succesfully */
339 silc_task_queue_free(server->timeout_queue);
341 silc_task_queue_free(server->io_queue);
343 for (i = 0; i < sock_count; i++)
344 silc_net_close_server(sock[i]);
349 /* Stops the SILC server. This function is used to shutdown the server.
350 This is usually called after the scheduler has returned. After stopping
351 the server one should call silc_server_free. */
353 void silc_server_stop(SilcServer server)
355 SILC_LOG_DEBUG(("Stopping server"));
357 /* Stop the scheduler, although it might be already stopped. This
358 doesn't hurt anyone. This removes all the tasks and task queues,
360 silc_schedule_stop();
361 silc_schedule_uninit();
363 silc_server_protocols_unregister();
365 SILC_LOG_DEBUG(("Server stopped"));
368 /* The heart of the server. This runs the scheduler thus runs the server. */
370 void silc_server_run(SilcServer server)
372 SILC_LOG_DEBUG(("Running server"));
374 /* Start the scheduler, the heart of the SILC server. When this returns
375 the program will be terminated. */
379 /* Timeout callback that will be called to retry connecting to remote
380 router. This is used by both normal and router server. This will wait
381 before retrying the connecting. The timeout is generated by exponential
382 backoff algorithm. */
384 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
386 SilcServerConnection sconn = (SilcServerConnection)context;
387 SilcServer server = sconn->server;
389 SILC_LOG_INFO(("Retrying connecting to a router"));
391 /* Calculate next timeout */
392 if (sconn->retry_count >= 1) {
393 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
394 if (sconn->retry_timeout > SILC_SERVER_RETRY_INTERVAL_MAX)
395 sconn->retry_timeout = SILC_SERVER_RETRY_INTERVAL_MAX;
397 sconn->retry_timeout = server->params->retry_interval_min;
399 sconn->retry_count++;
400 sconn->retry_timeout = sconn->retry_timeout +
401 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
403 /* If we've reached max retry count, give up. */
404 if (sconn->retry_count > server->params->retry_count &&
405 server->params->retry_keep_trying == FALSE) {
406 SILC_LOG_ERROR(("Could not connect to router, giving up"));
410 /* Wait one before retrying */
411 silc_task_register(server->timeout_queue, fd, silc_server_connect_router,
412 context, sconn->retry_timeout,
413 server->params->retry_interval_min_usec,
414 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
417 /* Generic routine to use connect to a router. */
419 SILC_TASK_CALLBACK(silc_server_connect_router)
421 SilcServerConnection sconn = (SilcServerConnection)context;
422 SilcServer server = sconn->server;
423 SilcSocketConnection newsocket;
424 SilcProtocol protocol;
425 SilcServerKEInternalContext *proto_ctx;
428 /* Connect to remote host */
429 sock = silc_net_create_connection(sconn->remote_port,
432 SILC_LOG_ERROR(("Could not connect to router"));
433 silc_task_register(server->timeout_queue, fd,
434 silc_server_connect_to_router_retry,
435 context, 0, 1, SILC_TASK_TIMEOUT,
436 SILC_TASK_PRI_NORMAL);
440 /* Set socket options */
441 silc_net_set_socket_nonblock(sock);
442 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
444 /* Create socket connection for the connection. Even though we
445 know that we are connecting to a router we will mark the socket
446 to be unknown connection until we have executed authentication
448 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
449 server->sockets[sock] = newsocket;
450 newsocket->hostname = sconn->remote_host;
451 newsocket->port = sconn->remote_port;
452 sconn->sock = newsocket;
454 /* Allocate internal protocol context. This is sent as context
456 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
457 proto_ctx->server = (void *)server;
458 proto_ctx->context = (void *)sconn;
459 proto_ctx->sock = newsocket;
460 proto_ctx->rng = server->rng;
461 proto_ctx->responder = FALSE;
463 /* Perform key exchange protocol. silc_server_connect_to_router_second
464 will be called after the protocol is finished. */
465 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
466 &protocol, proto_ctx,
467 silc_server_connect_to_router_second);
468 newsocket->protocol = protocol;
470 /* Register a timeout task that will be executed if the protocol
471 is not executed within set limit. */
472 proto_ctx->timeout_task =
473 silc_task_register(server->timeout_queue, sock,
474 silc_server_timeout_remote,
475 server, server->params->protocol_timeout,
476 server->params->protocol_timeout_usec,
480 /* Register the connection for network input and output. This sets
481 that scheduler will listen for incoming packets for this connection
482 and sets that outgoing packets may be sent to this connection as
483 well. However, this doesn't set the scheduler for outgoing traffic,
484 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
485 later when outgoing data is available. */
486 context = (void *)server;
487 SILC_REGISTER_CONNECTION_FOR_IO(sock);
489 /* Run the protocol */
490 protocol->execute(server->timeout_queue, 0, protocol, sock, 0, 0);
493 /* This function connects to our primary router or if we are a router this
494 establishes all our primary routes. This is called at the start of the
495 server to do authentication and key exchange with our router - called
498 SILC_TASK_CALLBACK(silc_server_connect_to_router)
500 SilcServer server = (SilcServer)context;
501 SilcServerConnection sconn;
503 SILC_LOG_DEBUG(("Connecting to router(s)"));
505 /* If we are normal SILC server we need to connect to our cell's
507 if (server->server_type == SILC_SERVER) {
508 SILC_LOG_DEBUG(("We are normal server"));
510 /* Create connection to the router, if configured. */
511 if (server->config->routers) {
513 /* Allocate connection object for hold connection specific stuff. */
514 sconn = silc_calloc(1, sizeof(*sconn));
515 sconn->server = server;
516 sconn->remote_host = server->config->routers->host;
517 sconn->remote_port = server->config->routers->port;
519 silc_task_register(server->timeout_queue, fd,
520 silc_server_connect_router,
521 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
522 SILC_TASK_PRI_NORMAL);
527 /* If we are a SILC router we need to establish all of our primary
529 if (server->server_type == SILC_ROUTER) {
530 SilcConfigServerSectionServerConnection *ptr;
532 SILC_LOG_DEBUG(("We are router"));
534 /* Create the connections to all our routes */
535 ptr = server->config->routers;
538 SILC_LOG_DEBUG(("Router connection [%s] %s:%d",
539 ptr->initiator ? "Initiator" : "Responder",
540 ptr->host, ptr->port));
542 if (ptr->initiator) {
543 /* Allocate connection object for hold connection specific stuff. */
544 sconn = silc_calloc(1, sizeof(*sconn));
545 sconn->server = server;
546 sconn->remote_host = ptr->host;
547 sconn->remote_port = ptr->port;
549 silc_task_register(server->timeout_queue, fd,
550 silc_server_connect_router,
551 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
552 SILC_TASK_PRI_NORMAL);
562 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
564 /* There wasn't a configured router, we will continue but we don't
565 have a connection to outside world. We will be standalone server. */
566 server->standalone = TRUE;
569 /* Second part of connecting to router(s). Key exchange protocol has been
570 executed and now we will execute authentication protocol. */
572 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
574 SilcProtocol protocol = (SilcProtocol)context;
575 SilcServerKEInternalContext *ctx =
576 (SilcServerKEInternalContext *)protocol->context;
577 SilcServer server = (SilcServer)ctx->server;
578 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
579 SilcSocketConnection sock = NULL;
580 SilcServerConnAuthInternalContext *proto_ctx;
582 SILC_LOG_DEBUG(("Start"));
584 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
585 /* Error occured during protocol */
586 silc_protocol_free(protocol);
588 silc_buffer_free(ctx->packet);
590 silc_ske_free(ctx->ske);
592 silc_free(ctx->dest_id);
594 sock->protocol = NULL;
595 silc_server_disconnect_remote(server, sock, "Server closed connection: "
596 "Key exchange failed");
600 /* Allocate internal context for the authentication protocol. This
601 is sent as context for the protocol. */
602 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
603 proto_ctx->server = (void *)server;
604 proto_ctx->context = (void *)sconn;
605 proto_ctx->sock = sock = server->sockets[fd];
606 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
607 proto_ctx->dest_id_type = ctx->dest_id_type;
608 proto_ctx->dest_id = ctx->dest_id;
610 /* Resolve the authentication method used in this connection */
611 proto_ctx->auth_meth = SILC_PROTOCOL_CONN_AUTH_PASSWORD;
612 if (server->config->routers) {
613 SilcConfigServerSectionServerConnection *conn = NULL;
615 /* Check if we find a match from user configured connections */
616 conn = silc_config_server_find_router_conn(server->config,
620 /* Match found. Use the configured authentication method */
621 proto_ctx->auth_meth = conn->auth_meth;
622 if (conn->auth_data) {
623 proto_ctx->auth_data = strdup(conn->auth_data);
624 proto_ctx->auth_data_len = strlen(conn->auth_data);
627 /* No match found. */
634 /* Free old protocol as it is finished now */
635 silc_protocol_free(protocol);
637 silc_buffer_free(ctx->packet);
639 sock->protocol = NULL;
641 /* Allocate the authentication protocol. This is allocated here
642 but we won't start it yet. We will be receiving party of this
643 protocol thus we will wait that connecting party will make
645 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
646 &sock->protocol, proto_ctx,
647 silc_server_connect_to_router_final);
649 /* Register timeout task. If the protocol is not executed inside
650 this timelimit the connection will be terminated. Currently
651 this is 15 seconds and is hard coded limit (XXX). */
652 proto_ctx->timeout_task =
653 silc_task_register(server->timeout_queue, sock->sock,
654 silc_server_timeout_remote,
655 (void *)server, 15, 0,
659 /* Run the protocol */
660 sock->protocol->execute(server->timeout_queue, 0,
661 sock->protocol, sock->sock, 0, 0);
664 /* Finalizes the connection to router. Registers a server task to the
665 queue so that we can accept new connections. */
667 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
669 SilcProtocol protocol = (SilcProtocol)context;
670 SilcServerConnAuthInternalContext *ctx =
671 (SilcServerConnAuthInternalContext *)protocol->context;
672 SilcServer server = (SilcServer)ctx->server;
673 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
674 SilcSocketConnection sock = ctx->sock;
675 SilcServerEntry id_entry;
677 unsigned char *id_string;
679 SILC_LOG_DEBUG(("Start"));
681 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
682 /* Error occured during protocol */
684 silc_free(ctx->dest_id);
685 silc_server_disconnect_remote(server, sock, "Server closed connection: "
686 "Authentication failed");
690 /* Add a task to the queue. This task receives new connections to the
691 server. This task remains on the queue until the end of the program. */
692 if (!server->listenning) {
693 silc_task_register(server->io_queue, server->sock,
694 silc_server_accept_new_connection,
695 (void *)server, 0, 0,
697 SILC_TASK_PRI_NORMAL);
698 server->listenning = TRUE;
701 /* Send NEW_SERVER packet to the router. We will become registered
702 to the SILC network after sending this packet. */
703 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
704 packet = silc_buffer_alloc(2 + 2 + SILC_ID_SERVER_LEN +
705 strlen(server->server_name));
706 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
707 silc_buffer_format(packet,
708 SILC_STR_UI_SHORT(SILC_ID_SERVER_LEN),
709 SILC_STR_UI_XNSTRING(id_string, SILC_ID_SERVER_LEN),
710 SILC_STR_UI_SHORT(strlen(server->server_name)),
711 SILC_STR_UI_XNSTRING(server->server_name,
712 strlen(server->server_name)),
715 /* Send the packet */
716 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
717 packet->data, packet->len, TRUE);
718 silc_buffer_free(packet);
719 silc_free(id_string);
721 SILC_LOG_DEBUG(("Connected to router %s", sock->hostname));
723 /* Add the connected router to local server list */
724 server->standalone = FALSE;
725 id_entry = silc_idlist_add_server(server->local_list,
726 sock->hostname ? sock->hostname : sock->ip,
727 SILC_ROUTER, ctx->dest_id, NULL, sock);
730 silc_free(ctx->dest_id);
731 silc_server_disconnect_remote(server, sock, "Server closed connection: "
732 "Authentication failed");
736 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
737 silc_free(sock->user_data);
738 sock->user_data = (void *)id_entry;
739 sock->type = SILC_SOCKET_TYPE_ROUTER;
740 server->id_entry->router = id_entry;
743 /* Free the temporary connection data context */
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;
926 void *id_entry = NULL;
928 SILC_LOG_DEBUG(("Start"));
930 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
931 /* Error occured during protocol */
932 silc_protocol_free(protocol);
934 silc_buffer_free(ctx->packet);
936 silc_ske_free(ctx->ske);
938 silc_free(ctx->dest_id);
941 sock->protocol = NULL;
942 silc_server_disconnect_remote(server, sock, "Server closed connection: "
943 "Authentication failed");
947 sock->type = ctx->conn_type;
949 case SILC_SOCKET_TYPE_CLIENT:
951 SilcClientEntry client;
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. */
960 client = silc_idlist_add_client(server->local_list,
961 NULL, NULL, NULL, NULL, NULL, sock);
963 SILC_LOG_ERROR(("Could not add new client to cache"));
964 silc_free(sock->user_data);
968 id_entry = (void *)client;
971 case SILC_SOCKET_TYPE_SERVER:
972 case SILC_SOCKET_TYPE_ROUTER:
974 SilcServerEntry new_server;
976 SILC_LOG_DEBUG(("Remote host is %s",
977 sock->type == SILC_SOCKET_TYPE_SERVER ?
978 "server" : "router"));
979 SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
980 sock->ip, sock->type == SILC_SOCKET_TYPE_SERVER ?
981 "server" : "router"));
983 /* Add the server into server cache. The server name and Server ID
984 is updated after we have received NEW_SERVER packet from the
987 silc_idlist_add_server(server->local_list, NULL,
988 sock->type == SILC_SOCKET_TYPE_SERVER ?
989 SILC_SERVER : SILC_ROUTER, NULL, NULL, sock);
991 SILC_LOG_ERROR(("Could not add new server to cache"));
992 silc_free(sock->user_data);
996 id_entry = (void *)new_server;
998 /* There is connection to other server now, if it is router then
999 we will have connection to outside world. If we are router but
1000 normal server connected to us then we will remain standalone,
1001 if we are standlone. */
1002 if (server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER) {
1003 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1004 server->standalone = FALSE;
1005 if (!server->id_entry->router)
1006 server->id_entry->router = id_entry;
1014 /* Add the common data structure to the ID entry. */
1016 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1018 /* Add to sockets internal pointer for fast referencing */
1019 silc_free(sock->user_data);
1020 sock->user_data = id_entry;
1022 /* Connection has been fully established now. Everything is ok. */
1023 SILC_LOG_DEBUG(("New connection authenticated"));
1025 silc_protocol_free(protocol);
1027 silc_buffer_free(ctx->packet);
1029 silc_ske_free(ctx->ske);
1031 silc_free(ctx->dest_id);
1033 sock->protocol = NULL;
1036 /* Internal routine that sends packet or marks packet to be sent. This
1037 is used directly only in special cases. Normal cases should use
1038 silc_server_packet_send. Returns < 0 error. */
1040 static int silc_server_packet_send_real(SilcServer server,
1041 SilcSocketConnection sock,
1046 /* Send the packet */
1047 ret = silc_packet_send(sock, force_send);
1051 /* Mark that there is some outgoing data available for this connection.
1052 This call sets the connection both for input and output (the input
1053 is set always and this call keeps the input setting, actually).
1054 Actual data sending is performed by silc_server_packet_process. */
1055 SILC_SET_CONNECTION_FOR_OUTPUT(sock->sock);
1057 /* Mark to socket that data is pending in outgoing buffer. This flag
1058 is needed if new data is added to the buffer before the earlier
1059 put data is sent to the network. */
1060 SILC_SET_OUTBUF_PENDING(sock);
1066 SilcPacketContext *packetdata;
1068 SilcSocketConnection sock;
1071 } SilcServerInternalPacket;
1073 /* This function is used to read packets from network and send packets to
1074 network. This is usually a generic task. */
1076 SILC_TASK_CALLBACK(silc_server_packet_process)
1078 SilcServer server = (SilcServer)context;
1079 SilcSocketConnection sock = server->sockets[fd];
1080 SilcIDListData idata;
1081 SilcCipher cipher = NULL;
1082 SilcHmac hmac = NULL;
1085 SILC_LOG_DEBUG(("Processing packet"));
1087 /* Packet sending */
1088 if (type == SILC_TASK_WRITE) {
1089 SILC_LOG_DEBUG(("Writing data to connection"));
1091 if (sock->outbuf->data - sock->outbuf->head)
1092 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1094 ret = silc_server_packet_send_real(server, sock, TRUE);
1096 /* If returned -2 could not write to connection now, will do
1101 /* The packet has been sent and now it is time to set the connection
1102 back to only for input. When there is again some outgoing data
1103 available for this connection it will be set for output as well.
1104 This call clears the output setting and sets it only for input. */
1105 SILC_SET_CONNECTION_FOR_INPUT(fd);
1106 SILC_UNSET_OUTBUF_PENDING(sock);
1108 silc_buffer_clear(sock->outbuf);
1112 /* Packet receiving */
1113 SILC_LOG_DEBUG(("Reading data from connection"));
1115 /* Read some data from connection */
1116 ret = silc_packet_receive(sock);
1122 SILC_LOG_DEBUG(("Read EOF"));
1124 /* If connection is disconnecting already we will finally
1125 close the connection */
1126 if (SILC_IS_DISCONNECTING(sock)) {
1127 if (sock->user_data)
1128 silc_server_free_sock_user_data(server, sock);
1129 silc_server_close_connection(server, sock);
1133 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1135 if (sock->user_data)
1136 silc_server_free_sock_user_data(server, sock);
1137 silc_server_close_connection(server, sock);
1141 /* If connection is disconnecting or disconnected we will ignore
1143 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1144 SILC_LOG_DEBUG(("Ignoring read data from invalid connection"));
1148 /* Get keys and stuff from ID entry */
1149 idata = (SilcIDListData)sock->user_data;
1151 idata->last_receive = time(NULL);
1152 cipher = idata->receive_key;
1156 /* Process the packet. This will call the parser that will then
1157 decrypt and parse the packet. */
1158 silc_packet_receive_process(sock, cipher, hmac, silc_server_packet_parse,
1162 /* Parses whole packet, received earlier. */
1164 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1166 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1167 SilcServer server = (SilcServer)parse_ctx->context;
1168 SilcSocketConnection sock = parse_ctx->sock;
1169 SilcPacketContext *packet = parse_ctx->packet;
1170 SilcBuffer buffer = packet->buffer;
1173 SILC_LOG_DEBUG(("Start"));
1175 /* Decrypt the received packet */
1176 ret = silc_packet_decrypt(parse_ctx->cipher, parse_ctx->hmac,
1182 /* Parse the packet. Packet type is returned. */
1183 ret = silc_packet_parse(packet);
1185 /* Parse the packet header in special way as this is "special"
1187 ret = silc_packet_parse_special(packet);
1190 if (ret == SILC_PACKET_NONE)
1193 /* Broadcast packet if it is marked as broadcast packet and it is
1194 originated from router and we are router. */
1195 if (server->server_type == SILC_ROUTER &&
1196 sock->type == SILC_SOCKET_TYPE_ROUTER &&
1197 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
1198 silc_server_packet_broadcast(server, server->id_entry->router->connection,
1202 /* Parse the incoming packet type */
1203 silc_server_packet_parse_type(server, sock, packet);
1206 silc_buffer_clear(sock->inbuf);
1208 silc_free(packet->src_id);
1210 silc_free(packet->dst_id);
1212 silc_free(parse_ctx);
1215 /* Parser callback called by silc_packet_receive_process. This merely
1216 registers timeout that will handle the actual parsing when appropriate. */
1218 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1220 SilcServer server = (SilcServer)parser_context->context;
1221 SilcSocketConnection sock = parser_context->sock;
1223 switch (sock->type) {
1224 case SILC_SOCKET_TYPE_CLIENT:
1225 case SILC_SOCKET_TYPE_UNKNOWN:
1226 /* Parse the packet with timeout */
1227 silc_task_register(server->timeout_queue, sock->sock,
1228 silc_server_packet_parse_real,
1229 (void *)parser_context, 0, 100000,
1231 SILC_TASK_PRI_NORMAL);
1233 case SILC_SOCKET_TYPE_SERVER:
1234 case SILC_SOCKET_TYPE_ROUTER:
1235 /* Packets from servers are parsed as soon as possible */
1236 silc_task_register(server->timeout_queue, sock->sock,
1237 silc_server_packet_parse_real,
1238 (void *)parser_context, 0, 1,
1240 SILC_TASK_PRI_NORMAL);
1247 /* Parses the packet type and calls what ever routines the packet type
1248 requires. This is done for all incoming packets. */
1250 void silc_server_packet_parse_type(SilcServer server,
1251 SilcSocketConnection sock,
1252 SilcPacketContext *packet)
1254 SilcBuffer buffer = packet->buffer;
1255 SilcPacketType type = packet->type;
1257 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1259 /* Parse the packet type */
1261 case SILC_PACKET_DISCONNECT:
1262 SILC_LOG_DEBUG(("Disconnect packet"));
1264 case SILC_PACKET_SUCCESS:
1266 * Success received for something. For now we can have only
1267 * one protocol for connection executing at once hence this
1268 * success message is for whatever protocol is executing currently.
1270 SILC_LOG_DEBUG(("Success packet"));
1271 if (sock->protocol) {
1272 sock->protocol->execute(server->timeout_queue, 0,
1273 sock->protocol, sock->sock, 0, 0);
1276 case SILC_PACKET_FAILURE:
1278 * Failure received for something. For now we can have only
1279 * one protocol for connection executing at once hence this
1280 * failure message is for whatever protocol is executing currently.
1282 SILC_LOG_DEBUG(("Failure packet"));
1283 if (sock->protocol) {
1284 /* XXX Audit the failure type */
1285 sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
1286 sock->protocol->execute(server->timeout_queue, 0,
1287 sock->protocol, sock->sock, 0, 0);
1290 case SILC_PACKET_REJECT:
1291 SILC_LOG_DEBUG(("Reject packet"));
1298 case SILC_PACKET_CHANNEL_MESSAGE:
1300 * Received channel message. Channel messages are special packets
1301 * (although probably most common ones) hence they are handled
1304 SILC_LOG_DEBUG(("Channel Message packet"));
1305 silc_server_channel_message(server, sock, packet);
1308 case SILC_PACKET_CHANNEL_KEY:
1310 * Received key for channel. As channels are created by the router
1311 * the keys are as well. We will distribute the key to all of our
1312 * locally connected clients on the particular channel. Router
1313 * never receives this channel and thus is ignored.
1315 SILC_LOG_DEBUG(("Channel Key packet"));
1316 silc_server_channel_key(server, sock, packet);
1322 case SILC_PACKET_COMMAND:
1324 * Recived command. Allocate command context and execute the command.
1326 SILC_LOG_DEBUG(("Command packet"));
1327 silc_server_command_process(server, sock, packet);
1330 case SILC_PACKET_COMMAND_REPLY:
1332 * Received command reply packet. Servers never send commands thus
1333 * they don't receive command reply packets either, except in cases
1334 * where server has forwarded command packet coming from client.
1335 * This must be the case here or we will ignore the packet.
1337 SILC_LOG_DEBUG(("Command Reply packet"));
1338 silc_server_packet_relay_command_reply(server, sock, packet);
1342 * Private Message packets
1344 case SILC_PACKET_PRIVATE_MESSAGE:
1346 * Received private message packet. The packet is coming from either
1349 SILC_LOG_DEBUG(("Private Message packet"));
1350 silc_server_private_message(server, sock, packet);
1353 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1357 * Key Exchange protocol packets
1359 case SILC_PACKET_KEY_EXCHANGE:
1360 SILC_LOG_DEBUG(("KE packet"));
1361 if (sock->protocol && sock->protocol->protocol->type
1362 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1364 SilcServerKEInternalContext *proto_ctx =
1365 (SilcServerKEInternalContext *)sock->protocol->context;
1367 proto_ctx->packet = buffer;
1369 /* Let the protocol handle the packet */
1370 sock->protocol->execute(server->timeout_queue, 0,
1371 sock->protocol, sock->sock, 0, 100000);
1373 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1374 "protocol active, packet dropped."));
1376 /* XXX Trigger KE protocol?? Rekey actually, maybe. */
1380 case SILC_PACKET_KEY_EXCHANGE_1:
1381 SILC_LOG_DEBUG(("KE 1 packet"));
1382 if (sock->protocol && sock->protocol->protocol->type
1383 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1385 SilcServerKEInternalContext *proto_ctx =
1386 (SilcServerKEInternalContext *)sock->protocol->context;
1388 if (proto_ctx->packet)
1389 silc_buffer_free(proto_ctx->packet);
1391 proto_ctx->packet = buffer;
1392 proto_ctx->dest_id_type = packet->src_id_type;
1393 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_type);
1395 /* Let the protocol handle the packet */
1396 sock->protocol->execute(server->timeout_queue, 0,
1397 sock->protocol, sock->sock,
1400 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1401 "protocol active, packet dropped."));
1405 case SILC_PACKET_KEY_EXCHANGE_2:
1406 SILC_LOG_DEBUG(("KE 2 packet"));
1407 if (sock->protocol && sock->protocol->protocol->type
1408 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1410 SilcServerKEInternalContext *proto_ctx =
1411 (SilcServerKEInternalContext *)sock->protocol->context;
1413 if (proto_ctx->packet)
1414 silc_buffer_free(proto_ctx->packet);
1416 proto_ctx->packet = buffer;
1417 proto_ctx->dest_id_type = packet->src_id_type;
1418 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_type);
1420 /* Let the protocol handle the packet */
1421 sock->protocol->execute(server->timeout_queue, 0,
1422 sock->protocol, sock->sock,
1425 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1426 "protocol active, packet dropped."));
1430 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1431 /* If we receive this packet we will send to the other end information
1432 about our mandatory authentication method for the connection.
1433 This packet maybe received at any time. */
1436 * Connection Authentication protocol packets
1438 case SILC_PACKET_CONNECTION_AUTH:
1439 /* Start of the authentication protocol. We receive here the
1440 authentication data and will verify it. */
1441 SILC_LOG_DEBUG(("Connection auth packet"));
1442 if (sock->protocol && sock->protocol->protocol->type
1443 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1445 SilcServerConnAuthInternalContext *proto_ctx =
1446 (SilcServerConnAuthInternalContext *)sock->protocol->context;
1448 proto_ctx->packet = buffer;
1450 /* Let the protocol handle the packet */
1451 sock->protocol->execute(server->timeout_queue, 0,
1452 sock->protocol, sock->sock, 0, 0);
1454 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1455 "protocol active, packet dropped."));
1459 case SILC_PACKET_NEW_ID:
1461 * Received New ID packet. This includes some new ID that has been
1462 * created. It may be for client, server or channel. This is the way
1463 * to distribute information about new registered entities in the
1466 SILC_LOG_DEBUG(("New ID packet"));
1467 silc_server_new_id(server, sock, packet);
1470 case SILC_PACKET_NEW_CLIENT:
1472 * Received new client packet. This includes client information that
1473 * we will use to create initial client ID. After creating new
1474 * ID we will send it to the client.
1476 SILC_LOG_DEBUG(("New Client packet"));
1477 silc_server_new_client(server, sock, packet);
1480 case SILC_PACKET_NEW_SERVER:
1482 * Received new server packet. This includes Server ID and some other
1483 * information that we may save. This is received after server has
1486 SILC_LOG_DEBUG(("New Server packet"));
1487 silc_server_new_server(server, sock, packet);
1490 case SILC_PACKET_NEW_CHANNEL:
1493 case SILC_PACKET_NEW_CHANNEL_USER:
1496 case SILC_PACKET_NEW_CHANNEL_LIST:
1499 case SILC_PACKET_NEW_CHANNEL_USER_LIST:
1502 case SILC_PACKET_REPLACE_ID:
1504 * Received replace ID packet. This sends the old ID that is to be
1505 * replaced with the new one included into the packet. Client must not
1508 SILC_LOG_DEBUG(("Replace ID packet"));
1509 silc_server_replace_id(server, sock, packet);
1512 case SILC_PACKET_REMOVE_ID:
1515 case SILC_PACKET_REMOVE_CHANNEL_USER:
1517 * Received packet to remove user from a channel. Routers notify other
1518 * routers about a user leaving a channel.
1520 SILC_LOG_DEBUG(("Remove Channel User packet"));
1521 silc_server_remove_channel_user(server, sock, packet);
1525 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
1531 /* Assembles a new packet to be sent out to network. This doesn't actually
1532 send the packet but creates the packet and fills the outgoing data
1533 buffer and marks the packet ready to be sent to network. However, If
1534 argument force_send is TRUE the packet is sent immediately and not put
1535 to queue. Normal case is that the packet is not sent immediately. */
1537 void silc_server_packet_send(SilcServer server,
1538 SilcSocketConnection sock,
1539 SilcPacketType type,
1540 SilcPacketFlags flags,
1541 unsigned char *data,
1542 unsigned int data_len,
1545 void *dst_id = NULL;
1546 SilcIdType dst_id_type = SILC_ID_NONE;
1551 /* Get data used in the packet sending, keys and stuff */
1552 switch(sock->type) {
1553 case SILC_SOCKET_TYPE_CLIENT:
1554 dst_id = ((SilcClientEntry)sock->user_data)->id;
1555 dst_id_type = SILC_ID_CLIENT;
1557 case SILC_SOCKET_TYPE_SERVER:
1558 case SILC_SOCKET_TYPE_ROUTER:
1559 dst_id = ((SilcServerEntry)sock->user_data)->id;
1560 dst_id_type = SILC_ID_SERVER;
1566 silc_server_packet_send_dest(server, sock, type, flags, dst_id,
1567 dst_id_type, data, data_len, force_send);
1570 /* Assembles a new packet to be sent out to network. This doesn't actually
1571 send the packet but creates the packet and fills the outgoing data
1572 buffer and marks the packet ready to be sent to network. However, If
1573 argument force_send is TRUE the packet is sent immediately and not put
1574 to queue. Normal case is that the packet is not sent immediately.
1575 Destination information is sent as argument for this function. */
1577 void silc_server_packet_send_dest(SilcServer server,
1578 SilcSocketConnection sock,
1579 SilcPacketType type,
1580 SilcPacketFlags flags,
1582 SilcIdType dst_id_type,
1583 unsigned char *data,
1584 unsigned int data_len,
1587 SilcPacketContext packetdata;
1588 SilcIDListData idata;
1589 SilcCipher cipher = NULL;
1590 SilcHmac hmac = NULL;
1591 unsigned char *dst_id_data = NULL;
1592 unsigned int dst_id_len = 0;
1594 SILC_LOG_DEBUG(("Sending packet, type %d", type));
1596 /* Get data used in the packet sending, keys and stuff */
1597 idata = (SilcIDListData)sock->user_data;
1600 dst_id_data = silc_id_id2str(dst_id, dst_id_type);
1601 dst_id_len = silc_id_get_len(dst_id_type);
1604 /* Set the packet context pointers */
1605 packetdata.type = type;
1606 packetdata.flags = flags;
1607 packetdata.src_id = silc_id_id2str(server->id, server->id_type);
1608 packetdata.src_id_len = SILC_ID_SERVER_LEN;
1609 packetdata.src_id_type = server->id_type;
1610 packetdata.dst_id = dst_id_data;
1611 packetdata.dst_id_len = dst_id_len;
1612 packetdata.dst_id_type = dst_id_type;
1613 packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
1614 packetdata.src_id_len + dst_id_len;
1615 packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
1616 packetdata.rng = server->rng;
1618 /* Prepare outgoing data buffer for packet sending */
1619 silc_packet_send_prepare(sock,
1620 SILC_PACKET_HEADER_LEN +
1621 packetdata.src_id_len +
1622 packetdata.dst_id_len,
1626 SILC_LOG_DEBUG(("Putting data to outgoing buffer, len %d", data_len));
1628 packetdata.buffer = sock->outbuf;
1630 /* Put the data to the buffer */
1631 if (data && data_len)
1632 silc_buffer_put(sock->outbuf, data, data_len);
1634 /* Create the outgoing packet */
1635 silc_packet_assemble(&packetdata);
1638 cipher = idata->send_key;
1642 /* Encrypt the packet */
1643 silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
1645 SILC_LOG_HEXDUMP(("Outgoing packet, len %d", sock->outbuf->len),
1646 sock->outbuf->data, sock->outbuf->len);
1648 /* Now actually send the packet */
1649 silc_server_packet_send_real(server, sock, force_send);
1651 if (packetdata.src_id)
1652 silc_free(packetdata.src_id);
1653 if (packetdata.dst_id)
1654 silc_free(packetdata.dst_id);
1657 /* Forwards packet. Packets sent with this function will be marked as
1658 forwarded (in the SILC header flags) so that the receiver knows that
1659 we have forwarded the packet to it. Forwarded packets are handled
1660 specially by the receiver as they are not destined to the receiver
1661 originally. However, the receiver knows this because the forwarded
1662 flag has been set (and the flag is authenticated). */
1664 void silc_server_packet_forward(SilcServer server,
1665 SilcSocketConnection sock,
1666 unsigned char *data, unsigned int data_len,
1669 SilcIDListData idata;
1670 SilcCipher cipher = NULL;
1671 SilcHmac hmac = NULL;
1673 SILC_LOG_DEBUG(("Forwarding packet"));
1675 /* Get data used in the packet sending, keys and stuff */
1676 idata = (SilcIDListData)sock->user_data;
1678 /* Prepare outgoing data buffer for packet sending */
1679 silc_packet_send_prepare(sock, 0, 0, data_len);
1681 /* Put the data to the buffer */
1682 if (data && data_len)
1683 silc_buffer_put(sock->outbuf, data, data_len);
1685 /* Add the FORWARDED flag to packet flags */
1686 sock->outbuf->data[2] |= (unsigned char)SILC_PACKET_FLAG_FORWARDED;
1689 cipher = idata->send_key;
1693 /* Encrypt the packet */
1694 silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
1696 SILC_LOG_HEXDUMP(("Forwarded packet, len %d", sock->outbuf->len),
1697 sock->outbuf->data, sock->outbuf->len);
1699 /* Now actually send the packet */
1700 silc_server_packet_send_real(server, sock, force_send);
1703 /* Broadcast received packet to our primary route. This function is used
1704 by router to further route received broadcast packet. It is expected
1705 that the broadcast flag from the packet is checked before calling this
1706 function. This does not check for the broadcast flag. The `sock' must
1707 be the socket of the primary route. */
1709 void silc_server_packet_broadcast(SilcServer server,
1710 SilcSocketConnection sock,
1711 SilcPacketContext *packet)
1713 SilcBuffer buffer = packet->buffer;
1714 SilcIDListData idata;
1717 SILC_LOG_DEBUG(("Broadcasting received broadcast packet"));
1719 /* If the packet is originated from our primary route we are
1720 not allowed to send the packet. */
1721 id = silc_id_str2id(packet->src_id, packet->src_id_type);
1722 if (id && SILC_ID_SERVER_COMPARE(id, server->id_entry->router->id)) {
1723 idata = (SilcIDListData)sock->user_data;
1724 silc_packet_send_prepare(sock, 0, 0, buffer->len);
1725 silc_buffer_put(sock->outbuf, buffer->data, buffer->len);
1726 silc_packet_encrypt(idata->send_key, idata->hmac,
1727 sock->outbuf, sock->outbuf->len);
1729 SILC_LOG_HEXDUMP(("Broadcasted packet, len %d", sock->outbuf->len),
1730 sock->outbuf->data, sock->outbuf->len);
1732 /* Now actually send the packet */
1733 silc_server_packet_send_real(server, sock, TRUE);
1738 SILC_LOG_DEBUG(("Will not broadcast to primary route since it is the "
1739 "original sender of this packet"));
1743 /* Internal routine to actually create the channel packet and send it
1744 to network. This is common function in channel message sending. If
1745 `channel_message' is TRUE this encrypts the message as it is strictly
1746 a channel message. If FALSE normal encryption process is used. */
1749 silc_server_packet_send_to_channel_real(SilcServer server,
1750 SilcSocketConnection sock,
1751 SilcPacketContext *packet,
1754 unsigned char *data,
1755 unsigned int data_len,
1756 int channel_message,
1759 packet->truelen = data_len + SILC_PACKET_HEADER_LEN +
1760 packet->src_id_len + packet->dst_id_len;
1762 /* Prepare outgoing data buffer for packet sending */
1763 silc_packet_send_prepare(sock,
1764 SILC_PACKET_HEADER_LEN +
1765 packet->src_id_len +
1770 packet->buffer = sock->outbuf;
1772 /* Put the data to buffer, assemble and encrypt the packet. The packet
1773 is encrypted with normal session key shared with the client. */
1774 silc_buffer_put(sock->outbuf, data, data_len);
1775 silc_packet_assemble(packet);
1776 if (channel_message)
1777 silc_packet_encrypt(cipher, hmac, sock->outbuf, SILC_PACKET_HEADER_LEN +
1778 packet->src_id_len + packet->dst_id_len +
1781 silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
1783 SILC_LOG_HEXDUMP(("Channel packet, len %d", sock->outbuf->len),
1784 sock->outbuf->data, sock->outbuf->len);
1786 /* Now actually send the packet */
1787 silc_server_packet_send_real(server, sock, force_send);
1790 /* This routine is used by the server to send packets to channel. The
1791 packet sent with this function is distributed to all clients on
1792 the channel. Usually this is used to send notify messages to the
1793 channel, things like notify about new user joining to the channel. */
1795 void silc_server_packet_send_to_channel(SilcServer server,
1796 SilcChannelEntry channel,
1797 SilcPacketType type,
1798 unsigned char *data,
1799 unsigned int data_len,
1802 SilcSocketConnection sock = NULL;
1803 SilcPacketContext packetdata;
1804 SilcClientEntry client = NULL;
1805 SilcServerEntry *routed = NULL;
1806 SilcChannelClientEntry chl;
1807 SilcIDListData idata;
1808 unsigned int routed_count = 0;
1810 /* This doesn't send channel message packets */
1811 if (type == SILC_PACKET_CHANNEL_MESSAGE)
1814 SILC_LOG_DEBUG(("Sending packet to channel"));
1816 /* Set the packet context pointers. */
1817 packetdata.flags = 0;
1818 packetdata.type = type;
1819 packetdata.src_id = silc_id_id2str(server->id, SILC_ID_SERVER);
1820 packetdata.src_id_len = SILC_ID_SERVER_LEN;
1821 packetdata.src_id_type = SILC_ID_SERVER;
1822 packetdata.dst_id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
1823 packetdata.dst_id_len = SILC_ID_CHANNEL_LEN;
1824 packetdata.dst_id_type = SILC_ID_CHANNEL;
1825 packetdata.rng = server->rng;
1826 packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
1827 packetdata.src_id_len + packetdata.dst_id_len;
1828 packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
1830 /* If there are global users in the channel we will send the message
1831 first to our router for further routing. */
1832 if (server->server_type == SILC_SERVER && !server->standalone &&
1833 channel->global_users) {
1834 SilcServerEntry router;
1836 /* Get data used in packet header encryption, keys and stuff. */
1837 router = server->id_entry->router;
1838 sock = (SilcSocketConnection)router->connection;
1839 idata = (SilcIDListData)router;
1841 SILC_LOG_DEBUG(("Sending channel message to router for routing"));
1843 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1844 idata->send_key, idata->hmac,
1845 data, data_len, FALSE, force_send);
1848 /* Send the message to clients on the channel's client list. */
1849 silc_list_start(channel->user_list);
1850 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
1851 client = chl->client;
1853 /* If client has router set it is not locally connected client and
1854 we will route the message to the router set in the client. */
1855 if (client && client->router && server->server_type == SILC_ROUTER) {
1858 /* Check if we have sent the packet to this route already */
1859 for (k = 0; k < routed_count; k++)
1860 if (routed[k] == client->router)
1862 if (k < routed_count)
1865 /* Get data used in packet header encryption, keys and stuff. */
1866 sock = (SilcSocketConnection)client->router->connection;
1867 idata = (SilcIDListData)client->router;
1869 /* Send the packet */
1870 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1871 idata->send_key, idata->hmac,
1872 data, data_len, FALSE,
1875 /* We want to make sure that the packet is routed to same router
1876 only once. Mark this route as sent route. */
1878 routed = silc_realloc(routed, sizeof(*routed) * (k + 1));
1879 routed[k] = client->router;
1885 /* Send to locally connected client */
1888 /* Get data used in packet header encryption, keys and stuff. */
1889 sock = (SilcSocketConnection)client->connection;
1890 idata = (SilcIDListData)client;
1892 /* Send the packet */
1893 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1894 idata->send_key, idata->hmac,
1895 data, data_len, FALSE,
1902 silc_free(packetdata.src_id);
1903 silc_free(packetdata.dst_id);
1906 /* This routine is explicitly used to relay messages to some channel.
1907 Packets sent with this function we have received earlier and are
1908 totally encrypted. This just sends the packet to all clients on
1909 the channel. If the sender of the packet is someone on the channel
1910 the message will not be sent to that client. The SILC Packet header
1911 is encrypted with the session key shared between us and the client.
1912 MAC is also computed before encrypting the header. Rest of the
1913 packet will be untouched. */
1915 void silc_server_packet_relay_to_channel(SilcServer server,
1916 SilcSocketConnection sender_sock,
1917 SilcChannelEntry channel,
1919 SilcIdType sender_type,
1920 unsigned char *data,
1921 unsigned int data_len,
1925 SilcSocketConnection sock = NULL;
1926 SilcPacketContext packetdata;
1927 SilcClientEntry client = NULL;
1928 SilcServerEntry *routed = NULL;
1929 SilcChannelClientEntry chl;
1930 unsigned int routed_count = 0;
1931 SilcIDListData idata;
1933 SILC_LOG_DEBUG(("Relaying packet to channel"));
1935 /* Set the packet context pointers. */
1936 packetdata.flags = 0;
1937 packetdata.type = SILC_PACKET_CHANNEL_MESSAGE;
1938 packetdata.src_id = silc_id_id2str(sender, sender_type);
1939 packetdata.src_id_len = silc_id_get_len(sender_type);
1940 packetdata.src_id_type = sender_type;
1941 packetdata.dst_id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
1942 packetdata.dst_id_len = SILC_ID_CHANNEL_LEN;
1943 packetdata.dst_id_type = SILC_ID_CHANNEL;
1944 packetdata.rng = server->rng;
1945 packetdata.padlen = SILC_PACKET_PADLEN((SILC_PACKET_HEADER_LEN +
1946 packetdata.src_id_len +
1947 packetdata.dst_id_len));
1949 /* If there are global users in the channel we will send the message
1950 first to our router for further routing. */
1951 if (server->server_type == SILC_SERVER && !server->standalone &&
1952 channel->global_users) {
1953 SilcServerEntry router;
1955 router = server->id_entry->router;
1957 /* Check that the sender is not our router. */
1958 if (sender_sock != (SilcSocketConnection)router->connection) {
1960 /* Get data used in packet header encryption, keys and stuff. */
1961 sock = (SilcSocketConnection)router->connection;
1962 idata = (SilcIDListData)router;
1964 SILC_LOG_DEBUG(("Sending channel message to router for routing"));
1966 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1967 idata->send_key, idata->hmac,
1968 data, data_len, TRUE,
1973 /* Send the message to clients on the channel's client list. */
1974 silc_list_start(channel->user_list);
1975 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
1976 client = chl->client;
1980 /* If sender is one on the channel do not send it the packet. */
1981 if (!found && !SILC_ID_CLIENT_COMPARE(client->id, sender)) {
1986 /* If the client has set router it means that it is not locally
1987 connected client and we will route the packet further. */
1988 if (server->server_type == SILC_ROUTER && client->router) {
1991 /* Sender maybe server as well so we want to make sure that
1992 we won't send the message to the server it came from. */
1993 if (!found && !SILC_ID_SERVER_COMPARE(client->router->id, sender)) {
1998 /* Check if we have sent the packet to this route already */
1999 for (k = 0; k < routed_count; k++)
2000 if (routed[k] == client->router)
2002 if (k < routed_count)
2005 /* Get data used in packet header encryption, keys and stuff. */
2006 sock = (SilcSocketConnection)client->router->connection;
2007 idata = (SilcIDListData)client->router;
2009 /* Send the packet */
2010 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
2011 idata->send_key, idata->hmac,
2012 data, data_len, TRUE,
2015 /* We want to make sure that the packet is routed to same router
2016 only once. Mark this route as sent route. */
2018 routed = silc_realloc(routed, sizeof(*routed) * (k + 1));
2019 routed[k] = client->router;
2025 /* XXX Check client's mode on the channel. */
2027 /* Get data used in packet header encryption, keys and stuff. */
2028 sock = (SilcSocketConnection)client->connection;
2029 idata = (SilcIDListData)client;
2031 SILC_LOG_DEBUG(("Sending packet to client %s",
2032 sock->hostname ? sock->hostname : sock->ip));
2034 /* Send the packet */
2035 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
2036 idata->send_key, idata->hmac,
2037 data, data_len, TRUE,
2042 silc_free(packetdata.src_id);
2043 silc_free(packetdata.dst_id);
2046 /* This function is used to send packets strictly to all local clients
2047 on a particular channel. This is used for example to distribute new
2048 channel key to all our locally connected clients on the channel.
2049 The packets are always encrypted with the session key shared between
2050 the client, this means these are not _to the channel_ but _to the client_
2053 void silc_server_packet_send_local_channel(SilcServer server,
2054 SilcChannelEntry channel,
2055 SilcPacketType type,
2056 SilcPacketFlags flags,
2057 unsigned char *data,
2058 unsigned int data_len,
2061 SilcClientEntry client;
2062 SilcChannelClientEntry chl;
2063 SilcSocketConnection sock = NULL;
2065 SILC_LOG_DEBUG(("Start"));
2067 /* Send the message to clients on the channel's client list. */
2068 silc_list_start(channel->user_list);
2069 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2070 client = chl->client;
2073 sock = (SilcSocketConnection)client->connection;
2075 /* Send the packet to the client */
2076 silc_server_packet_send_dest(server, sock, type, flags, client->id,
2077 SILC_ID_CLIENT, data, data_len,
2083 /* Relays received command reply packet to the correct destination. The
2084 destination must be one of our locally connected client or the packet
2085 will be ignored. This is called when server has forwarded one of
2086 client's command request to router and router has now replied to the
2089 void silc_server_packet_relay_command_reply(SilcServer server,
2090 SilcSocketConnection sock,
2091 SilcPacketContext *packet)
2093 SilcBuffer buffer = packet->buffer;
2094 SilcClientEntry client;
2096 SilcSocketConnection dst_sock;
2097 SilcIDListData idata;
2099 SILC_LOG_DEBUG(("Start"));
2101 /* Source must be server or router */
2102 if (packet->src_id_type != SILC_ID_SERVER &&
2103 sock->type != SILC_SOCKET_TYPE_ROUTER)
2106 /* Destination must be client */
2107 if (packet->dst_id_type != SILC_ID_CLIENT)
2110 /* Execute command reply locally for the command */
2111 silc_server_command_reply_process(server, sock, buffer);
2113 id = silc_id_str2id(packet->dst_id, SILC_ID_CLIENT);
2115 /* Destination must be one of ours */
2116 client = silc_idlist_find_client_by_id(server->local_list, id);
2122 /* Relay the packet to the client */
2124 dst_sock = (SilcSocketConnection)client->connection;
2125 silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len
2126 + packet->dst_id_len + packet->padlen);
2128 silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
2129 silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
2131 idata = (SilcIDListData)client;
2133 /* Encrypt packet */
2134 silc_packet_encrypt(idata->send_key, idata->hmac, dst_sock->outbuf,
2137 /* Send the packet */
2138 silc_server_packet_send_real(server, dst_sock, FALSE);
2143 silc_buffer_free(buffer);
2146 /* Closes connection to socket connection */
2148 void silc_server_close_connection(SilcServer server,
2149 SilcSocketConnection sock)
2152 SILC_LOG_DEBUG(("Closing connection %d", sock->sock));
2154 /* We won't listen for this connection anymore */
2155 silc_schedule_unset_listen_fd(sock->sock);
2157 /* Unregister all tasks */
2158 silc_task_unregister_by_fd(server->io_queue, sock->sock);
2159 silc_task_unregister_by_fd(server->timeout_queue, sock->sock);
2161 /* Close the actual connection */
2162 silc_net_close_connection(sock->sock);
2163 server->sockets[sock->sock] = NULL;
2164 silc_socket_free(sock);
2167 /* Sends disconnect message to remote connection and disconnects the
2170 void silc_server_disconnect_remote(SilcServer server,
2171 SilcSocketConnection sock,
2172 const char *fmt, ...)
2175 unsigned char buf[4096];
2177 memset(buf, 0, sizeof(buf));
2179 vsprintf(buf, fmt, ap);
2182 SILC_LOG_DEBUG(("Disconnecting remote host"));
2184 /* Notify remote end that the conversation is over. The notify message
2185 is tried to be sent immediately. */
2186 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2187 buf, strlen(buf), TRUE);
2189 /* Mark the connection to be disconnected */
2190 SILC_SET_DISCONNECTED(sock);
2191 silc_server_close_connection(server, sock);
2194 /* Free's user_data pointer from socket connection object. As this
2195 pointer maybe anything we wil switch here to find the correct
2196 data type and free it the way it needs to be free'd. */
2198 void silc_server_free_sock_user_data(SilcServer server,
2199 SilcSocketConnection sock)
2201 SILC_LOG_DEBUG(("Start"));
2203 switch(sock->type) {
2204 case SILC_SOCKET_TYPE_CLIENT:
2206 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2208 /* Remove client from all channels */
2209 silc_server_remove_from_channels(server, sock, user_data);
2211 /* XXX must take some info to history before freeing */
2213 /* Free the client entry and everything in it */
2214 silc_idlist_del_data(user_data);
2215 silc_idlist_del_client(server->local_list, user_data);
2218 case SILC_SOCKET_TYPE_SERVER:
2219 case SILC_SOCKET_TYPE_ROUTER:
2227 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2229 silc_idlist_del_data(user_data);
2230 silc_free(user_data);
2235 sock->user_data = NULL;
2238 /* Removes client from all channels it has joined. This is used when
2239 client connection is disconnected. If the client on a channel
2240 is last, the channel is removed as well. */
2242 void silc_server_remove_from_channels(SilcServer server,
2243 SilcSocketConnection sock,
2244 SilcClientEntry client)
2246 SilcChannelEntry channel;
2247 SilcChannelClientEntry chl;
2248 SilcBuffer chidp, clidp;
2250 SILC_LOG_DEBUG(("Start"));
2252 if (!client || !client->id)
2255 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2257 /* Remove the client from all channels. The client is removed from
2258 the channels' user list. */
2259 silc_list_start(client->channels);
2260 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2261 channel = chl->channel;
2262 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
2264 /* Remove from list */
2265 silc_list_del(client->channels, chl);
2267 /* If this client is last one on the channel the channel
2268 is removed all together. */
2269 if (silc_list_count(channel->user_list) < 2) {
2271 /* However, if the channel has marked global users then the
2272 channel is not created locally, and this does not remove the
2273 channel globally from SILC network, in this case we will
2274 notify that this client has left the channel. */
2275 if (channel->global_users)
2276 silc_server_send_notify_to_channel(server, channel,
2277 SILC_NOTIFY_TYPE_SIGNOFF, 1,
2278 clidp->data, clidp->len);
2280 silc_idlist_del_channel(server->local_list, channel);
2284 /* Remove from list */
2285 silc_list_del(channel->user_list, chl);
2288 /* Send notify to channel about client leaving SILC and thus
2289 the entire channel. */
2290 silc_server_send_notify_to_channel(server, channel,
2291 SILC_NOTIFY_TYPE_SIGNOFF, 1,
2292 clidp->data, clidp->len);
2293 silc_buffer_free(chidp);
2296 silc_buffer_free(clidp);
2299 /* Removes client from one channel. This is used for example when client
2300 calls LEAVE command to remove itself from the channel. Returns TRUE
2301 if channel still exists and FALSE if the channel is removed when
2302 last client leaves the channel. If `notify' is FALSE notify messages
2305 int silc_server_remove_from_one_channel(SilcServer server,
2306 SilcSocketConnection sock,
2307 SilcChannelEntry channel,
2308 SilcClientEntry client,
2311 SilcChannelEntry ch;
2312 SilcChannelClientEntry chl;
2315 SILC_LOG_DEBUG(("Start"));
2317 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2319 /* Remove the client from the channel. The client is removed from
2320 the channel's user list. */
2321 silc_list_start(client->channels);
2322 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2323 if (chl->channel != channel)
2328 /* Remove from list */
2329 silc_list_del(client->channels, chl);
2331 /* If this client is last one on the channel the channel
2332 is removed all together. */
2333 if (silc_list_count(channel->user_list) < 2) {
2334 /* Notify about leaving client if this channel has global users,
2335 ie. the channel is not created locally. */
2336 if (notify && channel->global_users)
2337 silc_server_send_notify_to_channel(server, channel,
2338 SILC_NOTIFY_TYPE_LEAVE, 1,
2339 clidp->data, clidp->len);
2341 silc_idlist_del_channel(server->local_list, channel);
2342 silc_buffer_free(clidp);
2346 /* Remove from list */
2347 silc_list_del(channel->user_list, chl);
2350 /* Send notify to channel about client leaving the channel */
2352 silc_server_send_notify_to_channel(server, channel,
2353 SILC_NOTIFY_TYPE_LEAVE, 1,
2354 clidp->data, clidp->len);
2358 silc_buffer_free(clidp);
2362 /* Returns TRUE if the given client is on the channel. FALSE if not.
2363 This works because we assure that the user list on the channel is
2364 always in up to date thus we can only check the channel list from
2365 `client' which is faster than checking the user list from `channel'. */
2367 int silc_server_client_on_channel(SilcClientEntry client,
2368 SilcChannelEntry channel)
2370 SilcChannelClientEntry chl;
2372 if (!client || !channel)
2375 silc_list_start(client->channels);
2376 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END)
2377 if (chl->channel == channel)
2383 /* Timeout callback. This is called if connection is idle or for some
2384 other reason is not responding within some period of time. This
2385 disconnects the remote end. */
2387 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2389 SilcServerConnection sconn = (SilcServerConnection)context;
2390 SilcSocketConnection sock = sconn->server->sockets[fd];
2392 silc_server_disconnect_remote(sconn->server, sock,
2393 "Server closed connection: "
2394 "Connection timeout");
2397 /* Internal routine used to send (relay, route) private messages to some
2398 destination. If the private message key does not exist then the message
2399 is re-encrypted, otherwise we just pass it along. */
2402 silc_server_private_message_send_internal(SilcServer server,
2403 SilcSocketConnection dst_sock,
2406 SilcPacketContext *packet)
2408 SilcBuffer buffer = packet->buffer;
2410 /* Send and re-encrypt if private messge key does not exist */
2411 if ((packet->flags & SILC_PACKET_FLAG_PRIVMSG_KEY) == FALSE) {
2413 silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len
2414 + packet->dst_id_len + packet->padlen);
2415 silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
2416 silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
2418 /* Re-encrypt packet */
2419 silc_packet_encrypt(cipher, hmac, dst_sock->outbuf, buffer->len);
2421 /* Send the packet */
2422 silc_server_packet_send_real(server, dst_sock, FALSE);
2425 /* Key exist so just send it */
2426 silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len
2427 + packet->dst_id_len + packet->padlen);
2428 silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
2429 silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
2430 silc_server_packet_send_real(server, dst_sock, FALSE);
2434 /* Received private message. This resolves the destination of the message
2435 and sends the packet. This is used by both server and router. If the
2436 destination is our locally connected client this sends the packet to
2437 the client. This may also send the message for further routing if
2438 the destination is not in our server (or router). */
2440 void silc_server_private_message(SilcServer server,
2441 SilcSocketConnection sock,
2442 SilcPacketContext *packet)
2444 SilcBuffer buffer = packet->buffer;
2446 SilcServerEntry router;
2447 SilcSocketConnection dst_sock;
2448 SilcClientEntry client;
2449 SilcIDListData idata;
2451 SILC_LOG_DEBUG(("Start"));
2453 if (!packet->dst_id) {
2454 SILC_LOG_ERROR(("Bad Client ID in private message packet, dropped"));
2458 /* Decode destination Client ID */
2459 id = silc_id_str2id(packet->dst_id, SILC_ID_CLIENT);
2461 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
2465 /* If the destination belongs to our server we don't have to route
2466 the message anywhere but to send it to the local destination. */
2467 client = silc_idlist_find_client_by_id(server->local_list, id);
2469 /* It exists, now deliver the message to the destination */
2470 dst_sock = (SilcSocketConnection)client->connection;
2472 /* If we are router and the client has router then the client is in
2473 our cell but not directly connected to us. */
2474 if (server->server_type == SILC_ROUTER && client->router) {
2475 /* We are of course in this case the client's router thus the real
2476 "router" of the client is the server who owns the client. Thus
2477 we will send the packet to that server. */
2478 router = (SilcServerEntry)dst_sock->user_data;
2479 idata = (SilcIDListData)router;
2480 // assert(client->router == server->id_entry);
2482 silc_server_private_message_send_internal(server, dst_sock,
2489 /* Seems that client really is directly connected to us */
2490 idata = (SilcIDListData)client;
2491 silc_server_private_message_send_internal(server, dst_sock,
2493 idata->hmac, packet);
2497 /* Destination belongs to someone not in this server. If we are normal
2498 server our action is to send the packet to our router. */
2499 if (server->server_type == SILC_SERVER && !server->standalone) {
2500 router = server->id_entry->router;
2502 /* Send to primary route */
2504 dst_sock = (SilcSocketConnection)router->connection;
2505 idata = (SilcIDListData)router;
2506 silc_server_private_message_send_internal(server, dst_sock,
2508 idata->hmac, packet);
2513 /* We are router and we will perform route lookup for the destination
2514 and send the message to fastest route. */
2515 if (server->server_type == SILC_ROUTER && !server->standalone) {
2516 dst_sock = silc_server_get_route(server, id, SILC_ID_CLIENT);
2517 router = (SilcServerEntry)dst_sock->user_data;
2518 idata = (SilcIDListData)router;
2520 /* Get fastest route and send packet. */
2522 silc_server_private_message_send_internal(server, dst_sock,
2524 idata->hmac, packet);
2530 silc_server_send_error(server, sock,
2531 "No such nickname: Private message not sent");
2533 silc_buffer_free(buffer);
2536 /* Process received channel message. The message can be originated from
2537 client or server. */
2539 void silc_server_channel_message(SilcServer server,
2540 SilcSocketConnection sock,
2541 SilcPacketContext *packet)
2543 SilcChannelEntry channel = NULL;
2544 SilcChannelClientEntry chl;
2545 SilcChannelID *id = NULL;
2546 void *sender = NULL;
2547 SilcBuffer buffer = packet->buffer;
2549 SILC_LOG_DEBUG(("Processing channel message"));
2552 if (packet->dst_id_type != SILC_ID_CHANNEL) {
2553 SILC_LOG_ERROR(("Received bad message for channel, dropped"));
2554 SILC_LOG_DEBUG(("Received bad message for channel, dropped"));
2558 /* Find channel entry */
2559 id = silc_id_str2id(packet->dst_id, SILC_ID_CHANNEL);
2560 channel = silc_idlist_find_channel_by_id(server->local_list, id);
2562 SILC_LOG_DEBUG(("Could not find channel"));
2566 /* See that this client is on the channel. If the message is coming
2567 from router we won't do the check as the message is from client that
2568 we don't know about. Also, if the original sender is not client
2569 (as it can be server as well) we don't do the check. */
2570 sender = silc_id_str2id(packet->src_id, packet->src_id_type);
2571 if (sock->type != SILC_SOCKET_TYPE_ROUTER &&
2572 packet->src_id_type == SILC_ID_CLIENT) {
2573 silc_list_start(channel->user_list);
2574 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2575 if (chl->client && !SILC_ID_CLIENT_COMPARE(chl->client->id, sender))
2578 if (chl == SILC_LIST_END)
2582 /* Distribute the packet to our local clients. This will send the
2583 packet for further routing as well, if needed. */
2584 silc_server_packet_relay_to_channel(server, sock, channel, sender,
2585 packet->src_id_type,
2586 packet->buffer->data,
2587 packet->buffer->len, FALSE);
2594 silc_buffer_free(buffer);
2597 /* Received channel key packet. We distribute the key to all of our locally
2598 connected clients on the channel. */
2599 /* XXX Router must accept this packet and distribute the key to all its
2600 server that has clients on the channel */
2602 void silc_server_channel_key(SilcServer server,
2603 SilcSocketConnection sock,
2604 SilcPacketContext *packet)
2606 SilcBuffer buffer = packet->buffer;
2607 SilcChannelKeyPayload payload = NULL;
2608 SilcChannelID *id = NULL;
2609 SilcChannelEntry channel;
2610 SilcChannelClientEntry chl;
2611 SilcClientEntry client;
2613 unsigned int tmp_len;
2616 if (packet->src_id_type != SILC_ID_SERVER &&
2617 sock->type != SILC_SOCKET_TYPE_ROUTER)
2620 /* Decode channel key payload */
2621 payload = silc_channel_key_payload_parse(buffer);
2623 SILC_LOG_ERROR(("Bad channel key payload, dropped"));
2627 /* Get channel ID */
2628 tmp = silc_channel_key_get_id(payload, &tmp_len);
2629 id = silc_id_payload_parse_id(tmp, tmp_len);
2633 /* Get the channel entry */
2634 channel = silc_idlist_find_channel_by_id(server->local_list, id);
2636 SILC_LOG_ERROR(("Received key for non-existent channel"));
2640 /* Save the key for us as well */
2641 tmp = silc_channel_key_get_key(payload, &tmp_len);
2644 cipher = silc_channel_key_get_cipher(payload, NULL);;
2647 if (!silc_cipher_alloc(cipher, &channel->channel_key))
2650 channel->key_len = tmp_len * 8;
2651 channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
2652 memcpy(channel->key, tmp, tmp_len);
2653 channel->channel_key->cipher->set_key(channel->channel_key->context,
2656 /* Distribute the key to all clients on the channel */
2657 /* XXX Some other sender should be used, I think this is not correct */
2658 silc_list_start(channel->user_list);
2659 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2660 client = chl->client;
2663 silc_server_packet_send_dest(server, client->connection,
2664 SILC_PACKET_CHANNEL_KEY, 0,
2665 client->id, SILC_ID_CLIENT,
2666 buffer->data, buffer->len, FALSE);
2673 silc_channel_key_payload_free(payload);
2674 silc_buffer_free(buffer);
2677 /* Sends current motd to client */
2679 void silc_server_send_motd(SilcServer server,
2680 SilcSocketConnection sock)
2685 if (server->config && server->config->motd &&
2686 server->config->motd->motd_file) {
2688 motd = silc_file_read(server->config->motd->motd_file, &motd_len);
2692 silc_server_send_notify(server, sock, SILC_NOTIFY_TYPE_MOTD, 1,
2698 /* Sends error message. Error messages may or may not have any
2701 void silc_server_send_error(SilcServer server,
2702 SilcSocketConnection sock,
2703 const char *fmt, ...)
2706 unsigned char buf[4096];
2708 memset(buf, 0, sizeof(buf));
2710 vsprintf(buf, fmt, ap);
2713 silc_server_packet_send(server, sock, SILC_PACKET_ERROR, 0,
2714 buf, strlen(buf), FALSE);
2717 /* Sends notify message. If format is TRUE the variable arguments are
2718 formatted and the formatted string is sent as argument payload. If it is
2719 FALSE then each argument is sent as separate argument and their format
2720 in the argument list must be { argument data, argument length }. */
2722 void silc_server_send_notify(SilcServer server,
2723 SilcSocketConnection sock,
2724 SilcNotifyType type,
2725 unsigned int argc, ...)
2732 packet = silc_notify_payload_encode(type, argc, ap);
2733 silc_server_packet_send(server, sock, SILC_PACKET_NOTIFY, 0,
2734 packet->data, packet->len, FALSE);
2735 silc_buffer_free(packet);
2738 /* Sends notify message destined to specific entity. */
2740 void silc_server_send_notify_dest(SilcServer server,
2741 SilcSocketConnection sock,
2743 SilcIdType dest_id_type,
2744 SilcNotifyType type,
2745 unsigned int argc, ...)
2752 packet = silc_notify_payload_encode(type, argc, ap);
2753 silc_server_packet_send_dest(server, sock, SILC_PACKET_NOTIFY, 0,
2754 dest_id, dest_id_type,
2755 packet->data, packet->len, FALSE);
2756 silc_buffer_free(packet);
2759 /* Sends notify message to a channel. The notify message sent is
2760 distributed to all clients on the channel. */
2762 void silc_server_send_notify_to_channel(SilcServer server,
2763 SilcChannelEntry channel,
2764 SilcNotifyType type,
2765 unsigned int argc, ...)
2772 packet = silc_notify_payload_encode(type, argc, ap);
2773 silc_server_packet_send_to_channel(server, channel,
2775 packet->data, packet->len, FALSE);
2776 silc_buffer_free(packet);
2779 /* Send notify message to all clients the client has joined. It is quaranteed
2780 that the message is sent only once to a client (ie. if a client is joined
2781 on two same channel it will receive only one notify message). Also, this
2782 sends only to local clients (locally connected if we are server, and to
2783 local servers if we are router). */
2785 void silc_server_send_notify_on_channels(SilcServer server,
2786 SilcClientEntry client,
2787 SilcNotifyType type,
2788 unsigned int argc, ...)
2791 SilcSocketConnection sock = NULL;
2792 SilcPacketContext packetdata;
2794 SilcClientEntry *sent_clients = NULL;
2795 unsigned int sent_clients_count = 0;
2796 SilcServerEntry *routed = NULL;
2797 unsigned int routed_count = 0;
2798 SilcChannelEntry channel;
2799 SilcChannelClientEntry chl, chl2;
2800 SilcIDListData idata;
2802 unsigned char *data;
2803 unsigned int data_len;
2804 int force_send = FALSE;
2807 if (!silc_list_count(client->channels))
2811 packet = silc_notify_payload_encode(type, argc, ap);
2812 data = packet->data;
2813 data_len = packet->len;
2815 /* Set the packet context pointers. */
2816 packetdata.flags = 0;
2817 packetdata.type = SILC_PACKET_NOTIFY;
2818 packetdata.src_id = silc_id_id2str(server->id, SILC_ID_SERVER);
2819 packetdata.src_id_len = SILC_ID_SERVER_LEN;
2820 packetdata.src_id_type = SILC_ID_SERVER;
2821 packetdata.rng = server->rng;
2823 silc_list_start(client->channels);
2824 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2825 channel = chl->channel;
2827 /* Send the message to all clients on the channel's client list. */
2828 silc_list_start(channel->user_list);
2829 while ((chl2 = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2832 /* Check if we have sent the packet to this client already */
2833 for (k = 0; k < sent_clients_count; k++)
2834 if (sent_clients[k] == c)
2836 if (k < sent_clients_count)
2839 /* If we are router and if this client has router set it is not
2840 locally connected client and we will route the message to the
2841 router set in the client. */
2842 if (c && c->router && server->server_type == SILC_ROUTER) {
2843 /* Check if we have sent the packet to this route already */
2844 for (k = 0; k < routed_count; k++)
2845 if (routed[k] == c->router)
2847 if (k < routed_count)
2850 /* Get data used in packet header encryption, keys and stuff. */
2851 sock = (SilcSocketConnection)c->router->connection;
2852 idata = (SilcIDListData)c->router;
2854 packetdata.dst_id = silc_id_id2str(c->router->id, SILC_ID_SERVER);
2855 packetdata.dst_id_len = SILC_ID_SERVER_LEN;
2856 packetdata.dst_id_type = SILC_ID_SERVER;
2857 packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
2858 packetdata.src_id_len + packetdata.dst_id_len;
2859 packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
2861 /* Send the packet */
2862 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
2863 idata->send_key, idata->hmac,
2864 data, data_len, FALSE,
2867 silc_free(packetdata.dst_id);
2869 /* We want to make sure that the packet is routed to same router
2870 only once. Mark this route as sent route. */
2872 routed = silc_realloc(routed, sizeof(*routed) * (k + 1));
2873 routed[k] = c->router;
2879 /* Send to locally connected client */
2882 /* Get data used in packet header encryption, keys and stuff. */
2883 sock = (SilcSocketConnection)c->connection;
2884 idata = (SilcIDListData)c;
2886 packetdata.dst_id = silc_id_id2str(c->id, SILC_ID_CLIENT);
2887 packetdata.dst_id_len = SILC_ID_CLIENT_LEN;
2888 packetdata.dst_id_type = SILC_ID_CLIENT;
2889 packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
2890 packetdata.src_id_len + packetdata.dst_id_len;
2891 packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
2893 /* Send the packet */
2894 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
2895 idata->send_key, idata->hmac,
2896 data, data_len, FALSE,
2899 silc_free(packetdata.dst_id);
2901 /* Make sure that we send the notify only once per client. */
2902 sent_clients = silc_realloc(sent_clients, sizeof(*sent_clients) *
2903 (sent_clients_count + 1));
2904 sent_clients[sent_clients_count] = c;
2905 sent_clients_count++;
2912 if (sent_clients_count)
2913 silc_free(sent_clients);
2914 silc_free(packetdata.src_id);
2917 /* Sends New ID Payload to remote end. The packet is used to distribute
2918 information about new registered clients, servers, channel etc. usually
2919 to routers so that they can keep these information up to date.
2920 If the argument `broadcast' is TRUE then the packet is sent as
2921 broadcast packet. */
2923 void silc_server_send_new_id(SilcServer server,
2924 SilcSocketConnection sock,
2926 void *id, SilcIdType id_type,
2927 unsigned int id_len)
2931 idp = silc_id_payload_encode(id, id_type);
2932 silc_server_packet_send(server, sock, SILC_PACKET_NEW_ID,
2933 broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
2934 idp->data, idp->len, FALSE);
2935 silc_buffer_free(idp);
2938 /* Sends Replace ID payload to remote end. This is used to replace old
2939 ID with new ID sent in the packet. This is called for example when
2940 user changes nickname and we create new ID for the user. If the
2941 argument `broadcast' is TRUE then the packet is sent as
2942 broadcast packet. */
2943 /* XXX It would be expected that the new id is same type as the old
2946 void silc_server_send_replace_id(SilcServer server,
2947 SilcSocketConnection sock,
2949 void *old_id, SilcIdType old_id_type,
2950 unsigned int old_id_len,
2951 void *new_id, SilcIdType new_id_type,
2952 unsigned int new_id_len)
2958 oid = silc_id_id2str(old_id, old_id_type);
2962 nid = silc_id_id2str(new_id, new_id_type);
2966 packet = silc_buffer_alloc(2 + 2 + 2 + 2 + old_id_len + new_id_len);
2967 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
2968 silc_buffer_format(packet,
2969 SILC_STR_UI_SHORT(old_id_type),
2970 SILC_STR_UI_SHORT(old_id_len),
2971 SILC_STR_UI_XNSTRING(oid, old_id_len),
2972 SILC_STR_UI_SHORT(new_id_type),
2973 SILC_STR_UI_SHORT(new_id_len),
2974 SILC_STR_UI_XNSTRING(nid, new_id_len),
2977 silc_server_packet_send(server, sock, SILC_PACKET_REPLACE_ID,
2978 broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
2979 packet->data, packet->len, FALSE);
2982 silc_buffer_free(packet);
2985 /* This function is used to send Remove Channel User payload. This may sent
2986 by server but is usually used only by router to notify other routers that
2987 user has left a channel. Normal server sends this packet to its router
2988 to notify that the router should not hold a record about this client
2989 on a channel anymore. Router distributes it further to other routers. */
2991 void silc_server_send_remove_channel_user(SilcServer server,
2992 SilcSocketConnection sock,
2994 void *client_id, void *channel_id)
2997 unsigned char *clid, *chid;
2999 clid = silc_id_id2str(client_id, SILC_ID_CLIENT);
3003 chid = silc_id_id2str(channel_id, SILC_ID_CHANNEL);
3007 packet = silc_buffer_alloc(2 + 2 + SILC_ID_CLIENT_LEN + SILC_ID_CHANNEL_LEN);
3008 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
3009 silc_buffer_format(packet,
3010 SILC_STR_UI_SHORT(SILC_ID_CLIENT_LEN),
3011 SILC_STR_UI_XNSTRING(clid, SILC_ID_CLIENT_LEN),
3012 SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
3013 SILC_STR_UI_XNSTRING(chid, SILC_ID_CHANNEL_LEN),
3016 silc_server_packet_send(server, sock, SILC_PACKET_REMOVE_CHANNEL_USER,
3017 broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
3018 packet->data, packet->len, FALSE);
3021 silc_buffer_free(packet);
3024 /* Received packet to replace a ID. This checks that the requested ID
3025 exists and replaces it with the new one. */
3027 void silc_server_replace_id(SilcServer server,
3028 SilcSocketConnection sock,
3029 SilcPacketContext *packet)
3031 SilcBuffer buffer = packet->buffer;
3032 unsigned char *old_id = NULL, *new_id = NULL;
3033 SilcIdType old_id_type, new_id_type;
3034 unsigned short old_id_len, new_id_len;
3035 void *id = NULL, *id2 = NULL;
3037 if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3038 packet->src_id_type == SILC_ID_CLIENT)
3041 SILC_LOG_DEBUG(("Replacing ID"));
3043 silc_buffer_unformat(buffer,
3044 SILC_STR_UI_SHORT(&old_id_type),
3045 SILC_STR_UI16_NSTRING_ALLOC(&old_id, &old_id_len),
3046 SILC_STR_UI_SHORT(&new_id_type),
3047 SILC_STR_UI16_NSTRING_ALLOC(&new_id, &new_id_len),
3050 if (old_id_type != new_id_type)
3053 if (old_id_len != silc_id_get_len(old_id_type) ||
3054 new_id_len != silc_id_get_len(new_id_type))
3057 id = silc_id_str2id(old_id, old_id_type);
3061 id2 = silc_id_str2id(new_id, new_id_type);
3065 /* Replace the old ID */
3066 switch(old_id_type) {
3067 case SILC_ID_CLIENT:
3068 if (silc_idlist_replace_client_id(server->local_list, id, id2) == NULL)
3069 if (server->server_type == SILC_ROUTER)
3070 silc_idlist_replace_client_id(server->global_list, id, id2);
3073 case SILC_ID_SERVER:
3074 if (silc_idlist_replace_server_id(server->local_list, id, id2) == NULL)
3075 if (server->server_type == SILC_ROUTER)
3076 silc_idlist_replace_server_id(server->global_list, id, id2);
3079 case SILC_ID_CHANNEL:
3080 /* XXX Hmm... Basically this cannot occur. Channel ID's cannot be
3099 /* Creates new channel. */
3101 SilcChannelEntry silc_server_new_channel(SilcServer server,
3102 SilcServerID *router_id,
3103 char *cipher, char *channel_name)
3106 SilcChannelID *channel_id;
3107 SilcChannelEntry entry;
3109 unsigned char channel_key[32];
3111 SILC_LOG_DEBUG(("Creating new channel"));
3113 /* Create channel key */
3114 for (i = 0; i < 32; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3121 silc_cipher_alloc(cipher, &key);
3122 key->cipher->set_key(key->context, channel_key, key_len);
3124 channel_name = strdup(channel_name);
3126 /* Create the channel */
3127 silc_id_create_channel_id(router_id, server->rng, &channel_id);
3128 entry = silc_idlist_add_channel(server->local_list, channel_name,
3129 SILC_CHANNEL_MODE_NONE, channel_id,
3132 silc_free(channel_name);
3136 entry->key = silc_calloc(key_len, sizeof(*entry->key));
3137 entry->key_len = key_len * 8;
3138 memcpy(entry->key, channel_key, key_len);
3139 memset(channel_key, 0, sizeof(channel_key));
3141 /* Notify other routers about the new channel. We send the packet
3142 to our primary route. */
3143 if (server->standalone == FALSE) {
3144 silc_server_send_new_id(server, server->id_entry->router->connection,
3145 server->server_type == SILC_SERVER ? FALSE : TRUE,
3146 entry->id, SILC_ID_CHANNEL, SILC_ID_CHANNEL_LEN);
3152 /* Create new client. This processes incoming NEW_CLIENT packet and creates
3153 Client ID for the client. Client becomes registered after calling this
3156 SilcClientEntry silc_server_new_client(SilcServer server,
3157 SilcSocketConnection sock,
3158 SilcPacketContext *packet)
3160 SilcBuffer buffer = packet->buffer;
3161 SilcClientEntry client;
3162 SilcIDCacheEntry cache;
3163 SilcClientID *client_id;
3165 SilcIDListData idata;
3166 char *username = NULL, *realname = NULL, *id_string;
3168 SILC_LOG_DEBUG(("Creating new client"));
3170 if (sock->type != SILC_SOCKET_TYPE_CLIENT)
3173 /* Take client entry */
3174 client = (SilcClientEntry)sock->user_data;
3175 idata = (SilcIDListData)client;
3177 /* Fetch the old client cache entry so that we can update it. */
3178 if (!silc_idcache_find_by_context(server->local_list->clients,
3179 sock->user_data, &cache)) {
3180 SILC_LOG_ERROR(("Lost client's cache entry - bad thing"));
3184 /* Parse incoming packet */
3185 silc_buffer_unformat(buffer,
3186 SILC_STR_UI16_STRING_ALLOC(&username),
3187 SILC_STR_UI16_STRING_ALLOC(&realname),
3190 /* Create Client ID */
3191 silc_id_create_client_id(server->id, server->rng, server->md5hash,
3192 username, &client_id);
3194 /* Update client entry */
3195 idata->registered = TRUE;
3196 client->nickname = strdup(username);
3197 client->username = username;
3198 client->userinfo = realname;
3199 client->id = client_id;
3201 /* Update the cache entry */
3202 cache->id = (void *)client_id;
3203 cache->type = SILC_ID_CLIENT;
3204 cache->data = username;
3205 silc_idcache_sort_by_data(server->local_list->clients);
3207 /* Notify our router about new client on the SILC network */
3208 if (!server->standalone)
3209 silc_server_send_new_id(server, (SilcSocketConnection)
3210 server->id_entry->router->connection,
3211 server->server_type == SILC_ROUTER ? TRUE : FALSE,
3212 client->id, SILC_ID_CLIENT, SILC_ID_CLIENT_LEN);
3214 /* Send the new client ID to the client. */
3215 id_string = silc_id_id2str(client->id, SILC_ID_CLIENT);
3216 reply = silc_buffer_alloc(2 + 2 + SILC_ID_CLIENT_LEN);
3217 silc_buffer_pull_tail(reply, SILC_BUFFER_END(reply));
3218 silc_buffer_format(reply,
3219 SILC_STR_UI_SHORT(SILC_ID_CLIENT),
3220 SILC_STR_UI_SHORT(SILC_ID_CLIENT_LEN),
3221 SILC_STR_UI_XNSTRING(id_string, SILC_ID_CLIENT_LEN),
3223 silc_server_packet_send(server, sock, SILC_PACKET_NEW_ID, 0,
3224 reply->data, reply->len, FALSE);
3225 silc_free(id_string);
3226 silc_buffer_free(reply);
3228 /* Send some nice info to the client */
3229 SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3230 ("Welcome to the SILC Network %s@%s",
3231 username, sock->hostname));
3232 SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3233 ("Your host is %s, running version %s",
3234 server->config->server_info->server_name,
3236 SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3237 ("Your connection is secured with %s cipher, "
3238 "key length %d bits",
3239 idata->send_key->cipher->name,
3240 idata->send_key->cipher->key_len));
3241 SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3242 ("Your current nickname is %s",
3246 silc_server_send_motd(server, sock);
3251 /* Create new server. This processes incoming NEW_SERVER packet and
3252 saves the received Server ID. The server is our locally connected
3253 server thus we save all the information and save it to local list.
3254 This funtion can be used by both normal server and router server.
3255 If normal server uses this it means that its router has connected
3256 to the server. If router uses this it means that one of the cell's
3257 servers is connected to the router. */
3259 SilcServerEntry silc_server_new_server(SilcServer server,
3260 SilcSocketConnection sock,
3261 SilcPacketContext *packet)
3263 SilcBuffer buffer = packet->buffer;
3264 SilcServerEntry new_server;
3265 SilcIDCacheEntry cache;
3266 SilcServerID *server_id;
3267 SilcIDListData idata;
3268 unsigned char *server_name, *id_string;
3269 unsigned short id_len;
3271 SILC_LOG_DEBUG(("Creating new server"));
3273 if (sock->type != SILC_SOCKET_TYPE_SERVER &&
3274 sock->type != SILC_SOCKET_TYPE_ROUTER)
3277 /* Take server entry */
3278 new_server = (SilcServerEntry)sock->user_data;
3279 idata = (SilcIDListData)new_server;
3281 /* Fetch the old server cache entry so that we can update it. */
3282 if (!silc_idcache_find_by_context(server->local_list->servers,
3283 sock->user_data, &cache)) {
3284 SILC_LOG_ERROR(("Lost server's cache entry - bad thing"));
3288 /* Parse the incoming packet */
3289 silc_buffer_unformat(buffer,
3290 SILC_STR_UI16_NSTRING_ALLOC(&id_string, &id_len),
3291 SILC_STR_UI16_STRING_ALLOC(&server_name),
3294 if (id_len > buffer->len) {
3295 silc_free(id_string);
3296 silc_free(server_name);
3301 server_id = silc_id_str2id(id_string, SILC_ID_SERVER);
3302 silc_free(id_string);
3304 /* Update client entry */
3305 idata->registered = TRUE;
3306 new_server->server_name = server_name;
3307 new_server->id = server_id;
3309 /* Update the cache entry */
3310 cache->id = (void *)server_id;
3311 cache->type = SILC_ID_SERVER;
3312 cache->data = server_name;
3313 silc_idcache_sort_by_data(server->local_list->servers);
3315 /* Distribute the information about new server in the SILC network
3316 to our router. If we are normal server we won't send anything
3317 since this connection must be our router connection. */
3318 if (server->server_type == SILC_ROUTER && !server->standalone &&
3319 server->id_entry->router->connection != sock)
3320 silc_server_send_new_id(server, server->id_entry->router->connection,
3321 TRUE, new_server->id, SILC_ID_SERVER,
3322 SILC_ID_SERVER_LEN);
3327 /* Processes incoming New ID Payload. New ID Payload is used to distribute
3328 information about newly registered clients, servers and created
3331 void silc_server_new_id(SilcServer server, SilcSocketConnection sock,
3332 SilcPacketContext *packet)
3334 SilcBuffer buffer = packet->buffer;
3336 SilcServerEntry tmpserver, router;
3337 SilcSocketConnection router_sock;
3342 SILC_LOG_DEBUG(("Processing new ID"));
3344 if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3345 server->server_type == SILC_SERVER ||
3346 packet->src_id_type != SILC_ID_SERVER)
3349 idp = silc_id_payload_parse(buffer);
3353 id_type = silc_id_payload_get_type(idp);
3355 /* Normal server cannot have other normal server connections */
3356 if (id_type == SILC_ID_SERVER && sock->type == SILC_SOCKET_TYPE_SERVER)
3359 id = silc_id_payload_get_id(idp);
3363 /* If the sender of this packet is server and we are router we need to
3364 broadcast this packet to other routers in the network. */
3365 if (!server->standalone && sock->type == SILC_SOCKET_TYPE_SERVER &&
3366 server->server_type == SILC_ROUTER) {
3367 SILC_LOG_DEBUG(("Broadcasting received New ID packet"));
3368 silc_server_packet_send(server, server->id_entry->router->connection,
3370 packet->flags | SILC_PACKET_FLAG_BROADCAST,
3371 buffer->data, buffer->len, FALSE);
3374 /* If the packet is originated from the one who sent it to us we know
3375 that the ID belongs to our cell, unless the sender was router. */
3376 tmpid = silc_id_str2id(packet->src_id, SILC_ID_SERVER);
3377 tmpserver = (SilcServerEntry)sock->user_data;
3379 if (!SILC_ID_SERVER_COMPARE(tmpid, tmpserver->id) &&
3380 sock->type == SILC_SOCKET_TYPE_SERVER) {
3381 id_list = server->local_list;
3383 router = sock->user_data;
3384 /* router = server->id_entry; */
3386 id_list = server->global_list;
3387 router_sock = (SilcSocketConnection)server->id_entry->router->connection;
3388 router = server->id_entry->router;
3394 case SILC_ID_CLIENT:
3396 SilcClientEntry idlist;
3398 SILC_LOG_DEBUG(("New client id(%s) from [%s] %s",
3399 silc_id_render(id, SILC_ID_CLIENT),
3400 sock->type == SILC_SOCKET_TYPE_SERVER ?
3401 "Server" : "Router", sock->hostname));
3403 /* Add the client to our local list. We are router and we keep
3404 cell specific local database of all clients in the cell. */
3405 idlist = silc_idlist_add_client(id_list, NULL, NULL, NULL,
3406 id, router, router_sock);
3410 case SILC_ID_SERVER:
3412 SilcServerEntry idlist;
3414 SILC_LOG_DEBUG(("New server id(%s) from [%s] %s",
3415 silc_id_render(id, SILC_ID_SERVER),
3416 sock->type == SILC_SOCKET_TYPE_SERVER ?
3417 "Server" : "Router", sock->hostname));
3419 /* Add the server to our local list. We are router and we keep
3420 cell specific local database of all servers in the cell. */
3421 idlist = silc_idlist_add_server(id_list, NULL, 0, id, router,
3426 case SILC_ID_CHANNEL:
3427 SILC_LOG_DEBUG(("New channel id(%s) from [%s] %s",
3428 silc_id_render(id, SILC_ID_CHANNEL),
3429 sock->type == SILC_SOCKET_TYPE_SERVER ?
3430 "Server" : "Router", sock->hostname));
3432 /* Add the channel to our local list. We are router and we keep
3433 cell specific local database of all channels in the cell. */
3434 silc_idlist_add_channel(id_list, NULL, 0, id, router, NULL);
3442 silc_id_payload_free(idp);
3445 /* Received packet to remove a user from a channel. Routers notify other
3446 routers that user has left a channel. Client must not send this packet.
3447 Normal server may send this packet but ignores if it receives one. */
3449 void silc_server_remove_channel_user(SilcServer server,
3450 SilcSocketConnection sock,
3451 SilcPacketContext *packet)
3453 SilcBuffer buffer = packet->buffer;
3454 unsigned char *tmp1 = NULL, *tmp2 = NULL;
3455 SilcClientID *client_id = NULL;
3456 SilcChannelID *channel_id = NULL;
3457 SilcChannelEntry channel;
3458 SilcClientEntry client;
3460 SILC_LOG_DEBUG(("Removing user from channel"));
3462 if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3463 server->server_type == SILC_SERVER)
3466 silc_buffer_unformat(buffer,
3467 SILC_STR_UI16_STRING_ALLOC(&tmp1),
3468 SILC_STR_UI16_STRING_ALLOC(&tmp2),
3474 client_id = silc_id_str2id(tmp1, SILC_ID_CLIENT);
3475 channel_id = silc_id_str2id(tmp2, SILC_ID_CHANNEL);
3476 if (!client_id || !channel_id)
3479 /* XXX routers should check server->global_list as well */
3480 /* Get channel entry */
3481 channel = silc_idlist_find_channel_by_id(server->local_list, channel_id);
3485 /* XXX routers should check server->global_list as well */
3486 /* Get client entry */
3487 client = silc_idlist_find_client_by_id(server->local_list, client_id);
3491 /* Remove from channel */
3492 silc_server_remove_from_one_channel(server, sock, channel, client, FALSE);
3500 silc_free(client_id);
3502 silc_free(channel_id);