sockfilt.c 43 KB

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