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 /* Broadcast packet if it is marked as broadcast packet and it is
1190 originated from router and we are router. */
1191 if (server->server_type == SILC_ROUTER &&
1192 sock->type == SILC_SOCKET_TYPE_ROUTER &&
1193 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
1194 silc_server_packet_broadcast(server, server->id_entry->router->connection,
1198 /* Parse the incoming packet type */
1199 silc_server_packet_parse_type(server, sock, packet);
1202 silc_buffer_clear(sock->inbuf);
1204 silc_free(packet->src_id);
1206 silc_free(packet->dst_id);
1208 silc_free(parse_ctx);
1211 /* Parser callback called by silc_packet_receive_process. This merely
1212 registers timeout that will handle the actual parsing when appropriate. */
1214 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1216 SilcServer server = (SilcServer)parser_context->context;
1217 SilcSocketConnection sock = parser_context->sock;
1219 switch (sock->type) {
1220 case SILC_SOCKET_TYPE_CLIENT:
1221 case SILC_SOCKET_TYPE_UNKNOWN:
1222 /* Parse the packet with timeout */
1223 silc_task_register(server->timeout_queue, sock->sock,
1224 silc_server_packet_parse_real,
1225 (void *)parser_context, 0, 100000,
1227 SILC_TASK_PRI_NORMAL);
1229 case SILC_SOCKET_TYPE_SERVER:
1230 case SILC_SOCKET_TYPE_ROUTER:
1231 /* Packets from servers are parsed as soon as possible */
1232 silc_task_register(server->timeout_queue, sock->sock,
1233 silc_server_packet_parse_real,
1234 (void *)parser_context, 0, 1,
1236 SILC_TASK_PRI_NORMAL);
1243 /* Parses the packet type and calls what ever routines the packet type
1244 requires. This is done for all incoming packets. */
1246 void silc_server_packet_parse_type(SilcServer server,
1247 SilcSocketConnection sock,
1248 SilcPacketContext *packet)
1250 SilcBuffer buffer = packet->buffer;
1251 SilcPacketType type = packet->type;
1253 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1255 /* Parse the packet type */
1257 case SILC_PACKET_DISCONNECT:
1258 SILC_LOG_DEBUG(("Disconnect packet"));
1260 case SILC_PACKET_SUCCESS:
1262 * Success received for something. For now we can have only
1263 * one protocol for connection executing at once hence this
1264 * success message is for whatever protocol is executing currently.
1266 SILC_LOG_DEBUG(("Success packet"));
1267 if (sock->protocol) {
1268 sock->protocol->execute(server->timeout_queue, 0,
1269 sock->protocol, sock->sock, 0, 0);
1272 case SILC_PACKET_FAILURE:
1274 * Failure received for something. For now we can have only
1275 * one protocol for connection executing at once hence this
1276 * failure message is for whatever protocol is executing currently.
1278 SILC_LOG_DEBUG(("Failure packet"));
1279 if (sock->protocol) {
1280 /* XXX Audit the failure type */
1281 sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
1282 sock->protocol->execute(server->timeout_queue, 0,
1283 sock->protocol, sock->sock, 0, 0);
1286 case SILC_PACKET_REJECT:
1287 SILC_LOG_DEBUG(("Reject packet"));
1294 case SILC_PACKET_CHANNEL_MESSAGE:
1296 * Received channel message. Channel messages are special packets
1297 * (although probably most common ones) hence they are handled
1300 SILC_LOG_DEBUG(("Channel Message packet"));
1301 silc_server_channel_message(server, sock, packet);
1304 case SILC_PACKET_CHANNEL_KEY:
1306 * Received key for channel. As channels are created by the router
1307 * the keys are as well. We will distribute the key to all of our
1308 * locally connected clients on the particular channel. Router
1309 * never receives this channel and thus is ignored.
1311 SILC_LOG_DEBUG(("Channel Key packet"));
1312 silc_server_channel_key(server, sock, packet);
1318 case SILC_PACKET_COMMAND:
1320 * Recived command. Allocate command context and execute the command.
1322 SILC_LOG_DEBUG(("Command packet"));
1323 silc_server_command_process(server, sock, packet);
1326 case SILC_PACKET_COMMAND_REPLY:
1328 * Received command reply packet. Servers never send commands thus
1329 * they don't receive command reply packets either, except in cases
1330 * where server has forwarded command packet coming from client.
1331 * This must be the case here or we will ignore the packet.
1333 SILC_LOG_DEBUG(("Command Reply packet"));
1334 silc_server_packet_relay_command_reply(server, sock, packet);
1338 * Private Message packets
1340 case SILC_PACKET_PRIVATE_MESSAGE:
1342 * Received private message packet. The packet is coming from either
1345 SILC_LOG_DEBUG(("Private Message packet"));
1346 silc_server_private_message(server, sock, packet);
1349 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1353 * Key Exchange protocol packets
1355 case SILC_PACKET_KEY_EXCHANGE:
1356 SILC_LOG_DEBUG(("KE packet"));
1357 if (sock->protocol && sock->protocol->protocol->type
1358 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1360 SilcServerKEInternalContext *proto_ctx =
1361 (SilcServerKEInternalContext *)sock->protocol->context;
1363 proto_ctx->packet = buffer;
1365 /* Let the protocol handle the packet */
1366 sock->protocol->execute(server->timeout_queue, 0,
1367 sock->protocol, sock->sock, 0, 100000);
1369 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1370 "protocol active, packet dropped."));
1372 /* XXX Trigger KE protocol?? Rekey actually, maybe. */
1376 case SILC_PACKET_KEY_EXCHANGE_1:
1377 SILC_LOG_DEBUG(("KE 1 packet"));
1378 if (sock->protocol && sock->protocol->protocol->type
1379 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1381 SilcServerKEInternalContext *proto_ctx =
1382 (SilcServerKEInternalContext *)sock->protocol->context;
1384 if (proto_ctx->packet)
1385 silc_buffer_free(proto_ctx->packet);
1387 proto_ctx->packet = buffer;
1388 proto_ctx->dest_id_type = packet->src_id_type;
1389 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_type);
1391 /* Let the protocol handle the packet */
1392 sock->protocol->execute(server->timeout_queue, 0,
1393 sock->protocol, sock->sock,
1396 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1397 "protocol active, packet dropped."));
1401 case SILC_PACKET_KEY_EXCHANGE_2:
1402 SILC_LOG_DEBUG(("KE 2 packet"));
1403 if (sock->protocol && sock->protocol->protocol->type
1404 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1406 SilcServerKEInternalContext *proto_ctx =
1407 (SilcServerKEInternalContext *)sock->protocol->context;
1409 if (proto_ctx->packet)
1410 silc_buffer_free(proto_ctx->packet);
1412 proto_ctx->packet = buffer;
1413 proto_ctx->dest_id_type = packet->src_id_type;
1414 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_type);
1416 /* Let the protocol handle the packet */
1417 sock->protocol->execute(server->timeout_queue, 0,
1418 sock->protocol, sock->sock,
1421 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1422 "protocol active, packet dropped."));
1426 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1427 /* If we receive this packet we will send to the other end information
1428 about our mandatory authentication method for the connection.
1429 This packet maybe received at any time. */
1432 * Connection Authentication protocol packets
1434 case SILC_PACKET_CONNECTION_AUTH:
1435 /* Start of the authentication protocol. We receive here the
1436 authentication data and will verify it. */
1437 SILC_LOG_DEBUG(("Connection auth packet"));
1438 if (sock->protocol && sock->protocol->protocol->type
1439 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1441 SilcServerConnAuthInternalContext *proto_ctx =
1442 (SilcServerConnAuthInternalContext *)sock->protocol->context;
1444 proto_ctx->packet = buffer;
1446 /* Let the protocol handle the packet */
1447 sock->protocol->execute(server->timeout_queue, 0,
1448 sock->protocol, sock->sock, 0, 0);
1450 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1451 "protocol active, packet dropped."));
1455 case SILC_PACKET_NEW_ID:
1457 * Received New ID packet. This includes some new ID that has been
1458 * created. It may be for client, server or channel. This is the way
1459 * to distribute information about new registered entities in the
1462 SILC_LOG_DEBUG(("New ID packet"));
1463 silc_server_new_id(server, sock, packet);
1466 case SILC_PACKET_NEW_CLIENT:
1468 * Received new client packet. This includes client information that
1469 * we will use to create initial client ID. After creating new
1470 * ID we will send it to the client.
1472 SILC_LOG_DEBUG(("New Client packet"));
1473 silc_server_new_client(server, sock, packet);
1476 case SILC_PACKET_NEW_SERVER:
1478 * Received new server packet. This includes Server ID and some other
1479 * information that we may save. This is received after server has
1482 SILC_LOG_DEBUG(("New Server packet"));
1483 silc_server_new_server(server, sock, packet);
1486 case SILC_PACKET_NEW_CHANNEL:
1489 case SILC_PACKET_NEW_CHANNEL_USER:
1492 case SILC_PACKET_NEW_CHANNEL_LIST:
1495 case SILC_PACKET_NEW_CHANNEL_USER_LIST:
1498 case SILC_PACKET_REPLACE_ID:
1500 * Received replace ID packet. This sends the old ID that is to be
1501 * replaced with the new one included into the packet. Client must not
1504 SILC_LOG_DEBUG(("Replace ID packet"));
1505 silc_server_replace_id(server, sock, packet);
1508 case SILC_PACKET_REMOVE_ID:
1511 case SILC_PACKET_REMOVE_CHANNEL_USER:
1513 * Received packet to remove user from a channel. Routers notify other
1514 * routers about a user leaving a channel.
1516 SILC_LOG_DEBUG(("Remove Channel User packet"));
1517 silc_server_remove_channel_user(server, sock, packet);
1521 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
1527 /* Assembles a new packet to be sent out to network. This doesn't actually
1528 send the packet but creates the packet and fills the outgoing data
1529 buffer and marks the packet ready to be sent to network. However, If
1530 argument force_send is TRUE the packet is sent immediately and not put
1531 to queue. Normal case is that the packet is not sent immediately. */
1533 void silc_server_packet_send(SilcServer server,
1534 SilcSocketConnection sock,
1535 SilcPacketType type,
1536 SilcPacketFlags flags,
1537 unsigned char *data,
1538 unsigned int data_len,
1541 void *dst_id = NULL;
1542 SilcIdType dst_id_type = SILC_ID_NONE;
1547 /* Get data used in the packet sending, keys and stuff */
1548 switch(sock->type) {
1549 case SILC_SOCKET_TYPE_CLIENT:
1550 dst_id = ((SilcClientEntry)sock->user_data)->id;
1551 dst_id_type = SILC_ID_CLIENT;
1553 case SILC_SOCKET_TYPE_SERVER:
1554 case SILC_SOCKET_TYPE_ROUTER:
1555 dst_id = ((SilcServerEntry)sock->user_data)->id;
1556 dst_id_type = SILC_ID_SERVER;
1562 silc_server_packet_send_dest(server, sock, type, flags, dst_id,
1563 dst_id_type, data, data_len, force_send);
1566 /* Assembles a new packet to be sent out to network. This doesn't actually
1567 send the packet but creates the packet and fills the outgoing data
1568 buffer and marks the packet ready to be sent to network. However, If
1569 argument force_send is TRUE the packet is sent immediately and not put
1570 to queue. Normal case is that the packet is not sent immediately.
1571 Destination information is sent as argument for this function. */
1573 void silc_server_packet_send_dest(SilcServer server,
1574 SilcSocketConnection sock,
1575 SilcPacketType type,
1576 SilcPacketFlags flags,
1578 SilcIdType dst_id_type,
1579 unsigned char *data,
1580 unsigned int data_len,
1583 SilcPacketContext packetdata;
1584 SilcIDListData idata;
1585 SilcCipher cipher = NULL;
1586 SilcHmac hmac = NULL;
1587 unsigned char *dst_id_data = NULL;
1588 unsigned int dst_id_len = 0;
1590 SILC_LOG_DEBUG(("Sending packet, type %d", type));
1592 /* Get data used in the packet sending, keys and stuff */
1593 idata = (SilcIDListData)sock->user_data;
1596 dst_id_data = silc_id_id2str(dst_id, dst_id_type);
1597 dst_id_len = silc_id_get_len(dst_id_type);
1600 /* Set the packet context pointers */
1601 packetdata.type = type;
1602 packetdata.flags = flags;
1603 packetdata.src_id = silc_id_id2str(server->id, server->id_type);
1604 packetdata.src_id_len = SILC_ID_SERVER_LEN;
1605 packetdata.src_id_type = server->id_type;
1606 packetdata.dst_id = dst_id_data;
1607 packetdata.dst_id_len = dst_id_len;
1608 packetdata.dst_id_type = dst_id_type;
1609 packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
1610 packetdata.src_id_len + dst_id_len;
1611 packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
1612 packetdata.rng = server->rng;
1614 /* Prepare outgoing data buffer for packet sending */
1615 silc_packet_send_prepare(sock,
1616 SILC_PACKET_HEADER_LEN +
1617 packetdata.src_id_len +
1618 packetdata.dst_id_len,
1622 SILC_LOG_DEBUG(("Putting data to outgoing buffer, len %d", data_len));
1624 packetdata.buffer = sock->outbuf;
1626 /* Put the data to the buffer */
1627 if (data && data_len)
1628 silc_buffer_put(sock->outbuf, data, data_len);
1630 /* Create the outgoing packet */
1631 silc_packet_assemble(&packetdata);
1634 cipher = idata->send_key;
1638 /* Encrypt the packet */
1639 silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
1641 SILC_LOG_HEXDUMP(("Outgoing packet, len %d", sock->outbuf->len),
1642 sock->outbuf->data, sock->outbuf->len);
1644 /* Now actually send the packet */
1645 silc_server_packet_send_real(server, sock, force_send);
1647 if (packetdata.src_id)
1648 silc_free(packetdata.src_id);
1649 if (packetdata.dst_id)
1650 silc_free(packetdata.dst_id);
1653 /* Forwards packet. Packets sent with this function will be marked as
1654 forwarded (in the SILC header flags) so that the receiver knows that
1655 we have forwarded the packet to it. Forwarded packets are handled
1656 specially by the receiver as they are not destined to the receiver
1657 originally. However, the receiver knows this because the forwarded
1658 flag has been set (and the flag is authenticated). */
1660 void silc_server_packet_forward(SilcServer server,
1661 SilcSocketConnection sock,
1662 unsigned char *data, unsigned int data_len,
1665 SilcIDListData idata;
1666 SilcCipher cipher = NULL;
1667 SilcHmac hmac = NULL;
1669 SILC_LOG_DEBUG(("Forwarding packet"));
1671 /* Get data used in the packet sending, keys and stuff */
1672 idata = (SilcIDListData)sock->user_data;
1674 /* Prepare outgoing data buffer for packet sending */
1675 silc_packet_send_prepare(sock, 0, 0, data_len);
1677 /* Mungle the packet flags and add the FORWARDED flag */
1679 data[2] |= (unsigned char)SILC_PACKET_FLAG_FORWARDED;
1681 /* Put the data to the buffer */
1682 if (data && data_len)
1683 silc_buffer_put(sock->outbuf, data, data_len);
1686 cipher = idata->send_key;
1690 /* Encrypt the packet */
1691 silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
1693 SILC_LOG_HEXDUMP(("Forwarded packet, len %d", sock->outbuf->len),
1694 sock->outbuf->data, sock->outbuf->len);
1696 /* Now actually send the packet */
1697 silc_server_packet_send_real(server, sock, force_send);
1700 /* Broadcast received packet to our primary route. This function is used
1701 by router to further route received broadcast packet. It is expected
1702 that the broadcast flag from the packet is checked before calling this
1703 function. This does not check for the broadcast flag. The `sock' must
1704 be the socket of the primary route. */
1706 void silc_server_packet_broadcast(SilcServer server,
1707 SilcSocketConnection sock,
1708 SilcPacketContext *packet)
1710 SilcBuffer buffer = packet->buffer;
1711 SilcIDListData idata;
1714 SILC_LOG_DEBUG(("Broadcasting received broadcast packet"));
1716 /* If the packet is originated from our primary route we are
1717 not allowed to send the packet. */
1718 id = silc_id_str2id(packet->src_id, packet->src_id_type);
1719 if (id && SILC_ID_SERVER_COMPARE(id, server->id_entry->router->id)) {
1720 idata = (SilcIDListData)sock->user_data;
1721 silc_packet_send_prepare(sock, 0, 0, buffer->len);
1722 silc_buffer_put(sock->outbuf, buffer->data, buffer->len);
1723 silc_packet_encrypt(idata->send_key, idata->hmac,
1724 sock->outbuf, sock->outbuf->len);
1726 SILC_LOG_HEXDUMP(("Broadcasted packet, len %d", sock->outbuf->len),
1727 sock->outbuf->data, sock->outbuf->len);
1729 /* Now actually send the packet */
1730 silc_server_packet_send_real(server, sock, TRUE);
1735 SILC_LOG_DEBUG(("Will not broadcast to primary route since it is the "
1736 "original sender of this packet"));
1740 /* Internal routine to actually create the channel packet and send it
1741 to network. This is common function in channel message sending. If
1742 `channel_message' is TRUE this encrypts the message as it is strictly
1743 a channel message. If FALSE normal encryption process is used. */
1746 silc_server_packet_send_to_channel_real(SilcServer server,
1747 SilcSocketConnection sock,
1748 SilcPacketContext *packet,
1751 unsigned char *data,
1752 unsigned int data_len,
1753 int channel_message,
1756 packet->truelen = data_len + SILC_PACKET_HEADER_LEN +
1757 packet->src_id_len + packet->dst_id_len;
1759 /* Prepare outgoing data buffer for packet sending */
1760 silc_packet_send_prepare(sock,
1761 SILC_PACKET_HEADER_LEN +
1762 packet->src_id_len +
1767 packet->buffer = sock->outbuf;
1769 /* Put the data to buffer, assemble and encrypt the packet. The packet
1770 is encrypted with normal session key shared with the client. */
1771 silc_buffer_put(sock->outbuf, data, data_len);
1772 silc_packet_assemble(packet);
1773 if (channel_message)
1774 silc_packet_encrypt(cipher, hmac, sock->outbuf, SILC_PACKET_HEADER_LEN +
1775 packet->src_id_len + packet->dst_id_len +
1778 silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
1780 SILC_LOG_HEXDUMP(("Channel packet, len %d", sock->outbuf->len),
1781 sock->outbuf->data, sock->outbuf->len);
1783 /* Now actually send the packet */
1784 silc_server_packet_send_real(server, sock, force_send);
1787 /* This routine is used by the server to send packets to channel. The
1788 packet sent with this function is distributed to all clients on
1789 the channel. Usually this is used to send notify messages to the
1790 channel, things like notify about new user joining to the channel. */
1792 void silc_server_packet_send_to_channel(SilcServer server,
1793 SilcChannelEntry channel,
1794 SilcPacketType type,
1795 unsigned char *data,
1796 unsigned int data_len,
1799 SilcSocketConnection sock = NULL;
1800 SilcPacketContext packetdata;
1801 SilcClientEntry client = NULL;
1802 SilcServerEntry *routed = NULL;
1803 SilcChannelClientEntry chl;
1804 SilcIDListData idata;
1805 unsigned int routed_count = 0;
1807 /* This doesn't send channel message packets */
1808 if (type == SILC_PACKET_CHANNEL_MESSAGE)
1811 SILC_LOG_DEBUG(("Sending packet to channel"));
1813 /* Set the packet context pointers. */
1814 packetdata.flags = 0;
1815 packetdata.type = type;
1816 packetdata.src_id = silc_id_id2str(server->id, SILC_ID_SERVER);
1817 packetdata.src_id_len = SILC_ID_SERVER_LEN;
1818 packetdata.src_id_type = SILC_ID_SERVER;
1819 packetdata.dst_id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
1820 packetdata.dst_id_len = SILC_ID_CHANNEL_LEN;
1821 packetdata.dst_id_type = SILC_ID_CHANNEL;
1822 packetdata.rng = server->rng;
1823 packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
1824 packetdata.src_id_len + packetdata.dst_id_len;
1825 packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
1827 /* If there are global users in the channel we will send the message
1828 first to our router for further routing. */
1829 if (server->server_type == SILC_SERVER && !server->standalone &&
1830 channel->global_users) {
1831 SilcServerEntry router;
1833 /* Get data used in packet header encryption, keys and stuff. */
1834 router = server->id_entry->router;
1835 sock = (SilcSocketConnection)router->connection;
1836 idata = (SilcIDListData)router;
1838 SILC_LOG_DEBUG(("Sending channel message to router for routing"));
1840 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1841 idata->send_key, idata->hmac,
1842 data, data_len, FALSE, force_send);
1845 /* Send the message to clients on the channel's client list. */
1846 silc_list_start(channel->user_list);
1847 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
1848 client = chl->client;
1850 /* If client has router set it is not locally connected client and
1851 we will route the message to the router set in the client. */
1852 if (client && client->router && server->server_type == SILC_ROUTER) {
1855 /* Check if we have sent the packet to this route already */
1856 for (k = 0; k < routed_count; k++)
1857 if (routed[k] == client->router)
1859 if (k < routed_count)
1862 /* Get data used in packet header encryption, keys and stuff. */
1863 sock = (SilcSocketConnection)client->router->connection;
1864 idata = (SilcIDListData)client->router;
1866 /* Send the packet */
1867 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1868 idata->send_key, idata->hmac,
1869 data, data_len, FALSE,
1872 /* We want to make sure that the packet is routed to same router
1873 only once. Mark this route as sent route. */
1875 routed = silc_realloc(routed, sizeof(*routed) * (k + 1));
1876 routed[k] = client->router;
1882 /* Send to locally connected client */
1885 /* Get data used in packet header encryption, keys and stuff. */
1886 sock = (SilcSocketConnection)client->connection;
1887 idata = (SilcIDListData)client;
1889 /* Send the packet */
1890 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1891 idata->send_key, idata->hmac,
1892 data, data_len, FALSE,
1899 silc_free(packetdata.src_id);
1900 silc_free(packetdata.dst_id);
1903 /* This routine is explicitly used to relay messages to some channel.
1904 Packets sent with this function we have received earlier and are
1905 totally encrypted. This just sends the packet to all clients on
1906 the channel. If the sender of the packet is someone on the channel
1907 the message will not be sent to that client. The SILC Packet header
1908 is encrypted with the session key shared between us and the client.
1909 MAC is also computed before encrypting the header. Rest of the
1910 packet will be untouched. */
1912 void silc_server_packet_relay_to_channel(SilcServer server,
1913 SilcSocketConnection sender_sock,
1914 SilcChannelEntry channel,
1916 SilcIdType sender_type,
1917 unsigned char *data,
1918 unsigned int data_len,
1922 SilcSocketConnection sock = NULL;
1923 SilcPacketContext packetdata;
1924 SilcClientEntry client = NULL;
1925 SilcServerEntry *routed = NULL;
1926 SilcChannelClientEntry chl;
1927 unsigned int routed_count = 0;
1928 SilcIDListData idata;
1930 SILC_LOG_DEBUG(("Relaying packet to channel"));
1932 /* Set the packet context pointers. */
1933 packetdata.flags = 0;
1934 packetdata.type = SILC_PACKET_CHANNEL_MESSAGE;
1935 packetdata.src_id = silc_id_id2str(sender, sender_type);
1936 packetdata.src_id_len = silc_id_get_len(sender_type);
1937 packetdata.src_id_type = sender_type;
1938 packetdata.dst_id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
1939 packetdata.dst_id_len = SILC_ID_CHANNEL_LEN;
1940 packetdata.dst_id_type = SILC_ID_CHANNEL;
1941 packetdata.rng = server->rng;
1942 packetdata.padlen = SILC_PACKET_PADLEN((SILC_PACKET_HEADER_LEN +
1943 packetdata.src_id_len +
1944 packetdata.dst_id_len));
1946 /* If there are global users in the channel we will send the message
1947 first to our router for further routing. */
1948 if (server->server_type == SILC_SERVER && !server->standalone &&
1949 channel->global_users) {
1950 SilcServerEntry router;
1952 router = server->id_entry->router;
1954 /* Check that the sender is not our router. */
1955 if (sender_sock != (SilcSocketConnection)router->connection) {
1957 /* Get data used in packet header encryption, keys and stuff. */
1958 sock = (SilcSocketConnection)router->connection;
1959 idata = (SilcIDListData)router;
1961 SILC_LOG_DEBUG(("Sending channel message to router for routing"));
1963 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1964 idata->send_key, idata->hmac,
1965 data, data_len, TRUE,
1970 /* Send the message to clients on the channel's client list. */
1971 silc_list_start(channel->user_list);
1972 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
1973 client = chl->client;
1977 /* If sender is one on the channel do not send it the packet. */
1978 if (!found && !SILC_ID_CLIENT_COMPARE(client->id, sender)) {
1983 /* If the client has set router it means that it is not locally
1984 connected client and we will route the packet further. */
1985 if (server->server_type == SILC_ROUTER && client->router) {
1988 /* Sender maybe server as well so we want to make sure that
1989 we won't send the message to the server it came from. */
1990 if (!found && !SILC_ID_SERVER_COMPARE(client->router->id, sender)) {
1995 /* Check if we have sent the packet to this route already */
1996 for (k = 0; k < routed_count; k++)
1997 if (routed[k] == client->router)
1999 if (k < routed_count)
2002 /* Get data used in packet header encryption, keys and stuff. */
2003 sock = (SilcSocketConnection)client->router->connection;
2004 idata = (SilcIDListData)client->router;
2006 /* Send the packet */
2007 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
2008 idata->send_key, idata->hmac,
2009 data, data_len, TRUE,
2012 /* We want to make sure that the packet is routed to same router
2013 only once. Mark this route as sent route. */
2015 routed = silc_realloc(routed, sizeof(*routed) * (k + 1));
2016 routed[k] = client->router;
2022 /* XXX Check client's mode on the channel. */
2024 /* Get data used in packet header encryption, keys and stuff. */
2025 sock = (SilcSocketConnection)client->connection;
2026 idata = (SilcIDListData)client;
2028 SILC_LOG_DEBUG(("Sending packet to client %s",
2029 sock->hostname ? sock->hostname : sock->ip));
2031 /* Send the packet */
2032 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
2033 idata->send_key, idata->hmac,
2034 data, data_len, TRUE,
2039 silc_free(packetdata.src_id);
2040 silc_free(packetdata.dst_id);
2043 /* This function is used to send packets strictly to all local clients
2044 on a particular channel. This is used for example to distribute new
2045 channel key to all our locally connected clients on the channel.
2046 The packets are always encrypted with the session key shared between
2047 the client, this means these are not _to the channel_ but _to the client_
2050 void silc_server_packet_send_local_channel(SilcServer server,
2051 SilcChannelEntry channel,
2052 SilcPacketType type,
2053 SilcPacketFlags flags,
2054 unsigned char *data,
2055 unsigned int data_len,
2058 SilcClientEntry client;
2059 SilcChannelClientEntry chl;
2060 SilcSocketConnection sock = NULL;
2062 SILC_LOG_DEBUG(("Start"));
2064 /* Send the message to clients on the channel's client list. */
2065 silc_list_start(channel->user_list);
2066 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2067 client = chl->client;
2070 sock = (SilcSocketConnection)client->connection;
2072 /* Send the packet to the client */
2073 silc_server_packet_send_dest(server, sock, type, flags, client->id,
2074 SILC_ID_CLIENT, data, data_len,
2080 /* Relays received command reply packet to the correct destination. The
2081 destination must be one of our locally connected client or the packet
2082 will be ignored. This is called when server has forwarded one of
2083 client's command request to router and router has now replied to the
2086 void silc_server_packet_relay_command_reply(SilcServer server,
2087 SilcSocketConnection sock,
2088 SilcPacketContext *packet)
2090 SilcBuffer buffer = packet->buffer;
2091 SilcClientEntry client;
2093 SilcSocketConnection dst_sock;
2094 SilcIDListData idata;
2096 SILC_LOG_DEBUG(("Start"));
2098 /* Source must be server or router */
2099 if (packet->src_id_type != SILC_ID_SERVER &&
2100 sock->type != SILC_SOCKET_TYPE_ROUTER)
2103 /* Destination must be client */
2104 if (packet->dst_id_type != SILC_ID_CLIENT)
2107 /* Execute command reply locally for the command */
2108 silc_server_command_reply_process(server, sock, buffer);
2110 id = silc_id_str2id(packet->dst_id, SILC_ID_CLIENT);
2112 /* Destination must be one of ours */
2113 client = silc_idlist_find_client_by_id(server->local_list, id);
2119 /* Relay the packet to the client */
2121 dst_sock = (SilcSocketConnection)client->connection;
2122 silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len
2123 + packet->dst_id_len + packet->padlen);
2125 silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
2126 silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
2128 idata = (SilcIDListData)client;
2130 /* Encrypt packet */
2131 silc_packet_encrypt(idata->send_key, idata->hmac, dst_sock->outbuf,
2134 /* Send the packet */
2135 silc_server_packet_send_real(server, dst_sock, FALSE);
2140 silc_buffer_free(buffer);
2143 /* Closes connection to socket connection */
2145 void silc_server_close_connection(SilcServer server,
2146 SilcSocketConnection sock)
2149 SILC_LOG_DEBUG(("Closing connection %d", sock->sock));
2151 /* We won't listen for this connection anymore */
2152 silc_schedule_unset_listen_fd(sock->sock);
2154 /* Unregister all tasks */
2155 silc_task_unregister_by_fd(server->io_queue, sock->sock);
2156 silc_task_unregister_by_fd(server->timeout_queue, sock->sock);
2158 /* Close the actual connection */
2159 silc_net_close_connection(sock->sock);
2160 server->sockets[sock->sock] = NULL;
2161 silc_socket_free(sock);
2164 /* Sends disconnect message to remote connection and disconnects the
2167 void silc_server_disconnect_remote(SilcServer server,
2168 SilcSocketConnection sock,
2169 const char *fmt, ...)
2172 unsigned char buf[4096];
2174 memset(buf, 0, sizeof(buf));
2176 vsprintf(buf, fmt, ap);
2179 SILC_LOG_DEBUG(("Disconnecting remote host"));
2181 /* Notify remote end that the conversation is over. The notify message
2182 is tried to be sent immediately. */
2183 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2184 buf, strlen(buf), TRUE);
2186 /* Mark the connection to be disconnected */
2187 SILC_SET_DISCONNECTED(sock);
2188 silc_server_close_connection(server, sock);
2191 /* Free's user_data pointer from socket connection object. As this
2192 pointer maybe anything we wil switch here to find the correct
2193 data type and free it the way it needs to be free'd. */
2195 void silc_server_free_sock_user_data(SilcServer server,
2196 SilcSocketConnection sock)
2198 SILC_LOG_DEBUG(("Start"));
2200 switch(sock->type) {
2201 case SILC_SOCKET_TYPE_CLIENT:
2203 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2205 /* Remove client from all channels */
2206 silc_server_remove_from_channels(server, sock, user_data);
2208 /* XXX must take some info to history before freeing */
2210 /* Free the client entry and everything in it */
2211 silc_idlist_del_data(user_data);
2212 silc_idlist_del_client(server->local_list, user_data);
2215 case SILC_SOCKET_TYPE_SERVER:
2216 case SILC_SOCKET_TYPE_ROUTER:
2224 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2226 silc_idlist_del_data(user_data);
2227 silc_free(user_data);
2232 sock->user_data = NULL;
2235 /* Removes client from all channels it has joined. This is used when
2236 client connection is disconnected. If the client on a channel
2237 is last, the channel is removed as well. */
2239 void silc_server_remove_from_channels(SilcServer server,
2240 SilcSocketConnection sock,
2241 SilcClientEntry client)
2243 SilcChannelEntry channel;
2244 SilcChannelClientEntry chl;
2245 SilcBuffer chidp, clidp;
2247 SILC_LOG_DEBUG(("Start"));
2249 if (!client || !client->id)
2252 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2254 /* Remove the client from all channels. The client is removed from
2255 the channels' user list. */
2256 silc_list_start(client->channels);
2257 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2258 channel = chl->channel;
2259 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
2261 /* Remove from list */
2262 silc_list_del(client->channels, chl);
2264 /* If this client is last one on the channel the channel
2265 is removed all together. */
2266 if (silc_list_count(channel->user_list) < 2) {
2268 /* However, if the channel has marked global users then the
2269 channel is not created locally, and this does not remove the
2270 channel globally from SILC network, in this case we will
2271 notify that this client has left the channel. */
2272 if (channel->global_users)
2273 silc_server_send_notify_to_channel(server, channel,
2274 SILC_NOTIFY_TYPE_SIGNOFF, 1,
2275 clidp->data, clidp->len);
2277 silc_idlist_del_channel(server->local_list, channel);
2281 /* Remove from list */
2282 silc_list_del(channel->user_list, chl);
2285 /* Send notify to channel about client leaving SILC and thus
2286 the entire channel. */
2287 silc_server_send_notify_to_channel(server, channel,
2288 SILC_NOTIFY_TYPE_SIGNOFF, 1,
2289 clidp->data, clidp->len);
2290 silc_buffer_free(chidp);
2293 silc_buffer_free(clidp);
2296 /* Removes client from one channel. This is used for example when client
2297 calls LEAVE command to remove itself from the channel. Returns TRUE
2298 if channel still exists and FALSE if the channel is removed when
2299 last client leaves the channel. If `notify' is FALSE notify messages
2302 int silc_server_remove_from_one_channel(SilcServer server,
2303 SilcSocketConnection sock,
2304 SilcChannelEntry channel,
2305 SilcClientEntry client,
2308 SilcChannelEntry ch;
2309 SilcChannelClientEntry chl;
2312 SILC_LOG_DEBUG(("Start"));
2314 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2316 /* Remove the client from the channel. The client is removed from
2317 the channel's user list. */
2318 silc_list_start(client->channels);
2319 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2320 if (chl->channel != channel)
2325 /* Remove from list */
2326 silc_list_del(client->channels, chl);
2328 /* If this client is last one on the channel the channel
2329 is removed all together. */
2330 if (silc_list_count(channel->user_list) < 2) {
2331 /* Notify about leaving client if this channel has global users,
2332 ie. the channel is not created locally. */
2333 if (notify && channel->global_users)
2334 silc_server_send_notify_to_channel(server, channel,
2335 SILC_NOTIFY_TYPE_LEAVE, 1,
2336 clidp->data, clidp->len);
2338 silc_idlist_del_channel(server->local_list, channel);
2339 silc_buffer_free(clidp);
2343 /* Remove from list */
2344 silc_list_del(channel->user_list, chl);
2347 /* Send notify to channel about client leaving the channel */
2349 silc_server_send_notify_to_channel(server, channel,
2350 SILC_NOTIFY_TYPE_LEAVE, 1,
2351 clidp->data, clidp->len);
2355 silc_buffer_free(clidp);
2359 /* Returns TRUE if the given client is on the channel. FALSE if not.
2360 This works because we assure that the user list on the channel is
2361 always in up to date thus we can only check the channel list from
2362 `client' which is faster than checking the user list from `channel'. */
2364 int silc_server_client_on_channel(SilcClientEntry client,
2365 SilcChannelEntry channel)
2367 SilcChannelClientEntry chl;
2369 if (!client || !channel)
2372 silc_list_start(client->channels);
2373 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END)
2374 if (chl->channel == channel)
2380 /* Timeout callback. This is called if connection is idle or for some
2381 other reason is not responding within some period of time. This
2382 disconnects the remote end. */
2384 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2386 SilcServerConnection sconn = (SilcServerConnection)context;
2387 SilcSocketConnection sock = sconn->server->sockets[fd];
2389 silc_server_disconnect_remote(sconn->server, sock,
2390 "Server closed connection: "
2391 "Connection timeout");
2394 /* Internal routine used to send (relay, route) private messages to some
2395 destination. If the private message key does not exist then the message
2396 is re-encrypted, otherwise we just pass it along. */
2399 silc_server_private_message_send_internal(SilcServer server,
2400 SilcSocketConnection dst_sock,
2403 SilcPacketContext *packet)
2405 SilcBuffer buffer = packet->buffer;
2407 /* Send and re-encrypt if private messge key does not exist */
2408 if ((packet->flags & SILC_PACKET_FLAG_PRIVMSG_KEY) == FALSE) {
2410 silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len
2411 + packet->dst_id_len + packet->padlen);
2412 silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
2413 silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
2415 /* Re-encrypt packet */
2416 silc_packet_encrypt(cipher, hmac, dst_sock->outbuf, buffer->len);
2418 /* Send the packet */
2419 silc_server_packet_send_real(server, dst_sock, FALSE);
2422 /* Key exist so just send it */
2423 silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len
2424 + packet->dst_id_len + packet->padlen);
2425 silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
2426 silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
2427 silc_server_packet_send_real(server, dst_sock, FALSE);
2431 /* Received private message. This resolves the destination of the message
2432 and sends the packet. This is used by both server and router. If the
2433 destination is our locally connected client this sends the packet to
2434 the client. This may also send the message for further routing if
2435 the destination is not in our server (or router). */
2437 void silc_server_private_message(SilcServer server,
2438 SilcSocketConnection sock,
2439 SilcPacketContext *packet)
2441 SilcBuffer buffer = packet->buffer;
2443 SilcServerEntry router;
2444 SilcSocketConnection dst_sock;
2445 SilcClientEntry client;
2446 SilcIDListData idata;
2448 SILC_LOG_DEBUG(("Start"));
2450 if (!packet->dst_id) {
2451 SILC_LOG_ERROR(("Bad Client ID in private message packet, dropped"));
2455 /* Decode destination Client ID */
2456 id = silc_id_str2id(packet->dst_id, SILC_ID_CLIENT);
2458 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
2462 /* If the destination belongs to our server we don't have to route
2463 the message anywhere but to send it to the local destination. */
2464 client = silc_idlist_find_client_by_id(server->local_list, id);
2466 /* It exists, now deliver the message to the destination */
2467 dst_sock = (SilcSocketConnection)client->connection;
2469 /* If we are router and the client has router then the client is in
2470 our cell but not directly connected to us. */
2471 if (server->server_type == SILC_ROUTER && client->router) {
2472 /* We are of course in this case the client's router thus the real
2473 "router" of the client is the server who owns the client. Thus
2474 we will send the packet to that server. */
2475 router = (SilcServerEntry)dst_sock->user_data;
2476 idata = (SilcIDListData)router;
2477 // assert(client->router == server->id_entry);
2479 silc_server_private_message_send_internal(server, dst_sock,
2486 /* Seems that client really is directly connected to us */
2487 idata = (SilcIDListData)client;
2488 silc_server_private_message_send_internal(server, dst_sock,
2490 idata->hmac, packet);
2494 /* Destination belongs to someone not in this server. If we are normal
2495 server our action is to send the packet to our router. */
2496 if (server->server_type == SILC_SERVER && !server->standalone) {
2497 router = server->id_entry->router;
2499 /* Send to primary route */
2501 dst_sock = (SilcSocketConnection)router->connection;
2502 idata = (SilcIDListData)router;
2503 silc_server_private_message_send_internal(server, dst_sock,
2505 idata->hmac, packet);
2510 /* We are router and we will perform route lookup for the destination
2511 and send the message to fastest route. */
2512 if (server->server_type == SILC_ROUTER && !server->standalone) {
2513 dst_sock = silc_server_get_route(server, id, SILC_ID_CLIENT);
2514 router = (SilcServerEntry)dst_sock->user_data;
2515 idata = (SilcIDListData)router;
2517 /* Get fastest route and send packet. */
2519 silc_server_private_message_send_internal(server, dst_sock,
2521 idata->hmac, packet);
2527 silc_server_send_error(server, sock,
2528 "No such nickname: Private message not sent");
2530 silc_buffer_free(buffer);
2533 /* Process received channel message. The message can be originated from
2534 client or server. */
2536 void silc_server_channel_message(SilcServer server,
2537 SilcSocketConnection sock,
2538 SilcPacketContext *packet)
2540 SilcChannelEntry channel = NULL;
2541 SilcChannelClientEntry chl;
2542 SilcChannelID *id = NULL;
2543 void *sender = NULL;
2544 SilcBuffer buffer = packet->buffer;
2546 SILC_LOG_DEBUG(("Processing channel message"));
2549 if (packet->dst_id_type != SILC_ID_CHANNEL) {
2550 SILC_LOG_ERROR(("Received bad message for channel, dropped"));
2551 SILC_LOG_DEBUG(("Received bad message for channel, dropped"));
2555 /* Find channel entry */
2556 id = silc_id_str2id(packet->dst_id, SILC_ID_CHANNEL);
2557 channel = silc_idlist_find_channel_by_id(server->local_list, id);
2559 SILC_LOG_DEBUG(("Could not find channel"));
2563 /* See that this client is on the channel. If the message is coming
2564 from router we won't do the check as the message is from client that
2565 we don't know about. Also, if the original sender is not client
2566 (as it can be server as well) we don't do the check. */
2567 sender = silc_id_str2id(packet->src_id, packet->src_id_type);
2568 if (sock->type != SILC_SOCKET_TYPE_ROUTER &&
2569 packet->src_id_type == SILC_ID_CLIENT) {
2570 silc_list_start(channel->user_list);
2571 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2572 if (chl->client && !SILC_ID_CLIENT_COMPARE(chl->client->id, sender))
2575 if (chl == SILC_LIST_END)
2579 /* Distribute the packet to our local clients. This will send the
2580 packet for further routing as well, if needed. */
2581 silc_server_packet_relay_to_channel(server, sock, channel, sender,
2582 packet->src_id_type,
2583 packet->buffer->data,
2584 packet->buffer->len, FALSE);
2591 silc_buffer_free(buffer);
2594 /* Received channel key packet. We distribute the key to all of our locally
2595 connected clients on the channel. */
2596 /* XXX Router must accept this packet and distribute the key to all its
2597 server that has clients on the channel */
2599 void silc_server_channel_key(SilcServer server,
2600 SilcSocketConnection sock,
2601 SilcPacketContext *packet)
2603 SilcBuffer buffer = packet->buffer;
2604 SilcChannelKeyPayload payload = NULL;
2605 SilcChannelID *id = NULL;
2606 SilcChannelEntry channel;
2607 SilcChannelClientEntry chl;
2608 SilcClientEntry client;
2610 unsigned int tmp_len;
2613 if (packet->src_id_type != SILC_ID_SERVER &&
2614 sock->type != SILC_SOCKET_TYPE_ROUTER)
2617 /* Decode channel key payload */
2618 payload = silc_channel_key_payload_parse(buffer);
2620 SILC_LOG_ERROR(("Bad channel key payload, dropped"));
2624 /* Get channel ID */
2625 tmp = silc_channel_key_get_id(payload, &tmp_len);
2626 id = silc_id_payload_parse_id(tmp, tmp_len);
2630 /* Get the channel entry */
2631 channel = silc_idlist_find_channel_by_id(server->local_list, id);
2633 SILC_LOG_ERROR(("Received key for non-existent channel"));
2637 /* Save the key for us as well */
2638 tmp = silc_channel_key_get_key(payload, &tmp_len);
2641 cipher = silc_channel_key_get_cipher(payload, NULL);;
2644 if (!silc_cipher_alloc(cipher, &channel->channel_key))
2647 channel->key_len = tmp_len * 8;
2648 channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
2649 memcpy(channel->key, tmp, tmp_len);
2650 channel->channel_key->cipher->set_key(channel->channel_key->context,
2653 /* Distribute the key to all clients on the channel */
2654 /* XXX Some other sender should be used, I think this is not correct */
2655 silc_list_start(channel->user_list);
2656 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2657 client = chl->client;
2660 silc_server_packet_send_dest(server, client->connection,
2661 SILC_PACKET_CHANNEL_KEY, 0,
2662 client->id, SILC_ID_CLIENT,
2663 buffer->data, buffer->len, FALSE);
2670 silc_channel_key_payload_free(payload);
2671 silc_buffer_free(buffer);
2674 /* Sends current motd to client */
2676 void silc_server_send_motd(SilcServer server,
2677 SilcSocketConnection sock)
2682 if (server->config && server->config->motd &&
2683 server->config->motd->motd_file) {
2685 motd = silc_file_read(server->config->motd->motd_file, &motd_len);
2689 silc_server_send_notify(server, sock, SILC_NOTIFY_TYPE_MOTD, 1,
2695 /* Sends error message. Error messages may or may not have any
2698 void silc_server_send_error(SilcServer server,
2699 SilcSocketConnection sock,
2700 const char *fmt, ...)
2703 unsigned char buf[4096];
2705 memset(buf, 0, sizeof(buf));
2707 vsprintf(buf, fmt, ap);
2710 silc_server_packet_send(server, sock, SILC_PACKET_ERROR, 0,
2711 buf, strlen(buf), FALSE);
2714 /* Sends notify message. If format is TRUE the variable arguments are
2715 formatted and the formatted string is sent as argument payload. If it is
2716 FALSE then each argument is sent as separate argument and their format
2717 in the argument list must be { argument data, argument length }. */
2719 void silc_server_send_notify(SilcServer server,
2720 SilcSocketConnection sock,
2721 SilcNotifyType type,
2722 unsigned int argc, ...)
2729 packet = silc_notify_payload_encode(type, argc, ap);
2730 silc_server_packet_send(server, sock, SILC_PACKET_NOTIFY, 0,
2731 packet->data, packet->len, FALSE);
2732 silc_buffer_free(packet);
2735 /* Sends notify message destined to specific entity. */
2737 void silc_server_send_notify_dest(SilcServer server,
2738 SilcSocketConnection sock,
2740 SilcIdType dest_id_type,
2741 SilcNotifyType type,
2742 unsigned int argc, ...)
2749 packet = silc_notify_payload_encode(type, argc, ap);
2750 silc_server_packet_send_dest(server, sock, SILC_PACKET_NOTIFY, 0,
2751 dest_id, dest_id_type,
2752 packet->data, packet->len, FALSE);
2753 silc_buffer_free(packet);
2756 /* Sends notify message to a channel. The notify message sent is
2757 distributed to all clients on the channel. */
2759 void silc_server_send_notify_to_channel(SilcServer server,
2760 SilcChannelEntry channel,
2761 SilcNotifyType type,
2762 unsigned int argc, ...)
2769 packet = silc_notify_payload_encode(type, argc, ap);
2770 silc_server_packet_send_to_channel(server, channel,
2772 packet->data, packet->len, FALSE);
2773 silc_buffer_free(packet);
2776 /* Send notify message to all clients the client has joined. It is quaranteed
2777 that the message is sent only once to a client (ie. if a client is joined
2778 on two same channel it will receive only one notify message). Also, this
2779 sends only to local clients (locally connected if we are server, and to
2780 local servers if we are router). */
2782 void silc_server_send_notify_on_channels(SilcServer server,
2783 SilcClientEntry client,
2784 SilcNotifyType type,
2785 unsigned int argc, ...)
2788 SilcSocketConnection sock = NULL;
2789 SilcPacketContext packetdata;
2791 SilcClientEntry *sent_clients = NULL;
2792 unsigned int sent_clients_count = 0;
2793 SilcServerEntry *routed = NULL;
2794 unsigned int routed_count = 0;
2795 SilcChannelEntry channel;
2796 SilcChannelClientEntry chl, chl2;
2797 SilcIDListData idata;
2799 unsigned char *data;
2800 unsigned int data_len;
2801 int force_send = FALSE;
2804 if (!silc_list_count(client->channels))
2808 packet = silc_notify_payload_encode(type, argc, ap);
2809 data = packet->data;
2810 data_len = packet->len;
2812 /* Set the packet context pointers. */
2813 packetdata.flags = 0;
2814 packetdata.type = SILC_PACKET_NOTIFY;
2815 packetdata.src_id = silc_id_id2str(server->id, SILC_ID_SERVER);
2816 packetdata.src_id_len = SILC_ID_SERVER_LEN;
2817 packetdata.src_id_type = SILC_ID_SERVER;
2818 packetdata.rng = server->rng;
2820 silc_list_start(client->channels);
2821 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2822 channel = chl->channel;
2824 /* Send the message to all clients on the channel's client list. */
2825 silc_list_start(channel->user_list);
2826 while ((chl2 = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2829 /* Check if we have sent the packet to this client already */
2830 for (k = 0; k < sent_clients_count; k++)
2831 if (sent_clients[k] == c)
2833 if (k < sent_clients_count)
2836 /* If we are router and if this client has router set it is not
2837 locally connected client and we will route the message to the
2838 router set in the client. */
2839 if (c && c->router && server->server_type == SILC_ROUTER) {
2840 /* Check if we have sent the packet to this route already */
2841 for (k = 0; k < routed_count; k++)
2842 if (routed[k] == c->router)
2844 if (k < routed_count)
2847 /* Get data used in packet header encryption, keys and stuff. */
2848 sock = (SilcSocketConnection)c->router->connection;
2849 idata = (SilcIDListData)c->router;
2851 packetdata.dst_id = silc_id_id2str(c->router->id, SILC_ID_SERVER);
2852 packetdata.dst_id_len = SILC_ID_SERVER_LEN;
2853 packetdata.dst_id_type = SILC_ID_SERVER;
2854 packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
2855 packetdata.src_id_len + packetdata.dst_id_len;
2856 packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
2858 /* Send the packet */
2859 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
2860 idata->send_key, idata->hmac,
2861 data, data_len, FALSE,
2864 silc_free(packetdata.dst_id);
2866 /* We want to make sure that the packet is routed to same router
2867 only once. Mark this route as sent route. */
2869 routed = silc_realloc(routed, sizeof(*routed) * (k + 1));
2870 routed[k] = c->router;
2876 /* Send to locally connected client */
2879 /* Get data used in packet header encryption, keys and stuff. */
2880 sock = (SilcSocketConnection)c->connection;
2881 idata = (SilcIDListData)c;
2883 packetdata.dst_id = silc_id_id2str(c->id, SILC_ID_CLIENT);
2884 packetdata.dst_id_len = SILC_ID_CLIENT_LEN;
2885 packetdata.dst_id_type = SILC_ID_CLIENT;
2886 packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
2887 packetdata.src_id_len + packetdata.dst_id_len;
2888 packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
2890 /* Send the packet */
2891 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
2892 idata->send_key, idata->hmac,
2893 data, data_len, FALSE,
2896 silc_free(packetdata.dst_id);
2898 /* Make sure that we send the notify only once per client. */
2899 sent_clients = silc_realloc(sent_clients, sizeof(*sent_clients) *
2900 (sent_clients_count + 1));
2901 sent_clients[sent_clients_count] = c;
2902 sent_clients_count++;
2909 if (sent_clients_count)
2910 silc_free(sent_clients);
2911 silc_free(packetdata.src_id);
2914 /* Sends New ID Payload to remote end. The packet is used to distribute
2915 information about new registered clients, servers, channel etc. usually
2916 to routers so that they can keep these information up to date.
2917 If the argument `broadcast' is TRUE then the packet is sent as
2918 broadcast packet. */
2920 void silc_server_send_new_id(SilcServer server,
2921 SilcSocketConnection sock,
2923 void *id, SilcIdType id_type,
2924 unsigned int id_len)
2928 idp = silc_id_payload_encode(id, id_type);
2929 silc_server_packet_send(server, sock, SILC_PACKET_NEW_ID,
2930 broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
2931 idp->data, idp->len, FALSE);
2932 silc_buffer_free(idp);
2935 /* Sends Replace ID payload to remote end. This is used to replace old
2936 ID with new ID sent in the packet. This is called for example when
2937 user changes nickname and we create new ID for the user. If the
2938 argument `broadcast' is TRUE then the packet is sent as
2939 broadcast packet. */
2940 /* XXX It would be expected that the new id is same type as the old
2943 void silc_server_send_replace_id(SilcServer server,
2944 SilcSocketConnection sock,
2946 void *old_id, SilcIdType old_id_type,
2947 unsigned int old_id_len,
2948 void *new_id, SilcIdType new_id_type,
2949 unsigned int new_id_len)
2955 oid = silc_id_id2str(old_id, old_id_type);
2959 nid = silc_id_id2str(new_id, new_id_type);
2963 packet = silc_buffer_alloc(2 + 2 + 2 + 2 + old_id_len + new_id_len);
2964 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
2965 silc_buffer_format(packet,
2966 SILC_STR_UI_SHORT(old_id_type),
2967 SILC_STR_UI_SHORT(old_id_len),
2968 SILC_STR_UI_XNSTRING(oid, old_id_len),
2969 SILC_STR_UI_SHORT(new_id_type),
2970 SILC_STR_UI_SHORT(new_id_len),
2971 SILC_STR_UI_XNSTRING(nid, new_id_len),
2974 silc_server_packet_send(server, sock, SILC_PACKET_REPLACE_ID,
2975 broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
2976 packet->data, packet->len, FALSE);
2979 silc_buffer_free(packet);
2982 /* This function is used to send Remove Channel User payload. This may sent
2983 by server but is usually used only by router to notify other routers that
2984 user has left a channel. Normal server sends this packet to its router
2985 to notify that the router should not hold a record about this client
2986 on a channel anymore. Router distributes it further to other routers. */
2988 void silc_server_send_remove_channel_user(SilcServer server,
2989 SilcSocketConnection sock,
2991 void *client_id, void *channel_id)
2994 unsigned char *clid, *chid;
2996 clid = silc_id_id2str(client_id, SILC_ID_CLIENT);
3000 chid = silc_id_id2str(channel_id, SILC_ID_CHANNEL);
3004 packet = silc_buffer_alloc(2 + 2 + SILC_ID_CLIENT_LEN + SILC_ID_CHANNEL_LEN);
3005 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
3006 silc_buffer_format(packet,
3007 SILC_STR_UI_SHORT(SILC_ID_CLIENT_LEN),
3008 SILC_STR_UI_XNSTRING(clid, SILC_ID_CLIENT_LEN),
3009 SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
3010 SILC_STR_UI_XNSTRING(chid, SILC_ID_CHANNEL_LEN),
3013 silc_server_packet_send(server, sock, SILC_PACKET_REMOVE_CHANNEL_USER,
3014 broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
3015 packet->data, packet->len, FALSE);
3018 silc_buffer_free(packet);
3021 /* Received packet to replace a ID. This checks that the requested ID
3022 exists and replaces it with the new one. */
3024 void silc_server_replace_id(SilcServer server,
3025 SilcSocketConnection sock,
3026 SilcPacketContext *packet)
3028 SilcBuffer buffer = packet->buffer;
3029 unsigned char *old_id = NULL, *new_id = NULL;
3030 SilcIdType old_id_type, new_id_type;
3031 unsigned short old_id_len, new_id_len;
3032 void *id = NULL, *id2 = NULL;
3034 if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3035 packet->src_id_type == SILC_ID_CLIENT)
3038 SILC_LOG_DEBUG(("Replacing ID"));
3040 silc_buffer_unformat(buffer,
3041 SILC_STR_UI_SHORT(&old_id_type),
3042 SILC_STR_UI16_NSTRING_ALLOC(&old_id, &old_id_len),
3043 SILC_STR_UI_SHORT(&new_id_type),
3044 SILC_STR_UI16_NSTRING_ALLOC(&new_id, &new_id_len),
3047 if (old_id_type != new_id_type)
3050 if (old_id_len != silc_id_get_len(old_id_type) ||
3051 new_id_len != silc_id_get_len(new_id_type))
3054 id = silc_id_str2id(old_id, old_id_type);
3058 id2 = silc_id_str2id(new_id, new_id_type);
3062 /* Replace the old ID */
3063 switch(old_id_type) {
3064 case SILC_ID_CLIENT:
3065 if (silc_idlist_replace_client_id(server->local_list, id, id2) == NULL)
3066 if (server->server_type == SILC_ROUTER)
3067 silc_idlist_replace_client_id(server->global_list, id, id2);
3070 case SILC_ID_SERVER:
3071 if (silc_idlist_replace_server_id(server->local_list, id, id2) == NULL)
3072 if (server->server_type == SILC_ROUTER)
3073 silc_idlist_replace_server_id(server->global_list, id, id2);
3076 case SILC_ID_CHANNEL:
3077 /* XXX Hmm... Basically this cannot occur. Channel ID's cannot be
3096 /* Creates new channel. */
3098 SilcChannelEntry silc_server_new_channel(SilcServer server,
3099 SilcServerID *router_id,
3100 char *cipher, char *channel_name)
3102 int i, channel_len, key_len;
3103 SilcChannelID *channel_id;
3104 SilcChannelEntry entry;
3106 unsigned char channel_key[32], *id_string;
3109 SILC_LOG_DEBUG(("Creating new channel"));
3111 /* Create channel key */
3112 for (i = 0; i < 32; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3119 silc_cipher_alloc(cipher, &key);
3120 key->cipher->set_key(key->context, channel_key, key_len);
3122 channel_name = strdup(channel_name);
3124 /* Create the channel */
3125 silc_id_create_channel_id(router_id, server->rng, &channel_id);
3126 entry = silc_idlist_add_channel(server->local_list, channel_name,
3127 SILC_CHANNEL_MODE_NONE, channel_id,
3130 silc_free(channel_name);
3134 entry->key = silc_calloc(key_len, sizeof(*entry->key));
3135 entry->key_len = key_len * 8;
3136 memcpy(entry->key, channel_key, key_len);
3137 memset(channel_key, 0, sizeof(channel_key));
3139 /* Notify other routers about the new channel. We send the packet
3140 to our primary route. */
3141 if (server->standalone == FALSE) {
3142 channel_len = strlen(channel_name);
3143 id_string = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3144 packet = silc_buffer_alloc(2 + SILC_ID_CHANNEL_LEN);
3146 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
3147 silc_buffer_format(packet,
3148 SILC_STR_UI_SHORT(channel_len),
3149 SILC_STR_UI_XNSTRING(channel_name, channel_len),
3150 SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
3151 SILC_STR_UI_XNSTRING(id_string, SILC_ID_CHANNEL_LEN),
3154 /* Send the packet to our router. */
3155 silc_server_packet_send(server, (SilcSocketConnection)
3156 server->id_entry->router->connection,
3157 SILC_PACKET_NEW_CHANNEL_USER, 0,
3158 packet->data, packet->len, TRUE);
3160 silc_free(id_string);
3161 silc_buffer_free(packet);
3167 /* Create new client. This processes incoming NEW_CLIENT packet and creates
3168 Client ID for the client. Client becomes registered after calling this
3171 SilcClientEntry silc_server_new_client(SilcServer server,
3172 SilcSocketConnection sock,
3173 SilcPacketContext *packet)
3175 SilcBuffer buffer = packet->buffer;
3176 SilcClientEntry client;
3177 SilcIDCacheEntry cache;
3178 SilcClientID *client_id;
3180 SilcIDListData idata;
3181 char *username = NULL, *realname = NULL, *id_string;
3183 SILC_LOG_DEBUG(("Creating new client"));
3185 if (sock->type != SILC_SOCKET_TYPE_CLIENT)
3188 /* Take client entry */
3189 client = (SilcClientEntry)sock->user_data;
3190 idata = (SilcIDListData)client;
3192 /* Fetch the old client cache entry so that we can update it. */
3193 if (!silc_idcache_find_by_context(server->local_list->clients,
3194 sock->user_data, &cache)) {
3195 SILC_LOG_ERROR(("Lost client's cache entry - bad thing"));
3199 /* Parse incoming packet */
3200 silc_buffer_unformat(buffer,
3201 SILC_STR_UI16_STRING_ALLOC(&username),
3202 SILC_STR_UI16_STRING_ALLOC(&realname),
3205 /* Create Client ID */
3206 silc_id_create_client_id(server->id, server->rng, server->md5hash,
3207 username, &client_id);
3209 /* Update client entry */
3210 idata->registered = TRUE;
3211 client->nickname = strdup(username);
3212 client->username = username;
3213 client->userinfo = realname;
3214 client->id = client_id;
3216 /* Update the cache entry */
3217 cache->id = (void *)client_id;
3218 cache->type = SILC_ID_CLIENT;
3219 cache->data = username;
3220 silc_idcache_sort_by_data(server->local_list->clients);
3222 /* Notify our router about new client on the SILC network */
3223 if (!server->standalone)
3224 silc_server_send_new_id(server, (SilcSocketConnection)
3225 server->id_entry->router->connection,
3226 server->server_type == SILC_ROUTER ? TRUE : FALSE,
3227 client->id, SILC_ID_CLIENT, SILC_ID_CLIENT_LEN);
3229 /* Send the new client ID to the client. */
3230 id_string = silc_id_id2str(client->id, SILC_ID_CLIENT);
3231 reply = silc_buffer_alloc(2 + 2 + SILC_ID_CLIENT_LEN);
3232 silc_buffer_pull_tail(reply, SILC_BUFFER_END(reply));
3233 silc_buffer_format(reply,
3234 SILC_STR_UI_SHORT(SILC_ID_CLIENT),
3235 SILC_STR_UI_SHORT(SILC_ID_CLIENT_LEN),
3236 SILC_STR_UI_XNSTRING(id_string, SILC_ID_CLIENT_LEN),
3238 silc_server_packet_send(server, sock, SILC_PACKET_NEW_ID, 0,
3239 reply->data, reply->len, FALSE);
3240 silc_free(id_string);
3241 silc_buffer_free(reply);
3243 /* Send some nice info to the client */
3244 SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3245 ("Welcome to the SILC Network %s@%s",
3246 username, sock->hostname));
3247 SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3248 ("Your host is %s, running version %s",
3249 server->config->server_info->server_name,
3251 SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3252 ("Your connection is secured with %s cipher, "
3253 "key length %d bits",
3254 idata->send_key->cipher->name,
3255 idata->send_key->cipher->key_len));
3256 SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3257 ("Your current nickname is %s",
3261 silc_server_send_motd(server, sock);
3266 /* Create new server. This processes incoming NEW_SERVER packet and
3267 saves the received Server ID. The server is our locally connected
3268 server thus we save all the information and save it to local list.
3269 This funtion can be used by both normal server and router server.
3270 If normal server uses this it means that its router has connected
3271 to the server. If router uses this it means that one of the cell's
3272 servers is connected to the router. */
3274 SilcServerEntry silc_server_new_server(SilcServer server,
3275 SilcSocketConnection sock,
3276 SilcPacketContext *packet)
3278 SilcBuffer buffer = packet->buffer;
3279 SilcServerEntry new_server;
3280 SilcIDCacheEntry cache;
3281 SilcServerID *server_id;
3282 SilcIDListData idata;
3283 unsigned char *server_name, *id_string;
3284 unsigned short id_len;
3286 SILC_LOG_DEBUG(("Creating new server"));
3288 if (sock->type != SILC_SOCKET_TYPE_SERVER &&
3289 sock->type != SILC_SOCKET_TYPE_ROUTER)
3292 /* Take server entry */
3293 new_server = (SilcServerEntry)sock->user_data;
3294 idata = (SilcIDListData)new_server;
3296 /* Fetch the old server cache entry so that we can update it. */
3297 if (!silc_idcache_find_by_context(server->local_list->servers,
3298 sock->user_data, &cache)) {
3299 SILC_LOG_ERROR(("Lost server's cache entry - bad thing"));
3303 /* Parse the incoming packet */
3304 silc_buffer_unformat(buffer,
3305 SILC_STR_UI16_NSTRING_ALLOC(&id_string, &id_len),
3306 SILC_STR_UI16_STRING_ALLOC(&server_name),
3309 if (id_len > buffer->len) {
3310 silc_free(id_string);
3311 silc_free(server_name);
3316 server_id = silc_id_str2id(id_string, SILC_ID_SERVER);
3317 silc_free(id_string);
3319 /* Update client entry */
3320 idata->registered = TRUE;
3321 new_server->server_name = server_name;
3322 new_server->id = server_id;
3324 /* Update the cache entry */
3325 cache->id = (void *)server_id;
3326 cache->type = SILC_ID_SERVER;
3327 cache->data = server_name;
3328 silc_idcache_sort_by_data(server->local_list->servers);
3330 /* Distribute the information about new server in the SILC network
3331 to our router. If we are normal server we won't send anything
3332 since this connection must be our router connection. */
3333 if (server->server_type == SILC_ROUTER && !server->standalone &&
3334 server->id_entry->router->connection != sock)
3335 silc_server_send_new_id(server, server->id_entry->router->connection,
3336 TRUE, new_server->id, SILC_ID_SERVER,
3337 SILC_ID_SERVER_LEN);
3342 /* Processes incoming New ID Payload. New ID Payload is used to distribute
3343 information about newly registered clients, servers and created
3346 void silc_server_new_id(SilcServer server, SilcSocketConnection sock,
3347 SilcPacketContext *packet)
3349 SilcBuffer buffer = packet->buffer;
3351 SilcServerEntry tmpserver, router;
3352 SilcSocketConnection router_sock;
3357 SILC_LOG_DEBUG(("Processing new ID"));
3359 if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3360 server->server_type == SILC_SERVER ||
3361 packet->src_id_type != SILC_ID_SERVER)
3364 idp = silc_id_payload_parse(buffer);
3368 id_type = silc_id_payload_get_type(idp);
3370 /* Normal server cannot have other normal server connections */
3371 if (id_type == SILC_ID_SERVER && sock->type == SILC_SOCKET_TYPE_SERVER)
3374 id = silc_id_payload_get_id(idp);
3378 /* If the sender of this packet is server and we are router we need to
3379 broadcast this packet to other routers in the network. */
3380 if (!server->standalone && sock->type == SILC_SOCKET_TYPE_SERVER &&
3381 server->server_type == SILC_ROUTER) {
3382 SILC_LOG_DEBUG(("Broadcasting received New ID packet"));
3383 silc_server_packet_send(server, server->id_entry->router->connection,
3385 packet->flags | SILC_PACKET_FLAG_BROADCAST,
3386 buffer->data, buffer->len, FALSE);
3389 /* If the packet is originated from the one who sent it to us we know
3390 that the ID belongs to our cell, unless the sender was router. */
3391 tmpid = silc_id_str2id(packet->src_id, SILC_ID_SERVER);
3392 tmpserver = (SilcServerEntry)sock->user_data;
3394 if (!SILC_ID_SERVER_COMPARE(tmpid, tmpserver->id) &&
3395 sock->type == SILC_SOCKET_TYPE_SERVER) {
3396 id_list = server->local_list;
3398 router = sock->user_data;
3399 /* router = server->id_entry; */
3401 id_list = server->global_list;
3402 router_sock = (SilcSocketConnection)server->id_entry->router->connection;
3403 router = server->id_entry->router;
3409 case SILC_ID_CLIENT:
3411 SilcClientEntry idlist;
3413 SILC_LOG_DEBUG(("New client id(%s) from [%s] %s",
3414 silc_id_render(id, SILC_ID_CLIENT),
3415 sock->type == SILC_SOCKET_TYPE_SERVER ?
3416 "Server" : "Router", sock->hostname));
3418 /* Add the client to our local list. We are router and we keep
3419 cell specific local database of all clients in the cell. */
3420 idlist = silc_idlist_add_client(id_list, NULL, NULL, NULL,
3421 id, router, router_sock);
3425 case SILC_ID_SERVER:
3427 SilcServerEntry idlist;
3429 SILC_LOG_DEBUG(("New server id(%s) from [%s] %s",
3430 silc_id_render(id, SILC_ID_SERVER),
3431 sock->type == SILC_SOCKET_TYPE_SERVER ?
3432 "Server" : "Router", sock->hostname));
3434 /* Add the server to our local list. We are router and we keep
3435 cell specific local database of all servers in the cell. */
3436 idlist = silc_idlist_add_server(id_list, NULL, 0, id, router,
3441 case SILC_ID_CHANNEL:
3442 SILC_LOG_DEBUG(("New channel id(%s) from [%s] %s",
3443 silc_id_render(id, SILC_ID_CHANNEL),
3444 sock->type == SILC_SOCKET_TYPE_SERVER ?
3445 "Server" : "Router", sock->hostname));
3447 /* Add the channel to our local list. We are router and we keep
3448 cell specific local database of all channels in the cell. */
3449 silc_idlist_add_channel(id_list, NULL, 0, id, router, NULL);
3457 silc_id_payload_free(idp);
3460 /* Received packet to remove a user from a channel. Routers notify other
3461 routers that user has left a channel. Client must not send this packet.
3462 Normal server may send this packet but ignores if it receives one. */
3464 void silc_server_remove_channel_user(SilcServer server,
3465 SilcSocketConnection sock,
3466 SilcPacketContext *packet)
3468 SilcBuffer buffer = packet->buffer;
3469 unsigned char *tmp1 = NULL, *tmp2 = NULL;
3470 SilcClientID *client_id = NULL;
3471 SilcChannelID *channel_id = NULL;
3472 SilcChannelEntry channel;
3473 SilcClientEntry client;
3475 SILC_LOG_DEBUG(("Removing user from channel"));
3477 if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3478 server->server_type == SILC_SERVER)
3481 silc_buffer_unformat(buffer,
3482 SILC_STR_UI16_STRING_ALLOC(&tmp1),
3483 SILC_STR_UI16_STRING_ALLOC(&tmp2),
3489 client_id = silc_id_str2id(tmp1, SILC_ID_CLIENT);
3490 channel_id = silc_id_str2id(tmp2, SILC_ID_CHANNEL);
3491 if (!client_id || !channel_id)
3494 /* XXX routers should check server->global_list as well */
3495 /* Get channel entry */
3496 channel = silc_idlist_find_channel_by_id(server->local_list, channel_id);
3500 /* XXX routers should check server->global_list as well */
3501 /* Get client entry */
3502 client = silc_idlist_find_client_by_id(server->local_list, client_id);
3506 /* Remove from channel */
3507 silc_server_remove_from_one_channel(server, sock, channel, client, FALSE);
3515 silc_free(client_id);
3517 silc_free(channel_id);