From 7e0a344210c8a45ceb5a5a456e817efa4e57cb9b Mon Sep 17 00:00:00 2001 From: Greg Alexander Date: Sun, 21 Dec 2014 15:57:19 -0500 Subject: [PATCH] a rough subset of openssh-6.7p1 ("portable" branch), as needed to build sftp-server --- openssh/buffer.h | 98 ++ openssh/openbsd-compat/fmt_scaled.c | 274 +++ openssh/sftp-common.c | 236 +++ openssh/sftp-common.h | 51 + openssh/sftp-server-main.c | 51 + openssh/sftp-server.c | 1638 ++++++++++++++++++ openssh/sftp.c | 2444 +++++++++++++++++++++++++++ openssh/sftp.h | 101 ++ 8 files changed, 4893 insertions(+) create mode 100644 openssh/buffer.h create mode 100644 openssh/openbsd-compat/fmt_scaled.c create mode 100644 openssh/sftp-common.c create mode 100644 openssh/sftp-common.h create mode 100644 openssh/sftp-server-main.c create mode 100644 openssh/sftp-server.c create mode 100644 openssh/sftp.c create mode 100644 openssh/sftp.h diff --git a/openssh/buffer.h b/openssh/buffer.h new file mode 100644 index 0000000..9d853ed --- /dev/null +++ b/openssh/buffer.h @@ -0,0 +1,98 @@ +/* $OpenBSD: buffer.h,v 1.25 2014/04/30 05:29:56 djm Exp $ */ + +/* + * Copyright (c) 2012 Damien Miller + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* Emulation wrappers for legacy OpenSSH buffer API atop sshbuf */ + +#ifndef BUFFER_H +#define BUFFER_H + +#include "sshbuf.h" + +typedef struct sshbuf Buffer; + +#define buffer_init(b) sshbuf_init(b) +#define buffer_clear(b) sshbuf_reset(b) +#define buffer_free(b) sshbuf_free(b) +#define buffer_dump(b) sshbuf_dump(b, stderr) + +/* XXX cast is safe: sshbuf never stores more than len 2^31 */ +#define buffer_len(b) ((u_int) sshbuf_len(b)) +#define buffer_ptr(b) sshbuf_mutable_ptr(b) + +void buffer_append(Buffer *, const void *, u_int); +void *buffer_append_space(Buffer *, u_int); +int buffer_check_alloc(Buffer *, u_int); +void buffer_get(Buffer *, void *, u_int); + +void buffer_consume(Buffer *, u_int); +void buffer_consume_end(Buffer *, u_int); + + +int buffer_get_ret(Buffer *, void *, u_int); +int buffer_consume_ret(Buffer *, u_int); +int buffer_consume_end_ret(Buffer *, u_int); + +#include +void buffer_put_bignum(Buffer *, const BIGNUM *); +void buffer_put_bignum2(Buffer *, const BIGNUM *); +void buffer_get_bignum(Buffer *, BIGNUM *); +void buffer_get_bignum2(Buffer *, BIGNUM *); +void buffer_put_bignum2_from_string(Buffer *, const u_char *, u_int); + +u_short buffer_get_short(Buffer *); +void buffer_put_short(Buffer *, u_short); + +u_int buffer_get_int(Buffer *); +void buffer_put_int(Buffer *, u_int); + +u_int64_t buffer_get_int64(Buffer *); +void buffer_put_int64(Buffer *, u_int64_t); + +int buffer_get_char(Buffer *); +void buffer_put_char(Buffer *, int); + +void *buffer_get_string(Buffer *, u_int *); +const void *buffer_get_string_ptr(Buffer *, u_int *); +void buffer_put_string(Buffer *, const void *, u_int); +char *buffer_get_cstring(Buffer *, u_int *); +void buffer_put_cstring(Buffer *, const char *); + +#define buffer_skip_string(b) (void)buffer_get_string_ptr(b, NULL); + +int buffer_put_bignum_ret(Buffer *, const BIGNUM *); +int buffer_get_bignum_ret(Buffer *, BIGNUM *); +int buffer_put_bignum2_ret(Buffer *, const BIGNUM *); +int buffer_get_bignum2_ret(Buffer *, BIGNUM *); +int buffer_get_short_ret(u_short *, Buffer *); +int buffer_get_int_ret(u_int *, Buffer *); +int buffer_get_int64_ret(u_int64_t *, Buffer *); +void *buffer_get_string_ret(Buffer *, u_int *); +char *buffer_get_cstring_ret(Buffer *, u_int *); +const void *buffer_get_string_ptr_ret(Buffer *, u_int *); +int buffer_get_char_ret(char *, Buffer *); + +#ifdef OPENSSL_HAS_ECC +#include +int buffer_put_ecpoint_ret(Buffer *, const EC_GROUP *, const EC_POINT *); +void buffer_put_ecpoint(Buffer *, const EC_GROUP *, const EC_POINT *); +int buffer_get_ecpoint_ret(Buffer *, const EC_GROUP *, EC_POINT *); +void buffer_get_ecpoint(Buffer *, const EC_GROUP *, EC_POINT *); +#endif + +#endif /* BUFFER_H */ + diff --git a/openssh/openbsd-compat/fmt_scaled.c b/openssh/openbsd-compat/fmt_scaled.c new file mode 100644 index 0000000..edd682a --- /dev/null +++ b/openssh/openbsd-compat/fmt_scaled.c @@ -0,0 +1,274 @@ +/* $OpenBSD: fmt_scaled.c,v 1.9 2007/03/20 03:42:52 tedu Exp $ */ + +/* + * Copyright (c) 2001, 2002, 2003 Ian F. Darwin. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* OPENBSD ORIGINAL: lib/libutil/fmt_scaled.c */ + +/* + * fmt_scaled: Format numbers scaled for human comprehension + * scan_scaled: Scan numbers in this format. + * + * "Human-readable" output uses 4 digits max, and puts a unit suffix at + * the end. Makes output compact and easy-to-read esp. on huge disks. + * Formatting code was originally in OpenBSD "df", converted to library routine. + * Scanning code written for OpenBSD libutil. + */ + +#include "includes.h" + +#ifndef HAVE_FMT_SCALED + +#include +#include +#include +#include +#include +#include + +typedef enum { + NONE = 0, KILO = 1, MEGA = 2, GIGA = 3, TERA = 4, PETA = 5, EXA = 6 +} unit_type; + +/* These three arrays MUST be in sync! XXX make a struct */ +static unit_type units[] = { NONE, KILO, MEGA, GIGA, TERA, PETA, EXA }; +static char scale_chars[] = "BKMGTPE"; +static long long scale_factors[] = { + 1LL, + 1024LL, + 1024LL*1024, + 1024LL*1024*1024, + 1024LL*1024*1024*1024, + 1024LL*1024*1024*1024*1024, + 1024LL*1024*1024*1024*1024*1024, +}; +#define SCALE_LENGTH (sizeof(units)/sizeof(units[0])) + +#define MAX_DIGITS (SCALE_LENGTH * 3) /* XXX strlen(sprintf("%lld", -1)? */ + +/** Convert the given input string "scaled" into numeric in "result". + * Return 0 on success, -1 and errno set on error. + */ +int +scan_scaled(char *scaled, long long *result) +{ + char *p = scaled; + int sign = 0; + unsigned int i, ndigits = 0, fract_digits = 0; + long long scale_fact = 1, whole = 0, fpart = 0; + + /* Skip leading whitespace */ + while (isascii(*p) && isspace(*p)) + ++p; + + /* Then at most one leading + or - */ + while (*p == '-' || *p == '+') { + if (*p == '-') { + if (sign) { + errno = EINVAL; + return -1; + } + sign = -1; + ++p; + } else if (*p == '+') { + if (sign) { + errno = EINVAL; + return -1; + } + sign = +1; + ++p; + } + } + + /* Main loop: Scan digits, find decimal point, if present. + * We don't allow exponentials, so no scientific notation + * (but note that E for Exa might look like e to some!). + * Advance 'p' to end, to get scale factor. + */ + for (; isascii(*p) && (isdigit(*p) || *p=='.'); ++p) { + if (*p == '.') { + if (fract_digits > 0) { /* oops, more than one '.' */ + errno = EINVAL; + return -1; + } + fract_digits = 1; + continue; + } + + i = (*p) - '0'; /* whew! finally a digit we can use */ + if (fract_digits > 0) { + if (fract_digits >= MAX_DIGITS-1) + /* ignore extra fractional digits */ + continue; + fract_digits++; /* for later scaling */ + fpart *= 10; + fpart += i; + } else { /* normal digit */ + if (++ndigits >= MAX_DIGITS) { + errno = ERANGE; + return -1; + } + whole *= 10; + whole += i; + } + } + + if (sign) { + whole *= sign; + fpart *= sign; + } + + /* If no scale factor given, we're done. fraction is discarded. */ + if (!*p) { + *result = whole; + return 0; + } + + /* Validate scale factor, and scale whole and fraction by it. */ + for (i = 0; i < SCALE_LENGTH; i++) { + + /** Are we there yet? */ + if (*p == scale_chars[i] || + *p == tolower(scale_chars[i])) { + + /* If it ends with alphanumerics after the scale char, bad. */ + if (isalnum(*(p+1))) { + errno = EINVAL; + return -1; + } + scale_fact = scale_factors[i]; + + /* scale whole part */ + whole *= scale_fact; + + /* truncate fpart so it does't overflow. + * then scale fractional part. + */ + while (fpart >= LLONG_MAX / scale_fact) { + fpart /= 10; + fract_digits--; + } + fpart *= scale_fact; + if (fract_digits > 0) { + for (i = 0; i < fract_digits -1; i++) + fpart /= 10; + } + whole += fpart; + *result = whole; + return 0; + } + } + errno = ERANGE; + return -1; +} + +/* Format the given "number" into human-readable form in "result". + * Result must point to an allocated buffer of length FMT_SCALED_STRSIZE. + * Return 0 on success, -1 and errno set if error. + */ +int +fmt_scaled(long long number, char *result) +{ + long long abval, fract = 0; + unsigned int i; + unit_type unit = NONE; + + abval = (number < 0LL) ? -number : number; /* no long long_abs yet */ + + /* Not every negative long long has a positive representation. + * Also check for numbers that are just too darned big to format + */ + if (abval < 0 || abval / 1024 >= scale_factors[SCALE_LENGTH-1]) { + errno = ERANGE; + return -1; + } + + /* scale whole part; get unscaled fraction */ + for (i = 0; i < SCALE_LENGTH; i++) { + if (abval/1024 < scale_factors[i]) { + unit = units[i]; + fract = (i == 0) ? 0 : abval % scale_factors[i]; + number /= scale_factors[i]; + if (i > 0) + fract /= scale_factors[i - 1]; + break; + } + } + + fract = (10 * fract + 512) / 1024; + /* if the result would be >= 10, round main number */ + if (fract == 10) { + if (number >= 0) + number++; + else + number--; + fract = 0; + } + + if (number == 0) + strlcpy(result, "0B", FMT_SCALED_STRSIZE); + else if (unit == NONE || number >= 100 || number <= -100) { + if (fract >= 5) { + if (number >= 0) + number++; + else + number--; + } + (void)snprintf(result, FMT_SCALED_STRSIZE, "%lld%c", + number, scale_chars[unit]); + } else + (void)snprintf(result, FMT_SCALED_STRSIZE, "%lld.%1lld%c", + number, fract, scale_chars[unit]); + + return 0; +} + +#ifdef MAIN +/* + * This is the original version of the program in the man page. + * Copy-and-paste whatever you need from it. + */ +int +main(int argc, char **argv) +{ + char *cinput = "1.5K", buf[FMT_SCALED_STRSIZE]; + long long ninput = 10483892, result; + + if (scan_scaled(cinput, &result) == 0) + printf("\"%s\" -> %lld\n", cinput, result); + else + perror(cinput); + + if (fmt_scaled(ninput, buf) == 0) + printf("%lld -> \"%s\"\n", ninput, buf); + else + fprintf(stderr, "%lld invalid (%s)\n", ninput, strerror(errno)); + + return 0; +} +#endif + +#endif /* HAVE_FMT_SCALED */ diff --git a/openssh/sftp-common.c b/openssh/sftp-common.c new file mode 100644 index 0000000..70a929c --- /dev/null +++ b/openssh/sftp-common.c @@ -0,0 +1,236 @@ +/* $OpenBSD: sftp-common.c,v 1.26 2014/01/09 03:26:00 guenther Exp $ */ +/* + * Copyright (c) 2001 Markus Friedl. All rights reserved. + * Copyright (c) 2001 Damien Miller. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#ifdef HAVE_UTIL_H +#include +#endif + +#include "xmalloc.h" +#include "buffer.h" +#include "log.h" + +#include "sftp.h" +#include "sftp-common.h" + +/* Clear contents of attributes structure */ +void +attrib_clear(Attrib *a) +{ + a->flags = 0; + a->size = 0; + a->uid = 0; + a->gid = 0; + a->perm = 0; + a->atime = 0; + a->mtime = 0; +} + +/* Convert from struct stat to filexfer attribs */ +void +stat_to_attrib(const struct stat *st, Attrib *a) +{ + attrib_clear(a); + a->flags = 0; + a->flags |= SSH2_FILEXFER_ATTR_SIZE; + a->size = st->st_size; + a->flags |= SSH2_FILEXFER_ATTR_UIDGID; + a->uid = st->st_uid; + a->gid = st->st_gid; + a->flags |= SSH2_FILEXFER_ATTR_PERMISSIONS; + a->perm = st->st_mode; + a->flags |= SSH2_FILEXFER_ATTR_ACMODTIME; + a->atime = st->st_atime; + a->mtime = st->st_mtime; +} + +/* Convert from filexfer attribs to struct stat */ +void +attrib_to_stat(const Attrib *a, struct stat *st) +{ + memset(st, 0, sizeof(*st)); + + if (a->flags & SSH2_FILEXFER_ATTR_SIZE) + st->st_size = a->size; + if (a->flags & SSH2_FILEXFER_ATTR_UIDGID) { + st->st_uid = a->uid; + st->st_gid = a->gid; + } + if (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) + st->st_mode = a->perm; + if (a->flags & SSH2_FILEXFER_ATTR_ACMODTIME) { + st->st_atime = a->atime; + st->st_mtime = a->mtime; + } +} + +/* Decode attributes in buffer */ +Attrib * +decode_attrib(Buffer *b) +{ + static Attrib a; + + attrib_clear(&a); + a.flags = buffer_get_int(b); + if (a.flags & SSH2_FILEXFER_ATTR_SIZE) + a.size = buffer_get_int64(b); + if (a.flags & SSH2_FILEXFER_ATTR_UIDGID) { + a.uid = buffer_get_int(b); + a.gid = buffer_get_int(b); + } + if (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) + a.perm = buffer_get_int(b); + if (a.flags & SSH2_FILEXFER_ATTR_ACMODTIME) { + a.atime = buffer_get_int(b); + a.mtime = buffer_get_int(b); + } + /* vendor-specific extensions */ + if (a.flags & SSH2_FILEXFER_ATTR_EXTENDED) { + char *type, *data; + int i, count; + + count = buffer_get_int(b); + for (i = 0; i < count; i++) { + type = buffer_get_string(b, NULL); + data = buffer_get_string(b, NULL); + debug3("Got file attribute \"%s\"", type); + free(type); + free(data); + } + } + return &a; +} + +/* Encode attributes to buffer */ +void +encode_attrib(Buffer *b, const Attrib *a) +{ + buffer_put_int(b, a->flags); + if (a->flags & SSH2_FILEXFER_ATTR_SIZE) + buffer_put_int64(b, a->size); + if (a->flags & SSH2_FILEXFER_ATTR_UIDGID) { + buffer_put_int(b, a->uid); + buffer_put_int(b, a->gid); + } + if (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) + buffer_put_int(b, a->perm); + if (a->flags & SSH2_FILEXFER_ATTR_ACMODTIME) { + buffer_put_int(b, a->atime); + buffer_put_int(b, a->mtime); + } +} + +/* Convert from SSH2_FX_ status to text error message */ +const char * +fx2txt(int status) +{ + switch (status) { + case SSH2_FX_OK: + return("No error"); + case SSH2_FX_EOF: + return("End of file"); + case SSH2_FX_NO_SUCH_FILE: + return("No such file or directory"); + case SSH2_FX_PERMISSION_DENIED: + return("Permission denied"); + case SSH2_FX_FAILURE: + return("Failure"); + case SSH2_FX_BAD_MESSAGE: + return("Bad message"); + case SSH2_FX_NO_CONNECTION: + return("No connection"); + case SSH2_FX_CONNECTION_LOST: + return("Connection lost"); + case SSH2_FX_OP_UNSUPPORTED: + return("Operation unsupported"); + default: + return("Unknown status"); + } + /* NOTREACHED */ +} + +/* + * drwxr-xr-x 5 markus markus 1024 Jan 13 18:39 .ssh + */ +char * +ls_file(const char *name, const struct stat *st, int remote, int si_units) +{ + int ulen, glen, sz = 0; + struct tm *ltime = localtime(&st->st_mtime); + char *user, *group; + char buf[1024], mode[11+1], tbuf[12+1], ubuf[11+1], gbuf[11+1]; + char sbuf[FMT_SCALED_STRSIZE]; + time_t now; + + strmode(st->st_mode, mode); + if (!remote) { + user = user_from_uid(st->st_uid, 0); + } else { + snprintf(ubuf, sizeof ubuf, "%u", (u_int)st->st_uid); + user = ubuf; + } + if (!remote) { + group = group_from_gid(st->st_gid, 0); + } else { + snprintf(gbuf, sizeof gbuf, "%u", (u_int)st->st_gid); + group = gbuf; + } + if (ltime != NULL) { + now = time(NULL); + if (now - (365*24*60*60)/2 < st->st_mtime && + now >= st->st_mtime) + sz = strftime(tbuf, sizeof tbuf, "%b %e %H:%M", ltime); + else + sz = strftime(tbuf, sizeof tbuf, "%b %e %Y", ltime); + } + if (sz == 0) + tbuf[0] = '\0'; + ulen = MAX(strlen(user), 8); + glen = MAX(strlen(group), 8); + if (si_units) { + fmt_scaled((long long)st->st_size, sbuf); + snprintf(buf, sizeof buf, "%s %3u %-*s %-*s %8s %s %s", mode, + (u_int)st->st_nlink, ulen, user, glen, group, + sbuf, tbuf, name); + } else { + snprintf(buf, sizeof buf, "%s %3u %-*s %-*s %8llu %s %s", mode, + (u_int)st->st_nlink, ulen, user, glen, group, + (unsigned long long)st->st_size, tbuf, name); + } + return xstrdup(buf); +} diff --git a/openssh/sftp-common.h b/openssh/sftp-common.h new file mode 100644 index 0000000..9ed86c0 --- /dev/null +++ b/openssh/sftp-common.h @@ -0,0 +1,51 @@ +/* $OpenBSD: sftp-common.h,v 1.11 2010/01/13 01:40:16 djm Exp $ */ + +/* + * Copyright (c) 2001 Markus Friedl. All rights reserved. + * Copyright (c) 2001 Damien Miller. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* Maximum packet that we are willing to send/accept */ +#define SFTP_MAX_MSG_LENGTH (256 * 1024) + +typedef struct Attrib Attrib; + +/* File attributes */ +struct Attrib { + u_int32_t flags; + u_int64_t size; + u_int32_t uid; + u_int32_t gid; + u_int32_t perm; + u_int32_t atime; + u_int32_t mtime; +}; + +void attrib_clear(Attrib *); +void stat_to_attrib(const struct stat *, Attrib *); +void attrib_to_stat(const Attrib *, struct stat *); +Attrib *decode_attrib(Buffer *); +void encode_attrib(Buffer *, const Attrib *); +char *ls_file(const char *, const struct stat *, int, int); + +const char *fx2txt(int); diff --git a/openssh/sftp-server-main.c b/openssh/sftp-server-main.c new file mode 100644 index 0000000..7e644ab --- /dev/null +++ b/openssh/sftp-server-main.c @@ -0,0 +1,51 @@ +/* $OpenBSD: sftp-server-main.c,v 1.4 2009/02/21 19:32:04 tobias Exp $ */ +/* + * Copyright (c) 2008 Markus Friedl. All rights reserved. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include "includes.h" + +#include +#include +#include +#include +#include + +#include "log.h" +#include "sftp.h" +#include "misc.h" + +void +cleanup_exit(int i) +{ + sftp_server_cleanup_exit(i); +} + +int +main(int argc, char **argv) +{ + struct passwd *user_pw; + + /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ + sanitise_stdfd(); + + if ((user_pw = getpwuid(getuid())) == NULL) { + fprintf(stderr, "No user found for uid %lu\n", + (u_long)getuid()); + return 1; + } + + return (sftp_server_main(argc, argv, user_pw)); +} diff --git a/openssh/sftp-server.c b/openssh/sftp-server.c new file mode 100644 index 0000000..0177130 --- /dev/null +++ b/openssh/sftp-server.c @@ -0,0 +1,1638 @@ +/* $OpenBSD: sftp-server.c,v 1.103 2014/01/17 06:23:24 dtucker Exp $ */ +/* + * Copyright (c) 2000-2004 Markus Friedl. All rights reserved. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include "includes.h" + +#include +#include +#include +#ifdef HAVE_SYS_TIME_H +# include +#endif +#ifdef HAVE_SYS_MOUNT_H +#include +#endif +#ifdef HAVE_SYS_STATVFS_H +#include +#endif +#ifdef HAVE_SYS_PRCTL_H +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "xmalloc.h" +#include "buffer.h" +#include "log.h" +#include "misc.h" +#include "match.h" +#include "uidswap.h" + +#include "sftp.h" +#include "sftp-common.h" + +/* helper */ +#define get_int64() buffer_get_int64(&iqueue); +#define get_int() buffer_get_int(&iqueue); +#define get_string(lenp) buffer_get_string(&iqueue, lenp); + +/* Our verbosity */ +static LogLevel log_level = SYSLOG_LEVEL_ERROR; + +/* Our client */ +static struct passwd *pw = NULL; +static char *client_addr = NULL; + +/* input and output queue */ +static Buffer iqueue; +static Buffer oqueue; + +/* Version of client */ +static u_int version; + +/* SSH2_FXP_INIT received */ +static int init_done; + +/* Disable writes */ +static int readonly; + +/* Requests that are allowed/denied */ +static char *request_whitelist, *request_blacklist; + +/* portable attributes, etc. */ +typedef struct Stat Stat; + +struct Stat { + char *name; + char *long_name; + Attrib attrib; +}; + +/* Packet handlers */ +static void process_open(u_int32_t id); +static void process_close(u_int32_t id); +static void process_read(u_int32_t id); +static void process_write(u_int32_t id); +static void process_stat(u_int32_t id); +static void process_lstat(u_int32_t id); +static void process_fstat(u_int32_t id); +static void process_setstat(u_int32_t id); +static void process_fsetstat(u_int32_t id); +static void process_opendir(u_int32_t id); +static void process_readdir(u_int32_t id); +static void process_remove(u_int32_t id); +static void process_mkdir(u_int32_t id); +static void process_rmdir(u_int32_t id); +static void process_realpath(u_int32_t id); +static void process_rename(u_int32_t id); +static void process_readlink(u_int32_t id); +static void process_symlink(u_int32_t id); +static void process_extended_posix_rename(u_int32_t id); +static void process_extended_statvfs(u_int32_t id); +static void process_extended_fstatvfs(u_int32_t id); +static void process_extended_hardlink(u_int32_t id); +static void process_extended_fsync(u_int32_t id); +static void process_extended(u_int32_t id); + +struct sftp_handler { + const char *name; /* user-visible name for fine-grained perms */ + const char *ext_name; /* extended request name */ + u_int type; /* packet type, for non extended packets */ + void (*handler)(u_int32_t); + int does_write; /* if nonzero, banned for readonly mode */ +}; + +struct sftp_handler handlers[] = { + /* NB. SSH2_FXP_OPEN does the readonly check in the handler itself */ + { "open", NULL, SSH2_FXP_OPEN, process_open, 0 }, + { "close", NULL, SSH2_FXP_CLOSE, process_close, 0 }, + { "read", NULL, SSH2_FXP_READ, process_read, 0 }, + { "write", NULL, SSH2_FXP_WRITE, process_write, 1 }, + { "lstat", NULL, SSH2_FXP_LSTAT, process_lstat, 0 }, + { "fstat", NULL, SSH2_FXP_FSTAT, process_fstat, 0 }, + { "setstat", NULL, SSH2_FXP_SETSTAT, process_setstat, 1 }, + { "fsetstat", NULL, SSH2_FXP_FSETSTAT, process_fsetstat, 1 }, + { "opendir", NULL, SSH2_FXP_OPENDIR, process_opendir, 0 }, + { "readdir", NULL, SSH2_FXP_READDIR, process_readdir, 0 }, + { "remove", NULL, SSH2_FXP_REMOVE, process_remove, 1 }, + { "mkdir", NULL, SSH2_FXP_MKDIR, process_mkdir, 1 }, + { "rmdir", NULL, SSH2_FXP_RMDIR, process_rmdir, 1 }, + { "realpath", NULL, SSH2_FXP_REALPATH, process_realpath, 0 }, + { "stat", NULL, SSH2_FXP_STAT, process_stat, 0 }, + { "rename", NULL, SSH2_FXP_RENAME, process_rename, 1 }, + { "readlink", NULL, SSH2_FXP_READLINK, process_readlink, 0 }, + { "symlink", NULL, SSH2_FXP_SYMLINK, process_symlink, 1 }, + { NULL, NULL, 0, NULL, 0 } +}; + +/* SSH2_FXP_EXTENDED submessages */ +struct sftp_handler extended_handlers[] = { + { "posix-rename", "posix-rename@openssh.com", 0, + process_extended_posix_rename, 1 }, + { "statvfs", "statvfs@openssh.com", 0, process_extended_statvfs, 0 }, + { "fstatvfs", "fstatvfs@openssh.com", 0, process_extended_fstatvfs, 0 }, + { "hardlink", "hardlink@openssh.com", 0, process_extended_hardlink, 1 }, + { "fsync", "fsync@openssh.com", 0, process_extended_fsync, 1 }, + { NULL, NULL, 0, NULL, 0 } +}; + +static int +request_permitted(struct sftp_handler *h) +{ + char *result; + + if (readonly && h->does_write) { + verbose("Refusing %s request in read-only mode", h->name); + return 0; + } + if (request_blacklist != NULL && + ((result = match_list(h->name, request_blacklist, NULL))) != NULL) { + free(result); + verbose("Refusing blacklisted %s request", h->name); + return 0; + } + if (request_whitelist != NULL && + ((result = match_list(h->name, request_whitelist, NULL))) != NULL) { + free(result); + debug2("Permitting whitelisted %s request", h->name); + return 1; + } + if (request_whitelist != NULL) { + verbose("Refusing non-whitelisted %s request", h->name); + return 0; + } + return 1; +} + +static int +errno_to_portable(int unixerrno) +{ + int ret = 0; + + switch (unixerrno) { + case 0: + ret = SSH2_FX_OK; + break; + case ENOENT: + case ENOTDIR: + case EBADF: + case ELOOP: + ret = SSH2_FX_NO_SUCH_FILE; + break; + case EPERM: + case EACCES: + case EFAULT: + ret = SSH2_FX_PERMISSION_DENIED; + break; + case ENAMETOOLONG: + case EINVAL: + ret = SSH2_FX_BAD_MESSAGE; + break; + case ENOSYS: + ret = SSH2_FX_OP_UNSUPPORTED; + break; + default: + ret = SSH2_FX_FAILURE; + break; + } + return ret; +} + +static int +flags_from_portable(int pflags) +{ + int flags = 0; + + if ((pflags & SSH2_FXF_READ) && + (pflags & SSH2_FXF_WRITE)) { + flags = O_RDWR; + } else if (pflags & SSH2_FXF_READ) { + flags = O_RDONLY; + } else if (pflags & SSH2_FXF_WRITE) { + flags = O_WRONLY; + } + if (pflags & SSH2_FXF_APPEND) + flags |= O_APPEND; + if (pflags & SSH2_FXF_CREAT) + flags |= O_CREAT; + if (pflags & SSH2_FXF_TRUNC) + flags |= O_TRUNC; + if (pflags & SSH2_FXF_EXCL) + flags |= O_EXCL; + return flags; +} + +static const char * +string_from_portable(int pflags) +{ + static char ret[128]; + + *ret = '\0'; + +#define PAPPEND(str) { \ + if (*ret != '\0') \ + strlcat(ret, ",", sizeof(ret)); \ + strlcat(ret, str, sizeof(ret)); \ + } + + if (pflags & SSH2_FXF_READ) + PAPPEND("READ") + if (pflags & SSH2_FXF_WRITE) + PAPPEND("WRITE") + if (pflags & SSH2_FXF_APPEND) + PAPPEND("APPEND") + if (pflags & SSH2_FXF_CREAT) + PAPPEND("CREATE") + if (pflags & SSH2_FXF_TRUNC) + PAPPEND("TRUNCATE") + if (pflags & SSH2_FXF_EXCL) + PAPPEND("EXCL") + + return ret; +} + +static Attrib * +get_attrib(void) +{ + return decode_attrib(&iqueue); +} + +/* handle handles */ + +typedef struct Handle Handle; +struct Handle { + int use; + DIR *dirp; + int fd; + int flags; + char *name; + u_int64_t bytes_read, bytes_write; + int next_unused; +}; + +enum { + HANDLE_UNUSED, + HANDLE_DIR, + HANDLE_FILE +}; + +Handle *handles = NULL; +u_int num_handles = 0; +int first_unused_handle = -1; + +static void handle_unused(int i) +{ + handles[i].use = HANDLE_UNUSED; + handles[i].next_unused = first_unused_handle; + first_unused_handle = i; +} + +static int +handle_new(int use, const char *name, int fd, int flags, DIR *dirp) +{ + int i; + + if (first_unused_handle == -1) { + if (num_handles + 1 <= num_handles) + return -1; + num_handles++; + handles = xrealloc(handles, num_handles, sizeof(Handle)); + handle_unused(num_handles - 1); + } + + i = first_unused_handle; + first_unused_handle = handles[i].next_unused; + + handles[i].use = use; + handles[i].dirp = dirp; + handles[i].fd = fd; + handles[i].flags = flags; + handles[i].name = xstrdup(name); + handles[i].bytes_read = handles[i].bytes_write = 0; + + return i; +} + +static int +handle_is_ok(int i, int type) +{ + return i >= 0 && (u_int)i < num_handles && handles[i].use == type; +} + +static int +handle_to_string(int handle, char **stringp, int *hlenp) +{ + if (stringp == NULL || hlenp == NULL) + return -1; + *stringp = xmalloc(sizeof(int32_t)); + put_u32(*stringp, handle); + *hlenp = sizeof(int32_t); + return 0; +} + +static int +handle_from_string(const char *handle, u_int hlen) +{ + int val; + + if (hlen != sizeof(int32_t)) + return -1; + val = get_u32(handle); + if (handle_is_ok(val, HANDLE_FILE) || + handle_is_ok(val, HANDLE_DIR)) + return val; + return -1; +} + +static char * +handle_to_name(int handle) +{ + if (handle_is_ok(handle, HANDLE_DIR)|| + handle_is_ok(handle, HANDLE_FILE)) + return handles[handle].name; + return NULL; +} + +static DIR * +handle_to_dir(int handle) +{ + if (handle_is_ok(handle, HANDLE_DIR)) + return handles[handle].dirp; + return NULL; +} + +static int +handle_to_fd(int handle) +{ + if (handle_is_ok(handle, HANDLE_FILE)) + return handles[handle].fd; + return -1; +} + +static int +handle_to_flags(int handle) +{ + if (handle_is_ok(handle, HANDLE_FILE)) + return handles[handle].flags; + return 0; +} + +static void +handle_update_read(int handle, ssize_t bytes) +{ + if (handle_is_ok(handle, HANDLE_FILE) && bytes > 0) + handles[handle].bytes_read += bytes; +} + +static void +handle_update_write(int handle, ssize_t bytes) +{ + if (handle_is_ok(handle, HANDLE_FILE) && bytes > 0) + handles[handle].bytes_write += bytes; +} + +static u_int64_t +handle_bytes_read(int handle) +{ + if (handle_is_ok(handle, HANDLE_FILE)) + return (handles[handle].bytes_read); + return 0; +} + +static u_int64_t +handle_bytes_write(int handle) +{ + if (handle_is_ok(handle, HANDLE_FILE)) + return (handles[handle].bytes_write); + return 0; +} + +static int +handle_close(int handle) +{ + int ret = -1; + + if (handle_is_ok(handle, HANDLE_FILE)) { + ret = close(handles[handle].fd); + free(handles[handle].name); + handle_unused(handle); + } else if (handle_is_ok(handle, HANDLE_DIR)) { + ret = closedir(handles[handle].dirp); + free(handles[handle].name); + handle_unused(handle); + } else { + errno = ENOENT; + } + return ret; +} + +static void +handle_log_close(int handle, char *emsg) +{ + if (handle_is_ok(handle, HANDLE_FILE)) { + logit("%s%sclose \"%s\" bytes read %llu written %llu", + emsg == NULL ? "" : emsg, emsg == NULL ? "" : " ", + handle_to_name(handle), + (unsigned long long)handle_bytes_read(handle), + (unsigned long long)handle_bytes_write(handle)); + } else { + logit("%s%sclosedir \"%s\"", + emsg == NULL ? "" : emsg, emsg == NULL ? "" : " ", + handle_to_name(handle)); + } +} + +static void +handle_log_exit(void) +{ + u_int i; + + for (i = 0; i < num_handles; i++) + if (handles[i].use != HANDLE_UNUSED) + handle_log_close(i, "forced"); +} + +static int +get_handle(void) +{ + char *handle; + int val = -1; + u_int hlen; + + handle = get_string(&hlen); + if (hlen < 256) + val = handle_from_string(handle, hlen); + free(handle); + return val; +} + +/* send replies */ + +static void +send_msg(Buffer *m) +{ + int mlen = buffer_len(m); + + buffer_put_int(&oqueue, mlen); + buffer_append(&oqueue, buffer_ptr(m), mlen); + buffer_consume(m, mlen); +} + +static const char * +status_to_message(u_int32_t status) +{ + const char *status_messages[] = { + "Success", /* SSH_FX_OK */ + "End of file", /* SSH_FX_EOF */ + "No such file", /* SSH_FX_NO_SUCH_FILE */ + "Permission denied", /* SSH_FX_PERMISSION_DENIED */ + "Failure", /* SSH_FX_FAILURE */ + "Bad message", /* SSH_FX_BAD_MESSAGE */ + "No connection", /* SSH_FX_NO_CONNECTION */ + "Connection lost", /* SSH_FX_CONNECTION_LOST */ + "Operation unsupported", /* SSH_FX_OP_UNSUPPORTED */ + "Unknown error" /* Others */ + }; + return (status_messages[MIN(status,SSH2_FX_MAX)]); +} + +static void +send_status(u_int32_t id, u_int32_t status) +{ + Buffer msg; + + debug3("request %u: sent status %u", id, status); + if (log_level > SYSLOG_LEVEL_VERBOSE || + (status != SSH2_FX_OK && status != SSH2_FX_EOF)) + logit("sent status %s", status_to_message(status)); + buffer_init(&msg); + buffer_put_char(&msg, SSH2_FXP_STATUS); + buffer_put_int(&msg, id); + buffer_put_int(&msg, status); + if (version >= 3) { + buffer_put_cstring(&msg, status_to_message(status)); + buffer_put_cstring(&msg, ""); + } + send_msg(&msg); + buffer_free(&msg); +} +static void +send_data_or_handle(char type, u_int32_t id, const char *data, int dlen) +{ + Buffer msg; + + buffer_init(&msg); + buffer_put_char(&msg, type); + buffer_put_int(&msg, id); + buffer_put_string(&msg, data, dlen); + send_msg(&msg); + buffer_free(&msg); +} + +static void +send_data(u_int32_t id, const char *data, int dlen) +{ + debug("request %u: sent data len %d", id, dlen); + send_data_or_handle(SSH2_FXP_DATA, id, data, dlen); +} + +static void +send_handle(u_int32_t id, int handle) +{ + char *string; + int hlen; + + handle_to_string(handle, &string, &hlen); + debug("request %u: sent handle handle %d", id, handle); + send_data_or_handle(SSH2_FXP_HANDLE, id, string, hlen); + free(string); +} + +static void +send_names(u_int32_t id, int count, const Stat *stats) +{ + Buffer msg; + int i; + + buffer_init(&msg); + buffer_put_char(&msg, SSH2_FXP_NAME); + buffer_put_int(&msg, id); + buffer_put_int(&msg, count); + debug("request %u: sent names count %d", id, count); + for (i = 0; i < count; i++) { + buffer_put_cstring(&msg, stats[i].name); + buffer_put_cstring(&msg, stats[i].long_name); + encode_attrib(&msg, &stats[i].attrib); + } + send_msg(&msg); + buffer_free(&msg); +} + +static void +send_attrib(u_int32_t id, const Attrib *a) +{ + Buffer msg; + + debug("request %u: sent attrib have 0x%x", id, a->flags); + buffer_init(&msg); + buffer_put_char(&msg, SSH2_FXP_ATTRS); + buffer_put_int(&msg, id); + encode_attrib(&msg, a); + send_msg(&msg); + buffer_free(&msg); +} + +static void +send_statvfs(u_int32_t id, struct statvfs *st) +{ + Buffer msg; + u_int64_t flag; + + flag = (st->f_flag & ST_RDONLY) ? SSH2_FXE_STATVFS_ST_RDONLY : 0; + flag |= (st->f_flag & ST_NOSUID) ? SSH2_FXE_STATVFS_ST_NOSUID : 0; + + buffer_init(&msg); + buffer_put_char(&msg, SSH2_FXP_EXTENDED_REPLY); + buffer_put_int(&msg, id); + buffer_put_int64(&msg, st->f_bsize); + buffer_put_int64(&msg, st->f_frsize); + buffer_put_int64(&msg, st->f_blocks); + buffer_put_int64(&msg, st->f_bfree); + buffer_put_int64(&msg, st->f_bavail); + buffer_put_int64(&msg, st->f_files); + buffer_put_int64(&msg, st->f_ffree); + buffer_put_int64(&msg, st->f_favail); + buffer_put_int64(&msg, FSID_TO_ULONG(st->f_fsid)); + buffer_put_int64(&msg, flag); + buffer_put_int64(&msg, st->f_namemax); + send_msg(&msg); + buffer_free(&msg); +} + +/* parse incoming */ + +static void +process_init(void) +{ + Buffer msg; + + version = get_int(); + verbose("received client version %u", version); + buffer_init(&msg); + buffer_put_char(&msg, SSH2_FXP_VERSION); + buffer_put_int(&msg, SSH2_FILEXFER_VERSION); + /* POSIX rename extension */ + buffer_put_cstring(&msg, "posix-rename@openssh.com"); + buffer_put_cstring(&msg, "1"); /* version */ + /* statvfs extension */ + buffer_put_cstring(&msg, "statvfs@openssh.com"); + buffer_put_cstring(&msg, "2"); /* version */ + /* fstatvfs extension */ + buffer_put_cstring(&msg, "fstatvfs@openssh.com"); + buffer_put_cstring(&msg, "2"); /* version */ + /* hardlink extension */ + buffer_put_cstring(&msg, "hardlink@openssh.com"); + buffer_put_cstring(&msg, "1"); /* version */ + /* fsync extension */ + buffer_put_cstring(&msg, "fsync@openssh.com"); + buffer_put_cstring(&msg, "1"); /* version */ + send_msg(&msg); + buffer_free(&msg); +} + +static void +process_open(u_int32_t id) +{ + u_int32_t pflags; + Attrib *a; + char *name; + int handle, fd, flags, mode, status = SSH2_FX_FAILURE; + + name = get_string(NULL); + pflags = get_int(); /* portable flags */ + debug3("request %u: open flags %d", id, pflags); + a = get_attrib(); + flags = flags_from_portable(pflags); + mode = (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ? a->perm : 0666; + logit("open \"%s\" flags %s mode 0%o", + name, string_from_portable(pflags), mode); + if (readonly && + ((flags & O_ACCMODE) == O_WRONLY || + (flags & O_ACCMODE) == O_RDWR)) { + verbose("Refusing open request in read-only mode"); + status = SSH2_FX_PERMISSION_DENIED; + } else { + fd = open(name, flags, mode); + if (fd < 0) { + status = errno_to_portable(errno); + } else { + handle = handle_new(HANDLE_FILE, name, fd, flags, NULL); + if (handle < 0) { + close(fd); + } else { + send_handle(id, handle); + status = SSH2_FX_OK; + } + } + } + if (status != SSH2_FX_OK) + send_status(id, status); + free(name); +} + +static void +process_close(u_int32_t id) +{ + int handle, ret, status = SSH2_FX_FAILURE; + + handle = get_handle(); + debug3("request %u: close handle %u", id, handle); + handle_log_close(handle, NULL); + ret = handle_close(handle); + status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK; + send_status(id, status); +} + +static void +process_read(u_int32_t id) +{ + char buf[64*1024]; + u_int32_t len; + int handle, fd, ret, status = SSH2_FX_FAILURE; + u_int64_t off; + + handle = get_handle(); + off = get_int64(); + len = get_int(); + + debug("request %u: read \"%s\" (handle %d) off %llu len %d", + id, handle_to_name(handle), handle, (unsigned long long)off, len); + if (len > sizeof buf) { + len = sizeof buf; + debug2("read change len %d", len); + } + fd = handle_to_fd(handle); + if (fd >= 0) { + if (lseek(fd, off, SEEK_SET) < 0) { + error("process_read: seek failed"); + status = errno_to_portable(errno); + } else { + ret = read(fd, buf, len); + if (ret < 0) { + status = errno_to_portable(errno); + } else if (ret == 0) { + status = SSH2_FX_EOF; + } else { + send_data(id, buf, ret); + status = SSH2_FX_OK; + handle_update_read(handle, ret); + } + } + } + if (status != SSH2_FX_OK) + send_status(id, status); +} + +static void +process_write(u_int32_t id) +{ + u_int64_t off; + u_int len; + int handle, fd, ret, status; + char *data; + + handle = get_handle(); + off = get_int64(); + data = get_string(&len); + + debug("request %u: write \"%s\" (handle %d) off %llu len %d", + id, handle_to_name(handle), handle, (unsigned long long)off, len); + fd = handle_to_fd(handle); + + if (fd < 0) + status = SSH2_FX_FAILURE; + else { + if (!(handle_to_flags(handle) & O_APPEND) && + lseek(fd, off, SEEK_SET) < 0) { + status = errno_to_portable(errno); + error("process_write: seek failed"); + } else { +/* XXX ATOMICIO ? */ + ret = write(fd, data, len); + if (ret < 0) { + error("process_write: write failed"); + status = errno_to_portable(errno); + } else if ((size_t)ret == len) { + status = SSH2_FX_OK; + handle_update_write(handle, ret); + } else { + debug2("nothing at all written"); + status = SSH2_FX_FAILURE; + } + } + } + send_status(id, status); + free(data); +} + +static void +process_do_stat(u_int32_t id, int do_lstat) +{ + Attrib a; + struct stat st; + char *name; + int ret, status = SSH2_FX_FAILURE; + + name = get_string(NULL); + debug3("request %u: %sstat", id, do_lstat ? "l" : ""); + verbose("%sstat name \"%s\"", do_lstat ? "l" : "", name); + ret = do_lstat ? lstat(name, &st) : stat(name, &st); + if (ret < 0) { + status = errno_to_portable(errno); + } else { + stat_to_attrib(&st, &a); + send_attrib(id, &a); + status = SSH2_FX_OK; + } + if (status != SSH2_FX_OK) + send_status(id, status); + free(name); +} + +static void +process_stat(u_int32_t id) +{ + process_do_stat(id, 0); +} + +static void +process_lstat(u_int32_t id) +{ + process_do_stat(id, 1); +} + +static void +process_fstat(u_int32_t id) +{ + Attrib a; + struct stat st; + int fd, ret, handle, status = SSH2_FX_FAILURE; + + handle = get_handle(); + debug("request %u: fstat \"%s\" (handle %u)", + id, handle_to_name(handle), handle); + fd = handle_to_fd(handle); + if (fd >= 0) { + ret = fstat(fd, &st); + if (ret < 0) { + status = errno_to_portable(errno); + } else { + stat_to_attrib(&st, &a); + send_attrib(id, &a); + status = SSH2_FX_OK; + } + } + if (status != SSH2_FX_OK) + send_status(id, status); +} + +static struct timeval * +attrib_to_tv(const Attrib *a) +{ + static struct timeval tv[2]; + + tv[0].tv_sec = a->atime; + tv[0].tv_usec = 0; + tv[1].tv_sec = a->mtime; + tv[1].tv_usec = 0; + return tv; +} + +static void +process_setstat(u_int32_t id) +{ + Attrib *a; + char *name; + int status = SSH2_FX_OK, ret; + + name = get_string(NULL); + a = get_attrib(); + debug("request %u: setstat name \"%s\"", id, name); + if (a->flags & SSH2_FILEXFER_ATTR_SIZE) { + logit("set \"%s\" size %llu", + name, (unsigned long long)a->size); + ret = truncate(name, a->size); + if (ret == -1) + status = errno_to_portable(errno); + } + if (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) { + logit("set \"%s\" mode %04o", name, a->perm); + ret = chmod(name, a->perm & 07777); + if (ret == -1) + status = errno_to_portable(errno); + } + if (a->flags & SSH2_FILEXFER_ATTR_ACMODTIME) { + char buf[64]; + time_t t = a->mtime; + + strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S", + localtime(&t)); + logit("set \"%s\" modtime %s", name, buf); + ret = utimes(name, attrib_to_tv(a)); + if (ret == -1) + status = errno_to_portable(errno); + } + if (a->flags & SSH2_FILEXFER_ATTR_UIDGID) { + logit("set \"%s\" owner %lu group %lu", name, + (u_long)a->uid, (u_long)a->gid); + ret = chown(name, a->uid, a->gid); + if (ret == -1) + status = errno_to_portable(errno); + } + send_status(id, status); + free(name); +} + +static void +process_fsetstat(u_int32_t id) +{ + Attrib *a; + int handle, fd, ret; + int status = SSH2_FX_OK; + + handle = get_handle(); + a = get_attrib(); + debug("request %u: fsetstat handle %d", id, handle); + fd = handle_to_fd(handle); + if (fd < 0) + status = SSH2_FX_FAILURE; + else { + char *name = handle_to_name(handle); + + if (a->flags & SSH2_FILEXFER_ATTR_SIZE) { + logit("set \"%s\" size %llu", + name, (unsigned long long)a->size); + ret = ftruncate(fd, a->size); + if (ret == -1) + status = errno_to_portable(errno); + } + if (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) { + logit("set \"%s\" mode %04o", name, a->perm); +#ifdef HAVE_FCHMOD + ret = fchmod(fd, a->perm & 07777); +#else + ret = chmod(name, a->perm & 07777); +#endif + if (ret == -1) + status = errno_to_portable(errno); + } + if (a->flags & SSH2_FILEXFER_ATTR_ACMODTIME) { + char buf[64]; + time_t t = a->mtime; + + strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S", + localtime(&t)); + logit("set \"%s\" modtime %s", name, buf); +#ifdef HAVE_FUTIMES + ret = futimes(fd, attrib_to_tv(a)); +#else + ret = utimes(name, attrib_to_tv(a)); +#endif + if (ret == -1) + status = errno_to_portable(errno); + } + if (a->flags & SSH2_FILEXFER_ATTR_UIDGID) { + logit("set \"%s\" owner %lu group %lu", name, + (u_long)a->uid, (u_long)a->gid); +#ifdef HAVE_FCHOWN + ret = fchown(fd, a->uid, a->gid); +#else + ret = chown(name, a->uid, a->gid); +#endif + if (ret == -1) + status = errno_to_portable(errno); + } + } + send_status(id, status); +} + +static void +process_opendir(u_int32_t id) +{ + DIR *dirp = NULL; + char *path; + int handle, status = SSH2_FX_FAILURE; + + path = get_string(NULL); + debug3("request %u: opendir", id); + logit("opendir \"%s\"", path); + dirp = opendir(path); + if (dirp == NULL) { + status = errno_to_portable(errno); + } else { + handle = handle_new(HANDLE_DIR, path, 0, 0, dirp); + if (handle < 0) { + closedir(dirp); + } else { + send_handle(id, handle); + status = SSH2_FX_OK; + } + + } + if (status != SSH2_FX_OK) + send_status(id, status); + free(path); +} + +static void +process_readdir(u_int32_t id) +{ + DIR *dirp; + struct dirent *dp; + char *path; + int handle; + + handle = get_handle(); + debug("request %u: readdir \"%s\" (handle %d)", id, + handle_to_name(handle), handle); + dirp = handle_to_dir(handle); + path = handle_to_name(handle); + if (dirp == NULL || path == NULL) { + send_status(id, SSH2_FX_FAILURE); + } else { + struct stat st; + char pathname[MAXPATHLEN]; + Stat *stats; + int nstats = 10, count = 0, i; + + stats = xcalloc(nstats, sizeof(Stat)); + while ((dp = readdir(dirp)) != NULL) { + if (count >= nstats) { + nstats *= 2; + stats = xrealloc(stats, nstats, sizeof(Stat)); + } +/* XXX OVERFLOW ? */ + snprintf(pathname, sizeof pathname, "%s%s%s", path, + strcmp(path, "/") ? "/" : "", dp->d_name); + if (lstat(pathname, &st) < 0) + continue; + stat_to_attrib(&st, &(stats[count].attrib)); + stats[count].name = xstrdup(dp->d_name); + stats[count].long_name = ls_file(dp->d_name, &st, 0, 0); + count++; + /* send up to 100 entries in one message */ + /* XXX check packet size instead */ + if (count == 100) + break; + } + if (count > 0) { + send_names(id, count, stats); + for (i = 0; i < count; i++) { + free(stats[i].name); + free(stats[i].long_name); + } + } else { + send_status(id, SSH2_FX_EOF); + } + free(stats); + } +} + +static void +process_remove(u_int32_t id) +{ + char *name; + int status = SSH2_FX_FAILURE; + int ret; + + name = get_string(NULL); + debug3("request %u: remove", id); + logit("remove name \"%s\"", name); + ret = unlink(name); + status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK; + send_status(id, status); + free(name); +} + +static void +process_mkdir(u_int32_t id) +{ + Attrib *a; + char *name; + int ret, mode, status = SSH2_FX_FAILURE; + + name = get_string(NULL); + a = get_attrib(); + mode = (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ? + a->perm & 07777 : 0777; + debug3("request %u: mkdir", id); + logit("mkdir name \"%s\" mode 0%o", name, mode); + ret = mkdir(name, mode); + status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK; + send_status(id, status); + free(name); +} + +static void +process_rmdir(u_int32_t id) +{ + char *name; + int ret, status; + + name = get_string(NULL); + debug3("request %u: rmdir", id); + logit("rmdir name \"%s\"", name); + ret = rmdir(name); + status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK; + send_status(id, status); + free(name); +} + +static void +process_realpath(u_int32_t id) +{ + char resolvedname[MAXPATHLEN]; + char *path; + + path = get_string(NULL); + if (path[0] == '\0') { + free(path); + path = xstrdup("."); + } + debug3("request %u: realpath", id); + verbose("realpath \"%s\"", path); + if (realpath(path, resolvedname) == NULL) { + send_status(id, errno_to_portable(errno)); + } else { + Stat s; + attrib_clear(&s.attrib); + s.name = s.long_name = resolvedname; + send_names(id, 1, &s); + } + free(path); +} + +static void +process_rename(u_int32_t id) +{ + char *oldpath, *newpath; + int status; + struct stat sb; + + oldpath = get_string(NULL); + newpath = get_string(NULL); + debug3("request %u: rename", id); + logit("rename old \"%s\" new \"%s\"", oldpath, newpath); + status = SSH2_FX_FAILURE; + if (lstat(oldpath, &sb) == -1) + status = errno_to_portable(errno); + else if (S_ISREG(sb.st_mode)) { + /* Race-free rename of regular files */ + if (link(oldpath, newpath) == -1) { + if (errno == EOPNOTSUPP || errno == ENOSYS +#ifdef EXDEV + || errno == EXDEV +#endif +#ifdef LINK_OPNOTSUPP_ERRNO + || errno == LINK_OPNOTSUPP_ERRNO +#endif + ) { + struct stat st; + + /* + * fs doesn't support links, so fall back to + * stat+rename. This is racy. + */ + if (stat(newpath, &st) == -1) { + if (rename(oldpath, newpath) == -1) + status = + errno_to_portable(errno); + else + status = SSH2_FX_OK; + } + } else { + status = errno_to_portable(errno); + } + } else if (unlink(oldpath) == -1) { + status = errno_to_portable(errno); + /* clean spare link */ + unlink(newpath); + } else + status = SSH2_FX_OK; + } else if (stat(newpath, &sb) == -1) { + if (rename(oldpath, newpath) == -1) + status = errno_to_portable(errno); + else + status = SSH2_FX_OK; + } + send_status(id, status); + free(oldpath); + free(newpath); +} + +static void +process_readlink(u_int32_t id) +{ + int len; + char buf[MAXPATHLEN]; + char *path; + + path = get_string(NULL); + debug3("request %u: readlink", id); + verbose("readlink \"%s\"", path); + if ((len = readlink(path, buf, sizeof(buf) - 1)) == -1) + send_status(id, errno_to_portable(errno)); + else { + Stat s; + + buf[len] = '\0'; + attrib_clear(&s.attrib); + s.name = s.long_name = buf; + send_names(id, 1, &s); + } + free(path); +} + +static void +process_symlink(u_int32_t id) +{ + char *oldpath, *newpath; + int ret, status; + + oldpath = get_string(NULL); + newpath = get_string(NULL); + debug3("request %u: symlink", id); + logit("symlink old \"%s\" new \"%s\"", oldpath, newpath); + /* this will fail if 'newpath' exists */ + ret = symlink(oldpath, newpath); + status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK; + send_status(id, status); + free(oldpath); + free(newpath); +} + +static void +process_extended_posix_rename(u_int32_t id) +{ + char *oldpath, *newpath; + int ret, status; + + oldpath = get_string(NULL); + newpath = get_string(NULL); + debug3("request %u: posix-rename", id); + logit("posix-rename old \"%s\" new \"%s\"", oldpath, newpath); + ret = rename(oldpath, newpath); + status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK; + send_status(id, status); + free(oldpath); + free(newpath); +} + +static void +process_extended_statvfs(u_int32_t id) +{ + char *path; + struct statvfs st; + + path = get_string(NULL); + debug3("request %u: statvfs", id); + logit("statvfs \"%s\"", path); + + if (statvfs(path, &st) != 0) + send_status(id, errno_to_portable(errno)); + else + send_statvfs(id, &st); + free(path); +} + +static void +process_extended_fstatvfs(u_int32_t id) +{ + int handle, fd; + struct statvfs st; + + handle = get_handle(); + debug("request %u: fstatvfs \"%s\" (handle %u)", + id, handle_to_name(handle), handle); + if ((fd = handle_to_fd(handle)) < 0) { + send_status(id, SSH2_FX_FAILURE); + return; + } + if (fstatvfs(fd, &st) != 0) + send_status(id, errno_to_portable(errno)); + else + send_statvfs(id, &st); +} + +static void +process_extended_hardlink(u_int32_t id) +{ + char *oldpath, *newpath; + int ret, status; + + oldpath = get_string(NULL); + newpath = get_string(NULL); + debug3("request %u: hardlink", id); + logit("hardlink old \"%s\" new \"%s\"", oldpath, newpath); + ret = link(oldpath, newpath); + status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK; + send_status(id, status); + free(oldpath); + free(newpath); +} + +static void +process_extended_fsync(u_int32_t id) +{ + int handle, fd, ret, status = SSH2_FX_OP_UNSUPPORTED; + + handle = get_handle(); + debug3("request %u: fsync (handle %u)", id, handle); + verbose("fsync \"%s\"", handle_to_name(handle)); + if ((fd = handle_to_fd(handle)) < 0) + status = SSH2_FX_NO_SUCH_FILE; + else if (handle_is_ok(handle, HANDLE_FILE)) { + ret = fsync(fd); + status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK; + } + send_status(id, status); +} + +static void +process_extended(u_int32_t id) +{ + char *request; + u_int i; + + request = get_string(NULL); + for (i = 0; extended_handlers[i].handler != NULL; i++) { + if (strcmp(request, extended_handlers[i].ext_name) == 0) { + if (!request_permitted(&extended_handlers[i])) + send_status(id, SSH2_FX_PERMISSION_DENIED); + else + extended_handlers[i].handler(id); + break; + } + } + if (extended_handlers[i].handler == NULL) { + error("Unknown extended request \"%.100s\"", request); + send_status(id, SSH2_FX_OP_UNSUPPORTED); /* MUST */ + } + free(request); +} + +/* stolen from ssh-agent */ + +static void +process(void) +{ + u_int msg_len, buf_len, consumed, type, i; + u_char *cp; + u_int32_t id; + + buf_len = buffer_len(&iqueue); + if (buf_len < 5) + return; /* Incomplete message. */ + cp = buffer_ptr(&iqueue); + msg_len = get_u32(cp); + if (msg_len > SFTP_MAX_MSG_LENGTH) { + error("bad message from %s local user %s", + client_addr, pw->pw_name); + sftp_server_cleanup_exit(11); + } + if (buf_len < msg_len + 4) + return; + buffer_consume(&iqueue, 4); + buf_len -= 4; + type = buffer_get_char(&iqueue); + + switch (type) { + case SSH2_FXP_INIT: + process_init(); + init_done = 1; + break; + case SSH2_FXP_EXTENDED: + if (!init_done) + fatal("Received extended request before init"); + id = get_int(); + process_extended(id); + break; + default: + if (!init_done) + fatal("Received %u request before init", type); + id = get_int(); + for (i = 0; handlers[i].handler != NULL; i++) { + if (type == handlers[i].type) { + if (!request_permitted(&handlers[i])) { + send_status(id, + SSH2_FX_PERMISSION_DENIED); + } else { + handlers[i].handler(id); + } + break; + } + } + if (handlers[i].handler == NULL) + error("Unknown message %u", type); + } + /* discard the remaining bytes from the current packet */ + if (buf_len < buffer_len(&iqueue)) { + error("iqueue grew unexpectedly"); + sftp_server_cleanup_exit(255); + } + consumed = buf_len - buffer_len(&iqueue); + if (msg_len < consumed) { + error("msg_len %u < consumed %u", msg_len, consumed); + sftp_server_cleanup_exit(255); + } + if (msg_len > consumed) + buffer_consume(&iqueue, msg_len - consumed); +} + +/* Cleanup handler that logs active handles upon normal exit */ +void +sftp_server_cleanup_exit(int i) +{ + if (pw != NULL && client_addr != NULL) { + handle_log_exit(); + logit("session closed for local user %s from [%s]", + pw->pw_name, client_addr); + } + _exit(i); +} + +static void +sftp_server_usage(void) +{ + extern char *__progname; + + fprintf(stderr, + "usage: %s [-ehR] [-d start_directory] [-f log_facility] " + "[-l log_level]\n\t[-P blacklisted_requests] " + "[-p whitelisted_requests] [-u umask]\n" + " %s -Q protocol_feature\n", + __progname, __progname); + exit(1); +} + +int +sftp_server_main(int argc, char **argv, struct passwd *user_pw) +{ + fd_set *rset, *wset; + int i, in, out, max, ch, skipargs = 0, log_stderr = 0; + ssize_t len, olen, set_size; + SyslogFacility log_facility = SYSLOG_FACILITY_AUTH; + char *cp, *homedir = NULL, buf[4*4096]; + long mask; + + extern char *optarg; + extern char *__progname; + + __progname = ssh_get_progname(argv[0]); + log_init(__progname, log_level, log_facility, log_stderr); + + pw = pwcopy(user_pw); + + while (!skipargs && (ch = getopt(argc, argv, + "d:f:l:P:p:Q:u:cehR")) != -1) { + switch (ch) { + case 'Q': + if (strcasecmp(optarg, "requests") != 0) { + fprintf(stderr, "Invalid query type\n"); + exit(1); + } + for (i = 0; handlers[i].handler != NULL; i++) + printf("%s\n", handlers[i].name); + for (i = 0; extended_handlers[i].handler != NULL; i++) + printf("%s\n", extended_handlers[i].name); + exit(0); + break; + case 'R': + readonly = 1; + break; + case 'c': + /* + * Ignore all arguments if we are invoked as a + * shell using "sftp-server -c command" + */ + skipargs = 1; + break; + case 'e': + log_stderr = 1; + break; + case 'l': + log_level = log_level_number(optarg); + if (log_level == SYSLOG_LEVEL_NOT_SET) + error("Invalid log level \"%s\"", optarg); + break; + case 'f': + log_facility = log_facility_number(optarg); + if (log_facility == SYSLOG_FACILITY_NOT_SET) + error("Invalid log facility \"%s\"", optarg); + break; + case 'd': + cp = tilde_expand_filename(optarg, user_pw->pw_uid); + homedir = percent_expand(cp, "d", user_pw->pw_dir, + "u", user_pw->pw_name, (char *)NULL); + free(cp); + break; + case 'p': + if (request_whitelist != NULL) + fatal("Permitted requests already set"); + request_whitelist = xstrdup(optarg); + break; + case 'P': + if (request_blacklist != NULL) + fatal("Refused requests already set"); + request_blacklist = xstrdup(optarg); + break; + case 'u': + errno = 0; + mask = strtol(optarg, &cp, 8); + if (mask < 0 || mask > 0777 || *cp != '\0' || + cp == optarg || (mask == 0 && errno != 0)) + fatal("Invalid umask \"%s\"", optarg); + (void)umask((mode_t)mask); + break; + case 'h': + default: + sftp_server_usage(); + } + } + + log_init(__progname, log_level, log_facility, log_stderr); + +#if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE) + /* + * On Linux, we should try to avoid making /proc/self/{mem,maps} + * available to the user so that sftp access doesn't automatically + * imply arbitrary code execution access that will break + * restricted configurations. + */ + if (prctl(PR_SET_DUMPABLE, 0) != 0) + fatal("unable to make the process undumpable"); +#endif /* defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE) */ + + if ((cp = getenv("SSH_CONNECTION")) != NULL) { + client_addr = xstrdup(cp); + if ((cp = strchr(client_addr, ' ')) == NULL) { + error("Malformed SSH_CONNECTION variable: \"%s\"", + getenv("SSH_CONNECTION")); + sftp_server_cleanup_exit(255); + } + *cp = '\0'; + } else + client_addr = xstrdup("UNKNOWN"); + + logit("session opened for local user %s from [%s]", + pw->pw_name, client_addr); + + in = STDIN_FILENO; + out = STDOUT_FILENO; + +#ifdef HAVE_CYGWIN + setmode(in, O_BINARY); + setmode(out, O_BINARY); +#endif + + max = 0; + if (in > max) + max = in; + if (out > max) + max = out; + + buffer_init(&iqueue); + buffer_init(&oqueue); + + set_size = howmany(max + 1, NFDBITS) * sizeof(fd_mask); + rset = (fd_set *)xmalloc(set_size); + wset = (fd_set *)xmalloc(set_size); + + if (homedir != NULL) { + if (chdir(homedir) != 0) { + error("chdir to \"%s\" failed: %s", homedir, + strerror(errno)); + } + } + + for (;;) { + memset(rset, 0, set_size); + memset(wset, 0, set_size); + + /* + * Ensure that we can read a full buffer and handle + * the worst-case length packet it can generate, + * otherwise apply backpressure by stopping reads. + */ + if (buffer_check_alloc(&iqueue, sizeof(buf)) && + buffer_check_alloc(&oqueue, SFTP_MAX_MSG_LENGTH)) + FD_SET(in, rset); + + olen = buffer_len(&oqueue); + if (olen > 0) + FD_SET(out, wset); + + if (select(max+1, rset, wset, NULL, NULL) < 0) { + if (errno == EINTR) + continue; + error("select: %s", strerror(errno)); + sftp_server_cleanup_exit(2); + } + + /* copy stdin to iqueue */ + if (FD_ISSET(in, rset)) { + len = read(in, buf, sizeof buf); + if (len == 0) { + debug("read eof"); + sftp_server_cleanup_exit(0); + } else if (len < 0) { + error("read: %s", strerror(errno)); + sftp_server_cleanup_exit(1); + } else { + buffer_append(&iqueue, buf, len); + } + } + /* send oqueue to stdout */ + if (FD_ISSET(out, wset)) { + len = write(out, buffer_ptr(&oqueue), olen); + if (len < 0) { + error("write: %s", strerror(errno)); + sftp_server_cleanup_exit(1); + } else { + buffer_consume(&oqueue, len); + } + } + + /* + * Process requests from client if we can fit the results + * into the output buffer, otherwise stop processing input + * and let the output queue drain. + */ + if (buffer_check_alloc(&oqueue, SFTP_MAX_MSG_LENGTH)) + process(); + } +} diff --git a/openssh/sftp.c b/openssh/sftp.c new file mode 100644 index 0000000..ff4d63d --- /dev/null +++ b/openssh/sftp.c @@ -0,0 +1,2444 @@ +/* $OpenBSD: sftp.c,v 1.164 2014/07/09 01:45:10 djm Exp $ */ +/* + * Copyright (c) 2001-2004 Damien Miller + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include "includes.h" + +#include +#include +#ifdef HAVE_SYS_STAT_H +# include +#endif +#include +#include +#include +#ifdef HAVE_SYS_STATVFS_H +#include +#endif + +#include +#include + +#ifdef HAVE_PATHS_H +# include +#endif +#ifdef HAVE_LIBGEN_H +#include +#endif +#ifdef HAVE_LOCALE_H +# include +#endif +#ifdef USE_LIBEDIT +#include +#else +typedef void EditLine; +#endif +#include +#include +#include +#include +#include +#include + +#ifdef HAVE_UTIL_H +# include +#endif + +#include "xmalloc.h" +#include "log.h" +#include "pathnames.h" +#include "misc.h" + +#include "sftp.h" +#include "buffer.h" +#include "sftp-common.h" +#include "sftp-client.h" + +#define DEFAULT_COPY_BUFLEN 32768 /* Size of buffer for up/download */ +#define DEFAULT_NUM_REQUESTS 64 /* # concurrent outstanding requests */ + +/* File to read commands from */ +FILE* infile; + +/* Are we in batchfile mode? */ +int batchmode = 0; + +/* PID of ssh transport process */ +static pid_t sshpid = -1; + +/* Suppress diagnositic messages */ +int quiet = 0; + +/* This is set to 0 if the progressmeter is not desired. */ +int showprogress = 1; + +/* When this option is set, we always recursively download/upload directories */ +int global_rflag = 0; + +/* When this option is set, we resume download or upload if possible */ +int global_aflag = 0; + +/* When this option is set, the file transfers will always preserve times */ +int global_pflag = 0; + +/* When this option is set, transfers will have fsync() called on each file */ +int global_fflag = 0; + +/* SIGINT received during command processing */ +volatile sig_atomic_t interrupted = 0; + +/* I wish qsort() took a separate ctx for the comparison function...*/ +int sort_flag; + +/* Context used for commandline completion */ +struct complete_ctx { + struct sftp_conn *conn; + char **remote_pathp; +}; + +int remote_glob(struct sftp_conn *, const char *, int, + int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */ + +extern char *__progname; + +/* Separators for interactive commands */ +#define WHITESPACE " \t\r\n" + +/* ls flags */ +#define LS_LONG_VIEW 0x0001 /* Full view ala ls -l */ +#define LS_SHORT_VIEW 0x0002 /* Single row view ala ls -1 */ +#define LS_NUMERIC_VIEW 0x0004 /* Long view with numeric uid/gid */ +#define LS_NAME_SORT 0x0008 /* Sort by name (default) */ +#define LS_TIME_SORT 0x0010 /* Sort by mtime */ +#define LS_SIZE_SORT 0x0020 /* Sort by file size */ +#define LS_REVERSE_SORT 0x0040 /* Reverse sort order */ +#define LS_SHOW_ALL 0x0080 /* Don't skip filenames starting with '.' */ +#define LS_SI_UNITS 0x0100 /* Display sizes as K, M, G, etc. */ + +#define VIEW_FLAGS (LS_LONG_VIEW|LS_SHORT_VIEW|LS_NUMERIC_VIEW|LS_SI_UNITS) +#define SORT_FLAGS (LS_NAME_SORT|LS_TIME_SORT|LS_SIZE_SORT) + +/* Commands for interactive mode */ +enum sftp_command { + I_CHDIR = 1, + I_CHGRP, + I_CHMOD, + I_CHOWN, + I_DF, + I_GET, + I_HELP, + I_LCHDIR, + I_LINK, + I_LLS, + I_LMKDIR, + I_LPWD, + I_LS, + I_LUMASK, + I_MKDIR, + I_PUT, + I_PWD, + I_QUIT, + I_REGET, + I_RENAME, + I_REPUT, + I_RM, + I_RMDIR, + I_SHELL, + I_SYMLINK, + I_VERSION, + I_PROGRESS, +}; + +struct CMD { + const char *c; + const int n; + const int t; +}; + +/* Type of completion */ +#define NOARGS 0 +#define REMOTE 1 +#define LOCAL 2 + +static const struct CMD cmds[] = { + { "bye", I_QUIT, NOARGS }, + { "cd", I_CHDIR, REMOTE }, + { "chdir", I_CHDIR, REMOTE }, + { "chgrp", I_CHGRP, REMOTE }, + { "chmod", I_CHMOD, REMOTE }, + { "chown", I_CHOWN, REMOTE }, + { "df", I_DF, REMOTE }, + { "dir", I_LS, REMOTE }, + { "exit", I_QUIT, NOARGS }, + { "get", I_GET, REMOTE }, + { "help", I_HELP, NOARGS }, + { "lcd", I_LCHDIR, LOCAL }, + { "lchdir", I_LCHDIR, LOCAL }, + { "lls", I_LLS, LOCAL }, + { "lmkdir", I_LMKDIR, LOCAL }, + { "ln", I_LINK, REMOTE }, + { "lpwd", I_LPWD, LOCAL }, + { "ls", I_LS, REMOTE }, + { "lumask", I_LUMASK, NOARGS }, + { "mkdir", I_MKDIR, REMOTE }, + { "mget", I_GET, REMOTE }, + { "mput", I_PUT, LOCAL }, + { "progress", I_PROGRESS, NOARGS }, + { "put", I_PUT, LOCAL }, + { "pwd", I_PWD, REMOTE }, + { "quit", I_QUIT, NOARGS }, + { "reget", I_REGET, REMOTE }, + { "rename", I_RENAME, REMOTE }, + { "reput", I_REPUT, LOCAL }, + { "rm", I_RM, REMOTE }, + { "rmdir", I_RMDIR, REMOTE }, + { "symlink", I_SYMLINK, REMOTE }, + { "version", I_VERSION, NOARGS }, + { "!", I_SHELL, NOARGS }, + { "?", I_HELP, NOARGS }, + { NULL, -1, -1 } +}; + +int interactive_loop(struct sftp_conn *, char *file1, char *file2); + +/* ARGSUSED */ +static void +killchild(int signo) +{ + if (sshpid > 1) { + kill(sshpid, SIGTERM); + waitpid(sshpid, NULL, 0); + } + + _exit(1); +} + +/* ARGSUSED */ +static void +cmd_interrupt(int signo) +{ + const char msg[] = "\rInterrupt \n"; + int olderrno = errno; + + (void)write(STDERR_FILENO, msg, sizeof(msg) - 1); + interrupted = 1; + errno = olderrno; +} + +static void +help(void) +{ + printf("Available commands:\n" + "bye Quit sftp\n" + "cd path Change remote directory to 'path'\n" + "chgrp grp path Change group of file 'path' to 'grp'\n" + "chmod mode path Change permissions of file 'path' to 'mode'\n" + "chown own path Change owner of file 'path' to 'own'\n" + "df [-hi] [path] Display statistics for current directory or\n" + " filesystem containing 'path'\n" + "exit Quit sftp\n" + "get [-Ppr] remote [local] Download file\n" + "reget remote [local] Resume download file\n" + "reput [local] remote Resume upload file\n" + "help Display this help text\n" + "lcd path Change local directory to 'path'\n" + "lls [ls-options [path]] Display local directory listing\n" + "lmkdir path Create local directory\n" + "ln [-s] oldpath newpath Link remote file (-s for symlink)\n" + "lpwd Print local working directory\n" + "ls [-1afhlnrSt] [path] Display remote directory listing\n" + "lumask umask Set local umask to 'umask'\n" + "mkdir path Create remote directory\n" + "progress Toggle display of progress meter\n" + "put [-Ppr] local [remote] Upload file\n" + "pwd Display remote working directory\n" + "quit Quit sftp\n" + "rename oldpath newpath Rename remote file\n" + "rm path Delete remote file\n" + "rmdir path Remove remote directory\n" + "symlink oldpath newpath Symlink remote file\n" + "version Show SFTP version\n" + "!command Execute 'command' in local shell\n" + "! Escape to local shell\n" + "? Synonym for help\n"); +} + +static void +local_do_shell(const char *args) +{ + int status; + char *shell; + pid_t pid; + + if (!*args) + args = NULL; + + if ((shell = getenv("SHELL")) == NULL || *shell == '\0') + shell = _PATH_BSHELL; + + if ((pid = fork()) == -1) + fatal("Couldn't fork: %s", strerror(errno)); + + if (pid == 0) { + /* XXX: child has pipe fds to ssh subproc open - issue? */ + if (args) { + debug3("Executing %s -c \"%s\"", shell, args); + execl(shell, shell, "-c", args, (char *)NULL); + } else { + debug3("Executing %s", shell); + execl(shell, shell, (char *)NULL); + } + fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell, + strerror(errno)); + _exit(1); + } + while (waitpid(pid, &status, 0) == -1) + if (errno != EINTR) + fatal("Couldn't wait for child: %s", strerror(errno)); + if (!WIFEXITED(status)) + error("Shell exited abnormally"); + else if (WEXITSTATUS(status)) + error("Shell exited with status %d", WEXITSTATUS(status)); +} + +static void +local_do_ls(const char *args) +{ + if (!args || !*args) + local_do_shell(_PATH_LS); + else { + int len = strlen(_PATH_LS " ") + strlen(args) + 1; + char *buf = xmalloc(len); + + /* XXX: quoting - rip quoting code from ftp? */ + snprintf(buf, len, _PATH_LS " %s", args); + local_do_shell(buf); + free(buf); + } +} + +/* Strip one path (usually the pwd) from the start of another */ +static char * +path_strip(char *path, char *strip) +{ + size_t len; + + if (strip == NULL) + return (xstrdup(path)); + + len = strlen(strip); + if (strncmp(path, strip, len) == 0) { + if (strip[len - 1] != '/' && path[len] == '/') + len++; + return (xstrdup(path + len)); + } + + return (xstrdup(path)); +} + +static char * +make_absolute(char *p, char *pwd) +{ + char *abs_str; + + /* Derelativise */ + if (p && p[0] != '/') { + abs_str = path_append(pwd, p); + free(p); + return(abs_str); + } else + return(p); +} + +static int +parse_getput_flags(const char *cmd, char **argv, int argc, + int *aflag, int *fflag, int *pflag, int *rflag) +{ + extern int opterr, optind, optopt, optreset; + int ch; + + optind = optreset = 1; + opterr = 0; + + *aflag = *fflag = *rflag = *pflag = 0; + while ((ch = getopt(argc, argv, "afPpRr")) != -1) { + switch (ch) { + case 'a': + *aflag = 1; + break; + case 'f': + *fflag = 1; + break; + case 'p': + case 'P': + *pflag = 1; + break; + case 'r': + case 'R': + *rflag = 1; + break; + default: + error("%s: Invalid flag -%c", cmd, optopt); + return -1; + } + } + + return optind; +} + +static int +parse_link_flags(const char *cmd, char **argv, int argc, int *sflag) +{ + extern int opterr, optind, optopt, optreset; + int ch; + + optind = optreset = 1; + opterr = 0; + + *sflag = 0; + while ((ch = getopt(argc, argv, "s")) != -1) { + switch (ch) { + case 's': + *sflag = 1; + break; + default: + error("%s: Invalid flag -%c", cmd, optopt); + return -1; + } + } + + return optind; +} + +static int +parse_rename_flags(const char *cmd, char **argv, int argc, int *lflag) +{ + extern int opterr, optind, optopt, optreset; + int ch; + + optind = optreset = 1; + opterr = 0; + + *lflag = 0; + while ((ch = getopt(argc, argv, "l")) != -1) { + switch (ch) { + case 'l': + *lflag = 1; + break; + default: + error("%s: Invalid flag -%c", cmd, optopt); + return -1; + } + } + + return optind; +} + +static int +parse_ls_flags(char **argv, int argc, int *lflag) +{ + extern int opterr, optind, optopt, optreset; + int ch; + + optind = optreset = 1; + opterr = 0; + + *lflag = LS_NAME_SORT; + while ((ch = getopt(argc, argv, "1Safhlnrt")) != -1) { + switch (ch) { + case '1': + *lflag &= ~VIEW_FLAGS; + *lflag |= LS_SHORT_VIEW; + break; + case 'S': + *lflag &= ~SORT_FLAGS; + *lflag |= LS_SIZE_SORT; + break; + case 'a': + *lflag |= LS_SHOW_ALL; + break; + case 'f': + *lflag &= ~SORT_FLAGS; + break; + case 'h': + *lflag |= LS_SI_UNITS; + break; + case 'l': + *lflag &= ~LS_SHORT_VIEW; + *lflag |= LS_LONG_VIEW; + break; + case 'n': + *lflag &= ~LS_SHORT_VIEW; + *lflag |= LS_NUMERIC_VIEW|LS_LONG_VIEW; + break; + case 'r': + *lflag |= LS_REVERSE_SORT; + break; + case 't': + *lflag &= ~SORT_FLAGS; + *lflag |= LS_TIME_SORT; + break; + default: + error("ls: Invalid flag -%c", optopt); + return -1; + } + } + + return optind; +} + +static int +parse_df_flags(const char *cmd, char **argv, int argc, int *hflag, int *iflag) +{ + extern int opterr, optind, optopt, optreset; + int ch; + + optind = optreset = 1; + opterr = 0; + + *hflag = *iflag = 0; + while ((ch = getopt(argc, argv, "hi")) != -1) { + switch (ch) { + case 'h': + *hflag = 1; + break; + case 'i': + *iflag = 1; + break; + default: + error("%s: Invalid flag -%c", cmd, optopt); + return -1; + } + } + + return optind; +} + +static int +parse_no_flags(const char *cmd, char **argv, int argc) +{ + extern int opterr, optind, optopt, optreset; + int ch; + + optind = optreset = 1; + opterr = 0; + + while ((ch = getopt(argc, argv, "")) != -1) { + switch (ch) { + default: + error("%s: Invalid flag -%c", cmd, optopt); + return -1; + } + } + + return optind; +} + +static int +is_dir(char *path) +{ + struct stat sb; + + /* XXX: report errors? */ + if (stat(path, &sb) == -1) + return(0); + + return(S_ISDIR(sb.st_mode)); +} + +static int +remote_is_dir(struct sftp_conn *conn, char *path) +{ + Attrib *a; + + /* XXX: report errors? */ + if ((a = do_stat(conn, path, 1)) == NULL) + return(0); + if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) + return(0); + return(S_ISDIR(a->perm)); +} + +/* Check whether path returned from glob(..., GLOB_MARK, ...) is a directory */ +static int +pathname_is_dir(char *pathname) +{ + size_t l = strlen(pathname); + + return l > 0 && pathname[l - 1] == '/'; +} + +static int +process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, + int pflag, int rflag, int resume, int fflag) +{ + char *abs_src = NULL; + char *abs_dst = NULL; + glob_t g; + char *filename, *tmp=NULL; + int i, r, err = 0; + + abs_src = xstrdup(src); + abs_src = make_absolute(abs_src, pwd); + memset(&g, 0, sizeof(g)); + + debug3("Looking up %s", abs_src); + if ((r = remote_glob(conn, abs_src, GLOB_MARK, NULL, &g)) != 0) { + if (r == GLOB_NOSPACE) { + error("Too many matches for \"%s\".", abs_src); + } else { + error("File \"%s\" not found.", abs_src); + } + err = -1; + goto out; + } + + /* + * If multiple matches then dst must be a directory or + * unspecified. + */ + if (g.gl_matchc > 1 && dst != NULL && !is_dir(dst)) { + error("Multiple source paths, but destination " + "\"%s\" is not a directory", dst); + err = -1; + goto out; + } + + for (i = 0; g.gl_pathv[i] && !interrupted; i++) { + tmp = xstrdup(g.gl_pathv[i]); + if ((filename = basename(tmp)) == NULL) { + error("basename %s: %s", tmp, strerror(errno)); + free(tmp); + err = -1; + goto out; + } + + if (g.gl_matchc == 1 && dst) { + if (is_dir(dst)) { + abs_dst = path_append(dst, filename); + } else { + abs_dst = xstrdup(dst); + } + } else if (dst) { + abs_dst = path_append(dst, filename); + } else { + abs_dst = xstrdup(filename); + } + free(tmp); + + resume |= global_aflag; + if (!quiet && resume) + printf("Resuming %s to %s\n", g.gl_pathv[i], abs_dst); + else if (!quiet && !resume) + printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst); + if (pathname_is_dir(g.gl_pathv[i]) && (rflag || global_rflag)) { + if (download_dir(conn, g.gl_pathv[i], abs_dst, NULL, + pflag || global_pflag, 1, resume, + fflag || global_fflag) == -1) + err = -1; + } else { + if (do_download(conn, g.gl_pathv[i], abs_dst, NULL, + pflag || global_pflag, resume, + fflag || global_fflag) == -1) + err = -1; + } + free(abs_dst); + abs_dst = NULL; + } + +out: + free(abs_src); + globfree(&g); + return(err); +} + +static int +process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, + int pflag, int rflag, int resume, int fflag) +{ + char *tmp_dst = NULL; + char *abs_dst = NULL; + char *tmp = NULL, *filename = NULL; + glob_t g; + int err = 0; + int i, dst_is_dir = 1; + struct stat sb; + + if (dst) { + tmp_dst = xstrdup(dst); + tmp_dst = make_absolute(tmp_dst, pwd); + } + + memset(&g, 0, sizeof(g)); + debug3("Looking up %s", src); + if (glob(src, GLOB_NOCHECK | GLOB_MARK, NULL, &g)) { + error("File \"%s\" not found.", src); + err = -1; + goto out; + } + + /* If we aren't fetching to pwd then stash this status for later */ + if (tmp_dst != NULL) + dst_is_dir = remote_is_dir(conn, tmp_dst); + + /* If multiple matches, dst may be directory or unspecified */ + if (g.gl_matchc > 1 && tmp_dst && !dst_is_dir) { + error("Multiple paths match, but destination " + "\"%s\" is not a directory", tmp_dst); + err = -1; + goto out; + } + + for (i = 0; g.gl_pathv[i] && !interrupted; i++) { + if (stat(g.gl_pathv[i], &sb) == -1) { + err = -1; + error("stat %s: %s", g.gl_pathv[i], strerror(errno)); + continue; + } + + tmp = xstrdup(g.gl_pathv[i]); + if ((filename = basename(tmp)) == NULL) { + error("basename %s: %s", tmp, strerror(errno)); + free(tmp); + err = -1; + goto out; + } + + if (g.gl_matchc == 1 && tmp_dst) { + /* If directory specified, append filename */ + if (dst_is_dir) + abs_dst = path_append(tmp_dst, filename); + else + abs_dst = xstrdup(tmp_dst); + } else if (tmp_dst) { + abs_dst = path_append(tmp_dst, filename); + } else { + abs_dst = make_absolute(xstrdup(filename), pwd); + } + free(tmp); + + resume |= global_aflag; + if (!quiet && resume) + printf("Resuming upload of %s to %s\n", g.gl_pathv[i], + abs_dst); + else if (!quiet && !resume) + printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst); + if (pathname_is_dir(g.gl_pathv[i]) && (rflag || global_rflag)) { + if (upload_dir(conn, g.gl_pathv[i], abs_dst, + pflag || global_pflag, 1, resume, + fflag || global_fflag) == -1) + err = -1; + } else { + if (do_upload(conn, g.gl_pathv[i], abs_dst, + pflag || global_pflag, resume, + fflag || global_fflag) == -1) + err = -1; + } + } + +out: + free(abs_dst); + free(tmp_dst); + globfree(&g); + return(err); +} + +static int +sdirent_comp(const void *aa, const void *bb) +{ + SFTP_DIRENT *a = *(SFTP_DIRENT **)aa; + SFTP_DIRENT *b = *(SFTP_DIRENT **)bb; + int rmul = sort_flag & LS_REVERSE_SORT ? -1 : 1; + +#define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1)) + if (sort_flag & LS_NAME_SORT) + return (rmul * strcmp(a->filename, b->filename)); + else if (sort_flag & LS_TIME_SORT) + return (rmul * NCMP(a->a.mtime, b->a.mtime)); + else if (sort_flag & LS_SIZE_SORT) + return (rmul * NCMP(a->a.size, b->a.size)); + + fatal("Unknown ls sort type"); +} + +/* sftp ls.1 replacement for directories */ +static int +do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag) +{ + int n; + u_int c = 1, colspace = 0, columns = 1; + SFTP_DIRENT **d; + + if ((n = do_readdir(conn, path, &d)) != 0) + return (n); + + if (!(lflag & LS_SHORT_VIEW)) { + u_int m = 0, width = 80; + struct winsize ws; + char *tmp; + + /* Count entries for sort and find longest filename */ + for (n = 0; d[n] != NULL; n++) { + if (d[n]->filename[0] != '.' || (lflag & LS_SHOW_ALL)) + m = MAX(m, strlen(d[n]->filename)); + } + + /* Add any subpath that also needs to be counted */ + tmp = path_strip(path, strip_path); + m += strlen(tmp); + free(tmp); + + if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1) + width = ws.ws_col; + + columns = width / (m + 2); + columns = MAX(columns, 1); + colspace = width / columns; + colspace = MIN(colspace, width); + } + + if (lflag & SORT_FLAGS) { + for (n = 0; d[n] != NULL; n++) + ; /* count entries */ + sort_flag = lflag & (SORT_FLAGS|LS_REVERSE_SORT); + qsort(d, n, sizeof(*d), sdirent_comp); + } + + for (n = 0; d[n] != NULL && !interrupted; n++) { + char *tmp, *fname; + + if (d[n]->filename[0] == '.' && !(lflag & LS_SHOW_ALL)) + continue; + + tmp = path_append(path, d[n]->filename); + fname = path_strip(tmp, strip_path); + free(tmp); + + if (lflag & LS_LONG_VIEW) { + if (lflag & (LS_NUMERIC_VIEW|LS_SI_UNITS)) { + char *lname; + struct stat sb; + + memset(&sb, 0, sizeof(sb)); + attrib_to_stat(&d[n]->a, &sb); + lname = ls_file(fname, &sb, 1, + (lflag & LS_SI_UNITS)); + printf("%s\n", lname); + free(lname); + } else + printf("%s\n", d[n]->longname); + } else { + printf("%-*s", colspace, fname); + if (c >= columns) { + printf("\n"); + c = 1; + } else + c++; + } + + free(fname); + } + + if (!(lflag & LS_LONG_VIEW) && (c != 1)) + printf("\n"); + + free_sftp_dirents(d); + return (0); +} + +/* sftp ls.1 replacement which handles path globs */ +static int +do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path, + int lflag) +{ + char *fname, *lname; + glob_t g; + int err, r; + struct winsize ws; + u_int i, c = 1, colspace = 0, columns = 1, m = 0, width = 80; + + memset(&g, 0, sizeof(g)); + + if ((r = remote_glob(conn, path, + GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE|GLOB_KEEPSTAT|GLOB_NOSORT, + NULL, &g)) != 0 || + (g.gl_pathc && !g.gl_matchc)) { + if (g.gl_pathc) + globfree(&g); + if (r == GLOB_NOSPACE) { + error("Can't ls: Too many matches for \"%s\"", path); + } else { + error("Can't ls: \"%s\" not found", path); + } + return -1; + } + + if (interrupted) + goto out; + + /* + * If the glob returns a single match and it is a directory, + * then just list its contents. + */ + if (g.gl_matchc == 1 && g.gl_statv[0] != NULL && + S_ISDIR(g.gl_statv[0]->st_mode)) { + err = do_ls_dir(conn, g.gl_pathv[0], strip_path, lflag); + globfree(&g); + return err; + } + + if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1) + width = ws.ws_col; + + if (!(lflag & LS_SHORT_VIEW)) { + /* Count entries for sort and find longest filename */ + for (i = 0; g.gl_pathv[i]; i++) + m = MAX(m, strlen(g.gl_pathv[i])); + + columns = width / (m + 2); + columns = MAX(columns, 1); + colspace = width / columns; + } + + for (i = 0; g.gl_pathv[i] && !interrupted; i++) { + fname = path_strip(g.gl_pathv[i], strip_path); + if (lflag & LS_LONG_VIEW) { + if (g.gl_statv[i] == NULL) { + error("no stat information for %s", fname); + continue; + } + lname = ls_file(fname, g.gl_statv[i], 1, + (lflag & LS_SI_UNITS)); + printf("%s\n", lname); + free(lname); + } else { + printf("%-*s", colspace, fname); + if (c >= columns) { + printf("\n"); + c = 1; + } else + c++; + } + free(fname); + } + + if (!(lflag & LS_LONG_VIEW) && (c != 1)) + printf("\n"); + + out: + if (g.gl_pathc) + globfree(&g); + + return 0; +} + +static int +do_df(struct sftp_conn *conn, char *path, int hflag, int iflag) +{ + struct sftp_statvfs st; + char s_used[FMT_SCALED_STRSIZE]; + char s_avail[FMT_SCALED_STRSIZE]; + char s_root[FMT_SCALED_STRSIZE]; + char s_total[FMT_SCALED_STRSIZE]; + unsigned long long ffree; + + if (do_statvfs(conn, path, &st, 1) == -1) + return -1; + if (iflag) { + ffree = st.f_files ? (100 * (st.f_files - st.f_ffree) / st.f_files) : 0; + printf(" Inodes Used Avail " + "(root) %%Capacity\n"); + printf("%11llu %11llu %11llu %11llu %3llu%%\n", + (unsigned long long)st.f_files, + (unsigned long long)(st.f_files - st.f_ffree), + (unsigned long long)st.f_favail, + (unsigned long long)st.f_ffree, ffree); + } else if (hflag) { + strlcpy(s_used, "error", sizeof(s_used)); + strlcpy(s_avail, "error", sizeof(s_avail)); + strlcpy(s_root, "error", sizeof(s_root)); + strlcpy(s_total, "error", sizeof(s_total)); + fmt_scaled((st.f_blocks - st.f_bfree) * st.f_frsize, s_used); + fmt_scaled(st.f_bavail * st.f_frsize, s_avail); + fmt_scaled(st.f_bfree * st.f_frsize, s_root); + fmt_scaled(st.f_blocks * st.f_frsize, s_total); + printf(" Size Used Avail (root) %%Capacity\n"); + printf("%7sB %7sB %7sB %7sB %3llu%%\n", + s_total, s_used, s_avail, s_root, + (unsigned long long)(100 * (st.f_blocks - st.f_bfree) / + st.f_blocks)); + } else { + printf(" Size Used Avail " + "(root) %%Capacity\n"); + printf("%12llu %12llu %12llu %12llu %3llu%%\n", + (unsigned long long)(st.f_frsize * st.f_blocks / 1024), + (unsigned long long)(st.f_frsize * + (st.f_blocks - st.f_bfree) / 1024), + (unsigned long long)(st.f_frsize * st.f_bavail / 1024), + (unsigned long long)(st.f_frsize * st.f_bfree / 1024), + (unsigned long long)(100 * (st.f_blocks - st.f_bfree) / + st.f_blocks)); + } + return 0; +} + +/* + * Undo escaping of glob sequences in place. Used to undo extra escaping + * applied in makeargv() when the string is destined for a function that + * does not glob it. + */ +static void +undo_glob_escape(char *s) +{ + size_t i, j; + + for (i = j = 0;;) { + if (s[i] == '\0') { + s[j] = '\0'; + return; + } + if (s[i] != '\\') { + s[j++] = s[i++]; + continue; + } + /* s[i] == '\\' */ + ++i; + switch (s[i]) { + case '?': + case '[': + case '*': + case '\\': + s[j++] = s[i++]; + break; + case '\0': + s[j++] = '\\'; + s[j] = '\0'; + return; + default: + s[j++] = '\\'; + s[j++] = s[i++]; + break; + } + } +} + +/* + * Split a string into an argument vector using sh(1)-style quoting, + * comment and escaping rules, but with some tweaks to handle glob(3) + * wildcards. + * The "sloppy" flag allows for recovery from missing terminating quote, for + * use in parsing incomplete commandlines during tab autocompletion. + * + * Returns NULL on error or a NULL-terminated array of arguments. + * + * If "lastquote" is not NULL, the quoting character used for the last + * argument is placed in *lastquote ("\0", "'" or "\""). + * + * If "terminated" is not NULL, *terminated will be set to 1 when the + * last argument's quote has been properly terminated or 0 otherwise. + * This parameter is only of use if "sloppy" is set. + */ +#define MAXARGS 128 +#define MAXARGLEN 8192 +static char ** +makeargv(const char *arg, int *argcp, int sloppy, char *lastquote, + u_int *terminated) +{ + int argc, quot; + size_t i, j; + static char argvs[MAXARGLEN]; + static char *argv[MAXARGS + 1]; + enum { MA_START, MA_SQUOTE, MA_DQUOTE, MA_UNQUOTED } state, q; + + *argcp = argc = 0; + if (strlen(arg) > sizeof(argvs) - 1) { + args_too_longs: + error("string too long"); + return NULL; + } + if (terminated != NULL) + *terminated = 1; + if (lastquote != NULL) + *lastquote = '\0'; + state = MA_START; + i = j = 0; + for (;;) { + if ((size_t)argc >= sizeof(argv) / sizeof(*argv)){ + error("Too many arguments."); + return NULL; + } + if (isspace((unsigned char)arg[i])) { + if (state == MA_UNQUOTED) { + /* Terminate current argument */ + argvs[j++] = '\0'; + argc++; + state = MA_START; + } else if (state != MA_START) + argvs[j++] = arg[i]; + } else if (arg[i] == '"' || arg[i] == '\'') { + q = arg[i] == '"' ? MA_DQUOTE : MA_SQUOTE; + if (state == MA_START) { + argv[argc] = argvs + j; + state = q; + if (lastquote != NULL) + *lastquote = arg[i]; + } else if (state == MA_UNQUOTED) + state = q; + else if (state == q) + state = MA_UNQUOTED; + else + argvs[j++] = arg[i]; + } else if (arg[i] == '\\') { + if (state == MA_SQUOTE || state == MA_DQUOTE) { + quot = state == MA_SQUOTE ? '\'' : '"'; + /* Unescape quote we are in */ + /* XXX support \n and friends? */ + if (arg[i + 1] == quot) { + i++; + argvs[j++] = arg[i]; + } else if (arg[i + 1] == '?' || + arg[i + 1] == '[' || arg[i + 1] == '*') { + /* + * Special case for sftp: append + * double-escaped glob sequence - + * glob will undo one level of + * escaping. NB. string can grow here. + */ + if (j >= sizeof(argvs) - 5) + goto args_too_longs; + argvs[j++] = '\\'; + argvs[j++] = arg[i++]; + argvs[j++] = '\\'; + argvs[j++] = arg[i]; + } else { + argvs[j++] = arg[i++]; + argvs[j++] = arg[i]; + } + } else { + if (state == MA_START) { + argv[argc] = argvs + j; + state = MA_UNQUOTED; + if (lastquote != NULL) + *lastquote = '\0'; + } + if (arg[i + 1] == '?' || arg[i + 1] == '[' || + arg[i + 1] == '*' || arg[i + 1] == '\\') { + /* + * Special case for sftp: append + * escaped glob sequence - + * glob will undo one level of + * escaping. + */ + argvs[j++] = arg[i++]; + argvs[j++] = arg[i]; + } else { + /* Unescape everything */ + /* XXX support \n and friends? */ + i++; + argvs[j++] = arg[i]; + } + } + } else if (arg[i] == '#') { + if (state == MA_SQUOTE || state == MA_DQUOTE) + argvs[j++] = arg[i]; + else + goto string_done; + } else if (arg[i] == '\0') { + if (state == MA_SQUOTE || state == MA_DQUOTE) { + if (sloppy) { + state = MA_UNQUOTED; + if (terminated != NULL) + *terminated = 0; + goto string_done; + } + error("Unterminated quoted argument"); + return NULL; + } + string_done: + if (state == MA_UNQUOTED) { + argvs[j++] = '\0'; + argc++; + } + break; + } else { + if (state == MA_START) { + argv[argc] = argvs + j; + state = MA_UNQUOTED; + if (lastquote != NULL) + *lastquote = '\0'; + } + if ((state == MA_SQUOTE || state == MA_DQUOTE) && + (arg[i] == '?' || arg[i] == '[' || arg[i] == '*')) { + /* + * Special case for sftp: escape quoted + * glob(3) wildcards. NB. string can grow + * here. + */ + if (j >= sizeof(argvs) - 3) + goto args_too_longs; + argvs[j++] = '\\'; + argvs[j++] = arg[i]; + } else + argvs[j++] = arg[i]; + } + i++; + } + *argcp = argc; + return argv; +} + +static int +parse_args(const char **cpp, int *ignore_errors, int *aflag, + int *fflag, int *hflag, int *iflag, int *lflag, int *pflag, + int *rflag, int *sflag, + unsigned long *n_arg, char **path1, char **path2) +{ + const char *cmd, *cp = *cpp; + char *cp2, **argv; + int base = 0; + long l; + int i, cmdnum, optidx, argc; + + /* Skip leading whitespace */ + cp = cp + strspn(cp, WHITESPACE); + + /* Check for leading '-' (disable error processing) */ + *ignore_errors = 0; + if (*cp == '-') { + *ignore_errors = 1; + cp++; + cp = cp + strspn(cp, WHITESPACE); + } + + /* Ignore blank lines and lines which begin with comment '#' char */ + if (*cp == '\0' || *cp == '#') + return (0); + + if ((argv = makeargv(cp, &argc, 0, NULL, NULL)) == NULL) + return -1; + + /* Figure out which command we have */ + for (i = 0; cmds[i].c != NULL; i++) { + if (argv[0] != NULL && strcasecmp(cmds[i].c, argv[0]) == 0) + break; + } + cmdnum = cmds[i].n; + cmd = cmds[i].c; + + /* Special case */ + if (*cp == '!') { + cp++; + cmdnum = I_SHELL; + } else if (cmdnum == -1) { + error("Invalid command."); + return -1; + } + + /* Get arguments and parse flags */ + *aflag = *fflag = *hflag = *iflag = *lflag = *pflag = 0; + *rflag = *sflag = 0; + *path1 = *path2 = NULL; + optidx = 1; + switch (cmdnum) { + case I_GET: + case I_REGET: + case I_REPUT: + case I_PUT: + if ((optidx = parse_getput_flags(cmd, argv, argc, + aflag, fflag, pflag, rflag)) == -1) + return -1; + /* Get first pathname (mandatory) */ + if (argc - optidx < 1) { + error("You must specify at least one path after a " + "%s command.", cmd); + return -1; + } + *path1 = xstrdup(argv[optidx]); + /* Get second pathname (optional) */ + if (argc - optidx > 1) { + *path2 = xstrdup(argv[optidx + 1]); + /* Destination is not globbed */ + undo_glob_escape(*path2); + } + break; + case I_LINK: + if ((optidx = parse_link_flags(cmd, argv, argc, sflag)) == -1) + return -1; + goto parse_two_paths; + case I_RENAME: + if ((optidx = parse_rename_flags(cmd, argv, argc, lflag)) == -1) + return -1; + goto parse_two_paths; + case I_SYMLINK: + if ((optidx = parse_no_flags(cmd, argv, argc)) == -1) + return -1; + parse_two_paths: + if (argc - optidx < 2) { + error("You must specify two paths after a %s " + "command.", cmd); + return -1; + } + *path1 = xstrdup(argv[optidx]); + *path2 = xstrdup(argv[optidx + 1]); + /* Paths are not globbed */ + undo_glob_escape(*path1); + undo_glob_escape(*path2); + break; + case I_RM: + case I_MKDIR: + case I_RMDIR: + case I_CHDIR: + case I_LCHDIR: + case I_LMKDIR: + if ((optidx = parse_no_flags(cmd, argv, argc)) == -1) + return -1; + /* Get pathname (mandatory) */ + if (argc - optidx < 1) { + error("You must specify a path after a %s command.", + cmd); + return -1; + } + *path1 = xstrdup(argv[optidx]); + /* Only "rm" globs */ + if (cmdnum != I_RM) + undo_glob_escape(*path1); + break; + case I_DF: + if ((optidx = parse_df_flags(cmd, argv, argc, hflag, + iflag)) == -1) + return -1; + /* Default to current directory if no path specified */ + if (argc - optidx < 1) + *path1 = NULL; + else { + *path1 = xstrdup(argv[optidx]); + undo_glob_escape(*path1); + } + break; + case I_LS: + if ((optidx = parse_ls_flags(argv, argc, lflag)) == -1) + return(-1); + /* Path is optional */ + if (argc - optidx > 0) + *path1 = xstrdup(argv[optidx]); + break; + case I_LLS: + /* Skip ls command and following whitespace */ + cp = cp + strlen(cmd) + strspn(cp, WHITESPACE); + case I_SHELL: + /* Uses the rest of the line */ + break; + case I_LUMASK: + case I_CHMOD: + base = 8; + case I_CHOWN: + case I_CHGRP: + if ((optidx = parse_no_flags(cmd, argv, argc)) == -1) + return -1; + /* Get numeric arg (mandatory) */ + if (argc - optidx < 1) + goto need_num_arg; + errno = 0; + l = strtol(argv[optidx], &cp2, base); + if (cp2 == argv[optidx] || *cp2 != '\0' || + ((l == LONG_MIN || l == LONG_MAX) && errno == ERANGE) || + l < 0) { + need_num_arg: + error("You must supply a numeric argument " + "to the %s command.", cmd); + return -1; + } + *n_arg = l; + if (cmdnum == I_LUMASK) + break; + /* Get pathname (mandatory) */ + if (argc - optidx < 2) { + error("You must specify a path after a %s command.", + cmd); + return -1; + } + *path1 = xstrdup(argv[optidx + 1]); + break; + case I_QUIT: + case I_PWD: + case I_LPWD: + case I_HELP: + case I_VERSION: + case I_PROGRESS: + if ((optidx = parse_no_flags(cmd, argv, argc)) == -1) + return -1; + break; + default: + fatal("Command not implemented"); + } + + *cpp = cp; + return(cmdnum); +} + +static int +parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd, + int err_abort) +{ + char *path1, *path2, *tmp; + int ignore_errors = 0, aflag = 0, fflag = 0, hflag = 0, + iflag = 0; + int lflag = 0, pflag = 0, rflag = 0, sflag = 0; + int cmdnum, i; + unsigned long n_arg = 0; + Attrib a, *aa; + char path_buf[MAXPATHLEN]; + int err = 0; + glob_t g; + + path1 = path2 = NULL; + cmdnum = parse_args(&cmd, &ignore_errors, &aflag, &fflag, &hflag, + &iflag, &lflag, &pflag, &rflag, &sflag, &n_arg, &path1, &path2); + if (ignore_errors != 0) + err_abort = 0; + + memset(&g, 0, sizeof(g)); + + /* Perform command */ + switch (cmdnum) { + case 0: + /* Blank line */ + break; + case -1: + /* Unrecognized command */ + err = -1; + break; + case I_REGET: + aflag = 1; + /* FALLTHROUGH */ + case I_GET: + err = process_get(conn, path1, path2, *pwd, pflag, + rflag, aflag, fflag); + break; + case I_REPUT: + aflag = 1; + /* FALLTHROUGH */ + case I_PUT: + err = process_put(conn, path1, path2, *pwd, pflag, + rflag, aflag, fflag); + break; + case I_RENAME: + path1 = make_absolute(path1, *pwd); + path2 = make_absolute(path2, *pwd); + err = do_rename(conn, path1, path2, lflag); + break; + case I_SYMLINK: + sflag = 1; + case I_LINK: + if (!sflag) + path1 = make_absolute(path1, *pwd); + path2 = make_absolute(path2, *pwd); + err = (sflag ? do_symlink : do_hardlink)(conn, path1, path2); + break; + case I_RM: + path1 = make_absolute(path1, *pwd); + remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g); + for (i = 0; g.gl_pathv[i] && !interrupted; i++) { + if (!quiet) + printf("Removing %s\n", g.gl_pathv[i]); + err = do_rm(conn, g.gl_pathv[i]); + if (err != 0 && err_abort) + break; + } + break; + case I_MKDIR: + path1 = make_absolute(path1, *pwd); + attrib_clear(&a); + a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS; + a.perm = 0777; + err = do_mkdir(conn, path1, &a, 1); + break; + case I_RMDIR: + path1 = make_absolute(path1, *pwd); + err = do_rmdir(conn, path1); + break; + case I_CHDIR: + path1 = make_absolute(path1, *pwd); + if ((tmp = do_realpath(conn, path1)) == NULL) { + err = 1; + break; + } + if ((aa = do_stat(conn, tmp, 0)) == NULL) { + free(tmp); + err = 1; + break; + } + if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) { + error("Can't change directory: Can't check target"); + free(tmp); + err = 1; + break; + } + if (!S_ISDIR(aa->perm)) { + error("Can't change directory: \"%s\" is not " + "a directory", tmp); + free(tmp); + err = 1; + break; + } + free(*pwd); + *pwd = tmp; + break; + case I_LS: + if (!path1) { + do_ls_dir(conn, *pwd, *pwd, lflag); + break; + } + + /* Strip pwd off beginning of non-absolute paths */ + tmp = NULL; + if (*path1 != '/') + tmp = *pwd; + + path1 = make_absolute(path1, *pwd); + err = do_globbed_ls(conn, path1, tmp, lflag); + break; + case I_DF: + /* Default to current directory if no path specified */ + if (path1 == NULL) + path1 = xstrdup(*pwd); + path1 = make_absolute(path1, *pwd); + err = do_df(conn, path1, hflag, iflag); + break; + case I_LCHDIR: + if (chdir(path1) == -1) { + error("Couldn't change local directory to " + "\"%s\": %s", path1, strerror(errno)); + err = 1; + } + break; + case I_LMKDIR: + if (mkdir(path1, 0777) == -1) { + error("Couldn't create local directory " + "\"%s\": %s", path1, strerror(errno)); + err = 1; + } + break; + case I_LLS: + local_do_ls(cmd); + break; + case I_SHELL: + local_do_shell(cmd); + break; + case I_LUMASK: + umask(n_arg); + printf("Local umask: %03lo\n", n_arg); + break; + case I_CHMOD: + path1 = make_absolute(path1, *pwd); + attrib_clear(&a); + a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS; + a.perm = n_arg; + remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g); + for (i = 0; g.gl_pathv[i] && !interrupted; i++) { + if (!quiet) + printf("Changing mode on %s\n", g.gl_pathv[i]); + err = do_setstat(conn, g.gl_pathv[i], &a); + if (err != 0 && err_abort) + break; + } + break; + case I_CHOWN: + case I_CHGRP: + path1 = make_absolute(path1, *pwd); + remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g); + for (i = 0; g.gl_pathv[i] && !interrupted; i++) { + if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) { + if (err_abort) { + err = -1; + break; + } else + continue; + } + if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) { + error("Can't get current ownership of " + "remote file \"%s\"", g.gl_pathv[i]); + if (err_abort) { + err = -1; + break; + } else + continue; + } + aa->flags &= SSH2_FILEXFER_ATTR_UIDGID; + if (cmdnum == I_CHOWN) { + if (!quiet) + printf("Changing owner on %s\n", + g.gl_pathv[i]); + aa->uid = n_arg; + } else { + if (!quiet) + printf("Changing group on %s\n", + g.gl_pathv[i]); + aa->gid = n_arg; + } + err = do_setstat(conn, g.gl_pathv[i], aa); + if (err != 0 && err_abort) + break; + } + break; + case I_PWD: + printf("Remote working directory: %s\n", *pwd); + break; + case I_LPWD: + if (!getcwd(path_buf, sizeof(path_buf))) { + error("Couldn't get local cwd: %s", strerror(errno)); + err = -1; + break; + } + printf("Local working directory: %s\n", path_buf); + break; + case I_QUIT: + /* Processed below */ + break; + case I_HELP: + help(); + break; + case I_VERSION: + printf("SFTP protocol version %u\n", sftp_proto_version(conn)); + break; + case I_PROGRESS: + showprogress = !showprogress; + if (showprogress) + printf("Progress meter enabled\n"); + else + printf("Progress meter disabled\n"); + break; + default: + fatal("%d is not implemented", cmdnum); + } + + if (g.gl_pathc) + globfree(&g); + free(path1); + free(path2); + + /* If an unignored error occurs in batch mode we should abort. */ + if (err_abort && err != 0) + return (-1); + else if (cmdnum == I_QUIT) + return (1); + + return (0); +} + +#ifdef USE_LIBEDIT +static char * +prompt(EditLine *el) +{ + return ("sftp> "); +} + +/* Display entries in 'list' after skipping the first 'len' chars */ +static void +complete_display(char **list, u_int len) +{ + u_int y, m = 0, width = 80, columns = 1, colspace = 0, llen; + struct winsize ws; + char *tmp; + + /* Count entries for sort and find longest */ + for (y = 0; list[y]; y++) + m = MAX(m, strlen(list[y])); + + if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1) + width = ws.ws_col; + + m = m > len ? m - len : 0; + columns = width / (m + 2); + columns = MAX(columns, 1); + colspace = width / columns; + colspace = MIN(colspace, width); + + printf("\n"); + m = 1; + for (y = 0; list[y]; y++) { + llen = strlen(list[y]); + tmp = llen > len ? list[y] + len : ""; + printf("%-*s", colspace, tmp); + if (m >= columns) { + printf("\n"); + m = 1; + } else + m++; + } + printf("\n"); +} + +/* + * Given a "list" of words that begin with a common prefix of "word", + * attempt to find an autocompletion to extends "word" by the next + * characters common to all entries in "list". + */ +static char * +complete_ambiguous(const char *word, char **list, size_t count) +{ + if (word == NULL) + return NULL; + + if (count > 0) { + u_int y, matchlen = strlen(list[0]); + + /* Find length of common stem */ + for (y = 1; list[y]; y++) { + u_int x; + + for (x = 0; x < matchlen; x++) + if (list[0][x] != list[y][x]) + break; + + matchlen = x; + } + + if (matchlen > strlen(word)) { + char *tmp = xstrdup(list[0]); + + tmp[matchlen] = '\0'; + return tmp; + } + } + + return xstrdup(word); +} + +/* Autocomplete a sftp command */ +static int +complete_cmd_parse(EditLine *el, char *cmd, int lastarg, char quote, + int terminated) +{ + u_int y, count = 0, cmdlen, tmplen; + char *tmp, **list, argterm[3]; + const LineInfo *lf; + + list = xcalloc((sizeof(cmds) / sizeof(*cmds)) + 1, sizeof(char *)); + + /* No command specified: display all available commands */ + if (cmd == NULL) { + for (y = 0; cmds[y].c; y++) + list[count++] = xstrdup(cmds[y].c); + + list[count] = NULL; + complete_display(list, 0); + + for (y = 0; list[y] != NULL; y++) + free(list[y]); + free(list); + return count; + } + + /* Prepare subset of commands that start with "cmd" */ + cmdlen = strlen(cmd); + for (y = 0; cmds[y].c; y++) { + if (!strncasecmp(cmd, cmds[y].c, cmdlen)) + list[count++] = xstrdup(cmds[y].c); + } + list[count] = NULL; + + if (count == 0) { + free(list); + return 0; + } + + /* Complete ambigious command */ + tmp = complete_ambiguous(cmd, list, count); + if (count > 1) + complete_display(list, 0); + + for (y = 0; list[y]; y++) + free(list[y]); + free(list); + + if (tmp != NULL) { + tmplen = strlen(tmp); + cmdlen = strlen(cmd); + /* If cmd may be extended then do so */ + if (tmplen > cmdlen) + if (el_insertstr(el, tmp + cmdlen) == -1) + fatal("el_insertstr failed."); + lf = el_line(el); + /* Terminate argument cleanly */ + if (count == 1) { + y = 0; + if (!terminated) + argterm[y++] = quote; + if (lastarg || *(lf->cursor) != ' ') + argterm[y++] = ' '; + argterm[y] = '\0'; + if (y > 0 && el_insertstr(el, argterm) == -1) + fatal("el_insertstr failed."); + } + free(tmp); + } + + return count; +} + +/* + * Determine whether a particular sftp command's arguments (if any) + * represent local or remote files. + */ +static int +complete_is_remote(char *cmd) { + int i; + + if (cmd == NULL) + return -1; + + for (i = 0; cmds[i].c; i++) { + if (!strncasecmp(cmd, cmds[i].c, strlen(cmds[i].c))) + return cmds[i].t; + } + + return -1; +} + +/* Autocomplete a filename "file" */ +static int +complete_match(EditLine *el, struct sftp_conn *conn, char *remote_path, + char *file, int remote, int lastarg, char quote, int terminated) +{ + glob_t g; + char *tmp, *tmp2, ins[8]; + u_int i, hadglob, pwdlen, len, tmplen, filelen, cesc, isesc, isabs; + int clen; + const LineInfo *lf; + + /* Glob from "file" location */ + if (file == NULL) + tmp = xstrdup("*"); + else + xasprintf(&tmp, "%s*", file); + + /* Check if the path is absolute. */ + isabs = tmp[0] == '/'; + + memset(&g, 0, sizeof(g)); + if (remote != LOCAL) { + tmp = make_absolute(tmp, remote_path); + remote_glob(conn, tmp, GLOB_DOOFFS|GLOB_MARK, NULL, &g); + } else + glob(tmp, GLOB_DOOFFS|GLOB_MARK, NULL, &g); + + /* Determine length of pwd so we can trim completion display */ + for (hadglob = tmplen = pwdlen = 0; tmp[tmplen] != 0; tmplen++) { + /* Terminate counting on first unescaped glob metacharacter */ + if (tmp[tmplen] == '*' || tmp[tmplen] == '?') { + if (tmp[tmplen] != '*' || tmp[tmplen + 1] != '\0') + hadglob = 1; + break; + } + if (tmp[tmplen] == '\\' && tmp[tmplen + 1] != '\0') + tmplen++; + if (tmp[tmplen] == '/') + pwdlen = tmplen + 1; /* track last seen '/' */ + } + free(tmp); + tmp = NULL; + + if (g.gl_matchc == 0) + goto out; + + if (g.gl_matchc > 1) + complete_display(g.gl_pathv, pwdlen); + + /* Don't try to extend globs */ + if (file == NULL || hadglob) + goto out; + + tmp2 = complete_ambiguous(file, g.gl_pathv, g.gl_matchc); + tmp = path_strip(tmp2, isabs ? NULL : remote_path); + free(tmp2); + + if (tmp == NULL) + goto out; + + tmplen = strlen(tmp); + filelen = strlen(file); + + /* Count the number of escaped characters in the input string. */ + cesc = isesc = 0; + for (i = 0; i < filelen; i++) { + if (!isesc && file[i] == '\\' && i + 1 < filelen){ + isesc = 1; + cesc++; + } else + isesc = 0; + } + + if (tmplen > (filelen - cesc)) { + tmp2 = tmp + filelen - cesc; + len = strlen(tmp2); + /* quote argument on way out */ + for (i = 0; i < len; i += clen) { + if ((clen = mblen(tmp2 + i, len - i)) < 0 || + (size_t)clen > sizeof(ins) - 2) + fatal("invalid multibyte character"); + ins[0] = '\\'; + memcpy(ins + 1, tmp2 + i, clen); + ins[clen + 1] = '\0'; + switch (tmp2[i]) { + case '\'': + case '"': + case '\\': + case '\t': + case '[': + case ' ': + case '#': + case '*': + if (quote == '\0' || tmp2[i] == quote) { + if (el_insertstr(el, ins) == -1) + fatal("el_insertstr " + "failed."); + break; + } + /* FALLTHROUGH */ + default: + if (el_insertstr(el, ins + 1) == -1) + fatal("el_insertstr failed."); + break; + } + } + } + + lf = el_line(el); + if (g.gl_matchc == 1) { + i = 0; + if (!terminated && quote != '\0') + ins[i++] = quote; + if (*(lf->cursor - 1) != '/' && + (lastarg || *(lf->cursor) != ' ')) + ins[i++] = ' '; + ins[i] = '\0'; + if (i > 0 && el_insertstr(el, ins) == -1) + fatal("el_insertstr failed."); + } + free(tmp); + + out: + globfree(&g); + return g.gl_matchc; +} + +/* tab-completion hook function, called via libedit */ +static unsigned char +complete(EditLine *el, int ch) +{ + char **argv, *line, quote; + int argc, carg; + u_int cursor, len, terminated, ret = CC_ERROR; + const LineInfo *lf; + struct complete_ctx *complete_ctx; + + lf = el_line(el); + if (el_get(el, EL_CLIENTDATA, (void**)&complete_ctx) != 0) + fatal("%s: el_get failed", __func__); + + /* Figure out which argument the cursor points to */ + cursor = lf->cursor - lf->buffer; + line = (char *)xmalloc(cursor + 1); + memcpy(line, lf->buffer, cursor); + line[cursor] = '\0'; + argv = makeargv(line, &carg, 1, "e, &terminated); + free(line); + + /* Get all the arguments on the line */ + len = lf->lastchar - lf->buffer; + line = (char *)xmalloc(len + 1); + memcpy(line, lf->buffer, len); + line[len] = '\0'; + argv = makeargv(line, &argc, 1, NULL, NULL); + + /* Ensure cursor is at EOL or a argument boundary */ + if (line[cursor] != ' ' && line[cursor] != '\0' && + line[cursor] != '\n') { + free(line); + return ret; + } + + if (carg == 0) { + /* Show all available commands */ + complete_cmd_parse(el, NULL, argc == carg, '\0', 1); + ret = CC_REDISPLAY; + } else if (carg == 1 && cursor > 0 && line[cursor - 1] != ' ') { + /* Handle the command parsing */ + if (complete_cmd_parse(el, argv[0], argc == carg, + quote, terminated) != 0) + ret = CC_REDISPLAY; + } else if (carg >= 1) { + /* Handle file parsing */ + int remote = complete_is_remote(argv[0]); + char *filematch = NULL; + + if (carg > 1 && line[cursor-1] != ' ') + filematch = argv[carg - 1]; + + if (remote != 0 && + complete_match(el, complete_ctx->conn, + *complete_ctx->remote_pathp, filematch, + remote, carg == argc, quote, terminated) != 0) + ret = CC_REDISPLAY; + } + + free(line); + return ret; +} +#endif /* USE_LIBEDIT */ + +int +interactive_loop(struct sftp_conn *conn, char *file1, char *file2) +{ + char *remote_path; + char *dir = NULL; + char cmd[2048]; + int err, interactive; + EditLine *el = NULL; +#ifdef USE_LIBEDIT + History *hl = NULL; + HistEvent hev; + extern char *__progname; + struct complete_ctx complete_ctx; + + if (!batchmode && isatty(STDIN_FILENO)) { + if ((el = el_init(__progname, stdin, stdout, stderr)) == NULL) + fatal("Couldn't initialise editline"); + if ((hl = history_init()) == NULL) + fatal("Couldn't initialise editline history"); + history(hl, &hev, H_SETSIZE, 100); + el_set(el, EL_HIST, history, hl); + + el_set(el, EL_PROMPT, prompt); + el_set(el, EL_EDITOR, "emacs"); + el_set(el, EL_TERMINAL, NULL); + el_set(el, EL_SIGNAL, 1); + el_source(el, NULL); + + /* Tab Completion */ + el_set(el, EL_ADDFN, "ftp-complete", + "Context sensitive argument completion", complete); + complete_ctx.conn = conn; + complete_ctx.remote_pathp = &remote_path; + el_set(el, EL_CLIENTDATA, (void*)&complete_ctx); + el_set(el, EL_BIND, "^I", "ftp-complete", NULL); + /* enable ctrl-left-arrow and ctrl-right-arrow */ + el_set(el, EL_BIND, "\\e[1;5C", "em-next-word", NULL); + el_set(el, EL_BIND, "\\e[5C", "em-next-word", NULL); + el_set(el, EL_BIND, "\\e[1;5D", "ed-prev-word", NULL); + el_set(el, EL_BIND, "\\e\\e[D", "ed-prev-word", NULL); + /* make ^w match ksh behaviour */ + el_set(el, EL_BIND, "^w", "ed-delete-prev-word", NULL); + } +#endif /* USE_LIBEDIT */ + + remote_path = do_realpath(conn, "."); + if (remote_path == NULL) + fatal("Need cwd"); + + if (file1 != NULL) { + dir = xstrdup(file1); + dir = make_absolute(dir, remote_path); + + if (remote_is_dir(conn, dir) && file2 == NULL) { + if (!quiet) + printf("Changing to: %s\n", dir); + snprintf(cmd, sizeof cmd, "cd \"%s\"", dir); + if (parse_dispatch_command(conn, cmd, + &remote_path, 1) != 0) { + free(dir); + free(remote_path); + free(conn); + return (-1); + } + } else { + /* XXX this is wrong wrt quoting */ + snprintf(cmd, sizeof cmd, "get%s %s%s%s", + global_aflag ? " -a" : "", dir, + file2 == NULL ? "" : " ", + file2 == NULL ? "" : file2); + err = parse_dispatch_command(conn, cmd, + &remote_path, 1); + free(dir); + free(remote_path); + free(conn); + return (err); + } + free(dir); + } + + setlinebuf(stdout); + setlinebuf(infile); + + interactive = !batchmode && isatty(STDIN_FILENO); + err = 0; + for (;;) { + char *cp; + + signal(SIGINT, SIG_IGN); + + if (el == NULL) { + if (interactive) + printf("sftp> "); + if (fgets(cmd, sizeof(cmd), infile) == NULL) { + if (interactive) + printf("\n"); + break; + } + if (!interactive) { /* Echo command */ + printf("sftp> %s", cmd); + if (strlen(cmd) > 0 && + cmd[strlen(cmd) - 1] != '\n') + printf("\n"); + } + } else { +#ifdef USE_LIBEDIT + const char *line; + int count = 0; + + if ((line = el_gets(el, &count)) == NULL || + count <= 0) { + printf("\n"); + break; + } + history(hl, &hev, H_ENTER, line); + if (strlcpy(cmd, line, sizeof(cmd)) >= sizeof(cmd)) { + fprintf(stderr, "Error: input line too long\n"); + continue; + } +#endif /* USE_LIBEDIT */ + } + + cp = strrchr(cmd, '\n'); + if (cp) + *cp = '\0'; + + /* Handle user interrupts gracefully during commands */ + interrupted = 0; + signal(SIGINT, cmd_interrupt); + + err = parse_dispatch_command(conn, cmd, &remote_path, + batchmode); + if (err != 0) + break; + } + free(remote_path); + free(conn); + +#ifdef USE_LIBEDIT + if (el != NULL) + el_end(el); +#endif /* USE_LIBEDIT */ + + /* err == 1 signifies normal "quit" exit */ + return (err >= 0 ? 0 : -1); +} + +static void +connect_to_server(char *path, char **args, int *in, int *out) +{ + int c_in, c_out; + +#ifdef USE_PIPES + int pin[2], pout[2]; + + if ((pipe(pin) == -1) || (pipe(pout) == -1)) + fatal("pipe: %s", strerror(errno)); + *in = pin[0]; + *out = pout[1]; + c_in = pout[0]; + c_out = pin[1]; +#else /* USE_PIPES */ + int inout[2]; + + if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1) + fatal("socketpair: %s", strerror(errno)); + *in = *out = inout[0]; + c_in = c_out = inout[1]; +#endif /* USE_PIPES */ + + if ((sshpid = fork()) == -1) + fatal("fork: %s", strerror(errno)); + else if (sshpid == 0) { + if ((dup2(c_in, STDIN_FILENO) == -1) || + (dup2(c_out, STDOUT_FILENO) == -1)) { + fprintf(stderr, "dup2: %s\n", strerror(errno)); + _exit(1); + } + close(*in); + close(*out); + close(c_in); + close(c_out); + + /* + * The underlying ssh is in the same process group, so we must + * ignore SIGINT if we want to gracefully abort commands, + * otherwise the signal will make it to the ssh process and + * kill it too. Contrawise, since sftp sends SIGTERMs to the + * underlying ssh, it must *not* ignore that signal. + */ + signal(SIGINT, SIG_IGN); + signal(SIGTERM, SIG_DFL); + execvp(path, args); + fprintf(stderr, "exec: %s: %s\n", path, strerror(errno)); + _exit(1); + } + + signal(SIGTERM, killchild); + signal(SIGINT, killchild); + signal(SIGHUP, killchild); + close(c_in); + close(c_out); +} + +static void +usage(void) +{ + extern char *__progname; + + fprintf(stderr, + "usage: %s [-1246aCfpqrv] [-B buffer_size] [-b batchfile] [-c cipher]\n" + " [-D sftp_server_path] [-F ssh_config] " + "[-i identity_file] [-l limit]\n" + " [-o ssh_option] [-P port] [-R num_requests] " + "[-S program]\n" + " [-s subsystem | sftp_server] host\n" + " %s [user@]host[:file ...]\n" + " %s [user@]host[:dir[/]]\n" + " %s -b batchfile [user@]host\n", + __progname, __progname, __progname, __progname); + exit(1); +} + +int +main(int argc, char **argv) +{ + int in, out, ch, err; + char *host = NULL, *userhost, *cp, *file2 = NULL; + int debug_level = 0, sshver = 2; + char *file1 = NULL, *sftp_server = NULL; + char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL; + const char *errstr; + LogLevel ll = SYSLOG_LEVEL_INFO; + arglist args; + extern int optind; + extern char *optarg; + struct sftp_conn *conn; + size_t copy_buffer_len = DEFAULT_COPY_BUFLEN; + size_t num_requests = DEFAULT_NUM_REQUESTS; + long long limit_kbps = 0; + + /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ + sanitise_stdfd(); + setlocale(LC_CTYPE, ""); + + __progname = ssh_get_progname(argv[0]); + memset(&args, '\0', sizeof(args)); + args.list = NULL; + addargs(&args, "%s", ssh_program); + addargs(&args, "-oForwardX11 no"); + addargs(&args, "-oForwardAgent no"); + addargs(&args, "-oPermitLocalCommand no"); + addargs(&args, "-oClearAllForwardings yes"); + + ll = SYSLOG_LEVEL_INFO; + infile = stdin; + + while ((ch = getopt(argc, argv, + "1246afhpqrvCc:D:i:l:o:s:S:b:B:F:P:R:")) != -1) { + switch (ch) { + /* Passed through to ssh(1) */ + case '4': + case '6': + case 'C': + addargs(&args, "-%c", ch); + break; + /* Passed through to ssh(1) with argument */ + case 'F': + case 'c': + case 'i': + case 'o': + addargs(&args, "-%c", ch); + addargs(&args, "%s", optarg); + break; + case 'q': + ll = SYSLOG_LEVEL_ERROR; + quiet = 1; + showprogress = 0; + addargs(&args, "-%c", ch); + break; + case 'P': + addargs(&args, "-oPort %s", optarg); + break; + case 'v': + if (debug_level < 3) { + addargs(&args, "-v"); + ll = SYSLOG_LEVEL_DEBUG1 + debug_level; + } + debug_level++; + break; + case '1': + sshver = 1; + if (sftp_server == NULL) + sftp_server = _PATH_SFTP_SERVER; + break; + case '2': + sshver = 2; + break; + case 'a': + global_aflag = 1; + break; + case 'B': + copy_buffer_len = strtol(optarg, &cp, 10); + if (copy_buffer_len == 0 || *cp != '\0') + fatal("Invalid buffer size \"%s\"", optarg); + break; + case 'b': + if (batchmode) + fatal("Batch file already specified."); + + /* Allow "-" as stdin */ + if (strcmp(optarg, "-") != 0 && + (infile = fopen(optarg, "r")) == NULL) + fatal("%s (%s).", strerror(errno), optarg); + showprogress = 0; + quiet = batchmode = 1; + addargs(&args, "-obatchmode yes"); + break; + case 'f': + global_fflag = 1; + break; + case 'p': + global_pflag = 1; + break; + case 'D': + sftp_direct = optarg; + break; + case 'l': + limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024, + &errstr); + if (errstr != NULL) + usage(); + limit_kbps *= 1024; /* kbps */ + break; + case 'r': + global_rflag = 1; + break; + case 'R': + num_requests = strtol(optarg, &cp, 10); + if (num_requests == 0 || *cp != '\0') + fatal("Invalid number of requests \"%s\"", + optarg); + break; + case 's': + sftp_server = optarg; + break; + case 'S': + ssh_program = optarg; + replacearg(&args, 0, "%s", ssh_program); + break; + case 'h': + default: + usage(); + } + } + + if (!isatty(STDERR_FILENO)) + showprogress = 0; + + log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1); + + if (sftp_direct == NULL) { + if (optind == argc || argc > (optind + 2)) + usage(); + + userhost = xstrdup(argv[optind]); + file2 = argv[optind+1]; + + if ((host = strrchr(userhost, '@')) == NULL) + host = userhost; + else { + *host++ = '\0'; + if (!userhost[0]) { + fprintf(stderr, "Missing username\n"); + usage(); + } + addargs(&args, "-l"); + addargs(&args, "%s", userhost); + } + + if ((cp = colon(host)) != NULL) { + *cp++ = '\0'; + file1 = cp; + } + + host = cleanhostname(host); + if (!*host) { + fprintf(stderr, "Missing hostname\n"); + usage(); + } + + addargs(&args, "-oProtocol %d", sshver); + + /* no subsystem if the server-spec contains a '/' */ + if (sftp_server == NULL || strchr(sftp_server, '/') == NULL) + addargs(&args, "-s"); + + addargs(&args, "--"); + addargs(&args, "%s", host); + addargs(&args, "%s", (sftp_server != NULL ? + sftp_server : "sftp")); + + connect_to_server(ssh_program, args.list, &in, &out); + } else { + args.list = NULL; + addargs(&args, "sftp-server"); + + connect_to_server(sftp_direct, args.list, &in, &out); + } + freeargs(&args); + + conn = do_init(in, out, copy_buffer_len, num_requests, limit_kbps); + if (conn == NULL) + fatal("Couldn't initialise connection to server"); + + if (!quiet) { + if (sftp_direct == NULL) + fprintf(stderr, "Connected to %s.\n", host); + else + fprintf(stderr, "Attached to %s.\n", sftp_direct); + } + + err = interactive_loop(conn, file1, file2); + +#if !defined(USE_PIPES) + shutdown(in, SHUT_RDWR); + shutdown(out, SHUT_RDWR); +#endif + + close(in); + close(out); + if (batchmode) + fclose(infile); + + while (waitpid(sshpid, NULL, 0) == -1) + if (errno != EINTR) + fatal("Couldn't wait for ssh process: %s", + strerror(errno)); + + exit(err == 0 ? 0 : 1); +} diff --git a/openssh/sftp.h b/openssh/sftp.h new file mode 100644 index 0000000..2bde8bb --- /dev/null +++ b/openssh/sftp.h @@ -0,0 +1,101 @@ +/* $OpenBSD: sftp.h,v 1.9 2008/06/13 00:12:02 dtucker Exp $ */ + +/* + * Copyright (c) 2001 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * draft-ietf-secsh-filexfer-01.txt + */ + +/* version */ +#define SSH2_FILEXFER_VERSION 3 + +/* client to server */ +#define SSH2_FXP_INIT 1 +#define SSH2_FXP_OPEN 3 +#define SSH2_FXP_CLOSE 4 +#define SSH2_FXP_READ 5 +#define SSH2_FXP_WRITE 6 +#define SSH2_FXP_LSTAT 7 +#define SSH2_FXP_STAT_VERSION_0 7 +#define SSH2_FXP_FSTAT 8 +#define SSH2_FXP_SETSTAT 9 +#define SSH2_FXP_FSETSTAT 10 +#define SSH2_FXP_OPENDIR 11 +#define SSH2_FXP_READDIR 12 +#define SSH2_FXP_REMOVE 13 +#define SSH2_FXP_MKDIR 14 +#define SSH2_FXP_RMDIR 15 +#define SSH2_FXP_REALPATH 16 +#define SSH2_FXP_STAT 17 +#define SSH2_FXP_RENAME 18 +#define SSH2_FXP_READLINK 19 +#define SSH2_FXP_SYMLINK 20 + +/* server to client */ +#define SSH2_FXP_VERSION 2 +#define SSH2_FXP_STATUS 101 +#define SSH2_FXP_HANDLE 102 +#define SSH2_FXP_DATA 103 +#define SSH2_FXP_NAME 104 +#define SSH2_FXP_ATTRS 105 + +#define SSH2_FXP_EXTENDED 200 +#define SSH2_FXP_EXTENDED_REPLY 201 + +/* attributes */ +#define SSH2_FILEXFER_ATTR_SIZE 0x00000001 +#define SSH2_FILEXFER_ATTR_UIDGID 0x00000002 +#define SSH2_FILEXFER_ATTR_PERMISSIONS 0x00000004 +#define SSH2_FILEXFER_ATTR_ACMODTIME 0x00000008 +#define SSH2_FILEXFER_ATTR_EXTENDED 0x80000000 + +/* portable open modes */ +#define SSH2_FXF_READ 0x00000001 +#define SSH2_FXF_WRITE 0x00000002 +#define SSH2_FXF_APPEND 0x00000004 +#define SSH2_FXF_CREAT 0x00000008 +#define SSH2_FXF_TRUNC 0x00000010 +#define SSH2_FXF_EXCL 0x00000020 + +/* statvfs@openssh.com f_flag flags */ +#define SSH2_FXE_STATVFS_ST_RDONLY 0x00000001 +#define SSH2_FXE_STATVFS_ST_NOSUID 0x00000002 + +/* status messages */ +#define SSH2_FX_OK 0 +#define SSH2_FX_EOF 1 +#define SSH2_FX_NO_SUCH_FILE 2 +#define SSH2_FX_PERMISSION_DENIED 3 +#define SSH2_FX_FAILURE 4 +#define SSH2_FX_BAD_MESSAGE 5 +#define SSH2_FX_NO_CONNECTION 6 +#define SSH2_FX_CONNECTION_LOST 7 +#define SSH2_FX_OP_UNSUPPORTED 8 +#define SSH2_FX_MAX 8 + +struct passwd; + +int sftp_server_main(int, char **, struct passwd *); +void sftp_server_cleanup_exit(int) __attribute__((noreturn));