socksd.c 30 KB

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