clientserver.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  1. /*
  2. * The socket based protocol for setting up a connection with rsyncd.
  3. *
  4. * Copyright (C) 1998-2001 Andrew Tridgell <tridge@samba.org>
  5. * Copyright (C) 2001-2002 Martin Pool <mbp@samba.org>
  6. * Copyright (C) 2002-2008 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. #include "rsync.h"
  22. #include "ifuncs.h"
  23. extern int quiet;
  24. extern int verbose;
  25. extern int dry_run;
  26. extern int output_motd;
  27. extern int list_only;
  28. extern int am_sender;
  29. extern int am_server;
  30. extern int am_daemon;
  31. extern int am_root;
  32. extern int rsync_port;
  33. extern int protect_args;
  34. extern int ignore_errors;
  35. extern int preserve_xattrs;
  36. extern int kluge_around_eof;
  37. extern int daemon_over_rsh;
  38. extern int sanitize_paths;
  39. extern int numeric_ids;
  40. extern int filesfrom_fd;
  41. extern int remote_protocol;
  42. extern int protocol_version;
  43. extern int io_timeout;
  44. extern int no_detach;
  45. extern int write_batch;
  46. extern int default_af_hint;
  47. extern int logfile_format_has_i;
  48. extern int logfile_format_has_o_or_i;
  49. extern mode_t orig_umask;
  50. extern char *bind_address;
  51. extern char *sockopts;
  52. extern char *config_file;
  53. extern char *logfile_format;
  54. extern char *files_from;
  55. extern char *tmpdir;
  56. extern struct chmod_mode_struct *chmod_modes;
  57. extern struct filter_list_struct daemon_filter_list;
  58. extern char curr_dir[];
  59. #ifdef ICONV_OPTION
  60. extern char *iconv_opt;
  61. extern iconv_t ic_send, ic_recv;
  62. #endif
  63. char *auth_user;
  64. int read_only = 0;
  65. int module_id = -1;
  66. int munge_symlinks = 0;
  67. struct chmod_mode_struct *daemon_chmod_modes;
  68. /* module_dirlen is the length of the module_dir string when in daemon
  69. * mode and module_dir is not "/"; otherwise 0. (Note that a chroot-
  70. * enabled module can have a non-"/" module_dir these days.) */
  71. char *module_dir = NULL;
  72. unsigned int module_dirlen = 0;
  73. static int rl_nulls = 0;
  74. #ifdef HAVE_SIGACTION
  75. static struct sigaction sigact;
  76. #endif
  77. /**
  78. * Run a client connected to an rsyncd. The alternative to this
  79. * function for remote-shell connections is do_cmd().
  80. *
  81. * After negotiating which module to use and reading the server's
  82. * motd, this hands over to client_run(). Telling the server the
  83. * module will cause it to chroot/setuid/etc.
  84. *
  85. * Instead of doing a transfer, the client may at this stage instead
  86. * get a listing of remote modules and exit.
  87. *
  88. * @return -1 for error in startup, or the result of client_run().
  89. * Either way, it eventually gets passed to exit_cleanup().
  90. **/
  91. int start_socket_client(char *host, int remote_argc, char *remote_argv[],
  92. int argc, char *argv[])
  93. {
  94. int fd, ret;
  95. char *p, *user = NULL;
  96. /* This is redundant with code in start_inband_exchange(), but this
  97. * short-circuits a problem in the client before we open a socket,
  98. * and the extra check won't hurt. */
  99. if (**remote_argv == '/') {
  100. rprintf(FERROR,
  101. "ERROR: The remote path must start with a module name not a /\n");
  102. return -1;
  103. }
  104. if ((p = strrchr(host, '@')) != NULL) {
  105. user = host;
  106. host = p+1;
  107. *p = '\0';
  108. }
  109. fd = open_socket_out_wrapped(host, rsync_port, bind_address,
  110. default_af_hint);
  111. if (fd == -1)
  112. exit_cleanup(RERR_SOCKETIO);
  113. #ifdef ICONV_CONST
  114. setup_iconv();
  115. #endif
  116. ret = start_inband_exchange(fd, fd, user, remote_argc, remote_argv);
  117. return ret ? ret : client_run(fd, fd, -1, argc, argv);
  118. }
  119. static int exchange_protocols(int f_in, int f_out, char *buf, size_t bufsiz, int am_client)
  120. {
  121. int remote_sub = -1;
  122. #if SUBPROTOCOL_VERSION != 0
  123. int our_sub = protocol_version < PROTOCOL_VERSION ? 0 : SUBPROTOCOL_VERSION;
  124. #else
  125. int our_sub = 0;
  126. #endif
  127. char *motd;
  128. io_printf(f_out, "@RSYNCD: %d.%d\n", protocol_version, our_sub);
  129. if (!am_client) {
  130. motd = lp_motd_file();
  131. if (motd && *motd) {
  132. FILE *f = fopen(motd,"r");
  133. while (f && !feof(f)) {
  134. int len = fread(buf, 1, bufsiz - 1, f);
  135. if (len > 0)
  136. write_buf(f_out, buf, len);
  137. }
  138. if (f)
  139. fclose(f);
  140. write_sbuf(f_out, "\n");
  141. }
  142. }
  143. /* This strips the \n. */
  144. if (!read_line_old(f_in, buf, bufsiz)) {
  145. if (am_client)
  146. rprintf(FERROR, "rsync: did not see server greeting\n");
  147. return -1;
  148. }
  149. if (sscanf(buf, "@RSYNCD: %d.%d", &remote_protocol, &remote_sub) < 1) {
  150. if (am_client)
  151. rprintf(FERROR, "rsync: server sent \"%s\" rather than greeting\n", buf);
  152. else
  153. io_printf(f_out, "@ERROR: protocol startup error\n");
  154. return -1;
  155. }
  156. if (remote_sub < 0) {
  157. if (remote_protocol == 30) {
  158. if (am_client)
  159. rprintf(FERROR, "rsync: server is speaking an incompatible beta of protocol 30\n");
  160. else
  161. io_printf(f_out, "@ERROR: your client is speaking an incompatible beta of protocol 30\n");
  162. return -1;
  163. }
  164. remote_sub = 0;
  165. }
  166. if (protocol_version > remote_protocol) {
  167. protocol_version = remote_protocol;
  168. if (remote_sub)
  169. protocol_version--;
  170. } else if (protocol_version == remote_protocol) {
  171. if (remote_sub != our_sub)
  172. protocol_version--;
  173. }
  174. #if SUBPROTOCOL_VERSION != 0
  175. else if (protocol_version < remote_protocol) {
  176. if (our_sub)
  177. protocol_version--;
  178. }
  179. #endif
  180. if (protocol_version >= 30)
  181. rl_nulls = 1;
  182. return 0;
  183. }
  184. int start_inband_exchange(int f_in, int f_out, const char *user, int argc, char *argv[])
  185. {
  186. int i, modlen;
  187. char line[BIGPATHBUFLEN];
  188. char *sargs[MAX_ARGS];
  189. int sargc = 0;
  190. char *p, *modname;
  191. assert(argc > 0 && *argv != NULL);
  192. if (**argv == '/') {
  193. rprintf(FERROR,
  194. "ERROR: The remote path must start with a module name\n");
  195. return -1;
  196. }
  197. if (!(p = strchr(*argv, '/')))
  198. modlen = strlen(*argv);
  199. else
  200. modlen = p - *argv;
  201. if (!(modname = new_array(char, modlen+1+1))) /* room for '/' & '\0' */
  202. out_of_memory("start_inband_exchange");
  203. strlcpy(modname, *argv, modlen + 1);
  204. modname[modlen] = '/';
  205. modname[modlen+1] = '\0';
  206. if (!user)
  207. user = getenv("USER");
  208. if (!user)
  209. user = getenv("LOGNAME");
  210. if (exchange_protocols(f_in, f_out, line, sizeof line, 1) < 0)
  211. return -1;
  212. /* set daemon_over_rsh to false since we need to build the
  213. * true set of args passed through the rsh/ssh connection;
  214. * this is a no-op for direct-socket-connection mode */
  215. daemon_over_rsh = 0;
  216. server_options(sargs, &sargc);
  217. if (sargc >= MAX_ARGS - 2)
  218. goto arg_overflow;
  219. sargs[sargc++] = ".";
  220. while (argc > 0) {
  221. if (sargc >= MAX_ARGS - 1) {
  222. arg_overflow:
  223. rprintf(FERROR, "internal: args[] overflowed in do_cmd()\n");
  224. exit_cleanup(RERR_SYNTAX);
  225. }
  226. if (strncmp(*argv, modname, modlen) == 0
  227. && argv[0][modlen] == '\0')
  228. sargs[sargc++] = modname; /* we send "modname/" */
  229. else
  230. sargs[sargc++] = *argv;
  231. argv++;
  232. argc--;
  233. }
  234. sargs[sargc] = NULL;
  235. if (verbose > 1)
  236. print_child_argv("sending daemon args:", sargs);
  237. io_printf(f_out, "%.*s\n", modlen, modname);
  238. /* Old servers may just drop the connection here,
  239. rather than sending a proper EXIT command. Yuck. */
  240. kluge_around_eof = list_only && protocol_version < 25 ? 1 : 0;
  241. while (1) {
  242. if (!read_line_old(f_in, line, sizeof line)) {
  243. rprintf(FERROR, "rsync: didn't get server startup line\n");
  244. return -1;
  245. }
  246. if (strncmp(line,"@RSYNCD: AUTHREQD ",18) == 0) {
  247. auth_client(f_out, user, line+18);
  248. continue;
  249. }
  250. if (strcmp(line,"@RSYNCD: OK") == 0)
  251. break;
  252. if (strcmp(line,"@RSYNCD: EXIT") == 0) {
  253. /* This is sent by recent versions of the
  254. * server to terminate the listing of modules.
  255. * We don't want to go on and transfer
  256. * anything; just exit. */
  257. exit(0);
  258. }
  259. if (strncmp(line, "@ERROR", 6) == 0) {
  260. rprintf(FERROR, "%s\n", line);
  261. /* This is always fatal; the server will now
  262. * close the socket. */
  263. return -1;
  264. }
  265. /* This might be a MOTD line or a module listing, but there is
  266. * no way to differentiate it. The manpage mentions this. */
  267. if (output_motd)
  268. rprintf(FINFO, "%s\n", line);
  269. }
  270. kluge_around_eof = 0;
  271. if (rl_nulls) {
  272. for (i = 0; i < sargc; i++) {
  273. if (!sargs[i]) /* stop at --protect-args NULL */
  274. break;
  275. write_sbuf(f_out, sargs[i]);
  276. write_byte(f_out, 0);
  277. }
  278. write_byte(f_out, 0);
  279. } else {
  280. for (i = 0; i < sargc; i++)
  281. io_printf(f_out, "%s\n", sargs[i]);
  282. write_sbuf(f_out, "\n");
  283. }
  284. if (protect_args)
  285. send_protected_args(f_out, sargs);
  286. if (protocol_version < 23) {
  287. if (protocol_version == 22 || !am_sender)
  288. io_start_multiplex_in();
  289. }
  290. free(modname);
  291. return 0;
  292. }
  293. static char *finish_pre_exec(pid_t pid, int fd, char *request,
  294. char **early_argv, char **argv)
  295. {
  296. int j = 0, status = -1;
  297. if (!request)
  298. request = "(NONE)";
  299. write_buf(fd, request, strlen(request)+1);
  300. if (early_argv) {
  301. for ( ; *early_argv; early_argv++)
  302. write_buf(fd, *early_argv, strlen(*early_argv)+1);
  303. j = 1; /* Skip arg0 name in argv. */
  304. }
  305. for ( ; argv[j]; j++) {
  306. write_buf(fd, argv[j], strlen(argv[j])+1);
  307. if (argv[j][0] == '.' && argv[j][1] == '\0')
  308. break;
  309. }
  310. write_byte(fd, 0);
  311. close(fd);
  312. if (wait_process(pid, &status, 0) < 0
  313. || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
  314. char *e;
  315. if (asprintf(&e, "pre-xfer exec returned failure (%d)%s%s\n",
  316. status, status < 0 ? ": " : "",
  317. status < 0 ? strerror(errno) : "") < 0)
  318. out_of_memory("finish_pre_exec");
  319. return e;
  320. }
  321. return NULL;
  322. }
  323. static int read_arg_from_pipe(int fd, char *buf, int limit)
  324. {
  325. char *bp = buf, *eob = buf + limit - 1;
  326. while (1) {
  327. int got = read(fd, bp, 1);
  328. if (got != 1) {
  329. if (got < 0 && errno == EINTR)
  330. continue;
  331. return -1;
  332. }
  333. if (*bp == '\0')
  334. break;
  335. if (bp < eob)
  336. bp++;
  337. }
  338. *bp = '\0';
  339. return bp - buf;
  340. }
  341. static int rsync_module(int f_in, int f_out, int i, char *addr, char *host)
  342. {
  343. int argc;
  344. char **argv, **orig_argv, **orig_early_argv, *chroot_path = NULL;
  345. char line[BIGPATHBUFLEN];
  346. uid_t uid = (uid_t)-2; /* canonically "nobody" */
  347. gid_t gid = (gid_t)-2;
  348. char *p, *err_msg = NULL;
  349. char *name = lp_name(i);
  350. int use_chroot = lp_use_chroot(i);
  351. int ret, pre_exec_fd = -1;
  352. pid_t pre_exec_pid = 0;
  353. char *request = NULL;
  354. #ifdef ICONV_OPTION
  355. iconv_opt = lp_charset(i);
  356. if (*iconv_opt)
  357. setup_iconv();
  358. iconv_opt = NULL;
  359. #endif
  360. if (!allow_access(addr, host, lp_hosts_allow(i), lp_hosts_deny(i))) {
  361. rprintf(FLOG, "rsync denied on module %s from %s (%s)\n",
  362. name, host, addr);
  363. if (!lp_list(i))
  364. io_printf(f_out, "@ERROR: Unknown module '%s'\n", name);
  365. else {
  366. io_printf(f_out,
  367. "@ERROR: access denied to %s from %s (%s)\n",
  368. name, host, addr);
  369. }
  370. return -1;
  371. }
  372. if (am_daemon && am_server) {
  373. rprintf(FLOG, "rsync allowed access on module %s from %s (%s)\n",
  374. name, host, addr);
  375. }
  376. if (!claim_connection(lp_lock_file(i), lp_max_connections(i))) {
  377. if (errno) {
  378. rsyserr(FLOG, errno, "failed to open lock file %s",
  379. lp_lock_file(i));
  380. io_printf(f_out, "@ERROR: failed to open lock file\n");
  381. } else {
  382. rprintf(FLOG, "max connections (%d) reached\n",
  383. lp_max_connections(i));
  384. io_printf(f_out, "@ERROR: max connections (%d) reached -- try again later\n",
  385. lp_max_connections(i));
  386. }
  387. return -1;
  388. }
  389. auth_user = auth_server(f_in, f_out, i, host, addr, "@RSYNCD: AUTHREQD ");
  390. if (!auth_user) {
  391. io_printf(f_out, "@ERROR: auth failed on module %s\n", name);
  392. return -1;
  393. }
  394. module_id = i;
  395. if (lp_read_only(i))
  396. read_only = 1;
  397. if (lp_transfer_logging(i) && !logfile_format)
  398. logfile_format = lp_log_format(i);
  399. if (log_format_has(logfile_format, 'i'))
  400. logfile_format_has_i = 1;
  401. if (logfile_format_has_i || log_format_has(logfile_format, 'o'))
  402. logfile_format_has_o_or_i = 1;
  403. am_root = (MY_UID() == 0);
  404. if (am_root) {
  405. p = lp_uid(i);
  406. if (!name_to_uid(p, &uid)) {
  407. if (!isDigit(p)) {
  408. rprintf(FLOG, "Invalid uid %s\n", p);
  409. io_printf(f_out, "@ERROR: invalid uid %s\n", p);
  410. return -1;
  411. }
  412. uid = atoi(p);
  413. }
  414. p = lp_gid(i);
  415. if (!name_to_gid(p, &gid)) {
  416. if (!isDigit(p)) {
  417. rprintf(FLOG, "Invalid gid %s\n", p);
  418. io_printf(f_out, "@ERROR: invalid gid %s\n", p);
  419. return -1;
  420. }
  421. gid = atoi(p);
  422. }
  423. }
  424. /* TODO: If we're not root, but the configuration requests
  425. * that we change to some uid other than the current one, then
  426. * log a warning. */
  427. /* TODO: Perhaps take a list of gids, and make them into the
  428. * supplementary groups. */
  429. module_dir = lp_path(i);
  430. if (use_chroot) {
  431. if ((p = strstr(module_dir, "/./")) != NULL) {
  432. *p = '\0';
  433. p += 2;
  434. } else if ((p = strdup("/")) == NULL) /* MEMORY LEAK */
  435. out_of_memory("rsync_module");
  436. }
  437. /* We do a change_dir() that doesn't actually call chdir()
  438. * just to make a relative path absolute. */
  439. strlcpy(line, curr_dir, sizeof line);
  440. if (!change_dir(module_dir, CD_SKIP_CHDIR))
  441. goto chdir_failed;
  442. if (strcmp(curr_dir, module_dir) != 0
  443. && (module_dir = strdup(curr_dir)) == NULL)
  444. out_of_memory("rsync_module");
  445. change_dir(line, CD_SKIP_CHDIR); /* Restore curr_dir. */
  446. if (use_chroot) {
  447. chroot_path = module_dir;
  448. module_dir = p; /* p is "/" or our inside-chroot path */
  449. }
  450. module_dirlen = clean_fname(module_dir, CFN_COLLAPSE_DOT_DOT_DIRS | CFN_DROP_TRAILING_DOT_DIR);
  451. if (module_dirlen == 1) {
  452. module_dirlen = 0;
  453. set_filter_dir("/", 1);
  454. } else
  455. set_filter_dir(module_dir, module_dirlen);
  456. p = lp_filter(i);
  457. parse_rule(&daemon_filter_list, p, MATCHFLG_WORD_SPLIT,
  458. XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3);
  459. p = lp_include_from(i);
  460. parse_filter_file(&daemon_filter_list, p, MATCHFLG_INCLUDE,
  461. XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
  462. p = lp_include(i);
  463. parse_rule(&daemon_filter_list, p,
  464. MATCHFLG_INCLUDE | MATCHFLG_WORD_SPLIT,
  465. XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES);
  466. p = lp_exclude_from(i);
  467. parse_filter_file(&daemon_filter_list, p, 0,
  468. XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
  469. p = lp_exclude(i);
  470. parse_rule(&daemon_filter_list, p, MATCHFLG_WORD_SPLIT,
  471. XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES);
  472. log_init(1);
  473. #ifdef HAVE_PUTENV
  474. if (*lp_prexfer_exec(i) || *lp_postxfer_exec(i)) {
  475. char *modname, *modpath, *hostaddr, *hostname, *username;
  476. int status;
  477. if (!use_chroot)
  478. p = module_dir;
  479. else if (module_dirlen) {
  480. pathjoin(line, sizeof line, chroot_path, module_dir+1);
  481. p = line;
  482. } else
  483. p = chroot_path;
  484. if (asprintf(&modname, "RSYNC_MODULE_NAME=%s", name) < 0
  485. || asprintf(&modpath, "RSYNC_MODULE_PATH=%s", p) < 0
  486. || asprintf(&hostaddr, "RSYNC_HOST_ADDR=%s", addr) < 0
  487. || asprintf(&hostname, "RSYNC_HOST_NAME=%s", host) < 0
  488. || asprintf(&username, "RSYNC_USER_NAME=%s", auth_user) < 0)
  489. out_of_memory("rsync_module");
  490. putenv(modname);
  491. putenv(modpath);
  492. putenv(hostaddr);
  493. putenv(hostname);
  494. putenv(username);
  495. umask(orig_umask);
  496. /* For post-xfer exec, fork a new process to run the rsync
  497. * daemon while this process waits for the exit status and
  498. * runs the indicated command at that point. */
  499. if (*lp_postxfer_exec(i)) {
  500. pid_t pid = fork();
  501. if (pid < 0) {
  502. rsyserr(FLOG, errno, "fork failed");
  503. io_printf(f_out, "@ERROR: fork failed\n");
  504. return -1;
  505. }
  506. if (pid) {
  507. if (asprintf(&p, "RSYNC_PID=%ld", (long)pid) > 0)
  508. putenv(p);
  509. if (wait_process(pid, &status, 0) < 0)
  510. status = -1;
  511. if (asprintf(&p, "RSYNC_RAW_STATUS=%d", status) > 0)
  512. putenv(p);
  513. if (WIFEXITED(status))
  514. status = WEXITSTATUS(status);
  515. else
  516. status = -1;
  517. if (asprintf(&p, "RSYNC_EXIT_STATUS=%d", status) > 0)
  518. putenv(p);
  519. system(lp_postxfer_exec(i));
  520. _exit(status);
  521. }
  522. }
  523. /* For pre-xfer exec, fork a child process to run the indicated
  524. * command, though it first waits for the parent process to
  525. * send us the user's request via a pipe. */
  526. if (*lp_prexfer_exec(i)) {
  527. int fds[2];
  528. if (asprintf(&p, "RSYNC_PID=%ld", (long)getpid()) > 0)
  529. putenv(p);
  530. if (pipe(fds) < 0 || (pre_exec_pid = fork()) < 0) {
  531. rsyserr(FLOG, errno, "pre-xfer exec preparation failed");
  532. io_printf(f_out, "@ERROR: pre-xfer exec preparation failed\n");
  533. return -1;
  534. }
  535. if (pre_exec_pid == 0) {
  536. char buf[BIGPATHBUFLEN];
  537. int j, len;
  538. close(fds[1]);
  539. set_blocking(fds[0]);
  540. len = read_arg_from_pipe(fds[0], buf, BIGPATHBUFLEN);
  541. if (len <= 0)
  542. _exit(1);
  543. if (asprintf(&p, "RSYNC_REQUEST=%s", buf) > 0)
  544. putenv(p);
  545. for (j = 0; ; j++) {
  546. len = read_arg_from_pipe(fds[0], buf,
  547. BIGPATHBUFLEN);
  548. if (len <= 0) {
  549. if (!len)
  550. break;
  551. _exit(1);
  552. }
  553. if (asprintf(&p, "RSYNC_ARG%d=%s", j, buf) > 0)
  554. putenv(p);
  555. }
  556. close(fds[0]);
  557. close(STDIN_FILENO);
  558. close(STDOUT_FILENO);
  559. status = system(lp_prexfer_exec(i));
  560. if (!WIFEXITED(status))
  561. _exit(1);
  562. _exit(WEXITSTATUS(status));
  563. }
  564. close(fds[0]);
  565. set_blocking(fds[1]);
  566. pre_exec_fd = fds[1];
  567. }
  568. umask(0);
  569. }
  570. #endif
  571. if (use_chroot) {
  572. /*
  573. * XXX: The 'use chroot' flag is a fairly reliable
  574. * source of confusion, because it fails under two
  575. * important circumstances: running as non-root,
  576. * running on Win32 (or possibly others). On the
  577. * other hand, if you are running as root, then it
  578. * might be better to always use chroot.
  579. *
  580. * So, perhaps if we can't chroot we should just issue
  581. * a warning, unless a "require chroot" flag is set,
  582. * in which case we fail.
  583. */
  584. if (chroot(chroot_path)) {
  585. rsyserr(FLOG, errno, "chroot %s failed", chroot_path);
  586. io_printf(f_out, "@ERROR: chroot failed\n");
  587. return -1;
  588. }
  589. if (!change_dir(module_dir, CD_NORMAL))
  590. goto chdir_failed;
  591. if (module_dirlen)
  592. sanitize_paths = 1;
  593. } else {
  594. if (!change_dir(module_dir, CD_NORMAL)) {
  595. chdir_failed:
  596. rsyserr(FLOG, errno, "chdir %s failed\n", module_dir);
  597. io_printf(f_out, "@ERROR: chdir failed\n");
  598. return -1;
  599. }
  600. sanitize_paths = 1;
  601. }
  602. if ((munge_symlinks = lp_munge_symlinks(i)) < 0)
  603. munge_symlinks = !use_chroot || module_dirlen;
  604. if (munge_symlinks) {
  605. STRUCT_STAT st;
  606. if (do_stat(SYMLINK_PREFIX, &st) == 0 && S_ISDIR(st.st_mode)) {
  607. rprintf(FLOG, "Symlink munging is unsupported when a %s directory exists.\n",
  608. SYMLINK_PREFIX);
  609. io_printf(f_out, "@ERROR: daemon security issue -- contact admin\n", name);
  610. exit_cleanup(RERR_UNSUPPORTED);
  611. }
  612. }
  613. if (am_root) {
  614. /* XXXX: You could argue that if the daemon is started
  615. * by a non-root user and they explicitly specify a
  616. * gid, then we should try to change to that gid --
  617. * this could be possible if it's already in their
  618. * supplementary groups. */
  619. /* TODO: Perhaps we need to document that if rsyncd is
  620. * started by somebody other than root it will inherit
  621. * all their supplementary groups. */
  622. if (setgid(gid)) {
  623. rsyserr(FLOG, errno, "setgid %d failed", (int)gid);
  624. io_printf(f_out, "@ERROR: setgid failed\n");
  625. return -1;
  626. }
  627. #ifdef HAVE_SETGROUPS
  628. /* Get rid of any supplementary groups this process
  629. * might have inheristed. */
  630. if (setgroups(1, &gid)) {
  631. rsyserr(FLOG, errno, "setgroups failed");
  632. io_printf(f_out, "@ERROR: setgroups failed\n");
  633. return -1;
  634. }
  635. #endif
  636. if (setuid(uid)) {
  637. rsyserr(FLOG, errno, "setuid %d failed", (int)uid);
  638. io_printf(f_out, "@ERROR: setuid failed\n");
  639. return -1;
  640. }
  641. am_root = (MY_UID() == 0);
  642. }
  643. if (lp_temp_dir(i) && *lp_temp_dir(i)) {
  644. tmpdir = lp_temp_dir(i);
  645. if (strlen(tmpdir) >= MAXPATHLEN - 10) {
  646. rprintf(FLOG,
  647. "the 'temp dir' value for %s is WAY too long -- ignoring.\n",
  648. name);
  649. tmpdir = NULL;
  650. }
  651. }
  652. io_printf(f_out, "@RSYNCD: OK\n");
  653. read_args(f_in, name, line, sizeof line, rl_nulls, &argv, &argc, &request);
  654. orig_argv = argv;
  655. verbose = 0; /* future verbosity is controlled by client options */
  656. ret = parse_arguments(&argc, (const char ***) &argv);
  657. if (protect_args && ret) {
  658. orig_early_argv = orig_argv;
  659. protect_args = 2;
  660. read_args(f_in, name, line, sizeof line, 1, &argv, &argc, &request);
  661. orig_argv = argv;
  662. ret = parse_arguments(&argc, (const char ***) &argv);
  663. } else
  664. orig_early_argv = NULL;
  665. if (pre_exec_pid) {
  666. err_msg = finish_pre_exec(pre_exec_pid, pre_exec_fd, request,
  667. orig_early_argv, orig_argv);
  668. }
  669. if (orig_early_argv)
  670. free(orig_early_argv);
  671. am_server = 1; /* Don't let someone try to be tricky. */
  672. quiet = 0;
  673. if (lp_ignore_errors(module_id))
  674. ignore_errors = 1;
  675. if (write_batch < 0)
  676. dry_run = 1;
  677. if (lp_fake_super(i)) {
  678. if (preserve_xattrs > 1)
  679. preserve_xattrs = 1;
  680. am_root = -1;
  681. } else if (am_root < 0) /* Treat --fake-super from client as --super. */
  682. am_root = 2;
  683. if (filesfrom_fd == 0)
  684. filesfrom_fd = f_in;
  685. if (request) {
  686. if (*auth_user) {
  687. rprintf(FLOG, "rsync %s %s from %s@%s (%s)\n",
  688. am_sender ? "on" : "to",
  689. request, auth_user, host, addr);
  690. } else {
  691. rprintf(FLOG, "rsync %s %s from %s (%s)\n",
  692. am_sender ? "on" : "to",
  693. request, host, addr);
  694. }
  695. free(request);
  696. }
  697. #ifndef DEBUG
  698. /* don't allow the logs to be flooded too fast */
  699. if (verbose > lp_max_verbosity(i))
  700. verbose = lp_max_verbosity(i);
  701. #endif
  702. if (protocol_version < 23
  703. && (protocol_version == 22 || am_sender))
  704. io_start_multiplex_out();
  705. else if (!ret || err_msg) {
  706. /* We have to get I/O multiplexing started so that we can
  707. * get the error back to the client. This means getting
  708. * the protocol setup finished first in later versions. */
  709. setup_protocol(f_out, f_in);
  710. if (!am_sender) {
  711. /* Since we failed in our option parsing, we may not
  712. * have finished parsing that the client sent us a
  713. * --files-from option, so look for it manually.
  714. * Without this, the socket would be in the wrong
  715. * state for the upcoming error message. */
  716. if (!files_from) {
  717. int i;
  718. for (i = 0; i < argc; i++) {
  719. if (strncmp(argv[i], "--files-from", 12) == 0) {
  720. files_from = "";
  721. break;
  722. }
  723. }
  724. }
  725. if (files_from)
  726. write_byte(f_out, 0);
  727. }
  728. io_start_multiplex_out();
  729. }
  730. if (!ret || err_msg) {
  731. if (err_msg)
  732. rwrite(FERROR, err_msg, strlen(err_msg), 0);
  733. else
  734. option_error();
  735. msleep(400);
  736. exit_cleanup(RERR_UNSUPPORTED);
  737. }
  738. #ifdef ICONV_OPTION
  739. if (!iconv_opt) {
  740. if (ic_send != (iconv_t)-1) {
  741. iconv_close(ic_send);
  742. ic_send = (iconv_t)-1;
  743. }
  744. if (ic_recv != (iconv_t)-1) {
  745. iconv_close(ic_recv);
  746. ic_recv = (iconv_t)-1;
  747. }
  748. }
  749. #endif
  750. if (!numeric_ids
  751. && (use_chroot ? lp_numeric_ids(i) != False : lp_numeric_ids(i) == True))
  752. numeric_ids = -1; /* Set --numeric-ids w/o breaking protocol. */
  753. if (lp_timeout(i) && lp_timeout(i) > io_timeout)
  754. set_io_timeout(lp_timeout(i));
  755. /* If we have some incoming/outgoing chmod changes, append them to
  756. * any user-specified changes (making our changes have priority).
  757. * We also get a pointer to just our changes so that a receiver
  758. * process can use them separately if --perms wasn't specified. */
  759. if (am_sender)
  760. p = lp_outgoing_chmod(i);
  761. else
  762. p = lp_incoming_chmod(i);
  763. if (*p && !(daemon_chmod_modes = parse_chmod(p, &chmod_modes))) {
  764. rprintf(FLOG, "Invalid \"%sing chmod\" directive: %s\n",
  765. am_sender ? "outgo" : "incom", p);
  766. }
  767. start_server(f_in, f_out, argc, argv);
  768. return 0;
  769. }
  770. /* send a list of available modules to the client. Don't list those
  771. with "list = False". */
  772. static void send_listing(int fd)
  773. {
  774. int n = lp_numservices();
  775. int i;
  776. for (i = 0; i < n; i++) {
  777. if (lp_list(i))
  778. io_printf(fd, "%-15s\t%s\n", lp_name(i), lp_comment(i));
  779. }
  780. if (protocol_version >= 25)
  781. io_printf(fd,"@RSYNCD: EXIT\n");
  782. }
  783. static int load_config(int globals_only)
  784. {
  785. if (!config_file) {
  786. if (am_server && am_root <= 0)
  787. config_file = RSYNCD_USERCONF;
  788. else
  789. config_file = RSYNCD_SYSCONF;
  790. }
  791. return lp_load(config_file, globals_only);
  792. }
  793. /* this is called when a connection is established to a client
  794. and we want to start talking. The setup of the system is done from
  795. here */
  796. int start_daemon(int f_in, int f_out)
  797. {
  798. char line[1024];
  799. char *addr, *host;
  800. int i;
  801. io_set_sock_fds(f_in, f_out);
  802. /* We must load the config file before calling any function that
  803. * might cause log-file output to occur. This ensures that the
  804. * "log file" param gets honored for the 2 non-forked use-cases
  805. * (when rsync is run by init and run by a remote shell). */
  806. if (!load_config(0))
  807. exit_cleanup(RERR_SYNTAX);
  808. addr = client_addr(f_in);
  809. host = client_name(f_in);
  810. rprintf(FLOG, "connect from %s (%s)\n", host, addr);
  811. if (!am_server) {
  812. set_socket_options(f_in, "SO_KEEPALIVE");
  813. set_nonblocking(f_in);
  814. }
  815. if (exchange_protocols(f_in, f_out, line, sizeof line, 0) < 0)
  816. return -1;
  817. line[0] = 0;
  818. if (!read_line_old(f_in, line, sizeof line))
  819. return -1;
  820. if (!*line || strcmp(line, "#list") == 0) {
  821. rprintf(FLOG, "module-list request from %s (%s)\n",
  822. host, addr);
  823. send_listing(f_out);
  824. return -1;
  825. }
  826. if (*line == '#') {
  827. /* it's some sort of command that I don't understand */
  828. io_printf(f_out, "@ERROR: Unknown command '%s'\n", line);
  829. return -1;
  830. }
  831. if ((i = lp_number(line)) < 0) {
  832. rprintf(FLOG, "unknown module '%s' tried from %s (%s)\n",
  833. line, host, addr);
  834. io_printf(f_out, "@ERROR: Unknown module '%s'\n", line);
  835. return -1;
  836. }
  837. #ifdef HAVE_SIGACTION
  838. sigact.sa_flags = SA_NOCLDSTOP;
  839. #endif
  840. SIGACTION(SIGCHLD, remember_children);
  841. return rsync_module(f_in, f_out, i, addr, host);
  842. }
  843. static void create_pid_file(void)
  844. {
  845. char *pid_file = lp_pid_file();
  846. char pidbuf[16];
  847. pid_t pid = getpid();
  848. int fd;
  849. if (!pid_file || !*pid_file)
  850. return;
  851. cleanup_set_pid(pid);
  852. if ((fd = do_open(pid_file, O_WRONLY|O_CREAT|O_EXCL, 0666 & ~orig_umask)) == -1) {
  853. cleanup_set_pid(0);
  854. fprintf(stderr, "failed to create pid file %s: %s\n", pid_file, strerror(errno));
  855. rsyserr(FLOG, errno, "failed to create pid file %s", pid_file);
  856. exit_cleanup(RERR_FILEIO);
  857. }
  858. snprintf(pidbuf, sizeof pidbuf, "%ld\n", (long)pid);
  859. write(fd, pidbuf, strlen(pidbuf));
  860. close(fd);
  861. }
  862. /* Become a daemon, discarding the controlling terminal. */
  863. static void become_daemon(void)
  864. {
  865. int i;
  866. pid_t pid = fork();
  867. if (pid) {
  868. if (pid < 0) {
  869. fprintf(stderr, "failed to fork: %s\n", strerror(errno));
  870. exit_cleanup(RERR_FILEIO);
  871. }
  872. _exit(0);
  873. }
  874. create_pid_file();
  875. /* detach from the terminal */
  876. #ifdef HAVE_SETSID
  877. setsid();
  878. #elif defined TIOCNOTTY
  879. i = open("/dev/tty", O_RDWR);
  880. if (i >= 0) {
  881. ioctl(i, (int)TIOCNOTTY, (char *)0);
  882. close(i);
  883. }
  884. #endif
  885. /* make sure that stdin, stdout an stderr don't stuff things
  886. * up (library functions, for example) */
  887. for (i = 0; i < 3; i++) {
  888. close(i);
  889. open("/dev/null", O_RDWR);
  890. }
  891. }
  892. int daemon_main(void)
  893. {
  894. if (is_a_socket(STDIN_FILENO)) {
  895. int i;
  896. /* we are running via inetd - close off stdout and
  897. * stderr so that library functions (and getopt) don't
  898. * try to use them. Redirect them to /dev/null */
  899. for (i = 1; i < 3; i++) {
  900. close(i);
  901. open("/dev/null", O_RDWR);
  902. }
  903. return start_daemon(STDIN_FILENO, STDIN_FILENO);
  904. }
  905. if (!load_config(1)) {
  906. fprintf(stderr, "Failed to parse config file: %s\n", config_file);
  907. exit_cleanup(RERR_SYNTAX);
  908. }
  909. if (no_detach)
  910. create_pid_file();
  911. else
  912. become_daemon();
  913. if (rsync_port == 0 && (rsync_port = lp_rsync_port()) == 0)
  914. rsync_port = RSYNC_PORT;
  915. if (bind_address == NULL && *lp_bind_address())
  916. bind_address = lp_bind_address();
  917. log_init(0);
  918. rprintf(FLOG, "rsyncd version %s starting, listening on port %d\n",
  919. RSYNC_VERSION, rsync_port);
  920. /* TODO: If listening on a particular address, then show that
  921. * address too. In fact, why not just do inet_ntop on the
  922. * local address??? */
  923. start_accept_loop(rsync_port, start_daemon);
  924. return -1;
  925. }