jbsockets.c 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663
  1. /*********************************************************************
  2. *
  3. * File : $Source: /cvsroot/ijbswa/current/jbsockets.c,v $
  4. *
  5. * Purpose : Contains wrappers for system-specific sockets code,
  6. * so that the rest of Privoxy can be more
  7. * OS-independent. Contains #ifdefs to make this work
  8. * on many platforms.
  9. *
  10. * Copyright : Written by and Copyright (C) 2001-2017 the
  11. * Privoxy team. https://www.privoxy.org/
  12. *
  13. * Based on the Internet Junkbuster originally written
  14. * by and Copyright (C) 1997 Anonymous Coders and
  15. * Junkbusters Corporation. http://www.junkbusters.com
  16. *
  17. * This program is free software; you can redistribute it
  18. * and/or modify it under the terms of the GNU General
  19. * Public License as published by the Free Software
  20. * Foundation; either version 2 of the License, or (at
  21. * your option) any later version.
  22. *
  23. * This program is distributed in the hope that it will
  24. * be useful, but WITHOUT ANY WARRANTY; without even the
  25. * implied warranty of MERCHANTABILITY or FITNESS FOR A
  26. * PARTICULAR PURPOSE. See the GNU General Public
  27. * License for more details.
  28. *
  29. * The GNU General Public License should be included with
  30. * this file. If not, you can view it at
  31. * http://www.gnu.org/copyleft/gpl.html
  32. * or write to the Free Software Foundation, Inc., 59
  33. * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  34. *
  35. *********************************************************************/
  36. #include "config.h"
  37. #include <stdlib.h>
  38. #include <stdio.h>
  39. #include <string.h>
  40. #include <errno.h>
  41. #include <fcntl.h>
  42. #include <sys/types.h>
  43. #ifdef _WIN32
  44. #ifndef STRICT
  45. #define STRICT
  46. #endif
  47. #include <winsock2.h>
  48. #include <windows.h>
  49. #include <sys/timeb.h>
  50. #include <io.h>
  51. #else
  52. #include <unistd.h>
  53. #include <sys/time.h>
  54. #include <netinet/in.h>
  55. #include <sys/ioctl.h>
  56. #include <netdb.h>
  57. #include <sys/socket.h>
  58. #ifndef __BEOS__
  59. #include <netinet/tcp.h>
  60. #include <arpa/inet.h>
  61. #else
  62. #include <socket.h>
  63. #endif
  64. #endif
  65. #ifdef HAVE_POLL
  66. #ifdef __GLIBC__
  67. #include <sys/poll.h>
  68. #else
  69. #include <poll.h>
  70. #endif /* def __GLIBC__ */
  71. #endif /* HAVE_POLL */
  72. #include "project.h"
  73. /* For mutex semaphores only */
  74. #include "jcc.h"
  75. #include "jbsockets.h"
  76. #include "filters.h"
  77. #include "errlog.h"
  78. #include "miscutil.h"
  79. /* Mac OSX doesn't define AI_NUMERICSESRV */
  80. #ifndef AI_NUMERICSERV
  81. #define AI_NUMERICSERV 0
  82. #endif
  83. /*
  84. * Maximum number of gethostbyname(_r) retries in case of
  85. * soft errors (TRY_AGAIN).
  86. * XXX: Does it make sense to make this a config option?
  87. */
  88. #define MAX_DNS_RETRIES 10
  89. #ifdef HAVE_RFC2553
  90. static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp);
  91. #else
  92. static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp);
  93. #endif
  94. /*********************************************************************
  95. *
  96. * Function : set_no_delay_flag
  97. *
  98. * Description : Disables the Nagle algorithm (TCP send coalescence)
  99. * for the given socket.
  100. *
  101. * Parameters :
  102. * 1 : fd = The file descriptor to operate on
  103. *
  104. * Returns : void
  105. *
  106. *********************************************************************/
  107. static void set_no_delay_flag(int fd)
  108. {
  109. #ifdef TCP_NODELAY
  110. int mi = 1;
  111. if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &mi, sizeof(int)))
  112. {
  113. log_error(LOG_LEVEL_ERROR,
  114. "Failed to disable TCP coalescence for socket %d", fd);
  115. }
  116. #else
  117. #warning set_no_delay_flag() is a nop due to lack of TCP_NODELAY
  118. #endif /* def TCP_NODELAY */
  119. }
  120. /*********************************************************************
  121. *
  122. * Function : connect_to
  123. *
  124. * Description : Open a socket and connect to it. Will check
  125. * that this is allowed according to ACL.
  126. *
  127. * Parameters :
  128. * 1 : host = hostname to connect to
  129. * 2 : portnum = port to connect to (XXX: should be unsigned)
  130. * 3 : csp = Current client state (buffers, headers, etc...)
  131. *
  132. * Returns : JB_INVALID_SOCKET => failure, else it is the socket
  133. * file descriptor.
  134. *
  135. *********************************************************************/
  136. jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
  137. {
  138. jb_socket fd;
  139. int forwarded_connect_retries = 0;
  140. do
  141. {
  142. /*
  143. * XXX: The whole errno overloading is ridiculous and should
  144. * be replaced with something sane and thread safe
  145. */
  146. /* errno = 0;*/
  147. #ifdef HAVE_RFC2553
  148. fd = rfc2553_connect_to(host, portnum, csp);
  149. #else
  150. fd = no_rfc2553_connect_to(host, portnum, csp);
  151. #endif
  152. if ((fd != JB_INVALID_SOCKET) || (errno == EINVAL)
  153. || (csp->fwd == NULL)
  154. || ((csp->fwd->forward_host == NULL) && (csp->fwd->type == SOCKS_NONE)))
  155. {
  156. break;
  157. }
  158. forwarded_connect_retries++;
  159. if (csp->config->forwarded_connect_retries != 0)
  160. {
  161. log_error(LOG_LEVEL_ERROR,
  162. "Attempt %d of %d to connect to %s failed. Trying again.",
  163. forwarded_connect_retries, csp->config->forwarded_connect_retries + 1, host);
  164. }
  165. } while (forwarded_connect_retries < csp->config->forwarded_connect_retries);
  166. return fd;
  167. }
  168. #ifdef HAVE_RFC2553
  169. /* Getaddrinfo implementation */
  170. static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
  171. {
  172. struct addrinfo hints, *result, *rp;
  173. char service[6];
  174. int retval;
  175. jb_socket fd;
  176. #ifdef HAVE_POLL
  177. struct pollfd poll_fd[1];
  178. #else
  179. fd_set wfds;
  180. struct timeval timeout;
  181. #endif
  182. #if !defined(_WIN32) && !defined(__BEOS__)
  183. int flags;
  184. #endif
  185. int connect_failed;
  186. /*
  187. * XXX: Initializing it here is only necessary
  188. * because not all situations are properly
  189. * covered yet.
  190. */
  191. int socket_error = 0;
  192. #ifdef FEATURE_ACL
  193. struct access_control_addr dst[1];
  194. #endif /* def FEATURE_ACL */
  195. /* Don't leak memory when retrying. */
  196. freez(csp->error_message);
  197. freez(csp->http->host_ip_addr_str);
  198. retval = snprintf(service, sizeof(service), "%d", portnum);
  199. if ((-1 == retval) || (sizeof(service) <= retval))
  200. {
  201. log_error(LOG_LEVEL_ERROR,
  202. "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
  203. portnum);
  204. csp->error_message = strdup("Invalid port number");
  205. csp->http->host_ip_addr_str = strdup("unknown");
  206. return(JB_INVALID_SOCKET);
  207. }
  208. memset((char *)&hints, 0, sizeof(hints));
  209. hints.ai_family = AF_UNSPEC;
  210. hints.ai_socktype = SOCK_STREAM;
  211. hints.ai_flags = AI_NUMERICSERV; /* avoid service look-up */
  212. #ifdef AI_ADDRCONFIG
  213. hints.ai_flags |= AI_ADDRCONFIG;
  214. #endif
  215. if ((retval = getaddrinfo(host, service, &hints, &result)))
  216. {
  217. log_error(LOG_LEVEL_INFO,
  218. "Can not resolve %s: %s", host, gai_strerror(retval));
  219. csp->error_message = strdup(gai_strerror(retval));
  220. csp->http->host_ip_addr_str = strdup("unknown");
  221. /* XXX: Should find a better way to propagate this error. */
  222. errno = EINVAL;
  223. return(JB_INVALID_SOCKET);
  224. }
  225. csp->http->host_ip_addr_str = malloc_or_die(NI_MAXHOST);
  226. for (rp = result; rp != NULL; rp = rp->ai_next)
  227. {
  228. #ifdef FEATURE_ACL
  229. memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
  230. if (block_acl(dst, csp))
  231. {
  232. socket_error = errno = EPERM;
  233. continue;
  234. }
  235. #endif /* def FEATURE_ACL */
  236. retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
  237. csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
  238. if (retval)
  239. {
  240. log_error(LOG_LEVEL_ERROR,
  241. "Failed to get the host name from the socket structure: %s",
  242. gai_strerror(retval));
  243. continue;
  244. }
  245. fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  246. #ifdef _WIN32
  247. if (fd == JB_INVALID_SOCKET)
  248. #else
  249. if (fd < 0)
  250. #endif
  251. {
  252. continue;
  253. }
  254. #ifndef HAVE_POLL
  255. #ifndef _WIN32
  256. if (fd >= FD_SETSIZE)
  257. {
  258. log_error(LOG_LEVEL_ERROR,
  259. "Server socket number too high to use select(): %d >= %d",
  260. fd, FD_SETSIZE);
  261. close_socket(fd);
  262. freeaddrinfo(result);
  263. return JB_INVALID_SOCKET;
  264. }
  265. #endif
  266. #endif
  267. #ifdef FEATURE_EXTERNAL_FILTERS
  268. mark_socket_for_close_on_execute(fd);
  269. #endif
  270. set_no_delay_flag(fd);
  271. #if !defined(_WIN32) && !defined(__BEOS__)
  272. if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
  273. {
  274. flags |= O_NDELAY;
  275. fcntl(fd, F_SETFL, flags);
  276. }
  277. #endif /* !defined(_WIN32) && !defined(__BEOS__) */
  278. connect_failed = 0;
  279. while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
  280. {
  281. #ifdef _WIN32
  282. if (errno == WSAEINPROGRESS)
  283. #else /* ifndef _WIN32 */
  284. if (errno == EINPROGRESS)
  285. #endif /* ndef _WIN32 */
  286. {
  287. break;
  288. }
  289. if (errno != EINTR)
  290. {
  291. socket_error = errno;
  292. close_socket(fd);
  293. connect_failed = 1;
  294. break;
  295. }
  296. }
  297. if (connect_failed)
  298. {
  299. continue;
  300. }
  301. #if !defined(_WIN32) && !defined(__BEOS__)
  302. if (flags != -1)
  303. {
  304. flags &= ~O_NDELAY;
  305. fcntl(fd, F_SETFL, flags);
  306. }
  307. #endif /* !defined(_WIN32) && !defined(__BEOS__) */
  308. #ifdef HAVE_POLL
  309. poll_fd[0].fd = fd;
  310. poll_fd[0].events = POLLOUT;
  311. retval = poll(poll_fd, 1, 30000);
  312. if (retval == 0)
  313. {
  314. if (rp->ai_next != NULL)
  315. {
  316. /* Log this now as we'll try another address next */
  317. log_error(LOG_LEVEL_CONNECT,
  318. "Could not connect to [%s]:%s: Operation timed out.",
  319. csp->http->host_ip_addr_str, service);
  320. }
  321. else
  322. {
  323. /*
  324. * This is the last address, don't log this now
  325. * as it would result in a duplicated log message.
  326. */
  327. socket_error = ETIMEDOUT;
  328. }
  329. }
  330. else if (retval > 0)
  331. #else
  332. /* wait for connection to complete */
  333. FD_ZERO(&wfds);
  334. FD_SET(fd, &wfds);
  335. memset(&timeout, 0, sizeof(timeout));
  336. timeout.tv_sec = 30;
  337. /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
  338. if ((select((int)fd + 1, NULL, &wfds, NULL, &timeout) > 0)
  339. && FD_ISSET(fd, &wfds))
  340. #endif
  341. {
  342. socklen_t optlen = sizeof(socket_error);
  343. if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &optlen))
  344. {
  345. if (!socket_error)
  346. {
  347. /* Connection established, no need to try other addresses. */
  348. break;
  349. }
  350. if (rp->ai_next != NULL)
  351. {
  352. /*
  353. * There's another address we can try, so log that this
  354. * one didn't work out. If the last one fails, too,
  355. * it will get logged outside the loop body so we don't
  356. * have to mention it here.
  357. */
  358. log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
  359. csp->http->host_ip_addr_str, service, strerror(socket_error));
  360. }
  361. }
  362. else
  363. {
  364. socket_error = errno;
  365. log_error(LOG_LEVEL_ERROR, "Could not get the state of "
  366. "the connection to [%s]:%s: %s; dropping connection.",
  367. csp->http->host_ip_addr_str, service, strerror(errno));
  368. }
  369. }
  370. /* Connection failed, try next address */
  371. close_socket(fd);
  372. }
  373. freeaddrinfo(result);
  374. if (!rp)
  375. {
  376. log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
  377. host, service, strerror(socket_error));
  378. csp->error_message = strdup(strerror(socket_error));
  379. return(JB_INVALID_SOCKET);
  380. }
  381. log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
  382. host, csp->http->host_ip_addr_str, service);
  383. return(fd);
  384. }
  385. #else /* ndef HAVE_RFC2553 */
  386. /* Pre-getaddrinfo implementation */
  387. static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
  388. {
  389. struct sockaddr_in inaddr;
  390. jb_socket fd;
  391. unsigned int addr;
  392. #ifdef HAVE_POLL
  393. struct pollfd poll_fd[1];
  394. #else
  395. fd_set wfds;
  396. struct timeval tv[1];
  397. #endif
  398. #if !defined(_WIN32) && !defined(__BEOS__)
  399. int flags;
  400. #endif
  401. #ifdef FEATURE_ACL
  402. struct access_control_addr dst[1];
  403. #endif /* def FEATURE_ACL */
  404. /* Don't leak memory when retrying. */
  405. freez(csp->http->host_ip_addr_str);
  406. memset((char *)&inaddr, 0, sizeof inaddr);
  407. if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
  408. {
  409. csp->http->host_ip_addr_str = strdup("unknown");
  410. return(JB_INVALID_SOCKET);
  411. }
  412. #ifdef FEATURE_ACL
  413. dst->addr = ntohl(addr);
  414. dst->port = portnum;
  415. if (block_acl(dst, csp))
  416. {
  417. errno = EPERM;
  418. return(JB_INVALID_SOCKET);
  419. }
  420. #endif /* def FEATURE_ACL */
  421. inaddr.sin_addr.s_addr = addr;
  422. inaddr.sin_family = AF_INET;
  423. csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
  424. #ifndef _WIN32
  425. if (sizeof(inaddr.sin_port) == sizeof(short))
  426. #endif /* ndef _WIN32 */
  427. {
  428. inaddr.sin_port = htons((unsigned short) portnum);
  429. }
  430. #ifndef _WIN32
  431. else
  432. {
  433. inaddr.sin_port = htonl((unsigned long)portnum);
  434. }
  435. #endif /* ndef _WIN32 */
  436. fd = socket(inaddr.sin_family, SOCK_STREAM, 0);
  437. #ifdef _WIN32
  438. if (fd == JB_INVALID_SOCKET)
  439. #else
  440. if (fd < 0)
  441. #endif
  442. {
  443. return(JB_INVALID_SOCKET);
  444. }
  445. #ifndef HAVE_POLL
  446. #ifndef _WIN32
  447. if (fd >= FD_SETSIZE)
  448. {
  449. log_error(LOG_LEVEL_ERROR,
  450. "Server socket number too high to use select(): %d >= %d",
  451. fd, FD_SETSIZE);
  452. close_socket(fd);
  453. return JB_INVALID_SOCKET;
  454. }
  455. #endif
  456. #endif
  457. set_no_delay_flag(fd);
  458. #if !defined(_WIN32) && !defined(__BEOS__)
  459. if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
  460. {
  461. flags |= O_NDELAY;
  462. fcntl(fd, F_SETFL, flags);
  463. #ifdef FEATURE_EXTERNAL_FILTERS
  464. mark_socket_for_close_on_execute(fd);
  465. #endif
  466. }
  467. #endif /* !defined(_WIN32) && !defined(__BEOS__) */
  468. while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
  469. {
  470. #ifdef _WIN32
  471. if (errno == WSAEINPROGRESS)
  472. #else /* ifndef _WIN32 */
  473. if (errno == EINPROGRESS)
  474. #endif /* ndef _WIN32 */
  475. {
  476. break;
  477. }
  478. if (errno != EINTR)
  479. {
  480. close_socket(fd);
  481. return(JB_INVALID_SOCKET);
  482. }
  483. }
  484. #if !defined(_WIN32) && !defined(__BEOS__)
  485. if (flags != -1)
  486. {
  487. flags &= ~O_NDELAY;
  488. fcntl(fd, F_SETFL, flags);
  489. }
  490. #endif /* !defined(_WIN32) && !defined(__BEOS__) */
  491. #ifdef HAVE_POLL
  492. poll_fd[0].fd = fd;
  493. poll_fd[0].events = POLLOUT;
  494. if (poll(poll_fd, 1, 30000) <= 0)
  495. #else
  496. /* wait for connection to complete */
  497. FD_ZERO(&wfds);
  498. FD_SET(fd, &wfds);
  499. tv->tv_sec = 30;
  500. tv->tv_usec = 0;
  501. /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
  502. if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
  503. #endif
  504. {
  505. close_socket(fd);
  506. return(JB_INVALID_SOCKET);
  507. }
  508. return(fd);
  509. }
  510. #endif /* ndef HAVE_RFC2553 */
  511. /*********************************************************************
  512. *
  513. * Function : write_socket
  514. *
  515. * Description : Write the contents of buf (for n bytes) to socket fd.
  516. *
  517. * Parameters :
  518. * 1 : fd = file descriptor (aka. handle) of socket to write to.
  519. * 2 : buf = pointer to data to be written.
  520. * 3 : len = length of data to be written to the socket "fd".
  521. *
  522. * Returns : 0 on success (entire buffer sent).
  523. * nonzero on error.
  524. *
  525. *********************************************************************/
  526. int write_socket(jb_socket fd, const char *buf, size_t len)
  527. {
  528. if (len == 0)
  529. {
  530. return 0;
  531. }
  532. #ifdef FUZZ
  533. if (!daemon_mode && fd <= 3)
  534. {
  535. log_error(LOG_LEVEL_WRITING, "Pretending to write to socket %d: %N", fd, len, buf);
  536. return 0;
  537. }
  538. #endif
  539. log_error(LOG_LEVEL_WRITING, "to socket %d: %N", fd, len, buf);
  540. #if defined(_WIN32)
  541. return (send(fd, buf, (int)len, 0) != (int)len);
  542. #elif defined(__BEOS__)
  543. return (send(fd, buf, len, 0) != len);
  544. #else
  545. return (write(fd, buf, len) != len);
  546. #endif
  547. }
  548. /*********************************************************************
  549. *
  550. * Function : write_socket_delayed
  551. *
  552. * Description : Write the contents of buf (for n bytes) to
  553. * socket fd, optionally delaying the operation.
  554. *
  555. * Parameters :
  556. * 1 : fd = File descriptor (aka. handle) of socket to write to.
  557. * 2 : buf = Pointer to data to be written.
  558. * 3 : len = Length of data to be written to the socket "fd".
  559. * 4 : delay = Delay in milliseconds.
  560. *
  561. * Returns : 0 on success (entire buffer sent).
  562. * nonzero on error.
  563. *
  564. *********************************************************************/
  565. int write_socket_delayed(jb_socket fd, const char *buf, size_t len, unsigned int delay)
  566. {
  567. size_t i = 0;
  568. if (delay == 0)
  569. {
  570. return write_socket(fd, buf, len);
  571. }
  572. while (i < len)
  573. {
  574. size_t write_length;
  575. enum {MAX_WRITE_LENGTH = 10};
  576. if ((i + MAX_WRITE_LENGTH) > len)
  577. {
  578. write_length = len - i;
  579. }
  580. else
  581. {
  582. write_length = MAX_WRITE_LENGTH;
  583. }
  584. privoxy_millisleep(delay);
  585. if (write_socket(fd, buf + i, write_length) != 0)
  586. {
  587. return 1;
  588. }
  589. i += write_length;
  590. }
  591. return 0;
  592. }
  593. /*********************************************************************
  594. *
  595. * Function : read_socket
  596. *
  597. * Description : Read from a TCP/IP socket in a platform independent way.
  598. *
  599. * Parameters :
  600. * 1 : fd = file descriptor of the socket to read
  601. * 2 : buf = pointer to buffer where data will be written
  602. * Must be >= len bytes long.
  603. * 3 : len = maximum number of bytes to read
  604. *
  605. * Returns : On success, the number of bytes read is returned (zero
  606. * indicates end of file), and the file position is advanced
  607. * by this number. It is not an error if this number is
  608. * smaller than the number of bytes requested; this may hap-
  609. * pen for example because fewer bytes are actually available
  610. * right now (maybe because we were close to end-of-file, or
  611. * because we are reading from a pipe, or from a terminal,
  612. * or because read() was interrupted by a signal). On error,
  613. * -1 is returned, and errno is set appropriately. In this
  614. * case it is left unspecified whether the file position (if
  615. * any) changes.
  616. *
  617. *********************************************************************/
  618. int read_socket(jb_socket fd, char *buf, int len)
  619. {
  620. int ret;
  621. if (len <= 0)
  622. {
  623. return(0);
  624. }
  625. #if defined(_WIN32)
  626. ret = recv(fd, buf, len, 0);
  627. #elif defined(__BEOS__)
  628. ret = recv(fd, buf, (size_t)len, 0);
  629. #else
  630. ret = (int)read(fd, buf, (size_t)len);
  631. #endif
  632. if (ret > 0)
  633. {
  634. log_error(LOG_LEVEL_RECEIVED, "from socket %d: %N", fd, ret, buf);
  635. }
  636. return ret;
  637. }
  638. /*********************************************************************
  639. *
  640. * Function : data_is_available
  641. *
  642. * Description : Waits for data to arrive on a socket.
  643. *
  644. * Parameters :
  645. * 1 : fd = file descriptor of the socket to read
  646. * 2 : seconds_to_wait = number of seconds after which we give up.
  647. *
  648. * Returns : TRUE if data arrived in time,
  649. * FALSE otherwise.
  650. *
  651. *********************************************************************/
  652. int data_is_available(jb_socket fd, int seconds_to_wait)
  653. {
  654. int n;
  655. char buf[10];
  656. #ifdef HAVE_POLL
  657. struct pollfd poll_fd[1];
  658. poll_fd[0].fd = fd;
  659. poll_fd[0].events = POLLIN;
  660. n = poll(poll_fd, 1, seconds_to_wait * 1000);
  661. #else
  662. fd_set rfds;
  663. struct timeval timeout;
  664. memset(&timeout, 0, sizeof(timeout));
  665. timeout.tv_sec = seconds_to_wait;
  666. FD_ZERO(&rfds);
  667. FD_SET(fd, &rfds);
  668. n = select(fd+1, &rfds, NULL, NULL, &timeout);
  669. #endif
  670. /*
  671. * XXX: Do we care about the different error conditions?
  672. */
  673. return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
  674. }
  675. /*********************************************************************
  676. *
  677. * Function : close_socket
  678. *
  679. * Description : Closes a TCP/IP socket
  680. *
  681. * Parameters :
  682. * 1 : fd = file descriptor of socket to be closed
  683. *
  684. * Returns : void
  685. *
  686. *********************************************************************/
  687. void close_socket(jb_socket fd)
  688. {
  689. #if defined(_WIN32) || defined(__BEOS__)
  690. closesocket(fd);
  691. #else
  692. close(fd);
  693. #endif
  694. }
  695. /*********************************************************************
  696. *
  697. * Function : drain_and_close_socket
  698. *
  699. * Description : Closes a TCP/IP socket after draining unread data
  700. *
  701. * Parameters :
  702. * 1 : fd = file descriptor of the socket to be closed
  703. *
  704. * Returns : void
  705. *
  706. *********************************************************************/
  707. void drain_and_close_socket(jb_socket fd)
  708. {
  709. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  710. if (socket_is_still_alive(fd))
  711. #endif
  712. {
  713. int bytes_drained_total = 0;
  714. int bytes_drained;
  715. #ifdef HAVE_SHUTDOWN
  716. /* Apparently Windows has shutdown() but not SHUT_WR. */
  717. #ifndef SHUT_WR
  718. #define SHUT_WR 1
  719. #endif
  720. if (0 != shutdown(fd, SHUT_WR))
  721. {
  722. log_error(LOG_LEVEL_CONNECT, "Failed to shutdown socket %d: %E", fd);
  723. }
  724. #endif
  725. #define ARBITRARY_DRAIN_LIMIT 10000
  726. do
  727. {
  728. char drainage[500];
  729. if (!data_is_available(fd, 0))
  730. {
  731. /*
  732. * If there is no data available right now, don't try
  733. * to drain the socket as read_socket() could block.
  734. */
  735. break;
  736. }
  737. bytes_drained = read_socket(fd, drainage, sizeof(drainage));
  738. if (bytes_drained < 0)
  739. {
  740. log_error(LOG_LEVEL_CONNECT, "Failed to drain socket %d: %E", fd);
  741. }
  742. else if (bytes_drained > 0)
  743. {
  744. bytes_drained_total += bytes_drained;
  745. if (bytes_drained_total > ARBITRARY_DRAIN_LIMIT)
  746. {
  747. log_error(LOG_LEVEL_CONNECT, "Giving up draining socket %d", fd);
  748. break;
  749. }
  750. }
  751. } while (bytes_drained > 0);
  752. if (bytes_drained_total != 0)
  753. {
  754. log_error(LOG_LEVEL_CONNECT,
  755. "Drained %d bytes before closing socket %d", bytes_drained_total, fd);
  756. }
  757. }
  758. close_socket(fd);
  759. }
  760. /*********************************************************************
  761. *
  762. * Function : bind_port
  763. *
  764. * Description : Call socket, set socket options, and listen.
  765. * Called by listen_loop to "boot up" our proxy address.
  766. *
  767. * Parameters :
  768. * 1 : hostnam = TCP/IP address to bind/listen to
  769. * 2 : portnum = port to listen on
  770. * 3 : backlog = Listen backlog
  771. * 4 : pfd = pointer used to return file descriptor.
  772. *
  773. * Returns : if success, returns 0 and sets *pfd.
  774. * if failure, returns -3 if address is in use,
  775. * -2 if address unresolvable,
  776. * -1 otherwise
  777. *********************************************************************/
  778. int bind_port(const char *hostnam, int portnum, int backlog, jb_socket *pfd)
  779. {
  780. #ifdef HAVE_RFC2553
  781. struct addrinfo hints;
  782. struct addrinfo *result, *rp;
  783. /*
  784. * XXX: portnum should be a string to allow symbolic service
  785. * names in the configuration file and to avoid the following
  786. * int2string.
  787. */
  788. char servnam[6];
  789. int retval;
  790. #else
  791. struct sockaddr_in inaddr;
  792. #endif /* def HAVE_RFC2553 */
  793. jb_socket fd;
  794. #ifndef _WIN32
  795. int one = 1;
  796. #endif /* ndef _WIN32 */
  797. *pfd = JB_INVALID_SOCKET;
  798. #ifdef HAVE_RFC2553
  799. retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
  800. if ((-1 == retval) || (sizeof(servnam) <= retval))
  801. {
  802. log_error(LOG_LEVEL_ERROR,
  803. "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
  804. portnum);
  805. return -1;
  806. }
  807. memset(&hints, 0, sizeof(struct addrinfo));
  808. if (hostnam == NULL)
  809. {
  810. /*
  811. * XXX: This is a hack. The right thing to do
  812. * would be to bind to both AF_INET and AF_INET6.
  813. * This will also fail if there is no AF_INET
  814. * version available.
  815. */
  816. hints.ai_family = AF_INET;
  817. }
  818. else
  819. {
  820. hints.ai_family = AF_UNSPEC;
  821. }
  822. hints.ai_socktype = SOCK_STREAM;
  823. hints.ai_flags = AI_PASSIVE;
  824. hints.ai_protocol = 0; /* Really any stream protocol or TCP only */
  825. hints.ai_canonname = NULL;
  826. hints.ai_addr = NULL;
  827. hints.ai_next = NULL;
  828. if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
  829. {
  830. log_error(LOG_LEVEL_ERROR,
  831. "Can not resolve %s: %s", hostnam, gai_strerror(retval));
  832. return -2;
  833. }
  834. #else
  835. memset((char *)&inaddr, '\0', sizeof inaddr);
  836. inaddr.sin_family = AF_INET;
  837. inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
  838. if (inaddr.sin_addr.s_addr == INADDR_NONE)
  839. {
  840. return(-2);
  841. }
  842. #ifndef _WIN32
  843. if (sizeof(inaddr.sin_port) == sizeof(short))
  844. #endif /* ndef _WIN32 */
  845. {
  846. inaddr.sin_port = htons((unsigned short) portnum);
  847. }
  848. #ifndef _WIN32
  849. else
  850. {
  851. inaddr.sin_port = htonl((unsigned long) portnum);
  852. }
  853. #endif /* ndef _WIN32 */
  854. #endif /* def HAVE_RFC2553 */
  855. #ifdef HAVE_RFC2553
  856. for (rp = result; rp != NULL; rp = rp->ai_next)
  857. {
  858. fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  859. #else
  860. fd = socket(AF_INET, SOCK_STREAM, 0);
  861. #endif /* def HAVE_RFC2553 */
  862. #ifdef _WIN32
  863. if (fd == JB_INVALID_SOCKET)
  864. #else
  865. if (fd < 0)
  866. #endif
  867. {
  868. #ifdef HAVE_RFC2553
  869. continue;
  870. #else
  871. return(-1);
  872. #endif
  873. }
  874. #ifdef FEATURE_EXTERNAL_FILTERS
  875. mark_socket_for_close_on_execute(fd);
  876. #endif
  877. #ifndef _WIN32
  878. /*
  879. * This is not needed for Win32 - in fact, it stops
  880. * duplicate instances of Privoxy from being caught.
  881. *
  882. * On UNIX, we assume the user is sensible enough not
  883. * to start Privoxy multiple times on the same IP.
  884. * Without this, stopping and restarting Privoxy
  885. * from a script fails.
  886. * Note: SO_REUSEADDR is meant to only take over
  887. * sockets which are *not* in listen state in Linux,
  888. * e.g. sockets in TIME_WAIT. YMMV.
  889. */
  890. setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
  891. #endif /* ndef _WIN32 */
  892. #ifdef IP_FREEBIND
  893. setsockopt(fd, IPPROTO_IP, IP_FREEBIND, (char *)&one, sizeof(one));
  894. #endif
  895. #ifdef HAVE_RFC2553
  896. if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
  897. #else
  898. if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
  899. #endif
  900. {
  901. #ifdef _WIN32
  902. errno = WSAGetLastError();
  903. if (errno == WSAEADDRINUSE)
  904. #else
  905. if (errno == EADDRINUSE)
  906. #endif
  907. {
  908. #ifdef HAVE_RFC2553
  909. freeaddrinfo(result);
  910. #endif
  911. close_socket(fd);
  912. return(-3);
  913. }
  914. else
  915. {
  916. close_socket(fd);
  917. #ifndef HAVE_RFC2553
  918. return(-1);
  919. }
  920. }
  921. #else
  922. }
  923. }
  924. else
  925. {
  926. /* bind() succeeded, escape from for-loop */
  927. /*
  928. * XXX: Support multiple listening sockets (e.g. localhost
  929. * resolves to AF_INET and AF_INET6, but only the first address
  930. * is used
  931. */
  932. break;
  933. }
  934. }
  935. freeaddrinfo(result);
  936. if (rp == NULL)
  937. {
  938. /* All bind()s failed */
  939. return(-1);
  940. }
  941. #endif /* ndef HAVE_RFC2553 */
  942. while (listen(fd, backlog) == -1)
  943. {
  944. if (errno != EINTR)
  945. {
  946. close_socket(fd);
  947. return(-1);
  948. }
  949. }
  950. *pfd = fd;
  951. return 0;
  952. }
  953. /*********************************************************************
  954. *
  955. * Function : get_host_information
  956. *
  957. * Description : Determines the IP address the client used to
  958. * reach us and the hostname associated with it.
  959. *
  960. * XXX: Most of the code has been copy and pasted
  961. * from accept_connection() and not all of the
  962. * ifdefs paths have been tested afterwards.
  963. *
  964. * Parameters :
  965. * 1 : afd = File descriptor returned from accept().
  966. * 2 : ip_address = Pointer to return the pointer to
  967. * the ip address string.
  968. * 3 : port = Pointer to return the pointer to
  969. * the TCP port string.
  970. * 4 : hostname = Pointer to return the pointer to
  971. * the hostname or NULL if the caller
  972. * isn't interested in it.
  973. *
  974. * Returns : void.
  975. *
  976. *********************************************************************/
  977. void get_host_information(jb_socket afd, char **ip_address, char **port,
  978. char **hostname)
  979. {
  980. #ifdef HAVE_RFC2553
  981. struct sockaddr_storage server;
  982. int retval;
  983. #else
  984. struct sockaddr_in server;
  985. struct hostent *host = NULL;
  986. #endif /* HAVE_RFC2553 */
  987. #if defined(_WIN32)
  988. /* according to accept_connection() this fixes a warning. */
  989. int s_length, s_length_provided;
  990. #else
  991. socklen_t s_length, s_length_provided;
  992. #endif
  993. #ifndef HAVE_RFC2553
  994. #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
  995. struct hostent result;
  996. #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
  997. struct hostent_data hdata;
  998. #else
  999. char hbuf[HOSTENT_BUFFER_SIZE];
  1000. int thd_err;
  1001. #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
  1002. #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
  1003. #endif /* ifndef HAVE_RFC2553 */
  1004. s_length = s_length_provided = sizeof(server);
  1005. if (NULL != hostname)
  1006. {
  1007. *hostname = NULL;
  1008. }
  1009. *ip_address = NULL;
  1010. *port = NULL;
  1011. if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
  1012. {
  1013. if (s_length > s_length_provided)
  1014. {
  1015. log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
  1016. return;
  1017. }
  1018. /*
  1019. * XXX: Workaround for missing header on Windows when
  1020. * configured with --disable-ipv6-support.
  1021. * The proper fix is to not use NI_MAXSERV in
  1022. * that case. It works by accident on other platforms
  1023. * as <netdb.h> is included unconditionally there.
  1024. */
  1025. #ifndef NI_MAXSERV
  1026. #define NI_MAXSERV 32
  1027. #endif
  1028. *port = malloc_or_die(NI_MAXSERV);
  1029. #ifdef HAVE_RFC2553
  1030. *ip_address = malloc_or_die(NI_MAXHOST);
  1031. retval = getnameinfo((struct sockaddr *) &server, s_length,
  1032. *ip_address, NI_MAXHOST, *port, NI_MAXSERV,
  1033. NI_NUMERICHOST|NI_NUMERICSERV);
  1034. if (retval)
  1035. {
  1036. log_error(LOG_LEVEL_ERROR,
  1037. "Unable to print my own IP address: %s", gai_strerror(retval));
  1038. freez(*ip_address);
  1039. freez(*port);
  1040. return;
  1041. }
  1042. #else
  1043. *ip_address = strdup(inet_ntoa(server.sin_addr));
  1044. snprintf(*port, NI_MAXSERV, "%hu", ntohs(server.sin_port));
  1045. #endif /* HAVE_RFC2553 */
  1046. if (NULL == hostname)
  1047. {
  1048. /*
  1049. * We're done here, the caller isn't
  1050. * interested in knowing the hostname.
  1051. */
  1052. return;
  1053. }
  1054. #ifdef HAVE_RFC2553
  1055. *hostname = malloc_or_die(NI_MAXHOST);
  1056. retval = getnameinfo((struct sockaddr *) &server, s_length,
  1057. *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
  1058. if (retval)
  1059. {
  1060. log_error(LOG_LEVEL_ERROR,
  1061. "Unable to resolve my own IP address: %s", gai_strerror(retval));
  1062. freez(*hostname);
  1063. }
  1064. #else
  1065. #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
  1066. gethostbyaddr_r((const char *)&server.sin_addr,
  1067. sizeof(server.sin_addr), AF_INET,
  1068. &result, hbuf, HOSTENT_BUFFER_SIZE,
  1069. &host, &thd_err);
  1070. #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
  1071. host = gethostbyaddr_r((const char *)&server.sin_addr,
  1072. sizeof(server.sin_addr), AF_INET,
  1073. &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
  1074. #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
  1075. if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
  1076. sizeof(server.sin_addr), AF_INET,
  1077. &result, &hdata))
  1078. {
  1079. host = &result;
  1080. }
  1081. else
  1082. {
  1083. host = NULL;
  1084. }
  1085. #elif defined(MUTEX_LOCKS_AVAILABLE)
  1086. privoxy_mutex_lock(&resolver_mutex);
  1087. host = gethostbyaddr((const char *)&server.sin_addr,
  1088. sizeof(server.sin_addr), AF_INET);
  1089. privoxy_mutex_unlock(&resolver_mutex);
  1090. #else
  1091. host = gethostbyaddr((const char *)&server.sin_addr,
  1092. sizeof(server.sin_addr), AF_INET);
  1093. #endif
  1094. if (host == NULL)
  1095. {
  1096. log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
  1097. }
  1098. else
  1099. {
  1100. *hostname = strdup(host->h_name);
  1101. }
  1102. #endif /* else def HAVE_RFC2553 */
  1103. }
  1104. return;
  1105. }
  1106. /*********************************************************************
  1107. *
  1108. * Function : accept_connection
  1109. *
  1110. * Description : Accepts a connection on one of possibly multiple
  1111. * sockets. The socket(s) to check must have been
  1112. * created using bind_port().
  1113. *
  1114. * Parameters :
  1115. * 1 : csp = Client state, cfd, ip_addr_str, and
  1116. * ip_addr_long will be set by this routine.
  1117. * 2 : fds = File descriptors returned from bind_port
  1118. *
  1119. * Returns : when a connection is accepted, it returns 1 (TRUE).
  1120. * On an error it returns 0 (FALSE).
  1121. *
  1122. *********************************************************************/
  1123. int accept_connection(struct client_state * csp, jb_socket fds[])
  1124. {
  1125. #ifdef HAVE_RFC2553
  1126. /* XXX: client is stored directly into csp->tcp_addr */
  1127. #define client (csp->tcp_addr)
  1128. #else
  1129. struct sockaddr_in client;
  1130. #endif
  1131. jb_socket afd;
  1132. #if defined(_WIN32)
  1133. /* Weirdness - fix a warning. */
  1134. int c_length;
  1135. #else
  1136. socklen_t c_length;
  1137. #endif
  1138. int retval;
  1139. int i;
  1140. int max_selected_socket;
  1141. #ifdef HAVE_POLL
  1142. struct pollfd poll_fds[MAX_LISTENING_SOCKETS];
  1143. nfds_t polled_sockets;
  1144. #else
  1145. fd_set selected_fds;
  1146. #endif
  1147. jb_socket fd;
  1148. const char *host_addr;
  1149. size_t listen_addr_size;
  1150. c_length = sizeof(client);
  1151. #ifdef HAVE_POLL
  1152. memset(poll_fds, 0, sizeof(poll_fds));
  1153. polled_sockets = 0;
  1154. #else
  1155. /*
  1156. * Wait for a connection on any socket.
  1157. * Return immediately if no socket is listening.
  1158. * XXX: Why not treat this as fatal error?
  1159. */
  1160. FD_ZERO(&selected_fds);
  1161. #endif
  1162. max_selected_socket = 0;
  1163. for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
  1164. {
  1165. if (JB_INVALID_SOCKET != fds[i])
  1166. {
  1167. #ifdef HAVE_POLL
  1168. poll_fds[i].fd = fds[i];
  1169. poll_fds[i].events = POLLIN;
  1170. polled_sockets++;
  1171. #else
  1172. FD_SET(fds[i], &selected_fds);
  1173. #endif
  1174. if (max_selected_socket < fds[i] + 1)
  1175. {
  1176. max_selected_socket = fds[i] + 1;
  1177. }
  1178. }
  1179. }
  1180. if (0 == max_selected_socket)
  1181. {
  1182. return 0;
  1183. }
  1184. do
  1185. {
  1186. #ifdef HAVE_POLL
  1187. retval = poll(poll_fds, polled_sockets, -1);
  1188. #else
  1189. retval = select(max_selected_socket, &selected_fds, NULL, NULL, NULL);
  1190. #endif
  1191. } while (retval < 0 && errno == EINTR);
  1192. if (retval <= 0)
  1193. {
  1194. if (0 == retval)
  1195. {
  1196. log_error(LOG_LEVEL_ERROR,
  1197. "Waiting on new client failed because select(2) returned 0."
  1198. " This should not happen.");
  1199. }
  1200. else
  1201. {
  1202. log_error(LOG_LEVEL_ERROR,
  1203. "Waiting on new client failed because of problems in select(2): "
  1204. "%s.", strerror(errno));
  1205. }
  1206. return 0;
  1207. }
  1208. #ifdef HAVE_POLL
  1209. for (i = 0; i < MAX_LISTENING_SOCKETS && (poll_fds[i].revents == 0); i++);
  1210. #else
  1211. for (i = 0; i < MAX_LISTENING_SOCKETS && !FD_ISSET(fds[i], &selected_fds);
  1212. i++);
  1213. #endif
  1214. if (i >= MAX_LISTENING_SOCKETS)
  1215. {
  1216. log_error(LOG_LEVEL_ERROR,
  1217. "select(2) reported connected clients (number = %u, "
  1218. "descriptor boundary = %u), but none found.",
  1219. retval, max_selected_socket);
  1220. return 0;
  1221. }
  1222. fd = fds[i];
  1223. /* Accept selected connection */
  1224. #ifdef _WIN32
  1225. afd = accept (fd, (struct sockaddr *) &client, &c_length);
  1226. if (afd == JB_INVALID_SOCKET)
  1227. {
  1228. return 0;
  1229. }
  1230. #else
  1231. do
  1232. {
  1233. afd = accept (fd, (struct sockaddr *) &client, &c_length);
  1234. } while (afd < 0 && errno == EINTR);
  1235. if (afd < 0)
  1236. {
  1237. return 0;
  1238. }
  1239. #endif
  1240. #ifdef SO_LINGER
  1241. {
  1242. struct linger linger_options;
  1243. linger_options.l_onoff = 1;
  1244. linger_options.l_linger = 5;
  1245. if (0 != setsockopt(afd, SOL_SOCKET, SO_LINGER, &linger_options, sizeof(linger_options)))
  1246. {
  1247. log_error(LOG_LEVEL_ERROR, "Setting SO_LINGER on socket %d failed.", afd);
  1248. }
  1249. }
  1250. #endif
  1251. #ifndef HAVE_POLL
  1252. #ifndef _WIN32
  1253. if (afd >= FD_SETSIZE)
  1254. {
  1255. log_error(LOG_LEVEL_ERROR,
  1256. "Client socket number too high to use select(): %d >= %d",
  1257. afd, FD_SETSIZE);
  1258. close_socket(afd);
  1259. return 0;
  1260. }
  1261. #endif
  1262. #endif
  1263. #ifdef FEATURE_EXTERNAL_FILTERS
  1264. mark_socket_for_close_on_execute(afd);
  1265. #endif
  1266. set_no_delay_flag(afd);
  1267. csp->cfd = afd;
  1268. #ifdef HAVE_RFC2553
  1269. csp->ip_addr_str = malloc_or_die(NI_MAXHOST);
  1270. retval = getnameinfo((struct sockaddr *) &client, c_length,
  1271. csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
  1272. if (!csp->ip_addr_str || retval)
  1273. {
  1274. log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
  1275. (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
  1276. freez(csp->ip_addr_str);
  1277. }
  1278. #undef client
  1279. #else
  1280. csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
  1281. csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
  1282. #endif /* def HAVE_RFC2553 */
  1283. /*
  1284. * Save the name and port of the accepting socket for later lookup.
  1285. *
  1286. * The string needs space for strlen(...) + 7 characters:
  1287. * strlen(haddr[i]) + 1 (':') + 5 (port digits) + 1 ('\0')
  1288. */
  1289. host_addr = (csp->config->haddr[i] != NULL) ? csp->config->haddr[i] : "";
  1290. listen_addr_size = strlen(host_addr) + 7;
  1291. csp->listen_addr_str = malloc_or_die(listen_addr_size);
  1292. retval = snprintf(csp->listen_addr_str, listen_addr_size,
  1293. "%s:%d", host_addr, csp->config->hport[i]);
  1294. if ((-1 == retval) || listen_addr_size <= retval)
  1295. {
  1296. log_error(LOG_LEVEL_ERROR,
  1297. "Server name (%s) and port number (%d) ASCII decimal representation"
  1298. "don't fit into %lu bytes",
  1299. host_addr, csp->config->hport[i], listen_addr_size);
  1300. return 0;
  1301. }
  1302. return 1;
  1303. }
  1304. /*********************************************************************
  1305. *
  1306. * Function : resolve_hostname_to_ip
  1307. *
  1308. * Description : Resolve a hostname to an internet tcp/ip address.
  1309. * NULL or an empty string resolve to INADDR_ANY.
  1310. *
  1311. * Parameters :
  1312. * 1 : host = hostname to resolve
  1313. *
  1314. * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if successful.
  1315. *
  1316. *********************************************************************/
  1317. unsigned long resolve_hostname_to_ip(const char *host)
  1318. {
  1319. struct sockaddr_in inaddr;
  1320. struct hostent *hostp;
  1321. #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
  1322. struct hostent result;
  1323. #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
  1324. char hbuf[HOSTENT_BUFFER_SIZE];
  1325. int thd_err;
  1326. #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
  1327. struct hostent_data hdata;
  1328. #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
  1329. #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
  1330. if ((host == NULL) || (*host == '\0'))
  1331. {
  1332. return(INADDR_ANY);
  1333. }
  1334. memset((char *) &inaddr, 0, sizeof inaddr);
  1335. if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
  1336. {
  1337. unsigned int dns_retries = 0;
  1338. #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
  1339. while (gethostbyname_r(host, &result, hbuf,
  1340. HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
  1341. && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
  1342. {
  1343. log_error(LOG_LEVEL_ERROR,
  1344. "Timeout #%u while trying to resolve %s. Trying again.",
  1345. dns_retries, host);
  1346. }
  1347. #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
  1348. while (NULL == (hostp = gethostbyname_r(host, &result,
  1349. hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
  1350. && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
  1351. {
  1352. log_error(LOG_LEVEL_ERROR,
  1353. "Timeout #%u while trying to resolve %s. Trying again.",
  1354. dns_retries, host);
  1355. }
  1356. #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
  1357. /*
  1358. * XXX: Doesn't retry in case of soft errors.
  1359. * Does this gethostbyname_r version set h_errno?
  1360. */
  1361. if (0 == gethostbyname_r(host, &result, &hdata))
  1362. {
  1363. hostp = &result;
  1364. }
  1365. else
  1366. {
  1367. hostp = NULL;
  1368. }
  1369. #elif defined(MUTEX_LOCKS_AVAILABLE)
  1370. privoxy_mutex_lock(&resolver_mutex);
  1371. while (NULL == (hostp = gethostbyname(host))
  1372. && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
  1373. {
  1374. log_error(LOG_LEVEL_ERROR,
  1375. "Timeout #%u while trying to resolve %s. Trying again.",
  1376. dns_retries, host);
  1377. }
  1378. privoxy_mutex_unlock(&resolver_mutex);
  1379. #else
  1380. while (NULL == (hostp = gethostbyname(host))
  1381. && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
  1382. {
  1383. log_error(LOG_LEVEL_ERROR,
  1384. "Timeout #%u while trying to resolve %s. Trying again.",
  1385. dns_retries, host);
  1386. }
  1387. #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
  1388. /*
  1389. * On Mac OSX, if a domain exists but doesn't have a type A
  1390. * record associated with it, the h_addr member of the struct
  1391. * hostent returned by gethostbyname is NULL, even if h_length
  1392. * is 4. Therefore the second test below.
  1393. */
  1394. if (hostp == NULL || hostp->h_addr == NULL)
  1395. {
  1396. errno = EINVAL;
  1397. log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
  1398. return(INADDR_NONE);
  1399. }
  1400. if (hostp->h_addrtype != AF_INET)
  1401. {
  1402. #ifdef _WIN32
  1403. errno = WSAEPROTOTYPE;
  1404. #else
  1405. errno = EPROTOTYPE;
  1406. #endif
  1407. log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
  1408. return(INADDR_NONE);
  1409. }
  1410. memcpy((char *)&inaddr.sin_addr, (char *)hostp->h_addr, sizeof(inaddr.sin_addr));
  1411. }
  1412. return(inaddr.sin_addr.s_addr);
  1413. }
  1414. /*********************************************************************
  1415. *
  1416. * Function : socket_is_still_alive
  1417. *
  1418. * Description : Figures out whether or not a socket is still alive.
  1419. *
  1420. * Parameters :
  1421. * 1 : sfd = The socket to check.
  1422. *
  1423. * Returns : TRUE for yes, otherwise FALSE.
  1424. *
  1425. *********************************************************************/
  1426. int socket_is_still_alive(jb_socket sfd)
  1427. {
  1428. char buf[10];
  1429. int no_data_waiting;
  1430. #ifdef HAVE_POLL
  1431. int poll_result;
  1432. struct pollfd poll_fd[1];
  1433. memset(poll_fd, 0, sizeof(poll_fd));
  1434. poll_fd[0].fd = sfd;
  1435. poll_fd[0].events = POLLIN;
  1436. poll_result = poll(poll_fd, 1, 0);
  1437. if (-1 == poll_result)
  1438. {
  1439. log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
  1440. return FALSE;
  1441. }
  1442. no_data_waiting = !(poll_fd[0].revents & POLLIN);
  1443. #else
  1444. fd_set readable_fds;
  1445. struct timeval timeout;
  1446. int ret;
  1447. memset(&timeout, '\0', sizeof(timeout));
  1448. FD_ZERO(&readable_fds);
  1449. FD_SET(sfd, &readable_fds);
  1450. ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
  1451. if (ret < 0)
  1452. {
  1453. log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
  1454. return FALSE;
  1455. }
  1456. no_data_waiting = !FD_ISSET(sfd, &readable_fds);
  1457. #endif /* def HAVE_POLL */
  1458. return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
  1459. }
  1460. #ifdef FEATURE_EXTERNAL_FILTERS
  1461. /*********************************************************************
  1462. *
  1463. * Function : mark_socket_for_close_on_execute
  1464. *
  1465. * Description : Marks a socket for close on execute.
  1466. *
  1467. * Used so that external filters have no direct
  1468. * access to sockets they shouldn't care about.
  1469. *
  1470. * Not implemented for all platforms.
  1471. *
  1472. * Parameters :
  1473. * 1 : fd = The socket to mark
  1474. *
  1475. * Returns : void.
  1476. *
  1477. *********************************************************************/
  1478. void mark_socket_for_close_on_execute(jb_socket fd)
  1479. {
  1480. #ifdef FEATURE_PTHREAD
  1481. int ret;
  1482. ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
  1483. if (ret == -1)
  1484. {
  1485. log_error(LOG_LEVEL_ERROR,
  1486. "fcntl(%d, F_SETFD, FD_CLOEXEC) failed", fd);
  1487. }
  1488. #else
  1489. #warning "Sockets will be visible to external filters"
  1490. #endif
  1491. }
  1492. #endif /* def FEATURE_EXTERNAL_FILTERS */
  1493. /*
  1494. Local Variables:
  1495. tab-width: 3
  1496. end:
  1497. */