GSocketControlMessage: clean up confusing code
[platform/upstream/glib.git] / gio / gsocks5proxy.c
1  /* GIO - GLib Input, Output and Streaming Library
2  *
3  * Copyright (C) 2008, 2010 Collabora, Ltd.
4  * Copyright (C) 2008 Nokia Corporation. All rights reserved.
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General
17  * Public License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
19  * Boston, MA 02111-1307, USA.
20  *
21  * Author:  Youness Alaoui <youness.alaoui@collabora.co.uk
22  *
23  * Contributors:
24  *          Nicolas Dufresne <nicolas.dufresne@collabora.co.uk>
25  */
26
27 #include "config.h"
28
29 #include "gsocks5proxy.h"
30
31 #include <string.h>
32
33 #include "giomodule.h"
34 #include "giomodule-priv.h"
35 #include "giostream.h"
36 #include "ginetaddress.h"
37 #include "ginputstream.h"
38 #include "glibintl.h"
39 #include "goutputstream.h"
40 #include "gproxy.h"
41 #include "gproxyaddress.h"
42 #include "gsimpleasyncresult.h"
43
44 #define SOCKS5_VERSION            0x05
45
46 #define SOCKS5_CMD_CONNECT        0x01
47 #define SOCKS5_CMD_BIND           0x02
48 #define SOCKS5_CMD_UDP_ASSOCIATE  0x03
49
50 #define SOCKS5_ATYP_IPV4          0x01
51 #define SOCKS5_ATYP_DOMAINNAME    0x03
52 #define SOCKS5_ATYP_IPV6          0x04
53
54 #define SOCKS5_AUTH_VERSION       0x01
55
56 #define SOCKS5_AUTH_NONE          0x00
57 #define SOCKS5_AUTH_GSSAPI        0x01
58 #define SOCKS5_AUTH_USR_PASS      0x02
59 #define SOCKS5_AUTH_NO_ACCEPT     0xff
60
61 #define SOCKS5_MAX_LEN            255
62 #define SOCKS5_RESERVED           0x00
63
64 #define SOCKS5_REP_SUCCEEDED      0x00
65 #define SOCKS5_REP_SRV_FAILURE    0x01
66 #define SOCKS5_REP_NOT_ALLOWED    0x02
67 #define SOCKS5_REP_NET_UNREACH    0x03
68 #define SOCKS5_REP_HOST_UNREACH   0x04
69 #define SOCKS5_REP_REFUSED        0x05
70 #define SOCKS5_REP_TTL_EXPIRED    0x06
71 #define SOCKS5_REP_CMD_NOT_SUP    0x07
72 #define SOCKS5_REP_ATYPE_NOT_SUP  0x08
73
74
75 struct _GSocks5Proxy
76 {
77   GObject parent;
78 };
79
80 struct _GSocks5ProxyClass
81 {
82   GObjectClass parent_class;
83 };
84
85 static void g_socks5_proxy_iface_init (GProxyInterface *proxy_iface);
86
87 #define g_socks5_proxy_get_type _g_socks5_proxy_get_type
88 G_DEFINE_TYPE_WITH_CODE (GSocks5Proxy, g_socks5_proxy, G_TYPE_OBJECT,
89                          G_IMPLEMENT_INTERFACE (G_TYPE_PROXY,
90                                                 g_socks5_proxy_iface_init)
91                          _g_io_modules_ensure_extension_points_registered ();
92                          g_io_extension_point_implement (G_PROXY_EXTENSION_POINT_NAME,
93                                                          g_define_type_id,
94                                                          "socks5",
95                                                          0))
96
97 static void
98 g_socks5_proxy_finalize (GObject *object)
99 {
100   /* must chain up */
101   G_OBJECT_CLASS (g_socks5_proxy_parent_class)->finalize (object);
102 }
103
104 static void
105 g_socks5_proxy_init (GSocks5Proxy *proxy)
106 {
107 }
108
109 /*
110  * +----+----------+----------+
111  * |VER | NMETHODS | METHODS  |
112  * +----+----------+----------+
113  * | 1  |    1     | 1 to 255 |
114  * +----+----------+----------+
115  */
116 #define SOCKS5_NEGO_MSG_LEN       4
117 static gint
118 set_nego_msg (guint8 *msg, gboolean has_auth)
119 {
120   gint len = 3;
121
122   msg[0] = SOCKS5_VERSION;
123   msg[1] = 0x01; /* number of methods supported */
124   msg[2] = SOCKS5_AUTH_NONE;
125
126   /* add support for authentication method */
127   if (has_auth)
128     {
129       msg[1] = 0x02; /* number of methods supported */
130       msg[3] = SOCKS5_AUTH_USR_PASS;
131       len++;
132     }
133
134   return len;
135 }
136
137
138 /*
139  * +----+--------+
140  * |VER | METHOD |
141  * +----+--------+
142  * | 1  |   1    |
143  * +----+--------+
144  */
145 #define SOCKS5_NEGO_REP_LEN       2
146 static gboolean
147 parse_nego_reply (const guint8 *data,
148                   gboolean     has_auth,
149                   gboolean    *must_auth,
150                   GError     **error)
151 {
152   if (data[0] != SOCKS5_VERSION)
153     {
154       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
155                            _("The server is not a SOCKSv5 proxy server."));
156       return FALSE;
157     }
158
159   switch (data[1])
160     {
161       case SOCKS5_AUTH_NONE:
162         *must_auth = FALSE;
163         break;
164
165       case SOCKS5_AUTH_USR_PASS:
166         if (!has_auth)
167           {
168             g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_NEED_AUTH,
169                            _("The SOCKSv5 proxy requires authentication."));
170             return FALSE;
171           }
172         *must_auth = TRUE;
173         break;
174
175       case SOCKS5_AUTH_GSSAPI:
176       case SOCKS5_AUTH_NO_ACCEPT:
177       default:
178         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_AUTH_FAILED,
179                              _("The SOCKSv5 require an authentication method that is not "
180                                "supported by GLib."));
181         return FALSE;
182         break;
183     }
184
185   return TRUE;
186 }
187
188 #define SOCKS5_AUTH_MSG_LEN       515
189 static gint
190 set_auth_msg (guint8      *msg,
191               const gchar *username,
192               const gchar *password,
193               GError **error)
194 {
195   gint len = 0;
196   gint ulen = 0; /* username length */
197   gint plen = 0; /* Password length */
198
199   if (username)
200     ulen = strlen (username);
201
202   if (password)
203     plen = strlen (password);
204
205   if (ulen > SOCKS5_MAX_LEN || plen > SOCKS5_MAX_LEN)
206     {
207       g_set_error (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
208                    _("Username or password is too long for SOCKSv5 "
209                      "protocol (max. is %i)."),
210                    SOCKS5_MAX_LEN);
211       return FALSE;
212     }
213
214   msg[len++] = SOCKS5_AUTH_VERSION;
215   msg[len++] = ulen;
216
217   if (ulen > 0)
218     memcpy (msg + len, username, ulen);
219
220   len += ulen;
221   msg[len++] = plen;
222
223   if (plen > 0)
224     memcpy (msg + len, password, plen);
225
226   len += plen;
227
228   return len;
229 }
230
231
232 static gboolean
233 check_auth_status (const guint8 *data, GError **error)
234 {
235   if (data[0] != SOCKS5_VERSION
236       || data[1] != SOCKS5_REP_SUCCEEDED)
237     {
238       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_AUTH_FAILED,
239                            _("SOCKSv5 authentication failed due to wrong "
240                              "username or password."));
241       return FALSE;
242     }
243   return TRUE;
244 }
245
246 /*
247  * +----+-----+-------+------+----------+----------+
248  * |VER | CMD |  RSV  | ATYP | DST.ADDR | DST.PORT |
249  * +----+-----+-------+------+----------+----------+
250  * | 1  |  1  | X'00' |  1   | Variable |    2     |
251  * +----+-----+-------+------+----------+----------+
252  * DST.ADDR is a string with first byte being the size. So DST.ADDR may not be
253  * longer then 256 bytes.
254  */
255 #define SOCKS5_CONN_MSG_LEN       262
256 static gint
257 set_connect_msg (guint8       *msg,
258                  const gchar *hostname,
259                  guint16      port,
260                  GError     **error)
261 {
262   guint len = 0;
263
264   msg[len++] = SOCKS5_VERSION;
265   msg[len++] = SOCKS5_CMD_CONNECT;
266   msg[len++] = SOCKS5_RESERVED;
267
268   if (g_hostname_is_ip_address (hostname))
269     {
270       GInetAddress *addr = g_inet_address_new_from_string (hostname);
271       gsize addr_len = g_inet_address_get_native_size (addr);
272
273       /* We are cheating for simplicity, here's the logic:
274        *   1 = IPV4 = 4 bytes / 4
275        *   4 = IPV6 = 16 bytes / 4 */
276       msg[len++] = addr_len / 4;
277       memcpy (msg + len, g_inet_address_to_bytes (addr), addr_len);
278       len += addr_len;
279
280       g_object_unref (addr);
281     }
282   else
283     {
284       gsize host_len = strlen (hostname);
285
286       if (host_len > SOCKS5_MAX_LEN)
287         {
288           g_set_error (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
289                        _("Hostname '%s' too long for SOCKSv5 protocol "
290                          "(maximum is %i bytes)"),
291                        hostname, SOCKS5_MAX_LEN);
292           return -1;
293         }
294
295       msg[len++] = SOCKS5_ATYP_DOMAINNAME;
296       msg[len++] = (guint8) host_len;
297       memcpy (msg + len, hostname, host_len);
298       len += host_len;
299     }
300
301     {
302       guint16 hp = g_htons (port);
303       memcpy (msg + len, &hp, 2);
304       len += 2;
305     }
306
307   return len;
308 }
309
310 /*
311  * +----+-----+-------+------+----------+----------+
312  * |VER | REP |  RSV  | ATYP | BND.ADDR | BND.PORT |
313  * +----+-----+-------+------+----------+----------+
314  * | 1  |  1  | X'00' |  1   | Variable |    2     |
315  * +----+-----+-------+------+----------+----------+
316  * This reply need to be read by small part to determin size. Buffer
317  * size is determined in function of the biggest part to read.
318  *
319  * The parser only requires 4 bytes.
320  */
321 #define SOCKS5_CONN_REP_LEN       255
322 static gboolean
323 parse_connect_reply (const guint8 *data, gint *atype, GError **error)
324 {
325   if (data[0] != SOCKS5_VERSION)
326     {
327       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
328                            _("The server is not a SOCKSv5 proxy server."));
329       return FALSE;
330     }
331
332   switch (data[1])
333     {
334       case SOCKS5_REP_SUCCEEDED:
335         if (data[2] != SOCKS5_RESERVED)
336           {
337             g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
338                            _("The server is not a SOCKSv5 proxy server."));
339             return FALSE;
340           }
341
342         switch (data[3])
343           {
344           case SOCKS5_ATYP_IPV4:
345           case SOCKS5_ATYP_IPV6:
346           case SOCKS5_ATYP_DOMAINNAME:
347             *atype = data[3];
348             break;
349
350           default:
351             g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
352                            _("The SOCKSv5 proxy server uses unkown address type."));
353             return FALSE;
354           }
355         break;
356
357       case SOCKS5_REP_SRV_FAILURE:
358         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
359                              _("Internal SOCKSv5 proxy server error."));
360         return FALSE;
361         break;
362
363       case SOCKS5_REP_NOT_ALLOWED:
364         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_NOT_ALLOWED,
365                              _("SOCKSv5 connection not allowed by ruleset."));
366         return FALSE;
367         break;
368
369       case SOCKS5_REP_TTL_EXPIRED:
370       case SOCKS5_REP_HOST_UNREACH:
371         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_HOST_UNREACHABLE,
372                              _("Host unreachable through SOCKSv5 server."));
373         return FALSE;
374         break;
375
376       case SOCKS5_REP_NET_UNREACH:
377         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NETWORK_UNREACHABLE,
378                              _("Network unreachable through SOCKSv5 proxy."));
379         return FALSE;
380         break;
381
382       case SOCKS5_REP_REFUSED:
383         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CONNECTION_REFUSED,
384                              _("Connection refused through SOCKSv5 proxy."));
385         return FALSE;
386         break;
387
388       case SOCKS5_REP_CMD_NOT_SUP:
389         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
390                              _("SOCKSv5 proxy does not support 'connect' command."));
391         return FALSE;
392         break;
393
394       case SOCKS5_REP_ATYPE_NOT_SUP:
395         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
396                              _("SOCKSv5 proxy does not support provided address type."));
397         return FALSE;
398         break;
399
400       default: /* Unknown error */
401         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
402                              _("Unkown SOCKSv5 proxy error."));
403         return FALSE;
404         break;
405     }
406
407   return TRUE;
408 }
409
410 static GIOStream *
411 g_socks5_proxy_connect (GProxy            *proxy,
412                         GIOStream         *io_stream,
413                         GProxyAddress     *proxy_address,
414                         GCancellable      *cancellable,
415                         GError          **error)
416 {
417   gboolean has_auth;
418   GInputStream *in;
419   GOutputStream *out;
420   const gchar *hostname;
421   guint16 port;
422   const gchar *username;
423   const gchar *password;
424
425   hostname = g_proxy_address_get_destination_hostname (proxy_address);
426   port = g_proxy_address_get_destination_port (proxy_address);
427   username = g_proxy_address_get_username (proxy_address);
428   password = g_proxy_address_get_password (proxy_address);
429
430   has_auth = username || password;
431   
432   in = g_io_stream_get_input_stream (io_stream);
433   out = g_io_stream_get_output_stream (io_stream);
434
435   /* Send SOCKS5 handshake */
436     {
437       guint8 msg[SOCKS5_NEGO_MSG_LEN];
438       gint len;
439
440       len = set_nego_msg (msg, has_auth);
441
442       if (!g_output_stream_write_all (out, msg, len, NULL,
443                                       cancellable, error))
444         goto error;
445     }
446
447   /* Recieve SOCKS5 response and reply with authentication if required */
448     {
449       guint8 data[SOCKS5_NEGO_REP_LEN];
450       gboolean must_auth = FALSE;
451
452       if (!g_input_stream_read_all (in, data, sizeof (data), NULL,
453                                     cancellable, error))
454         goto error;
455
456       if (!parse_nego_reply (data, has_auth, &must_auth, error))
457           goto error;
458
459       if (must_auth)
460         {
461           guint8 msg[SOCKS5_AUTH_MSG_LEN];
462           gint len;
463
464           len = set_auth_msg (msg, username, password, error);
465
466           if (len < 0)
467             goto error;
468           
469           if (!g_output_stream_write_all (out, msg, len, NULL,
470                                           cancellable, error))
471             goto error;
472
473           if (!g_input_stream_read_all (in, data, sizeof (data), NULL,
474                                         cancellable, error))
475             goto error;
476
477           if (!check_auth_status (data, error))
478             goto error;
479         }
480     }
481
482   /* Send SOCKS5 connection request */
483     {
484       guint8 msg[SOCKS5_CONN_MSG_LEN];
485       gint len;
486       
487       len = set_connect_msg (msg, hostname, port, error);
488
489       if (len < 0)
490         goto error;
491
492       if (!g_output_stream_write_all (out, msg, len, NULL,
493                                       cancellable, error))
494         goto error;
495     }
496
497   /* Read SOCKS5 response */
498     {
499       guint8 data[SOCKS5_CONN_REP_LEN];
500       gint atype;
501
502       if (!g_input_stream_read_all (in, data, 4, NULL,
503                                     cancellable, error))
504         goto error;
505
506       if (!parse_connect_reply (data, &atype, error))
507         goto error;
508
509       switch (atype)
510         {
511           case SOCKS5_ATYP_IPV4:
512             if (!g_input_stream_read_all (in, data, 6, NULL,
513                                           cancellable, error))
514               goto error;
515             break;
516
517           case SOCKS5_ATYP_IPV6:
518             if (!g_input_stream_read_all (in, data, 18, NULL,
519                                           cancellable, error))
520               goto error;
521             break;
522
523           case SOCKS5_ATYP_DOMAINNAME:
524             if (!g_input_stream_read_all (in, data, 1, NULL,
525                                           cancellable, error))
526               goto error;
527             if (!g_input_stream_read_all (in, data, data[0] + 2, NULL,
528                                           cancellable, error))
529               goto error;
530             break;
531         }
532     }
533
534   return g_object_ref (io_stream);
535
536 error:
537   return NULL;
538 }
539
540
541 typedef struct
542 {
543   GSimpleAsyncResult *simple;
544   GIOStream *io_stream;
545   gchar *hostname;
546   guint16 port;
547   gchar *username;
548   gchar *password;
549   guint8 *buffer;
550   gssize length;
551   gssize offset;
552   GCancellable *cancellable;
553 } ConnectAsyncData;
554
555 static void nego_msg_write_cb         (GObject          *source,
556                                        GAsyncResult     *res,
557                                        gpointer          user_data);
558 static void nego_reply_read_cb        (GObject          *source,
559                                        GAsyncResult     *res,
560                                        gpointer          user_data);
561 static void auth_msg_write_cb         (GObject          *source,
562                                        GAsyncResult     *res,
563                                        gpointer          user_data);
564 static void auth_reply_read_cb        (GObject          *source,
565                                        GAsyncResult     *result,
566                                        gpointer          user_data);
567 static void send_connect_msg          (ConnectAsyncData *data);
568 static void connect_msg_write_cb      (GObject          *source,
569                                        GAsyncResult     *result,
570                                        gpointer          user_data);
571 static void connect_reply_read_cb     (GObject          *source,
572                                        GAsyncResult     *result,
573                                        gpointer          user_data);
574 static void connect_addr_len_read_cb  (GObject          *source,
575                                        GAsyncResult     *result,
576                                        gpointer          user_data);
577 static void connect_addr_read_cb      (GObject          *source,
578                                        GAsyncResult     *result,
579                                        gpointer          user_data);
580
581 static void
582 free_connect_data (ConnectAsyncData *data)
583 {
584   if (data->io_stream)
585     g_object_unref (data->io_stream);
586
587   g_free (data->hostname);
588   g_free (data->username);
589   g_free (data->password);
590   
591   if (data->cancellable)
592     g_object_unref (data->cancellable);
593
594   g_slice_free (ConnectAsyncData, data);
595 }
596
597 static void
598 complete_async_from_error (ConnectAsyncData *data, GError *error)
599 {
600   GSimpleAsyncResult *simple = data->simple;
601   g_simple_async_result_set_from_error (data->simple,
602                                         error);
603   g_error_free (error);
604   g_simple_async_result_set_op_res_gpointer (simple, NULL, NULL);
605   g_simple_async_result_complete (simple);
606   g_object_unref (simple);
607 }
608
609 static void
610 do_read (GAsyncReadyCallback callback, ConnectAsyncData *data)
611 {
612    GInputStream *in;
613    in = g_io_stream_get_input_stream (data->io_stream);
614    g_input_stream_read_async (in,
615                               data->buffer + data->offset,
616                               data->length - data->offset,
617                               G_PRIORITY_DEFAULT, data->cancellable,
618                               callback, data);
619 }
620
621 static void
622 do_write (GAsyncReadyCallback callback, ConnectAsyncData *data)
623 {
624   GOutputStream *out;
625   out = g_io_stream_get_output_stream (data->io_stream);
626   g_output_stream_write_async (out,
627                                data->buffer + data->offset,
628                                data->length - data->offset,
629                                G_PRIORITY_DEFAULT, data->cancellable,
630                                callback, data);
631 }
632
633 static void
634 g_socks5_proxy_connect_async (GProxy               *proxy,
635                               GIOStream            *io_stream,
636                               GProxyAddress        *proxy_address,
637                               GCancellable         *cancellable,
638                               GAsyncReadyCallback   callback,
639                               gpointer              user_data)
640 {
641   GSimpleAsyncResult *simple;
642   ConnectAsyncData *data;
643
644   simple = g_simple_async_result_new (G_OBJECT (proxy),
645                                       callback, user_data,
646                                       g_socks5_proxy_connect_async);
647
648   data = g_slice_new0 (ConnectAsyncData);
649
650   data->simple = simple;
651   data->io_stream = g_object_ref (io_stream);
652
653   if (cancellable)
654     data->cancellable = g_object_ref (cancellable);
655
656   g_object_get (G_OBJECT (proxy_address),
657                 "destination-hostname", &data->hostname,
658                 "destination-port", &data->port,
659                 "username", &data->username,
660                 "password", &data->password,
661                 NULL);
662
663   g_simple_async_result_set_op_res_gpointer (simple, data, 
664                                              (GDestroyNotify) free_connect_data);
665
666   data->buffer = g_malloc0 (SOCKS5_NEGO_MSG_LEN);
667   data->length = set_nego_msg (data->buffer,
668                                data->username || data->password);
669   data->offset = 0;
670
671   do_write (nego_msg_write_cb, data);
672 }
673
674
675 static void
676 nego_msg_write_cb (GObject      *source,
677                    GAsyncResult *res,
678                    gpointer      user_data)
679 {
680   GError *error = NULL;
681   ConnectAsyncData *data = user_data;
682   gssize written;
683
684   written = g_output_stream_write_finish (G_OUTPUT_STREAM (source),
685                                           res, &error);
686
687   if (written < 0)
688     {
689       complete_async_from_error (data, error);
690       return;
691     }
692
693   data->offset += written;
694
695   if (data->offset == data->length)
696     {
697       g_free (data->buffer);
698
699       data->buffer = g_malloc0 (SOCKS5_NEGO_REP_LEN);
700       data->length = SOCKS5_NEGO_REP_LEN;
701       data->offset = 0;
702
703       do_read (nego_reply_read_cb, data);
704     }
705   else
706     {
707       do_write (nego_msg_write_cb, data);
708     }
709 }
710
711 static void
712 nego_reply_read_cb (GObject      *source,
713                     GAsyncResult *res,
714                     gpointer      user_data)
715 {
716   GError *error = NULL;
717   ConnectAsyncData *data = user_data;
718   gssize read;
719
720   read = g_input_stream_read_finish (G_INPUT_STREAM (source),
721                                      res, &error);
722
723   if (read < 0)
724     {
725       complete_async_from_error (data, error);
726       return;
727     }
728
729   data->offset += read;
730   
731   if (data->offset == data->length)
732     {
733       GError *error;
734       gboolean must_auth = FALSE;
735       gboolean has_auth = data->username || data->password;
736
737       if (!parse_nego_reply (data->buffer, has_auth, &must_auth, &error))
738         {
739           complete_async_from_error (data, error);
740           return;
741         }
742
743       if (must_auth)
744         {
745           g_free (data->buffer);
746
747           data->buffer = g_malloc0 (SOCKS5_AUTH_MSG_LEN);
748           data->length = set_auth_msg (data->buffer,
749                                        data->username,
750                                        data->password,
751                                        &error);
752           data->offset = 0;
753
754           if (data->length < 0)
755             {
756               complete_async_from_error (data, error);
757               return;
758             }
759           
760           do_write (auth_msg_write_cb, data);
761         }
762       else
763         {
764           send_connect_msg (data);
765         }
766     }
767   else
768     {
769       do_read (nego_reply_read_cb, data);
770     }
771 }
772
773 static void
774 auth_msg_write_cb (GObject      *source,
775                    GAsyncResult *result,
776                    gpointer      user_data)
777 {
778   GError *error = NULL;
779   ConnectAsyncData *data = user_data;
780   gssize written;
781
782   written = g_output_stream_write_finish (G_OUTPUT_STREAM (source),
783                                           result, &error);
784   
785   if (written < 0)
786     {
787       complete_async_from_error (data, error);
788       return;
789     }
790
791   data->offset += written;
792
793   if (data->offset == data->length)
794     {
795       g_free (data->buffer);
796
797       data->buffer = g_malloc0 (SOCKS5_NEGO_REP_LEN);
798       data->length = SOCKS5_NEGO_REP_LEN;
799       data->offset = 0;
800
801       do_read (auth_reply_read_cb, data);
802     }
803   else
804     {
805       do_write (auth_msg_write_cb, data);
806     }
807 }
808
809 static void
810 auth_reply_read_cb (GObject      *source,
811                     GAsyncResult *result,
812                     gpointer      user_data)
813 {
814   GError *error = NULL;
815   ConnectAsyncData *data = user_data;
816   gssize read;
817
818   read = g_input_stream_read_finish (G_INPUT_STREAM (source),
819                                      result, &error);
820
821   if (read < 0)
822     {
823       complete_async_from_error (data, error);
824       return;
825     }
826
827   data->offset += read;
828
829   if (data->offset == data->length)
830     {
831       if (!check_auth_status (data->buffer, &error))
832         {
833           complete_async_from_error (data, error);
834           return;
835         }
836         
837       send_connect_msg (data);
838     }
839   else
840     {
841       do_read (auth_reply_read_cb, data);
842     }
843 }
844
845 static void
846 send_connect_msg (ConnectAsyncData *data)
847 {
848   GError *error = NULL;
849
850   g_free (data->buffer);
851
852   data->buffer = g_malloc0 (SOCKS5_CONN_MSG_LEN);
853   data->length = set_connect_msg (data->buffer,
854                                   data->hostname,
855                                   data->port,
856                                   &error);
857   data->offset = 0;
858   
859   if (data->length < 0)
860     {
861       complete_async_from_error (data, error);
862       return;
863     }
864
865   do_write (connect_msg_write_cb, data);
866 }
867
868 static void
869 connect_msg_write_cb (GObject      *source,
870                       GAsyncResult *result,
871                       gpointer      user_data)
872 {
873   GError *error = NULL;
874   ConnectAsyncData *data = user_data;
875   gssize written;
876
877   written = g_output_stream_write_finish (G_OUTPUT_STREAM (source),
878                                           result, &error);
879   
880   if (written < 0)
881     {
882       complete_async_from_error (data, error);
883       return;
884     }
885
886   data->offset += written;
887
888   if (data->offset == data->length)
889     {
890       g_free (data->buffer);
891
892       data->buffer = g_malloc0 (SOCKS5_CONN_REP_LEN);
893       data->length = 4;
894       data->offset = 0;
895
896       do_read (connect_reply_read_cb, data);
897     }
898   else
899     {
900       do_write (connect_msg_write_cb, data);
901     }
902 }
903
904 static void
905 connect_reply_read_cb (GObject       *source,
906                        GAsyncResult  *result,
907                        gpointer       user_data)
908 {
909   GError *error = NULL;
910   ConnectAsyncData *data = user_data;
911   gssize read;
912
913   read = g_input_stream_read_finish (G_INPUT_STREAM (source),
914                                      result, &error);
915
916   if (read < 0)
917     {
918       complete_async_from_error (data, error);
919       return;
920     }
921
922   data->offset += read;
923
924   if (data->offset == data->length)
925     {
926       gint atype;
927
928       if (!parse_connect_reply (data->buffer, &atype, &error))
929         {
930           complete_async_from_error (data, error);
931           return;
932         }
933
934       switch (atype)
935         {
936           case SOCKS5_ATYP_IPV4:
937             data->length = 6;
938             data->offset = 0;
939             do_read (connect_addr_read_cb, data);
940             break;
941
942           case SOCKS5_ATYP_IPV6:
943             data->length = 18;
944             data->offset = 0;
945             do_read (connect_addr_read_cb, data);
946             break;
947
948           case SOCKS5_ATYP_DOMAINNAME:
949             data->length = 1;
950             data->offset = 0;
951             do_read (connect_addr_len_read_cb, data);
952             break;
953         }
954     }
955   else
956     {
957       do_read (connect_reply_read_cb, data);
958     }
959 }
960
961 static void
962 connect_addr_len_read_cb (GObject      *source,
963                           GAsyncResult *result,
964                           gpointer      user_data)
965 {
966   GError *error = NULL;
967   ConnectAsyncData *data = user_data;
968   gssize read;
969
970   read = g_input_stream_read_finish (G_INPUT_STREAM (source),
971                                      result, &error);
972
973   if (read < 0)
974     {
975       complete_async_from_error (data, error);
976       return;
977     }
978
979   data->length = data->buffer[0] + 2;
980   data->offset = 0;
981
982   do_read (connect_addr_read_cb, data);
983 }
984
985 static void
986 connect_addr_read_cb (GObject      *source,
987                       GAsyncResult *result,
988                       gpointer      user_data)
989 {
990   GError *error = NULL;
991   ConnectAsyncData *data = user_data;
992   gssize read;
993
994   read = g_input_stream_read_finish (G_INPUT_STREAM (source),
995                                      result, &error);
996
997   if (read < 0)
998     {
999       complete_async_from_error (data, error);
1000       return;
1001     }
1002
1003   data->offset += read;
1004
1005   if (data->offset == data->length)
1006     {
1007       GSimpleAsyncResult *simple = data->simple;
1008       g_simple_async_result_complete (simple);
1009       g_object_unref (simple);
1010     }
1011   else
1012     {
1013       do_read (connect_reply_read_cb, data);
1014     }
1015 }
1016
1017 static GIOStream *
1018 g_socks5_proxy_connect_finish (GProxy       *proxy,
1019                                GAsyncResult *result,
1020                                GError      **error)
1021 {
1022   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
1023   ConnectAsyncData *data = g_simple_async_result_get_op_res_gpointer (simple);
1024
1025   if (g_simple_async_result_propagate_error (simple, error))
1026     return NULL;
1027
1028   return g_object_ref (data->io_stream);
1029 }
1030
1031 static gboolean
1032 g_socks5_proxy_supports_hostname (GProxy *proxy)
1033 {
1034   return TRUE;
1035 }
1036
1037 static void
1038 g_socks5_proxy_class_init (GSocks5ProxyClass *class)
1039 {
1040   GObjectClass *object_class;
1041
1042   object_class = (GObjectClass *) class;
1043   object_class->finalize = g_socks5_proxy_finalize;
1044 }
1045
1046 static void
1047 g_socks5_proxy_iface_init (GProxyInterface *proxy_iface)
1048 {
1049   proxy_iface->connect  = g_socks5_proxy_connect;
1050   proxy_iface->connect_async = g_socks5_proxy_connect_async;
1051   proxy_iface->connect_finish = g_socks5_proxy_connect_finish;
1052   proxy_iface->supports_hostname = g_socks5_proxy_supports_hostname;
1053 }