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_packet_context_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_packet_context_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;
741 server->router = id_entry;
744 /* Free the temporary connection data context */
748 /* Free the protocol object */
749 silc_protocol_free(protocol);
751 silc_packet_context_free(ctx->packet);
753 silc_ske_free(ctx->ske);
755 sock->protocol = NULL;
758 /* Accepts new connections to the server. Accepting new connections are
759 done in three parts to make it async. */
761 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
763 SilcServer server = (SilcServer)context;
764 SilcSocketConnection newsocket;
765 SilcServerKEInternalContext *proto_ctx;
768 SILC_LOG_DEBUG(("Accepting new connection"));
770 sock = silc_net_accept_connection(server->sock);
772 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
776 /* Check max connections */
777 if (sock > SILC_SERVER_MAX_CONNECTIONS) {
778 if (server->config->redirect) {
779 /* XXX Redirecting connection to somewhere else now?? */
780 /*silc_server_send_notify("Server is full, trying to redirect..."); */
782 SILC_LOG_ERROR(("Refusing connection, server is full"));
787 /* Set socket options */
788 silc_net_set_socket_nonblock(sock);
789 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
791 /* We don't create a ID yet, since we don't know what type of connection
792 this is yet. But, we do add the connection to the socket table. */
793 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
794 server->sockets[sock] = newsocket;
796 /* XXX This MUST be done async as this will block the entire server
797 process. Either we have to do our own resolver stuff or in the future
798 we can use threads. */
799 /* Perform mandatory name and address lookups for the remote host. */
800 silc_net_check_host_by_sock(sock, &newsocket->hostname, &newsocket->ip);
801 if (!newsocket->ip || !newsocket->hostname) {
802 SILC_LOG_DEBUG(("IP lookup/DNS lookup failed"));
803 SILC_LOG_ERROR(("IP lookup/DNS lookup failed"));
807 SILC_LOG_INFO(("Incoming connection from %s (%s)", newsocket->hostname,
810 /* Allocate internal context for key exchange protocol. This is
811 sent as context for the protocol. */
812 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
813 proto_ctx->server = context;
814 proto_ctx->sock = newsocket;
815 proto_ctx->rng = server->rng;
816 proto_ctx->responder = TRUE;
818 /* Prepare the connection for key exchange protocol. We allocate the
819 protocol but will not start it yet. The connector will be the
820 initiator of the protocol thus we will wait for initiation from
821 there before we start the protocol. */
822 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
823 &newsocket->protocol, proto_ctx,
824 silc_server_accept_new_connection_second);
826 /* Register a timeout task that will be executed if the connector
827 will not start the key exchange protocol within 60 seconds. For
828 now, this is a hard coded limit. After 60 secs the connection will
829 be closed if the key exchange protocol has not been started. */
830 proto_ctx->timeout_task =
831 silc_task_register(server->timeout_queue, newsocket->sock,
832 silc_server_timeout_remote,
837 /* Register the connection for network input and output. This sets
838 that scheduler will listen for incoming packets for this connection
839 and sets that outgoing packets may be sent to this connection as well.
840 However, this doesn't set the scheduler for outgoing traffic, it
841 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
842 later when outgoing data is available. */
843 SILC_REGISTER_CONNECTION_FOR_IO(sock);
846 /* Second part of accepting new connection. Key exchange protocol has been
847 performed and now it is time to do little connection authentication
848 protocol to figure out whether this connection is client or server
849 and whether it has right to access this server (especially server
850 connections needs to be authenticated). */
852 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
854 SilcProtocol protocol = (SilcProtocol)context;
855 SilcServerKEInternalContext *ctx =
856 (SilcServerKEInternalContext *)protocol->context;
857 SilcServer server = (SilcServer)ctx->server;
858 SilcSocketConnection sock = NULL;
859 SilcServerConnAuthInternalContext *proto_ctx;
861 SILC_LOG_DEBUG(("Start"));
863 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
864 /* Error occured during protocol */
865 silc_protocol_free(protocol);
867 silc_packet_context_free(ctx->packet);
869 silc_ske_free(ctx->ske);
871 silc_free(ctx->dest_id);
874 sock->protocol = NULL;
875 silc_server_disconnect_remote(server, sock, "Server closed connection: "
876 "Key exchange failed");
880 /* Allocate internal context for the authentication protocol. This
881 is sent as context for the protocol. */
882 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
883 proto_ctx->server = (void *)server;
884 proto_ctx->sock = sock = server->sockets[fd];
885 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
886 proto_ctx->responder = TRUE;
887 proto_ctx->dest_id_type = ctx->dest_id_type;
888 proto_ctx->dest_id = ctx->dest_id;
890 /* Free old protocol as it is finished now */
891 silc_protocol_free(protocol);
893 silc_packet_context_free(ctx->packet);
895 sock->protocol = NULL;
897 /* Allocate the authentication protocol. This is allocated here
898 but we won't start it yet. We will be receiving party of this
899 protocol thus we will wait that connecting party will make
901 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
902 &sock->protocol, proto_ctx,
903 silc_server_accept_new_connection_final);
905 /* Register timeout task. If the protocol is not executed inside
906 this timelimit the connection will be terminated. Currently
907 this is 60 seconds and is hard coded limit (XXX). */
908 proto_ctx->timeout_task =
909 silc_task_register(server->timeout_queue, sock->sock,
910 silc_server_timeout_remote,
911 (void *)server, 60, 0,
916 /* Final part of accepting new connection. The connection has now
917 been authenticated and keys has been exchanged. We also know whether
918 this is client or server connection. */
920 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
922 SilcProtocol protocol = (SilcProtocol)context;
923 SilcServerConnAuthInternalContext *ctx =
924 (SilcServerConnAuthInternalContext *)protocol->context;
925 SilcServer server = (SilcServer)ctx->server;
926 SilcSocketConnection sock = ctx->sock;
927 void *id_entry = NULL;
929 SILC_LOG_DEBUG(("Start"));
931 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
932 /* Error occured during protocol */
933 silc_protocol_free(protocol);
935 silc_packet_context_free(ctx->packet);
937 silc_ske_free(ctx->ske);
939 silc_free(ctx->dest_id);
942 sock->protocol = NULL;
943 silc_server_disconnect_remote(server, sock, "Server closed connection: "
944 "Authentication failed");
948 sock->type = ctx->conn_type;
950 case SILC_SOCKET_TYPE_CLIENT:
952 SilcClientEntry client;
954 SILC_LOG_DEBUG(("Remote host is client"));
955 SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
958 /* Add the client to the client ID cache. The nickname and Client ID
959 and other information is created after we have received NEW_CLIENT
960 packet from client. */
961 client = silc_idlist_add_client(server->local_list,
962 NULL, NULL, NULL, NULL, NULL, sock);
964 SILC_LOG_ERROR(("Could not add new client to cache"));
965 silc_free(sock->user_data);
969 id_entry = (void *)client;
972 case SILC_SOCKET_TYPE_SERVER:
973 case SILC_SOCKET_TYPE_ROUTER:
975 SilcServerEntry new_server;
977 SILC_LOG_DEBUG(("Remote host is %s",
978 sock->type == SILC_SOCKET_TYPE_SERVER ?
979 "server" : "router"));
980 SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
981 sock->ip, sock->type == SILC_SOCKET_TYPE_SERVER ?
982 "server" : "router"));
984 /* Add the server into server cache. The server name and Server ID
985 is updated after we have received NEW_SERVER packet from the
988 silc_idlist_add_server(server->local_list, NULL,
989 sock->type == SILC_SOCKET_TYPE_SERVER ?
990 SILC_SERVER : SILC_ROUTER, NULL, NULL, sock);
992 SILC_LOG_ERROR(("Could not add new server to cache"));
993 silc_free(sock->user_data);
997 id_entry = (void *)new_server;
999 /* There is connection to other server now, if it is router then
1000 we will have connection to outside world. If we are router but
1001 normal server connected to us then we will remain standalone,
1002 if we are standlone. */
1003 if (server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER) {
1004 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1005 server->standalone = FALSE;
1006 if (!server->id_entry->router) {
1007 server->id_entry->router = id_entry;
1008 server->router = id_entry;
1017 /* Add the common data structure to the ID entry. */
1019 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1021 /* Add to sockets internal pointer for fast referencing */
1022 silc_free(sock->user_data);
1023 sock->user_data = id_entry;
1025 /* Connection has been fully established now. Everything is ok. */
1026 SILC_LOG_DEBUG(("New connection authenticated"));
1028 silc_protocol_free(protocol);
1030 silc_packet_context_free(ctx->packet);
1032 silc_ske_free(ctx->ske);
1034 silc_free(ctx->dest_id);
1036 sock->protocol = NULL;
1039 /* Internal routine that sends packet or marks packet to be sent. This
1040 is used directly only in special cases. Normal cases should use
1041 silc_server_packet_send. Returns < 0 error. */
1043 static int silc_server_packet_send_real(SilcServer server,
1044 SilcSocketConnection sock,
1049 /* Send the packet */
1050 ret = silc_packet_send(sock, force_send);
1054 /* Mark that there is some outgoing data available for this connection.
1055 This call sets the connection both for input and output (the input
1056 is set always and this call keeps the input setting, actually).
1057 Actual data sending is performed by silc_server_packet_process. */
1058 SILC_SET_CONNECTION_FOR_OUTPUT(sock->sock);
1060 /* Mark to socket that data is pending in outgoing buffer. This flag
1061 is needed if new data is added to the buffer before the earlier
1062 put data is sent to the network. */
1063 SILC_SET_OUTBUF_PENDING(sock);
1069 SilcPacketContext *packetdata;
1071 SilcSocketConnection sock;
1074 } SilcServerInternalPacket;
1076 /* This function is used to read packets from network and send packets to
1077 network. This is usually a generic task. */
1079 SILC_TASK_CALLBACK(silc_server_packet_process)
1081 SilcServer server = (SilcServer)context;
1082 SilcSocketConnection sock = server->sockets[fd];
1083 SilcIDListData idata;
1084 SilcCipher cipher = NULL;
1085 SilcHmac hmac = NULL;
1088 SILC_LOG_DEBUG(("Processing packet"));
1090 /* Packet sending */
1091 if (type == SILC_TASK_WRITE) {
1092 SILC_LOG_DEBUG(("Writing data to connection"));
1094 if (sock->outbuf->data - sock->outbuf->head)
1095 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1097 ret = silc_server_packet_send_real(server, sock, TRUE);
1099 /* If returned -2 could not write to connection now, will do
1104 /* The packet has been sent and now it is time to set the connection
1105 back to only for input. When there is again some outgoing data
1106 available for this connection it will be set for output as well.
1107 This call clears the output setting and sets it only for input. */
1108 SILC_SET_CONNECTION_FOR_INPUT(fd);
1109 SILC_UNSET_OUTBUF_PENDING(sock);
1111 silc_buffer_clear(sock->outbuf);
1115 /* Packet receiving */
1116 SILC_LOG_DEBUG(("Reading data from connection"));
1118 /* Read some data from connection */
1119 ret = silc_packet_receive(sock);
1125 SILC_LOG_DEBUG(("Read EOF"));
1127 /* If connection is disconnecting already we will finally
1128 close the connection */
1129 if (SILC_IS_DISCONNECTING(sock)) {
1130 if (sock->user_data)
1131 silc_server_free_sock_user_data(server, sock);
1132 silc_server_close_connection(server, sock);
1136 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1138 if (sock->user_data)
1139 silc_server_free_sock_user_data(server, sock);
1140 silc_server_close_connection(server, sock);
1144 /* If connection is disconnecting or disconnected we will ignore
1146 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1147 SILC_LOG_DEBUG(("Ignoring read data from invalid connection"));
1151 /* Get keys and stuff from ID entry */
1152 idata = (SilcIDListData)sock->user_data;
1154 idata->last_receive = time(NULL);
1155 cipher = idata->receive_key;
1159 /* Process the packet. This will call the parser that will then
1160 decrypt and parse the packet. */
1161 silc_packet_receive_process(sock, cipher, hmac, silc_server_packet_parse,
1165 /* Parses whole packet, received earlier. */
1167 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1169 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1170 SilcServer server = (SilcServer)parse_ctx->context;
1171 SilcSocketConnection sock = parse_ctx->sock;
1172 SilcPacketContext *packet = parse_ctx->packet;
1173 SilcBuffer buffer = packet->buffer;
1176 SILC_LOG_DEBUG(("Start"));
1178 /* Decrypt the received packet */
1179 ret = silc_packet_decrypt(parse_ctx->cipher, parse_ctx->hmac,
1185 /* Parse the packet. Packet type is returned. */
1186 ret = silc_packet_parse(packet);
1188 /* Parse the packet header in special way as this is "special"
1190 ret = silc_packet_parse_special(packet);
1193 if (ret == SILC_PACKET_NONE)
1196 /* Broadcast packet if it is marked as broadcast packet and it is
1197 originated from router and we are router. */
1198 if (server->server_type == SILC_ROUTER &&
1199 sock->type == SILC_SOCKET_TYPE_ROUTER &&
1200 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
1201 silc_server_packet_broadcast(server, server->router->connection, packet);
1204 /* Parse the incoming packet type */
1205 silc_server_packet_parse_type(server, sock, packet);
1208 silc_buffer_clear(sock->inbuf);
1209 silc_packet_context_free(packet);
1210 silc_free(parse_ctx);
1213 /* Parser callback called by silc_packet_receive_process. This merely
1214 registers timeout that will handle the actual parsing when appropriate. */
1216 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1218 SilcServer server = (SilcServer)parser_context->context;
1219 SilcSocketConnection sock = parser_context->sock;
1221 switch (sock->type) {
1222 case SILC_SOCKET_TYPE_CLIENT:
1223 case SILC_SOCKET_TYPE_UNKNOWN:
1224 /* Parse the packet with timeout */
1225 silc_task_register(server->timeout_queue, sock->sock,
1226 silc_server_packet_parse_real,
1227 (void *)parser_context, 0, 100000,
1229 SILC_TASK_PRI_NORMAL);
1231 case SILC_SOCKET_TYPE_SERVER:
1232 case SILC_SOCKET_TYPE_ROUTER:
1233 /* Packets from servers are parsed as soon as possible */
1234 silc_task_register(server->timeout_queue, sock->sock,
1235 silc_server_packet_parse_real,
1236 (void *)parser_context, 0, 1,
1238 SILC_TASK_PRI_NORMAL);
1245 /* Parses the packet type and calls what ever routines the packet type
1246 requires. This is done for all incoming packets. */
1248 void silc_server_packet_parse_type(SilcServer server,
1249 SilcSocketConnection sock,
1250 SilcPacketContext *packet)
1252 SilcPacketType type = packet->type;
1254 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1256 /* Parse the packet type */
1258 case SILC_PACKET_DISCONNECT:
1259 SILC_LOG_DEBUG(("Disconnect packet"));
1262 case SILC_PACKET_SUCCESS:
1264 * Success received for something. For now we can have only
1265 * one protocol for connection executing at once hence this
1266 * success message is for whatever protocol is executing currently.
1268 SILC_LOG_DEBUG(("Success packet"));
1269 if (sock->protocol) {
1270 sock->protocol->execute(server->timeout_queue, 0,
1271 sock->protocol, sock->sock, 0, 0);
1275 case SILC_PACKET_FAILURE:
1277 * Failure received for something. For now we can have only
1278 * one protocol for connection executing at once hence this
1279 * failure message is for whatever protocol is executing currently.
1281 SILC_LOG_DEBUG(("Failure packet"));
1282 if (sock->protocol) {
1283 /* XXX Audit the failure type */
1284 sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
1285 sock->protocol->execute(server->timeout_queue, 0,
1286 sock->protocol, sock->sock, 0, 0);
1290 case SILC_PACKET_REJECT:
1291 SILC_LOG_DEBUG(("Reject packet"));
1295 case SILC_PACKET_NOTIFY:
1297 * Received notify packet.
1299 SILC_LOG_DEBUG(("Notify packet"));
1305 case SILC_PACKET_CHANNEL_MESSAGE:
1307 * Received channel message. Channel messages are special packets
1308 * (although probably most common ones) hence they are handled
1311 SILC_LOG_DEBUG(("Channel Message packet"));
1312 silc_server_channel_message(server, sock, packet);
1315 case SILC_PACKET_CHANNEL_KEY:
1317 * Received key for channel. As channels are created by the router
1318 * the keys are as well. We will distribute the key to all of our
1319 * locally connected clients on the particular channel. Router
1320 * never receives this channel and thus is ignored.
1322 SILC_LOG_DEBUG(("Channel Key packet"));
1323 silc_server_channel_key(server, sock, packet);
1329 case SILC_PACKET_COMMAND:
1331 * Recived command. Allocate command context and execute the command.
1333 SILC_LOG_DEBUG(("Command packet"));
1334 silc_server_command_process(server, sock, packet);
1337 case SILC_PACKET_COMMAND_REPLY:
1339 * Received command reply packet. Servers never send commands thus
1340 * they don't receive command reply packets either, except in cases
1341 * where server has forwarded command packet coming from client.
1342 * This must be the case here or we will ignore the packet.
1344 SILC_LOG_DEBUG(("Command Reply packet"));
1345 silc_server_packet_relay_command_reply(server, sock, packet);
1349 * Private Message packets
1351 case SILC_PACKET_PRIVATE_MESSAGE:
1353 * Received private message packet. The packet is coming from either
1356 SILC_LOG_DEBUG(("Private Message packet"));
1357 silc_server_private_message(server, sock, packet);
1360 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1364 * Key Exchange protocol packets
1366 case SILC_PACKET_KEY_EXCHANGE:
1367 SILC_LOG_DEBUG(("KE packet"));
1368 if (sock->protocol && sock->protocol->protocol->type
1369 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1371 SilcServerKEInternalContext *proto_ctx =
1372 (SilcServerKEInternalContext *)sock->protocol->context;
1374 proto_ctx->packet = silc_packet_context_dup(packet);
1376 /* Let the protocol handle the packet */
1377 sock->protocol->execute(server->timeout_queue, 0,
1378 sock->protocol, sock->sock, 0, 100000);
1380 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1381 "protocol active, packet dropped."));
1383 /* XXX Trigger KE protocol?? Rekey actually, maybe. */
1387 case SILC_PACKET_KEY_EXCHANGE_1:
1388 SILC_LOG_DEBUG(("KE 1 packet"));
1389 if (sock->protocol && sock->protocol->protocol->type
1390 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1392 SilcServerKEInternalContext *proto_ctx =
1393 (SilcServerKEInternalContext *)sock->protocol->context;
1395 if (proto_ctx->packet)
1396 silc_packet_context_free(proto_ctx->packet);
1398 proto_ctx->packet = silc_packet_context_dup(packet);
1399 proto_ctx->dest_id_type = packet->src_id_type;
1400 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_type);
1402 /* Let the protocol handle the packet */
1403 sock->protocol->execute(server->timeout_queue, 0,
1404 sock->protocol, sock->sock,
1407 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1408 "protocol active, packet dropped."));
1412 case SILC_PACKET_KEY_EXCHANGE_2:
1413 SILC_LOG_DEBUG(("KE 2 packet"));
1414 if (sock->protocol && sock->protocol->protocol->type
1415 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1417 SilcServerKEInternalContext *proto_ctx =
1418 (SilcServerKEInternalContext *)sock->protocol->context;
1420 if (proto_ctx->packet)
1421 silc_packet_context_free(proto_ctx->packet);
1423 proto_ctx->packet = silc_packet_context_dup(packet);
1424 proto_ctx->dest_id_type = packet->src_id_type;
1425 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_type);
1427 /* Let the protocol handle the packet */
1428 sock->protocol->execute(server->timeout_queue, 0,
1429 sock->protocol, sock->sock,
1432 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1433 "protocol active, packet dropped."));
1437 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1438 /* If we receive this packet we will send to the other end information
1439 about our mandatory authentication method for the connection.
1440 This packet maybe received at any time. */
1441 SILC_LOG_DEBUG(("Connection authentication request packet"));
1445 * Connection Authentication protocol packets
1447 case SILC_PACKET_CONNECTION_AUTH:
1448 /* Start of the authentication protocol. We receive here the
1449 authentication data and will verify it. */
1450 SILC_LOG_DEBUG(("Connection auth packet"));
1451 if (sock->protocol && sock->protocol->protocol->type
1452 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1454 SilcServerConnAuthInternalContext *proto_ctx =
1455 (SilcServerConnAuthInternalContext *)sock->protocol->context;
1457 proto_ctx->packet = silc_packet_context_dup(packet);
1459 /* Let the protocol handle the packet */
1460 sock->protocol->execute(server->timeout_queue, 0,
1461 sock->protocol, sock->sock, 0, 0);
1463 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1464 "protocol active, packet dropped."));
1468 case SILC_PACKET_NEW_ID:
1470 * Received New ID packet. This includes some new ID that has been
1471 * created. It may be for client, server or channel. This is the way
1472 * to distribute information about new registered entities in the
1475 SILC_LOG_DEBUG(("New ID packet"));
1476 silc_server_new_id(server, sock, packet);
1479 case SILC_PACKET_NEW_CLIENT:
1481 * Received new client packet. This includes client information that
1482 * we will use to create initial client ID. After creating new
1483 * ID we will send it to the client.
1485 SILC_LOG_DEBUG(("New Client packet"));
1486 silc_server_new_client(server, sock, packet);
1489 case SILC_PACKET_NEW_SERVER:
1491 * Received new server packet. This includes Server ID and some other
1492 * information that we may save. This is received after server has
1495 SILC_LOG_DEBUG(("New Server packet"));
1496 silc_server_new_server(server, sock, packet);
1499 case SILC_PACKET_NEW_CHANNEL:
1502 case SILC_PACKET_NEW_CHANNEL_USER:
1505 case SILC_PACKET_NEW_CHANNEL_LIST:
1508 case SILC_PACKET_NEW_CHANNEL_USER_LIST:
1511 case SILC_PACKET_REPLACE_ID:
1513 * Received replace ID packet. This sends the old ID that is to be
1514 * replaced with the new one included into the packet. Client must not
1517 SILC_LOG_DEBUG(("Replace ID packet"));
1518 silc_server_replace_id(server, sock, packet);
1521 case SILC_PACKET_REMOVE_ID:
1523 * Received remove ID Packet.
1525 SILC_LOG_DEBUG(("Remove ID packet"));
1528 case SILC_PACKET_REMOVE_CHANNEL_USER:
1530 * Received packet to remove user from a channel. Routers notify other
1531 * routers about a user leaving a channel.
1533 SILC_LOG_DEBUG(("Remove Channel User packet"));
1534 silc_server_remove_channel_user(server, sock, packet);
1538 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
1544 /* Assembles a new packet to be sent out to network. This doesn't actually
1545 send the packet but creates the packet and fills the outgoing data
1546 buffer and marks the packet ready to be sent to network. However, If
1547 argument force_send is TRUE the packet is sent immediately and not put
1548 to queue. Normal case is that the packet is not sent immediately. */
1550 void silc_server_packet_send(SilcServer server,
1551 SilcSocketConnection sock,
1552 SilcPacketType type,
1553 SilcPacketFlags flags,
1554 unsigned char *data,
1555 unsigned int data_len,
1558 void *dst_id = NULL;
1559 SilcIdType dst_id_type = SILC_ID_NONE;
1564 /* Get data used in the packet sending, keys and stuff */
1565 switch(sock->type) {
1566 case SILC_SOCKET_TYPE_CLIENT:
1567 dst_id = ((SilcClientEntry)sock->user_data)->id;
1568 dst_id_type = SILC_ID_CLIENT;
1570 case SILC_SOCKET_TYPE_SERVER:
1571 case SILC_SOCKET_TYPE_ROUTER:
1572 dst_id = ((SilcServerEntry)sock->user_data)->id;
1573 dst_id_type = SILC_ID_SERVER;
1579 silc_server_packet_send_dest(server, sock, type, flags, dst_id,
1580 dst_id_type, data, data_len, force_send);
1583 /* Assembles a new packet to be sent out to network. This doesn't actually
1584 send the packet but creates the packet and fills the outgoing data
1585 buffer and marks the packet ready to be sent to network. However, If
1586 argument force_send is TRUE the packet is sent immediately and not put
1587 to queue. Normal case is that the packet is not sent immediately.
1588 Destination information is sent as argument for this function. */
1590 void silc_server_packet_send_dest(SilcServer server,
1591 SilcSocketConnection sock,
1592 SilcPacketType type,
1593 SilcPacketFlags flags,
1595 SilcIdType dst_id_type,
1596 unsigned char *data,
1597 unsigned int data_len,
1600 SilcPacketContext packetdata;
1601 SilcIDListData idata;
1602 SilcCipher cipher = NULL;
1603 SilcHmac hmac = NULL;
1604 unsigned char *dst_id_data = NULL;
1605 unsigned int dst_id_len = 0;
1607 SILC_LOG_DEBUG(("Sending packet, type %d", type));
1609 /* Get data used in the packet sending, keys and stuff */
1610 idata = (SilcIDListData)sock->user_data;
1613 dst_id_data = silc_id_id2str(dst_id, dst_id_type);
1614 dst_id_len = silc_id_get_len(dst_id_type);
1617 /* Set the packet context pointers */
1618 packetdata.type = type;
1619 packetdata.flags = flags;
1620 packetdata.src_id = silc_id_id2str(server->id, server->id_type);
1621 packetdata.src_id_len = SILC_ID_SERVER_LEN;
1622 packetdata.src_id_type = server->id_type;
1623 packetdata.dst_id = dst_id_data;
1624 packetdata.dst_id_len = dst_id_len;
1625 packetdata.dst_id_type = dst_id_type;
1626 packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
1627 packetdata.src_id_len + dst_id_len;
1628 packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
1629 packetdata.rng = server->rng;
1631 /* Prepare outgoing data buffer for packet sending */
1632 silc_packet_send_prepare(sock,
1633 SILC_PACKET_HEADER_LEN +
1634 packetdata.src_id_len +
1635 packetdata.dst_id_len,
1639 SILC_LOG_DEBUG(("Putting data to outgoing buffer, len %d", data_len));
1641 packetdata.buffer = sock->outbuf;
1643 /* Put the data to the buffer */
1644 if (data && data_len)
1645 silc_buffer_put(sock->outbuf, data, data_len);
1647 /* Create the outgoing packet */
1648 silc_packet_assemble(&packetdata);
1651 cipher = idata->send_key;
1655 /* Encrypt the packet */
1656 silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
1658 SILC_LOG_HEXDUMP(("Outgoing packet, len %d", sock->outbuf->len),
1659 sock->outbuf->data, sock->outbuf->len);
1661 /* Now actually send the packet */
1662 silc_server_packet_send_real(server, sock, force_send);
1664 if (packetdata.src_id)
1665 silc_free(packetdata.src_id);
1666 if (packetdata.dst_id)
1667 silc_free(packetdata.dst_id);
1670 /* Forwards packet. Packets sent with this function will be marked as
1671 forwarded (in the SILC header flags) so that the receiver knows that
1672 we have forwarded the packet to it. Forwarded packets are handled
1673 specially by the receiver as they are not destined to the receiver
1674 originally. However, the receiver knows this because the forwarded
1675 flag has been set (and the flag is authenticated). */
1677 void silc_server_packet_forward(SilcServer server,
1678 SilcSocketConnection sock,
1679 unsigned char *data, unsigned int data_len,
1682 SilcIDListData idata;
1683 SilcCipher cipher = NULL;
1684 SilcHmac hmac = NULL;
1686 SILC_LOG_DEBUG(("Forwarding packet"));
1688 /* Get data used in the packet sending, keys and stuff */
1689 idata = (SilcIDListData)sock->user_data;
1691 /* Prepare outgoing data buffer for packet sending */
1692 silc_packet_send_prepare(sock, 0, 0, data_len);
1694 /* Put the data to the buffer */
1695 if (data && data_len)
1696 silc_buffer_put(sock->outbuf, data, data_len);
1698 /* Add the FORWARDED flag to packet flags */
1699 sock->outbuf->data[2] |= (unsigned char)SILC_PACKET_FLAG_FORWARDED;
1702 cipher = idata->send_key;
1706 /* Encrypt the packet */
1707 silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
1709 SILC_LOG_HEXDUMP(("Forwarded packet, len %d", sock->outbuf->len),
1710 sock->outbuf->data, sock->outbuf->len);
1712 /* Now actually send the packet */
1713 silc_server_packet_send_real(server, sock, force_send);
1716 /* Broadcast received packet to our primary route. This function is used
1717 by router to further route received broadcast packet. It is expected
1718 that the broadcast flag from the packet is checked before calling this
1719 function. This does not test or set the broadcast flag. */
1721 void silc_server_packet_broadcast(SilcServer server,
1722 SilcSocketConnection sock,
1723 SilcPacketContext *packet)
1725 SilcBuffer buffer = packet->buffer;
1726 SilcIDListData idata;
1729 SILC_LOG_DEBUG(("Broadcasting received broadcast packet"));
1731 /* If the packet is originated from our primary route we are
1732 not allowed to send the packet. */
1733 id = silc_id_str2id(packet->src_id, packet->src_id_type);
1734 if (id && SILC_ID_SERVER_COMPARE(id, server->router->id)) {
1735 idata = (SilcIDListData)sock->user_data;
1737 silc_buffer_push(buffer, buffer->data - buffer->head);
1738 silc_packet_send_prepare(sock, 0, 0, buffer->len);
1739 silc_buffer_put(sock->outbuf, buffer->data, buffer->len);
1740 silc_packet_encrypt(idata->send_key, idata->hmac,
1741 sock->outbuf, sock->outbuf->len);
1743 SILC_LOG_HEXDUMP(("Broadcasted packet, len %d", sock->outbuf->len),
1744 sock->outbuf->data, sock->outbuf->len);
1746 /* Now actually send the packet */
1747 silc_server_packet_send_real(server, sock, TRUE);
1752 SILC_LOG_DEBUG(("Will not broadcast to primary route since it is the "
1753 "original sender of this packet"));
1757 /* Internal routine to actually create the channel packet and send it
1758 to network. This is common function in channel message sending. If
1759 `channel_message' is TRUE this encrypts the message as it is strictly
1760 a channel message. If FALSE normal encryption process is used. */
1763 silc_server_packet_send_to_channel_real(SilcServer server,
1764 SilcSocketConnection sock,
1765 SilcPacketContext *packet,
1768 unsigned char *data,
1769 unsigned int data_len,
1770 int channel_message,
1773 packet->truelen = data_len + SILC_PACKET_HEADER_LEN +
1774 packet->src_id_len + packet->dst_id_len;
1776 /* Prepare outgoing data buffer for packet sending */
1777 silc_packet_send_prepare(sock,
1778 SILC_PACKET_HEADER_LEN +
1779 packet->src_id_len +
1784 packet->buffer = sock->outbuf;
1786 /* Put the data to buffer, assemble and encrypt the packet. The packet
1787 is encrypted with normal session key shared with the client. */
1788 silc_buffer_put(sock->outbuf, data, data_len);
1789 silc_packet_assemble(packet);
1790 if (channel_message)
1791 silc_packet_encrypt(cipher, hmac, sock->outbuf, SILC_PACKET_HEADER_LEN +
1792 packet->src_id_len + packet->dst_id_len +
1795 silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
1797 SILC_LOG_HEXDUMP(("Channel packet, len %d", sock->outbuf->len),
1798 sock->outbuf->data, sock->outbuf->len);
1800 /* Now actually send the packet */
1801 silc_server_packet_send_real(server, sock, force_send);
1804 /* This routine is used by the server to send packets to channel. The
1805 packet sent with this function is distributed to all clients on
1806 the channel. Usually this is used to send notify messages to the
1807 channel, things like notify about new user joining to the channel. */
1809 void silc_server_packet_send_to_channel(SilcServer server,
1810 SilcChannelEntry channel,
1811 SilcPacketType type,
1812 unsigned char *data,
1813 unsigned int data_len,
1816 SilcSocketConnection sock = NULL;
1817 SilcPacketContext packetdata;
1818 SilcClientEntry client = NULL;
1819 SilcServerEntry *routed = NULL;
1820 SilcChannelClientEntry chl;
1821 SilcIDListData idata;
1822 unsigned int routed_count = 0;
1824 /* This doesn't send channel message packets */
1825 if (type == SILC_PACKET_CHANNEL_MESSAGE)
1828 SILC_LOG_DEBUG(("Sending packet to channel"));
1830 /* Set the packet context pointers. */
1831 packetdata.flags = 0;
1832 packetdata.type = type;
1833 packetdata.src_id = silc_id_id2str(server->id, SILC_ID_SERVER);
1834 packetdata.src_id_len = SILC_ID_SERVER_LEN;
1835 packetdata.src_id_type = SILC_ID_SERVER;
1836 packetdata.dst_id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
1837 packetdata.dst_id_len = SILC_ID_CHANNEL_LEN;
1838 packetdata.dst_id_type = SILC_ID_CHANNEL;
1839 packetdata.rng = server->rng;
1840 packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
1841 packetdata.src_id_len + packetdata.dst_id_len;
1842 packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
1844 /* If there are global users in the channel we will send the message
1845 first to our router for further routing. */
1846 if (server->server_type == SILC_SERVER && !server->standalone &&
1847 channel->global_users) {
1848 SilcServerEntry router;
1850 /* Get data used in packet header encryption, keys and stuff. */
1851 router = server->router;
1852 sock = (SilcSocketConnection)router->connection;
1853 idata = (SilcIDListData)router;
1855 SILC_LOG_DEBUG(("Sending channel message to router for routing"));
1857 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1858 idata->send_key, idata->hmac,
1859 data, data_len, FALSE, force_send);
1862 /* Send the message to clients on the channel's client list. */
1863 silc_list_start(channel->user_list);
1864 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
1865 client = chl->client;
1867 /* If client has router set it is not locally connected client and
1868 we will route the message to the router set in the client. */
1869 if (client && client->router && server->server_type == SILC_ROUTER) {
1872 /* Check if we have sent the packet to this route already */
1873 for (k = 0; k < routed_count; k++)
1874 if (routed[k] == client->router)
1876 if (k < routed_count)
1879 /* Get data used in packet header encryption, keys and stuff. */
1880 sock = (SilcSocketConnection)client->router->connection;
1881 idata = (SilcIDListData)client->router;
1883 /* Send the packet */
1884 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1885 idata->send_key, idata->hmac,
1886 data, data_len, FALSE,
1889 /* We want to make sure that the packet is routed to same router
1890 only once. Mark this route as sent route. */
1892 routed = silc_realloc(routed, sizeof(*routed) * (k + 1));
1893 routed[k] = client->router;
1899 /* Send to locally connected client */
1902 /* Get data used in packet header encryption, keys and stuff. */
1903 sock = (SilcSocketConnection)client->connection;
1904 idata = (SilcIDListData)client;
1906 /* Send the packet */
1907 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1908 idata->send_key, idata->hmac,
1909 data, data_len, FALSE,
1916 silc_free(packetdata.src_id);
1917 silc_free(packetdata.dst_id);
1920 /* This routine is explicitly used to relay messages to some channel.
1921 Packets sent with this function we have received earlier and are
1922 totally encrypted. This just sends the packet to all clients on
1923 the channel. If the sender of the packet is someone on the channel
1924 the message will not be sent to that client. The SILC Packet header
1925 is encrypted with the session key shared between us and the client.
1926 MAC is also computed before encrypting the header. Rest of the
1927 packet will be untouched. */
1929 void silc_server_packet_relay_to_channel(SilcServer server,
1930 SilcSocketConnection sender_sock,
1931 SilcChannelEntry channel,
1933 SilcIdType sender_type,
1934 unsigned char *data,
1935 unsigned int data_len,
1939 SilcSocketConnection sock = NULL;
1940 SilcPacketContext packetdata;
1941 SilcClientEntry client = NULL;
1942 SilcServerEntry *routed = NULL;
1943 SilcChannelClientEntry chl;
1944 unsigned int routed_count = 0;
1945 SilcIDListData idata;
1947 SILC_LOG_DEBUG(("Relaying packet to channel"));
1949 /* Set the packet context pointers. */
1950 packetdata.flags = 0;
1951 packetdata.type = SILC_PACKET_CHANNEL_MESSAGE;
1952 packetdata.src_id = silc_id_id2str(sender, sender_type);
1953 packetdata.src_id_len = silc_id_get_len(sender_type);
1954 packetdata.src_id_type = sender_type;
1955 packetdata.dst_id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
1956 packetdata.dst_id_len = SILC_ID_CHANNEL_LEN;
1957 packetdata.dst_id_type = SILC_ID_CHANNEL;
1958 packetdata.rng = server->rng;
1959 packetdata.padlen = SILC_PACKET_PADLEN((SILC_PACKET_HEADER_LEN +
1960 packetdata.src_id_len +
1961 packetdata.dst_id_len));
1963 /* If there are global users in the channel we will send the message
1964 first to our router for further routing. */
1965 if (server->server_type == SILC_SERVER && !server->standalone &&
1966 channel->global_users) {
1967 SilcServerEntry router;
1969 router = server->router;
1971 /* Check that the sender is not our router. */
1972 if (sender_sock != (SilcSocketConnection)router->connection) {
1974 /* Get data used in packet header encryption, keys and stuff. */
1975 sock = (SilcSocketConnection)router->connection;
1976 idata = (SilcIDListData)router;
1978 SILC_LOG_DEBUG(("Sending channel message to router for routing"));
1980 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1981 idata->send_key, idata->hmac,
1982 data, data_len, TRUE,
1987 /* Send the message to clients on the channel's client list. */
1988 silc_list_start(channel->user_list);
1989 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
1990 client = chl->client;
1994 /* If sender is one on the channel do not send it the packet. */
1995 if (!found && !SILC_ID_CLIENT_COMPARE(client->id, sender)) {
2000 /* If the client has set router it means that it is not locally
2001 connected client and we will route the packet further. */
2002 if (server->server_type == SILC_ROUTER && client->router) {
2005 /* Sender maybe server as well so we want to make sure that
2006 we won't send the message to the server it came from. */
2007 if (!found && !SILC_ID_SERVER_COMPARE(client->router->id, sender)) {
2012 /* Check if we have sent the packet to this route already */
2013 for (k = 0; k < routed_count; k++)
2014 if (routed[k] == client->router)
2016 if (k < routed_count)
2019 /* Get data used in packet header encryption, keys and stuff. */
2020 sock = (SilcSocketConnection)client->router->connection;
2021 idata = (SilcIDListData)client->router;
2023 /* Send the packet */
2024 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
2025 idata->send_key, idata->hmac,
2026 data, data_len, TRUE,
2029 /* We want to make sure that the packet is routed to same router
2030 only once. Mark this route as sent route. */
2032 routed = silc_realloc(routed, sizeof(*routed) * (k + 1));
2033 routed[k] = client->router;
2039 /* XXX Check client's mode on the channel. */
2041 /* Get data used in packet header encryption, keys and stuff. */
2042 sock = (SilcSocketConnection)client->connection;
2043 idata = (SilcIDListData)client;
2045 SILC_LOG_DEBUG(("Sending packet to client %s",
2046 sock->hostname ? sock->hostname : sock->ip));
2048 /* Send the packet */
2049 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
2050 idata->send_key, idata->hmac,
2051 data, data_len, TRUE,
2056 silc_free(packetdata.src_id);
2057 silc_free(packetdata.dst_id);
2060 /* This function is used to send packets strictly to all local clients
2061 on a particular channel. This is used for example to distribute new
2062 channel key to all our locally connected clients on the channel.
2063 The packets are always encrypted with the session key shared between
2064 the client, this means these are not _to the channel_ but _to the client_
2067 void silc_server_packet_send_local_channel(SilcServer server,
2068 SilcChannelEntry channel,
2069 SilcPacketType type,
2070 SilcPacketFlags flags,
2071 unsigned char *data,
2072 unsigned int data_len,
2075 SilcClientEntry client;
2076 SilcChannelClientEntry chl;
2077 SilcSocketConnection sock = NULL;
2079 SILC_LOG_DEBUG(("Start"));
2081 /* Send the message to clients on the channel's client list. */
2082 silc_list_start(channel->user_list);
2083 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2084 client = chl->client;
2087 sock = (SilcSocketConnection)client->connection;
2089 /* Send the packet to the client */
2090 silc_server_packet_send_dest(server, sock, type, flags, client->id,
2091 SILC_ID_CLIENT, data, data_len,
2097 /* Relays received command reply packet to the correct destination. The
2098 destination must be one of our locally connected client or the packet
2099 will be ignored. This is called when server has forwarded one of
2100 client's command request to router and router has now replied to the
2103 void silc_server_packet_relay_command_reply(SilcServer server,
2104 SilcSocketConnection sock,
2105 SilcPacketContext *packet)
2107 SilcBuffer buffer = packet->buffer;
2108 SilcClientEntry client;
2110 SilcSocketConnection dst_sock;
2111 SilcIDListData idata;
2113 SILC_LOG_DEBUG(("Start"));
2115 /* Source must be server or router */
2116 if (packet->src_id_type != SILC_ID_SERVER &&
2117 sock->type != SILC_SOCKET_TYPE_ROUTER)
2120 /* Destination must be client */
2121 if (packet->dst_id_type != SILC_ID_CLIENT)
2124 /* Execute command reply locally for the command */
2125 silc_server_command_reply_process(server, sock, buffer);
2127 id = silc_id_str2id(packet->dst_id, SILC_ID_CLIENT);
2129 /* Destination must be one of ours */
2130 client = silc_idlist_find_client_by_id(server->local_list, id);
2132 SILC_LOG_ERROR(("Cannot relay command reply to unknown client"));
2137 /* Relay the packet to the client */
2139 dst_sock = (SilcSocketConnection)client->connection;
2140 silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len
2141 + packet->dst_id_len + packet->padlen);
2143 silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
2144 silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
2146 idata = (SilcIDListData)client;
2148 /* Encrypt packet */
2149 silc_packet_encrypt(idata->send_key, idata->hmac, dst_sock->outbuf,
2152 /* Send the packet */
2153 silc_server_packet_send_real(server, dst_sock, TRUE);
2158 /* Closes connection to socket connection */
2160 void silc_server_close_connection(SilcServer server,
2161 SilcSocketConnection sock)
2164 SILC_LOG_DEBUG(("Closing connection %d", sock->sock));
2166 /* We won't listen for this connection anymore */
2167 silc_schedule_unset_listen_fd(sock->sock);
2169 /* Unregister all tasks */
2170 silc_task_unregister_by_fd(server->io_queue, sock->sock);
2171 silc_task_unregister_by_fd(server->timeout_queue, sock->sock);
2173 /* Close the actual connection */
2174 silc_net_close_connection(sock->sock);
2175 server->sockets[sock->sock] = NULL;
2176 silc_socket_free(sock);
2179 /* Sends disconnect message to remote connection and disconnects the
2182 void silc_server_disconnect_remote(SilcServer server,
2183 SilcSocketConnection sock,
2184 const char *fmt, ...)
2187 unsigned char buf[4096];
2189 memset(buf, 0, sizeof(buf));
2191 vsprintf(buf, fmt, ap);
2194 SILC_LOG_DEBUG(("Disconnecting remote host"));
2196 /* Notify remote end that the conversation is over. The notify message
2197 is tried to be sent immediately. */
2198 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2199 buf, strlen(buf), TRUE);
2201 /* Mark the connection to be disconnected */
2202 SILC_SET_DISCONNECTED(sock);
2203 silc_server_close_connection(server, sock);
2206 /* Free's user_data pointer from socket connection object. As this
2207 pointer maybe anything we wil switch here to find the correct
2208 data type and free it the way it needs to be free'd. */
2210 void silc_server_free_sock_user_data(SilcServer server,
2211 SilcSocketConnection sock)
2213 SILC_LOG_DEBUG(("Start"));
2215 switch(sock->type) {
2216 case SILC_SOCKET_TYPE_CLIENT:
2218 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2220 /* Remove client from all channels */
2221 silc_server_remove_from_channels(server, sock, user_data);
2223 /* XXX must take some info to history before freeing */
2225 /* Free the client entry and everything in it */
2226 silc_idlist_del_data(user_data);
2227 silc_idlist_del_client(server->local_list, user_data);
2230 case SILC_SOCKET_TYPE_SERVER:
2231 case SILC_SOCKET_TYPE_ROUTER:
2239 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2241 silc_idlist_del_data(user_data);
2242 silc_free(user_data);
2247 sock->user_data = NULL;
2250 /* Removes client from all channels it has joined. This is used when
2251 client connection is disconnected. If the client on a channel
2252 is last, the channel is removed as well. */
2254 void silc_server_remove_from_channels(SilcServer server,
2255 SilcSocketConnection sock,
2256 SilcClientEntry client)
2258 SilcChannelEntry channel;
2259 SilcChannelClientEntry chl;
2260 SilcBuffer chidp, clidp;
2262 SILC_LOG_DEBUG(("Start"));
2264 if (!client || !client->id)
2267 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2269 /* Remove the client from all channels. The client is removed from
2270 the channels' user list. */
2271 silc_list_start(client->channels);
2272 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2273 channel = chl->channel;
2274 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
2276 /* Remove from list */
2277 silc_list_del(client->channels, chl);
2279 /* If this client is last one on the channel the channel
2280 is removed all together. */
2281 if (silc_list_count(channel->user_list) < 2) {
2283 /* However, if the channel has marked global users then the
2284 channel is not created locally, and this does not remove the
2285 channel globally from SILC network, in this case we will
2286 notify that this client has left the channel. */
2287 if (channel->global_users)
2288 silc_server_send_notify_to_channel(server, channel,
2289 SILC_NOTIFY_TYPE_SIGNOFF, 1,
2290 clidp->data, clidp->len);
2292 silc_idlist_del_channel(server->local_list, channel);
2296 /* Remove from list */
2297 silc_list_del(channel->user_list, chl);
2300 /* Send notify to channel about client leaving SILC and thus
2301 the entire channel. */
2302 silc_server_send_notify_to_channel(server, channel,
2303 SILC_NOTIFY_TYPE_SIGNOFF, 1,
2304 clidp->data, clidp->len);
2305 silc_buffer_free(chidp);
2308 silc_buffer_free(clidp);
2311 /* Removes client from one channel. This is used for example when client
2312 calls LEAVE command to remove itself from the channel. Returns TRUE
2313 if channel still exists and FALSE if the channel is removed when
2314 last client leaves the channel. If `notify' is FALSE notify messages
2317 int silc_server_remove_from_one_channel(SilcServer server,
2318 SilcSocketConnection sock,
2319 SilcChannelEntry channel,
2320 SilcClientEntry client,
2323 SilcChannelEntry ch;
2324 SilcChannelClientEntry chl;
2327 SILC_LOG_DEBUG(("Start"));
2329 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2331 /* Remove the client from the channel. The client is removed from
2332 the channel's user list. */
2333 silc_list_start(client->channels);
2334 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2335 if (chl->channel != channel)
2340 /* Remove from list */
2341 silc_list_del(client->channels, chl);
2343 /* If this client is last one on the channel the channel
2344 is removed all together. */
2345 if (silc_list_count(channel->user_list) < 2) {
2346 /* Notify about leaving client if this channel has global users,
2347 ie. the channel is not created locally. */
2348 if (notify && channel->global_users)
2349 silc_server_send_notify_to_channel(server, channel,
2350 SILC_NOTIFY_TYPE_LEAVE, 1,
2351 clidp->data, clidp->len);
2353 silc_idlist_del_channel(server->local_list, channel);
2354 silc_buffer_free(clidp);
2358 /* Remove from list */
2359 silc_list_del(channel->user_list, chl);
2362 /* Send notify to channel about client leaving the channel */
2364 silc_server_send_notify_to_channel(server, channel,
2365 SILC_NOTIFY_TYPE_LEAVE, 1,
2366 clidp->data, clidp->len);
2370 silc_buffer_free(clidp);
2374 /* Returns TRUE if the given client is on the channel. FALSE if not.
2375 This works because we assure that the user list on the channel is
2376 always in up to date thus we can only check the channel list from
2377 `client' which is faster than checking the user list from `channel'. */
2379 int silc_server_client_on_channel(SilcClientEntry client,
2380 SilcChannelEntry channel)
2382 SilcChannelClientEntry chl;
2384 if (!client || !channel)
2387 silc_list_start(client->channels);
2388 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END)
2389 if (chl->channel == channel)
2395 /* Timeout callback. This is called if connection is idle or for some
2396 other reason is not responding within some period of time. This
2397 disconnects the remote end. */
2399 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2401 SilcServerConnection sconn = (SilcServerConnection)context;
2402 SilcSocketConnection sock = sconn->server->sockets[fd];
2404 silc_server_disconnect_remote(sconn->server, sock,
2405 "Server closed connection: "
2406 "Connection timeout");
2409 /* Internal routine used to send (relay, route) private messages to some
2410 destination. If the private message key does not exist then the message
2411 is re-encrypted, otherwise we just pass it along. */
2414 silc_server_private_message_send_internal(SilcServer server,
2415 SilcSocketConnection dst_sock,
2418 SilcPacketContext *packet)
2420 SilcBuffer buffer = packet->buffer;
2422 /* Send and re-encrypt if private messge key does not exist */
2423 if ((packet->flags & SILC_PACKET_FLAG_PRIVMSG_KEY) == FALSE) {
2425 silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len
2426 + packet->dst_id_len + packet->padlen);
2427 silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
2428 silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
2430 /* Re-encrypt packet */
2431 silc_packet_encrypt(cipher, hmac, dst_sock->outbuf, buffer->len);
2433 /* Send the packet */
2434 silc_server_packet_send_real(server, dst_sock, FALSE);
2437 /* Key exist so just send it */
2438 silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len
2439 + packet->dst_id_len + packet->padlen);
2440 silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
2441 silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
2442 silc_server_packet_send_real(server, dst_sock, FALSE);
2446 /* Received private message. This resolves the destination of the message
2447 and sends the packet. This is used by both server and router. If the
2448 destination is our locally connected client this sends the packet to
2449 the client. This may also send the message for further routing if
2450 the destination is not in our server (or router). */
2452 void silc_server_private_message(SilcServer server,
2453 SilcSocketConnection sock,
2454 SilcPacketContext *packet)
2457 SilcServerEntry router;
2458 SilcSocketConnection dst_sock;
2459 SilcClientEntry client;
2460 SilcIDListData idata;
2462 SILC_LOG_DEBUG(("Start"));
2464 if (!packet->dst_id) {
2465 SILC_LOG_ERROR(("Bad Client ID in private message packet, dropped"));
2469 /* Decode destination Client ID */
2470 id = silc_id_str2id(packet->dst_id, SILC_ID_CLIENT);
2472 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
2476 /* If the destination belongs to our server we don't have to route
2477 the message anywhere but to send it to the local destination. */
2478 client = silc_idlist_find_client_by_id(server->local_list, id);
2480 /* It exists, now deliver the message to the destination */
2481 dst_sock = (SilcSocketConnection)client->connection;
2483 /* If we are router and the client has router then the client is in
2484 our cell but not directly connected to us. */
2485 if (server->server_type == SILC_ROUTER && client->router) {
2486 /* We are of course in this case the client's router thus the real
2487 "router" of the client is the server who owns the client. Thus
2488 we will send the packet to that server. */
2489 router = (SilcServerEntry)dst_sock->user_data;
2490 idata = (SilcIDListData)router;
2491 // assert(client->router == server->id_entry);
2493 silc_server_private_message_send_internal(server, dst_sock,
2500 /* Seems that client really is directly connected to us */
2501 idata = (SilcIDListData)client;
2502 silc_server_private_message_send_internal(server, dst_sock,
2504 idata->hmac, packet);
2508 /* Destination belongs to someone not in this server. If we are normal
2509 server our action is to send the packet to our router. */
2510 if (server->server_type == SILC_SERVER && !server->standalone) {
2511 router = server->router;
2513 /* Send to primary route */
2515 dst_sock = (SilcSocketConnection)router->connection;
2516 idata = (SilcIDListData)router;
2517 silc_server_private_message_send_internal(server, dst_sock,
2519 idata->hmac, packet);
2524 /* We are router and we will perform route lookup for the destination
2525 and send the message to fastest route. */
2526 if (server->server_type == SILC_ROUTER && !server->standalone) {
2527 dst_sock = silc_server_get_route(server, id, SILC_ID_CLIENT);
2528 router = (SilcServerEntry)dst_sock->user_data;
2529 idata = (SilcIDListData)router;
2531 /* Get fastest route and send packet. */
2533 silc_server_private_message_send_internal(server, dst_sock,
2535 idata->hmac, packet);
2540 silc_server_send_error(server, sock,
2541 "No such nickname: Private message not sent");
2544 /* Process received channel message. The message can be originated from
2545 client or server. */
2547 void silc_server_channel_message(SilcServer server,
2548 SilcSocketConnection sock,
2549 SilcPacketContext *packet)
2551 SilcChannelEntry channel = NULL;
2552 SilcChannelClientEntry chl;
2553 SilcChannelID *id = NULL;
2554 void *sender = NULL;
2556 SILC_LOG_DEBUG(("Processing channel message"));
2559 if (packet->dst_id_type != SILC_ID_CHANNEL) {
2560 SILC_LOG_ERROR(("Received bad message for channel, dropped"));
2561 SILC_LOG_DEBUG(("Received bad message for channel, dropped"));
2565 /* Find channel entry */
2566 id = silc_id_str2id(packet->dst_id, SILC_ID_CHANNEL);
2567 channel = silc_idlist_find_channel_by_id(server->local_list, id);
2569 SILC_LOG_DEBUG(("Could not find channel"));
2573 /* See that this client is on the channel. If the message is coming
2574 from router we won't do the check as the message is from client that
2575 we don't know about. Also, if the original sender is not client
2576 (as it can be server as well) we don't do the check. */
2577 sender = silc_id_str2id(packet->src_id, packet->src_id_type);
2578 if (sock->type != SILC_SOCKET_TYPE_ROUTER &&
2579 packet->src_id_type == SILC_ID_CLIENT) {
2580 silc_list_start(channel->user_list);
2581 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2582 if (chl->client && !SILC_ID_CLIENT_COMPARE(chl->client->id, sender))
2585 if (chl == SILC_LIST_END)
2589 /* Distribute the packet to our local clients. This will send the
2590 packet for further routing as well, if needed. */
2591 silc_server_packet_relay_to_channel(server, sock, channel, sender,
2592 packet->src_id_type,
2593 packet->buffer->data,
2594 packet->buffer->len, FALSE);
2603 /* Received channel key packet. We distribute the key to all of our locally
2604 connected clients on the channel. */
2605 /* XXX Router must accept this packet and distribute the key to all its
2606 server that has clients on the channel */
2608 void silc_server_channel_key(SilcServer server,
2609 SilcSocketConnection sock,
2610 SilcPacketContext *packet)
2612 SilcBuffer buffer = packet->buffer;
2613 SilcChannelKeyPayload payload = NULL;
2614 SilcChannelID *id = NULL;
2615 SilcChannelEntry channel;
2616 SilcChannelClientEntry chl;
2618 unsigned int tmp_len;
2621 if (packet->src_id_type != SILC_ID_SERVER &&
2622 sock->type != SILC_SOCKET_TYPE_ROUTER)
2625 /* Decode channel key payload */
2626 payload = silc_channel_key_payload_parse(buffer);
2628 SILC_LOG_ERROR(("Bad channel key payload, dropped"));
2632 /* Get channel ID */
2633 tmp = silc_channel_key_get_id(payload, &tmp_len);
2634 id = silc_id_payload_parse_id(tmp, tmp_len);
2638 /* Get the channel entry */
2639 channel = silc_idlist_find_channel_by_id(server->local_list, id);
2641 SILC_LOG_ERROR(("Received key for non-existent channel"));
2645 /* Save the key for us as well */
2646 tmp = silc_channel_key_get_key(payload, &tmp_len);
2649 cipher = silc_channel_key_get_cipher(payload, NULL);;
2652 if (!silc_cipher_alloc(cipher, &channel->channel_key))
2655 /* Distribute the key to all clients on the channel */
2656 silc_list_start(channel->user_list);
2657 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2658 silc_server_packet_send(server, chl->client->connection,
2659 SILC_PACKET_CHANNEL_KEY, 0,
2660 buffer->data, buffer->len, TRUE);
2663 channel->key_len = tmp_len * 8;
2664 channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
2665 memcpy(channel->key, tmp, tmp_len);
2666 channel->channel_key->cipher->set_key(channel->channel_key->context,
2672 silc_channel_key_payload_free(payload);
2675 /* Sends current motd to client */
2677 void silc_server_send_motd(SilcServer server,
2678 SilcSocketConnection sock)
2683 if (server->config && server->config->motd &&
2684 server->config->motd->motd_file) {
2686 motd = silc_file_read(server->config->motd->motd_file, &motd_len);
2690 silc_server_send_notify(server, sock, SILC_NOTIFY_TYPE_MOTD, 1,
2696 /* Sends error message. Error messages may or may not have any
2699 void silc_server_send_error(SilcServer server,
2700 SilcSocketConnection sock,
2701 const char *fmt, ...)
2704 unsigned char buf[4096];
2706 memset(buf, 0, sizeof(buf));
2708 vsprintf(buf, fmt, ap);
2711 silc_server_packet_send(server, sock, SILC_PACKET_ERROR, 0,
2712 buf, strlen(buf), FALSE);
2715 /* Sends notify message. If format is TRUE the variable arguments are
2716 formatted and the formatted string is sent as argument payload. If it is
2717 FALSE then each argument is sent as separate argument and their format
2718 in the argument list must be { argument data, argument length }. */
2720 void silc_server_send_notify(SilcServer server,
2721 SilcSocketConnection sock,
2722 SilcNotifyType type,
2723 unsigned int argc, ...)
2730 packet = silc_notify_payload_encode(type, argc, ap);
2731 silc_server_packet_send(server, sock, SILC_PACKET_NOTIFY, 0,
2732 packet->data, packet->len, FALSE);
2733 silc_buffer_free(packet);
2736 /* Sends notify message destined to specific entity. */
2738 void silc_server_send_notify_dest(SilcServer server,
2739 SilcSocketConnection sock,
2741 SilcIdType dest_id_type,
2742 SilcNotifyType type,
2743 unsigned int argc, ...)
2750 packet = silc_notify_payload_encode(type, argc, ap);
2751 silc_server_packet_send_dest(server, sock, SILC_PACKET_NOTIFY, 0,
2752 dest_id, dest_id_type,
2753 packet->data, packet->len, FALSE);
2754 silc_buffer_free(packet);
2757 /* Sends notify message to a channel. The notify message sent is
2758 distributed to all clients on the channel. */
2760 void silc_server_send_notify_to_channel(SilcServer server,
2761 SilcChannelEntry channel,
2762 SilcNotifyType type,
2763 unsigned int argc, ...)
2770 packet = silc_notify_payload_encode(type, argc, ap);
2771 silc_server_packet_send_to_channel(server, channel,
2773 packet->data, packet->len, FALSE);
2774 silc_buffer_free(packet);
2777 /* Send notify message to all clients the client has joined. It is quaranteed
2778 that the message is sent only once to a client (ie. if a client is joined
2779 on two same channel it will receive only one notify message). Also, this
2780 sends only to local clients (locally connected if we are server, and to
2781 local servers if we are router). */
2783 void silc_server_send_notify_on_channels(SilcServer server,
2784 SilcClientEntry client,
2785 SilcNotifyType type,
2786 unsigned int argc, ...)
2789 SilcSocketConnection sock = NULL;
2790 SilcPacketContext packetdata;
2792 SilcClientEntry *sent_clients = NULL;
2793 unsigned int sent_clients_count = 0;
2794 SilcServerEntry *routed = NULL;
2795 unsigned int routed_count = 0;
2796 SilcChannelEntry channel;
2797 SilcChannelClientEntry chl, chl2;
2798 SilcIDListData idata;
2800 unsigned char *data;
2801 unsigned int data_len;
2802 int force_send = FALSE;
2805 if (!silc_list_count(client->channels))
2809 packet = silc_notify_payload_encode(type, argc, ap);
2810 data = packet->data;
2811 data_len = packet->len;
2813 /* Set the packet context pointers. */
2814 packetdata.flags = 0;
2815 packetdata.type = SILC_PACKET_NOTIFY;
2816 packetdata.src_id = silc_id_id2str(server->id, SILC_ID_SERVER);
2817 packetdata.src_id_len = SILC_ID_SERVER_LEN;
2818 packetdata.src_id_type = SILC_ID_SERVER;
2819 packetdata.rng = server->rng;
2821 silc_list_start(client->channels);
2822 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2823 channel = chl->channel;
2825 /* Send the message to all clients on the channel's client list. */
2826 silc_list_start(channel->user_list);
2827 while ((chl2 = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2830 /* Check if we have sent the packet to this client already */
2831 for (k = 0; k < sent_clients_count; k++)
2832 if (sent_clients[k] == c)
2834 if (k < sent_clients_count)
2837 /* If we are router and if this client has router set it is not
2838 locally connected client and we will route the message to the
2839 router set in the client. */
2840 if (c && c->router && server->server_type == SILC_ROUTER) {
2841 /* Check if we have sent the packet to this route already */
2842 for (k = 0; k < routed_count; k++)
2843 if (routed[k] == c->router)
2845 if (k < routed_count)
2848 /* Get data used in packet header encryption, keys and stuff. */
2849 sock = (SilcSocketConnection)c->router->connection;
2850 idata = (SilcIDListData)c->router;
2852 packetdata.dst_id = silc_id_id2str(c->router->id, SILC_ID_SERVER);
2853 packetdata.dst_id_len = SILC_ID_SERVER_LEN;
2854 packetdata.dst_id_type = SILC_ID_SERVER;
2855 packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
2856 packetdata.src_id_len + packetdata.dst_id_len;
2857 packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
2859 /* Send the packet */
2860 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
2861 idata->send_key, idata->hmac,
2862 data, data_len, FALSE,
2865 silc_free(packetdata.dst_id);
2867 /* We want to make sure that the packet is routed to same router
2868 only once. Mark this route as sent route. */
2870 routed = silc_realloc(routed, sizeof(*routed) * (k + 1));
2871 routed[k] = c->router;
2877 /* Send to locally connected client */
2880 /* Get data used in packet header encryption, keys and stuff. */
2881 sock = (SilcSocketConnection)c->connection;
2882 idata = (SilcIDListData)c;
2884 packetdata.dst_id = silc_id_id2str(c->id, SILC_ID_CLIENT);
2885 packetdata.dst_id_len = SILC_ID_CLIENT_LEN;
2886 packetdata.dst_id_type = SILC_ID_CLIENT;
2887 packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
2888 packetdata.src_id_len + packetdata.dst_id_len;
2889 packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
2891 /* Send the packet */
2892 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
2893 idata->send_key, idata->hmac,
2894 data, data_len, FALSE,
2897 silc_free(packetdata.dst_id);
2899 /* Make sure that we send the notify only once per client. */
2900 sent_clients = silc_realloc(sent_clients, sizeof(*sent_clients) *
2901 (sent_clients_count + 1));
2902 sent_clients[sent_clients_count] = c;
2903 sent_clients_count++;
2910 if (sent_clients_count)
2911 silc_free(sent_clients);
2912 silc_free(packetdata.src_id);
2915 /* Sends New ID Payload to remote end. The packet is used to distribute
2916 information about new registered clients, servers, channel etc. usually
2917 to routers so that they can keep these information up to date.
2918 If the argument `broadcast' is TRUE then the packet is sent as
2919 broadcast packet. */
2921 void silc_server_send_new_id(SilcServer server,
2922 SilcSocketConnection sock,
2924 void *id, SilcIdType id_type,
2925 unsigned int id_len)
2929 idp = silc_id_payload_encode(id, id_type);
2930 silc_server_packet_send(server, sock, SILC_PACKET_NEW_ID,
2931 broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
2932 idp->data, idp->len, FALSE);
2933 silc_buffer_free(idp);
2936 /* Sends Replace ID payload to remote end. This is used to replace old
2937 ID with new ID sent in the packet. This is called for example when
2938 user changes nickname and we create new ID for the user. If the
2939 argument `broadcast' is TRUE then the packet is sent as
2940 broadcast packet. */
2941 /* XXX It would be expected that the new id is same type as the old
2944 void silc_server_send_replace_id(SilcServer server,
2945 SilcSocketConnection sock,
2947 void *old_id, SilcIdType old_id_type,
2948 unsigned int old_id_len,
2949 void *new_id, SilcIdType new_id_type,
2950 unsigned int new_id_len)
2956 oid = silc_id_id2str(old_id, old_id_type);
2960 nid = silc_id_id2str(new_id, new_id_type);
2964 packet = silc_buffer_alloc(2 + 2 + 2 + 2 + old_id_len + new_id_len);
2965 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
2966 silc_buffer_format(packet,
2967 SILC_STR_UI_SHORT(old_id_type),
2968 SILC_STR_UI_SHORT(old_id_len),
2969 SILC_STR_UI_XNSTRING(oid, old_id_len),
2970 SILC_STR_UI_SHORT(new_id_type),
2971 SILC_STR_UI_SHORT(new_id_len),
2972 SILC_STR_UI_XNSTRING(nid, new_id_len),
2975 silc_server_packet_send(server, sock, SILC_PACKET_REPLACE_ID,
2976 broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
2977 packet->data, packet->len, FALSE);
2980 silc_buffer_free(packet);
2983 /* This function is used to send Remove Channel User payload. This may sent
2984 by server but is usually used only by router to notify other routers that
2985 user has left a channel. Normal server sends this packet to its router
2986 to notify that the router should not hold a record about this client
2987 on a channel anymore. Router distributes it further to other routers. */
2989 void silc_server_send_remove_channel_user(SilcServer server,
2990 SilcSocketConnection sock,
2992 void *client_id, void *channel_id)
2995 unsigned char *clid, *chid;
2997 clid = silc_id_id2str(client_id, SILC_ID_CLIENT);
3001 chid = silc_id_id2str(channel_id, SILC_ID_CHANNEL);
3005 packet = silc_buffer_alloc(2 + 2 + SILC_ID_CLIENT_LEN + SILC_ID_CHANNEL_LEN);
3006 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
3007 silc_buffer_format(packet,
3008 SILC_STR_UI_SHORT(SILC_ID_CLIENT_LEN),
3009 SILC_STR_UI_XNSTRING(clid, SILC_ID_CLIENT_LEN),
3010 SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
3011 SILC_STR_UI_XNSTRING(chid, SILC_ID_CHANNEL_LEN),
3014 silc_server_packet_send(server, sock, SILC_PACKET_REMOVE_CHANNEL_USER,
3015 broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
3016 packet->data, packet->len, FALSE);
3019 silc_buffer_free(packet);
3022 /* Received packet to replace a ID. This checks that the requested ID
3023 exists and replaces it with the new one. */
3025 void silc_server_replace_id(SilcServer server,
3026 SilcSocketConnection sock,
3027 SilcPacketContext *packet)
3029 SilcBuffer buffer = packet->buffer;
3030 unsigned char *old_id = NULL, *new_id = NULL;
3031 SilcIdType old_id_type, new_id_type;
3032 unsigned short old_id_len, new_id_len;
3033 void *id = NULL, *id2 = NULL;
3035 if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3036 packet->src_id_type == SILC_ID_CLIENT)
3039 SILC_LOG_DEBUG(("Replacing ID"));
3041 silc_buffer_unformat(buffer,
3042 SILC_STR_UI_SHORT(&old_id_type),
3043 SILC_STR_UI16_NSTRING_ALLOC(&old_id, &old_id_len),
3044 SILC_STR_UI_SHORT(&new_id_type),
3045 SILC_STR_UI16_NSTRING_ALLOC(&new_id, &new_id_len),
3048 if (old_id_type != new_id_type)
3051 if (old_id_len != silc_id_get_len(old_id_type) ||
3052 new_id_len != silc_id_get_len(new_id_type))
3055 id = silc_id_str2id(old_id, old_id_type);
3059 id2 = silc_id_str2id(new_id, new_id_type);
3063 /* If we are router and this packet is not already broadcast packet
3064 we will broadcast it. The sending socket really cannot be router or
3065 the router is buggy. If this packet is coming from router then it must
3066 have the broadcast flag set already and we won't do anything. */
3067 if (server->server_type == SILC_ROUTER &&
3068 sock->type == SILC_SOCKET_TYPE_SERVER &&
3069 !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
3070 SILC_LOG_DEBUG(("Broadcasting received Replace ID packet"));
3071 silc_server_packet_send(server, server->router->connection, packet->type,
3072 packet->flags | SILC_PACKET_FLAG_BROADCAST,
3073 buffer->data, buffer->len, FALSE);
3076 /* Replace the old ID */
3077 switch(old_id_type) {
3078 case SILC_ID_CLIENT:
3079 if (silc_idlist_replace_client_id(server->local_list, id, id2) == NULL)
3080 if (server->server_type == SILC_ROUTER)
3081 silc_idlist_replace_client_id(server->global_list, id, id2);
3084 case SILC_ID_SERVER:
3085 if (silc_idlist_replace_server_id(server->local_list, id, id2) == NULL)
3086 if (server->server_type == SILC_ROUTER)
3087 silc_idlist_replace_server_id(server->global_list, id, id2);
3090 case SILC_ID_CHANNEL:
3091 /* XXX Hmm... Basically this cannot occur. Channel ID's cannot be
3110 /* Creates new channel. */
3112 SilcChannelEntry silc_server_new_channel(SilcServer server,
3113 SilcServerID *router_id,
3114 char *cipher, char *channel_name)
3117 SilcChannelID *channel_id;
3118 SilcChannelEntry entry;
3120 unsigned char channel_key[32];
3122 SILC_LOG_DEBUG(("Creating new channel"));
3124 /* Create channel key */
3125 for (i = 0; i < 32; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3132 silc_cipher_alloc(cipher, &key);
3133 key->cipher->set_key(key->context, channel_key, key_len);
3135 channel_name = strdup(channel_name);
3137 /* Create the channel */
3138 silc_id_create_channel_id(router_id, server->rng, &channel_id);
3139 entry = silc_idlist_add_channel(server->local_list, channel_name,
3140 SILC_CHANNEL_MODE_NONE, channel_id,
3143 silc_free(channel_name);
3147 entry->key = silc_calloc(key_len, sizeof(*entry->key));
3148 entry->key_len = key_len * 8;
3149 memcpy(entry->key, channel_key, key_len);
3150 memset(channel_key, 0, sizeof(channel_key));
3152 /* Notify other routers about the new channel. We send the packet
3153 to our primary route. */
3154 if (server->standalone == FALSE) {
3155 silc_server_send_new_id(server, server->router->connection,
3156 server->server_type == SILC_SERVER ? FALSE : TRUE,
3157 entry->id, SILC_ID_CHANNEL, SILC_ID_CHANNEL_LEN);
3163 /* Create new client. This processes incoming NEW_CLIENT packet and creates
3164 Client ID for the client. Client becomes registered after calling this
3167 SilcClientEntry silc_server_new_client(SilcServer server,
3168 SilcSocketConnection sock,
3169 SilcPacketContext *packet)
3171 SilcBuffer buffer = packet->buffer;
3172 SilcClientEntry client;
3173 SilcIDCacheEntry cache;
3174 SilcClientID *client_id;
3176 SilcIDListData idata;
3177 char *username = NULL, *realname = NULL, *id_string;
3179 SILC_LOG_DEBUG(("Creating new client"));
3181 if (sock->type != SILC_SOCKET_TYPE_CLIENT)
3184 /* Take client entry */
3185 client = (SilcClientEntry)sock->user_data;
3186 idata = (SilcIDListData)client;
3188 /* Fetch the old client cache entry so that we can update it. */
3189 if (!silc_idcache_find_by_context(server->local_list->clients,
3190 sock->user_data, &cache)) {
3191 SILC_LOG_ERROR(("Lost client's cache entry - bad thing"));
3195 /* Parse incoming packet */
3196 silc_buffer_unformat(buffer,
3197 SILC_STR_UI16_STRING_ALLOC(&username),
3198 SILC_STR_UI16_STRING_ALLOC(&realname),
3201 /* Create Client ID */
3202 silc_id_create_client_id(server->id, server->rng, server->md5hash,
3203 username, &client_id);
3205 /* Update client entry */
3206 idata->registered = TRUE;
3207 client->nickname = strdup(username);
3208 client->username = username;
3209 client->userinfo = realname;
3210 client->id = client_id;
3212 /* Update the cache entry */
3213 cache->id = (void *)client_id;
3214 cache->type = SILC_ID_CLIENT;
3215 cache->data = username;
3216 silc_idcache_sort_by_data(server->local_list->clients);
3218 /* Notify our router about new client on the SILC network */
3219 if (!server->standalone)
3220 silc_server_send_new_id(server, (SilcSocketConnection)
3221 server->router->connection,
3222 server->server_type == SILC_ROUTER ? TRUE : FALSE,
3223 client->id, SILC_ID_CLIENT, SILC_ID_CLIENT_LEN);
3225 /* Send the new client ID to the client. */
3226 id_string = silc_id_id2str(client->id, SILC_ID_CLIENT);
3227 reply = silc_buffer_alloc(2 + 2 + SILC_ID_CLIENT_LEN);
3228 silc_buffer_pull_tail(reply, SILC_BUFFER_END(reply));
3229 silc_buffer_format(reply,
3230 SILC_STR_UI_SHORT(SILC_ID_CLIENT),
3231 SILC_STR_UI_SHORT(SILC_ID_CLIENT_LEN),
3232 SILC_STR_UI_XNSTRING(id_string, SILC_ID_CLIENT_LEN),
3234 silc_server_packet_send(server, sock, SILC_PACKET_NEW_ID, 0,
3235 reply->data, reply->len, FALSE);
3236 silc_free(id_string);
3237 silc_buffer_free(reply);
3239 /* Send some nice info to the client */
3240 SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3241 ("Welcome to the SILC Network %s@%s",
3242 username, sock->hostname));
3243 SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3244 ("Your host is %s, running version %s",
3245 server->config->server_info->server_name,
3247 SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3248 ("Your connection is secured with %s cipher, "
3249 "key length %d bits",
3250 idata->send_key->cipher->name,
3251 idata->send_key->cipher->key_len));
3252 SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3253 ("Your current nickname is %s",
3257 silc_server_send_motd(server, sock);
3262 /* Create new server. This processes incoming NEW_SERVER packet and
3263 saves the received Server ID. The server is our locally connected
3264 server thus we save all the information and save it to local list.
3265 This funtion can be used by both normal server and router server.
3266 If normal server uses this it means that its router has connected
3267 to the server. If router uses this it means that one of the cell's
3268 servers is connected to the router. */
3270 SilcServerEntry silc_server_new_server(SilcServer server,
3271 SilcSocketConnection sock,
3272 SilcPacketContext *packet)
3274 SilcBuffer buffer = packet->buffer;
3275 SilcServerEntry new_server;
3276 SilcIDCacheEntry cache;
3277 SilcServerID *server_id;
3278 SilcIDListData idata;
3279 unsigned char *server_name, *id_string;
3280 unsigned short id_len;
3282 SILC_LOG_DEBUG(("Creating new server"));
3284 if (sock->type != SILC_SOCKET_TYPE_SERVER &&
3285 sock->type != SILC_SOCKET_TYPE_ROUTER)
3288 /* Take server entry */
3289 new_server = (SilcServerEntry)sock->user_data;
3290 idata = (SilcIDListData)new_server;
3292 /* Fetch the old server cache entry so that we can update it. */
3293 if (!silc_idcache_find_by_context(server->local_list->servers,
3294 sock->user_data, &cache)) {
3295 SILC_LOG_ERROR(("Lost server's cache entry - bad thing"));
3299 /* Parse the incoming packet */
3300 silc_buffer_unformat(buffer,
3301 SILC_STR_UI16_NSTRING_ALLOC(&id_string, &id_len),
3302 SILC_STR_UI16_STRING_ALLOC(&server_name),
3305 if (id_len > buffer->len) {
3306 silc_free(id_string);
3307 silc_free(server_name);
3312 server_id = silc_id_str2id(id_string, SILC_ID_SERVER);
3313 silc_free(id_string);
3315 /* Update client entry */
3316 idata->registered = TRUE;
3317 new_server->server_name = server_name;
3318 new_server->id = server_id;
3320 /* Update the cache entry */
3321 cache->id = (void *)server_id;
3322 cache->type = SILC_ID_SERVER;
3323 cache->data = server_name;
3324 silc_idcache_sort_by_data(server->local_list->servers);
3326 /* Distribute the information about new server in the SILC network
3327 to our router. If we are normal server we won't send anything
3328 since this connection must be our router connection. */
3329 if (server->server_type == SILC_ROUTER && !server->standalone &&
3330 server->router->connection != sock)
3331 silc_server_send_new_id(server, server->router->connection,
3332 TRUE, new_server->id, SILC_ID_SERVER,
3333 SILC_ID_SERVER_LEN);
3338 /* Processes incoming New ID Payload. New ID Payload is used to distribute
3339 information about newly registered clients, servers and created
3342 void silc_server_new_id(SilcServer server, SilcSocketConnection sock,
3343 SilcPacketContext *packet)
3345 SilcBuffer buffer = packet->buffer;
3347 SilcServerEntry tmpserver, router;
3348 SilcSocketConnection router_sock;
3353 SILC_LOG_DEBUG(("Processing new ID"));
3355 if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3356 server->server_type == SILC_SERVER ||
3357 packet->src_id_type != SILC_ID_SERVER)
3360 idp = silc_id_payload_parse(buffer);
3364 id_type = silc_id_payload_get_type(idp);
3366 /* Normal server cannot have other normal server connections */
3367 if (id_type == SILC_ID_SERVER && sock->type == SILC_SOCKET_TYPE_SERVER)
3370 id = silc_id_payload_get_id(idp);
3374 /* If the sender of this packet is server and we are router we need to
3375 broadcast this packet to other routers in the network. */
3376 if (!server->standalone && server->server_type == SILC_ROUTER &&
3377 sock->type == SILC_SOCKET_TYPE_SERVER &&
3378 !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
3379 SILC_LOG_DEBUG(("Broadcasting received New ID packet"));
3380 silc_server_packet_send(server, server->router->connection,
3382 packet->flags | SILC_PACKET_FLAG_BROADCAST,
3383 buffer->data, buffer->len, FALSE);
3386 /* If the packet is originated from the one who sent it to us we know
3387 that the ID belongs to our cell, unless the sender was router. */
3388 tmpid = silc_id_str2id(packet->src_id, SILC_ID_SERVER);
3389 tmpserver = (SilcServerEntry)sock->user_data;
3391 if (!SILC_ID_SERVER_COMPARE(tmpid, tmpserver->id) &&
3392 sock->type == SILC_SOCKET_TYPE_SERVER) {
3393 id_list = server->local_list;
3395 router = sock->user_data;
3396 /* router = server->id_entry; */
3398 id_list = server->global_list;
3399 router_sock = (SilcSocketConnection)server->router->connection;
3400 router = server->router;
3406 case SILC_ID_CLIENT:
3408 SilcClientEntry idlist;
3410 SILC_LOG_DEBUG(("New client id(%s) from [%s] %s",
3411 silc_id_render(id, SILC_ID_CLIENT),
3412 sock->type == SILC_SOCKET_TYPE_SERVER ?
3413 "Server" : "Router", sock->hostname));
3415 /* Add the client to our local list. We are router and we keep
3416 cell specific local database of all clients in the cell. */
3417 idlist = silc_idlist_add_client(id_list, NULL, NULL, NULL,
3418 id, router, router_sock);
3422 case SILC_ID_SERVER:
3424 SilcServerEntry idlist;
3426 SILC_LOG_DEBUG(("New server id(%s) from [%s] %s",
3427 silc_id_render(id, SILC_ID_SERVER),
3428 sock->type == SILC_SOCKET_TYPE_SERVER ?
3429 "Server" : "Router", sock->hostname));
3431 /* Add the server to our local list. We are router and we keep
3432 cell specific local database of all servers in the cell. */
3433 idlist = silc_idlist_add_server(id_list, NULL, 0, id, router,
3438 case SILC_ID_CHANNEL:
3439 SILC_LOG_DEBUG(("New channel id(%s) from [%s] %s",
3440 silc_id_render(id, SILC_ID_CHANNEL),
3441 sock->type == SILC_SOCKET_TYPE_SERVER ?
3442 "Server" : "Router", sock->hostname));
3444 /* Add the channel to our local list. We are router and we keep
3445 cell specific local database of all channels in the cell. */
3446 silc_idlist_add_channel(id_list, NULL, 0, id, router, NULL);
3454 silc_id_payload_free(idp);
3457 /* Received packet to remove a user from a channel. Routers notify other
3458 routers that user has left a channel. Client must not send this packet.
3459 Normal server may send this packet but ignores if it receives one. */
3461 void silc_server_remove_channel_user(SilcServer server,
3462 SilcSocketConnection sock,
3463 SilcPacketContext *packet)
3465 SilcBuffer buffer = packet->buffer;
3466 unsigned char *tmp1 = NULL, *tmp2 = NULL;
3467 SilcClientID *client_id = NULL;
3468 SilcChannelID *channel_id = NULL;
3469 SilcChannelEntry channel;
3470 SilcClientEntry client;
3472 SILC_LOG_DEBUG(("Removing user from channel"));
3474 if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3475 server->server_type == SILC_SERVER)
3478 silc_buffer_unformat(buffer,
3479 SILC_STR_UI16_STRING_ALLOC(&tmp1),
3480 SILC_STR_UI16_STRING_ALLOC(&tmp2),
3486 client_id = silc_id_str2id(tmp1, SILC_ID_CLIENT);
3487 channel_id = silc_id_str2id(tmp2, SILC_ID_CHANNEL);
3488 if (!client_id || !channel_id)
3491 /* If we are router and this packet is not already broadcast packet
3492 we will broadcast it. The sending socket really cannot be router or
3493 the router is buggy. If this packet is coming from router then it must
3494 have the broadcast flag set already and we won't do anything. */
3495 if (!server->standalone && server->server_type == SILC_ROUTER &&
3496 sock->type == SILC_SOCKET_TYPE_SERVER &&
3497 !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
3498 SILC_LOG_DEBUG(("Broadcasting received Remove Channel User packet"));
3499 silc_server_packet_send(server, server->router->connection, packet->type,
3500 packet->flags | SILC_PACKET_FLAG_BROADCAST,
3501 buffer->data, buffer->len, FALSE);
3504 /* XXX routers should check server->global_list as well */
3505 /* Get channel entry */
3506 channel = silc_idlist_find_channel_by_id(server->local_list, channel_id);
3510 /* XXX routers should check server->global_list as well */
3511 /* Get client entry */
3512 client = silc_idlist_find_client_by_id(server->local_list, client_id);
3516 /* Remove from channel */
3517 silc_server_remove_from_one_channel(server, sock, channel, client, FALSE);
3525 silc_free(client_id);
3527 silc_free(channel_id);