sockfilt.c 45 KB

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