sockfilt.c 43 KB

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