2 * winsftp.c: the Windows-specific parts of PSFTP and PSCP.
13 char *get_ttymode(void *frontend, const char *mode) { return NULL; }
15 int get_userpass_input(prompts_t *p, const unsigned char *in, int inlen)
18 ret = cmdline_get_passwd_input(p, in, inlen);
20 ret = console_get_userpass_input(p, in, inlen);
24 void platform_get_x11_auth(struct X11Display *display, Conf *conf)
26 /* Do nothing, therefore no auth. */
28 const int platform_uses_x11_unix_by_default = TRUE;
30 /* ----------------------------------------------------------------------
31 * File access abstraction.
35 * Set local current directory. Returns NULL on success, or else an
36 * error message which must be freed after printing.
38 char *psftp_lcd(char *dir)
42 if (!SetCurrentDirectory(dir)) {
45 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
46 FORMAT_MESSAGE_FROM_SYSTEM |
47 FORMAT_MESSAGE_IGNORE_INSERTS,
49 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
50 (LPTSTR)&message, 0, NULL);
51 i = strcspn((char *)message, "\n");
52 ret = dupprintf("%.*s", i, (LPCTSTR)message);
60 * Get local current directory. Returns a string which must be
63 char *psftp_getcwd(void)
65 char *ret = snewn(256, char);
66 int len = GetCurrentDirectory(256, ret);
68 ret = sresize(ret, len, char);
69 GetCurrentDirectory(len, ret);
73 #define TIME_POSIX_TO_WIN(t, ft) do { \
75 uli.QuadPart = ((ULONGLONG)(t) + 11644473600ull) * 10000000ull; \
76 (ft).dwLowDateTime = uli.LowPart; \
77 (ft).dwHighDateTime = uli.HighPart; \
79 #define TIME_WIN_TO_POSIX(ft, t) do { \
81 uli.LowPart = (ft).dwLowDateTime; \
82 uli.HighPart = (ft).dwHighDateTime; \
83 uli.QuadPart = uli.QuadPart / 10000000ull - 11644473600ull; \
84 (t) = (unsigned long) uli.QuadPart; \
91 RFile *open_existing_file(const char *name, uint64 *size,
92 unsigned long *mtime, unsigned long *atime,
98 h = CreateFile(name, GENERIC_READ, FILE_SHARE_READ, NULL,
100 if (h == INVALID_HANDLE_VALUE)
108 lo = GetFileSize(h, &hi);
113 if (mtime || atime) {
114 FILETIME actime, wrtime;
115 GetFileTime(h, NULL, &actime, &wrtime);
117 TIME_WIN_TO_POSIX(actime, *atime);
119 TIME_WIN_TO_POSIX(wrtime, *mtime);
128 int read_from_file(RFile *f, void *buffer, int length)
132 ret = ReadFile(f->h, buffer, length, &read, NULL);
134 return -1; /* error */
139 void close_rfile(RFile *f)
149 WFile *open_new_file(const char *name, long perms)
154 h = CreateFile(name, GENERIC_WRITE, 0, NULL,
155 CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
156 if (h == INVALID_HANDLE_VALUE)
165 WFile *open_existing_wfile(const char *name, uint64 *size)
170 h = CreateFile(name, GENERIC_WRITE, FILE_SHARE_READ, NULL,
171 OPEN_EXISTING, 0, 0);
172 if (h == INVALID_HANDLE_VALUE)
180 lo = GetFileSize(h, &hi);
188 int write_to_file(WFile *f, void *buffer, int length)
192 ret = WriteFile(f->h, buffer, length, &written, NULL);
194 return -1; /* error */
199 void set_file_times(WFile *f, unsigned long mtime, unsigned long atime)
201 FILETIME actime, wrtime;
202 TIME_POSIX_TO_WIN(atime, actime);
203 TIME_POSIX_TO_WIN(mtime, wrtime);
204 SetFileTime(f->h, NULL, &actime, &wrtime);
207 void close_wfile(WFile *f)
213 /* Seek offset bytes through file, from whence, where whence is
214 FROM_START, FROM_CURRENT, or FROM_END */
215 int seek_file(WFile *f, uint64 offset, int whence)
221 movemethod = FILE_BEGIN;
224 movemethod = FILE_CURRENT;
227 movemethod = FILE_END;
234 LONG lo = offset.lo, hi = offset.hi;
235 SetFilePointer(f->h, lo, &hi, movemethod);
238 if (GetLastError() != NO_ERROR)
244 uint64 get_file_posn(WFile *f)
249 lo = SetFilePointer(f->h, 0L, &hi, FILE_CURRENT);
256 int file_type(const char *name)
259 attr = GetFileAttributes(name);
260 /* We know of no `weird' files under Windows. */
261 if (attr == (DWORD)-1)
262 return FILE_TYPE_NONEXISTENT;
263 else if (attr & FILE_ATTRIBUTE_DIRECTORY)
264 return FILE_TYPE_DIRECTORY;
266 return FILE_TYPE_FILE;
274 DirHandle *open_directory(const char *name)
277 WIN32_FIND_DATA fdat;
281 /* Enumerate files in dir `foo'. */
282 findfile = dupcat(name, "/*", NULL);
283 h = FindFirstFile(findfile, &fdat);
284 if (h == INVALID_HANDLE_VALUE)
288 ret = snew(DirHandle);
290 ret->name = dupstr(fdat.cFileName);
294 char *read_filename(DirHandle *dir)
299 WIN32_FIND_DATA fdat;
300 int ok = FindNextFile(dir->h, &fdat);
304 dir->name = dupstr(fdat.cFileName);
308 if (dir->name[0] == '.' &&
309 (dir->name[1] == '\0' ||
310 (dir->name[1] == '.' && dir->name[2] == '\0'))) {
315 } while (!dir->name);
318 char *ret = dir->name;
325 void close_directory(DirHandle *dir)
333 int test_wildcard(const char *name, int cmdline)
336 WIN32_FIND_DATA fdat;
338 /* First see if the exact name exists. */
339 if (GetFileAttributes(name) != (DWORD)-1)
340 return WCTYPE_FILENAME;
342 /* Otherwise see if a wildcard match finds anything. */
343 fh = FindFirstFile(name, &fdat);
344 if (fh == INVALID_HANDLE_VALUE)
345 return WCTYPE_NONEXISTENT;
348 return WCTYPE_WILDCARD;
351 struct WildcardMatcher {
357 char *stripslashes(const char *str, int local)
362 * On Windows, \ / : are all path component separators.
366 p = strchr(str, ':');
370 p = strrchr(str, '/');
374 p = strrchr(str, '\\');
381 WildcardMatcher *begin_wildcard_matching(const char *name)
384 WIN32_FIND_DATA fdat;
385 WildcardMatcher *ret;
388 h = FindFirstFile(name, &fdat);
389 if (h == INVALID_HANDLE_VALUE)
392 ret = snew(WildcardMatcher);
394 ret->srcpath = dupstr(name);
395 last = stripslashes(ret->srcpath, 1);
397 if (fdat.cFileName[0] == '.' &&
398 (fdat.cFileName[1] == '\0' ||
399 (fdat.cFileName[1] == '.' && fdat.cFileName[2] == '\0')))
402 ret->name = dupcat(ret->srcpath, fdat.cFileName, NULL);
407 char *wildcard_get_filename(WildcardMatcher *dir)
410 WIN32_FIND_DATA fdat;
411 int ok = FindNextFile(dir->h, &fdat);
416 if (fdat.cFileName[0] == '.' &&
417 (fdat.cFileName[1] == '\0' ||
418 (fdat.cFileName[1] == '.' && fdat.cFileName[2] == '\0')))
421 dir->name = dupcat(dir->srcpath, fdat.cFileName, NULL);
425 char *ret = dir->name;
432 void finish_wildcard_matching(WildcardMatcher *dir)
441 int vet_filename(const char *name)
443 if (strchr(name, '/') || strchr(name, '\\') || strchr(name, ':'))
446 if (!name[strspn(name, ".")]) /* entirely composed of dots */
452 int create_directory(const char *name)
454 return CreateDirectory(name, NULL) != 0;
457 char *dir_file_cat(const char *dir, const char *file)
459 return dupcat(dir, "\\", file, NULL);
462 /* ----------------------------------------------------------------------
463 * Platform-specific network handling.
467 * Be told what socket we're supposed to be using.
469 static SOCKET sftp_ssh_socket = INVALID_SOCKET;
470 static HANDLE netevent = INVALID_HANDLE_VALUE;
471 char *do_select(SOCKET skt, int startup)
475 sftp_ssh_socket = skt;
477 sftp_ssh_socket = INVALID_SOCKET;
479 if (p_WSAEventSelect) {
481 events = (FD_CONNECT | FD_READ | FD_WRITE |
482 FD_OOB | FD_CLOSE | FD_ACCEPT);
483 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
487 if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
488 switch (p_WSAGetLastError()) {
490 return "Network is down";
492 return "WSAEventSelect(): unknown error";
498 extern int select_result(WPARAM, LPARAM);
500 int do_eventsel_loop(HANDLE other_event)
502 int n, nhandles, nallhandles, netindex, otherindex;
503 unsigned long next, then;
508 unsigned long now = GETTICKCOUNT();
510 if (toplevel_callback_pending()) {
513 } else if (run_timers(now, &next)) {
515 now = GETTICKCOUNT();
516 if (now - then > next - then)
522 /* no need to initialise next here because we can never get
526 handles = handle_get_events(&nhandles);
527 handles = sresize(handles, nhandles+2, HANDLE);
528 nallhandles = nhandles;
530 if (netevent != INVALID_HANDLE_VALUE)
531 handles[netindex = nallhandles++] = netevent;
534 if (other_event != INVALID_HANDLE_VALUE)
535 handles[otherindex = nallhandles++] = other_event;
539 n = WaitForMultipleObjects(nallhandles, handles, FALSE, ticks);
541 if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
542 handle_got_event(handles[n - WAIT_OBJECT_0]);
543 } else if (netindex >= 0 && n == WAIT_OBJECT_0 + netindex) {
544 WSANETWORKEVENTS things;
546 extern SOCKET first_socket(int *), next_socket(int *);
547 extern int select_result(WPARAM, LPARAM);
551 * We must not call select_result() for any socket
552 * until we have finished enumerating within the
553 * tree. This is because select_result() may close
554 * the socket and modify the tree.
556 /* Count the active sockets. */
558 for (socket = first_socket(&socketstate);
559 socket != INVALID_SOCKET;
560 socket = next_socket(&socketstate)) i++;
562 /* Expand the buffer if necessary. */
563 sklist = snewn(i, SOCKET);
565 /* Retrieve the sockets into sklist. */
567 for (socket = first_socket(&socketstate);
568 socket != INVALID_SOCKET;
569 socket = next_socket(&socketstate)) {
570 sklist[skcount++] = socket;
573 /* Now we're done enumerating; go through the list. */
574 for (i = 0; i < skcount; i++) {
577 wp = (WPARAM) socket;
578 if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) {
579 static const struct { int bit, mask; } eventtypes[] = {
580 {FD_CONNECT_BIT, FD_CONNECT},
581 {FD_READ_BIT, FD_READ},
582 {FD_CLOSE_BIT, FD_CLOSE},
583 {FD_OOB_BIT, FD_OOB},
584 {FD_WRITE_BIT, FD_WRITE},
585 {FD_ACCEPT_BIT, FD_ACCEPT},
589 noise_ultralight(socket);
590 noise_ultralight(things.lNetworkEvents);
592 for (e = 0; e < lenof(eventtypes); e++)
593 if (things.lNetworkEvents & eventtypes[e].mask) {
595 int err = things.iErrorCode[eventtypes[e].bit];
596 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
597 select_result(wp, lp);
607 run_toplevel_callbacks();
609 if (n == WAIT_TIMEOUT) {
612 now = GETTICKCOUNT();
615 if (otherindex >= 0 && n == WAIT_OBJECT_0 + otherindex)
622 * Wait for some network data and process it.
624 * We have two variants of this function. One uses select() so that
625 * it's compatible with WinSock 1. The other uses WSAEventSelect
626 * and MsgWaitForMultipleObjects, so that we can consistently use
627 * WSAEventSelect throughout; this enables us to also implement
628 * ssh_sftp_get_cmdline() using a parallel mechanism.
630 int ssh_sftp_loop_iteration(void)
632 if (p_WSAEventSelect == NULL) {
635 unsigned long now = GETTICKCOUNT(), then;
637 if (sftp_ssh_socket == INVALID_SOCKET)
638 return -1; /* doom */
640 if (socket_writable(sftp_ssh_socket))
641 select_result((WPARAM) sftp_ssh_socket, (LPARAM) FD_WRITE);
646 struct timeval tv, *ptv;
648 if (run_timers(now, &next)) {
650 now = GETTICKCOUNT();
651 if (now - then > next - then)
655 tv.tv_sec = ticks / 1000;
656 tv.tv_usec = ticks % 1000 * 1000;
663 FD_SET(sftp_ssh_socket, &readfds);
664 ret = p_select(1, &readfds, NULL, NULL, ptv);
667 return -1; /* doom */
671 now = GETTICKCOUNT();
675 select_result((WPARAM) sftp_ssh_socket, (LPARAM) FD_READ);
679 return do_eventsel_loop(INVALID_HANDLE_VALUE);
684 * Read a command line from standard input.
686 * In the presence of WinSock 2, we can use WSAEventSelect to
687 * mediate between the socket and stdin, meaning we can send
688 * keepalives and respond to server events even while waiting at
689 * the PSFTP command prompt. Without WS2, we fall back to a simple
692 struct command_read_ctx {
697 static DWORD WINAPI command_read_thread(void *param)
699 struct command_read_ctx *ctx = (struct command_read_ctx *) param;
701 ctx->line = fgetline(stdin);
703 SetEvent(ctx->event);
708 char *ssh_sftp_get_cmdline(const char *prompt, int no_fds_ok)
711 struct command_read_ctx actx, *ctx = &actx;
715 fputs(prompt, stdout);
718 if ((sftp_ssh_socket == INVALID_SOCKET && no_fds_ok) ||
719 p_WSAEventSelect == NULL) {
720 return fgetline(stdin); /* very simple */
724 * Create a second thread to read from stdin. Process network
725 * and timing events until it terminates.
727 ctx->event = CreateEvent(NULL, FALSE, FALSE, NULL);
730 hThread = CreateThread(NULL, 0, command_read_thread, ctx, 0, &threadid);
732 CloseHandle(ctx->event);
733 fprintf(stderr, "Unable to create command input thread\n");
738 ret = do_eventsel_loop(ctx->event);
740 /* Error return can only occur if netevent==NULL, and it ain't. */
744 CloseHandle(hThread);
745 CloseHandle(ctx->event);
750 void platform_psftp_post_option_setup(void)
754 /* ----------------------------------------------------------------------
755 * Main program. Parse arguments etc.
757 int main(int argc, char *argv[])
761 dll_hijacking_protection();
763 ret = psftp_main(argc, argv);