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

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