sockfilt.c 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2017, 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.haxx.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. ***************************************************************************/
  22. #include "server_setup.h"
  23. /* Purpose
  24. *
  25. * 1. Accept a TCP connection on a custom port (IPv4 or IPv6), or connect
  26. * to a given (localhost) port.
  27. *
  28. * 2. Get commands on STDIN. Pass data on to the TCP stream.
  29. * Get data from TCP stream and pass on to STDOUT.
  30. *
  31. * This program is made to perform all the socket/stream/connection stuff for
  32. * the test suite's (perl) FTP server. Previously the perl code did all of
  33. * this by its own, but I decided to let this program do the socket layer
  34. * because of several things:
  35. *
  36. * o We want the perl code to work with rather old perl installations, thus
  37. * we cannot use recent perl modules or features.
  38. *
  39. * o We want IPv6 support for systems that provide it, and doing optional IPv6
  40. * support in perl seems if not impossible so at least awkward.
  41. *
  42. * o We want FTP-SSL support, which means that a connection that starts with
  43. * plain sockets needs to be able to "go SSL" in the midst. This would also
  44. * require some nasty perl stuff I'd rather avoid.
  45. *
  46. * (Source originally based on sws.c)
  47. */
  48. /*
  49. * Signal handling notes for sockfilt
  50. * ----------------------------------
  51. *
  52. * This program is a single-threaded process.
  53. *
  54. * This program is intended to be highly portable and as such it must be kept
  55. * as simple as possible, due to this the only signal handling mechanisms used
  56. * will be those of ANSI C, and used only in the most basic form which is good
  57. * enough for the purpose of this program.
  58. *
  59. * For the above reason and the specific needs of this program signals SIGHUP,
  60. * SIGPIPE and SIGALRM will be simply ignored on systems where this can be
  61. * done. If possible, signals SIGINT and SIGTERM will be handled by this
  62. * program as an indication to cleanup and finish execution as soon as
  63. * possible. This will be achieved with a single signal handler
  64. * 'exit_signal_handler' for both signals.
  65. *
  66. * The 'exit_signal_handler' upon the first SIGINT or SIGTERM received signal
  67. * will just set to one the global var 'got_exit_signal' storing in global var
  68. * 'exit_signal' the signal that triggered this change.
  69. *
  70. * Nothing fancy that could introduce problems is used, the program at certain
  71. * points in its normal flow checks if var 'got_exit_signal' is set and in
  72. * case this is true it just makes its way out of loops and functions in
  73. * structured and well behaved manner to achieve proper program cleanup and
  74. * termination.
  75. *
  76. * Even with the above mechanism implemented it is worthwile to note that
  77. * other signals might still be received, or that there might be systems on
  78. * which it is not possible to trap and ignore some of the above signals.
  79. * This implies that for increased portability and reliability the program
  80. * must be coded as if no signal was being ignored or handled at all. Enjoy
  81. * it!
  82. */
  83. #ifdef HAVE_SIGNAL_H
  84. #include <signal.h>
  85. #endif
  86. #ifdef HAVE_NETINET_IN_H
  87. #include <netinet/in.h>
  88. #endif
  89. #ifdef HAVE_NETINET_IN6_H
  90. #include <netinet/in6.h>
  91. #endif
  92. #ifdef HAVE_ARPA_INET_H
  93. #include <arpa/inet.h>
  94. #endif
  95. #ifdef HAVE_NETDB_H
  96. #include <netdb.h>
  97. #endif
  98. #define ENABLE_CURLX_PRINTF
  99. /* make the curlx header define all printf() functions to use the curlx_*
  100. versions instead */
  101. #include "curlx.h" /* from the private lib dir */
  102. #include "getpart.h"
  103. #include "inet_pton.h"
  104. #include "util.h"
  105. #include "server_sockaddr.h"
  106. #include "warnless.h"
  107. /* include memdebug.h last */
  108. #include "memdebug.h"
  109. #ifdef USE_WINSOCK
  110. #undef EINTR
  111. #define EINTR 4 /* errno.h value */
  112. #undef EAGAIN
  113. #define EAGAIN 11 /* errno.h value */
  114. #undef ENOMEM
  115. #define ENOMEM 12 /* errno.h value */
  116. #undef EINVAL
  117. #define EINVAL 22 /* errno.h value */
  118. #endif
  119. #define DEFAULT_PORT 8999
  120. #ifndef DEFAULT_LOGFILE
  121. #define DEFAULT_LOGFILE "log/sockfilt.log"
  122. #endif
  123. const char *serverlogfile = DEFAULT_LOGFILE;
  124. static bool verbose = FALSE;
  125. static bool bind_only = FALSE;
  126. #ifdef ENABLE_IPV6
  127. static bool use_ipv6 = FALSE;
  128. #endif
  129. static const char *ipv_inuse = "IPv4";
  130. static unsigned short port = DEFAULT_PORT;
  131. static unsigned short connectport = 0; /* if non-zero, we activate this mode */
  132. enum sockmode {
  133. PASSIVE_LISTEN, /* as a server waiting for connections */
  134. PASSIVE_CONNECT, /* as a server, connected to a client */
  135. ACTIVE, /* as a client, connected to a server */
  136. ACTIVE_DISCONNECT /* as a client, disconnected from server */
  137. };
  138. /* do-nothing macro replacement for systems which lack siginterrupt() */
  139. #ifndef HAVE_SIGINTERRUPT
  140. #define siginterrupt(x,y) do {} while(0)
  141. #endif
  142. /* vars used to keep around previous signal handlers */
  143. typedef RETSIGTYPE (*SIGHANDLER_T)(int);
  144. #ifdef SIGHUP
  145. static SIGHANDLER_T old_sighup_handler = SIG_ERR;
  146. #endif
  147. #ifdef SIGPIPE
  148. static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
  149. #endif
  150. #ifdef SIGALRM
  151. static SIGHANDLER_T old_sigalrm_handler = SIG_ERR;
  152. #endif
  153. #ifdef SIGINT
  154. static SIGHANDLER_T old_sigint_handler = SIG_ERR;
  155. #endif
  156. #ifdef SIGTERM
  157. static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
  158. #endif
  159. #if defined(SIGBREAK) && defined(WIN32)
  160. static SIGHANDLER_T old_sigbreak_handler = SIG_ERR;
  161. #endif
  162. /* var which if set indicates that the program should finish execution */
  163. SIG_ATOMIC_T got_exit_signal = 0;
  164. /* if next is set indicates the first signal handled in exit_signal_handler */
  165. static volatile int exit_signal = 0;
  166. /* signal handler that will be triggered to indicate that the program
  167. should finish its execution in a controlled manner as soon as possible.
  168. The first time this is called it will set got_exit_signal to one and
  169. store in exit_signal the signal that triggered its execution. */
  170. static RETSIGTYPE exit_signal_handler(int signum)
  171. {
  172. int old_errno = errno;
  173. if(got_exit_signal == 0) {
  174. got_exit_signal = 1;
  175. exit_signal = signum;
  176. }
  177. (void)signal(signum, exit_signal_handler);
  178. errno = old_errno;
  179. }
  180. static void install_signal_handlers(void)
  181. {
  182. #ifdef SIGHUP
  183. /* ignore SIGHUP signal */
  184. old_sighup_handler = signal(SIGHUP, SIG_IGN);
  185. if(old_sighup_handler == SIG_ERR)
  186. logmsg("cannot install SIGHUP handler: %s", strerror(errno));
  187. #endif
  188. #ifdef SIGPIPE
  189. /* ignore SIGPIPE signal */
  190. old_sigpipe_handler = signal(SIGPIPE, SIG_IGN);
  191. if(old_sigpipe_handler == SIG_ERR)
  192. logmsg("cannot install SIGPIPE handler: %s", strerror(errno));
  193. #endif
  194. #ifdef SIGALRM
  195. /* ignore SIGALRM signal */
  196. old_sigalrm_handler = signal(SIGALRM, SIG_IGN);
  197. if(old_sigalrm_handler == SIG_ERR)
  198. logmsg("cannot install SIGALRM handler: %s", strerror(errno));
  199. #endif
  200. #ifdef SIGINT
  201. /* handle SIGINT signal with our exit_signal_handler */
  202. old_sigint_handler = signal(SIGINT, exit_signal_handler);
  203. if(old_sigint_handler == SIG_ERR)
  204. logmsg("cannot install SIGINT handler: %s", strerror(errno));
  205. else
  206. siginterrupt(SIGINT, 1);
  207. #endif
  208. #ifdef SIGTERM
  209. /* handle SIGTERM signal with our exit_signal_handler */
  210. old_sigterm_handler = signal(SIGTERM, exit_signal_handler);
  211. if(old_sigterm_handler == SIG_ERR)
  212. logmsg("cannot install SIGTERM handler: %s", strerror(errno));
  213. else
  214. siginterrupt(SIGTERM, 1);
  215. #endif
  216. #if defined(SIGBREAK) && defined(WIN32)
  217. /* handle SIGBREAK signal with our exit_signal_handler */
  218. old_sigbreak_handler = signal(SIGBREAK, exit_signal_handler);
  219. if(old_sigbreak_handler == SIG_ERR)
  220. logmsg("cannot install SIGBREAK handler: %s", strerror(errno));
  221. else
  222. siginterrupt(SIGBREAK, 1);
  223. #endif
  224. }
  225. static void restore_signal_handlers(void)
  226. {
  227. #ifdef SIGHUP
  228. if(SIG_ERR != old_sighup_handler)
  229. (void)signal(SIGHUP, old_sighup_handler);
  230. #endif
  231. #ifdef SIGPIPE
  232. if(SIG_ERR != old_sigpipe_handler)
  233. (void)signal(SIGPIPE, old_sigpipe_handler);
  234. #endif
  235. #ifdef SIGALRM
  236. if(SIG_ERR != old_sigalrm_handler)
  237. (void)signal(SIGALRM, old_sigalrm_handler);
  238. #endif
  239. #ifdef SIGINT
  240. if(SIG_ERR != old_sigint_handler)
  241. (void)signal(SIGINT, old_sigint_handler);
  242. #endif
  243. #ifdef SIGTERM
  244. if(SIG_ERR != old_sigterm_handler)
  245. (void)signal(SIGTERM, old_sigterm_handler);
  246. #endif
  247. #if defined(SIGBREAK) && defined(WIN32)
  248. if(SIG_ERR != old_sigbreak_handler)
  249. (void)signal(SIGBREAK, old_sigbreak_handler);
  250. #endif
  251. }
  252. #ifdef WIN32
  253. /*
  254. * read-wrapper to support reading from stdin on Windows.
  255. */
  256. static ssize_t read_wincon(int fd, void *buf, size_t count)
  257. {
  258. HANDLE handle = NULL;
  259. DWORD mode, rcount = 0;
  260. BOOL success;
  261. if(fd == fileno(stdin)) {
  262. handle = GetStdHandle(STD_INPUT_HANDLE);
  263. }
  264. else {
  265. return read(fd, buf, count);
  266. }
  267. if(GetConsoleMode(handle, &mode)) {
  268. success = ReadConsole(handle, buf, curlx_uztoul(count), &rcount, NULL);
  269. }
  270. else {
  271. success = ReadFile(handle, buf, curlx_uztoul(count), &rcount, NULL);
  272. }
  273. if(success) {
  274. return rcount;
  275. }
  276. errno = GetLastError();
  277. return -1;
  278. }
  279. #undef read
  280. #define read(a,b,c) read_wincon(a,b,c)
  281. /*
  282. * write-wrapper to support writing to stdout and stderr on Windows.
  283. */
  284. static ssize_t write_wincon(int fd, const void *buf, size_t count)
  285. {
  286. HANDLE handle = NULL;
  287. DWORD mode, wcount = 0;
  288. BOOL success;
  289. if(fd == fileno(stdout)) {
  290. handle = GetStdHandle(STD_OUTPUT_HANDLE);
  291. }
  292. else if(fd == fileno(stderr)) {
  293. handle = GetStdHandle(STD_ERROR_HANDLE);
  294. }
  295. else {
  296. return write(fd, buf, count);
  297. }
  298. if(GetConsoleMode(handle, &mode)) {
  299. success = WriteConsole(handle, buf, curlx_uztoul(count), &wcount, NULL);
  300. }
  301. else {
  302. success = WriteFile(handle, buf, curlx_uztoul(count), &wcount, NULL);
  303. }
  304. if(success) {
  305. return wcount;
  306. }
  307. errno = GetLastError();
  308. return -1;
  309. }
  310. #undef write
  311. #define write(a,b,c) write_wincon(a,b,c)
  312. #endif
  313. /*
  314. * fullread is a wrapper around the read() function. This will repeat the call
  315. * to read() until it actually has read the complete number of bytes indicated
  316. * in nbytes or it fails with a condition that cannot be handled with a simple
  317. * retry of the read call.
  318. */
  319. static ssize_t fullread(int filedes, void *buffer, size_t nbytes)
  320. {
  321. int error;
  322. ssize_t nread = 0;
  323. do {
  324. ssize_t rc = read(filedes,
  325. (unsigned char *)buffer + nread, nbytes - nread);
  326. if(got_exit_signal) {
  327. logmsg("signalled to die");
  328. return -1;
  329. }
  330. if(rc < 0) {
  331. error = errno;
  332. if((error == EINTR) || (error == EAGAIN))
  333. continue;
  334. logmsg("reading from file descriptor: %d,", filedes);
  335. logmsg("unrecoverable read() failure: (%d) %s",
  336. error, strerror(error));
  337. return -1;
  338. }
  339. if(rc == 0) {
  340. logmsg("got 0 reading from stdin");
  341. return 0;
  342. }
  343. nread += rc;
  344. } while((size_t)nread < nbytes);
  345. if(verbose)
  346. logmsg("read %zd bytes", nread);
  347. return nread;
  348. }
  349. /*
  350. * fullwrite is a wrapper around the write() function. This will repeat the
  351. * call to write() until it actually has written the complete number of bytes
  352. * indicated in nbytes or it fails with a condition that cannot be handled
  353. * with a simple retry of the write call.
  354. */
  355. static ssize_t fullwrite(int filedes, const void *buffer, size_t nbytes)
  356. {
  357. int error;
  358. ssize_t nwrite = 0;
  359. do {
  360. ssize_t wc = write(filedes, (const unsigned char *)buffer + nwrite,
  361. nbytes - nwrite);
  362. if(got_exit_signal) {
  363. logmsg("signalled to die");
  364. return -1;
  365. }
  366. if(wc < 0) {
  367. error = errno;
  368. if((error == EINTR) || (error == EAGAIN))
  369. continue;
  370. logmsg("writing to file descriptor: %d,", filedes);
  371. logmsg("unrecoverable write() failure: (%d) %s",
  372. error, strerror(error));
  373. return -1;
  374. }
  375. if(wc == 0) {
  376. logmsg("put 0 writing to stdout");
  377. return 0;
  378. }
  379. nwrite += wc;
  380. } while((size_t)nwrite < nbytes);
  381. if(verbose)
  382. logmsg("wrote %zd bytes", nwrite);
  383. return nwrite;
  384. }
  385. /*
  386. * read_stdin tries to read from stdin nbytes into the given buffer. This is a
  387. * blocking function that will only return TRUE when nbytes have actually been
  388. * read or FALSE when an unrecoverable error has been detected. Failure of this
  389. * function is an indication that the sockfilt process should terminate.
  390. */
  391. static bool read_stdin(void *buffer, size_t nbytes)
  392. {
  393. ssize_t nread = fullread(fileno(stdin), buffer, nbytes);
  394. if(nread != (ssize_t)nbytes) {
  395. logmsg("exiting...");
  396. return FALSE;
  397. }
  398. return TRUE;
  399. }
  400. /*
  401. * write_stdout tries to write to stdio nbytes from the given buffer. This is a
  402. * blocking function that will only return TRUE when nbytes have actually been
  403. * written or FALSE when an unrecoverable error has been detected. Failure of
  404. * this function is an indication that the sockfilt process should terminate.
  405. */
  406. static bool write_stdout(const void *buffer, size_t nbytes)
  407. {
  408. ssize_t nwrite = fullwrite(fileno(stdout), buffer, nbytes);
  409. if(nwrite != (ssize_t)nbytes) {
  410. logmsg("exiting...");
  411. return FALSE;
  412. }
  413. return TRUE;
  414. }
  415. static void lograw(unsigned char *buffer, ssize_t len)
  416. {
  417. char data[120];
  418. ssize_t i;
  419. unsigned char *ptr = buffer;
  420. char *optr = data;
  421. ssize_t width = 0;
  422. int left = sizeof(data);
  423. for(i = 0; i<len; i++) {
  424. switch(ptr[i]) {
  425. case '\n':
  426. snprintf(optr, left, "\\n");
  427. width += 2;
  428. optr += 2;
  429. left -= 2;
  430. break;
  431. case '\r':
  432. snprintf(optr, left, "\\r");
  433. width += 2;
  434. optr += 2;
  435. left -= 2;
  436. break;
  437. default:
  438. snprintf(optr, left, "%c", (ISGRAPH(ptr[i]) ||
  439. ptr[i] == 0x20) ?ptr[i]:'.');
  440. width++;
  441. optr++;
  442. left--;
  443. break;
  444. }
  445. if(width>60) {
  446. logmsg("'%s'", data);
  447. width = 0;
  448. optr = data;
  449. left = sizeof(data);
  450. }
  451. }
  452. if(width)
  453. logmsg("'%s'", data);
  454. }
  455. #ifdef USE_WINSOCK
  456. /*
  457. * WinSock select() does not support standard file descriptors,
  458. * it can only check SOCKETs. The following function is an attempt
  459. * to re-create a select() function with support for other handle types.
  460. *
  461. * select() function with support for WINSOCK2 sockets and all
  462. * other handle types supported by WaitForMultipleObjectsEx() as
  463. * well as disk files, anonymous and names pipes, and character input.
  464. *
  465. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms687028.aspx
  466. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms741572.aspx
  467. */
  468. struct select_ws_wait_data {
  469. HANDLE handle; /* actual handle to wait for during select */
  470. HANDLE event; /* internal event to abort waiting thread */
  471. };
  472. static DWORD WINAPI select_ws_wait_thread(LPVOID lpParameter)
  473. {
  474. struct select_ws_wait_data *data;
  475. HANDLE handle, handles[2];
  476. INPUT_RECORD inputrecord;
  477. LARGE_INTEGER size, pos;
  478. DWORD type, length;
  479. /* retrieve handles from internal structure */
  480. data = (struct select_ws_wait_data *) lpParameter;
  481. if(data) {
  482. handle = data->handle;
  483. handles[0] = data->event;
  484. handles[1] = handle;
  485. free(data);
  486. }
  487. else
  488. return (DWORD)-1;
  489. /* retrieve the type of file to wait on */
  490. type = GetFileType(handle);
  491. switch(type) {
  492. case FILE_TYPE_DISK:
  493. /* The handle represents a file on disk, this means:
  494. * - WaitForMultipleObjectsEx will always be signalled for it.
  495. * - comparison of current position in file and total size of
  496. * the file can be used to check if we reached the end yet.
  497. *
  498. * Approach: Loop till either the internal event is signalled
  499. * or if the end of the file has already been reached.
  500. */
  501. while(WaitForMultipleObjectsEx(1, handles, FALSE, 0, FALSE)
  502. == WAIT_TIMEOUT) {
  503. /* get total size of file */
  504. length = 0;
  505. size.QuadPart = 0;
  506. size.LowPart = GetFileSize(handle, &length);
  507. if((size.LowPart != INVALID_FILE_SIZE) ||
  508. (GetLastError() == NO_ERROR)) {
  509. size.HighPart = length;
  510. /* get the current position within the file */
  511. pos.QuadPart = 0;
  512. pos.LowPart = SetFilePointer(handle, 0, &pos.HighPart,
  513. FILE_CURRENT);
  514. if((pos.LowPart != INVALID_SET_FILE_POINTER) ||
  515. (GetLastError() == NO_ERROR)) {
  516. /* compare position with size, abort if not equal */
  517. if(size.QuadPart == pos.QuadPart) {
  518. /* sleep and continue waiting */
  519. SleepEx(0, FALSE);
  520. continue;
  521. }
  522. }
  523. }
  524. /* there is some data available, stop waiting */
  525. break;
  526. }
  527. break;
  528. case FILE_TYPE_CHAR:
  529. /* The handle represents a character input, this means:
  530. * - WaitForMultipleObjectsEx will be signalled on any kind of input,
  531. * including mouse and window size events we do not care about.
  532. *
  533. * Approach: Loop till either the internal event is signalled
  534. * or we get signalled for an actual key-event.
  535. */
  536. while(WaitForMultipleObjectsEx(2, handles, FALSE, INFINITE, FALSE)
  537. == WAIT_OBJECT_0 + 1) {
  538. /* check if this is an actual console handle */
  539. length = 0;
  540. if(GetConsoleMode(handle, &length)) {
  541. /* retrieve an event from the console buffer */
  542. length = 0;
  543. if(PeekConsoleInput(handle, &inputrecord, 1, &length)) {
  544. /* check if the event is not an actual key-event */
  545. if(length == 1 && inputrecord.EventType != KEY_EVENT) {
  546. /* purge the non-key-event and continue waiting */
  547. ReadConsoleInput(handle, &inputrecord, 1, &length);
  548. continue;
  549. }
  550. }
  551. }
  552. /* there is some data available, stop waiting */
  553. break;
  554. }
  555. break;
  556. case FILE_TYPE_PIPE:
  557. /* The handle represents an anonymous or named pipe, this means:
  558. * - WaitForMultipleObjectsEx will always be signalled for it.
  559. * - peek into the pipe and retrieve the amount of data available.
  560. *
  561. * Approach: Loop till either the internal event is signalled
  562. * or there is data in the pipe available for reading.
  563. */
  564. while(WaitForMultipleObjectsEx(1, handles, FALSE, 0, FALSE)
  565. == WAIT_TIMEOUT) {
  566. /* peek into the pipe and retrieve the amount of data available */
  567. length = 0;
  568. if(PeekNamedPipe(handle, NULL, 0, NULL, &length, NULL)) {
  569. /* if there is no data available, sleep and continue waiting */
  570. if(length == 0) {
  571. SleepEx(0, FALSE);
  572. continue;
  573. }
  574. }
  575. else {
  576. /* if the pipe has been closed, sleep and continue waiting */
  577. if(GetLastError() == ERROR_BROKEN_PIPE) {
  578. SleepEx(0, FALSE);
  579. continue;
  580. }
  581. }
  582. /* there is some data available, stop waiting */
  583. break;
  584. }
  585. break;
  586. default:
  587. /* The handle has an unknown type, try to wait on it */
  588. WaitForMultipleObjectsEx(2, handles, FALSE, INFINITE, FALSE);
  589. break;
  590. }
  591. return 0;
  592. }
  593. static HANDLE select_ws_wait(HANDLE handle, HANDLE event)
  594. {
  595. struct select_ws_wait_data *data;
  596. HANDLE thread = NULL;
  597. /* allocate internal waiting data structure */
  598. data = malloc(sizeof(struct select_ws_wait_data));
  599. if(data) {
  600. data->handle = handle;
  601. data->event = event;
  602. /* launch waiting thread */
  603. thread = CreateThread(NULL, 0,
  604. &select_ws_wait_thread,
  605. data, 0, NULL);
  606. /* free data if thread failed to launch */
  607. if(!thread) {
  608. free(data);
  609. }
  610. }
  611. return thread;
  612. }
  613. struct select_ws_data {
  614. curl_socket_t fd; /* the original input handle (indexed by fds) */
  615. curl_socket_t wsasock; /* the internal socket handle (indexed by wsa) */
  616. WSAEVENT wsaevent; /* the internal WINSOCK2 event (indexed by wsa) */
  617. HANDLE thread; /* the internal threads handle (indexed by thd) */
  618. };
  619. static int select_ws(int nfds, fd_set *readfds, fd_set *writefds,
  620. fd_set *exceptfds, struct timeval *timeout)
  621. {
  622. DWORD milliseconds, wait, idx;
  623. WSANETWORKEVENTS wsanetevents;
  624. struct select_ws_data *data;
  625. HANDLE handle, *handles;
  626. WSAEVENT wsaevent;
  627. int error, fds;
  628. HANDLE waitevent = NULL;
  629. DWORD nfd = 0, thd = 0, wsa = 0;
  630. int ret = 0;
  631. /* check if the input value is valid */
  632. if(nfds < 0) {
  633. errno = EINVAL;
  634. return -1;
  635. }
  636. /* check if we got descriptors, sleep in case we got none */
  637. if(!nfds) {
  638. Sleep((timeout->tv_sec*1000)+(DWORD)(((double)timeout->tv_usec)/1000.0));
  639. return 0;
  640. }
  641. /* create internal event to signal waiting threads */
  642. waitevent = CreateEvent(NULL, TRUE, FALSE, NULL);
  643. if(!waitevent) {
  644. errno = ENOMEM;
  645. return -1;
  646. }
  647. /* allocate internal array for the internal data */
  648. data = calloc(nfds, sizeof(struct select_ws_data));
  649. if(data == NULL) {
  650. CloseHandle(waitevent);
  651. errno = ENOMEM;
  652. return -1;
  653. }
  654. /* allocate internal array for the internal event handles */
  655. handles = calloc(nfds, sizeof(HANDLE));
  656. if(handles == NULL) {
  657. CloseHandle(waitevent);
  658. free(data);
  659. errno = ENOMEM;
  660. return -1;
  661. }
  662. /* loop over the handles in the input descriptor sets */
  663. for(fds = 0; fds < nfds; fds++) {
  664. long networkevents = 0;
  665. handles[nfd] = 0;
  666. if(FD_ISSET(fds, readfds))
  667. networkevents |= FD_READ|FD_ACCEPT|FD_CLOSE;
  668. if(FD_ISSET(fds, writefds))
  669. networkevents |= FD_WRITE|FD_CONNECT;
  670. if(FD_ISSET(fds, exceptfds))
  671. networkevents |= FD_OOB|FD_CLOSE;
  672. /* only wait for events for which we actually care */
  673. if(networkevents) {
  674. data[nfd].fd = curlx_sitosk(fds);
  675. if(fds == fileno(stdin)) {
  676. handle = GetStdHandle(STD_INPUT_HANDLE);
  677. handle = select_ws_wait(handle, waitevent);
  678. handles[nfd] = handle;
  679. data[thd].thread = handle;
  680. thd++;
  681. }
  682. else if(fds == fileno(stdout)) {
  683. handles[nfd] = GetStdHandle(STD_OUTPUT_HANDLE);
  684. }
  685. else if(fds == fileno(stderr)) {
  686. handles[nfd] = GetStdHandle(STD_ERROR_HANDLE);
  687. }
  688. else {
  689. wsaevent = WSACreateEvent();
  690. if(wsaevent != WSA_INVALID_EVENT) {
  691. error = WSAEventSelect(fds, wsaevent, networkevents);
  692. if(error != SOCKET_ERROR) {
  693. handle = (HANDLE) wsaevent;
  694. handles[nfd] = handle;
  695. data[wsa].wsasock = curlx_sitosk(fds);
  696. data[wsa].wsaevent = wsaevent;
  697. wsa++;
  698. }
  699. else {
  700. curl_socket_t socket = curlx_sitosk(fds);
  701. WSACloseEvent(wsaevent);
  702. handle = (HANDLE) socket;
  703. handle = select_ws_wait(handle, waitevent);
  704. handles[nfd] = handle;
  705. data[thd].thread = handle;
  706. thd++;
  707. }
  708. }
  709. }
  710. nfd++;
  711. }
  712. }
  713. /* convert struct timeval to milliseconds */
  714. if(timeout) {
  715. milliseconds = ((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000));
  716. }
  717. else {
  718. milliseconds = INFINITE;
  719. }
  720. /* wait for one of the internal handles to trigger */
  721. wait = WaitForMultipleObjectsEx(nfd, handles, FALSE, milliseconds, FALSE);
  722. /* signal the event handle for the waiting threads */
  723. SetEvent(waitevent);
  724. /* loop over the internal handles returned in the descriptors */
  725. for(idx = 0; idx < nfd; idx++) {
  726. curl_socket_t sock = data[idx].fd;
  727. handle = handles[idx];
  728. fds = curlx_sktosi(sock);
  729. /* check if the current internal handle was triggered */
  730. if(wait != WAIT_FAILED && (wait - WAIT_OBJECT_0) <= idx &&
  731. WaitForSingleObjectEx(handle, 0, FALSE) == WAIT_OBJECT_0) {
  732. /* first handle stdin, stdout and stderr */
  733. if(fds == fileno(stdin)) {
  734. /* stdin is never ready for write or exceptional */
  735. FD_CLR(sock, writefds);
  736. FD_CLR(sock, exceptfds);
  737. }
  738. else if(fds == fileno(stdout) || fds == fileno(stderr)) {
  739. /* stdout and stderr are never ready for read or exceptional */
  740. FD_CLR(sock, readfds);
  741. FD_CLR(sock, exceptfds);
  742. }
  743. else {
  744. /* try to handle the event with the WINSOCK2 functions */
  745. wsanetevents.lNetworkEvents = 0;
  746. error = WSAEnumNetworkEvents(fds, handle, &wsanetevents);
  747. if(error != SOCKET_ERROR) {
  748. /* remove from descriptor set if not ready for read/accept/close */
  749. if(!(wsanetevents.lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE)))
  750. FD_CLR(sock, readfds);
  751. /* remove from descriptor set if not ready for write/connect */
  752. if(!(wsanetevents.lNetworkEvents & (FD_WRITE|FD_CONNECT)))
  753. FD_CLR(sock, writefds);
  754. /* HACK:
  755. * use exceptfds together with readfds to signal
  756. * that the connection was closed by the client.
  757. *
  758. * Reason: FD_CLOSE is only signaled once, sometimes
  759. * at the same time as FD_READ with data being available.
  760. * This means that recv/sread is not reliable to detect
  761. * that the connection is closed.
  762. */
  763. /* remove from descriptor set if not exceptional */
  764. if(!(wsanetevents.lNetworkEvents & (FD_OOB|FD_CLOSE)))
  765. FD_CLR(sock, exceptfds);
  766. }
  767. }
  768. /* check if the event has not been filtered using specific tests */
  769. if(FD_ISSET(sock, readfds) || FD_ISSET(sock, writefds) ||
  770. FD_ISSET(sock, exceptfds)) {
  771. ret++;
  772. }
  773. }
  774. else {
  775. /* remove from all descriptor sets since this handle did not trigger */
  776. FD_CLR(sock, readfds);
  777. FD_CLR(sock, writefds);
  778. FD_CLR(sock, exceptfds);
  779. }
  780. }
  781. for(fds = 0; fds < nfds; fds++) {
  782. if(FD_ISSET(fds, readfds))
  783. logmsg("select_ws: %d is readable", fds);
  784. if(FD_ISSET(fds, writefds))
  785. logmsg("select_ws: %d is writable", fds);
  786. if(FD_ISSET(fds, exceptfds))
  787. logmsg("select_ws: %d is excepted", fds);
  788. }
  789. for(idx = 0; idx < wsa; idx++) {
  790. WSAEventSelect(data[idx].wsasock, NULL, 0);
  791. WSACloseEvent(data[idx].wsaevent);
  792. }
  793. for(idx = 0; idx < thd; idx++) {
  794. WaitForSingleObject(data[idx].thread, INFINITE);
  795. CloseHandle(data[idx].thread);
  796. }
  797. CloseHandle(waitevent);
  798. free(handles);
  799. free(data);
  800. return ret;
  801. }
  802. #define select(a,b,c,d,e) select_ws(a,b,c,d,e)
  803. #endif /* USE_WINSOCK */
  804. /*
  805. sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
  806. if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
  807. accept()
  808. */
  809. static bool juggle(curl_socket_t *sockfdp,
  810. curl_socket_t listenfd,
  811. enum sockmode *mode)
  812. {
  813. struct timeval timeout;
  814. fd_set fds_read;
  815. fd_set fds_write;
  816. fd_set fds_err;
  817. curl_socket_t sockfd = CURL_SOCKET_BAD;
  818. int maxfd = -99;
  819. ssize_t rc;
  820. int error = 0;
  821. /* 'buffer' is this excessively large only to be able to support things like
  822. test 1003 which tests exceedingly large server response lines */
  823. unsigned char buffer[17010];
  824. char data[16];
  825. if(got_exit_signal) {
  826. logmsg("signalled to die, exiting...");
  827. return FALSE;
  828. }
  829. #ifdef HAVE_GETPPID
  830. /* As a last resort, quit if sockfilt process becomes orphan. Just in case
  831. parent ftpserver process has died without killing its sockfilt children */
  832. if(getppid() <= 1) {
  833. logmsg("process becomes orphan, exiting");
  834. return FALSE;
  835. }
  836. #endif
  837. timeout.tv_sec = 120;
  838. timeout.tv_usec = 0;
  839. FD_ZERO(&fds_read);
  840. FD_ZERO(&fds_write);
  841. FD_ZERO(&fds_err);
  842. FD_SET((curl_socket_t)fileno(stdin), &fds_read);
  843. switch(*mode) {
  844. case PASSIVE_LISTEN:
  845. /* server mode */
  846. sockfd = listenfd;
  847. /* there's always a socket to wait for */
  848. FD_SET(sockfd, &fds_read);
  849. maxfd = (int)sockfd;
  850. break;
  851. case PASSIVE_CONNECT:
  852. sockfd = *sockfdp;
  853. if(CURL_SOCKET_BAD == sockfd) {
  854. /* eeek, we are supposedly connected and then this cannot be -1 ! */
  855. logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
  856. maxfd = 0; /* stdin */
  857. }
  858. else {
  859. /* there's always a socket to wait for */
  860. FD_SET(sockfd, &fds_read);
  861. #ifdef USE_WINSOCK
  862. FD_SET(sockfd, &fds_err);
  863. #endif
  864. maxfd = (int)sockfd;
  865. }
  866. break;
  867. case ACTIVE:
  868. sockfd = *sockfdp;
  869. /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
  870. if(CURL_SOCKET_BAD != sockfd) {
  871. FD_SET(sockfd, &fds_read);
  872. #ifdef USE_WINSOCK
  873. FD_SET(sockfd, &fds_err);
  874. #endif
  875. maxfd = (int)sockfd;
  876. }
  877. else {
  878. logmsg("No socket to read on");
  879. maxfd = 0;
  880. }
  881. break;
  882. case ACTIVE_DISCONNECT:
  883. logmsg("disconnected, no socket to read on");
  884. maxfd = 0;
  885. sockfd = CURL_SOCKET_BAD;
  886. break;
  887. } /* switch(*mode) */
  888. do {
  889. /* select() blocking behavior call on blocking descriptors please */
  890. rc = select(maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
  891. if(got_exit_signal) {
  892. logmsg("signalled to die, exiting...");
  893. return FALSE;
  894. }
  895. } while((rc == -1) && ((error = errno) == EINTR));
  896. if(rc < 0) {
  897. logmsg("select() failed with error: (%d) %s",
  898. error, strerror(error));
  899. return FALSE;
  900. }
  901. if(rc == 0)
  902. /* timeout */
  903. return TRUE;
  904. if(FD_ISSET(fileno(stdin), &fds_read)) {
  905. ssize_t buffer_len;
  906. /* read from stdin, commands/data to be dealt with and possibly passed on
  907. to the socket
  908. protocol:
  909. 4 letter command + LF [mandatory]
  910. 4-digit hexadecimal data length + LF [if the command takes data]
  911. data [the data being as long as set above]
  912. Commands:
  913. DATA - plain pass-through data
  914. */
  915. if(!read_stdin(buffer, 5))
  916. return FALSE;
  917. logmsg("Received %c%c%c%c (on stdin)",
  918. buffer[0], buffer[1], buffer[2], buffer[3]);
  919. if(!memcmp("PING", buffer, 4)) {
  920. /* send reply on stdout, just proving we are alive */
  921. if(!write_stdout("PONG\n", 5))
  922. return FALSE;
  923. }
  924. else if(!memcmp("PORT", buffer, 4)) {
  925. /* Question asking us what PORT number we are listening to.
  926. Replies to PORT with "IPv[num]/[port]" */
  927. snprintf((char *)buffer, sizeof(buffer), "%s/%hu\n", ipv_inuse, port);
  928. buffer_len = (ssize_t)strlen((char *)buffer);
  929. snprintf(data, sizeof(data), "PORT\n%04zx\n", buffer_len);
  930. if(!write_stdout(data, 10))
  931. return FALSE;
  932. if(!write_stdout(buffer, buffer_len))
  933. return FALSE;
  934. }
  935. else if(!memcmp("QUIT", buffer, 4)) {
  936. /* just die */
  937. logmsg("quits");
  938. return FALSE;
  939. }
  940. else if(!memcmp("DATA", buffer, 4)) {
  941. /* data IN => data OUT */
  942. if(!read_stdin(buffer, 5))
  943. return FALSE;
  944. buffer[5] = '\0';
  945. buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
  946. if(buffer_len > (ssize_t)sizeof(buffer)) {
  947. logmsg("ERROR: Buffer size (%zu bytes) too small for data size "
  948. "(%zd bytes)", sizeof(buffer), buffer_len);
  949. return FALSE;
  950. }
  951. logmsg("> %zd bytes data, server => client", buffer_len);
  952. if(!read_stdin(buffer, buffer_len))
  953. return FALSE;
  954. lograw(buffer, buffer_len);
  955. if(*mode == PASSIVE_LISTEN) {
  956. logmsg("*** We are disconnected!");
  957. if(!write_stdout("DISC\n", 5))
  958. return FALSE;
  959. }
  960. else {
  961. /* send away on the socket */
  962. ssize_t bytes_written = swrite(sockfd, buffer, buffer_len);
  963. if(bytes_written != buffer_len) {
  964. logmsg("Not all data was sent. Bytes to send: %zd sent: %zd",
  965. buffer_len, bytes_written);
  966. }
  967. }
  968. }
  969. else if(!memcmp("DISC", buffer, 4)) {
  970. /* disconnect! */
  971. if(!write_stdout("DISC\n", 5))
  972. return FALSE;
  973. if(sockfd != CURL_SOCKET_BAD) {
  974. logmsg("====> Client forcibly disconnected");
  975. sclose(sockfd);
  976. *sockfdp = CURL_SOCKET_BAD;
  977. if(*mode == PASSIVE_CONNECT)
  978. *mode = PASSIVE_LISTEN;
  979. else
  980. *mode = ACTIVE_DISCONNECT;
  981. }
  982. else
  983. logmsg("attempt to close already dead connection");
  984. return TRUE;
  985. }
  986. }
  987. if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
  988. ssize_t nread_socket;
  989. if(*mode == PASSIVE_LISTEN) {
  990. /* there's no stream set up yet, this is an indication that there's a
  991. client connecting. */
  992. curl_socket_t newfd = accept(sockfd, NULL, NULL);
  993. if(CURL_SOCKET_BAD == newfd) {
  994. error = SOCKERRNO;
  995. logmsg("accept(%d, NULL, NULL) failed with error: (%d) %s",
  996. sockfd, error, strerror(error));
  997. }
  998. else {
  999. logmsg("====> Client connect");
  1000. if(!write_stdout("CNCT\n", 5))
  1001. return FALSE;
  1002. *sockfdp = newfd; /* store the new socket */
  1003. *mode = PASSIVE_CONNECT; /* we have connected */
  1004. }
  1005. return TRUE;
  1006. }
  1007. /* read from socket, pass on data to stdout */
  1008. nread_socket = sread(sockfd, buffer, sizeof(buffer));
  1009. if(nread_socket > 0) {
  1010. snprintf(data, sizeof(data), "DATA\n%04zx\n", nread_socket);
  1011. if(!write_stdout(data, 10))
  1012. return FALSE;
  1013. if(!write_stdout(buffer, nread_socket))
  1014. return FALSE;
  1015. logmsg("< %zd bytes data, client => server", nread_socket);
  1016. lograw(buffer, nread_socket);
  1017. }
  1018. if(nread_socket <= 0
  1019. #ifdef USE_WINSOCK
  1020. || FD_ISSET(sockfd, &fds_err)
  1021. #endif
  1022. ) {
  1023. logmsg("====> Client disconnect");
  1024. if(!write_stdout("DISC\n", 5))
  1025. return FALSE;
  1026. sclose(sockfd);
  1027. *sockfdp = CURL_SOCKET_BAD;
  1028. if(*mode == PASSIVE_CONNECT)
  1029. *mode = PASSIVE_LISTEN;
  1030. else
  1031. *mode = ACTIVE_DISCONNECT;
  1032. return TRUE;
  1033. }
  1034. }
  1035. return TRUE;
  1036. }
  1037. static curl_socket_t sockdaemon(curl_socket_t sock,
  1038. unsigned short *listenport)
  1039. {
  1040. /* passive daemon style */
  1041. srvr_sockaddr_union_t listener;
  1042. int flag;
  1043. int rc;
  1044. int totdelay = 0;
  1045. int maxretr = 10;
  1046. int delay = 20;
  1047. int attempt = 0;
  1048. int error = 0;
  1049. do {
  1050. attempt++;
  1051. flag = 1;
  1052. rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
  1053. (void *)&flag, sizeof(flag));
  1054. if(rc) {
  1055. error = SOCKERRNO;
  1056. logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
  1057. error, strerror(error));
  1058. if(maxretr) {
  1059. rc = wait_ms(delay);
  1060. if(rc) {
  1061. /* should not happen */
  1062. error = errno;
  1063. logmsg("wait_ms() failed with error: (%d) %s",
  1064. error, strerror(error));
  1065. sclose(sock);
  1066. return CURL_SOCKET_BAD;
  1067. }
  1068. if(got_exit_signal) {
  1069. logmsg("signalled to die, exiting...");
  1070. sclose(sock);
  1071. return CURL_SOCKET_BAD;
  1072. }
  1073. totdelay += delay;
  1074. delay *= 2; /* double the sleep for next attempt */
  1075. }
  1076. }
  1077. } while(rc && maxretr--);
  1078. if(rc) {
  1079. logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
  1080. attempt, totdelay, error, strerror(error));
  1081. logmsg("Continuing anyway...");
  1082. }
  1083. /* When the specified listener port is zero, it is actually a
  1084. request to let the system choose a non-zero available port. */
  1085. #ifdef ENABLE_IPV6
  1086. if(!use_ipv6) {
  1087. #endif
  1088. memset(&listener.sa4, 0, sizeof(listener.sa4));
  1089. listener.sa4.sin_family = AF_INET;
  1090. listener.sa4.sin_addr.s_addr = INADDR_ANY;
  1091. listener.sa4.sin_port = htons(*listenport);
  1092. rc = bind(sock, &listener.sa, sizeof(listener.sa4));
  1093. #ifdef ENABLE_IPV6
  1094. }
  1095. else {
  1096. memset(&listener.sa6, 0, sizeof(listener.sa6));
  1097. listener.sa6.sin6_family = AF_INET6;
  1098. listener.sa6.sin6_addr = in6addr_any;
  1099. listener.sa6.sin6_port = htons(*listenport);
  1100. rc = bind(sock, &listener.sa, sizeof(listener.sa6));
  1101. }
  1102. #endif /* ENABLE_IPV6 */
  1103. if(rc) {
  1104. error = SOCKERRNO;
  1105. logmsg("Error binding socket on port %hu: (%d) %s",
  1106. *listenport, error, strerror(error));
  1107. sclose(sock);
  1108. return CURL_SOCKET_BAD;
  1109. }
  1110. if(!*listenport) {
  1111. /* The system was supposed to choose a port number, figure out which
  1112. port we actually got and update the listener port value with it. */
  1113. curl_socklen_t la_size;
  1114. srvr_sockaddr_union_t localaddr;
  1115. #ifdef ENABLE_IPV6
  1116. if(!use_ipv6)
  1117. #endif
  1118. la_size = sizeof(localaddr.sa4);
  1119. #ifdef ENABLE_IPV6
  1120. else
  1121. la_size = sizeof(localaddr.sa6);
  1122. #endif
  1123. memset(&localaddr.sa, 0, (size_t)la_size);
  1124. if(getsockname(sock, &localaddr.sa, &la_size) < 0) {
  1125. error = SOCKERRNO;
  1126. logmsg("getsockname() failed with error: (%d) %s",
  1127. error, strerror(error));
  1128. sclose(sock);
  1129. return CURL_SOCKET_BAD;
  1130. }
  1131. switch(localaddr.sa.sa_family) {
  1132. case AF_INET:
  1133. *listenport = ntohs(localaddr.sa4.sin_port);
  1134. break;
  1135. #ifdef ENABLE_IPV6
  1136. case AF_INET6:
  1137. *listenport = ntohs(localaddr.sa6.sin6_port);
  1138. break;
  1139. #endif
  1140. default:
  1141. break;
  1142. }
  1143. if(!*listenport) {
  1144. /* Real failure, listener port shall not be zero beyond this point. */
  1145. logmsg("Apparently getsockname() succeeded, with listener port zero.");
  1146. logmsg("A valid reason for this failure is a binary built without");
  1147. logmsg("proper network library linkage. This might not be the only");
  1148. logmsg("reason, but double check it before anything else.");
  1149. sclose(sock);
  1150. return CURL_SOCKET_BAD;
  1151. }
  1152. }
  1153. /* bindonly option forces no listening */
  1154. if(bind_only) {
  1155. logmsg("instructed to bind port without listening");
  1156. return sock;
  1157. }
  1158. /* start accepting connections */
  1159. rc = listen(sock, 5);
  1160. if(0 != rc) {
  1161. error = SOCKERRNO;
  1162. logmsg("listen(%d, 5) failed with error: (%d) %s",
  1163. sock, error, strerror(error));
  1164. sclose(sock);
  1165. return CURL_SOCKET_BAD;
  1166. }
  1167. return sock;
  1168. }
  1169. int main(int argc, char *argv[])
  1170. {
  1171. srvr_sockaddr_union_t me;
  1172. curl_socket_t sock = CURL_SOCKET_BAD;
  1173. curl_socket_t msgsock = CURL_SOCKET_BAD;
  1174. int wrotepidfile = 0;
  1175. const char *pidname = ".sockfilt.pid";
  1176. bool juggle_again;
  1177. int rc;
  1178. int error;
  1179. int arg = 1;
  1180. enum sockmode mode = PASSIVE_LISTEN; /* default */
  1181. const char *addr = NULL;
  1182. while(argc>arg) {
  1183. if(!strcmp("--version", argv[arg])) {
  1184. printf("sockfilt IPv4%s\n",
  1185. #ifdef ENABLE_IPV6
  1186. "/IPv6"
  1187. #else
  1188. ""
  1189. #endif
  1190. );
  1191. return 0;
  1192. }
  1193. else if(!strcmp("--verbose", argv[arg])) {
  1194. verbose = TRUE;
  1195. arg++;
  1196. }
  1197. else if(!strcmp("--pidfile", argv[arg])) {
  1198. arg++;
  1199. if(argc>arg)
  1200. pidname = argv[arg++];
  1201. }
  1202. else if(!strcmp("--logfile", argv[arg])) {
  1203. arg++;
  1204. if(argc>arg)
  1205. serverlogfile = argv[arg++];
  1206. }
  1207. else if(!strcmp("--ipv6", argv[arg])) {
  1208. #ifdef ENABLE_IPV6
  1209. ipv_inuse = "IPv6";
  1210. use_ipv6 = TRUE;
  1211. #endif
  1212. arg++;
  1213. }
  1214. else if(!strcmp("--ipv4", argv[arg])) {
  1215. /* for completeness, we support this option as well */
  1216. #ifdef ENABLE_IPV6
  1217. ipv_inuse = "IPv4";
  1218. use_ipv6 = FALSE;
  1219. #endif
  1220. arg++;
  1221. }
  1222. else if(!strcmp("--bindonly", argv[arg])) {
  1223. bind_only = TRUE;
  1224. arg++;
  1225. }
  1226. else if(!strcmp("--port", argv[arg])) {
  1227. arg++;
  1228. if(argc>arg) {
  1229. char *endptr;
  1230. unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
  1231. if((endptr != argv[arg] + strlen(argv[arg])) ||
  1232. ((ulnum != 0UL) && ((ulnum < 1025UL) || (ulnum > 65535UL)))) {
  1233. fprintf(stderr, "sockfilt: invalid --port argument (%s)\n",
  1234. argv[arg]);
  1235. return 0;
  1236. }
  1237. port = curlx_ultous(ulnum);
  1238. arg++;
  1239. }
  1240. }
  1241. else if(!strcmp("--connect", argv[arg])) {
  1242. /* Asked to actively connect to the specified local port instead of
  1243. doing a passive server-style listening. */
  1244. arg++;
  1245. if(argc>arg) {
  1246. char *endptr;
  1247. unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
  1248. if((endptr != argv[arg] + strlen(argv[arg])) ||
  1249. (ulnum < 1025UL) || (ulnum > 65535UL)) {
  1250. fprintf(stderr, "sockfilt: invalid --connect argument (%s)\n",
  1251. argv[arg]);
  1252. return 0;
  1253. }
  1254. connectport = curlx_ultous(ulnum);
  1255. arg++;
  1256. }
  1257. }
  1258. else if(!strcmp("--addr", argv[arg])) {
  1259. /* Set an IP address to use with --connect; otherwise use localhost */
  1260. arg++;
  1261. if(argc>arg) {
  1262. addr = argv[arg];
  1263. arg++;
  1264. }
  1265. }
  1266. else {
  1267. puts("Usage: sockfilt [option]\n"
  1268. " --version\n"
  1269. " --verbose\n"
  1270. " --logfile [file]\n"
  1271. " --pidfile [file]\n"
  1272. " --ipv4\n"
  1273. " --ipv6\n"
  1274. " --bindonly\n"
  1275. " --port [port]\n"
  1276. " --connect [port]\n"
  1277. " --addr [address]");
  1278. return 0;
  1279. }
  1280. }
  1281. #ifdef WIN32
  1282. win32_init();
  1283. atexit(win32_cleanup);
  1284. setmode(fileno(stdin), O_BINARY);
  1285. setmode(fileno(stdout), O_BINARY);
  1286. setmode(fileno(stderr), O_BINARY);
  1287. #endif
  1288. install_signal_handlers();
  1289. #ifdef ENABLE_IPV6
  1290. if(!use_ipv6)
  1291. #endif
  1292. sock = socket(AF_INET, SOCK_STREAM, 0);
  1293. #ifdef ENABLE_IPV6
  1294. else
  1295. sock = socket(AF_INET6, SOCK_STREAM, 0);
  1296. #endif
  1297. if(CURL_SOCKET_BAD == sock) {
  1298. error = SOCKERRNO;
  1299. logmsg("Error creating socket: (%d) %s",
  1300. error, strerror(error));
  1301. write_stdout("FAIL\n", 5);
  1302. goto sockfilt_cleanup;
  1303. }
  1304. if(connectport) {
  1305. /* Active mode, we should connect to the given port number */
  1306. mode = ACTIVE;
  1307. #ifdef ENABLE_IPV6
  1308. if(!use_ipv6) {
  1309. #endif
  1310. memset(&me.sa4, 0, sizeof(me.sa4));
  1311. me.sa4.sin_family = AF_INET;
  1312. me.sa4.sin_port = htons(connectport);
  1313. me.sa4.sin_addr.s_addr = INADDR_ANY;
  1314. if(!addr)
  1315. addr = "127.0.0.1";
  1316. Curl_inet_pton(AF_INET, addr, &me.sa4.sin_addr);
  1317. rc = connect(sock, &me.sa, sizeof(me.sa4));
  1318. #ifdef ENABLE_IPV6
  1319. }
  1320. else {
  1321. memset(&me.sa6, 0, sizeof(me.sa6));
  1322. me.sa6.sin6_family = AF_INET6;
  1323. me.sa6.sin6_port = htons(connectport);
  1324. if(!addr)
  1325. addr = "::1";
  1326. Curl_inet_pton(AF_INET6, addr, &me.sa6.sin6_addr);
  1327. rc = connect(sock, &me.sa, sizeof(me.sa6));
  1328. }
  1329. #endif /* ENABLE_IPV6 */
  1330. if(rc) {
  1331. error = SOCKERRNO;
  1332. logmsg("Error connecting to port %hu: (%d) %s",
  1333. connectport, error, strerror(error));
  1334. write_stdout("FAIL\n", 5);
  1335. goto sockfilt_cleanup;
  1336. }
  1337. logmsg("====> Client connect");
  1338. msgsock = sock; /* use this as stream */
  1339. }
  1340. else {
  1341. /* passive daemon style */
  1342. sock = sockdaemon(sock, &port);
  1343. if(CURL_SOCKET_BAD == sock) {
  1344. write_stdout("FAIL\n", 5);
  1345. goto sockfilt_cleanup;
  1346. }
  1347. msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
  1348. }
  1349. logmsg("Running %s version", ipv_inuse);
  1350. if(connectport)
  1351. logmsg("Connected to port %hu", connectport);
  1352. else if(bind_only)
  1353. logmsg("Bound without listening on port %hu", port);
  1354. else
  1355. logmsg("Listening on port %hu", port);
  1356. wrotepidfile = write_pidfile(pidname);
  1357. if(!wrotepidfile) {
  1358. write_stdout("FAIL\n", 5);
  1359. goto sockfilt_cleanup;
  1360. }
  1361. do {
  1362. juggle_again = juggle(&msgsock, sock, &mode);
  1363. } while(juggle_again);
  1364. sockfilt_cleanup:
  1365. if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
  1366. sclose(msgsock);
  1367. if(sock != CURL_SOCKET_BAD)
  1368. sclose(sock);
  1369. if(wrotepidfile)
  1370. unlink(pidname);
  1371. restore_signal_handlers();
  1372. if(got_exit_signal) {
  1373. logmsg("============> sockfilt exits with signal (%d)", exit_signal);
  1374. /*
  1375. * To properly set the return status of the process we
  1376. * must raise the same signal SIGINT or SIGTERM that we
  1377. * caught and let the old handler take care of it.
  1378. */
  1379. raise(exit_signal);
  1380. }
  1381. logmsg("============> sockfilt quits");
  1382. return 0;
  1383. }