2
0

sockfilt.c 45 KB

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