1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 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 177 178 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 205 206 207 208 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 286 287 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 348 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 386 387 388 389 390 391 392 393 394 395 396 397 398 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 443 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 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 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 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
|
/*
* socks.cpp - SOCKS5 TCP proxy client/server
* Copyright (C) 2003 Justin Karneges
*
* 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
* version 2.1 of the License, or (at your option) any later version.
*
* 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 Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include "socks.h"
#include <qhostaddress.h>
#include <qstringlist.h>
#include <q3ptrlist.h>
#include <qtimer.h>
#include <qpointer.h>
#include <q3socketdevice.h>
#include <qsocketnotifier.h>
//Added by qt3to4:
#include <Q3CString>
#ifdef Q_OS_UNIX
#include <sys/types.h>
#include <netinet/in.h>
#endif
#ifdef Q_OS_WIN32
#include <windows.h>
#endif
#ifdef Q_OS_UNIX
#include <unistd.h>
#include <fcntl.h>
#endif
#include "servsock.h"
#include "bsocket.h"
#ifdef PROX_DEBUG
#include <stdio.h>
#endif
// CS_NAMESPACE_BEGIN
//----------------------------------------------------------------------------
// SocksUDP
//----------------------------------------------------------------------------
static QByteArray sp_create_udp(const QString &host, Q_UINT16 port, const QByteArray &buf)
{
// detect for IP addresses
//QHostAddress addr;
//if(addr.setAddress(host))
// return sp_set_request(addr, port, cmd1);
Q3CString h = host.utf8();
h.truncate(255);
h = QString::fromUtf8(h).utf8(); // delete any partial characters?
int hlen = h.length();
int at = 0;
QByteArray a(4);
a[at++] = 0x00; // reserved
a[at++] = 0x00; // reserved
a[at++] = 0x00; // frag
a[at++] = 0x03; // address type = domain
// host
a.resize(at+hlen+1);
a[at++] = hlen;
memcpy(a.data() + at, h.data(), hlen);
at += hlen;
// port
a.resize(at+2);
unsigned short p = htons(port);
memcpy(a.data() + at, &p, 2);
at += 2;
a.resize(at+buf.size());
memcpy(a.data() + at, buf.data(), buf.size());
return a;
}
struct SPS_UDP
{
QString host;
Q_UINT16 port;
QByteArray data;
};
static int sp_read_udp(QByteArray *from, SPS_UDP *s)
{
int full_len = 4;
if((int)from->size() < full_len)
return 0;
QString host;
QHostAddress addr;
unsigned char atype = from->at(3);
if(atype == 0x01) {
full_len += 4;
if((int)from->size() < full_len)
return 0;
Q_UINT32 ip4;
memcpy(&ip4, from->data() + 4, 4);
addr.setAddress(ntohl(ip4));
host = addr.toString();
}
else if(atype == 0x03) {
++full_len;
if((int)from->size() < full_len)
return 0;
unsigned char host_len = from->at(4);
full_len += host_len;
if((int)from->size() < full_len)
return 0;
Q3CString cs(host_len+1);
memcpy(cs.data(), from->data() + 5, host_len);
host = QString::fromLatin1(cs);
}
else if(atype == 0x04) {
full_len += 16;
if((int)from->size() < full_len)
return 0;
Q_UINT8 a6[16];
memcpy(a6, from->data() + 4, 16);
addr.setAddress(a6);
host = addr.toString();
}
full_len += 2;
if((int)from->size() < full_len)
return 0;
Q_UINT16 p;
memcpy(&p, from->data() + full_len - 2, 2);
s->host = host;
s->port = ntohs(p);
s->data.resize(from->size() - full_len);
memcpy(s->data.data(), from->data() + full_len, s->data.size());
return 1;
}
class SocksUDP::Private
{
public:
Q3SocketDevice *sd;
QSocketNotifier *sn;
SocksClient *sc;
QHostAddress routeAddr;
int routePort;
QString host;
int port;
};
SocksUDP::SocksUDP(SocksClient *sc, const QString &host, int port, const QHostAddress &routeAddr, int routePort)
:QObject(sc)
{
d = new Private;
d->sc = sc;
d->sd = new Q3SocketDevice(Q3SocketDevice::Datagram);
d->sd->setBlocking(false);
d->sn = new QSocketNotifier(d->sd->socket(), QSocketNotifier::Read);
connect(d->sn, SIGNAL(activated(int)), SLOT(sn_activated(int)));
d->host = host;
d->port = port;
d->routeAddr = routeAddr;
d->routePort = routePort;
}
SocksUDP::~SocksUDP()
{
delete d->sn;
delete d->sd;
delete d;
}
void SocksUDP::change(const QString &host, int port)
{
d->host = host;
d->port = port;
}
void SocksUDP::write(const QByteArray &data)
{
QByteArray buf = sp_create_udp(d->host, d->port, data);
d->sd->setBlocking(true);
d->sd->writeBlock(buf.data(), buf.size(), d->routeAddr, d->routePort);
d->sd->setBlocking(false);
}
void SocksUDP::sn_activated(int)
{
QByteArray buf(8192);
int actual = d->sd->readBlock(buf.data(), buf.size());
buf.resize(actual);
packetReady(buf);
}
//----------------------------------------------------------------------------
// SocksClient
//----------------------------------------------------------------------------
#define REQ_CONNECT 0x01
#define REQ_BIND 0x02
#define REQ_UDPASSOCIATE 0x03
#define RET_SUCCESS 0x00
#define RET_UNREACHABLE 0x04
#define RET_CONNREFUSED 0x05
// spc = socks packet client
// sps = socks packet server
// SPCS = socks packet client struct
// SPSS = socks packet server struct
// Version
static QByteArray spc_set_version()
{
QByteArray ver(4);
ver[0] = 0x05; // socks version 5
ver[1] = 0x02; // number of methods
ver[2] = 0x00; // no-auth
ver[3] = 0x02; // username
return ver;
}
static QByteArray sps_set_version(int method)
{
QByteArray ver(2);
ver[0] = 0x05;
ver[1] = method;
return ver;
}
struct SPCS_VERSION
{
unsigned char version;
QByteArray methodList;
};
static int spc_get_version(QByteArray *from, SPCS_VERSION *s)
{
if(from->size() < 1)
return 0;
if(from->at(0) != 0x05) // only SOCKS5 supported
return -1;
if(from->size() < 2)
return 0;
unsigned char mlen = from->at(1);
int num = mlen;
if(num > 16) // who the heck has over 16 auth methods??
return -1;
if(from->size() < 2 + num)
return 0;
QByteArray a = ByteStream::takeArray(from, 2+num);
s->version = a[0];
s->methodList.resize(num);
memcpy(s->methodList.data(), a.data() + 2, num);
return 1;
}
struct SPSS_VERSION
{
unsigned char version;
unsigned char method;
};
static int sps_get_version(QByteArray *from, SPSS_VERSION *s)
{
if(from->size() < 2)
return 0;
QByteArray a = ByteStream::takeArray(from, 2);
s->version = a[0];
s->method = a[1];
return 1;
}
// authUsername
static QByteArray spc_set_authUsername(const Q3CString &user, const Q3CString &pass)
{
int len1 = user.length();
int len2 = pass.length();
if(len1 > 255)
len1 = 255;
if(len2 > 255)
len2 = 255;
QByteArray a(1+1+len1+1+len2);
a[0] = 0x01; // username auth version 1
a[1] = len1;
memcpy(a.data() + 2, user.data(), len1);
a[2+len1] = len2;
memcpy(a.data() + 3 + len1, pass.data(), len2);
return a;
}
static QByteArray sps_set_authUsername(bool success)
{
QByteArray a(2);
a[0] = 0x01;
a[1] = success ? 0x00 : 0xff;
return a;
}
struct SPCS_AUTHUSERNAME
{
QString user, pass;
};
static int spc_get_authUsername(QByteArray *from, SPCS_AUTHUSERNAME *s)
{
if(from->size() < 1)
return 0;
unsigned char ver = from->at(0);
if(ver != 0x01)
return -1;
if(from->size() < 2)
return 0;
unsigned char ulen = from->at(1);
if((int)from->size() < ulen + 3)
return 0;
unsigned char plen = from->at(ulen+2);
if((int)from->size() < ulen + plen + 3)
return 0;
QByteArray a = ByteStream::takeArray(from, ulen + plen + 3);
Q3CString user, pass;
user.resize(ulen+1);
pass.resize(plen+1);
memcpy(user.data(), a.data()+2, ulen);
memcpy(pass.data(), a.data()+ulen+3, plen);
s->user = QString::fromUtf8(user);
s->pass = QString::fromUtf8(pass);
return 1;
}
struct SPSS_AUTHUSERNAME
{
unsigned char version;
bool success;
};
static int sps_get_authUsername(QByteArray *from, SPSS_AUTHUSERNAME *s)
{
if(from->size() < 2)
return 0;
QByteArray a = ByteStream::takeArray(from, 2);
s->version = a[0];
s->success = ((char) a[1] == 0 ? true: false);
return 1;
}
// connectRequest
static QByteArray sp_set_request(const QHostAddress &addr, unsigned short port, unsigned char cmd1)
{
int at = 0;
QByteArray a(4);
a[at++] = 0x05; // socks version 5
a[at++] = cmd1;
a[at++] = 0x00; // reserved
if(addr.isIp4Addr()) {
a[at++] = 0x01; // address type = ipv4
Q_UINT32 ip4 = htonl(addr.ip4Addr());
a.resize(at+4);
memcpy(a.data() + at, &ip4, 4);
at += 4;
}
else {
a[at++] = 0x04;
Q_UINT8 a6[16];
QStringList s6 = QStringList::split(':', addr.toString(), true);
int at = 0;
Q_UINT16 c;
bool ok;
for(QStringList::ConstIterator it = s6.begin(); it != s6.end(); ++it) {
c = (*it).toInt(&ok, 16);
a6[at++] = (c >> 8);
a6[at++] = c & 0xff;
}
a.resize(at+16);
memcpy(a.data() + at, a6, 16);
at += 16;
}
// port
a.resize(at+2);
unsigned short p = htons(port);
memcpy(a.data() + at, &p, 2);
return a;
}
static QByteArray sp_set_request(const QString &host, Q_UINT16 port, unsigned char cmd1)
{
// detect for IP addresses
QHostAddress addr;
if(addr.setAddress(host))
return sp_set_request(addr, port, cmd1);
Q3CString h = host.utf8();
h.truncate(255);
h = QString::fromUtf8(h).utf8(); // delete any partial characters?
int hlen = h.length();
int at = 0;
QByteArray a(4);
a[at++] = 0x05; // socks version 5
a[at++] = cmd1;
a[at++] = 0x00; // reserved
a[at++] = 0x03; // address type = domain
// host
a.resize(at+hlen+1);
a[at++] = hlen;
memcpy(a.data() + at, h.data(), hlen);
at += hlen;
// port
a.resize(at+2);
unsigned short p = htons(port);
memcpy(a.data() + at, &p, 2);
return a;
}
struct SPS_CONNREQ
{
unsigned char version;
unsigned char cmd;
int address_type;
QString host;
QHostAddress addr;
Q_UINT16 port;
};
static int sp_get_request(QByteArray *from, SPS_CONNREQ *s)
{
int full_len = 4;
if((int)from->size() < full_len)
return 0;
QString host;
QHostAddress addr;
unsigned char atype = from->at(3);
if(atype == 0x01) {
full_len += 4;
if((int)from->size() < full_len)
return 0;
Q_UINT32 ip4;
memcpy(&ip4, from->data() + 4, 4);
addr.setAddress(ntohl(ip4));
}
else if(atype == 0x03) {
++full_len;
if((int)from->size() < full_len)
return 0;
unsigned char host_len = from->at(4);
full_len += host_len;
if((int)from->size() < full_len)
return 0;
Q3CString cs(host_len+1);
memcpy(cs.data(), from->data() + 5, host_len);
host = QString::fromLatin1(cs);
}
else if(atype == 0x04) {
full_len += 16;
if((int)from->size() < full_len)
return 0;
Q_UINT8 a6[16];
memcpy(a6, from->data() + 4, 16);
addr.setAddress(a6);
}
full_len += 2;
if((int)from->size() < full_len)
return 0;
QByteArray a = ByteStream::takeArray(from, full_len);
Q_UINT16 p;
memcpy(&p, a.data() + full_len - 2, 2);
s->version = a[0];
s->cmd = a[1];
s->address_type = atype;
s->host = host;
s->addr = addr;
s->port = ntohs(p);
return 1;
}
enum { StepVersion, StepAuth, StepRequest };
class SocksClient::Private
{
public:
Private() {}
BSocket sock;
QString host;
int port;
QString user, pass;
QString real_host;
int real_port;
QByteArray recvBuf;
bool active;
int step;
int authMethod;
bool incoming, waiting;
QString rhost;
int rport;
int pending;
bool udp;
QString udpAddr;
int udpPort;
};
SocksClient::SocksClient(QObject *parent)
:ByteStream(parent)
{
init();
d->incoming = false;
}
SocksClient::SocksClient(int s, QObject *parent)
:ByteStream(parent)
{
init();
d->incoming = true;
d->waiting = true;
d->sock.setSocket(s);
}
void SocksClient::init()
{
d = new Private;
connect(&d->sock, SIGNAL(connected()), SLOT(sock_connected()));
connect(&d->sock, SIGNAL(connectionClosed()), SLOT(sock_connectionClosed()));
connect(&d->sock, SIGNAL(delayedCloseFinished()), SLOT(sock_delayedCloseFinished()));
connect(&d->sock, SIGNAL(readyRead()), SLOT(sock_readyRead()));
connect(&d->sock, SIGNAL(bytesWritten(int)), SLOT(sock_bytesWritten(int)));
connect(&d->sock, SIGNAL(error(int)), SLOT(sock_error(int)));
reset(true);
}
SocksClient::~SocksClient()
{
reset(true);
delete d;
}
void SocksClient::reset(bool clear)
{
if(d->sock.state() != BSocket::Idle)
d->sock.close();
if(clear)
clearReadBuffer();
d->recvBuf.resize(0);
d->active = false;
d->waiting = false;
d->udp = false;
d->pending = 0;
}
bool SocksClient::isIncoming() const
{
return d->incoming;
}
void SocksClient::setAuth(const QString &user, const QString &pass)
{
d->user = user;
d->pass = pass;
}
void SocksClient::connectToHost(const QString &proxyHost, int proxyPort, const QString &host, int port, bool udpMode)
{
reset(true);
d->host = proxyHost;
d->port = proxyPort;
d->real_host = host;
d->real_port = port;
d->udp = udpMode;
#ifdef PROX_DEBUG
fprintf(stderr, "SocksClient: Connecting to %s:%d", proxyHost.latin1(), proxyPort);
if(d->user.isEmpty())
fprintf(stderr, "\n");
else
fprintf(stderr, ", auth {%s,%s}\n", d->user.latin1(), d->pass.latin1());
#endif
d->sock.connectToHost(d->host, d->port);
}
bool SocksClient::isOpen() const
{
return d->active;
}
void SocksClient::close()
{
d->sock.close();
if(d->sock.bytesToWrite() == 0)
reset();
}
void SocksClient::writeData(const QByteArray &buf)
{
d->pending += buf.size();
d->sock.write(buf);
}
void SocksClient::write(const QByteArray &buf)
{
if(d->active && !d->udp)
d->sock.write(buf);
}
QByteArray SocksClient::read(int bytes)
{
return ByteStream::read(bytes);
}
int SocksClient::bytesAvailable() const
{
return ByteStream::bytesAvailable();
}
int SocksClient::bytesToWrite() const
{
if(d->active)
return d->sock.bytesToWrite();
else
return 0;
}
void SocksClient::sock_connected()
{
#ifdef PROX_DEBUG
fprintf(stderr, "SocksClient: Connected\n");
#endif
d->step = StepVersion;
writeData(spc_set_version());
}
void SocksClient::sock_connectionClosed()
{
if(d->active) {
reset();
connectionClosed();
}
else {
error(ErrProxyNeg);
}
}
void SocksClient::sock_delayedCloseFinished()
{
if(d->active) {
reset();
delayedCloseFinished();
}
}
void SocksClient::sock_readyRead()
{
QByteArray block = d->sock.read();
if(!d->active) {
if(d->incoming)
processIncoming(block);
else
processOutgoing(block);
}
else {
if(!d->udp) {
appendRead(block);
readyRead();
}
}
}
void SocksClient::processOutgoing(const QByteArray &block)
{
#ifdef PROX_DEBUG
// show hex
fprintf(stderr, "SocksClient: client recv { ");
for(int n = 0; n < (int)block.size(); ++n)
fprintf(stderr, "%02X ", (unsigned char)block[n]);
fprintf(stderr, " } \n");
#endif
ByteStream::appendArray(&d->recvBuf, block);
if(d->step == StepVersion) {
SPSS_VERSION s;
int r = sps_get_version(&d->recvBuf, &s);
if(r == -1) {
reset(true);
error(ErrProxyNeg);
return;
}
else if(r == 1) {
if(s.version != 0x05 || s.method == 0xff) {
#ifdef PROX_DEBUG
fprintf(stderr, "SocksClient: Method selection failed\n");
#endif
reset(true);
error(ErrProxyNeg);
return;
}
QString str;
if(s.method == 0x00) {
str = "None";
d->authMethod = AuthNone;
}
else if(s.method == 0x02) {
str = "Username/Password";
d->authMethod = AuthUsername;
}
else {
#ifdef PROX_DEBUG
fprintf(stderr, "SocksClient: Server wants to use unknown method '%02x'\n", s.method);
#endif
reset(true);
error(ErrProxyNeg);
return;
}
if(d->authMethod == AuthNone) {
// no auth, go straight to the request
do_request();
}
else if(d->authMethod == AuthUsername) {
d->step = StepAuth;
#ifdef PROX_DEBUG
fprintf(stderr, "SocksClient: Authenticating [Username] ...\n");
#endif
writeData(spc_set_authUsername(d->user.latin1(), d->pass.latin1()));
}
}
}
if(d->step == StepAuth) {
if(d->authMethod == AuthUsername) {
SPSS_AUTHUSERNAME s;
int r = sps_get_authUsername(&d->recvBuf, &s);
if(r == -1) {
reset(true);
error(ErrProxyNeg);
return;
}
else if(r == 1) {
if(s.version != 0x01) {
reset(true);
error(ErrProxyNeg);
return;
}
if(!s.success) {
reset(true);
error(ErrProxyAuth);
return;
}
do_request();
}
}
}
else if(d->step == StepRequest) {
SPS_CONNREQ s;
int r = sp_get_request(&d->recvBuf, &s);
if(r == -1) {
reset(true);
error(ErrProxyNeg);
return;
}
else if(r == 1) {
if(s.cmd != RET_SUCCESS) {
#ifdef PROX_DEBUG
fprintf(stderr, "SocksClient: client << Error >> [%02x]\n", s.cmd);
#endif
reset(true);
if(s.cmd == RET_UNREACHABLE)
error(ErrHostNotFound);
else if(s.cmd == RET_CONNREFUSED)
error(ErrConnectionRefused);
else
error(ErrProxyNeg);
return;
}
#ifdef PROX_DEBUG
fprintf(stderr, "SocksClient: client << Success >>\n");
#endif
if(d->udp) {
if(s.address_type == 0x03)
d->udpAddr = s.host;
else
d->udpAddr = s.addr.toString();
d->udpPort = s.port;
}
d->active = true;
QPointer<QObject> self = this;
connected();
if(!self)
return;
if(!d->recvBuf.isEmpty()) {
appendRead(d->recvBuf);
d->recvBuf.resize(0);
readyRead();
}
}
}
}
void SocksClient::do_request()
{
#ifdef PROX_DEBUG
fprintf(stderr, "SocksClient: Requesting ...\n");
#endif
d->step = StepRequest;
int cmd = d->udp ? REQ_UDPASSOCIATE : REQ_CONNECT;
QByteArray buf;
if(!d->real_host.isEmpty())
buf = sp_set_request(d->real_host, d->real_port, cmd);
else
buf = sp_set_request(QHostAddress(), 0, cmd);
writeData(buf);
}
void SocksClient::sock_bytesWritten(int x)
{
int bytes = x;
if(d->pending >= bytes) {
d->pending -= bytes;
bytes = 0;
}
else {
bytes -= d->pending;
d->pending = 0;
}
if(bytes > 0)
bytesWritten(bytes);
}
void SocksClient::sock_error(int x)
{
if(d->active) {
reset();
error(ErrRead);
}
else {
reset(true);
if(x == BSocket::ErrHostNotFound)
error(ErrProxyConnect);
else if(x == BSocket::ErrConnectionRefused)
error(ErrProxyConnect);
else if(x == BSocket::ErrRead)
error(ErrProxyNeg);
}
}
void SocksClient::serve()
{
d->waiting = false;
d->step = StepVersion;
continueIncoming();
}
void SocksClient::processIncoming(const QByteArray &block)
{
#ifdef PROX_DEBUG
// show hex
fprintf(stderr, "SocksClient: server recv { ");
for(int n = 0; n < (int)block.size(); ++n)
fprintf(stderr, "%02X ", (unsigned char)block[n]);
fprintf(stderr, " } \n");
#endif
ByteStream::appendArray(&d->recvBuf, block);
if(!d->waiting)
continueIncoming();
}
void SocksClient::continueIncoming()
{
if(d->recvBuf.isEmpty())
return;
if(d->step == StepVersion) {
SPCS_VERSION s;
int r = spc_get_version(&d->recvBuf, &s);
if(r == -1) {
reset(true);
error(ErrProxyNeg);
return;
}
else if(r == 1) {
if(s.version != 0x05) {
reset(true);
error(ErrProxyNeg);
return;
}
int methods = 0;
for(int n = 0; n < (int)s.methodList.size(); ++n) {
unsigned char c = s.methodList[n];
if(c == 0x00)
methods |= AuthNone;
else if(c == 0x02)
methods |= AuthUsername;
}
d->waiting = true;
incomingMethods(methods);
}
}
else if(d->step == StepAuth) {
SPCS_AUTHUSERNAME s;
int r = spc_get_authUsername(&d->recvBuf, &s);
if(r == -1) {
reset(true);
error(ErrProxyNeg);
return;
}
else if(r == 1) {
d->waiting = true;
incomingAuth(s.user, s.pass);
}
}
else if(d->step == StepRequest) {
SPS_CONNREQ s;
int r = sp_get_request(&d->recvBuf, &s);
if(r == -1) {
reset(true);
error(ErrProxyNeg);
return;
}
else if(r == 1) {
d->waiting = true;
if(s.cmd == REQ_CONNECT) {
if(!s.host.isEmpty())
d->rhost = s.host;
else
d->rhost = s.addr.toString();
d->rport = s.port;
incomingConnectRequest(d->rhost, d->rport);
}
else if(s.cmd == REQ_UDPASSOCIATE) {
incomingUDPAssociateRequest();
}
else {
requestDeny();
return;
}
}
}
}
void SocksClient::chooseMethod(int method)
{
if(d->step != StepVersion || !d->waiting)
return;
unsigned char c;
if(method == AuthNone) {
d->step = StepRequest;
c = 0x00;
}
else {
d->step = StepAuth;
c = 0x02;
}
// version response
d->waiting = false;
writeData(sps_set_version(c));
continueIncoming();
}
void SocksClient::authGrant(bool b)
{
if(d->step != StepAuth || !d->waiting)
return;
if(b)
d->step = StepRequest;
// auth response
d->waiting = false;
writeData(sps_set_authUsername(b));
if(!b) {
reset(true);
return;
}
continueIncoming();
}
void SocksClient::requestDeny()
{
if(d->step != StepRequest || !d->waiting)
return;
// response
d->waiting = false;
writeData(sp_set_request(d->rhost, d->rport, RET_UNREACHABLE));
reset(true);
}
void SocksClient::grantConnect()
{
if(d->step != StepRequest || !d->waiting)
return;
// response
d->waiting = false;
writeData(sp_set_request(d->rhost, d->rport, RET_SUCCESS));
d->active = true;
#ifdef PROX_DEBUG
fprintf(stderr, "SocksClient: server << Success >>\n");
#endif
if(!d->recvBuf.isEmpty()) {
appendRead(d->recvBuf);
d->recvBuf.resize(0);
readyRead();
}
}
void SocksClient::grantUDPAssociate(const QString &relayHost, int relayPort)
{
if(d->step != StepRequest || !d->waiting)
return;
// response
d->waiting = false;
writeData(sp_set_request(relayHost, relayPort, RET_SUCCESS));
d->udp = true;
d->active = true;
#ifdef PROX_DEBUG
fprintf(stderr, "SocksClient: server << Success >>\n");
#endif
if(!d->recvBuf.isEmpty())
d->recvBuf.resize(0);
}
QHostAddress SocksClient::peerAddress() const
{
return d->sock.peerAddress();
}
Q_UINT16 SocksClient::peerPort() const
{
return d->sock.peerPort();
}
QString SocksClient::udpAddress() const
{
return d->udpAddr;
}
Q_UINT16 SocksClient::udpPort() const
{
return d->udpPort;
}
SocksUDP *SocksClient::createUDP(const QString &host, int port, const QHostAddress &routeAddr, int routePort)
{
return new SocksUDP(this, host, port, routeAddr, routePort);
}
//----------------------------------------------------------------------------
// SocksServer
//----------------------------------------------------------------------------
class SocksServer::Private
{
public:
Private() {}
ServSock serv;
Q3PtrList<SocksClient> incomingConns;
Q3SocketDevice *sd;
QSocketNotifier *sn;
};
SocksServer::SocksServer(QObject *parent)
:QObject(parent)
{
d = new Private;
d->sd = 0;
d->sn = 0;
connect(&d->serv, SIGNAL(connectionReady(int)), SLOT(connectionReady(int)));
}
SocksServer::~SocksServer()
{
stop();
d->incomingConns.setAutoDelete(true);
d->incomingConns.clear();
delete d;
}
bool SocksServer::isActive() const
{
return d->serv.isActive();
}
bool SocksServer::listen(Q_UINT16 port, bool udp)
{
stop();
if(!d->serv.listen(port))
return false;
if(udp) {
d->sd = new Q3SocketDevice(Q3SocketDevice::Datagram);
#ifdef Q_OS_UNIX
::fcntl(d->sd->socket(), F_SETFD, FD_CLOEXEC);
#endif
d->sd->setBlocking(false);
if(!d->sd->bind(QHostAddress(), port)) {
delete d->sd;
d->sd = 0;
d->serv.stop();
return false;
}
d->sn = new QSocketNotifier(d->sd->socket(), QSocketNotifier::Read);
connect(d->sn, SIGNAL(activated(int)), SLOT(sn_activated(int)));
}
return true;
}
void SocksServer::stop()
{
delete d->sn;
d->sn = 0;
delete d->sd;
d->sd = 0;
d->serv.stop();
}
int SocksServer::port() const
{
return d->serv.port();
}
QHostAddress SocksServer::address() const
{
return d->serv.address();
}
SocksClient *SocksServer::takeIncoming()
{
if(d->incomingConns.isEmpty())
return 0;
SocksClient *c = d->incomingConns.getFirst();
d->incomingConns.removeRef(c);
// we don't care about errors anymore
disconnect(c, SIGNAL(error(int)), this, SLOT(connectionError()));
// don't serve the connection until the event loop, to give the caller a chance to map signals
QTimer::singleShot(0, c, SLOT(serve()));
return c;
}
void SocksServer::writeUDP(const QHostAddress &addr, int port, const QByteArray &data)
{
if(d->sd) {
d->sd->setBlocking(true);
d->sd->writeBlock(data.data(), data.size(), addr, port);
d->sd->setBlocking(false);
}
}
void SocksServer::connectionReady(int s)
{
SocksClient *c = new SocksClient(s, this);
connect(c, SIGNAL(error(int)), this, SLOT(connectionError()));
d->incomingConns.append(c);
incomingReady();
}
void SocksServer::connectionError()
{
SocksClient *c = (SocksClient *)sender();
d->incomingConns.removeRef(c);
c->deleteLater();
}
void SocksServer::sn_activated(int)
{
QByteArray buf(8192);
int actual = d->sd->readBlock(buf.data(), buf.size());
buf.resize(actual);
QHostAddress pa = d->sd->peerAddress();
int pp = d->sd->peerPort();
SPS_UDP s;
int r = sp_read_udp(&buf, &s);
if(r != 1)
return;
incomingUDP(s.host, s.port, pa, pp, s.data);
}
// CS_NAMESPACE_END
|