sockfilt.c 43 KB

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