[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.140

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