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_to_router);
32 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
33 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
34 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
35 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
37 SILC_TASK_CALLBACK(silc_server_packet_process);
38 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
39 SILC_TASK_CALLBACK(silc_server_timeout_remote);
41 extern char *server_version;
43 /* Allocates a new SILC server object. This has to be done before the server
44 can be used. After allocation one must call silc_server_init to initialize
45 the server. The new allocated server object is returned to the new_server
48 int silc_server_alloc(SilcServer *new_server)
52 SILC_LOG_DEBUG(("Allocating new server object"));
54 server = silc_calloc(1, sizeof(*server));
55 server->server_type = SILC_SERVER;
56 server->standalone = FALSE;
57 server->local_list = silc_calloc(1, sizeof(*server->local_list));
58 server->global_list = silc_calloc(1, sizeof(*server->global_list));
60 server->sim = silc_dlist_init();
68 /* Free's the SILC server object. This is called at the very end before
71 void silc_server_free(SilcServer server)
76 if (server->local_list)
77 silc_free(server->local_list);
78 if (server->global_list)
79 silc_free(server->global_list);
81 silc_rng_free(server->rng);
83 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
84 silc_dlist_del(server->sim, sim);
87 silc_dlist_uninit(server->sim);
89 silc_math_primegen_uninit(); /* XXX */
94 /* Initializes the entire SILC server. This is called always before running
95 the server. This is called only once at the initialization of the program.
96 This binds the server to its listenning port. After this function returns
97 one should call silc_server_run to start the server. This returns TRUE
98 when everything is ok to run the server. Configuration file must be
99 read and parsed before calling this. */
101 int silc_server_init(SilcServer server)
103 int *sock = NULL, sock_count = 0, i;
105 SilcServerEntry id_entry;
107 SILC_LOG_DEBUG(("Initializing server"));
109 assert(server->config);
111 /* Set log files where log message should be saved. */
112 server->config->server = server;
113 silc_config_server_setlogfiles(server->config);
115 /* Register all configured ciphers, PKCS and hash functions. */
116 silc_config_server_register_ciphers(server->config);
117 silc_config_server_register_pkcs(server->config);
118 silc_config_server_register_hashfuncs(server->config);
120 /* Initialize random number generator for the server. */
121 server->rng = silc_rng_alloc();
122 silc_rng_init(server->rng);
123 silc_math_primegen_init(); /* XXX */
125 /* Initialize hash functions for server to use */
126 silc_hash_alloc("md5", &server->md5hash);
127 silc_hash_alloc("sha1", &server->sha1hash);
129 /* Initialize none cipher */
130 silc_cipher_alloc("none", &server->none_cipher);
132 /* XXXXX Generate RSA key pair */
134 unsigned char *public_key;
135 unsigned char *private_key;
136 unsigned int pk_len, prv_len;
139 if (stat("pubkey.pub", &st) < 0 && stat("privkey.prv", &st) < 0) {
141 if (silc_pkcs_alloc("rsa", &server->pkcs) == FALSE) {
142 SILC_LOG_ERROR(("Could not create RSA key pair"));
146 if (server->pkcs->pkcs->init(server->pkcs->context,
147 1024, server->rng) == FALSE) {
148 SILC_LOG_ERROR(("Could not generate RSA key pair"));
152 public_key = server->pkcs->pkcs->get_public_key(server->pkcs->context,
154 private_key = server->pkcs->pkcs->get_private_key(server->pkcs->context,
157 SILC_LOG_HEXDUMP(("public key"), public_key, pk_len);
158 SILC_LOG_HEXDUMP(("private key"), private_key, prv_len);
161 silc_pkcs_public_key_alloc("rsa", "UN=root, HN=dummy",
163 server->private_key =
164 silc_pkcs_private_key_alloc("rsa", private_key, prv_len);
167 silc_pkcs_save_public_key("pubkey.pub", server->public_key,
169 silc_pkcs_save_private_key("privkey.prv", server->private_key, NULL,
172 memset(public_key, 0, pk_len);
173 memset(private_key, 0, prv_len);
174 silc_free(public_key);
175 silc_free(private_key);
177 silc_pkcs_load_public_key("pubkey.pub", &server->public_key,
179 silc_pkcs_load_private_key("privkey.prv", &server->private_key,
184 /* Create a listening server. Note that our server can listen on
185 multiple ports. All listeners are created here and now. */
186 /* XXX Still check this whether to use server_info or listen_port. */
188 while(server->config->listen_port) {
191 tmp = silc_net_create_server(server->config->listen_port->port,
192 server->config->listen_port->host);
196 sock = silc_realloc(sock, (sizeof(int *) * (sock_count + 1)));
197 sock[sock_count] = tmp;
198 server->config->listen_port = server->config->listen_port->next;
202 /* Initialize ID caches */
203 server->local_list->clients = silc_idcache_alloc(0);
204 server->local_list->servers = silc_idcache_alloc(0);
205 server->local_list->channels = silc_idcache_alloc(0);
207 /* XXX for now these are allocated for normal server as well as these
208 hold some global information that the server has fetched from its
209 router. For router these are used as they are supposed to be used
210 on router. The XXX can be remoevd later if this is the way we are
211 going to do this in the normal server as well. */
212 server->global_list->clients = silc_idcache_alloc(0);
213 server->global_list->servers = silc_idcache_alloc(0);
214 server->global_list->channels = silc_idcache_alloc(0);
216 /* Allocate the entire socket list that is used in server. Eventually
217 all connections will have entry in this table (it is a table of
218 pointers to the actual object that is allocated individually
220 server->sockets = silc_calloc(SILC_SERVER_MAX_CONNECTIONS,
221 sizeof(*server->sockets));
223 for (i = 0; i < sock_count; i++) {
224 SilcSocketConnection newsocket = NULL;
226 /* Set socket to non-blocking mode */
227 silc_net_set_socket_nonblock(sock[i]);
228 server->sock = sock[i];
230 /* Create a Server ID for the server. */
231 silc_id_create_server_id(sock[i], server->rng, &id);
237 server->id_type = SILC_ID_SERVER;
238 server->server_name = server->config->server_info->server_name;
240 /* Add ourselves to the server list. We don't have a router yet
241 beacuse we haven't established a route yet. It will be done later.
242 For now, NULL is sent as router. This allocates new entry to
245 silc_idlist_add_server(server->local_list,
246 server->config->server_info->server_name,
247 server->server_type, server->id, NULL,
248 server->send_key, server->receive_key,
249 NULL, NULL, NULL, NULL);
251 SILC_LOG_ERROR(("Could not add ourselves to cache"));
255 /* Add ourselves also to the socket table. The entry allocated above
256 is sent as argument for fast referencing in the future. */
257 silc_socket_alloc(sock[i], SILC_SOCKET_TYPE_SERVER, id_entry,
262 server->sockets[sock[i]] = newsocket;
264 /* Put the allocated socket pointer also to the entry allocated above
265 for fast back-referencing to the socket list. */
266 id_entry->connection = (void *)server->sockets[sock[i]];
267 server->id_entry = id_entry;
270 /* Register the task queues. In SILC we have by default three task queues.
271 One task queue for non-timeout tasks which perform different kind of
272 I/O on file descriptors, timeout task queue for timeout tasks, and,
273 generic non-timeout task queue whose tasks apply to all connections. */
274 silc_task_queue_alloc(&server->io_queue, TRUE);
275 if (!server->io_queue) {
278 silc_task_queue_alloc(&server->timeout_queue, TRUE);
279 if (!server->timeout_queue) {
282 silc_task_queue_alloc(&server->generic_queue, TRUE);
283 if (!server->generic_queue) {
287 /* Register protocols */
288 silc_server_protocols_register();
290 /* Initialize the scheduler */
291 silc_schedule_init(&server->io_queue, &server->timeout_queue,
292 &server->generic_queue,
293 SILC_SERVER_MAX_CONNECTIONS);
295 /* Add the first task to the queue. This is task that is executed by
296 timeout. It expires as soon as the caller calls silc_server_run. This
297 task performs authentication protocol and key exchange with our
299 if (silc_task_register(server->timeout_queue, sock[0],
300 silc_server_connect_to_router,
301 (void *)server, 0, 1,
303 SILC_TASK_PRI_NORMAL) == NULL) {
307 /* If server connections has been configured then we must be router as
308 normal server cannot have server connections, only router connections. */
309 if (server->config->servers)
310 server->server_type = SILC_ROUTER;
312 SILC_LOG_DEBUG(("Server initialized"));
314 /* We are done here, return succesfully */
318 silc_task_queue_free(server->timeout_queue);
320 silc_task_queue_free(server->io_queue);
322 for (i = 0; i < sock_count; i++)
323 silc_net_close_server(sock[i]);
328 /* Stops the SILC server. This function is used to shutdown the server.
329 This is usually called after the scheduler has returned. After stopping
330 the server one should call silc_server_free. */
332 void silc_server_stop(SilcServer server)
334 SILC_LOG_DEBUG(("Stopping server"));
336 /* Stop the scheduler, although it might be already stopped. This
337 doesn't hurt anyone. This removes all the tasks and task queues,
339 silc_schedule_stop();
340 silc_schedule_uninit();
342 silc_server_protocols_unregister();
344 SILC_LOG_DEBUG(("Server stopped"));
347 /* The heart of the server. This runs the scheduler thus runs the server. */
349 void silc_server_run(SilcServer server)
351 SILC_LOG_DEBUG(("Running server"));
353 /* Start the scheduler, the heart of the SILC server. When this returns
354 the program will be terminated. */
358 /* This function connects to our primary router or if we are a router this
359 establishes all our primary routes. This is called at the start of the
360 server to do authentication and key exchange with our router - called
363 SILC_TASK_CALLBACK(silc_server_connect_to_router)
365 SilcServer server = (SilcServer)context;
366 SilcSocketConnection newsocket;
369 SILC_LOG_DEBUG(("Connecting to router(s)"));
371 /* if we are normal SILC server we need to connect to our cell's
373 if (server->server_type == SILC_SERVER) {
374 SilcProtocol protocol;
375 SilcServerKEInternalContext *proto_ctx;
377 /* Create connection to the router, if configured. */
378 if (server->config->routers) {
379 sock = silc_net_create_connection(server->config->routers->port,
380 server->config->routers->host);
382 SILC_LOG_ERROR(("Could not connect to router"));
383 silc_schedule_stop();
387 /* Set socket options */
388 silc_net_set_socket_nonblock(sock);
389 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
391 /* Create socket connection for the connection. Even though we
392 know that we are connecting to a router we will mark the socket
393 to be unknown connection until we have executed authentication
395 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
396 server->sockets[sock] = newsocket;
397 newsocket->hostname = server->config->routers->host;
398 newsocket->port = server->config->routers->port;
400 /* Allocate internal protocol context. This is sent as context
402 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
403 proto_ctx->server = context;
404 proto_ctx->sock = newsocket;
405 proto_ctx->rng = server->rng;
406 proto_ctx->responder = FALSE;
408 /* Perform key exchange protocol. silc_server_connect_to_router_second
409 will be called after the protocol is finished. */
410 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
411 &protocol, proto_ctx,
412 silc_server_connect_to_router_second);
413 newsocket->protocol = protocol;
415 /* Register a timeout task that will be executed if the protocol
416 is not executed within 60 seconds. For now, this is a hard coded
417 limit. After 60 secs the connection will be closed if the key
418 exchange protocol has not been executed. */
419 proto_ctx->timeout_task =
420 silc_task_register(server->timeout_queue, sock,
421 silc_server_timeout_remote,
426 /* Register the connection for network input and output. This sets
427 that scheduler will listen for incoming packets for this connection
428 and sets that outgoing packets may be sent to this connection as
429 well. However, this doesn't set the scheduler for outgoing traffic,
430 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
431 later when outgoing data is available. */
432 SILC_REGISTER_CONNECTION_FOR_IO(sock);
434 /* Run the protocol */
435 protocol->execute(server->timeout_queue, 0, protocol, sock, 0, 0);
440 /* if we are a SILC router we need to establish all of our primary
442 if (server->server_type == SILC_ROUTER) {
443 SilcConfigServerSectionServerConnection *ptr;
445 /* Create the connections to all our routes */
446 ptr = server->config->routers;
448 SilcProtocol protocol;
449 SilcServerKEInternalContext *proto_ctx;
451 /* Create the connection to the remote end */
452 sock = silc_net_create_connection(ptr->port, ptr->host);
454 SILC_LOG_ERROR(("Could not connect to router"));
455 silc_schedule_stop();
459 /* Set socket options */
460 silc_net_set_socket_nonblock(sock);
461 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
463 /* Create socket connection for the connection. Even though we
464 know that we are connecting to a router we will mark the socket
465 to be unknown connection until we have executed authentication
467 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
468 server->sockets[sock] = newsocket;
469 newsocket->hostname = ptr->host;
470 newsocket->port = ptr->port;
472 /* Allocate internal protocol context. This is sent as context
474 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
475 proto_ctx->server = context;
476 proto_ctx->sock = newsocket;
477 proto_ctx->rng = server->rng;
478 proto_ctx->responder = FALSE;
480 /* Perform key exchange protocol. silc_server_connect_to_router_final
481 will be called after the protocol is finished. */
482 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
483 &protocol, proto_ctx,
484 silc_server_connect_to_router_second);
485 newsocket->protocol = protocol;
487 /* Register a timeout task that will be executed if the protocol
488 is not executed within 60 seconds. For now, this is a hard coded
489 limit. After 60 secs the connection will be closed if the key
490 exchange protocol has not been executed. */
491 proto_ctx->timeout_task =
492 silc_task_register(server->timeout_queue, sock,
493 silc_server_timeout_remote,
498 /* Register the connection for network input and output. This sets
499 that scheduler will listen for incoming packets for this connection
500 and sets that outgoing packets may be sent to this connection as
501 well. However, this doesn't set the scheduler for outgoing traffic,
502 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
503 later when outgoing data is available. */
504 SILC_REGISTER_CONNECTION_FOR_IO(sock);
506 /* Run the protocol */
507 protocol->execute(server->timeout_queue, 0, protocol, sock, 0, 0);
516 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
518 /* There wasn't a configured router, we will continue but we don't
519 have a connection to outside world. We will be standalone server. */
520 server->standalone = TRUE;
522 /* Add a task to the queue. This task receives new connections to the
523 server. This task remains on the queue until the end of the program. */
524 if (silc_task_register(server->io_queue, fd,
525 silc_server_accept_new_connection,
526 (void *)server, 0, 0,
528 SILC_TASK_PRI_NORMAL) == NULL) {
529 silc_schedule_stop();
534 /* Second part of connecting to router(s). Key exchange protocol has been
535 executed and now we will execute authentication protocol. */
537 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
539 SilcProtocol protocol = (SilcProtocol)context;
540 SilcServerKEInternalContext *ctx =
541 (SilcServerKEInternalContext *)protocol->context;
542 SilcServer server = (SilcServer)ctx->server;
543 SilcSocketConnection sock = NULL;
544 SilcServerConnAuthInternalContext *proto_ctx;
546 SILC_LOG_DEBUG(("Start"));
548 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
549 /* Error occured during protocol */
550 silc_protocol_free(protocol);
552 silc_buffer_free(ctx->packet);
554 silc_ske_free(ctx->ske);
556 silc_free(ctx->dest_id);
558 sock->protocol = NULL;
559 silc_server_disconnect_remote(server, sock, "Server closed connection: "
560 "Key exchange failed");
564 /* Allocate internal context for the authentication protocol. This
565 is sent as context for the protocol. */
566 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
567 proto_ctx->server = (void *)server;
568 proto_ctx->sock = sock = server->sockets[fd];
569 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
570 proto_ctx->dest_id_type = ctx->dest_id_type;
571 proto_ctx->dest_id = ctx->dest_id;
573 /* Resolve the authentication method used in this connection */
574 proto_ctx->auth_meth = SILC_PROTOCOL_CONN_AUTH_PASSWORD;
575 if (server->config->routers) {
576 SilcConfigServerSectionServerConnection *conn = NULL;
578 /* Check if we find a match from user configured connections */
579 conn = silc_config_server_find_router_conn(server->config,
583 /* Match found. Use the configured authentication method */
584 proto_ctx->auth_meth = conn->auth_meth;
585 if (conn->auth_data) {
586 proto_ctx->auth_data = strdup(conn->auth_data);
587 proto_ctx->auth_data_len = strlen(conn->auth_data);
590 /* No match found. */
597 /* Free old protocol as it is finished now */
598 silc_protocol_free(protocol);
600 silc_buffer_free(ctx->packet);
602 sock->protocol = NULL;
604 /* Allocate the authentication protocol. This is allocated here
605 but we won't start it yet. We will be receiving party of this
606 protocol thus we will wait that connecting party will make
608 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
609 &sock->protocol, proto_ctx,
610 silc_server_connect_to_router_final);
612 /* Register timeout task. If the protocol is not executed inside
613 this timelimit the connection will be terminated. Currently
614 this is 15 seconds and is hard coded limit (XXX). */
615 proto_ctx->timeout_task =
616 silc_task_register(server->timeout_queue, sock->sock,
617 silc_server_timeout_remote,
618 (void *)server, 15, 0,
622 /* Run the protocol */
623 sock->protocol->execute(server->timeout_queue, 0,
624 sock->protocol, sock->sock, 0, 0);
627 /* Finalizes the connection to router. Registers a server task to the
628 queue so that we can accept new connections. */
630 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
632 SilcProtocol protocol = (SilcProtocol)context;
633 SilcServerConnAuthInternalContext *ctx =
634 (SilcServerConnAuthInternalContext *)protocol->context;
635 SilcServer server = (SilcServer)ctx->server;
636 SilcSocketConnection sock = ctx->sock;
637 SilcServerEntry id_entry;
638 SilcUnknownEntry conn_data;
640 unsigned char *id_string;
642 SILC_LOG_DEBUG(("Start"));
644 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
645 /* Error occured during protocol */
646 silc_protocol_free(protocol);
648 silc_buffer_free(ctx->packet);
650 silc_ske_free(ctx->ske);
652 silc_free(ctx->dest_id);
654 sock->protocol = NULL;
655 silc_server_disconnect_remote(server, sock, "Server closed connection: "
656 "Authentication failed");
660 /* Add a task to the queue. This task receives new connections to the
661 server. This task remains on the queue until the end of the program. */
662 if (!server->listenning) {
663 if (silc_task_register(server->io_queue, server->sock,
664 silc_server_accept_new_connection,
665 (void *)server, 0, 0,
667 SILC_TASK_PRI_NORMAL) == NULL) {
668 silc_schedule_stop();
671 server->listenning = TRUE;
675 /* Send NEW_SERVER packet to the router. We will become registered
676 to the SILC network after sending this packet. */
677 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
678 packet = silc_buffer_alloc(2 + 2 + SILC_ID_SERVER_LEN +
679 strlen(server->server_name));
680 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
681 silc_buffer_format(packet,
682 SILC_STR_UI_SHORT(SILC_ID_SERVER_LEN),
683 SILC_STR_UI_XNSTRING(id_string, SILC_ID_SERVER_LEN),
684 SILC_STR_UI_SHORT(strlen(server->server_name)),
685 SILC_STR_UI_XNSTRING(server->server_name,
686 strlen(server->server_name)),
689 /* Send the packet */
690 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
691 packet->data, packet->len, TRUE);
692 silc_buffer_free(packet);
693 silc_free(id_string);
695 SILC_LOG_DEBUG(("Connected to router %s", sock->hostname));
697 /* Add the connected router to local server list */
698 server->standalone = FALSE;
699 conn_data = (SilcUnknownEntry)sock->user_data;
701 silc_idlist_add_server(server->local_list,
702 sock->hostname ? sock->hostname : sock->ip,
703 SILC_ROUTER, ctx->dest_id, NULL,
704 conn_data->send_key, conn_data->receive_key,
705 conn_data->pkcs, conn_data->hmac, NULL, sock);
707 id_entry->hmac_key = conn_data->hmac_key;
708 id_entry->hmac_key_len = conn_data->hmac_key_len;
709 sock->user_data = (void *)id_entry;
710 sock->type = SILC_SOCKET_TYPE_ROUTER;
711 server->id_entry->router = id_entry;
714 /* Free the temporary connection data context from key exchange */
715 silc_free(conn_data);
717 /* Free the protocol object */
718 silc_protocol_free(protocol);
720 silc_buffer_free(ctx->packet);
722 silc_ske_free(ctx->ske);
724 sock->protocol = NULL;
727 /* Accepts new connections to the server. Accepting new connections are
728 done in three parts to make it async. */
730 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
732 SilcServer server = (SilcServer)context;
733 SilcSocketConnection newsocket;
734 SilcServerKEInternalContext *proto_ctx;
737 SILC_LOG_DEBUG(("Accepting new connection"));
739 sock = silc_net_accept_connection(server->sock);
741 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
745 /* Check max connections */
746 if (sock > SILC_SERVER_MAX_CONNECTIONS) {
747 if (server->config->redirect) {
748 /* XXX Redirecting connection to somewhere else now?? */
749 /*silc_server_send_notify("Server is full, trying to redirect..."); */
751 SILC_LOG_ERROR(("Refusing connection, server is full"));
756 /* Set socket options */
757 silc_net_set_socket_nonblock(sock);
758 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
760 /* We don't create a ID yet, since we don't know what type of connection
761 this is yet. But, we do add the connection to the socket table. */
762 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
763 server->sockets[sock] = newsocket;
765 /* XXX This MUST be done async as this will block the entire server
766 process. Either we have to do our own resolver stuff or in the future
767 we can use threads. */
768 /* Perform mandatory name and address lookups for the remote host. */
769 silc_net_check_host_by_sock(sock, &newsocket->hostname, &newsocket->ip);
770 if (!newsocket->ip || !newsocket->hostname) {
771 SILC_LOG_DEBUG(("IP lookup/DNS lookup failed"));
772 SILC_LOG_ERROR(("IP lookup/DNS lookup failed"));
776 SILC_LOG_INFO(("Incoming connection from %s (%s)", newsocket->hostname,
779 /* Allocate internal context for key exchange protocol. This is
780 sent as context for the protocol. */
781 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
782 proto_ctx->server = context;
783 proto_ctx->sock = newsocket;
784 proto_ctx->rng = server->rng;
785 proto_ctx->responder = TRUE;
787 /* Prepare the connection for key exchange protocol. We allocate the
788 protocol but will not start it yet. The connector will be the
789 initiator of the protocol thus we will wait for initiation from
790 there before we start the protocol. */
791 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
792 &newsocket->protocol, proto_ctx,
793 silc_server_accept_new_connection_second);
795 /* Register a timeout task that will be executed if the connector
796 will not start the key exchange protocol within 60 seconds. For
797 now, this is a hard coded limit. After 60 secs the connection will
798 be closed if the key exchange protocol has not been started. */
799 proto_ctx->timeout_task =
800 silc_task_register(server->timeout_queue, newsocket->sock,
801 silc_server_timeout_remote,
806 /* Register the connection for network input and output. This sets
807 that scheduler will listen for incoming packets for this connection
808 and sets that outgoing packets may be sent to this connection as well.
809 However, this doesn't set the scheduler for outgoing traffic, it
810 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
811 later when outgoing data is available. */
812 SILC_REGISTER_CONNECTION_FOR_IO(sock);
815 /* Second part of accepting new connection. Key exchange protocol has been
816 performed and now it is time to do little connection authentication
817 protocol to figure out whether this connection is client or server
818 and whether it has right to access this server (especially server
819 connections needs to be authenticated). */
821 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
823 SilcProtocol protocol = (SilcProtocol)context;
824 SilcServerKEInternalContext *ctx =
825 (SilcServerKEInternalContext *)protocol->context;
826 SilcServer server = (SilcServer)ctx->server;
827 SilcSocketConnection sock = NULL;
828 SilcServerConnAuthInternalContext *proto_ctx;
830 SILC_LOG_DEBUG(("Start"));
832 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
833 /* Error occured during protocol */
834 silc_protocol_free(protocol);
836 silc_buffer_free(ctx->packet);
838 silc_ske_free(ctx->ske);
840 silc_free(ctx->dest_id);
843 sock->protocol = NULL;
844 silc_server_disconnect_remote(server, sock, "Server closed connection: "
845 "Key exchange failed");
849 /* Allocate internal context for the authentication protocol. This
850 is sent as context for the protocol. */
851 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
852 proto_ctx->server = (void *)server;
853 proto_ctx->sock = sock = server->sockets[fd];
854 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
855 proto_ctx->responder = TRUE;
856 proto_ctx->dest_id_type = ctx->dest_id_type;
857 proto_ctx->dest_id = ctx->dest_id;
859 /* Free old protocol as it is finished now */
860 silc_protocol_free(protocol);
862 silc_buffer_free(ctx->packet);
864 sock->protocol = NULL;
866 /* Allocate the authentication protocol. This is allocated here
867 but we won't start it yet. We will be receiving party of this
868 protocol thus we will wait that connecting party will make
870 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
871 &sock->protocol, proto_ctx,
872 silc_server_accept_new_connection_final);
874 /* Register timeout task. If the protocol is not executed inside
875 this timelimit the connection will be terminated. Currently
876 this is 60 seconds and is hard coded limit (XXX). */
877 proto_ctx->timeout_task =
878 silc_task_register(server->timeout_queue, sock->sock,
879 silc_server_timeout_remote,
880 (void *)server, 60, 0,
885 /* Final part of accepting new connection. The connection has now
886 been authenticated and keys has been exchanged. We also know whether
887 this is client or server connection. */
889 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
891 SilcProtocol protocol = (SilcProtocol)context;
892 SilcServerConnAuthInternalContext *ctx =
893 (SilcServerConnAuthInternalContext *)protocol->context;
894 SilcServer server = (SilcServer)ctx->server;
895 SilcSocketConnection sock = ctx->sock;
897 SILC_LOG_DEBUG(("Start"));
899 if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
900 /* Error occured during protocol */
901 silc_protocol_free(protocol);
903 silc_buffer_free(ctx->packet);
905 silc_ske_free(ctx->ske);
907 silc_free(ctx->dest_id);
910 sock->protocol = NULL;
911 silc_server_disconnect_remote(server, sock, "Server closed connection: "
912 "Authentication failed");
916 sock->type = ctx->conn_type;
918 case SILC_SOCKET_TYPE_CLIENT:
920 SilcClientEntry client;
921 SilcUnknownEntry conn_data = (SilcUnknownEntry)sock->user_data;
923 SILC_LOG_DEBUG(("Remote host is client"));
924 SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
927 /* Add the client to the client ID cache. The nickname and Client ID
928 and other information is created after we have received NEW_CLIENT
929 packet from client. */
931 silc_idlist_add_client(server->local_list, NULL, NULL, NULL, NULL,
932 NULL, conn_data->send_key,
933 conn_data->receive_key, conn_data->pkcs,
934 conn_data->hmac, NULL, sock);
936 SILC_LOG_ERROR(("Could not add new client to cache"));
937 silc_free(conn_data);
941 /* Free the temporary connection data context from key exchange */
942 silc_free(conn_data);
944 /* Add to sockets internal pointer for fast referencing */
945 sock->user_data = (void *)client;
948 case SILC_SOCKET_TYPE_SERVER:
949 case SILC_SOCKET_TYPE_ROUTER:
951 SilcServerEntry new_server;
952 SilcUnknownEntry conn_data = (SilcUnknownEntry)sock->user_data;
954 SILC_LOG_DEBUG(("Remote host is %s",
955 sock->type == SILC_SOCKET_TYPE_SERVER ?
956 "server" : "router"));
957 SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
958 sock->ip, sock->type == SILC_SOCKET_TYPE_SERVER ?
959 "server" : "router"));
961 /* Add the server into server cache. The server name and Server ID
962 is updated after we have received NEW_SERVER packet from the
965 silc_idlist_add_server(server->local_list, NULL,
966 sock->type == SILC_SOCKET_TYPE_SERVER ?
967 SILC_SERVER : SILC_ROUTER, NULL, NULL,
968 conn_data->send_key, conn_data->receive_key,
969 conn_data->pkcs, conn_data->hmac, NULL, sock);
971 SILC_LOG_ERROR(("Could not add new server to cache"));
972 silc_free(conn_data);
976 new_server->registered = TRUE;
977 new_server->hmac_key = conn_data->hmac_key;
978 new_server->hmac_key_len = conn_data->hmac_key_len;
980 /* Free the temporary connection data context from protocols */
981 silc_free(conn_data);
983 /* Add to sockets internal pointer for fast referencing */
984 sock->user_data = (void *)new_server;
986 /* There is connection to other server now, if it is router then
987 we will have connection to outside world. If we are router but
988 normal server connected to us then we will remain standalone,
989 if we are standlone. */
990 if (server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER) {
991 SILC_LOG_DEBUG(("We are not standalone server anymore"));
992 server->standalone = FALSE;
1000 /* Connection has been fully established now. Everything is ok. */
1001 SILC_LOG_DEBUG(("New connection authenticated"));
1003 silc_protocol_free(protocol);
1005 silc_buffer_free(ctx->packet);
1007 silc_ske_free(ctx->ske);
1009 silc_free(ctx->dest_id);
1011 sock->protocol = NULL;
1014 /* Internal routine that sends packet or marks packet to be sent. This
1015 is used directly only in special cases. Normal cases should use
1016 silc_server_packet_send. Returns < 0 error. */
1018 static int silc_server_packet_send_real(SilcServer server,
1019 SilcSocketConnection sock,
1024 /* Send the packet */
1025 ret = silc_packet_send(sock, force_send);
1029 /* Mark that there is some outgoing data available for this connection.
1030 This call sets the connection both for input and output (the input
1031 is set always and this call keeps the input setting, actually).
1032 Actual data sending is performed by silc_server_packet_process. */
1033 SILC_SET_CONNECTION_FOR_OUTPUT(sock->sock);
1035 /* Mark to socket that data is pending in outgoing buffer. This flag
1036 is needed if new data is added to the buffer before the earlier
1037 put data is sent to the network. */
1038 SILC_SET_OUTBUF_PENDING(sock);
1044 SilcPacketContext *packetdata;
1046 SilcSocketConnection sock;
1049 } SilcServerInternalPacket;
1051 /* This function is used to read packets from network and send packets to
1052 network. This is usually a generic task. */
1054 SILC_TASK_CALLBACK(silc_server_packet_process)
1056 SilcServer server = (SilcServer)context;
1057 SilcSocketConnection sock = server->sockets[fd];
1058 SilcCipher cipher = NULL;
1059 SilcHmac hmac = NULL;
1062 SILC_LOG_DEBUG(("Processing packet"));
1064 /* Packet sending */
1065 if (type == SILC_TASK_WRITE) {
1066 SILC_LOG_DEBUG(("Writing data to connection"));
1068 if (sock->outbuf->data - sock->outbuf->head)
1069 silc_buffer_push(sock->outbuf,
1070 sock->outbuf->data - sock->outbuf->head);
1072 ret = silc_server_packet_send_real(server, sock, TRUE);
1074 /* If returned -2 could not write to connection now, will do
1079 /* The packet has been sent and now it is time to set the connection
1080 back to only for input. When there is again some outgoing data
1081 available for this connection it will be set for output as well.
1082 This call clears the output setting and sets it only for input. */
1083 SILC_SET_CONNECTION_FOR_INPUT(fd);
1084 SILC_UNSET_OUTBUF_PENDING(sock);
1086 silc_buffer_clear(sock->outbuf);
1090 /* Packet receiving */
1091 if (type == SILC_TASK_READ) {
1092 SILC_LOG_DEBUG(("Reading data from connection"));
1094 /* Read some data from connection */
1095 ret = silc_packet_receive(sock);
1101 SILC_LOG_DEBUG(("Read EOF"));
1103 /* If connection is disconnecting already we will finally
1104 close the connection */
1105 if (SILC_IS_DISCONNECTING(sock)) {
1106 if (sock->user_data)
1107 silc_server_free_sock_user_data(server, sock);
1108 silc_server_close_connection(server, sock);
1112 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1114 if (sock->user_data)
1115 silc_server_free_sock_user_data(server, sock);
1116 silc_server_close_connection(server, sock);
1120 /* If connection is disconnecting or disconnected we will ignore
1122 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1123 SILC_LOG_DEBUG(("Ignoring read data from invalid connection"));
1127 switch (sock->type) {
1128 case SILC_SOCKET_TYPE_CLIENT:
1130 SilcClientEntry clnt = (SilcClientEntry)sock->user_data;
1134 clnt->last_receive = time(NULL);
1136 cipher = clnt->receive_key;
1140 case SILC_SOCKET_TYPE_SERVER:
1141 case SILC_SOCKET_TYPE_ROUTER:
1143 SilcServerEntry srvr = (SilcServerEntry)sock->user_data;
1147 srvr->last_receive = time(NULL);
1149 cipher = srvr->receive_key;
1153 case SILC_SOCKET_TYPE_UNKNOWN:
1155 SilcUnknownEntry conn_data = (SilcUnknownEntry)sock->user_data;
1159 cipher = conn_data->receive_key;
1160 hmac = conn_data->hmac;
1167 /* Process the packet. This will call the parser that will then
1168 decrypt and parse the packet. */
1169 silc_packet_receive_process(sock, cipher, hmac,
1170 silc_server_packet_parse, server);
1174 /* Parses whole packet, received earlier. */
1176 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1178 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1179 SilcServer server = (SilcServer)parse_ctx->context;
1180 SilcSocketConnection sock = parse_ctx->sock;
1181 SilcPacketContext *packet = parse_ctx->packet;
1182 SilcBuffer buffer = packet->buffer;
1185 SILC_LOG_DEBUG(("Start"));
1187 /* Decrypt the received packet */
1188 ret = silc_packet_decrypt(parse_ctx->cipher, parse_ctx->hmac,
1194 /* Parse the packet. Packet type is returned. */
1195 ret = silc_packet_parse(packet);
1197 /* Parse the packet header in special way as this is "special"
1199 ret = silc_packet_parse_special(packet);
1202 if (ret == SILC_PACKET_NONE)
1205 /* Parse the incoming packet type */
1206 silc_server_packet_parse_type(server, sock, packet);
1209 silc_buffer_clear(sock->inbuf);
1211 silc_free(packet->src_id);
1213 silc_free(packet->dst_id);
1215 silc_free(parse_ctx);
1218 /* Parser callback called by silc_packet_receive_process. This merely
1219 registers timeout that will handle the actual parsing whem appropriate. */
1221 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1223 SilcServer server = (SilcServer)parser_context->context;
1224 SilcSocketConnection sock = parser_context->sock;
1226 switch (sock->type) {
1227 case SILC_SOCKET_TYPE_CLIENT:
1228 case SILC_SOCKET_TYPE_UNKNOWN:
1229 /* Parse the packet with timeout */
1230 silc_task_register(server->timeout_queue, sock->sock,
1231 silc_server_packet_parse_real,
1232 (void *)parser_context, 0, 100000,
1234 SILC_TASK_PRI_NORMAL);
1236 case SILC_SOCKET_TYPE_SERVER:
1237 case SILC_SOCKET_TYPE_ROUTER:
1238 /* Packets from servers are parsed as soon as possible */
1239 silc_task_register(server->timeout_queue, sock->sock,
1240 silc_server_packet_parse_real,
1241 (void *)parser_context, 0, 1,
1243 SILC_TASK_PRI_NORMAL);
1250 /* Parses the packet type and calls what ever routines the packet type
1251 requires. This is done for all incoming packets. */
1253 void silc_server_packet_parse_type(SilcServer server,
1254 SilcSocketConnection sock,
1255 SilcPacketContext *packet)
1257 SilcBuffer buffer = packet->buffer;
1258 SilcPacketType type = packet->type;
1260 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1262 /* Parse the packet type */
1264 case SILC_PACKET_DISCONNECT:
1265 SILC_LOG_DEBUG(("Disconnect packet"));
1267 case SILC_PACKET_SUCCESS:
1269 * Success received for something. For now we can have only
1270 * one protocol for connection executing at once hence this
1271 * success message is for whatever protocol is executing currently.
1273 SILC_LOG_DEBUG(("Success packet"));
1274 if (sock->protocol) {
1275 sock->protocol->execute(server->timeout_queue, 0,
1276 sock->protocol, sock->sock, 0, 0);
1279 case SILC_PACKET_FAILURE:
1281 * Failure received for something. For now we can have only
1282 * one protocol for connection executing at once hence this
1283 * failure message is for whatever protocol is executing currently.
1285 SILC_LOG_DEBUG(("Failure packet"));
1286 if (sock->protocol) {
1287 /* XXX Audit the failure type */
1288 sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
1289 sock->protocol->execute(server->timeout_queue, 0,
1290 sock->protocol, sock->sock, 0, 0);
1293 case SILC_PACKET_REJECT:
1294 SILC_LOG_DEBUG(("Reject packet"));
1301 case SILC_PACKET_CHANNEL_MESSAGE:
1303 * Received channel message. Channel messages are special packets
1304 * (although probably most common ones) hence they are handled
1307 SILC_LOG_DEBUG(("Channel Message packet"));
1308 silc_server_channel_message(server, sock, packet);
1311 case SILC_PACKET_CHANNEL_KEY:
1313 * Received key for channel. As channels are created by the router
1314 * the keys are as well. We will distribute the key to all of our
1315 * locally connected clients on the particular channel. Router
1316 * never receives this channel and thus is ignored.
1318 SILC_LOG_DEBUG(("Channel Key packet"));
1319 silc_server_channel_key(server, sock, packet);
1325 case SILC_PACKET_COMMAND:
1327 * Recived command. Allocate command context and execute the command.
1329 SILC_LOG_DEBUG(("Command packet"));
1330 silc_server_command_process(server, sock, packet);
1333 case SILC_PACKET_COMMAND_REPLY:
1335 * Received command reply packet. Servers never send commands thus
1336 * they don't receive command reply packets either, except in cases
1337 * where server has forwarded command packet coming from client.
1338 * This must be the case here or we will ignore the packet.
1340 SILC_LOG_DEBUG(("Command Reply packet"));
1341 silc_server_packet_relay_command_reply(server, sock, packet);
1345 * Private Message packets
1347 case SILC_PACKET_PRIVATE_MESSAGE:
1349 * Received private message packet. The packet is coming from either
1352 SILC_LOG_DEBUG(("Private Message packet"));
1353 silc_server_private_message(server, sock, packet);
1356 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1360 * Key Exchange protocol packets
1362 case SILC_PACKET_KEY_EXCHANGE:
1363 SILC_LOG_DEBUG(("KE packet"));
1364 if (sock->protocol && sock->protocol->protocol->type
1365 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1367 SilcServerKEInternalContext *proto_ctx =
1368 (SilcServerKEInternalContext *)sock->protocol->context;
1370 proto_ctx->packet = buffer;
1372 /* Let the protocol handle the packet */
1373 sock->protocol->execute(server->timeout_queue, 0,
1374 sock->protocol, sock->sock, 0, 100000);
1376 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1377 "protocol active, packet dropped."));
1379 /* XXX Trigger KE protocol?? Rekey actually, maybe. */
1383 case SILC_PACKET_KEY_EXCHANGE_1:
1384 SILC_LOG_DEBUG(("KE 1 packet"));
1385 if (sock->protocol && sock->protocol->protocol->type
1386 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1388 SilcServerKEInternalContext *proto_ctx =
1389 (SilcServerKEInternalContext *)sock->protocol->context;
1391 if (proto_ctx->packet)
1392 silc_buffer_free(proto_ctx->packet);
1394 proto_ctx->packet = buffer;
1395 proto_ctx->dest_id_type = packet->src_id_type;
1396 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_type);
1398 /* Let the protocol handle the packet */
1399 sock->protocol->execute(server->timeout_queue, 0,
1400 sock->protocol, sock->sock,
1403 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1404 "protocol active, packet dropped."));
1408 case SILC_PACKET_KEY_EXCHANGE_2:
1409 SILC_LOG_DEBUG(("KE 2 packet"));
1410 if (sock->protocol && sock->protocol->protocol->type
1411 == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1413 SilcServerKEInternalContext *proto_ctx =
1414 (SilcServerKEInternalContext *)sock->protocol->context;
1416 if (proto_ctx->packet)
1417 silc_buffer_free(proto_ctx->packet);
1419 proto_ctx->packet = buffer;
1420 proto_ctx->dest_id_type = packet->src_id_type;
1421 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_type);
1423 /* Let the protocol handle the packet */
1424 sock->protocol->execute(server->timeout_queue, 0,
1425 sock->protocol, sock->sock,
1428 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1429 "protocol active, packet dropped."));
1433 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1434 /* If we receive this packet we will send to the other end information
1435 about our mandatory authentication method for the connection.
1436 This packet maybe received at any time. */
1439 * Connection Authentication protocol packets
1441 case SILC_PACKET_CONNECTION_AUTH:
1442 /* Start of the authentication protocol. We receive here the
1443 authentication data and will verify it. */
1444 SILC_LOG_DEBUG(("Connection auth packet"));
1445 if (sock->protocol && sock->protocol->protocol->type
1446 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1448 SilcServerConnAuthInternalContext *proto_ctx =
1449 (SilcServerConnAuthInternalContext *)sock->protocol->context;
1451 proto_ctx->packet = buffer;
1453 /* Let the protocol handle the packet */
1454 sock->protocol->execute(server->timeout_queue, 0,
1455 sock->protocol, sock->sock, 0, 0);
1457 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1458 "protocol active, packet dropped."));
1462 case SILC_PACKET_NEW_ID:
1464 * Received New ID packet. This includes some new ID that has been
1465 * created. It may be for client, server or channel. This is the way
1466 * to distribute information about new registered entities in the
1469 SILC_LOG_DEBUG(("New ID packet"));
1470 silc_server_new_id(server, sock, packet);
1473 case SILC_PACKET_NEW_CLIENT:
1475 * Received new client packet. This includes client information that
1476 * we will use to create initial client ID. After creating new
1477 * ID we will send it to the client.
1479 SILC_LOG_DEBUG(("New Client packet"));
1480 silc_server_new_client(server, sock, packet);
1483 case SILC_PACKET_NEW_SERVER:
1485 * Received new server packet. This includes Server ID and some other
1486 * information that we may save. This is received after server has
1489 SILC_LOG_DEBUG(("New Server packet"));
1490 silc_server_new_server(server, sock, packet);
1493 case SILC_PACKET_NEW_CHANNEL:
1496 case SILC_PACKET_NEW_CHANNEL_USER:
1499 case SILC_PACKET_NEW_CHANNEL_LIST:
1502 case SILC_PACKET_NEW_CHANNEL_USER_LIST:
1505 case SILC_PACKET_REPLACE_ID:
1507 * Received replace ID packet. This sends the old ID that is to be
1508 * replaced with the new one included into the packet. Client must not
1511 SILC_LOG_DEBUG(("Replace ID packet"));
1512 silc_server_replace_id(server, sock, packet);
1515 case SILC_PACKET_REMOVE_ID:
1518 case SILC_PACKET_REMOVE_CHANNEL_USER:
1520 * Received packet to remove user from a channel. Routers notify other
1521 * routers about a user leaving a channel.
1523 SILC_LOG_DEBUG(("Remove Channel User packet"));
1524 silc_server_remove_channel_user(server, sock, packet);
1528 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
1534 /* Assembles a new packet to be sent out to network. This doesn't actually
1535 send the packet but creates the packet and fills the outgoing data
1536 buffer and marks the packet ready to be sent to network. However, If
1537 argument force_send is TRUE the packet is sent immediately and not put
1538 to queue. Normal case is that the packet is not sent immediately. */
1540 void silc_server_packet_send(SilcServer server,
1541 SilcSocketConnection sock,
1542 SilcPacketType type,
1543 SilcPacketFlags flags,
1544 unsigned char *data,
1545 unsigned int data_len,
1548 void *dst_id = NULL;
1549 SilcIdType dst_id_type = SILC_ID_NONE;
1554 /* Get data used in the packet sending, keys and stuff */
1555 switch(sock->type) {
1556 case SILC_SOCKET_TYPE_CLIENT:
1557 if (((SilcClientEntry)sock->user_data)->id) {
1558 dst_id = ((SilcClientEntry)sock->user_data)->id;
1559 dst_id_type = SILC_ID_CLIENT;
1562 case SILC_SOCKET_TYPE_SERVER:
1563 case SILC_SOCKET_TYPE_ROUTER:
1564 if (((SilcServerEntry)sock->user_data)->id) {
1565 dst_id = ((SilcServerEntry)sock->user_data)->id;
1566 dst_id_type = SILC_ID_SERVER;
1573 silc_server_packet_send_dest(server, sock, type, flags, dst_id,
1574 dst_id_type, data, data_len, force_send);
1577 /* Assembles a new packet to be sent out to network. This doesn't actually
1578 send the packet but creates the packet and fills the outgoing data
1579 buffer and marks the packet ready to be sent to network. However, If
1580 argument force_send is TRUE the packet is sent immediately and not put
1581 to queue. Normal case is that the packet is not sent immediately.
1582 Destination information is sent as argument for this function. */
1584 void silc_server_packet_send_dest(SilcServer server,
1585 SilcSocketConnection sock,
1586 SilcPacketType type,
1587 SilcPacketFlags flags,
1589 SilcIdType dst_id_type,
1590 unsigned char *data,
1591 unsigned int data_len,
1594 SilcPacketContext packetdata;
1595 SilcCipher cipher = NULL;
1596 SilcHmac hmac = NULL;
1597 unsigned char *dst_id_data = NULL;
1598 unsigned int dst_id_len = 0;
1600 SILC_LOG_DEBUG(("Sending packet, type %d", type));
1602 /* Get data used in the packet sending, keys and stuff */
1603 switch(sock->type) {
1604 case SILC_SOCKET_TYPE_CLIENT:
1605 if (sock->user_data) {
1606 cipher = ((SilcClientEntry)sock->user_data)->send_key;
1607 hmac = ((SilcClientEntry)sock->user_data)->hmac;
1610 case SILC_SOCKET_TYPE_SERVER:
1611 case SILC_SOCKET_TYPE_ROUTER:
1612 if (sock->user_data) {
1613 cipher = ((SilcServerEntry)sock->user_data)->send_key;
1614 hmac = ((SilcServerEntry)sock->user_data)->hmac;
1618 if (sock->user_data) {
1619 /* We don't know what type of connection this is thus it must
1620 be in authentication phase. */
1621 cipher = ((SilcUnknownEntry)sock->user_data)->send_key;
1622 hmac = ((SilcUnknownEntry)sock->user_data)->hmac;
1628 dst_id_data = silc_id_id2str(dst_id, dst_id_type);
1629 dst_id_len = silc_id_get_len(dst_id_type);
1632 /* Set the packet context pointers */
1633 packetdata.type = type;
1634 packetdata.flags = flags;
1635 packetdata.src_id = silc_id_id2str(server->id, server->id_type);
1636 packetdata.src_id_len = SILC_ID_SERVER_LEN;
1637 packetdata.src_id_type = server->id_type;
1638 packetdata.dst_id = dst_id_data;
1639 packetdata.dst_id_len = dst_id_len;
1640 packetdata.dst_id_type = dst_id_type;
1641 packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
1642 packetdata.src_id_len + dst_id_len;
1643 packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
1644 packetdata.rng = server->rng;
1646 /* Prepare outgoing data buffer for packet sending */
1647 silc_packet_send_prepare(sock,
1648 SILC_PACKET_HEADER_LEN +
1649 packetdata.src_id_len +
1650 packetdata.dst_id_len,
1654 SILC_LOG_DEBUG(("Putting data to outgoing buffer, len %d", data_len));
1656 packetdata.buffer = sock->outbuf;
1658 /* Put the data to the buffer */
1659 if (data && data_len)
1660 silc_buffer_put(sock->outbuf, data, data_len);
1662 /* Create the outgoing packet */
1663 silc_packet_assemble(&packetdata);
1665 /* Encrypt the packet */
1667 silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
1669 SILC_LOG_HEXDUMP(("Outgoing packet, len %d", sock->outbuf->len),
1670 sock->outbuf->data, sock->outbuf->len);
1672 /* Now actually send the packet */
1673 silc_server_packet_send_real(server, sock, force_send);
1675 if (packetdata.src_id)
1676 silc_free(packetdata.src_id);
1677 if (packetdata.dst_id)
1678 silc_free(packetdata.dst_id);
1681 /* Forwards packet. Packets sent with this function will be marked as
1682 forwarded (in the SILC header flags) so that the receiver knows that
1683 we have forwarded the packet to it. Forwarded packets are handled
1684 specially by the receiver as they are not destined to the receiver
1685 originally. However, the receiver knows this because the forwarded
1686 flag has been set (and the flag is authenticated). */
1688 void silc_server_packet_forward(SilcServer server,
1689 SilcSocketConnection sock,
1690 unsigned char *data, unsigned int data_len,
1693 SilcCipher cipher = NULL;
1694 SilcHmac hmac = NULL;
1696 SILC_LOG_DEBUG(("Forwarding packet"));
1698 /* Get data used in the packet sending, keys and stuff */
1699 switch(sock->type) {
1700 case SILC_SOCKET_TYPE_CLIENT:
1701 if (sock->user_data) {
1702 cipher = ((SilcClientEntry )sock->user_data)->send_key;
1703 hmac = ((SilcClientEntry )sock->user_data)->hmac;
1706 case SILC_SOCKET_TYPE_SERVER:
1707 case SILC_SOCKET_TYPE_ROUTER:
1708 if (sock->user_data) {
1709 cipher = ((SilcServerEntry )sock->user_data)->send_key;
1710 hmac = ((SilcServerEntry )sock->user_data)->hmac;
1714 /* We won't forward to unknown destination - keys must exist with
1715 the destination before forwarding. */
1719 /* Prepare outgoing data buffer for packet sending */
1720 silc_packet_send_prepare(sock, 0, 0, data_len);
1722 /* Mungle the packet flags and add the FORWARDED flag */
1724 data[2] |= (unsigned char)SILC_PACKET_FLAG_FORWARDED;
1726 /* Put the data to the buffer */
1727 if (data && data_len)
1728 silc_buffer_put(sock->outbuf, data, data_len);
1730 /* Encrypt the packet */
1732 silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
1734 SILC_LOG_HEXDUMP(("Forwarded packet, len %d", sock->outbuf->len),
1735 sock->outbuf->data, sock->outbuf->len);
1737 /* Now actually send the packet */
1738 silc_server_packet_send_real(server, sock, force_send);
1741 /* Internal routine to actually create the channel packet and send it
1742 to network. This is common function in channel message sending. If
1743 `channel_message' is TRUE this encrypts the message as it is strictly
1744 a channel message. If FALSE normal encryption process is used. */
1747 silc_server_packet_send_to_channel_real(SilcServer server,
1748 SilcSocketConnection sock,
1749 SilcPacketContext *packet,
1752 unsigned char *data,
1753 unsigned int data_len,
1754 int channel_message,
1757 packet->truelen = data_len + SILC_PACKET_HEADER_LEN +
1758 packet->src_id_len + packet->dst_id_len;
1760 /* Prepare outgoing data buffer for packet sending */
1761 silc_packet_send_prepare(sock,
1762 SILC_PACKET_HEADER_LEN +
1763 packet->src_id_len +
1768 packet->buffer = sock->outbuf;
1770 /* Put the data to buffer, assemble and encrypt the packet. The packet
1771 is encrypted with normal session key shared with the client. */
1772 silc_buffer_put(sock->outbuf, data, data_len);
1773 silc_packet_assemble(packet);
1774 if (channel_message)
1775 silc_packet_encrypt(cipher, hmac, sock->outbuf, SILC_PACKET_HEADER_LEN +
1776 packet->src_id_len + packet->dst_id_len +
1779 silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
1781 SILC_LOG_HEXDUMP(("Channel packet, len %d", sock->outbuf->len),
1782 sock->outbuf->data, sock->outbuf->len);
1784 /* Now actually send the packet */
1785 silc_server_packet_send_real(server, sock, force_send);
1788 /* This routine is used by the server to send packets to channel. The
1789 packet sent with this function is distributed to all clients on
1790 the channel. Usually this is used to send notify messages to the
1791 channel, things like notify about new user joining to the channel. */
1793 void silc_server_packet_send_to_channel(SilcServer server,
1794 SilcChannelEntry channel,
1795 SilcPacketType type,
1796 unsigned char *data,
1797 unsigned int data_len,
1800 SilcSocketConnection sock = NULL;
1801 SilcPacketContext packetdata;
1802 SilcClientEntry client = NULL;
1803 SilcServerEntry *routed = NULL;
1804 SilcChannelClientEntry chl;
1805 unsigned int routed_count = 0;
1809 /* This doesn't send channel message packets */
1810 if (type == SILC_PACKET_CHANNEL_MESSAGE)
1813 SILC_LOG_DEBUG(("Sending packet to channel"));
1815 /* Set the packet context pointers. */
1816 packetdata.flags = 0;
1817 packetdata.type = type;
1818 packetdata.src_id = silc_id_id2str(server->id, SILC_ID_SERVER);
1819 packetdata.src_id_len = SILC_ID_SERVER_LEN;
1820 packetdata.src_id_type = SILC_ID_SERVER;
1821 packetdata.dst_id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
1822 packetdata.dst_id_len = SILC_ID_CHANNEL_LEN;
1823 packetdata.dst_id_type = SILC_ID_CHANNEL;
1824 packetdata.rng = server->rng;
1825 packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
1826 packetdata.src_id_len + packetdata.dst_id_len;
1827 packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
1829 /* If there are global users in the channel we will send the message
1830 first to our router for further routing. */
1831 if (server->server_type == SILC_SERVER && !server->standalone &&
1832 channel->global_users) {
1833 SilcServerEntry router;
1835 /* Get data used in packet header encryption, keys and stuff. */
1836 router = server->id_entry->router;
1837 sock = (SilcSocketConnection)router->connection;
1838 cipher = router->send_key;
1839 hmac = router->hmac;
1841 SILC_LOG_DEBUG(("Sending channel message to router for routing"));
1843 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1845 data_len, FALSE, force_send);
1848 /* Send the message to clients on the channel's client list. */
1849 silc_list_start(channel->user_list);
1850 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
1851 client = chl->client;
1853 /* If client has router set it is not locally connected client and
1854 we will route the message to the router set in the client. */
1855 if (client && client->router && server->server_type == SILC_ROUTER) {
1858 /* Check if we have sent the packet to this route already */
1859 for (k = 0; k < routed_count; k++)
1860 if (routed[k] == client->router)
1862 if (k < routed_count)
1865 /* Get data used in packet header encryption, keys and stuff. */
1866 sock = (SilcSocketConnection)client->router->connection;
1867 cipher = client->router->send_key;
1868 hmac = client->router->hmac;
1870 /* Send the packet */
1871 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1873 data_len, FALSE, force_send);
1875 /* We want to make sure that the packet is routed to same router
1876 only once. Mark this route as sent route. */
1878 routed = silc_realloc(routed, sizeof(*routed) * (k + 1));
1879 routed[k] = client->router;
1885 /* Send to locally connected client */
1888 /* Get data used in packet header encryption, keys and stuff. */
1889 sock = (SilcSocketConnection)client->connection;
1890 cipher = client->send_key;
1891 hmac = client->hmac;
1893 /* Send the packet */
1894 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1896 data_len, FALSE, force_send);
1902 silc_free(packetdata.src_id);
1903 silc_free(packetdata.dst_id);
1906 /* This routine is explicitly used to relay messages to some channel.
1907 Packets sent with this function we have received earlier and are
1908 totally encrypted. This just sends the packet to all clients on
1909 the channel. If the sender of the packet is someone on the channel
1910 the message will not be sent to that client. The SILC Packet header
1911 is encrypted with the session key shared between us and the client.
1912 MAC is also computed before encrypting the header. Rest of the
1913 packet will be untouched. */
1915 void silc_server_packet_relay_to_channel(SilcServer server,
1916 SilcSocketConnection sender_sock,
1917 SilcChannelEntry channel,
1919 SilcIdType sender_type,
1920 unsigned char *data,
1921 unsigned int data_len,
1925 SilcSocketConnection sock = NULL;
1926 SilcPacketContext packetdata;
1927 SilcClientEntry client = NULL;
1928 SilcServerEntry *routed = NULL;
1929 SilcChannelClientEntry chl;
1930 unsigned int routed_count = 0;
1934 SILC_LOG_DEBUG(("Relaying packet to channel"));
1936 /* Set the packet context pointers. */
1937 packetdata.flags = 0;
1938 packetdata.type = SILC_PACKET_CHANNEL_MESSAGE;
1939 packetdata.src_id = silc_id_id2str(sender, sender_type);
1940 packetdata.src_id_len = silc_id_get_len(sender_type);
1941 packetdata.src_id_type = sender_type;
1942 packetdata.dst_id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
1943 packetdata.dst_id_len = SILC_ID_CHANNEL_LEN;
1944 packetdata.dst_id_type = SILC_ID_CHANNEL;
1945 packetdata.rng = server->rng;
1946 packetdata.padlen = SILC_PACKET_PADLEN((SILC_PACKET_HEADER_LEN +
1947 packetdata.src_id_len +
1948 packetdata.dst_id_len));
1950 /* If there are global users in the channel we will send the message
1951 first to our router for further routing. */
1952 if (server->server_type == SILC_SERVER && !server->standalone &&
1953 channel->global_users) {
1954 SilcServerEntry router;
1956 router = server->id_entry->router;
1958 /* Check that the sender is not our router. */
1959 if (sender_sock != (SilcSocketConnection)router->connection) {
1961 /* Get data used in packet header encryption, keys and stuff. */
1962 sock = (SilcSocketConnection)router->connection;
1963 cipher = router->send_key;
1964 hmac = router->hmac;
1966 SILC_LOG_DEBUG(("Sending channel message to router for routing"));
1968 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1970 data_len, TRUE, force_send);
1974 /* Send the message to clients on the channel's client list. */
1975 silc_list_start(channel->user_list);
1976 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
1977 client = chl->client;
1981 /* If sender is one on the channel do not send it the packet. */
1982 if (!found && !SILC_ID_CLIENT_COMPARE(client->id, sender)) {
1987 /* If the client has set router it means that it is not locally
1988 connected client and we will route the packet further. */
1989 if (server->server_type == SILC_ROUTER && client->router) {
1992 /* Sender maybe server as well so we want to make sure that
1993 we won't send the message to the server it came from. */
1994 if (!found && !SILC_ID_SERVER_COMPARE(client->router->id, sender)) {
1999 /* Check if we have sent the packet to this route already */
2000 for (k = 0; k < routed_count; k++)
2001 if (routed[k] == client->router)
2003 if (k < routed_count)
2006 /* Get data used in packet header encryption, keys and stuff. */
2007 sock = (SilcSocketConnection)client->router->connection;
2008 cipher = client->router->send_key;
2009 hmac = client->router->hmac;
2011 /* Send the packet */
2012 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
2014 data_len, TRUE, force_send);
2016 /* We want to make sure that the packet is routed to same router
2017 only once. Mark this route as sent route. */
2019 routed = silc_realloc(routed, sizeof(*routed) * (k + 1));
2020 routed[k] = client->router;
2026 /* XXX Check client's mode on the channel. */
2028 /* Get data used in packet header encryption, keys and stuff. */
2029 sock = (SilcSocketConnection)client->connection;
2030 cipher = client->send_key;
2031 hmac = client->hmac;
2033 SILC_LOG_DEBUG(("Sending packet to client %s",
2034 sock->hostname ? sock->hostname : sock->ip));
2036 /* Send the packet */
2037 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
2039 data_len, TRUE, force_send);
2043 silc_free(packetdata.src_id);
2044 silc_free(packetdata.dst_id);
2047 /* This function is used to send packets strictly to all local clients
2048 on a particular channel. This is used for example to distribute new
2049 channel key to all our locally connected clients on the channel.
2050 The packets are always encrypted with the session key shared between
2051 the client, this means these are not _to the channel_ but _to the client_
2054 void silc_server_packet_send_local_channel(SilcServer server,
2055 SilcChannelEntry channel,
2056 SilcPacketType type,
2057 SilcPacketFlags flags,
2058 unsigned char *data,
2059 unsigned int data_len,
2062 SilcClientEntry client;
2063 SilcChannelClientEntry chl;
2064 SilcSocketConnection sock = NULL;
2066 SILC_LOG_DEBUG(("Start"));
2068 /* Send the message to clients on the channel's client list. */
2069 silc_list_start(channel->user_list);
2070 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2071 client = chl->client;
2074 sock = (SilcSocketConnection)client->connection;
2076 /* Send the packet to the client */
2077 silc_server_packet_send_dest(server, sock, type, flags, client->id,
2078 SILC_ID_CLIENT, data, data_len,
2084 /* Relays received command reply packet to the correct destination. The
2085 destination must be one of our locally connected client or the packet
2086 will be ignored. This is called when server has forwarded one of
2087 client's command request to router and router has now replied to the
2090 void silc_server_packet_relay_command_reply(SilcServer server,
2091 SilcSocketConnection sock,
2092 SilcPacketContext *packet)
2094 SilcBuffer buffer = packet->buffer;
2095 SilcClientEntry client;
2097 SilcSocketConnection dst_sock;
2099 SILC_LOG_DEBUG(("Start"));
2101 /* Source must be server or router */
2102 if (packet->src_id_type != SILC_ID_SERVER &&
2103 sock->type != SILC_SOCKET_TYPE_ROUTER)
2106 /* Destination must be client */
2107 if (packet->dst_id_type != SILC_ID_CLIENT)
2110 /* Execute command reply locally for the command */
2111 silc_server_command_reply_process(server, sock, buffer);
2113 id = silc_id_str2id(packet->dst_id, SILC_ID_CLIENT);
2115 /* Destination must be one of ours */
2116 client = silc_idlist_find_client_by_id(server->local_list, id);
2122 /* Relay the packet to the client */
2124 dst_sock = (SilcSocketConnection)client->connection;
2125 silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len
2126 + packet->dst_id_len + packet->padlen);
2128 silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
2129 silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
2131 /* Encrypt packet */
2132 if (client && client->send_key)
2133 silc_packet_encrypt(client->send_key, client->hmac,
2134 dst_sock->outbuf, buffer->len);
2136 /* Send the packet */
2137 silc_server_packet_send_real(server, dst_sock, FALSE);
2142 silc_buffer_free(buffer);
2145 /* Closes connection to socket connection */
2147 void silc_server_close_connection(SilcServer server,
2148 SilcSocketConnection sock)
2151 SILC_LOG_DEBUG(("Closing connection %d", sock->sock));
2153 /* We won't listen for this connection anymore */
2154 silc_schedule_unset_listen_fd(sock->sock);
2156 /* Unregister all tasks */
2157 silc_task_unregister_by_fd(server->io_queue, sock->sock);
2158 silc_task_unregister_by_fd(server->timeout_queue, sock->sock);
2160 /* Close the actual connection */
2161 silc_net_close_connection(sock->sock);
2162 server->sockets[sock->sock] = NULL;
2163 silc_socket_free(sock);
2166 /* Sends disconnect message to remote connection and disconnects the
2169 void silc_server_disconnect_remote(SilcServer server,
2170 SilcSocketConnection sock,
2171 const char *fmt, ...)
2174 unsigned char buf[4096];
2176 memset(buf, 0, sizeof(buf));
2178 vsprintf(buf, fmt, ap);
2181 SILC_LOG_DEBUG(("Disconnecting remote host"));
2183 /* Notify remote end that the conversation is over. The notify message
2184 is tried to be sent immediately. */
2185 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2186 buf, strlen(buf), TRUE);
2188 /* Mark the connection to be disconnected */
2189 SILC_SET_DISCONNECTED(sock);
2190 silc_server_close_connection(server, sock);
2193 /* Free's user_data pointer from socket connection object. As this
2194 pointer maybe anything we wil switch here to find the correct
2195 data type and free it the way it needs to be free'd. */
2197 void silc_server_free_sock_user_data(SilcServer server,
2198 SilcSocketConnection sock)
2200 SILC_LOG_DEBUG(("Start"));
2202 switch(sock->type) {
2203 case SILC_SOCKET_TYPE_CLIENT:
2205 SilcClientEntry user_data = (SilcClientEntry )sock->user_data;
2207 /* Remove client from all channels */
2208 silc_server_remove_from_channels(server, sock, user_data);
2210 /* Free the client entry and everything in it */
2211 /* XXX must take some info to history before freeing */
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 if (user_data->send_key)
2227 silc_cipher_free(user_data->send_key);
2228 if (user_data->receive_key)
2229 silc_cipher_free(user_data->receive_key);
2230 if (user_data->pkcs)
2231 silc_pkcs_free(user_data->pkcs);
2232 if (user_data->hmac) {
2233 silc_hmac_free(user_data->hmac);
2234 memset(user_data->hmac_key, 0, user_data->hmac_key_len);
2235 silc_free(user_data->hmac_key);
2237 silc_free(user_data);
2242 sock->user_data = NULL;
2247 /* Removes client from all channels it has joined. This is used when
2248 client connection is disconnected. If the client on a channel
2249 is last, the channel is removed as well. */
2251 void silc_server_remove_from_channels(SilcServer server,
2252 SilcSocketConnection sock,
2253 SilcClientEntry client)
2255 SilcChannelEntry channel;
2256 SilcChannelClientEntry chl;
2257 SilcBuffer chidp, clidp;
2259 SILC_LOG_DEBUG(("Start"));
2261 if (!client || !client->id)
2264 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2266 /* Remove the client from all channels. The client is removed from
2267 the channels' user list. */
2268 silc_list_start(client->channels);
2269 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2270 channel = chl->channel;
2271 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
2273 /* Remove from list */
2274 silc_list_del(client->channels, chl);
2276 /* If this client is last one on the channel the channel
2277 is removed all together. */
2278 if (silc_list_count(channel->user_list) < 2) {
2280 /* However, if the channel has marked global users then the
2281 channel is not created locally, and this does not remove the
2282 channel globally from SILC network, in this case we will
2283 notify that this client has left the channel. */
2284 if (channel->global_users)
2285 silc_server_send_notify_to_channel(server, channel,
2286 SILC_NOTIFY_TYPE_SIGNOFF, 1,
2287 clidp->data, clidp->len);
2289 silc_idlist_del_channel(server->local_list, channel);
2293 /* Remove from list */
2294 silc_list_del(channel->user_list, chl);
2297 /* Send notify to channel about client leaving SILC and thus
2298 the entire channel. */
2299 silc_server_send_notify_to_channel(server, channel,
2300 SILC_NOTIFY_TYPE_SIGNOFF, 1,
2301 clidp->data, clidp->len);
2302 silc_buffer_free(chidp);
2305 silc_buffer_free(clidp);
2308 /* Removes client from one channel. This is used for example when client
2309 calls LEAVE command to remove itself from the channel. Returns TRUE
2310 if channel still exists and FALSE if the channel is removed when
2311 last client leaves the channel. If `notify' is FALSE notify messages
2314 int silc_server_remove_from_one_channel(SilcServer server,
2315 SilcSocketConnection sock,
2316 SilcChannelEntry channel,
2317 SilcClientEntry client,
2320 SilcChannelEntry ch;
2321 SilcChannelClientEntry chl;
2324 SILC_LOG_DEBUG(("Start"));
2326 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2328 /* Remove the client from the channel. The client is removed from
2329 the channel's user list. */
2330 silc_list_start(client->channels);
2331 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2332 if (chl->channel != channel)
2337 /* Remove from list */
2338 silc_list_del(client->channels, chl);
2340 /* If this client is last one on the channel the channel
2341 is removed all together. */
2342 if (silc_list_count(channel->user_list) < 2) {
2343 /* Notify about leaving client if this channel has global users,
2344 ie. the channel is not created locally. */
2345 if (notify && channel->global_users)
2346 silc_server_send_notify_to_channel(server, channel,
2347 SILC_NOTIFY_TYPE_LEAVE, 1,
2348 clidp->data, clidp->len);
2350 silc_idlist_del_channel(server->local_list, channel);
2351 silc_buffer_free(clidp);
2355 /* Remove from list */
2356 silc_list_del(channel->user_list, chl);
2359 /* Send notify to channel about client leaving the channel */
2361 silc_server_send_notify_to_channel(server, channel,
2362 SILC_NOTIFY_TYPE_LEAVE, 1,
2363 clidp->data, clidp->len);
2367 silc_buffer_free(clidp);
2371 /* Returns TRUE if the given client is on the channel. FALSE if not.
2372 This works because we assure that the user list on the channel is
2373 always in up to date thus we can only check the channel list from
2374 `client' which is faster than checking the user list from `channel'. */
2376 int silc_server_client_on_channel(SilcClientEntry client,
2377 SilcChannelEntry channel)
2379 SilcChannelClientEntry chl;
2381 if (!client || !channel)
2384 silc_list_start(client->channels);
2385 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END)
2386 if (chl->channel == channel)
2392 /* Timeout callback. This is called if connection is idle or for some
2393 other reason is not responding within some period of time. This
2394 disconnects the remote end. */
2396 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2398 SilcServer server = (SilcServer)context;
2399 SilcSocketConnection sock = server->sockets[fd];
2401 silc_server_disconnect_remote(server, sock,
2402 "Server closed connection: "
2403 "Connection timeout");
2406 /* Internal routine used to send (relay, route) private messages to some
2407 destination. If the private message key does not exist then the message
2408 is re-encrypted, otherwise we just pass it along. */
2411 silc_server_private_message_send_internal(SilcServer server,
2412 SilcSocketConnection dst_sock,
2415 SilcPacketContext *packet)
2417 SilcBuffer buffer = packet->buffer;
2419 /* Send and re-encrypt if private messge key does not exist */
2420 if ((packet->flags & SILC_PACKET_FLAG_PRIVMSG_KEY) == FALSE) {
2422 silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len
2423 + packet->dst_id_len + packet->padlen);
2424 silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
2425 silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
2427 /* Re-encrypt packet */
2428 silc_packet_encrypt(cipher, hmac, dst_sock->outbuf, buffer->len);
2430 /* Send the packet */
2431 silc_server_packet_send_real(server, dst_sock, FALSE);
2434 /* Key exist so just send it */
2435 silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len
2436 + packet->dst_id_len + packet->padlen);
2437 silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
2438 silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
2439 silc_server_packet_send_real(server, dst_sock, FALSE);
2443 /* Received private message. This resolves the destination of the message
2444 and sends the packet. This is used by both server and router. If the
2445 destination is our locally connected client this sends the packet to
2446 the client. This may also send the message for further routing if
2447 the destination is not in our server (or router). */
2449 void silc_server_private_message(SilcServer server,
2450 SilcSocketConnection sock,
2451 SilcPacketContext *packet)
2453 SilcBuffer buffer = packet->buffer;
2455 SilcServerEntry router;
2456 SilcSocketConnection dst_sock;
2457 SilcClientEntry client;
2459 SILC_LOG_DEBUG(("Start"));
2461 if (!packet->dst_id) {
2462 SILC_LOG_ERROR(("Bad Client ID in private message packet, dropped"));
2466 /* Decode destination Client ID */
2467 id = silc_id_str2id(packet->dst_id, SILC_ID_CLIENT);
2469 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
2473 /* If the destination belongs to our server we don't have to route
2474 the message anywhere but to send it to the local destination. */
2475 client = silc_idlist_find_client_by_id(server->local_list, id);
2477 /* It exists, now deliver the message to the destination */
2478 dst_sock = (SilcSocketConnection)client->connection;
2480 /* If we are router and the client has router then the client is in
2481 our cell but not directly connected to us. */
2482 if (server->server_type == SILC_ROUTER && client->router) {
2483 /* We are of course in this case the client's router thus the real
2484 "router" of the client is the server who owns the client. Thus
2485 we will send the packet to that server. */
2486 router = (SilcServerEntry)dst_sock->user_data;
2487 // assert(client->router == server->id_entry);
2489 silc_server_private_message_send_internal(server, dst_sock,
2496 /* Seems that client really is directly connected to us */
2497 silc_server_private_message_send_internal(server, dst_sock,
2499 client->hmac, packet);
2503 /* Destination belongs to someone not in this server. If we are normal
2504 server our action is to send the packet to our router. */
2505 if (server->server_type == SILC_SERVER && !server->standalone) {
2506 router = server->id_entry->router;
2508 /* Send to primary route */
2510 dst_sock = (SilcSocketConnection)router->connection;
2511 silc_server_private_message_send_internal(server, dst_sock,
2513 router->hmac, packet);
2518 /* We are router and we will perform route lookup for the destination
2519 and send the message to fastest route. */
2520 if (server->server_type == SILC_ROUTER && !server->standalone) {
2521 dst_sock = silc_server_get_route(server, id, SILC_ID_CLIENT);
2522 router = (SilcServerEntry)dst_sock->user_data;
2524 /* Get fastest route and send packet. */
2526 silc_server_private_message_send_internal(server, dst_sock,
2528 router->hmac, packet);
2534 silc_server_send_error(server, sock,
2535 "No such nickname: Private message not sent");
2537 silc_buffer_free(buffer);
2540 /* Process received channel message. The message can be originated from
2541 client or server. */
2543 void silc_server_channel_message(SilcServer server,
2544 SilcSocketConnection sock,
2545 SilcPacketContext *packet)
2547 SilcChannelEntry channel = NULL;
2548 SilcChannelClientEntry chl;
2549 SilcChannelID *id = NULL;
2550 void *sender = NULL;
2551 SilcBuffer buffer = packet->buffer;
2553 SILC_LOG_DEBUG(("Processing channel message"));
2556 if (packet->dst_id_type != SILC_ID_CHANNEL) {
2557 SILC_LOG_ERROR(("Received bad message for channel, dropped"));
2558 SILC_LOG_DEBUG(("Received bad message for channel, dropped"));
2562 /* Find channel entry */
2563 id = silc_id_str2id(packet->dst_id, SILC_ID_CHANNEL);
2564 channel = silc_idlist_find_channel_by_id(server->local_list, id);
2566 SILC_LOG_DEBUG(("Could not find channel"));
2570 /* See that this client is on the channel. If the message is coming
2571 from router we won't do the check as the message is from client that
2572 we don't know about. Also, if the original sender is not client
2573 (as it can be server as well) we don't do the check. */
2574 sender = silc_id_str2id(packet->src_id, packet->src_id_type);
2575 if (sock->type != SILC_SOCKET_TYPE_ROUTER &&
2576 packet->src_id_type == SILC_ID_CLIENT) {
2577 silc_list_start(channel->user_list);
2578 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2579 if (chl->client && !SILC_ID_CLIENT_COMPARE(chl->client->id, sender))
2582 if (chl == SILC_LIST_END)
2586 /* Distribute the packet to our local clients. This will send the
2587 packet for further routing as well, if needed. */
2588 silc_server_packet_relay_to_channel(server, sock, channel, sender,
2589 packet->src_id_type,
2590 packet->buffer->data,
2591 packet->buffer->len, FALSE);
2598 silc_buffer_free(buffer);
2601 /* Received channel key packet. We distribute the key to all of our locally
2602 connected clients on the channel. */
2603 /* XXX Router must accept this packet and distribute the key to all its
2604 server that has clients on the channel */
2606 void silc_server_channel_key(SilcServer server,
2607 SilcSocketConnection sock,
2608 SilcPacketContext *packet)
2610 SilcBuffer buffer = packet->buffer;
2611 SilcChannelKeyPayload payload = NULL;
2612 SilcChannelID *id = NULL;
2613 SilcChannelEntry channel;
2614 SilcChannelClientEntry chl;
2615 SilcClientEntry client;
2617 unsigned int tmp_len;
2620 if (packet->src_id_type != SILC_ID_SERVER &&
2621 sock->type != SILC_SOCKET_TYPE_ROUTER)
2624 /* Decode channel key payload */
2625 payload = silc_channel_key_payload_parse(buffer);
2627 SILC_LOG_ERROR(("Bad channel key payload, dropped"));
2631 /* Get channel ID */
2632 tmp = silc_channel_key_get_id(payload, &tmp_len);
2633 id = silc_id_payload_parse_id(tmp, tmp_len);
2637 /* Get the channel entry */
2638 channel = silc_idlist_find_channel_by_id(server->local_list, id);
2640 SILC_LOG_ERROR(("Received key for non-existent channel"));
2644 /* Save the key for us as well */
2645 tmp = silc_channel_key_get_key(payload, &tmp_len);
2648 cipher = silc_channel_key_get_cipher(payload, NULL);;
2651 if (!silc_cipher_alloc(cipher, &channel->channel_key))
2654 channel->key_len = tmp_len * 8;
2655 channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
2656 memcpy(channel->key, tmp, tmp_len);
2657 channel->channel_key->cipher->set_key(channel->channel_key->context,
2660 /* Distribute the key to all clients on the channel */
2661 /* XXX Some other sender should be used, I think this is not correct */
2662 silc_list_start(channel->user_list);
2663 while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2664 client = chl->client;
2667 silc_server_packet_send_dest(server, client->connection,
2668 SILC_PACKET_CHANNEL_KEY, 0,
2669 client->id, SILC_ID_CLIENT,
2670 buffer->data, buffer->len, FALSE);
2677 silc_channel_key_payload_free(payload);
2678 silc_buffer_free(buffer);
2681 /* Sends current motd to client */
2683 void silc_server_send_motd(SilcServer server,
2684 SilcSocketConnection sock)
2689 if (server->config && server->config->motd &&
2690 server->config->motd->motd_file) {
2692 motd = silc_file_read(server->config->motd->motd_file, &motd_len);
2696 silc_server_send_notify(server, sock, SILC_NOTIFY_TYPE_MOTD, 1,
2702 /* Sends error message. Error messages may or may not have any
2705 void silc_server_send_error(SilcServer server,
2706 SilcSocketConnection sock,
2707 const char *fmt, ...)
2710 unsigned char buf[4096];
2712 memset(buf, 0, sizeof(buf));
2714 vsprintf(buf, fmt, ap);
2717 silc_server_packet_send(server, sock, SILC_PACKET_ERROR, 0,
2718 buf, strlen(buf), FALSE);
2721 /* Sends notify message. If format is TRUE the variable arguments are
2722 formatted and the formatted string is sent as argument payload. If it is
2723 FALSE then each argument is sent as separate argument and their format
2724 in the argument list must be { argument data, argument length }. */
2726 void silc_server_send_notify(SilcServer server,
2727 SilcSocketConnection sock,
2728 SilcNotifyType type,
2729 unsigned int argc, ...)
2736 packet = silc_notify_payload_encode(type, argc, ap);
2737 silc_server_packet_send(server, sock, SILC_PACKET_NOTIFY, 0,
2738 packet->data, packet->len, FALSE);
2739 silc_buffer_free(packet);
2742 /* Sends notify message destined to specific entity. */
2744 void silc_server_send_notify_dest(SilcServer server,
2745 SilcSocketConnection sock,
2747 SilcIdType dest_id_type,
2748 SilcNotifyType type,
2749 unsigned int argc, ...)
2756 packet = silc_notify_payload_encode(type, argc, ap);
2757 silc_server_packet_send_dest(server, sock, SILC_PACKET_NOTIFY, 0,
2758 dest_id, dest_id_type,
2759 packet->data, packet->len, FALSE);
2760 silc_buffer_free(packet);
2763 /* Sends notify message to a channel. The notify message sent is
2764 distributed to all clients on the channel. */
2766 void silc_server_send_notify_to_channel(SilcServer server,
2767 SilcChannelEntry channel,
2768 SilcNotifyType type,
2769 unsigned int argc, ...)
2776 packet = silc_notify_payload_encode(type, argc, ap);
2777 silc_server_packet_send_to_channel(server, channel,
2779 packet->data, packet->len, FALSE);
2780 silc_buffer_free(packet);
2783 /* Send notify message to all clients the client has joined. It is quaranteed
2784 that the message is sent only once to a client (ie. if a client is joined
2785 on two same channel it will receive only one notify message). Also, this
2786 sends only to local clients (locally connected if we are server, and to
2787 local servers if we are router). */
2789 void silc_server_send_notify_on_channels(SilcServer server,
2790 SilcClientEntry client,
2791 SilcNotifyType type,
2792 unsigned int argc, ...)
2795 SilcSocketConnection sock = NULL;
2796 SilcPacketContext packetdata;
2798 SilcClientEntry *sent_clients = NULL;
2799 unsigned int sent_clients_count = 0;
2800 SilcServerEntry *routed = NULL;
2801 unsigned int routed_count = 0;
2802 SilcChannelEntry channel;
2803 SilcChannelClientEntry chl, chl2;
2807 unsigned char *data;
2808 unsigned int data_len;
2809 int force_send = FALSE;
2812 if (!silc_list_count(client->channels))
2816 packet = silc_notify_payload_encode(type, argc, ap);
2817 data = packet->data;
2818 data_len = packet->len;
2820 /* Set the packet context pointers. */
2821 packetdata.flags = 0;
2822 packetdata.type = SILC_PACKET_NOTIFY;
2823 packetdata.src_id = silc_id_id2str(server->id, SILC_ID_SERVER);
2824 packetdata.src_id_len = SILC_ID_SERVER_LEN;
2825 packetdata.src_id_type = SILC_ID_SERVER;
2826 packetdata.rng = server->rng;
2828 silc_list_start(client->channels);
2829 while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2830 channel = chl->channel;
2832 /* Send the message to all clients on the channel's client list. */
2833 silc_list_start(channel->user_list);
2834 while ((chl2 = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2837 /* Check if we have sent the packet to this client already */
2838 for (k = 0; k < sent_clients_count; k++)
2839 if (sent_clients[k] == c)
2841 if (k < sent_clients_count)
2844 /* If we are router and if this client has router set it is not
2845 locally connected client and we will route the message to the
2846 router set in the client. */
2847 if (c && c->router && server->server_type == SILC_ROUTER) {
2848 /* Check if we have sent the packet to this route already */
2849 for (k = 0; k < routed_count; k++)
2850 if (routed[k] == c->router)
2852 if (k < routed_count)
2855 /* Get data used in packet header encryption, keys and stuff. */
2856 sock = (SilcSocketConnection)c->router->connection;
2857 cipher = c->router->send_key;
2858 hmac = c->router->hmac;
2860 packetdata.dst_id = silc_id_id2str(c->router->id, SILC_ID_SERVER);
2861 packetdata.dst_id_len = SILC_ID_SERVER_LEN;
2862 packetdata.dst_id_type = SILC_ID_SERVER;
2863 packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
2864 packetdata.src_id_len + packetdata.dst_id_len;
2865 packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
2867 /* Send the packet */
2868 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
2870 data_len, FALSE, force_send);
2872 silc_free(packetdata.dst_id);
2874 /* We want to make sure that the packet is routed to same router
2875 only once. Mark this route as sent route. */
2877 routed = silc_realloc(routed, sizeof(*routed) * (k + 1));
2878 routed[k] = c->router;
2884 /* Send to locally connected client */
2887 /* Get data used in packet header encryption, keys and stuff. */
2888 sock = (SilcSocketConnection)c->connection;
2889 cipher = c->send_key;
2892 packetdata.dst_id = silc_id_id2str(c->id, SILC_ID_CLIENT);
2893 packetdata.dst_id_len = SILC_ID_CLIENT_LEN;
2894 packetdata.dst_id_type = SILC_ID_CLIENT;
2895 packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
2896 packetdata.src_id_len + packetdata.dst_id_len;
2897 packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
2899 /* Send the packet */
2900 silc_server_packet_send_to_channel_real(server, sock, &packetdata,
2902 data_len, FALSE, force_send);
2904 silc_free(packetdata.dst_id);
2906 /* Make sure that we send the notify only once per client. */
2907 sent_clients = silc_realloc(sent_clients, sizeof(*sent_clients) *
2908 (sent_clients_count + 1));
2909 sent_clients[sent_clients_count] = c;
2910 sent_clients_count++;
2917 if (sent_clients_count)
2918 silc_free(sent_clients);
2919 silc_free(packetdata.src_id);
2922 /* Sends New ID Payload to remote end. The packet is used to distribute
2923 information about new registered clients, servers, channel etc. usually
2924 to routers so that they can keep these information up to date.
2925 If the argument `broadcast' is TRUE then the packet is sent as
2926 broadcast packet. */
2928 void silc_server_send_new_id(SilcServer server,
2929 SilcSocketConnection sock,
2931 void *id, SilcIdType id_type,
2932 unsigned int id_len)
2936 idp = silc_id_payload_encode(id, id_type);
2937 silc_server_packet_send(server, sock, SILC_PACKET_NEW_ID,
2938 broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
2939 idp->data, idp->len, FALSE);
2940 silc_buffer_free(idp);
2943 /* Sends Replace ID payload to remote end. This is used to replace old
2944 ID with new ID sent in the packet. This is called for example when
2945 user changes nickname and we create new ID for the user. If the
2946 argument `broadcast' is TRUE then the packet is sent as
2947 broadcast packet. */
2948 /* XXX It would be expected that the new id is same type as the old
2951 void silc_server_send_replace_id(SilcServer server,
2952 SilcSocketConnection sock,
2954 void *old_id, SilcIdType old_id_type,
2955 unsigned int old_id_len,
2956 void *new_id, SilcIdType new_id_type,
2957 unsigned int new_id_len)
2963 oid = silc_id_id2str(old_id, old_id_type);
2967 nid = silc_id_id2str(new_id, new_id_type);
2971 packet = silc_buffer_alloc(2 + 2 + 2 + 2 + old_id_len + new_id_len);
2972 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
2973 silc_buffer_format(packet,
2974 SILC_STR_UI_SHORT(old_id_type),
2975 SILC_STR_UI_SHORT(old_id_len),
2976 SILC_STR_UI_XNSTRING(oid, old_id_len),
2977 SILC_STR_UI_SHORT(new_id_type),
2978 SILC_STR_UI_SHORT(new_id_len),
2979 SILC_STR_UI_XNSTRING(nid, new_id_len),
2982 silc_server_packet_send(server, sock, SILC_PACKET_REPLACE_ID,
2983 broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
2984 packet->data, packet->len, FALSE);
2987 silc_buffer_free(packet);
2990 /* This function is used to send Remove Channel User payload. This may sent
2991 by server but is usually used only by router to notify other routers that
2992 user has left a channel. Normal server sends this packet to its router
2993 to notify that the router should not hold a record about this client
2994 on a channel anymore. Router distributes it further to other routers. */
2996 void silc_server_send_remove_channel_user(SilcServer server,
2997 SilcSocketConnection sock,
2999 void *client_id, void *channel_id)
3002 unsigned char *clid, *chid;
3004 clid = silc_id_id2str(client_id, SILC_ID_CLIENT);
3008 chid = silc_id_id2str(channel_id, SILC_ID_CHANNEL);
3012 packet = silc_buffer_alloc(2 + 2 + SILC_ID_CLIENT_LEN + SILC_ID_CHANNEL_LEN);
3013 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
3014 silc_buffer_format(packet,
3015 SILC_STR_UI_SHORT(SILC_ID_CLIENT_LEN),
3016 SILC_STR_UI_XNSTRING(clid, SILC_ID_CLIENT_LEN),
3017 SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
3018 SILC_STR_UI_XNSTRING(chid, SILC_ID_CHANNEL_LEN),
3021 silc_server_packet_send(server, sock, SILC_PACKET_REMOVE_CHANNEL_USER,
3022 broadcast ? SILC_PACKET_FLAG_BROADCAST : 0,
3023 packet->data, packet->len, FALSE);
3026 silc_buffer_free(packet);
3029 /* Received packet to replace a ID. This checks that the requested ID
3030 exists and replaces it with the new one. */
3032 void silc_server_replace_id(SilcServer server,
3033 SilcSocketConnection sock,
3034 SilcPacketContext *packet)
3036 SilcBuffer buffer = packet->buffer;
3037 unsigned char *old_id = NULL, *new_id = NULL;
3038 SilcIdType old_id_type, new_id_type;
3039 unsigned short old_id_len, new_id_len;
3040 void *id = NULL, *id2 = NULL;
3042 if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3043 packet->src_id_type == SILC_ID_CLIENT)
3046 SILC_LOG_DEBUG(("Replacing ID"));
3048 silc_buffer_unformat(buffer,
3049 SILC_STR_UI_SHORT(&old_id_type),
3050 SILC_STR_UI16_NSTRING_ALLOC(&old_id, &old_id_len),
3051 SILC_STR_UI_SHORT(&new_id_type),
3052 SILC_STR_UI16_NSTRING_ALLOC(&new_id, &new_id_len),
3055 if (old_id_type != new_id_type)
3058 if (old_id_len != silc_id_get_len(old_id_type) ||
3059 new_id_len != silc_id_get_len(new_id_type))
3062 id = silc_id_str2id(old_id, old_id_type);
3066 id2 = silc_id_str2id(new_id, new_id_type);
3070 /* Replace the old ID */
3071 switch(old_id_type) {
3072 case SILC_ID_CLIENT:
3073 if (silc_idlist_replace_client_id(server->local_list, id, id2) == NULL)
3074 if (server->server_type == SILC_ROUTER)
3075 silc_idlist_replace_client_id(server->global_list, id, id2);
3078 case SILC_ID_SERVER:
3079 if (silc_idlist_replace_server_id(server->local_list, id, id2) == NULL)
3080 if (server->server_type == SILC_ROUTER)
3081 silc_idlist_replace_server_id(server->global_list, id, id2);
3084 case SILC_ID_CHANNEL:
3085 /* XXX Hmm... Basically this cannot occur. Channel ID's cannot be
3104 /* Creates new channel. */
3106 SilcChannelEntry silc_server_new_channel(SilcServer server,
3107 SilcServerID *router_id,
3108 char *cipher, char *channel_name)
3110 int i, channel_len, key_len;
3111 SilcChannelID *channel_id;
3112 SilcChannelEntry entry;
3114 unsigned char channel_key[32], *id_string;
3117 SILC_LOG_DEBUG(("Creating new channel"));
3119 /* Create channel key */
3120 for (i = 0; i < 32; i++)
3121 channel_key[i] = silc_rng_get_byte(server->rng);
3128 silc_cipher_alloc(cipher, &key);
3129 key->cipher->set_key(key->context, channel_key, key_len);
3131 channel_name = strdup(channel_name);
3133 /* Create the channel */
3134 silc_id_create_channel_id(router_id, server->rng, &channel_id);
3135 entry = silc_idlist_add_channel(server->local_list, channel_name,
3136 SILC_CHANNEL_MODE_NONE, channel_id,
3139 silc_free(channel_name);
3143 entry->key = silc_calloc(key_len, sizeof(*entry->key));
3144 entry->key_len = key_len * 8;
3145 memcpy(entry->key, channel_key, key_len);
3146 memset(channel_key, 0, sizeof(channel_key));
3148 /* Notify other routers about the new channel. We send the packet
3149 to our primary route. */
3150 if (server->standalone == FALSE) {
3151 channel_len = strlen(channel_name);
3152 id_string = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3153 packet = silc_buffer_alloc(2 + SILC_ID_CHANNEL_LEN);
3155 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
3156 silc_buffer_format(packet,
3157 SILC_STR_UI_SHORT(channel_len),
3158 SILC_STR_UI_XNSTRING(channel_name, channel_len),
3159 SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
3160 SILC_STR_UI_XNSTRING(id_string, SILC_ID_CHANNEL_LEN),
3163 /* Send the packet to our router. */
3164 silc_server_packet_send(server, (SilcSocketConnection)
3165 server->id_entry->router->connection,
3166 SILC_PACKET_NEW_CHANNEL_USER, 0,
3167 packet->data, packet->len, TRUE);
3169 silc_free(id_string);
3170 silc_buffer_free(packet);
3176 /* Create new client. This processes incoming NEW_CLIENT packet and creates
3177 Client ID for the client. Client becomes registered after calling this
3180 SilcClientEntry silc_server_new_client(SilcServer server,
3181 SilcSocketConnection sock,
3182 SilcPacketContext *packet)
3184 SilcBuffer buffer = packet->buffer;
3185 SilcClientEntry client;
3186 SilcIDCacheEntry cache;
3187 SilcClientID *client_id;
3189 char *username = NULL, *realname = NULL, *id_string;
3191 SILC_LOG_DEBUG(("Creating new client"));
3193 if (sock->type != SILC_SOCKET_TYPE_CLIENT)
3196 /* Take client entry */
3197 client = (SilcClientEntry)sock->user_data;
3199 /* Fetch the old client cache entry so that we can update it. */
3200 if (!silc_idcache_find_by_context(server->local_list->clients,
3201 sock->user_data, &cache)) {
3202 SILC_LOG_ERROR(("Lost client's cache entry - bad thing"));
3206 /* Parse incoming packet */
3207 silc_buffer_unformat(buffer,
3208 SILC_STR_UI16_STRING_ALLOC(&username),
3209 SILC_STR_UI16_STRING_ALLOC(&realname),
3212 /* Create Client ID */
3213 silc_id_create_client_id(server->id, server->rng, server->md5hash,
3214 username, &client_id);
3216 /* Update client entry */
3217 client->registered = TRUE;
3218 client->nickname = strdup(username);
3219 client->username = username;
3220 client->userinfo = realname;
3221 client->id = client_id;
3223 /* Update the cache entry */
3224 cache->id = (void *)client_id;
3225 cache->type = SILC_ID_CLIENT;
3226 cache->data = username;
3227 silc_idcache_sort_by_data(server->local_list->clients);
3229 /* Notify our router about new client on the SILC network */
3230 if (!server->standalone)
3231 silc_server_send_new_id(server, (SilcSocketConnection)
3232 server->id_entry->router->connection,
3233 server->server_type == SILC_SERVER ? TRUE : FALSE,
3234 client->id, SILC_ID_CLIENT, SILC_ID_CLIENT_LEN);
3236 /* Send the new client ID to the client. */
3237 id_string = silc_id_id2str(client->id, SILC_ID_CLIENT);
3238 reply = silc_buffer_alloc(2 + 2 + SILC_ID_CLIENT_LEN);
3239 silc_buffer_pull_tail(reply, SILC_BUFFER_END(reply));
3240 silc_buffer_format(reply,
3241 SILC_STR_UI_SHORT(SILC_ID_CLIENT),
3242 SILC_STR_UI_SHORT(SILC_ID_CLIENT_LEN),
3243 SILC_STR_UI_XNSTRING(id_string, SILC_ID_CLIENT_LEN),
3245 silc_server_packet_send(server, sock, SILC_PACKET_NEW_ID, 0,
3246 reply->data, reply->len, FALSE);
3247 silc_free(id_string);
3248 silc_buffer_free(reply);
3250 /* Send some nice info to the client */
3251 SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3252 ("Welcome to the SILC Network %s@%s",
3253 username, sock->hostname));
3254 SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3255 ("Your host is %s, running version %s",
3256 server->config->server_info->server_name,
3258 SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3259 ("Your connection is secured with %s cipher, "
3260 "key length %d bits",
3261 client->send_key->cipher->name,
3262 client->send_key->cipher->key_len));
3263 SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3264 ("Your current nickname is %s",
3268 silc_server_send_motd(server, sock);
3273 /* Create new server. This processes incoming NEW_SERVER packet and
3274 saves the received Server ID. The server is our locally connected
3275 server thus we save all the information and save it to local list.
3276 This funtion can be used by both normal server and router server.
3277 If normal server uses this it means that its router has connected
3278 to the server. If router uses this it means that one of the cell's
3279 servers is connected to the router. */
3281 SilcServerEntry silc_server_new_server(SilcServer server,
3282 SilcSocketConnection sock,
3283 SilcPacketContext *packet)
3285 SilcBuffer buffer = packet->buffer;
3286 SilcServerEntry new_server;
3287 SilcIDCacheEntry cache;
3288 SilcServerID *server_id;
3289 unsigned char *server_name, *id_string;
3290 unsigned short id_len;
3292 SILC_LOG_DEBUG(("Creating new server"));
3294 if (sock->type != SILC_SOCKET_TYPE_SERVER &&
3295 sock->type != SILC_SOCKET_TYPE_ROUTER)
3298 /* Take server entry */
3299 new_server = (SilcServerEntry)sock->user_data;
3301 /* Fetch the old server cache entry so that we can update it. */
3302 if (!silc_idcache_find_by_context(server->local_list->servers,
3303 sock->user_data, &cache)) {
3304 SILC_LOG_ERROR(("Lost server's cache entry - bad thing"));
3308 /* Parse the incoming packet */
3309 silc_buffer_unformat(buffer,
3310 SILC_STR_UI16_NSTRING_ALLOC(&id_string, &id_len),
3311 SILC_STR_UI16_STRING_ALLOC(&server_name),
3314 if (id_len > buffer->len) {
3315 silc_free(id_string);
3316 silc_free(server_name);
3321 server_id = silc_id_payload_parse_id(id_string, id_len);
3322 silc_free(id_string);
3324 /* Update client entry */
3325 new_server->registered = TRUE;
3326 new_server->server_name = server_name;
3327 new_server->id = server_id;
3329 /* Update the cache entry */
3330 cache->id = (void *)server_id;
3331 cache->type = SILC_ID_SERVER;
3332 cache->data = server_name;
3333 silc_idcache_sort_by_data(server->local_list->servers);
3335 /* Distribute the information about new server in the SILC network
3336 to our router. If we are normal server we won't send anything
3337 since this connection must be our router connection. */
3338 if (server->server_type == SILC_ROUTER && !server->standalone)
3339 silc_server_send_new_id(server, server->id_entry->router->connection,
3340 TRUE, new_server->id, SILC_ID_SERVER,
3341 SILC_ID_SERVER_LEN);
3346 /* Processes incoming New ID Payload. New ID Payload is used to distribute
3347 information about newly registered clients, servers and created
3350 void silc_server_new_id(SilcServer server, SilcSocketConnection sock,
3351 SilcPacketContext *packet)
3353 SilcBuffer buffer = packet->buffer;
3355 SilcServerEntry tmpserver, router;
3356 SilcSocketConnection router_sock;
3361 SILC_LOG_DEBUG(("Processing new ID"));
3363 if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3364 server->server_type == SILC_SERVER ||
3365 packet->src_id_type != SILC_ID_SERVER)
3368 idp = silc_id_payload_parse(buffer);
3372 id_type = silc_id_payload_get_type(idp);
3374 /* Normal server cannot have other normal server connections */
3375 if (id_type == SILC_ID_SERVER && sock->type == SILC_SOCKET_TYPE_SERVER)
3378 id = silc_id_payload_get_id(idp);
3382 /* If the packet is originated from the one who sent it to us we know
3383 that the ID belongs to our cell, unless the sender was router. */
3384 tmpid = silc_id_str2id(packet->src_id, SILC_ID_SERVER);
3385 tmpserver = (SilcServerEntry)sock->user_data;
3387 if (!SILC_ID_SERVER_COMPARE(tmpid, tmpserver->id) &&
3388 sock->type == SILC_SOCKET_TYPE_SERVER) {
3389 id_list = server->local_list;
3391 router = sock->user_data;
3392 /* router = server->id_entry; */
3394 id_list = server->global_list;
3395 router_sock = (SilcSocketConnection)server->id_entry->router->connection;
3396 router = server->id_entry->router;
3402 case SILC_ID_CLIENT:
3404 SilcClientEntry idlist;
3406 /* Add the client to our local list. We are router and we keep
3407 cell specific local database of all clients in the cell. */
3408 idlist = silc_idlist_add_client(id_list, NULL, NULL, NULL,
3409 id, router, NULL, NULL,
3410 NULL, NULL, NULL, router_sock);
3414 case SILC_ID_SERVER:
3416 SilcServerEntry idlist;
3418 /* Add the server to our local list. We are router and we keep
3419 cell specific local database of all servers in the cell. */
3420 idlist = silc_idlist_add_server(id_list, NULL, 0,
3421 id, router, NULL, NULL,
3422 NULL, NULL, NULL, router_sock);
3426 case SILC_ID_CHANNEL:
3427 /* Add the channel to our local list. We are router and we keep
3428 cell specific local database of all channels in the cell. */
3429 silc_idlist_add_channel(id_list, NULL, 0, id, router, NULL);
3437 silc_id_payload_free(idp);
3440 /* Received packet to remove a user from a channel. Routers notify other
3441 routers that user has left a channel. Client must not send this packet.
3442 Normal server may send this packet but ignores if it receives one. */
3444 void silc_server_remove_channel_user(SilcServer server,
3445 SilcSocketConnection sock,
3446 SilcPacketContext *packet)
3448 SilcBuffer buffer = packet->buffer;
3449 unsigned char *tmp1 = NULL, *tmp2 = NULL;
3450 SilcClientID *client_id = NULL;
3451 SilcChannelID *channel_id = NULL;
3452 SilcChannelEntry channel;
3453 SilcClientEntry client;
3455 SILC_LOG_DEBUG(("Removing user from channel"));
3457 if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3458 server->server_type == SILC_SERVER)
3461 silc_buffer_unformat(buffer,
3462 SILC_STR_UI16_STRING_ALLOC(&tmp1),
3463 SILC_STR_UI16_STRING_ALLOC(&tmp2),
3469 client_id = silc_id_str2id(tmp1, SILC_ID_CLIENT);
3470 channel_id = silc_id_str2id(tmp2, SILC_ID_CHANNEL);
3471 if (!client_id || !channel_id)
3474 /* XXX routers should check server->global_list as well */
3475 /* Get channel entry */
3476 channel = silc_idlist_find_channel_by_id(server->local_list, channel_id);
3480 /* XXX routers should check server->global_list as well */
3481 /* Get client entry */
3482 client = silc_idlist_find_client_by_id(server->local_list, client_id);
3486 /* Remove from channel */
3487 silc_server_remove_from_one_channel(server, sock, channel, client, FALSE);
3495 silc_free(client_id);
3497 silc_free(channel_id);