Added support for the new private message key indicator packet.
[silc.git] / lib / silcclient / client.c
1 /*
2
3   client.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 1997 - 2004 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         if (conn->sock)
332           conn->sock->user_data = NULL;
333         silc_client_ftp_session_free(conn->internal->active_session);
334         conn->internal->active_session = NULL;
335       }
336
337       silc_client_ftp_free_sessions(client, conn);
338
339       if (conn->internal->pending_commands) {
340         silc_dlist_start(conn->internal->pending_commands);
341         while ((r = silc_dlist_get(conn->internal->pending_commands))
342                != SILC_LIST_END)
343           silc_dlist_del(conn->internal->pending_commands, r);
344         silc_dlist_uninit(conn->internal->pending_commands);
345       }
346
347       silc_free(conn->internal);
348       memset(conn, 0, sizeof(*conn));
349       silc_free(conn);
350
351       client->internal->conns[i] = NULL;
352     }
353 }
354
355 /* Adds listener socket to the listener sockets table. This function is
356    used to add socket objects that are listeners to the client.  This should
357    not be used to add other connection objects. */
358
359 void silc_client_add_socket(SilcClient client, SilcSocketConnection sock)
360 {
361   int i;
362
363   if (!client->internal->sockets) {
364     client->internal->sockets =
365       silc_calloc(1, sizeof(*client->internal->sockets));
366     client->internal->sockets[0] = silc_socket_dup(sock);
367     client->internal->sockets_count = 1;
368     return;
369   }
370
371   for (i = 0; i < client->internal->sockets_count; i++) {
372     if (client->internal->sockets[i] == NULL) {
373       client->internal->sockets[i] = silc_socket_dup(sock);
374       return;
375     }
376   }
377
378   client->internal->sockets =
379     silc_realloc(client->internal->sockets,
380                  sizeof(*client->internal->sockets) *
381                  (client->internal->sockets_count + 1));
382   client->internal->sockets[client->internal->sockets_count] =
383     silc_socket_dup(sock);
384   client->internal->sockets_count++;
385 }
386
387 /* Deletes listener socket from the listener sockets table. */
388
389 void silc_client_del_socket(SilcClient client, SilcSocketConnection sock)
390 {
391   int i;
392
393   if (!client->internal->sockets)
394     return;
395
396   for (i = 0; i < client->internal->sockets_count; i++) {
397     if (client->internal->sockets[i] == sock) {
398       silc_socket_free(sock);
399       client->internal->sockets[i] = NULL;
400       return;
401     }
402   }
403 }
404
405 static int
406 silc_client_connect_to_server_internal(SilcClientInternalConnectContext *ctx)
407 {
408   int sock;
409
410   /* XXX In the future we should give up this non-blocking connect all
411      together and use threads instead. */
412   /* Create connection to server asynchronously */
413   sock = silc_net_create_connection_async(NULL, ctx->port, ctx->host);
414   if (sock < 0)
415     return -1;
416
417   /* Register task that will receive the async connect and will
418      read the result. */
419   ctx->task = silc_schedule_task_add(ctx->client->schedule, sock,
420                                      silc_client_connect_to_server_start,
421                                      (void *)ctx, 0, 0,
422                                      SILC_TASK_FD,
423                                      SILC_TASK_PRI_NORMAL);
424   silc_schedule_set_listen_fd(ctx->client->schedule, sock, SILC_TASK_WRITE,
425                               FALSE);
426
427   ctx->sock = sock;
428
429   return sock;
430 }
431
432 /* Connects to remote server. This is the main routine used to connect
433    to SILC server. Returns -1 on error and the created socket otherwise.
434    The `context' is user context that is saved into the SilcClientConnection
435    that is created after the connection is created. Note that application
436    may handle the connecting process outside the library. If this is the
437    case then this function is not used at all. When the connecting is
438    done the `connect' client operation is called. */
439
440 int silc_client_connect_to_server(SilcClient client,
441                                   SilcClientConnectionParams *params,
442                                   int port, char *host, void *context)
443 {
444   SilcClientInternalConnectContext *ctx;
445   SilcClientConnection conn;
446   int sock;
447
448   SILC_LOG_DEBUG(("Connecting to port %d of server %s",
449                   port, host));
450
451   conn = silc_client_add_connection(client, params, host, port, context);
452
453   client->internal->ops->say(client, conn, SILC_CLIENT_MESSAGE_AUDIT,
454                              "Connecting to port %d of server %s", port, host);
455
456   /* Allocate internal context for connection process. This is
457      needed as we are doing async connecting. */
458   ctx = silc_calloc(1, sizeof(*ctx));
459   ctx->client = client;
460   ctx->conn = conn;
461   ctx->host = strdup(host);
462   ctx->port = port ? port : 706;
463   ctx->tries = 0;
464
465   /* Do the actual connecting process */
466   sock = silc_client_connect_to_server_internal(ctx);
467   if (sock == -1)
468     silc_client_del_connection(client, conn);
469   return sock;
470 }
471
472 /* Socket hostname and IP lookup callback that is called before actually
473    starting the key exchange.  The lookup is called from the function
474    silc_client_start_key_exchange. */
475
476 static void silc_client_start_key_exchange_cb(SilcSocketConnection sock,
477                                               void *context)
478 {
479   SilcClientConnection conn = (SilcClientConnection)context;
480   SilcClient client = conn->client;
481   SilcProtocol protocol;
482   SilcClientKEInternalContext *proto_ctx;
483
484   SILC_LOG_DEBUG(("Start"));
485
486   if (conn->sock->hostname) {
487     silc_free(conn->remote_host);
488     conn->remote_host = strdup(conn->sock->hostname);
489   } else {
490     conn->sock->hostname = strdup(conn->remote_host);
491   }
492   if (!conn->sock->ip)
493     conn->sock->ip = strdup(conn->sock->hostname);
494   conn->sock->port = conn->remote_port;
495
496   /* Allocate internal Key Exchange context. This is sent to the
497      protocol as context. */
498   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
499   proto_ctx->client = (void *)client;
500   proto_ctx->sock = silc_socket_dup(conn->sock);
501   proto_ctx->rng = client->rng;
502   proto_ctx->responder = FALSE;
503   proto_ctx->send_packet = silc_client_protocol_ke_send_packet;
504   proto_ctx->verify = silc_client_protocol_ke_verify_key;
505
506   /* Perform key exchange protocol. silc_client_connect_to_server_final
507      will be called after the protocol is finished. */
508   silc_protocol_alloc(SILC_PROTOCOL_CLIENT_KEY_EXCHANGE,
509                       &protocol, (void *)proto_ctx,
510                       silc_client_connect_to_server_second);
511   if (!protocol) {
512     client->internal->ops->say(client, conn, SILC_CLIENT_MESSAGE_ERROR,
513                                "Error: Could not start key exchange protocol");
514     silc_net_close_connection(conn->sock->sock);
515     client->internal->ops->connected(client, conn, SILC_CLIENT_CONN_ERROR);
516     return;
517   }
518   conn->sock->protocol = protocol;
519
520   /* Register the connection for network input and output. This sets
521      that scheduler will listen for incoming packets for this connection
522      and sets that outgoing packets may be sent to this connection as well.
523      However, this doesn't set the scheduler for outgoing traffic, it will
524      be set separately by calling SILC_CLIENT_SET_CONNECTION_FOR_OUTPUT,
525      later when outgoing data is available. */
526   context = (void *)client;
527   SILC_CLIENT_REGISTER_CONNECTION_FOR_IO(conn->sock->sock);
528
529   /* Execute the protocol */
530   silc_protocol_execute(protocol, client->schedule, 0, 0);
531 }
532
533 /* Start SILC Key Exchange (SKE) protocol to negotiate shared secret
534    key material between client and server.  This function can be called
535    directly if application is performing its own connecting and does not
536    use the connecting provided by this library. This function is normally
537    used only if the application performed the connecting outside the library.
538    The library however may use this internally. */
539
540 void silc_client_start_key_exchange(SilcClient client,
541                                     SilcClientConnection conn,
542                                     int fd)
543 {
544   assert(client->pkcs);
545   assert(client->public_key);
546   assert(client->private_key);
547
548   /* Allocate new socket connection object */
549   silc_socket_alloc(fd, SILC_SOCKET_TYPE_SERVER, (void *)conn, &conn->sock);
550
551   /* Sometimes when doing quick reconnects the new socket may be same as
552      the old one and there might be pending stuff for the old socket.
553      If new one is same then those pending sutff might cause problems.
554      Make sure they do not do that. */
555   silc_schedule_task_del_by_fd(client->schedule, fd);
556
557   conn->nickname = (client->nickname ? strdup(client->nickname) :
558                     strdup(client->username));
559
560   /* Resolve the remote hostname and IP address for our socket connection */
561   silc_socket_host_lookup(conn->sock, FALSE, silc_client_start_key_exchange_cb,
562                           conn, client->schedule);
563 }
564
565 /* Callback called when error has occurred during connecting (KE) to
566    the server.  The `connect' client operation will be called. */
567
568 SILC_TASK_CALLBACK(silc_client_connect_failure)
569 {
570   SilcClientKEInternalContext *ctx =
571     (SilcClientKEInternalContext *)context;
572   SilcClient client = (SilcClient)ctx->client;
573
574   client->internal->ops->connected(client, ctx->sock->user_data,
575                                    SILC_CLIENT_CONN_ERROR_KE);
576   if (ctx->packet)
577     silc_packet_context_free(ctx->packet);
578   silc_free(ctx);
579 }
580
581 /* Callback called when error has occurred during connecting (auth) to
582    the server.  The `connect' client operation will be called. */
583
584 SILC_TASK_CALLBACK(silc_client_connect_failure_auth)
585 {
586   SilcClientConnAuthInternalContext *ctx =
587     (SilcClientConnAuthInternalContext *)context;
588   SilcClient client = (SilcClient)ctx->client;
589
590   client->internal->ops->connected(client, ctx->sock->user_data, ctx->status);
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,
639                                        SILC_CLIENT_CONN_ERROR_TIMEOUT);
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     ctx->status = SILC_CLIENT_CONN_ERROR_AUTH;
792     goto err;
793   }
794
795   if (conn->internal->params.detach_data) {
796     /* Send RESUME_CLIENT packet to the server, which is used to resume
797        old detached session back. */
798     SilcBuffer auth;
799     SilcClientID *old_client_id;
800     unsigned char *old_id;
801     SilcUInt16 old_id_len;
802
803     if (!silc_client_process_detach_data(client, conn, &old_id, &old_id_len)) {
804       ctx->status = SILC_CLIENT_CONN_ERROR_RESUME;
805       goto err;
806     }
807
808     old_client_id = silc_id_str2id(old_id, old_id_len, SILC_ID_CLIENT);
809     if (!old_client_id) {
810       silc_free(old_id);
811       ctx->status = SILC_CLIENT_CONN_ERROR_RESUME;
812       goto err;
813     }
814
815     /* Generate authentication data that server will verify */
816     auth = silc_auth_public_key_auth_generate(client->public_key,
817                                               client->private_key,
818                                               client->rng,
819                                               conn->internal->hash,
820                                               old_client_id, SILC_ID_CLIENT);
821     if (!auth) {
822       silc_free(old_client_id);
823       silc_free(old_id);
824       ctx->status = SILC_CLIENT_CONN_ERROR_RESUME;
825       goto err;
826     }
827
828     packet = silc_buffer_alloc_size(2 + old_id_len + auth->len);
829     silc_buffer_format(packet,
830                        SILC_STR_UI_SHORT(old_id_len),
831                        SILC_STR_UI_XNSTRING(old_id, old_id_len),
832                        SILC_STR_UI_XNSTRING(auth->data, auth->len),
833                        SILC_STR_END);
834
835     /* Send the packet */
836     silc_client_packet_send(client, ctx->sock, SILC_PACKET_RESUME_CLIENT,
837                             NULL, 0, NULL, NULL,
838                             packet->data, packet->len, TRUE);
839     silc_buffer_free(packet);
840     silc_buffer_free(auth);
841     silc_free(old_client_id);
842     silc_free(old_id);
843   } else {
844     /* Send NEW_CLIENT packet to the server. We will become registered
845        to the SILC network after sending this packet and we will receive
846        client ID from the server. */
847     packet = silc_buffer_alloc(2 + 2 + strlen(client->username) +
848                                strlen(client->realname));
849     silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
850     silc_buffer_format(packet,
851                        SILC_STR_UI_SHORT(strlen(client->username)),
852                        SILC_STR_UI_XNSTRING(client->username,
853                                             strlen(client->username)),
854                        SILC_STR_UI_SHORT(strlen(client->realname)),
855                        SILC_STR_UI_XNSTRING(client->realname,
856                                             strlen(client->realname)),
857                        SILC_STR_END);
858
859     /* Send the packet */
860     silc_client_packet_send(client, ctx->sock, SILC_PACKET_NEW_CLIENT,
861                             NULL, 0, NULL, NULL,
862                             packet->data, packet->len, TRUE);
863     silc_buffer_free(packet);
864   }
865
866   /* Save remote ID. */
867   conn->remote_id = ctx->dest_id;
868   conn->remote_id_data = silc_id_id2str(ctx->dest_id, SILC_ID_SERVER);
869   conn->remote_id_data_len = silc_id_get_len(ctx->dest_id, SILC_ID_SERVER);
870
871   /* Register re-key timeout */
872   conn->internal->rekey->timeout = client->internal->params->rekey_secs;
873   conn->internal->rekey->context = (void *)client;
874   silc_schedule_task_add(client->schedule, conn->sock->sock,
875                          silc_client_rekey_callback,
876                          (void *)conn->sock, conn->internal->rekey->timeout, 0,
877                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
878
879   silc_protocol_free(protocol);
880   silc_free(ctx->auth_data);
881   if (ctx->ske)
882     silc_ske_free(ctx->ske);
883   silc_socket_free(ctx->sock);
884   silc_free(ctx);
885   conn->sock->protocol = NULL;
886   return;
887
888  err:
889   silc_protocol_free(protocol);
890   silc_free(ctx->auth_data);
891   silc_free(ctx->dest_id);
892   if (ctx->ske)
893     silc_ske_free(ctx->ske);
894   conn->sock->protocol = NULL;
895   silc_socket_free(ctx->sock);
896
897   /* Notify application of failure */
898   silc_schedule_task_add(client->schedule, ctx->sock->sock,
899                          silc_client_connect_failure_auth, ctx,
900                          0, 1, SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
901 }
902
903 /* Internal routine that sends packet or marks packet to be sent. This
904    is used directly only in special cases. Normal cases should use
905    silc_server_packet_send. Returns < 0 on error. */
906
907 int silc_client_packet_send_real(SilcClient client,
908                                  SilcSocketConnection sock,
909                                  bool force_send)
910 {
911   int ret;
912
913   /* If rekey protocol is active we must assure that all packets are
914      sent through packet queue. */
915   if (SILC_CLIENT_IS_REKEY(sock))
916     force_send = FALSE;
917
918   /* If outbound data is already pending do not force send */
919   if (SILC_IS_OUTBUF_PENDING(sock))
920     force_send = FALSE;
921
922   /* Send the packet */
923   ret = silc_packet_send(sock, force_send);
924   if (ret != -2)
925     return ret;
926
927   /* Mark that there is some outgoing data available for this connection.
928      This call sets the connection both for input and output (the input
929      is set always and this call keeps the input setting, actually).
930      Actual data sending is performed by silc_client_packet_process. */
931   SILC_CLIENT_SET_CONNECTION_FOR_OUTPUT(client->schedule, sock->sock);
932
933   /* Mark to socket that data is pending in outgoing buffer. This flag
934      is needed if new data is added to the buffer before the earlier
935      put data is sent to the network. */
936   SILC_SET_OUTBUF_PENDING(sock);
937
938   return 0;
939 }
940
941 /* Packet processing callback. This is used to send and receive packets
942    from network. This is generic task. */
943
944 SILC_TASK_CALLBACK_GLOBAL(silc_client_packet_process)
945 {
946   SilcClient client = (SilcClient)context;
947   SilcSocketConnection sock = NULL;
948   SilcClientConnection conn;
949   int ret;
950
951   SILC_LOG_DEBUG(("Processing packet"));
952
953   SILC_CLIENT_GET_SOCK(client, fd, sock);
954   if (sock == NULL)
955     return;
956
957   conn = (SilcClientConnection)sock->user_data;
958
959   /* Packet sending */
960   if (type == SILC_TASK_WRITE) {
961     /* Do not send data to disconnected connection */
962     if (SILC_IS_DISCONNECTED(sock))
963       return;
964
965     ret = silc_packet_send(sock, TRUE);
966
967     /* If returned -2 could not write to connection now, will do
968        it later. */
969     if (ret == -2)
970       return;
971
972     /* Error */
973     if (ret == -1)
974       return;
975
976     /* The packet has been sent and now it is time to set the connection
977        back to only for input. When there is again some outgoing data
978        available for this connection it will be set for output as well.
979        This call clears the output setting and sets it only for input. */
980     SILC_CLIENT_SET_CONNECTION_FOR_INPUT(client->schedule, fd);
981     SILC_UNSET_OUTBUF_PENDING(sock);
982
983     silc_buffer_clear(sock->outbuf);
984     return;
985   }
986
987   /* Packet receiving */
988   if (type == SILC_TASK_READ) {
989     /* Read data from network */
990     ret = silc_packet_receive(sock);
991     if (ret < 0)
992       return;
993
994     /* EOF */
995     if (ret == 0) {
996       SILC_LOG_DEBUG(("Read EOF"));
997
998       /* If connection is disconnecting already we will finally
999          close the connection */
1000       if (SILC_IS_DISCONNECTING(sock)) {
1001         if (sock == conn->sock && sock->type != SILC_SOCKET_TYPE_CLIENT)
1002           client->internal->ops->disconnected(client, conn, 0, NULL);
1003         silc_client_close_connection_real(client, sock, conn);
1004         return;
1005       }
1006
1007       SILC_LOG_DEBUG(("EOF from connection %d", sock->sock));
1008       if (sock == conn->sock && sock->type != SILC_SOCKET_TYPE_CLIENT)
1009         client->internal->ops->disconnected(client, conn, 0, NULL);
1010       silc_client_close_connection_real(client, sock, conn);
1011       return;
1012     }
1013
1014     /* Process the packet. This will call the parser that will then
1015        decrypt and parse the packet. */
1016     if (sock->type != SILC_SOCKET_TYPE_UNKNOWN)
1017       silc_packet_receive_process(sock, FALSE, conn->internal->receive_key,
1018                                   conn->internal->hmac_receive,
1019                                   conn->internal->psn_receive,
1020                                   silc_client_packet_parse, client);
1021     else
1022       silc_packet_receive_process(sock, FALSE, NULL, NULL, 0,
1023                                   silc_client_packet_parse, client);
1024   }
1025 }
1026
1027 /* Parser callback called by silc_packet_receive_process. Thie merely
1028    registers timeout that will handle the actual parsing when appropriate. */
1029
1030 static bool silc_client_packet_parse(SilcPacketParserContext *parser_context,
1031                                      void *context)
1032 {
1033   SilcClient client = (SilcClient)context;
1034   SilcSocketConnection sock = parser_context->sock;
1035   SilcClientConnection conn = (SilcClientConnection)sock->user_data;
1036   SilcPacketContext *packet = parser_context->packet;
1037   SilcPacketType ret;
1038
1039   if (conn && conn->internal->hmac_receive && conn->sock == sock)
1040     conn->internal->psn_receive = parser_context->packet->sequence + 1;
1041
1042   /* Parse the packet immediately */
1043   if (parser_context->normal)
1044     ret = silc_packet_parse(packet, conn->internal->receive_key);
1045   else
1046     ret = silc_packet_parse_special(packet, conn->internal->receive_key);
1047
1048   if (ret == SILC_PACKET_NONE) {
1049     silc_packet_context_free(packet);
1050     silc_free(parser_context);
1051     return FALSE;
1052   }
1053
1054   /* If protocol for this connection is key exchange or rekey then we'll
1055      process all packets synchronously, since there might be packets in
1056      queue that we are not able to decrypt without first processing the
1057      packets before them. */
1058   if (sock->protocol && sock->protocol->protocol &&
1059       (sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_KEY_EXCHANGE ||
1060        sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_REKEY)) {
1061
1062     /* Parse the incoming packet type */
1063     silc_client_packet_parse_type(client, sock, packet);
1064
1065     /* Reprocess the buffer since we'll return FALSE. This is because
1066        the `conn->internal->receive_key' might have become valid by processing
1067        the previous packet */
1068     if (sock->type != SILC_SOCKET_TYPE_UNKNOWN)
1069       silc_packet_receive_process(sock, FALSE, conn->internal->receive_key,
1070                                   conn->internal->hmac_receive,
1071                                   conn->internal->psn_receive,
1072                                   silc_client_packet_parse, client);
1073     else
1074       silc_packet_receive_process(sock, FALSE, NULL, NULL, 0,
1075                                   silc_client_packet_parse, client);
1076
1077     silc_packet_context_free(packet);
1078     silc_free(parser_context);
1079
1080     return FALSE;
1081   }
1082
1083   /* Parse the incoming packet type */
1084   silc_client_packet_parse_type(client, sock, packet);
1085   silc_packet_context_free(packet);
1086   silc_free(parser_context);
1087   return TRUE;
1088 }
1089
1090 /* Parses the packet type and calls what ever routines the packet type
1091    requires. This is done for all incoming packets. */
1092
1093 void silc_client_packet_parse_type(SilcClient client,
1094                                    SilcSocketConnection sock,
1095                                    SilcPacketContext *packet)
1096 {
1097   SilcBuffer buffer = packet->buffer;
1098   SilcPacketType type = packet->type;
1099
1100   SILC_LOG_DEBUG(("Parsing %s packet", silc_get_packet_name(type)));
1101
1102   /* Parse the packet type */
1103   switch(type) {
1104
1105   case SILC_PACKET_DISCONNECT:
1106     silc_client_disconnected_by_server(client, sock, buffer);
1107     break;
1108
1109   case SILC_PACKET_SUCCESS:
1110     /*
1111      * Success received for something. For now we can have only
1112      * one protocol for connection executing at once hence this
1113      * success message is for whatever protocol is executing currently.
1114      */
1115     if (sock->protocol)
1116       silc_protocol_execute(sock->protocol, client->schedule, 0, 0);
1117     break;
1118
1119   case SILC_PACKET_FAILURE:
1120     /*
1121      * Failure received for some protocol. Set the protocol state to
1122      * error and call the protocol callback. This fill cause error on
1123      * protocol and it will call the final callback.
1124      */
1125     silc_client_process_failure(client, sock, packet);
1126     break;
1127
1128   case SILC_PACKET_REJECT:
1129     break;
1130
1131   case SILC_PACKET_NOTIFY:
1132     /*
1133      * Received notify message
1134      */
1135     silc_client_notify_by_server(client, sock, packet);
1136     break;
1137
1138   case SILC_PACKET_ERROR:
1139     /*
1140      * Received error message
1141      */
1142     silc_client_error_by_server(client, sock, buffer);
1143     break;
1144
1145   case SILC_PACKET_CHANNEL_MESSAGE:
1146     /*
1147      * Received message to (from, actually) a channel
1148      */
1149     silc_client_channel_message(client, sock, packet);
1150     break;
1151
1152   case SILC_PACKET_CHANNEL_KEY:
1153     /*
1154      * Received key for a channel. By receiving this key the client will be
1155      * able to talk to the channel it has just joined. This can also be
1156      * a new key for existing channel as keys expire peridiocally.
1157      */
1158     silc_client_receive_channel_key(client, sock, buffer);
1159     break;
1160
1161   case SILC_PACKET_PRIVATE_MESSAGE:
1162     /*
1163      * Received private message
1164      */
1165     silc_client_private_message(client, sock, packet);
1166     break;
1167
1168   case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1169     /*
1170      * Received private message key indicator
1171      */
1172     silc_client_private_message_key(client, sock, packet);
1173     break;
1174
1175   case SILC_PACKET_COMMAND:
1176     /*
1177      * Received command packet, a special case since normally client
1178      * does not receive commands.
1179      */
1180     silc_client_command_process(client, sock, packet);
1181     break;
1182
1183   case SILC_PACKET_COMMAND_REPLY:
1184     /*
1185      * Recived reply for a command
1186      */
1187     silc_client_command_reply_process(client, sock, packet);
1188     break;
1189
1190   case SILC_PACKET_KEY_EXCHANGE:
1191     if (sock->protocol && sock->protocol->protocol &&
1192         sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_KEY_EXCHANGE) {
1193       SilcClientKEInternalContext *proto_ctx =
1194         (SilcClientKEInternalContext *)sock->protocol->context;
1195
1196       proto_ctx->packet = silc_packet_context_dup(packet);
1197       proto_ctx->dest_id_type = packet->src_id_type;
1198       proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1199                                           packet->src_id_type);
1200       if (!proto_ctx->dest_id)
1201         break;
1202
1203       /* Let the protocol handle the packet */
1204       silc_protocol_execute(sock->protocol, client->schedule, 0, 0);
1205     } else {
1206       SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1207                       "protocol active, packet dropped."));
1208     }
1209     break;
1210
1211   case SILC_PACKET_KEY_EXCHANGE_1:
1212     if (sock->protocol && sock->protocol->protocol &&
1213         (sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_KEY_EXCHANGE ||
1214          sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_REKEY)) {
1215
1216       if (sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_REKEY) {
1217         SilcClientRekeyInternalContext *proto_ctx =
1218           (SilcClientRekeyInternalContext *)sock->protocol->context;
1219
1220         if (proto_ctx->packet)
1221           silc_packet_context_free(proto_ctx->packet);
1222
1223         proto_ctx->packet = silc_packet_context_dup(packet);
1224
1225         /* Let the protocol handle the packet */
1226         silc_protocol_execute(sock->protocol, client->schedule, 0, 0);
1227       } else {
1228         SilcClientKEInternalContext *proto_ctx =
1229           (SilcClientKEInternalContext *)sock->protocol->context;
1230
1231         if (proto_ctx->packet)
1232           silc_packet_context_free(proto_ctx->packet);
1233
1234         proto_ctx->packet = silc_packet_context_dup(packet);
1235         proto_ctx->dest_id_type = packet->src_id_type;
1236         proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1237                                             packet->src_id_type);
1238         if (!proto_ctx->dest_id)
1239           break;
1240
1241         /* Let the protocol handle the packet */
1242         silc_protocol_execute(sock->protocol, client->schedule, 0, 0);
1243       }
1244     } else {
1245       SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1246                       "protocol active, packet dropped."));
1247     }
1248     break;
1249
1250   case SILC_PACKET_KEY_EXCHANGE_2:
1251     if (sock->protocol && sock->protocol->protocol &&
1252         (sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_KEY_EXCHANGE ||
1253          sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_REKEY)) {
1254
1255       if (sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_REKEY) {
1256         SilcClientRekeyInternalContext *proto_ctx =
1257           (SilcClientRekeyInternalContext *)sock->protocol->context;
1258
1259         if (proto_ctx->packet)
1260           silc_packet_context_free(proto_ctx->packet);
1261
1262         proto_ctx->packet = silc_packet_context_dup(packet);
1263
1264         /* Let the protocol handle the packet */
1265         silc_protocol_execute(sock->protocol, client->schedule, 0, 0);
1266       } else {
1267         SilcClientKEInternalContext *proto_ctx =
1268           (SilcClientKEInternalContext *)sock->protocol->context;
1269
1270         if (proto_ctx->packet)
1271           silc_packet_context_free(proto_ctx->packet);
1272         if (proto_ctx->dest_id)
1273           silc_free(proto_ctx->dest_id);
1274         proto_ctx->packet = silc_packet_context_dup(packet);
1275         proto_ctx->dest_id_type = packet->src_id_type;
1276         proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1277                                             packet->src_id_type);
1278         if (!proto_ctx->dest_id)
1279           break;
1280
1281         /* Let the protocol handle the packet */
1282         silc_protocol_execute(sock->protocol, client->schedule, 0, 0);
1283       }
1284     } else {
1285       SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1286                       "protocol active, packet dropped."));
1287     }
1288     break;
1289
1290   case SILC_PACKET_NEW_ID:
1291     {
1292       /*
1293        * Received new ID from server. This packet is received at
1294        * the connection to the server.  New ID is also received when
1295        * user changes nickname but in that case the new ID is received
1296        * as command reply and not as this packet type.
1297        */
1298       SilcIDPayload idp;
1299
1300       idp = silc_id_payload_parse(buffer->data, buffer->len);
1301       if (!idp)
1302         break;
1303       if (silc_id_payload_get_type(idp) != SILC_ID_CLIENT)
1304         break;
1305
1306       silc_client_receive_new_id(client, sock, idp);
1307       silc_id_payload_free(idp);
1308       break;
1309     }
1310
1311   case SILC_PACKET_HEARTBEAT:
1312     /*
1313      * Received heartbeat packet
1314      */
1315     SILC_LOG_DEBUG(("Heartbeat packet"));
1316     break;
1317
1318   case SILC_PACKET_KEY_AGREEMENT:
1319     /*
1320      * Received key agreement packet
1321      */
1322     SILC_LOG_DEBUG(("Key agreement packet"));
1323     silc_client_key_agreement(client, sock, packet);
1324     break;
1325
1326   case SILC_PACKET_REKEY:
1327     SILC_LOG_DEBUG(("Re-key packet"));
1328     /* We ignore this for now */
1329     break;
1330
1331   case SILC_PACKET_REKEY_DONE:
1332     SILC_LOG_DEBUG(("Re-key done packet"));
1333
1334     if (sock->protocol && sock->protocol->protocol &&
1335         sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_REKEY) {
1336
1337       SilcClientRekeyInternalContext *proto_ctx =
1338         (SilcClientRekeyInternalContext *)sock->protocol->context;
1339
1340       if (proto_ctx->packet)
1341         silc_packet_context_free(proto_ctx->packet);
1342
1343       proto_ctx->packet = silc_packet_context_dup(packet);
1344
1345       /* Let the protocol handle the packet */
1346       if (proto_ctx->responder == FALSE)
1347         silc_protocol_execute(sock->protocol, client->schedule, 0, 0);
1348       else
1349         /* Let the protocol handle the packet */
1350         silc_protocol_execute(sock->protocol, client->schedule,
1351                               0, 100000);
1352     } else {
1353       SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
1354                       "protocol active, packet dropped."));
1355     }
1356     break;
1357
1358   case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1359     /*
1360      * Reveived reply to our connection authentication method request
1361      * packet. This is used to resolve the authentication method for the
1362      * current session from the server if the client does not know it.
1363      */
1364     silc_client_connection_auth_request(client, sock, packet);
1365     break;
1366
1367   case SILC_PACKET_FTP:
1368     /* Received file transfer packet. */
1369     silc_client_ftp(client, sock, packet);
1370     break;
1371
1372   default:
1373     SILC_LOG_DEBUG(("Incorrect packet type %d, packet dropped", type));
1374     break;
1375   }
1376 }
1377
1378 /* Sends packet. This doesn't actually send the packet instead it assembles
1379    it and marks it to be sent. However, if force_send is TRUE the packet
1380    is sent immediately. if dst_id, cipher and hmac are NULL those parameters
1381    will be derived from sock argument. Otherwise the valid arguments sent
1382    are used. */
1383
1384 void silc_client_packet_send(SilcClient client,
1385                              SilcSocketConnection sock,
1386                              SilcPacketType type,
1387                              void *dst_id,
1388                              SilcIdType dst_id_type,
1389                              SilcCipher cipher,
1390                              SilcHmac hmac,
1391                              unsigned char *data,
1392                              SilcUInt32 data_len,
1393                              bool force_send)
1394 {
1395   SilcPacketContext packetdata;
1396   const SilcBufferStruct packet;
1397   int block_len;
1398   SilcUInt32 sequence = 0;
1399
1400   if (!sock)
1401     return;
1402
1403   SILC_LOG_DEBUG(("Sending packet, type %d", type));
1404
1405   /* Get data used in the packet sending, keys and stuff */
1406   if ((!cipher || !hmac || !dst_id) && sock->user_data) {
1407     if (!cipher && ((SilcClientConnection)sock->user_data)->internal->send_key)
1408       cipher = ((SilcClientConnection)sock->user_data)->internal->send_key;
1409
1410     if (!hmac && ((SilcClientConnection)sock->user_data)->internal->hmac_send)
1411       hmac = ((SilcClientConnection)sock->user_data)->internal->hmac_send;
1412
1413     if (!dst_id && ((SilcClientConnection)sock->user_data)->remote_id) {
1414       dst_id = ((SilcClientConnection)sock->user_data)->remote_id;
1415       dst_id_type = SILC_ID_SERVER;
1416     }
1417
1418     if (hmac)
1419       sequence = ((SilcClientConnection)sock->user_data)->internal->psn_send++;
1420
1421     /* Check for mandatory rekey */
1422     if (sequence == SILC_CLIENT_REKEY_THRESHOLD)
1423       silc_schedule_task_add(client->schedule, sock->sock,
1424                              silc_client_rekey_callback, sock, 0, 1,
1425                              SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1426   }
1427
1428   block_len = cipher ? silc_cipher_get_block_len(cipher) : 0;
1429
1430   /* Set the packet context pointers */
1431   packetdata.flags = 0;
1432   packetdata.type = type;
1433   if (sock->user_data &&
1434       ((SilcClientConnection)sock->user_data)->local_id_data) {
1435     packetdata.src_id = ((SilcClientConnection)sock->user_data)->local_id_data;
1436     packetdata.src_id_len =
1437       silc_id_get_len(((SilcClientConnection)sock->user_data)->local_id,
1438                       SILC_ID_CLIENT);
1439   } else {
1440     packetdata.src_id = silc_calloc(SILC_ID_CLIENT_LEN, sizeof(unsigned char));
1441     packetdata.src_id_len = SILC_ID_CLIENT_LEN;
1442   }
1443   packetdata.src_id_type = SILC_ID_CLIENT;
1444   if (dst_id) {
1445     packetdata.dst_id = silc_id_id2str(dst_id, dst_id_type);
1446     packetdata.dst_id_len = silc_id_get_len(dst_id, dst_id_type);
1447     packetdata.dst_id_type = dst_id_type;
1448   } else {
1449     packetdata.dst_id = NULL;
1450     packetdata.dst_id_len = 0;
1451     packetdata.dst_id_type = SILC_ID_NONE;
1452   }
1453   data_len = SILC_PACKET_DATALEN(data_len, (SILC_PACKET_HEADER_LEN +
1454                                             packetdata.src_id_len +
1455                                             packetdata.dst_id_len));
1456   packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
1457     packetdata.src_id_len + packetdata.dst_id_len;
1458   if (type == SILC_PACKET_CONNECTION_AUTH)
1459     SILC_PACKET_PADLEN_MAX(packetdata.truelen, block_len, packetdata.padlen);
1460   else
1461     SILC_PACKET_PADLEN(packetdata.truelen, block_len, packetdata.padlen);
1462
1463   /* Create the outgoing packet */
1464   if (!silc_packet_assemble(&packetdata, client->rng, cipher, hmac, sock,
1465                             data, data_len, (const SilcBuffer)&packet)) {
1466     SILC_LOG_ERROR(("Error assembling packet"));
1467     return;
1468   }
1469
1470   /* Encrypt the packet */
1471   if (cipher)
1472     silc_packet_encrypt(cipher, hmac, sequence, (SilcBuffer)&packet,
1473                         packet.len);
1474
1475   SILC_LOG_HEXDUMP(("Packet (%d), len %d", sequence, packet.len),
1476                    packet.data, packet.len);
1477
1478   /* Now actually send the packet */
1479   silc_client_packet_send_real(client, sock, force_send);
1480 }
1481
1482 /* Packet sending routine for application.  This is the only routine that
1483    is provided for application to send SILC packets. */
1484
1485 bool silc_client_send_packet(SilcClient client,
1486                              SilcClientConnection conn,
1487                              SilcPacketType type,
1488                              const unsigned char *data,
1489                              SilcUInt32 data_len)
1490 {
1491
1492   assert(client);
1493   if (!conn)
1494     return FALSE;
1495
1496   silc_client_packet_send(client, conn->sock, type, NULL, 0, NULL, NULL,
1497                           (unsigned char *)data, data_len, TRUE);
1498   return TRUE;
1499 }
1500
1501 void silc_client_packet_queue_purge(SilcClient client,
1502                                     SilcSocketConnection sock)
1503 {
1504   if (sock && SILC_IS_OUTBUF_PENDING(sock) &&
1505       !(SILC_IS_DISCONNECTED(sock))) {
1506     int ret;
1507
1508     ret = silc_packet_send(sock, TRUE);
1509     if (ret == -2) {
1510       if (sock->outbuf && sock->outbuf->len > 0) {
1511         /* Couldn't send all data, put the queue back up, we'll send
1512            rest later. */
1513         SILC_CLIENT_SET_CONNECTION_FOR_OUTPUT(client->schedule, sock->sock);
1514         SILC_SET_OUTBUF_PENDING(sock);
1515         return;
1516       }
1517     }
1518
1519     /* Purged all data */
1520     SILC_UNSET_OUTBUF_PENDING(sock);
1521     SILC_CLIENT_SET_CONNECTION_FOR_INPUT(client->schedule, sock->sock);
1522     silc_buffer_clear(sock->outbuf);
1523   }
1524 }
1525
1526 /* Closes connection to remote end. Free's all allocated data except
1527    for some information such as nickname etc. that are valid at all time.
1528    If the `sock' is NULL then the conn->sock will be used.  If `sock' is
1529    provided it will be checked whether the sock and `conn->sock' are the
1530    same (they can be different, ie. a socket can use `conn' as its
1531    connection but `conn->sock' might be actually a different connection
1532    than the `sock'). */
1533
1534 void silc_client_close_connection_real(SilcClient client,
1535                                        SilcSocketConnection sock,
1536                                        SilcClientConnection conn)
1537 {
1538   int del = FALSE;
1539
1540   SILC_LOG_DEBUG(("Start"));
1541
1542   if (!sock && !conn)
1543     return;
1544
1545   if (!sock || (sock && conn->sock == sock))
1546     del = TRUE;
1547   if (!sock)
1548     sock = conn->sock;
1549
1550   if (!sock) {
1551     if (del && conn)
1552       silc_client_del_connection(client, conn);
1553     return;
1554   }
1555
1556   /* We won't listen for this connection anymore */
1557   silc_schedule_unset_listen_fd(client->schedule, sock->sock);
1558
1559   /* Unregister all tasks */
1560   silc_schedule_task_del_by_fd(client->schedule, sock->sock);
1561
1562   /* Close the actual connection */
1563   silc_net_close_connection(sock->sock);
1564
1565   /* Cancel any active protocol */
1566   if (sock->protocol) {
1567     if (sock->protocol->protocol->type ==
1568         SILC_PROTOCOL_CLIENT_KEY_EXCHANGE ||
1569         sock->protocol->protocol->type ==
1570         SILC_PROTOCOL_CLIENT_CONNECTION_AUTH) {
1571       sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
1572       silc_protocol_execute_final(sock->protocol, client->schedule);
1573       /* The application will recall this function with these protocols
1574          (the ops->connected client operation). */
1575       return;
1576     } else {
1577       sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
1578       silc_protocol_execute_final(sock->protocol, client->schedule);
1579       sock->protocol = NULL;
1580     }
1581   }
1582
1583   /* Free everything */
1584   if (del && sock->user_data)
1585     silc_client_del_connection(client, conn);
1586
1587   silc_socket_free(sock);
1588 }
1589
1590 /* Closes the connection to the remote end */
1591
1592 void silc_client_close_connection(SilcClient client,
1593                                   SilcClientConnection conn)
1594 {
1595   silc_client_close_connection_real(client, NULL, conn);
1596 }
1597
1598 /* Called when we receive disconnection packet from server. This
1599    closes our end properly and displays the reason of the disconnection
1600    on the screen. */
1601
1602 SILC_TASK_CALLBACK(silc_client_disconnected_by_server_later)
1603 {
1604   SilcClient client = (SilcClient)context;
1605   SilcSocketConnection sock;
1606
1607   SILC_CLIENT_GET_SOCK(client, fd, sock);
1608   if (sock == NULL)
1609     return;
1610
1611   silc_client_close_connection_real(client, sock, sock->user_data);
1612 }
1613
1614 /* Called when we receive disconnection packet from server. This
1615    closes our end properly and displays the reason of the disconnection
1616    on the screen. */
1617
1618 void silc_client_disconnected_by_server(SilcClient client,
1619                                         SilcSocketConnection sock,
1620                                         SilcBuffer packet)
1621 {
1622   SilcClientConnection conn;
1623   SilcStatus status;
1624   char *message = NULL;
1625
1626   SILC_LOG_DEBUG(("Server disconnected us, sock %d", sock->sock));
1627
1628   if (packet->len < 1)
1629     return;
1630
1631   status = (SilcStatus)packet->data[0];
1632
1633   if (packet->len > 1 &&
1634       silc_utf8_valid(packet->data + 1, packet->len - 1))
1635     message = silc_memdup(packet->data + 1, packet->len - 1);
1636
1637   conn = (SilcClientConnection)sock->user_data;
1638   if (sock == conn->sock && sock->type != SILC_SOCKET_TYPE_CLIENT)
1639     client->internal->ops->disconnected(client, conn, status, message);
1640
1641   silc_free(message);
1642
1643   SILC_SET_DISCONNECTED(sock);
1644
1645   /* Close connection through scheduler. */
1646   silc_schedule_task_add(client->schedule, sock->sock,
1647                          silc_client_disconnected_by_server_later,
1648                          client, 0, 1, SILC_TASK_TIMEOUT,
1649                          SILC_TASK_PRI_NORMAL);
1650 }
1651
1652 /* Received error message from server. Display it on the screen.
1653    We don't take any action what so ever of the error message. */
1654
1655 void silc_client_error_by_server(SilcClient client,
1656                                  SilcSocketConnection sock,
1657                                  SilcBuffer message)
1658 {
1659   char *msg;
1660
1661   msg = silc_memdup(message->data, message->len);
1662   client->internal->ops->say(client, sock->user_data,
1663                              SILC_CLIENT_MESSAGE_AUDIT, msg);
1664   silc_free(msg);
1665 }
1666
1667 /* Auto-nicking callback to send NICK command to server. */
1668
1669 SILC_TASK_CALLBACK(silc_client_send_auto_nick)
1670 {
1671   SilcClientConnection conn = (SilcClientConnection)context;
1672   SilcClient client = conn->client;
1673   if (client)
1674     silc_client_command_send(client, conn, SILC_COMMAND_NICK,
1675                              ++conn->cmd_ident, 1, 1,
1676                              client->nickname, strlen(client->nickname));
1677 }
1678
1679 /* Client session resuming callback.  If the session was resumed
1680    this callback is called after the resuming is completed.  This
1681    will call the `connect' client operation to the application
1682    since it has not been called yet. */
1683
1684 static void silc_client_resume_session_cb(SilcClient client,
1685                                           SilcClientConnection conn,
1686                                           bool success,
1687                                           void *context)
1688 {
1689   SilcBuffer sidp;
1690
1691   /* Notify application that connection is created to server */
1692   client->internal->ops->connected(client, conn, success ?
1693                                    SILC_CLIENT_CONN_SUCCESS_RESUME :
1694                                    SILC_CLIENT_CONN_ERROR_RESUME);
1695
1696   if (success) {
1697     /* Issue INFO command to fetch the real server name and server
1698        information and other stuff. */
1699     silc_client_command_register(client, SILC_COMMAND_INFO, NULL, NULL,
1700                                  silc_client_command_reply_info_i, 0,
1701                                  ++conn->cmd_ident);
1702     sidp = silc_id_payload_encode(conn->remote_id, SILC_ID_SERVER);
1703     silc_client_command_send(client, conn, SILC_COMMAND_INFO,
1704                              conn->cmd_ident, 1, 2, sidp->data, sidp->len);
1705     silc_buffer_free(sidp);
1706   }
1707 }
1708
1709 /* Processes the received new Client ID from server. Old Client ID is
1710    deleted from cache and new one is added. */
1711
1712 void silc_client_receive_new_id(SilcClient client,
1713                                 SilcSocketConnection sock,
1714                                 SilcIDPayload idp)
1715 {
1716   SilcClientConnection conn = (SilcClientConnection)sock->user_data;
1717   int connecting = FALSE;
1718   SilcClientID *client_id = silc_id_payload_get_id(idp);
1719
1720   if (!conn->local_entry)
1721     connecting = TRUE;
1722
1723   /* Delete old ID from ID cache */
1724   if (conn->local_id) {
1725     /* Check whether they are different */
1726     if (SILC_ID_CLIENT_COMPARE(conn->local_id, client_id)) {
1727       silc_free(client_id);
1728       return;
1729     }
1730
1731     silc_idcache_del_by_context(conn->internal->client_cache,
1732                                 conn->local_entry);
1733     silc_free(conn->local_id);
1734   }
1735
1736   /* Save the new ID */
1737
1738   if (conn->local_id_data)
1739     silc_free(conn->local_id_data);
1740
1741   conn->local_id = client_id;
1742   conn->local_id_data = silc_id_payload_get_data(idp);
1743   conn->local_id_data_len = silc_id_payload_get_len(idp);;
1744
1745   if (!conn->local_entry)
1746     conn->local_entry = silc_calloc(1, sizeof(*conn->local_entry));
1747
1748   conn->local_entry->nickname = conn->nickname;
1749   if (!conn->local_entry->username)
1750     conn->local_entry->username = strdup(client->username);
1751   if (!conn->local_entry->server)
1752     conn->local_entry->server = strdup(conn->remote_host);
1753   conn->local_entry->id = conn->local_id;
1754   conn->local_entry->valid = TRUE;
1755   if (!conn->local_entry->channels)
1756     conn->local_entry->channels = silc_hash_table_alloc(1, silc_hash_ptr,
1757                                                         NULL, NULL,
1758                                                         NULL, NULL, NULL,
1759                                                         TRUE);
1760
1761   /* Put it to the ID cache */
1762   silc_idcache_add(conn->internal->client_cache,
1763                    strdup(conn->nickname), conn->local_id,
1764                    (void *)conn->local_entry, 0, NULL);
1765
1766   if (connecting) {
1767     SilcBuffer sidp;
1768
1769     /* Issue IDENTIFY command for itself to get resolved hostname
1770        correctly from server. */
1771     silc_client_command_register(client, SILC_COMMAND_IDENTIFY, NULL, NULL,
1772                                  silc_client_command_reply_identify_i, 0,
1773                                  ++conn->cmd_ident);
1774     sidp = silc_id_payload_encode(conn->local_entry->id, SILC_ID_CLIENT);
1775     silc_client_command_send(client, conn, SILC_COMMAND_IDENTIFY,
1776                              conn->cmd_ident, 1, 5, sidp->data, sidp->len);
1777     silc_buffer_free(sidp);
1778
1779     if (!conn->internal->params.detach_data) {
1780       /* Send NICK command if the nickname was set by the application (and is
1781          not same as the username). Send this with little timeout. */
1782       if (client->nickname && strcmp(client->nickname, client->username))
1783         silc_schedule_task_add(client->schedule, 0,
1784                                silc_client_send_auto_nick, conn,
1785                                1, 0, SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1786
1787       /* Notify application of successful connection. We do it here now that
1788          we've received the Client ID and are allowed to send traffic. */
1789       client->internal->ops->connected(client, conn, SILC_CLIENT_CONN_SUCCESS);
1790
1791       /* Issue INFO command to fetch the real server name and server
1792          information and other stuff. */
1793       silc_client_command_register(client, SILC_COMMAND_INFO, NULL, NULL,
1794                                    silc_client_command_reply_info_i, 0,
1795                                    ++conn->cmd_ident);
1796       sidp = silc_id_payload_encode(conn->remote_id, SILC_ID_SERVER);
1797       silc_client_command_send(client, conn, SILC_COMMAND_INFO,
1798                                conn->cmd_ident, 1, 2, sidp->data, sidp->len);
1799       silc_buffer_free(sidp);
1800     } else {
1801       /* We are resuming session.  Start resolving informations from the
1802          server we need to set the client libary in the state before
1803          detaching the session.  The connect client operation is called
1804          after this is successfully completed */
1805       silc_client_resume_session(client, conn, silc_client_resume_session_cb,
1806                                  NULL);
1807     }
1808   }
1809 }
1810
1811 /* Removes a client entry from all channels it has joined. */
1812
1813 void silc_client_remove_from_channels(SilcClient client,
1814                                       SilcClientConnection conn,
1815                                       SilcClientEntry client_entry)
1816 {
1817   SilcHashTableList htl;
1818   SilcChannelUser chu;
1819
1820   silc_hash_table_list(client_entry->channels, &htl);
1821   while (silc_hash_table_get(&htl, NULL, (void *)&chu)) {
1822     silc_hash_table_del(chu->client->channels, chu->channel);
1823     silc_hash_table_del(chu->channel->user_list, chu->client);
1824     silc_free(chu);
1825   }
1826
1827   silc_hash_table_list_reset(&htl);
1828 }
1829
1830 /* Replaces `old' client entries from all channels to `new' client entry.
1831    This can be called for example when nickname changes and old ID entry
1832    is replaced from ID cache with the new one. If the old ID entry is only
1833    updated, then this fucntion needs not to be called. */
1834
1835 void silc_client_replace_from_channels(SilcClient client,
1836                                        SilcClientConnection conn,
1837                                        SilcClientEntry old,
1838                                        SilcClientEntry new)
1839 {
1840   SilcHashTableList htl;
1841   SilcChannelUser chu;
1842
1843   silc_hash_table_list(old->channels, &htl);
1844   while (silc_hash_table_get(&htl, NULL, (void *)&chu)) {
1845     /* Replace client entry */
1846     silc_hash_table_del(chu->client->channels, chu->channel);
1847     silc_hash_table_del(chu->channel->user_list, chu->client);
1848
1849     chu->client = new;
1850     silc_hash_table_add(chu->channel->user_list, chu->client, chu);
1851     silc_hash_table_add(chu->client->channels, chu->channel, chu);
1852   }
1853   silc_hash_table_list_reset(&htl);
1854 }
1855
1856 /* Registers failure timeout to process the received failure packet
1857    with timeout. */
1858
1859 void silc_client_process_failure(SilcClient client,
1860                                  SilcSocketConnection sock,
1861                                  SilcPacketContext *packet)
1862 {
1863   SilcUInt32 failure = 0;
1864
1865   if (sock->protocol) {
1866     if (packet->buffer->len >= 4)
1867       SILC_GET32_MSB(failure, packet->buffer->data);
1868
1869     /* Notify application */
1870     client->internal->ops->failure(client, sock->user_data, sock->protocol,
1871                                    SILC_32_TO_PTR(failure));
1872   }
1873 }
1874
1875 /* A timeout callback for the re-key. We will be the initiator of the
1876    re-key protocol. */
1877
1878 SILC_TASK_CALLBACK_GLOBAL(silc_client_rekey_callback)
1879 {
1880   SilcSocketConnection sock = (SilcSocketConnection)context;
1881   SilcClientConnection conn = (SilcClientConnection)sock->user_data;
1882   SilcClient client = (SilcClient)conn->internal->rekey->context;
1883   SilcProtocol protocol;
1884   SilcClientRekeyInternalContext *proto_ctx;
1885
1886   SILC_LOG_DEBUG(("Start"));
1887
1888   /* If rekey protocol is active already wait for it to finish */
1889   if (sock->protocol && sock->protocol->protocol &&
1890       sock->protocol->protocol->type == SILC_PROTOCOL_CLIENT_REKEY)
1891     return;
1892
1893   /* Allocate internal protocol context. This is sent as context
1894      to the protocol. */
1895   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1896   proto_ctx->client = (void *)client;
1897   proto_ctx->sock = silc_socket_dup(sock);
1898   proto_ctx->responder = FALSE;
1899   proto_ctx->pfs = conn->internal->rekey->pfs;
1900
1901   /* Perform rekey protocol. Will call the final callback after the
1902      protocol is over. */
1903   silc_protocol_alloc(SILC_PROTOCOL_CLIENT_REKEY,
1904                       &protocol, proto_ctx, silc_client_rekey_final);
1905   sock->protocol = protocol;
1906
1907   /* Run the protocol */
1908   silc_protocol_execute(protocol, client->schedule, 0, 0);
1909 }
1910
1911 /* The final callback for the REKEY protocol. This will actually take the
1912    new key material into use. */
1913
1914 SILC_TASK_CALLBACK(silc_client_rekey_final)
1915 {
1916   SilcProtocol protocol = (SilcProtocol)context;
1917   SilcClientRekeyInternalContext *ctx =
1918     (SilcClientRekeyInternalContext *)protocol->context;
1919   SilcClient client = (SilcClient)ctx->client;
1920   SilcSocketConnection sock = ctx->sock;
1921   SilcClientConnection conn = (SilcClientConnection)sock->user_data;
1922
1923   SILC_LOG_DEBUG(("Start"));
1924
1925   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1926       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1927     /* Error occured during protocol */
1928     silc_protocol_cancel(protocol, client->schedule);
1929     silc_protocol_free(protocol);
1930     sock->protocol = NULL;
1931     if (ctx->packet)
1932       silc_packet_context_free(ctx->packet);
1933     if (ctx->ske)
1934       silc_ske_free(ctx->ske);
1935     silc_socket_free(ctx->sock);
1936     silc_free(ctx);
1937     return;
1938   }
1939
1940   /* Purge the outgoing data queue to assure that all rekey packets really
1941      go to the network before we quit the protocol. */
1942   silc_client_packet_queue_purge(client, sock);
1943
1944   /* Re-register re-key timeout */
1945   if (ctx->responder == FALSE)
1946     silc_schedule_task_add(client->schedule, sock->sock,
1947                            silc_client_rekey_callback,
1948                            sock, conn->internal->rekey->timeout, 0,
1949                            SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1950
1951   /* Cleanup */
1952   silc_protocol_free(protocol);
1953   sock->protocol = NULL;
1954   if (ctx->packet)
1955     silc_packet_context_free(ctx->packet);
1956   if (ctx->ske)
1957     silc_ske_free(ctx->ske);
1958   silc_socket_free(ctx->sock);
1959   silc_free(ctx);
1960 }
1961
1962 /* Processes incoming connection authentication method request packet.
1963    It is a reply to our previously sent request. The packet can be used
1964    to resolve the authentication method for the current session if the
1965    client does not know it beforehand. */
1966
1967 void silc_client_connection_auth_request(SilcClient client,
1968                                          SilcSocketConnection sock,
1969                                          SilcPacketContext *packet)
1970 {
1971   SilcClientConnection conn = (SilcClientConnection)sock->user_data;
1972   SilcUInt16 conn_type, auth_meth;
1973   int ret;
1974
1975   /* If we haven't send our request then ignore this one. */
1976   if (!conn->internal->connauth)
1977     return;
1978
1979   /* Parse the payload */
1980   ret = silc_buffer_unformat(packet->buffer,
1981                              SILC_STR_UI_SHORT(&conn_type),
1982                              SILC_STR_UI_SHORT(&auth_meth),
1983                              SILC_STR_END);
1984   if (ret == -1)
1985     auth_meth = SILC_AUTH_NONE;
1986
1987   /* Call the request callback to notify application for received
1988      authentication method information. */
1989   if (conn->internal->connauth->callback)
1990     (*conn->internal->connauth->callback)(client, conn, auth_meth,
1991                                           conn->internal->connauth->context);
1992
1993   silc_schedule_task_del(client->schedule, conn->internal->connauth->timeout);
1994
1995   silc_free(conn->internal->connauth);
1996   conn->internal->connauth = NULL;
1997 }
1998
1999 /* Timeout task callback called if the server does not reply to our
2000    connection authentication method request in the specified time interval. */
2001
2002 SILC_TASK_CALLBACK(silc_client_request_authentication_method_timeout)
2003 {
2004   SilcClientConnection conn = (SilcClientConnection)context;
2005   SilcClient client = conn->client;
2006
2007   if (!conn->internal->connauth)
2008     return;
2009
2010   /* Call the request callback to notify application */
2011   if (conn->internal->connauth->callback)
2012     (*conn->internal->connauth->callback)(client, conn, SILC_AUTH_NONE,
2013                                           conn->internal->connauth->context);
2014
2015   silc_free(conn->internal->connauth);
2016   conn->internal->connauth = NULL;
2017 }
2018
2019 /* This function can be used to request the current authentication method
2020    from the server. This may be called when connecting to the server
2021    and the client library requests the authentication data from the
2022    application. If the application does not know the current authentication
2023    method it can request it from the server using this function.
2024    The `callback' with `context' will be called after the server has
2025    replied back with the current authentication method. */
2026
2027 void
2028 silc_client_request_authentication_method(SilcClient client,
2029                                           SilcClientConnection conn,
2030                                           SilcConnectionAuthRequest callback,
2031                                           void *context)
2032 {
2033   SilcClientConnAuthRequest connauth;
2034   SilcBuffer packet;
2035
2036   assert(client && conn);
2037   connauth = silc_calloc(1, sizeof(*connauth));
2038   connauth->callback = callback;
2039   connauth->context = context;
2040
2041   if (conn->internal->connauth)
2042     silc_free(conn->internal->connauth);
2043
2044   conn->internal->connauth = connauth;
2045
2046   /* Assemble the request packet and send it to the server */
2047   packet = silc_buffer_alloc(4);
2048   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
2049   silc_buffer_format(packet,
2050                      SILC_STR_UI_SHORT(SILC_SOCKET_TYPE_CLIENT),
2051                      SILC_STR_UI_SHORT(SILC_AUTH_NONE),
2052                      SILC_STR_END);
2053   silc_client_packet_send(client, conn->sock,
2054                           SILC_PACKET_CONNECTION_AUTH_REQUEST,
2055                           NULL, 0, NULL, NULL,
2056                           packet->data, packet->len, FALSE);
2057   silc_buffer_free(packet);
2058
2059   /* Register a timeout in case server does not reply anything back. */
2060   connauth->timeout =
2061     silc_schedule_task_add(client->schedule, conn->sock->sock,
2062                            silc_client_request_authentication_method_timeout,
2063                            conn,
2064                            client->internal->params->connauth_request_secs, 0,
2065                            SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2066 }