sockfilt.c 44 KB

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