Fixed rekey protocol related bugs.
[silc.git] / lib / silcclient / client.c
1 /*
2
3   client.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 1997 - 2003 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     }
640     return;
641   }
642
643   silc_schedule_unset_listen_fd(client->schedule, fd);
644   silc_schedule_task_del(client->schedule, ctx->task);
645   silc_free(ctx);
646
647   silc_client_start_key_exchange(client, conn, fd);
648 }
649
650 /* Second part of the connecting to the server. This executed
651    authentication protocol. */
652
653 SILC_TASK_CALLBACK(silc_client_connect_to_server_second)
654 {
655   SilcProtocol protocol = (SilcProtocol)context;
656   SilcClientKEInternalContext *ctx =
657     (SilcClientKEInternalContext *)protocol->context;
658   SilcClient client = (SilcClient)ctx->client;
659   SilcSocketConnection sock = NULL;
660   SilcClientConnAuthInternalContext *proto_ctx;
661
662   SILC_LOG_DEBUG(("Start"));
663
664   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
665       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
666     /* Error occured during protocol */
667     SILC_LOG_DEBUG(("Error during KE protocol"));
668     silc_protocol_free(protocol);
669     silc_ske_free_key_material(ctx->keymat);
670     if (ctx->ske)
671       silc_ske_free(ctx->ske);
672     if (ctx->dest_id)
673       silc_free(ctx->dest_id);
674     ctx->sock->protocol = NULL;
675     silc_socket_free(ctx->sock);
676
677     /* Notify application of failure */
678     silc_schedule_task_add(client->schedule, ctx->sock->sock,
679                            silc_client_connect_failure, ctx,
680                            0, 1, SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
681     return;
682   }
683
684   /* We now have the key material as the result of the key exchange
685      protocol. Take the key material into use. Free the raw key material
686      as soon as we've set them into use. */
687   silc_client_protocol_ke_set_keys(ctx->ske, ctx->sock, ctx->keymat,
688                                    ctx->ske->prop->cipher,
689                                    ctx->ske->prop->pkcs,
690                                    ctx->ske->prop->hash,
691                                    ctx->ske->prop->hmac,
692                                    ctx->ske->prop->group,
693                                    ctx->responder);
694   silc_ske_free_key_material(ctx->keymat);
695
696   /* Allocate internal context for the authentication protocol. This
697      is sent as context for the protocol. */
698   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
699   proto_ctx->client = (void *)client;
700   proto_ctx->sock = sock = ctx->sock;
701   proto_ctx->ske = ctx->ske;    /* Save SKE object from previous protocol */
702   proto_ctx->dest_id_type = ctx->dest_id_type;
703   proto_ctx->dest_id = ctx->dest_id;
704
705   /* Free old protocol as it is finished now */
706   silc_protocol_free(protocol);
707   if (ctx->packet)
708     silc_packet_context_free(ctx->packet);
709   ctx->packet = NULL;
710   silc_free(ctx);
711   sock->protocol = NULL;
712
713   /* Resolve the authentication method to be used in this connection. The
714      completion callback is called after the application has resolved
715      the authentication method. */
716   client->internal->ops->get_auth_method(client, sock->user_data,
717                                          sock->hostname,
718                                          sock->port,
719                                          silc_client_resolve_auth_method,
720                                          proto_ctx);
721 }
722
723 /* Authentication method resolving callback. Application calls this function
724    after we've called the client->internal->ops->get_auth_method
725    client operation to resolve the authentication method. We will continue
726    the executiong of the protocol in this function. */
727
728 void silc_client_resolve_auth_method(bool success,
729                                      SilcProtocolAuthMeth auth_meth,
730                                      const unsigned char *auth_data,
731                                      SilcUInt32 auth_data_len, void *context)
732 {
733   SilcClientConnAuthInternalContext *proto_ctx =
734     (SilcClientConnAuthInternalContext *)context;
735   SilcClient client = (SilcClient)proto_ctx->client;
736
737   if (!success)
738     auth_meth = SILC_AUTH_NONE;
739
740   proto_ctx->auth_meth = auth_meth;
741
742   if (success && auth_data && auth_data_len) {
743
744     /* Passphrase must be UTF-8 encoded, if it isn't encode it */
745     if (auth_meth == SILC_AUTH_PASSWORD &&
746         !silc_utf8_valid(auth_data, auth_data_len)) {
747       int payload_len = 0;
748       unsigned char *autf8 = NULL;
749       payload_len = silc_utf8_encoded_len(auth_data, auth_data_len,
750                                           SILC_STRING_ASCII);
751       autf8 = silc_calloc(payload_len, sizeof(*autf8));
752       auth_data_len = silc_utf8_encode(auth_data, auth_data_len,
753                                        SILC_STRING_ASCII, autf8, payload_len);
754       auth_data = autf8;
755     }
756
757     proto_ctx->auth_data = silc_memdup(auth_data, auth_data_len);
758     proto_ctx->auth_data_len = auth_data_len;
759   }
760
761   /* Allocate the authenteication protocol and execute it. */
762   silc_protocol_alloc(SILC_PROTOCOL_CLIENT_CONNECTION_AUTH,
763                       &proto_ctx->sock->protocol, (void *)proto_ctx,
764                       silc_client_connect_to_server_final);
765
766   /* Execute the protocol */
767   silc_protocol_execute(proto_ctx->sock->protocol, client->schedule, 0, 0);
768 }
769
770 /* Finalizes the connection to the remote SILC server. This is called
771    after authentication protocol has been completed. This send our
772    user information to the server to receive our client ID from
773    server. */
774
775 SILC_TASK_CALLBACK(silc_client_connect_to_server_final)
776 {
777   SilcProtocol protocol = (SilcProtocol)context;
778   SilcClientConnAuthInternalContext *ctx =
779     (SilcClientConnAuthInternalContext *)protocol->context;
780   SilcClient client = (SilcClient)ctx->client;
781   SilcClientConnection conn = (SilcClientConnection)ctx->sock->user_data;
782   SilcBuffer packet;
783
784   SILC_LOG_DEBUG(("Start"));
785
786   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
787       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
788     /* Error occured during protocol */
789     SILC_LOG_DEBUG(("Error during authentication protocol"));
790     goto err;
791   }
792
793   if (conn->internal->params.detach_data) {
794     /* Send RESUME_CLIENT packet to the server, which is used to resume
795        old detached session back. */
796     SilcBuffer auth;
797     SilcClientID *old_client_id;
798     unsigned char *old_id;
799     SilcUInt16 old_id_len;
800
801     if (!silc_client_process_detach_data(client, conn, &old_id, &old_id_len))
802       goto err;
803
804     old_client_id = silc_id_str2id(old_id, old_id_len, SILC_ID_CLIENT);
805     if (!old_client_id) {
806       silc_free(old_id);
807       goto err;
808     }
809
810     /* Generate authentication data that server will verify */
811     auth = silc_auth_public_key_auth_generate(client->public_key,
812                                               client->private_key,
813                                               client->rng,
814                                               conn->internal->hash,
815                                               old_client_id, SILC_ID_CLIENT);
816     if (!auth) {
817       silc_free(old_client_id);
818       silc_free(old_id);
819       goto err;
820     }
821
822     packet = silc_buffer_alloc_size(2 + old_id_len + auth->len);
823     silc_buffer_format(packet,
824                        SILC_STR_UI_SHORT(old_id_len),
825                        SILC_STR_UI_XNSTRING(old_id, old_id_len),
826                        SILC_STR_UI_XNSTRING(auth->data, auth->len),
827                        SILC_STR_END);
828
829     /* Send the packet */
830     silc_client_packet_send(client, ctx->sock, SILC_PACKET_RESUME_CLIENT,
831                             NULL, 0, NULL, NULL,
832                             packet->data, packet->len, TRUE);
833     silc_buffer_free(packet);
834     silc_buffer_free(auth);
835     silc_free(old_client_id);
836     silc_free(old_id);
837   } else {
838     /* Send NEW_CLIENT packet to the server. We will become registered
839        to the SILC network after sending this packet and we will receive
840        client ID from the server. */
841     packet = silc_buffer_alloc(2 + 2 + strlen(client->username) +
842                                strlen(client->realname));
843     silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
844     silc_buffer_format(packet,
845                        SILC_STR_UI_SHORT(strlen(client->username)),
846                        SILC_STR_UI_XNSTRING(client->username,
847                                             strlen(client->username)),
848                        SILC_STR_UI_SHORT(strlen(client->realname)),
849                        SILC_STR_UI_XNSTRING(client->realname,
850                                             strlen(client->realname)),
851                        SILC_STR_END);
852
853     /* Send the packet */
854     silc_client_packet_send(client, ctx->sock, SILC_PACKET_NEW_CLIENT,
855                             NULL, 0, NULL, NULL,
856                             packet->data, packet->len, TRUE);
857     silc_buffer_free(packet);
858   }
859
860   /* Save remote ID. */
861   conn->remote_id = ctx->dest_id;
862   conn->remote_id_data = silc_id_id2str(ctx->dest_id, SILC_ID_SERVER);
863   conn->remote_id_data_len = silc_id_get_len(ctx->dest_id, SILC_ID_SERVER);
864
865   /* Register re-key timeout */
866   conn->internal->rekey->timeout = client->internal->params->rekey_secs;
867   conn->internal->rekey->context = (void *)client;
868   silc_schedule_task_add(client->schedule, conn->sock->sock,
869                          silc_client_rekey_callback,
870                          (void *)conn->sock, conn->internal->rekey->timeout, 0,
871                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
872
873   silc_protocol_free(protocol);
874   silc_free(ctx->auth_data);
875   if (ctx->ske)
876     silc_ske_free(ctx->ske);
877   silc_socket_free(ctx->sock);
878   silc_free(ctx);
879   conn->sock->protocol = NULL;
880   return;
881
882  err:
883   silc_protocol_free(protocol);
884   silc_free(ctx->auth_data);
885   silc_free(ctx->dest_id);
886   if (ctx->ske)
887     silc_ske_free(ctx->ske);
888   conn->sock->protocol = NULL;
889   silc_socket_free(ctx->sock);
890
891   /* Notify application of failure */
892   silc_schedule_task_add(client->schedule, ctx->sock->sock,
893                          silc_client_connect_failure_auth, ctx,
894                          0, 1, SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
895 }
896
897 /* Internal routine that sends packet or marks packet to be sent. This
898    is used directly only in special cases. Normal cases should use
899    silc_server_packet_send. Returns < 0 on error. */
900
901 bool silc_client_packet_send_real(SilcClient client,
902                                  SilcSocketConnection sock,
903                                  bool force_send)
904 {
905   int ret;
906
907   /* If rekey protocol is active we must assure that all packets are
908      sent through packet queue. */
909   if (SILC_CLIENT_IS_REKEY(sock))
910     force_send = FALSE;
911
912   /* If outbound data is already pending do not force send */
913   if (SILC_IS_OUTBUF_PENDING(sock))
914     force_send = FALSE;
915
916   /* Send the packet */
917   ret = silc_packet_send(sock, force_send);
918   if (ret != -2)
919     return ret;
920
921   /* Mark that there is some outgoing data available for this connection.
922      This call sets the connection both for input and output (the input
923      is set always and this call keeps the input setting, actually).
924      Actual data sending is performed by silc_client_packet_process. */
925   SILC_CLIENT_SET_CONNECTION_FOR_OUTPUT(client->schedule, sock->sock);
926
927   /* Mark to socket that data is pending in outgoing buffer. This flag
928      is needed if new data is added to the buffer before the earlier
929      put data is sent to the network. */
930   SILC_SET_OUTBUF_PENDING(sock);
931
932   return 0;
933 }
934
935 /* Packet processing callback. This is used to send and receive packets
936    from network. This is generic task. */
937
938 SILC_TASK_CALLBACK_GLOBAL(silc_client_packet_process)
939 {
940   SilcClient client = (SilcClient)context;
941   SilcSocketConnection sock = NULL;
942   SilcClientConnection conn;
943   int ret;
944
945   SILC_LOG_DEBUG(("Processing packet"));
946
947   SILC_CLIENT_GET_SOCK(client, fd, sock);
948   if (sock == NULL)
949     return;
950
951   conn = (SilcClientConnection)sock->user_data;
952
953   /* Packet sending */
954   if (type == SILC_TASK_WRITE) {
955     /* Do not send data to disconnected connection */
956     if (SILC_IS_DISCONNECTED(sock))
957       return;
958
959     ret = silc_packet_send(sock, TRUE);
960
961     /* If returned -2 could not write to connection now, will do
962        it later. */
963     if (ret == -2)
964       return;
965
966     /* Error */
967     if (ret == -1)
968       return;
969
970     /* The packet has been sent and now it is time to set the connection
971        back to only for input. When there is again some outgoing data
972        available for this connection it will be set for output as well.
973        This call clears the output setting and sets it only for input. */
974     SILC_CLIENT_SET_CONNECTION_FOR_INPUT(client->schedule, fd);
975     SILC_UNSET_OUTBUF_PENDING(sock);
976
977     silc_buffer_clear(sock->outbuf);
978     return;
979   }
980
981   /* Packet receiving */
982   if (type == SILC_TASK_READ) {
983     /* Read data from network */
984     ret = silc_packet_receive(sock);
985     if (ret < 0)
986       return;
987
988     /* EOF */
989     if (ret == 0) {
990       SILC_LOG_DEBUG(("Read EOF"));
991
992       /* If connection is disconnecting already we will finally
993          close the connection */
994       if (SILC_IS_DISCONNECTING(sock)) {
995         if (sock == conn->sock && sock->type != SILC_SOCKET_TYPE_CLIENT)
996           client->internal->ops->disconnected(client, conn, 0, NULL);
997         silc_client_close_connection_real(client, sock, conn);
998         return;
999       }
1000
1001       SILC_LOG_DEBUG(("EOF from connection %d", sock->sock));
1002       if (sock == conn->sock && sock->type != SILC_SOCKET_TYPE_CLIENT)
1003         client->internal->ops->disconnected(client, conn, 0, NULL);
1004       silc_client_close_connection_real(client, sock, conn);
1005       return;
1006     }
1007
1008     /* Process the packet. This will call the parser that will then
1009        decrypt and parse the packet. */
1010     if (sock->type != SILC_SOCKET_TYPE_UNKNOWN)
1011       silc_packet_receive_process(sock, FALSE, conn->internal->receive_key,
1012                                   conn->internal->hmac_receive,
1013                                   conn->internal->psn_receive,
1014                                   silc_client_packet_parse, client);
1015     else
1016       silc_packet_receive_process(sock, FALSE, NULL, NULL, 0,
1017                                   silc_client_packet_parse, client);
1018   }
1019 }
1020
1021 /* Parser callback called by silc_packet_receive_process. Thie merely
1022    registers timeout that will handle the actual parsing when appropriate. */
1023
1024 static bool silc_client_packet_parse(SilcPacketParserContext *parser_context,
1025                                      void *context)
1026 {
1027   SilcClient client = (SilcClient)context;
1028   SilcSocketConnection sock = parser_context->sock;
1029   SilcClientConnection conn = (SilcClientConnection)sock->user_data;
1030   SilcPacketContext *packet = parser_context->packet;
1031   SilcPacketType ret;
1032
1033   if (conn && conn->internal->hmac_receive && conn->sock == sock)
1034     conn->internal->psn_receive = parser_context->packet->sequence + 1;
1035
1036   /* Parse the packet immediately */
1037   if (parser_context->normal)
1038     ret = silc_packet_parse(packet, conn->internal->receive_key);
1039   else
1040     ret = silc_packet_parse_special(packet, conn->internal->receive_key);
1041
1042   if (ret == SILC_PACKET_NONE) {
1043     silc_packet_context_free(packet);
1044     silc_free(parser_context);
1045     return FALSE;
1046   }
1047
1048   /* If protocol for this connection is key exchange or rekey then we'll
1049      process all packets synchronously, since there might be packets in
1050      queue that we are not able to decrypt without first processing the
1051      packets before them. */
1052   if (sock->protocol && sock->protocol->protocol &&
1053       (sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_KEY_EXCHANGE ||
1054        sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_REKEY)) {
1055
1056     /* Parse the incoming packet type */
1057     silc_client_packet_parse_type(client, sock, packet);
1058     silc_packet_context_free(packet);
1059     silc_free(parser_context);
1060
1061     /* Reprocess the buffer since we'll return FALSE. This is because
1062        the `conn->internal->receive_key' might have become valid by processing
1063        the previous packet */
1064     if (sock->type != SILC_SOCKET_TYPE_UNKNOWN)
1065       silc_packet_receive_process(sock, FALSE, conn->internal->receive_key,
1066                                   conn->internal->hmac_receive,
1067                                   conn->internal->psn_receive,
1068                                   silc_client_packet_parse, client);
1069     else
1070       silc_packet_receive_process(sock, FALSE, NULL, NULL, 0,
1071                                   silc_client_packet_parse, client);
1072
1073     return FALSE;
1074   }
1075
1076   /* Parse the incoming packet type */
1077   silc_client_packet_parse_type(client, sock, packet);
1078   silc_packet_context_free(packet);
1079   silc_free(parser_context);
1080   return TRUE;
1081 }
1082
1083 /* Parses the packet type and calls what ever routines the packet type
1084    requires. This is done for all incoming packets. */
1085
1086 void silc_client_packet_parse_type(SilcClient client,
1087                                    SilcSocketConnection sock,
1088                                    SilcPacketContext *packet)
1089 {
1090   SilcBuffer buffer = packet->buffer;
1091   SilcPacketType type = packet->type;
1092
1093   SILC_LOG_DEBUG(("Parsing %s packet", silc_get_packet_name(type)));
1094
1095   /* Parse the packet type */
1096   switch(type) {
1097
1098   case SILC_PACKET_DISCONNECT:
1099     silc_client_disconnected_by_server(client, sock, buffer);
1100     break;
1101
1102   case SILC_PACKET_SUCCESS:
1103     /*
1104      * Success received for something. For now we can have only
1105      * one protocol for connection executing at once hence this
1106      * success message is for whatever protocol is executing currently.
1107      */
1108     if (sock->protocol)
1109       silc_protocol_execute(sock->protocol, client->schedule, 0, 0);
1110     break;
1111
1112   case SILC_PACKET_FAILURE:
1113     /*
1114      * Failure received for some protocol. Set the protocol state to
1115      * error and call the protocol callback. This fill cause error on
1116      * protocol and it will call the final callback.
1117      */
1118     silc_client_process_failure(client, sock, packet);
1119     break;
1120
1121   case SILC_PACKET_REJECT:
1122     break;
1123
1124   case SILC_PACKET_NOTIFY:
1125     /*
1126      * Received notify message
1127      */
1128     silc_client_notify_by_server(client, sock, packet);
1129     break;
1130
1131   case SILC_PACKET_ERROR:
1132     /*
1133      * Received error message
1134      */
1135     silc_client_error_by_server(client, sock, buffer);
1136     break;
1137
1138   case SILC_PACKET_CHANNEL_MESSAGE:
1139     /*
1140      * Received message to (from, actually) a channel
1141      */
1142     silc_client_channel_message(client, sock, packet);
1143     break;
1144
1145   case SILC_PACKET_CHANNEL_KEY:
1146     /*
1147      * Received key for a channel. By receiving this key the client will be
1148      * able to talk to the channel it has just joined. This can also be
1149      * a new key for existing channel as keys expire peridiocally.
1150      */
1151     silc_client_receive_channel_key(client, sock, buffer);
1152     break;
1153
1154   case SILC_PACKET_PRIVATE_MESSAGE:
1155     /*
1156      * Received private message
1157      */
1158     silc_client_private_message(client, sock, packet);
1159     break;
1160
1161   case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1162     /*
1163      * Received private message key
1164      */
1165     break;
1166
1167   case SILC_PACKET_COMMAND:
1168     /*
1169      * Received command packet, a special case since normally client
1170      * does not receive commands.
1171      */
1172     silc_client_command_process(client, sock, packet);
1173     break;
1174
1175   case SILC_PACKET_COMMAND_REPLY:
1176     /*
1177      * Recived reply for a command
1178      */
1179     silc_client_command_reply_process(client, sock, packet);
1180     break;
1181
1182   case SILC_PACKET_KEY_EXCHANGE:
1183     if (sock->protocol && sock->protocol->protocol &&
1184         sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_KEY_EXCHANGE) {
1185       SilcClientKEInternalContext *proto_ctx =
1186         (SilcClientKEInternalContext *)sock->protocol->context;
1187
1188       proto_ctx->packet = silc_packet_context_dup(packet);
1189       proto_ctx->dest_id_type = packet->src_id_type;
1190       proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1191                                           packet->src_id_type);
1192       if (!proto_ctx->dest_id)
1193         break;
1194
1195       /* Let the protocol handle the packet */
1196       silc_protocol_execute(sock->protocol, client->schedule, 0, 0);
1197     } else {
1198       SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1199                       "protocol active, packet dropped."));
1200     }
1201     break;
1202
1203   case SILC_PACKET_KEY_EXCHANGE_1:
1204     if (sock->protocol && sock->protocol->protocol &&
1205         (sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_KEY_EXCHANGE ||
1206          sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_REKEY)) {
1207
1208       if (sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_REKEY) {
1209         SilcClientRekeyInternalContext *proto_ctx =
1210           (SilcClientRekeyInternalContext *)sock->protocol->context;
1211
1212         if (proto_ctx->packet)
1213           silc_packet_context_free(proto_ctx->packet);
1214
1215         proto_ctx->packet = silc_packet_context_dup(packet);
1216
1217         /* Let the protocol handle the packet */
1218         silc_protocol_execute(sock->protocol, client->schedule, 0, 0);
1219       } else {
1220         SilcClientKEInternalContext *proto_ctx =
1221           (SilcClientKEInternalContext *)sock->protocol->context;
1222
1223         if (proto_ctx->packet)
1224           silc_packet_context_free(proto_ctx->packet);
1225
1226         proto_ctx->packet = silc_packet_context_dup(packet);
1227         proto_ctx->dest_id_type = packet->src_id_type;
1228         proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1229                                             packet->src_id_type);
1230         if (!proto_ctx->dest_id)
1231           break;
1232
1233         /* Let the protocol handle the packet */
1234         silc_protocol_execute(sock->protocol, client->schedule, 0, 0);
1235       }
1236     } else {
1237       SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1238                       "protocol active, packet dropped."));
1239     }
1240     break;
1241
1242   case SILC_PACKET_KEY_EXCHANGE_2:
1243     if (sock->protocol && sock->protocol->protocol &&
1244         (sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_KEY_EXCHANGE ||
1245          sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_REKEY)) {
1246
1247       if (sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_REKEY) {
1248         SilcClientRekeyInternalContext *proto_ctx =
1249           (SilcClientRekeyInternalContext *)sock->protocol->context;
1250
1251         if (proto_ctx->packet)
1252           silc_packet_context_free(proto_ctx->packet);
1253
1254         proto_ctx->packet = silc_packet_context_dup(packet);
1255
1256         /* Let the protocol handle the packet */
1257         silc_protocol_execute(sock->protocol, client->schedule, 0, 0);
1258       } else {
1259         SilcClientKEInternalContext *proto_ctx =
1260           (SilcClientKEInternalContext *)sock->protocol->context;
1261
1262         if (proto_ctx->packet)
1263           silc_packet_context_free(proto_ctx->packet);
1264         if (proto_ctx->dest_id)
1265           silc_free(proto_ctx->dest_id);
1266         proto_ctx->packet = silc_packet_context_dup(packet);
1267         proto_ctx->dest_id_type = packet->src_id_type;
1268         proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1269                                             packet->src_id_type);
1270         if (!proto_ctx->dest_id)
1271           break;
1272
1273         /* Let the protocol handle the packet */
1274         silc_protocol_execute(sock->protocol, client->schedule, 0, 0);
1275       }
1276     } else {
1277       SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1278                       "protocol active, packet dropped."));
1279     }
1280     break;
1281
1282   case SILC_PACKET_NEW_ID:
1283     {
1284       /*
1285        * Received new ID from server. This packet is received at
1286        * the connection to the server.  New ID is also received when
1287        * user changes nickname but in that case the new ID is received
1288        * as command reply and not as this packet type.
1289        */
1290       SilcIDPayload idp;
1291
1292       idp = silc_id_payload_parse(buffer->data, buffer->len);
1293       if (!idp)
1294         break;
1295       if (silc_id_payload_get_type(idp) != SILC_ID_CLIENT)
1296         break;
1297
1298       silc_client_receive_new_id(client, sock, idp);
1299       silc_id_payload_free(idp);
1300       break;
1301     }
1302
1303   case SILC_PACKET_HEARTBEAT:
1304     /*
1305      * Received heartbeat packet
1306      */
1307     SILC_LOG_DEBUG(("Heartbeat packet"));
1308     break;
1309
1310   case SILC_PACKET_KEY_AGREEMENT:
1311     /*
1312      * Received key agreement packet
1313      */
1314     SILC_LOG_DEBUG(("Key agreement packet"));
1315     silc_client_key_agreement(client, sock, packet);
1316     break;
1317
1318   case SILC_PACKET_REKEY:
1319     SILC_LOG_DEBUG(("Re-key packet"));
1320     /* We ignore this for now */
1321     break;
1322
1323   case SILC_PACKET_REKEY_DONE:
1324     SILC_LOG_DEBUG(("Re-key done packet"));
1325
1326     if (sock->protocol && sock->protocol->protocol &&
1327         sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_REKEY) {
1328
1329       SilcClientRekeyInternalContext *proto_ctx =
1330         (SilcClientRekeyInternalContext *)sock->protocol->context;
1331
1332       if (proto_ctx->packet)
1333         silc_packet_context_free(proto_ctx->packet);
1334
1335       proto_ctx->packet = silc_packet_context_dup(packet);
1336
1337       /* Let the protocol handle the packet */
1338       if (proto_ctx->responder == FALSE)
1339         silc_protocol_execute(sock->protocol, client->schedule, 0, 0);
1340       else
1341         /* Let the protocol handle the packet */
1342         silc_protocol_execute(sock->protocol, client->schedule,
1343                               0, 100000);
1344     } else {
1345       SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
1346                       "protocol active, packet dropped."));
1347     }
1348     break;
1349
1350   case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1351     /*
1352      * Reveived reply to our connection authentication method request
1353      * packet. This is used to resolve the authentication method for the
1354      * current session from the server if the client does not know it.
1355      */
1356     silc_client_connection_auth_request(client, sock, packet);
1357     break;
1358
1359   case SILC_PACKET_FTP:
1360     /* Received file transfer packet. */
1361     silc_client_ftp(client, sock, packet);
1362     break;
1363
1364   default:
1365     SILC_LOG_DEBUG(("Incorrect packet type %d, packet dropped", type));
1366     break;
1367   }
1368 }
1369
1370 /* Sends packet. This doesn't actually send the packet instead it assembles
1371    it and marks it to be sent. However, if force_send is TRUE the packet
1372    is sent immediately. if dst_id, cipher and hmac are NULL those parameters
1373    will be derived from sock argument. Otherwise the valid arguments sent
1374    are used. */
1375
1376 void silc_client_packet_send(SilcClient client,
1377                              SilcSocketConnection sock,
1378                              SilcPacketType type,
1379                              void *dst_id,
1380                              SilcIdType dst_id_type,
1381                              SilcCipher cipher,
1382                              SilcHmac hmac,
1383                              unsigned char *data,
1384                              SilcUInt32 data_len,
1385                              bool force_send)
1386 {
1387   SilcPacketContext packetdata;
1388   const SilcBufferStruct packet;
1389   int block_len;
1390   SilcUInt32 sequence = 0;
1391
1392   if (!sock)
1393     return;
1394
1395   SILC_LOG_DEBUG(("Sending packet, type %d", type));
1396
1397   /* Get data used in the packet sending, keys and stuff */
1398   if ((!cipher || !hmac || !dst_id) && sock->user_data) {
1399     if (!cipher && ((SilcClientConnection)sock->user_data)->internal->send_key)
1400       cipher = ((SilcClientConnection)sock->user_data)->internal->send_key;
1401
1402     if (!hmac && ((SilcClientConnection)sock->user_data)->internal->hmac_send)
1403       hmac = ((SilcClientConnection)sock->user_data)->internal->hmac_send;
1404
1405     if (!dst_id && ((SilcClientConnection)sock->user_data)->remote_id) {
1406       dst_id = ((SilcClientConnection)sock->user_data)->remote_id;
1407       dst_id_type = SILC_ID_SERVER;
1408     }
1409
1410     if (hmac)
1411       sequence = ((SilcClientConnection)sock->user_data)->internal->psn_send++;
1412
1413     /* Check for mandatory rekey */
1414     if (sequence == SILC_CLIENT_REKEY_THRESHOLD)
1415       silc_schedule_task_add(client->schedule, sock->sock,
1416                              silc_client_rekey_callback, sock, 0, 1,
1417                              SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1418   }
1419
1420   block_len = cipher ? silc_cipher_get_block_len(cipher) : 0;
1421
1422   /* Set the packet context pointers */
1423   packetdata.flags = 0;
1424   packetdata.type = type;
1425   if (sock->user_data &&
1426       ((SilcClientConnection)sock->user_data)->local_id_data) {
1427     packetdata.src_id = ((SilcClientConnection)sock->user_data)->local_id_data;
1428     packetdata.src_id_len =
1429       silc_id_get_len(((SilcClientConnection)sock->user_data)->local_id,
1430                       SILC_ID_CLIENT);
1431   } else {
1432     packetdata.src_id = silc_calloc(SILC_ID_CLIENT_LEN, sizeof(unsigned char));
1433     packetdata.src_id_len = SILC_ID_CLIENT_LEN;
1434   }
1435   packetdata.src_id_type = SILC_ID_CLIENT;
1436   if (dst_id) {
1437     packetdata.dst_id = silc_id_id2str(dst_id, dst_id_type);
1438     packetdata.dst_id_len = silc_id_get_len(dst_id, dst_id_type);
1439     packetdata.dst_id_type = dst_id_type;
1440   } else {
1441     packetdata.dst_id = NULL;
1442     packetdata.dst_id_len = 0;
1443     packetdata.dst_id_type = SILC_ID_NONE;
1444   }
1445   data_len = SILC_PACKET_DATALEN(data_len, (SILC_PACKET_HEADER_LEN +
1446                                             packetdata.src_id_len +
1447                                             packetdata.dst_id_len));
1448   packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
1449     packetdata.src_id_len + packetdata.dst_id_len;
1450   if (type == SILC_PACKET_CONNECTION_AUTH)
1451     SILC_PACKET_PADLEN_MAX(packetdata.truelen, block_len, packetdata.padlen);
1452   else
1453     SILC_PACKET_PADLEN(packetdata.truelen, block_len, packetdata.padlen);
1454
1455   /* Create the outgoing packet */
1456   if (!silc_packet_assemble(&packetdata, client->rng, cipher, hmac, sock,
1457                             data, data_len, (const SilcBuffer)&packet)) {
1458     SILC_LOG_ERROR(("Error assembling packet"));
1459     return;
1460   }
1461
1462   /* Encrypt the packet */
1463   if (cipher)
1464     silc_packet_encrypt(cipher, hmac, sequence, (SilcBuffer)&packet,
1465                         packet.len);
1466
1467   SILC_LOG_HEXDUMP(("Packet (%d), len %d", sequence, packet.len),
1468                    packet.data, packet.len);
1469
1470   /* Now actually send the packet */
1471   silc_client_packet_send_real(client, sock, force_send);
1472 }
1473
1474 /* Packet sending routine for application.  This is the only routine that
1475    is provided for application to send SILC packets. */
1476
1477 bool silc_client_send_packet(SilcClient client,
1478                              SilcClientConnection conn,
1479                              SilcPacketType type,
1480                              const unsigned char *data,
1481                              SilcUInt32 data_len)
1482 {
1483
1484   assert(client);
1485   if (!conn)
1486     return FALSE;
1487
1488   silc_client_packet_send(client, conn->sock, type, NULL, 0, NULL, NULL,
1489                           (unsigned char *)data, data_len, TRUE);
1490   return TRUE;
1491 }
1492
1493 void silc_client_packet_queue_purge(SilcClient client,
1494                                     SilcSocketConnection sock)
1495 {
1496   if (sock && SILC_IS_OUTBUF_PENDING(sock) &&
1497       (SILC_IS_DISCONNECTED(sock) == FALSE)) {
1498     silc_packet_send(sock, TRUE);
1499     SILC_UNSET_OUTBUF_PENDING(sock);
1500     SILC_CLIENT_SET_CONNECTION_FOR_INPUT(client->schedule, sock->sock);
1501     silc_buffer_clear(sock->outbuf);
1502   }
1503 }
1504
1505 /* Closes connection to remote end. Free's all allocated data except
1506    for some information such as nickname etc. that are valid at all time.
1507    If the `sock' is NULL then the conn->sock will be used.  If `sock' is
1508    provided it will be checked whether the sock and `conn->sock' are the
1509    same (they can be different, ie. a socket can use `conn' as its
1510    connection but `conn->sock' might be actually a different connection
1511    than the `sock'). */
1512
1513 void silc_client_close_connection_real(SilcClient client,
1514                                        SilcSocketConnection sock,
1515                                        SilcClientConnection conn)
1516 {
1517   int del = FALSE;
1518
1519   SILC_LOG_DEBUG(("Start"));
1520
1521   if (!sock && !conn)
1522     return;
1523
1524   if (!sock || (sock && conn->sock == sock))
1525     del = TRUE;
1526   if (!sock)
1527     sock = conn->sock;
1528
1529   /* We won't listen for this connection anymore */
1530   silc_schedule_unset_listen_fd(client->schedule, sock->sock);
1531
1532   /* Unregister all tasks */
1533   silc_schedule_task_del_by_fd(client->schedule, sock->sock);
1534
1535   /* Close the actual connection */
1536   silc_net_close_connection(sock->sock);
1537
1538   /* Cancel any active protocol */
1539   if (sock->protocol) {
1540     if (sock->protocol->protocol->type ==
1541         SILC_PROTOCOL_CLIENT_KEY_EXCHANGE ||
1542         sock->protocol->protocol->type ==
1543         SILC_PROTOCOL_CLIENT_CONNECTION_AUTH) {
1544       sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
1545       silc_protocol_execute_final(sock->protocol, client->schedule);
1546       /* The application will recall this function with these protocols
1547          (the ops->connected client operation). */
1548       return;
1549     } else {
1550       sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
1551       silc_protocol_execute_final(sock->protocol, client->schedule);
1552       sock->protocol = NULL;
1553     }
1554   }
1555
1556   /* Free everything */
1557   if (del && sock->user_data)
1558     silc_client_del_connection(client, conn);
1559
1560   silc_socket_free(sock);
1561 }
1562
1563 /* Closes the connection to the remote end */
1564
1565 void silc_client_close_connection(SilcClient client,
1566                                   SilcClientConnection conn)
1567 {
1568   silc_client_close_connection_real(client, NULL, conn);
1569 }
1570
1571 /* Called when we receive disconnection packet from server. This
1572    closes our end properly and displays the reason of the disconnection
1573    on the screen. */
1574
1575 SILC_TASK_CALLBACK(silc_client_disconnected_by_server_later)
1576 {
1577   SilcClient client = (SilcClient)context;
1578   SilcSocketConnection sock;
1579
1580   SILC_CLIENT_GET_SOCK(client, fd, sock);
1581   if (sock == NULL)
1582     return;
1583
1584   silc_client_close_connection_real(client, sock, sock->user_data);
1585 }
1586
1587 /* Called when we receive disconnection packet from server. This
1588    closes our end properly and displays the reason of the disconnection
1589    on the screen. */
1590
1591 void silc_client_disconnected_by_server(SilcClient client,
1592                                         SilcSocketConnection sock,
1593                                         SilcBuffer packet)
1594 {
1595   SilcClientConnection conn;
1596   SilcStatus status;
1597   char *message = NULL;
1598
1599   SILC_LOG_DEBUG(("Server disconnected us, sock %d", sock->sock));
1600
1601   if (packet->len < 1)
1602     return;
1603
1604   status = (SilcStatus)packet->data[0];
1605
1606   if (packet->len > 1 &&
1607       silc_utf8_valid(packet->data + 1, packet->len - 1))
1608     message = silc_memdup(packet->data + 1, packet->len - 1);
1609
1610   conn = (SilcClientConnection)sock->user_data;
1611   if (sock == conn->sock && sock->type != SILC_SOCKET_TYPE_CLIENT)
1612     client->internal->ops->disconnected(client, conn, status, message);
1613
1614   silc_free(message);
1615
1616   SILC_SET_DISCONNECTED(sock);
1617
1618   /* Close connection through scheduler. */
1619   silc_schedule_task_add(client->schedule, sock->sock,
1620                          silc_client_disconnected_by_server_later,
1621                          client, 0, 1, SILC_TASK_TIMEOUT,
1622                          SILC_TASK_PRI_NORMAL);
1623 }
1624
1625 /* Received error message from server. Display it on the screen.
1626    We don't take any action what so ever of the error message. */
1627
1628 void silc_client_error_by_server(SilcClient client,
1629                                  SilcSocketConnection sock,
1630                                  SilcBuffer message)
1631 {
1632   char *msg;
1633
1634   msg = silc_memdup(message->data, message->len);
1635   client->internal->ops->say(client, sock->user_data,
1636                              SILC_CLIENT_MESSAGE_AUDIT, msg);
1637   silc_free(msg);
1638 }
1639
1640 /* Auto-nicking callback to send NICK command to server. */
1641
1642 SILC_TASK_CALLBACK(silc_client_send_auto_nick)
1643 {
1644   SilcClientConnection conn = (SilcClientConnection)context;
1645   SilcClient client = conn->client;
1646   if (client)
1647     silc_client_command_send(client, conn, SILC_COMMAND_NICK,
1648                              ++conn->cmd_ident, 1, 1,
1649                              client->nickname, strlen(client->nickname));
1650 }
1651
1652 /* Client session resuming callback.  If the session was resumed
1653    this callback is called after the resuming is completed.  This
1654    will call the `connect' client operation to the application
1655    since it has not been called yet. */
1656
1657 static void silc_client_resume_session_cb(SilcClient client,
1658                                           SilcClientConnection conn,
1659                                           bool success,
1660                                           void *context)
1661 {
1662   SilcBuffer sidp;
1663
1664   /* Notify application that connection is created to server */
1665   client->internal->ops->connected(client, conn, success ?
1666                                    SILC_CLIENT_CONN_SUCCESS_RESUME :
1667                                    SILC_CLIENT_CONN_ERROR);
1668
1669   if (success) {
1670     /* Issue INFO command to fetch the real server name and server
1671        information and other stuff. */
1672     silc_client_command_register(client, SILC_COMMAND_INFO, NULL, NULL,
1673                                  silc_client_command_reply_info_i, 0,
1674                                  ++conn->cmd_ident);
1675     sidp = silc_id_payload_encode(conn->remote_id, SILC_ID_SERVER);
1676     silc_client_command_send(client, conn, SILC_COMMAND_INFO,
1677                              conn->cmd_ident, 1, 2, sidp->data, sidp->len);
1678     silc_buffer_free(sidp);
1679   }
1680 }
1681
1682 /* Processes the received new Client ID from server. Old Client ID is
1683    deleted from cache and new one is added. */
1684
1685 void silc_client_receive_new_id(SilcClient client,
1686                                 SilcSocketConnection sock,
1687                                 SilcIDPayload idp)
1688 {
1689   SilcClientConnection conn = (SilcClientConnection)sock->user_data;
1690   int connecting = FALSE;
1691   SilcClientID *client_id = silc_id_payload_get_id(idp);
1692
1693   if (!conn->local_entry)
1694     connecting = TRUE;
1695
1696   /* Delete old ID from ID cache */
1697   if (conn->local_id) {
1698     /* Check whether they are different */
1699     if (SILC_ID_CLIENT_COMPARE(conn->local_id, client_id)) {
1700       silc_free(client_id);
1701       return;
1702     }
1703
1704     silc_idcache_del_by_context(conn->internal->client_cache,
1705                                 conn->local_entry);
1706     silc_free(conn->local_id);
1707   }
1708
1709   /* Save the new ID */
1710
1711   if (conn->local_id_data)
1712     silc_free(conn->local_id_data);
1713
1714   conn->local_id = client_id;
1715   conn->local_id_data = silc_id_payload_get_data(idp);
1716   conn->local_id_data_len = silc_id_payload_get_len(idp);;
1717
1718   if (!conn->local_entry)
1719     conn->local_entry = silc_calloc(1, sizeof(*conn->local_entry));
1720
1721   conn->local_entry->nickname = conn->nickname;
1722   if (!conn->local_entry->username)
1723     conn->local_entry->username = strdup(client->username);
1724   if (!conn->local_entry->server)
1725     conn->local_entry->server = strdup(conn->remote_host);
1726   conn->local_entry->id = conn->local_id;
1727   conn->local_entry->valid = TRUE;
1728   if (!conn->local_entry->channels)
1729     conn->local_entry->channels = silc_hash_table_alloc(1, silc_hash_ptr,
1730                                                         NULL, NULL,
1731                                                         NULL, NULL, NULL,
1732                                                         TRUE);
1733
1734   /* Put it to the ID cache */
1735   silc_idcache_add(conn->internal->client_cache,
1736                    strdup(conn->nickname), conn->local_id,
1737                    (void *)conn->local_entry, 0, NULL);
1738
1739   if (connecting) {
1740     SilcBuffer sidp;
1741
1742     /* Issue IDENTIFY command for itself to get resolved hostname
1743        correctly from server. */
1744     silc_client_command_register(client, SILC_COMMAND_IDENTIFY, NULL, NULL,
1745                                  silc_client_command_reply_identify_i, 0,
1746                                  ++conn->cmd_ident);
1747     sidp = silc_id_payload_encode(conn->local_entry->id, SILC_ID_CLIENT);
1748     silc_client_command_send(client, conn, SILC_COMMAND_IDENTIFY,
1749                              conn->cmd_ident, 1, 5, sidp->data, sidp->len);
1750     silc_buffer_free(sidp);
1751
1752     if (!conn->internal->params.detach_data) {
1753       /* Send NICK command if the nickname was set by the application (and is
1754          not same as the username). Send this with little timeout. */
1755       if (client->nickname && strcmp(client->nickname, client->username))
1756         silc_schedule_task_add(client->schedule, 0,
1757                                silc_client_send_auto_nick, conn,
1758                                1, 0, SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1759
1760       /* Notify application of successful connection. We do it here now that
1761          we've received the Client ID and are allowed to send traffic. */
1762       client->internal->ops->connected(client, conn, SILC_CLIENT_CONN_SUCCESS);
1763
1764       /* Issue INFO command to fetch the real server name and server
1765          information and other stuff. */
1766       silc_client_command_register(client, SILC_COMMAND_INFO, NULL, NULL,
1767                                    silc_client_command_reply_info_i, 0,
1768                                    ++conn->cmd_ident);
1769       sidp = silc_id_payload_encode(conn->remote_id, SILC_ID_SERVER);
1770       silc_client_command_send(client, conn, SILC_COMMAND_INFO,
1771                                conn->cmd_ident, 1, 2, sidp->data, sidp->len);
1772       silc_buffer_free(sidp);
1773     } else {
1774       /* We are resuming session.  Start resolving informations from the
1775          server we need to set the client libary in the state before
1776          detaching the session.  The connect client operation is called
1777          after this is successfully completed */
1778       silc_client_resume_session(client, conn, silc_client_resume_session_cb,
1779                                  NULL);
1780     }
1781   }
1782 }
1783
1784 /* Removes a client entry from all channels it has joined. */
1785
1786 void silc_client_remove_from_channels(SilcClient client,
1787                                       SilcClientConnection conn,
1788                                       SilcClientEntry client_entry)
1789 {
1790   SilcHashTableList htl;
1791   SilcChannelUser chu;
1792
1793   silc_hash_table_list(client_entry->channels, &htl);
1794   while (silc_hash_table_get(&htl, NULL, (void **)&chu)) {
1795     silc_hash_table_del(chu->client->channels, chu->channel);
1796     silc_hash_table_del(chu->channel->user_list, chu->client);
1797     silc_free(chu);
1798   }
1799
1800   silc_hash_table_list_reset(&htl);
1801 }
1802
1803 /* Replaces `old' client entries from all channels to `new' client entry.
1804    This can be called for example when nickname changes and old ID entry
1805    is replaced from ID cache with the new one. If the old ID entry is only
1806    updated, then this fucntion needs not to be called. */
1807
1808 void silc_client_replace_from_channels(SilcClient client,
1809                                        SilcClientConnection conn,
1810                                        SilcClientEntry old,
1811                                        SilcClientEntry new)
1812 {
1813   SilcHashTableList htl;
1814   SilcChannelUser chu;
1815
1816   silc_hash_table_list(old->channels, &htl);
1817   while (silc_hash_table_get(&htl, NULL, (void **)&chu)) {
1818     /* Replace client entry */
1819     silc_hash_table_del(chu->client->channels, chu->channel);
1820     silc_hash_table_del(chu->channel->user_list, chu->client);
1821
1822     chu->client = new;
1823     silc_hash_table_add(chu->channel->user_list, chu->client, chu);
1824     silc_hash_table_add(chu->client->channels, chu->channel, chu);
1825   }
1826   silc_hash_table_list_reset(&htl);
1827 }
1828
1829 /* Registers failure timeout to process the received failure packet
1830    with timeout. */
1831
1832 void silc_client_process_failure(SilcClient client,
1833                                  SilcSocketConnection sock,
1834                                  SilcPacketContext *packet)
1835 {
1836   SilcUInt32 failure = 0;
1837
1838   if (sock->protocol) {
1839     if (packet->buffer->len >= 4)
1840       SILC_GET32_MSB(failure, packet->buffer->data);
1841
1842     /* Notify application */
1843     client->internal->ops->failure(client, sock->user_data, sock->protocol,
1844                                    (void *)failure);
1845   }
1846 }
1847
1848 /* A timeout callback for the re-key. We will be the initiator of the
1849    re-key protocol. */
1850
1851 SILC_TASK_CALLBACK_GLOBAL(silc_client_rekey_callback)
1852 {
1853   SilcSocketConnection sock = (SilcSocketConnection)context;
1854   SilcClientConnection conn = (SilcClientConnection)sock->user_data;
1855   SilcClient client = (SilcClient)conn->internal->rekey->context;
1856   SilcProtocol protocol;
1857   SilcClientRekeyInternalContext *proto_ctx;
1858
1859   SILC_LOG_DEBUG(("Start"));
1860
1861   /* If rekey protocol is active already wait for it to finish */
1862   if (sock->protocol && sock->protocol->protocol &&
1863       sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_REKEY)
1864     return;
1865
1866   /* Allocate internal protocol context. This is sent as context
1867      to the protocol. */
1868   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1869   proto_ctx->client = (void *)client;
1870   proto_ctx->sock = silc_socket_dup(sock);
1871   proto_ctx->responder = FALSE;
1872   proto_ctx->pfs = conn->internal->rekey->pfs;
1873
1874   /* Perform rekey protocol. Will call the final callback after the
1875      protocol is over. */
1876   silc_protocol_alloc(SILC_PROTOCOL_CLIENT_REKEY,
1877                       &protocol, proto_ctx, silc_client_rekey_final);
1878   sock->protocol = protocol;
1879
1880   /* Run the protocol */
1881   silc_protocol_execute(protocol, client->schedule, 0, 0);
1882 }
1883
1884 /* The final callback for the REKEY protocol. This will actually take the
1885    new key material into use. */
1886
1887 SILC_TASK_CALLBACK(silc_client_rekey_final)
1888 {
1889   SilcProtocol protocol = (SilcProtocol)context;
1890   SilcClientRekeyInternalContext *ctx =
1891     (SilcClientRekeyInternalContext *)protocol->context;
1892   SilcClient client = (SilcClient)ctx->client;
1893   SilcSocketConnection sock = ctx->sock;
1894   SilcClientConnection conn = (SilcClientConnection)sock->user_data;
1895
1896   SILC_LOG_DEBUG(("Start"));
1897
1898   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1899       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1900     /* Error occured during protocol */
1901     silc_protocol_cancel(protocol, client->schedule);
1902     silc_protocol_free(protocol);
1903     sock->protocol = NULL;
1904     if (ctx->packet)
1905       silc_packet_context_free(ctx->packet);
1906     if (ctx->ske)
1907       silc_ske_free(ctx->ske);
1908     silc_socket_free(ctx->sock);
1909     silc_free(ctx);
1910     return;
1911   }
1912
1913   /* Purge the outgoing data queue to assure that all rekey packets really
1914      go to the network before we quit the protocol. */
1915   silc_client_packet_queue_purge(client, sock);
1916
1917   /* Re-register re-key timeout */
1918   if (ctx->responder == FALSE)
1919     silc_schedule_task_add(client->schedule, sock->sock,
1920                            silc_client_rekey_callback,
1921                            sock, conn->internal->rekey->timeout, 0,
1922                            SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1923
1924   /* Cleanup */
1925   silc_protocol_free(protocol);
1926   sock->protocol = NULL;
1927   if (ctx->packet)
1928     silc_packet_context_free(ctx->packet);
1929   if (ctx->ske)
1930     silc_ske_free(ctx->ske);
1931   silc_socket_free(ctx->sock);
1932   silc_free(ctx);
1933 }
1934
1935 /* Processes incoming connection authentication method request packet.
1936    It is a reply to our previously sent request. The packet can be used
1937    to resolve the authentication method for the current session if the
1938    client does not know it beforehand. */
1939
1940 void silc_client_connection_auth_request(SilcClient client,
1941                                          SilcSocketConnection sock,
1942                                          SilcPacketContext *packet)
1943 {
1944   SilcClientConnection conn = (SilcClientConnection)sock->user_data;
1945   SilcUInt16 conn_type, auth_meth;
1946   int ret;
1947
1948   /* If we haven't send our request then ignore this one. */
1949   if (!conn->internal->connauth)
1950     return;
1951
1952   /* Parse the payload */
1953   ret = silc_buffer_unformat(packet->buffer,
1954                              SILC_STR_UI_SHORT(&conn_type),
1955                              SILC_STR_UI_SHORT(&auth_meth),
1956                              SILC_STR_END);
1957   if (ret == -1)
1958     auth_meth = SILC_AUTH_NONE;
1959
1960   /* Call the request callback to notify application for received
1961      authentication method information. */
1962   if (conn->internal->connauth->callback)
1963     (*conn->internal->connauth->callback)(client, conn, auth_meth,
1964                                           conn->internal->connauth->context);
1965
1966   silc_schedule_task_del(client->schedule, conn->internal->connauth->timeout);
1967
1968   silc_free(conn->internal->connauth);
1969   conn->internal->connauth = NULL;
1970 }
1971
1972 /* Timeout task callback called if the server does not reply to our
1973    connection authentication method request in the specified time interval. */
1974
1975 SILC_TASK_CALLBACK(silc_client_request_authentication_method_timeout)
1976 {
1977   SilcClientConnection conn = (SilcClientConnection)context;
1978   SilcClient client = conn->client;
1979
1980   if (!conn->internal->connauth)
1981     return;
1982
1983   /* Call the request callback to notify application */
1984   if (conn->internal->connauth->callback)
1985     (*conn->internal->connauth->callback)(client, conn, SILC_AUTH_NONE,
1986                                           conn->internal->connauth->context);
1987
1988   silc_free(conn->internal->connauth);
1989   conn->internal->connauth = NULL;
1990 }
1991
1992 /* This function can be used to request the current authentication method
1993    from the server. This may be called when connecting to the server
1994    and the client library requests the authentication data from the
1995    application. If the application does not know the current authentication
1996    method it can request it from the server using this function.
1997    The `callback' with `context' will be called after the server has
1998    replied back with the current authentication method. */
1999
2000 void
2001 silc_client_request_authentication_method(SilcClient client,
2002                                           SilcClientConnection conn,
2003                                           SilcConnectionAuthRequest callback,
2004                                           void *context)
2005 {
2006   SilcClientConnAuthRequest connauth;
2007   SilcBuffer packet;
2008
2009   assert(client && conn);
2010   connauth = silc_calloc(1, sizeof(*connauth));
2011   connauth->callback = callback;
2012   connauth->context = context;
2013
2014   if (conn->internal->connauth)
2015     silc_free(conn->internal->connauth);
2016
2017   conn->internal->connauth = connauth;
2018
2019   /* Assemble the request packet and send it to the server */
2020   packet = silc_buffer_alloc(4);
2021   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
2022   silc_buffer_format(packet,
2023                      SILC_STR_UI_SHORT(SILC_SOCKET_TYPE_CLIENT),
2024                      SILC_STR_UI_SHORT(SILC_AUTH_NONE),
2025                      SILC_STR_END);
2026   silc_client_packet_send(client, conn->sock,
2027                           SILC_PACKET_CONNECTION_AUTH_REQUEST,
2028                           NULL, 0, NULL, NULL,
2029                           packet->data, packet->len, FALSE);
2030   silc_buffer_free(packet);
2031
2032   /* Register a timeout in case server does not reply anything back. */
2033   connauth->timeout =
2034     silc_schedule_task_add(client->schedule, conn->sock->sock,
2035                            silc_client_request_authentication_method_timeout,
2036                            conn,
2037                            client->internal->params->connauth_request_secs, 0,
2038                            SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2039 }