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