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));
61 server->sim = silc_dlist_init();
69 /* Free's the SILC server object. This is called at the very end before
72 void silc_server_free(SilcServer server)
77 if (server->local_list)
78 silc_free(server->local_list);
79 if (server->global_list)
80 silc_free(server->global_list);
82 silc_rng_free(server->rng);
84 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
85 silc_dlist_del(server->sim, sim);
88 silc_dlist_uninit(server->sim);
91 silc_free(server->params);
93 silc_math_primegen_uninit(); /* XXX */
98 /* Initializes the entire SILC server. This is called always before running
99 the server. This is called only once at the initialization of the program.
100 This binds the server to its listenning port. After this function returns
101 one should call silc_server_run to start the server. This returns TRUE
102 when everything is ok to run the server. Configuration file must be
103 read and parsed before calling this. */
105 int silc_server_init(SilcServer server)
107 int *sock = NULL, sock_count = 0, i;
109 SilcServerEntry id_entry;
111 SILC_LOG_DEBUG(("Initializing server"));
113 assert(server->config);
115 /* XXX After server is made as Silc Server Library this can be given
116 as argument, for now this is hard coded */
117 server->params = silc_calloc(1, sizeof(*server->params));
118 server->params->retry_count = SILC_SERVER_RETRY_COUNT;
119 server->params->retry_interval_min = SILC_SERVER_RETRY_INTERVAL_MIN;
120 server->params->retry_interval_max = SILC_SERVER_RETRY_INTERVAL_MAX;
121 server->params->retry_keep_trying = FALSE;
122 server->params->protocol_timeout = 60;
124 /* Set log files where log message should be saved. */
125 server->config->server = server;
126 silc_config_server_setlogfiles(server->config);
128 /* Register all configured ciphers, PKCS and hash functions. */
129 silc_config_server_register_ciphers(server->config);
130 silc_config_server_register_pkcs(server->config);
131 silc_config_server_register_hashfuncs(server->config);
133 /* Initialize random number generator for the server. */
134 server->rng = silc_rng_alloc();
135 silc_rng_init(server->rng);
136 silc_math_primegen_init(); /* XXX */
138 /* Initialize hash functions for server to use */
139 silc_hash_alloc("md5", &server->md5hash);
140 silc_hash_alloc("sha1", &server->sha1hash);
142 /* Initialize none cipher */
143 silc_cipher_alloc("none", &server->none_cipher);
145 /* XXXXX Generate RSA key pair */
147 unsigned char *public_key;
148 unsigned char *private_key;
149 unsigned int pk_len, prv_len;
152 if (stat("pubkey.pub", &st) < 0 && stat("privkey.prv", &st) < 0) {
154 if (silc_pkcs_alloc("rsa", &server->pkcs) == FALSE) {
155 SILC_LOG_ERROR(("Could not create RSA key pair"));
159 if (server->pkcs->pkcs->init(server->pkcs->context,
160 1024, server->rng) == FALSE) {
161 SILC_LOG_ERROR(("Could not generate RSA key pair"));
165 public_key = server->pkcs->pkcs->get_public_key(server->pkcs->context,
167 private_key = server->pkcs->pkcs->get_private_key(server->pkcs->context,
170 SILC_LOG_HEXDUMP(("public key"), public_key, pk_len);
171 SILC_LOG_HEXDUMP(("private key"), private_key, prv_len);
174 silc_pkcs_public_key_alloc("rsa", "UN=root, HN=dummy",
176 server->private_key =
177 silc_pkcs_private_key_alloc("rsa", private_key, prv_len);
180 silc_pkcs_save_public_key("pubkey.pub", server->public_key,
182 silc_pkcs_save_private_key("privkey.prv", server->private_key, NULL,
185 memset(public_key, 0, pk_len);
186 memset(private_key, 0, prv_len);
187 silc_free(public_key);
188 silc_free(private_key);
190 silc_pkcs_load_public_key("pubkey.pub", &server->public_key,
192 silc_pkcs_load_private_key("privkey.prv", &server->private_key,
197 /* Create a listening server. Note that our server can listen on
198 multiple ports. All listeners are created here and now. */
199 /* XXX Still check this whether to use server_info or listen_port. */
201 while(server->config->listen_port) {
204 tmp = silc_net_create_server(server->config->listen_port->port,
205 server->config->listen_port->host);
209 sock = silc_realloc(sock, (sizeof(int *) * (sock_count + 1)));
210 sock[sock_count] = tmp;
211 server->config->listen_port = server->config->listen_port->next;
215 /* Initialize ID caches */
216 server->local_list->clients = silc_idcache_alloc(0);
217 server->local_list->servers = silc_idcache_alloc(0);
218 server->local_list->channels = silc_idcache_alloc(0);
220 /* XXX for now these are allocated for normal server as well as these
221 hold some global information that the server has fetched from its
222 router. For router these are used as they are supposed to be used
223 on router. The XXX can be remoevd later if this is the way we are
224 going to do this in the normal server as well. */
225 server->global_list->clients = silc_idcache_alloc(0);
226 server->global_list->servers = silc_idcache_alloc(0);
227 server->global_list->channels = silc_idcache_alloc(0);
229 /* Allocate the entire socket list that is used in server. Eventually
230 all connections will have entry in this table (it is a table of
231 pointers to the actual object that is allocated individually
233 server->sockets = silc_calloc(SILC_SERVER_MAX_CONNECTIONS,
234 sizeof(*server->sockets));
236 for (i = 0; i < sock_count; i++) {
237 SilcSocketConnection newsocket = NULL;
239 /* Set socket to non-blocking mode */
240 silc_net_set_socket_nonblock(sock[i]);
241 server->sock = sock[i];
243 /* Create a Server ID for the server. */
244 silc_id_create_server_id(sock[i], server->rng, &id);
250 server->id_type = SILC_ID_SERVER;
251 server->server_name = server->config->server_info->server_name;
253 /* Add ourselves to the server list. We don't have a router yet
254 beacuse we haven't established a route yet. It will be done later.
255 For now, NULL is sent as router. This allocates new entry to
258 silc_idlist_add_server(server->local_list,
259 server->config->server_info->server_name,
260 server->server_type, server->id, NULL, NULL);
262 SILC_LOG_ERROR(("Could not add ourselves to cache"));
266 /* Add ourselves also to the socket table. The entry allocated above
267 is sent as argument for fast referencing in the future. */
268 silc_socket_alloc(sock[i], SILC_SOCKET_TYPE_SERVER, id_entry,
273 server->sockets[sock[i]] = newsocket;
275 /* Put the allocated socket pointer also to the entry allocated above
276 for fast back-referencing to the socket list. */
277 id_entry->connection = (void *)server->sockets[sock[i]];
278 server->id_entry = id_entry;
281 /* Register the task queues. In SILC we have by default three task queues.
282 One task queue for non-timeout tasks which perform different kind of
283 I/O on file descriptors, timeout task queue for timeout tasks, and,
284 generic non-timeout task queue whose tasks apply to all connections. */
285 silc_task_queue_alloc(&server->io_queue, TRUE);
286 if (!server->io_queue) {
289 silc_task_queue_alloc(&server->timeout_queue, TRUE);
290 if (!server->timeout_queue) {
293 silc_task_queue_alloc(&server->generic_queue, TRUE);
294 if (!server->generic_queue) {
298 /* Register protocols */
299 silc_server_protocols_register();
301 /* Initialize the scheduler */
302 silc_schedule_init(&server->io_queue, &server->timeout_queue,
303 &server->generic_queue,
304 SILC_SERVER_MAX_CONNECTIONS);
306 /* Add the first task to the queue. This is task that is executed by
307 timeout. It expires as soon as the caller calls silc_server_run. This
308 task performs authentication protocol and key exchange with our
310 silc_task_register(server->timeout_queue, sock[0],
311 silc_server_connect_to_router,
312 (void *)server, 0, 1,
314 SILC_TASK_PRI_NORMAL);
316 /* Add listener task to the queue. This task receives new connections to the
317 server. This task remains on the queue until the end of the program. */
318 silc_task_register(server->io_queue, sock[0],
319 silc_server_accept_new_connection,
320 (void *)server, 0, 0,
322 SILC_TASK_PRI_NORMAL);
323 server->listenning = TRUE;
325 /* If server connections has been configured then we must be router as
326 normal server cannot have server connections, only router connections. */
327 if (server->config->servers)
328 server->server_type = SILC_ROUTER;
330 SILC_LOG_DEBUG(("Server initialized"));
332 /* We are done here, return succesfully */
335 silc_task_queue_free(server->timeout_queue);
337 silc_task_queue_free(server->io_queue);
339 for (i = 0; i < sock_count; i++)
340 silc_net_close_server(sock[i]);
345 /* Stops the SILC server. This function is used to shutdown the server.
346 This is usually called after the scheduler has returned. After stopping
347 the server one should call silc_server_free. */
349 void silc_server_stop(SilcServer server)
351 SILC_LOG_DEBUG(("Stopping server"));
353 /* Stop the scheduler, although it might be already stopped. This
354 doesn't hurt anyone. This removes all the tasks and task queues,
356 silc_schedule_stop();
357 silc_schedule_uninit();
359 silc_server_protocols_unregister();
361 SILC_LOG_DEBUG(("Server stopped"));
364 /* The heart of the server. This runs the scheduler thus runs the server. */
366 void silc_server_run(SilcServer server)
368 SILC_LOG_DEBUG(("Running server"));
370 /* Start the scheduler, the heart of the SILC server. When this returns
371 the program will be terminated. */
375 /* Timeout callback that will be called to retry connecting to remote
376 router. This is used by both normal and router server. This will wait
377 before retrying the connecting. The timeout is generated by exponential
378 backoff algorithm. */
380 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
382 SilcServerConnection sconn = (SilcServerConnection)context;
383 SilcServer server = sconn->server;
385 SILC_LOG_INFO(("Retrying connecting to a router"));
387 /* Calculate next timeout */
388 if (sconn->retry_count >= 1) {
389 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
390 if (sconn->retry_timeout > SILC_SERVER_RETRY_INTERVAL_MAX)
391 sconn->retry_timeout = SILC_SERVER_RETRY_INTERVAL_MAX;
393 sconn->retry_timeout = server->params->retry_interval_min;
395 sconn->retry_count++;
396 sconn->retry_timeout = sconn->retry_timeout +
397 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
399 /* If we've reached max retry count, give up. */
400 if (sconn->retry_count > server->params->retry_count &&
401 server->params->retry_keep_trying == FALSE) {
402 SILC_LOG_ERROR(("Could not connect to router, giving up"));
406 /* Wait one before retrying */
407 silc_task_register(server->timeout_queue, fd, silc_server_connect_router,
408 context, sconn->retry_timeout,
409 server->params->retry_interval_min_usec,
410 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
413 /* Generic routine to use connect to a router. */
415 SILC_TASK_CALLBACK(silc_server_connect_router)
417 SilcServerConnection sconn = (SilcServerConnection)context;
418 SilcServer server = sconn->server;
419 SilcSocketConnection newsocket;
420 SilcProtocol protocol;
421 SilcServerKEInternalContext *proto_ctx;
424 /* Connect to remote host */
425 sock = silc_net_create_connection(sconn->remote_port,
428 SILC_LOG_ERROR(("Could not connect to router"));
429 silc_task_register(server->timeout_queue, fd,
430 silc_server_connect_to_router_retry,
431 context, 0, 1, SILC_TASK_TIMEOUT,
432 SILC_TASK_PRI_NORMAL);
436 /* Set socket options */
437 silc_net_set_socket_nonblock(sock);
438 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
440 /* Create socket connection for the connection. Even though we
441 know that we are connecting to a router we will mark the socket
442 to be unknown connection until we have executed authentication
444 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
445 server->sockets[sock] = newsocket;
446 newsocket->hostname = sconn->remote_host;
447 newsocket->port = sconn->remote_port;
448 sconn->sock = newsocket;
450 /* Allocate internal protocol context. This is sent as context
452 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
453 proto_ctx->server = (void *)server;
454 proto_ctx->context = (void *)sconn;
455 proto_ctx->sock = newsocket;
456 proto_ctx->rng = server->rng;
457 proto_ctx->responder = FALSE;
459 /* Perform key exchange protocol. silc_server_connect_to_router_second
460 will be called after the protocol is finished. */
461 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
462 &protocol, proto_ctx,
463 silc_server_connect_to_router_second);
464 newsocket->protocol = protocol;
466 /* Register a timeout task that will be executed if the protocol
467 is not executed within set limit. */
468 proto_ctx->timeout_task =
469 silc_task_register(server->timeout_queue, sock,
470 silc_server_timeout_remote,
471 server, server->params->protocol_timeout,
472 server->params->protocol_timeout_usec,
476 /* Register the connection for network input and output. This sets
477 that scheduler will listen for incoming packets for this connection
478 and sets that outgoing packets may be sent to this connection as
479 well. However, this doesn't set the scheduler for outgoing traffic,
480 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
481 later when outgoing data is available. */
482 context = (void *)server;
483 SILC_REGISTER_CONNECTION_FOR_IO(sock);
485 /* Run the protocol */
486 protocol->execute(server->timeout_queue, 0, protocol, sock, 0, 0);
489 /* This function connects to our primary router or if we are a router this
490 establishes all our primary routes. This is called at the start of the
491 server to do authentication and key exchange with our router - called
494 SILC_TASK_CALLBACK(silc_server_connect_to_router)
496 SilcServer server = (SilcServer)context;
497 SilcServerConnection sconn;
499 SILC_LOG_DEBUG(("Connecting to router(s)"));
501 /* If we are normal SILC server we need to connect to our cell's
503 if (server->server_type == SILC_SERVER) {
504 SILC_LOG_DEBUG(("We are normal server"));
506 /* Create connection to the router, if configured. */
507 if (server->config->routers) {
509 /* Allocate connection object for hold connection specific stuff. */
510 sconn = silc_calloc(1, sizeof(*sconn));
511 sconn->server = server;
512 sconn->remote_host = server->config->routers->host;
513 sconn->remote_port = server->config->routers->port;
515 silc_task_register(server->timeout_queue, fd,
516 silc_server_connect_router,
517 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
518 SILC_TASK_PRI_NORMAL);
523 /* If we are a SILC router we need to establish all of our primary
525 if (server->server_type == SILC_ROUTER) {
526 SilcConfigServerSectionServerConnection *ptr;
528 SILC_LOG_DEBUG(("We are router"));
530 /* Create the connections to all our routes */
531 ptr = server->config->routers;
534 SILC_LOG_DEBUG(("Router connection [%s] %s:%d",
535 ptr->initiator ? "Initiator" : "Responder",
536 ptr->host, ptr->port));
538 if (ptr->initiator) {
539 /* Allocate connection object for hold connection specific stuff. */
540 sconn = silc_calloc(1, sizeof(*sconn));
541 sconn->server = server;
542 sconn->remote_host = ptr->host;
543 sconn->remote_port = ptr->port;
545 silc_task_register(server->timeout_queue, fd,
546 silc_server_connect_router,
547 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
548 SILC_TASK_PRI_NORMAL);
558 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
560 /* There wasn't a configured router, we will continue but we don't
561 have a connection to outside world. We will be standalone server. */
562 server->standalone = TRUE;
565 /* Second part of connecting to router(s). Key exchange protocol has been
566 executed and now we will execute authentication protocol. */
568 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
570 SilcProtocol protocol = (SilcProtocol)context;
571 SilcServerKEInternalContext *ctx =
572 (SilcServerKEInternalContext *)protocol->context;
573 SilcServer server = (SilcServer)ctx->server;
574 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
575 SilcSocketConnection sock = NULL;
576 SilcServerConnAuthInternalContext *proto_ctx;
578 SILC_LOG_DEBUG(("Start"));
580 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
581 /* Error occured during protocol */
582 silc_protocol_free(protocol);
584 silc_buffer_free(ctx->packet);
586 silc_ske_free(ctx->ske);
588 silc_free(ctx->dest_id);
590 sock->protocol = NULL;
591 silc_server_disconnect_remote(server, sock, "Server closed connection: "
592 "Key exchange failed");
596 /* Allocate internal context for the authentication protocol. This
597 is sent as context for the protocol. */
598 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
599 proto_ctx->server = (void *)server;
600 proto_ctx->context = (void *)sconn;
601 proto_ctx->sock = sock = server->sockets[fd];
602 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
603 proto_ctx->dest_id_type = ctx->dest_id_type;
604 proto_ctx->dest_id = ctx->dest_id;
606 /* Resolve the authentication method used in this connection */
607 proto_ctx->auth_meth = SILC_PROTOCOL_CONN_AUTH_PASSWORD;
608 if (server->config->routers) {
609 SilcConfigServerSectionServerConnection *conn = NULL;
611 /* Check if we find a match from user configured connections */
612 conn = silc_config_server_find_router_conn(server->config,
616 /* Match found. Use the configured authentication method */
617 proto_ctx->auth_meth = conn->auth_meth;
618 if (conn->auth_data) {
619 proto_ctx->auth_data = strdup(conn->auth_data);
620 proto_ctx->auth_data_len = strlen(conn->auth_data);
623 /* No match found. */
630 /* Free old protocol as it is finished now */
631 silc_protocol_free(protocol);
633 silc_buffer_free(ctx->packet);
635 sock->protocol = NULL;
637 /* Allocate the authentication protocol. This is allocated here
638 but we won't start it yet. We will be receiving party of this
639 protocol thus we will wait that connecting party will make
641 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
642 &sock->protocol, proto_ctx,
643 silc_server_connect_to_router_final);
645 /* Register timeout task. If the protocol is not executed inside
646 this timelimit the connection will be terminated. Currently
647 this is 15 seconds and is hard coded limit (XXX). */
648 proto_ctx->timeout_task =
649 silc_task_register(server->timeout_queue, sock->sock,
650 silc_server_timeout_remote,
651 (void *)server, 15, 0,
655 /* Run the protocol */
656 sock->protocol->execute(server->timeout_queue, 0,
657 sock->protocol, sock->sock, 0, 0);
660 /* Finalizes the connection to router. Registers a server task to the
661 queue so that we can accept new connections. */
663 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
665 SilcProtocol protocol = (SilcProtocol)context;
666 SilcServerConnAuthInternalContext *ctx =
667 (SilcServerConnAuthInternalContext *)protocol->context;
668 SilcServer server = (SilcServer)ctx->server;
669 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
670 SilcSocketConnection sock = ctx->sock;
671 SilcServerEntry id_entry;
673 unsigned char *id_string;
675 SILC_LOG_DEBUG(("Start"));
677 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
678 /* Error occured during protocol */
680 silc_free(ctx->dest_id);
681 silc_server_disconnect_remote(server, sock, "Server closed connection: "
682 "Authentication failed");
686 /* Add a task to the queue. This task receives new connections to the
687 server. This task remains on the queue until the end of the program. */
688 if (!server->listenning) {
689 silc_task_register(server->io_queue, server->sock,
690 silc_server_accept_new_connection,
691 (void *)server, 0, 0,
693 SILC_TASK_PRI_NORMAL);
694 server->listenning = TRUE;
697 /* Send NEW_SERVER packet to the router. We will become registered
698 to the SILC network after sending this packet. */
699 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
700 packet = silc_buffer_alloc(2 + 2 + SILC_ID_SERVER_LEN +
701 strlen(server->server_name));
702 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
703 silc_buffer_format(packet,
704 SILC_STR_UI_SHORT(SILC_ID_SERVER_LEN),
705 SILC_STR_UI_XNSTRING(id_string, SILC_ID_SERVER_LEN),
706 SILC_STR_UI_SHORT(strlen(server->server_name)),
707 SILC_STR_UI_XNSTRING(server->server_name,
708 strlen(server->server_name)),
711 /* Send the packet */
712 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
713 packet->data, packet->len, TRUE);
714 silc_buffer_free(packet);
715 silc_free(id_string);
717 SILC_LOG_DEBUG(("Connected to router %s", sock->hostname));
719 /* Add the connected router to local server list */
720 server->standalone = FALSE;
721 id_entry = silc_idlist_add_server(server->local_list,
722 sock->hostname ? sock->hostname : sock->ip,
723 SILC_ROUTER, ctx->dest_id, NULL, sock);
726 silc_free(ctx->dest_id);
727 silc_server_disconnect_remote(server, sock, "Server closed connection: "
728 "Authentication failed");
732 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
733 silc_free(sock->user_data);
734 sock->user_data = (void *)id_entry;
735 sock->type = SILC_SOCKET_TYPE_ROUTER;
736 server->id_entry->router = id_entry;
739 /* Free the temporary connection data context */
743 /* Free the protocol object */
744 silc_protocol_free(protocol);
746 silc_buffer_free(ctx->packet);
748 silc_ske_free(ctx->ske);
750 sock->protocol = NULL;
753 /* Accepts new connections to the server. Accepting new connections are
754 done in three parts to make it async. */
756 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
758 SilcServer server = (SilcServer)context;
759 SilcSocketConnection newsocket;
760 SilcServerKEInternalContext *proto_ctx;
763 SILC_LOG_DEBUG(("Accepting new connection"));
765 sock = silc_net_accept_connection(server->sock);
767 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
771 /* Check max connections */
772 if (sock > SILC_SERVER_MAX_CONNECTIONS) {
773 if (server->config->redirect) {
774 /* XXX Redirecting connection to somewhere else now?? */
775 /*silc_server_send_notify("Server is full, trying to redirect..."); */
777 SILC_LOG_ERROR(("Refusing connection, server is full"));
782 /* Set socket options */
783 silc_net_set_socket_nonblock(sock);
784 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
786 /* We don't create a ID yet, since we don't know what type of connection
787 this is yet. But, we do add the connection to the socket table. */
788 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
789 server->sockets[sock] = newsocket;
791 /* XXX This MUST be done async as this will block the entire server
792 process. Either we have to do our own resolver stuff or in the future
793 we can use threads. */
794 /* Perform mandatory name and address lookups for the remote host. */
795 silc_net_check_host_by_sock(sock, &newsocket->hostname, &newsocket->ip);
796 if (!newsocket->ip || !newsocket->hostname) {
797 SILC_LOG_DEBUG(("IP lookup/DNS lookup failed"));
798 SILC_LOG_ERROR(("IP lookup/DNS lookup failed"));
802 SILC_LOG_INFO(("Incoming connection from %s (%s)", newsocket->hostname,
805 /* Allocate internal context for key exchange protocol. This is
806 sent as context for the protocol. */
807 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
808 proto_ctx->server = context;
809 proto_ctx->sock = newsocket;
810 proto_ctx->rng = server->rng;
811 proto_ctx->responder = TRUE;
813 /* Prepare the connection for key exchange protocol. We allocate the
814 protocol but will not start it yet. The connector will be the
815 initiator of the protocol thus we will wait for initiation from
816 there before we start the protocol. */
817 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
818 &newsocket->protocol, proto_ctx,
819 silc_server_accept_new_connection_second);
821 /* Register a timeout task that will be executed if the connector
822 will not start the key exchange protocol within 60 seconds. For
823 now, this is a hard coded limit. After 60 secs the connection will
824 be closed if the key exchange protocol has not been started. */
825 proto_ctx->timeout_task =
826 silc_task_register(server->timeout_queue, newsocket->sock,
827 silc_server_timeout_remote,
832 /* Register the connection for network input and output. This sets
833 that scheduler will listen for incoming packets for this connection
834 and sets that outgoing packets may be sent to this connection as well.
835 However, this doesn't set the scheduler for outgoing traffic, it
836 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
837 later when outgoing data is available. */
838 SILC_REGISTER_CONNECTION_FOR_IO(sock);
841 /* Second part of accepting new connection. Key exchange protocol has been
842 performed and now it is time to do little connection authentication
843 protocol to figure out whether this connection is client or server
844 and whether it has right to access this server (especially server
845 connections needs to be authenticated). */
847 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
849 SilcProtocol protocol = (SilcProtocol)context;
850 SilcServerKEInternalContext *ctx =
851 (SilcServerKEInternalContext *)protocol->context;
852 SilcServer server = (SilcServer)ctx->server;
853 SilcSocketConnection sock = NULL;
854 SilcServerConnAuthInternalContext *proto_ctx;
856 SILC_LOG_DEBUG(("Start"));
858 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
859 /* Error occured during protocol */
860 silc_protocol_free(protocol);
862 silc_buffer_free(ctx->packet);
864 silc_ske_free(ctx->ske);
866 silc_free(ctx->dest_id);
869 sock->protocol = NULL;
870 silc_server_disconnect_remote(server, sock, "Server closed connection: "
871 "Key exchange failed");
875 /* Allocate internal context for the authentication protocol. This
876 is sent as context for the protocol. */
877 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
878 proto_ctx->server = (void *)server;
879 proto_ctx->sock = sock = server->sockets[fd];
880 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
881 proto_ctx->responder = TRUE;
882 proto_ctx->dest_id_type = ctx->dest_id_type;
883 proto_ctx->dest_id = ctx->dest_id;
885 /* Free old protocol as it is finished now */
886 silc_protocol_free(protocol);
888 silc_buffer_free(ctx->packet);
890 sock->protocol = NULL;
892 /* Allocate the authentication protocol. This is allocated here
893 but we won't start it yet. We will be receiving party of this
894 protocol thus we will wait that connecting party will make
896 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
897 &sock->protocol, proto_ctx,
898 silc_server_accept_new_connection_final);
900 /* Register timeout task. If the protocol is not executed inside
901 this timelimit the connection will be terminated. Currently
902 this is 60 seconds and is hard coded limit (XXX). */
903 proto_ctx->timeout_task =
904 silc_task_register(server->timeout_queue, sock->sock,
905 silc_server_timeout_remote,
906 (void *)server, 60, 0,
911 /* Final part of accepting new connection. The connection has now
912 been authenticated and keys has been exchanged. We also know whether
913 this is client or server connection. */
915 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
917 SilcProtocol protocol = (SilcProtocol)context;
918 SilcServerConnAuthInternalContext *ctx =
919 (SilcServerConnAuthInternalContext *)protocol->context;
920 SilcServer server = (SilcServer)ctx->server;
921 SilcSocketConnection sock = ctx->sock;
922 void *id_entry = NULL;
924 SILC_LOG_DEBUG(("Start"));
926 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
927 /* Error occured during protocol */
928 silc_protocol_free(protocol);
930 silc_buffer_free(ctx->packet);
932 silc_ske_free(ctx->ske);
934 silc_free(ctx->dest_id);
937 sock->protocol = NULL;
938 silc_server_disconnect_remote(server, sock, "Server closed connection: "
939 "Authentication failed");
943 sock->type = ctx->conn_type;
945 case SILC_SOCKET_TYPE_CLIENT:
947 SilcClientEntry client;
949 SILC_LOG_DEBUG(("Remote host is client"));
950 SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
953 /* Add the client to the client ID cache. The nickname and Client ID
954 and other information is created after we have received NEW_CLIENT
955 packet from client. */
956 client = silc_idlist_add_client(server->local_list,
957 NULL, NULL, NULL, NULL, NULL, sock);
959 SILC_LOG_ERROR(("Could not add new client to cache"));
960 silc_free(sock->user_data);
964 id_entry = (void *)client;
967 case SILC_SOCKET_TYPE_SERVER:
968 case SILC_SOCKET_TYPE_ROUTER:
970 SilcServerEntry new_server;
972 SILC_LOG_DEBUG(("Remote host is %s",
973 sock->type == SILC_SOCKET_TYPE_SERVER ?
974 "server" : "router"));
975 SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
976 sock->ip, sock->type == SILC_SOCKET_TYPE_SERVER ?
977 "server" : "router"));
979 /* Add the server into server cache. The server name and Server ID
980 is updated after we have received NEW_SERVER packet from the
983 silc_idlist_add_server(server->local_list, NULL,
984 sock->type == SILC_SOCKET_TYPE_SERVER ?
985 SILC_SERVER : SILC_ROUTER, NULL, NULL, sock);
987 SILC_LOG_ERROR(("Could not add new server to cache"));
988 silc_free(sock->user_data);
992 id_entry = (void *)new_server;
994 /* There is connection to other server now, if it is router then
995 we will have connection to outside world. If we are router but
996 normal server connected to us then we will remain standalone,
997 if we are standlone. */
998 if (server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER) {
999 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1000 server->standalone = FALSE;
1001 if (!server->id_entry->router)
1002 server->id_entry->router = id_entry;
1010 /* Add the common data structure to the ID entry. */
1012 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1014 /* Add to sockets internal pointer for fast referencing */
1015 silc_free(sock->user_data);
1016 sock->user_data = id_entry;
1018 /* Connection has been fully established now. Everything is ok. */
1019 SILC_LOG_DEBUG(("New connection authenticated"));
1021 silc_protocol_free(protocol);
1023 silc_buffer_free(ctx->packet);
1025 silc_ske_free(ctx->ske);
1027 silc_free(ctx->dest_id);
1029 sock->protocol = NULL;
1032 /* Internal routine that sends packet or marks packet to be sent. This
1033 is used directly only in special cases. Normal cases should use
1034 silc_server_packet_send. Returns < 0 error. */
1036 static int silc_server_packet_send_real(SilcServer server,
1037 SilcSocketConnection sock,
1042 /* Send the packet */
1043 ret = silc_packet_send(sock, force_send);
1047 /* Mark that there is some outgoing data available for this connection.
1048 This call sets the connection both for input and output (the input
1049 is set always and this call keeps the input setting, actually).
1050 Actual data sending is performed by silc_server_packet_process. */
1051 SILC_SET_CONNECTION_FOR_OUTPUT(sock->sock);
1053 /* Mark to socket that data is pending in outgoing buffer. This flag
1054 is needed if new data is added to the buffer before the earlier
1055 put data is sent to the network. */
1056 SILC_SET_OUTBUF_PENDING(sock);
1062 SilcPacketContext *packetdata;
1064 SilcSocketConnection sock;
1067 } SilcServerInternalPacket;
1069 /* This function is used to read packets from network and send packets to
1070 network. This is usually a generic task. */
1072 SILC_TASK_CALLBACK(silc_server_packet_process)
1074 SilcServer server = (SilcServer)context;
1075 SilcSocketConnection sock = server->sockets[fd];
1076 SilcIDListData idata;
1077 SilcCipher cipher = NULL;
1078 SilcHmac hmac = NULL;
1081 SILC_LOG_DEBUG(("Processing packet"));
1083 /* Packet sending */
1084 if (type == SILC_TASK_WRITE) {
1085 SILC_LOG_DEBUG(("Writing data to connection"));
1087 if (sock->outbuf->data - sock->outbuf->head)
1088 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1090 ret = silc_server_packet_send_real(server, sock, TRUE);
1092 /* If returned -2 could not write to connection now, will do
1097 /* The packet has been sent and now it is time to set the connection
1098 back to only for input. When there is again some outgoing data
1099 available for this connection it will be set for output as well.
1100 This call clears the output setting and sets it only for input. */
1101 SILC_SET_CONNECTION_FOR_INPUT(fd);
1102 SILC_UNSET_OUTBUF_PENDING(sock);
1104 silc_buffer_clear(sock->outbuf);
1108 /* Packet receiving */
1109 SILC_LOG_DEBUG(("Reading data from connection"));
1111 /* Read some data from connection */
1112 ret = silc_packet_receive(sock);
1118 SILC_LOG_DEBUG(("Read EOF"));
1120 /* If connection is disconnecting already we will finally
1121 close the connection */
1122 if (SILC_IS_DISCONNECTING(sock)) {
1123 if (sock->user_data)
1124 silc_server_free_sock_user_data(server, sock);
1125 silc_server_close_connection(server, sock);
1129 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1131 if (sock->user_data)
1132 silc_server_free_sock_user_data(server, sock);
1133 silc_server_close_connection(server, sock);
1137 /* If connection is disconnecting or disconnected we will ignore
1139 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1140 SILC_LOG_DEBUG(("Ignoring read data from invalid connection"));
1144 /* Get keys and stuff from ID entry */
1145 idata = (SilcIDListData)sock->user_data;
1147 idata->last_receive = time(NULL);
1148 cipher = idata->receive_key;
1152 /* Process the packet. This will call the parser that will then
1153 decrypt and parse the packet. */
1154 silc_packet_receive_process(sock, cipher, hmac, silc_server_packet_parse,
1158 /* Parses whole packet, received earlier. */
1160 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1162 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1163 SilcServer server = (SilcServer)parse_ctx->context;
1164 SilcSocketConnection sock = parse_ctx->sock;
1165 SilcPacketContext *packet = parse_ctx->packet;
1166 SilcBuffer buffer = packet->buffer;
1169 SILC_LOG_DEBUG(("Start"));
1171 /* Decrypt the received packet */
1172 ret = silc_packet_decrypt(parse_ctx->cipher, parse_ctx->hmac,
1178 /* Parse the packet. Packet type is returned. */
1179 ret = silc_packet_parse(packet);
1181 /* Parse the packet header in special way as this is "special"
1183 ret = silc_packet_parse_special(packet);
1186 if (ret == SILC_PACKET_NONE)
1189 /* Parse the incoming packet type */
1190 silc_server_packet_parse_type(server, sock, packet);
1193 silc_buffer_clear(sock->inbuf);
1195 silc_free(packet->src_id);
1197 silc_free(packet->dst_id);
1199 silc_free(parse_ctx);
1202 /* Parser callback called by silc_packet_receive_process. This merely
1203 registers timeout that will handle the actual parsing whem appropriate. */
1205 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1207 SilcServer server = (SilcServer)parser_context->context;
1208 SilcSocketConnection sock = parser_context->sock;
1210 switch (sock->type) {
1211 case SILC_SOCKET_TYPE_CLIENT:
1212 case SILC_SOCKET_TYPE_UNKNOWN:
1213 /* Parse the packet with timeout */
1214 silc_task_register(server->timeout_queue, sock->sock,
1215 silc_server_packet_parse_real,
1216 (void *)parser_context, 0, 100000,
1218 SILC_TASK_PRI_NORMAL);
1220 case SILC_SOCKET_TYPE_SERVER:
1221 case SILC_SOCKET_TYPE_ROUTER:
1222 /* Packets from servers are parsed as soon as possible */
1223 silc_task_register(server->timeout_queue, sock->sock,
1224 silc_server_packet_parse_real,
1225 (void *)parser_context, 0, 1,
1227 SILC_TASK_PRI_NORMAL);
1234 /* Parses the packet type and calls what ever routines the packet type
1235 requires. This is done for all incoming packets. */
1237 void silc_server_packet_parse_type(SilcServer server,
1238 SilcSocketConnection sock,
1239 SilcPacketContext *packet)
1241 SilcBuffer buffer = packet->buffer;
1242 SilcPacketType type = packet->type;
1244 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1246 /* Parse the packet type */
1248 case SILC_PACKET_DISCONNECT:
1249 SILC_LOG_DEBUG(("Disconnect packet"));
1251 case SILC_PACKET_SUCCESS:
1253 * Success received for something. For now we can have only
1254 * one protocol for connection executing at once hence this
1255 * success message is for whatever protocol is executing currently.
1257 SILC_LOG_DEBUG(("Success packet"));
1258 if (sock->protocol) {
1259 sock->protocol->execute(server->timeout_queue, 0,
1260 sock->protocol, sock->sock, 0, 0);
1263 case SILC_PACKET_FAILURE:
1265 * Failure received for something. For now we can have only
1266 * one protocol for connection executing at once hence this
1267 * failure message is for whatever protocol is executing currently.
1269 SILC_LOG_DEBUG(("Failure packet"));
1270 if (sock->protocol) {
1271 /* XXX Audit the failure type */
1272 sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
1273 sock->protocol->execute(server->timeout_queue, 0,
1274 sock->protocol, sock->sock, 0, 0);
1277 case SILC_PACKET_REJECT:
1278 SILC_LOG_DEBUG(("Reject packet"));
1285 case SILC_PACKET_CHANNEL_MESSAGE:
1287 * Received channel message. Channel messages are special packets
1288 * (although probably most common ones) hence they are handled
1291 SILC_LOG_DEBUG(("Channel Message packet"));
1292 silc_server_channel_message(server, sock, packet);
1295 case SILC_PACKET_CHANNEL_KEY:
1297 * Received key for channel. As channels are created by the router
1298 * the keys are as well. We will distribute the key to all of our
1299 * locally connected clients on the particular channel. Router
1300 * never receives this channel and thus is ignored.
1302 SILC_LOG_DEBUG(("Channel Key packet"));
1303 silc_server_channel_key(server, sock, packet);
1309 case SILC_PACKET_COMMAND:
1311 * Recived command. Allocate command context and execute the command.
1313 SILC_LOG_DEBUG(("Command packet"));
1314 silc_server_command_process(server, sock, packet);
1317 case SILC_PACKET_COMMAND_REPLY:
1319 * Received command reply packet. Servers never send commands thus
1320 * they don't receive command reply packets either, except in cases
1321 * where server has forwarded command packet coming from client.
1322 * This must be the case here or we will ignore the packet.
1324 SILC_LOG_DEBUG(("Command Reply packet"));
1325 silc_server_packet_relay_command_reply(server, sock, packet);
1329 * Private Message packets
1331 case SILC_PACKET_PRIVATE_MESSAGE:
1333 * Received private message packet. The packet is coming from either
1336 SILC_LOG_DEBUG(("Private Message packet"));
1337 silc_server_private_message(server, sock, packet);
1340 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1344 * Key Exchange protocol packets
1346 case SILC_PACKET_KEY_EXCHANGE:
1347 SILC_LOG_DEBUG(("KE packet"));
1348 if (sock->protocol && sock->protocol->protocol->type
1349 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1351 SilcServerKEInternalContext *proto_ctx =
1352 (SilcServerKEInternalContext *)sock->protocol->context;
1354 proto_ctx->packet = buffer;
1356 /* Let the protocol handle the packet */
1357 sock->protocol->execute(server->timeout_queue, 0,
1358 sock->protocol, sock->sock, 0, 100000);
1360 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1361 "protocol active, packet dropped."));
1363 /* XXX Trigger KE protocol?? Rekey actually, maybe. */
1367 case SILC_PACKET_KEY_EXCHANGE_1:
1368 SILC_LOG_DEBUG(("KE 1 packet"));
1369 if (sock->protocol && sock->protocol->protocol->type
1370 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1372 SilcServerKEInternalContext *proto_ctx =
1373 (SilcServerKEInternalContext *)sock->protocol->context;
1375 if (proto_ctx->packet)
1376 silc_buffer_free(proto_ctx->packet);
1378 proto_ctx->packet = buffer;
1379 proto_ctx->dest_id_type = packet->src_id_type;
1380 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_type);
1382 /* Let the protocol handle the packet */
1383 sock->protocol->execute(server->timeout_queue, 0,
1384 sock->protocol, sock->sock,
1387 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1388 "protocol active, packet dropped."));
1392 case SILC_PACKET_KEY_EXCHANGE_2:
1393 SILC_LOG_DEBUG(("KE 2 packet"));
1394 if (sock->protocol && sock->protocol->protocol->type
1395 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1397 SilcServerKEInternalContext *proto_ctx =
1398 (SilcServerKEInternalContext *)sock->protocol->context;
1400 if (proto_ctx->packet)
1401 silc_buffer_free(proto_ctx->packet);
1403 proto_ctx->packet = buffer;
1404 proto_ctx->dest_id_type = packet->src_id_type;
1405 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_type);
1407 /* Let the protocol handle the packet */
1408 sock->protocol->execute(server->timeout_queue, 0,
1409 sock->protocol, sock->sock,
1412 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1413 "protocol active, packet dropped."));
1417 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1418 /* If we receive this packet we will send to the other end information
1419 about our mandatory authentication method for the connection.
1420 This packet maybe received at any time. */
1423 * Connection Authentication protocol packets
1425 case SILC_PACKET_CONNECTION_AUTH:
1426 /* Start of the authentication protocol. We receive here the
1427 authentication data and will verify it. */
1428 SILC_LOG_DEBUG(("Connection auth packet"));
1429 if (sock->protocol && sock->protocol->protocol->type
1430 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1432 SilcServerConnAuthInternalContext *proto_ctx =
1433 (SilcServerConnAuthInternalContext *)sock->protocol->context;
1435 proto_ctx->packet = buffer;
1437 /* Let the protocol handle the packet */
1438 sock->protocol->execute(server->timeout_queue, 0,
1439 sock->protocol, sock->sock, 0, 0);
1441 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1442 "protocol active, packet dropped."));
1446 case SILC_PACKET_NEW_ID:
1448 * Received New ID packet. This includes some new ID that has been
1449 * created. It may be for client, server or channel. This is the way
1450 * to distribute information about new registered entities in the
1453 SILC_LOG_DEBUG(("New ID packet"));
1454 silc_server_new_id(server, sock, packet);
1457 case SILC_PACKET_NEW_CLIENT:
1459 * Received new client packet. This includes client information that
1460 * we will use to create initial client ID. After creating new
1461 * ID we will send it to the client.
1463 SILC_LOG_DEBUG(("New Client packet"));
1464 silc_server_new_client(server, sock, packet);
1467 case SILC_PACKET_NEW_SERVER:
1469 * Received new server packet. This includes Server ID and some other
1470 * information that we may save. This is received after server has
1473 SILC_LOG_DEBUG(("New Server packet"));
1474 silc_server_new_server(server, sock, packet);
1477 case SILC_PACKET_NEW_CHANNEL:
1480 case SILC_PACKET_NEW_CHANNEL_USER:
1483 case SILC_PACKET_NEW_CHANNEL_LIST:
1486 case SILC_PACKET_NEW_CHANNEL_USER_LIST:
1489 case SILC_PACKET_REPLACE_ID:
1491 * Received replace ID packet. This sends the old ID that is to be
1492 * replaced with the new one included into the packet. Client must not
1495 SILC_LOG_DEBUG(("Replace ID packet"));
1496 silc_server_replace_id(server, sock, packet);
1499 case SILC_PACKET_REMOVE_ID:
1502 case SILC_PACKET_REMOVE_CHANNEL_USER:
1504 * Received packet to remove user from a channel. Routers notify other
1505 * routers about a user leaving a channel.
1507 SILC_LOG_DEBUG(("Remove Channel User packet"));
1508 silc_server_remove_channel_user(server, sock, packet);
1512 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
1518 /* Assembles a new packet to be sent out to network. This doesn't actually
1519 send the packet but creates the packet and fills the outgoing data
1520 buffer and marks the packet ready to be sent to network. However, If
1521 argument force_send is TRUE the packet is sent immediately and not put
1522 to queue. Normal case is that the packet is not sent immediately. */
1524 void silc_server_packet_send(SilcServer server,
1525 SilcSocketConnection sock,
1526 SilcPacketType type,
1527 SilcPacketFlags flags,
1528 unsigned char *data,
1529 unsigned int data_len,
1532 void *dst_id = NULL;
1533 SilcIdType dst_id_type = SILC_ID_NONE;
1538 /* Get data used in the packet sending, keys and stuff */
1539 switch(sock->type) {
1540 case SILC_SOCKET_TYPE_CLIENT:
1541 dst_id = ((SilcClientEntry)sock->user_data)->id;
1542 dst_id_type = SILC_ID_CLIENT;
1544 case SILC_SOCKET_TYPE_SERVER:
1545 case SILC_SOCKET_TYPE_ROUTER:
1546 dst_id = ((SilcServerEntry)sock->user_data)->id;
1547 dst_id_type = SILC_ID_SERVER;
1553 silc_server_packet_send_dest(server, sock, type, flags, dst_id,
1554 dst_id_type, data, data_len, force_send);
1557 /* Assembles a new packet to be sent out to network. This doesn't actually
1558 send the packet but creates the packet and fills the outgoing data
1559 buffer and marks the packet ready to be sent to network. However, If
1560 argument force_send is TRUE the packet is sent immediately and not put
1561 to queue. Normal case is that the packet is not sent immediately.
1562 Destination information is sent as argument for this function. */
1564 void silc_server_packet_send_dest(SilcServer server,
1565 SilcSocketConnection sock,
1566 SilcPacketType type,
1567 SilcPacketFlags flags,
1569 SilcIdType dst_id_type,
1570 unsigned char *data,
1571 unsigned int data_len,
1574 SilcPacketContext packetdata;
1575 SilcIDListData idata;
1576 SilcCipher cipher = NULL;
1577 SilcHmac hmac = NULL;
1578 unsigned char *dst_id_data = NULL;
1579 unsigned int dst_id_len = 0;
1581 SILC_LOG_DEBUG(("Sending packet, type %d", type));
1583 /* Get data used in the packet sending, keys and stuff */
1584 idata = (SilcIDListData)sock->user_data;
1587 dst_id_data = silc_id_id2str(dst_id, dst_id_type);
1588 dst_id_len = silc_id_get_len(dst_id_type);
1591 /* Set the packet context pointers */
1592 packetdata.type = type;
1593 packetdata.flags = flags;
1594 packetdata.src_id = silc_id_id2str(server->id, server->id_type);
1595 packetdata.src_id_len = SILC_ID_SERVER_LEN;
1596 packetdata.src_id_type = server->id_type;
1597 packetdata.dst_id = dst_id_data;
1598 packetdata.dst_id_len = dst_id_len;
1599 packetdata.dst_id_type = dst_id_type;
1600 packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
1601 packetdata.src_id_len + dst_id_len;
1602 packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
1603 packetdata.rng = server->rng;
1605 /* Prepare outgoing data buffer for packet sending */
1606 silc_packet_send_prepare(sock,
1607 SILC_PACKET_HEADER_LEN +
1608 packetdata.src_id_len +
1609 packetdata.dst_id_len,
1613 SILC_LOG_DEBUG(("Putting data to outgoing buffer, len %d", data_len));
1615 packetdata.buffer = sock->outbuf;
1617 /* Put the data to the buffer */
1618 if (data && data_len)
1619 silc_buffer_put(sock->outbuf, data, data_len);
1621 /* Create the outgoing packet */
1622 silc_packet_assemble(&packetdata);
1625 cipher = idata->send_key;
1629 /* Encrypt the packet */
1630 silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
1632 SILC_LOG_HEXDUMP(("Outgoing packet, len %d", sock->outbuf->len),
1633 sock->outbuf->data, sock->outbuf->len);
1635 /* Now actually send the packet */
1636 silc_server_packet_send_real(server, sock, force_send);
1638 if (packetdata.src_id)
1639 silc_free(packetdata.src_id);
1640 if (packetdata.dst_id)
1641 silc_free(packetdata.dst_id);
1644 /* Forwards packet. Packets sent with this function will be marked as
1645 forwarded (in the SILC header flags) so that the receiver knows that
1646 we have forwarded the packet to it. Forwarded packets are handled
1647 specially by the receiver as they are not destined to the receiver
1648 originally. However, the receiver knows this because the forwarded
1649 flag has been set (and the flag is authenticated). */
1651 void silc_server_packet_forward(SilcServer server,
1652 SilcSocketConnection sock,
1653 unsigned char *data, unsigned int data_len,
1656 SilcIDListData idata;
1657 SilcCipher cipher = NULL;
1658 SilcHmac hmac = NULL;
1660 SILC_LOG_DEBUG(("Forwarding packet"));
1662 /* Get data used in the packet sending, keys and stuff */
1663 idata = (SilcIDListData)sock->user_data;
1665 /* Prepare outgoing data buffer for packet sending */
1666 silc_packet_send_prepare(sock, 0, 0, data_len);
1668 /* Mungle the packet flags and add the FORWARDED flag */
1670 data[2] |= (unsigned char)SILC_PACKET_FLAG_FORWARDED;
1672 /* Put the data to the buffer */
1673 if (data && data_len)
1674 silc_buffer_put(sock->outbuf, data, data_len);
1677 cipher = idata->send_key;
1681 /* Encrypt the packet */
1682 silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
1684 SILC_LOG_HEXDUMP(("Forwarded packet, len %d", sock->outbuf->len),
1685 sock->outbuf->data, sock->outbuf->len);
1687 /* Now actually send the packet */
1688 silc_server_packet_send_real(server, sock, force_send);
1691 /* Internal routine to actually create the channel packet and send it
1692 to network. This is common function in channel message sending. If
1693 `channel_message' is TRUE this encrypts the message as it is strictly
1694 a channel message. If FALSE normal encryption process is used. */
1697 silc_server_packet_send_to_channel_real(SilcServer server,
1698 SilcSocketConnection sock,
1699 SilcPacketContext *packet,
1702 unsigned char *data,
1703 unsigned int data_len,
1704 int channel_message,
1707 packet->truelen = data_len + SILC_PACKET_HEADER_LEN +
1708 packet->src_id_len + packet->dst_id_len;
1710 /* Prepare outgoing data buffer for packet sending */
1711 silc_packet_send_prepare(sock,
1712 SILC_PACKET_HEADER_LEN +
1713 packet->src_id_len +
1718 packet->buffer = sock->outbuf;
1720 /* Put the data to buffer, assemble and encrypt the packet. The packet
1721 is encrypted with normal session key shared with the client. */
1722 silc_buffer_put(sock->outbuf, data, data_len);
1723 silc_packet_assemble(packet);
1724 if (channel_message)
1725 silc_packet_encrypt(cipher, hmac, sock->outbuf, SILC_PACKET_HEADER_LEN +
1726 packet->src_id_len + packet->dst_id_len +
1729 silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
1731 SILC_LOG_HEXDUMP(("Channel packet, len %d", sock->outbuf->len),
1732 sock->outbuf->data, sock->outbuf->len);
1734 /* Now actually send the packet */
1735 silc_server_packet_send_real(server, sock, force_send);
1738 /* This routine is used by the server to send packets to channel. The
1739 packet sent with this function is distributed to all clients on
1740 the channel. Usually this is used to send notify messages to the
1741 channel, things like notify about new user joining to the channel. */
1743 void silc_server_packet_send_to_channel(SilcServer server,
1744 SilcChannelEntry channel,
1745 SilcPacketType type,
1746 unsigned char *data,
1747 unsigned int data_len,
1750 SilcSocketConnection sock = NULL;
1751 SilcPacketContext packetdata;
1752 SilcClientEntry client = NULL;
1753 SilcServerEntry *routed = NULL;
1754 SilcChannelClientEntry chl;
1755 SilcIDListData idata;
1756 unsigned int routed_count = 0;
1758 /* This doesn't send channel message packets */
1759 if (type == SILC_PACKET_CHANNEL_MESSAGE)
1762 SILC_LOG_DEBUG(("Sending packet to channel"));
1764 /* Set the packet context pointers. */
1765 packetdata.flags = 0;
1766 packetdata.type = type;
1767 packetdata.src_id = silc_id_id2str(server->id, SILC_ID_SERVER);
1768 packetdata.src_id_len = SILC_ID_SERVER_LEN;
1769 packetdata.src_id_type = SILC_ID_SERVER;
1770 packetdata.dst_id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
1771 packetdata.dst_id_len = SILC_ID_CHANNEL_LEN;
1772 packetdata.dst_id_type = SILC_ID_CHANNEL;
1773 packetdata.rng = server->rng;
1774 packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
1775 packetdata.src_id_len + packetdata.dst_id_len;
1776 packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
1778 /* If there are global users in the channel we will send the message
1779 first to our router for further routing. */
1780 if (server->server_type == SILC_SERVER && !server->standalone &&
1781 channel->global_users) {
1782 SilcServerEntry router;
1784 /* Get data used in packet header encryption, keys and stuff. */
1785 router = server->id_entry->router;
1786 sock = (SilcSocketConnection)router->connection;
1787 idata = (SilcIDListData)router;
1789 SILC_LOG_DEBUG(("Sending channel message to router for routing"));
1791 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1792 idata->send_key, idata->hmac,
1793 data, data_len, FALSE, force_send);
1796 /* Send the message to clients on the channel's client list. */
1797 silc_list_start(channel->user_list);
1798 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
1799 client = chl->client;
1801 /* If client has router set it is not locally connected client and
1802 we will route the message to the router set in the client. */
1803 if (client && client->router && server->server_type == SILC_ROUTER) {
1806 /* Check if we have sent the packet to this route already */
1807 for (k = 0; k < routed_count; k++)
1808 if (routed[k] == client->router)
1810 if (k < routed_count)
1813 /* Get data used in packet header encryption, keys and stuff. */
1814 sock = (SilcSocketConnection)client->router->connection;
1815 idata = (SilcIDListData)client->router;
1817 /* Send the packet */
1818 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1819 idata->send_key, idata->hmac,
1820 data, data_len, FALSE,
1823 /* We want to make sure that the packet is routed to same router
1824 only once. Mark this route as sent route. */
1826 routed = silc_realloc(routed, sizeof(*routed) * (k + 1));
1827 routed[k] = client->router;
1833 /* Send to locally connected client */
1836 /* Get data used in packet header encryption, keys and stuff. */
1837 sock = (SilcSocketConnection)client->connection;
1838 idata = (SilcIDListData)client;
1840 /* Send the packet */
1841 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1842 idata->send_key, idata->hmac,
1843 data, data_len, FALSE,
1850 silc_free(packetdata.src_id);
1851 silc_free(packetdata.dst_id);
1854 /* This routine is explicitly used to relay messages to some channel.
1855 Packets sent with this function we have received earlier and are
1856 totally encrypted. This just sends the packet to all clients on
1857 the channel. If the sender of the packet is someone on the channel
1858 the message will not be sent to that client. The SILC Packet header
1859 is encrypted with the session key shared between us and the client.
1860 MAC is also computed before encrypting the header. Rest of the
1861 packet will be untouched. */
1863 void silc_server_packet_relay_to_channel(SilcServer server,
1864 SilcSocketConnection sender_sock,
1865 SilcChannelEntry channel,
1867 SilcIdType sender_type,
1868 unsigned char *data,
1869 unsigned int data_len,
1873 SilcSocketConnection sock = NULL;
1874 SilcPacketContext packetdata;
1875 SilcClientEntry client = NULL;
1876 SilcServerEntry *routed = NULL;
1877 SilcChannelClientEntry chl;
1878 unsigned int routed_count = 0;
1879 SilcIDListData idata;
1881 SILC_LOG_DEBUG(("Relaying packet to channel"));
1883 /* Set the packet context pointers. */
1884 packetdata.flags = 0;
1885 packetdata.type = SILC_PACKET_CHANNEL_MESSAGE;
1886 packetdata.src_id = silc_id_id2str(sender, sender_type);
1887 packetdata.src_id_len = silc_id_get_len(sender_type);
1888 packetdata.src_id_type = sender_type;
1889 packetdata.dst_id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
1890 packetdata.dst_id_len = SILC_ID_CHANNEL_LEN;
1891 packetdata.dst_id_type = SILC_ID_CHANNEL;
1892 packetdata.rng = server->rng;
1893 packetdata.padlen = SILC_PACKET_PADLEN((SILC_PACKET_HEADER_LEN +
1894 packetdata.src_id_len +
1895 packetdata.dst_id_len));
1897 /* If there are global users in the channel we will send the message
1898 first to our router for further routing. */
1899 if (server->server_type == SILC_SERVER && !server->standalone &&
1900 channel->global_users) {
1901 SilcServerEntry router;
1903 router = server->id_entry->router;
1905 /* Check that the sender is not our router. */
1906 if (sender_sock != (SilcSocketConnection)router->connection) {
1908 /* Get data used in packet header encryption, keys and stuff. */
1909 sock = (SilcSocketConnection)router->connection;
1910 idata = (SilcIDListData)router;
1912 SILC_LOG_DEBUG(("Sending channel message to router for routing"));
1914 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1915 idata->send_key, idata->hmac,
1916 data, data_len, TRUE,
1921 /* Send the message to clients on the channel's client list. */
1922 silc_list_start(channel->user_list);
1923 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
1924 client = chl->client;
1928 /* If sender is one on the channel do not send it the packet. */
1929 if (!found && !SILC_ID_CLIENT_COMPARE(client->id, sender)) {
1934 /* If the client has set router it means that it is not locally
1935 connected client and we will route the packet further. */
1936 if (server->server_type == SILC_ROUTER && client->router) {
1939 /* Sender maybe server as well so we want to make sure that
1940 we won't send the message to the server it came from. */
1941 if (!found && !SILC_ID_SERVER_COMPARE(client->router->id, sender)) {
1946 /* Check if we have sent the packet to this route already */
1947 for (k = 0; k < routed_count; k++)
1948 if (routed[k] == client->router)
1950 if (k < routed_count)
1953 /* Get data used in packet header encryption, keys and stuff. */
1954 sock = (SilcSocketConnection)client->router->connection;
1955 idata = (SilcIDListData)client->router;
1957 /* Send the packet */
1958 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1959 idata->send_key, idata->hmac,
1960 data, data_len, TRUE,
1963 /* We want to make sure that the packet is routed to same router
1964 only once. Mark this route as sent route. */
1966 routed = silc_realloc(routed, sizeof(*routed) * (k + 1));
1967 routed[k] = client->router;
1973 /* XXX Check client's mode on the channel. */
1975 /* Get data used in packet header encryption, keys and stuff. */
1976 sock = (SilcSocketConnection)client->connection;
1977 idata = (SilcIDListData)client;
1979 SILC_LOG_DEBUG(("Sending packet to client %s",
1980 sock->hostname ? sock->hostname : sock->ip));
1982 /* Send the packet */
1983 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1984 idata->send_key, idata->hmac,
1985 data, data_len, TRUE,
1990 silc_free(packetdata.src_id);
1991 silc_free(packetdata.dst_id);
1994 /* This function is used to send packets strictly to all local clients
1995 on a particular channel. This is used for example to distribute new
1996 channel key to all our locally connected clients on the channel.
1997 The packets are always encrypted with the session key shared between
1998 the client, this means these are not _to the channel_ but _to the client_
2001 void silc_server_packet_send_local_channel(SilcServer server,
2002 SilcChannelEntry channel,
2003 SilcPacketType type,
2004 SilcPacketFlags flags,
2005 unsigned char *data,
2006 unsigned int data_len,
2009 SilcClientEntry client;
2010 SilcChannelClientEntry chl;
2011 SilcSocketConnection sock = NULL;
2013 SILC_LOG_DEBUG(("Start"));
2015 /* Send the message to clients on the channel's client list. */
2016 silc_list_start(channel->user_list);
2017 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2018 client = chl->client;
2021 sock = (SilcSocketConnection)client->connection;
2023 /* Send the packet to the client */
2024 silc_server_packet_send_dest(server, sock, type, flags, client->id,
2025 SILC_ID_CLIENT, data, data_len,
2031 /* Relays received command reply packet to the correct destination. The
2032 destination must be one of our locally connected client or the packet
2033 will be ignored. This is called when server has forwarded one of
2034 client's command request to router and router has now replied to the
2037 void silc_server_packet_relay_command_reply(SilcServer server,
2038 SilcSocketConnection sock,
2039 SilcPacketContext *packet)
2041 SilcBuffer buffer = packet->buffer;
2042 SilcClientEntry client;
2044 SilcSocketConnection dst_sock;
2045 SilcIDListData idata;
2047 SILC_LOG_DEBUG(("Start"));
2049 /* Source must be server or router */
2050 if (packet->src_id_type != SILC_ID_SERVER &&
2051 sock->type != SILC_SOCKET_TYPE_ROUTER)
2054 /* Destination must be client */
2055 if (packet->dst_id_type != SILC_ID_CLIENT)
2058 /* Execute command reply locally for the command */
2059 silc_server_command_reply_process(server, sock, buffer);
2061 id = silc_id_str2id(packet->dst_id, SILC_ID_CLIENT);
2063 /* Destination must be one of ours */
2064 client = silc_idlist_find_client_by_id(server->local_list, id);
2070 /* Relay the packet to the client */
2072 dst_sock = (SilcSocketConnection)client->connection;
2073 silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len
2074 + packet->dst_id_len + packet->padlen);
2076 silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
2077 silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
2079 idata = (SilcIDListData)client;
2081 /* Encrypt packet */
2082 silc_packet_encrypt(idata->send_key, idata->hmac, dst_sock->outbuf,
2085 /* Send the packet */
2086 silc_server_packet_send_real(server, dst_sock, FALSE);
2091 silc_buffer_free(buffer);
2094 /* Closes connection to socket connection */
2096 void silc_server_close_connection(SilcServer server,
2097 SilcSocketConnection sock)
2100 SILC_LOG_DEBUG(("Closing connection %d", sock->sock));
2102 /* We won't listen for this connection anymore */
2103 silc_schedule_unset_listen_fd(sock->sock);
2105 /* Unregister all tasks */
2106 silc_task_unregister_by_fd(server->io_queue, sock->sock);
2107 silc_task_unregister_by_fd(server->timeout_queue, sock->sock);
2109 /* Close the actual connection */
2110 silc_net_close_connection(sock->sock);
2111 server->sockets[sock->sock] = NULL;
2112 silc_socket_free(sock);
2115 /* Sends disconnect message to remote connection and disconnects the
2118 void silc_server_disconnect_remote(SilcServer server,
2119 SilcSocketConnection sock,
2120 const char *fmt, ...)
2123 unsigned char buf[4096];
2125 memset(buf, 0, sizeof(buf));
2127 vsprintf(buf, fmt, ap);
2130 SILC_LOG_DEBUG(("Disconnecting remote host"));
2132 /* Notify remote end that the conversation is over. The notify message
2133 is tried to be sent immediately. */
2134 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2135 buf, strlen(buf), TRUE);
2137 /* Mark the connection to be disconnected */
2138 SILC_SET_DISCONNECTED(sock);
2139 silc_server_close_connection(server, sock);
2142 /* Free's user_data pointer from socket connection object. As this
2143 pointer maybe anything we wil switch here to find the correct
2144 data type and free it the way it needs to be free'd. */
2146 void silc_server_free_sock_user_data(SilcServer server,
2147 SilcSocketConnection sock)
2149 SILC_LOG_DEBUG(("Start"));
2151 switch(sock->type) {
2152 case SILC_SOCKET_TYPE_CLIENT:
2154 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2156 /* Remove client from all channels */
2157 silc_server_remove_from_channels(server, sock, user_data);
2159 /* XXX must take some info to history before freeing */
2161 /* Free the client entry and everything in it */
2162 silc_idlist_del_data(user_data);
2163 silc_idlist_del_client(server->local_list, user_data);
2166 case SILC_SOCKET_TYPE_SERVER:
2167 case SILC_SOCKET_TYPE_ROUTER:
2175 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2177 silc_idlist_del_data(user_data);
2178 silc_free(user_data);
2183 sock->user_data = NULL;
2186 /* Removes client from all channels it has joined. This is used when
2187 client connection is disconnected. If the client on a channel
2188 is last, the channel is removed as well. */
2190 void silc_server_remove_from_channels(SilcServer server,
2191 SilcSocketConnection sock,
2192 SilcClientEntry client)
2194 SilcChannelEntry channel;
2195 SilcChannelClientEntry chl;
2196 SilcBuffer chidp, clidp;
2198 SILC_LOG_DEBUG(("Start"));
2200 if (!client || !client->id)
2203 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2205 /* Remove the client from all channels. The client is removed from
2206 the channels' user list. */
2207 silc_list_start(client->channels);
2208 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2209 channel = chl->channel;
2210 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
2212 /* Remove from list */
2213 silc_list_del(client->channels, chl);
2215 /* If this client is last one on the channel the channel
2216 is removed all together. */
2217 if (silc_list_count(channel->user_list) < 2) {
2219 /* However, if the channel has marked global users then the
2220 channel is not created locally, and this does not remove the
2221 channel globally from SILC network, in this case we will
2222 notify that this client has left the channel. */
2223 if (channel->global_users)
2224 silc_server_send_notify_to_channel(server, channel,
2225 SILC_NOTIFY_TYPE_SIGNOFF, 1,
2226 clidp->data, clidp->len);
2228 silc_idlist_del_channel(server->local_list, channel);
2232 /* Remove from list */
2233 silc_list_del(channel->user_list, chl);
2236 /* Send notify to channel about client leaving SILC and thus
2237 the entire channel. */
2238 silc_server_send_notify_to_channel(server, channel,
2239 SILC_NOTIFY_TYPE_SIGNOFF, 1,
2240 clidp->data, clidp->len);
2241 silc_buffer_free(chidp);
2244 silc_buffer_free(clidp);
2247 /* Removes client from one channel. This is used for example when client
2248 calls LEAVE command to remove itself from the channel. Returns TRUE
2249 if channel still exists and FALSE if the channel is removed when
2250 last client leaves the channel. If `notify' is FALSE notify messages
2253 int silc_server_remove_from_one_channel(SilcServer server,
2254 SilcSocketConnection sock,
2255 SilcChannelEntry channel,
2256 SilcClientEntry client,
2259 SilcChannelEntry ch;
2260 SilcChannelClientEntry chl;
2263 SILC_LOG_DEBUG(("Start"));
2265 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2267 /* Remove the client from the channel. The client is removed from
2268 the channel's user list. */
2269 silc_list_start(client->channels);
2270 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2271 if (chl->channel != 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) {
2282 /* Notify about leaving client if this channel has global users,
2283 ie. the channel is not created locally. */
2284 if (notify && channel->global_users)
2285 silc_server_send_notify_to_channel(server, channel,
2286 SILC_NOTIFY_TYPE_LEAVE, 1,
2287 clidp->data, clidp->len);
2289 silc_idlist_del_channel(server->local_list, channel);
2290 silc_buffer_free(clidp);
2294 /* Remove from list */
2295 silc_list_del(channel->user_list, chl);
2298 /* Send notify to channel about client leaving the channel */
2300 silc_server_send_notify_to_channel(server, channel,
2301 SILC_NOTIFY_TYPE_LEAVE, 1,
2302 clidp->data, clidp->len);
2306 silc_buffer_free(clidp);
2310 /* Returns TRUE if the given client is on the channel. FALSE if not.
2311 This works because we assure that the user list on the channel is
2312 always in up to date thus we can only check the channel list from
2313 `client' which is faster than checking the user list from `channel'. */
2315 int silc_server_client_on_channel(SilcClientEntry client,
2316 SilcChannelEntry channel)
2318 SilcChannelClientEntry chl;
2320 if (!client || !channel)
2323 silc_list_start(client->channels);
2324 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END)
2325 if (chl->channel == channel)
2331 /* Timeout callback. This is called if connection is idle or for some
2332 other reason is not responding within some period of time. This
2333 disconnects the remote end. */
2335 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2337 SilcServerConnection sconn = (SilcServerConnection)context;
2338 SilcSocketConnection sock = sconn->server->sockets[fd];
2340 silc_server_disconnect_remote(sconn->server, sock,
2341 "Server closed connection: "
2342 "Connection timeout");
2345 /* Internal routine used to send (relay, route) private messages to some
2346 destination. If the private message key does not exist then the message
2347 is re-encrypted, otherwise we just pass it along. */
2350 silc_server_private_message_send_internal(SilcServer server,
2351 SilcSocketConnection dst_sock,
2354 SilcPacketContext *packet)
2356 SilcBuffer buffer = packet->buffer;
2358 /* Send and re-encrypt if private messge key does not exist */
2359 if ((packet->flags & SILC_PACKET_FLAG_PRIVMSG_KEY) == FALSE) {
2361 silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len
2362 + packet->dst_id_len + packet->padlen);
2363 silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
2364 silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
2366 /* Re-encrypt packet */
2367 silc_packet_encrypt(cipher, hmac, dst_sock->outbuf, buffer->len);
2369 /* Send the packet */
2370 silc_server_packet_send_real(server, dst_sock, FALSE);
2373 /* Key exist so just send it */
2374 silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len
2375 + packet->dst_id_len + packet->padlen);
2376 silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
2377 silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
2378 silc_server_packet_send_real(server, dst_sock, FALSE);
2382 /* Received private message. This resolves the destination of the message
2383 and sends the packet. This is used by both server and router. If the
2384 destination is our locally connected client this sends the packet to
2385 the client. This may also send the message for further routing if
2386 the destination is not in our server (or router). */
2388 void silc_server_private_message(SilcServer server,
2389 SilcSocketConnection sock,
2390 SilcPacketContext *packet)
2392 SilcBuffer buffer = packet->buffer;
2394 SilcServerEntry router;
2395 SilcSocketConnection dst_sock;
2396 SilcClientEntry client;
2397 SilcIDListData idata;
2399 SILC_LOG_DEBUG(("Start"));
2401 if (!packet->dst_id) {
2402 SILC_LOG_ERROR(("Bad Client ID in private message packet, dropped"));
2406 /* Decode destination Client ID */
2407 id = silc_id_str2id(packet->dst_id, SILC_ID_CLIENT);
2409 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
2413 /* If the destination belongs to our server we don't have to route
2414 the message anywhere but to send it to the local destination. */
2415 client = silc_idlist_find_client_by_id(server->local_list, id);
2417 /* It exists, now deliver the message to the destination */
2418 dst_sock = (SilcSocketConnection)client->connection;
2420 /* If we are router and the client has router then the client is in
2421 our cell but not directly connected to us. */
2422 if (server->server_type == SILC_ROUTER && client->router) {
2423 /* We are of course in this case the client's router thus the real
2424 "router" of the client is the server who owns the client. Thus
2425 we will send the packet to that server. */
2426 router = (SilcServerEntry)dst_sock->user_data;
2427 idata = (SilcIDListData)router;
2428 // assert(client->router == server->id_entry);
2430 silc_server_private_message_send_internal(server, dst_sock,
2437 /* Seems that client really is directly connected to us */
2438 idata = (SilcIDListData)client;
2439 silc_server_private_message_send_internal(server, dst_sock,
2441 idata->hmac, packet);
2445 /* Destination belongs to someone not in this server. If we are normal
2446 server our action is to send the packet to our router. */
2447 if (server->server_type == SILC_SERVER && !server->standalone) {
2448 router = server->id_entry->router;
2450 /* Send to primary route */
2452 dst_sock = (SilcSocketConnection)router->connection;
2453 idata = (SilcIDListData)router;
2454 silc_server_private_message_send_internal(server, dst_sock,
2456 idata->hmac, packet);
2461 /* We are router and we will perform route lookup for the destination
2462 and send the message to fastest route. */
2463 if (server->server_type == SILC_ROUTER && !server->standalone) {
2464 dst_sock = silc_server_get_route(server, id, SILC_ID_CLIENT);
2465 router = (SilcServerEntry)dst_sock->user_data;
2466 idata = (SilcIDListData)router;
2468 /* Get fastest route and send packet. */
2470 silc_server_private_message_send_internal(server, dst_sock,
2472 idata->hmac, packet);
2478 silc_server_send_error(server, sock,
2479 "No such nickname: Private message not sent");
2481 silc_buffer_free(buffer);
2484 /* Process received channel message. The message can be originated from
2485 client or server. */
2487 void silc_server_channel_message(SilcServer server,
2488 SilcSocketConnection sock,
2489 SilcPacketContext *packet)
2491 SilcChannelEntry channel = NULL;
2492 SilcChannelClientEntry chl;
2493 SilcChannelID *id = NULL;
2494 void *sender = NULL;
2495 SilcBuffer buffer = packet->buffer;
2497 SILC_LOG_DEBUG(("Processing channel message"));
2500 if (packet->dst_id_type != SILC_ID_CHANNEL) {
2501 SILC_LOG_ERROR(("Received bad message for channel, dropped"));
2502 SILC_LOG_DEBUG(("Received bad message for channel, dropped"));
2506 /* Find channel entry */
2507 id = silc_id_str2id(packet->dst_id, SILC_ID_CHANNEL);
2508 channel = silc_idlist_find_channel_by_id(server->local_list, id);
2510 SILC_LOG_DEBUG(("Could not find channel"));
2514 /* See that this client is on the channel. If the message is coming
2515 from router we won't do the check as the message is from client that
2516 we don't know about. Also, if the original sender is not client
2517 (as it can be server as well) we don't do the check. */
2518 sender = silc_id_str2id(packet->src_id, packet->src_id_type);
2519 if (sock->type != SILC_SOCKET_TYPE_ROUTER &&
2520 packet->src_id_type == SILC_ID_CLIENT) {
2521 silc_list_start(channel->user_list);
2522 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2523 if (chl->client && !SILC_ID_CLIENT_COMPARE(chl->client->id, sender))
2526 if (chl == SILC_LIST_END)
2530 /* Distribute the packet to our local clients. This will send the
2531 packet for further routing as well, if needed. */
2532 silc_server_packet_relay_to_channel(server, sock, channel, sender,
2533 packet->src_id_type,
2534 packet->buffer->data,
2535 packet->buffer->len, FALSE);
2542 silc_buffer_free(buffer);
2545 /* Received channel key packet. We distribute the key to all of our locally
2546 connected clients on the channel. */
2547 /* XXX Router must accept this packet and distribute the key to all its
2548 server that has clients on the channel */
2550 void silc_server_channel_key(SilcServer server,
2551 SilcSocketConnection sock,
2552 SilcPacketContext *packet)
2554 SilcBuffer buffer = packet->buffer;
2555 SilcChannelKeyPayload payload = NULL;
2556 SilcChannelID *id = NULL;
2557 SilcChannelEntry channel;
2558 SilcChannelClientEntry chl;
2559 SilcClientEntry client;
2561 unsigned int tmp_len;
2564 if (packet->src_id_type != SILC_ID_SERVER &&
2565 sock->type != SILC_SOCKET_TYPE_ROUTER)
2568 /* Decode channel key payload */
2569 payload = silc_channel_key_payload_parse(buffer);
2571 SILC_LOG_ERROR(("Bad channel key payload, dropped"));
2575 /* Get channel ID */
2576 tmp = silc_channel_key_get_id(payload, &tmp_len);
2577 id = silc_id_payload_parse_id(tmp, tmp_len);
2581 /* Get the channel entry */
2582 channel = silc_idlist_find_channel_by_id(server->local_list, id);
2584 SILC_LOG_ERROR(("Received key for non-existent channel"));
2588 /* Save the key for us as well */
2589 tmp = silc_channel_key_get_key(payload, &tmp_len);
2592 cipher = silc_channel_key_get_cipher(payload, NULL);;
2595 if (!silc_cipher_alloc(cipher, &channel->channel_key))
2598 channel->key_len = tmp_len * 8;
2599 channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
2600 memcpy(channel->key, tmp, tmp_len);
2601 channel->channel_key->cipher->set_key(channel->channel_key->context,
2604 /* Distribute the key to all clients on the channel */
2605 /* XXX Some other sender should be used, I think this is not correct */
2606 silc_list_start(channel->user_list);
2607 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2608 client = chl->client;
2611 silc_server_packet_send_dest(server, client->connection,
2612 SILC_PACKET_CHANNEL_KEY, 0,
2613 client->id, SILC_ID_CLIENT,
2614 buffer->data, buffer->len, FALSE);
2621 silc_channel_key_payload_free(payload);
2622 silc_buffer_free(buffer);
2625 /* Sends current motd to client */
2627 void silc_server_send_motd(SilcServer server,
2628 SilcSocketConnection sock)
2633 if (server->config && server->config->motd &&
2634 server->config->motd->motd_file) {
2636 motd = silc_file_read(server->config->motd->motd_file, &motd_len);
2640 silc_server_send_notify(server, sock, SILC_NOTIFY_TYPE_MOTD, 1,
2646 /* Sends error message. Error messages may or may not have any
2649 void silc_server_send_error(SilcServer server,
2650 SilcSocketConnection sock,
2651 const char *fmt, ...)
2654 unsigned char buf[4096];
2656 memset(buf, 0, sizeof(buf));
2658 vsprintf(buf, fmt, ap);
2661 silc_server_packet_send(server, sock, SILC_PACKET_ERROR, 0,
2662 buf, strlen(buf), FALSE);
2665 /* Sends notify message. If format is TRUE the variable arguments are
2666 formatted and the formatted string is sent as argument payload. If it is
2667 FALSE then each argument is sent as separate argument and their format
2668 in the argument list must be { argument data, argument length }. */
2670 void silc_server_send_notify(SilcServer server,
2671 SilcSocketConnection sock,
2672 SilcNotifyType type,
2673 unsigned int argc, ...)
2680 packet = silc_notify_payload_encode(type, argc, ap);
2681 silc_server_packet_send(server, sock, SILC_PACKET_NOTIFY, 0,
2682 packet->data, packet->len, FALSE);
2683 silc_buffer_free(packet);
2686 /* Sends notify message destined to specific entity. */
2688 void silc_server_send_notify_dest(SilcServer server,
2689 SilcSocketConnection sock,
2691 SilcIdType dest_id_type,
2692 SilcNotifyType type,
2693 unsigned int argc, ...)
2700 packet = silc_notify_payload_encode(type, argc, ap);
2701 silc_server_packet_send_dest(server, sock, SILC_PACKET_NOTIFY, 0,
2702 dest_id, dest_id_type,
2703 packet->data, packet->len, FALSE);
2704 silc_buffer_free(packet);
2707 /* Sends notify message to a channel. The notify message sent is
2708 distributed to all clients on the channel. */
2710 void silc_server_send_notify_to_channel(SilcServer server,
2711 SilcChannelEntry channel,
2712 SilcNotifyType type,
2713 unsigned int argc, ...)
2720 packet = silc_notify_payload_encode(type, argc, ap);
2721 silc_server_packet_send_to_channel(server, channel,
2723 packet->data, packet->len, FALSE);
2724 silc_buffer_free(packet);
2727 /* Send notify message to all clients the client has joined. It is quaranteed
2728 that the message is sent only once to a client (ie. if a client is joined
2729 on two same channel it will receive only one notify message). Also, this
2730 sends only to local clients (locally connected if we are server, and to
2731 local servers if we are router). */
2733 void silc_server_send_notify_on_channels(SilcServer server,
2734 SilcClientEntry client,
2735 SilcNotifyType type,
2736 unsigned int argc, ...)
2739 SilcSocketConnection sock = NULL;
2740 SilcPacketContext packetdata;
2742 SilcClientEntry *sent_clients = NULL;
2743 unsigned int sent_clients_count = 0;
2744 SilcServerEntry *routed = NULL;
2745 unsigned int routed_count = 0;
2746 SilcChannelEntry channel;
2747 SilcChannelClientEntry chl, chl2;
2748 SilcIDListData idata;
2750 unsigned char *data;
2751 unsigned int data_len;
2752 int force_send = FALSE;
2755 if (!silc_list_count(client->channels))
2759 packet = silc_notify_payload_encode(type, argc, ap);
2760 data = packet->data;
2761 data_len = packet->len;
2763 /* Set the packet context pointers. */
2764 packetdata.flags = 0;
2765 packetdata.type = SILC_PACKET_NOTIFY;
2766 packetdata.src_id = silc_id_id2str(server->id, SILC_ID_SERVER);
2767 packetdata.src_id_len = SILC_ID_SERVER_LEN;
2768 packetdata.src_id_type = SILC_ID_SERVER;
2769 packetdata.rng = server->rng;
2771 silc_list_start(client->channels);
2772 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2773 channel = chl->channel;
2775 /* Send the message to all clients on the channel's client list. */
2776 silc_list_start(channel->user_list);
2777 while ((chl2 = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2780 /* Check if we have sent the packet to this client already */
2781 for (k = 0; k < sent_clients_count; k++)
2782 if (sent_clients[k] == c)
2784 if (k < sent_clients_count)
2787 /* If we are router and if this client has router set it is not
2788 locally connected client and we will route the message to the
2789 router set in the client. */
2790 if (c && c->router && server->server_type == SILC_ROUTER) {
2791 /* Check if we have sent the packet to this route already */
2792 for (k = 0; k < routed_count; k++)
2793 if (routed[k] == c->router)
2795 if (k < routed_count)
2798 /* Get data used in packet header encryption, keys and stuff. */
2799 sock = (SilcSocketConnection)c->router->connection;
2800 idata = (SilcIDListData)c->router;
2802 packetdata.dst_id = silc_id_id2str(c->router->id, SILC_ID_SERVER);
2803 packetdata.dst_id_len = SILC_ID_SERVER_LEN;
2804 packetdata.dst_id_type = SILC_ID_SERVER;
2805 packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
2806 packetdata.src_id_len + packetdata.dst_id_len;
2807 packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
2809 /* Send the packet */
2810 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
2811 idata->send_key, idata->hmac,
2812 data, data_len, FALSE,
2815 silc_free(packetdata.dst_id);
2817 /* We want to make sure that the packet is routed to same router
2818 only once. Mark this route as sent route. */
2820 routed = silc_realloc(routed, sizeof(*routed) * (k + 1));
2821 routed[k] = c->router;
2827 /* Send to locally connected client */
2830 /* Get data used in packet header encryption, keys and stuff. */
2831 sock = (SilcSocketConnection)c->connection;
2832 idata = (SilcIDListData)c;
2834 packetdata.dst_id = silc_id_id2str(c->id, SILC_ID_CLIENT);
2835 packetdata.dst_id_len = SILC_ID_CLIENT_LEN;
2836 packetdata.dst_id_type = SILC_ID_CLIENT;
2837 packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
2838 packetdata.src_id_len + packetdata.dst_id_len;
2839 packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
2841 /* Send the packet */
2842 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
2843 idata->send_key, idata->hmac,
2844 data, data_len, FALSE,
2847 silc_free(packetdata.dst_id);
2849 /* Make sure that we send the notify only once per client. */
2850 sent_clients = silc_realloc(sent_clients, sizeof(*sent_clients) *
2851 (sent_clients_count + 1));
2852 sent_clients[sent_clients_count] = c;
2853 sent_clients_count++;
2860 if (sent_clients_count)
2861 silc_free(sent_clients);
2862 silc_free(packetdata.src_id);
2865 /* Sends New ID Payload to remote end. The packet is used to distribute
2866 information about new registered clients, servers, channel etc. usually
2867 to routers so that they can keep these information up to date.
2868 If the argument `broadcast' is TRUE then the packet is sent as
2869 broadcast packet. */
2871 void silc_server_send_new_id(SilcServer server,
2872 SilcSocketConnection sock,
2874 void *id, SilcIdType id_type,
2875 unsigned int id_len)
2879 idp = silc_id_payload_encode(id, id_type);
2880 silc_server_packet_send(server, sock, SILC_PACKET_NEW_ID,
2881 broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
2882 idp->data, idp->len, FALSE);
2883 silc_buffer_free(idp);
2886 /* Sends Replace ID payload to remote end. This is used to replace old
2887 ID with new ID sent in the packet. This is called for example when
2888 user changes nickname and we create new ID for the user. If the
2889 argument `broadcast' is TRUE then the packet is sent as
2890 broadcast packet. */
2891 /* XXX It would be expected that the new id is same type as the old
2894 void silc_server_send_replace_id(SilcServer server,
2895 SilcSocketConnection sock,
2897 void *old_id, SilcIdType old_id_type,
2898 unsigned int old_id_len,
2899 void *new_id, SilcIdType new_id_type,
2900 unsigned int new_id_len)
2906 oid = silc_id_id2str(old_id, old_id_type);
2910 nid = silc_id_id2str(new_id, new_id_type);
2914 packet = silc_buffer_alloc(2 + 2 + 2 + 2 + old_id_len + new_id_len);
2915 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
2916 silc_buffer_format(packet,
2917 SILC_STR_UI_SHORT(old_id_type),
2918 SILC_STR_UI_SHORT(old_id_len),
2919 SILC_STR_UI_XNSTRING(oid, old_id_len),
2920 SILC_STR_UI_SHORT(new_id_type),
2921 SILC_STR_UI_SHORT(new_id_len),
2922 SILC_STR_UI_XNSTRING(nid, new_id_len),
2925 silc_server_packet_send(server, sock, SILC_PACKET_REPLACE_ID,
2926 broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
2927 packet->data, packet->len, FALSE);
2930 silc_buffer_free(packet);
2933 /* This function is used to send Remove Channel User payload. This may sent
2934 by server but is usually used only by router to notify other routers that
2935 user has left a channel. Normal server sends this packet to its router
2936 to notify that the router should not hold a record about this client
2937 on a channel anymore. Router distributes it further to other routers. */
2939 void silc_server_send_remove_channel_user(SilcServer server,
2940 SilcSocketConnection sock,
2942 void *client_id, void *channel_id)
2945 unsigned char *clid, *chid;
2947 clid = silc_id_id2str(client_id, SILC_ID_CLIENT);
2951 chid = silc_id_id2str(channel_id, SILC_ID_CHANNEL);
2955 packet = silc_buffer_alloc(2 + 2 + SILC_ID_CLIENT_LEN + SILC_ID_CHANNEL_LEN);
2956 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
2957 silc_buffer_format(packet,
2958 SILC_STR_UI_SHORT(SILC_ID_CLIENT_LEN),
2959 SILC_STR_UI_XNSTRING(clid, SILC_ID_CLIENT_LEN),
2960 SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
2961 SILC_STR_UI_XNSTRING(chid, SILC_ID_CHANNEL_LEN),
2964 silc_server_packet_send(server, sock, SILC_PACKET_REMOVE_CHANNEL_USER,
2965 broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
2966 packet->data, packet->len, FALSE);
2969 silc_buffer_free(packet);
2972 /* Received packet to replace a ID. This checks that the requested ID
2973 exists and replaces it with the new one. */
2975 void silc_server_replace_id(SilcServer server,
2976 SilcSocketConnection sock,
2977 SilcPacketContext *packet)
2979 SilcBuffer buffer = packet->buffer;
2980 unsigned char *old_id = NULL, *new_id = NULL;
2981 SilcIdType old_id_type, new_id_type;
2982 unsigned short old_id_len, new_id_len;
2983 void *id = NULL, *id2 = NULL;
2985 if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
2986 packet->src_id_type == SILC_ID_CLIENT)
2989 SILC_LOG_DEBUG(("Replacing ID"));
2991 silc_buffer_unformat(buffer,
2992 SILC_STR_UI_SHORT(&old_id_type),
2993 SILC_STR_UI16_NSTRING_ALLOC(&old_id, &old_id_len),
2994 SILC_STR_UI_SHORT(&new_id_type),
2995 SILC_STR_UI16_NSTRING_ALLOC(&new_id, &new_id_len),
2998 if (old_id_type != new_id_type)
3001 if (old_id_len != silc_id_get_len(old_id_type) ||
3002 new_id_len != silc_id_get_len(new_id_type))
3005 id = silc_id_str2id(old_id, old_id_type);
3009 id2 = silc_id_str2id(new_id, new_id_type);
3013 /* Replace the old ID */
3014 switch(old_id_type) {
3015 case SILC_ID_CLIENT:
3016 if (silc_idlist_replace_client_id(server->local_list, id, id2) == NULL)
3017 if (server->server_type == SILC_ROUTER)
3018 silc_idlist_replace_client_id(server->global_list, id, id2);
3021 case SILC_ID_SERVER:
3022 if (silc_idlist_replace_server_id(server->local_list, id, id2) == NULL)
3023 if (server->server_type == SILC_ROUTER)
3024 silc_idlist_replace_server_id(server->global_list, id, id2);
3027 case SILC_ID_CHANNEL:
3028 /* XXX Hmm... Basically this cannot occur. Channel ID's cannot be
3047 /* Creates new channel. */
3049 SilcChannelEntry silc_server_new_channel(SilcServer server,
3050 SilcServerID *router_id,
3051 char *cipher, char *channel_name)
3053 int i, channel_len, key_len;
3054 SilcChannelID *channel_id;
3055 SilcChannelEntry entry;
3057 unsigned char channel_key[32], *id_string;
3060 SILC_LOG_DEBUG(("Creating new channel"));
3062 /* Create channel key */
3063 for (i = 0; i < 32; i++)
3064 channel_key[i] = silc_rng_get_byte(server->rng);
3071 silc_cipher_alloc(cipher, &key);
3072 key->cipher->set_key(key->context, channel_key, key_len);
3074 channel_name = strdup(channel_name);
3076 /* Create the channel */
3077 silc_id_create_channel_id(router_id, server->rng, &channel_id);
3078 entry = silc_idlist_add_channel(server->local_list, channel_name,
3079 SILC_CHANNEL_MODE_NONE, channel_id,
3082 silc_free(channel_name);
3086 entry->key = silc_calloc(key_len, sizeof(*entry->key));
3087 entry->key_len = key_len * 8;
3088 memcpy(entry->key, channel_key, key_len);
3089 memset(channel_key, 0, sizeof(channel_key));
3091 /* Notify other routers about the new channel. We send the packet
3092 to our primary route. */
3093 if (server->standalone == FALSE) {
3094 channel_len = strlen(channel_name);
3095 id_string = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3096 packet = silc_buffer_alloc(2 + SILC_ID_CHANNEL_LEN);
3098 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
3099 silc_buffer_format(packet,
3100 SILC_STR_UI_SHORT(channel_len),
3101 SILC_STR_UI_XNSTRING(channel_name, channel_len),
3102 SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
3103 SILC_STR_UI_XNSTRING(id_string, SILC_ID_CHANNEL_LEN),
3106 /* Send the packet to our router. */
3107 silc_server_packet_send(server, (SilcSocketConnection)
3108 server->id_entry->router->connection,
3109 SILC_PACKET_NEW_CHANNEL_USER, 0,
3110 packet->data, packet->len, TRUE);
3112 silc_free(id_string);
3113 silc_buffer_free(packet);
3119 /* Create new client. This processes incoming NEW_CLIENT packet and creates
3120 Client ID for the client. Client becomes registered after calling this
3123 SilcClientEntry silc_server_new_client(SilcServer server,
3124 SilcSocketConnection sock,
3125 SilcPacketContext *packet)
3127 SilcBuffer buffer = packet->buffer;
3128 SilcClientEntry client;
3129 SilcIDCacheEntry cache;
3130 SilcClientID *client_id;
3132 SilcIDListData idata;
3133 char *username = NULL, *realname = NULL, *id_string;
3135 SILC_LOG_DEBUG(("Creating new client"));
3137 if (sock->type != SILC_SOCKET_TYPE_CLIENT)
3140 /* Take client entry */
3141 client = (SilcClientEntry)sock->user_data;
3142 idata = (SilcIDListData)client;
3144 /* Fetch the old client cache entry so that we can update it. */
3145 if (!silc_idcache_find_by_context(server->local_list->clients,
3146 sock->user_data, &cache)) {
3147 SILC_LOG_ERROR(("Lost client's cache entry - bad thing"));
3151 /* Parse incoming packet */
3152 silc_buffer_unformat(buffer,
3153 SILC_STR_UI16_STRING_ALLOC(&username),
3154 SILC_STR_UI16_STRING_ALLOC(&realname),
3157 /* Create Client ID */
3158 silc_id_create_client_id(server->id, server->rng, server->md5hash,
3159 username, &client_id);
3161 /* Update client entry */
3162 idata->registered = TRUE;
3163 client->nickname = strdup(username);
3164 client->username = username;
3165 client->userinfo = realname;
3166 client->id = client_id;
3168 /* Update the cache entry */
3169 cache->id = (void *)client_id;
3170 cache->type = SILC_ID_CLIENT;
3171 cache->data = username;
3172 silc_idcache_sort_by_data(server->local_list->clients);
3174 /* Notify our router about new client on the SILC network */
3175 if (!server->standalone)
3176 silc_server_send_new_id(server, (SilcSocketConnection)
3177 server->id_entry->router->connection,
3178 server->server_type == SILC_SERVER ? TRUE : FALSE,
3179 client->id, SILC_ID_CLIENT, SILC_ID_CLIENT_LEN);
3181 /* Send the new client ID to the client. */
3182 id_string = silc_id_id2str(client->id, SILC_ID_CLIENT);
3183 reply = silc_buffer_alloc(2 + 2 + SILC_ID_CLIENT_LEN);
3184 silc_buffer_pull_tail(reply, SILC_BUFFER_END(reply));
3185 silc_buffer_format(reply,
3186 SILC_STR_UI_SHORT(SILC_ID_CLIENT),
3187 SILC_STR_UI_SHORT(SILC_ID_CLIENT_LEN),
3188 SILC_STR_UI_XNSTRING(id_string, SILC_ID_CLIENT_LEN),
3190 silc_server_packet_send(server, sock, SILC_PACKET_NEW_ID, 0,
3191 reply->data, reply->len, FALSE);
3192 silc_free(id_string);
3193 silc_buffer_free(reply);
3195 /* Send some nice info to the client */
3196 SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3197 ("Welcome to the SILC Network %s@%s",
3198 username, sock->hostname));
3199 SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3200 ("Your host is %s, running version %s",
3201 server->config->server_info->server_name,
3203 SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3204 ("Your connection is secured with %s cipher, "
3205 "key length %d bits",
3206 idata->send_key->cipher->name,
3207 idata->send_key->cipher->key_len));
3208 SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3209 ("Your current nickname is %s",
3213 silc_server_send_motd(server, sock);
3218 /* Create new server. This processes incoming NEW_SERVER packet and
3219 saves the received Server ID. The server is our locally connected
3220 server thus we save all the information and save it to local list.
3221 This funtion can be used by both normal server and router server.
3222 If normal server uses this it means that its router has connected
3223 to the server. If router uses this it means that one of the cell's
3224 servers is connected to the router. */
3226 SilcServerEntry silc_server_new_server(SilcServer server,
3227 SilcSocketConnection sock,
3228 SilcPacketContext *packet)
3230 SilcBuffer buffer = packet->buffer;
3231 SilcServerEntry new_server;
3232 SilcIDCacheEntry cache;
3233 SilcServerID *server_id;
3234 SilcIDListData idata;
3235 unsigned char *server_name, *id_string;
3236 unsigned short id_len;
3238 SILC_LOG_DEBUG(("Creating new server"));
3240 if (sock->type != SILC_SOCKET_TYPE_SERVER &&
3241 sock->type != SILC_SOCKET_TYPE_ROUTER)
3244 /* Take server entry */
3245 new_server = (SilcServerEntry)sock->user_data;
3246 idata = (SilcIDListData)new_server;
3248 /* Fetch the old server cache entry so that we can update it. */
3249 if (!silc_idcache_find_by_context(server->local_list->servers,
3250 sock->user_data, &cache)) {
3251 SILC_LOG_ERROR(("Lost server's cache entry - bad thing"));
3255 /* Parse the incoming packet */
3256 silc_buffer_unformat(buffer,
3257 SILC_STR_UI16_NSTRING_ALLOC(&id_string, &id_len),
3258 SILC_STR_UI16_STRING_ALLOC(&server_name),
3261 if (id_len > buffer->len) {
3262 silc_free(id_string);
3263 silc_free(server_name);
3268 server_id = silc_id_str2id(id_string, SILC_ID_SERVER);
3269 silc_free(id_string);
3271 /* Update client entry */
3272 idata->registered = TRUE;
3273 new_server->server_name = server_name;
3274 new_server->id = server_id;
3276 /* Update the cache entry */
3277 cache->id = (void *)server_id;
3278 cache->type = SILC_ID_SERVER;
3279 cache->data = server_name;
3280 silc_idcache_sort_by_data(server->local_list->servers);
3282 /* Distribute the information about new server in the SILC network
3283 to our router. If we are normal server we won't send anything
3284 since this connection must be our router connection. */
3285 if (server->server_type == SILC_ROUTER && !server->standalone &&
3286 server->id_entry->router->connection != sock)
3287 silc_server_send_new_id(server, server->id_entry->router->connection,
3288 TRUE, new_server->id, SILC_ID_SERVER,
3289 SILC_ID_SERVER_LEN);
3294 /* Processes incoming New ID Payload. New ID Payload is used to distribute
3295 information about newly registered clients, servers and created
3298 void silc_server_new_id(SilcServer server, SilcSocketConnection sock,
3299 SilcPacketContext *packet)
3301 SilcBuffer buffer = packet->buffer;
3303 SilcServerEntry tmpserver, router;
3304 SilcSocketConnection router_sock;
3309 SILC_LOG_DEBUG(("Processing new ID"));
3311 if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3312 server->server_type == SILC_SERVER ||
3313 packet->src_id_type != SILC_ID_SERVER)
3316 idp = silc_id_payload_parse(buffer);
3320 id_type = silc_id_payload_get_type(idp);
3322 /* Normal server cannot have other normal server connections */
3323 if (id_type == SILC_ID_SERVER && sock->type == SILC_SOCKET_TYPE_SERVER)
3326 id = silc_id_payload_get_id(idp);
3330 /* If the packet is originated from the one who sent it to us we know
3331 that the ID belongs to our cell, unless the sender was router. */
3332 tmpid = silc_id_str2id(packet->src_id, SILC_ID_SERVER);
3333 tmpserver = (SilcServerEntry)sock->user_data;
3335 if (!SILC_ID_SERVER_COMPARE(tmpid, tmpserver->id) &&
3336 sock->type == SILC_SOCKET_TYPE_SERVER) {
3337 id_list = server->local_list;
3339 router = sock->user_data;
3340 /* router = server->id_entry; */
3342 id_list = server->global_list;
3343 router_sock = (SilcSocketConnection)server->id_entry->router->connection;
3344 router = server->id_entry->router;
3350 case SILC_ID_CLIENT:
3352 SilcClientEntry idlist;
3354 /* Add the client to our local list. We are router and we keep
3355 cell specific local database of all clients in the cell. */
3356 idlist = silc_idlist_add_client(id_list, NULL, NULL, NULL,
3357 id, router, router_sock);
3361 case SILC_ID_SERVER:
3363 SilcServerEntry idlist;
3365 /* Add the server to our local list. We are router and we keep
3366 cell specific local database of all servers in the cell. */
3367 idlist = silc_idlist_add_server(id_list, NULL, 0, id, router,
3372 case SILC_ID_CHANNEL:
3373 /* Add the channel to our local list. We are router and we keep
3374 cell specific local database of all channels in the cell. */
3375 silc_idlist_add_channel(id_list, NULL, 0, id, router, NULL);
3383 silc_id_payload_free(idp);
3386 /* Received packet to remove a user from a channel. Routers notify other
3387 routers that user has left a channel. Client must not send this packet.
3388 Normal server may send this packet but ignores if it receives one. */
3390 void silc_server_remove_channel_user(SilcServer server,
3391 SilcSocketConnection sock,
3392 SilcPacketContext *packet)
3394 SilcBuffer buffer = packet->buffer;
3395 unsigned char *tmp1 = NULL, *tmp2 = NULL;
3396 SilcClientID *client_id = NULL;
3397 SilcChannelID *channel_id = NULL;
3398 SilcChannelEntry channel;
3399 SilcClientEntry client;
3401 SILC_LOG_DEBUG(("Removing user from channel"));
3403 if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3404 server->server_type == SILC_SERVER)
3407 silc_buffer_unformat(buffer,
3408 SILC_STR_UI16_STRING_ALLOC(&tmp1),
3409 SILC_STR_UI16_STRING_ALLOC(&tmp2),
3415 client_id = silc_id_str2id(tmp1, SILC_ID_CLIENT);
3416 channel_id = silc_id_str2id(tmp2, SILC_ID_CHANNEL);
3417 if (!client_id || !channel_id)
3420 /* XXX routers should check server->global_list as well */
3421 /* Get channel entry */
3422 channel = silc_idlist_find_channel_by_id(server->local_list, channel_id);
3426 /* XXX routers should check server->global_list as well */
3427 /* Get client entry */
3428 client = silc_idlist_find_client_by_id(server->local_list, client_id);
3432 /* Remove from channel */
3433 silc_server_remove_from_one_channel(server, sock, channel, client, FALSE);
3441 silc_free(client_id);
3443 silc_free(channel_id);