[BACK]Return to sftp-server.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ssh

Annotation of src/usr.bin/ssh/sftp-server.c, Revision 1.136

1.136   ! djm         1: /* $OpenBSD: sftp-server.c,v 1.135 2022/01/01 01:55:30 jsg Exp $ */
1.1       markus      2: /*
1.45      markus      3:  * Copyright (c) 2000-2004 Markus Friedl.  All rights reserved.
1.1       markus      4:  *
1.45      markus      5:  * Permission to use, copy, modify, and distribute this software for any
                      6:  * purpose with or without fee is hereby granted, provided that the above
                      7:  * copyright notice and this permission notice appear in all copies.
1.1       markus      8:  *
1.45      markus      9:  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
                     10:  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
                     11:  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
                     12:  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
                     13:  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
                     14:  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
                     15:  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1.1       markus     16:  */
1.52      stevesk    17:
                     18: #include <sys/types.h>
1.122     djm        19: #include <sys/resource.h>
1.52      stevesk    20: #include <sys/stat.h>
1.66      stevesk    21: #include <sys/time.h>
1.79      djm        22: #include <sys/mount.h>
                     23: #include <sys/statvfs.h>
1.51      stevesk    24:
                     25: #include <dirent.h>
1.62      stevesk    26: #include <errno.h>
1.59      stevesk    27: #include <fcntl.h>
1.132     deraadt    28: #include <poll.h>
1.68      stevesk    29: #include <stdlib.h>
1.69      stevesk    30: #include <stdio.h>
1.65      stevesk    31: #include <string.h>
1.70      deraadt    32: #include <pwd.h>
1.64      stevesk    33: #include <time.h>
1.63      stevesk    34: #include <unistd.h>
1.70      deraadt    35: #include <stdarg.h>
1.1       markus     36:
1.70      deraadt    37: #include "xmalloc.h"
1.104     djm        38: #include "sshbuf.h"
                     39: #include "ssherr.h"
1.14      markus     40: #include "log.h"
1.49      djm        41: #include "misc.h"
1.98      djm        42: #include "match.h"
1.58      djm        43: #include "uidswap.h"
1.1       markus     44:
1.10      markus     45: #include "sftp.h"
1.15      djm        46: #include "sftp-common.h"
1.1       markus     47:
1.117     djm        48: char *sftp_realpath(const char *, char *); /* sftp-realpath.c */
                     49:
1.122     djm        50: /* Maximum data read that we are willing to accept */
1.124     djm        51: #define SFTP_MAX_READ_LENGTH (SFTP_MAX_MSG_LENGTH - 1024)
1.122     djm        52:
1.58      djm        53: /* Our verbosity */
1.98      djm        54: static LogLevel log_level = SYSLOG_LEVEL_ERROR;
1.58      djm        55:
                     56: /* Our client */
1.98      djm        57: static struct passwd *pw = NULL;
                     58: static char *client_addr = NULL;
1.1       markus     59:
                     60: /* input and output queue */
1.104     djm        61: struct sshbuf *iqueue;
                     62: struct sshbuf *oqueue;
1.1       markus     63:
1.23      djm        64: /* Version of client */
1.98      djm        65: static u_int version;
                     66:
                     67: /* SSH2_FXP_INIT received */
                     68: static int init_done;
1.23      djm        69:
1.90      djm        70: /* Disable writes */
1.98      djm        71: static int readonly;
                     72:
                     73: /* Requests that are allowed/denied */
1.118     djm        74: static char *request_allowlist, *request_denylist;
1.90      djm        75:
1.43      miod       76: /* portable attributes, etc. */
1.1       markus     77: typedef struct Stat Stat;
                     78:
1.15      djm        79: struct Stat {
1.1       markus     80:        char *name;
                     81:        char *long_name;
                     82:        Attrib attrib;
                     83: };
                     84:
1.98      djm        85: /* Packet handlers */
                     86: static void process_open(u_int32_t id);
                     87: static void process_close(u_int32_t id);
                     88: static void process_read(u_int32_t id);
                     89: static void process_write(u_int32_t id);
                     90: static void process_stat(u_int32_t id);
                     91: static void process_lstat(u_int32_t id);
                     92: static void process_fstat(u_int32_t id);
                     93: static void process_setstat(u_int32_t id);
                     94: static void process_fsetstat(u_int32_t id);
                     95: static void process_opendir(u_int32_t id);
                     96: static void process_readdir(u_int32_t id);
                     97: static void process_remove(u_int32_t id);
                     98: static void process_mkdir(u_int32_t id);
                     99: static void process_rmdir(u_int32_t id);
                    100: static void process_realpath(u_int32_t id);
                    101: static void process_rename(u_int32_t id);
                    102: static void process_readlink(u_int32_t id);
                    103: static void process_symlink(u_int32_t id);
                    104: static void process_extended_posix_rename(u_int32_t id);
                    105: static void process_extended_statvfs(u_int32_t id);
                    106: static void process_extended_fstatvfs(u_int32_t id);
                    107: static void process_extended_hardlink(u_int32_t id);
1.102     djm       108: static void process_extended_fsync(u_int32_t id);
1.114     djm       109: static void process_extended_lsetstat(u_int32_t id);
1.122     djm       110: static void process_extended_limits(u_int32_t id);
1.129     djm       111: static void process_extended_expand(u_int32_t id);
1.98      djm       112: static void process_extended(u_int32_t id);
                    113:
                    114: struct sftp_handler {
                    115:        const char *name;       /* user-visible name for fine-grained perms */
                    116:        const char *ext_name;   /* extended request name */
                    117:        u_int type;             /* packet type, for non extended packets */
                    118:        void (*handler)(u_int32_t);
                    119:        int does_write;         /* if nonzero, banned for readonly mode */
                    120: };
                    121:
1.113     djm       122: static const struct sftp_handler handlers[] = {
1.98      djm       123:        /* NB. SSH2_FXP_OPEN does the readonly check in the handler itself */
                    124:        { "open", NULL, SSH2_FXP_OPEN, process_open, 0 },
                    125:        { "close", NULL, SSH2_FXP_CLOSE, process_close, 0 },
                    126:        { "read", NULL, SSH2_FXP_READ, process_read, 0 },
                    127:        { "write", NULL, SSH2_FXP_WRITE, process_write, 1 },
                    128:        { "lstat", NULL, SSH2_FXP_LSTAT, process_lstat, 0 },
                    129:        { "fstat", NULL, SSH2_FXP_FSTAT, process_fstat, 0 },
                    130:        { "setstat", NULL, SSH2_FXP_SETSTAT, process_setstat, 1 },
                    131:        { "fsetstat", NULL, SSH2_FXP_FSETSTAT, process_fsetstat, 1 },
                    132:        { "opendir", NULL, SSH2_FXP_OPENDIR, process_opendir, 0 },
                    133:        { "readdir", NULL, SSH2_FXP_READDIR, process_readdir, 0 },
                    134:        { "remove", NULL, SSH2_FXP_REMOVE, process_remove, 1 },
                    135:        { "mkdir", NULL, SSH2_FXP_MKDIR, process_mkdir, 1 },
                    136:        { "rmdir", NULL, SSH2_FXP_RMDIR, process_rmdir, 1 },
                    137:        { "realpath", NULL, SSH2_FXP_REALPATH, process_realpath, 0 },
                    138:        { "stat", NULL, SSH2_FXP_STAT, process_stat, 0 },
                    139:        { "rename", NULL, SSH2_FXP_RENAME, process_rename, 1 },
                    140:        { "readlink", NULL, SSH2_FXP_READLINK, process_readlink, 0 },
                    141:        { "symlink", NULL, SSH2_FXP_SYMLINK, process_symlink, 1 },
                    142:        { NULL, NULL, 0, NULL, 0 }
                    143: };
                    144:
                    145: /* SSH2_FXP_EXTENDED submessages */
1.113     djm       146: static const struct sftp_handler extended_handlers[] = {
1.98      djm       147:        { "posix-rename", "posix-rename@openssh.com", 0,
1.127     djm       148:            process_extended_posix_rename, 1 },
1.98      djm       149:        { "statvfs", "statvfs@openssh.com", 0, process_extended_statvfs, 0 },
                    150:        { "fstatvfs", "fstatvfs@openssh.com", 0, process_extended_fstatvfs, 0 },
                    151:        { "hardlink", "hardlink@openssh.com", 0, process_extended_hardlink, 1 },
1.102     djm       152:        { "fsync", "fsync@openssh.com", 0, process_extended_fsync, 1 },
1.114     djm       153:        { "lsetstat", "lsetstat@openssh.com", 0, process_extended_lsetstat, 1 },
1.128     djm       154:        { "limits", "limits@openssh.com", 0, process_extended_limits, 0 },
1.129     djm       155:        { "expand-path", "expand-path@openssh.com", 0,
                    156:            process_extended_expand, 0 },
1.98      djm       157:        { NULL, NULL, 0, NULL, 0 }
                    158: };
                    159:
1.125     djm       160: static const struct sftp_handler *
                    161: extended_handler_byname(const char *name)
                    162: {
                    163:        int i;
                    164:
                    165:        for (i = 0; extended_handlers[i].handler != NULL; i++) {
                    166:                if (strcmp(name, extended_handlers[i].ext_name) == 0)
                    167:                        return &extended_handlers[i];
                    168:        }
                    169:        return NULL;
                    170: }
                    171:
1.98      djm       172: static int
1.113     djm       173: request_permitted(const struct sftp_handler *h)
1.98      djm       174: {
                    175:        char *result;
                    176:
                    177:        if (readonly && h->does_write) {
                    178:                verbose("Refusing %s request in read-only mode", h->name);
                    179:                return 0;
                    180:        }
1.118     djm       181:        if (request_denylist != NULL &&
                    182:            ((result = match_list(h->name, request_denylist, NULL))) != NULL) {
1.98      djm       183:                free(result);
1.118     djm       184:                verbose("Refusing denylisted %s request", h->name);
1.98      djm       185:                return 0;
                    186:        }
1.118     djm       187:        if (request_allowlist != NULL &&
                    188:            ((result = match_list(h->name, request_allowlist, NULL))) != NULL) {
1.98      djm       189:                free(result);
1.118     djm       190:                debug2("Permitting allowlisted %s request", h->name);
1.98      djm       191:                return 1;
                    192:        }
1.118     djm       193:        if (request_allowlist != NULL) {
                    194:                verbose("Refusing non-allowlisted %s request", h->name);
1.98      djm       195:                return 0;
                    196:        }
                    197:        return 1;
                    198: }
                    199:
1.28      itojun    200: static int
1.2       markus    201: errno_to_portable(int unixerrno)
1.1       markus    202: {
                    203:        int ret = 0;
1.22      deraadt   204:
1.2       markus    205:        switch (unixerrno) {
1.1       markus    206:        case 0:
1.10      markus    207:                ret = SSH2_FX_OK;
1.1       markus    208:                break;
                    209:        case ENOENT:
                    210:        case ENOTDIR:
                    211:        case EBADF:
                    212:        case ELOOP:
1.10      markus    213:                ret = SSH2_FX_NO_SUCH_FILE;
1.1       markus    214:                break;
                    215:        case EPERM:
                    216:        case EACCES:
                    217:        case EFAULT:
1.10      markus    218:                ret = SSH2_FX_PERMISSION_DENIED;
1.1       markus    219:                break;
                    220:        case ENAMETOOLONG:
                    221:        case EINVAL:
1.10      markus    222:                ret = SSH2_FX_BAD_MESSAGE;
1.82      dtucker   223:                break;
                    224:        case ENOSYS:
                    225:                ret = SSH2_FX_OP_UNSUPPORTED;
1.1       markus    226:                break;
                    227:        default:
1.10      markus    228:                ret = SSH2_FX_FAILURE;
1.1       markus    229:                break;
                    230:        }
                    231:        return ret;
                    232: }
                    233:
1.28      itojun    234: static int
1.1       markus    235: flags_from_portable(int pflags)
                    236: {
                    237:        int flags = 0;
1.22      deraadt   238:
1.20      deraadt   239:        if ((pflags & SSH2_FXF_READ) &&
                    240:            (pflags & SSH2_FXF_WRITE)) {
1.1       markus    241:                flags = O_RDWR;
1.10      markus    242:        } else if (pflags & SSH2_FXF_READ) {
1.1       markus    243:                flags = O_RDONLY;
1.10      markus    244:        } else if (pflags & SSH2_FXF_WRITE) {
1.1       markus    245:                flags = O_WRONLY;
                    246:        }
1.101     djm       247:        if (pflags & SSH2_FXF_APPEND)
                    248:                flags |= O_APPEND;
1.10      markus    249:        if (pflags & SSH2_FXF_CREAT)
1.1       markus    250:                flags |= O_CREAT;
1.10      markus    251:        if (pflags & SSH2_FXF_TRUNC)
1.1       markus    252:                flags |= O_TRUNC;
1.10      markus    253:        if (pflags & SSH2_FXF_EXCL)
1.1       markus    254:                flags |= O_EXCL;
                    255:        return flags;
                    256: }
                    257:
1.58      djm       258: static const char *
                    259: string_from_portable(int pflags)
                    260: {
                    261:        static char ret[128];
                    262:
                    263:        *ret = '\0';
                    264:
                    265: #define PAPPEND(str)   {                               \
                    266:                if (*ret != '\0')                       \
                    267:                        strlcat(ret, ",", sizeof(ret)); \
1.70      deraadt   268:                strlcat(ret, str, sizeof(ret));         \
1.58      djm       269:        }
                    270:
                    271:        if (pflags & SSH2_FXF_READ)
                    272:                PAPPEND("READ")
                    273:        if (pflags & SSH2_FXF_WRITE)
                    274:                PAPPEND("WRITE")
1.101     djm       275:        if (pflags & SSH2_FXF_APPEND)
                    276:                PAPPEND("APPEND")
1.58      djm       277:        if (pflags & SSH2_FXF_CREAT)
                    278:                PAPPEND("CREATE")
                    279:        if (pflags & SSH2_FXF_TRUNC)
                    280:                PAPPEND("TRUNCATE")
                    281:        if (pflags & SSH2_FXF_EXCL)
                    282:                PAPPEND("EXCL")
                    283:
                    284:        return ret;
                    285: }
                    286:
1.1       markus    287: /* handle handles */
                    288:
                    289: typedef struct Handle Handle;
                    290: struct Handle {
                    291:        int use;
                    292:        DIR *dirp;
                    293:        int fd;
1.101     djm       294:        int flags;
1.1       markus    295:        char *name;
1.58      djm       296:        u_int64_t bytes_read, bytes_write;
1.75      djm       297:        int next_unused;
1.1       markus    298: };
1.22      deraadt   299:
1.1       markus    300: enum {
                    301:        HANDLE_UNUSED,
                    302:        HANDLE_DIR,
                    303:        HANDLE_FILE
                    304: };
1.22      deraadt   305:
1.113     djm       306: static Handle *handles = NULL;
                    307: static u_int num_handles = 0;
                    308: static int first_unused_handle = -1;
1.75      djm       309:
                    310: static void handle_unused(int i)
                    311: {
                    312:        handles[i].use = HANDLE_UNUSED;
                    313:        handles[i].next_unused = first_unused_handle;
                    314:        first_unused_handle = i;
1.1       markus    315: }
                    316:
1.28      itojun    317: static int
1.101     djm       318: handle_new(int use, const char *name, int fd, int flags, DIR *dirp)
1.1       markus    319: {
1.75      djm       320:        int i;
                    321:
                    322:        if (first_unused_handle == -1) {
                    323:                if (num_handles + 1 <= num_handles)
                    324:                        return -1;
                    325:                num_handles++;
1.106     deraadt   326:                handles = xreallocarray(handles, num_handles, sizeof(Handle));
1.75      djm       327:                handle_unused(num_handles - 1);
                    328:        }
                    329:
                    330:        i = first_unused_handle;
                    331:        first_unused_handle = handles[i].next_unused;
                    332:
                    333:        handles[i].use = use;
                    334:        handles[i].dirp = dirp;
                    335:        handles[i].fd = fd;
1.101     djm       336:        handles[i].flags = flags;
1.75      djm       337:        handles[i].name = xstrdup(name);
                    338:        handles[i].bytes_read = handles[i].bytes_write = 0;
1.22      deraadt   339:
1.75      djm       340:        return i;
1.1       markus    341: }
                    342:
1.28      itojun    343: static int
1.1       markus    344: handle_is_ok(int i, int type)
                    345: {
1.75      djm       346:        return i >= 0 && (u_int)i < num_handles && handles[i].use == type;
1.1       markus    347: }
                    348:
1.28      itojun    349: static int
1.104     djm       350: handle_to_string(int handle, u_char **stringp, int *hlenp)
1.1       markus    351: {
                    352:        if (stringp == NULL || hlenp == NULL)
                    353:                return -1;
1.13      markus    354:        *stringp = xmalloc(sizeof(int32_t));
1.57      djm       355:        put_u32(*stringp, handle);
1.13      markus    356:        *hlenp = sizeof(int32_t);
1.1       markus    357:        return 0;
                    358: }
                    359:
1.28      itojun    360: static int
1.104     djm       361: handle_from_string(const u_char *handle, u_int hlen)
1.1       markus    362: {
1.13      markus    363:        int val;
1.22      deraadt   364:
1.13      markus    365:        if (hlen != sizeof(int32_t))
1.1       markus    366:                return -1;
1.57      djm       367:        val = get_u32(handle);
1.1       markus    368:        if (handle_is_ok(val, HANDLE_FILE) ||
                    369:            handle_is_ok(val, HANDLE_DIR))
                    370:                return val;
                    371:        return -1;
                    372: }
                    373:
1.28      itojun    374: static char *
1.1       markus    375: handle_to_name(int handle)
                    376: {
                    377:        if (handle_is_ok(handle, HANDLE_DIR)||
                    378:            handle_is_ok(handle, HANDLE_FILE))
                    379:                return handles[handle].name;
                    380:        return NULL;
                    381: }
                    382:
1.28      itojun    383: static DIR *
1.1       markus    384: handle_to_dir(int handle)
                    385: {
                    386:        if (handle_is_ok(handle, HANDLE_DIR))
                    387:                return handles[handle].dirp;
                    388:        return NULL;
                    389: }
                    390:
1.28      itojun    391: static int
1.1       markus    392: handle_to_fd(int handle)
                    393: {
1.17      stevesk   394:        if (handle_is_ok(handle, HANDLE_FILE))
1.1       markus    395:                return handles[handle].fd;
                    396:        return -1;
                    397: }
                    398:
1.101     djm       399: static int
                    400: handle_to_flags(int handle)
                    401: {
                    402:        if (handle_is_ok(handle, HANDLE_FILE))
                    403:                return handles[handle].flags;
                    404:        return 0;
                    405: }
                    406:
1.58      djm       407: static void
                    408: handle_update_read(int handle, ssize_t bytes)
                    409: {
                    410:        if (handle_is_ok(handle, HANDLE_FILE) && bytes > 0)
                    411:                handles[handle].bytes_read += bytes;
                    412: }
                    413:
                    414: static void
                    415: handle_update_write(int handle, ssize_t bytes)
                    416: {
                    417:        if (handle_is_ok(handle, HANDLE_FILE) && bytes > 0)
                    418:                handles[handle].bytes_write += bytes;
                    419: }
                    420:
                    421: static u_int64_t
                    422: handle_bytes_read(int handle)
                    423: {
                    424:        if (handle_is_ok(handle, HANDLE_FILE))
                    425:                return (handles[handle].bytes_read);
                    426:        return 0;
                    427: }
                    428:
                    429: static u_int64_t
                    430: handle_bytes_write(int handle)
                    431: {
                    432:        if (handle_is_ok(handle, HANDLE_FILE))
                    433:                return (handles[handle].bytes_write);
                    434:        return 0;
                    435: }
                    436:
1.28      itojun    437: static int
1.1       markus    438: handle_close(int handle)
                    439: {
                    440:        int ret = -1;
1.22      deraadt   441:
1.1       markus    442:        if (handle_is_ok(handle, HANDLE_FILE)) {
                    443:                ret = close(handles[handle].fd);
1.97      djm       444:                free(handles[handle].name);
1.75      djm       445:                handle_unused(handle);
1.1       markus    446:        } else if (handle_is_ok(handle, HANDLE_DIR)) {
                    447:                ret = closedir(handles[handle].dirp);
1.97      djm       448:                free(handles[handle].name);
1.75      djm       449:                handle_unused(handle);
1.1       markus    450:        } else {
                    451:                errno = ENOENT;
                    452:        }
                    453:        return ret;
                    454: }
                    455:
1.58      djm       456: static void
                    457: handle_log_close(int handle, char *emsg)
                    458: {
                    459:        if (handle_is_ok(handle, HANDLE_FILE)) {
                    460:                logit("%s%sclose \"%s\" bytes read %llu written %llu",
                    461:                    emsg == NULL ? "" : emsg, emsg == NULL ? "" : " ",
                    462:                    handle_to_name(handle),
1.72      stevesk   463:                    (unsigned long long)handle_bytes_read(handle),
                    464:                    (unsigned long long)handle_bytes_write(handle));
1.58      djm       465:        } else {
                    466:                logit("%s%sclosedir \"%s\"",
                    467:                    emsg == NULL ? "" : emsg, emsg == NULL ? "" : " ",
                    468:                    handle_to_name(handle));
                    469:        }
                    470: }
                    471:
                    472: static void
                    473: handle_log_exit(void)
                    474: {
                    475:        u_int i;
                    476:
1.75      djm       477:        for (i = 0; i < num_handles; i++)
1.58      djm       478:                if (handles[i].use != HANDLE_UNUSED)
                    479:                        handle_log_close(i, "forced");
                    480: }
                    481:
1.28      itojun    482: static int
1.104     djm       483: get_handle(struct sshbuf *queue, int *hp)
1.1       markus    484: {
1.104     djm       485:        u_char *handle;
                    486:        int r;
                    487:        size_t hlen;
                    488:
                    489:        *hp = -1;
                    490:        if ((r = sshbuf_get_string(queue, &handle, &hlen)) != 0)
                    491:                return r;
1.10      markus    492:        if (hlen < 256)
1.104     djm       493:                *hp = handle_from_string(handle, hlen);
1.97      djm       494:        free(handle);
1.104     djm       495:        return 0;
1.1       markus    496: }
                    497:
                    498: /* send replies */
                    499:
1.28      itojun    500: static void
1.104     djm       501: send_msg(struct sshbuf *m)
1.1       markus    502: {
1.104     djm       503:        int r;
1.22      deraadt   504:
1.104     djm       505:        if ((r = sshbuf_put_stringb(oqueue, m)) != 0)
1.120     djm       506:                fatal_fr(r, "enqueue");
1.104     djm       507:        sshbuf_reset(m);
1.1       markus    508: }
                    509:
1.58      djm       510: static const char *
                    511: status_to_message(u_int32_t status)
1.1       markus    512: {
1.23      djm       513:        const char *status_messages[] = {
                    514:                "Success",                      /* SSH_FX_OK */
                    515:                "End of file",                  /* SSH_FX_EOF */
                    516:                "No such file",                 /* SSH_FX_NO_SUCH_FILE */
                    517:                "Permission denied",            /* SSH_FX_PERMISSION_DENIED */
                    518:                "Failure",                      /* SSH_FX_FAILURE */
                    519:                "Bad message",                  /* SSH_FX_BAD_MESSAGE */
                    520:                "No connection",                /* SSH_FX_NO_CONNECTION */
                    521:                "Connection lost",              /* SSH_FX_CONNECTION_LOST */
                    522:                "Operation unsupported",        /* SSH_FX_OP_UNSUPPORTED */
                    523:                "Unknown error"                 /* Others */
                    524:        };
1.110     deraadt   525:        return (status_messages[MINIMUM(status,SSH2_FX_MAX)]);
1.58      djm       526: }
1.22      deraadt   527:
1.58      djm       528: static void
1.136   ! djm       529: send_status_errmsg(u_int32_t id, u_int32_t status, const char *errmsg)
1.58      djm       530: {
1.104     djm       531:        struct sshbuf *msg;
                    532:        int r;
1.58      djm       533:
                    534:        debug3("request %u: sent status %u", id, status);
                    535:        if (log_level > SYSLOG_LEVEL_VERBOSE ||
                    536:            (status != SSH2_FX_OK && status != SSH2_FX_EOF))
                    537:                logit("sent status %s", status_to_message(status));
1.104     djm       538:        if ((msg = sshbuf_new()) == NULL)
1.120     djm       539:                fatal_f("sshbuf_new failed");
1.104     djm       540:        if ((r = sshbuf_put_u8(msg, SSH2_FXP_STATUS)) != 0 ||
                    541:            (r = sshbuf_put_u32(msg, id)) != 0 ||
                    542:            (r = sshbuf_put_u32(msg, status)) != 0)
1.120     djm       543:                fatal_fr(r, "compose");
1.23      djm       544:        if (version >= 3) {
1.136   ! djm       545:                if ((r = sshbuf_put_cstring(msg, errmsg == NULL ?
        !           546:                    status_to_message(status) : errmsg)) != 0 ||
1.104     djm       547:                    (r = sshbuf_put_cstring(msg, "")) != 0)
1.120     djm       548:                        fatal_fr(r, "compose message");
1.23      djm       549:        }
1.104     djm       550:        send_msg(msg);
                    551:        sshbuf_free(msg);
1.1       markus    552: }
1.136   ! djm       553:
        !           554: static void
        !           555: send_status(u_int32_t id, u_int32_t status)
        !           556: {
        !           557:        return send_status_errmsg(id, status, NULL);
        !           558: }
        !           559:
1.28      itojun    560: static void
1.104     djm       561: send_data_or_handle(char type, u_int32_t id, const u_char *data, int dlen)
1.1       markus    562: {
1.104     djm       563:        struct sshbuf *msg;
                    564:        int r;
1.22      deraadt   565:
1.104     djm       566:        if ((msg = sshbuf_new()) == NULL)
1.120     djm       567:                fatal_f("sshbuf_new failed");
1.104     djm       568:        if ((r = sshbuf_put_u8(msg, type)) != 0 ||
                    569:            (r = sshbuf_put_u32(msg, id)) != 0 ||
                    570:            (r = sshbuf_put_string(msg, data, dlen)) != 0)
1.120     djm       571:                fatal_fr(r, "compose");
1.104     djm       572:        send_msg(msg);
                    573:        sshbuf_free(msg);
1.1       markus    574: }
                    575:
1.28      itojun    576: static void
1.104     djm       577: send_data(u_int32_t id, const u_char *data, int dlen)
1.1       markus    578: {
1.58      djm       579:        debug("request %u: sent data len %d", id, dlen);
1.10      markus    580:        send_data_or_handle(SSH2_FXP_DATA, id, data, dlen);
1.1       markus    581: }
                    582:
1.28      itojun    583: static void
1.1       markus    584: send_handle(u_int32_t id, int handle)
                    585: {
1.104     djm       586:        u_char *string;
1.1       markus    587:        int hlen;
1.22      deraadt   588:
1.1       markus    589:        handle_to_string(handle, &string, &hlen);
1.58      djm       590:        debug("request %u: sent handle handle %d", id, handle);
1.10      markus    591:        send_data_or_handle(SSH2_FXP_HANDLE, id, string, hlen);
1.97      djm       592:        free(string);
1.1       markus    593: }
                    594:
1.28      itojun    595: static void
1.44      jakob     596: send_names(u_int32_t id, int count, const Stat *stats)
1.1       markus    597: {
1.104     djm       598:        struct sshbuf *msg;
                    599:        int i, r;
1.22      deraadt   600:
1.104     djm       601:        if ((msg = sshbuf_new()) == NULL)
1.120     djm       602:                fatal_f("sshbuf_new failed");
1.104     djm       603:        if ((r = sshbuf_put_u8(msg, SSH2_FXP_NAME)) != 0 ||
                    604:            (r = sshbuf_put_u32(msg, id)) != 0 ||
                    605:            (r = sshbuf_put_u32(msg, count)) != 0)
1.120     djm       606:                fatal_fr(r, "compose");
1.58      djm       607:        debug("request %u: sent names count %d", id, count);
1.1       markus    608:        for (i = 0; i < count; i++) {
1.104     djm       609:                if ((r = sshbuf_put_cstring(msg, stats[i].name)) != 0 ||
                    610:                    (r = sshbuf_put_cstring(msg, stats[i].long_name)) != 0 ||
                    611:                    (r = encode_attrib(msg, &stats[i].attrib)) != 0)
1.120     djm       612:                        fatal_fr(r, "compose filenames/attrib");
1.1       markus    613:        }
1.104     djm       614:        send_msg(msg);
                    615:        sshbuf_free(msg);
1.1       markus    616: }
                    617:
1.28      itojun    618: static void
1.44      jakob     619: send_attrib(u_int32_t id, const Attrib *a)
1.1       markus    620: {
1.104     djm       621:        struct sshbuf *msg;
                    622:        int r;
1.22      deraadt   623:
1.58      djm       624:        debug("request %u: sent attrib have 0x%x", id, a->flags);
1.104     djm       625:        if ((msg = sshbuf_new()) == NULL)
1.120     djm       626:                fatal_f("sshbuf_new failed");
1.104     djm       627:        if ((r = sshbuf_put_u8(msg, SSH2_FXP_ATTRS)) != 0 ||
                    628:            (r = sshbuf_put_u32(msg, id)) != 0 ||
                    629:            (r = encode_attrib(msg, a)) != 0)
1.120     djm       630:                fatal_fr(r, "compose");
1.104     djm       631:        send_msg(msg);
                    632:        sshbuf_free(msg);
1.1       markus    633: }
                    634:
1.79      djm       635: static void
                    636: send_statvfs(u_int32_t id, struct statvfs *st)
                    637: {
1.104     djm       638:        struct sshbuf *msg;
1.79      djm       639:        u_int64_t flag;
1.104     djm       640:        int r;
1.79      djm       641:
                    642:        flag = (st->f_flag & ST_RDONLY) ? SSH2_FXE_STATVFS_ST_RDONLY : 0;
                    643:        flag |= (st->f_flag & ST_NOSUID) ? SSH2_FXE_STATVFS_ST_NOSUID : 0;
                    644:
1.104     djm       645:        if ((msg = sshbuf_new()) == NULL)
1.120     djm       646:                fatal_f("sshbuf_new failed");
1.104     djm       647:        if ((r = sshbuf_put_u8(msg, SSH2_FXP_EXTENDED_REPLY)) != 0 ||
                    648:            (r = sshbuf_put_u32(msg, id)) != 0 ||
                    649:            (r = sshbuf_put_u64(msg, st->f_bsize)) != 0 ||
                    650:            (r = sshbuf_put_u64(msg, st->f_frsize)) != 0 ||
                    651:            (r = sshbuf_put_u64(msg, st->f_blocks)) != 0 ||
                    652:            (r = sshbuf_put_u64(msg, st->f_bfree)) != 0 ||
                    653:            (r = sshbuf_put_u64(msg, st->f_bavail)) != 0 ||
                    654:            (r = sshbuf_put_u64(msg, st->f_files)) != 0 ||
                    655:            (r = sshbuf_put_u64(msg, st->f_ffree)) != 0 ||
                    656:            (r = sshbuf_put_u64(msg, st->f_favail)) != 0 ||
                    657:            (r = sshbuf_put_u64(msg, st->f_fsid)) != 0 ||
                    658:            (r = sshbuf_put_u64(msg, flag)) != 0 ||
                    659:            (r = sshbuf_put_u64(msg, st->f_namemax)) != 0)
1.120     djm       660:                fatal_fr(r, "compose");
1.104     djm       661:        send_msg(msg);
                    662:        sshbuf_free(msg);
1.79      djm       663: }
                    664:
1.125     djm       665: /*
                    666:  * Prepare SSH2_FXP_VERSION extension advertisement for a single extension.
1.135     jsg       667:  * The extension is checked for permission prior to advertisement.
1.125     djm       668:  */
                    669: static int
                    670: compose_extension(struct sshbuf *msg, const char *name, const char *ver)
                    671: {
                    672:        int r;
                    673:        const struct sftp_handler *exthnd;
                    674:
                    675:        if ((exthnd = extended_handler_byname(name)) == NULL)
                    676:                fatal_f("internal error: no handler for %s", name);
                    677:        if (!request_permitted(exthnd)) {
                    678:                debug2_f("refusing to advertise disallowed extension %s", name);
                    679:                return 0;
                    680:        }
                    681:        if ((r = sshbuf_put_cstring(msg, name)) != 0 ||
                    682:            (r = sshbuf_put_cstring(msg, ver)) != 0)
                    683:                fatal_fr(r, "compose %s", name);
                    684:        return 0;
                    685: }
                    686:
1.1       markus    687: /* parse incoming */
                    688:
1.28      itojun    689: static void
1.1       markus    690: process_init(void)
                    691: {
1.104     djm       692:        struct sshbuf *msg;
                    693:        int r;
1.1       markus    694:
1.104     djm       695:        if ((r = sshbuf_get_u32(iqueue, &version)) != 0)
1.120     djm       696:                fatal_fr(r, "parse");
1.94      djm       697:        verbose("received client version %u", version);
1.104     djm       698:        if ((msg = sshbuf_new()) == NULL)
1.120     djm       699:                fatal_f("sshbuf_new failed");
1.104     djm       700:        if ((r = sshbuf_put_u8(msg, SSH2_FXP_VERSION)) != 0 ||
1.125     djm       701:            (r = sshbuf_put_u32(msg, SSH2_FILEXFER_VERSION)) != 0)
1.120     djm       702:                fatal_fr(r, "compose");
1.125     djm       703:
1.135     jsg       704:         /* extension advertisements */
1.125     djm       705:        compose_extension(msg, "posix-rename@openssh.com", "1");
                    706:        compose_extension(msg, "statvfs@openssh.com", "2");
                    707:        compose_extension(msg, "fstatvfs@openssh.com", "2");
                    708:        compose_extension(msg, "hardlink@openssh.com", "1");
                    709:        compose_extension(msg, "fsync@openssh.com", "1");
                    710:        compose_extension(msg, "lsetstat@openssh.com", "1");
                    711:        compose_extension(msg, "limits@openssh.com", "1");
1.129     djm       712:        compose_extension(msg, "expand-path@openssh.com", "1");
1.125     djm       713:
1.104     djm       714:        send_msg(msg);
                    715:        sshbuf_free(msg);
1.1       markus    716: }
                    717:
1.28      itojun    718: static void
1.98      djm       719: process_open(u_int32_t id)
1.1       markus    720: {
1.98      djm       721:        u_int32_t pflags;
1.104     djm       722:        Attrib a;
1.1       markus    723:        char *name;
1.104     djm       724:        int r, handle, fd, flags, mode, status = SSH2_FX_FAILURE;
                    725:
                    726:        if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
                    727:            (r = sshbuf_get_u32(iqueue, &pflags)) != 0 || /* portable flags */
                    728:            (r = decode_attrib(iqueue, &a)) != 0)
1.120     djm       729:                fatal_fr(r, "parse");
1.1       markus    730:
1.61      djm       731:        debug3("request %u: open flags %d", id, pflags);
1.1       markus    732:        flags = flags_from_portable(pflags);
1.104     djm       733:        mode = (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ? a.perm : 0666;
1.58      djm       734:        logit("open \"%s\" flags %s mode 0%o",
                    735:            name, string_from_portable(pflags), mode);
1.90      djm       736:        if (readonly &&
1.111     djm       737:            ((flags & O_ACCMODE) != O_RDONLY ||
                    738:            (flags & (O_CREAT|O_TRUNC)) != 0)) {
1.98      djm       739:                verbose("Refusing open request in read-only mode");
1.104     djm       740:                status = SSH2_FX_PERMISSION_DENIED;
1.98      djm       741:        } else {
1.90      djm       742:                fd = open(name, flags, mode);
1.116     deraadt   743:                if (fd == -1) {
1.90      djm       744:                        status = errno_to_portable(errno);
1.1       markus    745:                } else {
1.101     djm       746:                        handle = handle_new(HANDLE_FILE, name, fd, flags, NULL);
1.90      djm       747:                        if (handle < 0) {
                    748:                                close(fd);
                    749:                        } else {
                    750:                                send_handle(id, handle);
                    751:                                status = SSH2_FX_OK;
                    752:                        }
1.1       markus    753:                }
                    754:        }
1.10      markus    755:        if (status != SSH2_FX_OK)
1.1       markus    756:                send_status(id, status);
1.97      djm       757:        free(name);
1.1       markus    758: }
                    759:
1.28      itojun    760: static void
1.98      djm       761: process_close(u_int32_t id)
1.1       markus    762: {
1.104     djm       763:        int r, handle, ret, status = SSH2_FX_FAILURE;
                    764:
                    765:        if ((r = get_handle(iqueue, &handle)) != 0)
1.120     djm       766:                fatal_fr(r, "parse");
1.1       markus    767:
1.58      djm       768:        debug3("request %u: close handle %u", id, handle);
                    769:        handle_log_close(handle, NULL);
1.1       markus    770:        ret = handle_close(handle);
1.10      markus    771:        status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1.1       markus    772:        send_status(id, status);
                    773: }
                    774:
1.28      itojun    775: static void
1.98      djm       776: process_read(u_int32_t id)
1.1       markus    777: {
1.124     djm       778:        static u_char *buf;
                    779:        static size_t buflen;
1.98      djm       780:        u_int32_t len;
1.104     djm       781:        int r, handle, fd, ret, status = SSH2_FX_FAILURE;
1.1       markus    782:        u_int64_t off;
                    783:
1.104     djm       784:        if ((r = get_handle(iqueue, &handle)) != 0 ||
                    785:            (r = sshbuf_get_u64(iqueue, &off)) != 0 ||
                    786:            (r = sshbuf_get_u32(iqueue, &len)) != 0)
1.120     djm       787:                fatal_fr(r, "parse");
1.1       markus    788:
1.124     djm       789:        debug("request %u: read \"%s\" (handle %d) off %llu len %u",
1.58      djm       790:            id, handle_to_name(handle), handle, (unsigned long long)off, len);
1.124     djm       791:        if ((fd = handle_to_fd(handle)) == -1)
                    792:                goto out;
                    793:        if (len > SFTP_MAX_READ_LENGTH) {
                    794:                debug2("read change len %u to %u", len, SFTP_MAX_READ_LENGTH);
                    795:                len = SFTP_MAX_READ_LENGTH;
                    796:        }
                    797:        if (len > buflen) {
                    798:                debug3_f("allocate %zu => %u", buflen, len);
                    799:                if ((buf = realloc(NULL, len)) == NULL)
                    800:                        fatal_f("realloc failed");
                    801:                buflen = len;
                    802:        }
                    803:        if (lseek(fd, off, SEEK_SET) == -1) {
                    804:                status = errno_to_portable(errno);
                    805:                error_f("seek \"%.100s\": %s", handle_to_name(handle),
                    806:                    strerror(errno));
                    807:                goto out;
                    808:        }
                    809:        if (len == 0) {
                    810:                /* weird, but not strictly disallowed */
                    811:                ret = 0;
                    812:        } else if ((ret = read(fd, buf, len)) == -1) {
                    813:                status = errno_to_portable(errno);
                    814:                error_f("read \"%.100s\": %s", handle_to_name(handle),
                    815:                    strerror(errno));
                    816:                goto out;
                    817:        } else if (ret == 0) {
                    818:                status = SSH2_FX_EOF;
                    819:                goto out;
                    820:        }
                    821:        send_data(id, buf, ret);
                    822:        handle_update_read(handle, ret);
                    823:        /* success */
                    824:        status = SSH2_FX_OK;
                    825:  out:
1.10      markus    826:        if (status != SSH2_FX_OK)
1.1       markus    827:                send_status(id, status);
                    828: }
                    829:
1.28      itojun    830: static void
1.98      djm       831: process_write(u_int32_t id)
1.1       markus    832: {
                    833:        u_int64_t off;
1.104     djm       834:        size_t len;
                    835:        int r, handle, fd, ret, status;
                    836:        u_char *data;
                    837:
                    838:        if ((r = get_handle(iqueue, &handle)) != 0 ||
                    839:            (r = sshbuf_get_u64(iqueue, &off)) != 0 ||
                    840:            (r = sshbuf_get_string(iqueue, &data, &len)) != 0)
1.120     djm       841:                fatal_fr(r, "parse");
1.1       markus    842:
1.104     djm       843:        debug("request %u: write \"%s\" (handle %d) off %llu len %zu",
1.58      djm       844:            id, handle_to_name(handle), handle, (unsigned long long)off, len);
1.1       markus    845:        fd = handle_to_fd(handle);
1.104     djm       846:
1.90      djm       847:        if (fd < 0)
                    848:                status = SSH2_FX_FAILURE;
                    849:        else {
1.101     djm       850:                if (!(handle_to_flags(handle) & O_APPEND) &&
1.123     djm       851:                    lseek(fd, off, SEEK_SET) == -1) {
1.1       markus    852:                        status = errno_to_portable(errno);
1.123     djm       853:                        error_f("seek \"%.100s\": %s", handle_to_name(handle),
                    854:                            strerror(errno));
1.1       markus    855:                } else {
                    856: /* XXX ATOMICIO ? */
                    857:                        ret = write(fd, data, len);
1.116     deraadt   858:                        if (ret == -1) {
1.1       markus    859:                                status = errno_to_portable(errno);
1.123     djm       860:                                error_f("write \"%.100s\": %s",
                    861:                                    handle_to_name(handle), strerror(errno));
1.48      djm       862:                        } else if ((size_t)ret == len) {
1.10      markus    863:                                status = SSH2_FX_OK;
1.58      djm       864:                                handle_update_write(handle, ret);
1.1       markus    865:                        } else {
1.120     djm       866:                                debug2_f("nothing at all written");
1.90      djm       867:                                status = SSH2_FX_FAILURE;
1.1       markus    868:                        }
                    869:                }
                    870:        }
                    871:        send_status(id, status);
1.97      djm       872:        free(data);
1.1       markus    873: }
                    874:
1.28      itojun    875: static void
1.98      djm       876: process_do_stat(u_int32_t id, int do_lstat)
1.1       markus    877: {
1.13      markus    878:        Attrib a;
1.1       markus    879:        struct stat st;
                    880:        char *name;
1.104     djm       881:        int r, status = SSH2_FX_FAILURE;
                    882:
                    883:        if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0)
1.120     djm       884:                fatal_fr(r, "parse");
1.1       markus    885:
1.58      djm       886:        debug3("request %u: %sstat", id, do_lstat ? "l" : "");
                    887:        verbose("%sstat name \"%s\"", do_lstat ? "l" : "", name);
1.104     djm       888:        r = do_lstat ? lstat(name, &st) : stat(name, &st);
1.116     deraadt   889:        if (r == -1) {
1.1       markus    890:                status = errno_to_portable(errno);
                    891:        } else {
1.13      markus    892:                stat_to_attrib(&st, &a);
                    893:                send_attrib(id, &a);
1.10      markus    894:                status = SSH2_FX_OK;
1.1       markus    895:        }
1.10      markus    896:        if (status != SSH2_FX_OK)
1.1       markus    897:                send_status(id, status);
1.97      djm       898:        free(name);
1.1       markus    899: }
                    900:
1.28      itojun    901: static void
1.98      djm       902: process_stat(u_int32_t id)
1.1       markus    903: {
1.98      djm       904:        process_do_stat(id, 0);
1.1       markus    905: }
                    906:
1.28      itojun    907: static void
1.98      djm       908: process_lstat(u_int32_t id)
1.1       markus    909: {
1.98      djm       910:        process_do_stat(id, 1);
1.1       markus    911: }
                    912:
1.28      itojun    913: static void
1.98      djm       914: process_fstat(u_int32_t id)
1.1       markus    915: {
1.13      markus    916:        Attrib a;
1.1       markus    917:        struct stat st;
1.104     djm       918:        int fd, r, handle, status = SSH2_FX_FAILURE;
1.1       markus    919:
1.104     djm       920:        if ((r = get_handle(iqueue, &handle)) != 0)
1.120     djm       921:                fatal_fr(r, "parse");
1.58      djm       922:        debug("request %u: fstat \"%s\" (handle %u)",
                    923:            id, handle_to_name(handle), handle);
1.1       markus    924:        fd = handle_to_fd(handle);
1.71      stevesk   925:        if (fd >= 0) {
1.104     djm       926:                r = fstat(fd, &st);
1.116     deraadt   927:                if (r == -1) {
1.1       markus    928:                        status = errno_to_portable(errno);
                    929:                } else {
1.13      markus    930:                        stat_to_attrib(&st, &a);
                    931:                        send_attrib(id, &a);
1.10      markus    932:                        status = SSH2_FX_OK;
1.1       markus    933:                }
                    934:        }
1.10      markus    935:        if (status != SSH2_FX_OK)
1.1       markus    936:                send_status(id, status);
                    937: }
                    938:
1.28      itojun    939: static struct timeval *
1.44      jakob     940: attrib_to_tv(const Attrib *a)
1.1       markus    941: {
                    942:        static struct timeval tv[2];
1.22      deraadt   943:
1.1       markus    944:        tv[0].tv_sec = a->atime;
                    945:        tv[0].tv_usec = 0;
                    946:        tv[1].tv_sec = a->mtime;
                    947:        tv[1].tv_usec = 0;
                    948:        return tv;
                    949: }
                    950:
1.114     djm       951: static struct timespec *
                    952: attrib_to_ts(const Attrib *a)
                    953: {
                    954:        static struct timespec ts[2];
                    955:
                    956:        ts[0].tv_sec = a->atime;
                    957:        ts[0].tv_nsec = 0;
                    958:        ts[1].tv_sec = a->mtime;
                    959:        ts[1].tv_nsec = 0;
                    960:        return ts;
                    961: }
                    962:
1.28      itojun    963: static void
1.98      djm       964: process_setstat(u_int32_t id)
1.1       markus    965: {
1.104     djm       966:        Attrib a;
1.1       markus    967:        char *name;
1.104     djm       968:        int r, status = SSH2_FX_OK;
                    969:
                    970:        if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
                    971:            (r = decode_attrib(iqueue, &a)) != 0)
1.120     djm       972:                fatal_fr(r, "parse");
1.1       markus    973:
1.58      djm       974:        debug("request %u: setstat name \"%s\"", id, name);
1.104     djm       975:        if (a.flags & SSH2_FILEXFER_ATTR_SIZE) {
1.72      stevesk   976:                logit("set \"%s\" size %llu",
1.104     djm       977:                    name, (unsigned long long)a.size);
                    978:                r = truncate(name, a.size);
                    979:                if (r == -1)
1.33      markus    980:                        status = errno_to_portable(errno);
                    981:        }
1.104     djm       982:        if (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
                    983:                logit("set \"%s\" mode %04o", name, a.perm);
                    984:                r = chmod(name, a.perm & 07777);
                    985:                if (r == -1)
1.1       markus    986:                        status = errno_to_portable(errno);
                    987:        }
1.104     djm       988:        if (a.flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
1.58      djm       989:                char buf[64];
1.104     djm       990:                time_t t = a.mtime;
1.58      djm       991:
                    992:                strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
                    993:                    localtime(&t));
                    994:                logit("set \"%s\" modtime %s", name, buf);
1.104     djm       995:                r = utimes(name, attrib_to_tv(&a));
                    996:                if (r == -1)
1.1       markus    997:                        status = errno_to_portable(errno);
                    998:        }
1.104     djm       999:        if (a.flags & SSH2_FILEXFER_ATTR_UIDGID) {
1.58      djm      1000:                logit("set \"%s\" owner %lu group %lu", name,
1.104     djm      1001:                    (u_long)a.uid, (u_long)a.gid);
                   1002:                r = chown(name, a.uid, a.gid);
                   1003:                if (r == -1)
1.18      stevesk  1004:                        status = errno_to_portable(errno);
                   1005:        }
1.1       markus   1006:        send_status(id, status);
1.97      djm      1007:        free(name);
1.1       markus   1008: }
                   1009:
1.28      itojun   1010: static void
1.98      djm      1011: process_fsetstat(u_int32_t id)
1.1       markus   1012: {
1.104     djm      1013:        Attrib a;
                   1014:        int handle, fd, r;
1.10      markus   1015:        int status = SSH2_FX_OK;
1.1       markus   1016:
1.104     djm      1017:        if ((r = get_handle(iqueue, &handle)) != 0 ||
                   1018:            (r = decode_attrib(iqueue, &a)) != 0)
1.120     djm      1019:                fatal_fr(r, "parse");
1.104     djm      1020:
1.58      djm      1021:        debug("request %u: fsetstat handle %d", id, handle);
1.1       markus   1022:        fd = handle_to_fd(handle);
1.90      djm      1023:        if (fd < 0)
1.10      markus   1024:                status = SSH2_FX_FAILURE;
1.90      djm      1025:        else {
1.58      djm      1026:                char *name = handle_to_name(handle);
                   1027:
1.104     djm      1028:                if (a.flags & SSH2_FILEXFER_ATTR_SIZE) {
1.72      stevesk  1029:                        logit("set \"%s\" size %llu",
1.104     djm      1030:                            name, (unsigned long long)a.size);
                   1031:                        r = ftruncate(fd, a.size);
                   1032:                        if (r == -1)
1.33      markus   1033:                                status = errno_to_portable(errno);
                   1034:                }
1.104     djm      1035:                if (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
                   1036:                        logit("set \"%s\" mode %04o", name, a.perm);
                   1037:                        r = fchmod(fd, a.perm & 07777);
                   1038:                        if (r == -1)
1.1       markus   1039:                                status = errno_to_portable(errno);
                   1040:                }
1.104     djm      1041:                if (a.flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
1.58      djm      1042:                        char buf[64];
1.104     djm      1043:                        time_t t = a.mtime;
1.58      djm      1044:
                   1045:                        strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
                   1046:                            localtime(&t));
                   1047:                        logit("set \"%s\" modtime %s", name, buf);
1.104     djm      1048:                        r = futimes(fd, attrib_to_tv(&a));
                   1049:                        if (r == -1)
1.18      stevesk  1050:                                status = errno_to_portable(errno);
                   1051:                }
1.104     djm      1052:                if (a.flags & SSH2_FILEXFER_ATTR_UIDGID) {
1.58      djm      1053:                        logit("set \"%s\" owner %lu group %lu", name,
1.104     djm      1054:                            (u_long)a.uid, (u_long)a.gid);
                   1055:                        r = fchown(fd, a.uid, a.gid);
                   1056:                        if (r == -1)
1.1       markus   1057:                                status = errno_to_portable(errno);
                   1058:                }
                   1059:        }
                   1060:        send_status(id, status);
                   1061: }
                   1062:
1.28      itojun   1063: static void
1.98      djm      1064: process_opendir(u_int32_t id)
1.1       markus   1065: {
                   1066:        DIR *dirp = NULL;
                   1067:        char *path;
1.104     djm      1068:        int r, handle, status = SSH2_FX_FAILURE;
                   1069:
                   1070:        if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
1.120     djm      1071:                fatal_fr(r, "parse");
1.1       markus   1072:
1.58      djm      1073:        debug3("request %u: opendir", id);
                   1074:        logit("opendir \"%s\"", path);
1.17      stevesk  1075:        dirp = opendir(path);
1.1       markus   1076:        if (dirp == NULL) {
                   1077:                status = errno_to_portable(errno);
                   1078:        } else {
1.101     djm      1079:                handle = handle_new(HANDLE_DIR, path, 0, 0, dirp);
1.1       markus   1080:                if (handle < 0) {
                   1081:                        closedir(dirp);
                   1082:                } else {
                   1083:                        send_handle(id, handle);
1.10      markus   1084:                        status = SSH2_FX_OK;
1.1       markus   1085:                }
1.17      stevesk  1086:
1.1       markus   1087:        }
1.10      markus   1088:        if (status != SSH2_FX_OK)
1.1       markus   1089:                send_status(id, status);
1.97      djm      1090:        free(path);
1.1       markus   1091: }
                   1092:
1.28      itojun   1093: static void
1.98      djm      1094: process_readdir(u_int32_t id)
1.1       markus   1095: {
                   1096:        DIR *dirp;
                   1097:        struct dirent *dp;
                   1098:        char *path;
1.104     djm      1099:        int r, handle;
                   1100:
                   1101:        if ((r = get_handle(iqueue, &handle)) != 0)
1.120     djm      1102:                fatal_fr(r, "parse");
1.1       markus   1103:
1.58      djm      1104:        debug("request %u: readdir \"%s\" (handle %d)", id,
                   1105:            handle_to_name(handle), handle);
1.1       markus   1106:        dirp = handle_to_dir(handle);
                   1107:        path = handle_to_name(handle);
                   1108:        if (dirp == NULL || path == NULL) {
1.10      markus   1109:                send_status(id, SSH2_FX_FAILURE);
1.1       markus   1110:        } else {
                   1111:                struct stat st;
1.105     deraadt  1112:                char pathname[PATH_MAX];
1.1       markus   1113:                Stat *stats;
                   1114:                int nstats = 10, count = 0, i;
1.36      deraadt  1115:
1.54      djm      1116:                stats = xcalloc(nstats, sizeof(Stat));
1.1       markus   1117:                while ((dp = readdir(dirp)) != NULL) {
                   1118:                        if (count >= nstats) {
                   1119:                                nstats *= 2;
1.106     deraadt  1120:                                stats = xreallocarray(stats, nstats, sizeof(Stat));
1.1       markus   1121:                        }
                   1122: /* XXX OVERFLOW ? */
1.30      jakob    1123:                        snprintf(pathname, sizeof pathname, "%s%s%s", path,
                   1124:                            strcmp(path, "/") ? "/" : "", dp->d_name);
1.116     deraadt  1125:                        if (lstat(pathname, &st) == -1)
1.1       markus   1126:                                continue;
1.13      markus   1127:                        stat_to_attrib(&st, &(stats[count].attrib));
1.1       markus   1128:                        stats[count].name = xstrdup(dp->d_name);
1.91      djm      1129:                        stats[count].long_name = ls_file(dp->d_name, &st, 0, 0);
1.1       markus   1130:                        count++;
                   1131:                        /* send up to 100 entries in one message */
1.11      markus   1132:                        /* XXX check packet size instead */
1.1       markus   1133:                        if (count == 100)
                   1134:                                break;
                   1135:                }
1.10      markus   1136:                if (count > 0) {
                   1137:                        send_names(id, count, stats);
1.31      deraadt  1138:                        for (i = 0; i < count; i++) {
1.97      djm      1139:                                free(stats[i].name);
                   1140:                                free(stats[i].long_name);
1.10      markus   1141:                        }
                   1142:                } else {
                   1143:                        send_status(id, SSH2_FX_EOF);
1.1       markus   1144:                }
1.97      djm      1145:                free(stats);
1.1       markus   1146:        }
                   1147: }
                   1148:
1.28      itojun   1149: static void
1.98      djm      1150: process_remove(u_int32_t id)
1.1       markus   1151: {
                   1152:        char *name;
1.104     djm      1153:        int r, status = SSH2_FX_FAILURE;
                   1154:
                   1155:        if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0)
1.120     djm      1156:                fatal_fr(r, "parse");
1.1       markus   1157:
1.58      djm      1158:        debug3("request %u: remove", id);
                   1159:        logit("remove name \"%s\"", name);
1.104     djm      1160:        r = unlink(name);
                   1161:        status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1.1       markus   1162:        send_status(id, status);
1.97      djm      1163:        free(name);
1.1       markus   1164: }
                   1165:
1.28      itojun   1166: static void
1.98      djm      1167: process_mkdir(u_int32_t id)
1.1       markus   1168: {
1.104     djm      1169:        Attrib a;
1.1       markus   1170:        char *name;
1.104     djm      1171:        int r, mode, status = SSH2_FX_FAILURE;
                   1172:
                   1173:        if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
                   1174:            (r = decode_attrib(iqueue, &a)) != 0)
1.120     djm      1175:                fatal_fr(r, "parse");
1.1       markus   1176:
1.104     djm      1177:        mode = (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ?
                   1178:            a.perm & 07777 : 0777;
1.58      djm      1179:        debug3("request %u: mkdir", id);
                   1180:        logit("mkdir name \"%s\" mode 0%o", name, mode);
1.104     djm      1181:        r = mkdir(name, mode);
                   1182:        status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1.1       markus   1183:        send_status(id, status);
1.97      djm      1184:        free(name);
1.1       markus   1185: }
                   1186:
1.28      itojun   1187: static void
1.98      djm      1188: process_rmdir(u_int32_t id)
1.1       markus   1189: {
                   1190:        char *name;
1.104     djm      1191:        int r, status;
                   1192:
                   1193:        if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0)
1.120     djm      1194:                fatal_fr(r, "parse");
1.1       markus   1195:
1.58      djm      1196:        debug3("request %u: rmdir", id);
                   1197:        logit("rmdir name \"%s\"", name);
1.104     djm      1198:        r = rmdir(name);
                   1199:        status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1.1       markus   1200:        send_status(id, status);
1.97      djm      1201:        free(name);
1.1       markus   1202: }
                   1203:
1.28      itojun   1204: static void
1.98      djm      1205: process_realpath(u_int32_t id)
1.1       markus   1206: {
1.105     deraadt  1207:        char resolvedname[PATH_MAX];
1.1       markus   1208:        char *path;
1.104     djm      1209:        int r;
                   1210:
                   1211:        if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
1.120     djm      1212:                fatal_fr(r, "parse");
1.1       markus   1213:
1.7       markus   1214:        if (path[0] == '\0') {
1.97      djm      1215:                free(path);
1.7       markus   1216:                path = xstrdup(".");
                   1217:        }
1.58      djm      1218:        debug3("request %u: realpath", id);
                   1219:        verbose("realpath \"%s\"", path);
1.117     djm      1220:        if (sftp_realpath(path, resolvedname) == NULL) {
1.1       markus   1221:                send_status(id, errno_to_portable(errno));
                   1222:        } else {
                   1223:                Stat s;
                   1224:                attrib_clear(&s.attrib);
                   1225:                s.name = s.long_name = resolvedname;
                   1226:                send_names(id, 1, &s);
                   1227:        }
1.97      djm      1228:        free(path);
1.1       markus   1229: }
                   1230:
1.28      itojun   1231: static void
1.98      djm      1232: process_rename(u_int32_t id)
1.1       markus   1233: {
                   1234:        char *oldpath, *newpath;
1.104     djm      1235:        int r, status;
1.41      deraadt  1236:        struct stat sb;
1.1       markus   1237:
1.104     djm      1238:        if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
                   1239:            (r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
1.120     djm      1240:                fatal_fr(r, "parse");
1.104     djm      1241:
1.58      djm      1242:        debug3("request %u: rename", id);
                   1243:        logit("rename old \"%s\" new \"%s\"", oldpath, newpath);
1.41      deraadt  1244:        status = SSH2_FX_FAILURE;
1.98      djm      1245:        if (lstat(oldpath, &sb) == -1)
1.39      markus   1246:                status = errno_to_portable(errno);
1.41      deraadt  1247:        else if (S_ISREG(sb.st_mode)) {
                   1248:                /* Race-free rename of regular files */
1.47      dtucker  1249:                if (link(oldpath, newpath) == -1) {
                   1250:                        if (errno == EOPNOTSUPP) {
                   1251:                                struct stat st;
                   1252:
                   1253:                                /*
                   1254:                                 * fs doesn't support links, so fall back to
                   1255:                                 * stat+rename.  This is racy.
                   1256:                                 */
                   1257:                                if (stat(newpath, &st) == -1) {
                   1258:                                        if (rename(oldpath, newpath) == -1)
                   1259:                                                status =
                   1260:                                                    errno_to_portable(errno);
                   1261:                                        else
                   1262:                                                status = SSH2_FX_OK;
                   1263:                                }
                   1264:                        } else {
                   1265:                                status = errno_to_portable(errno);
                   1266:                        }
                   1267:                } else if (unlink(oldpath) == -1) {
1.41      deraadt  1268:                        status = errno_to_portable(errno);
                   1269:                        /* clean spare link */
                   1270:                        unlink(newpath);
                   1271:                } else
                   1272:                        status = SSH2_FX_OK;
                   1273:        } else if (stat(newpath, &sb) == -1) {
                   1274:                if (rename(oldpath, newpath) == -1)
                   1275:                        status = errno_to_portable(errno);
                   1276:                else
                   1277:                        status = SSH2_FX_OK;
                   1278:        }
1.1       markus   1279:        send_status(id, status);
1.97      djm      1280:        free(oldpath);
                   1281:        free(newpath);
1.1       markus   1282: }
                   1283:
1.28      itojun   1284: static void
1.98      djm      1285: process_readlink(u_int32_t id)
1.23      djm      1286: {
1.104     djm      1287:        int r, len;
1.105     deraadt  1288:        char buf[PATH_MAX];
1.23      djm      1289:        char *path;
                   1290:
1.104     djm      1291:        if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
1.120     djm      1292:                fatal_fr(r, "parse");
1.104     djm      1293:
1.58      djm      1294:        debug3("request %u: readlink", id);
                   1295:        verbose("readlink \"%s\"", path);
1.46      avsm     1296:        if ((len = readlink(path, buf, sizeof(buf) - 1)) == -1)
1.23      djm      1297:                send_status(id, errno_to_portable(errno));
                   1298:        else {
                   1299:                Stat s;
1.31      deraadt  1300:
1.46      avsm     1301:                buf[len] = '\0';
1.23      djm      1302:                attrib_clear(&s.attrib);
1.46      avsm     1303:                s.name = s.long_name = buf;
1.23      djm      1304:                send_names(id, 1, &s);
                   1305:        }
1.97      djm      1306:        free(path);
1.23      djm      1307: }
                   1308:
1.28      itojun   1309: static void
1.98      djm      1310: process_symlink(u_int32_t id)
1.23      djm      1311: {
                   1312:        char *oldpath, *newpath;
1.104     djm      1313:        int r, status;
                   1314:
                   1315:        if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
                   1316:            (r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
1.120     djm      1317:                fatal_fr(r, "parse");
1.23      djm      1318:
1.58      djm      1319:        debug3("request %u: symlink", id);
                   1320:        logit("symlink old \"%s\" new \"%s\"", oldpath, newpath);
1.39      markus   1321:        /* this will fail if 'newpath' exists */
1.104     djm      1322:        r = symlink(oldpath, newpath);
                   1323:        status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1.23      djm      1324:        send_status(id, status);
1.97      djm      1325:        free(oldpath);
                   1326:        free(newpath);
1.23      djm      1327: }
                   1328:
1.28      itojun   1329: static void
1.78      djm      1330: process_extended_posix_rename(u_int32_t id)
                   1331: {
                   1332:        char *oldpath, *newpath;
1.104     djm      1333:        int r, status;
                   1334:
                   1335:        if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
                   1336:            (r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
1.120     djm      1337:                fatal_fr(r, "parse");
1.78      djm      1338:
                   1339:        debug3("request %u: posix-rename", id);
                   1340:        logit("posix-rename old \"%s\" new \"%s\"", oldpath, newpath);
1.104     djm      1341:        r = rename(oldpath, newpath);
                   1342:        status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1.90      djm      1343:        send_status(id, status);
1.97      djm      1344:        free(oldpath);
                   1345:        free(newpath);
1.78      djm      1346: }
                   1347:
                   1348: static void
1.79      djm      1349: process_extended_statvfs(u_int32_t id)
                   1350: {
                   1351:        char *path;
                   1352:        struct statvfs st;
1.104     djm      1353:        int r;
1.79      djm      1354:
1.104     djm      1355:        if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
1.120     djm      1356:                fatal_fr(r, "parse");
1.103     dtucker  1357:        debug3("request %u: statvfs", id);
                   1358:        logit("statvfs \"%s\"", path);
1.79      djm      1359:
                   1360:        if (statvfs(path, &st) != 0)
                   1361:                send_status(id, errno_to_portable(errno));
                   1362:        else
                   1363:                send_statvfs(id, &st);
1.127     djm      1364:        free(path);
1.79      djm      1365: }
                   1366:
                   1367: static void
                   1368: process_extended_fstatvfs(u_int32_t id)
                   1369: {
1.104     djm      1370:        int r, handle, fd;
1.79      djm      1371:        struct statvfs st;
                   1372:
1.104     djm      1373:        if ((r = get_handle(iqueue, &handle)) != 0)
1.120     djm      1374:                fatal_fr(r, "parse");
1.79      djm      1375:        debug("request %u: fstatvfs \"%s\" (handle %u)",
                   1376:            id, handle_to_name(handle), handle);
                   1377:        if ((fd = handle_to_fd(handle)) < 0) {
                   1378:                send_status(id, SSH2_FX_FAILURE);
                   1379:                return;
                   1380:        }
                   1381:        if (fstatvfs(fd, &st) != 0)
                   1382:                send_status(id, errno_to_portable(errno));
                   1383:        else
                   1384:                send_statvfs(id, &st);
                   1385: }
                   1386:
                   1387: static void
1.93      djm      1388: process_extended_hardlink(u_int32_t id)
                   1389: {
                   1390:        char *oldpath, *newpath;
1.104     djm      1391:        int r, status;
                   1392:
                   1393:        if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
                   1394:            (r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
1.120     djm      1395:                fatal_fr(r, "parse");
1.93      djm      1396:
                   1397:        debug3("request %u: hardlink", id);
                   1398:        logit("hardlink old \"%s\" new \"%s\"", oldpath, newpath);
1.104     djm      1399:        r = link(oldpath, newpath);
                   1400:        status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1.93      djm      1401:        send_status(id, status);
1.97      djm      1402:        free(oldpath);
                   1403:        free(newpath);
1.102     djm      1404: }
                   1405:
                   1406: static void
                   1407: process_extended_fsync(u_int32_t id)
                   1408: {
1.104     djm      1409:        int handle, fd, r, status = SSH2_FX_OP_UNSUPPORTED;
1.102     djm      1410:
1.104     djm      1411:        if ((r = get_handle(iqueue, &handle)) != 0)
1.120     djm      1412:                fatal_fr(r, "parse");
1.102     djm      1413:        debug3("request %u: fsync (handle %u)", id, handle);
                   1414:        verbose("fsync \"%s\"", handle_to_name(handle));
                   1415:        if ((fd = handle_to_fd(handle)) < 0)
                   1416:                status = SSH2_FX_NO_SUCH_FILE;
                   1417:        else if (handle_is_ok(handle, HANDLE_FILE)) {
1.104     djm      1418:                r = fsync(fd);
                   1419:                status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1.102     djm      1420:        }
                   1421:        send_status(id, status);
1.114     djm      1422: }
                   1423:
                   1424: static void
                   1425: process_extended_lsetstat(u_int32_t id)
                   1426: {
                   1427:        Attrib a;
                   1428:        char *name;
                   1429:        int r, status = SSH2_FX_OK;
                   1430:
                   1431:        if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
                   1432:            (r = decode_attrib(iqueue, &a)) != 0)
1.120     djm      1433:                fatal_fr(r, "parse");
1.114     djm      1434:
                   1435:        debug("request %u: lsetstat name \"%s\"", id, name);
                   1436:        if (a.flags & SSH2_FILEXFER_ATTR_SIZE) {
                   1437:                /* nonsensical for links */
                   1438:                status = SSH2_FX_BAD_MESSAGE;
                   1439:                goto out;
                   1440:        }
                   1441:        if (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
                   1442:                logit("set \"%s\" mode %04o", name, a.perm);
                   1443:                r = fchmodat(AT_FDCWD, name,
                   1444:                    a.perm & 07777, AT_SYMLINK_NOFOLLOW);
                   1445:                if (r == -1)
                   1446:                        status = errno_to_portable(errno);
                   1447:        }
                   1448:        if (a.flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
                   1449:                char buf[64];
                   1450:                time_t t = a.mtime;
                   1451:
                   1452:                strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
                   1453:                    localtime(&t));
                   1454:                logit("set \"%s\" modtime %s", name, buf);
                   1455:                r = utimensat(AT_FDCWD, name,
                   1456:                    attrib_to_ts(&a), AT_SYMLINK_NOFOLLOW);
                   1457:                if (r == -1)
                   1458:                        status = errno_to_portable(errno);
                   1459:        }
                   1460:        if (a.flags & SSH2_FILEXFER_ATTR_UIDGID) {
                   1461:                logit("set \"%s\" owner %lu group %lu", name,
                   1462:                    (u_long)a.uid, (u_long)a.gid);
                   1463:                r = fchownat(AT_FDCWD, name, a.uid, a.gid,
                   1464:                    AT_SYMLINK_NOFOLLOW);
                   1465:                if (r == -1)
                   1466:                        status = errno_to_portable(errno);
                   1467:        }
                   1468:  out:
                   1469:        send_status(id, status);
                   1470:        free(name);
1.122     djm      1471: }
                   1472:
                   1473: static void
                   1474: process_extended_limits(u_int32_t id)
                   1475: {
                   1476:        struct sshbuf *msg;
                   1477:        int r;
                   1478:        uint64_t nfiles = 0;
                   1479:        struct rlimit rlim;
                   1480:
                   1481:        debug("request %u: limits", id);
                   1482:
                   1483:        if (getrlimit(RLIMIT_NOFILE, &rlim) != -1 && rlim.rlim_cur > 5)
                   1484:                nfiles = rlim.rlim_cur - 5; /* stdio(3) + syslog + spare */
                   1485:
                   1486:        if ((msg = sshbuf_new()) == NULL)
                   1487:                fatal_f("sshbuf_new failed");
                   1488:        if ((r = sshbuf_put_u8(msg, SSH2_FXP_EXTENDED_REPLY)) != 0 ||
                   1489:            (r = sshbuf_put_u32(msg, id)) != 0 ||
                   1490:            /* max-packet-length */
                   1491:            (r = sshbuf_put_u64(msg, SFTP_MAX_MSG_LENGTH)) != 0 ||
                   1492:            /* max-read-length */
                   1493:            (r = sshbuf_put_u64(msg, SFTP_MAX_READ_LENGTH)) != 0 ||
                   1494:            /* max-write-length */
                   1495:            (r = sshbuf_put_u64(msg, SFTP_MAX_MSG_LENGTH - 1024)) != 0 ||
                   1496:            /* max-open-handles */
                   1497:            (r = sshbuf_put_u64(msg, nfiles)) != 0)
                   1498:                fatal_fr(r, "compose");
                   1499:        send_msg(msg);
                   1500:        sshbuf_free(msg);
1.129     djm      1501: }
                   1502:
                   1503: static void
                   1504: process_extended_expand(u_int32_t id)
                   1505: {
                   1506:        char cwd[PATH_MAX], resolvedname[PATH_MAX];
                   1507:        char *path, *npath;
                   1508:        int r;
                   1509:        Stat s;
                   1510:
                   1511:        if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
                   1512:                fatal_fr(r, "parse");
                   1513:        if (getcwd(cwd, sizeof(cwd)) == NULL) {
                   1514:                send_status(id, errno_to_portable(errno));
                   1515:                goto out;
                   1516:        }
                   1517:
                   1518:        debug3("request %u: expand, original \"%s\"", id, path);
                   1519:        if (path[0] == '\0') {
                   1520:                /* empty path */
                   1521:                free(path);
                   1522:                path = xstrdup(".");
                   1523:        } else if (*path == '~') {
                   1524:                /* ~ expand path */
                   1525:                /* Special-case for "~" and "~/" to respect homedir flag */
                   1526:                if (strcmp(path, "~") == 0) {
                   1527:                        free(path);
                   1528:                        path = xstrdup(cwd);
                   1529:                } else if (strncmp(path, "~/", 2) == 0) {
                   1530:                        npath = xstrdup(path + 2);
                   1531:                        free(path);
                   1532:                        xasprintf(&path, "%s/%s", cwd, npath);
1.130     dtucker  1533:                        free(npath);
1.129     djm      1534:                } else {
                   1535:                        /* ~user expansions */
                   1536:                        if (tilde_expand(path, pw->pw_uid, &npath) != 0) {
1.131     djm      1537:                                send_status(id, errno_to_portable(ENOENT));
1.129     djm      1538:                                goto out;
                   1539:                        }
                   1540:                        free(path);
                   1541:                        path = npath;
                   1542:                }
                   1543:        } else if (*path != '/') {
                   1544:                /* relative path */
                   1545:                xasprintf(&npath, "%s/%s", cwd, path);
                   1546:                free(path);
                   1547:                path = npath;
                   1548:        }
                   1549:        verbose("expand \"%s\"", path);
                   1550:        if (sftp_realpath(path, resolvedname) == NULL) {
                   1551:                send_status(id, errno_to_portable(errno));
                   1552:                goto out;
                   1553:        }
                   1554:        attrib_clear(&s.attrib);
                   1555:        s.name = s.long_name = resolvedname;
                   1556:        send_names(id, 1, &s);
                   1557:  out:
                   1558:        free(path);
1.93      djm      1559: }
                   1560:
                   1561: static void
1.98      djm      1562: process_extended(u_int32_t id)
1.10      markus   1563: {
                   1564:        char *request;
1.126     djm      1565:        int r;
1.125     djm      1566:        const struct sftp_handler *exthand;
1.10      markus   1567:
1.104     djm      1568:        if ((r = sshbuf_get_cstring(iqueue, &request, NULL)) != 0)
1.120     djm      1569:                fatal_fr(r, "parse");
1.125     djm      1570:        if ((exthand = extended_handler_byname(request)) == NULL) {
1.98      djm      1571:                error("Unknown extended request \"%.100s\"", request);
1.78      djm      1572:                send_status(id, SSH2_FX_OP_UNSUPPORTED);        /* MUST */
1.125     djm      1573:        } else {
                   1574:                if (!request_permitted(exthand))
                   1575:                        send_status(id, SSH2_FX_PERMISSION_DENIED);
                   1576:                else
                   1577:                        exthand->handler(id);
1.98      djm      1578:        }
1.97      djm      1579:        free(request);
1.10      markus   1580: }
1.1       markus   1581:
                   1582: /* stolen from ssh-agent */
                   1583:
1.28      itojun   1584: static void
1.1       markus   1585: process(void)
                   1586: {
1.104     djm      1587:        u_int msg_len;
                   1588:        u_int buf_len;
                   1589:        u_int consumed;
                   1590:        u_char type;
                   1591:        const u_char *cp;
                   1592:        int i, r;
1.98      djm      1593:        u_int32_t id;
1.1       markus   1594:
1.104     djm      1595:        buf_len = sshbuf_len(iqueue);
1.34      markus   1596:        if (buf_len < 5)
1.1       markus   1597:                return;         /* Incomplete message. */
1.104     djm      1598:        cp = sshbuf_ptr(iqueue);
1.57      djm      1599:        msg_len = get_u32(cp);
1.50      djm      1600:        if (msg_len > SFTP_MAX_MSG_LENGTH) {
1.58      djm      1601:                error("bad message from %s local user %s",
                   1602:                    client_addr, pw->pw_name);
1.76      markus   1603:                sftp_server_cleanup_exit(11);
1.1       markus   1604:        }
1.34      markus   1605:        if (buf_len < msg_len + 4)
1.1       markus   1606:                return;
1.104     djm      1607:        if ((r = sshbuf_consume(iqueue, 4)) != 0)
1.120     djm      1608:                fatal_fr(r, "consume");
1.34      markus   1609:        buf_len -= 4;
1.104     djm      1610:        if ((r = sshbuf_get_u8(iqueue, &type)) != 0)
1.120     djm      1611:                fatal_fr(r, "parse type");
1.98      djm      1612:
1.1       markus   1613:        switch (type) {
1.10      markus   1614:        case SSH2_FXP_INIT:
1.1       markus   1615:                process_init();
1.98      djm      1616:                init_done = 1;
1.1       markus   1617:                break;
1.10      markus   1618:        case SSH2_FXP_EXTENDED:
1.98      djm      1619:                if (!init_done)
                   1620:                        fatal("Received extended request before init");
1.104     djm      1621:                if ((r = sshbuf_get_u32(iqueue, &id)) != 0)
1.120     djm      1622:                        fatal_fr(r, "parse extended ID");
1.98      djm      1623:                process_extended(id);
1.10      markus   1624:                break;
1.1       markus   1625:        default:
1.98      djm      1626:                if (!init_done)
                   1627:                        fatal("Received %u request before init", type);
1.104     djm      1628:                if ((r = sshbuf_get_u32(iqueue, &id)) != 0)
1.120     djm      1629:                        fatal_fr(r, "parse ID");
1.98      djm      1630:                for (i = 0; handlers[i].handler != NULL; i++) {
                   1631:                        if (type == handlers[i].type) {
                   1632:                                if (!request_permitted(&handlers[i])) {
                   1633:                                        send_status(id,
                   1634:                                            SSH2_FX_PERMISSION_DENIED);
                   1635:                                } else {
                   1636:                                        handlers[i].handler(id);
                   1637:                                }
                   1638:                                break;
                   1639:                        }
                   1640:                }
                   1641:                if (handlers[i].handler == NULL)
                   1642:                        error("Unknown message %u", type);
1.1       markus   1643:        }
1.34      markus   1644:        /* discard the remaining bytes from the current packet */
1.104     djm      1645:        if (buf_len < sshbuf_len(iqueue)) {
1.76      markus   1646:                error("iqueue grew unexpectedly");
                   1647:                sftp_server_cleanup_exit(255);
                   1648:        }
1.104     djm      1649:        consumed = buf_len - sshbuf_len(iqueue);
1.76      markus   1650:        if (msg_len < consumed) {
1.98      djm      1651:                error("msg_len %u < consumed %u", msg_len, consumed);
1.76      markus   1652:                sftp_server_cleanup_exit(255);
                   1653:        }
1.104     djm      1654:        if (msg_len > consumed &&
                   1655:            (r = sshbuf_consume(iqueue, msg_len - consumed)) != 0)
1.120     djm      1656:                fatal_fr(r, "consume");
1.1       markus   1657: }
                   1658:
1.58      djm      1659: /* Cleanup handler that logs active handles upon normal exit */
                   1660: void
1.76      markus   1661: sftp_server_cleanup_exit(int i)
1.58      djm      1662: {
                   1663:        if (pw != NULL && client_addr != NULL) {
                   1664:                handle_log_exit();
                   1665:                logit("session closed for local user %s from [%s]",
                   1666:                    pw->pw_name, client_addr);
                   1667:        }
                   1668:        _exit(i);
                   1669: }
                   1670:
                   1671: static void
1.76      markus   1672: sftp_server_usage(void)
1.58      djm      1673: {
                   1674:        extern char *__progname;
                   1675:
                   1676:        fprintf(stderr,
1.96      jmc      1677:            "usage: %s [-ehR] [-d start_directory] [-f log_facility] "
1.118     djm      1678:            "[-l log_level]\n\t[-P denied_requests] "
                   1679:            "[-p allowed_requests] [-u umask]\n"
1.100     jmc      1680:            "       %s -Q protocol_feature\n",
                   1681:            __progname, __progname);
1.58      djm      1682:        exit(1);
                   1683: }
                   1684:
1.1       markus   1685: int
1.77      djm      1686: sftp_server_main(int argc, char **argv, struct passwd *user_pw)
1.1       markus   1687: {
1.132     deraadt  1688:        int i, r, in, out, ch, skipargs = 0, log_stderr = 0;
                   1689:        ssize_t len, olen;
1.58      djm      1690:        SyslogFacility log_facility = SYSLOG_FACILITY_AUTH;
1.112     djm      1691:        char *cp, *homedir = NULL, uidstr[32], buf[4*4096];
1.92      djm      1692:        long mask;
1.58      djm      1693:
                   1694:        extern char *optarg;
                   1695:        extern char *__progname;
1.49      djm      1696:
1.58      djm      1697:        log_init(__progname, log_level, log_facility, log_stderr);
                   1698:
1.95      djm      1699:        pw = pwcopy(user_pw);
                   1700:
1.98      djm      1701:        while (!skipargs && (ch = getopt(argc, argv,
                   1702:            "d:f:l:P:p:Q:u:cehR")) != -1) {
1.58      djm      1703:                switch (ch) {
1.98      djm      1704:                case 'Q':
                   1705:                        if (strcasecmp(optarg, "requests") != 0) {
                   1706:                                fprintf(stderr, "Invalid query type\n");
                   1707:                                exit(1);
                   1708:                        }
                   1709:                        for (i = 0; handlers[i].handler != NULL; i++)
                   1710:                                printf("%s\n", handlers[i].name);
                   1711:                        for (i = 0; extended_handlers[i].handler != NULL; i++)
                   1712:                                printf("%s\n", extended_handlers[i].name);
                   1713:                        exit(0);
                   1714:                        break;
1.90      djm      1715:                case 'R':
                   1716:                        readonly = 1;
                   1717:                        break;
1.58      djm      1718:                case 'c':
                   1719:                        /*
                   1720:                         * Ignore all arguments if we are invoked as a
1.70      deraadt  1721:                         * shell using "sftp-server -c command"
1.58      djm      1722:                         */
                   1723:                        skipargs = 1;
                   1724:                        break;
                   1725:                case 'e':
                   1726:                        log_stderr = 1;
                   1727:                        break;
                   1728:                case 'l':
                   1729:                        log_level = log_level_number(optarg);
                   1730:                        if (log_level == SYSLOG_LEVEL_NOT_SET)
                   1731:                                error("Invalid log level \"%s\"", optarg);
                   1732:                        break;
                   1733:                case 'f':
                   1734:                        log_facility = log_facility_number(optarg);
1.74      djm      1735:                        if (log_facility == SYSLOG_FACILITY_NOT_SET)
1.58      djm      1736:                                error("Invalid log facility \"%s\"", optarg);
1.86      djm      1737:                        break;
1.95      djm      1738:                case 'd':
                   1739:                        cp = tilde_expand_filename(optarg, user_pw->pw_uid);
1.112     djm      1740:                        snprintf(uidstr, sizeof(uidstr), "%llu",
                   1741:                            (unsigned long long)pw->pw_uid);
1.95      djm      1742:                        homedir = percent_expand(cp, "d", user_pw->pw_dir,
1.112     djm      1743:                            "u", user_pw->pw_name, "U", uidstr, (char *)NULL);
1.95      djm      1744:                        free(cp);
1.98      djm      1745:                        break;
                   1746:                case 'p':
1.118     djm      1747:                        if (request_allowlist != NULL)
1.98      djm      1748:                                fatal("Permitted requests already set");
1.118     djm      1749:                        request_allowlist = xstrdup(optarg);
1.98      djm      1750:                        break;
                   1751:                case 'P':
1.118     djm      1752:                        if (request_denylist != NULL)
1.98      djm      1753:                                fatal("Refused requests already set");
1.118     djm      1754:                        request_denylist = xstrdup(optarg);
1.95      djm      1755:                        break;
1.86      djm      1756:                case 'u':
1.92      djm      1757:                        errno = 0;
                   1758:                        mask = strtol(optarg, &cp, 8);
                   1759:                        if (mask < 0 || mask > 0777 || *cp != '\0' ||
                   1760:                            cp == optarg || (mask == 0 && errno != 0))
                   1761:                                fatal("Invalid umask \"%s\"", optarg);
                   1762:                        (void)umask((mode_t)mask);
1.58      djm      1763:                        break;
                   1764:                case 'h':
                   1765:                default:
1.76      markus   1766:                        sftp_server_usage();
1.58      djm      1767:                }
                   1768:        }
                   1769:
                   1770:        log_init(__progname, log_level, log_facility, log_stderr);
                   1771:
                   1772:        if ((cp = getenv("SSH_CONNECTION")) != NULL) {
                   1773:                client_addr = xstrdup(cp);
1.76      markus   1774:                if ((cp = strchr(client_addr, ' ')) == NULL) {
                   1775:                        error("Malformed SSH_CONNECTION variable: \"%s\"",
1.58      djm      1776:                            getenv("SSH_CONNECTION"));
1.76      markus   1777:                        sftp_server_cleanup_exit(255);
                   1778:                }
1.58      djm      1779:                *cp = '\0';
                   1780:        } else
                   1781:                client_addr = xstrdup("UNKNOWN");
                   1782:
                   1783:        logit("session opened for local user %s from [%s]",
                   1784:            pw->pw_name, client_addr);
1.10      markus   1785:
1.89      djm      1786:        in = STDIN_FILENO;
                   1787:        out = STDOUT_FILENO;
1.1       markus   1788:
1.104     djm      1789:        if ((iqueue = sshbuf_new()) == NULL)
1.120     djm      1790:                fatal_f("sshbuf_new failed");
1.104     djm      1791:        if ((oqueue = sshbuf_new()) == NULL)
1.120     djm      1792:                fatal_f("sshbuf_new failed");
1.1       markus   1793:
1.95      djm      1794:        if (homedir != NULL) {
                   1795:                if (chdir(homedir) != 0) {
                   1796:                        error("chdir to \"%s\" failed: %s", homedir,
                   1797:                            strerror(errno));
                   1798:                }
                   1799:        }
1.21      millert  1800:
1.1       markus   1801:        for (;;) {
1.132     deraadt  1802:                struct pollfd pfd[2];
                   1803:
                   1804:                memset(pfd, 0, sizeof pfd);
                   1805:                pfd[0].fd = pfd[1].fd = -1;
1.1       markus   1806:
1.73      djm      1807:                /*
                   1808:                 * Ensure that we can read a full buffer and handle
                   1809:                 * the worst-case length packet it can generate,
                   1810:                 * otherwise apply backpressure by stopping reads.
                   1811:                 */
1.104     djm      1812:                if ((r = sshbuf_check_reserve(iqueue, sizeof(buf))) == 0 &&
                   1813:                    (r = sshbuf_check_reserve(oqueue,
1.133     deraadt  1814:                    SFTP_MAX_MSG_LENGTH)) == 0) {
1.132     deraadt  1815:                        pfd[0].fd = in;
1.133     deraadt  1816:                        pfd[0].events = POLLIN;
                   1817:                }
1.104     djm      1818:                else if (r != SSH_ERR_NO_BUFFER_SPACE)
1.120     djm      1819:                        fatal_fr(r, "reserve");
1.73      djm      1820:
1.104     djm      1821:                olen = sshbuf_len(oqueue);
1.133     deraadt  1822:                if (olen > 0) {
1.132     deraadt  1823:                        pfd[1].fd = out;
1.133     deraadt  1824:                        pfd[1].events = POLLOUT;
                   1825:                }
1.1       markus   1826:
1.132     deraadt  1827:                if (poll(pfd, 2, -1) == -1) {
1.1       markus   1828:                        if (errno == EINTR)
                   1829:                                continue;
1.132     deraadt  1830:                        error("poll: %s", strerror(errno));
1.76      markus   1831:                        sftp_server_cleanup_exit(2);
1.1       markus   1832:                }
                   1833:
                   1834:                /* copy stdin to iqueue */
1.134     djm      1835:                if (pfd[0].revents & (POLLIN|POLLHUP)) {
1.1       markus   1836:                        len = read(in, buf, sizeof buf);
                   1837:                        if (len == 0) {
                   1838:                                debug("read eof");
1.76      markus   1839:                                sftp_server_cleanup_exit(0);
1.116     deraadt  1840:                        } else if (len == -1) {
1.134     djm      1841:                                if (errno != EAGAIN && errno != EINTR) {
                   1842:                                        error("read: %s", strerror(errno));
                   1843:                                        sftp_server_cleanup_exit(1);
                   1844:                                }
1.120     djm      1845:                        } else if ((r = sshbuf_put(iqueue, buf, len)) != 0)
                   1846:                                fatal_fr(r, "sshbuf_put");
1.1       markus   1847:                }
                   1848:                /* send oqueue to stdout */
1.134     djm      1849:                if (pfd[1].revents & (POLLOUT|POLLHUP)) {
1.104     djm      1850:                        len = write(out, sshbuf_ptr(oqueue), olen);
1.134     djm      1851:                        if (len == 0 || (len == -1 && errno == EPIPE)) {
                   1852:                                debug("write eof");
                   1853:                                sftp_server_cleanup_exit(0);
                   1854:                        } else if (len == -1) {
1.76      markus   1855:                                sftp_server_cleanup_exit(1);
1.134     djm      1856:                                if (errno != EAGAIN && errno != EINTR) {
                   1857:                                        error("write: %s", strerror(errno));
                   1858:                                        sftp_server_cleanup_exit(1);
                   1859:                                }
1.120     djm      1860:                        } else if ((r = sshbuf_consume(oqueue, len)) != 0)
                   1861:                                fatal_fr(r, "consume");
1.1       markus   1862:                }
1.73      djm      1863:
                   1864:                /*
                   1865:                 * Process requests from client if we can fit the results
                   1866:                 * into the output buffer, otherwise stop processing input
                   1867:                 * and let the output queue drain.
                   1868:                 */
1.104     djm      1869:                r = sshbuf_check_reserve(oqueue, SFTP_MAX_MSG_LENGTH);
                   1870:                if (r == 0)
1.73      djm      1871:                        process();
1.104     djm      1872:                else if (r != SSH_ERR_NO_BUFFER_SPACE)
1.120     djm      1873:                        fatal_fr(r, "reserve");
1.1       markus   1874:        }
                   1875: }