socksd.c 31 KB

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