clientserver.c 28 KB

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