sockfilt.c 44 KB

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