5 Author: Pekka Riikonen <priikone@poseidon.pspt.fi>
7 Copyright (C) 1997 - 2001 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.
22 #include "clientlibincludes.h"
23 #include "client_internal.h"
25 /* Static task callback prototypes */
26 SILC_TASK_CALLBACK(silc_client_connect_to_server_start);
27 SILC_TASK_CALLBACK(silc_client_connect_to_server_second);
28 SILC_TASK_CALLBACK(silc_client_connect_to_server_final);
29 SILC_TASK_CALLBACK(silc_client_packet_parse_real);
30 SILC_TASK_CALLBACK(silc_client_rekey_callback);
31 SILC_TASK_CALLBACK(silc_client_rekey_final);
33 static void silc_client_packet_parse(SilcPacketParserContext *parser_context);
34 static void silc_client_packet_parse_type(SilcClient client,
35 SilcSocketConnection sock,
36 SilcPacketContext *packet);
38 /* Allocates new client object. This has to be done before client may
39 work. After calling this one must call silc_client_init to initialize
40 the client. The `application' is application specific user data pointer
41 and caller must free it. */
43 SilcClient silc_client_alloc(SilcClientOperations *ops,
44 SilcClientParams *params,
46 const char *silc_version)
48 SilcClient new_client;
50 new_client = silc_calloc(1, sizeof(*new_client));
51 new_client->application = application;
52 new_client->ops = ops;
53 new_client->silc_client_version = strdup(silc_version);
54 new_client->params = silc_calloc(1, sizeof(*new_client->params));
57 memcpy(new_client->params, params, sizeof(*params));
59 if (!new_client->params->rekey_secs)
60 new_client->params->rekey_secs = 3600;
65 /* Frees client object and its internals. */
67 void silc_client_free(SilcClient client)
71 silc_rng_free(client->rng);
73 silc_free(client->silc_client_version);
74 silc_free(client->params);
79 /* Initializes the client. This makes all the necessary steps to make
80 the client ready to be run. One must call silc_client_run to run the
81 client. Returns FALSE if error occured, TRUE otherwise. */
83 int silc_client_init(SilcClient client)
85 SILC_LOG_DEBUG(("Initializing client"));
87 /* Initialize hash functions for client to use */
88 silc_hash_alloc("md5", &client->md5hash);
89 silc_hash_alloc("sha1", &client->sha1hash);
91 /* Initialize none cipher */
92 silc_cipher_alloc("none", &client->none_cipher);
94 /* Initialize random number generator */
95 client->rng = silc_rng_alloc();
96 silc_rng_init(client->rng);
97 silc_rng_global_init(client->rng);
99 /* Register protocols */
100 silc_client_protocols_register();
102 /* Initialize the scheduler */
103 client->schedule = silc_schedule_init(&client->io_queue,
104 &client->timeout_queue,
105 &client->generic_queue, 5000);
106 if (!client->schedule)
112 /* Stops the client. This is called to stop the client and thus to stop
115 void silc_client_stop(SilcClient client)
117 SILC_LOG_DEBUG(("Stopping client"));
119 /* Stop the scheduler, although it might be already stopped. This
120 doesn't hurt anyone. This removes all the tasks and task queues,
122 silc_schedule_stop(client->schedule);
123 silc_schedule_uninit(client->schedule);
125 silc_client_protocols_unregister();
127 SILC_LOG_DEBUG(("Client stopped"));
130 /* Runs the client. This starts the scheduler from the utility library.
131 When this functions returns the execution of the appliation is over. */
133 void silc_client_run(SilcClient client)
135 SILC_LOG_DEBUG(("Running client"));
137 /* Start the scheduler, the heart of the SILC client. When this returns
138 the program will be terminated. */
139 silc_schedule(client->schedule);
142 /* Allocates and adds new connection to the client. This adds the allocated
143 connection to the connection table and returns a pointer to it. A client
144 can have multiple connections to multiple servers. Every connection must
145 be added to the client using this function. User data `context' may
146 be sent as argument. This function is normally used only if the
147 application performed the connecting outside the library. The library
148 however may use this internally. */
150 SilcClientConnection silc_client_add_connection(SilcClient client,
155 SilcClientConnection conn;
158 conn = silc_calloc(1, sizeof(*conn));
160 /* Initialize ID caches */
161 conn->client_cache = silc_idcache_alloc(0, SILC_ID_CLIENT, NULL);
162 conn->channel_cache = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
163 conn->server_cache = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
164 conn->client = client;
165 conn->remote_host = strdup(hostname);
166 conn->remote_port = port;
167 conn->context = context;
168 conn->pending_commands = silc_dlist_init();
170 /* Add the connection to connections table */
171 for (i = 0; i < client->conns_count; i++)
172 if (client->conns && !client->conns[i]) {
173 client->conns[i] = conn;
177 client->conns = silc_realloc(client->conns, sizeof(*client->conns)
178 * (client->conns_count + 1));
179 client->conns[client->conns_count] = conn;
180 client->conns_count++;
185 /* Removes connection from client. Frees all memory. */
187 void silc_client_del_connection(SilcClient client, SilcClientConnection conn)
191 for (i = 0; i < client->conns_count; i++)
192 if (client->conns[i] == conn) {
193 if (conn->pending_commands)
194 silc_dlist_uninit(conn->pending_commands);
196 client->conns[i] = NULL;
200 /* Adds listener socket to the listener sockets table. This function is
201 used to add socket objects that are listeners to the client. This should
202 not be used to add other connection objects. */
204 void silc_client_add_socket(SilcClient client, SilcSocketConnection sock)
208 if (!client->sockets) {
209 client->sockets = silc_calloc(1, sizeof(*client->sockets));
210 client->sockets[0] = silc_socket_dup(sock);
211 client->sockets_count = 1;
215 for (i = 0; i < client->sockets_count; i++) {
216 if (client->sockets[i] == NULL) {
217 client->sockets[i] = silc_socket_dup(sock);
222 client->sockets = silc_realloc(client->sockets, sizeof(*client->sockets) *
223 (client->sockets_count + 1));
224 client->sockets[client->sockets_count] = silc_socket_dup(sock);
225 client->sockets_count++;
228 /* Deletes listener socket from the listener sockets table. */
230 void silc_client_del_socket(SilcClient client, SilcSocketConnection sock)
234 if (!client->sockets)
237 for (i = 0; i < client->sockets_count; i++) {
238 if (client->sockets[i] == sock) {
239 silc_socket_free(sock);
240 client->sockets[i] = NULL;
247 silc_client_connect_to_server_internal(SilcClientInternalConnectContext *ctx)
251 /* XXX In the future we should give up this non-blocking connect all
252 together and use threads instead. */
253 /* Create connection to server asynchronously */
254 sock = silc_net_create_connection_async(ctx->port, ctx->host);
258 /* Register task that will receive the async connect and will
260 ctx->task = silc_task_register(ctx->client->io_queue, sock,
261 silc_client_connect_to_server_start,
264 SILC_TASK_PRI_NORMAL);
265 silc_task_reset_iotype(ctx->task, SILC_TASK_WRITE);
266 silc_schedule_set_listen_fd(ctx->client->schedule, sock, ctx->task->iomask);
273 /* Connects to remote server. This is the main routine used to connect
274 to SILC server. Returns -1 on error and the created socket otherwise.
275 The `context' is user context that is saved into the SilcClientConnection
276 that is created after the connection is created. Note that application
277 may handle the connecting process outside the library. If this is the
278 case then this function is not used at all. When the connecting is
279 done the `connect' client operation is called. */
281 int silc_client_connect_to_server(SilcClient client, int port,
282 char *host, void *context)
284 SilcClientInternalConnectContext *ctx;
285 SilcClientConnection conn;
288 SILC_LOG_DEBUG(("Connecting to port %d of server %s",
291 conn = silc_client_add_connection(client, host, port, context);
293 client->ops->say(client, conn, SILC_CLIENT_MESSAGE_AUDIT,
294 "Connecting to port %d of server %s", port, host);
296 /* Allocate internal context for connection process. This is
297 needed as we are doing async connecting. */
298 ctx = silc_calloc(1, sizeof(*ctx));
299 ctx->client = client;
301 ctx->host = strdup(host);
305 /* Do the actual connecting process */
306 sock = silc_client_connect_to_server_internal(ctx);
308 silc_client_del_connection(client, conn);
312 /* Start SILC Key Exchange (SKE) protocol to negotiate shared secret
313 key material between client and server. This function can be called
314 directly if application is performing its own connecting and does not
315 use the connecting provided by this library. This function is normally
316 used only if the application performed the connecting outside the library.
317 The library however may use this internally. */
319 int silc_client_start_key_exchange(SilcClient client,
320 SilcClientConnection conn,
323 SilcProtocol protocol;
324 SilcClientKEInternalContext *proto_ctx;
327 /* Allocate new socket connection object */
328 silc_socket_alloc(fd, SILC_SOCKET_TYPE_SERVER, (void *)conn, &conn->sock);
330 conn->nickname = strdup(client->username);
331 conn->sock->hostname = conn->remote_host;
332 conn->sock->ip = strdup(conn->remote_host);
333 conn->sock->port = conn->remote_port;
335 /* Allocate internal Key Exchange context. This is sent to the
336 protocol as context. */
337 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
338 proto_ctx->client = (void *)client;
339 proto_ctx->sock = silc_socket_dup(conn->sock);
340 proto_ctx->rng = client->rng;
341 proto_ctx->responder = FALSE;
342 proto_ctx->send_packet = silc_client_protocol_ke_send_packet;
343 proto_ctx->verify = silc_client_protocol_ke_verify_key;
345 /* Perform key exchange protocol. silc_client_connect_to_server_final
346 will be called after the protocol is finished. */
347 silc_protocol_alloc(SILC_PROTOCOL_CLIENT_KEY_EXCHANGE,
348 &protocol, (void *)proto_ctx,
349 silc_client_connect_to_server_second);
351 client->ops->say(client, conn, SILC_CLIENT_MESSAGE_ERROR,
352 "Error: Could not start authentication protocol");
355 conn->sock->protocol = protocol;
357 /* Register the connection for network input and output. This sets
358 that scheduler will listen for incoming packets for this connection
359 and sets that outgoing packets may be sent to this connection as well.
360 However, this doesn't set the scheduler for outgoing traffic, it will
361 be set separately by calling SILC_CLIENT_SET_CONNECTION_FOR_OUTPUT,
362 later when outgoing data is available. */
363 context = (void *)client;
364 SILC_CLIENT_REGISTER_CONNECTION_FOR_IO(fd);
366 /* Execute the protocol */
367 silc_protocol_execute(protocol, client->timeout_queue, 0, 0);
371 /* Start of the connection to the remote server. This is called after
372 succesful TCP/IP connection has been established to the remote host. */
374 SILC_TASK_CALLBACK(silc_client_connect_to_server_start)
376 SilcClientInternalConnectContext *ctx =
377 (SilcClientInternalConnectContext *)context;
378 SilcClient client = ctx->client;
379 SilcClientConnection conn = ctx->conn;
380 int opt, opt_len = sizeof(opt);
382 SILC_LOG_DEBUG(("Start"));
384 /* Check the socket status as it might be in error */
385 silc_net_get_socket_opt(fd, SOL_SOCKET, SO_ERROR, &opt, &opt_len);
387 if (ctx->tries < 2) {
388 /* Connection failed but lets try again */
389 client->ops->say(client, conn, SILC_CLIENT_MESSAGE_ERROR,
390 "Could not connect to server %s: %s",
391 ctx->host, strerror(opt));
392 client->ops->say(client, conn, SILC_CLIENT_MESSAGE_AUDIT,
393 "Connecting to port %d of server %s resumed",
394 ctx->port, ctx->host);
396 /* Unregister old connection try */
397 silc_schedule_unset_listen_fd(client->schedule, fd);
398 silc_net_close_connection(fd);
399 silc_task_unregister(client->io_queue, ctx->task);
402 silc_client_connect_to_server_internal(ctx);
405 /* Connection failed and we won't try anymore */
406 client->ops->say(client, conn, SILC_CLIENT_MESSAGE_ERROR,
407 "Could not connect to server %s: %s",
408 ctx->host, strerror(opt));
409 silc_schedule_unset_listen_fd(client->schedule, fd);
410 silc_net_close_connection(fd);
411 silc_task_unregister(client->io_queue, ctx->task);
414 /* Notify application of failure */
415 client->ops->connect(client, conn, FALSE);
416 silc_client_del_connection(client, conn);
421 silc_schedule_unset_listen_fd(client->schedule, fd);
422 silc_task_unregister(client->io_queue, ctx->task);
425 if (!silc_client_start_key_exchange(client, conn, fd)) {
426 silc_net_close_connection(fd);
427 client->ops->connect(client, conn, FALSE);
431 /* Second part of the connecting to the server. This executed
432 authentication protocol. */
434 SILC_TASK_CALLBACK(silc_client_connect_to_server_second)
436 SilcProtocol protocol = (SilcProtocol)context;
437 SilcClientKEInternalContext *ctx =
438 (SilcClientKEInternalContext *)protocol->context;
439 SilcClient client = (SilcClient)ctx->client;
440 SilcSocketConnection sock = NULL;
441 SilcClientConnAuthInternalContext *proto_ctx;
443 SILC_LOG_DEBUG(("Start"));
445 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
446 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
447 /* Error occured during protocol */
448 SILC_LOG_DEBUG(("Error during KE protocol"));
449 silc_protocol_free(protocol);
450 silc_ske_free_key_material(ctx->keymat);
452 silc_ske_free(ctx->ske);
454 silc_free(ctx->dest_id);
455 ctx->sock->protocol = NULL;
456 silc_socket_free(ctx->sock);
458 /* Notify application of failure */
459 client->ops->connect(client, ctx->sock->user_data, FALSE);
464 /* We now have the key material as the result of the key exchange
465 protocol. Take the key material into use. Free the raw key material
466 as soon as we've set them into use. */
467 silc_client_protocol_ke_set_keys(ctx->ske, ctx->sock, ctx->keymat,
468 ctx->ske->prop->cipher,
469 ctx->ske->prop->pkcs,
470 ctx->ske->prop->hash,
471 ctx->ske->prop->hmac,
472 ctx->ske->prop->group);
473 silc_ske_free_key_material(ctx->keymat);
475 /* Allocate internal context for the authentication protocol. This
476 is sent as context for the protocol. */
477 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
478 proto_ctx->client = (void *)client;
479 proto_ctx->sock = sock = ctx->sock;
480 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
481 proto_ctx->dest_id_type = ctx->dest_id_type;
482 proto_ctx->dest_id = ctx->dest_id;
484 /* Resolve the authentication method to be used in this connection */
485 if (!client->ops->get_auth_method(client, sock->user_data, sock->hostname,
486 sock->port, &proto_ctx->auth_meth,
487 &proto_ctx->auth_data,
488 &proto_ctx->auth_data_len))
489 proto_ctx->auth_meth = SILC_AUTH_NONE;
491 /* Free old protocol as it is finished now */
492 silc_protocol_free(protocol);
494 silc_packet_context_free(ctx->packet);
496 sock->protocol = NULL;
498 /* Allocate the authenteication protocol and execute it. */
499 silc_protocol_alloc(SILC_PROTOCOL_CLIENT_CONNECTION_AUTH,
500 &sock->protocol, (void *)proto_ctx,
501 silc_client_connect_to_server_final);
503 /* Execute the protocol */
504 silc_protocol_execute(sock->protocol, client->timeout_queue, 0, 0);
507 /* Finalizes the connection to the remote SILC server. This is called
508 after authentication protocol has been completed. This send our
509 user information to the server to receive our client ID from
512 SILC_TASK_CALLBACK(silc_client_connect_to_server_final)
514 SilcProtocol protocol = (SilcProtocol)context;
515 SilcClientConnAuthInternalContext *ctx =
516 (SilcClientConnAuthInternalContext *)protocol->context;
517 SilcClient client = (SilcClient)ctx->client;
518 SilcClientConnection conn = (SilcClientConnection)ctx->sock->user_data;
521 SILC_LOG_DEBUG(("Start"));
523 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
524 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
525 /* Error occured during protocol */
526 SILC_LOG_DEBUG(("Error during authentication protocol"));
527 silc_protocol_free(protocol);
529 silc_free(ctx->auth_data);
531 silc_ske_free(ctx->ske);
533 silc_free(ctx->dest_id);
534 conn->sock->protocol = NULL;
535 silc_socket_free(ctx->sock);
537 /* Notify application of failure */
538 client->ops->connect(client, ctx->sock->user_data, FALSE);
543 /* Send NEW_CLIENT packet to the server. We will become registered
544 to the SILC network after sending this packet and we will receive
545 client ID from the server. */
546 packet = silc_buffer_alloc(2 + 2 + strlen(client->username) +
547 strlen(client->realname));
548 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
549 silc_buffer_format(packet,
550 SILC_STR_UI_SHORT(strlen(client->username)),
551 SILC_STR_UI_XNSTRING(client->username,
552 strlen(client->username)),
553 SILC_STR_UI_SHORT(strlen(client->realname)),
554 SILC_STR_UI_XNSTRING(client->realname,
555 strlen(client->realname)),
558 /* Send the packet */
559 silc_client_packet_send(client, ctx->sock, SILC_PACKET_NEW_CLIENT,
561 packet->data, packet->len, TRUE);
562 silc_buffer_free(packet);
564 /* Save remote ID. */
565 conn->remote_id = ctx->dest_id;
566 conn->remote_id_data = silc_id_id2str(ctx->dest_id, SILC_ID_SERVER);
567 conn->remote_id_data_len = silc_id_get_len(ctx->dest_id, SILC_ID_SERVER);
569 /* Register re-key timeout */
570 conn->rekey->timeout = client->params->rekey_secs;
571 conn->rekey->context = (void *)client;
572 silc_task_register(client->timeout_queue, conn->sock->sock,
573 silc_client_rekey_callback,
574 (void *)conn->sock, conn->rekey->timeout, 0,
575 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
577 silc_protocol_free(protocol);
579 silc_free(ctx->auth_data);
581 silc_ske_free(ctx->ske);
582 silc_socket_free(ctx->sock);
584 conn->sock->protocol = NULL;
587 /* Internal routine that sends packet or marks packet to be sent. This
588 is used directly only in special cases. Normal cases should use
589 silc_server_packet_send. Returns < 0 on error. */
591 int silc_client_packet_send_real(SilcClient client,
592 SilcSocketConnection sock,
598 /* If rekey protocol is active we must assure that all packets are
599 sent through packet queue. */
600 if (flush == FALSE && SILC_CLIENT_IS_REKEY(sock))
603 /* Send the packet */
604 ret = silc_packet_send(sock, force_send);
608 /* Mark that there is some outgoing data available for this connection.
609 This call sets the connection both for input and output (the input
610 is set always and this call keeps the input setting, actually).
611 Actual data sending is performed by silc_client_packet_process. */
612 SILC_CLIENT_SET_CONNECTION_FOR_OUTPUT(client->schedule, sock->sock);
614 /* Mark to socket that data is pending in outgoing buffer. This flag
615 is needed if new data is added to the buffer before the earlier
616 put data is sent to the network. */
617 SILC_SET_OUTBUF_PENDING(sock);
622 /* Packet processing callback. This is used to send and receive packets
623 from network. This is generic task. */
625 SILC_TASK_CALLBACK_GLOBAL(silc_client_packet_process)
627 SilcClient client = (SilcClient)context;
628 SilcSocketConnection sock = NULL;
629 SilcClientConnection conn;
632 SILC_LOG_DEBUG(("Processing packet"));
634 SILC_CLIENT_GET_SOCK(client, fd, sock);
638 conn = (SilcClientConnection)sock->user_data;
641 if (type == SILC_TASK_WRITE) {
642 SILC_LOG_DEBUG(("Writing data to connection"));
644 if (sock->outbuf->data - sock->outbuf->head)
645 silc_buffer_push(sock->outbuf,
646 sock->outbuf->data - sock->outbuf->head);
648 ret = silc_client_packet_send_real(client, sock, TRUE, TRUE);
650 /* If returned -2 could not write to connection now, will do
655 /* The packet has been sent and now it is time to set the connection
656 back to only for input. When there is again some outgoing data
657 available for this connection it will be set for output as well.
658 This call clears the output setting and sets it only for input. */
659 SILC_CLIENT_SET_CONNECTION_FOR_INPUT(client->schedule, fd);
660 SILC_UNSET_OUTBUF_PENDING(sock);
662 silc_buffer_clear(sock->outbuf);
666 /* Packet receiving */
667 if (type == SILC_TASK_READ) {
668 SILC_LOG_DEBUG(("Reading data from connection"));
670 /* Read data from network */
671 ret = silc_packet_receive(sock);
677 SILC_LOG_DEBUG(("Read EOF"));
679 /* If connection is disconnecting already we will finally
680 close the connection */
681 if (SILC_IS_DISCONNECTING(sock)) {
682 if (sock == conn->sock)
683 client->ops->disconnect(client, conn);
684 silc_client_close_connection(client, sock, conn);
688 SILC_LOG_DEBUG(("EOF from connection %d", sock->sock));
689 if (sock == conn->sock)
690 client->ops->disconnect(client, conn);
691 silc_client_close_connection(client, sock, conn);
695 /* Process the packet. This will call the parser that will then
696 decrypt and parse the packet. */
697 if (sock->type != SILC_SOCKET_TYPE_UNKNOWN)
698 silc_packet_receive_process(sock, conn->receive_key, conn->hmac_receive,
699 silc_client_packet_parse, client);
701 silc_packet_receive_process(sock, NULL, NULL,
702 silc_client_packet_parse, client);
706 /* Callback function that the silc_packet_decrypt will call to make the
707 decision whether the packet is normal or special packet. We will
708 return TRUE if it is normal and FALSE if it is special */
710 static int silc_client_packet_decrypt_check(SilcPacketType packet_type,
712 SilcPacketContext *packet,
716 /* Packet is normal packet, if:
718 1) packet is private message packet and does not have private key set
719 2) is other packet than channel message packet
721 all other packets are special packets
724 if (packet_type == SILC_PACKET_PRIVATE_MESSAGE &&
725 (buffer->data[2] & SILC_PACKET_FLAG_PRIVMSG_KEY))
728 if (packet_type != SILC_PACKET_CHANNEL_MESSAGE)
734 /* Parses whole packet, received earlier. */
736 SILC_TASK_CALLBACK(silc_client_packet_parse_real)
738 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
739 SilcClient client = (SilcClient)parse_ctx->context;
740 SilcPacketContext *packet = parse_ctx->packet;
741 SilcBuffer buffer = packet->buffer;
742 SilcSocketConnection sock = parse_ctx->sock;
743 SilcClientConnection conn = (SilcClientConnection)sock->user_data;
746 SILC_LOG_DEBUG(("Start"));
748 /* Decrypt the received packet */
749 if (sock->type != SILC_SOCKET_TYPE_UNKNOWN)
750 ret = silc_packet_decrypt(conn->receive_key, conn->hmac_receive,
752 silc_client_packet_decrypt_check, parse_ctx);
754 ret = silc_packet_decrypt(NULL, NULL, buffer, packet,
755 silc_client_packet_decrypt_check, parse_ctx);
761 /* Parse the packet. Packet type is returned. */
762 ret = silc_packet_parse(packet);
764 /* Parse the packet header in special way as this is "special"
766 ret = silc_packet_parse_special(packet);
769 if (ret == SILC_PACKET_NONE)
772 /* Parse the incoming packet type */
773 silc_client_packet_parse_type(client, sock, packet);
776 /* silc_buffer_clear(sock->inbuf); */
777 silc_packet_context_free(packet);
778 silc_free(parse_ctx);
781 /* Parser callback called by silc_packet_receive_process. Thie merely
782 registers timeout that will handle the actual parsing when appropriate. */
784 void silc_client_packet_parse(SilcPacketParserContext *parser_context)
786 SilcClient client = (SilcClient)parser_context->context;
788 /* Parse the packet */
789 silc_task_register(client->timeout_queue, parser_context->sock->sock,
790 silc_client_packet_parse_real,
791 (void *)parser_context, 0, 1,
793 SILC_TASK_PRI_NORMAL);
796 /* Parses the packet type and calls what ever routines the packet type
797 requires. This is done for all incoming packets. */
799 void silc_client_packet_parse_type(SilcClient client,
800 SilcSocketConnection sock,
801 SilcPacketContext *packet)
803 SilcBuffer buffer = packet->buffer;
804 SilcPacketType type = packet->type;
806 SILC_LOG_DEBUG(("Parsing packet type %d", type));
808 /* Parse the packet type */
810 case SILC_PACKET_DISCONNECT:
811 silc_client_disconnected_by_server(client, sock, buffer);
813 case SILC_PACKET_SUCCESS:
815 * Success received for something. For now we can have only
816 * one protocol for connection executing at once hence this
817 * success message is for whatever protocol is executing currently.
820 silc_protocol_execute(sock->protocol, client->timeout_queue, 0, 0);
822 case SILC_PACKET_FAILURE:
824 * Failure received for some protocol. Set the protocol state to
825 * error and call the protocol callback. This fill cause error on
826 * protocol and it will call the final callback.
828 silc_client_process_failure(client, sock, packet);
830 case SILC_PACKET_REJECT:
833 case SILC_PACKET_NOTIFY:
835 * Received notify message
837 silc_client_notify_by_server(client, sock, packet);
840 case SILC_PACKET_ERROR:
842 * Received error message
844 silc_client_error_by_server(client, sock, buffer);
847 case SILC_PACKET_CHANNEL_MESSAGE:
849 * Received message to (from, actually) a channel
851 silc_client_channel_message(client, sock, packet);
853 case SILC_PACKET_CHANNEL_KEY:
855 * Received key for a channel. By receiving this key the client will be
856 * able to talk to the channel it has just joined. This can also be
857 * a new key for existing channel as keys expire peridiocally.
859 silc_client_receive_channel_key(client, sock, buffer);
862 case SILC_PACKET_PRIVATE_MESSAGE:
864 * Received private message
866 silc_client_private_message(client, sock, packet);
868 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
870 * Received private message key
874 case SILC_PACKET_COMMAND_REPLY:
876 * Recived reply for a command
878 silc_client_command_reply_process(client, sock, packet);
881 case SILC_PACKET_KEY_EXCHANGE:
882 if (sock->protocol && sock->protocol->protocol &&
883 sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_KEY_EXCHANGE) {
884 SilcClientKEInternalContext *proto_ctx =
885 (SilcClientKEInternalContext *)sock->protocol->context;
887 proto_ctx->packet = silc_packet_context_dup(packet);
888 proto_ctx->dest_id_type = packet->src_id_type;
889 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
890 packet->src_id_type);
891 if (!proto_ctx->dest_id)
894 /* Let the protocol handle the packet */
895 silc_protocol_execute(sock->protocol, client->timeout_queue, 0, 0);
897 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
898 "protocol active, packet dropped."));
902 case SILC_PACKET_KEY_EXCHANGE_1:
903 if (sock->protocol && sock->protocol->protocol &&
904 (sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_KEY_EXCHANGE ||
905 sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_REKEY)) {
907 if (sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_REKEY) {
908 SilcClientRekeyInternalContext *proto_ctx =
909 (SilcClientRekeyInternalContext *)sock->protocol->context;
911 if (proto_ctx->packet)
912 silc_packet_context_free(proto_ctx->packet);
914 proto_ctx->packet = silc_packet_context_dup(packet);
916 /* Let the protocol handle the packet */
917 silc_protocol_execute(sock->protocol, client->timeout_queue, 0, 0);
919 SilcClientKEInternalContext *proto_ctx =
920 (SilcClientKEInternalContext *)sock->protocol->context;
922 if (proto_ctx->packet)
923 silc_packet_context_free(proto_ctx->packet);
925 proto_ctx->packet = silc_packet_context_dup(packet);
926 proto_ctx->dest_id_type = packet->src_id_type;
927 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
928 packet->src_id_type);
929 if (!proto_ctx->dest_id)
932 /* Let the protocol handle the packet */
933 silc_protocol_execute(sock->protocol, client->timeout_queue, 0, 0);
936 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
937 "protocol active, packet dropped."));
940 case SILC_PACKET_KEY_EXCHANGE_2:
941 if (sock->protocol && sock->protocol->protocol &&
942 (sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_KEY_EXCHANGE ||
943 sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_REKEY)) {
945 if (sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_REKEY) {
946 SilcClientRekeyInternalContext *proto_ctx =
947 (SilcClientRekeyInternalContext *)sock->protocol->context;
949 if (proto_ctx->packet)
950 silc_packet_context_free(proto_ctx->packet);
952 proto_ctx->packet = silc_packet_context_dup(packet);
954 /* Let the protocol handle the packet */
955 silc_protocol_execute(sock->protocol, client->timeout_queue, 0, 0);
957 SilcClientKEInternalContext *proto_ctx =
958 (SilcClientKEInternalContext *)sock->protocol->context;
960 if (proto_ctx->packet)
961 silc_packet_context_free(proto_ctx->packet);
963 proto_ctx->packet = silc_packet_context_dup(packet);
964 proto_ctx->dest_id_type = packet->src_id_type;
965 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
966 packet->src_id_type);
967 if (!proto_ctx->dest_id)
970 /* Let the protocol handle the packet */
971 silc_protocol_execute(sock->protocol, client->timeout_queue, 0, 0);
974 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
975 "protocol active, packet dropped."));
979 case SILC_PACKET_NEW_ID:
982 * Received new ID from server. This packet is received at
983 * the connection to the server. New ID is also received when
984 * user changes nickname but in that case the new ID is received
985 * as command reply and not as this packet type.
989 idp = silc_id_payload_parse(buffer);
992 if (silc_id_payload_get_type(idp) != SILC_ID_CLIENT)
995 silc_client_receive_new_id(client, sock, idp);
996 silc_id_payload_free(idp);
1000 case SILC_PACKET_HEARTBEAT:
1002 * Received heartbeat packet
1004 SILC_LOG_DEBUG(("Heartbeat packet"));
1007 case SILC_PACKET_KEY_AGREEMENT:
1009 * Received key agreement packet
1011 SILC_LOG_DEBUG(("Key agreement packet"));
1012 silc_client_key_agreement(client, sock, packet);
1015 case SILC_PACKET_REKEY:
1016 SILC_LOG_DEBUG(("Re-key packet"));
1017 /* We ignore this for now */
1020 case SILC_PACKET_REKEY_DONE:
1021 SILC_LOG_DEBUG(("Re-key done packet"));
1023 if (sock->protocol && sock->protocol->protocol &&
1024 sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_REKEY) {
1026 SilcClientRekeyInternalContext *proto_ctx =
1027 (SilcClientRekeyInternalContext *)sock->protocol->context;
1029 if (proto_ctx->packet)
1030 silc_packet_context_free(proto_ctx->packet);
1032 proto_ctx->packet = silc_packet_context_dup(packet);
1034 /* Let the protocol handle the packet */
1035 if (proto_ctx->responder == FALSE)
1036 silc_protocol_execute(sock->protocol, client->timeout_queue, 0, 0);
1038 /* Let the protocol handle the packet */
1039 silc_protocol_execute(sock->protocol, client->timeout_queue,
1042 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
1043 "protocol active, packet dropped."));
1048 SILC_LOG_DEBUG(("Incorrect packet type %d, packet dropped", type));
1053 /* Sends packet. This doesn't actually send the packet instead it assembles
1054 it and marks it to be sent. However, if force_send is TRUE the packet
1055 is sent immediately. if dst_id, cipher and hmac are NULL those parameters
1056 will be derived from sock argument. Otherwise the valid arguments sent
1059 void silc_client_packet_send(SilcClient client,
1060 SilcSocketConnection sock,
1061 SilcPacketType type,
1063 SilcIdType dst_id_type,
1066 unsigned char *data,
1070 SilcPacketContext packetdata;
1075 SILC_LOG_DEBUG(("Sending packet, type %d", type));
1077 /* Get data used in the packet sending, keys and stuff */
1078 if ((!cipher || !hmac || !dst_id) && sock->user_data) {
1079 if (!cipher && ((SilcClientConnection)sock->user_data)->send_key)
1080 cipher = ((SilcClientConnection)sock->user_data)->send_key;
1082 if (!hmac && ((SilcClientConnection)sock->user_data)->hmac_send)
1083 hmac = ((SilcClientConnection)sock->user_data)->hmac_send;
1085 if (!dst_id && ((SilcClientConnection)sock->user_data)->remote_id) {
1086 dst_id = ((SilcClientConnection)sock->user_data)->remote_id;
1087 dst_id_type = SILC_ID_SERVER;
1091 /* Set the packet context pointers */
1092 packetdata.flags = 0;
1093 packetdata.type = type;
1094 if (sock->user_data &&
1095 ((SilcClientConnection)sock->user_data)->local_id_data) {
1096 packetdata.src_id = ((SilcClientConnection)sock->user_data)->local_id_data;
1097 packetdata.src_id_len =
1098 silc_id_get_len(((SilcClientConnection)sock->user_data)->local_id,
1101 packetdata.src_id = silc_calloc(SILC_ID_CLIENT_LEN, sizeof(unsigned char));
1102 packetdata.src_id_len = SILC_ID_CLIENT_LEN;
1104 packetdata.src_id_type = SILC_ID_CLIENT;
1106 packetdata.dst_id = silc_id_id2str(dst_id, dst_id_type);
1107 packetdata.dst_id_len = silc_id_get_len(dst_id, dst_id_type);
1108 packetdata.dst_id_type = dst_id_type;
1110 packetdata.dst_id = NULL;
1111 packetdata.dst_id_len = 0;
1112 packetdata.dst_id_type = SILC_ID_NONE;
1114 packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
1115 packetdata.src_id_len + packetdata.dst_id_len;
1116 packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
1118 /* Prepare outgoing data buffer for packet sending */
1119 silc_packet_send_prepare(sock,
1120 SILC_PACKET_HEADER_LEN +
1121 packetdata.src_id_len +
1122 packetdata.dst_id_len,
1126 SILC_LOG_DEBUG(("Putting data to outgoing buffer, len %d", data_len));
1128 packetdata.buffer = sock->outbuf;
1130 /* Put the data to the buffer */
1131 if (data && data_len)
1132 silc_buffer_put(sock->outbuf, data, data_len);
1134 /* Create the outgoing packet */
1135 silc_packet_assemble(&packetdata);
1137 /* Encrypt the packet */
1139 silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
1141 SILC_LOG_HEXDUMP(("Packet, len %d", sock->outbuf->len),
1142 sock->outbuf->data, sock->outbuf->len);
1144 /* Now actually send the packet */
1145 silc_client_packet_send_real(client, sock, force_send, FALSE);
1148 /* Closes connection to remote end. Free's all allocated data except
1149 for some information such as nickname etc. that are valid at all time.
1150 If the `sock' is NULL then the conn->sock will be used. If `sock' is
1151 provided it will be checked whether the sock and `conn->sock' are the
1152 same (they can be different, ie. a socket can use `conn' as its
1153 connection but `conn->sock' might be actually a different connection
1154 than the `sock'). */
1156 void silc_client_close_connection(SilcClient client,
1157 SilcSocketConnection sock,
1158 SilcClientConnection conn)
1162 if (!sock || (sock && conn->sock == sock))
1167 /* We won't listen for this connection anymore */
1168 silc_schedule_unset_listen_fd(client->schedule, sock->sock);
1170 /* Unregister all tasks */
1171 silc_task_unregister_by_fd(client->io_queue, sock->sock);
1172 silc_task_unregister_by_fd(client->timeout_queue, sock->sock);
1174 /* Close the actual connection */
1175 silc_net_close_connection(sock->sock);
1177 /* Cancel any active protocol */
1178 if (sock->protocol) {
1179 if (sock->protocol->protocol->type ==
1180 SILC_PROTOCOL_CLIENT_KEY_EXCHANGE ||
1181 sock->protocol->protocol->type ==
1182 SILC_PROTOCOL_CLIENT_CONNECTION_AUTH) {
1183 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
1184 silc_protocol_execute_final(sock->protocol, client->timeout_queue);
1185 sock->protocol = NULL;
1186 /* The application will recall this function with these protocols
1187 (the ops->connect client operation). */
1190 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
1191 silc_protocol_execute_final(sock->protocol, client->timeout_queue);
1192 sock->protocol = NULL;
1196 /* Free everything */
1197 if (del && sock->user_data) {
1198 /* XXX Free all client entries and channel entries. */
1200 /* Clear ID caches */
1201 if (conn->client_cache)
1202 silc_idcache_del_all(conn->client_cache);
1203 if (conn->channel_cache)
1204 silc_idcache_del_all(conn->channel_cache);
1207 if (conn->remote_host)
1208 silc_free(conn->remote_host);
1210 silc_free(conn->local_id);
1211 if (conn->local_id_data)
1212 silc_free(conn->local_id_data);
1214 silc_cipher_free(conn->send_key);
1215 if (conn->receive_key)
1216 silc_cipher_free(conn->receive_key);
1217 if (conn->hmac_send) /* conn->hmac_receive is same */
1218 silc_hmac_free(conn->hmac_send);
1219 if (conn->pending_commands)
1220 silc_dlist_uninit(conn->pending_commands);
1222 silc_free(conn->rekey);
1224 memset(conn, 0, sizeof(*conn));
1225 silc_client_del_connection(client, conn);
1228 silc_socket_free(sock);
1231 /* Called when we receive disconnection packet from server. This
1232 closes our end properly and displays the reason of the disconnection
1235 void silc_client_disconnected_by_server(SilcClient client,
1236 SilcSocketConnection sock,
1241 SILC_LOG_DEBUG(("Server disconnected us, sock %d", sock->sock));
1243 msg = silc_calloc(message->len + 1, sizeof(char));
1244 memcpy(msg, message->data, message->len);
1245 client->ops->say(client, sock->user_data, SILC_CLIENT_MESSAGE_AUDIT, msg);
1248 SILC_SET_DISCONNECTED(sock);
1249 silc_client_close_connection(client, sock, sock->user_data);
1252 /* Received error message from server. Display it on the screen.
1253 We don't take any action what so ever of the error message. */
1255 void silc_client_error_by_server(SilcClient client,
1256 SilcSocketConnection sock,
1261 msg = silc_calloc(message->len + 1, sizeof(char));
1262 memcpy(msg, message->data, message->len);
1263 client->ops->say(client, sock->user_data, SILC_CLIENT_MESSAGE_AUDIT, msg);
1267 /* Processes the received new Client ID from server. Old Client ID is
1268 deleted from cache and new one is added. */
1270 void silc_client_receive_new_id(SilcClient client,
1271 SilcSocketConnection sock,
1274 SilcClientConnection conn = (SilcClientConnection)sock->user_data;
1275 int connecting = FALSE;
1278 if (!conn->local_entry)
1281 /* Delete old ID from ID cache */
1282 if (conn->local_id) {
1283 silc_idcache_del_by_context(conn->client_cache, conn->local_entry);
1284 silc_free(conn->local_id);
1287 /* Save the new ID */
1289 if (conn->local_id_data)
1290 silc_free(conn->local_id_data);
1292 conn->local_id = silc_id_payload_get_id(idp);
1293 conn->local_id_data = silc_id_payload_get_data(idp);
1294 conn->local_id_data_len = silc_id_payload_get_len(idp);;
1296 if (!conn->local_entry)
1297 conn->local_entry = silc_calloc(1, sizeof(*conn->local_entry));
1299 conn->local_entry->nickname = conn->nickname;
1300 if (!conn->local_entry->username) {
1301 conn->local_entry->username =
1302 silc_calloc(strlen(client->username) + strlen(client->hostname) + 1,
1303 sizeof(conn->local_entry->username));
1304 sprintf(conn->local_entry->username, "%s@%s", client->username,
1307 conn->local_entry->server = strdup(conn->remote_host);
1308 conn->local_entry->id = conn->local_id;
1310 /* Put it to the ID cache */
1311 silc_idcache_add(conn->client_cache, conn->nickname, conn->local_id,
1312 (void *)conn->local_entry, FALSE);
1314 /* Issue INFO command to fetch the real server name and server information
1316 sidp = silc_id_payload_encode(conn->remote_id, SILC_ID_SERVER);
1317 silc_client_send_command(client, conn, SILC_COMMAND_INFO,
1318 ++conn->cmd_ident, 1, 2, sidp->data, sidp->len);
1319 silc_buffer_free(sidp);
1321 /* Notify application of successful connection. We do it here now that
1322 we've received the Client ID and are allowed to send traffic. */
1324 client->ops->connect(client, conn, TRUE);
1327 /* Processed received Channel ID for a channel. This is called when client
1328 joins to channel and server replies with channel ID. The ID is cached.
1329 Returns the created channel entry. This is also called when received
1330 channel ID in for example USERS command reply that we do not have. */
1332 SilcChannelEntry silc_client_new_channel_id(SilcClient client,
1333 SilcSocketConnection sock,
1338 SilcClientConnection conn = (SilcClientConnection)sock->user_data;
1339 SilcChannelEntry channel;
1341 SILC_LOG_DEBUG(("New channel ID"));
1343 channel = silc_calloc(1, sizeof(*channel));
1344 channel->channel_name = channel_name;
1345 channel->id = silc_id_payload_get_id(idp);
1346 channel->mode = mode;
1347 silc_list_init(channel->clients, struct SilcChannelUserStruct, next);
1349 /* Put it to the ID cache */
1350 silc_idcache_add(conn->channel_cache, channel_name, (void *)channel->id,
1351 (void *)channel, FALSE);
1356 /* Removes a client entry from all channel it has joined. This really is
1357 a performance killer (client_entry should have pointers to channel
1360 void silc_client_remove_from_channels(SilcClient client,
1361 SilcClientConnection conn,
1362 SilcClientEntry client_entry)
1364 SilcIDCacheEntry id_cache;
1365 SilcIDCacheList list;
1366 SilcChannelEntry channel;
1367 SilcChannelUser chu;
1369 if (!silc_idcache_get_all(conn->channel_cache, &list))
1372 silc_idcache_list_first(list, &id_cache);
1373 channel = (SilcChannelEntry)id_cache->context;
1377 /* Remove client from channel */
1378 silc_list_start(channel->clients);
1379 while ((chu = silc_list_get(channel->clients)) != SILC_LIST_END) {
1380 if (chu->client == client_entry) {
1381 silc_list_del(channel->clients, chu);
1387 if (!silc_idcache_list_next(list, &id_cache))
1390 channel = (SilcChannelEntry)id_cache->context;
1393 silc_idcache_list_free(list);
1396 /* Replaces `old' client entries from all channels to `new' client entry.
1397 This can be called for example when nickname changes and old ID entry
1398 is replaced from ID cache with the new one. If the old ID entry is only
1399 updated, then this fucntion needs not to be called. */
1401 void silc_client_replace_from_channels(SilcClient client,
1402 SilcClientConnection conn,
1403 SilcClientEntry old,
1404 SilcClientEntry new)
1406 SilcIDCacheEntry id_cache;
1407 SilcIDCacheList list;
1408 SilcChannelEntry channel;
1409 SilcChannelUser chu;
1411 if (!silc_idcache_get_all(conn->channel_cache, &list))
1414 silc_idcache_list_first(list, &id_cache);
1415 channel = (SilcChannelEntry)id_cache->context;
1419 /* Replace client entry */
1420 silc_list_start(channel->clients);
1421 while ((chu = silc_list_get(channel->clients)) != SILC_LIST_END) {
1422 if (chu->client == old) {
1428 if (!silc_idcache_list_next(list, &id_cache))
1431 channel = (SilcChannelEntry)id_cache->context;
1434 silc_idcache_list_free(list);
1437 /* Registers failure timeout to process the received failure packet
1440 void silc_client_process_failure(SilcClient client,
1441 SilcSocketConnection sock,
1442 SilcPacketContext *packet)
1446 if (sock->protocol) {
1447 if (packet->buffer->len >= 4)
1448 SILC_GET32_MSB(failure, packet->buffer->data);
1450 /* Notify application */
1451 client->ops->failure(client, sock->user_data, sock->protocol,
1456 /* A timeout callback for the re-key. We will be the initiator of the
1459 SILC_TASK_CALLBACK(silc_client_rekey_callback)
1461 SilcSocketConnection sock = (SilcSocketConnection)context;
1462 SilcClientConnection conn = (SilcClientConnection)sock->user_data;
1463 SilcClient client = (SilcClient)conn->rekey->context;
1464 SilcProtocol protocol;
1465 SilcClientRekeyInternalContext *proto_ctx;
1467 SILC_LOG_DEBUG(("Start"));
1469 /* Allocate internal protocol context. This is sent as context
1471 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1472 proto_ctx->client = (void *)client;
1473 proto_ctx->sock = silc_socket_dup(sock);
1474 proto_ctx->responder = FALSE;
1475 proto_ctx->pfs = conn->rekey->pfs;
1477 /* Perform rekey protocol. Will call the final callback after the
1478 protocol is over. */
1479 silc_protocol_alloc(SILC_PROTOCOL_CLIENT_REKEY,
1480 &protocol, proto_ctx, silc_client_rekey_final);
1481 sock->protocol = protocol;
1483 /* Run the protocol */
1484 silc_protocol_execute(protocol, client->timeout_queue, 0, 0);
1486 /* Re-register re-key timeout */
1487 silc_task_register(client->timeout_queue, sock->sock,
1488 silc_client_rekey_callback,
1489 context, conn->rekey->timeout, 0,
1490 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1493 /* The final callback for the REKEY protocol. This will actually take the
1494 new key material into use. */
1496 SILC_TASK_CALLBACK(silc_client_rekey_final)
1498 SilcProtocol protocol = (SilcProtocol)context;
1499 SilcClientRekeyInternalContext *ctx =
1500 (SilcClientRekeyInternalContext *)protocol->context;
1501 SilcClient client = (SilcClient)ctx->client;
1502 SilcSocketConnection sock = ctx->sock;
1504 SILC_LOG_DEBUG(("Start"));
1506 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1507 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1508 /* Error occured during protocol */
1509 silc_protocol_cancel(protocol, client->timeout_queue);
1510 silc_protocol_free(protocol);
1511 sock->protocol = NULL;
1513 silc_packet_context_free(ctx->packet);
1515 silc_ske_free(ctx->ske);
1516 silc_socket_free(ctx->sock);
1522 silc_protocol_free(protocol);
1523 sock->protocol = NULL;
1525 silc_packet_context_free(ctx->packet);
1527 silc_ske_free(ctx->ske);
1528 silc_socket_free(ctx->sock);