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