2 * scp.c - Scp (Secure Copy) client for PuTTY.
3 * Joris van Rantwijk, Simon Tatham
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.
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.)
30 #define PUTTY_DO_GLOBALS
37 #define TIME_POSIX_TO_WIN(t, ft) (*(LONGLONG*)&(ft) = \
38 ((LONGLONG) (t) + (LONGLONG) 11644473600) * (LONGLONG) 10000000)
39 #define TIME_WIN_TO_POSIX(ft, t) ((t) = (unsigned long) \
40 ((*(LONGLONG*)&(ft)) / (LONGLONG) 10000000 - (LONGLONG) 11644473600))
42 /* GUI Adaptation - Sept 2000 */
44 /* This is just a base value from which the main message numbers are
46 #define WM_APP_BASE 0x8000
48 /* These two pass a single character value in wParam. They represent
49 * the visible output from PSCP. */
50 #define WM_STD_OUT_CHAR ( WM_APP_BASE+400 )
51 #define WM_STD_ERR_CHAR ( WM_APP_BASE+401 )
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. */
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 )
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
69 #define WM_RET_ERR_CNT ( WM_APP_BASE+406 )
70 #define WM_LS_RET_ERR_CNT ( WM_APP_BASE+407 )
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). */
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 )
81 static int verbose
= 0;
82 static int recursive
= 0;
83 static int preserve
= 0;
84 static int targetshouldbedirectory
= 0;
85 static int statistics
= 1;
86 static int portnumber
= 0;
87 static int prev_stats_len
= 0;
88 static int scp_unsafe_mode
= 0;
89 static char *password
= NULL
;
91 /* GUI Adaptation - Sept 2000 */
92 #define NAME_STR_MAX 2048
93 static char statname
[NAME_STR_MAX
+ 1];
94 static unsigned long statsize
= 0;
95 static unsigned long statdone
= 0;
96 static unsigned long stateta
= 0;
97 static unsigned long statratebs
= 0;
98 static int statperct
= 0;
99 static unsigned long statelapsed
= 0;
100 static int gui_mode
= 0;
101 static char *gui_hwnd
= NULL
;
102 static int using_sftp
= 0;
104 static void source(char *src
);
105 static void rsource(char *src
);
106 static void sink(char *targ
, char *src
);
107 /* GUI Adaptation - Sept 2000 */
108 static void tell_char(FILE * stream
, char c
);
109 static void tell_str(FILE * stream
, char *str
);
110 static void tell_user(FILE * stream
, char *fmt
, ...);
111 static void gui_update_stats(char *name
, unsigned long size
,
112 int percentage
, unsigned long elapsed
,
113 unsigned long done
, unsigned long eta
,
114 unsigned long ratebs
);
117 * The maximum amount of queued data we accept before we stop and
118 * wait for the server to process some.
120 #define MAX_SCP_BUFSIZE 16384
122 void ldisc_send(char *buf
, int len
, int interactive
)
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
133 /* GUI Adaptation - Sept 2000 */
134 static void send_msg(HWND h
, UINT message
, WPARAM wParam
)
136 while (!PostMessage(h
, message
, wParam
, 0))
140 static void tell_char(FILE * stream
, char c
)
145 unsigned int msg_id
= WM_STD_OUT_CHAR
;
146 if (stream
== stderr
)
147 msg_id
= WM_STD_ERR_CHAR
;
148 send_msg((HWND
) atoi(gui_hwnd
), msg_id
, (WPARAM
) c
);
152 static void tell_str(FILE * stream
, char *str
)
156 for (i
= 0; i
< strlen(str
); ++i
)
157 tell_char(stream
, str
[i
]);
160 static void tell_user(FILE * stream
, char *fmt
, ...)
162 char str
[0x100]; /* Make the size big enough */
165 vsprintf(str
, fmt
, ap
);
168 tell_str(stream
, str
);
171 static void gui_update_stats(char *name
, unsigned long size
,
172 int percentage
, unsigned long elapsed
,
173 unsigned long done
, unsigned long eta
,
174 unsigned long ratebs
)
178 if (strcmp(name
, statname
) != 0) {
179 for (i
= 0; i
< strlen(name
); ++i
)
180 send_msg((HWND
) atoi(gui_hwnd
), WM_STATS_CHAR
,
182 send_msg((HWND
) atoi(gui_hwnd
), WM_STATS_CHAR
, (WPARAM
) '\n');
183 strcpy(statname
, name
);
185 if (statsize
!= size
) {
186 send_msg((HWND
) atoi(gui_hwnd
), WM_STATS_SIZE
, (WPARAM
) size
);
189 if (statdone
!= done
) {
190 send_msg((HWND
) atoi(gui_hwnd
), WM_STATS_DONE
, (WPARAM
) done
);
193 if (stateta
!= eta
) {
194 send_msg((HWND
) atoi(gui_hwnd
), WM_STATS_ETA
, (WPARAM
) eta
);
197 if (statratebs
!= ratebs
) {
198 send_msg((HWND
) atoi(gui_hwnd
), WM_STATS_RATEBS
, (WPARAM
) ratebs
);
201 if (statelapsed
!= elapsed
) {
202 send_msg((HWND
) atoi(gui_hwnd
), WM_STATS_ELAPSED
,
204 statelapsed
= elapsed
;
206 if (statperct
!= percentage
) {
207 send_msg((HWND
) atoi(gui_hwnd
), WM_STATS_PERCENT
,
208 (WPARAM
) percentage
);
209 statperct
= percentage
;
214 * Print an error message and perform a fatal exit.
216 void fatalbox(char *fmt
, ...)
218 char str
[0x100]; /* Make the size big enough */
221 strcpy(str
, "Fatal: ");
222 vsprintf(str
+ strlen(str
), fmt
, ap
);
225 tell_str(stderr
, str
);
229 unsigned int msg_id
= WM_RET_ERR_CNT
;
231 msg_id
= WM_LS_RET_ERR_CNT
;
233 ((HWND
) atoi(gui_hwnd
), msg_id
, (WPARAM
) errs
,
234 0 /*lParam */ ))SleepEx(1000, TRUE
);
239 void connection_fatal(char *fmt
, ...)
241 char str
[0x100]; /* Make the size big enough */
244 strcpy(str
, "Fatal: ");
245 vsprintf(str
+ strlen(str
), fmt
, ap
);
248 tell_str(stderr
, str
);
252 unsigned int msg_id
= WM_RET_ERR_CNT
;
254 msg_id
= WM_LS_RET_ERR_CNT
;
256 ((HWND
) atoi(gui_hwnd
), msg_id
, (WPARAM
) errs
,
257 0 /*lParam */ ))SleepEx(1000, TRUE
);
264 * Be told what socket we're supposed to be using.
266 static SOCKET scp_ssh_socket
;
267 char *do_select(SOCKET skt
, int startup
)
270 scp_ssh_socket
= skt
;
272 scp_ssh_socket
= INVALID_SOCKET
;
275 extern int select_result(WPARAM
, LPARAM
);
278 * Receive a block of data from the SSH link. Block until all data
281 * To do this, we repeatedly call the SSH protocol module, with our
282 * own trap in from_backend() to catch the data that comes back. We
283 * do this until we have enough data.
286 static unsigned char *outptr
; /* where to put the data */
287 static unsigned outlen
; /* how much data required */
288 static unsigned char *pending
= NULL
; /* any spare data */
289 static unsigned pendlen
= 0, pendsize
= 0; /* length and phys. size of buffer */
290 int from_backend(int is_stderr
, char *data
, int datalen
)
292 unsigned char *p
= (unsigned char *) data
;
293 unsigned len
= (unsigned) datalen
;
298 * stderr data is just spouted to local stderr and otherwise
302 fwrite(data
, 1, len
, stderr
);
307 * If this is before the real session begins, just return.
313 unsigned used
= outlen
;
316 memcpy(outptr
, p
, used
);
324 if (pendsize
< pendlen
+ len
) {
325 pendsize
= pendlen
+ len
+ 4096;
326 pending
= (pending ?
srealloc(pending
, pendsize
) :
329 fatalbox("Out of memory");
331 memcpy(pending
+ pendlen
, p
, len
);
337 static int scp_process_network_event(void)
342 FD_SET(scp_ssh_socket
, &readfds
);
343 if (select(1, &readfds
, NULL
, NULL
, NULL
) < 0)
345 select_result((WPARAM
) scp_ssh_socket
, (LPARAM
) FD_READ
);
348 static int ssh_scp_recv(unsigned char *buf
, int len
)
354 * See if the pending-input block contains some of what we
358 unsigned pendused
= pendlen
;
359 if (pendused
> outlen
)
361 memcpy(outptr
, pending
, pendused
);
362 memmove(pending
, pending
+ pendused
, pendlen
- pendused
);
376 if (!scp_process_network_event())
384 * Loop through the ssh connection and authentication process.
386 static void ssh_scp_init(void)
388 if (scp_ssh_socket
== INVALID_SOCKET
)
390 while (!back
->sendok()) {
393 FD_SET(scp_ssh_socket
, &readfds
);
394 if (select(1, &readfds
, NULL
, NULL
, NULL
) < 0)
396 select_result((WPARAM
) scp_ssh_socket
, (LPARAM
) FD_READ
);
398 using_sftp
= !ssh_fallback_cmd
;
402 * Print an error message and exit after closing the SSH link.
404 static void bump(char *fmt
, ...)
406 char str
[0x100]; /* Make the size big enough */
409 strcpy(str
, "Fatal: ");
410 vsprintf(str
+ strlen(str
), fmt
, ap
);
413 tell_str(stderr
, str
);
416 if (back
!= NULL
&& back
->socket() != NULL
) {
418 back
->special(TS_EOF
);
419 ssh_scp_recv(&ch
, 1);
423 unsigned int msg_id
= WM_RET_ERR_CNT
;
425 msg_id
= WM_LS_RET_ERR_CNT
;
427 ((HWND
) atoi(gui_hwnd
), msg_id
, (WPARAM
) errs
,
428 0 /*lParam */ ))SleepEx(1000, TRUE
);
435 * Open an SSH connection to user@host and execute cmd.
437 static void do_cmd(char *host
, char *user
, char *cmd
)
439 char *err
, *realhost
;
442 if (host
== NULL
|| host
[0] == '\0')
443 bump("Empty host name");
445 /* Try to load settings for this host */
446 do_defaults(host
, &cfg
);
447 if (cfg
.host
[0] == '\0') {
448 /* No settings for this host; use defaults */
449 do_defaults(NULL
, &cfg
);
450 strncpy(cfg
.host
, host
, sizeof(cfg
.host
) - 1);
451 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
456 * Enact command-line overrides.
461 * Trim leading whitespace off the hostname if it's there.
464 int space
= strspn(cfg
.host
, " \t");
465 memmove(cfg
.host
, cfg
.host
+space
, 1+strlen(cfg
.host
)-space
);
468 /* See if host is of the form user@host */
469 if (cfg
.host
[0] != '\0') {
470 char *atsign
= strchr(cfg
.host
, '@');
471 /* Make sure we're not overflowing the user field */
473 if (atsign
- cfg
.host
< sizeof cfg
.username
) {
474 strncpy(cfg
.username
, cfg
.host
, atsign
- cfg
.host
);
475 cfg
.username
[atsign
- cfg
.host
] = '\0';
477 memmove(cfg
.host
, atsign
+ 1, 1 + strlen(atsign
+ 1));
482 * Trim a colon suffix off the hostname if it's there.
484 cfg
.host
[strcspn(cfg
.host
, ":")] = '\0';
487 if (user
!= NULL
&& user
[0] != '\0') {
488 strncpy(cfg
.username
, user
, sizeof(cfg
.username
) - 1);
489 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
490 } else if (cfg
.username
[0] == '\0') {
492 if (GetUserName(user
, &namelen
) == FALSE
)
493 bump("Empty user name");
494 user
= smalloc(namelen
* sizeof(char));
495 GetUserName(user
, &namelen
);
497 tell_user(stderr
, "Guessing user name: %s", user
);
498 strncpy(cfg
.username
, user
, sizeof(cfg
.username
) - 1);
499 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
503 if (cfg
.protocol
!= PROT_SSH
)
507 cfg
.port
= portnumber
;
510 * Disable scary things which shouldn't be enabled for simple
511 * things like SCP and SFTP: agent forwarding, port forwarding,
516 cfg
.portfwd
[0] = cfg
.portfwd
[1] = '\0';
519 * Attempt to start the SFTP subsystem as a first choice,
520 * falling back to the provided scp command if that fails.
522 strcpy(cfg
.remote_cmd
, "sftp");
523 cfg
.ssh_subsys
= TRUE
;
524 cfg
.remote_cmd_ptr2
= cmd
;
525 cfg
.ssh_subsys2
= FALSE
;
530 err
= back
->init(cfg
.host
, cfg
.port
, &realhost
, 0);
532 bump("ssh_init: %s", err
);
534 if (verbose
&& realhost
!= NULL
)
535 tell_user(stderr
, "Connected to %s\n", realhost
);
540 * Update statistic information about current file.
542 static void print_stats(char *name
, unsigned long size
, unsigned long done
,
543 time_t start
, time_t now
)
552 elap
= (unsigned long) difftime(now
, start
);
555 ratebs
= (float) done
/ elap
;
557 ratebs
= (float) done
;
562 eta
= (unsigned long) ((size
- done
) / ratebs
);
563 sprintf(etastr
, "%02ld:%02ld:%02ld",
564 eta
/ 3600, (eta
% 3600) / 60, eta
% 60);
566 pct
= (int) (100 * (done
* 1.0 / size
));
569 /* GUI Adaptation - Sept 2000 */
570 gui_update_stats(name
, size
, pct
, elap
, done
, eta
,
571 (unsigned long) ratebs
);
573 len
= printf("\r%-25.25s | %10ld kB | %5.1f kB/s | ETA: %8s | %3d%%",
574 name
, done
/ 1024, ratebs
/ 1024.0, etastr
, pct
);
575 if (len
< prev_stats_len
)
576 printf("%*s", prev_stats_len
- len
, "");
577 prev_stats_len
= len
;
585 * Find a colon in str and return a pointer to the colon.
586 * This is used to separate hostname from filename.
588 static char *colon(char *str
)
590 /* We ignore a leading colon, since the hostname cannot be
591 empty. We also ignore a colon as second character because
592 of filenames like f:myfile.txt. */
593 if (str
[0] == '\0' || str
[0] == ':' || str
[1] == ':')
595 while (*str
!= '\0' && *str
!= ':' && *str
!= '/' && *str
!= '\\')
604 * Return a pointer to the portion of str that comes after the last
605 * slash (or backslash or colon, if `local' is TRUE).
607 static char *stripslashes(char *str
, int local
)
612 p
= strchr(str
, ':');
616 p
= strrchr(str
, '/');
620 p
= strrchr(str
, '\\');
628 * Determine whether a string is entirely composed of dots.
630 static int is_dots(char *str
)
632 return str
[strspn(str
, ".")] == '\0';
636 * Wait for a response from the other side.
637 * Return 0 if ok, -1 if error.
639 static int response(void)
641 char ch
, resp
, rbuf
[2048];
644 if (ssh_scp_recv(&resp
, 1) <= 0)
645 bump("Lost connection");
655 case 2: /* fatal error */
657 if (ssh_scp_recv(&ch
, 1) <= 0)
658 bump("Protocol error: Lost connection");
660 } while (p
< sizeof(rbuf
) && ch
!= '\n');
663 tell_user(stderr
, "%s\n", rbuf
);
671 int sftp_recvdata(char *buf
, int len
)
673 return ssh_scp_recv(buf
, len
);
675 int sftp_senddata(char *buf
, int len
)
677 back
->send((unsigned char *) buf
, len
);
681 /* ----------------------------------------------------------------------
682 * sftp-based replacement for the hacky `pscp -ls'.
684 static int sftp_ls_compare(const void *av
, const void *bv
)
686 const struct fxp_name
*a
= (const struct fxp_name
*) av
;
687 const struct fxp_name
*b
= (const struct fxp_name
*) bv
;
688 return strcmp(a
->filename
, b
->filename
);
690 void scp_sftp_listdir(char *dirname
)
692 struct fxp_handle
*dirh
;
693 struct fxp_names
*names
;
694 struct fxp_name
*ournames
;
695 int nnames
, namesize
;
699 tell_user(stderr
, "unable to initialise SFTP: %s", fxp_error());
704 printf("Listing directory %s\n", dirname
);
706 dirh
= fxp_opendir(dirname
);
708 printf("Unable to open %s: %s\n", dirname
, fxp_error());
710 nnames
= namesize
= 0;
715 names
= fxp_readdir(dirh
);
717 if (fxp_error_type() == SSH_FX_EOF
)
719 printf("Reading directory %s: %s\n", dirname
, fxp_error());
722 if (names
->nnames
== 0) {
723 fxp_free_names(names
);
727 if (nnames
+ names
->nnames
>= namesize
) {
728 namesize
+= names
->nnames
+ 128;
730 srealloc(ournames
, namesize
* sizeof(*ournames
));
733 for (i
= 0; i
< names
->nnames
; i
++)
734 ournames
[nnames
++] = names
->names
[i
];
736 names
->nnames
= 0; /* prevent free_names */
737 fxp_free_names(names
);
742 * Now we have our filenames. Sort them by actual file
743 * name, and then output the longname parts.
745 qsort(ournames
, nnames
, sizeof(*ournames
), sftp_ls_compare
);
750 for (i
= 0; i
< nnames
; i
++)
751 printf("%s\n", ournames
[i
].longname
);
755 /* ----------------------------------------------------------------------
756 * Helper routines that contain the actual SCP protocol elements,
757 * implemented both as SCP1 and SFTP.
760 static struct scp_sftp_dirstack
{
761 struct scp_sftp_dirstack
*next
;
762 struct fxp_name
*names
;
763 int namepos
, namelen
;
766 int matched_something
; /* wildcard match set was non-empty */
767 } *scp_sftp_dirstack_head
;
768 static char *scp_sftp_remotepath
, *scp_sftp_currentname
;
769 static char *scp_sftp_wildcard
;
770 static int scp_sftp_targetisdir
, scp_sftp_donethistarget
;
771 static int scp_sftp_preserve
, scp_sftp_recursive
;
772 static unsigned long scp_sftp_mtime
, scp_sftp_atime
;
773 static int scp_has_times
;
774 static struct fxp_handle
*scp_sftp_filehandle
;
775 static uint64 scp_sftp_fileoffset
;
777 void scp_source_setup(char *target
, int shouldbedir
)
781 * Find out whether the target filespec is in fact a
784 struct fxp_attrs attrs
;
787 tell_user(stderr
, "unable to initialise SFTP: %s", fxp_error());
792 if (!fxp_stat(target
, &attrs
) ||
793 !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
))
794 scp_sftp_targetisdir
= 0;
796 scp_sftp_targetisdir
= (attrs
.permissions
& 0040000) != 0;
798 if (shouldbedir
&& !scp_sftp_targetisdir
) {
799 bump("pscp: remote filespec %s: not a directory\n", target
);
802 scp_sftp_remotepath
= dupstr(target
);
810 int scp_send_errmsg(char *str
)
813 /* do nothing; we never need to send our errors to the server */
815 back
->send("\001", 1); /* scp protocol error prefix */
816 back
->send(str
, strlen(str
));
818 return 0; /* can't fail */
821 int scp_send_filetimes(unsigned long mtime
, unsigned long atime
)
824 scp_sftp_mtime
= mtime
;
825 scp_sftp_atime
= atime
;
830 sprintf(buf
, "T%lu 0 %lu 0\n", mtime
, atime
);
831 back
->send(buf
, strlen(buf
));
836 int scp_send_filename(char *name
, unsigned long size
, int modes
)
840 if (scp_sftp_targetisdir
) {
841 fullname
= dupcat(scp_sftp_remotepath
, "/", name
, NULL
);
843 fullname
= dupstr(scp_sftp_remotepath
);
845 scp_sftp_filehandle
=
846 fxp_open(fullname
, SSH_FXF_WRITE
| SSH_FXF_CREAT
| SSH_FXF_TRUNC
);
847 if (!scp_sftp_filehandle
) {
848 tell_user(stderr
, "pscp: unable to open %s: %s",
849 fullname
, fxp_error());
853 scp_sftp_fileoffset
= uint64_make(0, 0);
858 sprintf(buf
, "C%04o %lu ", modes
, size
);
859 back
->send(buf
, strlen(buf
));
860 back
->send(name
, strlen(name
));
866 int scp_send_filedata(char *data
, int len
)
869 if (!scp_sftp_filehandle
) {
872 if (!fxp_write(scp_sftp_filehandle
, data
, scp_sftp_fileoffset
, len
)) {
873 tell_user(stderr
, "error while writing: %s\n", fxp_error());
877 scp_sftp_fileoffset
= uint64_add32(scp_sftp_fileoffset
, len
);
880 int bufsize
= back
->send(data
, len
);
883 * If the network transfer is backing up - that is, the
884 * remote site is not accepting data as fast as we can
885 * produce it - then we must loop on network events until
886 * we have space in the buffer again.
888 while (bufsize
> MAX_SCP_BUFSIZE
) {
889 if (!scp_process_network_event())
891 bufsize
= back
->sendbuffer();
898 int scp_send_finish(void)
901 struct fxp_attrs attrs
;
902 if (!scp_sftp_filehandle
) {
906 attrs
.flags
= SSH_FILEXFER_ATTR_ACMODTIME
;
907 attrs
.atime
= scp_sftp_atime
;
908 attrs
.mtime
= scp_sftp_mtime
;
909 if (!fxp_fsetstat(scp_sftp_filehandle
, attrs
)) {
910 tell_user(stderr
, "unable to set file times: %s\n", fxp_error());
914 fxp_close(scp_sftp_filehandle
);
923 char *scp_save_remotepath(void)
926 return scp_sftp_remotepath
;
931 void scp_restore_remotepath(char *data
)
934 scp_sftp_remotepath
= data
;
937 int scp_send_dirname(char *name
, int modes
)
942 struct fxp_attrs attrs
;
943 if (scp_sftp_targetisdir
) {
944 fullname
= dupcat(scp_sftp_remotepath
, "/", name
, NULL
);
946 fullname
= dupstr(scp_sftp_remotepath
);
950 * We don't worry about whether we managed to create the
951 * directory, because if it exists already it's OK just to
952 * use it. Instead, we will stat it afterwards, and if it
953 * exists and is a directory we will assume we were either
954 * successful or it didn't matter.
956 if (!fxp_mkdir(fullname
))
959 err
= "server reported no error";
960 if (!fxp_stat(fullname
, &attrs
) ||
961 !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
) ||
962 !(attrs
.permissions
& 0040000)) {
963 tell_user(stderr
, "unable to create directory %s: %s",
969 scp_sftp_remotepath
= fullname
;
974 sprintf(buf
, "D%04o 0 ", modes
);
975 back
->send(buf
, strlen(buf
));
976 back
->send(name
, strlen(name
));
982 int scp_send_enddir(void)
985 sfree(scp_sftp_remotepath
);
988 back
->send("E\n", 2);
994 * Yes, I know; I have an scp_sink_setup _and_ an scp_sink_init.
995 * That's bad. The difference is that scp_sink_setup is called once
996 * right at the start, whereas scp_sink_init is called to
997 * initialise every level of recursion in the protocol.
999 int scp_sink_setup(char *source
, int preserve
, int recursive
)
1005 tell_user(stderr
, "unable to initialise SFTP: %s", fxp_error());
1010 * It's possible that the source string we've been given
1011 * contains a wildcard. If so, we must split the directory
1012 * away from the wildcard itself (throwing an error if any
1013 * wildcardness comes before the final slash) and arrange
1014 * things so that a dirstack entry will be set up.
1016 newsource
= smalloc(1+strlen(source
));
1017 if (!wc_unescape(newsource
, source
)) {
1018 /* Yes, here we go; it's a wildcard. Bah. */
1019 char *dupsource
, *lastpart
, *dirpart
, *wildcard
;
1020 dupsource
= dupstr(source
);
1021 lastpart
= stripslashes(dupsource
, 0);
1022 wildcard
= dupstr(lastpart
);
1024 if (*dupsource
&& dupsource
[1]) {
1026 * The remains of dupsource are at least two
1027 * characters long, meaning the pathname wasn't
1028 * empty or just `/'. Hence, we remove the trailing
1031 lastpart
[-1] = '\0';
1032 } else if (!*dupsource
) {
1034 * The remains of dupsource are _empty_ - the whole
1035 * pathname was a wildcard. Hence we need to
1036 * replace it with ".".
1039 dupsource
= dupstr(".");
1043 * Now we have separated our string into dupsource (the
1044 * directory part) and wildcard. Both of these will
1045 * need freeing at some point. Next step is to remove
1046 * wildcard escapes from the directory part, throwing
1047 * an error if it contains a real wildcard.
1049 dirpart
= smalloc(1+strlen(dupsource
));
1050 if (!wc_unescape(dirpart
, dupsource
)) {
1051 tell_user(stderr
, "%s: multiple-level wildcards unsupported",
1061 * Now we have dirpart (unescaped, ie a valid remote
1062 * path), and wildcard (a wildcard). This will be
1063 * sufficient to arrange a dirstack entry.
1065 scp_sftp_remotepath
= dirpart
;
1066 scp_sftp_wildcard
= wildcard
;
1069 scp_sftp_remotepath
= newsource
;
1070 scp_sftp_wildcard
= NULL
;
1072 scp_sftp_preserve
= preserve
;
1073 scp_sftp_recursive
= recursive
;
1074 scp_sftp_donethistarget
= 0;
1075 scp_sftp_dirstack_head
= NULL
;
1080 int scp_sink_init(void)
1088 #define SCP_SINK_FILE 1
1089 #define SCP_SINK_DIR 2
1090 #define SCP_SINK_ENDDIR 3
1091 #define SCP_SINK_RETRY 4 /* not an action; just try again */
1092 struct scp_sink_action
{
1093 int action
; /* FILE, DIR, ENDDIR */
1094 char *buf
; /* will need freeing after use */
1095 char *name
; /* filename or dirname (not ENDDIR) */
1096 int mode
; /* access mode (not ENDDIR) */
1097 unsigned long size
; /* file size (not ENDDIR) */
1098 int settime
; /* 1 if atime and mtime are filled */
1099 unsigned long atime
, mtime
; /* access times for the file */
1102 int scp_get_sink_action(struct scp_sink_action
*act
)
1106 int must_free_fname
;
1107 struct fxp_attrs attrs
;
1110 if (!scp_sftp_dirstack_head
) {
1111 if (!scp_sftp_donethistarget
) {
1113 * Simple case: we are only dealing with one file.
1115 fname
= scp_sftp_remotepath
;
1116 must_free_fname
= 0;
1117 scp_sftp_donethistarget
= 1;
1120 * Even simpler case: one file _which we've done_.
1121 * Return 1 (finished).
1127 * We're now in the middle of stepping through a list
1128 * of names returned from fxp_readdir(); so let's carry
1131 struct scp_sftp_dirstack
*head
= scp_sftp_dirstack_head
;
1132 while (head
->namepos
< head
->namelen
&&
1133 (is_dots(head
->names
[head
->namepos
].filename
) ||
1135 !wc_match(head
->wildcard
,
1136 head
->names
[head
->namepos
].filename
))))
1137 head
->namepos
++; /* skip . and .. */
1138 if (head
->namepos
< head
->namelen
) {
1139 head
->matched_something
= 1;
1140 fname
= dupcat(head
->dirpath
, "/",
1141 head
->names
[head
->namepos
++].filename
,
1143 must_free_fname
= 1;
1146 * We've come to the end of the list; pop it off
1147 * the stack and return an ENDDIR action (or RETRY
1148 * if this was a wildcard match).
1150 if (head
->wildcard
) {
1151 act
->action
= SCP_SINK_RETRY
;
1152 if (!head
->matched_something
) {
1153 tell_user(stderr
, "pscp: wildcard '%s' matched "
1154 "no files", head
->wildcard
);
1157 sfree(head
->wildcard
);
1160 act
->action
= SCP_SINK_ENDDIR
;
1163 sfree(head
->dirpath
);
1165 scp_sftp_dirstack_head
= head
->next
;
1173 * Now we have a filename. Stat it, and see if it's a file
1176 ret
= fxp_stat(fname
, &attrs
);
1177 if (!ret
|| !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
)) {
1178 tell_user(stderr
, "unable to identify %s: %s", fname
,
1179 ret ?
"file type not supplied" : fxp_error());
1184 if (attrs
.permissions
& 0040000) {
1185 struct scp_sftp_dirstack
*newitem
;
1186 struct fxp_handle
*dirhandle
;
1187 int nnames
, namesize
;
1188 struct fxp_name
*ournames
;
1189 struct fxp_names
*names
;
1192 * It's a directory. If we're not in recursive mode,
1193 * this merits a complaint (which is fatal if the name
1194 * was specified directly, but not if it was matched by
1197 * We skip this complaint completely if
1198 * scp_sftp_wildcard is set, because that's an
1199 * indication that we're not actually supposed to
1200 * _recursively_ transfer the dir, just scan it for
1201 * things matching the wildcard.
1203 if (!scp_sftp_recursive
&& !scp_sftp_wildcard
) {
1204 tell_user(stderr
, "pscp: %s: is a directory", fname
);
1206 if (must_free_fname
) sfree(fname
);
1207 if (scp_sftp_dirstack_head
) {
1208 act
->action
= SCP_SINK_RETRY
;
1216 * Otherwise, the fun begins. We must fxp_opendir() the
1217 * directory, slurp the filenames into memory, return
1218 * SCP_SINK_DIR (unless this is a wildcard match), and
1219 * set targetisdir. The next time we're called, we will
1220 * run through the list of filenames one by one,
1221 * matching them against a wildcard if present.
1223 * If targetisdir is _already_ set (meaning we're
1224 * already in the middle of going through another such
1225 * list), we must push the other (target,namelist) pair
1228 dirhandle
= fxp_opendir(fname
);
1230 tell_user(stderr
, "scp: unable to open directory %s: %s",
1231 fname
, fxp_error());
1232 if (must_free_fname
) sfree(fname
);
1236 nnames
= namesize
= 0;
1241 names
= fxp_readdir(dirhandle
);
1242 if (names
== NULL
) {
1243 if (fxp_error_type() == SSH_FX_EOF
)
1245 tell_user(stderr
, "scp: reading directory %s: %s\n",
1246 fname
, fxp_error());
1247 if (must_free_fname
) sfree(fname
);
1252 if (names
->nnames
== 0) {
1253 fxp_free_names(names
);
1256 if (nnames
+ names
->nnames
>= namesize
) {
1257 namesize
+= names
->nnames
+ 128;
1259 srealloc(ournames
, namesize
* sizeof(*ournames
));
1261 for (i
= 0; i
< names
->nnames
; i
++)
1262 ournames
[nnames
++] = names
->names
[i
];
1263 names
->nnames
= 0; /* prevent free_names */
1264 fxp_free_names(names
);
1266 fxp_close(dirhandle
);
1268 newitem
= smalloc(sizeof(struct scp_sftp_dirstack
));
1269 newitem
->next
= scp_sftp_dirstack_head
;
1270 newitem
->names
= ournames
;
1271 newitem
->namepos
= 0;
1272 newitem
->namelen
= nnames
;
1273 if (must_free_fname
)
1274 newitem
->dirpath
= fname
;
1276 newitem
->dirpath
= dupstr(fname
);
1277 if (scp_sftp_wildcard
) {
1278 newitem
->wildcard
= scp_sftp_wildcard
;
1279 newitem
->matched_something
= 0;
1280 scp_sftp_wildcard
= NULL
;
1282 newitem
->wildcard
= NULL
;
1284 scp_sftp_dirstack_head
= newitem
;
1286 if (newitem
->wildcard
) {
1287 act
->action
= SCP_SINK_RETRY
;
1289 act
->action
= SCP_SINK_DIR
;
1290 act
->buf
= dupstr(stripslashes(fname
, 0));
1291 act
->name
= act
->buf
;
1292 act
->size
= 0; /* duhh, it's a directory */
1293 act
->mode
= 07777 & attrs
.permissions
;
1294 if (scp_sftp_preserve
&&
1295 (attrs
.flags
& SSH_FILEXFER_ATTR_ACMODTIME
)) {
1296 act
->atime
= attrs
.atime
;
1297 act
->mtime
= attrs
.mtime
;
1306 * It's a file. Return SCP_SINK_FILE.
1308 act
->action
= SCP_SINK_FILE
;
1309 act
->buf
= dupstr(stripslashes(fname
, 0));
1310 act
->name
= act
->buf
;
1311 if (attrs
.flags
& SSH_FILEXFER_ATTR_SIZE
) {
1312 if (uint64_compare(attrs
.size
,
1313 uint64_make(0, ULONG_MAX
)) > 0) {
1314 act
->size
= ULONG_MAX
; /* *boggle* */
1316 act
->size
= attrs
.size
.lo
;
1318 act
->size
= ULONG_MAX
; /* no idea */
1319 act
->mode
= 07777 & attrs
.permissions
;
1320 if (scp_sftp_preserve
&&
1321 (attrs
.flags
& SSH_FILEXFER_ATTR_ACMODTIME
)) {
1322 act
->atime
= attrs
.atime
;
1323 act
->mtime
= attrs
.mtime
;
1327 if (must_free_fname
)
1328 scp_sftp_currentname
= fname
;
1330 scp_sftp_currentname
= dupstr(fname
);
1345 if (ssh_scp_recv(&ch
, 1) <= 0)
1348 bump("Protocol error: Unexpected newline");
1352 if (ssh_scp_recv(&ch
, 1) <= 0)
1353 bump("Lost connection");
1356 act
->buf
= srealloc(act
->buf
, bufsize
);
1359 } while (ch
!= '\n');
1360 act
->buf
[i
- 1] = '\0';
1362 case '\01': /* error */
1363 tell_user(stderr
, "%s\n", act
->buf
);
1365 continue; /* go round again */
1366 case '\02': /* fatal error */
1367 bump("%s", act
->buf
);
1370 act
->action
= SCP_SINK_ENDDIR
;
1373 if (sscanf(act
->buf
, "%ld %*d %ld %*d",
1374 &act
->mtime
, &act
->atime
) == 2) {
1377 continue; /* go round again */
1379 bump("Protocol error: Illegal time format");
1382 act
->action
= (action
== 'C' ? SCP_SINK_FILE
: SCP_SINK_DIR
);
1385 bump("Protocol error: Expected control record");
1388 * We will go round this loop only once, unless we hit
1395 * If we get here, we must have seen SCP_SINK_FILE or
1398 if (sscanf(act
->buf
, "%o %lu %n", &act
->mode
, &act
->size
, &i
) != 2)
1399 bump("Protocol error: Illegal file descriptor format");
1400 act
->name
= act
->buf
+ i
;
1405 int scp_accept_filexfer(void)
1408 scp_sftp_filehandle
=
1409 fxp_open(scp_sftp_currentname
, SSH_FXF_READ
);
1410 if (!scp_sftp_filehandle
) {
1411 tell_user(stderr
, "pscp: unable to open %s: %s",
1412 scp_sftp_currentname
, fxp_error());
1416 scp_sftp_fileoffset
= uint64_make(0, 0);
1417 sfree(scp_sftp_currentname
);
1421 return 0; /* can't fail */
1425 int scp_recv_filedata(char *data
, int len
)
1428 int actuallen
= fxp_read(scp_sftp_filehandle
, data
,
1429 scp_sftp_fileoffset
, len
);
1430 if (actuallen
== -1 && fxp_error_type() != SSH_FX_EOF
) {
1431 tell_user(stderr
, "pscp: error while reading: %s", fxp_error());
1438 scp_sftp_fileoffset
= uint64_add32(scp_sftp_fileoffset
, actuallen
);
1442 return ssh_scp_recv(data
, len
);
1446 int scp_finish_filerecv(void)
1449 fxp_close(scp_sftp_filehandle
);
1457 /* ----------------------------------------------------------------------
1458 * Send an error message to the other side and to the screen.
1459 * Increment error counter.
1461 static void run_err(const char *fmt
, ...)
1467 strcpy(str
, "scp: ");
1468 vsprintf(str
+ strlen(str
), fmt
, ap
);
1470 scp_send_errmsg(str
);
1471 tell_user(stderr
, "%s", str
);
1476 * Execute the source part of the SCP protocol.
1478 static void source(char *src
)
1485 unsigned long stat_bytes
;
1486 time_t stat_starttime
, stat_lasttime
;
1488 attr
= GetFileAttributes(src
);
1489 if (attr
== (DWORD
) - 1) {
1490 run_err("%s: No such file or directory", src
);
1494 if ((attr
& FILE_ATTRIBUTE_DIRECTORY
) != 0) {
1497 * Avoid . and .. directories.
1500 p
= strrchr(src
, '/');
1502 p
= strrchr(src
, '\\');
1507 if (!strcmp(p
, ".") || !strcmp(p
, ".."))
1508 /* skip . and .. */ ;
1512 run_err("%s: not a regular file", src
);
1517 if ((last
= strrchr(src
, '/')) == NULL
)
1521 if (strrchr(last
, '\\') != NULL
)
1522 last
= strrchr(last
, '\\') + 1;
1523 if (last
== src
&& strchr(src
, ':') != NULL
)
1524 last
= strchr(src
, ':') + 1;
1526 f
= CreateFile(src
, GENERIC_READ
, FILE_SHARE_READ
, NULL
,
1527 OPEN_EXISTING
, 0, 0);
1528 if (f
== INVALID_HANDLE_VALUE
) {
1529 run_err("%s: Cannot open file", src
);
1534 FILETIME actime
, wrtime
;
1535 unsigned long mtime
, atime
;
1536 GetFileTime(f
, NULL
, &actime
, &wrtime
);
1537 TIME_WIN_TO_POSIX(actime
, atime
);
1538 TIME_WIN_TO_POSIX(wrtime
, mtime
);
1539 if (scp_send_filetimes(mtime
, atime
))
1543 size
= GetFileSize(f
, NULL
);
1545 tell_user(stderr
, "Sending file %s, size=%lu", last
, size
);
1546 if (scp_send_filename(last
, size
, 0644))
1550 stat_starttime
= time(NULL
);
1553 for (i
= 0; i
< size
; i
+= 4096) {
1554 char transbuf
[4096];
1559 if (!ReadFile(f
, transbuf
, k
, &j
, NULL
) || j
!= k
) {
1562 bump("%s: Read error", src
);
1564 if (scp_send_filedata(transbuf
, k
))
1565 bump("%s: Network error occurred", src
);
1569 if (time(NULL
) != stat_lasttime
|| i
+ k
== size
) {
1570 stat_lasttime
= time(NULL
);
1571 print_stats(last
, size
, stat_bytes
,
1572 stat_starttime
, stat_lasttime
);
1579 (void) scp_send_finish();
1583 * Recursively send the contents of a directory.
1585 static void rsource(char *src
)
1587 char *last
, *findfile
;
1590 WIN32_FIND_DATA fdat
;
1593 if ((last
= strrchr(src
, '/')) == NULL
)
1597 if (strrchr(last
, '\\') != NULL
)
1598 last
= strrchr(last
, '\\') + 1;
1599 if (last
== src
&& strchr(src
, ':') != NULL
)
1600 last
= strchr(src
, ':') + 1;
1602 /* maybe send filetime */
1604 save_target
= scp_save_remotepath();
1607 tell_user(stderr
, "Entering directory: %s", last
);
1608 if (scp_send_dirname(last
, 0755))
1611 findfile
= dupcat(src
, "/*", NULL
);
1612 dir
= FindFirstFile(findfile
, &fdat
);
1613 ok
= (dir
!= INVALID_HANDLE_VALUE
);
1615 if (strcmp(fdat
.cFileName
, ".") == 0 ||
1616 strcmp(fdat
.cFileName
, "..") == 0) {
1617 /* ignore . and .. */
1619 char *foundfile
= dupcat(src
, "/", fdat
.cFileName
, NULL
);
1623 ok
= FindNextFile(dir
, &fdat
);
1628 (void) scp_send_enddir();
1630 scp_restore_remotepath(save_target
);
1634 * Execute the sink part of the SCP protocol.
1636 static void sink(char *targ
, char *src
)
1643 unsigned long received
;
1645 unsigned long stat_bytes
;
1646 time_t stat_starttime
, stat_lasttime
;
1649 attr
= GetFileAttributes(targ
);
1650 if (attr
!= (DWORD
) - 1 && (attr
& FILE_ATTRIBUTE_DIRECTORY
) != 0)
1653 if (targetshouldbedirectory
&& !targisdir
)
1654 bump("%s: Not a directory", targ
);
1658 struct scp_sink_action act
;
1659 if (scp_get_sink_action(&act
))
1662 if (act
.action
== SCP_SINK_ENDDIR
)
1665 if (act
.action
== SCP_SINK_RETRY
)
1670 * Prevent the remote side from maliciously writing to
1671 * files outside the target area by sending a filename
1672 * containing `../'. In fact, it shouldn't be sending
1673 * filenames with any slashes or colons in at all; so
1674 * we'll find the last slash, backslash or colon in the
1675 * filename and use only the part after that. (And
1678 * In addition, we also ensure here that if we're
1679 * copying a single file and the target is a directory
1680 * (common usage: `pscp host:filename .') the remote
1681 * can't send us a _different_ file name. We can
1682 * distinguish this case because `src' will be non-NULL
1683 * and the last component of that will fail to match
1684 * (the last component of) the name sent.
1686 * Well, not always; if `src' is a wildcard, we do
1687 * expect to get back filenames that don't correspond
1688 * exactly to it. Ideally in this case, we would like
1689 * to ensure that the returned filename actually
1690 * matches the wildcard pattern - but one of SCP's
1691 * protocol infelicities is that wildcard matching is
1692 * done at the server end _by the server's rules_ and
1693 * so in general this is infeasible. Hence, we only
1694 * accept filenames that don't correspond to `src' if
1695 * unsafe mode is enabled or we are using SFTP (which
1696 * resolves remote wildcards on the client side and can
1699 char *striptarget
, *stripsrc
;
1701 striptarget
= stripslashes(act
.name
, 1);
1702 if (striptarget
!= act
.name
) {
1703 tell_user(stderr
, "warning: remote host sent a compound"
1704 " pathname '%s'", act
.name
);
1705 tell_user(stderr
, " renaming local file to '%s'",
1710 * Also check to see if the target filename is '.' or
1711 * '..', or indeed '...' and so on because Windows
1712 * appears to interpret those like '..'.
1714 if (is_dots(striptarget
)) {
1715 bump("security violation: remote host attempted to write to"
1716 " a '.' or '..' path!");
1720 stripsrc
= stripslashes(src
, 1);
1721 if (strcmp(striptarget
, stripsrc
) &&
1722 !using_sftp
&& !scp_unsafe_mode
) {
1723 tell_user(stderr
, "warning: remote host tried to write "
1724 "to a file called '%s'", striptarget
);
1725 tell_user(stderr
, " when we requested a file "
1726 "called '%s'.", stripsrc
);
1727 tell_user(stderr
, " If this is a wildcard, "
1728 "consider upgrading to SSH 2 or using");
1729 tell_user(stderr
, " the '-unsafe' option. Renaming"
1730 " of this file has been disallowed.");
1731 /* Override the name the server provided with our own. */
1732 striptarget
= stripsrc
;
1736 if (targ
[0] != '\0')
1737 destfname
= dupcat(targ
, "\\", striptarget
, NULL
);
1739 destfname
= dupstr(striptarget
);
1742 * In this branch of the if, the target area is a
1743 * single file with an explicitly specified name in any
1744 * case, so there's no danger.
1746 destfname
= dupstr(targ
);
1748 attr
= GetFileAttributes(destfname
);
1749 exists
= (attr
!= (DWORD
) - 1);
1751 if (act
.action
== SCP_SINK_DIR
) {
1752 if (exists
&& (attr
& FILE_ATTRIBUTE_DIRECTORY
) == 0) {
1753 run_err("%s: Not a directory", destfname
);
1757 if (!CreateDirectory(destfname
, NULL
)) {
1758 run_err("%s: Cannot create directory", destfname
);
1762 sink(destfname
, NULL
);
1763 /* can we set the timestamp for directories ? */
1767 f
= CreateFile(destfname
, GENERIC_WRITE
, 0, NULL
,
1768 CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, 0);
1769 if (f
== INVALID_HANDLE_VALUE
) {
1770 run_err("%s: Cannot create file", destfname
);
1774 if (scp_accept_filexfer())
1778 stat_starttime
= time(NULL
);
1780 stat_name
= stripslashes(destfname
, 1);
1783 while (received
< act
.size
) {
1784 char transbuf
[4096];
1785 DWORD blksize
, read
, written
;
1787 if (blksize
> act
.size
- received
)
1788 blksize
= act
.size
- received
;
1789 read
= scp_recv_filedata(transbuf
, blksize
);
1791 bump("Lost connection");
1794 if (!WriteFile(f
, transbuf
, read
, &written
, NULL
) ||
1797 /* FIXME: in sftp we can actually abort the transfer */
1799 printf("\r%-25.25s | %50s\n",
1801 "Write error.. waiting for end of file");
1806 if (time(NULL
) > stat_lasttime
||
1807 received
+ read
== act
.size
) {
1808 stat_lasttime
= time(NULL
);
1809 print_stats(stat_name
, act
.size
, stat_bytes
,
1810 stat_starttime
, stat_lasttime
);
1816 FILETIME actime
, wrtime
;
1817 TIME_POSIX_TO_WIN(act
.atime
, actime
);
1818 TIME_POSIX_TO_WIN(act
.mtime
, wrtime
);
1819 SetFileTime(f
, NULL
, &actime
, &wrtime
);
1824 run_err("%s: Write error", destfname
);
1827 (void) scp_finish_filerecv();
1834 * We will copy local files to a remote server.
1836 static void toremote(int argc
, char *argv
[])
1838 char *src
, *targ
, *host
, *user
;
1842 targ
= argv
[argc
- 1];
1844 /* Separate host from filename */
1848 bump("targ == NULL in toremote()");
1852 /* Substitute "." for emtpy target */
1854 /* Separate host and username */
1856 host
= strrchr(host
, '@');
1867 /* Find out if the source filespec covers multiple files
1868 if so, we should set the targetshouldbedirectory flag */
1870 WIN32_FIND_DATA fdat
;
1871 if (colon(argv
[0]) != NULL
)
1872 bump("%s: Remote to remote not supported", argv
[0]);
1873 fh
= FindFirstFile(argv
[0], &fdat
);
1874 if (fh
== INVALID_HANDLE_VALUE
)
1875 bump("%s: No such file or directory\n", argv
[0]);
1876 if (FindNextFile(fh
, &fdat
))
1877 targetshouldbedirectory
= 1;
1881 cmd
= smalloc(strlen(targ
) + 100);
1882 sprintf(cmd
, "scp%s%s%s%s -t %s",
1883 verbose ?
" -v" : "",
1884 recursive ?
" -r" : "",
1885 preserve ?
" -p" : "",
1886 targetshouldbedirectory ?
" -d" : "", targ
);
1887 do_cmd(host
, user
, cmd
);
1890 scp_source_setup(targ
, targetshouldbedirectory
);
1892 for (i
= 0; i
< argc
- 1; i
++) {
1893 char *srcpath
, *last
;
1895 WIN32_FIND_DATA fdat
;
1897 if (colon(src
) != NULL
) {
1898 tell_user(stderr
, "%s: Remote to remote not supported\n", src
);
1904 * Trim off the last pathname component of `src', to
1905 * provide the base pathname which will be prepended to
1906 * filenames returned from Find{First,Next}File.
1908 srcpath
= dupstr(src
);
1909 last
= stripslashes(srcpath
, 1);
1912 dir
= FindFirstFile(src
, &fdat
);
1913 if (dir
== INVALID_HANDLE_VALUE
) {
1914 run_err("%s: No such file or directory", src
);
1920 * Ensure that . and .. are never matched by wildcards,
1921 * but only by deliberate action.
1923 if (!strcmp(fdat
.cFileName
, ".") ||
1924 !strcmp(fdat
.cFileName
, "..")) {
1926 * Find*File has returned a special dir. We require
1927 * that _either_ `src' ends in a backslash followed
1928 * by that string, _or_ `src' is precisely that
1931 int len
= strlen(src
), dlen
= strlen(fdat
.cFileName
);
1932 if (len
== dlen
&& !strcmp(src
, fdat
.cFileName
)) {
1934 } else if (len
> dlen
+ 1 && src
[len
- dlen
- 1] == '\\' &&
1935 !strcmp(src
+ len
- dlen
, fdat
.cFileName
)) {
1938 continue; /* ignore this one */
1940 filename
= dupcat(srcpath
, fdat
.cFileName
, NULL
);
1943 } while (FindNextFile(dir
, &fdat
));
1950 * We will copy files from a remote server to the local machine.
1952 static void tolocal(int argc
, char *argv
[])
1954 char *src
, *targ
, *host
, *user
;
1958 bump("More than one remote source not supported");
1963 /* Separate host from filename */
1967 bump("Local to local copy not supported");
1971 /* Substitute "." for empty filename */
1973 /* Separate username and hostname */
1975 host
= strrchr(host
, '@');
1985 cmd
= smalloc(strlen(src
) + 100);
1986 sprintf(cmd
, "scp%s%s%s%s -f %s",
1987 verbose ?
" -v" : "",
1988 recursive ?
" -r" : "",
1989 preserve ?
" -p" : "",
1990 targetshouldbedirectory ?
" -d" : "", src
);
1991 do_cmd(host
, user
, cmd
);
1994 if (scp_sink_setup(src
, preserve
, recursive
))
2001 * We will issue a list command to get a remote directory.
2003 static void get_dir_list(int argc
, char *argv
[])
2005 char *src
, *host
, *user
;
2011 /* Separate host from filename */
2015 bump("Local to local copy not supported");
2019 /* Substitute "." for empty filename */
2021 /* Separate username and hostname */
2023 host
= strrchr(host
, '@');
2033 cmd
= smalloc(4 * strlen(src
) + 100);
2034 strcpy(cmd
, "ls -la '");
2035 p
= cmd
+ strlen(cmd
);
2036 for (q
= src
; *q
; q
++) {
2049 do_cmd(host
, user
, cmd
);
2053 scp_sftp_listdir(src
);
2055 while (ssh_scp_recv(&c
, 1) > 0)
2056 tell_char(stdout
, c
);
2061 * Initialize the Win$ock driver.
2063 static void init_winsock(void)
2068 winsock_ver
= MAKEWORD(1, 1);
2069 if (WSAStartup(winsock_ver
, &wsadata
))
2070 bump("Unable to initialise WinSock");
2071 if (LOBYTE(wsadata
.wVersion
) != 1 || HIBYTE(wsadata
.wVersion
) != 1)
2072 bump("WinSock version is incompatible with 1.1");
2076 * Short description of parameters.
2078 static void usage(void)
2080 printf("PuTTY Secure Copy client\n");
2081 printf("%s\n", ver
);
2082 printf("Usage: pscp [options] [user@]host:source target\n");
2084 (" pscp [options] source [source...] [user@]host:target\n");
2085 printf(" pscp [options] -ls user@host:filespec\n");
2086 printf("Options:\n");
2087 printf(" -p preserve file attributes\n");
2088 printf(" -q quiet, don't show statistics\n");
2089 printf(" -r copy directories recursively\n");
2090 printf(" -v show verbose messages\n");
2091 printf(" -P port connect to specified port\n");
2092 printf(" -pw passw login with specified password\n");
2093 printf(" -unsafe allow server-side wildcards (DANGEROUS)\n");
2096 * -gui is an internal option, used by GUI front ends to get
2097 * pscp to pass progress reports back to them. It's not an
2098 * ordinary user-accessible option, so it shouldn't be part of
2099 * the command-line help. The only people who need to know
2100 * about it are programmers, and they can read the source.
2103 (" -gui hWnd GUI mode with the windows handle for receiving messages\n");
2108 void cmdline_error(char *p
, ...)
2111 fprintf(stderr
, "pscp: ");
2113 vfprintf(stderr
, p
, ap
);
2115 fputc('\n', stderr
);
2120 * Main program (no, really?)
2122 int main(int argc
, char *argv
[])
2126 default_protocol
= PROT_TELNET
;
2128 flags
= FLAG_STDERR
;
2129 cmdline_tooltype
= TOOLTYPE_FILETRANSFER
;
2130 ssh_get_line
= &console_get_line
;
2134 for (i
= 1; i
< argc
; i
++) {
2136 if (argv
[i
][0] != '-')
2138 ret
= cmdline_process_param(argv
[i
], i
+1<argc?argv
[i
+1]:NULL
, 1);
2140 cmdline_error("option \"%s\" requires an argument", argv
[i
]);
2141 } else if (ret
== 2) {
2142 i
++; /* skip next argument */
2143 } else if (ret
== 1) {
2144 /* We have our own verbosity in addition to `flags'. */
2145 if (flags
& FLAG_VERBOSE
)
2147 } else if (strcmp(argv
[i
], "-r") == 0) {
2149 } else if (strcmp(argv
[i
], "-p") == 0) {
2151 } else if (strcmp(argv
[i
], "-q") == 0) {
2153 } else if (strcmp(argv
[i
], "-h") == 0 || strcmp(argv
[i
], "-?") == 0) {
2155 } else if (strcmp(argv
[i
], "-gui") == 0 && i
+ 1 < argc
) {
2156 gui_hwnd
= argv
[++i
];
2158 console_batch_mode
= TRUE
;
2159 } else if (strcmp(argv
[i
], "-ls") == 0) {
2161 } else if (strcmp(argv
[i
], "-batch") == 0) {
2162 console_batch_mode
= 1;
2163 } else if (strcmp(argv
[i
], "-unsafe") == 0) {
2164 scp_unsafe_mode
= 1;
2165 } else if (strcmp(argv
[i
], "--") == 0) {
2178 get_dir_list(argc
, argv
);
2185 targetshouldbedirectory
= 1;
2187 if (colon(argv
[argc
- 1]) != NULL
)
2188 toremote(argc
, argv
);
2190 tolocal(argc
, argv
);
2193 if (back
!= NULL
&& back
->socket() != NULL
) {
2195 back
->special(TS_EOF
);
2196 ssh_scp_recv(&ch
, 1);
2201 /* GUI Adaptation - August 2000 */
2203 unsigned int msg_id
= WM_RET_ERR_CNT
;
2205 msg_id
= WM_LS_RET_ERR_CNT
;
2207 ((HWND
) atoi(gui_hwnd
), msg_id
, (WPARAM
) errs
,
2208 0 /*lParam */ ))SleepEx(1000, TRUE
);
2210 return (errs
== 0 ?
0 : 1);