2
0

socksd.c 31 KB

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