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