gsocks5proxy.c 24.3 KB
Newer Older
1 2 3 4 5 6 7 8
 /* GIO - GLib Input, Output and Streaming Library
 *
 * Copyright (C) 2008, 2010 Collabora, Ltd.
 * Copyright (C) 2008 Nokia Corporation. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
9
 * version 2.1 of the License, or (at your option) any later version.
10 11 12 13 14 15 16
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
17
 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
 *
 * Author:  Youness Alaoui <youness.alaoui@collabora.co.uk
 *
 * Contributors:
 *	    Nicolas Dufresne <nicolas.dufresne@collabora.co.uk>
 */

#include "config.h"

#include "gsocks5proxy.h"

#include <string.h>

#include "giomodule.h"
#include "giomodule-priv.h"
#include "giostream.h"
#include "ginetaddress.h"
#include "ginputstream.h"
#include "glibintl.h"
#include "goutputstream.h"
#include "gproxy.h"
#include "gproxyaddress.h"
40
#include "gtask.h"
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176

#define SOCKS5_VERSION		  0x05

#define SOCKS5_CMD_CONNECT	  0x01
#define SOCKS5_CMD_BIND		  0x02
#define SOCKS5_CMD_UDP_ASSOCIATE  0x03

#define SOCKS5_ATYP_IPV4	  0x01
#define SOCKS5_ATYP_DOMAINNAME	  0x03
#define SOCKS5_ATYP_IPV6	  0x04

#define SOCKS5_AUTH_VERSION	  0x01

#define SOCKS5_AUTH_NONE	  0x00
#define SOCKS5_AUTH_GSSAPI	  0x01
#define SOCKS5_AUTH_USR_PASS	  0x02
#define SOCKS5_AUTH_NO_ACCEPT	  0xff

#define SOCKS5_MAX_LEN		  255
#define SOCKS5_RESERVED		  0x00

#define SOCKS5_REP_SUCCEEDED	  0x00
#define SOCKS5_REP_SRV_FAILURE    0x01
#define SOCKS5_REP_NOT_ALLOWED    0x02
#define SOCKS5_REP_NET_UNREACH    0x03
#define SOCKS5_REP_HOST_UNREACH   0x04
#define SOCKS5_REP_REFUSED        0x05
#define SOCKS5_REP_TTL_EXPIRED    0x06
#define SOCKS5_REP_CMD_NOT_SUP    0x07
#define SOCKS5_REP_ATYPE_NOT_SUP  0x08


struct _GSocks5Proxy
{
  GObject parent;
};

struct _GSocks5ProxyClass
{
  GObjectClass parent_class;
};

static void g_socks5_proxy_iface_init (GProxyInterface *proxy_iface);

#define g_socks5_proxy_get_type _g_socks5_proxy_get_type
G_DEFINE_TYPE_WITH_CODE (GSocks5Proxy, g_socks5_proxy, G_TYPE_OBJECT,
			 G_IMPLEMENT_INTERFACE (G_TYPE_PROXY,
						g_socks5_proxy_iface_init)
			 _g_io_modules_ensure_extension_points_registered ();
			 g_io_extension_point_implement (G_PROXY_EXTENSION_POINT_NAME,
							 g_define_type_id,
							 "socks5",
							 0))

static void
g_socks5_proxy_finalize (GObject *object)
{
  /* must chain up */
  G_OBJECT_CLASS (g_socks5_proxy_parent_class)->finalize (object);
}

static void
g_socks5_proxy_init (GSocks5Proxy *proxy)
{
}

/*
 * +----+----------+----------+
 * |VER | NMETHODS | METHODS  |
 * +----+----------+----------+
 * | 1  |    1     | 1 to 255 |
 * +----+----------+----------+
 */
#define SOCKS5_NEGO_MSG_LEN	  4
static gint
set_nego_msg (guint8 *msg, gboolean has_auth)
{
  gint len = 3;

  msg[0] = SOCKS5_VERSION;
  msg[1] = 0x01; /* number of methods supported */
  msg[2] = SOCKS5_AUTH_NONE;

  /* add support for authentication method */
  if (has_auth)
    {
      msg[1] = 0x02; /* number of methods supported */
      msg[3] = SOCKS5_AUTH_USR_PASS;
      len++;
    }

  return len;
}


/*
 * +----+--------+
 * |VER | METHOD |
 * +----+--------+
 * | 1  |   1    |
 * +----+--------+
 */
#define SOCKS5_NEGO_REP_LEN	  2
static gboolean
parse_nego_reply (const guint8 *data,
		  gboolean     has_auth,
		  gboolean    *must_auth,
		  GError     **error)
{
  if (data[0] != SOCKS5_VERSION)
    {
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
			   _("The server is not a SOCKSv5 proxy server."));
      return FALSE;
    }

  switch (data[1])
    {
      case SOCKS5_AUTH_NONE:
	*must_auth = FALSE;
	break;

      case SOCKS5_AUTH_USR_PASS:
	if (!has_auth)
	  {
	    g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_NEED_AUTH,
			   _("The SOCKSv5 proxy requires authentication."));
	    return FALSE;
	  }
	*must_auth = TRUE;
	break;

      case SOCKS5_AUTH_GSSAPI:
      case SOCKS5_AUTH_NO_ACCEPT:
      default:
	g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_AUTH_FAILED,
177 178
			     _("The SOCKSv5 proxy requires an authentication "
			       "method that is not supported by GLib."));
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
	return FALSE;
	break;
    }

  return TRUE;
}

#define SOCKS5_AUTH_MSG_LEN       515
static gint
set_auth_msg (guint8	  *msg,
	      const gchar *username,
	      const gchar *password,
	      GError **error)
{
  gint len = 0;
  gint ulen = 0; /* username length */
  gint plen = 0; /* Password length */

  if (username)
    ulen = strlen (username);

  if (password)
    plen = strlen (password);

  if (ulen > SOCKS5_MAX_LEN || plen > SOCKS5_MAX_LEN)
    {
205 206
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
			   _("Username or password is too long for SOCKSv5 "
207
			     "protocol."));
208
      return -1;
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
    }

  msg[len++] = SOCKS5_AUTH_VERSION;
  msg[len++] = ulen;

  if (ulen > 0)
    memcpy (msg + len, username, ulen);

  len += ulen;
  msg[len++] = plen;

  if (plen > 0)
    memcpy (msg + len, password, plen);

  len += plen;

  return len;
}


static gboolean
check_auth_status (const guint8 *data, GError **error)
{
  if (data[0] != SOCKS5_VERSION
      || data[1] != SOCKS5_REP_SUCCEEDED)
    {
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_AUTH_FAILED,
			   _("SOCKSv5 authentication failed due to wrong "
			     "username or password."));
      return FALSE;
    }
  return TRUE;
}

/*
 * +----+-----+-------+------+----------+----------+
 * |VER | CMD |  RSV  | ATYP | DST.ADDR | DST.PORT |
 * +----+-----+-------+------+----------+----------+
 * | 1  |  1  | X'00' |  1   | Variable |    2     |
 * +----+-----+-------+------+----------+----------+
 * DST.ADDR is a string with first byte being the size. So DST.ADDR may not be
 * longer then 256 bytes.
 */
#define SOCKS5_CONN_MSG_LEN	  262
static gint
set_connect_msg (guint8       *msg,
		 const gchar *hostname,
		 guint16      port,
		 GError     **error)
{
  guint len = 0;

  msg[len++] = SOCKS5_VERSION;
  msg[len++] = SOCKS5_CMD_CONNECT;
  msg[len++] = SOCKS5_RESERVED;

  if (g_hostname_is_ip_address (hostname))
    {
      GInetAddress *addr = g_inet_address_new_from_string (hostname);
      gsize addr_len = g_inet_address_get_native_size (addr);

      /* We are cheating for simplicity, here's the logic:
       *   1 = IPV4 = 4 bytes / 4
       *   4 = IPV6 = 16 bytes / 4 */
      msg[len++] = addr_len / 4;
      memcpy (msg + len, g_inet_address_to_bytes (addr), addr_len);
      len += addr_len;

      g_object_unref (addr);
    }
  else
    {
      gsize host_len = strlen (hostname);

      if (host_len > SOCKS5_MAX_LEN)
	{
	  g_set_error (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
286
		       _("Hostname “%s” is too long for SOCKSv5 protocol"),
287
		       hostname);
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
	  return -1;
	}

      msg[len++] = SOCKS5_ATYP_DOMAINNAME;
      msg[len++] = (guint8) host_len;
      memcpy (msg + len, hostname, host_len);
      len += host_len;
    }

    {
      guint16 hp = g_htons (port);
      memcpy (msg + len, &hp, 2);
      len += 2;
    }

  return len;
}

/*
 * +----+-----+-------+------+----------+----------+
 * |VER | REP |  RSV  | ATYP | BND.ADDR | BND.PORT |
 * +----+-----+-------+------+----------+----------+
 * | 1  |  1  | X'00' |  1   | Variable |    2     |
 * +----+-----+-------+------+----------+----------+
 * This reply need to be read by small part to determin size. Buffer
 * size is determined in function of the biggest part to read.
 *
 * The parser only requires 4 bytes.
 */
#define SOCKS5_CONN_REP_LEN	  255
static gboolean
parse_connect_reply (const guint8 *data, gint *atype, GError **error)
{
  if (data[0] != SOCKS5_VERSION)
    {
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
			   _("The server is not a SOCKSv5 proxy server."));
      return FALSE;
    }

  switch (data[1])
    {
      case SOCKS5_REP_SUCCEEDED:
	if (data[2] != SOCKS5_RESERVED)
	  {
	    g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
			   _("The server is not a SOCKSv5 proxy server."));
	    return FALSE;
	  }

	switch (data[3])
	  {
	  case SOCKS5_ATYP_IPV4:
	  case SOCKS5_ATYP_IPV6:
	  case SOCKS5_ATYP_DOMAINNAME:
	    *atype = data[3];
	    break;

	  default:
	    g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
Matthias Clasen's avatar
Matthias Clasen committed
348
			   _("The SOCKSv5 proxy server uses unknown address type."));
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
	    return FALSE;
	  }
	break;

      case SOCKS5_REP_SRV_FAILURE:
	g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
			     _("Internal SOCKSv5 proxy server error."));
	return FALSE;
	break;

      case SOCKS5_REP_NOT_ALLOWED:
	g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_NOT_ALLOWED,
			     _("SOCKSv5 connection not allowed by ruleset."));
	return FALSE;
	break;

      case SOCKS5_REP_TTL_EXPIRED:
      case SOCKS5_REP_HOST_UNREACH:
	g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_HOST_UNREACHABLE,
			     _("Host unreachable through SOCKSv5 server."));
	return FALSE;
	break;

      case SOCKS5_REP_NET_UNREACH:
	g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NETWORK_UNREACHABLE,
			     _("Network unreachable through SOCKSv5 proxy."));
	return FALSE;
	break;

      case SOCKS5_REP_REFUSED:
	g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CONNECTION_REFUSED,
			     _("Connection refused through SOCKSv5 proxy."));
	return FALSE;
	break;

      case SOCKS5_REP_CMD_NOT_SUP:
	g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
386
			     _("SOCKSv5 proxy does not support “connect” command."));
387 388 389 390 391 392 393 394 395 396 397
	return FALSE;
	break;

      case SOCKS5_REP_ATYPE_NOT_SUP:
	g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
			     _("SOCKSv5 proxy does not support provided address type."));
	return FALSE;
	break;

      default: /* Unknown error */
	g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PROXY_FAILED,
398
			     _("Unknown SOCKSv5 proxy error."));
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
	return FALSE;
	break;
    }

  return TRUE;
}

static GIOStream *
g_socks5_proxy_connect (GProxy            *proxy,
			GIOStream         *io_stream,
			GProxyAddress     *proxy_address,
			GCancellable      *cancellable,
			GError          **error)
{
  gboolean has_auth;
  GInputStream *in;
  GOutputStream *out;
  const gchar *hostname;
  guint16 port;
  const gchar *username;
  const gchar *password;

  hostname = g_proxy_address_get_destination_hostname (proxy_address);
  port = g_proxy_address_get_destination_port (proxy_address);
  username = g_proxy_address_get_username (proxy_address);
  password = g_proxy_address_get_password (proxy_address);

  has_auth = username || password;
  
  in = g_io_stream_get_input_stream (io_stream);
  out = g_io_stream_get_output_stream (io_stream);

  /* Send SOCKS5 handshake */
    {
      guint8 msg[SOCKS5_NEGO_MSG_LEN];
      gint len;

      len = set_nego_msg (msg, has_auth);

      if (!g_output_stream_write_all (out, msg, len, NULL,
				      cancellable, error))
	goto error;
    }

Matthias Clasen's avatar
Matthias Clasen committed
443
  /* Receive SOCKS5 response and reply with authentication if required */
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
    {
      guint8 data[SOCKS5_NEGO_REP_LEN];
      gboolean must_auth = FALSE;

      if (!g_input_stream_read_all (in, data, sizeof (data), NULL,
				    cancellable, error))
	goto error;

      if (!parse_nego_reply (data, has_auth, &must_auth, error))
	  goto error;

      if (must_auth)
	{
	  guint8 msg[SOCKS5_AUTH_MSG_LEN];
	  gint len;

	  len = set_auth_msg (msg, username, password, error);

	  if (len < 0)
	    goto error;
	  
	  if (!g_output_stream_write_all (out, msg, len, NULL,
					  cancellable, error))
	    goto error;

	  if (!g_input_stream_read_all (in, data, sizeof (data), NULL,
					cancellable, error))
	    goto error;

	  if (!check_auth_status (data, error))
	    goto error;
	}
    }

  /* Send SOCKS5 connection request */
    {
      guint8 msg[SOCKS5_CONN_MSG_LEN];
      gint len;
      
      len = set_connect_msg (msg, hostname, port, error);

      if (len < 0)
	goto error;

      if (!g_output_stream_write_all (out, msg, len, NULL,
				      cancellable, error))
	goto error;
    }

  /* Read SOCKS5 response */
    {
      guint8 data[SOCKS5_CONN_REP_LEN];
      gint atype;

      if (!g_input_stream_read_all (in, data, 4, NULL,
				    cancellable, error))
	goto error;

      if (!parse_connect_reply (data, &atype, error))
	goto error;

      switch (atype)
	{
	  case SOCKS5_ATYP_IPV4:
	    if (!g_input_stream_read_all (in, data, 6, NULL,
					  cancellable, error))
	      goto error;
	    break;

	  case SOCKS5_ATYP_IPV6:
	    if (!g_input_stream_read_all (in, data, 18, NULL,
					  cancellable, error))
	      goto error;
	    break;

	  case SOCKS5_ATYP_DOMAINNAME:
	    if (!g_input_stream_read_all (in, data, 1, NULL,
					  cancellable, error))
	      goto error;
	    if (!g_input_stream_read_all (in, data, data[0] + 2, NULL,
					  cancellable, error))
	      goto error;
	    break;
	}
    }

  return g_object_ref (io_stream);

error:
  return NULL;
}


typedef struct
{
  GIOStream *io_stream;
  gchar *hostname;
  guint16 port;
  gchar *username;
  gchar *password;
  guint8 *buffer;
  gssize length;
  gssize offset;
} ConnectAsyncData;

static void nego_msg_write_cb	      (GObject          *source,
				       GAsyncResult     *res,
				       gpointer          user_data);
static void nego_reply_read_cb	      (GObject          *source,
				       GAsyncResult     *res,
				       gpointer          user_data);
static void auth_msg_write_cb	      (GObject          *source,
				       GAsyncResult     *res,
				       gpointer          user_data);
static void auth_reply_read_cb	      (GObject          *source,
				       GAsyncResult     *result,
				       gpointer          user_data);
561
static void send_connect_msg	      (GTask            *task);
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
static void connect_msg_write_cb      (GObject          *source,
				       GAsyncResult     *result,
				       gpointer          user_data);
static void connect_reply_read_cb     (GObject          *source,
				       GAsyncResult     *result,
				       gpointer          user_data);
static void connect_addr_len_read_cb  (GObject          *source,
				       GAsyncResult     *result,
				       gpointer          user_data);
static void connect_addr_read_cb      (GObject          *source,
				       GAsyncResult     *result,
				       gpointer          user_data);

static void
free_connect_data (ConnectAsyncData *data)
{
578
  g_object_unref (data->io_stream);
579 580 581 582

  g_free (data->hostname);
  g_free (data->username);
  g_free (data->password);
583
  g_free (data->buffer);
584 585 586 587 588

  g_slice_free (ConnectAsyncData, data);
}

static void
589
do_read (GAsyncReadyCallback callback, GTask *task, ConnectAsyncData *data)
590 591 592 593 594 595
{
   GInputStream *in;
   in = g_io_stream_get_input_stream (data->io_stream);
   g_input_stream_read_async (in,
			      data->buffer + data->offset,
			      data->length - data->offset,
596 597 598
			      g_task_get_priority (task),
			      g_task_get_cancellable (task),
			      callback, task);
599 600 601
}

static void
602
do_write (GAsyncReadyCallback callback, GTask *task, ConnectAsyncData *data)
603 604 605 606 607 608
{
  GOutputStream *out;
  out = g_io_stream_get_output_stream (data->io_stream);
  g_output_stream_write_async (out,
			       data->buffer + data->offset,
			       data->length - data->offset,
609 610 611
			       g_task_get_priority (task),
			       g_task_get_cancellable (task),
			       callback, task);
612 613 614 615 616 617 618 619 620 621
}

static void
g_socks5_proxy_connect_async (GProxy               *proxy,
			      GIOStream            *io_stream,
			      GProxyAddress        *proxy_address,
			      GCancellable         *cancellable,
			      GAsyncReadyCallback   callback,
			      gpointer              user_data)
{
622
  GTask *task;
623 624 625 626 627
  ConnectAsyncData *data;

  data = g_slice_new0 (ConnectAsyncData);
  data->io_stream = g_object_ref (io_stream);

628
  task = g_task_new (proxy, cancellable, callback, user_data);
629
  g_task_set_source_tag (task, g_socks5_proxy_connect_async);
630
  g_task_set_task_data (task, data, (GDestroyNotify) free_connect_data);
631 632 633 634 635 636 637 638 639 640 641 642 643

  g_object_get (G_OBJECT (proxy_address),
		"destination-hostname", &data->hostname,
		"destination-port", &data->port,
		"username", &data->username,
		"password", &data->password,
		NULL);

  data->buffer = g_malloc0 (SOCKS5_NEGO_MSG_LEN);
  data->length = set_nego_msg (data->buffer,
			       data->username || data->password);
  data->offset = 0;

644
  do_write (nego_msg_write_cb, task, data);
645 646 647 648 649 650 651 652
}


static void
nego_msg_write_cb (GObject      *source,
		   GAsyncResult *res,
		   gpointer      user_data)
{
653 654
  GTask *task = user_data;
  ConnectAsyncData *data = g_task_get_task_data (task);
655 656 657 658 659 660 661 662
  GError *error = NULL;
  gssize written;

  written = g_output_stream_write_finish (G_OUTPUT_STREAM (source),
					  res, &error);

  if (written < 0)
    {
663 664
      g_task_return_error (task, error);
      g_object_unref (task);
665 666 667 668 669 670 671 672 673 674 675 676 677
      return;
    }

  data->offset += written;

  if (data->offset == data->length)
    {
      g_free (data->buffer);

      data->buffer = g_malloc0 (SOCKS5_NEGO_REP_LEN);
      data->length = SOCKS5_NEGO_REP_LEN;
      data->offset = 0;

678
      do_read (nego_reply_read_cb, task, data);
679 680 681
    }
  else
    {
682
      do_write (nego_msg_write_cb, task, data);
683 684 685 686 687 688 689 690
    }
}

static void
nego_reply_read_cb (GObject      *source,
		    GAsyncResult *res,
		    gpointer      user_data)
{
691 692
  GTask *task = user_data;
  ConnectAsyncData *data = g_task_get_task_data (task);
693 694 695 696 697 698 699 700
  GError *error = NULL;
  gssize read;

  read = g_input_stream_read_finish (G_INPUT_STREAM (source),
				     res, &error);

  if (read < 0)
    {
701 702
      g_task_return_error (task, error);
      g_object_unref (task);
703 704 705 706 707 708 709
      return;
    }

  data->offset += read;
  
  if (data->offset == data->length)
    {
710
      GError *error = NULL;
711 712 713 714 715
      gboolean must_auth = FALSE;
      gboolean has_auth = data->username || data->password;

      if (!parse_nego_reply (data->buffer, has_auth, &must_auth, &error))
	{
716 717
	  g_task_return_error (task, error);
	  g_object_unref (task);
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
	  return;
	}

      if (must_auth)
	{
	  g_free (data->buffer);

	  data->buffer = g_malloc0 (SOCKS5_AUTH_MSG_LEN);
	  data->length = set_auth_msg (data->buffer,
				       data->username,
				       data->password,
				       &error);
	  data->offset = 0;

	  if (data->length < 0)
	    {
734 735
	      g_task_return_error (task, error);
	      g_object_unref (task);
736 737 738
	      return;
	    }
	  
739
	  do_write (auth_msg_write_cb, task, data);
740 741 742
	}
      else
	{
743
	  send_connect_msg (task);
744 745 746 747
	}
    }
  else
    {
748
      do_read (nego_reply_read_cb, task, data);
749 750 751 752 753 754 755 756
    }
}

static void
auth_msg_write_cb (GObject      *source,
		   GAsyncResult *result,
		   gpointer      user_data)
{
757 758
  GTask *task = user_data;
  ConnectAsyncData *data = g_task_get_task_data (task);
759 760 761 762 763 764 765 766
  GError *error = NULL;
  gssize written;

  written = g_output_stream_write_finish (G_OUTPUT_STREAM (source),
					  result, &error);
  
  if (written < 0)
    {
767 768
      g_task_return_error (task, error);
      g_object_unref (task);
769 770 771 772 773 774 775 776 777 778 779 780 781
      return;
    }

  data->offset += written;

  if (data->offset == data->length)
    {
      g_free (data->buffer);

      data->buffer = g_malloc0 (SOCKS5_NEGO_REP_LEN);
      data->length = SOCKS5_NEGO_REP_LEN;
      data->offset = 0;

782
      do_read (auth_reply_read_cb, task, data);
783 784 785
    }
  else
    {
786
      do_write (auth_msg_write_cb, task, data);
787 788 789 790 791 792 793 794
    }
}

static void
auth_reply_read_cb (GObject      *source,
		    GAsyncResult *result,
		    gpointer      user_data)
{
795 796
  GTask *task = user_data;
  ConnectAsyncData *data = g_task_get_task_data (task);
797 798 799 800 801 802 803 804
  GError *error = NULL;
  gssize read;

  read = g_input_stream_read_finish (G_INPUT_STREAM (source),
				     result, &error);

  if (read < 0)
    {
805 806
      g_task_return_error (task, error);
      g_object_unref (task);
807 808 809 810 811 812 813 814 815
      return;
    }

  data->offset += read;

  if (data->offset == data->length)
    {
      if (!check_auth_status (data->buffer, &error))
	{
816 817
	  g_task_return_error (task, error);
	  g_object_unref (task);
818 819 820
	  return;
	}
	
821
      send_connect_msg (task);
822 823 824
    }
  else
    {
825
      do_read (auth_reply_read_cb, task, data);
826 827 828 829
    }
}

static void
830
send_connect_msg (GTask *task)
831
{
832
  ConnectAsyncData *data = g_task_get_task_data (task);
833 834 835 836 837 838 839 840 841 842 843 844 845
  GError *error = NULL;

  g_free (data->buffer);

  data->buffer = g_malloc0 (SOCKS5_CONN_MSG_LEN);
  data->length = set_connect_msg (data->buffer,
				  data->hostname,
				  data->port,
				  &error);
  data->offset = 0;
  
  if (data->length < 0)
    {
846 847
      g_task_return_error (task, error);
      g_object_unref (task);
848 849 850
      return;
    }

851
  do_write (connect_msg_write_cb, task, data);
852 853 854 855 856 857 858
}

static void
connect_msg_write_cb (GObject      *source,
		      GAsyncResult *result,
		      gpointer      user_data)
{
859 860
  GTask *task = user_data;
  ConnectAsyncData *data = g_task_get_task_data (task);
861 862 863 864 865 866 867 868
  GError *error = NULL;
  gssize written;

  written = g_output_stream_write_finish (G_OUTPUT_STREAM (source),
					  result, &error);
  
  if (written < 0)
    {
869 870
      g_task_return_error (task, error);
      g_object_unref (task);
871 872 873 874 875 876 877 878 879 880 881 882 883
      return;
    }

  data->offset += written;

  if (data->offset == data->length)
    {
      g_free (data->buffer);

      data->buffer = g_malloc0 (SOCKS5_CONN_REP_LEN);
      data->length = 4;
      data->offset = 0;

884
      do_read (connect_reply_read_cb, task, data);
885 886 887
    }
  else
    {
888
      do_write (connect_msg_write_cb, task, data);
889 890 891 892 893 894 895 896
    }
}

static void
connect_reply_read_cb (GObject       *source,
		       GAsyncResult  *result,
		       gpointer       user_data)
{
897 898
  GTask *task = user_data;
  ConnectAsyncData *data = g_task_get_task_data (task);
899 900 901 902 903 904 905 906
  GError *error = NULL;
  gssize read;

  read = g_input_stream_read_finish (G_INPUT_STREAM (source),
				     result, &error);

  if (read < 0)
    {
907 908
      g_task_return_error (task, error);
      g_object_unref (task);
909 910 911 912 913 914 915 916 917 918 919
      return;
    }

  data->offset += read;

  if (data->offset == data->length)
    {
      gint atype;

      if (!parse_connect_reply (data->buffer, &atype, &error))
	{
920 921
	  g_task_return_error (task, error);
	  g_object_unref (task);
922 923 924 925 926 927 928 929
	  return;
	}

      switch (atype)
	{
	  case SOCKS5_ATYP_IPV4:
	    data->length = 6;
	    data->offset = 0;
930
	    do_read (connect_addr_read_cb, task, data);
931 932 933 934 935
	    break;

	  case SOCKS5_ATYP_IPV6:
	    data->length = 18;
	    data->offset = 0;
936
	    do_read (connect_addr_read_cb, task, data);
937 938 939 940 941
	    break;

	  case SOCKS5_ATYP_DOMAINNAME:
	    data->length = 1;
	    data->offset = 0;
942
	    do_read (connect_addr_len_read_cb, task, data);
943 944 945 946 947
	    break;
	}
    }
  else
    {
948
      do_read (connect_reply_read_cb, task, data);
949 950 951 952 953 954 955 956
    }
}

static void
connect_addr_len_read_cb (GObject      *source,
			  GAsyncResult *result,
			  gpointer      user_data)
{
957 958
  GTask *task = user_data;
  ConnectAsyncData *data = g_task_get_task_data (task);
959 960 961 962 963 964 965 966
  GError *error = NULL;
  gssize read;

  read = g_input_stream_read_finish (G_INPUT_STREAM (source),
				     result, &error);

  if (read < 0)
    {
967 968
      g_task_return_error (task, error);
      g_object_unref (task);
969 970 971 972 973 974
      return;
    }

  data->length = data->buffer[0] + 2;
  data->offset = 0;

975
  do_read (connect_addr_read_cb, task, data);
976 977 978 979 980 981 982
}

static void
connect_addr_read_cb (GObject      *source,
		      GAsyncResult *result,
		      gpointer      user_data)
{
983 984
  GTask *task = user_data;
  ConnectAsyncData *data = g_task_get_task_data (task);
985 986 987 988 989 990 991 992
  GError *error = NULL;
  gssize read;

  read = g_input_stream_read_finish (G_INPUT_STREAM (source),
				     result, &error);

  if (read < 0)
    {
993 994
      g_task_return_error (task, error);
      g_object_unref (task);
995 996 997 998 999 1000 1001
      return;
    }

  data->offset += read;

  if (data->offset == data->length)
    {
1002 1003 1004
      g_task_return_pointer (task, g_object_ref (data->io_stream), g_object_unref);
      g_object_unref (task);
      return;
1005 1006 1007
    }
  else
    {
1008
      do_read (connect_reply_read_cb, task, data);
1009 1010 1011 1012 1013 1014 1015 1016
    }
}

static GIOStream *
g_socks5_proxy_connect_finish (GProxy       *proxy,
			       GAsyncResult *result,
			       GError      **error)
{
1017
  return g_task_propagate_pointer (G_TASK (result), error);
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
}

static gboolean
g_socks5_proxy_supports_hostname (GProxy *proxy)
{
  return TRUE;
}

static void
g_socks5_proxy_class_init (GSocks5ProxyClass *class)
{
  GObjectClass *object_class;

  object_class = (GObjectClass *) class;
  object_class->finalize = g_socks5_proxy_finalize;
}

static void
g_socks5_proxy_iface_init (GProxyInterface *proxy_iface)
{
  proxy_iface->connect  = g_socks5_proxy_connect;
  proxy_iface->connect_async = g_socks5_proxy_connect_async;
  proxy_iface->connect_finish = g_socks5_proxy_connect_finish;
  proxy_iface->supports_hostname = g_socks5_proxy_supports_hostname;
}