socksd.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. ***************************************************************************/
  22. #include "server_setup.h"
  23. #include <stdlib.h>
  24. /* Function
  25. *
  26. * Accepts a TCP connection on a custom port (IPv4 or IPv6). Connects to a
  27. * given addr + port backend (that is NOT extracted form the client's
  28. * request). The backend server default to connect to can be set with
  29. * --backend and --backendport.
  30. *
  31. * Read commands from FILE (set with --config). The commands control how to
  32. * act and is reset to defaults each client TCP connect.
  33. *
  34. * Config file keywords:
  35. *
  36. * "version [number: 5]" - requires the communication to use this version.
  37. * "nmethods_min [number: 1]" - the minimum numberf NMETHODS the client must
  38. * state
  39. * "nmethods_max [number: 3]" - the minimum numberf NMETHODS the client must
  40. * state
  41. * "user [string]" - the user name that must match (if method is 2)
  42. * "password [string]" - the password that must match (if method is 2)
  43. * "backend [IPv4]" - numerical IPv4 address of backend to connect to
  44. * "backendport [number:0]" - TCP port of backend to connect to. 0 means use
  45. the client's specified port number.
  46. * "method [number: 0]" - connect method to respond with:
  47. * 0 - no auth
  48. * 1 - GSSAPI (not supported)
  49. * 2 - user + password
  50. * "response [number]" - the decimal number to respond to a connect
  51. * SOCKS5: 0 is OK, SOCKS4: 90 is ok
  52. *
  53. */
  54. /* based on sockfilt.c */
  55. #ifdef HAVE_SIGNAL_H
  56. #include <signal.h>
  57. #endif
  58. #ifdef HAVE_NETINET_IN_H
  59. #include <netinet/in.h>
  60. #endif
  61. #ifdef HAVE_NETINET_IN6_H
  62. #include <netinet/in6.h>
  63. #endif
  64. #ifdef HAVE_ARPA_INET_H
  65. #include <arpa/inet.h>
  66. #endif
  67. #ifdef HAVE_NETDB_H
  68. #include <netdb.h>
  69. #endif
  70. #define ENABLE_CURLX_PRINTF
  71. /* make the curlx header define all printf() functions to use the curlx_*
  72. versions instead */
  73. #include "curlx.h" /* from the private lib dir */
  74. #include "getpart.h"
  75. #include "inet_pton.h"
  76. #include "util.h"
  77. #include "server_sockaddr.h"
  78. #include "warnless.h"
  79. /* include memdebug.h last */
  80. #include "memdebug.h"
  81. #ifdef USE_WINSOCK
  82. #undef EINTR
  83. #define EINTR 4 /* errno.h value */
  84. #undef EAGAIN
  85. #define EAGAIN 11 /* errno.h value */
  86. #undef ENOMEM
  87. #define ENOMEM 12 /* errno.h value */
  88. #undef EINVAL
  89. #define EINVAL 22 /* errno.h value */
  90. #endif
  91. #define DEFAULT_PORT 8905
  92. #ifndef DEFAULT_LOGFILE
  93. #define DEFAULT_LOGFILE "log/socksd.log"
  94. #endif
  95. #ifndef DEFAULT_CONFIG
  96. #define DEFAULT_CONFIG "socksd.config"
  97. #endif
  98. static const char *backendaddr = "127.0.0.1";
  99. static unsigned short backendport = 0; /* default is use client's */
  100. struct configurable {
  101. unsigned char version; /* initial version byte in the request must match
  102. this */
  103. unsigned char nmethods_min; /* minimum number of nmethods to expect */
  104. unsigned char nmethods_max; /* maximum number of nmethods to expect */
  105. unsigned char responseversion;
  106. unsigned char responsemethod;
  107. unsigned char reqcmd;
  108. unsigned char connectrep;
  109. unsigned short port; /* backend port */
  110. char addr[32]; /* backend IPv4 numerical */
  111. char user[256];
  112. char password[256];
  113. };
  114. #define CONFIG_VERSION 5
  115. #define CONFIG_NMETHODS_MIN 1 /* unauth, gssapi, auth */
  116. #define CONFIG_NMETHODS_MAX 3
  117. #define CONFIG_RESPONSEVERSION CONFIG_VERSION
  118. #define CONFIG_RESPONSEMETHOD 0 /* no auth */
  119. #define CONFIG_REQCMD 1 /* CONNECT */
  120. #define CONFIG_PORT backendport
  121. #define CONFIG_ADDR backendaddr
  122. #define CONFIG_CONNECTREP 0
  123. static struct configurable config;
  124. const char *serverlogfile = DEFAULT_LOGFILE;
  125. static const char *configfile = DEFAULT_CONFIG;
  126. #ifdef ENABLE_IPV6
  127. static bool use_ipv6 = FALSE;
  128. #endif
  129. static const char *ipv_inuse = "IPv4";
  130. static unsigned short port = DEFAULT_PORT;
  131. static void resetdefaults(void)
  132. {
  133. logmsg("Reset to defaults");
  134. config.version = CONFIG_VERSION;
  135. config.nmethods_min = CONFIG_NMETHODS_MIN;
  136. config.nmethods_max = CONFIG_NMETHODS_MAX;
  137. config.responseversion = CONFIG_RESPONSEVERSION;
  138. config.responsemethod = CONFIG_RESPONSEMETHOD;
  139. config.reqcmd = CONFIG_REQCMD;
  140. config.connectrep = CONFIG_CONNECTREP;
  141. config.port = CONFIG_PORT;
  142. strcpy(config.addr, CONFIG_ADDR);
  143. strcpy(config.user, "user");
  144. strcpy(config.password, "password");
  145. }
  146. static unsigned char byteval(char *value)
  147. {
  148. unsigned long num = strtoul(value, NULL, 10);
  149. return num & 0xff;
  150. }
  151. static unsigned short shortval(char *value)
  152. {
  153. unsigned long num = strtoul(value, NULL, 10);
  154. return num & 0xffff;
  155. }
  156. static void getconfig(void)
  157. {
  158. FILE *fp = fopen(configfile, FOPEN_READTEXT);
  159. resetdefaults();
  160. if(fp) {
  161. char buffer[512];
  162. logmsg("parse config file");
  163. while(fgets(buffer, sizeof(buffer), fp)) {
  164. char key[32];
  165. char value[32];
  166. if(2 == sscanf(buffer, "%31s %31s", key, value)) {
  167. if(!strcmp(key, "version")) {
  168. config.version = byteval(value);
  169. logmsg("version [%d] set", config.version);
  170. }
  171. else if(!strcmp(key, "nmethods_min")) {
  172. config.nmethods_min = byteval(value);
  173. logmsg("nmethods_min [%d] set", config.nmethods_min);
  174. }
  175. else if(!strcmp(key, "nmethods_max")) {
  176. config.nmethods_max = byteval(value);
  177. logmsg("nmethods_max [%d] set", config.nmethods_max);
  178. }
  179. else if(!strcmp(key, "backend")) {
  180. strcpy(config.addr, value);
  181. logmsg("backend [%s] set", config.addr);
  182. }
  183. else if(!strcmp(key, "backendport")) {
  184. config.port = shortval(value);
  185. logmsg("backendport [%d] set", config.port);
  186. }
  187. else if(!strcmp(key, "user")) {
  188. strcpy(config.user, value);
  189. logmsg("user [%s] set", config.user);
  190. }
  191. else if(!strcmp(key, "password")) {
  192. strcpy(config.password, value);
  193. logmsg("password [%s] set", config.password);
  194. }
  195. /* Methods:
  196. o X'00' NO AUTHENTICATION REQUIRED
  197. o X'01' GSSAPI
  198. o X'02' USERNAME/PASSWORD
  199. */
  200. else if(!strcmp(key, "method")) {
  201. config.responsemethod = byteval(value);
  202. logmsg("method [%d] set", config.responsemethod);
  203. }
  204. else if(!strcmp(key, "response")) {
  205. config.connectrep = byteval(value);
  206. logmsg("response [%d] set", config.connectrep);
  207. }
  208. }
  209. }
  210. fclose(fp);
  211. }
  212. }
  213. static void loghex(unsigned char *buffer, ssize_t len)
  214. {
  215. char data[1200];
  216. ssize_t i;
  217. unsigned char *ptr = buffer;
  218. char *optr = data;
  219. ssize_t width = 0;
  220. int left = sizeof(data);
  221. for(i = 0; i<len && (left >= 0); i++) {
  222. msnprintf(optr, left, "%02x", ptr[i]);
  223. width += 2;
  224. optr += 2;
  225. left -= 2;
  226. }
  227. if(width)
  228. logmsg("'%s'", data);
  229. }
  230. /* RFC 1928, SOCKS5 byte index */
  231. #define SOCKS5_VERSION 0
  232. #define SOCKS5_NMETHODS 1 /* number of methods that is listed */
  233. /* in the request: */
  234. #define SOCKS5_REQCMD 1
  235. #define SOCKS5_RESERVED 2
  236. #define SOCKS5_ATYP 3
  237. #define SOCKS5_DSTADDR 4
  238. /* connect response */
  239. #define SOCKS5_REP 1
  240. #define SOCKS5_BNDADDR 4
  241. /* auth request */
  242. #define SOCKS5_ULEN 1
  243. #define SOCKS5_UNAME 2
  244. #define SOCKS4_CD 1
  245. #define SOCKS4_DSTPORT 2
  246. /* connect to a given IPv4 address, not the one asked for */
  247. static curl_socket_t socksconnect(unsigned short connectport,
  248. const char *connectaddr)
  249. {
  250. int rc;
  251. srvr_sockaddr_union_t me;
  252. curl_socket_t sock = socket(AF_INET, SOCK_STREAM, 0);
  253. if(sock == CURL_SOCKET_BAD)
  254. return CURL_SOCKET_BAD;
  255. memset(&me.sa4, 0, sizeof(me.sa4));
  256. me.sa4.sin_family = AF_INET;
  257. me.sa4.sin_port = htons(connectport);
  258. me.sa4.sin_addr.s_addr = INADDR_ANY;
  259. Curl_inet_pton(AF_INET, connectaddr, &me.sa4.sin_addr);
  260. rc = connect(sock, &me.sa, sizeof(me.sa4));
  261. if(rc) {
  262. int error = SOCKERRNO;
  263. logmsg("Error connecting to %s:%hu: (%d) %s",
  264. connectaddr, connectport, error, strerror(error));
  265. return CURL_SOCKET_BAD;
  266. }
  267. logmsg("Connected fine to %s:%d", connectaddr, connectport);
  268. return sock;
  269. }
  270. static curl_socket_t socks4(curl_socket_t fd,
  271. unsigned char *buffer,
  272. ssize_t rc)
  273. {
  274. unsigned char response[256 + 16];
  275. curl_socket_t connfd;
  276. unsigned char cd;
  277. unsigned short s4port;
  278. if(buffer[SOCKS4_CD] != 1) {
  279. logmsg("SOCKS4 CD is not 1: %d", buffer[SOCKS4_CD]);
  280. return CURL_SOCKET_BAD;
  281. }
  282. if(rc < 9) {
  283. logmsg("SOCKS4 connect message too short: %d", rc);
  284. return CURL_SOCKET_BAD;
  285. }
  286. if(!config.port)
  287. s4port = (unsigned short)((buffer[SOCKS4_DSTPORT]<<8) |
  288. (buffer[SOCKS4_DSTPORT + 1]));
  289. else
  290. s4port = config.port;
  291. connfd = socksconnect(s4port, config.addr);
  292. if(connfd == CURL_SOCKET_BAD) {
  293. /* failed */
  294. cd = 91;
  295. }
  296. else {
  297. /* success */
  298. cd = 90;
  299. }
  300. response[0] = 0; /* reply version 0 */
  301. response[1] = cd; /* result */
  302. /* copy port and address from connect request */
  303. memcpy(&response[2], &buffer[SOCKS4_DSTPORT], 6);
  304. rc = (send)(fd, (char *)response, 8, 0);
  305. if(rc != 8) {
  306. logmsg("Sending SOCKS4 response failed!");
  307. return CURL_SOCKET_BAD;
  308. }
  309. logmsg("Sent %d bytes", rc);
  310. loghex(response, rc);
  311. if(cd == 90)
  312. /* now do the transfer */
  313. return connfd;
  314. if(connfd != CURL_SOCKET_BAD)
  315. sclose(connfd);
  316. return CURL_SOCKET_BAD;
  317. }
  318. static curl_socket_t sockit(curl_socket_t fd)
  319. {
  320. unsigned char buffer[256 + 16];
  321. unsigned char response[256 + 16];
  322. ssize_t rc;
  323. unsigned char len;
  324. unsigned char type;
  325. unsigned char rep = 0;
  326. unsigned char *address;
  327. unsigned short socksport;
  328. curl_socket_t connfd = CURL_SOCKET_BAD;
  329. unsigned short s5port;
  330. getconfig();
  331. rc = recv(fd, (char *)buffer, sizeof(buffer), 0);
  332. logmsg("READ %d bytes", rc);
  333. loghex(buffer, rc);
  334. if(buffer[SOCKS5_VERSION] == 4)
  335. return socks4(fd, buffer, rc);
  336. if(buffer[SOCKS5_VERSION] != config.version) {
  337. logmsg("VERSION byte not %d", config.version);
  338. return CURL_SOCKET_BAD;
  339. }
  340. if((buffer[SOCKS5_NMETHODS] < config.nmethods_min) ||
  341. (buffer[SOCKS5_NMETHODS] > config.nmethods_max)) {
  342. logmsg("NMETHODS byte not within %d - %d ",
  343. config.nmethods_min, config.nmethods_max);
  344. return CURL_SOCKET_BAD;
  345. }
  346. /* after NMETHODS follows that many bytes listing the methods the client
  347. says it supports */
  348. if(rc != (buffer[SOCKS5_NMETHODS] + 2)) {
  349. logmsg("Expected %d bytes, got %d", buffer[SOCKS5_NMETHODS] + 2, rc);
  350. return CURL_SOCKET_BAD;
  351. }
  352. logmsg("Incoming request deemed fine!");
  353. /* respond with two bytes: VERSION + METHOD */
  354. response[0] = config.responseversion;
  355. response[1] = config.responsemethod;
  356. rc = (send)(fd, (char *)response, 2, 0);
  357. if(rc != 2) {
  358. logmsg("Sending response failed!");
  359. return CURL_SOCKET_BAD;
  360. }
  361. logmsg("Sent %d bytes", rc);
  362. loghex(response, rc);
  363. /* expect the request or auth */
  364. rc = recv(fd, (char *)buffer, sizeof(buffer), 0);
  365. logmsg("READ %d bytes", rc);
  366. loghex(buffer, rc);
  367. if(config.responsemethod == 2) {
  368. /* RFC 1929 authentication
  369. +----+------+----------+------+----------+
  370. |VER | ULEN | UNAME | PLEN | PASSWD |
  371. +----+------+----------+------+----------+
  372. | 1 | 1 | 1 to 255 | 1 | 1 to 255 |
  373. +----+------+----------+------+----------+
  374. */
  375. unsigned char ulen;
  376. unsigned char plen;
  377. bool login = TRUE;
  378. if(rc < 5) {
  379. logmsg("Too short auth input: %d", rc);
  380. return CURL_SOCKET_BAD;
  381. }
  382. if(buffer[SOCKS5_VERSION] != 1) {
  383. logmsg("Auth VERSION byte not 1, got %d", buffer[SOCKS5_VERSION]);
  384. return CURL_SOCKET_BAD;
  385. }
  386. ulen = buffer[SOCKS5_ULEN];
  387. if(rc < 4 + ulen) {
  388. logmsg("Too short packet for username: %d", rc);
  389. return CURL_SOCKET_BAD;
  390. }
  391. plen = buffer[SOCKS5_ULEN + ulen + 1];
  392. if(rc < 3 + ulen + plen) {
  393. logmsg("Too short packet for ulen %d plen %d: %d", ulen, plen, rc);
  394. return CURL_SOCKET_BAD;
  395. }
  396. if((ulen != strlen(config.user)) ||
  397. (plen != strlen(config.password)) ||
  398. memcmp(&buffer[SOCKS5_UNAME], config.user, ulen) ||
  399. memcmp(&buffer[SOCKS5_UNAME + ulen + 1], config.password, plen)) {
  400. /* no match! */
  401. logmsg("mismatched credentials!");
  402. login = FALSE;
  403. }
  404. response[0] = 1;
  405. response[1] = login ? 0 : 1;
  406. rc = (send)(fd, (char *)response, 2, 0);
  407. if(rc != 2) {
  408. logmsg("Sending auth response failed!");
  409. return CURL_SOCKET_BAD;
  410. }
  411. logmsg("Sent %d bytes", rc);
  412. loghex(response, rc);
  413. if(!login)
  414. return CURL_SOCKET_BAD;
  415. /* expect the request */
  416. rc = recv(fd, (char *)buffer, sizeof(buffer), 0);
  417. logmsg("READ %d bytes", rc);
  418. loghex(buffer, rc);
  419. }
  420. if(rc < 6) {
  421. logmsg("Too short for request: %d", rc);
  422. return CURL_SOCKET_BAD;
  423. }
  424. if(buffer[SOCKS5_VERSION] != config.version) {
  425. logmsg("Request VERSION byte not %d", config.version);
  426. return CURL_SOCKET_BAD;
  427. }
  428. /* 1 == CONNECT */
  429. if(buffer[SOCKS5_REQCMD] != config.reqcmd) {
  430. logmsg("Request COMMAND byte not %d", config.reqcmd);
  431. return CURL_SOCKET_BAD;
  432. }
  433. /* reserved, should be zero */
  434. if(buffer[SOCKS5_RESERVED]) {
  435. logmsg("Request COMMAND byte not %d", config.reqcmd);
  436. return CURL_SOCKET_BAD;
  437. }
  438. /* ATYP:
  439. o IP V4 address: X'01'
  440. o DOMAINNAME: X'03'
  441. o IP V6 address: X'04'
  442. */
  443. type = buffer[SOCKS5_ATYP];
  444. address = &buffer[SOCKS5_DSTADDR];
  445. switch(type) {
  446. case 1:
  447. /* 4 bytes IPv4 address */
  448. len = 4;
  449. break;
  450. case 3:
  451. /* The first octet of the address field contains the number of octets of
  452. name that follow */
  453. len = buffer[SOCKS5_DSTADDR];
  454. len++;
  455. break;
  456. case 4:
  457. /* 16 bytes IPv6 address */
  458. len = 16;
  459. break;
  460. default:
  461. logmsg("Unknown ATYP %d", type);
  462. return CURL_SOCKET_BAD;
  463. }
  464. if(rc < (4 + len + 2)) {
  465. logmsg("Request too short: %d, expected %d", rc, 4 + len + 2);
  466. return CURL_SOCKET_BAD;
  467. }
  468. if(!config.port) {
  469. unsigned char *portp = &buffer[SOCKS5_DSTADDR + len];
  470. s5port = (unsigned short)((portp[0]<<8) | (portp[1]));
  471. }
  472. else
  473. s5port = config.port;
  474. if(!config.connectrep)
  475. connfd = socksconnect(s5port, config.addr);
  476. if(connfd == CURL_SOCKET_BAD) {
  477. /* failed */
  478. rep = 1;
  479. }
  480. else {
  481. rep = config.connectrep;
  482. }
  483. /* */
  484. response[SOCKS5_VERSION] = config.responseversion;
  485. /*
  486. o REP Reply field:
  487. o X'00' succeeded
  488. o X'01' general SOCKS server failure
  489. o X'02' connection not allowed by ruleset
  490. o X'03' Network unreachable
  491. o X'04' Host unreachable
  492. o X'05' Connection refused
  493. o X'06' TTL expired
  494. o X'07' Command not supported
  495. o X'08' Address type not supported
  496. o X'09' to X'FF' unassigned
  497. */
  498. response[SOCKS5_REP] = rep;
  499. response[SOCKS5_RESERVED] = 0; /* must be zero */
  500. response[SOCKS5_ATYP] = type; /* address type */
  501. /* mirror back the original addr + port */
  502. /* address or hostname */
  503. memcpy(&response[SOCKS5_BNDADDR], address, len);
  504. /* port number */
  505. memcpy(&response[SOCKS5_BNDADDR + len],
  506. &buffer[SOCKS5_DSTADDR + len], sizeof(socksport));
  507. rc = (send)(fd, (char *)response, len + 6, 0);
  508. if(rc != (len + 6)) {
  509. logmsg("Sending connect response failed!");
  510. return CURL_SOCKET_BAD;
  511. }
  512. logmsg("Sent %d bytes", rc);
  513. loghex(response, rc);
  514. if(!rep)
  515. return connfd;
  516. if(connfd != CURL_SOCKET_BAD)
  517. sclose(connfd);
  518. return CURL_SOCKET_BAD;
  519. }
  520. struct perclient {
  521. size_t fromremote;
  522. size_t fromclient;
  523. curl_socket_t remotefd;
  524. curl_socket_t clientfd;
  525. bool used;
  526. };
  527. /* return non-zero when transfer is done */
  528. static int tunnel(struct perclient *cp, fd_set *fds)
  529. {
  530. ssize_t nread;
  531. ssize_t nwrite;
  532. char buffer[512];
  533. if(FD_ISSET(cp->clientfd, fds)) {
  534. /* read from client, send to remote */
  535. nread = recv(cp->clientfd, buffer, sizeof(buffer), 0);
  536. if(nread > 0) {
  537. nwrite = send(cp->remotefd, (char *)buffer,
  538. (SEND_TYPE_ARG3)nread, 0);
  539. if(nwrite != nread)
  540. return 1;
  541. cp->fromclient += nwrite;
  542. }
  543. else
  544. return 1;
  545. }
  546. if(FD_ISSET(cp->remotefd, fds)) {
  547. /* read from remote, send to client */
  548. nread = recv(cp->remotefd, buffer, sizeof(buffer), 0);
  549. if(nread > 0) {
  550. nwrite = send(cp->clientfd, (char *)buffer,
  551. (SEND_TYPE_ARG3)nread, 0);
  552. if(nwrite != nread)
  553. return 1;
  554. cp->fromremote += nwrite;
  555. }
  556. else
  557. return 1;
  558. }
  559. return 0;
  560. }
  561. /*
  562. sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
  563. if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
  564. accept()
  565. */
  566. static bool incoming(curl_socket_t listenfd)
  567. {
  568. fd_set fds_read;
  569. fd_set fds_write;
  570. fd_set fds_err;
  571. int clients = 0; /* connected clients */
  572. struct perclient c[2];
  573. memset(c, 0, sizeof(c));
  574. if(got_exit_signal) {
  575. logmsg("signalled to die, exiting...");
  576. return FALSE;
  577. }
  578. #ifdef HAVE_GETPPID
  579. /* As a last resort, quit if socks5 process becomes orphan. */
  580. if(getppid() <= 1) {
  581. logmsg("process becomes orphan, exiting");
  582. return FALSE;
  583. }
  584. #endif
  585. do {
  586. int i;
  587. ssize_t rc;
  588. int error = 0;
  589. curl_socket_t sockfd = listenfd;
  590. int maxfd = (int)sockfd;
  591. FD_ZERO(&fds_read);
  592. FD_ZERO(&fds_write);
  593. FD_ZERO(&fds_err);
  594. /* there's always a socket to wait for */
  595. FD_SET(sockfd, &fds_read);
  596. for(i = 0; i < 2; i++) {
  597. if(c[i].used) {
  598. curl_socket_t fd = c[i].clientfd;
  599. FD_SET(fd, &fds_read);
  600. if((int)fd > maxfd)
  601. maxfd = (int)fd;
  602. fd = c[i].remotefd;
  603. FD_SET(fd, &fds_read);
  604. if((int)fd > maxfd)
  605. maxfd = (int)fd;
  606. }
  607. }
  608. do {
  609. /* select() blocking behavior call on blocking descriptors please */
  610. rc = select(maxfd + 1, &fds_read, &fds_write, &fds_err, NULL);
  611. if(got_exit_signal) {
  612. logmsg("signalled to die, exiting...");
  613. return FALSE;
  614. }
  615. } while((rc == -1) && ((error = errno) == EINTR));
  616. if(rc < 0) {
  617. logmsg("select() failed with error: (%d) %s",
  618. error, strerror(error));
  619. return FALSE;
  620. }
  621. if((clients < 2) && FD_ISSET(sockfd, &fds_read)) {
  622. curl_socket_t newfd = accept(sockfd, NULL, NULL);
  623. if(CURL_SOCKET_BAD == newfd) {
  624. error = SOCKERRNO;
  625. logmsg("accept(%d, NULL, NULL) failed with error: (%d) %s",
  626. sockfd, error, strerror(error));
  627. }
  628. else {
  629. curl_socket_t remotefd;
  630. logmsg("====> Client connect, fd %d. Read config from %s",
  631. newfd, configfile);
  632. remotefd = sockit(newfd); /* SOCKS until done */
  633. if(remotefd == CURL_SOCKET_BAD) {
  634. logmsg("====> Client disconnect");
  635. sclose(newfd);
  636. }
  637. else {
  638. struct perclient *cp = &c[0];
  639. logmsg("====> Tunnel transfer");
  640. if(c[0].used)
  641. cp = &c[1];
  642. cp->fromremote = 0;
  643. cp->fromclient = 0;
  644. cp->clientfd = newfd;
  645. cp->remotefd = remotefd;
  646. cp->used = TRUE;
  647. clients++;
  648. }
  649. }
  650. }
  651. for(i = 0; i < 2; i++) {
  652. struct perclient *cp = &c[i];
  653. if(cp->used) {
  654. if(tunnel(cp, &fds_read)) {
  655. logmsg("SOCKS transfer completed. Bytes: < %zu > %zu",
  656. cp->fromremote, cp->fromclient);
  657. sclose(cp->clientfd);
  658. sclose(cp->remotefd);
  659. cp->used = FALSE;
  660. clients--;
  661. }
  662. }
  663. }
  664. } while(clients);
  665. return TRUE;
  666. }
  667. static curl_socket_t sockdaemon(curl_socket_t sock,
  668. unsigned short *listenport)
  669. {
  670. /* passive daemon style */
  671. srvr_sockaddr_union_t listener;
  672. int flag;
  673. int rc;
  674. int totdelay = 0;
  675. int maxretr = 10;
  676. int delay = 20;
  677. int attempt = 0;
  678. int error = 0;
  679. do {
  680. attempt++;
  681. flag = 1;
  682. rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
  683. (void *)&flag, sizeof(flag));
  684. if(rc) {
  685. error = SOCKERRNO;
  686. logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
  687. error, strerror(error));
  688. if(maxretr) {
  689. rc = wait_ms(delay);
  690. if(rc) {
  691. /* should not happen */
  692. error = errno;
  693. logmsg("wait_ms() failed with error: (%d) %s",
  694. error, strerror(error));
  695. sclose(sock);
  696. return CURL_SOCKET_BAD;
  697. }
  698. if(got_exit_signal) {
  699. logmsg("signalled to die, exiting...");
  700. sclose(sock);
  701. return CURL_SOCKET_BAD;
  702. }
  703. totdelay += delay;
  704. delay *= 2; /* double the sleep for next attempt */
  705. }
  706. }
  707. } while(rc && maxretr--);
  708. if(rc) {
  709. logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
  710. attempt, totdelay, error, strerror(error));
  711. logmsg("Continuing anyway...");
  712. }
  713. /* When the specified listener port is zero, it is actually a
  714. request to let the system choose a non-zero available port. */
  715. #ifdef ENABLE_IPV6
  716. if(!use_ipv6) {
  717. #endif
  718. memset(&listener.sa4, 0, sizeof(listener.sa4));
  719. listener.sa4.sin_family = AF_INET;
  720. listener.sa4.sin_addr.s_addr = INADDR_ANY;
  721. listener.sa4.sin_port = htons(*listenport);
  722. rc = bind(sock, &listener.sa, sizeof(listener.sa4));
  723. #ifdef ENABLE_IPV6
  724. }
  725. else {
  726. memset(&listener.sa6, 0, sizeof(listener.sa6));
  727. listener.sa6.sin6_family = AF_INET6;
  728. listener.sa6.sin6_addr = in6addr_any;
  729. listener.sa6.sin6_port = htons(*listenport);
  730. rc = bind(sock, &listener.sa, sizeof(listener.sa6));
  731. }
  732. #endif /* ENABLE_IPV6 */
  733. if(rc) {
  734. error = SOCKERRNO;
  735. logmsg("Error binding socket on port %hu: (%d) %s",
  736. *listenport, error, strerror(error));
  737. sclose(sock);
  738. return CURL_SOCKET_BAD;
  739. }
  740. if(!*listenport) {
  741. /* The system was supposed to choose a port number, figure out which
  742. port we actually got and update the listener port value with it. */
  743. curl_socklen_t la_size;
  744. srvr_sockaddr_union_t localaddr;
  745. #ifdef ENABLE_IPV6
  746. if(!use_ipv6)
  747. #endif
  748. la_size = sizeof(localaddr.sa4);
  749. #ifdef ENABLE_IPV6
  750. else
  751. la_size = sizeof(localaddr.sa6);
  752. #endif
  753. memset(&localaddr.sa, 0, (size_t)la_size);
  754. if(getsockname(sock, &localaddr.sa, &la_size) < 0) {
  755. error = SOCKERRNO;
  756. logmsg("getsockname() failed with error: (%d) %s",
  757. error, strerror(error));
  758. sclose(sock);
  759. return CURL_SOCKET_BAD;
  760. }
  761. switch(localaddr.sa.sa_family) {
  762. case AF_INET:
  763. *listenport = ntohs(localaddr.sa4.sin_port);
  764. break;
  765. #ifdef ENABLE_IPV6
  766. case AF_INET6:
  767. *listenport = ntohs(localaddr.sa6.sin6_port);
  768. break;
  769. #endif
  770. default:
  771. break;
  772. }
  773. if(!*listenport) {
  774. /* Real failure, listener port shall not be zero beyond this point. */
  775. logmsg("Apparently getsockname() succeeded, with listener port zero.");
  776. logmsg("A valid reason for this failure is a binary built without");
  777. logmsg("proper network library linkage. This might not be the only");
  778. logmsg("reason, but double check it before anything else.");
  779. sclose(sock);
  780. return CURL_SOCKET_BAD;
  781. }
  782. }
  783. /* start accepting connections */
  784. rc = listen(sock, 5);
  785. if(0 != rc) {
  786. error = SOCKERRNO;
  787. logmsg("listen(%d, 5) failed with error: (%d) %s",
  788. sock, error, strerror(error));
  789. sclose(sock);
  790. return CURL_SOCKET_BAD;
  791. }
  792. return sock;
  793. }
  794. int main(int argc, char *argv[])
  795. {
  796. curl_socket_t sock = CURL_SOCKET_BAD;
  797. curl_socket_t msgsock = CURL_SOCKET_BAD;
  798. int wrotepidfile = 0;
  799. int wroteportfile = 0;
  800. const char *pidname = ".socksd.pid";
  801. const char *portname = NULL; /* none by default */
  802. bool juggle_again;
  803. int error;
  804. int arg = 1;
  805. while(argc>arg) {
  806. if(!strcmp("--version", argv[arg])) {
  807. printf("socksd IPv4%s\n",
  808. #ifdef ENABLE_IPV6
  809. "/IPv6"
  810. #else
  811. ""
  812. #endif
  813. );
  814. return 0;
  815. }
  816. else if(!strcmp("--pidfile", argv[arg])) {
  817. arg++;
  818. if(argc>arg)
  819. pidname = argv[arg++];
  820. }
  821. else if(!strcmp("--portfile", argv[arg])) {
  822. arg++;
  823. if(argc>arg)
  824. portname = argv[arg++];
  825. }
  826. else if(!strcmp("--config", argv[arg])) {
  827. arg++;
  828. if(argc>arg)
  829. configfile = argv[arg++];
  830. }
  831. else if(!strcmp("--backend", argv[arg])) {
  832. arg++;
  833. if(argc>arg)
  834. backendaddr = argv[arg++];
  835. }
  836. else if(!strcmp("--backendport", argv[arg])) {
  837. arg++;
  838. if(argc>arg)
  839. backendport = (unsigned short)atoi(argv[arg++]);
  840. }
  841. else if(!strcmp("--logfile", argv[arg])) {
  842. arg++;
  843. if(argc>arg)
  844. serverlogfile = argv[arg++];
  845. }
  846. else if(!strcmp("--ipv6", argv[arg])) {
  847. #ifdef ENABLE_IPV6
  848. ipv_inuse = "IPv6";
  849. use_ipv6 = TRUE;
  850. #endif
  851. arg++;
  852. }
  853. else if(!strcmp("--ipv4", argv[arg])) {
  854. /* for completeness, we support this option as well */
  855. #ifdef ENABLE_IPV6
  856. ipv_inuse = "IPv4";
  857. use_ipv6 = FALSE;
  858. #endif
  859. arg++;
  860. }
  861. else if(!strcmp("--port", argv[arg])) {
  862. arg++;
  863. if(argc>arg) {
  864. char *endptr;
  865. unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
  866. port = curlx_ultous(ulnum);
  867. arg++;
  868. }
  869. }
  870. else {
  871. puts("Usage: socksd [option]\n"
  872. " --backend [ipv4 addr]\n"
  873. " --backendport [TCP port]\n"
  874. " --config [file]\n"
  875. " --version\n"
  876. " --logfile [file]\n"
  877. " --pidfile [file]\n"
  878. " --portfile [file]\n"
  879. " --ipv4\n"
  880. " --ipv6\n"
  881. " --bindonly\n"
  882. " --port [port]\n");
  883. return 0;
  884. }
  885. }
  886. #ifdef WIN32
  887. win32_init();
  888. atexit(win32_cleanup);
  889. setmode(fileno(stdin), O_BINARY);
  890. setmode(fileno(stdout), O_BINARY);
  891. setmode(fileno(stderr), O_BINARY);
  892. #endif
  893. install_signal_handlers(false);
  894. #ifdef ENABLE_IPV6
  895. if(!use_ipv6)
  896. #endif
  897. sock = socket(AF_INET, SOCK_STREAM, 0);
  898. #ifdef ENABLE_IPV6
  899. else
  900. sock = socket(AF_INET6, SOCK_STREAM, 0);
  901. #endif
  902. if(CURL_SOCKET_BAD == sock) {
  903. error = SOCKERRNO;
  904. logmsg("Error creating socket: (%d) %s",
  905. error, strerror(error));
  906. goto socks5_cleanup;
  907. }
  908. {
  909. /* passive daemon style */
  910. sock = sockdaemon(sock, &port);
  911. if(CURL_SOCKET_BAD == sock) {
  912. goto socks5_cleanup;
  913. }
  914. msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
  915. }
  916. logmsg("Running %s version", ipv_inuse);
  917. logmsg("Listening on port %hu", port);
  918. wrotepidfile = write_pidfile(pidname);
  919. if(!wrotepidfile) {
  920. goto socks5_cleanup;
  921. }
  922. if(portname) {
  923. wroteportfile = write_portfile(portname, port);
  924. if(!wroteportfile) {
  925. goto socks5_cleanup;
  926. }
  927. }
  928. do {
  929. juggle_again = incoming(sock);
  930. } while(juggle_again);
  931. socks5_cleanup:
  932. if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
  933. sclose(msgsock);
  934. if(sock != CURL_SOCKET_BAD)
  935. sclose(sock);
  936. if(wrotepidfile)
  937. unlink(pidname);
  938. if(wroteportfile)
  939. unlink(portname);
  940. restore_signal_handlers(false);
  941. if(got_exit_signal) {
  942. logmsg("============> socksd exits with signal (%d)", exit_signal);
  943. /*
  944. * To properly set the return status of the process we
  945. * must raise the same signal SIGINT or SIGTERM that we
  946. * caught and let the old handler take care of it.
  947. */
  948. raise(exit_signal);
  949. }
  950. logmsg("============> socksd quits");
  951. return 0;
  952. }