2
0

sockfilt.c 45 KB

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