2 * winsftp.c: the Windows-specific parts of PSFTP and PSCP.
10 /* ----------------------------------------------------------------------
11 * Interface to GUI driver program.
14 /* This is just a base value from which the main message numbers are
16 #define WM_APP_BASE 0x8000
18 /* These two pass a single character value in wParam. They represent
19 * the visible output from PSCP. */
20 #define WM_STD_OUT_CHAR ( WM_APP_BASE+400 )
21 #define WM_STD_ERR_CHAR ( WM_APP_BASE+401 )
23 /* These pass a transfer status update. WM_STATS_CHAR passes a single
24 * character in wParam, and is called repeatedly to pass the name of
25 * the file, terminated with "\n". WM_STATS_SIZE passes the size of
26 * the file being transferred in wParam. WM_STATS_ELAPSED is called
27 * to pass the elapsed time (in seconds) in wParam, and
28 * WM_STATS_PERCENT passes the percentage of the transfer which is
29 * complete, also in wParam. */
30 #define WM_STATS_CHAR ( WM_APP_BASE+402 )
31 #define WM_STATS_SIZE ( WM_APP_BASE+403 )
32 #define WM_STATS_PERCENT ( WM_APP_BASE+404 )
33 #define WM_STATS_ELAPSED ( WM_APP_BASE+405 )
35 /* These are used at the end of a run to pass an error code in
36 * wParam: zero means success, nonzero means failure. WM_RET_ERR_CNT
37 * is used after a copy, and WM_LS_RET_ERR_CNT is used after a file
39 #define WM_RET_ERR_CNT ( WM_APP_BASE+406 )
40 #define WM_LS_RET_ERR_CNT ( WM_APP_BASE+407 )
42 /* More transfer status update messages. WM_STATS_DONE passes the
43 * number of bytes sent so far in wParam. WM_STATS_ETA passes the
44 * estimated time to completion (in seconds). WM_STATS_RATEBS passes
45 * the average transfer rate (in bytes per second). */
46 #define WM_STATS_DONE ( WM_APP_BASE+408 )
47 #define WM_STATS_ETA ( WM_APP_BASE+409 )
48 #define WM_STATS_RATEBS ( WM_APP_BASE+410 )
50 #define NAME_STR_MAX 2048
51 static char statname
[NAME_STR_MAX
+ 1];
52 static unsigned long statsize
= 0;
53 static unsigned long statdone
= 0;
54 static unsigned long stateta
= 0;
55 static unsigned long statratebs
= 0;
56 static int statperct
= 0;
57 static unsigned long statelapsed
= 0;
59 static HWND gui_hwnd
= NULL
;
61 static void send_msg(HWND h
, UINT message
, WPARAM wParam
)
63 while (!PostMessage(h
, message
, wParam
, 0))
67 void gui_send_char(int is_stderr
, int c
)
69 unsigned int msg_id
= WM_STD_OUT_CHAR
;
71 msg_id
= WM_STD_ERR_CHAR
;
72 send_msg(gui_hwnd
, msg_id
, (WPARAM
) c
);
75 void gui_send_errcount(int list
, int errs
)
77 unsigned int msg_id
= WM_RET_ERR_CNT
;
79 msg_id
= WM_LS_RET_ERR_CNT
;
80 while (!PostMessage(gui_hwnd
, msg_id
, (WPARAM
) errs
, 0))
84 void gui_update_stats(char *name
, unsigned long size
,
85 int percentage
, unsigned long elapsed
,
86 unsigned long done
, unsigned long eta
,
91 if (strcmp(name
, statname
) != 0) {
92 for (i
= 0; i
< strlen(name
); ++i
)
93 send_msg(gui_hwnd
, WM_STATS_CHAR
, (WPARAM
) name
[i
]);
94 send_msg(gui_hwnd
, WM_STATS_CHAR
, (WPARAM
) '\n');
95 strcpy(statname
, name
);
97 if (statsize
!= size
) {
98 send_msg(gui_hwnd
, WM_STATS_SIZE
, (WPARAM
) size
);
101 if (statdone
!= done
) {
102 send_msg(gui_hwnd
, WM_STATS_DONE
, (WPARAM
) done
);
105 if (stateta
!= eta
) {
106 send_msg(gui_hwnd
, WM_STATS_ETA
, (WPARAM
) eta
);
109 if (statratebs
!= ratebs
) {
110 send_msg(gui_hwnd
, WM_STATS_RATEBS
, (WPARAM
) ratebs
);
113 if (statelapsed
!= elapsed
) {
114 send_msg(gui_hwnd
, WM_STATS_ELAPSED
, (WPARAM
) elapsed
);
115 statelapsed
= elapsed
;
117 if (statperct
!= percentage
) {
118 send_msg(gui_hwnd
, WM_STATS_PERCENT
, (WPARAM
) percentage
);
119 statperct
= percentage
;
123 void gui_enable(char *arg
)
125 gui_hwnd
= (HWND
) atoi(arg
);
128 /* ----------------------------------------------------------------------
129 * File access abstraction.
133 * Set local current directory. Returns NULL on success, or else an
134 * error message which must be freed after printing.
136 char *psftp_lcd(char *dir
)
140 if (!SetCurrentDirectory(dir
)) {
143 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
144 FORMAT_MESSAGE_FROM_SYSTEM
|
145 FORMAT_MESSAGE_IGNORE_INSERTS
,
146 NULL
, GetLastError(),
147 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
148 (LPTSTR
)&message
, 0, NULL
);
149 i
= strcspn((char *)message
, "\n");
150 ret
= dupprintf("%.*s", i
, (LPCTSTR
)message
);
158 * Get local current directory. Returns a string which must be
161 char *psftp_getcwd(void)
163 char *ret
= snewn(256, char);
164 int len
= GetCurrentDirectory(256, ret
);
166 ret
= sresize(ret
, len
, char);
167 GetCurrentDirectory(len
, ret
);
171 #define TIME_POSIX_TO_WIN(t, ft) (*(LONGLONG*)&(ft) = \
172 ((LONGLONG) (t) + (LONGLONG) 11644473600) * (LONGLONG) 10000000)
173 #define TIME_WIN_TO_POSIX(ft, t) ((t) = (unsigned long) \
174 ((*(LONGLONG*)&(ft)) / (LONGLONG) 10000000 - (LONGLONG) 11644473600))
180 RFile
*open_existing_file(char *name
, unsigned long *size
,
181 unsigned long *mtime
, unsigned long *atime
)
186 h
= CreateFile(name
, GENERIC_READ
, FILE_SHARE_READ
, NULL
,
187 OPEN_EXISTING
, 0, 0);
188 if (h
== INVALID_HANDLE_VALUE
)
195 *size
= GetFileSize(h
, NULL
);
197 if (mtime
|| atime
) {
198 FILETIME actime
, wrtime
;
199 GetFileTime(h
, NULL
, &actime
, &wrtime
);
201 TIME_WIN_TO_POSIX(actime
, *atime
);
203 TIME_WIN_TO_POSIX(wrtime
, *mtime
);
209 int read_from_file(RFile
*f
, void *buffer
, int length
)
212 ret
= ReadFile(f
->h
, buffer
, length
, &read
, NULL
);
214 return -1; /* error */
219 void close_rfile(RFile
*f
)
229 WFile
*open_new_file(char *name
)
234 h
= CreateFile(name
, GENERIC_WRITE
, 0, NULL
,
235 CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, 0);
236 if (h
== INVALID_HANDLE_VALUE
)
245 int write_to_file(WFile
*f
, void *buffer
, int length
)
248 ret
= WriteFile(f
->h
, buffer
, length
, &written
, NULL
);
250 return -1; /* error */
255 void set_file_times(WFile
*f
, unsigned long mtime
, unsigned long atime
)
257 FILETIME actime
, wrtime
;
258 TIME_POSIX_TO_WIN(atime
, actime
);
259 TIME_POSIX_TO_WIN(mtime
, wrtime
);
260 SetFileTime(f
->h
, NULL
, &actime
, &wrtime
);
263 void close_wfile(WFile
*f
)
269 int file_type(char *name
)
272 attr
= GetFileAttributes(name
);
273 /* We know of no `weird' files under Windows. */
274 if (attr
== (DWORD
)-1)
275 return FILE_TYPE_NONEXISTENT
;
276 else if (attr
& FILE_ATTRIBUTE_DIRECTORY
)
277 return FILE_TYPE_DIRECTORY
;
279 return FILE_TYPE_FILE
;
287 DirHandle
*open_directory(char *name
)
290 WIN32_FIND_DATA fdat
;
294 /* Enumerate files in dir `foo'. */
295 findfile
= dupcat(name
, "/*", NULL
);
296 h
= FindFirstFile(findfile
, &fdat
);
297 if (h
== INVALID_HANDLE_VALUE
)
301 ret
= snew(DirHandle
);
303 ret
->name
= dupstr(fdat
.cFileName
);
307 char *read_filename(DirHandle
*dir
)
310 WIN32_FIND_DATA fdat
;
311 int ok
= FindNextFile(dir
->h
, &fdat
);
316 if (fdat
.cFileName
[0] == '.' &&
317 (fdat
.cFileName
[1] == '\0' ||
318 (fdat
.cFileName
[1] == '.' && fdat
.cFileName
[2] == '\0')))
321 dir
->name
= dupstr(fdat
.cFileName
);
325 char *ret
= dir
->name
;
332 void close_directory(DirHandle
*dir
)
340 int test_wildcard(char *name
, int cmdline
)
343 WIN32_FIND_DATA fdat
;
345 /* First see if the exact name exists. */
346 if (GetFileAttributes(name
) != (DWORD
)-1)
347 return WCTYPE_FILENAME
;
349 /* Otherwise see if a wildcard match finds anything. */
350 fh
= FindFirstFile(name
, &fdat
);
351 if (fh
== INVALID_HANDLE_VALUE
)
352 return WCTYPE_NONEXISTENT
;
355 return WCTYPE_WILDCARD
;
358 struct WildcardMatcher
{
365 * Return a pointer to the portion of str that comes after the last
366 * slash (or backslash or colon, if `local' is TRUE).
368 static char *stripslashes(char *str
, int local
)
373 p
= strchr(str
, ':');
377 p
= strrchr(str
, '/');
381 p
= strrchr(str
, '\\');
388 WildcardMatcher
*begin_wildcard_matching(char *name
)
391 WIN32_FIND_DATA fdat
;
392 WildcardMatcher
*ret
;
395 h
= FindFirstFile(name
, &fdat
);
396 if (h
== INVALID_HANDLE_VALUE
)
399 ret
= snew(WildcardMatcher
);
401 ret
->srcpath
= dupstr(name
);
402 last
= stripslashes(ret
->srcpath
, 1);
404 if (fdat
.cFileName
[0] == '.' &&
405 (fdat
.cFileName
[1] == '\0' ||
406 (fdat
.cFileName
[1] == '.' && fdat
.cFileName
[2] == '\0')))
409 ret
->name
= dupcat(ret
->srcpath
, fdat
.cFileName
, NULL
);
414 char *wildcard_get_filename(WildcardMatcher
*dir
)
417 WIN32_FIND_DATA fdat
;
418 int ok
= FindNextFile(dir
->h
, &fdat
);
423 if (fdat
.cFileName
[0] == '.' &&
424 (fdat
.cFileName
[1] == '\0' ||
425 (fdat
.cFileName
[1] == '.' && fdat
.cFileName
[2] == '\0')))
428 dir
->name
= dupcat(dir
->srcpath
, fdat
.cFileName
, NULL
);
432 char *ret
= dir
->name
;
439 void finish_wildcard_matching(WildcardMatcher
*dir
)
448 int create_directory(char *name
)
450 return CreateDirectory(name
, NULL
) != 0;
453 char *dir_file_cat(char *dir
, char *file
)
455 return dupcat(dir
, "\\", file
, NULL
);
458 /* ----------------------------------------------------------------------
459 * Platform-specific network handling.
463 * Be told what socket we're supposed to be using.
465 static SOCKET sftp_ssh_socket
;
466 static HANDLE netevent
= NULL
;
467 char *do_select(SOCKET skt
, int startup
)
471 sftp_ssh_socket
= skt
;
473 sftp_ssh_socket
= INVALID_SOCKET
;
475 if (p_WSAEventSelect
) {
477 events
= (FD_CONNECT
| FD_READ
| FD_WRITE
|
478 FD_OOB
| FD_CLOSE
| FD_ACCEPT
);
479 netevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
483 if (p_WSAEventSelect(skt
, netevent
, events
) == SOCKET_ERROR
) {
484 switch (p_WSAGetLastError()) {
486 return "Network is down";
488 return "WSAEventSelect(): unknown error";
494 extern int select_result(WPARAM
, LPARAM
);
496 int do_eventsel_loop(HANDLE other_event
)
503 long now
= GETTICKCOUNT();
506 return -1; /* doom */
509 handles
[0] = netevent
;
510 handles
[1] = other_event
;
512 if (run_timers(now
, &next
)) {
513 ticks
= next
- GETTICKCOUNT();
514 if (ticks
< 0) ticks
= 0; /* just in case */
519 n
= MsgWaitForMultipleObjects(other_event ?
2 : 1, handles
, FALSE
, ticks
,
522 if (n
== WAIT_OBJECT_0
+ 0) {
523 WSANETWORKEVENTS things
;
525 extern SOCKET
first_socket(int *), next_socket(int *);
526 extern int select_result(WPARAM
, LPARAM
);
530 * We must not call select_result() for any socket
531 * until we have finished enumerating within the
532 * tree. This is because select_result() may close
533 * the socket and modify the tree.
535 /* Count the active sockets. */
537 for (socket
= first_socket(&socketstate
);
538 socket
!= INVALID_SOCKET
;
539 socket
= next_socket(&socketstate
)) i
++;
541 /* Expand the buffer if necessary. */
542 sklist
= snewn(i
, SOCKET
);
544 /* Retrieve the sockets into sklist. */
546 for (socket
= first_socket(&socketstate
);
547 socket
!= INVALID_SOCKET
;
548 socket
= next_socket(&socketstate
)) {
549 sklist
[skcount
++] = socket
;
552 /* Now we're done enumerating; go through the list. */
553 for (i
= 0; i
< skcount
; i
++) {
556 wp
= (WPARAM
) socket
;
557 if (!p_WSAEnumNetworkEvents(socket
, NULL
, &things
)) {
558 static const struct { int bit
, mask
; } eventtypes
[] = {
559 {FD_CONNECT_BIT
, FD_CONNECT
},
560 {FD_READ_BIT
, FD_READ
},
561 {FD_CLOSE_BIT
, FD_CLOSE
},
562 {FD_OOB_BIT
, FD_OOB
},
563 {FD_WRITE_BIT
, FD_WRITE
},
564 {FD_ACCEPT_BIT
, FD_ACCEPT
},
568 noise_ultralight(socket
);
569 noise_ultralight(things
.lNetworkEvents
);
571 for (e
= 0; e
< lenof(eventtypes
); e
++)
572 if (things
.lNetworkEvents
& eventtypes
[e
].mask
) {
574 int err
= things
.iErrorCode
[eventtypes
[e
].bit
];
575 lp
= WSAMAKESELECTREPLY(eventtypes
[e
].mask
, err
);
576 select_result(wp
, lp
);
584 if (n
== WAIT_TIMEOUT
) {
587 now
= GETTICKCOUNT();
590 if (other_event
&& n
== WAIT_OBJECT_0
+ 1)
597 * Wait for some network data and process it.
599 * We have two variants of this function. One uses select() so that
600 * it's compatible with WinSock 1. The other uses WSAEventSelect
601 * and MsgWaitForMultipleObjects, so that we can consistently use
602 * WSAEventSelect throughout; this enables us to also implement
603 * ssh_sftp_get_cmdline() using a parallel mechanism.
605 int ssh_sftp_loop_iteration(void)
607 if (sftp_ssh_socket
== INVALID_SOCKET
)
608 return -1; /* doom */
610 if (p_WSAEventSelect
== NULL
) {
613 long now
= GETTICKCOUNT();
615 if (socket_writable(sftp_ssh_socket
))
616 select_result((WPARAM
) sftp_ssh_socket
, (LPARAM
) FD_WRITE
);
620 struct timeval tv
, *ptv
;
622 if (run_timers(now
, &next
)) {
623 ticks
= next
- GETTICKCOUNT();
625 ticks
= 1; /* just in case */
626 tv
.tv_sec
= ticks
/ 1000;
627 tv
.tv_usec
= ticks
% 1000 * 1000;
634 FD_SET(sftp_ssh_socket
, &readfds
);
635 ret
= p_select(1, &readfds
, NULL
, NULL
, ptv
);
638 return -1; /* doom */
642 now
= GETTICKCOUNT();
646 select_result((WPARAM
) sftp_ssh_socket
, (LPARAM
) FD_READ
);
650 return do_eventsel_loop(NULL
);
655 * Read a command line from standard input.
657 * In the presence of WinSock 2, we can use WSAEventSelect to
658 * mediate between the socket and stdin, meaning we can send
659 * keepalives and respond to server events even while waiting at
660 * the PSFTP command prompt. Without WS2, we fall back to a simple
663 struct command_read_ctx
{
668 static DWORD WINAPI
command_read_thread(void *param
)
670 struct command_read_ctx
*ctx
= (struct command_read_ctx
*) param
;
672 ctx
->line
= fgetline(stdin
);
674 SetEvent(ctx
->event
);
679 char *ssh_sftp_get_cmdline(char *prompt
)
682 struct command_read_ctx actx
, *ctx
= &actx
;
685 fputs(prompt
, stdout
);
688 if (sftp_ssh_socket
== INVALID_SOCKET
|| p_WSAEventSelect
== NULL
) {
689 return fgetline(stdin
); /* very simple */
693 * Create a second thread to read from stdin. Process network
694 * and timing events until it terminates.
696 ctx
->event
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
699 if (!CreateThread(NULL
, 0, command_read_thread
,
700 ctx
, 0, &threadid
)) {
701 fprintf(stderr
, "Unable to create command input thread\n");
706 ret
= do_eventsel_loop(ctx
->event
);
708 /* Error return can only occur if netevent==NULL, and it ain't. */
715 /* ----------------------------------------------------------------------
716 * Main program. Parse arguments etc.
718 int main(int argc
, char *argv
[])
722 ret
= psftp_main(argc
, argv
);