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

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