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