socket.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  1. /*
  2. * Socket functions used in rsync.
  3. *
  4. * Copyright (C) 1992-2001 Andrew Tridgell <tridge@samba.org>
  5. * Copyright (C) 2001, 2002 Martin Pool <mbp@samba.org>
  6. * Copyright (C) 2003-2009 Wayne Davison
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, visit the http://fsf.org website.
  20. */
  21. /* This file is now converted to use the new-style getaddrinfo()
  22. * interface, which supports IPv6 but is also supported on recent
  23. * IPv4-only machines. On systems that don't have that interface, we
  24. * emulate it using the KAME implementation. */
  25. #include "rsync.h"
  26. #include "ifuncs.h"
  27. #include <netinet/in_systm.h>
  28. #include <netinet/ip.h>
  29. #include <netinet/tcp.h>
  30. extern char *bind_address;
  31. extern char *sockopts;
  32. extern int default_af_hint;
  33. extern int connect_timeout;
  34. #ifdef HAVE_SIGACTION
  35. static struct sigaction sigact;
  36. #endif
  37. static int sock_exec(const char *prog);
  38. /* Establish a proxy connection on an open socket to a web proxy by using the
  39. * CONNECT method. If proxy_user and proxy_pass are not NULL, they are used to
  40. * authenticate to the proxy using the "Basic" proxy-authorization protocol. */
  41. static int establish_proxy_connection(int fd, char *host, int port,
  42. char *proxy_user, char *proxy_pass)
  43. {
  44. char *cp, buffer[1024];
  45. char *authhdr, authbuf[1024];
  46. int len;
  47. if (proxy_user && proxy_pass) {
  48. stringjoin(buffer, sizeof buffer,
  49. proxy_user, ":", proxy_pass, NULL);
  50. len = strlen(buffer);
  51. if ((len*8 + 5) / 6 >= (int)sizeof authbuf - 3) {
  52. rprintf(FERROR,
  53. "authentication information is too long\n");
  54. return -1;
  55. }
  56. base64_encode(buffer, len, authbuf, 1);
  57. authhdr = "\r\nProxy-Authorization: Basic ";
  58. } else {
  59. *authbuf = '\0';
  60. authhdr = "";
  61. }
  62. snprintf(buffer, sizeof buffer, "CONNECT %s:%d HTTP/1.0%s%s\r\n\r\n",
  63. host, port, authhdr, authbuf);
  64. len = strlen(buffer);
  65. if (write(fd, buffer, len) != len) {
  66. rsyserr(FERROR, errno, "failed to write to proxy");
  67. return -1;
  68. }
  69. for (cp = buffer; cp < &buffer[sizeof buffer - 1]; cp++) {
  70. if (read(fd, cp, 1) != 1) {
  71. rsyserr(FERROR, errno, "failed to read from proxy");
  72. return -1;
  73. }
  74. if (*cp == '\n')
  75. break;
  76. }
  77. if (*cp != '\n')
  78. cp++;
  79. *cp-- = '\0';
  80. if (*cp == '\r')
  81. *cp = '\0';
  82. if (strncmp(buffer, "HTTP/", 5) != 0) {
  83. rprintf(FERROR, "bad response from proxy -- %s\n",
  84. buffer);
  85. return -1;
  86. }
  87. for (cp = &buffer[5]; isDigit(cp) || *cp == '.'; cp++) {}
  88. while (*cp == ' ')
  89. cp++;
  90. if (*cp != '2') {
  91. rprintf(FERROR, "bad response from proxy -- %s\n",
  92. buffer);
  93. return -1;
  94. }
  95. /* throw away the rest of the HTTP header */
  96. while (1) {
  97. for (cp = buffer; cp < &buffer[sizeof buffer - 1]; cp++) {
  98. if (read(fd, cp, 1) != 1) {
  99. rsyserr(FERROR, errno,
  100. "failed to read from proxy");
  101. return -1;
  102. }
  103. if (*cp == '\n')
  104. break;
  105. }
  106. if (cp > buffer && *cp == '\n')
  107. cp--;
  108. if (cp == buffer && (*cp == '\n' || *cp == '\r'))
  109. break;
  110. }
  111. return 0;
  112. }
  113. /* Try to set the local address for a newly-created socket.
  114. * Return -1 if this fails. */
  115. int try_bind_local(int s, int ai_family, int ai_socktype,
  116. const char *bind_addr)
  117. {
  118. int error;
  119. struct addrinfo bhints, *bres_all, *r;
  120. memset(&bhints, 0, sizeof bhints);
  121. bhints.ai_family = ai_family;
  122. bhints.ai_socktype = ai_socktype;
  123. bhints.ai_flags = AI_PASSIVE;
  124. if ((error = getaddrinfo(bind_addr, NULL, &bhints, &bres_all))) {
  125. rprintf(FERROR, RSYNC_NAME ": getaddrinfo %s: %s\n",
  126. bind_addr, gai_strerror(error));
  127. return -1;
  128. }
  129. for (r = bres_all; r; r = r->ai_next) {
  130. if (bind(s, r->ai_addr, r->ai_addrlen) == -1)
  131. continue;
  132. freeaddrinfo(bres_all);
  133. return s;
  134. }
  135. /* no error message; there might be some problem that allows
  136. * creation of the socket but not binding, perhaps if the
  137. * machine has no ipv6 address of this name. */
  138. freeaddrinfo(bres_all);
  139. return -1;
  140. }
  141. /* connect() timeout handler based on alarm() */
  142. static RETSIGTYPE contimeout_handler(UNUSED(int val))
  143. {
  144. connect_timeout = -1;
  145. }
  146. /* Open a socket to a tcp remote host with the specified port.
  147. *
  148. * Based on code from Warren. Proxy support by Stephen Rothwell.
  149. * getaddrinfo() rewrite contributed by KAME.net.
  150. *
  151. * Now that we support IPv6 we need to look up the remote machine's address
  152. * first, using af_hint to set a preference for the type of address. Then
  153. * depending on whether it has v4 or v6 addresses we try to open a connection.
  154. *
  155. * The loop allows for machines with some addresses which may not be reachable,
  156. * perhaps because we can't e.g. route ipv6 to that network but we can get ip4
  157. * packets through.
  158. *
  159. * bind_addr: local address to use. Normally NULL to bind the wildcard address.
  160. *
  161. * af_hint: address family, e.g. AF_INET or AF_INET6. */
  162. int open_socket_out(char *host, int port, const char *bind_addr,
  163. int af_hint)
  164. {
  165. int type = SOCK_STREAM;
  166. int error, s, j, addr_cnt, *errnos;
  167. struct addrinfo hints, *res0, *res;
  168. char portbuf[10];
  169. char *h, *cp;
  170. int proxied = 0;
  171. char buffer[1024];
  172. char *proxy_user = NULL, *proxy_pass = NULL;
  173. /* if we have a RSYNC_PROXY env variable then redirect our
  174. * connetcion via a web proxy at the given address. */
  175. h = getenv("RSYNC_PROXY");
  176. proxied = h != NULL && *h != '\0';
  177. if (proxied) {
  178. strlcpy(buffer, h, sizeof buffer);
  179. /* Is the USER:PASS@ prefix present? */
  180. if ((cp = strrchr(buffer, '@')) != NULL) {
  181. *cp++ = '\0';
  182. /* The remainder is the HOST:PORT part. */
  183. h = cp;
  184. if ((cp = strchr(buffer, ':')) == NULL) {
  185. rprintf(FERROR,
  186. "invalid proxy specification: should be USER:PASS@HOST:PORT\n");
  187. return -1;
  188. }
  189. *cp++ = '\0';
  190. proxy_user = buffer;
  191. proxy_pass = cp;
  192. } else {
  193. /* The whole buffer is the HOST:PORT part. */
  194. h = buffer;
  195. }
  196. if ((cp = strchr(h, ':')) == NULL) {
  197. rprintf(FERROR,
  198. "invalid proxy specification: should be HOST:PORT\n");
  199. return -1;
  200. }
  201. *cp++ = '\0';
  202. strlcpy(portbuf, cp, sizeof portbuf);
  203. if (verbose >= 2) {
  204. rprintf(FINFO, "connection via http proxy %s port %s\n",
  205. h, portbuf);
  206. }
  207. } else {
  208. snprintf(portbuf, sizeof portbuf, "%d", port);
  209. h = host;
  210. }
  211. memset(&hints, 0, sizeof hints);
  212. hints.ai_family = af_hint;
  213. hints.ai_socktype = type;
  214. error = getaddrinfo(h, portbuf, &hints, &res0);
  215. if (error) {
  216. rprintf(FERROR, RSYNC_NAME ": getaddrinfo: %s %s: %s\n",
  217. h, portbuf, gai_strerror(error));
  218. return -1;
  219. }
  220. for (res = res0, addr_cnt = 0; res; res = res->ai_next, addr_cnt++) {}
  221. errnos = new_array0(int, addr_cnt);
  222. if (!errnos)
  223. out_of_memory("open_socket_out");
  224. s = -1;
  225. /* Try to connect to all addresses for this machine until we get
  226. * through. It might e.g. be multi-homed, or have both IPv4 and IPv6
  227. * addresses. We need to create a socket for each record, since the
  228. * address record tells us what protocol to use to try to connect. */
  229. for (res = res0, j = 0; res; res = res->ai_next, j++) {
  230. s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
  231. if (s < 0)
  232. continue;
  233. if (bind_addr
  234. && try_bind_local(s, res->ai_family, type,
  235. bind_addr) == -1) {
  236. close(s);
  237. s = -1;
  238. continue;
  239. }
  240. if (connect_timeout > 0) {
  241. SIGACTION(SIGALRM, contimeout_handler);
  242. alarm(connect_timeout);
  243. }
  244. set_socket_options(s, sockopts);
  245. while (connect(s, res->ai_addr, res->ai_addrlen) < 0) {
  246. if (connect_timeout < 0)
  247. exit_cleanup(RERR_CONTIMEOUT);
  248. if (errno == EINTR)
  249. continue;
  250. close(s);
  251. s = -1;
  252. break;
  253. }
  254. if (connect_timeout > 0)
  255. alarm(0);
  256. if (s < 0) {
  257. errnos[j] = errno;
  258. continue;
  259. }
  260. if (proxied
  261. && establish_proxy_connection(s, host, port,
  262. proxy_user, proxy_pass) != 0) {
  263. close(s);
  264. s = -1;
  265. continue;
  266. }
  267. break;
  268. }
  269. freeaddrinfo(res0);
  270. if (s < 0) {
  271. char buf[2048];
  272. for (res = res0, j = 0; res; res = res->ai_next, j++) {
  273. if (errnos[j] == 0)
  274. continue;
  275. if (inet_ntop(res->ai_family, res->ai_addr->sa_data + 2, buf, sizeof buf) == NULL)
  276. strlcpy(buf, "*inet_ntop failed*", sizeof buf);
  277. rsyserr(FERROR, errnos[j], "failed to connect to %s (%s)", h, buf);
  278. }
  279. s = -1;
  280. }
  281. free(errnos);
  282. return s;
  283. }
  284. /* Open an outgoing socket, but allow for it to be intercepted by
  285. * $RSYNC_CONNECT_PROG, which will execute a program across a TCP
  286. * socketpair rather than really opening a socket.
  287. *
  288. * We use this primarily in testing to detect TCP flow bugs, but not
  289. * cause security problems by really opening remote connections.
  290. *
  291. * This is based on the Samba LIBSMB_PROG feature.
  292. *
  293. * bind_addr: local address to use. Normally NULL to get the stack default. */
  294. int open_socket_out_wrapped(char *host, int port, const char *bind_addr,
  295. int af_hint)
  296. {
  297. char *prog = getenv("RSYNC_CONNECT_PROG");
  298. if (prog && strchr(prog, '%')) {
  299. int hlen = strlen(host);
  300. int len = strlen(prog) + 1;
  301. char *f, *t;
  302. for (f = prog; *f; f++) {
  303. if (*f != '%')
  304. continue;
  305. /* Compute more than enough room. */
  306. if (f[1] == '%')
  307. f++;
  308. else
  309. len += hlen;
  310. }
  311. f = prog;
  312. if (!(prog = new_array(char, len)))
  313. out_of_memory("open_socket_out_wrapped");
  314. for (t = prog; *f; f++) {
  315. if (*f == '%') {
  316. switch (*++f) {
  317. case '%':
  318. /* Just skips the extra '%'. */
  319. break;
  320. case 'H':
  321. memcpy(t, host, hlen);
  322. t += hlen;
  323. continue;
  324. default:
  325. f--; /* pass % through */
  326. break;
  327. }
  328. }
  329. *t++ = *f;
  330. }
  331. *t = '\0';
  332. }
  333. if (verbose >= 2) {
  334. rprintf(FINFO, "%sopening tcp connection to %s port %d\n",
  335. prog ? "Using RSYNC_CONNECT_PROG instead of " : "",
  336. host, port);
  337. }
  338. if (prog)
  339. return sock_exec(prog);
  340. return open_socket_out(host, port, bind_addr, af_hint);
  341. }
  342. /* Open one or more sockets for incoming data using the specified type,
  343. * port, and address.
  344. *
  345. * The getaddrinfo() call may return several address results, e.g. for
  346. * the machine's IPv4 and IPv6 name.
  347. *
  348. * We return an array of file-descriptors to the sockets, with a trailing
  349. * -1 value to indicate the end of the list.
  350. *
  351. * bind_addr: local address to bind, or NULL to allow it to default. */
  352. static int *open_socket_in(int type, int port, const char *bind_addr,
  353. int af_hint)
  354. {
  355. int one = 1;
  356. int s, *socks, maxs, i, ecnt;
  357. struct addrinfo hints, *all_ai, *resp;
  358. char portbuf[10], **errmsgs;
  359. int error;
  360. memset(&hints, 0, sizeof hints);
  361. hints.ai_family = af_hint;
  362. hints.ai_socktype = type;
  363. hints.ai_flags = AI_PASSIVE;
  364. snprintf(portbuf, sizeof portbuf, "%d", port);
  365. error = getaddrinfo(bind_addr, portbuf, &hints, &all_ai);
  366. if (error) {
  367. rprintf(FERROR, RSYNC_NAME ": getaddrinfo: bind address %s: %s\n",
  368. bind_addr, gai_strerror(error));
  369. return NULL;
  370. }
  371. /* Count max number of sockets we might open. */
  372. for (maxs = 0, resp = all_ai; resp; resp = resp->ai_next, maxs++) {}
  373. socks = new_array(int, maxs + 1);
  374. errmsgs = new_array(char *, maxs);
  375. if (!socks || !errmsgs)
  376. out_of_memory("open_socket_in");
  377. /* We may not be able to create the socket, if for example the
  378. * machine knows about IPv6 in the C library, but not in the
  379. * kernel. */
  380. for (resp = all_ai, i = ecnt = 0; resp; resp = resp->ai_next) {
  381. s = socket(resp->ai_family, resp->ai_socktype,
  382. resp->ai_protocol);
  383. if (s == -1) {
  384. int r = asprintf(&errmsgs[ecnt++],
  385. "socket(%d,%d,%d) failed: %s\n",
  386. (int)resp->ai_family, (int)resp->ai_socktype,
  387. (int)resp->ai_protocol, strerror(errno));
  388. if (r < 0)
  389. out_of_memory("open_socket_in");
  390. /* See if there's another address that will work... */
  391. continue;
  392. }
  393. setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
  394. (char *)&one, sizeof one);
  395. if (sockopts)
  396. set_socket_options(s, sockopts);
  397. else
  398. set_socket_options(s, lp_socket_options());
  399. #ifdef IPV6_V6ONLY
  400. if (resp->ai_family == AF_INET6) {
  401. if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
  402. (char *)&one, sizeof one) < 0
  403. && default_af_hint != AF_INET6) {
  404. close(s);
  405. continue;
  406. }
  407. }
  408. #endif
  409. /* Now we've got a socket - we need to bind it. */
  410. if (bind(s, resp->ai_addr, resp->ai_addrlen) < 0) {
  411. /* Nope, try another */
  412. int r = asprintf(&errmsgs[ecnt++],
  413. "bind() failed: %s (address-family %d)\n",
  414. strerror(errno), (int)resp->ai_family);
  415. if (r < 0)
  416. out_of_memory("open_socket_in");
  417. close(s);
  418. continue;
  419. }
  420. socks[i++] = s;
  421. }
  422. socks[i] = -1;
  423. if (all_ai)
  424. freeaddrinfo(all_ai);
  425. /* Only output the socket()/bind() messages if we were totally
  426. * unsuccessful, or if the daemon is being run with -vv. */
  427. for (s = 0; s < ecnt; s++) {
  428. if (!i || verbose > 1)
  429. rwrite(FLOG, errmsgs[s], strlen(errmsgs[s]), 0);
  430. free(errmsgs[s]);
  431. }
  432. free(errmsgs);
  433. if (!i) {
  434. rprintf(FERROR,
  435. "unable to bind any inbound sockets on port %d\n",
  436. port);
  437. free(socks);
  438. return NULL;
  439. }
  440. return socks;
  441. }
  442. /* Determine if a file descriptor is in fact a socket. */
  443. int is_a_socket(int fd)
  444. {
  445. int v;
  446. socklen_t l = sizeof (int);
  447. /* Parameters to getsockopt, setsockopt etc are very
  448. * unstandardized across platforms, so don't be surprised if
  449. * there are compiler warnings on e.g. SCO OpenSwerver or AIX.
  450. * It seems they all eventually get the right idea.
  451. *
  452. * Debian says: ``The fifth argument of getsockopt and
  453. * setsockopt is in reality an int [*] (and this is what BSD
  454. * 4.* and libc4 and libc5 have). Some POSIX confusion
  455. * resulted in the present socklen_t. The draft standard has
  456. * not been adopted yet, but glibc2 already follows it and
  457. * also has socklen_t [*]. See also accept(2).''
  458. *
  459. * We now return to your regularly scheduled programming. */
  460. return getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0;
  461. }
  462. static RETSIGTYPE sigchld_handler(UNUSED(int val))
  463. {
  464. #ifdef WNOHANG
  465. while (waitpid(-1, NULL, WNOHANG) > 0) {}
  466. #endif
  467. #ifndef HAVE_SIGACTION
  468. signal(SIGCHLD, sigchld_handler);
  469. #endif
  470. }
  471. void start_accept_loop(int port, int (*fn)(int, int))
  472. {
  473. fd_set deffds;
  474. int *sp, maxfd, i;
  475. #ifdef HAVE_SIGACTION
  476. sigact.sa_flags = SA_NOCLDSTOP;
  477. #endif
  478. /* open an incoming socket */
  479. sp = open_socket_in(SOCK_STREAM, port, bind_address, default_af_hint);
  480. if (sp == NULL)
  481. exit_cleanup(RERR_SOCKETIO);
  482. /* ready to listen */
  483. FD_ZERO(&deffds);
  484. for (i = 0, maxfd = -1; sp[i] >= 0; i++) {
  485. if (listen(sp[i], 5) < 0) {
  486. rsyserr(FERROR, errno, "listen() on socket failed");
  487. #ifdef INET6
  488. if (errno == EADDRINUSE && i > 0) {
  489. rprintf(FINFO,
  490. "Try using --ipv4 or --ipv6 to avoid this listen() error.\n");
  491. }
  492. #endif
  493. exit_cleanup(RERR_SOCKETIO);
  494. }
  495. FD_SET(sp[i], &deffds);
  496. if (maxfd < sp[i])
  497. maxfd = sp[i];
  498. }
  499. /* now accept incoming connections - forking a new process
  500. * for each incoming connection */
  501. while (1) {
  502. fd_set fds;
  503. pid_t pid;
  504. int fd;
  505. struct sockaddr_storage addr;
  506. socklen_t addrlen = sizeof addr;
  507. /* close log file before the potentially very long select so
  508. * file can be trimmed by another process instead of growing
  509. * forever */
  510. logfile_close();
  511. #ifdef FD_COPY
  512. FD_COPY(&deffds, &fds);
  513. #else
  514. fds = deffds;
  515. #endif
  516. if (select(maxfd + 1, &fds, NULL, NULL, NULL) < 1)
  517. continue;
  518. for (i = 0, fd = -1; sp[i] >= 0; i++) {
  519. if (FD_ISSET(sp[i], &fds)) {
  520. fd = accept(sp[i], (struct sockaddr *)&addr,
  521. &addrlen);
  522. break;
  523. }
  524. }
  525. if (fd < 0)
  526. continue;
  527. SIGACTION(SIGCHLD, sigchld_handler);
  528. if ((pid = fork()) == 0) {
  529. int ret;
  530. for (i = 0; sp[i] >= 0; i++)
  531. close(sp[i]);
  532. /* Re-open log file in child before possibly giving
  533. * up privileges (see logfile_close() above). */
  534. logfile_reopen();
  535. ret = fn(fd, fd);
  536. close_all();
  537. _exit(ret);
  538. } else if (pid < 0) {
  539. rsyserr(FERROR, errno,
  540. "could not create child server process");
  541. close(fd);
  542. /* This might have happened because we're
  543. * overloaded. Sleep briefly before trying to
  544. * accept again. */
  545. sleep(2);
  546. } else {
  547. /* Parent doesn't need this fd anymore. */
  548. close(fd);
  549. }
  550. }
  551. }
  552. enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
  553. struct
  554. {
  555. char *name;
  556. int level;
  557. int option;
  558. int value;
  559. int opttype;
  560. } socket_options[] = {
  561. {"SO_KEEPALIVE", SOL_SOCKET, SO_KEEPALIVE, 0, OPT_BOOL},
  562. {"SO_REUSEADDR", SOL_SOCKET, SO_REUSEADDR, 0, OPT_BOOL},
  563. {"SO_BROADCAST", SOL_SOCKET, SO_BROADCAST, 0, OPT_BOOL},
  564. #ifdef TCP_NODELAY
  565. {"TCP_NODELAY", IPPROTO_TCP, TCP_NODELAY, 0, OPT_BOOL},
  566. #endif
  567. #ifdef IPTOS_LOWDELAY
  568. {"IPTOS_LOWDELAY", IPPROTO_IP, IP_TOS, IPTOS_LOWDELAY, OPT_ON},
  569. #endif
  570. #ifdef IPTOS_THROUGHPUT
  571. {"IPTOS_THROUGHPUT", IPPROTO_IP, IP_TOS, IPTOS_THROUGHPUT, OPT_ON},
  572. #endif
  573. #ifdef SO_SNDBUF
  574. {"SO_SNDBUF", SOL_SOCKET, SO_SNDBUF, 0, OPT_INT},
  575. #endif
  576. #ifdef SO_RCVBUF
  577. {"SO_RCVBUF", SOL_SOCKET, SO_RCVBUF, 0, OPT_INT},
  578. #endif
  579. #ifdef SO_SNDLOWAT
  580. {"SO_SNDLOWAT", SOL_SOCKET, SO_SNDLOWAT, 0, OPT_INT},
  581. #endif
  582. #ifdef SO_RCVLOWAT
  583. {"SO_RCVLOWAT", SOL_SOCKET, SO_RCVLOWAT, 0, OPT_INT},
  584. #endif
  585. #ifdef SO_SNDTIMEO
  586. {"SO_SNDTIMEO", SOL_SOCKET, SO_SNDTIMEO, 0, OPT_INT},
  587. #endif
  588. #ifdef SO_RCVTIMEO
  589. {"SO_RCVTIMEO", SOL_SOCKET, SO_RCVTIMEO, 0, OPT_INT},
  590. #endif
  591. {NULL,0,0,0,0}
  592. };
  593. /* Set user socket options. */
  594. void set_socket_options(int fd, char *options)
  595. {
  596. char *tok;
  597. if (!options || !*options)
  598. return;
  599. options = strdup(options);
  600. if (!options)
  601. out_of_memory("set_socket_options");
  602. for (tok = strtok(options, " \t,"); tok; tok = strtok(NULL," \t,")) {
  603. int ret=0,i;
  604. int value = 1;
  605. char *p;
  606. int got_value = 0;
  607. if ((p = strchr(tok,'='))) {
  608. *p = 0;
  609. value = atoi(p+1);
  610. got_value = 1;
  611. }
  612. for (i = 0; socket_options[i].name; i++) {
  613. if (strcmp(socket_options[i].name,tok)==0)
  614. break;
  615. }
  616. if (!socket_options[i].name) {
  617. rprintf(FERROR,"Unknown socket option %s\n",tok);
  618. continue;
  619. }
  620. switch (socket_options[i].opttype) {
  621. case OPT_BOOL:
  622. case OPT_INT:
  623. ret = setsockopt(fd,socket_options[i].level,
  624. socket_options[i].option,
  625. (char *)&value, sizeof (int));
  626. break;
  627. case OPT_ON:
  628. if (got_value)
  629. rprintf(FERROR,"syntax error -- %s does not take a value\n",tok);
  630. {
  631. int on = socket_options[i].value;
  632. ret = setsockopt(fd,socket_options[i].level,
  633. socket_options[i].option,
  634. (char *)&on, sizeof (int));
  635. }
  636. break;
  637. }
  638. if (ret != 0) {
  639. rsyserr(FERROR, errno,
  640. "failed to set socket option %s", tok);
  641. }
  642. }
  643. free(options);
  644. }
  645. /* This is like socketpair but uses tcp. The function guarantees that nobody
  646. * else can attach to the socket, or if they do that this function fails and
  647. * the socket gets closed. Returns 0 on success, -1 on failure. The resulting
  648. * file descriptors are symmetrical. Currently only for RSYNC_CONNECT_PROG. */
  649. static int socketpair_tcp(int fd[2])
  650. {
  651. int listener;
  652. struct sockaddr_in sock;
  653. struct sockaddr_in sock2;
  654. socklen_t socklen = sizeof sock;
  655. int connect_done = 0;
  656. fd[0] = fd[1] = listener = -1;
  657. memset(&sock, 0, sizeof sock);
  658. if ((listener = socket(PF_INET, SOCK_STREAM, 0)) == -1)
  659. goto failed;
  660. memset(&sock2, 0, sizeof sock2);
  661. #ifdef HAVE_SOCKADDR_IN_LEN
  662. sock2.sin_len = sizeof sock2;
  663. #endif
  664. sock2.sin_family = PF_INET;
  665. sock2.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  666. if (bind(listener, (struct sockaddr *)&sock2, sizeof sock2) != 0
  667. || listen(listener, 1) != 0
  668. || getsockname(listener, (struct sockaddr *)&sock, &socklen) != 0
  669. || (fd[1] = socket(PF_INET, SOCK_STREAM, 0)) == -1)
  670. goto failed;
  671. set_nonblocking(fd[1]);
  672. sock.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  673. if (connect(fd[1], (struct sockaddr *)&sock, sizeof sock) == -1) {
  674. if (errno != EINPROGRESS)
  675. goto failed;
  676. } else
  677. connect_done = 1;
  678. if ((fd[0] = accept(listener, (struct sockaddr *)&sock2, &socklen)) == -1)
  679. goto failed;
  680. close(listener);
  681. listener = -1;
  682. set_blocking(fd[1]);
  683. if (connect_done == 0) {
  684. if (connect(fd[1], (struct sockaddr *)&sock, sizeof sock) != 0
  685. && errno != EISCONN)
  686. goto failed;
  687. }
  688. /* all OK! */
  689. return 0;
  690. failed:
  691. if (fd[0] != -1)
  692. close(fd[0]);
  693. if (fd[1] != -1)
  694. close(fd[1]);
  695. if (listener != -1)
  696. close(listener);
  697. return -1;
  698. }
  699. /* Run a program on a local tcp socket, so that we can talk to it's stdin and
  700. * stdout. This is used to fake a connection to a daemon for testing -- not
  701. * for the normal case of running SSH.
  702. *
  703. * Retruns a socket which is attached to a subprocess running "prog". stdin and
  704. * stdout are attached. stderr is left attached to the original stderr. */
  705. static int sock_exec(const char *prog)
  706. {
  707. pid_t pid;
  708. int fd[2];
  709. if (socketpair_tcp(fd) != 0) {
  710. rsyserr(FERROR, errno, "socketpair_tcp failed");
  711. return -1;
  712. }
  713. if (verbose >= 2)
  714. rprintf(FINFO, "Running socket program: \"%s\"\n", prog);
  715. pid = fork();
  716. if (pid < 0) {
  717. rsyserr(FERROR, errno, "fork");
  718. exit_cleanup(RERR_IPC);
  719. }
  720. if (pid == 0) {
  721. close(fd[0]);
  722. if (dup2(fd[1], STDIN_FILENO) < 0
  723. || dup2(fd[1], STDOUT_FILENO) < 0) {
  724. fprintf(stderr, "Failed to run \"%s\"\n", prog);
  725. exit(1);
  726. }
  727. exit(system(prog));
  728. }
  729. close(fd[1]);
  730. return fd[0];
  731. }