Tizen 2.1 base
[platform/upstream/glib2.0.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 proxy requires 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_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
208                            _("Username or password is too long for SOCKSv5 "
209                              "protocol."));
210       return FALSE;
211     }
212
213   msg[len++] = SOCKS5_AUTH_VERSION;
214   msg[len++] = ulen;
215
216   if (ulen > 0)
217     memcpy (msg + len, username, ulen);
218
219   len += ulen;
220   msg[len++] = plen;
221
222   if (plen > 0)
223     memcpy (msg + len, password, plen);
224
225   len += plen;
226
227   return len;
228 }
229
230
231 static gboolean
232 check_auth_status (const guint8 *data, GError **error)
233 {
234   if (data[0] != SOCKS5_VERSION
235       || data[1] != SOCKS5_REP_SUCCEEDED)
236     {
237       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_AUTH_FAILED,
238                            _("SOCKSv5 authentication failed due to wrong "
239                              "username or password."));
240       return FALSE;
241     }
242   return TRUE;
243 }
244
245 /*
246  * +----+-----+-------+------+----------+----------+
247  * |VER | CMD |  RSV  | ATYP | DST.ADDR | DST.PORT |
248  * +----+-----+-------+------+----------+----------+
249  * | 1  |  1  | X'00' |  1   | Variable |    2     |
250  * +----+-----+-------+------+----------+----------+
251  * DST.ADDR is a string with first byte being the size. So DST.ADDR may not be
252  * longer then 256 bytes.
253  */
254 #define SOCKS5_CONN_MSG_LEN       262
255 static gint
256 set_connect_msg (guint8       *msg,
257                  const gchar *hostname,
258                  guint16      port,
259                  GError     **error)
260 {
261   guint len = 0;
262
263   msg[len++] = SOCKS5_VERSION;
264   msg[len++] = SOCKS5_CMD_CONNECT;
265   msg[len++] = SOCKS5_RESERVED;
266
267   if (g_hostname_is_ip_address (hostname))
268     {
269       GInetAddress *addr = g_inet_address_new_from_string (hostname);
270       gsize addr_len = g_inet_address_get_native_size (addr);
271
272       /* We are cheating for simplicity, here's the logic:
273        *   1 = IPV4 = 4 bytes / 4
274        *   4 = IPV6 = 16 bytes / 4 */
275       msg[len++] = addr_len / 4;
276       memcpy (msg + len, g_inet_address_to_bytes (addr), addr_len);
277       len += addr_len;
278
279       g_object_unref (addr);
280     }
281   else
282     {
283       gsize host_len = strlen (hostname);
284
285       if (host_len > SOCKS5_MAX_LEN)
286         {
287           g_set_error (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
288                        _("Hostname '%s' is too long for SOCKSv5 protocol"),
289                        hostname);
290           return -1;
291         }
292
293       msg[len++] = SOCKS5_ATYP_DOMAINNAME;
294       msg[len++] = (guint8) host_len;
295       memcpy (msg + len, hostname, host_len);
296       len += host_len;
297     }
298
299     {
300       guint16 hp = g_htons (port);
301       memcpy (msg + len, &hp, 2);
302       len += 2;
303     }
304
305   return len;
306 }
307
308 /*
309  * +----+-----+-------+------+----------+----------+
310  * |VER | REP |  RSV  | ATYP | BND.ADDR | BND.PORT |
311  * +----+-----+-------+------+----------+----------+
312  * | 1  |  1  | X'00' |  1   | Variable |    2     |
313  * +----+-----+-------+------+----------+----------+
314  * This reply need to be read by small part to determin size. Buffer
315  * size is determined in function of the biggest part to read.
316  *
317  * The parser only requires 4 bytes.
318  */
319 #define SOCKS5_CONN_REP_LEN       255
320 static gboolean
321 parse_connect_reply (const guint8 *data, gint *atype, GError **error)
322 {
323   if (data[0] != SOCKS5_VERSION)
324     {
325       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
326                            _("The server is not a SOCKSv5 proxy server."));
327       return FALSE;
328     }
329
330   switch (data[1])
331     {
332       case SOCKS5_REP_SUCCEEDED:
333         if (data[2] != SOCKS5_RESERVED)
334           {
335             g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
336                            _("The server is not a SOCKSv5 proxy server."));
337             return FALSE;
338           }
339
340         switch (data[3])
341           {
342           case SOCKS5_ATYP_IPV4:
343           case SOCKS5_ATYP_IPV6:
344           case SOCKS5_ATYP_DOMAINNAME:
345             *atype = data[3];
346             break;
347
348           default:
349             g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
350                            _("The SOCKSv5 proxy server uses unknown address type."));
351             return FALSE;
352           }
353         break;
354
355       case SOCKS5_REP_SRV_FAILURE:
356         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
357                              _("Internal SOCKSv5 proxy server error."));
358         return FALSE;
359         break;
360
361       case SOCKS5_REP_NOT_ALLOWED:
362         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_NOT_ALLOWED,
363                              _("SOCKSv5 connection not allowed by ruleset."));
364         return FALSE;
365         break;
366
367       case SOCKS5_REP_TTL_EXPIRED:
368       case SOCKS5_REP_HOST_UNREACH:
369         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_HOST_UNREACHABLE,
370                              _("Host unreachable through SOCKSv5 server."));
371         return FALSE;
372         break;
373
374       case SOCKS5_REP_NET_UNREACH:
375         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NETWORK_UNREACHABLE,
376                              _("Network unreachable through SOCKSv5 proxy."));
377         return FALSE;
378         break;
379
380       case SOCKS5_REP_REFUSED:
381         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CONNECTION_REFUSED,
382                              _("Connection refused through SOCKSv5 proxy."));
383         return FALSE;
384         break;
385
386       case SOCKS5_REP_CMD_NOT_SUP:
387         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
388                              _("SOCKSv5 proxy does not support 'connect' command."));
389         return FALSE;
390         break;
391
392       case SOCKS5_REP_ATYPE_NOT_SUP:
393         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
394                              _("SOCKSv5 proxy does not support provided address type."));
395         return FALSE;
396         break;
397
398       default: /* Unknown error */
399         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
400                              _("Unknown SOCKSv5 proxy error."));
401         return FALSE;
402         break;
403     }
404
405   return TRUE;
406 }
407
408 static GIOStream *
409 g_socks5_proxy_connect (GProxy            *proxy,
410                         GIOStream         *io_stream,
411                         GProxyAddress     *proxy_address,
412                         GCancellable      *cancellable,
413                         GError          **error)
414 {
415   gboolean has_auth;
416   GInputStream *in;
417   GOutputStream *out;
418   const gchar *hostname;
419   guint16 port;
420   const gchar *username;
421   const gchar *password;
422
423   hostname = g_proxy_address_get_destination_hostname (proxy_address);
424   port = g_proxy_address_get_destination_port (proxy_address);
425   username = g_proxy_address_get_username (proxy_address);
426   password = g_proxy_address_get_password (proxy_address);
427
428   has_auth = username || password;
429   
430   in = g_io_stream_get_input_stream (io_stream);
431   out = g_io_stream_get_output_stream (io_stream);
432
433   /* Send SOCKS5 handshake */
434     {
435       guint8 msg[SOCKS5_NEGO_MSG_LEN];
436       gint len;
437
438       len = set_nego_msg (msg, has_auth);
439
440       if (!g_output_stream_write_all (out, msg, len, NULL,
441                                       cancellable, error))
442         goto error;
443     }
444
445   /* Receive SOCKS5 response and reply with authentication if required */
446     {
447       guint8 data[SOCKS5_NEGO_REP_LEN];
448       gboolean must_auth = FALSE;
449
450       if (!g_input_stream_read_all (in, data, sizeof (data), NULL,
451                                     cancellable, error))
452         goto error;
453
454       if (!parse_nego_reply (data, has_auth, &must_auth, error))
455           goto error;
456
457       if (must_auth)
458         {
459           guint8 msg[SOCKS5_AUTH_MSG_LEN];
460           gint len;
461
462           len = set_auth_msg (msg, username, password, error);
463
464           if (len < 0)
465             goto error;
466           
467           if (!g_output_stream_write_all (out, msg, len, NULL,
468                                           cancellable, error))
469             goto error;
470
471           if (!g_input_stream_read_all (in, data, sizeof (data), NULL,
472                                         cancellable, error))
473             goto error;
474
475           if (!check_auth_status (data, error))
476             goto error;
477         }
478     }
479
480   /* Send SOCKS5 connection request */
481     {
482       guint8 msg[SOCKS5_CONN_MSG_LEN];
483       gint len;
484       
485       len = set_connect_msg (msg, hostname, port, error);
486
487       if (len < 0)
488         goto error;
489
490       if (!g_output_stream_write_all (out, msg, len, NULL,
491                                       cancellable, error))
492         goto error;
493     }
494
495   /* Read SOCKS5 response */
496     {
497       guint8 data[SOCKS5_CONN_REP_LEN];
498       gint atype;
499
500       if (!g_input_stream_read_all (in, data, 4, NULL,
501                                     cancellable, error))
502         goto error;
503
504       if (!parse_connect_reply (data, &atype, error))
505         goto error;
506
507       switch (atype)
508         {
509           case SOCKS5_ATYP_IPV4:
510             if (!g_input_stream_read_all (in, data, 6, NULL,
511                                           cancellable, error))
512               goto error;
513             break;
514
515           case SOCKS5_ATYP_IPV6:
516             if (!g_input_stream_read_all (in, data, 18, NULL,
517                                           cancellable, error))
518               goto error;
519             break;
520
521           case SOCKS5_ATYP_DOMAINNAME:
522             if (!g_input_stream_read_all (in, data, 1, NULL,
523                                           cancellable, error))
524               goto error;
525             if (!g_input_stream_read_all (in, data, data[0] + 2, NULL,
526                                           cancellable, error))
527               goto error;
528             break;
529         }
530     }
531
532   return g_object_ref (io_stream);
533
534 error:
535   return NULL;
536 }
537
538
539 typedef struct
540 {
541   GSimpleAsyncResult *simple;
542   GIOStream *io_stream;
543   gchar *hostname;
544   guint16 port;
545   gchar *username;
546   gchar *password;
547   guint8 *buffer;
548   gssize length;
549   gssize offset;
550   GCancellable *cancellable;
551 } ConnectAsyncData;
552
553 static void nego_msg_write_cb         (GObject          *source,
554                                        GAsyncResult     *res,
555                                        gpointer          user_data);
556 static void nego_reply_read_cb        (GObject          *source,
557                                        GAsyncResult     *res,
558                                        gpointer          user_data);
559 static void auth_msg_write_cb         (GObject          *source,
560                                        GAsyncResult     *res,
561                                        gpointer          user_data);
562 static void auth_reply_read_cb        (GObject          *source,
563                                        GAsyncResult     *result,
564                                        gpointer          user_data);
565 static void send_connect_msg          (ConnectAsyncData *data);
566 static void connect_msg_write_cb      (GObject          *source,
567                                        GAsyncResult     *result,
568                                        gpointer          user_data);
569 static void connect_reply_read_cb     (GObject          *source,
570                                        GAsyncResult     *result,
571                                        gpointer          user_data);
572 static void connect_addr_len_read_cb  (GObject          *source,
573                                        GAsyncResult     *result,
574                                        gpointer          user_data);
575 static void connect_addr_read_cb      (GObject          *source,
576                                        GAsyncResult     *result,
577                                        gpointer          user_data);
578
579 static void
580 free_connect_data (ConnectAsyncData *data)
581 {
582   if (data->io_stream)
583     g_object_unref (data->io_stream);
584
585   g_free (data->hostname);
586   g_free (data->username);
587   g_free (data->password);
588   g_free (data->buffer);
589   
590   if (data->cancellable)
591     g_object_unref (data->cancellable);
592
593   g_slice_free (ConnectAsyncData, data);
594 }
595
596 static void
597 complete_async_from_error (ConnectAsyncData *data, GError *error)
598 {
599   GSimpleAsyncResult *simple = data->simple;
600   g_simple_async_result_take_error (data->simple, error);
601   g_simple_async_result_set_op_res_gpointer (simple, NULL, NULL);
602   g_simple_async_result_complete (simple);
603   g_object_unref (simple);
604 }
605
606 static void
607 do_read (GAsyncReadyCallback callback, ConnectAsyncData *data)
608 {
609    GInputStream *in;
610    in = g_io_stream_get_input_stream (data->io_stream);
611    g_input_stream_read_async (in,
612                               data->buffer + data->offset,
613                               data->length - data->offset,
614                               G_PRIORITY_DEFAULT, data->cancellable,
615                               callback, data);
616 }
617
618 static void
619 do_write (GAsyncReadyCallback callback, ConnectAsyncData *data)
620 {
621   GOutputStream *out;
622   out = g_io_stream_get_output_stream (data->io_stream);
623   g_output_stream_write_async (out,
624                                data->buffer + data->offset,
625                                data->length - data->offset,
626                                G_PRIORITY_DEFAULT, data->cancellable,
627                                callback, data);
628 }
629
630 static void
631 g_socks5_proxy_connect_async (GProxy               *proxy,
632                               GIOStream            *io_stream,
633                               GProxyAddress        *proxy_address,
634                               GCancellable         *cancellable,
635                               GAsyncReadyCallback   callback,
636                               gpointer              user_data)
637 {
638   GSimpleAsyncResult *simple;
639   ConnectAsyncData *data;
640
641   simple = g_simple_async_result_new (G_OBJECT (proxy),
642                                       callback, user_data,
643                                       g_socks5_proxy_connect_async);
644
645   data = g_slice_new0 (ConnectAsyncData);
646
647   data->simple = simple;
648   data->io_stream = g_object_ref (io_stream);
649
650   if (cancellable)
651     data->cancellable = g_object_ref (cancellable);
652
653   g_object_get (G_OBJECT (proxy_address),
654                 "destination-hostname", &data->hostname,
655                 "destination-port", &data->port,
656                 "username", &data->username,
657                 "password", &data->password,
658                 NULL);
659
660   g_simple_async_result_set_op_res_gpointer (simple, data, 
661                                              (GDestroyNotify) free_connect_data);
662
663   data->buffer = g_malloc0 (SOCKS5_NEGO_MSG_LEN);
664   data->length = set_nego_msg (data->buffer,
665                                data->username || data->password);
666   data->offset = 0;
667
668   do_write (nego_msg_write_cb, data);
669 }
670
671
672 static void
673 nego_msg_write_cb (GObject      *source,
674                    GAsyncResult *res,
675                    gpointer      user_data)
676 {
677   GError *error = NULL;
678   ConnectAsyncData *data = user_data;
679   gssize written;
680
681   written = g_output_stream_write_finish (G_OUTPUT_STREAM (source),
682                                           res, &error);
683
684   if (written < 0)
685     {
686       complete_async_from_error (data, error);
687       return;
688     }
689
690   data->offset += written;
691
692   if (data->offset == data->length)
693     {
694       g_free (data->buffer);
695
696       data->buffer = g_malloc0 (SOCKS5_NEGO_REP_LEN);
697       data->length = SOCKS5_NEGO_REP_LEN;
698       data->offset = 0;
699
700       do_read (nego_reply_read_cb, data);
701     }
702   else
703     {
704       do_write (nego_msg_write_cb, data);
705     }
706 }
707
708 static void
709 nego_reply_read_cb (GObject      *source,
710                     GAsyncResult *res,
711                     gpointer      user_data)
712 {
713   GError *error = NULL;
714   ConnectAsyncData *data = user_data;
715   gssize read;
716
717   read = g_input_stream_read_finish (G_INPUT_STREAM (source),
718                                      res, &error);
719
720   if (read < 0)
721     {
722       complete_async_from_error (data, error);
723       return;
724     }
725
726   data->offset += read;
727   
728   if (data->offset == data->length)
729     {
730       GError *error;
731       gboolean must_auth = FALSE;
732       gboolean has_auth = data->username || data->password;
733
734       if (!parse_nego_reply (data->buffer, has_auth, &must_auth, &error))
735         {
736           complete_async_from_error (data, error);
737           return;
738         }
739
740       if (must_auth)
741         {
742           g_free (data->buffer);
743
744           data->buffer = g_malloc0 (SOCKS5_AUTH_MSG_LEN);
745           data->length = set_auth_msg (data->buffer,
746                                        data->username,
747                                        data->password,
748                                        &error);
749           data->offset = 0;
750
751           if (data->length < 0)
752             {
753               complete_async_from_error (data, error);
754               return;
755             }
756           
757           do_write (auth_msg_write_cb, data);
758         }
759       else
760         {
761           send_connect_msg (data);
762         }
763     }
764   else
765     {
766       do_read (nego_reply_read_cb, data);
767     }
768 }
769
770 static void
771 auth_msg_write_cb (GObject      *source,
772                    GAsyncResult *result,
773                    gpointer      user_data)
774 {
775   GError *error = NULL;
776   ConnectAsyncData *data = user_data;
777   gssize written;
778
779   written = g_output_stream_write_finish (G_OUTPUT_STREAM (source),
780                                           result, &error);
781   
782   if (written < 0)
783     {
784       complete_async_from_error (data, error);
785       return;
786     }
787
788   data->offset += written;
789
790   if (data->offset == data->length)
791     {
792       g_free (data->buffer);
793
794       data->buffer = g_malloc0 (SOCKS5_NEGO_REP_LEN);
795       data->length = SOCKS5_NEGO_REP_LEN;
796       data->offset = 0;
797
798       do_read (auth_reply_read_cb, data);
799     }
800   else
801     {
802       do_write (auth_msg_write_cb, data);
803     }
804 }
805
806 static void
807 auth_reply_read_cb (GObject      *source,
808                     GAsyncResult *result,
809                     gpointer      user_data)
810 {
811   GError *error = NULL;
812   ConnectAsyncData *data = user_data;
813   gssize read;
814
815   read = g_input_stream_read_finish (G_INPUT_STREAM (source),
816                                      result, &error);
817
818   if (read < 0)
819     {
820       complete_async_from_error (data, error);
821       return;
822     }
823
824   data->offset += read;
825
826   if (data->offset == data->length)
827     {
828       if (!check_auth_status (data->buffer, &error))
829         {
830           complete_async_from_error (data, error);
831           return;
832         }
833         
834       send_connect_msg (data);
835     }
836   else
837     {
838       do_read (auth_reply_read_cb, data);
839     }
840 }
841
842 static void
843 send_connect_msg (ConnectAsyncData *data)
844 {
845   GError *error = NULL;
846
847   g_free (data->buffer);
848
849   data->buffer = g_malloc0 (SOCKS5_CONN_MSG_LEN);
850   data->length = set_connect_msg (data->buffer,
851                                   data->hostname,
852                                   data->port,
853                                   &error);
854   data->offset = 0;
855   
856   if (data->length < 0)
857     {
858       complete_async_from_error (data, error);
859       return;
860     }
861
862   do_write (connect_msg_write_cb, data);
863 }
864
865 static void
866 connect_msg_write_cb (GObject      *source,
867                       GAsyncResult *result,
868                       gpointer      user_data)
869 {
870   GError *error = NULL;
871   ConnectAsyncData *data = user_data;
872   gssize written;
873
874   written = g_output_stream_write_finish (G_OUTPUT_STREAM (source),
875                                           result, &error);
876   
877   if (written < 0)
878     {
879       complete_async_from_error (data, error);
880       return;
881     }
882
883   data->offset += written;
884
885   if (data->offset == data->length)
886     {
887       g_free (data->buffer);
888
889       data->buffer = g_malloc0 (SOCKS5_CONN_REP_LEN);
890       data->length = 4;
891       data->offset = 0;
892
893       do_read (connect_reply_read_cb, data);
894     }
895   else
896     {
897       do_write (connect_msg_write_cb, data);
898     }
899 }
900
901 static void
902 connect_reply_read_cb (GObject       *source,
903                        GAsyncResult  *result,
904                        gpointer       user_data)
905 {
906   GError *error = NULL;
907   ConnectAsyncData *data = user_data;
908   gssize read;
909
910   read = g_input_stream_read_finish (G_INPUT_STREAM (source),
911                                      result, &error);
912
913   if (read < 0)
914     {
915       complete_async_from_error (data, error);
916       return;
917     }
918
919   data->offset += read;
920
921   if (data->offset == data->length)
922     {
923       gint atype;
924
925       if (!parse_connect_reply (data->buffer, &atype, &error))
926         {
927           complete_async_from_error (data, error);
928           return;
929         }
930
931       switch (atype)
932         {
933           case SOCKS5_ATYP_IPV4:
934             data->length = 6;
935             data->offset = 0;
936             do_read (connect_addr_read_cb, data);
937             break;
938
939           case SOCKS5_ATYP_IPV6:
940             data->length = 18;
941             data->offset = 0;
942             do_read (connect_addr_read_cb, data);
943             break;
944
945           case SOCKS5_ATYP_DOMAINNAME:
946             data->length = 1;
947             data->offset = 0;
948             do_read (connect_addr_len_read_cb, data);
949             break;
950         }
951     }
952   else
953     {
954       do_read (connect_reply_read_cb, data);
955     }
956 }
957
958 static void
959 connect_addr_len_read_cb (GObject      *source,
960                           GAsyncResult *result,
961                           gpointer      user_data)
962 {
963   GError *error = NULL;
964   ConnectAsyncData *data = user_data;
965   gssize read;
966
967   read = g_input_stream_read_finish (G_INPUT_STREAM (source),
968                                      result, &error);
969
970   if (read < 0)
971     {
972       complete_async_from_error (data, error);
973       return;
974     }
975
976   data->length = data->buffer[0] + 2;
977   data->offset = 0;
978
979   do_read (connect_addr_read_cb, data);
980 }
981
982 static void
983 connect_addr_read_cb (GObject      *source,
984                       GAsyncResult *result,
985                       gpointer      user_data)
986 {
987   GError *error = NULL;
988   ConnectAsyncData *data = user_data;
989   gssize read;
990
991   read = g_input_stream_read_finish (G_INPUT_STREAM (source),
992                                      result, &error);
993
994   if (read < 0)
995     {
996       complete_async_from_error (data, error);
997       return;
998     }
999
1000   data->offset += read;
1001
1002   if (data->offset == data->length)
1003     {
1004       GSimpleAsyncResult *simple = data->simple;
1005       g_simple_async_result_complete (simple);
1006       g_object_unref (simple);
1007     }
1008   else
1009     {
1010       do_read (connect_reply_read_cb, data);
1011     }
1012 }
1013
1014 static GIOStream *
1015 g_socks5_proxy_connect_finish (GProxy       *proxy,
1016                                GAsyncResult *result,
1017                                GError      **error)
1018 {
1019   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
1020   ConnectAsyncData *data = g_simple_async_result_get_op_res_gpointer (simple);
1021
1022   if (g_simple_async_result_propagate_error (simple, error))
1023     return NULL;
1024
1025   return g_object_ref (data->io_stream);
1026 }
1027
1028 static gboolean
1029 g_socks5_proxy_supports_hostname (GProxy *proxy)
1030 {
1031   return TRUE;
1032 }
1033
1034 static void
1035 g_socks5_proxy_class_init (GSocks5ProxyClass *class)
1036 {
1037   GObjectClass *object_class;
1038
1039   object_class = (GObjectClass *) class;
1040   object_class->finalize = g_socks5_proxy_finalize;
1041 }
1042
1043 static void
1044 g_socks5_proxy_iface_init (GProxyInterface *proxy_iface)
1045 {
1046   proxy_iface->connect  = g_socks5_proxy_connect;
1047   proxy_iface->connect_async = g_socks5_proxy_connect_async;
1048   proxy_iface->connect_finish = g_socks5_proxy_connect_finish;
1049   proxy_iface->supports_hostname = g_socks5_proxy_supports_hostname;
1050 }