socket.c 22 KB

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