]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - windows/winsftp.c
GTK2: Return 2.20 compatibility back
[PuTTY.git] / windows / winsftp.c
1 /*
2  * winsftp.c: the Windows-specific parts of PSFTP and PSCP.
3  */
4
5 #include <winsock2.h> /* need to put this first, for winelib builds */
6 #include <assert.h>
7
8 #define NEED_DECLARATION_OF_SELECT
9
10 #include "putty.h"
11 #include "psftp.h"
12 #include "ssh.h"
13 #include "int64.h"
14 #include "winsecur.h"
15
16 char *get_ttymode(void *frontend, const char *mode) { return NULL; }
17
18 int get_userpass_input(prompts_t *p, const unsigned char *in, int inlen)
19 {
20     int ret;
21     ret = cmdline_get_passwd_input(p, in, inlen);
22     if (ret == -1)
23         ret = console_get_userpass_input(p, in, inlen);
24     return ret;
25 }
26
27 void platform_get_x11_auth(struct X11Display *display, Conf *conf)
28 {
29     /* Do nothing, therefore no auth. */
30 }
31 const int platform_uses_x11_unix_by_default = TRUE;
32
33 /* ----------------------------------------------------------------------
34  * File access abstraction.
35  */
36
37 /*
38  * Set local current directory. Returns NULL on success, or else an
39  * error message which must be freed after printing.
40  */
41 char *psftp_lcd(char *dir)
42 {
43     char *ret = NULL;
44
45     if (!SetCurrentDirectory(dir)) {
46         LPVOID message;
47         int i;
48         FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
49                       FORMAT_MESSAGE_FROM_SYSTEM |
50                       FORMAT_MESSAGE_IGNORE_INSERTS,
51                       NULL, GetLastError(),
52                       MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
53                       (LPTSTR)&message, 0, NULL);
54         i = strcspn((char *)message, "\n");
55         ret = dupprintf("%.*s", i, (LPCTSTR)message);
56         LocalFree(message);
57     }
58
59     return ret;
60 }
61
62 /*
63  * Get local current directory. Returns a string which must be
64  * freed.
65  */
66 char *psftp_getcwd(void)
67 {
68     char *ret = snewn(256, char);
69     int len = GetCurrentDirectory(256, ret);
70     if (len > 256)
71         ret = sresize(ret, len, char);
72     GetCurrentDirectory(len, ret);
73     return ret;
74 }
75
76 #define TIME_POSIX_TO_WIN(t, ft) do { \
77     ULARGE_INTEGER uli; \
78     uli.QuadPart = ((ULONGLONG)(t) + 11644473600ull) * 10000000ull; \
79     (ft).dwLowDateTime  = uli.LowPart; \
80     (ft).dwHighDateTime = uli.HighPart; \
81 } while(0)
82 #define TIME_WIN_TO_POSIX(ft, t) do { \
83     ULARGE_INTEGER uli; \
84     uli.LowPart  = (ft).dwLowDateTime; \
85     uli.HighPart = (ft).dwHighDateTime; \
86     uli.QuadPart = uli.QuadPart / 10000000ull - 11644473600ull; \
87     (t) = (unsigned long) uli.QuadPart; \
88 } while(0)
89
90 struct RFile {
91     HANDLE h;
92 };
93
94 RFile *open_existing_file(const char *name, uint64 *size,
95                           unsigned long *mtime, unsigned long *atime,
96                           long *perms)
97 {
98     HANDLE h;
99     RFile *ret;
100
101     h = CreateFile(name, GENERIC_READ, FILE_SHARE_READ, NULL,
102                    OPEN_EXISTING, 0, 0);
103     if (h == INVALID_HANDLE_VALUE)
104         return NULL;
105
106     ret = snew(RFile);
107     ret->h = h;
108
109     if (size) {
110         DWORD lo, hi;
111         lo = GetFileSize(h, &hi);
112         size->lo = lo;
113         size->hi = hi;
114     }
115
116     if (mtime || atime) {
117         FILETIME actime, wrtime;
118         GetFileTime(h, NULL, &actime, &wrtime);
119         if (atime)
120             TIME_WIN_TO_POSIX(actime, *atime);
121         if (mtime)
122             TIME_WIN_TO_POSIX(wrtime, *mtime);
123     }
124
125     if (perms)
126         *perms = -1;
127
128     return ret;
129 }
130
131 int read_from_file(RFile *f, void *buffer, int length)
132 {
133     int ret;
134     DWORD read;
135     ret = ReadFile(f->h, buffer, length, &read, NULL);
136     if (!ret)
137         return -1;                     /* error */
138     else
139         return read;
140 }
141
142 void close_rfile(RFile *f)
143 {
144     CloseHandle(f->h);
145     sfree(f);
146 }
147
148 struct WFile {
149     HANDLE h;
150 };
151
152 WFile *open_new_file(const char *name, long perms)
153 {
154     HANDLE h;
155     WFile *ret;
156
157     h = CreateFile(name, GENERIC_WRITE, 0, NULL,
158                    CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
159     if (h == INVALID_HANDLE_VALUE)
160         return NULL;
161
162     ret = snew(WFile);
163     ret->h = h;
164
165     return ret;
166 }
167
168 WFile *open_existing_wfile(const char *name, uint64 *size)
169 {
170     HANDLE h;
171     WFile *ret;
172
173     h = CreateFile(name, GENERIC_WRITE, FILE_SHARE_READ, NULL,
174                    OPEN_EXISTING, 0, 0);
175     if (h == INVALID_HANDLE_VALUE)
176         return NULL;
177
178     ret = snew(WFile);
179     ret->h = h;
180
181     if (size) {
182         DWORD lo, hi;
183         lo = GetFileSize(h, &hi);
184         size->lo = lo;
185         size->hi = hi;
186     }
187
188     return ret;
189 }
190
191 int write_to_file(WFile *f, void *buffer, int length)
192 {
193     int ret;
194     DWORD written;
195     ret = WriteFile(f->h, buffer, length, &written, NULL);
196     if (!ret)
197         return -1;                     /* error */
198     else
199         return written;
200 }
201
202 void set_file_times(WFile *f, unsigned long mtime, unsigned long atime)
203 {
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);
208 }
209
210 void close_wfile(WFile *f)
211 {
212     CloseHandle(f->h);
213     sfree(f);
214 }
215
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)
219 {
220     DWORD movemethod;
221
222     switch (whence) {
223     case FROM_START:
224         movemethod = FILE_BEGIN;
225         break;
226     case FROM_CURRENT:
227         movemethod = FILE_CURRENT;
228         break;
229     case FROM_END:
230         movemethod = FILE_END;
231         break;
232     default:
233         return -1;
234     }
235
236     {
237         LONG lo = offset.lo, hi = offset.hi;
238         SetFilePointer(f->h, lo, &hi, movemethod);
239     }
240     
241     if (GetLastError() != NO_ERROR)
242         return -1;
243     else 
244         return 0;
245 }
246
247 uint64 get_file_posn(WFile *f)
248 {
249     uint64 ret;
250     LONG lo, hi = 0;
251
252     lo = SetFilePointer(f->h, 0L, &hi, FILE_CURRENT);
253     ret.lo = lo;
254     ret.hi = hi;
255
256     return ret;
257 }
258
259 int file_type(const char *name)
260 {
261     DWORD attr;
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;
268     else
269         return FILE_TYPE_FILE;
270 }
271
272 struct DirHandle {
273     HANDLE h;
274     char *name;
275 };
276
277 DirHandle *open_directory(const char *name)
278 {
279     HANDLE h;
280     WIN32_FIND_DATA fdat;
281     char *findfile;
282     DirHandle *ret;
283
284     /* Enumerate files in dir `foo'. */
285     findfile = dupcat(name, "/*", NULL);
286     h = FindFirstFile(findfile, &fdat);
287     if (h == INVALID_HANDLE_VALUE)
288         return NULL;
289     sfree(findfile);
290
291     ret = snew(DirHandle);
292     ret->h = h;
293     ret->name = dupstr(fdat.cFileName);
294     return ret;
295 }
296
297 char *read_filename(DirHandle *dir)
298 {
299     do {
300
301         if (!dir->name) {
302             WIN32_FIND_DATA fdat;
303             int ok = FindNextFile(dir->h, &fdat);
304             if (!ok)
305                 return NULL;
306             else
307                 dir->name = dupstr(fdat.cFileName);
308         }
309
310         assert(dir->name);
311         if (dir->name[0] == '.' &&
312             (dir->name[1] == '\0' ||
313              (dir->name[1] == '.' && dir->name[2] == '\0'))) {
314             sfree(dir->name);
315             dir->name = NULL;
316         }
317
318     } while (!dir->name);
319
320     if (dir->name) {
321         char *ret = dir->name;
322         dir->name = NULL;
323         return ret;
324     } else
325         return NULL;
326 }
327
328 void close_directory(DirHandle *dir)
329 {
330     FindClose(dir->h);
331     if (dir->name)
332         sfree(dir->name);
333     sfree(dir);
334 }
335
336 int test_wildcard(const char *name, int cmdline)
337 {
338     HANDLE fh;
339     WIN32_FIND_DATA fdat;
340
341     /* First see if the exact name exists. */
342     if (GetFileAttributes(name) != (DWORD)-1)
343         return WCTYPE_FILENAME;
344
345     /* Otherwise see if a wildcard match finds anything. */
346     fh = FindFirstFile(name, &fdat);
347     if (fh == INVALID_HANDLE_VALUE)
348         return WCTYPE_NONEXISTENT;
349
350     FindClose(fh);
351     return WCTYPE_WILDCARD;
352 }
353
354 struct WildcardMatcher {
355     HANDLE h;
356     char *name;
357     char *srcpath;
358 };
359
360 char *stripslashes(const char *str, int local)
361 {
362     char *p;
363
364     /*
365      * On Windows, \ / : are all path component separators.
366      */
367
368     if (local) {
369         p = strchr(str, ':');
370         if (p) str = p+1;
371     }
372
373     p = strrchr(str, '/');
374     if (p) str = p+1;
375
376     if (local) {
377         p = strrchr(str, '\\');
378         if (p) str = p+1;
379     }
380
381     return (char *)str;
382 }
383
384 WildcardMatcher *begin_wildcard_matching(const char *name)
385 {
386     HANDLE h;
387     WIN32_FIND_DATA fdat;
388     WildcardMatcher *ret;
389     char *last;
390
391     h = FindFirstFile(name, &fdat);
392     if (h == INVALID_HANDLE_VALUE)
393         return NULL;
394
395     ret = snew(WildcardMatcher);
396     ret->h = h;
397     ret->srcpath = dupstr(name);
398     last = stripslashes(ret->srcpath, 1);
399     *last = '\0';
400     if (fdat.cFileName[0] == '.' &&
401         (fdat.cFileName[1] == '\0' ||
402          (fdat.cFileName[1] == '.' && fdat.cFileName[2] == '\0')))
403         ret->name = NULL;
404     else
405         ret->name = dupcat(ret->srcpath, fdat.cFileName, NULL);
406
407     return ret;
408 }
409
410 char *wildcard_get_filename(WildcardMatcher *dir)
411 {
412     while (!dir->name) {
413         WIN32_FIND_DATA fdat;
414         int ok = FindNextFile(dir->h, &fdat);
415
416         if (!ok)
417             return NULL;
418
419         if (fdat.cFileName[0] == '.' &&
420             (fdat.cFileName[1] == '\0' ||
421              (fdat.cFileName[1] == '.' && fdat.cFileName[2] == '\0')))
422             dir->name = NULL;
423         else
424             dir->name = dupcat(dir->srcpath, fdat.cFileName, NULL);
425     }
426
427     if (dir->name) {
428         char *ret = dir->name;
429         dir->name = NULL;
430         return ret;
431     } else
432         return NULL;
433 }
434
435 void finish_wildcard_matching(WildcardMatcher *dir)
436 {
437     FindClose(dir->h);
438     if (dir->name)
439         sfree(dir->name);
440     sfree(dir->srcpath);
441     sfree(dir);
442 }
443
444 int vet_filename(const char *name)
445 {
446     if (strchr(name, '/') || strchr(name, '\\') || strchr(name, ':'))
447         return FALSE;
448
449     if (!name[strspn(name, ".")])      /* entirely composed of dots */
450         return FALSE;
451
452     return TRUE;
453 }
454
455 int create_directory(const char *name)
456 {
457     return CreateDirectory(name, NULL) != 0;
458 }
459
460 char *dir_file_cat(const char *dir, const char *file)
461 {
462     return dupcat(dir, "\\", file, NULL);
463 }
464
465 /* ----------------------------------------------------------------------
466  * Platform-specific network handling.
467  */
468
469 /*
470  * Be told what socket we're supposed to be using.
471  */
472 static SOCKET sftp_ssh_socket = INVALID_SOCKET;
473 static HANDLE netevent = INVALID_HANDLE_VALUE;
474 char *do_select(SOCKET skt, int startup)
475 {
476     int events;
477     if (startup)
478         sftp_ssh_socket = skt;
479     else
480         sftp_ssh_socket = INVALID_SOCKET;
481
482     if (p_WSAEventSelect) {
483         if (startup) {
484             events = (FD_CONNECT | FD_READ | FD_WRITE |
485                       FD_OOB | FD_CLOSE | FD_ACCEPT);
486             netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
487         } else {
488             events = 0;
489         }
490         if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
491             switch (p_WSAGetLastError()) {
492               case WSAENETDOWN:
493                 return "Network is down";
494               default:
495                 return "WSAEventSelect(): unknown error";
496             }
497         }
498     }
499     return NULL;
500 }
501 extern int select_result(WPARAM, LPARAM);
502
503 int do_eventsel_loop(HANDLE other_event)
504 {
505     int n, nhandles, nallhandles, netindex, otherindex;
506     unsigned long next, then;
507     long ticks;
508     HANDLE *handles;
509     SOCKET *sklist;
510     int skcount;
511     unsigned long now = GETTICKCOUNT();
512
513     if (toplevel_callback_pending()) {
514         ticks = 0;
515         next = now;
516     } else if (run_timers(now, &next)) {
517         then = now;
518         now = GETTICKCOUNT();
519         if (now - then > next - then)
520             ticks = 0;
521         else
522             ticks = next - now;
523     } else {
524         ticks = INFINITE;
525         /* no need to initialise next here because we can never get
526          * WAIT_TIMEOUT */
527     }
528
529     handles = handle_get_events(&nhandles);
530     handles = sresize(handles, nhandles+2, HANDLE);
531     nallhandles = nhandles;
532
533     if (netevent != INVALID_HANDLE_VALUE)
534         handles[netindex = nallhandles++] = netevent;
535     else
536         netindex = -1;
537     if (other_event != INVALID_HANDLE_VALUE)
538         handles[otherindex = nallhandles++] = other_event;
539     else
540         otherindex = -1;
541
542     n = WaitForMultipleObjects(nallhandles, handles, FALSE, ticks);
543
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;
548         SOCKET socket;
549         extern SOCKET first_socket(int *), next_socket(int *);
550         extern int select_result(WPARAM, LPARAM);
551         int i, socketstate;
552
553         /*
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.
558          */
559         /* Count the active sockets. */
560         i = 0;
561         for (socket = first_socket(&socketstate);
562              socket != INVALID_SOCKET;
563              socket = next_socket(&socketstate)) i++;
564
565         /* Expand the buffer if necessary. */
566         sklist = snewn(i, SOCKET);
567
568         /* Retrieve the sockets into sklist. */
569         skcount = 0;
570         for (socket = first_socket(&socketstate);
571              socket != INVALID_SOCKET;
572              socket = next_socket(&socketstate)) {
573             sklist[skcount++] = socket;
574         }
575
576         /* Now we're done enumerating; go through the list. */
577         for (i = 0; i < skcount; i++) {
578             WPARAM wp;
579             socket = sklist[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},
589                 };
590                 int e;
591
592                 noise_ultralight(socket);
593                 noise_ultralight(things.lNetworkEvents);
594
595                 for (e = 0; e < lenof(eventtypes); e++)
596                     if (things.lNetworkEvents & eventtypes[e].mask) {
597                         LPARAM lp;
598                         int err = things.iErrorCode[eventtypes[e].bit];
599                         lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
600                         select_result(wp, lp);
601                     }
602             }
603         }
604
605         sfree(sklist);
606     }
607
608     sfree(handles);
609
610     run_toplevel_callbacks();
611
612     if (n == WAIT_TIMEOUT) {
613         now = next;
614     } else {
615         now = GETTICKCOUNT();
616     }
617
618     if (otherindex >= 0 && n == WAIT_OBJECT_0 + otherindex)
619         return 1;
620
621     return 0;
622 }
623
624 /*
625  * Wait for some network data and process it.
626  *
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.
632  */
633 int ssh_sftp_loop_iteration(void)
634 {
635     if (p_WSAEventSelect == NULL) {
636         fd_set readfds;
637         int ret;
638         unsigned long now = GETTICKCOUNT(), then;
639
640         if (sftp_ssh_socket == INVALID_SOCKET)
641             return -1;                 /* doom */
642
643         if (socket_writable(sftp_ssh_socket))
644             select_result((WPARAM) sftp_ssh_socket, (LPARAM) FD_WRITE);
645
646         do {
647             unsigned long next;
648             long ticks;
649             struct timeval tv, *ptv;
650
651             if (run_timers(now, &next)) {
652                 then = now;
653                 now = GETTICKCOUNT();
654                 if (now - then > next - then)
655                     ticks = 0;
656                 else
657                     ticks = next - now;
658                 tv.tv_sec = ticks / 1000;
659                 tv.tv_usec = ticks % 1000 * 1000;
660                 ptv = &tv;
661             } else {
662                 ptv = NULL;
663             }
664
665             FD_ZERO(&readfds);
666             FD_SET(sftp_ssh_socket, &readfds);
667             ret = p_select(1, &readfds, NULL, NULL, ptv);
668
669             if (ret < 0)
670                 return -1;                     /* doom */
671             else if (ret == 0)
672                 now = next;
673             else
674                 now = GETTICKCOUNT();
675
676         } while (ret == 0);
677
678         select_result((WPARAM) sftp_ssh_socket, (LPARAM) FD_READ);
679
680         return 0;
681     } else {
682         return do_eventsel_loop(INVALID_HANDLE_VALUE);
683     }
684 }
685
686 /*
687  * Read a command line from standard input.
688  * 
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
693  * fgets.
694  */
695 struct command_read_ctx {
696     HANDLE event;
697     char *line;
698 };
699
700 static DWORD WINAPI command_read_thread(void *param)
701 {
702     struct command_read_ctx *ctx = (struct command_read_ctx *) param;
703
704     ctx->line = fgetline(stdin);
705
706     SetEvent(ctx->event);
707
708     return 0;
709 }
710
711 char *ssh_sftp_get_cmdline(const char *prompt, int no_fds_ok)
712 {
713     int ret;
714     struct command_read_ctx actx, *ctx = &actx;
715     DWORD threadid;
716     HANDLE hThread;
717
718     fputs(prompt, stdout);
719     fflush(stdout);
720
721     if ((sftp_ssh_socket == INVALID_SOCKET && no_fds_ok) ||
722         p_WSAEventSelect == NULL) {
723         return fgetline(stdin);        /* very simple */
724     }
725
726     /*
727      * Create a second thread to read from stdin. Process network
728      * and timing events until it terminates.
729      */
730     ctx->event = CreateEvent(NULL, FALSE, FALSE, NULL);
731     ctx->line = NULL;
732
733     hThread = CreateThread(NULL, 0, command_read_thread, ctx, 0, &threadid);
734     if (!hThread) {
735         CloseHandle(ctx->event);
736         fprintf(stderr, "Unable to create command input thread\n");
737         cleanup_exit(1);
738     }
739
740     do {
741         ret = do_eventsel_loop(ctx->event);
742
743         /* Error return can only occur if netevent==NULL, and it ain't. */
744         assert(ret >= 0);
745     } while (ret == 0);
746
747     CloseHandle(hThread);
748     CloseHandle(ctx->event);
749
750     return ctx->line;
751 }
752
753 void platform_psftp_pre_conn_setup(void)
754 {
755     if (restricted_acl) {
756         logevent(NULL, "Running with restricted process ACL");
757     }
758 }
759
760 /* ----------------------------------------------------------------------
761  * Main program. Parse arguments etc.
762  */
763 int main(int argc, char *argv[])
764 {
765     int ret;
766
767     dll_hijacking_protection();
768
769     ret = psftp_main(argc, argv);
770
771     return ret;
772 }