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

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