sockfilt.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2009, 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. * $Id$
  22. ***************************************************************************/
  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. #include "setup.h" /* portability help from the lib directory */
  81. #ifdef HAVE_SIGNAL_H
  82. #include <signal.h>
  83. #endif
  84. #ifdef HAVE_UNISTD_H
  85. #include <unistd.h>
  86. #endif
  87. #ifdef HAVE_SYS_SOCKET_H
  88. #include <sys/socket.h>
  89. #endif
  90. #ifdef HAVE_NETINET_IN_H
  91. #include <netinet/in.h>
  92. #endif
  93. #ifdef HAVE_ARPA_INET_H
  94. #include <arpa/inet.h>
  95. #endif
  96. #ifdef HAVE_NETDB_H
  97. #include <netdb.h>
  98. #endif
  99. #define ENABLE_CURLX_PRINTF
  100. /* make the curlx header define all printf() functions to use the curlx_*
  101. versions instead */
  102. #include "curlx.h" /* from the private lib dir */
  103. #include "getpart.h"
  104. #include "inet_pton.h"
  105. #include "util.h"
  106. /* include memdebug.h last */
  107. #include "memdebug.h"
  108. #define DEFAULT_PORT 8999
  109. #ifndef DEFAULT_LOGFILE
  110. #define DEFAULT_LOGFILE "log/sockfilt.log"
  111. #endif
  112. const char *serverlogfile = DEFAULT_LOGFILE;
  113. static bool verbose = FALSE;
  114. #ifdef ENABLE_IPV6
  115. static bool use_ipv6 = FALSE;
  116. #endif
  117. static const char *ipv_inuse = "IPv4";
  118. static unsigned short port = DEFAULT_PORT;
  119. static unsigned short connectport = 0; /* if non-zero, we activate this mode */
  120. enum sockmode {
  121. PASSIVE_LISTEN, /* as a server waiting for connections */
  122. PASSIVE_CONNECT, /* as a server, connected to a client */
  123. ACTIVE, /* as a client, connected to a server */
  124. ACTIVE_DISCONNECT /* as a client, disconnected from server */
  125. };
  126. /* do-nothing macro replacement for systems which lack siginterrupt() */
  127. #ifndef HAVE_SIGINTERRUPT
  128. #define siginterrupt(x,y) do {} while(0)
  129. #endif
  130. /* vars used to keep around previous signal handlers */
  131. typedef RETSIGTYPE (*SIGHANDLER_T)(int);
  132. #ifdef SIGHUP
  133. static SIGHANDLER_T old_sighup_handler = SIG_ERR;
  134. #endif
  135. #ifdef SIGPIPE
  136. static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
  137. #endif
  138. #ifdef SIGALRM
  139. static SIGHANDLER_T old_sigalrm_handler = SIG_ERR;
  140. #endif
  141. #ifdef SIGINT
  142. static SIGHANDLER_T old_sigint_handler = SIG_ERR;
  143. #endif
  144. #ifdef SIGTERM
  145. static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
  146. #endif
  147. /* var which if set indicates that the program should finish execution */
  148. SIG_ATOMIC_T got_exit_signal = 0;
  149. /* if next is set indicates the first signal handled in exit_signal_handler */
  150. static volatile int exit_signal = 0;
  151. /* signal handler that will be triggered to indicate that the program
  152. should finish its execution in a controlled manner as soon as possible.
  153. The first time this is called it will set got_exit_signal to one and
  154. store in exit_signal the signal that triggered its execution. */
  155. static RETSIGTYPE exit_signal_handler(int signum)
  156. {
  157. int old_errno = ERRNO;
  158. if(got_exit_signal == 0) {
  159. got_exit_signal = 1;
  160. exit_signal = signum;
  161. }
  162. (void)signal(signum, exit_signal_handler);
  163. SET_ERRNO(old_errno);
  164. }
  165. static void install_signal_handlers(void)
  166. {
  167. #ifdef SIGHUP
  168. /* ignore SIGHUP signal */
  169. if((old_sighup_handler = signal(SIGHUP, SIG_IGN)) == SIG_ERR)
  170. logmsg("cannot install SIGHUP handler: %s", strerror(ERRNO));
  171. #endif
  172. #ifdef SIGPIPE
  173. /* ignore SIGPIPE signal */
  174. if((old_sigpipe_handler = signal(SIGPIPE, SIG_IGN)) == SIG_ERR)
  175. logmsg("cannot install SIGPIPE handler: %s", strerror(ERRNO));
  176. #endif
  177. #ifdef SIGALRM
  178. /* ignore SIGALRM signal */
  179. if((old_sigalrm_handler = signal(SIGALRM, SIG_IGN)) == SIG_ERR)
  180. logmsg("cannot install SIGALRM handler: %s", strerror(ERRNO));
  181. #endif
  182. #ifdef SIGINT
  183. /* handle SIGINT signal with our exit_signal_handler */
  184. if((old_sigint_handler = signal(SIGINT, exit_signal_handler)) == SIG_ERR)
  185. logmsg("cannot install SIGINT handler: %s", strerror(ERRNO));
  186. else
  187. siginterrupt(SIGINT, 1);
  188. #endif
  189. #ifdef SIGTERM
  190. /* handle SIGTERM signal with our exit_signal_handler */
  191. if((old_sigterm_handler = signal(SIGTERM, exit_signal_handler)) == SIG_ERR)
  192. logmsg("cannot install SIGTERM handler: %s", strerror(ERRNO));
  193. else
  194. siginterrupt(SIGTERM, 1);
  195. #endif
  196. }
  197. static void restore_signal_handlers(void)
  198. {
  199. #ifdef SIGHUP
  200. if(SIG_ERR != old_sighup_handler)
  201. (void)signal(SIGHUP, old_sighup_handler);
  202. #endif
  203. #ifdef SIGPIPE
  204. if(SIG_ERR != old_sigpipe_handler)
  205. (void)signal(SIGPIPE, old_sigpipe_handler);
  206. #endif
  207. #ifdef SIGALRM
  208. if(SIG_ERR != old_sigalrm_handler)
  209. (void)signal(SIGALRM, old_sigalrm_handler);
  210. #endif
  211. #ifdef SIGINT
  212. if(SIG_ERR != old_sigint_handler)
  213. (void)signal(SIGINT, old_sigint_handler);
  214. #endif
  215. #ifdef SIGTERM
  216. if(SIG_ERR != old_sigterm_handler)
  217. (void)signal(SIGTERM, old_sigterm_handler);
  218. #endif
  219. }
  220. /*
  221. * fullread is a wrapper around the read() function. This will repeat the call
  222. * to read() until it actually has read the complete number of bytes indicated
  223. * in nbytes or it fails with a condition that cannot be handled with a simple
  224. * retry of the read call.
  225. */
  226. static ssize_t fullread(int filedes, void *buffer, size_t nbytes)
  227. {
  228. int error;
  229. ssize_t rc;
  230. ssize_t nread = 0;
  231. do {
  232. rc = read(filedes, (unsigned char *)buffer + nread, nbytes - nread);
  233. if(got_exit_signal) {
  234. logmsg("signalled to die");
  235. return -1;
  236. }
  237. if(rc < 0) {
  238. error = ERRNO;
  239. if((error == EINTR) || (error == EAGAIN))
  240. continue;
  241. logmsg("unrecoverable read() failure: %s", strerror(error));
  242. return -1;
  243. }
  244. if(rc == 0) {
  245. logmsg("got 0 reading from stdin");
  246. return 0;
  247. }
  248. nread += rc;
  249. } while((size_t)nread < nbytes);
  250. if(verbose)
  251. logmsg("read %zd bytes", nread);
  252. return nread;
  253. }
  254. /*
  255. * fullwrite is a wrapper around the write() function. This will repeat the
  256. * call to write() until it actually has written the complete number of bytes
  257. * indicated in nbytes or it fails with a condition that cannot be handled
  258. * with a simple retry of the write call.
  259. */
  260. static ssize_t fullwrite(int filedes, const void *buffer, size_t nbytes)
  261. {
  262. int error;
  263. ssize_t wc;
  264. ssize_t nwrite = 0;
  265. do {
  266. wc = write(filedes, (unsigned char *)buffer + nwrite, nbytes - nwrite);
  267. if(got_exit_signal) {
  268. logmsg("signalled to die");
  269. return -1;
  270. }
  271. if(wc < 0) {
  272. error = ERRNO;
  273. if((error == EINTR) || (error == EAGAIN))
  274. continue;
  275. logmsg("unrecoverable write() failure: %s", strerror(error));
  276. return -1;
  277. }
  278. if(wc == 0) {
  279. logmsg("put 0 writing to stdout");
  280. return 0;
  281. }
  282. nwrite += wc;
  283. } while((size_t)nwrite < nbytes);
  284. if(verbose)
  285. logmsg("wrote %zd bytes", nwrite);
  286. return nwrite;
  287. }
  288. /*
  289. * read_stdin tries to read from stdin nbytes into the given buffer. This is a
  290. * blocking function that will only return TRUE when nbytes have actually been
  291. * read or FALSE when an unrecoverable error has been detected. Failure of this
  292. * function is an indication that the sockfilt process should terminate.
  293. */
  294. static bool read_stdin(void *buffer, size_t nbytes)
  295. {
  296. ssize_t nread = fullread(fileno(stdin), buffer, nbytes);
  297. if(nread != (ssize_t)nbytes) {
  298. logmsg("exiting...");
  299. return FALSE;
  300. }
  301. return TRUE;
  302. }
  303. /*
  304. * write_stdout tries to write to stdio nbytes from the given buffer. This is a
  305. * blocking function that will only return TRUE when nbytes have actually been
  306. * written or FALSE when an unrecoverable error has been detected. Failure of
  307. * this function is an indication that the sockfilt process should terminate.
  308. */
  309. static bool write_stdout(const void *buffer, size_t nbytes)
  310. {
  311. ssize_t nwrite = fullwrite(fileno(stdout), buffer, nbytes);
  312. if(nwrite != (ssize_t)nbytes) {
  313. logmsg("exiting...");
  314. return FALSE;
  315. }
  316. return TRUE;
  317. }
  318. static void lograw(unsigned char *buffer, ssize_t len)
  319. {
  320. char data[120];
  321. ssize_t i;
  322. unsigned char *ptr = buffer;
  323. char *optr = data;
  324. ssize_t width=0;
  325. for(i=0; i<len; i++) {
  326. switch(ptr[i]) {
  327. case '\n':
  328. sprintf(optr, "\\n");
  329. width += 2;
  330. optr += 2;
  331. break;
  332. case '\r':
  333. sprintf(optr, "\\r");
  334. width += 2;
  335. optr += 2;
  336. break;
  337. default:
  338. sprintf(optr, "%c", (ISGRAPH(ptr[i]) || ptr[i]==0x20) ?ptr[i]:'.');
  339. width++;
  340. optr++;
  341. break;
  342. }
  343. if(width>60) {
  344. logmsg("'%s'", data);
  345. width = 0;
  346. optr = data;
  347. }
  348. }
  349. if(width)
  350. logmsg("'%s'", data);
  351. }
  352. /*
  353. sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
  354. if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
  355. accept()
  356. */
  357. static bool juggle(curl_socket_t *sockfdp,
  358. curl_socket_t listenfd,
  359. enum sockmode *mode)
  360. {
  361. struct timeval timeout;
  362. fd_set fds_read;
  363. fd_set fds_write;
  364. fd_set fds_err;
  365. curl_socket_t sockfd = CURL_SOCKET_BAD;
  366. curl_socket_t maxfd = CURL_SOCKET_BAD;
  367. ssize_t rc;
  368. ssize_t nread_socket;
  369. ssize_t bytes_written;
  370. ssize_t buffer_len;
  371. int error = 0;
  372. /* 'buffer' is this excessively large only to be able to support things like
  373. test 1003 which tests exceedingly large server response lines */
  374. unsigned char buffer[17010];
  375. char data[16];
  376. if(got_exit_signal) {
  377. logmsg("signalled to die, exiting...");
  378. return FALSE;
  379. }
  380. #ifdef HAVE_GETPPID
  381. /* As a last resort, quit if sockfilt process becomes orphan. Just in case
  382. parent ftpserver process has died without killing its sockfilt children */
  383. if(getppid() <= 1) {
  384. logmsg("process becomes orphan, exiting");
  385. return FALSE;
  386. }
  387. #endif
  388. timeout.tv_sec = 120;
  389. timeout.tv_usec = 0;
  390. FD_ZERO(&fds_read);
  391. FD_ZERO(&fds_write);
  392. FD_ZERO(&fds_err);
  393. FD_SET(fileno(stdin), &fds_read);
  394. switch(*mode) {
  395. case PASSIVE_LISTEN:
  396. /* server mode */
  397. sockfd = listenfd;
  398. /* there's always a socket to wait for */
  399. FD_SET(sockfd, &fds_read);
  400. maxfd = sockfd;
  401. break;
  402. case PASSIVE_CONNECT:
  403. sockfd = *sockfdp;
  404. if(CURL_SOCKET_BAD == sockfd) {
  405. /* eeek, we are supposedly connected and then this cannot be -1 ! */
  406. logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
  407. maxfd = 0; /* stdin */
  408. }
  409. else {
  410. /* there's always a socket to wait for */
  411. FD_SET(sockfd, &fds_read);
  412. maxfd = sockfd;
  413. }
  414. break;
  415. case ACTIVE:
  416. sockfd = *sockfdp;
  417. /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
  418. if(CURL_SOCKET_BAD != sockfd) {
  419. FD_SET(sockfd, &fds_read);
  420. maxfd = sockfd;
  421. }
  422. else {
  423. logmsg("No socket to read on");
  424. maxfd = 0;
  425. }
  426. break;
  427. case ACTIVE_DISCONNECT:
  428. logmsg("disconnected, no socket to read on");
  429. maxfd = 0;
  430. sockfd = CURL_SOCKET_BAD;
  431. break;
  432. } /* switch(*mode) */
  433. do {
  434. rc = select((int)maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
  435. if(got_exit_signal) {
  436. logmsg("signalled to die, exiting...");
  437. return FALSE;
  438. }
  439. } while((rc == -1) && ((error = SOCKERRNO) == EINTR));
  440. if(rc < 0) {
  441. logmsg("select() failed with error: (%d) %s",
  442. error, strerror(error));
  443. return FALSE;
  444. }
  445. if(rc == 0)
  446. /* timeout */
  447. return TRUE;
  448. if(FD_ISSET(fileno(stdin), &fds_read)) {
  449. /* read from stdin, commands/data to be dealt with and possibly passed on
  450. to the socket
  451. protocol:
  452. 4 letter command + LF [mandatory]
  453. 4-digit hexadecimal data length + LF [if the command takes data]
  454. data [the data being as long as set above]
  455. Commands:
  456. DATA - plain pass-thru data
  457. */
  458. if(!read_stdin(buffer, 5))
  459. return FALSE;
  460. logmsg("Received %c%c%c%c (on stdin)",
  461. buffer[0], buffer[1], buffer[2], buffer[3] );
  462. if(!memcmp("PING", buffer, 4)) {
  463. /* send reply on stdout, just proving we are alive */
  464. if(!write_stdout("PONG\n", 5))
  465. return FALSE;
  466. }
  467. else if(!memcmp("PORT", buffer, 4)) {
  468. /* Question asking us what PORT number we are listening to.
  469. Replies to PORT with "IPv[num]/[port]" */
  470. sprintf((char *)buffer, "%s/%d\n", ipv_inuse, (int)port);
  471. buffer_len = (ssize_t)strlen((char *)buffer);
  472. snprintf(data, sizeof(data), "PORT\n%04x\n", buffer_len);
  473. if(!write_stdout(data, 10))
  474. return FALSE;
  475. if(!write_stdout(buffer, buffer_len))
  476. return FALSE;
  477. }
  478. else if(!memcmp("QUIT", buffer, 4)) {
  479. /* just die */
  480. logmsg("quits");
  481. return FALSE;
  482. }
  483. else if(!memcmp("DATA", buffer, 4)) {
  484. /* data IN => data OUT */
  485. if(!read_stdin(buffer, 5))
  486. return FALSE;
  487. buffer[5] = '\0';
  488. buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
  489. if (buffer_len > (ssize_t)sizeof(buffer)) {
  490. logmsg("ERROR: Buffer size (%zu bytes) too small for data size "
  491. "(%zd bytes)", sizeof(buffer), buffer_len);
  492. return FALSE;
  493. }
  494. logmsg("> %zd bytes data, server => client", buffer_len);
  495. if(!read_stdin(buffer, buffer_len))
  496. return FALSE;
  497. lograw(buffer, buffer_len);
  498. if(*mode == PASSIVE_LISTEN) {
  499. logmsg("*** We are disconnected!");
  500. if(!write_stdout("DISC\n", 5))
  501. return FALSE;
  502. }
  503. else {
  504. /* send away on the socket */
  505. bytes_written = swrite(sockfd, buffer, buffer_len);
  506. if(bytes_written != buffer_len) {
  507. logmsg("Not all data was sent. Bytes to send: %zd sent: %zd",
  508. buffer_len, bytes_written);
  509. }
  510. }
  511. }
  512. else if(!memcmp("DISC", buffer, 4)) {
  513. /* disconnect! */
  514. if(!write_stdout("DISC\n", 5))
  515. return FALSE;
  516. if(sockfd != CURL_SOCKET_BAD) {
  517. logmsg("====> Client forcibly disconnected");
  518. sclose(sockfd);
  519. *sockfdp = CURL_SOCKET_BAD;
  520. if(*mode == PASSIVE_CONNECT)
  521. *mode = PASSIVE_LISTEN;
  522. else
  523. *mode = ACTIVE_DISCONNECT;
  524. }
  525. else
  526. logmsg("attempt to close already dead connection");
  527. return TRUE;
  528. }
  529. }
  530. if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
  531. if(*mode == PASSIVE_LISTEN) {
  532. /* there's no stream set up yet, this is an indication that there's a
  533. client connecting. */
  534. sockfd = accept(sockfd, NULL, NULL);
  535. if(CURL_SOCKET_BAD == sockfd)
  536. logmsg("accept() failed");
  537. else {
  538. logmsg("====> Client connect");
  539. if(!write_stdout("CNCT\n", 5))
  540. return FALSE;
  541. *sockfdp = sockfd; /* store the new socket */
  542. *mode = PASSIVE_CONNECT; /* we have connected */
  543. }
  544. return TRUE;
  545. }
  546. /* read from socket, pass on data to stdout */
  547. nread_socket = sread(sockfd, buffer, sizeof(buffer));
  548. if(nread_socket <= 0) {
  549. logmsg("====> Client disconnect");
  550. if(!write_stdout("DISC\n", 5))
  551. return FALSE;
  552. sclose(sockfd);
  553. *sockfdp = CURL_SOCKET_BAD;
  554. if(*mode == PASSIVE_CONNECT)
  555. *mode = PASSIVE_LISTEN;
  556. else
  557. *mode = ACTIVE_DISCONNECT;
  558. return TRUE;
  559. }
  560. snprintf(data, sizeof(data), "DATA\n%04x\n", nread_socket);
  561. if(!write_stdout(data, 10))
  562. return FALSE;
  563. if(!write_stdout(buffer, nread_socket))
  564. return FALSE;
  565. logmsg("< %zd bytes data, client => server", nread_socket);
  566. lograw(buffer, nread_socket);
  567. }
  568. return TRUE;
  569. }
  570. static curl_socket_t sockdaemon(curl_socket_t sock,
  571. unsigned short *listenport)
  572. {
  573. /* passive daemon style */
  574. struct sockaddr_in me;
  575. #ifdef ENABLE_IPV6
  576. struct sockaddr_in6 me6;
  577. #endif /* ENABLE_IPV6 */
  578. int flag = 1;
  579. int rc;
  580. int totdelay = 0;
  581. int maxretr = 10;
  582. int delay= 20;
  583. int attempt = 0;
  584. int error = 0;
  585. do {
  586. attempt++;
  587. rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
  588. (void *)&flag, sizeof(flag));
  589. if(rc) {
  590. error = SOCKERRNO;
  591. if(maxretr) {
  592. rc = wait_ms(delay);
  593. if(rc) {
  594. /* should not happen */
  595. error = SOCKERRNO;
  596. logmsg("wait_ms() failed: (%d) %s", error, strerror(error));
  597. sclose(sock);
  598. return CURL_SOCKET_BAD;
  599. }
  600. if(got_exit_signal) {
  601. logmsg("signalled to die, exiting...");
  602. sclose(sock);
  603. return CURL_SOCKET_BAD;
  604. }
  605. totdelay += delay;
  606. delay *= 2; /* double the sleep for next attempt */
  607. }
  608. }
  609. } while(rc && maxretr--);
  610. if(rc) {
  611. logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
  612. attempt, totdelay, error, strerror(error));
  613. logmsg("Continuing anyway...");
  614. }
  615. #ifdef ENABLE_IPV6
  616. if(!use_ipv6) {
  617. #endif
  618. memset(&me, 0, sizeof(me));
  619. me.sin_family = AF_INET;
  620. me.sin_addr.s_addr = INADDR_ANY;
  621. me.sin_port = htons(*listenport);
  622. rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
  623. #ifdef ENABLE_IPV6
  624. }
  625. else {
  626. memset(&me6, 0, sizeof(me6));
  627. me6.sin6_family = AF_INET6;
  628. me6.sin6_addr = in6addr_any;
  629. me6.sin6_port = htons(*listenport);
  630. rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
  631. }
  632. #endif /* ENABLE_IPV6 */
  633. if(rc) {
  634. error = SOCKERRNO;
  635. logmsg("Error binding socket: (%d) %s", error, strerror(error));
  636. sclose(sock);
  637. return CURL_SOCKET_BAD;
  638. }
  639. if(!*listenport) {
  640. /* The system picked a port number, now figure out which port we actually
  641. got */
  642. /* we succeeded to bind */
  643. struct sockaddr_in add;
  644. curl_socklen_t socksize = sizeof(add);
  645. if(getsockname(sock, (struct sockaddr *) &add,
  646. &socksize)<0) {
  647. error = SOCKERRNO;
  648. logmsg("getsockname() failed with error: (%d) %s",
  649. error, strerror(error));
  650. sclose(sock);
  651. return CURL_SOCKET_BAD;
  652. }
  653. *listenport = ntohs(add.sin_port);
  654. }
  655. /* start accepting connections */
  656. rc = listen(sock, 5);
  657. if(0 != rc) {
  658. error = SOCKERRNO;
  659. logmsg("listen() failed with error: (%d) %s",
  660. error, strerror(error));
  661. sclose(sock);
  662. return CURL_SOCKET_BAD;
  663. }
  664. return sock;
  665. }
  666. int main(int argc, char *argv[])
  667. {
  668. struct sockaddr_in me;
  669. #ifdef ENABLE_IPV6
  670. struct sockaddr_in6 me6;
  671. #endif /* ENABLE_IPV6 */
  672. curl_socket_t sock = CURL_SOCKET_BAD;
  673. curl_socket_t msgsock = CURL_SOCKET_BAD;
  674. int wrotepidfile = 0;
  675. char *pidname= (char *)".sockfilt.pid";
  676. int rc;
  677. int error;
  678. int arg=1;
  679. enum sockmode mode = PASSIVE_LISTEN; /* default */
  680. const char *addr = NULL;
  681. while(argc>arg) {
  682. if(!strcmp("--version", argv[arg])) {
  683. printf("sockfilt IPv4%s\n",
  684. #ifdef ENABLE_IPV6
  685. "/IPv6"
  686. #else
  687. ""
  688. #endif
  689. );
  690. return 0;
  691. }
  692. else if(!strcmp("--verbose", argv[arg])) {
  693. verbose = TRUE;
  694. arg++;
  695. }
  696. else if(!strcmp("--pidfile", argv[arg])) {
  697. arg++;
  698. if(argc>arg)
  699. pidname = argv[arg++];
  700. }
  701. else if(!strcmp("--logfile", argv[arg])) {
  702. arg++;
  703. if(argc>arg)
  704. serverlogfile = argv[arg++];
  705. }
  706. else if(!strcmp("--ipv6", argv[arg])) {
  707. #ifdef ENABLE_IPV6
  708. ipv_inuse = "IPv6";
  709. use_ipv6 = TRUE;
  710. #endif
  711. arg++;
  712. }
  713. else if(!strcmp("--ipv4", argv[arg])) {
  714. /* for completeness, we support this option as well */
  715. #ifdef ENABLE_IPV6
  716. ipv_inuse = "IPv4";
  717. use_ipv6 = FALSE;
  718. #endif
  719. arg++;
  720. }
  721. else if(!strcmp("--port", argv[arg])) {
  722. arg++;
  723. if(argc>arg) {
  724. port = (unsigned short)atoi(argv[arg]);
  725. arg++;
  726. }
  727. }
  728. else if(!strcmp("--connect", argv[arg])) {
  729. /* Asked to actively connect to the specified local port instead of
  730. doing a passive server-style listening. */
  731. arg++;
  732. if(argc>arg) {
  733. connectport = (unsigned short)atoi(argv[arg]);
  734. arg++;
  735. }
  736. }
  737. else if(!strcmp("--addr", argv[arg])) {
  738. /* Set an IP address to use with --connect; otherwise use localhost */
  739. arg++;
  740. if(argc>arg) {
  741. addr = argv[arg];
  742. arg++;
  743. }
  744. }
  745. else {
  746. puts("Usage: sockfilt [option]\n"
  747. " --version\n"
  748. " --verbose\n"
  749. " --logfile [file]\n"
  750. " --pidfile [file]\n"
  751. " --ipv4\n"
  752. " --ipv6\n"
  753. " --port [port]\n"
  754. " --connect [port]\n"
  755. " --addr [address]");
  756. return 0;
  757. }
  758. }
  759. #ifdef WIN32
  760. win32_init();
  761. atexit(win32_cleanup);
  762. #endif
  763. install_signal_handlers();
  764. #ifdef ENABLE_IPV6
  765. if(!use_ipv6)
  766. #endif
  767. sock = socket(AF_INET, SOCK_STREAM, 0);
  768. #ifdef ENABLE_IPV6
  769. else
  770. sock = socket(AF_INET6, SOCK_STREAM, 0);
  771. #endif
  772. if(CURL_SOCKET_BAD == sock) {
  773. error = SOCKERRNO;
  774. logmsg("Error creating socket: (%d) %s",
  775. error, strerror(error));
  776. goto sockfilt_cleanup;
  777. }
  778. if(connectport) {
  779. /* Active mode, we should connect to the given port number */
  780. mode = ACTIVE;
  781. #ifdef ENABLE_IPV6
  782. if(!use_ipv6) {
  783. #endif
  784. memset(&me, 0, sizeof(me));
  785. me.sin_family = AF_INET;
  786. me.sin_port = htons(connectport);
  787. me.sin_addr.s_addr = INADDR_ANY;
  788. if (!addr)
  789. addr = "127.0.0.1";
  790. Curl_inet_pton(AF_INET, addr, &me.sin_addr);
  791. rc = connect(sock, (struct sockaddr *) &me, sizeof(me));
  792. #ifdef ENABLE_IPV6
  793. }
  794. else {
  795. memset(&me6, 0, sizeof(me6));
  796. me6.sin6_family = AF_INET6;
  797. me6.sin6_port = htons(connectport);
  798. if (!addr)
  799. addr = "::1";
  800. Curl_inet_pton(AF_INET6, addr, &me6.sin6_addr);
  801. rc = connect(sock, (struct sockaddr *) &me6, sizeof(me6));
  802. }
  803. #endif /* ENABLE_IPV6 */
  804. if(rc) {
  805. error = SOCKERRNO;
  806. logmsg("Error connecting to port %hu: (%d) %s",
  807. connectport, error, strerror(error));
  808. goto sockfilt_cleanup;
  809. }
  810. logmsg("====> Client connect");
  811. msgsock = sock; /* use this as stream */
  812. }
  813. else {
  814. /* passive daemon style */
  815. sock = sockdaemon(sock, &port);
  816. if(CURL_SOCKET_BAD == sock)
  817. goto sockfilt_cleanup;
  818. msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
  819. }
  820. logmsg("Running %s version", ipv_inuse);
  821. if(connectport)
  822. logmsg("Connected to port %hu", connectport);
  823. else
  824. logmsg("Listening on port %hu", port);
  825. wrotepidfile = write_pidfile(pidname);
  826. if(!wrotepidfile)
  827. goto sockfilt_cleanup;
  828. while(juggle(&msgsock, sock, &mode));
  829. sockfilt_cleanup:
  830. if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
  831. sclose(msgsock);
  832. if(sock != CURL_SOCKET_BAD)
  833. sclose(sock);
  834. if(wrotepidfile)
  835. unlink(pidname);
  836. restore_signal_handlers();
  837. if(got_exit_signal) {
  838. logmsg("============> sockfilt exits with signal (%d)", exit_signal);
  839. /*
  840. * To properly set the return status of the process we
  841. * must raise the same signal SIGINT or SIGTERM that we
  842. * caught and let the old handler take care of it.
  843. */
  844. raise(exit_signal);
  845. }
  846. logmsg("============> sockfilt quits");
  847. return 0;
  848. }