Annotation of embedaddon/rsync/clientserver.c, revision 1.1.1.4

1.1       misho       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>
1.1.1.4 ! misho       6:  * Copyright (C) 2002-2020 Wayne Davison
1.1       misho       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: 
                     22: #include "rsync.h"
1.1.1.2   misho      23: #include "itypes.h"
1.1.1.4 ! misho      24: #include "ifuncs.h"
1.1       misho      25: 
                     26: extern int quiet;
                     27: extern int dry_run;
                     28: extern int output_motd;
                     29: extern int list_only;
                     30: extern int am_sender;
                     31: extern int am_server;
                     32: extern int am_daemon;
                     33: extern int am_root;
1.1.1.4 ! misho      34: extern int msgs2stderr;
1.1       misho      35: extern int rsync_port;
                     36: extern int protect_args;
                     37: extern int ignore_errors;
                     38: extern int preserve_xattrs;
                     39: extern int kluge_around_eof;
1.1.1.2   misho      40: extern int munge_symlinks;
1.1.1.4 ! misho      41: extern int open_noatime;
1.1       misho      42: extern int sanitize_paths;
                     43: extern int numeric_ids;
                     44: extern int filesfrom_fd;
                     45: extern int remote_protocol;
                     46: extern int protocol_version;
1.1.1.4 ! misho      47: extern int always_checksum;
        !            48: extern int checksum_files;
1.1       misho      49: extern int io_timeout;
                     50: extern int no_detach;
                     51: extern int write_batch;
                     52: extern int default_af_hint;
                     53: extern int logfile_format_has_i;
                     54: extern int logfile_format_has_o_or_i;
                     55: extern char *bind_address;
                     56: extern char *config_file;
1.1.1.4 ! misho      57: extern char *link_by_hash_dir;
1.1       misho      58: extern char *logfile_format;
                     59: extern char *files_from;
                     60: extern char *tmpdir;
1.1.1.4 ! misho      61: extern char *early_input_file;
1.1       misho      62: extern struct chmod_mode_struct *chmod_modes;
1.1.1.2   misho      63: extern filter_rule_list daemon_filter_list;
1.1       misho      64: #ifdef ICONV_OPTION
                     65: extern char *iconv_opt;
                     66: extern iconv_t ic_send, ic_recv;
                     67: #endif
1.1.1.4 ! misho      68: extern uid_t our_uid;
        !            69: extern gid_t our_gid;
1.1       misho      70: 
                     71: char *auth_user;
                     72: int read_only = 0;
                     73: int module_id = -1;
1.1.1.4 ! misho      74: int pid_file_fd = -1;
        !            75: int early_input_len = 0;
        !            76: char *early_input = NULL;
        !            77: pid_t namecvt_pid = 0;
1.1       misho      78: struct chmod_mode_struct *daemon_chmod_modes;
                     79: 
1.1.1.4 ! misho      80: #define EARLY_INPUT_CMD "#early_input="
        !            81: #define EARLY_INPUT_CMDLEN (sizeof EARLY_INPUT_CMD - 1)
        !            82: 
1.1       misho      83: /* module_dirlen is the length of the module_dir string when in daemon
                     84:  * mode and module_dir is not "/"; otherwise 0.  (Note that a chroot-
                     85:  * enabled module can have a non-"/" module_dir these days.) */
                     86: char *module_dir = NULL;
                     87: unsigned int module_dirlen = 0;
                     88: 
                     89: char *full_module_path;
                     90: 
                     91: static int rl_nulls = 0;
1.1.1.4 ! misho      92: static int namecvt_fd_req = -1, namecvt_fd_ans = -1;
1.1       misho      93: 
                     94: #ifdef HAVE_SIGACTION
                     95: static struct sigaction sigact;
                     96: #endif
                     97: 
1.1.1.3   misho      98: static item_list gid_list = EMPTY_ITEM_LIST;
1.1.1.2   misho      99: 
                    100: /* Used when "reverse lookup" is off. */
                    101: const char undetermined_hostname[] = "UNDETERMINED";
                    102: 
1.1       misho     103: /**
                    104:  * Run a client connected to an rsyncd.  The alternative to this
                    105:  * function for remote-shell connections is do_cmd().
                    106:  *
                    107:  * After negotiating which module to use and reading the server's
                    108:  * motd, this hands over to client_run().  Telling the server the
                    109:  * module will cause it to chroot/setuid/etc.
                    110:  *
                    111:  * Instead of doing a transfer, the client may at this stage instead
                    112:  * get a listing of remote modules and exit.
                    113:  *
                    114:  * @return -1 for error in startup, or the result of client_run().
                    115:  * Either way, it eventually gets passed to exit_cleanup().
                    116:  **/
                    117: int start_socket_client(char *host, int remote_argc, char *remote_argv[],
                    118:                        int argc, char *argv[])
                    119: {
                    120:        int fd, ret;
                    121:        char *p, *user = NULL;
                    122: 
                    123:        /* This is redundant with code in start_inband_exchange(), but this
                    124:         * short-circuits a problem in the client before we open a socket,
                    125:         * and the extra check won't hurt. */
                    126:        if (**remote_argv == '/') {
                    127:                rprintf(FERROR,
                    128:                        "ERROR: The remote path must start with a module name not a /\n");
                    129:                return -1;
                    130:        }
                    131: 
                    132:        if ((p = strrchr(host, '@')) != NULL) {
                    133:                user = host;
                    134:                host = p+1;
                    135:                *p = '\0';
                    136:        }
                    137: 
1.1.1.4 ! misho     138:        fd = open_socket_out_wrapped(host, rsync_port, bind_address, default_af_hint);
1.1       misho     139:        if (fd == -1)
                    140:                exit_cleanup(RERR_SOCKETIO);
                    141: 
                    142: #ifdef ICONV_CONST
                    143:        setup_iconv();
                    144: #endif
                    145: 
1.1.1.4 ! misho     146:        ret = start_inband_exchange(fd, fd, user, host, remote_argc, remote_argv);
1.1       misho     147: 
                    148:        return ret ? ret : client_run(fd, fd, -1, argc, argv);
                    149: }
                    150: 
                    151: static int exchange_protocols(int f_in, int f_out, char *buf, size_t bufsiz, int am_client)
                    152: {
                    153:        int remote_sub = -1;
                    154: #if SUBPROTOCOL_VERSION != 0
                    155:        int our_sub = protocol_version < PROTOCOL_VERSION ? 0 : SUBPROTOCOL_VERSION;
                    156: #else
                    157:        int our_sub = 0;
                    158: #endif
                    159: 
                    160:        io_printf(f_out, "@RSYNCD: %d.%d\n", protocol_version, our_sub);
                    161:        if (!am_client) {
1.1.1.4 ! misho     162:                char *motd = lp_motd_file();
1.1       misho     163:                if (motd && *motd) {
1.1.1.4 ! misho     164:                        FILE *f = fopen(motd, "r");
1.1       misho     165:                        while (f && !feof(f)) {
                    166:                                int len = fread(buf, 1, bufsiz - 1, f);
                    167:                                if (len > 0)
                    168:                                        write_buf(f_out, buf, len);
                    169:                        }
                    170:                        if (f)
                    171:                                fclose(f);
                    172:                        write_sbuf(f_out, "\n");
                    173:                }
                    174:        }
                    175: 
                    176:        /* This strips the \n. */
1.1.1.2   misho     177:        if (!read_line_old(f_in, buf, bufsiz, 0)) {
1.1       misho     178:                if (am_client)
                    179:                        rprintf(FERROR, "rsync: did not see server greeting\n");
                    180:                return -1;
                    181:        }
                    182: 
                    183:        if (sscanf(buf, "@RSYNCD: %d.%d", &remote_protocol, &remote_sub) < 1) {
                    184:                if (am_client)
                    185:                        rprintf(FERROR, "rsync: server sent \"%s\" rather than greeting\n", buf);
                    186:                else
                    187:                        io_printf(f_out, "@ERROR: protocol startup error\n");
                    188:                return -1;
                    189:        }
                    190: 
                    191:        if (remote_sub < 0) {
                    192:                if (remote_protocol == 30) {
                    193:                        if (am_client)
                    194:                                rprintf(FERROR, "rsync: server is speaking an incompatible beta of protocol 30\n");
                    195:                        else
                    196:                                io_printf(f_out, "@ERROR: your client is speaking an incompatible beta of protocol 30\n");
                    197:                        return -1;
                    198:                }
                    199:                remote_sub = 0;
                    200:        }
                    201: 
                    202:        if (protocol_version > remote_protocol) {
                    203:                protocol_version = remote_protocol;
                    204:                if (remote_sub)
                    205:                        protocol_version--;
                    206:        } else if (protocol_version == remote_protocol) {
                    207:                if (remote_sub != our_sub)
                    208:                        protocol_version--;
                    209:        }
                    210: #if SUBPROTOCOL_VERSION != 0
                    211:        else if (protocol_version < remote_protocol) {
                    212:                if (our_sub)
                    213:                        protocol_version--;
                    214:        }
                    215: #endif
                    216: 
                    217:        if (protocol_version >= 30)
                    218:                rl_nulls = 1;
                    219: 
                    220:        return 0;
                    221: }
                    222: 
1.1.1.4 ! misho     223: int start_inband_exchange(int f_in, int f_out, const char *user, const char *host, int argc, char *argv[])
1.1       misho     224: {
                    225:        int i, modlen;
                    226:        char line[BIGPATHBUFLEN];
                    227:        char *sargs[MAX_ARGS];
                    228:        int sargc = 0;
                    229:        char *p, *modname;
                    230: 
                    231:        assert(argc > 0 && *argv != NULL);
                    232: 
                    233:        if (**argv == '/') {
                    234:                rprintf(FERROR,
                    235:                        "ERROR: The remote path must start with a module name\n");
                    236:                return -1;
                    237:        }
                    238: 
                    239:        if (!(p = strchr(*argv, '/')))
                    240:                modlen = strlen(*argv);
                    241:        else
                    242:                modlen = p - *argv;
                    243: 
1.1.1.4 ! misho     244:        modname = new_array(char, modlen+1+1); /* room for '/' & '\0' */
1.1       misho     245:        strlcpy(modname, *argv, modlen + 1);
                    246:        modname[modlen] = '/';
                    247:        modname[modlen+1] = '\0';
                    248: 
                    249:        if (!user)
                    250:                user = getenv("USER");
                    251:        if (!user)
                    252:                user = getenv("LOGNAME");
                    253: 
                    254:        if (exchange_protocols(f_in, f_out, line, sizeof line, 1) < 0)
                    255:                return -1;
                    256: 
1.1.1.4 ! misho     257:        if (early_input_file) {
        !           258:                STRUCT_STAT st;
        !           259:                FILE *f = fopen(early_input_file, "rb");
        !           260:                if (!f || do_fstat(fileno(f), &st) < 0) {
        !           261:                        rsyserr(FERROR, errno, "failed to open %s", early_input_file);
        !           262:                        return -1;
        !           263:                }
        !           264:                early_input_len = st.st_size;
        !           265:                if (early_input_len > (int)sizeof line) {
        !           266:                        rprintf(FERROR, "%s is > %d bytes.\n", early_input_file, (int)sizeof line);
        !           267:                        return -1;
        !           268:                }
        !           269:                if (early_input_len > 0) {
        !           270:                        io_printf(f_out, EARLY_INPUT_CMD "%d\n", early_input_len);
        !           271:                        while (early_input_len > 0) {
        !           272:                                int len;
        !           273:                                if (feof(f)) {
        !           274:                                        rprintf(FERROR, "Early EOF in %s\n", early_input_file);
        !           275:                                        return -1;
        !           276:                                }
        !           277:                                len = fread(line, 1, early_input_len, f);
        !           278:                                if (len > 0) {
        !           279:                                        write_buf(f_out, line, len);
        !           280:                                        early_input_len -= len;
        !           281:                                }
        !           282:                        }
        !           283:                }
        !           284:                fclose(f);
        !           285:        }
        !           286: 
1.1       misho     287:        server_options(sargs, &sargc);
                    288: 
                    289:        if (sargc >= MAX_ARGS - 2)
                    290:                goto arg_overflow;
                    291: 
                    292:        sargs[sargc++] = ".";
                    293: 
                    294:        while (argc > 0) {
                    295:                if (sargc >= MAX_ARGS - 1) {
                    296:                  arg_overflow:
                    297:                        rprintf(FERROR, "internal: args[] overflowed in do_cmd()\n");
                    298:                        exit_cleanup(RERR_SYNTAX);
                    299:                }
                    300:                if (strncmp(*argv, modname, modlen) == 0
                    301:                 && argv[0][modlen] == '\0')
                    302:                        sargs[sargc++] = modname; /* we send "modname/" */
                    303:                else if (**argv == '-') {
                    304:                        if (asprintf(sargs + sargc++, "./%s", *argv) < 0)
                    305:                                out_of_memory("start_inband_exchange");
                    306:                } else
                    307:                        sargs[sargc++] = *argv;
                    308:                argv++;
                    309:                argc--;
                    310:        }
                    311: 
                    312:        sargs[sargc] = NULL;
                    313: 
1.1.1.2   misho     314:        if (DEBUG_GTE(CMD, 1))
1.1       misho     315:                print_child_argv("sending daemon args:", sargs);
                    316: 
                    317:        io_printf(f_out, "%.*s\n", modlen, modname);
                    318: 
                    319:        /* Old servers may just drop the connection here,
                    320:         rather than sending a proper EXIT command.  Yuck. */
                    321:        kluge_around_eof = list_only && protocol_version < 25 ? 1 : 0;
                    322: 
                    323:        while (1) {
1.1.1.2   misho     324:                if (!read_line_old(f_in, line, sizeof line, 0)) {
1.1       misho     325:                        rprintf(FERROR, "rsync: didn't get server startup line\n");
                    326:                        return -1;
                    327:                }
                    328: 
                    329:                if (strncmp(line,"@RSYNCD: AUTHREQD ",18) == 0) {
                    330:                        auth_client(f_out, user, line+18);
                    331:                        continue;
                    332:                }
                    333: 
1.1.1.4 ! misho     334:                if (strcmp(line, "@RSYNCD: GSS") == 0) {
        !           335: #ifdef GSSAPI_OPTION
        !           336:                        if (auth_gss_client(f_out, host) < 0)
        !           337:                                return -1;
        !           338:                        continue;
        !           339: #else
        !           340:                        rprintf(FERROR, "GSSAPI is not supported\n");
        !           341:                        return -1;
        !           342: #endif
        !           343:                }
        !           344: 
1.1       misho     345:                if (strcmp(line,"@RSYNCD: OK") == 0)
                    346:                        break;
                    347: 
                    348:                if (strcmp(line,"@RSYNCD: EXIT") == 0) {
                    349:                        /* This is sent by recent versions of the
                    350:                         * server to terminate the listing of modules.
                    351:                         * We don't want to go on and transfer
                    352:                         * anything; just exit. */
                    353:                        exit(0);
                    354:                }
                    355: 
                    356:                if (strncmp(line, "@ERROR", 6) == 0) {
                    357:                        rprintf(FERROR, "%s\n", line);
                    358:                        /* This is always fatal; the server will now
                    359:                         * close the socket. */
                    360:                        return -1;
                    361:                }
                    362: 
                    363:                /* This might be a MOTD line or a module listing, but there is
                    364:                 * no way to differentiate it.  The manpage mentions this. */
                    365:                if (output_motd)
                    366:                        rprintf(FINFO, "%s\n", line);
                    367:        }
                    368:        kluge_around_eof = 0;
                    369: 
                    370:        if (rl_nulls) {
                    371:                for (i = 0; i < sargc; i++) {
                    372:                        if (!sargs[i]) /* stop at --protect-args NULL */
                    373:                                break;
                    374:                        write_sbuf(f_out, sargs[i]);
                    375:                        write_byte(f_out, 0);
                    376:                }
                    377:                write_byte(f_out, 0);
                    378:        } else {
                    379:                for (i = 0; i < sargc; i++)
                    380:                        io_printf(f_out, "%s\n", sargs[i]);
                    381:                write_sbuf(f_out, "\n");
                    382:        }
                    383: 
                    384:        if (protect_args)
                    385:                send_protected_args(f_out, sargs);
                    386: 
                    387:        if (protocol_version < 23) {
                    388:                if (protocol_version == 22 || !am_sender)
1.1.1.2   misho     389:                        io_start_multiplex_in(f_in);
1.1       misho     390:        }
                    391: 
                    392:        free(modname);
                    393: 
                    394:        return 0;
                    395: }
                    396: 
1.1.1.4 ! misho     397: #ifdef HAVE_PUTENV
        !           398: static int read_arg_from_pipe(int fd, char *buf, int limit)
        !           399: {
        !           400:        char *bp = buf, *eob = buf + limit - 1;
        !           401: 
        !           402:        while (1) {
        !           403:                int got = read(fd, bp, 1);
        !           404:                if (got != 1) {
        !           405:                        if (got < 0 && errno == EINTR)
        !           406:                                continue;
        !           407:                        return -1;
        !           408:                }
        !           409:                if (*bp == '\0')
        !           410:                        break;
        !           411:                if (bp < eob)
        !           412:                        bp++;
        !           413:        }
        !           414:        *bp = '\0';
        !           415: 
        !           416:        return bp - buf;
        !           417: }
        !           418: #endif
        !           419: 
        !           420: static void set_env_str(const char *var, const char *str)
        !           421: {
        !           422: #ifdef HAVE_PUTENV
        !           423:        char *mem;
        !           424:        if (asprintf(&mem, "%s=%s", var, str) < 0)
        !           425:                out_of_memory("set_env_str");
        !           426:        putenv(mem);
        !           427: #endif
        !           428: }
        !           429: 
        !           430: #ifdef HAVE_PUTENV
        !           431: void set_env_num(const char *var, long num)
        !           432: {
        !           433:        char *mem;
        !           434:        if (asprintf(&mem, "%s=%ld", var, num) < 0)
        !           435:                out_of_memory("set_env_num");
        !           436:        putenv(mem);
        !           437: }
        !           438: #endif
        !           439: 
        !           440: /* Used for "early exec", "pre-xfer exec", and the "name converter" script. */
        !           441: static pid_t start_pre_exec(const char *cmd, int *arg_fd_ptr, int *error_fd_ptr)
        !           442: {
        !           443:        int arg_fds[2], error_fds[2], arg_fd;
        !           444:        pid_t pid;
        !           445: 
        !           446:        if ((error_fd_ptr && pipe(error_fds) < 0) || pipe(arg_fds) < 0 || (pid = fork()) < 0)
        !           447:                return (pid_t)-1;
        !           448: 
        !           449:        if (pid == 0) {
        !           450:                char buf[BIGPATHBUFLEN];
        !           451:                int j, len, status;
        !           452: 
        !           453:                if (error_fd_ptr) {
        !           454:                        close(error_fds[0]);
        !           455:                        set_blocking(error_fds[1]);
        !           456:                }
        !           457: 
        !           458:                close(arg_fds[1]);
        !           459:                arg_fd = arg_fds[0];
        !           460:                set_blocking(arg_fd);
        !           461: 
        !           462:                len = read_arg_from_pipe(arg_fd, buf, BIGPATHBUFLEN);
        !           463:                if (len <= 0)
        !           464:                        _exit(1);
        !           465:                set_env_str("RSYNC_REQUEST", buf);
        !           466: 
        !           467:                for (j = 0; ; j++) {
        !           468:                        char *p;
        !           469:                        len = read_arg_from_pipe(arg_fd, buf, BIGPATHBUFLEN);
        !           470:                        if (len <= 0) {
        !           471:                                if (!len)
        !           472:                                        break;
        !           473:                                _exit(1);
        !           474:                        }
        !           475:                        if (asprintf(&p, "RSYNC_ARG%d=%s", j, buf) >= 0)
        !           476:                                putenv(p);
        !           477:                }
        !           478: 
        !           479:                dup2(arg_fd, STDIN_FILENO);
        !           480:                close(arg_fd);
        !           481: 
        !           482:                if (error_fd_ptr) {
        !           483:                        dup2(error_fds[1], STDOUT_FILENO);
        !           484:                        close(error_fds[1]);
        !           485:                }
        !           486: 
        !           487:                status = shell_exec(cmd);
        !           488: 
        !           489:                if (!WIFEXITED(status))
        !           490:                        _exit(1);
        !           491:                _exit(WEXITSTATUS(status));
        !           492:        }
        !           493: 
        !           494:        if (error_fd_ptr) {
        !           495:                close(error_fds[1]);
        !           496:                *error_fd_ptr = error_fds[0];
        !           497:                set_blocking(error_fds[0]);
        !           498:        }
        !           499: 
        !           500:        close(arg_fds[0]);
        !           501:        arg_fd = *arg_fd_ptr = arg_fds[1];
        !           502:        set_blocking(arg_fd);
        !           503: 
        !           504:        return pid;
        !           505: }
        !           506: 
        !           507: static void write_pre_exec_args(int write_fd, char *request, char **early_argv, char **argv, int exec_type)
1.1       misho     508: {
1.1.1.4 ! misho     509:        int j = 0;
1.1       misho     510: 
                    511:        if (!request)
                    512:                request = "(NONE)";
                    513: 
1.1.1.2   misho     514:        write_buf(write_fd, request, strlen(request)+1);
1.1       misho     515:        if (early_argv) {
                    516:                for ( ; *early_argv; early_argv++)
1.1.1.2   misho     517:                        write_buf(write_fd, *early_argv, strlen(*early_argv)+1);
1.1       misho     518:                j = 1; /* Skip arg0 name in argv. */
                    519:        }
1.1.1.4 ! misho     520:        if (argv) {
        !           521:                for ( ; argv[j]; j++)
        !           522:                        write_buf(write_fd, argv[j], strlen(argv[j])+1);
        !           523:        }
1.1.1.2   misho     524:        write_byte(write_fd, 0);
                    525: 
1.1.1.4 ! misho     526:        if (exec_type == 1 && early_input_len)
        !           527:                write_buf(write_fd, early_input, early_input_len);
1.1.1.2   misho     528: 
1.1.1.4 ! misho     529:        if (exec_type != 2) /* the name converter needs this left open */
        !           530:                close(write_fd);
        !           531: }
        !           532: 
        !           533: static char *finish_pre_exec(const char *desc, pid_t pid, int read_fd)
        !           534: {
        !           535:        char buf[BIGPATHBUFLEN], *bp, *cr;
        !           536:        int j, status = -1, msglen = sizeof buf - 1;
        !           537: 
        !           538:        if (read_fd >= 0) {
        !           539:                /* Read the stdout from the program.  This it is only displayed
        !           540:                 * to the user if the script also returns an error status. */
        !           541:                for (bp = buf, cr = buf; msglen > 0; msglen -= j) {
        !           542:                        if ((j = read(read_fd, bp, msglen)) <= 0) {
        !           543:                                if (j == 0)
        !           544:                                        break;
        !           545:                                if (errno == EINTR)
        !           546:                                        continue;
        !           547:                                break; /* Just ignore the read error for now... */
        !           548:                        }
        !           549:                        bp[j] = '\0';
        !           550:                        while (1) {
        !           551:                                if ((cr = strchr(cr, '\r')) == NULL) {
        !           552:                                        cr = bp + j;
        !           553:                                        break;
        !           554:                                }
        !           555:                                if (!cr[1])
        !           556:                                        break; /* wait for more data before we decide what to do */
        !           557:                                if (cr[1] == '\n') {
        !           558:                                        memmove(cr, cr+1, j - (cr - bp));
        !           559:                                        j--;
        !           560:                                } else
        !           561:                                        cr++;
        !           562:                        }
        !           563:                        bp += j;
1.1.1.2   misho     564:                }
1.1.1.4 ! misho     565:                *bp = '\0';
1.1       misho     566: 
1.1.1.4 ! misho     567:                close(read_fd);
        !           568:        } else
        !           569:                *buf = '\0';
1.1       misho     570: 
                    571:        if (wait_process(pid, &status, 0) < 0
                    572:         || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
                    573:                char *e;
1.1.1.4 ! misho     574:                if (asprintf(&e, "%s returned failure (%d)%s%s%s\n%s",
        !           575:                             desc, status, status < 0 ? ": " : "",
1.1.1.2   misho     576:                             status < 0 ? strerror(errno) : "",
                    577:                             *buf ? ":" : "", buf) < 0)
                    578:                        return "out_of_memory in finish_pre_exec\n";
1.1       misho     579:                return e;
                    580:        }
                    581:        return NULL;
                    582: }
                    583: 
                    584: static int path_failure(int f_out, const char *dir, BOOL was_chdir)
                    585: {
                    586:        if (was_chdir)
1.1.1.4 ! misho     587:                rsyserr(FLOG, errno, "chdir %s failed", dir);
1.1       misho     588:        else
                    589:                rprintf(FLOG, "normalize_path(%s) failed\n", dir);
                    590:        io_printf(f_out, "@ERROR: chdir failed\n");
                    591:        return -1;
                    592: }
                    593: 
1.1.1.2   misho     594: static int add_a_group(int f_out, const char *gname)
                    595: {
1.1.1.3   misho     596:        gid_t gid, *gid_p;
1.1.1.2   misho     597:        if (!group_to_gid(gname, &gid, True)) {
                    598:                rprintf(FLOG, "Invalid gid %s\n", gname);
                    599:                io_printf(f_out, "@ERROR: invalid gid %s\n", gname);
                    600:                return -1;
                    601:        }
1.1.1.3   misho     602:        gid_p = EXPAND_ITEM_LIST(&gid_list, gid_t, -32);
                    603:        *gid_p = gid;
1.1.1.2   misho     604:        return 0;
                    605: }
                    606: 
                    607: #ifdef HAVE_GETGROUPLIST
                    608: static int want_all_groups(int f_out, uid_t uid)
                    609: {
                    610:        const char *err;
1.1.1.3   misho     611:        if ((err = getallgroups(uid, &gid_list)) != NULL) {
1.1.1.2   misho     612:                rsyserr(FLOG, errno, "%s", err);
                    613:                io_printf(f_out, "@ERROR: %s\n", err);
                    614:                return -1;
                    615:        }
                    616:        return 0;
                    617: }
                    618: #elif defined HAVE_INITGROUPS
                    619: static struct passwd *want_all_groups(int f_out, uid_t uid)
                    620: {
                    621:        struct passwd *pw;
1.1.1.3   misho     622:        gid_t *gid_p;
1.1.1.2   misho     623:        if ((pw = getpwuid(uid)) == NULL) {
                    624:                rsyserr(FLOG, errno, "getpwuid failed");
                    625:                io_printf(f_out, "@ERROR: getpwuid failed\n");
                    626:                return NULL;
                    627:        }
1.1.1.3   misho     628:        /* Start with the default group and initgroups() will add the rest. */
                    629:        gid_p = EXPAND_ITEM_LIST(&gid_list, gid_t, -32);
                    630:        *gid_p = pw->pw_gid;
1.1.1.2   misho     631:        return pw;
                    632: }
                    633: #endif
                    634: 
                    635: static int rsync_module(int f_in, int f_out, int i, const char *addr, const char *host)
1.1       misho     636: {
                    637:        int argc;
                    638:        char **argv, **orig_argv, **orig_early_argv, *module_chdir;
                    639:        char line[BIGPATHBUFLEN];
1.1.1.2   misho     640: #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
                    641:        struct passwd *pw = NULL;
                    642: #endif
                    643:        uid_t uid;
                    644:        int set_uid;
1.1       misho     645:        char *p, *err_msg = NULL;
                    646:        char *name = lp_name(i);
                    647:        int use_chroot = lp_use_chroot(i);
1.1.1.2   misho     648:        int ret, pre_exec_arg_fd = -1, pre_exec_error_fd = -1;
                    649:        int save_munge_symlinks;
1.1       misho     650:        pid_t pre_exec_pid = 0;
                    651:        char *request = NULL;
                    652: 
1.1.1.2   misho     653:        set_env_str("RSYNC_MODULE_NAME", name);
                    654: 
1.1       misho     655: #ifdef ICONV_OPTION
                    656:        iconv_opt = lp_charset(i);
                    657:        if (*iconv_opt)
                    658:                setup_iconv();
                    659:        iconv_opt = NULL;
                    660: #endif
                    661: 
1.1.1.2   misho     662:        /* If reverse lookup is disabled globally but enabled for this module,
                    663:         * we need to do it now before the access check. */
                    664:        if (host == undetermined_hostname && lp_reverse_lookup(i))
1.1.1.4 ! misho     665:                host = client_name(client_addr(f_in));
1.1.1.2   misho     666:        set_env_str("RSYNC_HOST_NAME", host);
                    667:        set_env_str("RSYNC_HOST_ADDR", addr);
                    668: 
                    669:        if (!allow_access(addr, &host, i)) {
1.1       misho     670:                rprintf(FLOG, "rsync denied on module %s from %s (%s)\n",
                    671:                        name, host, addr);
                    672:                if (!lp_list(i))
                    673:                        io_printf(f_out, "@ERROR: Unknown module '%s'\n", name);
                    674:                else {
                    675:                        io_printf(f_out,
                    676:                                  "@ERROR: access denied to %s from %s (%s)\n",
                    677:                                  name, host, addr);
                    678:                }
                    679:                return -1;
                    680:        }
                    681: 
1.1.1.4 ! misho     682:        if (*lp_link_by_hash_dir(i))
        !           683:                link_by_hash_dir = lp_link_by_hash_dir(i);
        !           684: 
        !           685:        if (am_daemon > 0) {
1.1       misho     686:                rprintf(FLOG, "rsync allowed access on module %s from %s (%s)\n",
                    687:                        name, host, addr);
                    688:        }
                    689: 
                    690:        if (!claim_connection(lp_lock_file(i), lp_max_connections(i))) {
                    691:                if (errno) {
                    692:                        rsyserr(FLOG, errno, "failed to open lock file %s",
                    693:                                lp_lock_file(i));
                    694:                        io_printf(f_out, "@ERROR: failed to open lock file\n");
                    695:                } else {
                    696:                        rprintf(FLOG, "max connections (%d) reached\n",
                    697:                                lp_max_connections(i));
                    698:                        io_printf(f_out, "@ERROR: max connections (%d) reached -- try again later\n",
                    699:                                lp_max_connections(i));
                    700:                }
                    701:                return -1;
                    702:        }
                    703: 
1.1.1.2   misho     704:        read_only = lp_read_only(i); /* may also be overridden by auth_server() */
1.1.1.4 ! misho     705: #ifdef GSSAPI_OPTION
        !           706:        if (lp_use_gssapi(i))
        !           707:                auth_user = auth_gss_server(f_in, f_out, i, host, addr, "@RSYNCD: GSS");
        !           708:        else
        !           709: #endif
        !           710:                auth_user = auth_server(f_in, f_out, i, host, addr, "@RSYNCD: AUTHREQD ");
1.1       misho     711: 
                    712:        if (!auth_user) {
                    713:                io_printf(f_out, "@ERROR: auth failed on module %s\n", name);
                    714:                return -1;
                    715:        }
1.1.1.2   misho     716:        set_env_str("RSYNC_USER_NAME", auth_user);
1.1       misho     717: 
                    718:        module_id = i;
                    719: 
1.1.1.4 ! misho     720:        if (lp_transfer_logging(module_id) && !logfile_format)
        !           721:                logfile_format = lp_log_format(module_id);
1.1       misho     722:        if (log_format_has(logfile_format, 'i'))
                    723:                logfile_format_has_i = 1;
                    724:        if (logfile_format_has_i || log_format_has(logfile_format, 'o'))
                    725:                logfile_format_has_o_or_i = 1;
                    726: 
1.1.1.2   misho     727:        uid = MY_UID();
1.1.1.4 ! misho     728:        am_root = (uid == ROOT_UID);
1.1       misho     729: 
1.1.1.4 ! misho     730:        p = *lp_uid(module_id) ? lp_uid(module_id) : am_root ? NOBODY_USER : NULL;
1.1.1.2   misho     731:        if (p) {
                    732:                if (!user_to_uid(p, &uid, True)) {
                    733:                        rprintf(FLOG, "Invalid uid %s\n", p);
                    734:                        io_printf(f_out, "@ERROR: invalid uid %s\n", p);
                    735:                        return -1;
1.1       misho     736:                }
1.1.1.2   misho     737:                set_uid = 1;
                    738:        } else
                    739:                set_uid = 0;
1.1       misho     740: 
1.1.1.4 ! misho     741:        p = *lp_gid(module_id) ? conf_strtok(lp_gid(module_id)) : NULL;
1.1.1.2   misho     742:        if (p) {
                    743:                /* The "*" gid must be the first item in the list. */
                    744:                if (strcmp(p, "*") == 0) {
                    745: #ifdef HAVE_GETGROUPLIST
                    746:                        if (want_all_groups(f_out, uid) < 0)
                    747:                                return -1;
                    748: #elif defined HAVE_INITGROUPS
                    749:                        if ((pw = want_all_groups(f_out, uid)) == NULL)
                    750:                                return -1;
                    751: #else
                    752:                        rprintf(FLOG, "This rsync does not support a gid of \"*\"\n");
                    753:                        io_printf(f_out, "@ERROR: invalid gid setting.\n");
                    754:                        return -1;
                    755: #endif
                    756:                } else if (add_a_group(f_out, p) < 0)
                    757:                        return -1;
1.1.1.4 ! misho     758:                while ((p = conf_strtok(NULL)) != NULL) {
1.1.1.2   misho     759: #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
                    760:                        if (pw) {
                    761:                                rprintf(FLOG, "This rsync cannot add groups after \"*\".\n");
                    762:                                io_printf(f_out, "@ERROR: invalid gid setting.\n");
1.1       misho     763:                                return -1;
                    764:                        }
1.1.1.2   misho     765: #endif
                    766:                        if (add_a_group(f_out, p) < 0)
                    767:                                return -1;
1.1       misho     768:                }
1.1.1.2   misho     769:        } else if (am_root) {
                    770:                if (add_a_group(f_out, NOBODY_GROUP) < 0)
                    771:                        return -1;
1.1       misho     772:        }
                    773: 
1.1.1.4 ! misho     774:        module_dir = lp_path(module_id);
1.1       misho     775:        if (*module_dir == '\0') {
                    776:                rprintf(FLOG, "No path specified for module %s\n", name);
                    777:                io_printf(f_out, "@ERROR: no path setting.\n");
                    778:                return -1;
                    779:        }
                    780:        if (use_chroot) {
                    781:                if ((p = strstr(module_dir, "/./")) != NULL) {
                    782:                        *p = '\0'; /* Temporary... */
                    783:                        if (!(module_chdir = normalize_path(module_dir, True, NULL)))
                    784:                                return path_failure(f_out, module_dir, False);
                    785:                        *p = '/';
                    786:                        if (!(p = normalize_path(p + 2, True, &module_dirlen)))
                    787:                                return path_failure(f_out, strstr(module_dir, "/./"), False);
                    788:                        if (!(full_module_path = normalize_path(module_dir, False, NULL)))
                    789:                                full_module_path = module_dir;
                    790:                        module_dir = p;
                    791:                } else {
                    792:                        if (!(module_chdir = normalize_path(module_dir, False, NULL)))
                    793:                                return path_failure(f_out, module_dir, False);
                    794:                        full_module_path = module_chdir;
                    795:                        module_dir = "/";
                    796:                        module_dirlen = 1;
                    797:                }
                    798:        } else {
                    799:                if (!(module_chdir = normalize_path(module_dir, False, &module_dirlen)))
                    800:                        return path_failure(f_out, module_dir, False);
                    801:                full_module_path = module_dir = module_chdir;
                    802:        }
1.1.1.2   misho     803:        set_env_str("RSYNC_MODULE_PATH", full_module_path);
1.1       misho     804: 
                    805:        if (module_dirlen == 1) {
                    806:                module_dirlen = 0;
                    807:                set_filter_dir("/", 1);
                    808:        } else
                    809:                set_filter_dir(module_dir, module_dirlen);
                    810: 
1.1.1.4 ! misho     811:        p = lp_filter(module_id);
1.1.1.2   misho     812:        parse_filter_str(&daemon_filter_list, p, rule_template(FILTRULE_WORD_SPLIT),
1.1.1.4 ! misho     813:                XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3);
1.1       misho     814: 
1.1.1.4 ! misho     815:        p = lp_include_from(module_id);
1.1.1.2   misho     816:        parse_filter_file(&daemon_filter_list, p, rule_template(FILTRULE_INCLUDE),
1.1.1.4 ! misho     817:                XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
1.1       misho     818: 
1.1.1.4 ! misho     819:        p = lp_include(module_id);
1.1.1.2   misho     820:        parse_filter_str(&daemon_filter_list, p,
1.1.1.4 ! misho     821:                rule_template(FILTRULE_INCLUDE | FILTRULE_WORD_SPLIT),
        !           822:                XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES);
1.1       misho     823: 
1.1.1.4 ! misho     824:        p = lp_exclude_from(module_id);
1.1.1.2   misho     825:        parse_filter_file(&daemon_filter_list, p, rule_template(0),
1.1.1.4 ! misho     826:                XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
1.1       misho     827: 
1.1.1.4 ! misho     828:        p = lp_exclude(module_id);
1.1.1.2   misho     829:        parse_filter_str(&daemon_filter_list, p, rule_template(FILTRULE_WORD_SPLIT),
1.1.1.4 ! misho     830:                XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES);
1.1       misho     831: 
                    832:        log_init(1);
                    833: 
1.1.1.4 ! misho     834:        if (*lp_db_config(i)) {
        !           835:                db_read_config(FLOG, lp_db_config(i));
        !           836:                db_lax = lp_db_lax(i);
        !           837:        }
        !           838: 
1.1       misho     839: #ifdef HAVE_PUTENV
1.1.1.4 ! misho     840:        if ((*lp_early_exec(module_id) || *lp_prexfer_exec(module_id)
        !           841:          || *lp_postxfer_exec(module_id) || *lp_name_converter(module_id))
        !           842:         && !getenv("RSYNC_NO_XFER_EXEC")) {
        !           843:                set_env_num("RSYNC_PID", (long)getpid());
1.1       misho     844: 
                    845:                /* For post-xfer exec, fork a new process to run the rsync
                    846:                 * daemon while this process waits for the exit status and
                    847:                 * runs the indicated command at that point. */
1.1.1.4 ! misho     848:                if (*lp_postxfer_exec(module_id)) {
1.1       misho     849:                        pid_t pid = fork();
                    850:                        if (pid < 0) {
                    851:                                rsyserr(FLOG, errno, "fork failed");
                    852:                                io_printf(f_out, "@ERROR: fork failed\n");
                    853:                                return -1;
                    854:                        }
                    855:                        if (pid) {
1.1.1.4 ! misho     856:                                int status;
1.1.1.2   misho     857:                                close(f_in);
                    858:                                if (f_out != f_in)
                    859:                                        close(f_out);
1.1       misho     860:                                if (wait_process(pid, &status, 0) < 0)
                    861:                                        status = -1;
1.1.1.2   misho     862:                                set_env_num("RSYNC_RAW_STATUS", status);
1.1       misho     863:                                if (WIFEXITED(status))
                    864:                                        status = WEXITSTATUS(status);
                    865:                                else
                    866:                                        status = -1;
1.1.1.2   misho     867:                                set_env_num("RSYNC_EXIT_STATUS", status);
1.1.1.4 ! misho     868:                                if (shell_exec(lp_postxfer_exec(module_id)) < 0)
1.1       misho     869:                                        status = -1;
                    870:                                _exit(status);
                    871:                        }
                    872:                }
1.1.1.4 ! misho     873: 
        !           874:                /* For early exec, fork a child process to run the indicated
        !           875:                 * command and wait for it to exit. */
        !           876:                if (*lp_early_exec(module_id)) {
        !           877:                        int arg_fd;
        !           878:                        pid_t pid = start_pre_exec(lp_early_exec(module_id), &arg_fd, NULL);
        !           879:                        if (pid == (pid_t)-1) {
        !           880:                                rsyserr(FLOG, errno, "early exec preparation failed");
        !           881:                                io_printf(f_out, "@ERROR: early exec preparation failed\n");
        !           882:                                return -1;
        !           883:                        }
        !           884:                        write_pre_exec_args(arg_fd, NULL, NULL, NULL, 1);
        !           885:                        if (finish_pre_exec("early exec", pid, -1) != NULL) {
        !           886:                                rsyserr(FLOG, errno, "early exec failed");
        !           887:                                io_printf(f_out, "@ERROR: early exec failed\n");
        !           888:                                return -1;
        !           889:                        }
        !           890:                }
        !           891: 
1.1       misho     892:                /* For pre-xfer exec, fork a child process to run the indicated
                    893:                 * command, though it first waits for the parent process to
                    894:                 * send us the user's request via a pipe. */
1.1.1.4 ! misho     895:                if (*lp_prexfer_exec(module_id)) {
        !           896:                        pre_exec_pid = start_pre_exec(lp_prexfer_exec(module_id), &pre_exec_arg_fd, &pre_exec_error_fd);
        !           897:                        if (pre_exec_pid == (pid_t)-1) {
1.1       misho     898:                                rsyserr(FLOG, errno, "pre-xfer exec preparation failed");
                    899:                                io_printf(f_out, "@ERROR: pre-xfer exec preparation failed\n");
                    900:                                return -1;
                    901:                        }
1.1.1.4 ! misho     902:                }
        !           903: 
        !           904:                if (*lp_name_converter(module_id)) {
        !           905:                        namecvt_pid = start_pre_exec(lp_name_converter(module_id), &namecvt_fd_req, &namecvt_fd_ans);
        !           906:                        if (namecvt_pid == (pid_t)-1) {
        !           907:                                rsyserr(FLOG, errno, "name-converter exec preparation failed");
        !           908:                                io_printf(f_out, "@ERROR: name-converter exec preparation failed\n");
        !           909:                                return -1;
1.1       misho     910:                        }
                    911:                }
                    912:        }
                    913: #endif
                    914: 
1.1.1.4 ! misho     915:        if (early_input) {
        !           916:                free(early_input);
        !           917:                early_input = NULL;
        !           918:        }
        !           919: 
1.1       misho     920:        if (use_chroot) {
                    921:                /*
                    922:                 * XXX: The 'use chroot' flag is a fairly reliable
                    923:                 * source of confusion, because it fails under two
                    924:                 * important circumstances: running as non-root,
                    925:                 * running on Win32 (or possibly others).  On the
                    926:                 * other hand, if you are running as root, then it
                    927:                 * might be better to always use chroot.
                    928:                 *
                    929:                 * So, perhaps if we can't chroot we should just issue
                    930:                 * a warning, unless a "require chroot" flag is set,
                    931:                 * in which case we fail.
                    932:                 */
                    933:                if (chroot(module_chdir)) {
                    934:                        rsyserr(FLOG, errno, "chroot %s failed", module_chdir);
                    935:                        io_printf(f_out, "@ERROR: chroot failed\n");
                    936:                        return -1;
                    937:                }
                    938:                module_chdir = module_dir;
                    939:        }
                    940: 
                    941:        if (!change_dir(module_chdir, CD_NORMAL))
                    942:                return path_failure(f_out, module_chdir, True);
1.1.1.4 ! misho     943:        if (module_dirlen || (!use_chroot && !*lp_daemon_chroot()))
1.1       misho     944:                sanitize_paths = 1;
                    945: 
1.1.1.4 ! misho     946:        if ((munge_symlinks = lp_munge_symlinks(module_id)) < 0)
1.1       misho     947:                munge_symlinks = !use_chroot || module_dirlen;
                    948:        if (munge_symlinks) {
                    949:                STRUCT_STAT st;
1.1.1.2   misho     950:                char prefix[SYMLINK_PREFIX_LEN]; /* NOT +1 ! */
                    951:                strlcpy(prefix, SYMLINK_PREFIX, sizeof prefix); /* trim the trailing slash */
                    952:                if (do_stat(prefix, &st) == 0 && S_ISDIR(st.st_mode)) {
                    953:                        rprintf(FLOG, "Symlink munging is unsafe when a %s directory exists.\n",
                    954:                                prefix);
1.1       misho     955:                        io_printf(f_out, "@ERROR: daemon security issue -- contact admin\n", name);
                    956:                        exit_cleanup(RERR_UNSUPPORTED);
                    957:                }
                    958:        }
                    959: 
1.1.1.3   misho     960:        if (gid_list.count) {
                    961:                gid_t *gid_array = gid_list.items;
                    962:                if (setgid(gid_array[0])) {
                    963:                        rsyserr(FLOG, errno, "setgid %ld failed", (long)gid_array[0]);
1.1       misho     964:                        io_printf(f_out, "@ERROR: setgid failed\n");
                    965:                        return -1;
                    966:                }
                    967: #ifdef HAVE_SETGROUPS
1.1.1.2   misho     968:                /* Set the group(s) we want to be active. */
1.1.1.3   misho     969:                if (setgroups(gid_list.count, gid_array)) {
1.1       misho     970:                        rsyserr(FLOG, errno, "setgroups failed");
                    971:                        io_printf(f_out, "@ERROR: setgroups failed\n");
                    972:                        return -1;
                    973:                }
                    974: #endif
1.1.1.2   misho     975: #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
                    976:                /* pw is set if the user wants all the user's groups. */
                    977:                if (pw && initgroups(pw->pw_name, pw->pw_gid) < 0) {
                    978:                        rsyserr(FLOG, errno, "initgroups failed");
                    979:                        io_printf(f_out, "@ERROR: initgroups failed\n");
                    980:                        return -1;
                    981:                }
                    982: #endif
1.1.1.4 ! misho     983:                our_gid = MY_GID();
1.1.1.2   misho     984:        }
1.1       misho     985: 
1.1.1.2   misho     986:        if (set_uid) {
1.1       misho     987:                if (setuid(uid) < 0
                    988: #ifdef HAVE_SETEUID
                    989:                 || seteuid(uid) < 0
                    990: #endif
                    991:                ) {
1.1.1.2   misho     992:                        rsyserr(FLOG, errno, "setuid %ld failed", (long)uid);
1.1       misho     993:                        io_printf(f_out, "@ERROR: setuid failed\n");
                    994:                        return -1;
                    995:                }
                    996: 
1.1.1.4 ! misho     997:                our_uid = MY_UID();
        !           998:                am_root = (our_uid == ROOT_UID);
1.1       misho     999:        }
                   1000: 
1.1.1.4 ! misho    1001:        if (lp_temp_dir(module_id) && *lp_temp_dir(module_id)) {
        !          1002:                tmpdir = lp_temp_dir(module_id);
1.1       misho    1003:                if (strlen(tmpdir) >= MAXPATHLEN - 10) {
                   1004:                        rprintf(FLOG,
                   1005:                                "the 'temp dir' value for %s is WAY too long -- ignoring.\n",
                   1006:                                name);
                   1007:                        tmpdir = NULL;
                   1008:                }
                   1009:        }
                   1010: 
                   1011:        io_printf(f_out, "@RSYNCD: OK\n");
                   1012: 
                   1013:        read_args(f_in, name, line, sizeof line, rl_nulls, &argv, &argc, &request);
                   1014:        orig_argv = argv;
                   1015: 
1.1.1.2   misho    1016:        save_munge_symlinks = munge_symlinks;
                   1017: 
                   1018:        reset_output_levels(); /* future verbosity is controlled by client options */
1.1       misho    1019:        ret = parse_arguments(&argc, (const char ***) &argv);
                   1020:        if (protect_args && ret) {
                   1021:                orig_early_argv = orig_argv;
                   1022:                protect_args = 2;
                   1023:                read_args(f_in, name, line, sizeof line, 1, &argv, &argc, &request);
                   1024:                orig_argv = argv;
                   1025:                ret = parse_arguments(&argc, (const char ***) &argv);
                   1026:        } else
                   1027:                orig_early_argv = NULL;
                   1028: 
1.1.1.4 ! misho    1029:        /* The default is to use the user's setting unless the module sets True or False. */
        !          1030:        if (lp_open_noatime(module_id) >= 0)
        !          1031:                open_noatime = lp_open_noatime(module_id);
        !          1032: 
1.1.1.2   misho    1033:        munge_symlinks = save_munge_symlinks; /* The client mustn't control this. */
                   1034: 
1.1.1.4 ! misho    1035:        if (am_daemon > 0)
        !          1036:                msgs2stderr = 0; /* A non-rsh-run daemon doesn't have stderr for msgs. */
        !          1037: 
1.1       misho    1038:        if (pre_exec_pid) {
1.1.1.4 ! misho    1039:                write_pre_exec_args(pre_exec_arg_fd, request, orig_early_argv, orig_argv, 0);
        !          1040:                err_msg = finish_pre_exec("pre-xfer exec", pre_exec_pid, pre_exec_error_fd);
1.1       misho    1041:        }
                   1042: 
1.1.1.4 ! misho    1043:        if (namecvt_pid)
        !          1044:                write_pre_exec_args(namecvt_fd_req, request, orig_early_argv, orig_argv, 2);
        !          1045: 
1.1       misho    1046:        if (orig_early_argv)
                   1047:                free(orig_early_argv);
                   1048: 
                   1049:        am_server = 1; /* Don't let someone try to be tricky. */
                   1050:        quiet = 0;
1.1.1.4 ! misho    1051:        db_config = NULL;
        !          1052: 
1.1       misho    1053:        if (lp_ignore_errors(module_id))
                   1054:                ignore_errors = 1;
                   1055:        if (write_batch < 0)
                   1056:                dry_run = 1;
                   1057: 
1.1.1.4 ! misho    1058:        if (lp_fake_super(module_id)) {
1.1       misho    1059:                if (preserve_xattrs > 1)
                   1060:                        preserve_xattrs = 1;
                   1061:                am_root = -1;
                   1062:        } else if (am_root < 0) /* Treat --fake-super from client as --super. */
                   1063:                am_root = 2;
                   1064: 
1.1.1.4 ! misho    1065:        checksum_files = always_checksum ? lp_checksum_files(i)
        !          1066:                                         : CSF_IGNORE_FILES;
        !          1067: 
1.1       misho    1068:        if (filesfrom_fd == 0)
                   1069:                filesfrom_fd = f_in;
                   1070: 
                   1071:        if (request) {
                   1072:                if (*auth_user) {
                   1073:                        rprintf(FLOG, "rsync %s %s from %s@%s (%s)\n",
                   1074:                                am_sender ? "on" : "to",
                   1075:                                request, auth_user, host, addr);
                   1076:                } else {
                   1077:                        rprintf(FLOG, "rsync %s %s from %s (%s)\n",
                   1078:                                am_sender ? "on" : "to",
                   1079:                                request, host, addr);
                   1080:                }
                   1081:                free(request);
                   1082:        }
                   1083: 
                   1084: #ifndef DEBUG
                   1085:        /* don't allow the logs to be flooded too fast */
1.1.1.4 ! misho    1086:        limit_output_verbosity(lp_max_verbosity(module_id));
1.1       misho    1087: #endif
                   1088: 
1.1.1.4 ! misho    1089:        if (protocol_version < 23 && (protocol_version == 22 || am_sender))
1.1.1.2   misho    1090:                io_start_multiplex_out(f_out);
1.1       misho    1091:        else if (!ret || err_msg) {
                   1092:                /* We have to get I/O multiplexing started so that we can
                   1093:                 * get the error back to the client.  This means getting
                   1094:                 * the protocol setup finished first in later versions. */
                   1095:                setup_protocol(f_out, f_in);
                   1096:                if (!am_sender) {
                   1097:                        /* Since we failed in our option parsing, we may not
                   1098:                         * have finished parsing that the client sent us a
                   1099:                         * --files-from option, so look for it manually.
                   1100:                         * Without this, the socket would be in the wrong
                   1101:                         * state for the upcoming error message. */
                   1102:                        if (!files_from) {
                   1103:                                int i;
                   1104:                                for (i = 0; i < argc; i++) {
                   1105:                                        if (strncmp(argv[i], "--files-from", 12) == 0) {
                   1106:                                                files_from = "";
                   1107:                                                break;
                   1108:                                        }
                   1109:                                }
                   1110:                        }
                   1111:                        if (files_from)
                   1112:                                write_byte(f_out, 0);
                   1113:                }
1.1.1.2   misho    1114:                io_start_multiplex_out(f_out);
1.1       misho    1115:        }
                   1116: 
                   1117:        if (!ret || err_msg) {
1.1.1.2   misho    1118:                if (err_msg) {
                   1119:                        while ((p = strchr(err_msg, '\n')) != NULL) {
                   1120:                                int len = p - err_msg + 1;
                   1121:                                rwrite(FERROR, err_msg, len, 0);
                   1122:                                err_msg += len;
                   1123:                        }
                   1124:                        if (*err_msg)
                   1125:                                rprintf(FERROR, "%s\n", err_msg);
1.1.1.4 ! misho    1126:                        io_flush(MSG_FLUSH);
1.1.1.2   misho    1127:                } else
1.1       misho    1128:                        option_error();
                   1129:                msleep(400);
                   1130:                exit_cleanup(RERR_UNSUPPORTED);
                   1131:        }
                   1132: 
                   1133: #ifdef ICONV_OPTION
                   1134:        if (!iconv_opt) {
                   1135:                if (ic_send != (iconv_t)-1) {
                   1136:                        iconv_close(ic_send);
                   1137:                        ic_send = (iconv_t)-1;
                   1138:                }
                   1139:                if (ic_recv != (iconv_t)-1) {
                   1140:                        iconv_close(ic_recv);
                   1141:                        ic_recv = (iconv_t)-1;
                   1142:                }
                   1143:        }
                   1144: #endif
                   1145: 
                   1146:        if (!numeric_ids
1.1.1.4 ! misho    1147:         && (use_chroot ? lp_numeric_ids(module_id) != False && !*lp_name_converter(module_id)
        !          1148:                        : lp_numeric_ids(module_id) == True))
1.1       misho    1149:                numeric_ids = -1; /* Set --numeric-ids w/o breaking protocol. */
                   1150: 
1.1.1.4 ! misho    1151:        if (lp_timeout(module_id) && (!io_timeout || lp_timeout(module_id) < io_timeout))
        !          1152:                set_io_timeout(lp_timeout(module_id));
1.1       misho    1153: 
                   1154:        /* If we have some incoming/outgoing chmod changes, append them to
                   1155:         * any user-specified changes (making our changes have priority).
                   1156:         * We also get a pointer to just our changes so that a receiver
                   1157:         * process can use them separately if --perms wasn't specified. */
                   1158:        if (am_sender)
1.1.1.4 ! misho    1159:                p = lp_outgoing_chmod(module_id);
1.1       misho    1160:        else
1.1.1.4 ! misho    1161:                p = lp_incoming_chmod(module_id);
1.1       misho    1162:        if (*p && !(daemon_chmod_modes = parse_chmod(p, &chmod_modes))) {
                   1163:                rprintf(FLOG, "Invalid \"%sing chmod\" directive: %s\n",
                   1164:                        am_sender ? "outgo" : "incom", p);
                   1165:        }
                   1166: 
                   1167:        start_server(f_in, f_out, argc, argv);
                   1168: 
                   1169:        return 0;
                   1170: }
                   1171: 
1.1.1.4 ! misho    1172: BOOL namecvt_call(const char *cmd, const char **name_p, id_t *id_p)
        !          1173: {
        !          1174:        char buf[1024];
        !          1175:        int got, len;
        !          1176: 
        !          1177:        if (*name_p)
        !          1178:                len = snprintf(buf, sizeof buf, "%s %s\n", cmd, *name_p);
        !          1179:        else
        !          1180:                len = snprintf(buf, sizeof buf, "%s %ld\n", cmd, (long)*id_p);
        !          1181:        if (len >= (int)sizeof buf) {
        !          1182:                rprintf(FERROR, "namecvt_call() request was too large.\n");
        !          1183:                exit_cleanup(RERR_UNSUPPORTED);
        !          1184:        }
        !          1185: 
        !          1186:        while ((got = write(namecvt_fd_req, buf, len)) != len) {
        !          1187:                if (got < 0 && errno == EINTR)
        !          1188:                        continue;
        !          1189:                rprintf(FERROR, "Connection to name-converter failed.\n");
        !          1190:                exit_cleanup(RERR_SOCKETIO);
        !          1191:        }
        !          1192: 
        !          1193:        if (!read_line_old(namecvt_fd_ans, buf, sizeof buf, 0))
        !          1194:                return False;
        !          1195: 
        !          1196:        if (*name_p)
        !          1197:                *id_p = (id_t)atol(buf);
        !          1198:        else
        !          1199:                *name_p = strdup(buf);
        !          1200: 
        !          1201:        return True;
        !          1202: }
        !          1203: 
1.1       misho    1204: /* send a list of available modules to the client. Don't list those
                   1205:    with "list = False". */
                   1206: static void send_listing(int fd)
                   1207: {
1.1.1.2   misho    1208:        int n = lp_num_modules();
1.1       misho    1209:        int i;
                   1210: 
                   1211:        for (i = 0; i < n; i++) {
                   1212:                if (lp_list(i))
                   1213:                        io_printf(fd, "%-15s\t%s\n", lp_name(i), lp_comment(i));
                   1214:        }
                   1215: 
                   1216:        if (protocol_version >= 25)
                   1217:                io_printf(fd,"@RSYNCD: EXIT\n");
                   1218: }
                   1219: 
                   1220: static int load_config(int globals_only)
                   1221: {
                   1222:        if (!config_file) {
1.1.1.4 ! misho    1223:                if (am_daemon < 0 && am_root <= 0)
1.1       misho    1224:                        config_file = RSYNCD_USERCONF;
                   1225:                else
                   1226:                        config_file = RSYNCD_SYSCONF;
                   1227:        }
                   1228:        return lp_load(config_file, globals_only);
                   1229: }
                   1230: 
                   1231: /* this is called when a connection is established to a client
                   1232:    and we want to start talking. The setup of the system is done from
                   1233:    here */
                   1234: int start_daemon(int f_in, int f_out)
                   1235: {
                   1236:        char line[1024];
1.1.1.2   misho    1237:        const char *addr, *host;
1.1.1.4 ! misho    1238:        char *p;
1.1       misho    1239:        int i;
                   1240: 
1.1.1.4 ! misho    1241:        /* At this point, am_server is only set for a daemon started via rsh.
        !          1242:         * Because am_server gets forced on soon, we'll set am_daemon to -1 as
        !          1243:         * a flag that can be checked later on to distinguish a normal daemon
        !          1244:         * from an rsh-run daemon. */
        !          1245:        if (am_server)
        !          1246:                am_daemon = -1;
        !          1247: 
1.1       misho    1248:        io_set_sock_fds(f_in, f_out);
                   1249: 
                   1250:        /* We must load the config file before calling any function that
                   1251:         * might cause log-file output to occur.  This ensures that the
                   1252:         * "log file" param gets honored for the 2 non-forked use-cases
                   1253:         * (when rsync is run by init and run by a remote shell). */
                   1254:        if (!load_config(0))
                   1255:                exit_cleanup(RERR_SYNTAX);
                   1256: 
1.1.1.4 ! misho    1257:        if (lp_proxy_protocol() && !read_proxy_protocol_header(f_in))
        !          1258:                return -1;
        !          1259: 
        !          1260:        p = lp_daemon_chroot();
        !          1261:        if (*p) {
        !          1262:                log_init(0); /* Make use we've initialized syslog before chrooting. */
        !          1263:                if (chroot(p) < 0 || chdir("/") < 0) {
        !          1264:                        rsyserr(FLOG, errno, "daemon chroot %s failed", p);
        !          1265:                        return -1;
        !          1266:                }
        !          1267:        }
        !          1268:        p = lp_daemon_gid();
        !          1269:        if (*p) {
        !          1270:                gid_t gid;
        !          1271:                if (!group_to_gid(p, &gid, True)) {
        !          1272:                        rprintf(FLOG, "Invalid daemon gid: %s\n", p);
        !          1273:                        return -1;
        !          1274:                }
        !          1275:                if (setgid(gid) < 0) {
        !          1276:                        rsyserr(FLOG, errno, "Unable to set group to daemon gid %ld", (long)gid);
        !          1277:                        return -1;
        !          1278:                }
        !          1279:                our_gid = MY_GID();
        !          1280:        }
        !          1281:        p = lp_daemon_uid();
        !          1282:        if (*p) {
        !          1283:                uid_t uid;
        !          1284:                if (!user_to_uid(p, &uid, True)) {
        !          1285:                        rprintf(FLOG, "Invalid daemon uid: %s\n", p);
        !          1286:                        return -1;
        !          1287:                }
        !          1288:                if (setuid(uid) < 0) {
        !          1289:                        rsyserr(FLOG, errno, "Unable to set user to daemon uid %ld", (long)uid);
        !          1290:                        return -1;
        !          1291:                }
        !          1292:                our_uid = MY_UID();
        !          1293:                am_root = (our_uid == ROOT_UID);
        !          1294:        }
        !          1295: 
1.1       misho    1296:        addr = client_addr(f_in);
1.1.1.4 ! misho    1297:        host = lp_reverse_lookup(-1) ? client_name(addr) : undetermined_hostname;
1.1       misho    1298:        rprintf(FLOG, "connect from %s (%s)\n", host, addr);
                   1299: 
1.1.1.4 ! misho    1300:        if (am_daemon > 0) {
1.1       misho    1301:                set_socket_options(f_in, "SO_KEEPALIVE");
                   1302:                set_nonblocking(f_in);
                   1303:        }
                   1304: 
                   1305:        if (exchange_protocols(f_in, f_out, line, sizeof line, 0) < 0)
                   1306:                return -1;
                   1307: 
                   1308:        line[0] = 0;
1.1.1.2   misho    1309:        if (!read_line_old(f_in, line, sizeof line, 0))
1.1       misho    1310:                return -1;
                   1311: 
1.1.1.4 ! misho    1312:        if (strncmp(line, EARLY_INPUT_CMD, EARLY_INPUT_CMDLEN) == 0) {
        !          1313:                early_input_len = strtol(line + EARLY_INPUT_CMDLEN, NULL, 10);
        !          1314:                if (early_input_len <= 0 || early_input_len > BIGPATHBUFLEN) {
        !          1315:                        io_printf(f_out, "@ERROR: invalid early_input length\n");
        !          1316:                        return -1;
        !          1317:                }
        !          1318:                early_input = new_array(char, early_input_len);
        !          1319:                read_buf(f_in, early_input, early_input_len);
        !          1320: 
        !          1321:                if (!read_line_old(f_in, line, sizeof line, 0))
        !          1322:                        return -1;
        !          1323:        }
        !          1324: 
1.1       misho    1325:        if (!*line || strcmp(line, "#list") == 0) {
                   1326:                rprintf(FLOG, "module-list request from %s (%s)\n",
                   1327:                        host, addr);
                   1328:                send_listing(f_out);
                   1329:                return -1;
                   1330:        }
                   1331: 
                   1332:        if (*line == '#') {
                   1333:                /* it's some sort of command that I don't understand */
                   1334:                io_printf(f_out, "@ERROR: Unknown command '%s'\n", line);
                   1335:                return -1;
                   1336:        }
                   1337: 
                   1338:        if ((i = lp_number(line)) < 0) {
                   1339:                rprintf(FLOG, "unknown module '%s' tried from %s (%s)\n",
                   1340:                        line, host, addr);
                   1341:                io_printf(f_out, "@ERROR: Unknown module '%s'\n", line);
                   1342:                return -1;
                   1343:        }
                   1344: 
                   1345: #ifdef HAVE_SIGACTION
                   1346:        sigact.sa_flags = SA_NOCLDSTOP;
                   1347: #endif
                   1348:        SIGACTION(SIGCHLD, remember_children);
                   1349: 
                   1350:        return rsync_module(f_in, f_out, i, addr, host);
                   1351: }
                   1352: 
                   1353: static void create_pid_file(void)
                   1354: {
                   1355:        char *pid_file = lp_pid_file();
1.1.1.4 ! misho    1356:        char pidbuf[32];
        !          1357:        STRUCT_STAT st1, st2;
        !          1358:        char *fail = NULL;
1.1       misho    1359: 
                   1360:        if (!pid_file || !*pid_file)
                   1361:                return;
                   1362: 
1.1.1.4 ! misho    1363: #ifdef O_NOFOLLOW
        !          1364: #define SAFE_OPEN_FLAGS (O_CREAT|O_NOFOLLOW)
        !          1365: #else
        !          1366: #define SAFE_OPEN_FLAGS (O_CREAT)
        !          1367: #endif
        !          1368: 
        !          1369:        /* These tests make sure that a temp-style lock dir is handled safely. */
        !          1370:        st1.st_mode = 0;
        !          1371:        if (do_lstat(pid_file, &st1) == 0 && !S_ISREG(st1.st_mode) && unlink(pid_file) < 0)
        !          1372:                fail = "unlink";
        !          1373:        else if ((pid_file_fd = do_open(pid_file, O_RDWR|SAFE_OPEN_FLAGS, 0664)) < 0)
        !          1374:                fail = S_ISREG(st1.st_mode) ? "open" : "create";
        !          1375:        else if (!lock_range(pid_file_fd, 0, 4))
        !          1376:                fail = "lock";
        !          1377:        else if (do_fstat(pid_file_fd, &st1) < 0)
        !          1378:                fail = "fstat opened";
        !          1379:        else if (st1.st_size > (int)sizeof pidbuf)
        !          1380:                fail = "find small";
        !          1381:        else if (do_lstat(pid_file, &st2) < 0)
        !          1382:                fail = "lstat";
        !          1383:        else if (!S_ISREG(st1.st_mode))
        !          1384:                fail = "avoid file overwrite race for";
        !          1385:        else if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
        !          1386:                fail = "verify stat info for";
        !          1387: #ifdef HAVE_FTRUNCATE
        !          1388:        else if (do_ftruncate(pid_file_fd, 0) < 0)
        !          1389:                fail = "truncate";
        !          1390: #endif
        !          1391:        else {
        !          1392:                pid_t pid = getpid();
        !          1393:                int len = snprintf(pidbuf, sizeof pidbuf, "%d\n", (int)pid);
        !          1394: #ifndef HAVE_FTRUNCATE
        !          1395:                /* What can we do with a too-long file and no truncate? I guess we'll add extra newlines. */
        !          1396:                while (len < st1.st_size) /* We already verified that st_size chars fits in the buffer. */
        !          1397:                        pidbuf[len++] = '\n';
        !          1398:                /* We don't need the buffer to end in a '\0' (and we may not have room to add it). */
        !          1399: #endif
        !          1400:                if (write(pid_file_fd, pidbuf, len) != len)
        !          1401:                         fail = "write";
        !          1402:                cleanup_set_pid(pid); /* Mark the file for removal on exit, even if the write failed. */
        !          1403:        }
        !          1404: 
        !          1405:        if (fail) {
        !          1406:                char msg[1024];
        !          1407:                snprintf(msg, sizeof msg, "failed to %s pid file %s: %s\n",
        !          1408:                        fail, pid_file, strerror(errno));
        !          1409:                fputs(msg, stderr);
        !          1410:                rprintf(FLOG, "%s", msg);
1.1       misho    1411:                exit_cleanup(RERR_FILEIO);
                   1412:        }
1.1.1.4 ! misho    1413: 
        !          1414:        /* The file is left open so that the lock remains valid. It is closed in our forked child procs. */
1.1       misho    1415: }
                   1416: 
                   1417: /* Become a daemon, discarding the controlling terminal. */
                   1418: static void become_daemon(void)
                   1419: {
                   1420:        int i;
                   1421:        pid_t pid = fork();
                   1422: 
                   1423:        if (pid) {
                   1424:                if (pid < 0) {
                   1425:                        fprintf(stderr, "failed to fork: %s\n", strerror(errno));
                   1426:                        exit_cleanup(RERR_FILEIO);
                   1427:                }
                   1428:                _exit(0);
                   1429:        }
                   1430: 
                   1431:        create_pid_file();
                   1432: 
                   1433:        /* detach from the terminal */
                   1434: #ifdef HAVE_SETSID
                   1435:        setsid();
                   1436: #elif defined TIOCNOTTY
                   1437:        i = open("/dev/tty", O_RDWR);
                   1438:        if (i >= 0) {
                   1439:                ioctl(i, (int)TIOCNOTTY, (char *)0);
                   1440:                close(i);
                   1441:        }
                   1442: #endif
                   1443:        /* make sure that stdin, stdout an stderr don't stuff things
                   1444:         * up (library functions, for example) */
                   1445:        for (i = 0; i < 3; i++) {
                   1446:                close(i);
                   1447:                open("/dev/null", O_RDWR);
                   1448:        }
                   1449: }
                   1450: 
                   1451: int daemon_main(void)
                   1452: {
                   1453:        if (is_a_socket(STDIN_FILENO)) {
                   1454:                int i;
                   1455: 
                   1456:                /* we are running via inetd - close off stdout and
                   1457:                 * stderr so that library functions (and getopt) don't
                   1458:                 * try to use them. Redirect them to /dev/null */
                   1459:                for (i = 1; i < 3; i++) {
                   1460:                        close(i);
                   1461:                        open("/dev/null", O_RDWR);
                   1462:                }
                   1463: 
                   1464:                return start_daemon(STDIN_FILENO, STDIN_FILENO);
                   1465:        }
                   1466: 
                   1467:        if (!load_config(1)) {
                   1468:                fprintf(stderr, "Failed to parse config file: %s\n", config_file);
                   1469:                exit_cleanup(RERR_SYNTAX);
                   1470:        }
1.1.1.2   misho    1471:        set_dparams(0);
1.1       misho    1472: 
                   1473:        if (no_detach)
                   1474:                create_pid_file();
                   1475:        else
                   1476:                become_daemon();
                   1477: 
                   1478:        if (rsync_port == 0 && (rsync_port = lp_rsync_port()) == 0)
                   1479:                rsync_port = RSYNC_PORT;
                   1480:        if (bind_address == NULL && *lp_bind_address())
                   1481:                bind_address = lp_bind_address();
                   1482: 
                   1483:        log_init(0);
                   1484: 
                   1485:        rprintf(FLOG, "rsyncd version %s starting, listening on port %d\n",
1.1.1.4 ! misho    1486:                rsync_version(), rsync_port);
1.1       misho    1487:        /* TODO: If listening on a particular address, then show that
                   1488:         * address too.  In fact, why not just do getnameinfo on the
                   1489:         * local address??? */
                   1490: 
1.1.1.4 ! misho    1491: #ifdef HAVE_LIBSLP
        !          1492:        if (lp_use_slp() && register_services()) {
        !          1493:                rprintf(FINFO,
        !          1494:                    "Couldn't register with service discovery protocol, continuing anyway\n");
        !          1495:        }
        !          1496: #endif
        !          1497: 
1.1       misho    1498:        start_accept_loop(rsync_port, start_daemon);
                   1499:        return -1;
                   1500: }

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>