sockfilt.c 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2013, 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 http://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 as
  55. * simple as possible, due to this the only signal handling mechanisms used will
  56. * be those of ANSI C, and used only in the most basic form which is good enough
  57. * 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 done.
  61. * If possible, signals SIGINT and SIGTERM will be handled by this program as an
  62. * indication to cleanup and finish execution as soon as possible. This will be
  63. * achieved with a single signal handler 'exit_signal_handler' for both signals.
  64. *
  65. * The 'exit_signal_handler' upon the first SIGINT or SIGTERM received signal
  66. * will just set to one the global var 'got_exit_signal' storing in global var
  67. * 'exit_signal' the signal that triggered this change.
  68. *
  69. * Nothing fancy that could introduce problems is used, the program at certain
  70. * points in its normal flow checks if var 'got_exit_signal' is set and in case
  71. * this is true it just makes its way out of loops and functions in structured
  72. * and well behaved manner to achieve proper program cleanup and termination.
  73. *
  74. * Even with the above mechanism implemented it is worthwile to note that other
  75. * signals might still be received, or that there might be systems on which it
  76. * is not possible to trap and ignore some of the above signals. This implies
  77. * that for increased portability and reliability the program must be coded as
  78. * if no signal was being ignored or handled at all. Enjoy it!
  79. */
  80. #ifdef HAVE_SIGNAL_H
  81. #include <signal.h>
  82. #endif
  83. #ifdef HAVE_NETINET_IN_H
  84. #include <netinet/in.h>
  85. #endif
  86. #ifdef HAVE_ARPA_INET_H
  87. #include <arpa/inet.h>
  88. #endif
  89. #ifdef HAVE_NETDB_H
  90. #include <netdb.h>
  91. #endif
  92. #ifdef USE_WINSOCK
  93. #include <conio.h> /* for _kbhit() used in select_ws() */
  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. if((old_sighup_handler = signal(SIGHUP, SIG_IGN)) == SIG_ERR)
  182. logmsg("cannot install SIGHUP handler: %s", strerror(errno));
  183. #endif
  184. #ifdef SIGPIPE
  185. /* ignore SIGPIPE signal */
  186. if((old_sigpipe_handler = signal(SIGPIPE, SIG_IGN)) == SIG_ERR)
  187. logmsg("cannot install SIGPIPE handler: %s", strerror(errno));
  188. #endif
  189. #ifdef SIGALRM
  190. /* ignore SIGALRM signal */
  191. if((old_sigalrm_handler = signal(SIGALRM, SIG_IGN)) == SIG_ERR)
  192. logmsg("cannot install SIGALRM handler: %s", strerror(errno));
  193. #endif
  194. #ifdef SIGINT
  195. /* handle SIGINT signal with our exit_signal_handler */
  196. if((old_sigint_handler = signal(SIGINT, exit_signal_handler)) == SIG_ERR)
  197. logmsg("cannot install SIGINT handler: %s", strerror(errno));
  198. else
  199. siginterrupt(SIGINT, 1);
  200. #endif
  201. #ifdef SIGTERM
  202. /* handle SIGTERM signal with our exit_signal_handler */
  203. if((old_sigterm_handler = signal(SIGTERM, exit_signal_handler)) == SIG_ERR)
  204. logmsg("cannot install SIGTERM handler: %s", strerror(errno));
  205. else
  206. siginterrupt(SIGTERM, 1);
  207. #endif
  208. #if defined(SIGBREAK) && defined(WIN32)
  209. /* handle SIGBREAK signal with our exit_signal_handler */
  210. if((old_sigbreak_handler = signal(SIGBREAK, exit_signal_handler)) == SIG_ERR)
  211. logmsg("cannot install SIGBREAK handler: %s", strerror(errno));
  212. else
  213. siginterrupt(SIGBREAK, 1);
  214. #endif
  215. }
  216. static void restore_signal_handlers(void)
  217. {
  218. #ifdef SIGHUP
  219. if(SIG_ERR != old_sighup_handler)
  220. (void)signal(SIGHUP, old_sighup_handler);
  221. #endif
  222. #ifdef SIGPIPE
  223. if(SIG_ERR != old_sigpipe_handler)
  224. (void)signal(SIGPIPE, old_sigpipe_handler);
  225. #endif
  226. #ifdef SIGALRM
  227. if(SIG_ERR != old_sigalrm_handler)
  228. (void)signal(SIGALRM, old_sigalrm_handler);
  229. #endif
  230. #ifdef SIGINT
  231. if(SIG_ERR != old_sigint_handler)
  232. (void)signal(SIGINT, old_sigint_handler);
  233. #endif
  234. #ifdef SIGTERM
  235. if(SIG_ERR != old_sigterm_handler)
  236. (void)signal(SIGTERM, old_sigterm_handler);
  237. #endif
  238. #if defined(SIGBREAK) && defined(WIN32)
  239. if(SIG_ERR != old_sigbreak_handler)
  240. (void)signal(SIGBREAK, old_sigbreak_handler);
  241. #endif
  242. }
  243. #ifdef WIN32
  244. /*
  245. * read-wrapper to support reading from stdin on Windows.
  246. */
  247. static ssize_t read_wincon(int fd, void *buf, size_t count)
  248. {
  249. HANDLE handle = NULL;
  250. DWORD mode, rcount = 0;
  251. BOOL success;
  252. if(fd == fileno(stdin)) {
  253. handle = GetStdHandle(STD_INPUT_HANDLE);
  254. }
  255. else {
  256. return read(fd, buf, count);
  257. }
  258. if(GetConsoleMode(handle, &mode)) {
  259. success = ReadConsole(handle, buf, count, &rcount, NULL);
  260. }
  261. else {
  262. success = ReadFile(handle, buf, count, &rcount, NULL);
  263. }
  264. if(success) {
  265. return rcount;
  266. }
  267. errno = GetLastError();
  268. return -1;
  269. }
  270. #define read(a,b,c) read_wincon(a,b,c)
  271. /*
  272. * write-wrapper to support writing to stdout and stderr on Windows.
  273. */
  274. static ssize_t write_wincon(int fd, const void *buf, size_t count)
  275. {
  276. HANDLE handle = NULL;
  277. DWORD mode, wcount = 0;
  278. BOOL success;
  279. if(fd == fileno(stdout)) {
  280. handle = GetStdHandle(STD_OUTPUT_HANDLE);
  281. }
  282. else if(fd == fileno(stderr)) {
  283. handle = GetStdHandle(STD_ERROR_HANDLE);
  284. }
  285. else {
  286. return write(fd, buf, count);
  287. }
  288. if(GetConsoleMode(handle, &mode)) {
  289. success = WriteConsole(handle, buf, count, &wcount, NULL);
  290. }
  291. else {
  292. success = WriteFile(handle, buf, count, &wcount, NULL);
  293. }
  294. if(success) {
  295. return wcount;
  296. }
  297. errno = GetLastError();
  298. return -1;
  299. }
  300. #define write(a,b,c) write_wincon(a,b,c)
  301. #endif
  302. /*
  303. * fullread is a wrapper around the read() function. This will repeat the call
  304. * to read() until it actually has read the complete number of bytes indicated
  305. * in nbytes or it fails with a condition that cannot be handled with a simple
  306. * retry of the read call.
  307. */
  308. static ssize_t fullread(int filedes, void *buffer, size_t nbytes)
  309. {
  310. int error;
  311. ssize_t rc;
  312. ssize_t nread = 0;
  313. do {
  314. rc = read(filedes, (unsigned char *)buffer + nread, nbytes - nread);
  315. if(got_exit_signal) {
  316. logmsg("signalled to die");
  317. return -1;
  318. }
  319. if(rc < 0) {
  320. error = errno;
  321. if((error == EINTR) || (error == EAGAIN))
  322. continue;
  323. logmsg("reading from file descriptor: %d,", filedes);
  324. logmsg("unrecoverable read() failure: (%d) %s",
  325. error, strerror(error));
  326. return -1;
  327. }
  328. if(rc == 0) {
  329. logmsg("got 0 reading from stdin");
  330. return 0;
  331. }
  332. nread += rc;
  333. } while((size_t)nread < nbytes);
  334. if(verbose)
  335. logmsg("read %zd bytes", nread);
  336. return nread;
  337. }
  338. /*
  339. * fullwrite is a wrapper around the write() function. This will repeat the
  340. * call to write() until it actually has written the complete number of bytes
  341. * indicated in nbytes or it fails with a condition that cannot be handled
  342. * with a simple retry of the write call.
  343. */
  344. static ssize_t fullwrite(int filedes, const void *buffer, size_t nbytes)
  345. {
  346. int error;
  347. ssize_t wc;
  348. ssize_t nwrite = 0;
  349. do {
  350. wc = write(filedes, (unsigned char *)buffer + nwrite, nbytes - nwrite);
  351. if(got_exit_signal) {
  352. logmsg("signalled to die");
  353. return -1;
  354. }
  355. if(wc < 0) {
  356. error = errno;
  357. if((error == EINTR) || (error == EAGAIN))
  358. continue;
  359. logmsg("writing to file descriptor: %d,", filedes);
  360. logmsg("unrecoverable write() failure: (%d) %s",
  361. error, strerror(error));
  362. return -1;
  363. }
  364. if(wc == 0) {
  365. logmsg("put 0 writing to stdout");
  366. return 0;
  367. }
  368. nwrite += wc;
  369. } while((size_t)nwrite < nbytes);
  370. if(verbose)
  371. logmsg("wrote %zd bytes", nwrite);
  372. return nwrite;
  373. }
  374. /*
  375. * read_stdin tries to read from stdin nbytes into the given buffer. This is a
  376. * blocking function that will only return TRUE when nbytes have actually been
  377. * read or FALSE when an unrecoverable error has been detected. Failure of this
  378. * function is an indication that the sockfilt process should terminate.
  379. */
  380. static bool read_stdin(void *buffer, size_t nbytes)
  381. {
  382. ssize_t nread = fullread(fileno(stdin), buffer, nbytes);
  383. if(nread != (ssize_t)nbytes) {
  384. logmsg("exiting...");
  385. return FALSE;
  386. }
  387. return TRUE;
  388. }
  389. /*
  390. * write_stdout tries to write to stdio nbytes from the given buffer. This is a
  391. * blocking function that will only return TRUE when nbytes have actually been
  392. * written or FALSE when an unrecoverable error has been detected. Failure of
  393. * this function is an indication that the sockfilt process should terminate.
  394. */
  395. static bool write_stdout(const void *buffer, size_t nbytes)
  396. {
  397. ssize_t nwrite = fullwrite(fileno(stdout), buffer, nbytes);
  398. if(nwrite != (ssize_t)nbytes) {
  399. logmsg("exiting...");
  400. return FALSE;
  401. }
  402. return TRUE;
  403. }
  404. static void lograw(unsigned char *buffer, ssize_t len)
  405. {
  406. char data[120];
  407. ssize_t i;
  408. unsigned char *ptr = buffer;
  409. char *optr = data;
  410. ssize_t width=0;
  411. for(i=0; i<len; i++) {
  412. switch(ptr[i]) {
  413. case '\n':
  414. sprintf(optr, "\\n");
  415. width += 2;
  416. optr += 2;
  417. break;
  418. case '\r':
  419. sprintf(optr, "\\r");
  420. width += 2;
  421. optr += 2;
  422. break;
  423. default:
  424. sprintf(optr, "%c", (ISGRAPH(ptr[i]) || ptr[i]==0x20) ?ptr[i]:'.');
  425. width++;
  426. optr++;
  427. break;
  428. }
  429. if(width>60) {
  430. logmsg("'%s'", data);
  431. width = 0;
  432. optr = data;
  433. }
  434. }
  435. if(width)
  436. logmsg("'%s'", data);
  437. }
  438. #ifdef USE_WINSOCK
  439. /*
  440. * WinSock select() does not support standard file descriptors,
  441. * it can only check SOCKETs. The following function is an attempt
  442. * to re-create a select() function with support for other handle types.
  443. *
  444. * select() function with support for WINSOCK2 sockets and all
  445. * other handle types supported by WaitForMultipleObjectsEx().
  446. *
  447. * TODO: Differentiate between read/write/except for non-SOCKET handles.
  448. *
  449. * http://msdn.microsoft.com/en-us/library/windows/desktop/ms687028.aspx
  450. * http://msdn.microsoft.com/en-us/library/windows/desktop/ms741572.aspx
  451. */
  452. static int select_ws(int nfds, fd_set *readfds, fd_set *writefds,
  453. fd_set *exceptfds, struct timeval *timeout)
  454. {
  455. long networkevents;
  456. DWORD milliseconds, wait, idx, mode, avail, events, inputs;
  457. WSAEVENT wsaevent, *wsaevents;
  458. WSANETWORKEVENTS wsanetevents;
  459. INPUT_RECORD *inputrecords;
  460. HANDLE handle, *handles;
  461. curl_socket_t sock, *fdarr, *wsasocks;
  462. int error, fds;
  463. DWORD nfd = 0, wsa = 0;
  464. int ret = 0;
  465. /* check if the input value is valid */
  466. if(nfds < 0) {
  467. errno = EINVAL;
  468. return -1;
  469. }
  470. /* check if we got descriptors, sleep in case we got none */
  471. if(!nfds) {
  472. Sleep((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000));
  473. return 0;
  474. }
  475. /* allocate internal array for the original input handles */
  476. fdarr = malloc(nfds * sizeof(curl_socket_t));
  477. if(fdarr == NULL) {
  478. errno = ENOMEM;
  479. return -1;
  480. }
  481. /* allocate internal array for the internal event handles */
  482. handles = malloc(nfds * sizeof(HANDLE));
  483. if(handles == NULL) {
  484. errno = ENOMEM;
  485. return -1;
  486. }
  487. /* allocate internal array for the internal socket handles */
  488. wsasocks = malloc(nfds * sizeof(curl_socket_t));
  489. if(wsasocks == NULL) {
  490. errno = ENOMEM;
  491. return -1;
  492. }
  493. /* allocate internal array for the internal WINSOCK2 events */
  494. wsaevents = malloc(nfds * sizeof(WSAEVENT));
  495. if(wsaevents == NULL) {
  496. errno = ENOMEM;
  497. return -1;
  498. }
  499. /* loop over the handles in the input descriptor sets */
  500. for(fds = 0; fds < nfds; fds++) {
  501. networkevents = 0;
  502. handles[nfd] = 0;
  503. if(FD_ISSET(fds, readfds))
  504. networkevents |= FD_READ|FD_ACCEPT|FD_CLOSE;
  505. if(FD_ISSET(fds, writefds))
  506. networkevents |= FD_WRITE|FD_CONNECT;
  507. if(FD_ISSET(fds, exceptfds))
  508. networkevents |= FD_OOB|FD_CLOSE;
  509. /* only wait for events for which we actually care */
  510. if(networkevents) {
  511. fdarr[nfd] = curlx_sitosk(fds);
  512. if(fds == fileno(stdin)) {
  513. handles[nfd] = GetStdHandle(STD_INPUT_HANDLE);
  514. }
  515. else if(fds == fileno(stdout)) {
  516. handles[nfd] = GetStdHandle(STD_OUTPUT_HANDLE);
  517. }
  518. else if(fds == fileno(stderr)) {
  519. handles[nfd] = GetStdHandle(STD_ERROR_HANDLE);
  520. }
  521. else {
  522. wsaevent = WSACreateEvent();
  523. if(wsaevent != WSA_INVALID_EVENT) {
  524. error = WSAEventSelect(fds, wsaevent, networkevents);
  525. if(error != SOCKET_ERROR) {
  526. handles[nfd] = wsaevent;
  527. wsasocks[wsa] = curlx_sitosk(fds);
  528. wsaevents[wsa] = wsaevent;
  529. wsa++;
  530. }
  531. else {
  532. handles[nfd] = (HANDLE) curlx_sitosk(fds);
  533. WSACloseEvent(wsaevent);
  534. }
  535. }
  536. }
  537. nfd++;
  538. }
  539. }
  540. /* convert struct timeval to milliseconds */
  541. if(timeout) {
  542. milliseconds = ((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000));
  543. }
  544. else {
  545. milliseconds = INFINITE;
  546. }
  547. /* wait for one of the internal handles to trigger */
  548. wait = WaitForMultipleObjectsEx(nfd, handles, FALSE, milliseconds, FALSE);
  549. /* loop over the internal handles returned in the descriptors */
  550. for(idx = 0; idx < nfd; idx++) {
  551. handle = handles[idx];
  552. sock = fdarr[idx];
  553. fds = curlx_sktosi(sock);
  554. /* check if the current internal handle was triggered */
  555. if(wait != WAIT_FAILED && (wait - WAIT_OBJECT_0) <= idx &&
  556. WaitForSingleObjectEx(handle, 0, FALSE) == WAIT_OBJECT_0) {
  557. /* try to handle the event with STD* handle functions */
  558. if(fds == fileno(stdin)) {
  559. /* check if there is no data in the input buffer */
  560. if(!stdin->_cnt) {
  561. /* check if we are getting data from a PIPE */
  562. if(!GetConsoleMode(handle, &mode)) {
  563. /* check if there is no data from PIPE input */
  564. if(!PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL))
  565. avail = 0;
  566. if(!avail) {
  567. FD_CLR(sock, readfds);
  568. /* reduce CPU load */
  569. Sleep(10);
  570. }
  571. } /* check if there is no data from keyboard input */
  572. else if (!_kbhit()) {
  573. /* check if there are INPUT_RECORDs in the input buffer */
  574. if(GetNumberOfConsoleInputEvents(handle, &events)) {
  575. if(events > 0) {
  576. /* remove INPUT_RECORDs from the input buffer */
  577. inputrecords = (INPUT_RECORD*)malloc(events *
  578. sizeof(INPUT_RECORD));
  579. if(inputrecords) {
  580. if(!ReadConsoleInput(handle, inputrecords,
  581. events, &inputs))
  582. inputs = 0;
  583. free(inputrecords);
  584. }
  585. /* check if we got all inputs, otherwise clear buffer */
  586. if(events != inputs)
  587. FlushConsoleInputBuffer(handle);
  588. }
  589. }
  590. /* remove from descriptor set since there is no real data */
  591. FD_CLR(sock, readfds);
  592. }
  593. }
  594. /* stdin is never ready for write or exceptional */
  595. FD_CLR(sock, writefds);
  596. FD_CLR(sock, exceptfds);
  597. }
  598. else if(fds == fileno(stdout) || fds == fileno(stderr)) {
  599. /* stdout and stderr are never ready for read or exceptional */
  600. FD_CLR(sock, readfds);
  601. FD_CLR(sock, exceptfds);
  602. }
  603. else {
  604. /* try to handle the event with the WINSOCK2 functions */
  605. error = WSAEnumNetworkEvents(fds, handle, &wsanetevents);
  606. if(error != SOCKET_ERROR) {
  607. /* remove from descriptor set if not ready for read/accept/close */
  608. if(!(wsanetevents.lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE)))
  609. FD_CLR(sock, readfds);
  610. /* remove from descriptor set if not ready for write/connect */
  611. if(!(wsanetevents.lNetworkEvents & (FD_WRITE|FD_CONNECT)))
  612. FD_CLR(sock, writefds);
  613. /* HACK:
  614. * use exceptfds together with readfds to signal
  615. * that the connection was closed by the client.
  616. *
  617. * Reason: FD_CLOSE is only signaled once, sometimes
  618. * at the same time as FD_READ with data being available.
  619. * This means that recv/sread is not reliable to detect
  620. * that the connection is closed.
  621. */
  622. /* remove from descriptor set if not exceptional */
  623. if(!(wsanetevents.lNetworkEvents & (FD_OOB|FD_CLOSE)))
  624. FD_CLR(sock, exceptfds);
  625. }
  626. }
  627. /* check if the event has not been filtered using specific tests */
  628. if(FD_ISSET(sock, readfds) || FD_ISSET(sock, writefds) ||
  629. FD_ISSET(sock, exceptfds)) {
  630. ret++;
  631. }
  632. }
  633. else {
  634. /* remove from all descriptor sets since this handle did not trigger */
  635. FD_CLR(sock, readfds);
  636. FD_CLR(sock, writefds);
  637. FD_CLR(sock, exceptfds);
  638. }
  639. }
  640. for(idx = 0; idx < wsa; idx++) {
  641. WSAEventSelect(wsasocks[idx], NULL, 0);
  642. WSACloseEvent(wsaevents[idx]);
  643. }
  644. free(wsaevents);
  645. free(wsasocks);
  646. free(handles);
  647. free(fdarr);
  648. return ret;
  649. }
  650. #define select(a,b,c,d,e) select_ws(a,b,c,d,e)
  651. #endif /* USE_WINSOCK */
  652. /*
  653. sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
  654. if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
  655. accept()
  656. */
  657. static bool juggle(curl_socket_t *sockfdp,
  658. curl_socket_t listenfd,
  659. enum sockmode *mode)
  660. {
  661. struct timeval timeout;
  662. fd_set fds_read;
  663. fd_set fds_write;
  664. fd_set fds_err;
  665. curl_socket_t sockfd = CURL_SOCKET_BAD;
  666. int maxfd = -99;
  667. ssize_t rc;
  668. ssize_t nread_socket;
  669. ssize_t bytes_written;
  670. ssize_t buffer_len;
  671. int error = 0;
  672. /* 'buffer' is this excessively large only to be able to support things like
  673. test 1003 which tests exceedingly large server response lines */
  674. unsigned char buffer[17010];
  675. char data[16];
  676. if(got_exit_signal) {
  677. logmsg("signalled to die, exiting...");
  678. return FALSE;
  679. }
  680. #ifdef HAVE_GETPPID
  681. /* As a last resort, quit if sockfilt process becomes orphan. Just in case
  682. parent ftpserver process has died without killing its sockfilt children */
  683. if(getppid() <= 1) {
  684. logmsg("process becomes orphan, exiting");
  685. return FALSE;
  686. }
  687. #endif
  688. timeout.tv_sec = 120;
  689. timeout.tv_usec = 0;
  690. FD_ZERO(&fds_read);
  691. FD_ZERO(&fds_write);
  692. FD_ZERO(&fds_err);
  693. FD_SET((curl_socket_t)fileno(stdin), &fds_read);
  694. switch(*mode) {
  695. case PASSIVE_LISTEN:
  696. /* server mode */
  697. sockfd = listenfd;
  698. /* there's always a socket to wait for */
  699. FD_SET(sockfd, &fds_read);
  700. maxfd = (int)sockfd;
  701. break;
  702. case PASSIVE_CONNECT:
  703. sockfd = *sockfdp;
  704. if(CURL_SOCKET_BAD == sockfd) {
  705. /* eeek, we are supposedly connected and then this cannot be -1 ! */
  706. logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
  707. maxfd = 0; /* stdin */
  708. }
  709. else {
  710. /* there's always a socket to wait for */
  711. FD_SET(sockfd, &fds_read);
  712. #ifdef USE_WINSOCK
  713. FD_SET(sockfd, &fds_err);
  714. #endif
  715. maxfd = (int)sockfd;
  716. }
  717. break;
  718. case ACTIVE:
  719. sockfd = *sockfdp;
  720. /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
  721. if(CURL_SOCKET_BAD != sockfd) {
  722. FD_SET(sockfd, &fds_read);
  723. #ifdef USE_WINSOCK
  724. FD_SET(sockfd, &fds_err);
  725. #endif
  726. maxfd = (int)sockfd;
  727. }
  728. else {
  729. logmsg("No socket to read on");
  730. maxfd = 0;
  731. }
  732. break;
  733. case ACTIVE_DISCONNECT:
  734. logmsg("disconnected, no socket to read on");
  735. maxfd = 0;
  736. sockfd = CURL_SOCKET_BAD;
  737. break;
  738. } /* switch(*mode) */
  739. do {
  740. /* select() blocking behavior call on blocking descriptors please */
  741. rc = select(maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
  742. if(got_exit_signal) {
  743. logmsg("signalled to die, exiting...");
  744. return FALSE;
  745. }
  746. } while((rc == -1) && ((error = errno) == EINTR));
  747. if(rc < 0) {
  748. logmsg("select() failed with error: (%d) %s",
  749. error, strerror(error));
  750. return FALSE;
  751. }
  752. if(rc == 0)
  753. /* timeout */
  754. return TRUE;
  755. if(FD_ISSET(fileno(stdin), &fds_read)) {
  756. /* read from stdin, commands/data to be dealt with and possibly passed on
  757. to the socket
  758. protocol:
  759. 4 letter command + LF [mandatory]
  760. 4-digit hexadecimal data length + LF [if the command takes data]
  761. data [the data being as long as set above]
  762. Commands:
  763. DATA - plain pass-thru data
  764. */
  765. if(!read_stdin(buffer, 5))
  766. return FALSE;
  767. logmsg("Received %c%c%c%c (on stdin)",
  768. buffer[0], buffer[1], buffer[2], buffer[3] );
  769. if(!memcmp("PING", buffer, 4)) {
  770. /* send reply on stdout, just proving we are alive */
  771. if(!write_stdout("PONG\n", 5))
  772. return FALSE;
  773. }
  774. else if(!memcmp("PORT", buffer, 4)) {
  775. /* Question asking us what PORT number we are listening to.
  776. Replies to PORT with "IPv[num]/[port]" */
  777. sprintf((char *)buffer, "%s/%hu\n", ipv_inuse, port);
  778. buffer_len = (ssize_t)strlen((char *)buffer);
  779. snprintf(data, sizeof(data), "PORT\n%04zx\n", buffer_len);
  780. if(!write_stdout(data, 10))
  781. return FALSE;
  782. if(!write_stdout(buffer, buffer_len))
  783. return FALSE;
  784. }
  785. else if(!memcmp("QUIT", buffer, 4)) {
  786. /* just die */
  787. logmsg("quits");
  788. return FALSE;
  789. }
  790. else if(!memcmp("DATA", buffer, 4)) {
  791. /* data IN => data OUT */
  792. if(!read_stdin(buffer, 5))
  793. return FALSE;
  794. buffer[5] = '\0';
  795. buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
  796. if (buffer_len > (ssize_t)sizeof(buffer)) {
  797. logmsg("ERROR: Buffer size (%zu bytes) too small for data size "
  798. "(%zd bytes)", sizeof(buffer), buffer_len);
  799. return FALSE;
  800. }
  801. logmsg("> %zd bytes data, server => client", buffer_len);
  802. if(!read_stdin(buffer, buffer_len))
  803. return FALSE;
  804. lograw(buffer, buffer_len);
  805. if(*mode == PASSIVE_LISTEN) {
  806. logmsg("*** We are disconnected!");
  807. if(!write_stdout("DISC\n", 5))
  808. return FALSE;
  809. }
  810. else {
  811. /* send away on the socket */
  812. bytes_written = swrite(sockfd, buffer, buffer_len);
  813. if(bytes_written != buffer_len) {
  814. logmsg("Not all data was sent. Bytes to send: %zd sent: %zd",
  815. buffer_len, bytes_written);
  816. }
  817. }
  818. }
  819. else if(!memcmp("DISC", buffer, 4)) {
  820. /* disconnect! */
  821. if(!write_stdout("DISC\n", 5))
  822. return FALSE;
  823. if(sockfd != CURL_SOCKET_BAD) {
  824. logmsg("====> Client forcibly disconnected");
  825. sclose(sockfd);
  826. *sockfdp = CURL_SOCKET_BAD;
  827. if(*mode == PASSIVE_CONNECT)
  828. *mode = PASSIVE_LISTEN;
  829. else
  830. *mode = ACTIVE_DISCONNECT;
  831. }
  832. else
  833. logmsg("attempt to close already dead connection");
  834. return TRUE;
  835. }
  836. }
  837. if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
  838. curl_socket_t newfd = CURL_SOCKET_BAD; /* newly accepted socket */
  839. if(*mode == PASSIVE_LISTEN) {
  840. /* there's no stream set up yet, this is an indication that there's a
  841. client connecting. */
  842. newfd = accept(sockfd, NULL, NULL);
  843. if(CURL_SOCKET_BAD == newfd) {
  844. error = SOCKERRNO;
  845. logmsg("accept(%d, NULL, NULL) failed with error: (%d) %s",
  846. sockfd, error, strerror(error));
  847. }
  848. else {
  849. logmsg("====> Client connect");
  850. if(!write_stdout("CNCT\n", 5))
  851. return FALSE;
  852. *sockfdp = newfd; /* store the new socket */
  853. *mode = PASSIVE_CONNECT; /* we have connected */
  854. }
  855. return TRUE;
  856. }
  857. /* read from socket, pass on data to stdout */
  858. nread_socket = sread(sockfd, buffer, sizeof(buffer));
  859. if(nread_socket > 0) {
  860. snprintf(data, sizeof(data), "DATA\n%04zx\n", nread_socket);
  861. if(!write_stdout(data, 10))
  862. return FALSE;
  863. if(!write_stdout(buffer, nread_socket))
  864. return FALSE;
  865. logmsg("< %zd bytes data, client => server", nread_socket);
  866. lograw(buffer, nread_socket);
  867. }
  868. if(nread_socket <= 0
  869. #ifdef USE_WINSOCK
  870. || FD_ISSET(sockfd, &fds_err)
  871. #endif
  872. ) {
  873. logmsg("====> Client disconnect");
  874. if(!write_stdout("DISC\n", 5))
  875. return FALSE;
  876. sclose(sockfd);
  877. *sockfdp = CURL_SOCKET_BAD;
  878. if(*mode == PASSIVE_CONNECT)
  879. *mode = PASSIVE_LISTEN;
  880. else
  881. *mode = ACTIVE_DISCONNECT;
  882. return TRUE;
  883. }
  884. }
  885. return TRUE;
  886. }
  887. static curl_socket_t sockdaemon(curl_socket_t sock,
  888. unsigned short *listenport)
  889. {
  890. /* passive daemon style */
  891. srvr_sockaddr_union_t listener;
  892. int flag;
  893. int rc;
  894. int totdelay = 0;
  895. int maxretr = 10;
  896. int delay= 20;
  897. int attempt = 0;
  898. int error = 0;
  899. do {
  900. attempt++;
  901. flag = 1;
  902. rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
  903. (void *)&flag, sizeof(flag));
  904. if(rc) {
  905. error = SOCKERRNO;
  906. logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
  907. error, strerror(error));
  908. if(maxretr) {
  909. rc = wait_ms(delay);
  910. if(rc) {
  911. /* should not happen */
  912. error = errno;
  913. logmsg("wait_ms() failed with error: (%d) %s",
  914. error, strerror(error));
  915. sclose(sock);
  916. return CURL_SOCKET_BAD;
  917. }
  918. if(got_exit_signal) {
  919. logmsg("signalled to die, exiting...");
  920. sclose(sock);
  921. return CURL_SOCKET_BAD;
  922. }
  923. totdelay += delay;
  924. delay *= 2; /* double the sleep for next attempt */
  925. }
  926. }
  927. } while(rc && maxretr--);
  928. if(rc) {
  929. logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
  930. attempt, totdelay, error, strerror(error));
  931. logmsg("Continuing anyway...");
  932. }
  933. /* When the specified listener port is zero, it is actually a
  934. request to let the system choose a non-zero available port. */
  935. #ifdef ENABLE_IPV6
  936. if(!use_ipv6) {
  937. #endif
  938. memset(&listener.sa4, 0, sizeof(listener.sa4));
  939. listener.sa4.sin_family = AF_INET;
  940. listener.sa4.sin_addr.s_addr = INADDR_ANY;
  941. listener.sa4.sin_port = htons(*listenport);
  942. rc = bind(sock, &listener.sa, sizeof(listener.sa4));
  943. #ifdef ENABLE_IPV6
  944. }
  945. else {
  946. memset(&listener.sa6, 0, sizeof(listener.sa6));
  947. listener.sa6.sin6_family = AF_INET6;
  948. listener.sa6.sin6_addr = in6addr_any;
  949. listener.sa6.sin6_port = htons(*listenport);
  950. rc = bind(sock, &listener.sa, sizeof(listener.sa6));
  951. }
  952. #endif /* ENABLE_IPV6 */
  953. if(rc) {
  954. error = SOCKERRNO;
  955. logmsg("Error binding socket on port %hu: (%d) %s",
  956. *listenport, error, strerror(error));
  957. sclose(sock);
  958. return CURL_SOCKET_BAD;
  959. }
  960. if(!*listenport) {
  961. /* The system was supposed to choose a port number, figure out which
  962. port we actually got and update the listener port value with it. */
  963. curl_socklen_t la_size;
  964. srvr_sockaddr_union_t localaddr;
  965. #ifdef ENABLE_IPV6
  966. if(!use_ipv6)
  967. #endif
  968. la_size = sizeof(localaddr.sa4);
  969. #ifdef ENABLE_IPV6
  970. else
  971. la_size = sizeof(localaddr.sa6);
  972. #endif
  973. memset(&localaddr.sa, 0, (size_t)la_size);
  974. if(getsockname(sock, &localaddr.sa, &la_size) < 0) {
  975. error = SOCKERRNO;
  976. logmsg("getsockname() failed with error: (%d) %s",
  977. error, strerror(error));
  978. sclose(sock);
  979. return CURL_SOCKET_BAD;
  980. }
  981. switch (localaddr.sa.sa_family) {
  982. case AF_INET:
  983. *listenport = ntohs(localaddr.sa4.sin_port);
  984. break;
  985. #ifdef ENABLE_IPV6
  986. case AF_INET6:
  987. *listenport = ntohs(localaddr.sa6.sin6_port);
  988. break;
  989. #endif
  990. default:
  991. break;
  992. }
  993. if(!*listenport) {
  994. /* Real failure, listener port shall not be zero beyond this point. */
  995. logmsg("Apparently getsockname() succeeded, with listener port zero.");
  996. logmsg("A valid reason for this failure is a binary built without");
  997. logmsg("proper network library linkage. This might not be the only");
  998. logmsg("reason, but double check it before anything else.");
  999. sclose(sock);
  1000. return CURL_SOCKET_BAD;
  1001. }
  1002. }
  1003. /* bindonly option forces no listening */
  1004. if(bind_only) {
  1005. logmsg("instructed to bind port without listening");
  1006. return sock;
  1007. }
  1008. /* start accepting connections */
  1009. rc = listen(sock, 5);
  1010. if(0 != rc) {
  1011. error = SOCKERRNO;
  1012. logmsg("listen(%d, 5) failed with error: (%d) %s",
  1013. sock, error, strerror(error));
  1014. sclose(sock);
  1015. return CURL_SOCKET_BAD;
  1016. }
  1017. return sock;
  1018. }
  1019. int main(int argc, char *argv[])
  1020. {
  1021. srvr_sockaddr_union_t me;
  1022. curl_socket_t sock = CURL_SOCKET_BAD;
  1023. curl_socket_t msgsock = CURL_SOCKET_BAD;
  1024. int wrotepidfile = 0;
  1025. char *pidname= (char *)".sockfilt.pid";
  1026. bool juggle_again;
  1027. int rc;
  1028. int error;
  1029. int arg=1;
  1030. enum sockmode mode = PASSIVE_LISTEN; /* default */
  1031. const char *addr = NULL;
  1032. while(argc>arg) {
  1033. if(!strcmp("--version", argv[arg])) {
  1034. printf("sockfilt IPv4%s\n",
  1035. #ifdef ENABLE_IPV6
  1036. "/IPv6"
  1037. #else
  1038. ""
  1039. #endif
  1040. );
  1041. return 0;
  1042. }
  1043. else if(!strcmp("--verbose", argv[arg])) {
  1044. verbose = TRUE;
  1045. arg++;
  1046. }
  1047. else if(!strcmp("--pidfile", argv[arg])) {
  1048. arg++;
  1049. if(argc>arg)
  1050. pidname = argv[arg++];
  1051. }
  1052. else if(!strcmp("--logfile", argv[arg])) {
  1053. arg++;
  1054. if(argc>arg)
  1055. serverlogfile = argv[arg++];
  1056. }
  1057. else if(!strcmp("--ipv6", argv[arg])) {
  1058. #ifdef ENABLE_IPV6
  1059. ipv_inuse = "IPv6";
  1060. use_ipv6 = TRUE;
  1061. #endif
  1062. arg++;
  1063. }
  1064. else if(!strcmp("--ipv4", argv[arg])) {
  1065. /* for completeness, we support this option as well */
  1066. #ifdef ENABLE_IPV6
  1067. ipv_inuse = "IPv4";
  1068. use_ipv6 = FALSE;
  1069. #endif
  1070. arg++;
  1071. }
  1072. else if(!strcmp("--bindonly", argv[arg])) {
  1073. bind_only = TRUE;
  1074. arg++;
  1075. }
  1076. else if(!strcmp("--port", argv[arg])) {
  1077. arg++;
  1078. if(argc>arg) {
  1079. char *endptr;
  1080. unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
  1081. if((endptr != argv[arg] + strlen(argv[arg])) ||
  1082. ((ulnum != 0UL) && ((ulnum < 1025UL) || (ulnum > 65535UL)))) {
  1083. fprintf(stderr, "sockfilt: invalid --port argument (%s)\n",
  1084. argv[arg]);
  1085. return 0;
  1086. }
  1087. port = curlx_ultous(ulnum);
  1088. arg++;
  1089. }
  1090. }
  1091. else if(!strcmp("--connect", argv[arg])) {
  1092. /* Asked to actively connect to the specified local port instead of
  1093. doing a passive server-style listening. */
  1094. arg++;
  1095. if(argc>arg) {
  1096. char *endptr;
  1097. unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
  1098. if((endptr != argv[arg] + strlen(argv[arg])) ||
  1099. (ulnum < 1025UL) || (ulnum > 65535UL)) {
  1100. fprintf(stderr, "sockfilt: invalid --connect argument (%s)\n",
  1101. argv[arg]);
  1102. return 0;
  1103. }
  1104. connectport = curlx_ultous(ulnum);
  1105. arg++;
  1106. }
  1107. }
  1108. else if(!strcmp("--addr", argv[arg])) {
  1109. /* Set an IP address to use with --connect; otherwise use localhost */
  1110. arg++;
  1111. if(argc>arg) {
  1112. addr = argv[arg];
  1113. arg++;
  1114. }
  1115. }
  1116. else {
  1117. puts("Usage: sockfilt [option]\n"
  1118. " --version\n"
  1119. " --verbose\n"
  1120. " --logfile [file]\n"
  1121. " --pidfile [file]\n"
  1122. " --ipv4\n"
  1123. " --ipv6\n"
  1124. " --bindonly\n"
  1125. " --port [port]\n"
  1126. " --connect [port]\n"
  1127. " --addr [address]");
  1128. return 0;
  1129. }
  1130. }
  1131. #ifdef WIN32
  1132. win32_init();
  1133. atexit(win32_cleanup);
  1134. setmode(fileno(stdin), O_BINARY);
  1135. setmode(fileno(stdout), O_BINARY);
  1136. setmode(fileno(stderr), O_BINARY);
  1137. #endif
  1138. install_signal_handlers();
  1139. #ifdef ENABLE_IPV6
  1140. if(!use_ipv6)
  1141. #endif
  1142. sock = socket(AF_INET, SOCK_STREAM, 0);
  1143. #ifdef ENABLE_IPV6
  1144. else
  1145. sock = socket(AF_INET6, SOCK_STREAM, 0);
  1146. #endif
  1147. if(CURL_SOCKET_BAD == sock) {
  1148. error = SOCKERRNO;
  1149. logmsg("Error creating socket: (%d) %s",
  1150. error, strerror(error));
  1151. write_stdout("FAIL\n", 5);
  1152. goto sockfilt_cleanup;
  1153. }
  1154. if(connectport) {
  1155. /* Active mode, we should connect to the given port number */
  1156. mode = ACTIVE;
  1157. #ifdef ENABLE_IPV6
  1158. if(!use_ipv6) {
  1159. #endif
  1160. memset(&me.sa4, 0, sizeof(me.sa4));
  1161. me.sa4.sin_family = AF_INET;
  1162. me.sa4.sin_port = htons(connectport);
  1163. me.sa4.sin_addr.s_addr = INADDR_ANY;
  1164. if (!addr)
  1165. addr = "127.0.0.1";
  1166. Curl_inet_pton(AF_INET, addr, &me.sa4.sin_addr);
  1167. rc = connect(sock, &me.sa, sizeof(me.sa4));
  1168. #ifdef ENABLE_IPV6
  1169. }
  1170. else {
  1171. memset(&me.sa6, 0, sizeof(me.sa6));
  1172. me.sa6.sin6_family = AF_INET6;
  1173. me.sa6.sin6_port = htons(connectport);
  1174. if (!addr)
  1175. addr = "::1";
  1176. Curl_inet_pton(AF_INET6, addr, &me.sa6.sin6_addr);
  1177. rc = connect(sock, &me.sa, sizeof(me.sa6));
  1178. }
  1179. #endif /* ENABLE_IPV6 */
  1180. if(rc) {
  1181. error = SOCKERRNO;
  1182. logmsg("Error connecting to port %hu: (%d) %s",
  1183. connectport, error, strerror(error));
  1184. write_stdout("FAIL\n", 5);
  1185. goto sockfilt_cleanup;
  1186. }
  1187. logmsg("====> Client connect");
  1188. msgsock = sock; /* use this as stream */
  1189. }
  1190. else {
  1191. /* passive daemon style */
  1192. sock = sockdaemon(sock, &port);
  1193. if(CURL_SOCKET_BAD == sock) {
  1194. write_stdout("FAIL\n", 5);
  1195. goto sockfilt_cleanup;
  1196. }
  1197. msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
  1198. }
  1199. logmsg("Running %s version", ipv_inuse);
  1200. if(connectport)
  1201. logmsg("Connected to port %hu", connectport);
  1202. else if(bind_only)
  1203. logmsg("Bound without listening on port %hu", port);
  1204. else
  1205. logmsg("Listening on port %hu", port);
  1206. wrotepidfile = write_pidfile(pidname);
  1207. if(!wrotepidfile) {
  1208. write_stdout("FAIL\n", 5);
  1209. goto sockfilt_cleanup;
  1210. }
  1211. do {
  1212. juggle_again = juggle(&msgsock, sock, &mode);
  1213. } while(juggle_again);
  1214. sockfilt_cleanup:
  1215. if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
  1216. sclose(msgsock);
  1217. if(sock != CURL_SOCKET_BAD)
  1218. sclose(sock);
  1219. if(wrotepidfile)
  1220. unlink(pidname);
  1221. restore_signal_handlers();
  1222. if(got_exit_signal) {
  1223. logmsg("============> sockfilt exits with signal (%d)", exit_signal);
  1224. /*
  1225. * To properly set the return status of the process we
  1226. * must raise the same signal SIGINT or SIGTERM that we
  1227. * caught and let the old handler take care of it.
  1228. */
  1229. raise(exit_signal);
  1230. }
  1231. logmsg("============> sockfilt quits");
  1232. return 0;
  1233. }