OSDN Git Service

Modify features and documents for 1.98b the urgent security release.
[ffftp/ffftp.git] / contrib / putty / PSCP.C
diff --git a/contrib/putty/PSCP.C b/contrib/putty/PSCP.C
deleted file mode 100644 (file)
index 14fff5c..0000000
+++ /dev/null
@@ -1,2308 +0,0 @@
-/*\r
- * scp.c  -  Scp (Secure Copy) client for PuTTY.\r
- * Joris van Rantwijk, Simon Tatham\r
- *\r
- * This is mainly based on ssh-1.2.26/scp.c by Timo Rinne & Tatu Ylonen.\r
- * They, in turn, used stuff from BSD rcp.\r
- * \r
- * (SGT, 2001-09-10: Joris van Rantwijk assures me that although\r
- * this file as originally submitted was inspired by, and\r
- * _structurally_ based on, ssh-1.2.26's scp.c, there wasn't any\r
- * actual code duplicated, so the above comment shouldn't give rise\r
- * to licensing issues.)\r
- */\r
-\r
-#include <stdlib.h>\r
-#include <stdio.h>\r
-#include <string.h>\r
-#include <limits.h>\r
-#include <time.h>\r
-#include <assert.h>\r
-\r
-#define PUTTY_DO_GLOBALS\r
-#include "putty.h"\r
-#include "psftp.h"\r
-#include "ssh.h"\r
-#include "sftp.h"\r
-#include "storage.h"\r
-#include "int64.h"\r
-\r
-static int list = 0;\r
-static int verbose = 0;\r
-static int recursive = 0;\r
-static int preserve = 0;\r
-static int targetshouldbedirectory = 0;\r
-static int statistics = 1;\r
-static int prev_stats_len = 0;\r
-static int scp_unsafe_mode = 0;\r
-static int errs = 0;\r
-static int try_scp = 1;\r
-static int try_sftp = 1;\r
-static int main_cmd_is_sftp = 0;\r
-static int fallback_cmd_is_sftp = 0;\r
-static int using_sftp = 0;\r
-\r
-static Backend *back;\r
-static void *backhandle;\r
-static Config cfg;\r
-\r
-static void source(char *src);\r
-static void rsource(char *src);\r
-static void sink(char *targ, char *src);\r
-\r
-const char *const appname = "PSCP";\r
-\r
-/*\r
- * The maximum amount of queued data we accept before we stop and\r
- * wait for the server to process some.\r
- */\r
-#define MAX_SCP_BUFSIZE 16384\r
-\r
-void ldisc_send(void *handle, char *buf, int len, int interactive)\r
-{\r
-    /*\r
-     * This is only here because of the calls to ldisc_send(NULL,\r
-     * 0) in ssh.c. Nothing in PSCP actually needs to use the ldisc\r
-     * as an ldisc. So if we get called with any real data, I want\r
-     * to know about it.\r
-     */\r
-    assert(len == 0);\r
-}\r
-\r
-static void tell_char(FILE * stream, char c)\r
-{\r
-    fputc(c, stream);\r
-}\r
-\r
-static void tell_str(FILE * stream, char *str)\r
-{\r
-    unsigned int i;\r
-\r
-    for (i = 0; i < strlen(str); ++i)\r
-       tell_char(stream, str[i]);\r
-}\r
-\r
-static void tell_user(FILE * stream, char *fmt, ...)\r
-{\r
-    char *str, *str2;\r
-    va_list ap;\r
-    va_start(ap, fmt);\r
-    str = dupvprintf(fmt, ap);\r
-    va_end(ap);\r
-    str2 = dupcat(str, "\n", NULL);\r
-    sfree(str);\r
-    tell_str(stream, str2);\r
-    sfree(str2);\r
-}\r
-\r
-/*\r
- *  Print an error message and perform a fatal exit.\r
- */\r
-void fatalbox(char *fmt, ...)\r
-{\r
-    char *str, *str2;\r
-    va_list ap;\r
-    va_start(ap, fmt);\r
-    str = dupvprintf(fmt, ap);\r
-    str2 = dupcat("Fatal: ", str, "\n", NULL);\r
-    sfree(str);\r
-    va_end(ap);\r
-    tell_str(stderr, str2);\r
-    sfree(str2);\r
-    errs++;\r
-\r
-    cleanup_exit(1);\r
-}\r
-void modalfatalbox(char *fmt, ...)\r
-{\r
-    char *str, *str2;\r
-    va_list ap;\r
-    va_start(ap, fmt);\r
-    str = dupvprintf(fmt, ap);\r
-    str2 = dupcat("Fatal: ", str, "\n", NULL);\r
-    sfree(str);\r
-    va_end(ap);\r
-    tell_str(stderr, str2);\r
-    sfree(str2);\r
-    errs++;\r
-\r
-    cleanup_exit(1);\r
-}\r
-void connection_fatal(void *frontend, char *fmt, ...)\r
-{\r
-    char *str, *str2;\r
-    va_list ap;\r
-    va_start(ap, fmt);\r
-    str = dupvprintf(fmt, ap);\r
-    str2 = dupcat("Fatal: ", str, "\n", NULL);\r
-    sfree(str);\r
-    va_end(ap);\r
-    tell_str(stderr, str2);\r
-    sfree(str2);\r
-    errs++;\r
-\r
-    cleanup_exit(1);\r
-}\r
-\r
-/*\r
- * In pscp, all agent requests should be synchronous, so this is a\r
- * never-called stub.\r
- */\r
-void agent_schedule_callback(void (*callback)(void *, void *, int),\r
-                            void *callback_ctx, void *data, int len)\r
-{\r
-    assert(!"We shouldn't be here");\r
-}\r
-\r
-/*\r
- * Receive a block of data from the SSH link. Block until all data\r
- * is available.\r
- *\r
- * To do this, we repeatedly call the SSH protocol module, with our\r
- * own trap in from_backend() to catch the data that comes back. We\r
- * do this until we have enough data.\r
- */\r
-\r
-static unsigned char *outptr;         /* where to put the data */\r
-static unsigned outlen;                       /* how much data required */\r
-static unsigned char *pending = NULL;  /* any spare data */\r
-static unsigned pendlen = 0, pendsize = 0;     /* length and phys. size of buffer */\r
-int from_backend(void *frontend, int is_stderr, const char *data, int datalen)\r
-{\r
-    unsigned char *p = (unsigned char *) data;\r
-    unsigned len = (unsigned) datalen;\r
-\r
-    /*\r
-     * stderr data is just spouted to local stderr and otherwise\r
-     * ignored.\r
-     */\r
-    if (is_stderr) {\r
-       if (len > 0)\r
-           if (fwrite(data, 1, len, stderr) < len)\r
-               /* oh well */;\r
-       return 0;\r
-    }\r
-\r
-    if ((outlen > 0) && (len > 0)) {\r
-       unsigned used = outlen;\r
-       if (used > len)\r
-           used = len;\r
-       memcpy(outptr, p, used);\r
-       outptr += used;\r
-       outlen -= used;\r
-       p += used;\r
-       len -= used;\r
-    }\r
-\r
-    if (len > 0) {\r
-       if (pendsize < pendlen + len) {\r
-           pendsize = pendlen + len + 4096;\r
-           pending = sresize(pending, pendsize, unsigned char);\r
-       }\r
-       memcpy(pending + pendlen, p, len);\r
-       pendlen += len;\r
-    }\r
-\r
-    return 0;\r
-}\r
-int from_backend_untrusted(void *frontend_handle, const char *data, int len)\r
-{\r
-    /*\r
-     * No "untrusted" output should get here (the way the code is\r
-     * currently, it's all diverted by FLAG_STDERR).\r
-     */\r
-    assert(!"Unexpected call to from_backend_untrusted()");\r
-    return 0; /* not reached */\r
-}\r
-static int ssh_scp_recv(unsigned char *buf, int len)\r
-{\r
-    outptr = buf;\r
-    outlen = len;\r
-\r
-    /*\r
-     * See if the pending-input block contains some of what we\r
-     * need.\r
-     */\r
-    if (pendlen > 0) {\r
-       unsigned pendused = pendlen;\r
-       if (pendused > outlen)\r
-           pendused = outlen;\r
-       memcpy(outptr, pending, pendused);\r
-       memmove(pending, pending + pendused, pendlen - pendused);\r
-       outptr += pendused;\r
-       outlen -= pendused;\r
-       pendlen -= pendused;\r
-       if (pendlen == 0) {\r
-           pendsize = 0;\r
-           sfree(pending);\r
-           pending = NULL;\r
-       }\r
-       if (outlen == 0)\r
-           return len;\r
-    }\r
-\r
-    while (outlen > 0) {\r
-       if (back->exitcode(backhandle) >= 0 || ssh_sftp_loop_iteration() < 0)\r
-           return 0;                  /* doom */\r
-    }\r
-\r
-    return len;\r
-}\r
-\r
-/*\r
- * Loop through the ssh connection and authentication process.\r
- */\r
-static void ssh_scp_init(void)\r
-{\r
-    while (!back->sendok(backhandle)) {\r
-        if (back->exitcode(backhandle) >= 0) {\r
-            errs++;\r
-            return;\r
-        }\r
-       if (ssh_sftp_loop_iteration() < 0) {\r
-            errs++;\r
-           return;                    /* doom */\r
-        }\r
-    }\r
-\r
-    /* Work out which backend we ended up using. */\r
-    if (!ssh_fallback_cmd(backhandle))\r
-       using_sftp = main_cmd_is_sftp;\r
-    else\r
-       using_sftp = fallback_cmd_is_sftp;\r
-\r
-    if (verbose) {\r
-       if (using_sftp)\r
-           tell_user(stderr, "Using SFTP");\r
-       else\r
-           tell_user(stderr, "Using SCP1");\r
-    }\r
-}\r
-\r
-/*\r
- *  Print an error message and exit after closing the SSH link.\r
- */\r
-static void bump(char *fmt, ...)\r
-{\r
-    char *str, *str2;\r
-    va_list ap;\r
-    va_start(ap, fmt);\r
-    str = dupvprintf(fmt, ap);\r
-    va_end(ap);\r
-    str2 = dupcat(str, "\n", NULL);\r
-    sfree(str);\r
-    tell_str(stderr, str2);\r
-    sfree(str2);\r
-    errs++;\r
-\r
-    if (back != NULL && back->connected(backhandle)) {\r
-       char ch;\r
-       back->special(backhandle, TS_EOF);\r
-       ssh_scp_recv((unsigned char *) &ch, 1);\r
-    }\r
-\r
-    cleanup_exit(1);\r
-}\r
-\r
-/*\r
- *  Open an SSH connection to user@host and execute cmd.\r
- */\r
-static void do_cmd(char *host, char *user, char *cmd)\r
-{\r
-    const char *err;\r
-    char *realhost;\r
-    void *logctx;\r
-\r
-    if (host == NULL || host[0] == '\0')\r
-       bump("Empty host name");\r
-\r
-    /*\r
-     * Remove fiddly bits of address: remove a colon suffix, and\r
-     * the square brackets around an IPv6 literal address.\r
-     */\r
-    if (host[0] == '[') {\r
-       host++;\r
-       host[strcspn(host, "]")] = '\0';\r
-    } else {\r
-       host[strcspn(host, ":")] = '\0';\r
-    }\r
-\r
-    /*\r
-     * If we haven't loaded session details already (e.g., from -load),\r
-     * try looking for a session called "host".\r
-     */\r
-    if (!loaded_session) {\r
-       /* Try to load settings for `host' into a temporary config */\r
-       Config cfg2;\r
-       cfg2.host[0] = '\0';\r
-       do_defaults(host, &cfg2);\r
-       if (cfg2.host[0] != '\0') {\r
-           /* Settings present and include hostname */\r
-           /* Re-load data into the real config. */\r
-           do_defaults(host, &cfg);\r
-       } else {\r
-           /* Session doesn't exist or mention a hostname. */\r
-           /* Use `host' as a bare hostname. */\r
-           strncpy(cfg.host, host, sizeof(cfg.host) - 1);\r
-           cfg.host[sizeof(cfg.host) - 1] = '\0';\r
-       }\r
-    } else {\r
-       /* Patch in hostname `host' to session details. */\r
-       strncpy(cfg.host, host, sizeof(cfg.host) - 1);\r
-       cfg.host[sizeof(cfg.host) - 1] = '\0';\r
-    }\r
-\r
-    /*\r
-     * Force use of SSH. (If they got the protocol wrong we assume the\r
-     * port is useless too.)\r
-     */\r
-    if (cfg.protocol != PROT_SSH) {\r
-        cfg.protocol = PROT_SSH;\r
-        cfg.port = 22;\r
-    }\r
-\r
-    /*\r
-     * Enact command-line overrides.\r
-     */\r
-    cmdline_run_saved(&cfg);\r
-\r
-    /*\r
-     * Trim leading whitespace off the hostname if it's there.\r
-     */\r
-    {\r
-       int space = strspn(cfg.host, " \t");\r
-       memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);\r
-    }\r
-\r
-    /* See if host is of the form user@host */\r
-    if (cfg.host[0] != '\0') {\r
-       char *atsign = strrchr(cfg.host, '@');\r
-       /* Make sure we're not overflowing the user field */\r
-       if (atsign) {\r
-           if (atsign - cfg.host < sizeof cfg.username) {\r
-               strncpy(cfg.username, cfg.host, atsign - cfg.host);\r
-               cfg.username[atsign - cfg.host] = '\0';\r
-           }\r
-           memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));\r
-       }\r
-    }\r
-\r
-    /*\r
-     * Remove any remaining whitespace from the hostname.\r
-     */\r
-    {\r
-       int p1 = 0, p2 = 0;\r
-       while (cfg.host[p2] != '\0') {\r
-           if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {\r
-               cfg.host[p1] = cfg.host[p2];\r
-               p1++;\r
-           }\r
-           p2++;\r
-       }\r
-       cfg.host[p1] = '\0';\r
-    }\r
-\r
-    /* Set username */\r
-    if (user != NULL && user[0] != '\0') {\r
-       strncpy(cfg.username, user, sizeof(cfg.username) - 1);\r
-       cfg.username[sizeof(cfg.username) - 1] = '\0';\r
-    } else if (cfg.username[0] == '\0') {\r
-       user = get_username();\r
-       if (!user)\r
-           bump("Empty user name");\r
-       else {\r
-           if (verbose)\r
-               tell_user(stderr, "Guessing user name: %s", user);\r
-           strncpy(cfg.username, user, sizeof(cfg.username) - 1);\r
-           cfg.username[sizeof(cfg.username) - 1] = '\0';\r
-           sfree(user);\r
-       }\r
-    }\r
-\r
-    /*\r
-     * Disable scary things which shouldn't be enabled for simple\r
-     * things like SCP and SFTP: agent forwarding, port forwarding,\r
-     * X forwarding.\r
-     */\r
-    cfg.x11_forward = 0;\r
-    cfg.agentfwd = 0;\r
-    cfg.portfwd[0] = cfg.portfwd[1] = '\0';\r
-    cfg.ssh_simple = TRUE;\r
-\r
-    /*\r
-     * Set up main and possibly fallback command depending on\r
-     * options specified by user.\r
-     * Attempt to start the SFTP subsystem as a first choice,\r
-     * falling back to the provided scp command if that fails.\r
-     */\r
-    cfg.remote_cmd_ptr2 = NULL;\r
-    if (try_sftp) {\r
-       /* First choice is SFTP subsystem. */\r
-       main_cmd_is_sftp = 1;\r
-       strcpy(cfg.remote_cmd, "sftp");\r
-       cfg.ssh_subsys = TRUE;\r
-       if (try_scp) {\r
-           /* Fallback is to use the provided scp command. */\r
-           fallback_cmd_is_sftp = 0;\r
-           cfg.remote_cmd_ptr2 = cmd;\r
-           cfg.ssh_subsys2 = FALSE;\r
-       } else {\r
-           /* Since we're not going to try SCP, we may as well try\r
-            * harder to find an SFTP server, since in the current\r
-            * implementation we have a spare slot. */\r
-           fallback_cmd_is_sftp = 1;\r
-           /* see psftp.c for full explanation of this kludge */\r
-           cfg.remote_cmd_ptr2 = \r
-               "test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server\n"\r
-               "test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server\n"\r
-               "exec sftp-server";\r
-           cfg.ssh_subsys2 = FALSE;\r
-       }\r
-    } else {\r
-       /* Don't try SFTP at all; just try the scp command. */\r
-       main_cmd_is_sftp = 0;\r
-       cfg.remote_cmd_ptr = cmd;\r
-       cfg.ssh_subsys = FALSE;\r
-    }\r
-    cfg.nopty = TRUE;\r
-\r
-    back = &ssh_backend;\r
-\r
-    err = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port, &realhost, \r
-                    0, cfg.tcp_keepalives);\r
-    if (err != NULL)\r
-       bump("ssh_init: %s", err);\r
-    logctx = log_init(NULL, &cfg);\r
-    back->provide_logctx(backhandle, logctx);\r
-    console_provide_logctx(logctx);\r
-    ssh_scp_init();\r
-    if (verbose && realhost != NULL && errs == 0)\r
-       tell_user(stderr, "Connected to %s\n", realhost);\r
-    sfree(realhost);\r
-}\r
-\r
-/*\r
- *  Update statistic information about current file.\r
- */\r
-static void print_stats(char *name, uint64 size, uint64 done,\r
-                       time_t start, time_t now)\r
-{\r
-    float ratebs;\r
-    unsigned long eta;\r
-    char *etastr;\r
-    int pct;\r
-    int len;\r
-    int elap;\r
-    double donedbl;\r
-    double sizedbl;\r
-\r
-    elap = (unsigned long) difftime(now, start);\r
-\r
-    if (now > start)\r
-       ratebs = (float) (uint64_to_double(done) / elap);\r
-    else\r
-       ratebs = (float) uint64_to_double(done);\r
-\r
-    if (ratebs < 1.0)\r
-       eta = (unsigned long) (uint64_to_double(uint64_subtract(size, done)));\r
-    else {\r
-        eta = (unsigned long)\r
-           ((uint64_to_double(uint64_subtract(size, done)) / ratebs));\r
-    }\r
-\r
-    etastr = dupprintf("%02ld:%02ld:%02ld",\r
-                      eta / 3600, (eta % 3600) / 60, eta % 60);\r
-\r
-    donedbl = uint64_to_double(done);\r
-    sizedbl = uint64_to_double(size);\r
-    pct = (int) (100 * (donedbl * 1.0 / sizedbl));\r
-\r
-    {\r
-       char donekb[40];\r
-       /* divide by 1024 to provide kB */\r
-       uint64_decimal(uint64_shift_right(done, 10), donekb);\r
-       len = printf("\r%-25.25s | %s kB | %5.1f kB/s | ETA: %8s | %3d%%",\r
-                    name,\r
-                    donekb, ratebs / 1024.0, etastr, pct);\r
-       if (len < prev_stats_len)\r
-           printf("%*s", prev_stats_len - len, "");\r
-       prev_stats_len = len;\r
-\r
-       if (uint64_compare(done, size) == 0)\r
-           printf("\n");\r
-\r
-       fflush(stdout);\r
-    }\r
-\r
-    free(etastr);\r
-}\r
-\r
-/*\r
- *  Find a colon in str and return a pointer to the colon.\r
- *  This is used to separate hostname from filename.\r
- */\r
-static char *colon(char *str)\r
-{\r
-    /* We ignore a leading colon, since the hostname cannot be\r
-       empty. We also ignore a colon as second character because\r
-       of filenames like f:myfile.txt. */\r
-    if (str[0] == '\0' || str[0] == ':' ||\r
-        (str[0] != '[' && str[1] == ':'))\r
-       return (NULL);\r
-    while (*str != '\0' && *str != ':' && *str != '/' && *str != '\\') {\r
-       if (*str == '[') {\r
-           /* Skip over IPv6 literal addresses\r
-            * (eg: 'jeroen@[2001:db8::1]:myfile.txt') */\r
-           char *ipv6_end = strchr(str, ']');\r
-           if (ipv6_end) {\r
-               str = ipv6_end;\r
-           }\r
-       }\r
-       str++;\r
-    }\r
-    if (*str == ':')\r
-       return (str);\r
-    else\r
-       return (NULL);\r
-}\r
-\r
-/*\r
- * Return a pointer to the portion of str that comes after the last\r
- * slash (or backslash or colon, if `local' is TRUE).\r
- */\r
-static char *stripslashes(char *str, int local)\r
-{\r
-    char *p;\r
-\r
-    if (local) {\r
-        p = strchr(str, ':');\r
-        if (p) str = p+1;\r
-    }\r
-\r
-    p = strrchr(str, '/');\r
-    if (p) str = p+1;\r
-\r
-    if (local) {\r
-       p = strrchr(str, '\\');\r
-       if (p) str = p+1;\r
-    }\r
-\r
-    return str;\r
-}\r
-\r
-/*\r
- * Determine whether a string is entirely composed of dots.\r
- */\r
-static int is_dots(char *str)\r
-{\r
-    return str[strspn(str, ".")] == '\0';\r
-}\r
-\r
-/*\r
- *  Wait for a response from the other side.\r
- *  Return 0 if ok, -1 if error.\r
- */\r
-static int response(void)\r
-{\r
-    char ch, resp, rbuf[2048];\r
-    int p;\r
-\r
-    if (ssh_scp_recv((unsigned char *) &resp, 1) <= 0)\r
-       bump("Lost connection");\r
-\r
-    p = 0;\r
-    switch (resp) {\r
-      case 0:                         /* ok */\r
-       return (0);\r
-      default:\r
-       rbuf[p++] = resp;\r
-       /* fallthrough */\r
-      case 1:                         /* error */\r
-      case 2:                         /* fatal error */\r
-       do {\r
-           if (ssh_scp_recv((unsigned char *) &ch, 1) <= 0)\r
-               bump("Protocol error: Lost connection");\r
-           rbuf[p++] = ch;\r
-       } while (p < sizeof(rbuf) && ch != '\n');\r
-       rbuf[p - 1] = '\0';\r
-       if (resp == 1)\r
-           tell_user(stderr, "%s\n", rbuf);\r
-       else\r
-           bump("%s", rbuf);\r
-       errs++;\r
-       return (-1);\r
-    }\r
-}\r
-\r
-int sftp_recvdata(char *buf, int len)\r
-{\r
-    return ssh_scp_recv((unsigned char *) buf, len);\r
-}\r
-int sftp_senddata(char *buf, int len)\r
-{\r
-    back->send(backhandle, buf, len);\r
-    return 1;\r
-}\r
-\r
-/* ----------------------------------------------------------------------\r
- * sftp-based replacement for the hacky `pscp -ls'.\r
- */\r
-static int sftp_ls_compare(const void *av, const void *bv)\r
-{\r
-    const struct fxp_name *a = (const struct fxp_name *) av;\r
-    const struct fxp_name *b = (const struct fxp_name *) bv;\r
-    return strcmp(a->filename, b->filename);\r
-}\r
-void scp_sftp_listdir(char *dirname)\r
-{\r
-    struct fxp_handle *dirh;\r
-    struct fxp_names *names;\r
-    struct fxp_name *ournames;\r
-    struct sftp_packet *pktin;\r
-    struct sftp_request *req, *rreq;\r
-    int nnames, namesize;\r
-    int i;\r
-\r
-    if (!fxp_init()) {\r
-       tell_user(stderr, "unable to initialise SFTP: %s", fxp_error());\r
-       errs++;\r
-       return;\r
-    }\r
-\r
-    printf("Listing directory %s\n", dirname);\r
-\r
-    sftp_register(req = fxp_opendir_send(dirname));\r
-    rreq = sftp_find_request(pktin = sftp_recv());\r
-    assert(rreq == req);\r
-    dirh = fxp_opendir_recv(pktin, rreq);\r
-\r
-    if (dirh == NULL) {\r
-       printf("Unable to open %s: %s\n", dirname, fxp_error());\r
-    } else {\r
-       nnames = namesize = 0;\r
-       ournames = NULL;\r
-\r
-       while (1) {\r
-\r
-           sftp_register(req = fxp_readdir_send(dirh));\r
-           rreq = sftp_find_request(pktin = sftp_recv());\r
-           assert(rreq == req);\r
-           names = fxp_readdir_recv(pktin, rreq);\r
-\r
-           if (names == NULL) {\r
-               if (fxp_error_type() == SSH_FX_EOF)\r
-                   break;\r
-               printf("Reading directory %s: %s\n", dirname, fxp_error());\r
-               break;\r
-           }\r
-           if (names->nnames == 0) {\r
-               fxp_free_names(names);\r
-               break;\r
-           }\r
-\r
-           if (nnames + names->nnames >= namesize) {\r
-               namesize += names->nnames + 128;\r
-               ournames = sresize(ournames, namesize, struct fxp_name);\r
-           }\r
-\r
-           for (i = 0; i < names->nnames; i++)\r
-               ournames[nnames++] = names->names[i];\r
-           names->nnames = 0;         /* prevent free_names */\r
-           fxp_free_names(names);\r
-       }\r
-       sftp_register(req = fxp_close_send(dirh));\r
-       rreq = sftp_find_request(pktin = sftp_recv());\r
-       assert(rreq == req);\r
-       fxp_close_recv(pktin, rreq);\r
-\r
-       /*\r
-        * Now we have our filenames. Sort them by actual file\r
-        * name, and then output the longname parts.\r
-        */\r
-       qsort(ournames, nnames, sizeof(*ournames), sftp_ls_compare);\r
-\r
-       /*\r
-        * And print them.\r
-        */\r
-       for (i = 0; i < nnames; i++)\r
-           printf("%s\n", ournames[i].longname);\r
-    }\r
-}\r
-\r
-/* ----------------------------------------------------------------------\r
- * Helper routines that contain the actual SCP protocol elements,\r
- * implemented both as SCP1 and SFTP.\r
- */\r
-\r
-static struct scp_sftp_dirstack {\r
-    struct scp_sftp_dirstack *next;\r
-    struct fxp_name *names;\r
-    int namepos, namelen;\r
-    char *dirpath;\r
-    char *wildcard;\r
-    int matched_something;            /* wildcard match set was non-empty */\r
-} *scp_sftp_dirstack_head;\r
-static char *scp_sftp_remotepath, *scp_sftp_currentname;\r
-static char *scp_sftp_wildcard;\r
-static int scp_sftp_targetisdir, scp_sftp_donethistarget;\r
-static int scp_sftp_preserve, scp_sftp_recursive;\r
-static unsigned long scp_sftp_mtime, scp_sftp_atime;\r
-static int scp_has_times;\r
-static struct fxp_handle *scp_sftp_filehandle;\r
-static struct fxp_xfer *scp_sftp_xfer;\r
-static uint64 scp_sftp_fileoffset;\r
-\r
-int scp_source_setup(char *target, int shouldbedir)\r
-{\r
-    if (using_sftp) {\r
-       /*\r
-        * Find out whether the target filespec is in fact a\r
-        * directory.\r
-        */\r
-       struct sftp_packet *pktin;\r
-       struct sftp_request *req, *rreq;\r
-       struct fxp_attrs attrs;\r
-       int ret;\r
-\r
-       if (!fxp_init()) {\r
-           tell_user(stderr, "unable to initialise SFTP: %s", fxp_error());\r
-           errs++;\r
-           return 1;\r
-       }\r
-\r
-       sftp_register(req = fxp_stat_send(target));\r
-       rreq = sftp_find_request(pktin = sftp_recv());\r
-       assert(rreq == req);\r
-       ret = fxp_stat_recv(pktin, rreq, &attrs);\r
-\r
-       if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS))\r
-           scp_sftp_targetisdir = 0;\r
-       else\r
-           scp_sftp_targetisdir = (attrs.permissions & 0040000) != 0;\r
-\r
-       if (shouldbedir && !scp_sftp_targetisdir) {\r
-           bump("pscp: remote filespec %s: not a directory\n", target);\r
-       }\r
-\r
-       scp_sftp_remotepath = dupstr(target);\r
-\r
-       scp_has_times = 0;\r
-    } else {\r
-       (void) response();\r
-    }\r
-    return 0;\r
-}\r
-\r
-int scp_send_errmsg(char *str)\r
-{\r
-    if (using_sftp) {\r
-       /* do nothing; we never need to send our errors to the server */\r
-    } else {\r
-       back->send(backhandle, "\001", 1);/* scp protocol error prefix */\r
-       back->send(backhandle, str, strlen(str));\r
-    }\r
-    return 0;                         /* can't fail */\r
-}\r
-\r
-int scp_send_filetimes(unsigned long mtime, unsigned long atime)\r
-{\r
-    if (using_sftp) {\r
-       scp_sftp_mtime = mtime;\r
-       scp_sftp_atime = atime;\r
-       scp_has_times = 1;\r
-       return 0;\r
-    } else {\r
-       char buf[80];\r
-       sprintf(buf, "T%lu 0 %lu 0\n", mtime, atime);\r
-       back->send(backhandle, buf, strlen(buf));\r
-       return response();\r
-    }\r
-}\r
-\r
-int scp_send_filename(char *name, uint64 size, int modes)\r
-{\r
-    if (using_sftp) {\r
-       char *fullname;\r
-       struct sftp_packet *pktin;\r
-       struct sftp_request *req, *rreq;\r
-\r
-       if (scp_sftp_targetisdir) {\r
-           fullname = dupcat(scp_sftp_remotepath, "/", name, NULL);\r
-       } else {\r
-           fullname = dupstr(scp_sftp_remotepath);\r
-       }\r
-\r
-       sftp_register(req = fxp_open_send(fullname, SSH_FXF_WRITE |\r
-                                         SSH_FXF_CREAT | SSH_FXF_TRUNC));\r
-       rreq = sftp_find_request(pktin = sftp_recv());\r
-       assert(rreq == req);\r
-       scp_sftp_filehandle = fxp_open_recv(pktin, rreq);\r
-\r
-       if (!scp_sftp_filehandle) {\r
-           tell_user(stderr, "pscp: unable to open %s: %s",\r
-                     fullname, fxp_error());\r
-           errs++;\r
-           return 1;\r
-       }\r
-       scp_sftp_fileoffset = uint64_make(0, 0);\r
-       scp_sftp_xfer = xfer_upload_init(scp_sftp_filehandle,\r
-                                        scp_sftp_fileoffset);\r
-       sfree(fullname);\r
-       return 0;\r
-    } else {\r
-       char buf[40];\r
-       char sizestr[40];\r
-       uint64_decimal(size, sizestr);\r
-       sprintf(buf, "C%04o %s ", modes, sizestr);\r
-       back->send(backhandle, buf, strlen(buf));\r
-       back->send(backhandle, name, strlen(name));\r
-       back->send(backhandle, "\n", 1);\r
-       return response();\r
-    }\r
-}\r
-\r
-int scp_send_filedata(char *data, int len)\r
-{\r
-    if (using_sftp) {\r
-       int ret;\r
-       struct sftp_packet *pktin;\r
-\r
-       if (!scp_sftp_filehandle) {\r
-           return 1;\r
-       }\r
-\r
-       while (!xfer_upload_ready(scp_sftp_xfer)) {\r
-           pktin = sftp_recv();\r
-           ret = xfer_upload_gotpkt(scp_sftp_xfer, pktin);\r
-           if (!ret) {\r
-               tell_user(stderr, "error while writing: %s\n", fxp_error());\r
-               errs++;\r
-               return 1;\r
-           }\r
-       }\r
-\r
-       xfer_upload_data(scp_sftp_xfer, data, len);\r
-\r
-       scp_sftp_fileoffset = uint64_add32(scp_sftp_fileoffset, len);\r
-       return 0;\r
-    } else {\r
-       int bufsize = back->send(backhandle, data, len);\r
-\r
-       /*\r
-        * If the network transfer is backing up - that is, the\r
-        * remote site is not accepting data as fast as we can\r
-        * produce it - then we must loop on network events until\r
-        * we have space in the buffer again.\r
-        */\r
-       while (bufsize > MAX_SCP_BUFSIZE) {\r
-           if (ssh_sftp_loop_iteration() < 0)\r
-               return 1;\r
-           bufsize = back->sendbuffer(backhandle);\r
-       }\r
-\r
-       return 0;\r
-    }\r
-}\r
-\r
-int scp_send_finish(void)\r
-{\r
-    if (using_sftp) {\r
-       struct fxp_attrs attrs;\r
-       struct sftp_packet *pktin;\r
-       struct sftp_request *req, *rreq;\r
-       int ret;\r
-\r
-       while (!xfer_done(scp_sftp_xfer)) {\r
-           pktin = sftp_recv();\r
-           xfer_upload_gotpkt(scp_sftp_xfer, pktin);\r
-       }\r
-       xfer_cleanup(scp_sftp_xfer);\r
-\r
-       if (!scp_sftp_filehandle) {\r
-           return 1;\r
-       }\r
-       if (scp_has_times) {\r
-           attrs.flags = SSH_FILEXFER_ATTR_ACMODTIME;\r
-           attrs.atime = scp_sftp_atime;\r
-           attrs.mtime = scp_sftp_mtime;\r
-           sftp_register(req = fxp_fsetstat_send(scp_sftp_filehandle, attrs));\r
-           rreq = sftp_find_request(pktin = sftp_recv());\r
-           assert(rreq == req);\r
-           ret = fxp_fsetstat_recv(pktin, rreq);\r
-           if (!ret) {\r
-               tell_user(stderr, "unable to set file times: %s\n", fxp_error());\r
-               errs++;\r
-           }\r
-       }\r
-       sftp_register(req = fxp_close_send(scp_sftp_filehandle));\r
-       rreq = sftp_find_request(pktin = sftp_recv());\r
-       assert(rreq == req);\r
-       fxp_close_recv(pktin, rreq);\r
-       scp_has_times = 0;\r
-       return 0;\r
-    } else {\r
-       back->send(backhandle, "", 1);\r
-       return response();\r
-    }\r
-}\r
-\r
-char *scp_save_remotepath(void)\r
-{\r
-    if (using_sftp)\r
-       return scp_sftp_remotepath;\r
-    else\r
-       return NULL;\r
-}\r
-\r
-void scp_restore_remotepath(char *data)\r
-{\r
-    if (using_sftp)\r
-       scp_sftp_remotepath = data;\r
-}\r
-\r
-int scp_send_dirname(char *name, int modes)\r
-{\r
-    if (using_sftp) {\r
-       char *fullname;\r
-       char const *err;\r
-       struct fxp_attrs attrs;\r
-       struct sftp_packet *pktin;\r
-       struct sftp_request *req, *rreq;\r
-       int ret;\r
-\r
-       if (scp_sftp_targetisdir) {\r
-           fullname = dupcat(scp_sftp_remotepath, "/", name, NULL);\r
-       } else {\r
-           fullname = dupstr(scp_sftp_remotepath);\r
-       }\r
-\r
-       /*\r
-        * We don't worry about whether we managed to create the\r
-        * directory, because if it exists already it's OK just to\r
-        * use it. Instead, we will stat it afterwards, and if it\r
-        * exists and is a directory we will assume we were either\r
-        * successful or it didn't matter.\r
-        */\r
-       sftp_register(req = fxp_mkdir_send(fullname));\r
-       rreq = sftp_find_request(pktin = sftp_recv());\r
-       assert(rreq == req);\r
-       ret = fxp_mkdir_recv(pktin, rreq);\r
-\r
-       if (!ret)\r
-           err = fxp_error();\r
-       else\r
-           err = "server reported no error";\r
-\r
-       sftp_register(req = fxp_stat_send(fullname));\r
-       rreq = sftp_find_request(pktin = sftp_recv());\r
-       assert(rreq == req);\r
-       ret = fxp_stat_recv(pktin, rreq, &attrs);\r
-\r
-       if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) ||\r
-           !(attrs.permissions & 0040000)) {\r
-           tell_user(stderr, "unable to create directory %s: %s",\r
-                     fullname, err);\r
-           errs++;\r
-           return 1;\r
-       }\r
-\r
-       scp_sftp_remotepath = fullname;\r
-\r
-       return 0;\r
-    } else {\r
-       char buf[40];\r
-       sprintf(buf, "D%04o 0 ", modes);\r
-       back->send(backhandle, buf, strlen(buf));\r
-       back->send(backhandle, name, strlen(name));\r
-       back->send(backhandle, "\n", 1);\r
-       return response();\r
-    }\r
-}\r
-\r
-int scp_send_enddir(void)\r
-{\r
-    if (using_sftp) {\r
-       sfree(scp_sftp_remotepath);\r
-       return 0;\r
-    } else {\r
-       back->send(backhandle, "E\n", 2);\r
-       return response();\r
-    }\r
-}\r
-\r
-/*\r
- * Yes, I know; I have an scp_sink_setup _and_ an scp_sink_init.\r
- * That's bad. The difference is that scp_sink_setup is called once\r
- * right at the start, whereas scp_sink_init is called to\r
- * initialise every level of recursion in the protocol.\r
- */\r
-int scp_sink_setup(char *source, int preserve, int recursive)\r
-{\r
-    if (using_sftp) {\r
-       char *newsource;\r
-\r
-       if (!fxp_init()) {\r
-           tell_user(stderr, "unable to initialise SFTP: %s", fxp_error());\r
-           errs++;\r
-           return 1;\r
-       }\r
-       /*\r
-        * It's possible that the source string we've been given\r
-        * contains a wildcard. If so, we must split the directory\r
-        * away from the wildcard itself (throwing an error if any\r
-        * wildcardness comes before the final slash) and arrange\r
-        * things so that a dirstack entry will be set up.\r
-        */\r
-       newsource = snewn(1+strlen(source), char);\r
-       if (!wc_unescape(newsource, source)) {\r
-           /* Yes, here we go; it's a wildcard. Bah. */\r
-           char *dupsource, *lastpart, *dirpart, *wildcard;\r
-           dupsource = dupstr(source);\r
-           lastpart = stripslashes(dupsource, 0);\r
-           wildcard = dupstr(lastpart);\r
-           *lastpart = '\0';\r
-           if (*dupsource && dupsource[1]) {\r
-               /*\r
-                * The remains of dupsource are at least two\r
-                * characters long, meaning the pathname wasn't\r
-                * empty or just `/'. Hence, we remove the trailing\r
-                * slash.\r
-                */\r
-               lastpart[-1] = '\0';\r
-           } else if (!*dupsource) {\r
-               /*\r
-                * The remains of dupsource are _empty_ - the whole\r
-                * pathname was a wildcard. Hence we need to\r
-                * replace it with ".".\r
-                */\r
-               sfree(dupsource);\r
-               dupsource = dupstr(".");\r
-           }\r
-\r
-           /*\r
-            * Now we have separated our string into dupsource (the\r
-            * directory part) and wildcard. Both of these will\r
-            * need freeing at some point. Next step is to remove\r
-            * wildcard escapes from the directory part, throwing\r
-            * an error if it contains a real wildcard.\r
-            */\r
-           dirpart = snewn(1+strlen(dupsource), char);\r
-           if (!wc_unescape(dirpart, dupsource)) {\r
-               tell_user(stderr, "%s: multiple-level wildcards unsupported",\r
-                         source);\r
-               errs++;\r
-               sfree(dirpart);\r
-               sfree(wildcard);\r
-               sfree(dupsource);\r
-               return 1;\r
-           }\r
-\r
-           /*\r
-            * Now we have dirpart (unescaped, ie a valid remote\r
-            * path), and wildcard (a wildcard). This will be\r
-            * sufficient to arrange a dirstack entry.\r
-            */\r
-           scp_sftp_remotepath = dirpart;\r
-           scp_sftp_wildcard = wildcard;\r
-           sfree(dupsource);\r
-       } else {\r
-           scp_sftp_remotepath = newsource;\r
-           scp_sftp_wildcard = NULL;\r
-       }\r
-       scp_sftp_preserve = preserve;\r
-       scp_sftp_recursive = recursive;\r
-       scp_sftp_donethistarget = 0;\r
-       scp_sftp_dirstack_head = NULL;\r
-    }\r
-    return 0;\r
-}\r
-\r
-int scp_sink_init(void)\r
-{\r
-    if (!using_sftp) {\r
-       back->send(backhandle, "", 1);\r
-    }\r
-    return 0;\r
-}\r
-\r
-#define SCP_SINK_FILE   1\r
-#define SCP_SINK_DIR    2\r
-#define SCP_SINK_ENDDIR 3\r
-#define SCP_SINK_RETRY  4             /* not an action; just try again */\r
-struct scp_sink_action {\r
-    int action;                               /* FILE, DIR, ENDDIR */\r
-    char *buf;                        /* will need freeing after use */\r
-    char *name;                               /* filename or dirname (not ENDDIR) */\r
-    int mode;                         /* access mode (not ENDDIR) */\r
-    uint64 size;                      /* file size (not ENDDIR) */\r
-    int settime;                      /* 1 if atime and mtime are filled */\r
-    unsigned long atime, mtime;               /* access times for the file */\r
-};\r
-\r
-int scp_get_sink_action(struct scp_sink_action *act)\r
-{\r
-    if (using_sftp) {\r
-       char *fname;\r
-       int must_free_fname;\r
-       struct fxp_attrs attrs;\r
-       struct sftp_packet *pktin;\r
-       struct sftp_request *req, *rreq;\r
-       int ret;\r
-\r
-       if (!scp_sftp_dirstack_head) {\r
-           if (!scp_sftp_donethistarget) {\r
-               /*\r
-                * Simple case: we are only dealing with one file.\r
-                */\r
-               fname = scp_sftp_remotepath;\r
-               must_free_fname = 0;\r
-               scp_sftp_donethistarget = 1;\r
-           } else {\r
-               /*\r
-                * Even simpler case: one file _which we've done_.\r
-                * Return 1 (finished).\r
-                */\r
-               return 1;\r
-           }\r
-       } else {\r
-           /*\r
-            * We're now in the middle of stepping through a list\r
-            * of names returned from fxp_readdir(); so let's carry\r
-            * on.\r
-            */\r
-           struct scp_sftp_dirstack *head = scp_sftp_dirstack_head;\r
-           while (head->namepos < head->namelen &&\r
-                  (is_dots(head->names[head->namepos].filename) ||\r
-                   (head->wildcard &&\r
-                    !wc_match(head->wildcard,\r
-                              head->names[head->namepos].filename))))\r
-               head->namepos++;       /* skip . and .. */\r
-           if (head->namepos < head->namelen) {\r
-               head->matched_something = 1;\r
-               fname = dupcat(head->dirpath, "/",\r
-                              head->names[head->namepos++].filename,\r
-                              NULL);\r
-               must_free_fname = 1;\r
-           } else {\r
-               /*\r
-                * We've come to the end of the list; pop it off\r
-                * the stack and return an ENDDIR action (or RETRY\r
-                * if this was a wildcard match).\r
-                */\r
-               if (head->wildcard) {\r
-                   act->action = SCP_SINK_RETRY;\r
-                   if (!head->matched_something) {\r
-                       tell_user(stderr, "pscp: wildcard '%s' matched "\r
-                                 "no files", head->wildcard);\r
-                       errs++;\r
-                   }\r
-                   sfree(head->wildcard);\r
-\r
-               } else {\r
-                   act->action = SCP_SINK_ENDDIR;\r
-               }\r
-\r
-               sfree(head->dirpath);\r
-               sfree(head->names);\r
-               scp_sftp_dirstack_head = head->next;\r
-               sfree(head);\r
-\r
-               return 0;\r
-           }\r
-       }\r
-\r
-       /*\r
-        * Now we have a filename. Stat it, and see if it's a file\r
-        * or a directory.\r
-        */\r
-       sftp_register(req = fxp_stat_send(fname));\r
-       rreq = sftp_find_request(pktin = sftp_recv());\r
-       assert(rreq == req);\r
-       ret = fxp_stat_recv(pktin, rreq, &attrs);\r
-\r
-       if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS)) {\r
-           tell_user(stderr, "unable to identify %s: %s", fname,\r
-                     ret ? "file type not supplied" : fxp_error());\r
-           errs++;\r
-           return 1;\r
-       }\r
-\r
-       if (attrs.permissions & 0040000) {\r
-           struct scp_sftp_dirstack *newitem;\r
-           struct fxp_handle *dirhandle;\r
-           int nnames, namesize;\r
-           struct fxp_name *ournames;\r
-           struct fxp_names *names;\r
-\r
-           /*\r
-            * It's a directory. If we're not in recursive mode,\r
-            * this merits a complaint (which is fatal if the name\r
-            * was specified directly, but not if it was matched by\r
-            * a wildcard).\r
-            * \r
-            * We skip this complaint completely if\r
-            * scp_sftp_wildcard is set, because that's an\r
-            * indication that we're not actually supposed to\r
-            * _recursively_ transfer the dir, just scan it for\r
-            * things matching the wildcard.\r
-            */\r
-           if (!scp_sftp_recursive && !scp_sftp_wildcard) {\r
-               tell_user(stderr, "pscp: %s: is a directory", fname);\r
-               errs++;\r
-               if (must_free_fname) sfree(fname);\r
-               if (scp_sftp_dirstack_head) {\r
-                   act->action = SCP_SINK_RETRY;\r
-                   return 0;\r
-               } else {\r
-                   return 1;\r
-               }\r
-           }\r
-\r
-           /*\r
-            * Otherwise, the fun begins. We must fxp_opendir() the\r
-            * directory, slurp the filenames into memory, return\r
-            * SCP_SINK_DIR (unless this is a wildcard match), and\r
-            * set targetisdir. The next time we're called, we will\r
-            * run through the list of filenames one by one,\r
-            * matching them against a wildcard if present.\r
-            * \r
-            * If targetisdir is _already_ set (meaning we're\r
-            * already in the middle of going through another such\r
-            * list), we must push the other (target,namelist) pair\r
-            * on a stack.\r
-            */\r
-           sftp_register(req = fxp_opendir_send(fname));\r
-           rreq = sftp_find_request(pktin = sftp_recv());\r
-           assert(rreq == req);\r
-           dirhandle = fxp_opendir_recv(pktin, rreq);\r
-\r
-           if (!dirhandle) {\r
-               tell_user(stderr, "scp: unable to open directory %s: %s",\r
-                         fname, fxp_error());\r
-               if (must_free_fname) sfree(fname);\r
-               errs++;\r
-               return 1;\r
-           }\r
-           nnames = namesize = 0;\r
-           ournames = NULL;\r
-           while (1) {\r
-               int i;\r
-\r
-               sftp_register(req = fxp_readdir_send(dirhandle));\r
-               rreq = sftp_find_request(pktin = sftp_recv());\r
-               assert(rreq == req);\r
-               names = fxp_readdir_recv(pktin, rreq);\r
-\r
-               if (names == NULL) {\r
-                   if (fxp_error_type() == SSH_FX_EOF)\r
-                       break;\r
-                   tell_user(stderr, "scp: reading directory %s: %s\n",\r
-                             fname, fxp_error());\r
-                   if (must_free_fname) sfree(fname);\r
-                   sfree(ournames);\r
-                   errs++;\r
-                   return 1;\r
-               }\r
-               if (names->nnames == 0) {\r
-                   fxp_free_names(names);\r
-                   break;\r
-               }\r
-               if (nnames + names->nnames >= namesize) {\r
-                   namesize += names->nnames + 128;\r
-                   ournames = sresize(ournames, namesize, struct fxp_name);\r
-               }\r
-               for (i = 0; i < names->nnames; i++) {\r
-                   if (!strcmp(names->names[i].filename, ".") ||\r
-                       !strcmp(names->names[i].filename, "..")) {\r
-                       /*\r
-                        * . and .. are normal consequences of\r
-                        * reading a directory, and aren't worth\r
-                        * complaining about.\r
-                        */\r
-                   } else if (!vet_filename(names->names[i].filename)) {\r
-                       tell_user(stderr, "ignoring potentially dangerous server-"\r
-                                 "supplied filename '%s'\n",\r
-                                 names->names[i].filename);\r
-                   } else\r
-                       ournames[nnames++] = names->names[i];\r
-               }\r
-               names->nnames = 0;             /* prevent free_names */\r
-               fxp_free_names(names);\r
-           }\r
-           sftp_register(req = fxp_close_send(dirhandle));\r
-           rreq = sftp_find_request(pktin = sftp_recv());\r
-           assert(rreq == req);\r
-           fxp_close_recv(pktin, rreq);\r
-\r
-           newitem = snew(struct scp_sftp_dirstack);\r
-           newitem->next = scp_sftp_dirstack_head;\r
-           newitem->names = ournames;\r
-           newitem->namepos = 0;\r
-           newitem->namelen = nnames;\r
-           if (must_free_fname)\r
-               newitem->dirpath = fname;\r
-           else\r
-               newitem->dirpath = dupstr(fname);\r
-           if (scp_sftp_wildcard) {\r
-               newitem->wildcard = scp_sftp_wildcard;\r
-               newitem->matched_something = 0;\r
-               scp_sftp_wildcard = NULL;\r
-           } else {\r
-               newitem->wildcard = NULL;\r
-           }\r
-           scp_sftp_dirstack_head = newitem;\r
-\r
-           if (newitem->wildcard) {\r
-               act->action = SCP_SINK_RETRY;\r
-           } else {\r
-               act->action = SCP_SINK_DIR;\r
-               act->buf = dupstr(stripslashes(fname, 0));\r
-               act->name = act->buf;\r
-               act->size = uint64_make(0,0);     /* duhh, it's a directory */\r
-               act->mode = 07777 & attrs.permissions;\r
-               if (scp_sftp_preserve &&\r
-                   (attrs.flags & SSH_FILEXFER_ATTR_ACMODTIME)) {\r
-                   act->atime = attrs.atime;\r
-                   act->mtime = attrs.mtime;\r
-                   act->settime = 1;\r
-               } else\r
-                   act->settime = 0;\r
-           }\r
-           return 0;\r
-\r
-       } else {\r
-           /*\r
-            * It's a file. Return SCP_SINK_FILE.\r
-            */\r
-           act->action = SCP_SINK_FILE;\r
-           act->buf = dupstr(stripslashes(fname, 0));\r
-           act->name = act->buf;\r
-           if (attrs.flags & SSH_FILEXFER_ATTR_SIZE) {\r
-               act->size = attrs.size;\r
-           } else\r
-               act->size = uint64_make(ULONG_MAX,ULONG_MAX);   /* no idea */\r
-           act->mode = 07777 & attrs.permissions;\r
-           if (scp_sftp_preserve &&\r
-               (attrs.flags & SSH_FILEXFER_ATTR_ACMODTIME)) {\r
-               act->atime = attrs.atime;\r
-               act->mtime = attrs.mtime;\r
-               act->settime = 1;\r
-           } else\r
-               act->settime = 0;\r
-           if (must_free_fname)\r
-               scp_sftp_currentname = fname;\r
-           else\r
-               scp_sftp_currentname = dupstr(fname);\r
-           return 0;\r
-       }\r
-\r
-    } else {\r
-       int done = 0;\r
-       int i, bufsize;\r
-       int action;\r
-       char ch;\r
-\r
-       act->settime = 0;\r
-       act->buf = NULL;\r
-       bufsize = 0;\r
-\r
-       while (!done) {\r
-           if (ssh_scp_recv((unsigned char *) &ch, 1) <= 0)\r
-               return 1;\r
-           if (ch == '\n')\r
-               bump("Protocol error: Unexpected newline");\r
-           i = 0;\r
-           action = ch;\r
-           do {\r
-               if (ssh_scp_recv((unsigned char *) &ch, 1) <= 0)\r
-                   bump("Lost connection");\r
-               if (i >= bufsize) {\r
-                   bufsize = i + 128;\r
-                   act->buf = sresize(act->buf, bufsize, char);\r
-               }\r
-               act->buf[i++] = ch;\r
-           } while (ch != '\n');\r
-           act->buf[i - 1] = '\0';\r
-           switch (action) {\r
-             case '\01':                      /* error */\r
-               tell_user(stderr, "%s\n", act->buf);\r
-               errs++;\r
-               continue;                      /* go round again */\r
-             case '\02':                      /* fatal error */\r
-               bump("%s", act->buf);\r
-             case 'E':\r
-               back->send(backhandle, "", 1);\r
-               act->action = SCP_SINK_ENDDIR;\r
-               return 0;\r
-             case 'T':\r
-               if (sscanf(act->buf, "%ld %*d %ld %*d",\r
-                          &act->mtime, &act->atime) == 2) {\r
-                   act->settime = 1;\r
-                   back->send(backhandle, "", 1);\r
-                   continue;          /* go round again */\r
-               }\r
-               bump("Protocol error: Illegal time format");\r
-             case 'C':\r
-             case 'D':\r
-               act->action = (action == 'C' ? SCP_SINK_FILE : SCP_SINK_DIR);\r
-               break;\r
-             default:\r
-               bump("Protocol error: Expected control record");\r
-           }\r
-           /*\r
-            * We will go round this loop only once, unless we hit\r
-            * `continue' above.\r
-            */\r
-           done = 1;\r
-       }\r
-\r
-       /*\r
-        * If we get here, we must have seen SCP_SINK_FILE or\r
-        * SCP_SINK_DIR.\r
-        */\r
-       {\r
-           char sizestr[40];\r
-       \r
-           if (sscanf(act->buf, "%o %s %n", &act->mode, sizestr, &i) != 2)\r
-               bump("Protocol error: Illegal file descriptor format");\r
-           act->size = uint64_from_decimal(sizestr);\r
-           act->name = act->buf + i;\r
-           return 0;\r
-       }\r
-    }\r
-}\r
-\r
-int scp_accept_filexfer(void)\r
-{\r
-    if (using_sftp) {\r
-       struct sftp_packet *pktin;\r
-       struct sftp_request *req, *rreq;\r
-\r
-       sftp_register(req = fxp_open_send(scp_sftp_currentname, SSH_FXF_READ));\r
-       rreq = sftp_find_request(pktin = sftp_recv());\r
-       assert(rreq == req);\r
-       scp_sftp_filehandle = fxp_open_recv(pktin, rreq);\r
-\r
-       if (!scp_sftp_filehandle) {\r
-           tell_user(stderr, "pscp: unable to open %s: %s",\r
-                     scp_sftp_currentname, fxp_error());\r
-           errs++;\r
-           return 1;\r
-       }\r
-       scp_sftp_fileoffset = uint64_make(0, 0);\r
-       scp_sftp_xfer = xfer_download_init(scp_sftp_filehandle,\r
-                                          scp_sftp_fileoffset);\r
-       sfree(scp_sftp_currentname);\r
-       return 0;\r
-    } else {\r
-       back->send(backhandle, "", 1);\r
-       return 0;                      /* can't fail */\r
-    }\r
-}\r
-\r
-int scp_recv_filedata(char *data, int len)\r
-{\r
-    if (using_sftp) {\r
-       struct sftp_packet *pktin;\r
-       int ret, actuallen;\r
-       void *vbuf;\r
-\r
-       xfer_download_queue(scp_sftp_xfer);\r
-       pktin = sftp_recv();\r
-       ret = xfer_download_gotpkt(scp_sftp_xfer, pktin);\r
-\r
-       if (ret < 0) {\r
-           tell_user(stderr, "pscp: error while reading: %s", fxp_error());\r
-           errs++;\r
-           return -1;\r
-       }\r
-\r
-       if (xfer_download_data(scp_sftp_xfer, &vbuf, &actuallen)) {\r
-           /*\r
-            * This assertion relies on the fact that the natural\r
-            * block size used in the xfer manager is at most that\r
-            * used in this module. I don't like crossing layers in\r
-            * this way, but it'll do for now.\r
-            */\r
-           assert(actuallen <= len);\r
-           memcpy(data, vbuf, actuallen);\r
-           sfree(vbuf);\r
-       } else\r
-           actuallen = 0;\r
-\r
-       scp_sftp_fileoffset = uint64_add32(scp_sftp_fileoffset, actuallen);\r
-\r
-       return actuallen;\r
-    } else {\r
-       return ssh_scp_recv((unsigned char *) data, len);\r
-    }\r
-}\r
-\r
-int scp_finish_filerecv(void)\r
-{\r
-    if (using_sftp) {\r
-       struct sftp_packet *pktin;\r
-       struct sftp_request *req, *rreq;\r
-\r
-       /*\r
-        * Ensure that xfer_done() will work correctly, so we can\r
-        * clean up any outstanding requests from the file\r
-        * transfer.\r
-        */\r
-       xfer_set_error(scp_sftp_xfer);\r
-       while (!xfer_done(scp_sftp_xfer)) {\r
-           void *vbuf;\r
-           int len;\r
-\r
-           pktin = sftp_recv();\r
-           xfer_download_gotpkt(scp_sftp_xfer, pktin);\r
-           if (xfer_download_data(scp_sftp_xfer, &vbuf, &len))\r
-               sfree(vbuf);\r
-       }\r
-       xfer_cleanup(scp_sftp_xfer);\r
-\r
-       sftp_register(req = fxp_close_send(scp_sftp_filehandle));\r
-       rreq = sftp_find_request(pktin = sftp_recv());\r
-       assert(rreq == req);\r
-       fxp_close_recv(pktin, rreq);\r
-       return 0;\r
-    } else {\r
-       back->send(backhandle, "", 1);\r
-       return response();\r
-    }\r
-}\r
-\r
-/* ----------------------------------------------------------------------\r
- *  Send an error message to the other side and to the screen.\r
- *  Increment error counter.\r
- */\r
-static void run_err(const char *fmt, ...)\r
-{\r
-    char *str, *str2;\r
-    va_list ap;\r
-    va_start(ap, fmt);\r
-    errs++;\r
-    str = dupvprintf(fmt, ap);\r
-    str2 = dupcat("scp: ", str, "\n", NULL);\r
-    sfree(str);\r
-    scp_send_errmsg(str2);\r
-    tell_user(stderr, "%s", str2);\r
-    va_end(ap);\r
-    sfree(str2);\r
-}\r
-\r
-/*\r
- *  Execute the source part of the SCP protocol.\r
- */\r
-static void source(char *src)\r
-{\r
-    uint64 size;\r
-    unsigned long mtime, atime;\r
-    char *last;\r
-    RFile *f;\r
-    int attr;\r
-    uint64 i;\r
-    uint64 stat_bytes;\r
-    time_t stat_starttime, stat_lasttime;\r
-\r
-    attr = file_type(src);\r
-    if (attr == FILE_TYPE_NONEXISTENT ||\r
-       attr == FILE_TYPE_WEIRD) {\r
-       run_err("%s: %s file or directory", src,\r
-               (attr == FILE_TYPE_WEIRD ? "Not a" : "No such"));\r
-       return;\r
-    }\r
-\r
-    if (attr == FILE_TYPE_DIRECTORY) {\r
-       if (recursive) {\r
-           /*\r
-            * Avoid . and .. directories.\r
-            */\r
-           char *p;\r
-           p = strrchr(src, '/');\r
-           if (!p)\r
-               p = strrchr(src, '\\');\r
-           if (!p)\r
-               p = src;\r
-           else\r
-               p++;\r
-           if (!strcmp(p, ".") || !strcmp(p, ".."))\r
-               /* skip . and .. */ ;\r
-           else\r
-               rsource(src);\r
-       } else {\r
-           run_err("%s: not a regular file", src);\r
-       }\r
-       return;\r
-    }\r
-\r
-    if ((last = strrchr(src, '/')) == NULL)\r
-       last = src;\r
-    else\r
-       last++;\r
-    if (strrchr(last, '\\') != NULL)\r
-       last = strrchr(last, '\\') + 1;\r
-    if (last == src && strchr(src, ':') != NULL)\r
-       last = strchr(src, ':') + 1;\r
-\r
-    f = open_existing_file(src, &size, &mtime, &atime);\r
-    if (f == NULL) {\r
-       run_err("%s: Cannot open file", src);\r
-       return;\r
-    }\r
-    if (preserve) {\r
-       if (scp_send_filetimes(mtime, atime))\r
-           return;\r
-    }\r
-\r
-    if (verbose) {\r
-       char sizestr[40];\r
-       uint64_decimal(size, sizestr);\r
-       tell_user(stderr, "Sending file %s, size=%s", last, sizestr);\r
-    }\r
-    if (scp_send_filename(last, size, 0644))\r
-       return;\r
-\r
-    stat_bytes = uint64_make(0,0);\r
-    stat_starttime = time(NULL);\r
-    stat_lasttime = 0;\r
-\r
-    for (i = uint64_make(0,0);\r
-        uint64_compare(i,size) < 0;\r
-        i = uint64_add32(i,4096)) {\r
-       char transbuf[4096];\r
-       int j, k = 4096;\r
-\r
-       if (uint64_compare(uint64_add32(i, k),size) > 0) /* i + k > size */ \r
-           k = (uint64_subtract(size, i)).lo;  /* k = size - i; */\r
-       if ((j = read_from_file(f, transbuf, k)) != k) {\r
-           if (statistics)\r
-               printf("\n");\r
-           bump("%s: Read error", src);\r
-       }\r
-       if (scp_send_filedata(transbuf, k))\r
-           bump("%s: Network error occurred", src);\r
-\r
-       if (statistics) {\r
-           stat_bytes = uint64_add32(stat_bytes, k);\r
-           if (time(NULL) != stat_lasttime ||\r
-               (uint64_compare(uint64_add32(i, k), size) == 0)) {\r
-               stat_lasttime = time(NULL);\r
-               print_stats(last, size, stat_bytes,\r
-                           stat_starttime, stat_lasttime);\r
-           }\r
-       }\r
-\r
-    }\r
-    close_rfile(f);\r
-\r
-    (void) scp_send_finish();\r
-}\r
-\r
-/*\r
- *  Recursively send the contents of a directory.\r
- */\r
-static void rsource(char *src)\r
-{\r
-    char *last;\r
-    char *save_target;\r
-    DirHandle *dir;\r
-\r
-    if ((last = strrchr(src, '/')) == NULL)\r
-       last = src;\r
-    else\r
-       last++;\r
-    if (strrchr(last, '\\') != NULL)\r
-       last = strrchr(last, '\\') + 1;\r
-    if (last == src && strchr(src, ':') != NULL)\r
-       last = strchr(src, ':') + 1;\r
-\r
-    /* maybe send filetime */\r
-\r
-    save_target = scp_save_remotepath();\r
-\r
-    if (verbose)\r
-       tell_user(stderr, "Entering directory: %s", last);\r
-    if (scp_send_dirname(last, 0755))\r
-       return;\r
-\r
-    dir = open_directory(src);\r
-    if (dir != NULL) {\r
-       char *filename;\r
-       while ((filename = read_filename(dir)) != NULL) {\r
-           char *foundfile = dupcat(src, "/", filename, NULL);\r
-           source(foundfile);\r
-           sfree(foundfile);\r
-           sfree(filename);\r
-       }\r
-    }\r
-    close_directory(dir);\r
-\r
-    (void) scp_send_enddir();\r
-\r
-    scp_restore_remotepath(save_target);\r
-}\r
-\r
-/*\r
- * Execute the sink part of the SCP protocol.\r
- */\r
-static void sink(char *targ, char *src)\r
-{\r
-    char *destfname;\r
-    int targisdir = 0;\r
-    int exists;\r
-    int attr;\r
-    WFile *f;\r
-    uint64 received;\r
-    int wrerror = 0;\r
-    uint64 stat_bytes;\r
-    time_t stat_starttime, stat_lasttime;\r
-    char *stat_name;\r
-\r
-    attr = file_type(targ);\r
-    if (attr == FILE_TYPE_DIRECTORY)\r
-       targisdir = 1;\r
-\r
-    if (targetshouldbedirectory && !targisdir)\r
-       bump("%s: Not a directory", targ);\r
-\r
-    scp_sink_init();\r
-    while (1) {\r
-       struct scp_sink_action act;\r
-       if (scp_get_sink_action(&act))\r
-           return;\r
-\r
-       if (act.action == SCP_SINK_ENDDIR)\r
-           return;\r
-\r
-       if (act.action == SCP_SINK_RETRY)\r
-           continue;\r
-\r
-       if (targisdir) {\r
-           /*\r
-            * Prevent the remote side from maliciously writing to\r
-            * files outside the target area by sending a filename\r
-            * containing `../'. In fact, it shouldn't be sending\r
-            * filenames with any slashes or colons in at all; so\r
-            * we'll find the last slash, backslash or colon in the\r
-            * filename and use only the part after that. (And\r
-            * warn!)\r
-            * \r
-            * In addition, we also ensure here that if we're\r
-            * copying a single file and the target is a directory\r
-            * (common usage: `pscp host:filename .') the remote\r
-            * can't send us a _different_ file name. We can\r
-            * distinguish this case because `src' will be non-NULL\r
-            * and the last component of that will fail to match\r
-            * (the last component of) the name sent.\r
-            * \r
-            * Well, not always; if `src' is a wildcard, we do\r
-            * expect to get back filenames that don't correspond\r
-            * exactly to it. Ideally in this case, we would like\r
-            * to ensure that the returned filename actually\r
-            * matches the wildcard pattern - but one of SCP's\r
-            * protocol infelicities is that wildcard matching is\r
-            * done at the server end _by the server's rules_ and\r
-            * so in general this is infeasible. Hence, we only\r
-            * accept filenames that don't correspond to `src' if\r
-            * unsafe mode is enabled or we are using SFTP (which\r
-            * resolves remote wildcards on the client side and can\r
-            * be trusted).\r
-            */\r
-           char *striptarget, *stripsrc;\r
-\r
-           striptarget = stripslashes(act.name, 1);\r
-           if (striptarget != act.name) {\r
-               tell_user(stderr, "warning: remote host sent a compound"\r
-                         " pathname '%s'", act.name);\r
-               tell_user(stderr, "         renaming local file to '%s'",\r
-                          striptarget);\r
-           }\r
-\r
-           /*\r
-            * Also check to see if the target filename is '.' or\r
-            * '..', or indeed '...' and so on because Windows\r
-            * appears to interpret those like '..'.\r
-            */\r
-           if (is_dots(striptarget)) {\r
-               bump("security violation: remote host attempted to write to"\r
-                    " a '.' or '..' path!");\r
-           }\r
-\r
-           if (src) {\r
-               stripsrc = stripslashes(src, 1);\r
-               if (strcmp(striptarget, stripsrc) &&\r
-                   !using_sftp && !scp_unsafe_mode) {\r
-                   tell_user(stderr, "warning: remote host tried to write "\r
-                             "to a file called '%s'", striptarget);\r
-                   tell_user(stderr, "         when we requested a file "\r
-                             "called '%s'.", stripsrc);\r
-                   tell_user(stderr, "         If this is a wildcard, "\r
-                             "consider upgrading to SSH-2 or using");\r
-                   tell_user(stderr, "         the '-unsafe' option. Renaming"\r
-                             " of this file has been disallowed.");\r
-                   /* Override the name the server provided with our own. */\r
-                   striptarget = stripsrc;\r
-               }\r
-           }\r
-\r
-           if (targ[0] != '\0')\r
-               destfname = dir_file_cat(targ, striptarget);\r
-           else\r
-               destfname = dupstr(striptarget);\r
-       } else {\r
-           /*\r
-            * In this branch of the if, the target area is a\r
-            * single file with an explicitly specified name in any\r
-            * case, so there's no danger.\r
-            */\r
-           destfname = dupstr(targ);\r
-       }\r
-       attr = file_type(destfname);\r
-       exists = (attr != FILE_TYPE_NONEXISTENT);\r
-\r
-       if (act.action == SCP_SINK_DIR) {\r
-           if (exists && attr != FILE_TYPE_DIRECTORY) {\r
-               run_err("%s: Not a directory", destfname);\r
-               continue;\r
-           }\r
-           if (!exists) {\r
-               if (!create_directory(destfname)) {\r
-                   run_err("%s: Cannot create directory", destfname);\r
-                   continue;\r
-               }\r
-           }\r
-           sink(destfname, NULL);\r
-           /* can we set the timestamp for directories ? */\r
-           continue;\r
-       }\r
-\r
-       f = open_new_file(destfname);\r
-       if (f == NULL) {\r
-           run_err("%s: Cannot create file", destfname);\r
-           continue;\r
-       }\r
-\r
-       if (scp_accept_filexfer())\r
-           return;\r
-\r
-       stat_bytes = uint64_make(0, 0);\r
-       stat_starttime = time(NULL);\r
-       stat_lasttime = 0;\r
-       stat_name = stripslashes(destfname, 1);\r
-\r
-       received = uint64_make(0, 0);\r
-       while (uint64_compare(received,act.size) < 0) {\r
-           char transbuf[32768];\r
-           uint64 blksize;\r
-           int read;\r
-           blksize = uint64_make(0, 32768);\r
-           if (uint64_compare(blksize,uint64_subtract(act.size,received)) > 0)\r
-             blksize = uint64_subtract(act.size,received);\r
-           read = scp_recv_filedata(transbuf, (int)blksize.lo);\r
-           if (read <= 0)\r
-               bump("Lost connection");\r
-           if (wrerror)\r
-               continue;\r
-           if (write_to_file(f, transbuf, read) != (int)read) {\r
-               wrerror = 1;\r
-               /* FIXME: in sftp we can actually abort the transfer */\r
-               if (statistics)\r
-                   printf("\r%-25.25s | %50s\n",\r
-                          stat_name,\r
-                          "Write error.. waiting for end of file");\r
-               continue;\r
-           }\r
-           if (statistics) {\r
-               stat_bytes = uint64_add32(stat_bytes,read);\r
-               if (time(NULL) > stat_lasttime ||\r
-                   uint64_compare(uint64_add32(received, read), act.size) == 0) {\r
-                   stat_lasttime = time(NULL);\r
-                   print_stats(stat_name, act.size, stat_bytes,\r
-                               stat_starttime, stat_lasttime);\r
-               }\r
-           }\r
-           received = uint64_add32(received, read);\r
-       }\r
-       if (act.settime) {\r
-           set_file_times(f, act.mtime, act.atime);\r
-       }\r
-\r
-       close_wfile(f);\r
-       if (wrerror) {\r
-           run_err("%s: Write error", destfname);\r
-           continue;\r
-       }\r
-       (void) scp_finish_filerecv();\r
-       sfree(destfname);\r
-       sfree(act.buf);\r
-    }\r
-}\r
-\r
-/*\r
- * We will copy local files to a remote server.\r
- */\r
-static void toremote(int argc, char *argv[])\r
-{\r
-    char *src, *targ, *host, *user;\r
-    char *cmd;\r
-    int i, wc_type;\r
-\r
-    targ = argv[argc - 1];\r
-\r
-    /* Separate host from filename */\r
-    host = targ;\r
-    targ = colon(targ);\r
-    if (targ == NULL)\r
-       bump("targ == NULL in toremote()");\r
-    *targ++ = '\0';\r
-    if (*targ == '\0')\r
-       targ = ".";\r
-    /* Substitute "." for empty target */\r
-\r
-    /* Separate host and username */\r
-    user = host;\r
-    host = strrchr(host, '@');\r
-    if (host == NULL) {\r
-       host = user;\r
-       user = NULL;\r
-    } else {\r
-       *host++ = '\0';\r
-       if (*user == '\0')\r
-           user = NULL;\r
-    }\r
-\r
-    if (argc == 2) {\r
-       if (colon(argv[0]) != NULL)\r
-           bump("%s: Remote to remote not supported", argv[0]);\r
-\r
-       wc_type = test_wildcard(argv[0], 1);\r
-       if (wc_type == WCTYPE_NONEXISTENT)\r
-           bump("%s: No such file or directory\n", argv[0]);\r
-       else if (wc_type == WCTYPE_WILDCARD)\r
-           targetshouldbedirectory = 1;\r
-    }\r
-\r
-    cmd = dupprintf("scp%s%s%s%s -t %s",\r
-                   verbose ? " -v" : "",\r
-                   recursive ? " -r" : "",\r
-                   preserve ? " -p" : "",\r
-                   targetshouldbedirectory ? " -d" : "", targ);\r
-    do_cmd(host, user, cmd);\r
-    sfree(cmd);\r
-\r
-    if (scp_source_setup(targ, targetshouldbedirectory))\r
-       return;\r
-\r
-    for (i = 0; i < argc - 1; i++) {\r
-       src = argv[i];\r
-       if (colon(src) != NULL) {\r
-           tell_user(stderr, "%s: Remote to remote not supported\n", src);\r
-           errs++;\r
-           continue;\r
-       }\r
-\r
-       wc_type = test_wildcard(src, 1);\r
-       if (wc_type == WCTYPE_NONEXISTENT) {\r
-           run_err("%s: No such file or directory", src);\r
-           continue;\r
-       } else if (wc_type == WCTYPE_FILENAME) {\r
-           source(src);\r
-           continue;\r
-       } else {\r
-           WildcardMatcher *wc;\r
-           char *filename;\r
-\r
-           wc = begin_wildcard_matching(src);\r
-           if (wc == NULL) {\r
-               run_err("%s: No such file or directory", src);\r
-               continue;\r
-           }\r
-\r
-           while ((filename = wildcard_get_filename(wc)) != NULL) {\r
-               source(filename);\r
-               sfree(filename);\r
-           }\r
-\r
-           finish_wildcard_matching(wc);\r
-       }\r
-    }\r
-}\r
-\r
-/*\r
- *  We will copy files from a remote server to the local machine.\r
- */\r
-static void tolocal(int argc, char *argv[])\r
-{\r
-    char *src, *targ, *host, *user;\r
-    char *cmd;\r
-\r
-    if (argc != 2)\r
-       bump("More than one remote source not supported");\r
-\r
-    src = argv[0];\r
-    targ = argv[1];\r
-\r
-    /* Separate host from filename */\r
-    host = src;\r
-    src = colon(src);\r
-    if (src == NULL)\r
-       bump("Local to local copy not supported");\r
-    *src++ = '\0';\r
-    if (*src == '\0')\r
-       src = ".";\r
-    /* Substitute "." for empty filename */\r
-\r
-    /* Separate username and hostname */\r
-    user = host;\r
-    host = strrchr(host, '@');\r
-    if (host == NULL) {\r
-       host = user;\r
-       user = NULL;\r
-    } else {\r
-       *host++ = '\0';\r
-       if (*user == '\0')\r
-           user = NULL;\r
-    }\r
-\r
-    cmd = dupprintf("scp%s%s%s%s -f %s",\r
-                   verbose ? " -v" : "",\r
-                   recursive ? " -r" : "",\r
-                   preserve ? " -p" : "",\r
-                   targetshouldbedirectory ? " -d" : "", src);\r
-    do_cmd(host, user, cmd);\r
-    sfree(cmd);\r
-\r
-    if (scp_sink_setup(src, preserve, recursive))\r
-       return;\r
-\r
-    sink(targ, src);\r
-}\r
-\r
-/*\r
- *  We will issue a list command to get a remote directory.\r
- */\r
-static void get_dir_list(int argc, char *argv[])\r
-{\r
-    char *src, *host, *user;\r
-    char *cmd, *p, *q;\r
-    char c;\r
-\r
-    src = argv[0];\r
-\r
-    /* Separate host from filename */\r
-    host = src;\r
-    src = colon(src);\r
-    if (src == NULL)\r
-       bump("Local file listing not supported");\r
-    *src++ = '\0';\r
-    if (*src == '\0')\r
-       src = ".";\r
-    /* Substitute "." for empty filename */\r
-\r
-    /* Separate username and hostname */\r
-    user = host;\r
-    host = strrchr(host, '@');\r
-    if (host == NULL) {\r
-       host = user;\r
-       user = NULL;\r
-    } else {\r
-       *host++ = '\0';\r
-       if (*user == '\0')\r
-           user = NULL;\r
-    }\r
-\r
-    cmd = snewn(4 * strlen(src) + 100, char);\r
-    strcpy(cmd, "ls -la '");\r
-    p = cmd + strlen(cmd);\r
-    for (q = src; *q; q++) {\r
-       if (*q == '\'') {\r
-           *p++ = '\'';\r
-           *p++ = '\\';\r
-           *p++ = '\'';\r
-           *p++ = '\'';\r
-       } else {\r
-           *p++ = *q;\r
-       }\r
-    }\r
-    *p++ = '\'';\r
-    *p = '\0';\r
-\r
-    do_cmd(host, user, cmd);\r
-    sfree(cmd);\r
-\r
-    if (using_sftp) {\r
-       scp_sftp_listdir(src);\r
-    } else {\r
-       while (ssh_scp_recv((unsigned char *) &c, 1) > 0)\r
-           tell_char(stdout, c);\r
-    }\r
-}\r
-\r
-/*\r
- *  Short description of parameters.\r
- */\r
-static void usage(void)\r
-{\r
-    printf("PuTTY Secure Copy client\n");\r
-    printf("%s\n", ver);\r
-    printf("Usage: pscp [options] [user@]host:source target\n");\r
-    printf\r
-       ("       pscp [options] source [source...] [user@]host:target\n");\r
-    printf("       pscp [options] -ls [user@]host:filespec\n");\r
-    printf("Options:\n");\r
-    printf("  -V        print version information and exit\n");\r
-    printf("  -pgpfp    print PGP key fingerprints and exit\n");\r
-    printf("  -p        preserve file attributes\n");\r
-    printf("  -q        quiet, don't show statistics\n");\r
-    printf("  -r        copy directories recursively\n");\r
-    printf("  -v        show verbose messages\n");\r
-    printf("  -load sessname  Load settings from saved session\n");\r
-    printf("  -P port   connect to specified port\n");\r
-    printf("  -l user   connect with specified username\n");\r
-    printf("  -pw passw login with specified password\n");\r
-    printf("  -1 -2     force use of particular SSH protocol version\n");\r
-    printf("  -4 -6     force use of IPv4 or IPv6\n");\r
-    printf("  -C        enable compression\n");\r
-    printf("  -i key    private key file for authentication\n");\r
-    printf("  -noagent  disable use of Pageant\n");\r
-    printf("  -agent    enable use of Pageant\n");\r
-    printf("  -batch    disable all interactive prompts\n");\r
-    printf("  -unsafe   allow server-side wildcards (DANGEROUS)\n");\r
-    printf("  -sftp     force use of SFTP protocol\n");\r
-    printf("  -scp      force use of SCP protocol\n");\r
-#if 0\r
-    /*\r
-     * -gui is an internal option, used by GUI front ends to get\r
-     * pscp to pass progress reports back to them. It's not an\r
-     * ordinary user-accessible option, so it shouldn't be part of\r
-     * the command-line help. The only people who need to know\r
-     * about it are programmers, and they can read the source.\r
-     */\r
-    printf\r
-       ("  -gui hWnd GUI mode with the windows handle for receiving messages\n");\r
-#endif\r
-    cleanup_exit(1);\r
-}\r
-\r
-void version(void)\r
-{\r
-    printf("pscp: %s\n", ver);\r
-    cleanup_exit(1);\r
-}\r
-\r
-void cmdline_error(char *p, ...)\r
-{\r
-    va_list ap;\r
-    fprintf(stderr, "pscp: ");\r
-    va_start(ap, p);\r
-    vfprintf(stderr, p, ap);\r
-    va_end(ap);\r
-    fprintf(stderr, "\n      try typing just \"pscp\" for help\n");\r
-    exit(1);\r
-}\r
-\r
-/*\r
- * Main program. (Called `psftp_main' because it gets called from\r
- * *sftp.c; bit silly, I know, but it had to be called _something_.)\r
- */\r
-int psftp_main(int argc, char *argv[])\r
-{\r
-    int i;\r
-\r
-    default_protocol = PROT_TELNET;\r
-\r
-    flags = FLAG_STDERR\r
-#ifdef FLAG_SYNCAGENT\r
-       | FLAG_SYNCAGENT\r
-#endif\r
-       ;\r
-    cmdline_tooltype = TOOLTYPE_FILETRANSFER;\r
-    sk_init();\r
-\r
-    /* Load Default Settings before doing anything else. */\r
-    do_defaults(NULL, &cfg);\r
-    loaded_session = FALSE;\r
-\r
-    for (i = 1; i < argc; i++) {\r
-       int ret;\r
-       if (argv[i][0] != '-')\r
-           break;\r
-       ret = cmdline_process_param(argv[i], i+1<argc?argv[i+1]:NULL, 1, &cfg);\r
-       if (ret == -2) {\r
-           cmdline_error("option \"%s\" requires an argument", argv[i]);\r
-       } else if (ret == 2) {\r
-           i++;               /* skip next argument */\r
-       } else if (ret == 1) {\r
-           /* We have our own verbosity in addition to `flags'. */\r
-           if (flags & FLAG_VERBOSE)\r
-               verbose = 1;\r
-        } else if (strcmp(argv[i], "-pgpfp") == 0) {\r
-            pgp_fingerprints();\r
-            return 1;\r
-       } else if (strcmp(argv[i], "-r") == 0) {\r
-           recursive = 1;\r
-       } else if (strcmp(argv[i], "-p") == 0) {\r
-           preserve = 1;\r
-       } else if (strcmp(argv[i], "-q") == 0) {\r
-           statistics = 0;\r
-       } else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-?") == 0) {\r
-           usage();\r
-       } else if (strcmp(argv[i], "-V") == 0) {\r
-            version();\r
-        } else if (strcmp(argv[i], "-ls") == 0) {\r
-           list = 1;\r
-       } else if (strcmp(argv[i], "-batch") == 0) {\r
-           console_batch_mode = 1;\r
-       } else if (strcmp(argv[i], "-unsafe") == 0) {\r
-           scp_unsafe_mode = 1;\r
-       } else if (strcmp(argv[i], "-sftp") == 0) {\r
-           try_scp = 0; try_sftp = 1;\r
-       } else if (strcmp(argv[i], "-scp") == 0) {\r
-           try_scp = 1; try_sftp = 0;\r
-       } else if (strcmp(argv[i], "--") == 0) {\r
-           i++;\r
-           break;\r
-       } else {\r
-           cmdline_error("unknown option \"%s\"", argv[i]);\r
-       }\r
-    }\r
-    argc -= i;\r
-    argv += i;\r
-    back = NULL;\r
-\r
-    if (list) {\r
-       if (argc != 1)\r
-           usage();\r
-       get_dir_list(argc, argv);\r
-\r
-    } else {\r
-\r
-       if (argc < 2)\r
-           usage();\r
-       if (argc > 2)\r
-           targetshouldbedirectory = 1;\r
-\r
-       if (colon(argv[argc - 1]) != NULL)\r
-           toremote(argc, argv);\r
-       else\r
-           tolocal(argc, argv);\r
-    }\r
-\r
-    if (back != NULL && back->connected(backhandle)) {\r
-       char ch;\r
-       back->special(backhandle, TS_EOF);\r
-       ssh_scp_recv((unsigned char *) &ch, 1);\r
-    }\r
-    random_save_seed();\r
-\r
-    cmdline_cleanup();\r
-    console_provide_logctx(NULL);\r
-    back->free(backhandle);\r
-    backhandle = NULL;\r
-    back = NULL;\r
-    sk_cleanup();\r
-    return (errs == 0 ? 0 : 1);\r
-}\r
-\r
-/* end */\r