sockfilt.c 45 KB

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