Fix culpable lack of generality in keyboard-interactive
[sgt/putty] / scp.c
CommitLineData
07d9aa13 1/*
a673e210 2 * scp.c - Scp (Secure Copy) client for PuTTY.
3 * Joris van Rantwijk, Simon Tatham
07d9aa13 4 *
a673e210 5 * This is mainly based on ssh-1.2.26/scp.c by Timo Rinne & Tatu Ylonen.
6 * They, in turn, used stuff from BSD rcp.
7 *
8 * (SGT, 2001-09-10: Joris van Rantwijk assures me that although
9 * this file as originally submitted was inspired by, and
10 * _structurally_ based on, ssh-1.2.26's scp.c, there wasn't any
11 * actual code duplicated, so the above comment shouldn't give rise
12 * to licensing issues.)
07d9aa13 13 */
14
07d9aa13 15#include <windows.h>
4d331a77 16#ifndef AUTO_WINSOCK
17#ifdef WINSOCK_TWO
18#include <winsock2.h>
19#else
07d9aa13 20#include <winsock.h>
4d331a77 21#endif
22#endif
07d9aa13 23#include <stdlib.h>
24#include <stdio.h>
25#include <string.h>
fd5e5847 26#include <limits.h>
07d9aa13 27#include <time.h>
feb7fdfe 28#include <assert.h>
07d9aa13 29
30#define PUTTY_DO_GLOBALS
31#include "putty.h"
fd5e5847 32#include "ssh.h"
33#include "sftp.h"
8c3cd914 34#include "winstuff.h"
a9422f39 35#include "storage.h"
07d9aa13 36
07d9aa13 37#define TIME_POSIX_TO_WIN(t, ft) (*(LONGLONG*)&(ft) = \
c51a56e2 38 ((LONGLONG) (t) + (LONGLONG) 11644473600) * (LONGLONG) 10000000)
07d9aa13 39#define TIME_WIN_TO_POSIX(ft, t) ((t) = (unsigned long) \
c51a56e2 40 ((*(LONGLONG*)&(ft)) / (LONGLONG) 10000000 - (LONGLONG) 11644473600))
07d9aa13 41
cc87246d 42/* GUI Adaptation - Sept 2000 */
037fb113 43
44/* This is just a base value from which the main message numbers are
45 * derived. */
cc87246d 46#define WM_APP_BASE 0x8000
037fb113 47
48/* These two pass a single character value in wParam. They represent
49 * the visible output from PSCP. */
cc87246d 50#define WM_STD_OUT_CHAR ( WM_APP_BASE+400 )
51#define WM_STD_ERR_CHAR ( WM_APP_BASE+401 )
037fb113 52
53/* These pass a transfer status update. WM_STATS_CHAR passes a single
54 * character in wParam, and is called repeatedly to pass the name of
55 * the file, terminated with "\n". WM_STATS_SIZE passes the size of
56 * the file being transferred in wParam. WM_STATS_ELAPSED is called
57 * to pass the elapsed time (in seconds) in wParam, and
58 * WM_STATS_PERCENT passes the percentage of the transfer which is
59 * complete, also in wParam. */
cc87246d 60#define WM_STATS_CHAR ( WM_APP_BASE+402 )
61#define WM_STATS_SIZE ( WM_APP_BASE+403 )
62#define WM_STATS_PERCENT ( WM_APP_BASE+404 )
63#define WM_STATS_ELAPSED ( WM_APP_BASE+405 )
037fb113 64
65/* These are used at the end of a run to pass an error code in
66 * wParam: zero means success, nonzero means failure. WM_RET_ERR_CNT
67 * is used after a copy, and WM_LS_RET_ERR_CNT is used after a file
68 * list operation. */
cc87246d 69#define WM_RET_ERR_CNT ( WM_APP_BASE+406 )
70#define WM_LS_RET_ERR_CNT ( WM_APP_BASE+407 )
037fb113 71
72/* More transfer status update messages. WM_STATS_DONE passes the
73 * number of bytes sent so far in wParam. WM_STATS_ETA passes the
74 * estimated time to completion (in seconds). WM_STATS_RATEBS passes
75 * the average transfer rate (in bytes per second). */
d524be1c 76#define WM_STATS_DONE ( WM_APP_BASE+408 )
77#define WM_STATS_ETA ( WM_APP_BASE+409 )
78#define WM_STATS_RATEBS ( WM_APP_BASE+410 )
cc87246d 79
2bc6a386 80static int list = 0;
fb09bf1c 81static int verbose = 0;
07d9aa13 82static int recursive = 0;
83static int preserve = 0;
84static int targetshouldbedirectory = 0;
85static int statistics = 1;
b8a19193 86static int portnumber = 0;
b1daf518 87static int prev_stats_len = 0;
cd1f39ab 88static int scp_unsafe_mode = 0;
b8a19193 89static char *password = NULL;
07d9aa13 90static int errs = 0;
cc87246d 91/* GUI Adaptation - Sept 2000 */
92#define NAME_STR_MAX 2048
32874aea 93static char statname[NAME_STR_MAX + 1];
cc87246d 94static unsigned long statsize = 0;
d524be1c 95static unsigned long statdone = 0;
96static unsigned long stateta = 0;
97static unsigned long statratebs = 0;
cc87246d 98static int statperct = 0;
90a14a09 99static unsigned long statelapsed = 0;
cc87246d 100static int gui_mode = 0;
101static char *gui_hwnd = NULL;
fd5e5847 102static int using_sftp = 0;
07d9aa13 103
104static void source(char *src);
105static void rsource(char *src);
ca2d5943 106static void sink(char *targ, char *src);
cc87246d 107/* GUI Adaptation - Sept 2000 */
32874aea 108static void tell_char(FILE * stream, char c);
109static void tell_str(FILE * stream, char *str);
110static void tell_user(FILE * stream, char *fmt, ...);
90a14a09 111static void gui_update_stats(char *name, unsigned long size,
d524be1c 112 int percentage, unsigned long elapsed,
113 unsigned long done, unsigned long eta,
114 unsigned long ratebs);
07d9aa13 115
5471d09a 116/*
117 * The maximum amount of queued data we accept before we stop and
118 * wait for the server to process some.
119 */
120#define MAX_SCP_BUFSIZE 16384
121
760e88b2 122void ldisc_send(char *buf, int len, int interactive)
32874aea 123{
feb7fdfe 124 /*
125 * This is only here because of the calls to ldisc_send(NULL,
126 * 0) in ssh.c. Nothing in PSCP actually needs to use the ldisc
127 * as an ldisc. So if we get called with any real data, I want
128 * to know about it.
129 */
130 assert(len == 0);
131}
132
cc87246d 133/* GUI Adaptation - Sept 2000 */
75cab814 134static void send_msg(HWND h, UINT message, WPARAM wParam)
cc87246d 135{
32874aea 136 while (!PostMessage(h, message, wParam, 0))
137 SleepEx(1000, TRUE);
cc87246d 138}
139
32874aea 140static void tell_char(FILE * stream, char c)
cc87246d 141{
142 if (!gui_mode)
143 fputc(c, stream);
32874aea 144 else {
cc87246d 145 unsigned int msg_id = WM_STD_OUT_CHAR;
32874aea 146 if (stream == stderr)
147 msg_id = WM_STD_ERR_CHAR;
148 send_msg((HWND) atoi(gui_hwnd), msg_id, (WPARAM) c);
cc87246d 149 }
150}
151
32874aea 152static void tell_str(FILE * stream, char *str)
cc87246d 153{
154 unsigned int i;
155
32874aea 156 for (i = 0; i < strlen(str); ++i)
cc87246d 157 tell_char(stream, str[i]);
158}
159
32874aea 160static void tell_user(FILE * stream, char *fmt, ...)
cc87246d 161{
32874aea 162 char str[0x100]; /* Make the size big enough */
cc87246d 163 va_list ap;
164 va_start(ap, fmt);
165 vsprintf(str, fmt, ap);
166 va_end(ap);
167 strcat(str, "\n");
168 tell_str(stream, str);
169}
170
32874aea 171static void gui_update_stats(char *name, unsigned long size,
d524be1c 172 int percentage, unsigned long elapsed,
173 unsigned long done, unsigned long eta,
174 unsigned long ratebs)
cc87246d 175{
176 unsigned int i;
177
32874aea 178 if (strcmp(name, statname) != 0) {
179 for (i = 0; i < strlen(name); ++i)
180 send_msg((HWND) atoi(gui_hwnd), WM_STATS_CHAR,
181 (WPARAM) name[i]);
182 send_msg((HWND) atoi(gui_hwnd), WM_STATS_CHAR, (WPARAM) '\n');
183 strcpy(statname, name);
cc87246d 184 }
32874aea 185 if (statsize != size) {
186 send_msg((HWND) atoi(gui_hwnd), WM_STATS_SIZE, (WPARAM) size);
cc87246d 187 statsize = size;
188 }
d524be1c 189 if (statdone != done) {
190 send_msg((HWND) atoi(gui_hwnd), WM_STATS_DONE, (WPARAM) done);
191 statdone = done;
192 }
193 if (stateta != eta) {
194 send_msg((HWND) atoi(gui_hwnd), WM_STATS_ETA, (WPARAM) eta);
195 stateta = eta;
196 }
197 if (statratebs != ratebs) {
198 send_msg((HWND) atoi(gui_hwnd), WM_STATS_RATEBS, (WPARAM) ratebs);
199 statratebs = ratebs;
200 }
32874aea 201 if (statelapsed != elapsed) {
202 send_msg((HWND) atoi(gui_hwnd), WM_STATS_ELAPSED,
203 (WPARAM) elapsed);
cc87246d 204 statelapsed = elapsed;
205 }
32874aea 206 if (statperct != percentage) {
207 send_msg((HWND) atoi(gui_hwnd), WM_STATS_PERCENT,
208 (WPARAM) percentage);
cc87246d 209 statperct = percentage;
210 }
211}
212
fb09bf1c 213/*
07d9aa13 214 * Print an error message and perform a fatal exit.
215 */
216void fatalbox(char *fmt, ...)
217{
32874aea 218 char str[0x100]; /* Make the size big enough */
c51a56e2 219 va_list ap;
220 va_start(ap, fmt);
120e4b40 221 strcpy(str, "Fatal: ");
32874aea 222 vsprintf(str + strlen(str), fmt, ap);
c51a56e2 223 va_end(ap);
cc87246d 224 strcat(str, "\n");
225 tell_str(stderr, str);
2bc6a386 226 errs++;
227
228 if (gui_mode) {
229 unsigned int msg_id = WM_RET_ERR_CNT;
230 if (list)
231 msg_id = WM_LS_RET_ERR_CNT;
232 while (!PostMessage
233 ((HWND) atoi(gui_hwnd), msg_id, (WPARAM) errs,
234 0 /*lParam */ ))SleepEx(1000, TRUE);
235 }
cc87246d 236
93b581bd 237 cleanup_exit(1);
07d9aa13 238}
8d5de777 239void connection_fatal(char *fmt, ...)
240{
32874aea 241 char str[0x100]; /* Make the size big enough */
8d5de777 242 va_list ap;
243 va_start(ap, fmt);
120e4b40 244 strcpy(str, "Fatal: ");
32874aea 245 vsprintf(str + strlen(str), fmt, ap);
8d5de777 246 va_end(ap);
247 strcat(str, "\n");
248 tell_str(stderr, str);
2bc6a386 249 errs++;
250
251 if (gui_mode) {
252 unsigned int msg_id = WM_RET_ERR_CNT;
253 if (list)
254 msg_id = WM_LS_RET_ERR_CNT;
255 while (!PostMessage
256 ((HWND) atoi(gui_hwnd), msg_id, (WPARAM) errs,
257 0 /*lParam */ ))SleepEx(1000, TRUE);
258 }
8d5de777 259
93b581bd 260 cleanup_exit(1);
8d5de777 261}
07d9aa13 262
07d9aa13 263/*
8df7a775 264 * Be told what socket we're supposed to be using.
265 */
266static SOCKET scp_ssh_socket;
32874aea 267char *do_select(SOCKET skt, int startup)
268{
8df7a775 269 if (startup)
270 scp_ssh_socket = skt;
271 else
272 scp_ssh_socket = INVALID_SOCKET;
273 return NULL;
274}
275extern int select_result(WPARAM, LPARAM);
276
277/*
3bdaf79d 278 * Receive a block of data from the SSH link. Block until all data
279 * is available.
280 *
281 * To do this, we repeatedly call the SSH protocol module, with our
fe50e814 282 * own trap in from_backend() to catch the data that comes back. We
283 * do this until we have enough data.
3bdaf79d 284 */
8df7a775 285
32874aea 286static unsigned char *outptr; /* where to put the data */
287static unsigned outlen; /* how much data required */
3bdaf79d 288static unsigned char *pending = NULL; /* any spare data */
32874aea 289static unsigned pendlen = 0, pendsize = 0; /* length and phys. size of buffer */
5471d09a 290int from_backend(int is_stderr, char *data, int datalen)
32874aea 291{
292 unsigned char *p = (unsigned char *) data;
293 unsigned len = (unsigned) datalen;
fe50e814 294
2b0c045b 295 assert(len > 0);
296
3bdaf79d 297 /*
fe50e814 298 * stderr data is just spouted to local stderr and otherwise
299 * ignored.
3bdaf79d 300 */
fe50e814 301 if (is_stderr) {
302 fwrite(data, 1, len, stderr);
5471d09a 303 return 0;
fe50e814 304 }
3bdaf79d 305
3bdaf79d 306 /*
307 * If this is before the real session begins, just return.
308 */
309 if (!outptr)
5471d09a 310 return 0;
3bdaf79d 311
312 if (outlen > 0) {
32874aea 313 unsigned used = outlen;
314 if (used > len)
315 used = len;
316 memcpy(outptr, p, used);
317 outptr += used;
318 outlen -= used;
319 p += used;
320 len -= used;
3bdaf79d 321 }
322
323 if (len > 0) {
32874aea 324 if (pendsize < pendlen + len) {
325 pendsize = pendlen + len + 4096;
326 pending = (pending ? srealloc(pending, pendsize) :
327 smalloc(pendsize));
328 if (!pending)
329 fatalbox("Out of memory");
330 }
331 memcpy(pending + pendlen, p, len);
332 pendlen += len;
3bdaf79d 333 }
5471d09a 334
335 return 0;
336}
337static int scp_process_network_event(void)
338{
339 fd_set readfds;
340
341 FD_ZERO(&readfds);
342 FD_SET(scp_ssh_socket, &readfds);
343 if (select(1, &readfds, NULL, NULL, NULL) < 0)
344 return 0; /* doom */
345 select_result((WPARAM) scp_ssh_socket, (LPARAM) FD_READ);
346 return 1;
3bdaf79d 347}
32874aea 348static int ssh_scp_recv(unsigned char *buf, int len)
349{
3bdaf79d 350 outptr = buf;
351 outlen = len;
352
353 /*
354 * See if the pending-input block contains some of what we
355 * need.
356 */
357 if (pendlen > 0) {
32874aea 358 unsigned pendused = pendlen;
359 if (pendused > outlen)
360 pendused = outlen;
3bdaf79d 361 memcpy(outptr, pending, pendused);
32874aea 362 memmove(pending, pending + pendused, pendlen - pendused);
3bdaf79d 363 outptr += pendused;
364 outlen -= pendused;
32874aea 365 pendlen -= pendused;
366 if (pendlen == 0) {
367 pendsize = 0;
368 sfree(pending);
369 pending = NULL;
370 }
371 if (outlen == 0)
372 return len;
3bdaf79d 373 }
374
375 while (outlen > 0) {
5471d09a 376 if (!scp_process_network_event())
32874aea 377 return 0; /* doom */
3bdaf79d 378 }
379
380 return len;
381}
382
383/*
384 * Loop through the ssh connection and authentication process.
385 */
32874aea 386static void ssh_scp_init(void)
387{
8df7a775 388 if (scp_ssh_socket == INVALID_SOCKET)
3bdaf79d 389 return;
390 while (!back->sendok()) {
32874aea 391 fd_set readfds;
392 FD_ZERO(&readfds);
393 FD_SET(scp_ssh_socket, &readfds);
394 if (select(1, &readfds, NULL, NULL, NULL) < 0)
395 return; /* doom */
396 select_result((WPARAM) scp_ssh_socket, (LPARAM) FD_READ);
3bdaf79d 397 }
fd5e5847 398 using_sftp = !ssh_fallback_cmd;
3bdaf79d 399}
400
401/*
07d9aa13 402 * Print an error message and exit after closing the SSH link.
403 */
404static void bump(char *fmt, ...)
405{
32874aea 406 char str[0x100]; /* Make the size big enough */
c51a56e2 407 va_list ap;
408 va_start(ap, fmt);
120e4b40 409 strcpy(str, "Fatal: ");
32874aea 410 vsprintf(str + strlen(str), fmt, ap);
c51a56e2 411 va_end(ap);
cc87246d 412 strcat(str, "\n");
413 tell_str(stderr, str);
2bc6a386 414 errs++;
cc87246d 415
eba78553 416 if (back != NULL && back->socket() != NULL) {
c51a56e2 417 char ch;
3bdaf79d 418 back->special(TS_EOF);
fb09bf1c 419 ssh_scp_recv(&ch, 1);
c51a56e2 420 }
2bc6a386 421
422 if (gui_mode) {
423 unsigned int msg_id = WM_RET_ERR_CNT;
424 if (list)
425 msg_id = WM_LS_RET_ERR_CNT;
426 while (!PostMessage
427 ((HWND) atoi(gui_hwnd), msg_id, (WPARAM) errs,
428 0 /*lParam */ ))SleepEx(1000, TRUE);
429 }
430
93b581bd 431 cleanup_exit(1);
07d9aa13 432}
433
07d9aa13 434/*
435 * Open an SSH connection to user@host and execute cmd.
436 */
437static void do_cmd(char *host, char *user, char *cmd)
438{
c51a56e2 439 char *err, *realhost;
f5e6a5c6 440 DWORD namelen;
c51a56e2 441
442 if (host == NULL || host[0] == '\0')
443 bump("Empty host name");
444
445 /* Try to load settings for this host */
a9422f39 446 do_defaults(host, &cfg);
c51a56e2 447 if (cfg.host[0] == '\0') {
448 /* No settings for this host; use defaults */
32874aea 449 do_defaults(NULL, &cfg);
450 strncpy(cfg.host, host, sizeof(cfg.host) - 1);
451 cfg.host[sizeof(cfg.host) - 1] = '\0';
c51a56e2 452 cfg.port = 22;
453 }
454
449925a6 455 /*
456 * Trim leading whitespace off the hostname if it's there.
457 */
458 {
459 int space = strspn(cfg.host, " \t");
460 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
461 }
462
463 /* See if host is of the form user@host */
464 if (cfg.host[0] != '\0') {
465 char *atsign = strchr(cfg.host, '@');
466 /* Make sure we're not overflowing the user field */
467 if (atsign) {
468 if (atsign - cfg.host < sizeof cfg.username) {
469 strncpy(cfg.username, cfg.host, atsign - cfg.host);
470 cfg.username[atsign - cfg.host] = '\0';
471 }
472 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
473 }
474 }
475
476 /*
477 * Trim a colon suffix off the hostname if it's there.
478 */
479 cfg.host[strcspn(cfg.host, ":")] = '\0';
480
c51a56e2 481 /* Set username */
482 if (user != NULL && user[0] != '\0') {
32874aea 483 strncpy(cfg.username, user, sizeof(cfg.username) - 1);
484 cfg.username[sizeof(cfg.username) - 1] = '\0';
c51a56e2 485 } else if (cfg.username[0] == '\0') {
f5e6a5c6 486 namelen = 0;
487 if (GetUserName(user, &namelen) == FALSE)
488 bump("Empty user name");
93558b21 489 user = smalloc(namelen * sizeof(char));
f5e6a5c6 490 GetUserName(user, &namelen);
32874aea 491 if (verbose)
492 tell_user(stderr, "Guessing user name: %s", user);
493 strncpy(cfg.username, user, sizeof(cfg.username) - 1);
494 cfg.username[sizeof(cfg.username) - 1] = '\0';
f5e6a5c6 495 free(user);
c51a56e2 496 }
497
498 if (cfg.protocol != PROT_SSH)
499 cfg.port = 22;
500
ed89e8a5 501 if (portnumber)
502 cfg.port = portnumber;
503
fd5e5847 504 /*
d27b4a18 505 * Disable scary things which shouldn't be enabled for simple
506 * things like SCP and SFTP: agent forwarding, port forwarding,
507 * X forwarding.
508 */
509 cfg.x11_forward = 0;
510 cfg.agentfwd = 0;
511 cfg.portfwd[0] = cfg.portfwd[1] = '\0';
512
513 /*
fd5e5847 514 * Attempt to start the SFTP subsystem as a first choice,
515 * falling back to the provided scp command if that fails.
516 */
517 strcpy(cfg.remote_cmd, "sftp");
518 cfg.ssh_subsys = TRUE;
519 cfg.remote_cmd_ptr2 = cmd;
520 cfg.ssh_subsys2 = FALSE;
3bdaf79d 521 cfg.nopty = TRUE;
522
523 back = &ssh_backend;
524
2184a5d9 525 err = back->init(cfg.host, cfg.port, &realhost, 0);
c51a56e2 526 if (err != NULL)
527 bump("ssh_init: %s", err);
3bdaf79d 528 ssh_scp_init();
c51a56e2 529 if (verbose && realhost != NULL)
cc87246d 530 tell_user(stderr, "Connected to %s\n", realhost);
6e1ebb76 531 sfree(realhost);
07d9aa13 532}
533
07d9aa13 534/*
535 * Update statistic information about current file.
536 */
537static void print_stats(char *name, unsigned long size, unsigned long done,
32874aea 538 time_t start, time_t now)
07d9aa13 539{
c51a56e2 540 float ratebs;
541 unsigned long eta;
542 char etastr[10];
543 int pct;
b1daf518 544 int len;
d524be1c 545 int elap;
c51a56e2 546
d524be1c 547 elap = (unsigned long) difftime(now, start);
c51a56e2 548
d524be1c 549 if (now > start)
550 ratebs = (float) done / elap;
551 else
552 ratebs = (float) done;
553
554 if (ratebs < 1.0)
555 eta = size - done;
556 else
557 eta = (unsigned long) ((size - done) / ratebs);
558 sprintf(etastr, "%02ld:%02ld:%02ld",
559 eta / 3600, (eta % 3600) / 60, eta % 60);
c51a56e2 560
d524be1c 561 pct = (int) (100 * (done * 1.0 / size));
c51a56e2 562
d524be1c 563 if (gui_mode)
564 /* GUI Adaptation - Sept 2000 */
565 gui_update_stats(name, size, pct, elap, done, eta,
566 (unsigned long) ratebs);
567 else {
b1daf518 568 len = printf("\r%-25.25s | %10ld kB | %5.1f kB/s | ETA: %8s | %3d%%",
569 name, done / 1024, ratebs / 1024.0, etastr, pct);
570 if (len < prev_stats_len)
571 printf("%*s", prev_stats_len - len, "");
572 prev_stats_len = len;
c51a56e2 573
cc87246d 574 if (done == size)
575 printf("\n");
576 }
07d9aa13 577}
578
07d9aa13 579/*
580 * Find a colon in str and return a pointer to the colon.
39ddf0ff 581 * This is used to separate hostname from filename.
07d9aa13 582 */
32874aea 583static char *colon(char *str)
07d9aa13 584{
c51a56e2 585 /* We ignore a leading colon, since the hostname cannot be
32874aea 586 empty. We also ignore a colon as second character because
587 of filenames like f:myfile.txt. */
588 if (str[0] == '\0' || str[0] == ':' || str[1] == ':')
c51a56e2 589 return (NULL);
32874aea 590 while (*str != '\0' && *str != ':' && *str != '/' && *str != '\\')
c51a56e2 591 str++;
592 if (*str == ':')
593 return (str);
594 else
595 return (NULL);
07d9aa13 596}
597
07d9aa13 598/*
03f64569 599 * Return a pointer to the portion of str that comes after the last
b3dcd9b2 600 * slash (or backslash or colon, if `local' is TRUE).
03f64569 601 */
4eb24e3a 602static char *stripslashes(char *str, int local)
03f64569 603{
604 char *p;
605
b3dcd9b2 606 if (local) {
607 p = strchr(str, ':');
608 if (p) str = p+1;
609 }
610
03f64569 611 p = strrchr(str, '/');
612 if (p) str = p+1;
613
4eb24e3a 614 if (local) {
615 p = strrchr(str, '\\');
616 if (p) str = p+1;
617 }
03f64569 618
619 return str;
620}
621
622/*
fd5e5847 623 * Determine whether a string is entirely composed of dots.
624 */
625static int is_dots(char *str)
626{
627 return str[strspn(str, ".")] == '\0';
628}
629
630/*
07d9aa13 631 * Wait for a response from the other side.
632 * Return 0 if ok, -1 if error.
633 */
634static int response(void)
635{
c51a56e2 636 char ch, resp, rbuf[2048];
637 int p;
638
fb09bf1c 639 if (ssh_scp_recv(&resp, 1) <= 0)
c51a56e2 640 bump("Lost connection");
641
642 p = 0;
643 switch (resp) {
32874aea 644 case 0: /* ok */
c51a56e2 645 return (0);
646 default:
647 rbuf[p++] = resp;
648 /* fallthrough */
32874aea 649 case 1: /* error */
650 case 2: /* fatal error */
c51a56e2 651 do {
fb09bf1c 652 if (ssh_scp_recv(&ch, 1) <= 0)
c51a56e2 653 bump("Protocol error: Lost connection");
654 rbuf[p++] = ch;
655 } while (p < sizeof(rbuf) && ch != '\n');
32874aea 656 rbuf[p - 1] = '\0';
c51a56e2 657 if (resp == 1)
cc87246d 658 tell_user(stderr, "%s\n", rbuf);
c51a56e2 659 else
660 bump("%s", rbuf);
661 errs++;
662 return (-1);
663 }
07d9aa13 664}
665
fd5e5847 666int sftp_recvdata(char *buf, int len)
667{
668 return ssh_scp_recv(buf, len);
669}
670int sftp_senddata(char *buf, int len)
671{
672 back->send((unsigned char *) buf, len);
673 return 1;
674}
675
676/* ----------------------------------------------------------------------
677 * sftp-based replacement for the hacky `pscp -ls'.
678 */
679static int sftp_ls_compare(const void *av, const void *bv)
680{
681 const struct fxp_name *a = (const struct fxp_name *) av;
682 const struct fxp_name *b = (const struct fxp_name *) bv;
683 return strcmp(a->filename, b->filename);
684}
685void scp_sftp_listdir(char *dirname)
686{
687 struct fxp_handle *dirh;
688 struct fxp_names *names;
689 struct fxp_name *ournames;
690 int nnames, namesize;
fd5e5847 691 int i;
692
9acdecb3 693 if (!fxp_init()) {
694 tell_user(stderr, "unable to initialise SFTP: %s", fxp_error());
695 errs++;
696 return;
697 }
698
fd5e5847 699 printf("Listing directory %s\n", dirname);
700
701 dirh = fxp_opendir(dirname);
702 if (dirh == NULL) {
cdcbdf3b 703 printf("Unable to open %s: %s\n", dirname, fxp_error());
fd5e5847 704 } else {
705 nnames = namesize = 0;
706 ournames = NULL;
707
708 while (1) {
709
710 names = fxp_readdir(dirh);
711 if (names == NULL) {
712 if (fxp_error_type() == SSH_FX_EOF)
713 break;
cdcbdf3b 714 printf("Reading directory %s: %s\n", dirname, fxp_error());
fd5e5847 715 break;
716 }
717 if (names->nnames == 0) {
718 fxp_free_names(names);
719 break;
720 }
721
722 if (nnames + names->nnames >= namesize) {
723 namesize += names->nnames + 128;
724 ournames =
725 srealloc(ournames, namesize * sizeof(*ournames));
726 }
727
728 for (i = 0; i < names->nnames; i++)
729 ournames[nnames++] = names->names[i];
730
731 names->nnames = 0; /* prevent free_names */
732 fxp_free_names(names);
733 }
734 fxp_close(dirh);
735
736 /*
737 * Now we have our filenames. Sort them by actual file
738 * name, and then output the longname parts.
739 */
740 qsort(ournames, nnames, sizeof(*ournames), sftp_ls_compare);
741
742 /*
743 * And print them.
744 */
745 for (i = 0; i < nnames; i++)
746 printf("%s\n", ournames[i].longname);
747 }
748}
749
120e4b40 750/* ----------------------------------------------------------------------
751 * Helper routines that contain the actual SCP protocol elements,
fd5e5847 752 * implemented both as SCP1 and SFTP.
120e4b40 753 */
754
fd5e5847 755static struct scp_sftp_dirstack {
756 struct scp_sftp_dirstack *next;
757 struct fxp_name *names;
758 int namepos, namelen;
759 char *dirpath;
4eb24e3a 760 char *wildcard;
825ec8ee 761 int matched_something; /* wildcard match set was non-empty */
fd5e5847 762} *scp_sftp_dirstack_head;
763static char *scp_sftp_remotepath, *scp_sftp_currentname;
4eb24e3a 764static char *scp_sftp_wildcard;
fd5e5847 765static int scp_sftp_targetisdir, scp_sftp_donethistarget;
766static int scp_sftp_preserve, scp_sftp_recursive;
767static unsigned long scp_sftp_mtime, scp_sftp_atime;
768static int scp_has_times;
769static struct fxp_handle *scp_sftp_filehandle;
770static uint64 scp_sftp_fileoffset;
771
772void scp_source_setup(char *target, int shouldbedir)
773{
774 if (using_sftp) {
775 /*
776 * Find out whether the target filespec is in fact a
777 * directory.
778 */
779 struct fxp_attrs attrs;
780
02105c79 781 if (!fxp_init()) {
782 tell_user(stderr, "unable to initialise SFTP: %s", fxp_error());
783 errs++;
784 return 1;
785 }
786
fd5e5847 787 if (!fxp_stat(target, &attrs) ||
788 !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS))
789 scp_sftp_targetisdir = 0;
790 else
791 scp_sftp_targetisdir = (attrs.permissions & 0040000) != 0;
792
793 if (shouldbedir && !scp_sftp_targetisdir) {
794 bump("pscp: remote filespec %s: not a directory\n", target);
795 }
796
797 scp_sftp_remotepath = dupstr(target);
798
799 scp_has_times = 0;
800 } else {
801 (void) response();
802 }
803}
804
120e4b40 805int scp_send_errmsg(char *str)
806{
fd5e5847 807 if (using_sftp) {
808 /* do nothing; we never need to send our errors to the server */
809 } else {
810 back->send("\001", 1); /* scp protocol error prefix */
811 back->send(str, strlen(str));
812 }
120e4b40 813 return 0; /* can't fail */
814}
815
816int scp_send_filetimes(unsigned long mtime, unsigned long atime)
817{
fd5e5847 818 if (using_sftp) {
819 scp_sftp_mtime = mtime;
820 scp_sftp_atime = atime;
821 scp_has_times = 1;
822 return 0;
823 } else {
824 char buf[80];
825 sprintf(buf, "T%lu 0 %lu 0\n", mtime, atime);
826 back->send(buf, strlen(buf));
827 return response();
828 }
120e4b40 829}
830
831int scp_send_filename(char *name, unsigned long size, int modes)
832{
fd5e5847 833 if (using_sftp) {
834 char *fullname;
835 if (scp_sftp_targetisdir) {
836 fullname = dupcat(scp_sftp_remotepath, "/", name, NULL);
837 } else {
838 fullname = dupstr(scp_sftp_remotepath);
839 }
840 scp_sftp_filehandle =
841 fxp_open(fullname, SSH_FXF_WRITE | SSH_FXF_CREAT | SSH_FXF_TRUNC);
842 if (!scp_sftp_filehandle) {
843 tell_user(stderr, "pscp: unable to open %s: %s",
844 fullname, fxp_error());
845 errs++;
846 return 1;
847 }
848 scp_sftp_fileoffset = uint64_make(0, 0);
849 sfree(fullname);
850 return 0;
851 } else {
852 char buf[40];
853 sprintf(buf, "C%04o %lu ", modes, size);
854 back->send(buf, strlen(buf));
855 back->send(name, strlen(name));
856 back->send("\n", 1);
857 return response();
858 }
120e4b40 859}
860
861int scp_send_filedata(char *data, int len)
862{
fd5e5847 863 if (using_sftp) {
864 if (!scp_sftp_filehandle) {
865 return 1;
866 }
867 if (!fxp_write(scp_sftp_filehandle, data, scp_sftp_fileoffset, len)) {
868 tell_user(stderr, "error while writing: %s\n", fxp_error());
869 errs++;
870 return 1;
871 }
872 scp_sftp_fileoffset = uint64_add32(scp_sftp_fileoffset, len);
873 return 0;
874 } else {
875 int bufsize = back->send(data, len);
120e4b40 876
fd5e5847 877 /*
878 * If the network transfer is backing up - that is, the
879 * remote site is not accepting data as fast as we can
880 * produce it - then we must loop on network events until
881 * we have space in the buffer again.
882 */
883 while (bufsize > MAX_SCP_BUFSIZE) {
884 if (!scp_process_network_event())
885 return 1;
886 bufsize = back->sendbuffer();
887 }
888
889 return 0;
890 }
891}
892
893int scp_send_finish(void)
894{
895 if (using_sftp) {
896 struct fxp_attrs attrs;
897 if (!scp_sftp_filehandle) {
120e4b40 898 return 1;
fd5e5847 899 }
900 if (scp_has_times) {
901 attrs.flags = SSH_FILEXFER_ATTR_ACMODTIME;
902 attrs.atime = scp_sftp_atime;
903 attrs.mtime = scp_sftp_mtime;
904 if (!fxp_fsetstat(scp_sftp_filehandle, attrs)) {
905 tell_user(stderr, "unable to set file times: %s\n", fxp_error());
906 errs++;
907 }
908 }
909 fxp_close(scp_sftp_filehandle);
910 scp_has_times = 0;
911 return 0;
912 } else {
913 back->send("", 1);
914 return response();
120e4b40 915 }
fd5e5847 916}
120e4b40 917
fd5e5847 918char *scp_save_remotepath(void)
919{
920 if (using_sftp)
921 return scp_sftp_remotepath;
922 else
923 return NULL;
120e4b40 924}
925
fd5e5847 926void scp_restore_remotepath(char *data)
120e4b40 927{
fd5e5847 928 if (using_sftp)
929 scp_sftp_remotepath = data;
120e4b40 930}
931
932int scp_send_dirname(char *name, int modes)
933{
fd5e5847 934 if (using_sftp) {
935 char *fullname;
936 char const *err;
937 struct fxp_attrs attrs;
938 if (scp_sftp_targetisdir) {
939 fullname = dupcat(scp_sftp_remotepath, "/", name, NULL);
940 } else {
941 fullname = dupstr(scp_sftp_remotepath);
942 }
943
944 /*
945 * We don't worry about whether we managed to create the
946 * directory, because if it exists already it's OK just to
947 * use it. Instead, we will stat it afterwards, and if it
948 * exists and is a directory we will assume we were either
949 * successful or it didn't matter.
950 */
951 if (!fxp_mkdir(fullname))
952 err = fxp_error();
953 else
954 err = "server reported no error";
955 if (!fxp_stat(fullname, &attrs) ||
956 !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) ||
957 !(attrs.permissions & 0040000)) {
958 tell_user(stderr, "unable to create directory %s: %s",
959 fullname, err);
960 errs++;
961 return 1;
962 }
963
964 scp_sftp_remotepath = fullname;
965
966 return 0;
967 } else {
968 char buf[40];
969 sprintf(buf, "D%04o 0 ", modes);
970 back->send(buf, strlen(buf));
971 back->send(name, strlen(name));
972 back->send("\n", 1);
973 return response();
974 }
120e4b40 975}
976
977int scp_send_enddir(void)
978{
fd5e5847 979 if (using_sftp) {
980 sfree(scp_sftp_remotepath);
981 return 0;
982 } else {
983 back->send("E\n", 2);
984 return response();
985 }
986}
987
988/*
989 * Yes, I know; I have an scp_sink_setup _and_ an scp_sink_init.
990 * That's bad. The difference is that scp_sink_setup is called once
991 * right at the start, whereas scp_sink_init is called to
992 * initialise every level of recursion in the protocol.
993 */
4eb24e3a 994int scp_sink_setup(char *source, int preserve, int recursive)
fd5e5847 995{
996 if (using_sftp) {
4eb24e3a 997 char *newsource;
02105c79 998
999 if (!fxp_init()) {
1000 tell_user(stderr, "unable to initialise SFTP: %s", fxp_error());
1001 errs++;
1002 return 1;
1003 }
4eb24e3a 1004 /*
1005 * It's possible that the source string we've been given
1006 * contains a wildcard. If so, we must split the directory
1007 * away from the wildcard itself (throwing an error if any
1008 * wildcardness comes before the final slash) and arrange
1009 * things so that a dirstack entry will be set up.
1010 */
1011 newsource = smalloc(1+strlen(source));
1012 if (!wc_unescape(newsource, source)) {
1013 /* Yes, here we go; it's a wildcard. Bah. */
1014 char *dupsource, *lastpart, *dirpart, *wildcard;
1015 dupsource = dupstr(source);
1016 lastpart = stripslashes(dupsource, 0);
1017 wildcard = dupstr(lastpart);
1018 *lastpart = '\0';
1019 if (*dupsource && dupsource[1]) {
1020 /*
1021 * The remains of dupsource are at least two
1022 * characters long, meaning the pathname wasn't
1023 * empty or just `/'. Hence, we remove the trailing
1024 * slash.
1025 */
1026 lastpart[-1] = '\0';
6b18a524 1027 } else if (!*dupsource) {
1028 /*
1029 * The remains of dupsource are _empty_ - the whole
1030 * pathname was a wildcard. Hence we need to
1031 * replace it with ".".
1032 */
1033 sfree(dupsource);
1034 dupsource = dupstr(".");
4eb24e3a 1035 }
1036
1037 /*
1038 * Now we have separated our string into dupsource (the
1039 * directory part) and wildcard. Both of these will
1040 * need freeing at some point. Next step is to remove
1041 * wildcard escapes from the directory part, throwing
1042 * an error if it contains a real wildcard.
1043 */
1044 dirpart = smalloc(1+strlen(dupsource));
1045 if (!wc_unescape(dirpart, dupsource)) {
1046 tell_user(stderr, "%s: multiple-level wildcards unsupported",
1047 source);
1048 errs++;
1049 sfree(dirpart);
1050 sfree(wildcard);
1051 sfree(dupsource);
1052 return 1;
1053 }
1054
1055 /*
1056 * Now we have dirpart (unescaped, ie a valid remote
1057 * path), and wildcard (a wildcard). This will be
1058 * sufficient to arrange a dirstack entry.
1059 */
1060 scp_sftp_remotepath = dirpart;
1061 scp_sftp_wildcard = wildcard;
1062 sfree(dupsource);
1063 } else {
1064 scp_sftp_remotepath = newsource;
1065 scp_sftp_wildcard = NULL;
1066 }
fd5e5847 1067 scp_sftp_preserve = preserve;
1068 scp_sftp_recursive = recursive;
1069 scp_sftp_donethistarget = 0;
1070 scp_sftp_dirstack_head = NULL;
1071 }
4eb24e3a 1072 return 0;
120e4b40 1073}
1074
1075int scp_sink_init(void)
1076{
fd5e5847 1077 if (!using_sftp) {
1078 back->send("", 1);
1079 }
120e4b40 1080 return 0;
1081}
1082
1083#define SCP_SINK_FILE 1
1084#define SCP_SINK_DIR 2
1085#define SCP_SINK_ENDDIR 3
4eb24e3a 1086#define SCP_SINK_RETRY 4 /* not an action; just try again */
120e4b40 1087struct scp_sink_action {
1088 int action; /* FILE, DIR, ENDDIR */
1089 char *buf; /* will need freeing after use */
1090 char *name; /* filename or dirname (not ENDDIR) */
1091 int mode; /* access mode (not ENDDIR) */
1092 unsigned long size; /* file size (not ENDDIR) */
1093 int settime; /* 1 if atime and mtime are filled */
1094 unsigned long atime, mtime; /* access times for the file */
1095};
1096
1097int scp_get_sink_action(struct scp_sink_action *act)
1098{
fd5e5847 1099 if (using_sftp) {
1100 char *fname;
1101 int must_free_fname;
1102 struct fxp_attrs attrs;
1103 int ret;
1104
1105 if (!scp_sftp_dirstack_head) {
1106 if (!scp_sftp_donethistarget) {
1107 /*
1108 * Simple case: we are only dealing with one file.
1109 */
1110 fname = scp_sftp_remotepath;
1111 must_free_fname = 0;
1112 scp_sftp_donethistarget = 1;
1113 } else {
1114 /*
1115 * Even simpler case: one file _which we've done_.
1116 * Return 1 (finished).
1117 */
1118 return 1;
1119 }
1120 } else {
1121 /*
1122 * We're now in the middle of stepping through a list
1123 * of names returned from fxp_readdir(); so let's carry
1124 * on.
1125 */
1126 struct scp_sftp_dirstack *head = scp_sftp_dirstack_head;
1127 while (head->namepos < head->namelen &&
4eb24e3a 1128 (is_dots(head->names[head->namepos].filename) ||
1129 (head->wildcard &&
1130 !wc_match(head->wildcard,
1131 head->names[head->namepos].filename))))
fd5e5847 1132 head->namepos++; /* skip . and .. */
1133 if (head->namepos < head->namelen) {
825ec8ee 1134 head->matched_something = 1;
fd5e5847 1135 fname = dupcat(head->dirpath, "/",
1136 head->names[head->namepos++].filename,
1137 NULL);
1138 must_free_fname = 1;
1139 } else {
1140 /*
1141 * We've come to the end of the list; pop it off
4eb24e3a 1142 * the stack and return an ENDDIR action (or RETRY
1143 * if this was a wildcard match).
fd5e5847 1144 */
4eb24e3a 1145 if (head->wildcard) {
1146 act->action = SCP_SINK_RETRY;
825ec8ee 1147 if (!head->matched_something) {
1148 tell_user(stderr, "pscp: wildcard '%s' matched "
1149 "no files", head->wildcard);
1150 errs++;
1151 }
4eb24e3a 1152 sfree(head->wildcard);
825ec8ee 1153
4eb24e3a 1154 } else {
1155 act->action = SCP_SINK_ENDDIR;
1156 }
1157
fd5e5847 1158 sfree(head->dirpath);
1159 sfree(head->names);
1160 scp_sftp_dirstack_head = head->next;
1161 sfree(head);
1162
fd5e5847 1163 return 0;
1164 }
1165 }
cd1f39ab 1166
fd5e5847 1167 /*
1168 * Now we have a filename. Stat it, and see if it's a file
1169 * or a directory.
1170 */
1171 ret = fxp_stat(fname, &attrs);
1172 if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS)) {
1173 tell_user(stderr, "unable to identify %s: %s", fname,
1174 ret ? "file type not supplied" : fxp_error());
1175 errs++;
120e4b40 1176 return 1;
fd5e5847 1177 }
1178
1179 if (attrs.permissions & 0040000) {
1180 struct scp_sftp_dirstack *newitem;
1181 struct fxp_handle *dirhandle;
1182 int nnames, namesize;
1183 struct fxp_name *ournames;
1184 struct fxp_names *names;
1185
1186 /*
37dfb97a 1187 * It's a directory. If we're not in recursive mode,
1188 * this merits a complaint (which is fatal if the name
1189 * was specified directly, but not if it was matched by
1190 * a wildcard).
1191 *
1192 * We skip this complaint completely if
1193 * scp_sftp_wildcard is set, because that's an
1194 * indication that we're not actually supposed to
1195 * _recursively_ transfer the dir, just scan it for
1196 * things matching the wildcard.
fd5e5847 1197 */
4eb24e3a 1198 if (!scp_sftp_recursive && !scp_sftp_wildcard) {
fd5e5847 1199 tell_user(stderr, "pscp: %s: is a directory", fname);
1200 errs++;
1201 if (must_free_fname) sfree(fname);
37dfb97a 1202 if (scp_sftp_dirstack_head) {
1203 act->action = SCP_SINK_RETRY;
1204 return 0;
1205 } else {
1206 return 1;
1207 }
120e4b40 1208 }
fd5e5847 1209
1210 /*
1211 * Otherwise, the fun begins. We must fxp_opendir() the
1212 * directory, slurp the filenames into memory, return
4eb24e3a 1213 * SCP_SINK_DIR (unless this is a wildcard match), and
1214 * set targetisdir. The next time we're called, we will
1215 * run through the list of filenames one by one,
1216 * matching them against a wildcard if present.
fd5e5847 1217 *
1218 * If targetisdir is _already_ set (meaning we're
1219 * already in the middle of going through another such
1220 * list), we must push the other (target,namelist) pair
1221 * on a stack.
1222 */
1223 dirhandle = fxp_opendir(fname);
1224 if (!dirhandle) {
1225 tell_user(stderr, "scp: unable to open directory %s: %s",
1226 fname, fxp_error());
1227 if (must_free_fname) sfree(fname);
1228 errs++;
1229 return 1;
1230 }
1231 nnames = namesize = 0;
1232 ournames = NULL;
1233 while (1) {
1234 int i;
1235
1236 names = fxp_readdir(dirhandle);
1237 if (names == NULL) {
1238 if (fxp_error_type() == SSH_FX_EOF)
1239 break;
1240 tell_user(stderr, "scp: reading directory %s: %s\n",
1241 fname, fxp_error());
1242 if (must_free_fname) sfree(fname);
1243 sfree(ournames);
1244 errs++;
1245 return 1;
1246 }
1247 if (names->nnames == 0) {
1248 fxp_free_names(names);
1249 break;
1250 }
1251 if (nnames + names->nnames >= namesize) {
1252 namesize += names->nnames + 128;
1253 ournames =
1254 srealloc(ournames, namesize * sizeof(*ournames));
1255 }
1256 for (i = 0; i < names->nnames; i++)
1257 ournames[nnames++] = names->names[i];
1258 names->nnames = 0; /* prevent free_names */
1259 fxp_free_names(names);
1260 }
1261 fxp_close(dirhandle);
1262
1263 newitem = smalloc(sizeof(struct scp_sftp_dirstack));
1264 newitem->next = scp_sftp_dirstack_head;
1265 newitem->names = ournames;
1266 newitem->namepos = 0;
1267 newitem->namelen = nnames;
1268 if (must_free_fname)
1269 newitem->dirpath = fname;
1270 else
1271 newitem->dirpath = dupstr(fname);
4eb24e3a 1272 if (scp_sftp_wildcard) {
1273 newitem->wildcard = scp_sftp_wildcard;
825ec8ee 1274 newitem->matched_something = 0;
4eb24e3a 1275 scp_sftp_wildcard = NULL;
1276 } else {
1277 newitem->wildcard = NULL;
1278 }
fd5e5847 1279 scp_sftp_dirstack_head = newitem;
1280
4eb24e3a 1281 if (newitem->wildcard) {
1282 act->action = SCP_SINK_RETRY;
1283 } else {
1284 act->action = SCP_SINK_DIR;
1285 act->buf = dupstr(stripslashes(fname, 0));
1286 act->name = act->buf;
1287 act->size = 0; /* duhh, it's a directory */
1288 act->mode = 07777 & attrs.permissions;
1289 if (scp_sftp_preserve &&
1290 (attrs.flags & SSH_FILEXFER_ATTR_ACMODTIME)) {
1291 act->atime = attrs.atime;
1292 act->mtime = attrs.mtime;
1293 act->settime = 1;
1294 } else
1295 act->settime = 0;
1296 }
120e4b40 1297 return 0;
fd5e5847 1298
1299 } else {
1300 /*
1301 * It's a file. Return SCP_SINK_FILE.
1302 */
1303 act->action = SCP_SINK_FILE;
4eb24e3a 1304 act->buf = dupstr(stripslashes(fname, 0));
fd5e5847 1305 act->name = act->buf;
1306 if (attrs.flags & SSH_FILEXFER_ATTR_SIZE) {
1307 if (uint64_compare(attrs.size,
1308 uint64_make(0, ULONG_MAX)) > 0) {
1309 act->size = ULONG_MAX; /* *boggle* */
1310 } else
1311 act->size = attrs.size.lo;
1312 } else
1313 act->size = ULONG_MAX; /* no idea */
1314 act->mode = 07777 & attrs.permissions;
1315 if (scp_sftp_preserve &&
1316 (attrs.flags & SSH_FILEXFER_ATTR_ACMODTIME)) {
1317 act->atime = attrs.atime;
1318 act->mtime = attrs.mtime;
120e4b40 1319 act->settime = 1;
fd5e5847 1320 } else
1321 act->settime = 0;
1322 if (must_free_fname)
1323 scp_sftp_currentname = fname;
1324 else
1325 scp_sftp_currentname = dupstr(fname);
1326 return 0;
1327 }
1328
1329 } else {
1330 int done = 0;
1331 int i, bufsize;
1332 int action;
1333 char ch;
1334
1335 act->settime = 0;
1336 act->buf = NULL;
1337 bufsize = 0;
1338
1339 while (!done) {
1340 if (ssh_scp_recv(&ch, 1) <= 0)
1341 return 1;
1342 if (ch == '\n')
1343 bump("Protocol error: Unexpected newline");
1344 i = 0;
1345 action = ch;
1346 do {
1347 if (ssh_scp_recv(&ch, 1) <= 0)
1348 bump("Lost connection");
1349 if (i >= bufsize) {
1350 bufsize = i + 128;
1351 act->buf = srealloc(act->buf, bufsize);
1352 }
1353 act->buf[i++] = ch;
1354 } while (ch != '\n');
1355 act->buf[i - 1] = '\0';
1356 switch (action) {
1357 case '\01': /* error */
1358 tell_user(stderr, "%s\n", act->buf);
1359 errs++;
1360 continue; /* go round again */
1361 case '\02': /* fatal error */
1362 bump("%s", act->buf);
1363 case 'E':
120e4b40 1364 back->send("", 1);
fd5e5847 1365 act->action = SCP_SINK_ENDDIR;
1366 return 0;
1367 case 'T':
1368 if (sscanf(act->buf, "%ld %*d %ld %*d",
1369 &act->mtime, &act->atime) == 2) {
1370 act->settime = 1;
1371 back->send("", 1);
1372 continue; /* go round again */
1373 }
1374 bump("Protocol error: Illegal time format");
1375 case 'C':
1376 case 'D':
1377 act->action = (action == 'C' ? SCP_SINK_FILE : SCP_SINK_DIR);
1378 break;
1379 default:
1380 bump("Protocol error: Expected control record");
120e4b40 1381 }
fd5e5847 1382 /*
1383 * We will go round this loop only once, unless we hit
1384 * `continue' above.
1385 */
1386 done = 1;
120e4b40 1387 }
fd5e5847 1388
120e4b40 1389 /*
fd5e5847 1390 * If we get here, we must have seen SCP_SINK_FILE or
1391 * SCP_SINK_DIR.
120e4b40 1392 */
fd5e5847 1393 if (sscanf(act->buf, "%o %lu %n", &act->mode, &act->size, &i) != 2)
1394 bump("Protocol error: Illegal file descriptor format");
1395 act->name = act->buf + i;
1396 return 0;
120e4b40 1397 }
120e4b40 1398}
1399
1400int scp_accept_filexfer(void)
1401{
fd5e5847 1402 if (using_sftp) {
1403 scp_sftp_filehandle =
1404 fxp_open(scp_sftp_currentname, SSH_FXF_READ);
1405 if (!scp_sftp_filehandle) {
1406 tell_user(stderr, "pscp: unable to open %s: %s",
1407 scp_sftp_currentname, fxp_error());
1408 errs++;
1409 return 1;
1410 }
1411 scp_sftp_fileoffset = uint64_make(0, 0);
1412 sfree(scp_sftp_currentname);
1413 return 0;
1414 } else {
1415 back->send("", 1);
1416 return 0; /* can't fail */
1417 }
120e4b40 1418}
1419
1420int scp_recv_filedata(char *data, int len)
1421{
fd5e5847 1422 if (using_sftp) {
1423 int actuallen = fxp_read(scp_sftp_filehandle, data,
1424 scp_sftp_fileoffset, len);
1425 if (actuallen == -1 && fxp_error_type() != SSH_FX_EOF) {
1426 tell_user(stderr, "pscp: error while reading: %s", fxp_error());
1427 errs++;
1428 return -1;
1429 }
1430 if (actuallen < 0)
1431 actuallen = 0;
1432
1433 scp_sftp_fileoffset = uint64_add32(scp_sftp_fileoffset, actuallen);
1434
1435 return actuallen;
1436 } else {
1437 return ssh_scp_recv(data, len);
1438 }
120e4b40 1439}
1440
1441int scp_finish_filerecv(void)
1442{
fd5e5847 1443 if (using_sftp) {
1444 fxp_close(scp_sftp_filehandle);
1445 return 0;
1446 } else {
1447 back->send("", 1);
1448 return response();
1449 }
120e4b40 1450}
1451
1452/* ----------------------------------------------------------------------
07d9aa13 1453 * Send an error message to the other side and to the screen.
1454 * Increment error counter.
1455 */
1456static void run_err(const char *fmt, ...)
1457{
c51a56e2 1458 char str[2048];
1459 va_list ap;
1460 va_start(ap, fmt);
1461 errs++;
9520eba8 1462 strcpy(str, "scp: ");
32874aea 1463 vsprintf(str + strlen(str), fmt, ap);
c51a56e2 1464 strcat(str, "\n");
120e4b40 1465 scp_send_errmsg(str);
32874aea 1466 tell_user(stderr, "%s", str);
c51a56e2 1467 va_end(ap);
07d9aa13 1468}
1469
07d9aa13 1470/*
1471 * Execute the source part of the SCP protocol.
1472 */
1473static void source(char *src)
1474{
c51a56e2 1475 unsigned long size;
1476 char *last;
1477 HANDLE f;
1478 DWORD attr;
1479 unsigned long i;
1480 unsigned long stat_bytes;
1481 time_t stat_starttime, stat_lasttime;
1482
1483 attr = GetFileAttributes(src);
32874aea 1484 if (attr == (DWORD) - 1) {
c51a56e2 1485 run_err("%s: No such file or directory", src);
1486 return;
1487 }
1488
1489 if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
7f1f80de 1490 if (recursive) {
32874aea 1491 /*
1492 * Avoid . and .. directories.
1493 */
1494 char *p;
1495 p = strrchr(src, '/');
1496 if (!p)
1497 p = strrchr(src, '\\');
1498 if (!p)
1499 p = src;
1500 else
1501 p++;
1502 if (!strcmp(p, ".") || !strcmp(p, ".."))
1503 /* skip . and .. */ ;
1504 else
1505 rsource(src);
1506 } else {
c51a56e2 1507 run_err("%s: not a regular file", src);
32874aea 1508 }
c51a56e2 1509 return;
1510 }
1511
1512 if ((last = strrchr(src, '/')) == NULL)
1513 last = src;
1514 else
1515 last++;
1516 if (strrchr(last, '\\') != NULL)
1517 last = strrchr(last, '\\') + 1;
1518 if (last == src && strchr(src, ':') != NULL)
1519 last = strchr(src, ':') + 1;
1520
1521 f = CreateFile(src, GENERIC_READ, FILE_SHARE_READ, NULL,
1522 OPEN_EXISTING, 0, 0);
1523 if (f == INVALID_HANDLE_VALUE) {
486543a1 1524 run_err("%s: Cannot open file", src);
c51a56e2 1525 return;
1526 }
1527
1528 if (preserve) {
1529 FILETIME actime, wrtime;
1530 unsigned long mtime, atime;
1531 GetFileTime(f, NULL, &actime, &wrtime);
1532 TIME_WIN_TO_POSIX(actime, atime);
1533 TIME_WIN_TO_POSIX(wrtime, mtime);
120e4b40 1534 if (scp_send_filetimes(mtime, atime))
c51a56e2 1535 return;
1536 }
1537
1538 size = GetFileSize(f, NULL);
c51a56e2 1539 if (verbose)
120e4b40 1540 tell_user(stderr, "Sending file %s, size=%lu", last, size);
1541 if (scp_send_filename(last, size, 0644))
c51a56e2 1542 return;
1543
2d466ffd 1544 stat_bytes = 0;
1545 stat_starttime = time(NULL);
1546 stat_lasttime = 0;
c51a56e2 1547
1548 for (i = 0; i < size; i += 4096) {
1549 char transbuf[4096];
1550 DWORD j, k = 4096;
5471d09a 1551
32874aea 1552 if (i + k > size)
1553 k = size - i;
1554 if (!ReadFile(f, transbuf, k, &j, NULL) || j != k) {
1555 if (statistics)
1556 printf("\n");
c51a56e2 1557 bump("%s: Read error", src);
07d9aa13 1558 }
120e4b40 1559 if (scp_send_filedata(transbuf, k))
1560 bump("%s: Network error occurred", src);
1561
c51a56e2 1562 if (statistics) {
1563 stat_bytes += k;
32874aea 1564 if (time(NULL) != stat_lasttime || i + k == size) {
c51a56e2 1565 stat_lasttime = time(NULL);
1566 print_stats(last, size, stat_bytes,
1567 stat_starttime, stat_lasttime);
1568 }
07d9aa13 1569 }
5471d09a 1570
c51a56e2 1571 }
1572 CloseHandle(f);
07d9aa13 1573
120e4b40 1574 (void) scp_send_finish();
07d9aa13 1575}
1576
07d9aa13 1577/*
1578 * Recursively send the contents of a directory.
1579 */
1580static void rsource(char *src)
1581{
03f64569 1582 char *last, *findfile;
fd5e5847 1583 char *save_target;
c51a56e2 1584 HANDLE dir;
1585 WIN32_FIND_DATA fdat;
1586 int ok;
1587
1588 if ((last = strrchr(src, '/')) == NULL)
1589 last = src;
1590 else
1591 last++;
1592 if (strrchr(last, '\\') != NULL)
1593 last = strrchr(last, '\\') + 1;
1594 if (last == src && strchr(src, ':') != NULL)
1595 last = strchr(src, ':') + 1;
1596
1597 /* maybe send filetime */
1598
fd5e5847 1599 save_target = scp_save_remotepath();
1600
c51a56e2 1601 if (verbose)
120e4b40 1602 tell_user(stderr, "Entering directory: %s", last);
1603 if (scp_send_dirname(last, 0755))
c51a56e2 1604 return;
1605
03f64569 1606 findfile = dupcat(src, "/*", NULL);
1607 dir = FindFirstFile(findfile, &fdat);
c51a56e2 1608 ok = (dir != INVALID_HANDLE_VALUE);
1609 while (ok) {
1610 if (strcmp(fdat.cFileName, ".") == 0 ||
1611 strcmp(fdat.cFileName, "..") == 0) {
03f64569 1612 /* ignore . and .. */
c51a56e2 1613 } else {
fd5e5847 1614 char *foundfile = dupcat(src, "/", fdat.cFileName, NULL);
03f64569 1615 source(foundfile);
1616 sfree(foundfile);
07d9aa13 1617 }
c51a56e2 1618 ok = FindNextFile(dir, &fdat);
1619 }
1620 FindClose(dir);
03f64569 1621 sfree(findfile);
07d9aa13 1622
120e4b40 1623 (void) scp_send_enddir();
fd5e5847 1624
1625 scp_restore_remotepath(save_target);
07d9aa13 1626}
1627
07d9aa13 1628/*
03f64569 1629 * Execute the sink part of the SCP protocol.
07d9aa13 1630 */
ca2d5943 1631static void sink(char *targ, char *src)
07d9aa13 1632{
03f64569 1633 char *destfname;
c51a56e2 1634 int targisdir = 0;
c51a56e2 1635 int exists;
1636 DWORD attr;
1637 HANDLE f;
120e4b40 1638 unsigned long received;
c51a56e2 1639 int wrerror = 0;
1640 unsigned long stat_bytes;
1641 time_t stat_starttime, stat_lasttime;
1642 char *stat_name;
1643
1644 attr = GetFileAttributes(targ);
32874aea 1645 if (attr != (DWORD) - 1 && (attr & FILE_ATTRIBUTE_DIRECTORY) != 0)
c51a56e2 1646 targisdir = 1;
1647
1648 if (targetshouldbedirectory && !targisdir)
1649 bump("%s: Not a directory", targ);
1650
120e4b40 1651 scp_sink_init();
c51a56e2 1652 while (1) {
120e4b40 1653 struct scp_sink_action act;
1654 if (scp_get_sink_action(&act))
c51a56e2 1655 return;
07d9aa13 1656
120e4b40 1657 if (act.action == SCP_SINK_ENDDIR)
1658 return;
03f64569 1659
4eb24e3a 1660 if (act.action == SCP_SINK_RETRY)
1661 continue;
1662
c51a56e2 1663 if (targisdir) {
03f64569 1664 /*
1665 * Prevent the remote side from maliciously writing to
1666 * files outside the target area by sending a filename
1667 * containing `../'. In fact, it shouldn't be sending
b3dcd9b2 1668 * filenames with any slashes or colons in at all; so
1669 * we'll find the last slash, backslash or colon in the
1670 * filename and use only the part after that. (And
1671 * warn!)
03f64569 1672 *
1673 * In addition, we also ensure here that if we're
1674 * copying a single file and the target is a directory
1675 * (common usage: `pscp host:filename .') the remote
1676 * can't send us a _different_ file name. We can
1677 * distinguish this case because `src' will be non-NULL
1678 * and the last component of that will fail to match
1679 * (the last component of) the name sent.
4eeae4a3 1680 *
cd1f39ab 1681 * Well, not always; if `src' is a wildcard, we do
4eeae4a3 1682 * expect to get back filenames that don't correspond
cd1f39ab 1683 * exactly to it. Ideally in this case, we would like
1684 * to ensure that the returned filename actually
1685 * matches the wildcard pattern - but one of SCP's
1686 * protocol infelicities is that wildcard matching is
1687 * done at the server end _by the server's rules_ and
1688 * so in general this is infeasible. Hence, we only
1689 * accept filenames that don't correspond to `src' if
1690 * unsafe mode is enabled or we are using SFTP (which
1691 * resolves remote wildcards on the client side and can
1692 * be trusted).
03f64569 1693 */
1694 char *striptarget, *stripsrc;
1695
4eb24e3a 1696 striptarget = stripslashes(act.name, 1);
03f64569 1697 if (striptarget != act.name) {
1698 tell_user(stderr, "warning: remote host sent a compound"
b3dcd9b2 1699 " pathname '%s'", act.name);
1700 tell_user(stderr, " renaming local file to '%s'",
1701 striptarget);
03f64569 1702 }
1703
1704 /*
1705 * Also check to see if the target filename is '.' or
1706 * '..', or indeed '...' and so on because Windows
1707 * appears to interpret those like '..'.
1708 */
fd5e5847 1709 if (is_dots(striptarget)) {
03f64569 1710 bump("security violation: remote host attempted to write to"
1711 " a '.' or '..' path!");
1712 }
1713
1714 if (src) {
4eb24e3a 1715 stripsrc = stripslashes(src, 1);
cd1f39ab 1716 if (strcmp(striptarget, stripsrc) &&
1717 !using_sftp && !scp_unsafe_mode) {
1718 tell_user(stderr, "warning: remote host tried to write "
1719 "to a file called '%s'", striptarget);
1720 tell_user(stderr, " when we requested a file "
1721 "called '%s'.", stripsrc);
1722 tell_user(stderr, " If this is a wildcard, "
1723 "consider upgrading to SSH 2 or using");
1724 tell_user(stderr, " the '-unsafe' option. Renaming"
1725 " of this file has been disallowed.");
4eeae4a3 1726 /* Override the name the server provided with our own. */
1727 striptarget = stripsrc;
03f64569 1728 }
03f64569 1729 }
1730
c51a56e2 1731 if (targ[0] != '\0')
03f64569 1732 destfname = dupcat(targ, "\\", striptarget, NULL);
1733 else
1734 destfname = dupstr(striptarget);
c51a56e2 1735 } else {
03f64569 1736 /*
1737 * In this branch of the if, the target area is a
1738 * single file with an explicitly specified name in any
1739 * case, so there's no danger.
1740 */
1741 destfname = dupstr(targ);
c51a56e2 1742 }
03f64569 1743 attr = GetFileAttributes(destfname);
32874aea 1744 exists = (attr != (DWORD) - 1);
c51a56e2 1745
120e4b40 1746 if (act.action == SCP_SINK_DIR) {
c51a56e2 1747 if (exists && (attr & FILE_ATTRIBUTE_DIRECTORY) == 0) {
03f64569 1748 run_err("%s: Not a directory", destfname);
c51a56e2 1749 continue;
1750 }
1751 if (!exists) {
03f64569 1752 if (!CreateDirectory(destfname, NULL)) {
1753 run_err("%s: Cannot create directory", destfname);
c51a56e2 1754 continue;
1755 }
1756 }
03f64569 1757 sink(destfname, NULL);
c51a56e2 1758 /* can we set the timestamp for directories ? */
1759 continue;
1760 }
07d9aa13 1761
03f64569 1762 f = CreateFile(destfname, GENERIC_WRITE, 0, NULL,
c51a56e2 1763 CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
1764 if (f == INVALID_HANDLE_VALUE) {
03f64569 1765 run_err("%s: Cannot create file", destfname);
c51a56e2 1766 continue;
1767 }
07d9aa13 1768
120e4b40 1769 if (scp_accept_filexfer())
1770 return;
07d9aa13 1771
2d466ffd 1772 stat_bytes = 0;
1773 stat_starttime = time(NULL);
1774 stat_lasttime = 0;
4eb24e3a 1775 stat_name = stripslashes(destfname, 1);
07d9aa13 1776
120e4b40 1777 received = 0;
1778 while (received < act.size) {
c51a56e2 1779 char transbuf[4096];
120e4b40 1780 DWORD blksize, read, written;
1781 blksize = 4096;
1782 if (blksize > act.size - received)
1783 blksize = act.size - received;
1784 read = scp_recv_filedata(transbuf, blksize);
1785 if (read <= 0)
c51a56e2 1786 bump("Lost connection");
32874aea 1787 if (wrerror)
1788 continue;
120e4b40 1789 if (!WriteFile(f, transbuf, read, &written, NULL) ||
1790 written != read) {
c51a56e2 1791 wrerror = 1;
120e4b40 1792 /* FIXME: in sftp we can actually abort the transfer */
c51a56e2 1793 if (statistics)
1794 printf("\r%-25.25s | %50s\n",
1795 stat_name,
1796 "Write error.. waiting for end of file");
1797 continue;
1798 }
1799 if (statistics) {
120e4b40 1800 stat_bytes += read;
1801 if (time(NULL) > stat_lasttime ||
1802 received + read == act.size) {
c51a56e2 1803 stat_lasttime = time(NULL);
120e4b40 1804 print_stats(stat_name, act.size, stat_bytes,
c51a56e2 1805 stat_starttime, stat_lasttime);
07d9aa13 1806 }
c51a56e2 1807 }
120e4b40 1808 received += read;
c51a56e2 1809 }
120e4b40 1810 if (act.settime) {
c51a56e2 1811 FILETIME actime, wrtime;
120e4b40 1812 TIME_POSIX_TO_WIN(act.atime, actime);
1813 TIME_POSIX_TO_WIN(act.mtime, wrtime);
c51a56e2 1814 SetFileTime(f, NULL, &actime, &wrtime);
07d9aa13 1815 }
07d9aa13 1816
c51a56e2 1817 CloseHandle(f);
1818 if (wrerror) {
03f64569 1819 run_err("%s: Write error", destfname);
c51a56e2 1820 continue;
1821 }
120e4b40 1822 (void) scp_finish_filerecv();
03f64569 1823 sfree(destfname);
d4aa8594 1824 sfree(act.buf);
c51a56e2 1825 }
1826}
07d9aa13 1827
1828/*
120e4b40 1829 * We will copy local files to a remote server.
07d9aa13 1830 */
1831static void toremote(int argc, char *argv[])
1832{
c51a56e2 1833 char *src, *targ, *host, *user;
1834 char *cmd;
1835 int i;
1836
32874aea 1837 targ = argv[argc - 1];
c51a56e2 1838
39ddf0ff 1839 /* Separate host from filename */
c51a56e2 1840 host = targ;
1841 targ = colon(targ);
1842 if (targ == NULL)
1843 bump("targ == NULL in toremote()");
1844 *targ++ = '\0';
1845 if (*targ == '\0')
1846 targ = ".";
1847 /* Substitute "." for emtpy target */
1848
39ddf0ff 1849 /* Separate host and username */
c51a56e2 1850 user = host;
1851 host = strrchr(host, '@');
1852 if (host == NULL) {
1853 host = user;
1854 user = NULL;
1855 } else {
1856 *host++ = '\0';
1857 if (*user == '\0')
1858 user = NULL;
1859 }
1860
1861 if (argc == 2) {
1862 /* Find out if the source filespec covers multiple files
32874aea 1863 if so, we should set the targetshouldbedirectory flag */
c51a56e2 1864 HANDLE fh;
1865 WIN32_FIND_DATA fdat;
1866 if (colon(argv[0]) != NULL)
1867 bump("%s: Remote to remote not supported", argv[0]);
1868 fh = FindFirstFile(argv[0], &fdat);
1869 if (fh == INVALID_HANDLE_VALUE)
1870 bump("%s: No such file or directory\n", argv[0]);
1871 if (FindNextFile(fh, &fdat))
1872 targetshouldbedirectory = 1;
1873 FindClose(fh);
1874 }
1875
1876 cmd = smalloc(strlen(targ) + 100);
1877 sprintf(cmd, "scp%s%s%s%s -t %s",
1878 verbose ? " -v" : "",
1879 recursive ? " -r" : "",
1880 preserve ? " -p" : "",
32874aea 1881 targetshouldbedirectory ? " -d" : "", targ);
c51a56e2 1882 do_cmd(host, user, cmd);
1883 sfree(cmd);
1884
fd5e5847 1885 scp_source_setup(targ, targetshouldbedirectory);
c51a56e2 1886
1887 for (i = 0; i < argc - 1; i++) {
03f64569 1888 char *srcpath, *last;
c51a56e2 1889 HANDLE dir;
1890 WIN32_FIND_DATA fdat;
1891 src = argv[i];
1892 if (colon(src) != NULL) {
cc87246d 1893 tell_user(stderr, "%s: Remote to remote not supported\n", src);
c51a56e2 1894 errs++;
1895 continue;
07d9aa13 1896 }
03f64569 1897
1898 /*
1899 * Trim off the last pathname component of `src', to
1900 * provide the base pathname which will be prepended to
1901 * filenames returned from Find{First,Next}File.
1902 */
1903 srcpath = dupstr(src);
4eb24e3a 1904 last = stripslashes(srcpath, 1);
03f64569 1905 *last = '\0';
03f64569 1906
c51a56e2 1907 dir = FindFirstFile(src, &fdat);
1908 if (dir == INVALID_HANDLE_VALUE) {
1909 run_err("%s: No such file or directory", src);
1910 continue;
07d9aa13 1911 }
c51a56e2 1912 do {
03f64569 1913 char *filename;
7f266ffb 1914 /*
1915 * Ensure that . and .. are never matched by wildcards,
1916 * but only by deliberate action.
1917 */
1918 if (!strcmp(fdat.cFileName, ".") ||
1919 !strcmp(fdat.cFileName, "..")) {
1920 /*
1921 * Find*File has returned a special dir. We require
1922 * that _either_ `src' ends in a backslash followed
1923 * by that string, _or_ `src' is precisely that
1924 * string.
1925 */
1926 int len = strlen(src), dlen = strlen(fdat.cFileName);
1927 if (len == dlen && !strcmp(src, fdat.cFileName)) {
32874aea 1928 /* ok */ ;
1929 } else if (len > dlen + 1 && src[len - dlen - 1] == '\\' &&
1930 !strcmp(src + len - dlen, fdat.cFileName)) {
1931 /* ok */ ;
7f266ffb 1932 } else
1933 continue; /* ignore this one */
1934 }
03f64569 1935 filename = dupcat(srcpath, fdat.cFileName, NULL);
1936 source(filename);
1937 sfree(filename);
c51a56e2 1938 } while (FindNextFile(dir, &fdat));
1939 FindClose(dir);
03f64569 1940 sfree(srcpath);
c51a56e2 1941 }
07d9aa13 1942}
1943
07d9aa13 1944/*
1945 * We will copy files from a remote server to the local machine.
1946 */
1947static void tolocal(int argc, char *argv[])
1948{
c51a56e2 1949 char *src, *targ, *host, *user;
1950 char *cmd;
1951
1952 if (argc != 2)
1953 bump("More than one remote source not supported");
1954
1955 src = argv[0];
1956 targ = argv[1];
1957
39ddf0ff 1958 /* Separate host from filename */
c51a56e2 1959 host = src;
1960 src = colon(src);
1961 if (src == NULL)
1962 bump("Local to local copy not supported");
1963 *src++ = '\0';
1964 if (*src == '\0')
1965 src = ".";
1966 /* Substitute "." for empty filename */
1967
39ddf0ff 1968 /* Separate username and hostname */
c51a56e2 1969 user = host;
1970 host = strrchr(host, '@');
1971 if (host == NULL) {
1972 host = user;
1973 user = NULL;
1974 } else {
1975 *host++ = '\0';
1976 if (*user == '\0')
1977 user = NULL;
1978 }
1979
1980 cmd = smalloc(strlen(src) + 100);
1981 sprintf(cmd, "scp%s%s%s%s -f %s",
1982 verbose ? " -v" : "",
1983 recursive ? " -r" : "",
1984 preserve ? " -p" : "",
32874aea 1985 targetshouldbedirectory ? " -d" : "", src);
c51a56e2 1986 do_cmd(host, user, cmd);
1987 sfree(cmd);
1988
4eb24e3a 1989 if (scp_sink_setup(src, preserve, recursive))
1990 return;
fd5e5847 1991
ca2d5943 1992 sink(targ, src);
07d9aa13 1993}
1994
07d9aa13 1995/*
39ddf0ff 1996 * We will issue a list command to get a remote directory.
1997 */
1998static void get_dir_list(int argc, char *argv[])
1999{
2000 char *src, *host, *user;
2001 char *cmd, *p, *q;
2002 char c;
2003
2004 src = argv[0];
2005
2006 /* Separate host from filename */
2007 host = src;
2008 src = colon(src);
2009 if (src == NULL)
2010 bump("Local to local copy not supported");
2011 *src++ = '\0';
2012 if (*src == '\0')
2013 src = ".";
2014 /* Substitute "." for empty filename */
2015
2016 /* Separate username and hostname */
2017 user = host;
2018 host = strrchr(host, '@');
2019 if (host == NULL) {
2020 host = user;
2021 user = NULL;
2022 } else {
2023 *host++ = '\0';
2024 if (*user == '\0')
2025 user = NULL;
2026 }
2027
32874aea 2028 cmd = smalloc(4 * strlen(src) + 100);
39ddf0ff 2029 strcpy(cmd, "ls -la '");
2030 p = cmd + strlen(cmd);
2031 for (q = src; *q; q++) {
2032 if (*q == '\'') {
32874aea 2033 *p++ = '\'';
2034 *p++ = '\\';
2035 *p++ = '\'';
2036 *p++ = '\'';
39ddf0ff 2037 } else {
2038 *p++ = *q;
2039 }
2040 }
2041 *p++ = '\'';
2042 *p = '\0';
cc87246d 2043
39ddf0ff 2044 do_cmd(host, user, cmd);
2045 sfree(cmd);
2046
fd5e5847 2047 if (using_sftp) {
2048 scp_sftp_listdir(src);
2049 } else {
2050 while (ssh_scp_recv(&c, 1) > 0)
2051 tell_char(stdout, c);
2052 }
39ddf0ff 2053}
2054
2055/*
07d9aa13 2056 * Initialize the Win$ock driver.
2057 */
996c8c3b 2058static void init_winsock(void)
07d9aa13 2059{
c51a56e2 2060 WORD winsock_ver;
2061 WSADATA wsadata;
2062
2063 winsock_ver = MAKEWORD(1, 1);
2064 if (WSAStartup(winsock_ver, &wsadata))
2065 bump("Unable to initialise WinSock");
32874aea 2066 if (LOBYTE(wsadata.wVersion) != 1 || HIBYTE(wsadata.wVersion) != 1)
c51a56e2 2067 bump("WinSock version is incompatible with 1.1");
07d9aa13 2068}
2069
07d9aa13 2070/*
2071 * Short description of parameters.
2072 */
996c8c3b 2073static void usage(void)
07d9aa13 2074{
c51a56e2 2075 printf("PuTTY Secure Copy client\n");
2076 printf("%s\n", ver);
a3e55ea1 2077 printf("Usage: pscp [options] [user@]host:source target\n");
32874aea 2078 printf
2079 (" pscp [options] source [source...] [user@]host:target\n");
a3e55ea1 2080 printf(" pscp [options] -ls user@host:filespec\n");
b8a19193 2081 printf("Options:\n");
2082 printf(" -p preserve file attributes\n");
2083 printf(" -q quiet, don't show statistics\n");
2084 printf(" -r copy directories recursively\n");
2085 printf(" -v show verbose messages\n");
2086 printf(" -P port connect to specified port\n");
2087 printf(" -pw passw login with specified password\n");
cd1f39ab 2088 printf(" -unsafe allow server-side wildcards (DANGEROUS)\n");
ee8b0370 2089#if 0
2090 /*
2091 * -gui is an internal option, used by GUI front ends to get
2092 * pscp to pass progress reports back to them. It's not an
2093 * ordinary user-accessible option, so it shouldn't be part of
2094 * the command-line help. The only people who need to know
2095 * about it are programmers, and they can read the source.
2096 */
32874aea 2097 printf
2098 (" -gui hWnd GUI mode with the windows handle for receiving messages\n");
ee8b0370 2099#endif
93b581bd 2100 cleanup_exit(1);
07d9aa13 2101}
2102
07d9aa13 2103/*
2104 * Main program (no, really?)
2105 */
2106int main(int argc, char *argv[])
2107{
c51a56e2 2108 int i;
2109
fb09bf1c 2110 default_protocol = PROT_TELNET;
2111
67779be7 2112 flags = FLAG_STDERR;
ff2ae367 2113 ssh_get_line = &console_get_line;
c51a56e2 2114 init_winsock();
8df7a775 2115 sk_init();
c51a56e2 2116
2117 for (i = 1; i < argc; i++) {
2118 if (argv[i][0] != '-')
2119 break;
2120 if (strcmp(argv[i], "-v") == 0)
4017be6d 2121 verbose = 1, flags |= FLAG_VERBOSE;
c51a56e2 2122 else if (strcmp(argv[i], "-r") == 0)
2123 recursive = 1;
2124 else if (strcmp(argv[i], "-p") == 0)
2125 preserve = 1;
2126 else if (strcmp(argv[i], "-q") == 0)
2127 statistics = 0;
ff2ae367 2128 else if (strcmp(argv[i], "-batch") == 0)
2129 console_batch_mode = 1;
32874aea 2130 else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-?") == 0)
c51a56e2 2131 usage();
32874aea 2132 else if (strcmp(argv[i], "-P") == 0 && i + 1 < argc)
b8a19193 2133 portnumber = atoi(argv[++i]);
32874aea 2134 else if (strcmp(argv[i], "-pw") == 0 && i + 1 < argc)
ff2ae367 2135 console_password = argv[++i];
32874aea 2136 else if (strcmp(argv[i], "-gui") == 0 && i + 1 < argc) {
cc87246d 2137 gui_hwnd = argv[++i];
2138 gui_mode = 1;
ff2ae367 2139 console_batch_mode = TRUE;
cc87246d 2140 } else if (strcmp(argv[i], "-ls") == 0)
32874aea 2141 list = 1;
cd1f39ab 2142 else if (strcmp(argv[i], "-unsafe") == 0)
2143 scp_unsafe_mode = 1;
32874aea 2144 else if (strcmp(argv[i], "--") == 0) {
2145 i++;
2146 break;
2147 } else
c51a56e2 2148 usage();
2149 }
2150 argc -= i;
2151 argv += i;
eba78553 2152 back = NULL;
c51a56e2 2153
39ddf0ff 2154 if (list) {
2155 if (argc != 1)
2156 usage();
2157 get_dir_list(argc, argv);
c51a56e2 2158
39ddf0ff 2159 } else {
2160
2161 if (argc < 2)
2162 usage();
2163 if (argc > 2)
2164 targetshouldbedirectory = 1;
2165
32874aea 2166 if (colon(argv[argc - 1]) != NULL)
39ddf0ff 2167 toremote(argc, argv);
2168 else
2169 tolocal(argc, argv);
2170 }
c51a56e2 2171
eba78553 2172 if (back != NULL && back->socket() != NULL) {
c51a56e2 2173 char ch;
3bdaf79d 2174 back->special(TS_EOF);
fb09bf1c 2175 ssh_scp_recv(&ch, 1);
c51a56e2 2176 }
2177 WSACleanup();
2178 random_save_seed();
07d9aa13 2179
cc87246d 2180 /* GUI Adaptation - August 2000 */
2181 if (gui_mode) {
2182 unsigned int msg_id = WM_RET_ERR_CNT;
32874aea 2183 if (list)
2184 msg_id = WM_LS_RET_ERR_CNT;
2185 while (!PostMessage
2186 ((HWND) atoi(gui_hwnd), msg_id, (WPARAM) errs,
2187 0 /*lParam */ ))SleepEx(1000, TRUE);
cc87246d 2188 }
c51a56e2 2189 return (errs == 0 ? 0 : 1);
07d9aa13 2190}
2191
2192/* end */