updates.
[silc.git] / lib / silcclient / client.c
1 /*
2
3   client.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 1997 - 2001 Pekka Riikonen
8
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.
13   
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.
18
19 */
20 /* $Id$ */
21
22 #include "clientlibincludes.h"
23 #include "client_internal.h"
24
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_rekey_callback);
30 SILC_TASK_CALLBACK(silc_client_rekey_final);
31
32 static bool silc_client_packet_parse(SilcPacketParserContext *parser_context,
33                                      void *context);
34 static void silc_client_packet_parse_type(SilcClient client, 
35                                           SilcSocketConnection sock,
36                                           SilcPacketContext *packet);
37 void silc_client_resolve_auth_method(bool success,
38                                      SilcProtocolAuthMeth auth_meth,
39                                      const unsigned char *auth_data,
40                                      uint32 auth_data_len, void *context);
41
42 /* Allocates new client object. This has to be done before client may
43    work. After calling this one must call silc_client_init to initialize
44    the client. The `application' is application specific user data pointer
45    and caller must free it. */
46
47 SilcClient silc_client_alloc(SilcClientOperations *ops, 
48                              SilcClientParams *params,
49                              void *application,
50                              const char *silc_version)
51 {
52   SilcClient new_client;
53
54   new_client = silc_calloc(1, sizeof(*new_client));
55   new_client->application = application;
56   new_client->ops = ops;
57   new_client->silc_client_version = strdup(silc_version);
58   new_client->params = silc_calloc(1, sizeof(*new_client->params));
59
60   if (params)
61     memcpy(new_client->params, params, sizeof(*params));
62
63   if (!new_client->params->task_max)
64     new_client->params->task_max = 200;
65
66   if (!new_client->params->rekey_secs)
67     new_client->params->rekey_secs = 3600;
68
69   if (!new_client->params->connauth_request_secs)
70     new_client->params->connauth_request_secs = 2;
71
72   new_client->params->
73     nickname_format[sizeof(new_client->params->nickname_format) - 1] = 0;
74
75   return new_client;
76 }
77
78 /* Frees client object and its internals. */
79
80 void silc_client_free(SilcClient client)
81 {
82   if (client) {
83     if (client->rng)
84       silc_rng_free(client->rng);
85
86     silc_free(client->silc_client_version);
87     silc_free(client->params);
88     silc_free(client);
89   }
90 }
91
92 /* Initializes the client. This makes all the necessary steps to make
93    the client ready to be run. One must call silc_client_run to run the
94    client. Returns FALSE if error occured, TRUE otherwise. */
95
96 int silc_client_init(SilcClient client)
97 {
98   SILC_LOG_DEBUG(("Initializing client"));
99
100   /* Initialize hash functions for client to use */
101   silc_hash_alloc("md5", &client->md5hash);
102   silc_hash_alloc("sha1", &client->sha1hash);
103
104   /* Initialize none cipher */
105   silc_cipher_alloc("none", &client->none_cipher);
106
107   /* Initialize random number generator */
108   client->rng = silc_rng_alloc();
109   silc_rng_init(client->rng);
110   silc_rng_global_init(client->rng);
111
112   /* Register protocols */
113   silc_client_protocols_register();
114
115   /* Initialize the scheduler */
116   client->schedule = silc_schedule_init(client->params->task_max ?
117                                         client->params->task_max : 200);
118   if (!client->schedule)
119     return FALSE;
120
121   return TRUE;
122 }
123
124 /* Stops the client. This is called to stop the client and thus to stop
125    the program. */
126
127 void silc_client_stop(SilcClient client)
128 {
129   SILC_LOG_DEBUG(("Stopping client"));
130
131   silc_schedule_stop(client->schedule);
132   silc_schedule_uninit(client->schedule);
133
134   silc_client_protocols_unregister();
135
136   SILC_LOG_DEBUG(("Client stopped"));
137 }
138
139 /* Runs the client. This starts the scheduler from the utility library.
140    When this functions returns the execution of the appliation is over. */
141
142 void silc_client_run(SilcClient client)
143 {
144   SILC_LOG_DEBUG(("Running client"));
145
146   /* Start the scheduler, the heart of the SILC client. When this returns
147      the program will be terminated. */
148   silc_schedule(client->schedule);
149 }
150
151 static void silc_client_entry_destructor(SilcIDCache cache,
152                                          SilcIDCacheEntry entry)
153 {
154   silc_free(entry->name);
155 }
156
157 /* Allocates and adds new connection to the client. This adds the allocated
158    connection to the connection table and returns a pointer to it. A client
159    can have multiple connections to multiple servers. Every connection must
160    be added to the client using this function. User data `context' may
161    be sent as argument. This function is normally used only if the 
162    application performed the connecting outside the library. The library
163    however may use this internally. */
164
165 SilcClientConnection silc_client_add_connection(SilcClient client,
166                                                 char *hostname,
167                                                 int port,
168                                                 void *context)
169 {
170   SilcClientConnection conn;
171   int i;
172
173   conn = silc_calloc(1, sizeof(*conn));
174
175   /* Initialize ID caches */
176   conn->client_cache = silc_idcache_alloc(0, SILC_ID_CLIENT, 
177                                           silc_client_entry_destructor);
178   conn->channel_cache = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
179   conn->server_cache = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
180   conn->client = client;
181   conn->remote_host = strdup(hostname);
182   conn->remote_port = port;
183   conn->context = context;
184   conn->pending_commands = silc_dlist_init();
185   conn->ftp_sessions = silc_dlist_init();
186
187   /* Add the connection to connections table */
188   for (i = 0; i < client->conns_count; i++)
189     if (client->conns && !client->conns[i]) {
190       client->conns[i] = conn;
191       return conn;
192     }
193
194   client->conns = silc_realloc(client->conns, sizeof(*client->conns)
195                                * (client->conns_count + 1));
196   client->conns[client->conns_count] = conn;
197   client->conns_count++;
198
199   return conn;
200 }
201
202 /* Removes connection from client. Frees all memory. */
203
204 void silc_client_del_connection(SilcClient client, SilcClientConnection conn)
205 {
206   int i;
207
208   for (i = 0; i < client->conns_count; i++)
209     if (client->conns[i] == conn) {
210
211       silc_idcache_free(conn->client_cache);
212       silc_idcache_free(conn->channel_cache);
213       silc_idcache_free(conn->server_cache);
214       if (conn->pending_commands)
215         silc_dlist_uninit(conn->pending_commands);
216       silc_free(conn->remote_host);
217       silc_dlist_uninit(conn->ftp_sessions);
218       silc_free(conn);
219
220       client->conns[i] = NULL;
221     }
222 }
223
224 /* Adds listener socket to the listener sockets table. This function is
225    used to add socket objects that are listeners to the client.  This should
226    not be used to add other connection objects. */
227
228 void silc_client_add_socket(SilcClient client, SilcSocketConnection sock)
229 {
230   int i;
231
232   if (!client->sockets) {
233     client->sockets = silc_calloc(1, sizeof(*client->sockets));
234     client->sockets[0] = silc_socket_dup(sock);
235     client->sockets_count = 1;
236     return;
237   }
238
239   for (i = 0; i < client->sockets_count; i++) {
240     if (client->sockets[i] == NULL) {
241       client->sockets[i] = silc_socket_dup(sock);
242       return;
243     }
244   }
245
246   client->sockets = silc_realloc(client->sockets, sizeof(*client->sockets) *
247                                  (client->sockets_count + 1));
248   client->sockets[client->sockets_count] = silc_socket_dup(sock);
249   client->sockets_count++;
250 }
251
252 /* Deletes listener socket from the listener sockets table. */
253
254 void silc_client_del_socket(SilcClient client, SilcSocketConnection sock)
255 {
256   int i;
257
258   if (!client->sockets)
259     return;
260
261   for (i = 0; i < client->sockets_count; i++) {
262     if (client->sockets[i] == sock) {
263       silc_socket_free(sock);
264       client->sockets[i] = NULL;
265       return;
266     }
267   }
268 }
269
270 static int 
271 silc_client_connect_to_server_internal(SilcClientInternalConnectContext *ctx)
272 {
273   int sock;
274
275   /* XXX In the future we should give up this non-blocking connect all
276      together and use threads instead. */
277   /* Create connection to server asynchronously */
278   sock = silc_net_create_connection_async(NULL, ctx->port, ctx->host);
279   if (sock < 0)
280     return -1;
281
282   /* Register task that will receive the async connect and will
283      read the result. */
284   ctx->task = silc_schedule_task_add(ctx->client->schedule, sock, 
285                                      silc_client_connect_to_server_start,
286                                      (void *)ctx, 0, 0, 
287                                      SILC_TASK_FD,
288                                      SILC_TASK_PRI_NORMAL);
289   silc_schedule_set_listen_fd(ctx->client->schedule, sock, SILC_TASK_WRITE);
290
291   ctx->sock = sock;
292
293   return sock;
294 }
295
296 /* Connects to remote server. This is the main routine used to connect
297    to SILC server. Returns -1 on error and the created socket otherwise. 
298    The `context' is user context that is saved into the SilcClientConnection
299    that is created after the connection is created. Note that application
300    may handle the connecting process outside the library. If this is the
301    case then this function is not used at all. When the connecting is
302    done the `connect' client operation is called. */
303
304 int silc_client_connect_to_server(SilcClient client, int port,
305                                   char *host, void *context)
306 {
307   SilcClientInternalConnectContext *ctx;
308   SilcClientConnection conn;
309   int sock;
310
311   SILC_LOG_DEBUG(("Connecting to port %d of server %s",
312                   port, host));
313
314   conn = silc_client_add_connection(client, host, port, context);
315
316   client->ops->say(client, conn, SILC_CLIENT_MESSAGE_AUDIT, 
317                    "Connecting to port %d of server %s", port, host);
318
319   /* Allocate internal context for connection process. This is
320      needed as we are doing async connecting. */
321   ctx = silc_calloc(1, sizeof(*ctx));
322   ctx->client = client;
323   ctx->conn = conn;
324   ctx->host = strdup(host);
325   ctx->port = port;
326   ctx->tries = 0;
327
328   /* Do the actual connecting process */
329   sock = silc_client_connect_to_server_internal(ctx);
330   if (sock == -1)
331     silc_client_del_connection(client, conn);
332   return sock;
333 }
334
335 /* Start SILC Key Exchange (SKE) protocol to negotiate shared secret
336    key material between client and server.  This function can be called
337    directly if application is performing its own connecting and does not
338    use the connecting provided by this library. This function is normally
339    used only if the application performed the connecting outside the library.
340    The library however may use this internally. */
341
342 bool silc_client_start_key_exchange(SilcClient client,
343                                     SilcClientConnection conn,
344                                     int fd)
345 {
346   SilcProtocol protocol;
347   SilcClientKEInternalContext *proto_ctx;
348   void *context;
349
350   /* Allocate new socket connection object */
351   silc_socket_alloc(fd, SILC_SOCKET_TYPE_SERVER, (void *)conn, &conn->sock);
352
353   /* Sometimes when doing quick reconnects the new socket may be same as
354      the old one and there might be pending stuff for the old socket. 
355      If new one is same then those pending sutff might cause problems.
356      Make sure they do not do that. */
357   silc_schedule_task_del_by_fd(client->schedule, fd);
358
359   conn->nickname = strdup(client->username);
360   conn->sock->hostname = conn->remote_host;
361   conn->sock->ip = strdup(conn->remote_host);
362   conn->sock->port = conn->remote_port;
363
364   /* Allocate internal Key Exchange context. This is sent to the
365      protocol as context. */
366   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
367   proto_ctx->client = (void *)client;
368   proto_ctx->sock = silc_socket_dup(conn->sock);
369   proto_ctx->rng = client->rng;
370   proto_ctx->responder = FALSE;
371   proto_ctx->send_packet = silc_client_protocol_ke_send_packet;
372   proto_ctx->verify = silc_client_protocol_ke_verify_key;
373
374   /* Perform key exchange protocol. silc_client_connect_to_server_final
375      will be called after the protocol is finished. */
376   silc_protocol_alloc(SILC_PROTOCOL_CLIENT_KEY_EXCHANGE, 
377                       &protocol, (void *)proto_ctx,
378                       silc_client_connect_to_server_second);
379   if (!protocol) {
380     client->ops->say(client, conn, SILC_CLIENT_MESSAGE_ERROR,
381                      "Error: Could not start key exchange protocol");
382     return FALSE;
383   }
384   conn->sock->protocol = protocol;
385
386   /* Register the connection for network input and output. This sets
387      that scheduler will listen for incoming packets for this connection 
388      and sets that outgoing packets may be sent to this connection as well.
389      However, this doesn't set the scheduler for outgoing traffic, it will 
390      be set separately by calling SILC_CLIENT_SET_CONNECTION_FOR_OUTPUT,
391      later when outgoing data is available. */
392   context = (void *)client;
393   SILC_CLIENT_REGISTER_CONNECTION_FOR_IO(fd);
394
395   /* Execute the protocol */
396   silc_protocol_execute(protocol, client->schedule, 0, 0);
397   return TRUE;
398 }
399
400 /* Start of the connection to the remote server. This is called after
401    succesful TCP/IP connection has been established to the remote host. */
402
403 SILC_TASK_CALLBACK(silc_client_connect_to_server_start)
404 {
405   SilcClientInternalConnectContext *ctx =
406     (SilcClientInternalConnectContext *)context;
407   SilcClient client = ctx->client;
408   SilcClientConnection conn = ctx->conn;
409   int opt, opt_len = sizeof(opt);
410
411   SILC_LOG_DEBUG(("Start"));
412
413   /* Check the socket status as it might be in error */
414   silc_net_get_socket_opt(fd, SOL_SOCKET, SO_ERROR, &opt, &opt_len);
415   if (opt != 0) {
416     if (ctx->tries < 2) {
417       /* Connection failed but lets try again */
418       client->ops->say(client, conn, SILC_CLIENT_MESSAGE_ERROR,
419                        "Could not connect to server %s: %s",
420                        ctx->host, strerror(opt));
421       client->ops->say(client, conn, SILC_CLIENT_MESSAGE_AUDIT, 
422                        "Connecting to port %d of server %s resumed", 
423                        ctx->port, ctx->host);
424
425       /* Unregister old connection try */
426       silc_schedule_unset_listen_fd(client->schedule, fd);
427       silc_net_close_connection(fd);
428       silc_schedule_task_del(client->schedule, ctx->task);
429
430       /* Try again */
431       silc_client_connect_to_server_internal(ctx);
432       ctx->tries++;
433     } else {
434       /* Connection failed and we won't try anymore */
435       client->ops->say(client, conn, SILC_CLIENT_MESSAGE_ERROR,
436                        "Could not connect to server %s: %s",
437                        ctx->host, strerror(opt));
438       silc_schedule_unset_listen_fd(client->schedule, fd);
439       silc_net_close_connection(fd);
440       silc_schedule_task_del(client->schedule, ctx->task);
441       silc_free(ctx);
442
443       /* Notify application of failure */
444       client->ops->connect(client, conn, FALSE);
445       silc_client_del_connection(client, conn);
446     }
447     return;
448   }
449
450   silc_schedule_unset_listen_fd(client->schedule, fd);
451   silc_schedule_task_del(client->schedule, ctx->task);
452   silc_free(ctx);
453
454   if (!silc_client_start_key_exchange(client, conn, fd)) {
455     silc_net_close_connection(fd);
456     client->ops->connect(client, conn, FALSE);
457   }
458 }
459
460 /* Second part of the connecting to the server. This executed 
461    authentication protocol. */
462
463 SILC_TASK_CALLBACK(silc_client_connect_to_server_second)
464 {
465   SilcProtocol protocol = (SilcProtocol)context;
466   SilcClientKEInternalContext *ctx = 
467     (SilcClientKEInternalContext *)protocol->context;
468   SilcClient client = (SilcClient)ctx->client;
469   SilcSocketConnection sock = NULL;
470   SilcClientConnAuthInternalContext *proto_ctx;
471
472   SILC_LOG_DEBUG(("Start"));
473
474   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
475       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
476     /* Error occured during protocol */
477     SILC_LOG_DEBUG(("Error during KE protocol"));
478     silc_protocol_free(protocol);
479     silc_ske_free_key_material(ctx->keymat);
480     if (ctx->ske)
481       silc_ske_free(ctx->ske);
482     if (ctx->dest_id)
483       silc_free(ctx->dest_id);
484     ctx->sock->protocol = NULL;
485     silc_socket_free(ctx->sock);
486
487     /* Notify application of failure */
488     client->ops->connect(client, ctx->sock->user_data, FALSE);
489     silc_free(ctx);
490     return;
491   }
492
493   /* We now have the key material as the result of the key exchange
494      protocol. Take the key material into use. Free the raw key material
495      as soon as we've set them into use. */
496   silc_client_protocol_ke_set_keys(ctx->ske, ctx->sock, ctx->keymat,
497                                    ctx->ske->prop->cipher,
498                                    ctx->ske->prop->pkcs,
499                                    ctx->ske->prop->hash,
500                                    ctx->ske->prop->hmac,
501                                    ctx->ske->prop->group,
502                                    ctx->responder);
503   silc_ske_free_key_material(ctx->keymat);
504
505   /* Allocate internal context for the authentication protocol. This
506      is sent as context for the protocol. */
507   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
508   proto_ctx->client = (void *)client;
509   proto_ctx->sock = sock = ctx->sock;
510   proto_ctx->ske = ctx->ske;    /* Save SKE object from previous protocol */
511   proto_ctx->dest_id_type = ctx->dest_id_type;
512   proto_ctx->dest_id = ctx->dest_id;
513
514   /* Free old protocol as it is finished now */
515   silc_protocol_free(protocol);
516   if (ctx->packet)
517     silc_packet_context_free(ctx->packet);
518   silc_free(ctx);
519   sock->protocol = NULL;
520
521   /* Resolve the authentication method to be used in this connection. The
522      completion callback is called after the application has resolved
523      the authentication method. */
524   client->ops->get_auth_method(client, sock->user_data, sock->hostname,
525                                sock->port, silc_client_resolve_auth_method,
526                                proto_ctx);
527 }
528
529 /* Authentication method resolving callback. Application calls this function
530    after we've called the client->ops->get_auth_method client operation
531    to resolve the authentication method. We will continue the executiong
532    of the protocol in this function. */
533
534 void silc_client_resolve_auth_method(bool success,
535                                      SilcProtocolAuthMeth auth_meth,
536                                      const unsigned char *auth_data,
537                                      uint32 auth_data_len, void *context)
538 {
539   SilcClientConnAuthInternalContext *proto_ctx =
540     (SilcClientConnAuthInternalContext *)context;
541   SilcClient client = (SilcClient)proto_ctx->client;
542
543   if (!success)
544     auth_meth = SILC_AUTH_NONE;
545
546   proto_ctx->auth_meth = auth_meth;
547
548   if (auth_data && auth_data_len) {
549     proto_ctx->auth_data = silc_calloc(auth_data_len, sizeof(*auth_data));
550     memcpy(proto_ctx->auth_data, auth_data, auth_data_len);
551     proto_ctx->auth_data_len = auth_data_len;
552   }
553
554   /* Allocate the authenteication protocol and execute it. */
555   silc_protocol_alloc(SILC_PROTOCOL_CLIENT_CONNECTION_AUTH, 
556                       &proto_ctx->sock->protocol, (void *)proto_ctx, 
557                       silc_client_connect_to_server_final);
558
559   /* Execute the protocol */
560   silc_protocol_execute(proto_ctx->sock->protocol, client->schedule, 0, 0);
561 }
562
563 /* Finalizes the connection to the remote SILC server. This is called
564    after authentication protocol has been completed. This send our
565    user information to the server to receive our client ID from
566    server. */
567
568 SILC_TASK_CALLBACK(silc_client_connect_to_server_final)
569 {
570   SilcProtocol protocol = (SilcProtocol)context;
571   SilcClientConnAuthInternalContext *ctx = 
572     (SilcClientConnAuthInternalContext *)protocol->context;
573   SilcClient client = (SilcClient)ctx->client;
574   SilcClientConnection conn = (SilcClientConnection)ctx->sock->user_data;
575   SilcBuffer packet;
576
577   SILC_LOG_DEBUG(("Start"));
578
579   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
580       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
581     /* Error occured during protocol */
582     SILC_LOG_DEBUG(("Error during authentication protocol"));
583     silc_protocol_free(protocol);
584     if (ctx->auth_data)
585       silc_free(ctx->auth_data);
586     if (ctx->ske)
587       silc_ske_free(ctx->ske);
588     if (ctx->dest_id)
589       silc_free(ctx->dest_id);
590     conn->sock->protocol = NULL;
591     silc_socket_free(ctx->sock);
592
593     /* Notify application of failure */
594     client->ops->connect(client, ctx->sock->user_data, FALSE);
595     silc_free(ctx);
596     return;
597   }
598
599   /* Send NEW_CLIENT packet to the server. We will become registered
600      to the SILC network after sending this packet and we will receive
601      client ID from the server. */
602   packet = silc_buffer_alloc(2 + 2 + strlen(client->username) + 
603                              strlen(client->realname));
604   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
605   silc_buffer_format(packet,
606                      SILC_STR_UI_SHORT(strlen(client->username)),
607                      SILC_STR_UI_XNSTRING(client->username,
608                                           strlen(client->username)),
609                      SILC_STR_UI_SHORT(strlen(client->realname)),
610                      SILC_STR_UI_XNSTRING(client->realname,
611                                           strlen(client->realname)),
612                      SILC_STR_END);
613
614   /* Send the packet */
615   silc_client_packet_send(client, ctx->sock, SILC_PACKET_NEW_CLIENT,
616                           NULL, 0, NULL, NULL, 
617                           packet->data, packet->len, TRUE);
618   silc_buffer_free(packet);
619
620   /* Save remote ID. */
621   conn->remote_id = ctx->dest_id;
622   conn->remote_id_data = silc_id_id2str(ctx->dest_id, SILC_ID_SERVER);
623   conn->remote_id_data_len = silc_id_get_len(ctx->dest_id, SILC_ID_SERVER);
624
625   /* Register re-key timeout */
626   conn->rekey->timeout = client->params->rekey_secs;
627   conn->rekey->context = (void *)client;
628   silc_schedule_task_add(client->schedule, conn->sock->sock, 
629                          silc_client_rekey_callback,
630                          (void *)conn->sock, conn->rekey->timeout, 0,
631                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
632
633   silc_protocol_free(protocol);
634   if (ctx->auth_data)
635     silc_free(ctx->auth_data);
636   if (ctx->ske)
637     silc_ske_free(ctx->ske);
638   silc_socket_free(ctx->sock);
639   silc_free(ctx);
640   conn->sock->protocol = NULL;
641 }
642
643 /* Internal routine that sends packet or marks packet to be sent. This
644    is used directly only in special cases. Normal cases should use
645    silc_server_packet_send. Returns < 0 on error. */
646
647 int silc_client_packet_send_real(SilcClient client,
648                                  SilcSocketConnection sock,
649                                  bool force_send)
650 {
651   int ret;
652
653   /* If rekey protocol is active we must assure that all packets are
654      sent through packet queue. */
655   if (SILC_CLIENT_IS_REKEY(sock))
656     force_send = FALSE;
657
658   /* If outbound data is already pending do not force send */
659   if (SILC_IS_OUTBUF_PENDING(sock))
660     force_send = FALSE;
661
662   /* Send the packet */
663   ret = silc_packet_send(sock, force_send);
664   if (ret != -2)
665     return ret;
666
667   /* Mark that there is some outgoing data available for this connection. 
668      This call sets the connection both for input and output (the input
669      is set always and this call keeps the input setting, actually). 
670      Actual data sending is performed by silc_client_packet_process. */
671   SILC_CLIENT_SET_CONNECTION_FOR_OUTPUT(client->schedule, sock->sock);
672
673   /* Mark to socket that data is pending in outgoing buffer. This flag
674      is needed if new data is added to the buffer before the earlier
675      put data is sent to the network. */
676   SILC_SET_OUTBUF_PENDING(sock);
677
678   return 0;
679 }
680
681 /* Packet processing callback. This is used to send and receive packets
682    from network. This is generic task. */
683
684 SILC_TASK_CALLBACK_GLOBAL(silc_client_packet_process)
685 {
686   SilcClient client = (SilcClient)context;
687   SilcSocketConnection sock = NULL;
688   SilcClientConnection conn;
689   int ret;
690
691   SILC_LOG_DEBUG(("Processing packet"));
692
693   SILC_CLIENT_GET_SOCK(client, fd, sock);
694   if (sock == NULL)
695     return;
696
697   conn = (SilcClientConnection)sock->user_data;
698
699   /* Packet sending */
700   if (type == SILC_TASK_WRITE) {
701     /* Do not send data to disconnected connection */
702     if (SILC_IS_DISCONNECTED(sock))
703       return;
704
705     if (sock->outbuf->data - sock->outbuf->head)
706       silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
707
708     ret = silc_packet_send(sock, TRUE);
709
710     /* If returned -2 could not write to connection now, will do
711        it later. */
712     if (ret == -2)
713       return;
714
715     /* Error */
716     if (ret == -1)
717       return;
718     
719     /* The packet has been sent and now it is time to set the connection
720        back to only for input. When there is again some outgoing data 
721        available for this connection it will be set for output as well. 
722        This call clears the output setting and sets it only for input. */
723     SILC_CLIENT_SET_CONNECTION_FOR_INPUT(client->schedule, fd);
724     SILC_UNSET_OUTBUF_PENDING(sock);
725
726     silc_buffer_clear(sock->outbuf);
727     return;
728   }
729
730   /* Packet receiving */
731   if (type == SILC_TASK_READ) {
732     /* Read data from network */
733     ret = silc_packet_receive(sock);
734     if (ret < 0)
735       return;
736     
737     /* EOF */
738     if (ret == 0) {
739       SILC_LOG_DEBUG(("Read EOF"));
740
741       /* If connection is disconnecting already we will finally
742          close the connection */
743       if (SILC_IS_DISCONNECTING(sock)) {
744         if (sock == conn->sock && sock->type != SILC_SOCKET_TYPE_CLIENT)
745           client->ops->disconnect(client, conn);
746         silc_client_close_connection(client, sock, conn);
747         return;
748       }
749       
750       SILC_LOG_DEBUG(("EOF from connection %d", sock->sock));
751       if (sock == conn->sock && sock->type != SILC_SOCKET_TYPE_CLIENT)
752         client->ops->disconnect(client, conn);
753       silc_client_close_connection(client, sock, conn);
754       return;
755     }
756
757     /* Process the packet. This will call the parser that will then
758        decrypt and parse the packet. */
759     if (sock->type != SILC_SOCKET_TYPE_UNKNOWN)
760       silc_packet_receive_process(sock, FALSE, conn->receive_key, 
761                                   conn->hmac_receive, conn->psn_receive,
762                                   silc_client_packet_parse, client);
763     else
764       silc_packet_receive_process(sock, FALSE, NULL, NULL, 0, 
765                                   silc_client_packet_parse, client);
766   }
767 }
768
769 /* Parser callback called by silc_packet_receive_process. Thie merely
770    registers timeout that will handle the actual parsing when appropriate. */
771
772 static bool silc_client_packet_parse(SilcPacketParserContext *parser_context,
773                                      void *context)
774 {
775   SilcClient client = (SilcClient)context;
776   SilcSocketConnection sock = parser_context->sock;
777   SilcClientConnection conn = (SilcClientConnection)sock->user_data;
778   SilcPacketContext *packet = parser_context->packet;
779   SilcPacketType ret;
780
781   if (conn && conn->hmac_receive)
782     conn->psn_receive = parser_context->packet->sequence + 1;
783
784   /* Parse the packet immediately */
785   if (parser_context->normal)
786     ret = silc_packet_parse(packet, conn->receive_key);
787   else
788     ret = silc_packet_parse_special(packet, conn->receive_key);
789
790   if (ret == SILC_PACKET_NONE) {
791     silc_packet_context_free(packet);
792     silc_free(parser_context);
793     return FALSE;
794   }
795   
796   /* If protocol for this connection is key exchange or rekey then we'll
797      process all packets synchronously, since there might be packets in
798      queue that we are not able to decrypt without first processing the
799      packets before them. */
800   if (sock->protocol && sock->protocol->protocol && 
801       (sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_KEY_EXCHANGE ||
802        sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_REKEY)) {
803
804     /* Parse the incoming packet type */
805     silc_client_packet_parse_type(client, sock, packet);
806     silc_packet_context_free(packet);
807     silc_free(parser_context);
808
809     /* Reprocess the buffer since we'll return FALSE. This is because
810        the `conn->receive_key' might have become valid by processing
811        the previous packet */
812     if (sock->type != SILC_SOCKET_TYPE_UNKNOWN)
813       silc_packet_receive_process(sock, FALSE, conn->receive_key, 
814                                   conn->hmac_receive, conn->psn_receive,
815                                   silc_client_packet_parse, client);
816     else
817       silc_packet_receive_process(sock, FALSE, NULL, NULL, 0, 
818                                   silc_client_packet_parse, client);
819     
820     return FALSE;
821   }
822
823   /* Parse the incoming packet type */
824   silc_client_packet_parse_type(client, sock, packet);
825   silc_packet_context_free(packet);
826   silc_free(parser_context);
827   return TRUE;
828 }
829
830 /* Parses the packet type and calls what ever routines the packet type
831    requires. This is done for all incoming packets. */
832
833 void silc_client_packet_parse_type(SilcClient client, 
834                                    SilcSocketConnection sock,
835                                    SilcPacketContext *packet)
836 {
837   SilcBuffer buffer = packet->buffer;
838   SilcPacketType type = packet->type;
839
840   SILC_LOG_DEBUG(("Parsing packet type %d", type));
841
842   /* Parse the packet type */
843   switch(type) {
844   case SILC_PACKET_DISCONNECT:
845     silc_client_disconnected_by_server(client, sock, buffer);
846     break;
847   case SILC_PACKET_SUCCESS:
848     /*
849      * Success received for something. For now we can have only
850      * one protocol for connection executing at once hence this
851      * success message is for whatever protocol is executing currently.
852      */
853     if (sock->protocol)
854       silc_protocol_execute(sock->protocol, client->schedule, 0, 0);
855     break;
856   case SILC_PACKET_FAILURE:
857     /*
858      * Failure received for some protocol. Set the protocol state to 
859      * error and call the protocol callback. This fill cause error on
860      * protocol and it will call the final callback.
861      */
862     silc_client_process_failure(client, sock, packet);
863     break;
864   case SILC_PACKET_REJECT:
865     break;
866
867   case SILC_PACKET_NOTIFY:
868     /*
869      * Received notify message 
870      */
871     silc_client_notify_by_server(client, sock, packet);
872     break;
873
874   case SILC_PACKET_ERROR:
875     /*
876      * Received error message
877      */
878     silc_client_error_by_server(client, sock, buffer);
879     break;
880
881   case SILC_PACKET_CHANNEL_MESSAGE:
882     /*
883      * Received message to (from, actually) a channel
884      */
885     silc_client_channel_message(client, sock, packet);
886     break;
887   case SILC_PACKET_CHANNEL_KEY:
888     /*
889      * Received key for a channel. By receiving this key the client will be
890      * able to talk to the channel it has just joined. This can also be
891      * a new key for existing channel as keys expire peridiocally.
892      */
893     silc_client_receive_channel_key(client, sock, buffer);
894     break;
895
896   case SILC_PACKET_PRIVATE_MESSAGE:
897     /*
898      * Received private message
899      */
900     silc_client_private_message(client, sock, packet);
901     break;
902   case SILC_PACKET_PRIVATE_MESSAGE_KEY:
903     /*
904      * Received private message key
905      */
906     break;
907
908   case SILC_PACKET_COMMAND_REPLY:
909     /*
910      * Recived reply for a command
911      */
912     silc_client_command_reply_process(client, sock, packet);
913     break;
914
915   case SILC_PACKET_KEY_EXCHANGE:
916     if (sock->protocol && sock->protocol->protocol && 
917         sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_KEY_EXCHANGE) {
918       SilcClientKEInternalContext *proto_ctx = 
919         (SilcClientKEInternalContext *)sock->protocol->context;
920
921       proto_ctx->packet = silc_packet_context_dup(packet);
922       proto_ctx->dest_id_type = packet->src_id_type;
923       proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
924                                           packet->src_id_type);
925       if (!proto_ctx->dest_id)
926         break;
927
928       /* Let the protocol handle the packet */
929       silc_protocol_execute(sock->protocol, client->schedule, 0, 0);
930     } else {
931       SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
932                       "protocol active, packet dropped."));
933     }
934     break;
935
936   case SILC_PACKET_KEY_EXCHANGE_1:
937     if (sock->protocol && sock->protocol->protocol && 
938         (sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_KEY_EXCHANGE ||
939          sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_REKEY)) {
940
941       if (sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_REKEY) {
942         SilcClientRekeyInternalContext *proto_ctx = 
943           (SilcClientRekeyInternalContext *)sock->protocol->context;
944         
945         if (proto_ctx->packet)
946           silc_packet_context_free(proto_ctx->packet);
947         
948         proto_ctx->packet = silc_packet_context_dup(packet);
949
950         /* Let the protocol handle the packet */
951         silc_protocol_execute(sock->protocol, client->schedule, 0, 0);
952       } else {
953         SilcClientKEInternalContext *proto_ctx = 
954           (SilcClientKEInternalContext *)sock->protocol->context;
955         
956         if (proto_ctx->packet)
957           silc_packet_context_free(proto_ctx->packet);
958         
959         proto_ctx->packet = silc_packet_context_dup(packet);
960         proto_ctx->dest_id_type = packet->src_id_type;
961         proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
962                                             packet->src_id_type);
963         if (!proto_ctx->dest_id)
964           break;
965         
966         /* Let the protocol handle the packet */
967         silc_protocol_execute(sock->protocol, client->schedule, 0, 0);
968       }
969     } else {
970       SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
971                       "protocol active, packet dropped."));
972     }
973     break;
974   case SILC_PACKET_KEY_EXCHANGE_2:
975     if (sock->protocol && sock->protocol->protocol && 
976         (sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_KEY_EXCHANGE ||
977          sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_REKEY)) {
978
979       if (sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_REKEY) {
980         SilcClientRekeyInternalContext *proto_ctx = 
981           (SilcClientRekeyInternalContext *)sock->protocol->context;
982         
983         if (proto_ctx->packet)
984           silc_packet_context_free(proto_ctx->packet);
985         
986         proto_ctx->packet = silc_packet_context_dup(packet);
987
988         /* Let the protocol handle the packet */
989         silc_protocol_execute(sock->protocol, client->schedule, 0, 0);
990       } else {
991         SilcClientKEInternalContext *proto_ctx = 
992           (SilcClientKEInternalContext *)sock->protocol->context;
993         
994         if (proto_ctx->packet)
995           silc_packet_context_free(proto_ctx->packet);
996         
997         proto_ctx->packet = silc_packet_context_dup(packet);
998         proto_ctx->dest_id_type = packet->src_id_type;
999         proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1000                                             packet->src_id_type);
1001         if (!proto_ctx->dest_id)
1002           break;
1003         
1004         /* Let the protocol handle the packet */
1005         silc_protocol_execute(sock->protocol, client->schedule, 0, 0);
1006       }
1007     } else {
1008       SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1009                       "protocol active, packet dropped."));
1010     }
1011     break;
1012
1013   case SILC_PACKET_NEW_ID:
1014     {
1015       /*
1016        * Received new ID from server. This packet is received at
1017        * the connection to the server.  New ID is also received when 
1018        * user changes nickname but in that case the new ID is received
1019        * as command reply and not as this packet type.
1020        */
1021       SilcIDPayload idp;
1022
1023       idp = silc_id_payload_parse(buffer);
1024       if (!idp)
1025         break;
1026       if (silc_id_payload_get_type(idp) != SILC_ID_CLIENT)
1027         break;
1028
1029       silc_client_receive_new_id(client, sock, idp);
1030       silc_id_payload_free(idp);
1031       break;
1032     }
1033
1034   case SILC_PACKET_HEARTBEAT:
1035     /*
1036      * Received heartbeat packet
1037      */
1038     SILC_LOG_DEBUG(("Heartbeat packet"));
1039     break;
1040
1041   case SILC_PACKET_KEY_AGREEMENT:
1042     /*
1043      * Received key agreement packet
1044      */
1045     SILC_LOG_DEBUG(("Key agreement packet"));
1046     silc_client_key_agreement(client, sock, packet);
1047     break;
1048
1049   case SILC_PACKET_REKEY:
1050     SILC_LOG_DEBUG(("Re-key packet"));
1051     /* We ignore this for now */
1052     break;
1053
1054   case SILC_PACKET_REKEY_DONE:
1055     SILC_LOG_DEBUG(("Re-key done packet"));
1056
1057     if (sock->protocol && sock->protocol->protocol && 
1058         sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_REKEY) {
1059
1060       SilcClientRekeyInternalContext *proto_ctx = 
1061         (SilcClientRekeyInternalContext *)sock->protocol->context;
1062       
1063       if (proto_ctx->packet)
1064         silc_packet_context_free(proto_ctx->packet);
1065       
1066       proto_ctx->packet = silc_packet_context_dup(packet);
1067
1068       /* Let the protocol handle the packet */
1069       if (proto_ctx->responder == FALSE)
1070         silc_protocol_execute(sock->protocol, client->schedule, 0, 0);
1071       else
1072         /* Let the protocol handle the packet */
1073         silc_protocol_execute(sock->protocol, client->schedule, 
1074                               0, 100000);
1075     } else {
1076       SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
1077                       "protocol active, packet dropped."));
1078     }
1079     break;
1080
1081   case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1082     /*
1083      * Reveived reply to our connection authentication method request
1084      * packet. This is used to resolve the authentication method for the
1085      * current session from the server if the client does not know it.
1086      */
1087     silc_client_connection_auth_request(client, sock, packet);
1088     break;
1089
1090   case SILC_PACKET_FTP:
1091     /* Received file transfer packet. */
1092     silc_client_ftp(client, sock, packet);
1093     break;
1094
1095   default:
1096     SILC_LOG_DEBUG(("Incorrect packet type %d, packet dropped", type));
1097     break;
1098   }
1099 }
1100
1101 /* Sends packet. This doesn't actually send the packet instead it assembles
1102    it and marks it to be sent. However, if force_send is TRUE the packet
1103    is sent immediately. if dst_id, cipher and hmac are NULL those parameters
1104    will be derived from sock argument. Otherwise the valid arguments sent
1105    are used. */
1106
1107 void silc_client_packet_send(SilcClient client, 
1108                              SilcSocketConnection sock,
1109                              SilcPacketType type, 
1110                              void *dst_id,
1111                              SilcIdType dst_id_type,
1112                              SilcCipher cipher,
1113                              SilcHmac hmac,
1114                              unsigned char *data, 
1115                              uint32 data_len, 
1116                              int force_send)
1117 {
1118   SilcPacketContext packetdata;
1119   int block_len;
1120   uint32 sequence = 0;
1121
1122   if (!sock)
1123     return;
1124
1125   SILC_LOG_DEBUG(("Sending packet, type %d", type));
1126
1127   /* Get data used in the packet sending, keys and stuff */
1128   if ((!cipher || !hmac || !dst_id) && sock->user_data) {
1129     if (!cipher && ((SilcClientConnection)sock->user_data)->send_key)
1130       cipher = ((SilcClientConnection)sock->user_data)->send_key;
1131
1132     if (!hmac && ((SilcClientConnection)sock->user_data)->hmac_send)
1133       hmac = ((SilcClientConnection)sock->user_data)->hmac_send;
1134
1135     if (!dst_id && ((SilcClientConnection)sock->user_data)->remote_id) {
1136       dst_id = ((SilcClientConnection)sock->user_data)->remote_id;
1137       dst_id_type = SILC_ID_SERVER;
1138     }
1139
1140     if (hmac)
1141       sequence = ((SilcClientConnection)sock->user_data)->psn_send++;
1142   }
1143
1144   block_len = cipher ? silc_cipher_get_block_len(cipher) : 0;
1145
1146   /* Set the packet context pointers */
1147   packetdata.flags = 0;
1148   packetdata.type = type;
1149   if (sock->user_data && 
1150       ((SilcClientConnection)sock->user_data)->local_id_data) {
1151     packetdata.src_id = ((SilcClientConnection)sock->user_data)->local_id_data;
1152     packetdata.src_id_len = 
1153       silc_id_get_len(((SilcClientConnection)sock->user_data)->local_id,
1154                       SILC_ID_CLIENT);
1155   } else { 
1156     packetdata.src_id = silc_calloc(SILC_ID_CLIENT_LEN, sizeof(unsigned char));
1157     packetdata.src_id_len = SILC_ID_CLIENT_LEN;
1158   }
1159   packetdata.src_id_type = SILC_ID_CLIENT;
1160   if (dst_id) {
1161     packetdata.dst_id = silc_id_id2str(dst_id, dst_id_type);
1162     packetdata.dst_id_len = silc_id_get_len(dst_id, dst_id_type);
1163     packetdata.dst_id_type = dst_id_type;
1164   } else {
1165     packetdata.dst_id = NULL;
1166     packetdata.dst_id_len = 0;
1167     packetdata.dst_id_type = SILC_ID_NONE;
1168   }
1169   packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN + 
1170     packetdata.src_id_len + packetdata.dst_id_len;
1171   packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen, block_len);
1172
1173   /* Prepare outgoing data buffer for packet sending */
1174   silc_packet_send_prepare(sock, 
1175                            SILC_PACKET_HEADER_LEN +
1176                            packetdata.src_id_len + 
1177                            packetdata.dst_id_len,
1178                            packetdata.padlen,
1179                            data_len);
1180
1181   SILC_LOG_DEBUG(("Putting data to outgoing buffer, len %d", data_len));
1182
1183   packetdata.buffer = sock->outbuf;
1184
1185   /* Put the data to the buffer */
1186   if (data && data_len)
1187     silc_buffer_put(sock->outbuf, data, data_len);
1188
1189   /* Create the outgoing packet */
1190   silc_packet_assemble(&packetdata, cipher);
1191
1192   /* Encrypt the packet */
1193   if (cipher)
1194     silc_packet_encrypt(cipher, hmac, sequence, sock->outbuf, 
1195                         sock->outbuf->len);
1196
1197   SILC_LOG_HEXDUMP(("Packet (%d), len %d", sequence, sock->outbuf->len),
1198                    sock->outbuf->data, sock->outbuf->len);
1199
1200   /* Now actually send the packet */
1201   silc_client_packet_send_real(client, sock, force_send);
1202 }
1203
1204 void silc_client_packet_queue_purge(SilcClient client,
1205                                     SilcSocketConnection sock)
1206 {
1207   if (sock && SILC_IS_OUTBUF_PENDING(sock) && 
1208       (SILC_IS_DISCONNECTED(sock) == FALSE)) {
1209     if (sock->outbuf->data - sock->outbuf->head)
1210       silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1211
1212     silc_packet_send(sock, TRUE);
1213
1214     SILC_CLIENT_SET_CONNECTION_FOR_INPUT(client->schedule, sock->sock);
1215     SILC_UNSET_OUTBUF_PENDING(sock);
1216     silc_buffer_clear(sock->outbuf);
1217   }
1218 }
1219
1220 /* Closes connection to remote end. Free's all allocated data except
1221    for some information such as nickname etc. that are valid at all time. 
1222    If the `sock' is NULL then the conn->sock will be used.  If `sock' is
1223    provided it will be checked whether the sock and `conn->sock' are the
1224    same (they can be different, ie. a socket can use `conn' as its
1225    connection but `conn->sock' might be actually a different connection
1226    than the `sock'). */
1227
1228 void silc_client_close_connection(SilcClient client,
1229                                   SilcSocketConnection sock,
1230                                   SilcClientConnection conn)
1231 {
1232   int del = FALSE;
1233
1234   if (!sock || (sock && conn->sock == sock))
1235     del = TRUE;
1236   if (!sock)
1237     sock = conn->sock;
1238
1239   /* We won't listen for this connection anymore */
1240   silc_schedule_unset_listen_fd(client->schedule, sock->sock);
1241
1242   /* Unregister all tasks */
1243   silc_schedule_task_del_by_fd(client->schedule, sock->sock);
1244   silc_schedule_task_del_by_fd(client->schedule, sock->sock);
1245
1246   /* Close the actual connection */
1247   silc_net_close_connection(sock->sock);
1248
1249   /* Cancel any active protocol */
1250   if (sock->protocol) {
1251     if (sock->protocol->protocol->type == 
1252         SILC_PROTOCOL_CLIENT_KEY_EXCHANGE ||
1253         sock->protocol->protocol->type == 
1254         SILC_PROTOCOL_CLIENT_CONNECTION_AUTH) {
1255       sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
1256       silc_protocol_execute_final(sock->protocol, client->schedule);
1257       /* The application will recall this function with these protocols
1258          (the ops->connect client operation). */
1259       return;
1260     } else {
1261       sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
1262       silc_protocol_execute_final(sock->protocol, client->schedule);
1263       sock->protocol = NULL;
1264     }
1265   }
1266
1267   /* Free everything */
1268   if (del && sock->user_data) {
1269     /* Free all cache entries */
1270     SilcIDCacheList list;
1271     SilcIDCacheEntry entry;
1272     bool ret;
1273
1274     if (silc_idcache_get_all(conn->client_cache, &list)) {
1275       ret = silc_idcache_list_first(list, &entry);
1276       while (ret) {
1277         silc_client_del_client(client, conn, entry->context);
1278         ret = silc_idcache_list_next(list, &entry);
1279       }
1280       silc_idcache_list_free(list);
1281     }
1282
1283     if (silc_idcache_get_all(conn->channel_cache, &list)) {
1284       ret = silc_idcache_list_first(list, &entry);
1285       while (ret) {
1286         silc_client_del_channel(client, conn, entry->context);
1287         ret = silc_idcache_list_next(list, &entry);
1288       }
1289       silc_idcache_list_free(list);
1290     }
1291
1292     if (silc_idcache_get_all(conn->server_cache, &list)) {
1293       ret = silc_idcache_list_first(list, &entry);
1294       while (ret) {
1295         silc_client_del_server(client, conn, entry->context);
1296         ret = silc_idcache_list_next(list, &entry);
1297       }
1298       silc_idcache_list_free(list);
1299     }
1300
1301     /* Clear ID caches */
1302     if (conn->client_cache)
1303       silc_idcache_del_all(conn->client_cache);
1304     if (conn->channel_cache)
1305       silc_idcache_del_all(conn->channel_cache);
1306     if (conn->server_cache)
1307       silc_idcache_del_all(conn->server_cache);
1308
1309     /* Free data (my ID is freed in above silc_client_del_client) */
1310     if (conn->remote_host)
1311       silc_free(conn->remote_host);
1312     if (conn->local_id_data)
1313       silc_free(conn->local_id_data);
1314     if (conn->send_key)
1315       silc_cipher_free(conn->send_key);
1316     if (conn->receive_key)
1317       silc_cipher_free(conn->receive_key);
1318     if (conn->hmac_send)
1319       silc_hmac_free(conn->hmac_send);
1320     if (conn->hmac_receive)
1321       silc_hmac_free(conn->hmac_receive);
1322     if (conn->pending_commands)
1323       silc_dlist_uninit(conn->pending_commands);
1324     if (conn->rekey)
1325       silc_free(conn->rekey);
1326
1327     if (conn->active_session) {
1328       sock->user_data = NULL;
1329       silc_client_ftp_session_free(conn->active_session);
1330       conn->active_session = NULL;
1331     }
1332
1333     silc_client_ftp_free_sessions(client, conn);
1334
1335     memset(conn, 0, sizeof(*conn));
1336     silc_client_del_connection(client, conn);
1337   }
1338
1339   silc_socket_free(sock);
1340 }
1341
1342 /* Called when we receive disconnection packet from server. This 
1343    closes our end properly and displays the reason of the disconnection
1344    on the screen. */
1345
1346 void silc_client_disconnected_by_server(SilcClient client,
1347                                         SilcSocketConnection sock,
1348                                         SilcBuffer message)
1349 {
1350   char *msg;
1351
1352   SILC_LOG_DEBUG(("Server disconnected us, sock %d", sock->sock));
1353
1354   msg = silc_calloc(message->len + 1, sizeof(char));
1355   memcpy(msg, message->data, message->len);
1356   client->ops->say(client, sock->user_data, SILC_CLIENT_MESSAGE_AUDIT, msg);
1357   silc_free(msg);
1358
1359   SILC_SET_DISCONNECTED(sock);
1360   silc_client_close_connection(client, sock, sock->user_data);
1361 }
1362
1363 /* Received error message from server. Display it on the screen. 
1364    We don't take any action what so ever of the error message. */
1365
1366 void silc_client_error_by_server(SilcClient client,
1367                                  SilcSocketConnection sock,
1368                                  SilcBuffer message)
1369 {
1370   char *msg;
1371
1372   msg = silc_calloc(message->len + 1, sizeof(char));
1373   memcpy(msg, message->data, message->len);
1374   client->ops->say(client, sock->user_data, SILC_CLIENT_MESSAGE_AUDIT, msg);
1375   silc_free(msg);
1376 }
1377
1378 /* Processes the received new Client ID from server. Old Client ID is
1379    deleted from cache and new one is added. */
1380
1381 void silc_client_receive_new_id(SilcClient client,
1382                                 SilcSocketConnection sock,
1383                                 SilcIDPayload idp)
1384 {
1385   SilcClientConnection conn = (SilcClientConnection)sock->user_data;
1386   int connecting = FALSE;
1387   SilcBuffer sidp;
1388
1389   if (!conn->local_entry)
1390     connecting = TRUE;
1391
1392   /* Delete old ID from ID cache */
1393   if (conn->local_id) {
1394     silc_idcache_del_by_context(conn->client_cache, conn->local_entry);
1395     silc_free(conn->local_id);
1396   }
1397   
1398   /* Save the new ID */
1399
1400   if (conn->local_id_data)
1401     silc_free(conn->local_id_data);
1402
1403   conn->local_id = silc_id_payload_get_id(idp);
1404   conn->local_id_data = silc_id_payload_get_data(idp);
1405   conn->local_id_data_len = silc_id_payload_get_len(idp);;
1406
1407   if (!conn->local_entry)
1408     conn->local_entry = silc_calloc(1, sizeof(*conn->local_entry));
1409
1410   conn->local_entry->nickname = conn->nickname;
1411   if (!conn->local_entry->username)
1412     conn->local_entry->username = strdup(client->username);
1413   if (!conn->local_entry->hostname)
1414     conn->local_entry->hostname = strdup(client->hostname);
1415   conn->local_entry->server = strdup(conn->remote_host);
1416   conn->local_entry->id = conn->local_id;
1417   conn->local_entry->valid = TRUE;
1418   
1419   /* Put it to the ID cache */
1420   silc_idcache_add(conn->client_cache, strdup(conn->nickname), conn->local_id, 
1421                    (void *)conn->local_entry, FALSE);
1422
1423   /* Issue INFO command to fetch the real server name and server information
1424      and other stuff. */
1425   sidp = silc_id_payload_encode(conn->remote_id, SILC_ID_SERVER);
1426   silc_client_send_command(client, conn, SILC_COMMAND_INFO,
1427                            ++conn->cmd_ident, 1, 2, sidp->data, sidp->len);
1428   silc_buffer_free(sidp);
1429
1430   /* Notify application of successful connection. We do it here now that
1431      we've received the Client ID and are allowed to send traffic. */
1432   if (connecting)
1433     client->ops->connect(client, conn, TRUE);
1434 }
1435
1436 /* Processed received Channel ID for a channel. This is called when client
1437    joins to channel and server replies with channel ID. The ID is cached. 
1438    Returns the created channel entry. This is also called when received
1439    channel ID in for example USERS command reply that we do not have. */
1440
1441 SilcChannelEntry silc_client_new_channel_id(SilcClient client,
1442                                             SilcSocketConnection sock,
1443                                             char *channel_name,
1444                                             uint32 mode, 
1445                                             SilcIDPayload idp)
1446 {
1447   SilcClientConnection conn = (SilcClientConnection)sock->user_data;
1448   SilcChannelEntry channel;
1449
1450   SILC_LOG_DEBUG(("New channel ID"));
1451
1452   channel = silc_calloc(1, sizeof(*channel));
1453   channel->channel_name = channel_name;
1454   channel->id = silc_id_payload_get_id(idp);
1455   channel->mode = mode;
1456   silc_list_init(channel->clients, struct SilcChannelUserStruct, next);
1457
1458   /* Put it to the ID cache */
1459   silc_idcache_add(conn->channel_cache, channel->channel_name, 
1460                    (void *)channel->id, (void *)channel, FALSE);
1461
1462   return channel;
1463 }
1464
1465 /* Removes a client entry from all channel it has joined. This really is
1466    a performance killer (client_entry should have pointers to channel 
1467    entry list). */
1468
1469 void silc_client_remove_from_channels(SilcClient client,
1470                                       SilcClientConnection conn,
1471                                       SilcClientEntry client_entry)
1472 {
1473   SilcIDCacheEntry id_cache;
1474   SilcIDCacheList list;
1475   SilcChannelEntry channel;
1476   SilcChannelUser chu;
1477
1478   if (!silc_idcache_get_all(conn->channel_cache, &list))
1479     return;
1480
1481   silc_idcache_list_first(list, &id_cache);
1482   channel = (SilcChannelEntry)id_cache->context;
1483   
1484   while (channel) {
1485     
1486     /* Remove client from channel */
1487     silc_list_start(channel->clients);
1488     while ((chu = silc_list_get(channel->clients)) != SILC_LIST_END) {
1489       if (chu->client == client_entry) {
1490         silc_list_del(channel->clients, chu);
1491         silc_free(chu);
1492         break;
1493       }
1494     }
1495
1496     if (!silc_idcache_list_next(list, &id_cache))
1497       break;
1498     
1499     channel = (SilcChannelEntry)id_cache->context;
1500   }
1501
1502   silc_idcache_list_free(list);
1503 }
1504
1505 /* Replaces `old' client entries from all channels to `new' client entry.
1506    This can be called for example when nickname changes and old ID entry
1507    is replaced from ID cache with the new one. If the old ID entry is only
1508    updated, then this fucntion needs not to be called. */
1509
1510 void silc_client_replace_from_channels(SilcClient client, 
1511                                        SilcClientConnection conn,
1512                                        SilcClientEntry old,
1513                                        SilcClientEntry new)
1514 {
1515   SilcIDCacheEntry id_cache;
1516   SilcIDCacheList list;
1517   SilcChannelEntry channel;
1518   SilcChannelUser chu;
1519
1520   if (!silc_idcache_get_all(conn->channel_cache, &list))
1521     return;
1522
1523   silc_idcache_list_first(list, &id_cache);
1524   channel = (SilcChannelEntry)id_cache->context;
1525   
1526   while (channel) {
1527     
1528     /* Replace client entry */
1529     silc_list_start(channel->clients);
1530     while ((chu = silc_list_get(channel->clients)) != SILC_LIST_END) {
1531       if (chu->client == old) {
1532         chu->client = new;
1533         break;
1534       }
1535     }
1536
1537     if (!silc_idcache_list_next(list, &id_cache))
1538       break;
1539     
1540     channel = (SilcChannelEntry)id_cache->context;
1541   }
1542
1543   silc_idcache_list_free(list);
1544 }
1545
1546 /* Registers failure timeout to process the received failure packet
1547    with timeout. */
1548
1549 void silc_client_process_failure(SilcClient client,
1550                                  SilcSocketConnection sock,
1551                                  SilcPacketContext *packet)
1552 {
1553   uint32 failure = 0;
1554
1555   if (sock->protocol) {
1556     if (packet->buffer->len >= 4)
1557       SILC_GET32_MSB(failure, packet->buffer->data);
1558
1559     /* Notify application */
1560     client->ops->failure(client, sock->user_data, sock->protocol,
1561                          (void *)failure);
1562   }
1563 }
1564
1565 /* A timeout callback for the re-key. We will be the initiator of the
1566    re-key protocol. */
1567
1568 SILC_TASK_CALLBACK(silc_client_rekey_callback)
1569 {
1570   SilcSocketConnection sock = (SilcSocketConnection)context;
1571   SilcClientConnection conn = (SilcClientConnection)sock->user_data;
1572   SilcClient client = (SilcClient)conn->rekey->context;
1573   SilcProtocol protocol;
1574   SilcClientRekeyInternalContext *proto_ctx;
1575
1576   SILC_LOG_DEBUG(("Start"));
1577
1578   /* Allocate internal protocol context. This is sent as context
1579      to the protocol. */
1580   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1581   proto_ctx->client = (void *)client;
1582   proto_ctx->sock = silc_socket_dup(sock);
1583   proto_ctx->responder = FALSE;
1584   proto_ctx->pfs = conn->rekey->pfs;
1585       
1586   /* Perform rekey protocol. Will call the final callback after the
1587      protocol is over. */
1588   silc_protocol_alloc(SILC_PROTOCOL_CLIENT_REKEY, 
1589                       &protocol, proto_ctx, silc_client_rekey_final);
1590   sock->protocol = protocol;
1591       
1592   /* Run the protocol */
1593   silc_protocol_execute(protocol, client->schedule, 0, 0);
1594
1595   /* Re-register re-key timeout */
1596   silc_schedule_task_add(client->schedule, sock->sock, 
1597                          silc_client_rekey_callback,
1598                          context, conn->rekey->timeout, 0,
1599                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1600 }
1601
1602 /* The final callback for the REKEY protocol. This will actually take the
1603    new key material into use. */
1604
1605 SILC_TASK_CALLBACK(silc_client_rekey_final)
1606 {
1607   SilcProtocol protocol = (SilcProtocol)context;
1608   SilcClientRekeyInternalContext *ctx =
1609     (SilcClientRekeyInternalContext *)protocol->context;
1610   SilcClient client = (SilcClient)ctx->client;
1611   SilcSocketConnection sock = ctx->sock;
1612
1613   SILC_LOG_DEBUG(("Start"));
1614
1615   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1616       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1617     /* Error occured during protocol */
1618     silc_protocol_cancel(protocol, client->schedule);
1619     silc_protocol_free(protocol);
1620     sock->protocol = NULL;
1621     if (ctx->packet)
1622       silc_packet_context_free(ctx->packet);
1623     if (ctx->ske)
1624       silc_ske_free(ctx->ske);
1625     silc_socket_free(ctx->sock);
1626     silc_free(ctx);
1627     return;
1628   }
1629
1630   /* Purge the outgoing data queue to assure that all rekey packets really
1631      go to the network before we quit the protocol. */
1632   silc_client_packet_queue_purge(client, sock);
1633
1634   /* Cleanup */
1635   silc_protocol_free(protocol);
1636   sock->protocol = NULL;
1637   if (ctx->packet)
1638     silc_packet_context_free(ctx->packet);
1639   if (ctx->ske)
1640     silc_ske_free(ctx->ske);
1641   silc_socket_free(ctx->sock);
1642   silc_free(ctx);
1643 }
1644
1645 /* Processes incoming connection authentication method request packet.
1646    It is a reply to our previously sent request. The packet can be used
1647    to resolve the authentication method for the current session if the
1648    client does not know it beforehand. */
1649
1650 void silc_client_connection_auth_request(SilcClient client,
1651                                          SilcSocketConnection sock,
1652                                          SilcPacketContext *packet)
1653 {
1654   SilcClientConnection conn = (SilcClientConnection)sock->user_data;
1655   uint16 conn_type, auth_meth;
1656   int ret;
1657
1658   /* If we haven't send our request then ignore this one. */
1659   if (!conn->connauth)
1660     return;
1661
1662   /* Parse the payload */
1663   ret = silc_buffer_unformat(packet->buffer,
1664                              SILC_STR_UI_SHORT(&conn_type),
1665                              SILC_STR_UI_SHORT(&auth_meth),
1666                              SILC_STR_END);
1667   if (ret == -1)
1668     auth_meth = SILC_AUTH_NONE;
1669
1670   /* Call the request callback to notify application for received 
1671      authentication method information. */
1672   if (conn->connauth->callback)
1673     (*conn->connauth->callback)(client, conn, auth_meth,
1674                                 conn->connauth->context);
1675
1676   silc_schedule_task_del(client->schedule, conn->connauth->timeout);
1677
1678   silc_free(conn->connauth);
1679   conn->connauth = NULL;
1680 }
1681
1682 /* Timeout task callback called if the server does not reply to our 
1683    connection authentication method request in the specified time interval. */
1684
1685 SILC_TASK_CALLBACK(silc_client_request_authentication_method_timeout)
1686 {
1687   SilcClientConnection conn = (SilcClientConnection)context;
1688   SilcClient client = conn->client;
1689
1690   if (!conn->connauth)
1691     return;
1692
1693   /* Call the request callback to notify application */
1694   if (conn->connauth->callback)
1695     (*conn->connauth->callback)(client, conn, SILC_AUTH_NONE,
1696                                 conn->connauth->context);
1697
1698   silc_free(conn->connauth);
1699   conn->connauth = NULL;
1700 }
1701
1702 /* This function can be used to request the current authentication method
1703    from the server. This may be called when connecting to the server
1704    and the client library requests the authentication data from the
1705    application. If the application does not know the current authentication
1706    method it can request it from the server using this function.
1707    The `callback' with `context' will be called after the server has
1708    replied back with the current authentication method. */
1709
1710 void 
1711 silc_client_request_authentication_method(SilcClient client,
1712                                           SilcClientConnection conn,
1713                                           SilcConnectionAuthRequest callback,
1714                                           void *context)
1715 {
1716   SilcClientConnAuthRequest connauth;
1717   SilcBuffer packet;
1718
1719   connauth = silc_calloc(1, sizeof(*connauth));
1720   connauth->callback = callback;
1721   connauth->context = context;
1722
1723   if (conn->connauth)
1724     silc_free(conn->connauth);
1725
1726   conn->connauth = connauth;
1727
1728   /* Assemble the request packet and send it to the server */
1729   packet = silc_buffer_alloc(4);
1730   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1731   silc_buffer_format(packet,
1732                      SILC_STR_UI_SHORT(SILC_SOCKET_TYPE_CLIENT),
1733                      SILC_STR_UI_SHORT(SILC_AUTH_NONE),
1734                      SILC_STR_END);
1735   silc_client_packet_send(client, conn->sock, 
1736                           SILC_PACKET_CONNECTION_AUTH_REQUEST,
1737                           NULL, 0, NULL, NULL, 
1738                           packet->data, packet->len, FALSE);
1739   silc_buffer_free(packet);
1740
1741   /* Register a timeout in case server does not reply anything back. */
1742   connauth->timeout =
1743     silc_schedule_task_add(client->schedule, conn->sock->sock, 
1744                            silc_client_request_authentication_method_timeout,
1745                            conn, client->params->connauth_request_secs, 0,
1746                            SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1747 }