2 * winsftp.c: the Windows-specific parts of PSFTP and PSCP.
5 #include <winsock2.h> /* need to put this first, for winelib builds */
8 #define NEED_DECLARATION_OF_SELECT
16 char *get_ttymode(void *frontend, const char *mode) { return NULL; }
18 int get_userpass_input(prompts_t *p, const unsigned char *in, int inlen)
21 ret = cmdline_get_passwd_input(p, in, inlen);
23 ret = console_get_userpass_input(p, in, inlen);
27 void platform_get_x11_auth(struct X11Display *display, Conf *conf)
29 /* Do nothing, therefore no auth. */
31 const int platform_uses_x11_unix_by_default = TRUE;
33 /* ----------------------------------------------------------------------
34 * File access abstraction.
38 * Set local current directory. Returns NULL on success, or else an
39 * error message which must be freed after printing.
41 char *psftp_lcd(char *dir)
45 if (!SetCurrentDirectory(dir)) {
48 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
49 FORMAT_MESSAGE_FROM_SYSTEM |
50 FORMAT_MESSAGE_IGNORE_INSERTS,
52 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
53 (LPTSTR)&message, 0, NULL);
54 i = strcspn((char *)message, "\n");
55 ret = dupprintf("%.*s", i, (LPCTSTR)message);
63 * Get local current directory. Returns a string which must be
66 char *psftp_getcwd(void)
68 char *ret = snewn(256, char);
69 int len = GetCurrentDirectory(256, ret);
71 ret = sresize(ret, len, char);
72 GetCurrentDirectory(len, ret);
76 #define TIME_POSIX_TO_WIN(t, ft) do { \
78 uli.QuadPart = ((ULONGLONG)(t) + 11644473600ull) * 10000000ull; \
79 (ft).dwLowDateTime = uli.LowPart; \
80 (ft).dwHighDateTime = uli.HighPart; \
82 #define TIME_WIN_TO_POSIX(ft, t) do { \
84 uli.LowPart = (ft).dwLowDateTime; \
85 uli.HighPart = (ft).dwHighDateTime; \
86 uli.QuadPart = uli.QuadPart / 10000000ull - 11644473600ull; \
87 (t) = (unsigned long) uli.QuadPart; \
94 RFile *open_existing_file(const char *name, uint64 *size,
95 unsigned long *mtime, unsigned long *atime,
101 h = CreateFile(name, GENERIC_READ, FILE_SHARE_READ, NULL,
102 OPEN_EXISTING, 0, 0);
103 if (h == INVALID_HANDLE_VALUE)
111 lo = GetFileSize(h, &hi);
116 if (mtime || atime) {
117 FILETIME actime, wrtime;
118 GetFileTime(h, NULL, &actime, &wrtime);
120 TIME_WIN_TO_POSIX(actime, *atime);
122 TIME_WIN_TO_POSIX(wrtime, *mtime);
131 int read_from_file(RFile *f, void *buffer, int length)
135 ret = ReadFile(f->h, buffer, length, &read, NULL);
137 return -1; /* error */
142 void close_rfile(RFile *f)
152 WFile *open_new_file(const char *name, long perms)
157 h = CreateFile(name, GENERIC_WRITE, 0, NULL,
158 CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
159 if (h == INVALID_HANDLE_VALUE)
168 WFile *open_existing_wfile(const char *name, uint64 *size)
173 h = CreateFile(name, GENERIC_WRITE, FILE_SHARE_READ, NULL,
174 OPEN_EXISTING, 0, 0);
175 if (h == INVALID_HANDLE_VALUE)
183 lo = GetFileSize(h, &hi);
191 int write_to_file(WFile *f, void *buffer, int length)
195 ret = WriteFile(f->h, buffer, length, &written, NULL);
197 return -1; /* error */
202 void set_file_times(WFile *f, unsigned long mtime, unsigned long atime)
204 FILETIME actime, wrtime;
205 TIME_POSIX_TO_WIN(atime, actime);
206 TIME_POSIX_TO_WIN(mtime, wrtime);
207 SetFileTime(f->h, NULL, &actime, &wrtime);
210 void close_wfile(WFile *f)
216 /* Seek offset bytes through file, from whence, where whence is
217 FROM_START, FROM_CURRENT, or FROM_END */
218 int seek_file(WFile *f, uint64 offset, int whence)
224 movemethod = FILE_BEGIN;
227 movemethod = FILE_CURRENT;
230 movemethod = FILE_END;
237 LONG lo = offset.lo, hi = offset.hi;
238 SetFilePointer(f->h, lo, &hi, movemethod);
241 if (GetLastError() != NO_ERROR)
247 uint64 get_file_posn(WFile *f)
252 lo = SetFilePointer(f->h, 0L, &hi, FILE_CURRENT);
259 int file_type(const char *name)
262 attr = GetFileAttributes(name);
263 /* We know of no `weird' files under Windows. */
264 if (attr == (DWORD)-1)
265 return FILE_TYPE_NONEXISTENT;
266 else if (attr & FILE_ATTRIBUTE_DIRECTORY)
267 return FILE_TYPE_DIRECTORY;
269 return FILE_TYPE_FILE;
277 DirHandle *open_directory(const char *name)
280 WIN32_FIND_DATA fdat;
284 /* Enumerate files in dir `foo'. */
285 findfile = dupcat(name, "/*", NULL);
286 h = FindFirstFile(findfile, &fdat);
287 if (h == INVALID_HANDLE_VALUE)
291 ret = snew(DirHandle);
293 ret->name = dupstr(fdat.cFileName);
297 char *read_filename(DirHandle *dir)
302 WIN32_FIND_DATA fdat;
303 int ok = FindNextFile(dir->h, &fdat);
307 dir->name = dupstr(fdat.cFileName);
311 if (dir->name[0] == '.' &&
312 (dir->name[1] == '\0' ||
313 (dir->name[1] == '.' && dir->name[2] == '\0'))) {
318 } while (!dir->name);
321 char *ret = dir->name;
328 void close_directory(DirHandle *dir)
336 int test_wildcard(const char *name, int cmdline)
339 WIN32_FIND_DATA fdat;
341 /* First see if the exact name exists. */
342 if (GetFileAttributes(name) != (DWORD)-1)
343 return WCTYPE_FILENAME;
345 /* Otherwise see if a wildcard match finds anything. */
346 fh = FindFirstFile(name, &fdat);
347 if (fh == INVALID_HANDLE_VALUE)
348 return WCTYPE_NONEXISTENT;
351 return WCTYPE_WILDCARD;
354 struct WildcardMatcher {
360 char *stripslashes(const char *str, int local)
365 * On Windows, \ / : are all path component separators.
369 p = strchr(str, ':');
373 p = strrchr(str, '/');
377 p = strrchr(str, '\\');
384 WildcardMatcher *begin_wildcard_matching(const char *name)
387 WIN32_FIND_DATA fdat;
388 WildcardMatcher *ret;
391 h = FindFirstFile(name, &fdat);
392 if (h == INVALID_HANDLE_VALUE)
395 ret = snew(WildcardMatcher);
397 ret->srcpath = dupstr(name);
398 last = stripslashes(ret->srcpath, 1);
400 if (fdat.cFileName[0] == '.' &&
401 (fdat.cFileName[1] == '\0' ||
402 (fdat.cFileName[1] == '.' && fdat.cFileName[2] == '\0')))
405 ret->name = dupcat(ret->srcpath, fdat.cFileName, NULL);
410 char *wildcard_get_filename(WildcardMatcher *dir)
413 WIN32_FIND_DATA fdat;
414 int ok = FindNextFile(dir->h, &fdat);
419 if (fdat.cFileName[0] == '.' &&
420 (fdat.cFileName[1] == '\0' ||
421 (fdat.cFileName[1] == '.' && fdat.cFileName[2] == '\0')))
424 dir->name = dupcat(dir->srcpath, fdat.cFileName, NULL);
428 char *ret = dir->name;
435 void finish_wildcard_matching(WildcardMatcher *dir)
444 int vet_filename(const char *name)
446 if (strchr(name, '/') || strchr(name, '\\') || strchr(name, ':'))
449 if (!name[strspn(name, ".")]) /* entirely composed of dots */
455 int create_directory(const char *name)
457 return CreateDirectory(name, NULL) != 0;
460 char *dir_file_cat(const char *dir, const char *file)
462 return dupcat(dir, "\\", file, NULL);
465 /* ----------------------------------------------------------------------
466 * Platform-specific network handling.
470 * Be told what socket we're supposed to be using.
472 static SOCKET sftp_ssh_socket = INVALID_SOCKET;
473 static HANDLE netevent = INVALID_HANDLE_VALUE;
474 char *do_select(SOCKET skt, int startup)
478 sftp_ssh_socket = skt;
480 sftp_ssh_socket = INVALID_SOCKET;
482 if (p_WSAEventSelect) {
484 events = (FD_CONNECT | FD_READ | FD_WRITE |
485 FD_OOB | FD_CLOSE | FD_ACCEPT);
486 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
490 if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
491 switch (p_WSAGetLastError()) {
493 return "Network is down";
495 return "WSAEventSelect(): unknown error";
501 extern int select_result(WPARAM, LPARAM);
503 int do_eventsel_loop(HANDLE other_event)
505 int n, nhandles, nallhandles, netindex, otherindex;
506 unsigned long next, then;
511 unsigned long now = GETTICKCOUNT();
513 if (toplevel_callback_pending()) {
516 } else if (run_timers(now, &next)) {
518 now = GETTICKCOUNT();
519 if (now - then > next - then)
525 /* no need to initialise next here because we can never get
529 handles = handle_get_events(&nhandles);
530 handles = sresize(handles, nhandles+2, HANDLE);
531 nallhandles = nhandles;
533 if (netevent != INVALID_HANDLE_VALUE)
534 handles[netindex = nallhandles++] = netevent;
537 if (other_event != INVALID_HANDLE_VALUE)
538 handles[otherindex = nallhandles++] = other_event;
542 n = WaitForMultipleObjects(nallhandles, handles, FALSE, ticks);
544 if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
545 handle_got_event(handles[n - WAIT_OBJECT_0]);
546 } else if (netindex >= 0 && n == WAIT_OBJECT_0 + netindex) {
547 WSANETWORKEVENTS things;
549 extern SOCKET first_socket(int *), next_socket(int *);
550 extern int select_result(WPARAM, LPARAM);
554 * We must not call select_result() for any socket
555 * until we have finished enumerating within the
556 * tree. This is because select_result() may close
557 * the socket and modify the tree.
559 /* Count the active sockets. */
561 for (socket = first_socket(&socketstate);
562 socket != INVALID_SOCKET;
563 socket = next_socket(&socketstate)) i++;
565 /* Expand the buffer if necessary. */
566 sklist = snewn(i, SOCKET);
568 /* Retrieve the sockets into sklist. */
570 for (socket = first_socket(&socketstate);
571 socket != INVALID_SOCKET;
572 socket = next_socket(&socketstate)) {
573 sklist[skcount++] = socket;
576 /* Now we're done enumerating; go through the list. */
577 for (i = 0; i < skcount; i++) {
580 wp = (WPARAM) socket;
581 if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) {
582 static const struct { int bit, mask; } eventtypes[] = {
583 {FD_CONNECT_BIT, FD_CONNECT},
584 {FD_READ_BIT, FD_READ},
585 {FD_CLOSE_BIT, FD_CLOSE},
586 {FD_OOB_BIT, FD_OOB},
587 {FD_WRITE_BIT, FD_WRITE},
588 {FD_ACCEPT_BIT, FD_ACCEPT},
592 noise_ultralight(socket);
593 noise_ultralight(things.lNetworkEvents);
595 for (e = 0; e < lenof(eventtypes); e++)
596 if (things.lNetworkEvents & eventtypes[e].mask) {
598 int err = things.iErrorCode[eventtypes[e].bit];
599 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
600 select_result(wp, lp);
610 run_toplevel_callbacks();
612 if (n == WAIT_TIMEOUT) {
615 now = GETTICKCOUNT();
618 if (otherindex >= 0 && n == WAIT_OBJECT_0 + otherindex)
625 * Wait for some network data and process it.
627 * We have two variants of this function. One uses select() so that
628 * it's compatible with WinSock 1. The other uses WSAEventSelect
629 * and MsgWaitForMultipleObjects, so that we can consistently use
630 * WSAEventSelect throughout; this enables us to also implement
631 * ssh_sftp_get_cmdline() using a parallel mechanism.
633 int ssh_sftp_loop_iteration(void)
635 if (p_WSAEventSelect == NULL) {
638 unsigned long now = GETTICKCOUNT(), then;
640 if (sftp_ssh_socket == INVALID_SOCKET)
641 return -1; /* doom */
643 if (socket_writable(sftp_ssh_socket))
644 select_result((WPARAM) sftp_ssh_socket, (LPARAM) FD_WRITE);
649 struct timeval tv, *ptv;
651 if (run_timers(now, &next)) {
653 now = GETTICKCOUNT();
654 if (now - then > next - then)
658 tv.tv_sec = ticks / 1000;
659 tv.tv_usec = ticks % 1000 * 1000;
666 FD_SET(sftp_ssh_socket, &readfds);
667 ret = p_select(1, &readfds, NULL, NULL, ptv);
670 return -1; /* doom */
674 now = GETTICKCOUNT();
678 select_result((WPARAM) sftp_ssh_socket, (LPARAM) FD_READ);
682 return do_eventsel_loop(INVALID_HANDLE_VALUE);
687 * Read a command line from standard input.
689 * In the presence of WinSock 2, we can use WSAEventSelect to
690 * mediate between the socket and stdin, meaning we can send
691 * keepalives and respond to server events even while waiting at
692 * the PSFTP command prompt. Without WS2, we fall back to a simple
695 struct command_read_ctx {
700 static DWORD WINAPI command_read_thread(void *param)
702 struct command_read_ctx *ctx = (struct command_read_ctx *) param;
704 ctx->line = fgetline(stdin);
706 SetEvent(ctx->event);
711 char *ssh_sftp_get_cmdline(const char *prompt, int no_fds_ok)
714 struct command_read_ctx actx, *ctx = &actx;
718 fputs(prompt, stdout);
721 if ((sftp_ssh_socket == INVALID_SOCKET && no_fds_ok) ||
722 p_WSAEventSelect == NULL) {
723 return fgetline(stdin); /* very simple */
727 * Create a second thread to read from stdin. Process network
728 * and timing events until it terminates.
730 ctx->event = CreateEvent(NULL, FALSE, FALSE, NULL);
733 hThread = CreateThread(NULL, 0, command_read_thread, ctx, 0, &threadid);
735 CloseHandle(ctx->event);
736 fprintf(stderr, "Unable to create command input thread\n");
741 ret = do_eventsel_loop(ctx->event);
743 /* Error return can only occur if netevent==NULL, and it ain't. */
747 CloseHandle(hThread);
748 CloseHandle(ctx->event);
753 void platform_psftp_pre_conn_setup(void)
755 if (restricted_acl) {
756 logevent(NULL, "Running with restricted process ACL");
760 /* ----------------------------------------------------------------------
761 * Main program. Parse arguments etc.
763 int main(int argc, char *argv[])
767 dll_hijacking_protection();
769 ret = psftp_main(argc, argv);