... and there's a Unix port of PSCP. Ooh.
[u/mdw/putty] / winsftp.c
1 /*
2 * winsftp.c: the Windows-specific parts of PSFTP and PSCP.
3 */
4
5 #include <windows.h>
6 #ifndef AUTO_WINSOCK
7 #ifdef WINSOCK_TWO
8 #include <winsock2.h>
9 #else
10 #include <winsock.h>
11 #endif
12 #endif
13
14 #include "putty.h"
15 #include "psftp.h"
16
17 /* ----------------------------------------------------------------------
18 * Interface to GUI driver program.
19 */
20
21 /* This is just a base value from which the main message numbers are
22 * derived. */
23 #define WM_APP_BASE 0x8000
24
25 /* These two pass a single character value in wParam. They represent
26 * the visible output from PSCP. */
27 #define WM_STD_OUT_CHAR ( WM_APP_BASE+400 )
28 #define WM_STD_ERR_CHAR ( WM_APP_BASE+401 )
29
30 /* These pass a transfer status update. WM_STATS_CHAR passes a single
31 * character in wParam, and is called repeatedly to pass the name of
32 * the file, terminated with "\n". WM_STATS_SIZE passes the size of
33 * the file being transferred in wParam. WM_STATS_ELAPSED is called
34 * to pass the elapsed time (in seconds) in wParam, and
35 * WM_STATS_PERCENT passes the percentage of the transfer which is
36 * complete, also in wParam. */
37 #define WM_STATS_CHAR ( WM_APP_BASE+402 )
38 #define WM_STATS_SIZE ( WM_APP_BASE+403 )
39 #define WM_STATS_PERCENT ( WM_APP_BASE+404 )
40 #define WM_STATS_ELAPSED ( WM_APP_BASE+405 )
41
42 /* These are used at the end of a run to pass an error code in
43 * wParam: zero means success, nonzero means failure. WM_RET_ERR_CNT
44 * is used after a copy, and WM_LS_RET_ERR_CNT is used after a file
45 * list operation. */
46 #define WM_RET_ERR_CNT ( WM_APP_BASE+406 )
47 #define WM_LS_RET_ERR_CNT ( WM_APP_BASE+407 )
48
49 /* More transfer status update messages. WM_STATS_DONE passes the
50 * number of bytes sent so far in wParam. WM_STATS_ETA passes the
51 * estimated time to completion (in seconds). WM_STATS_RATEBS passes
52 * the average transfer rate (in bytes per second). */
53 #define WM_STATS_DONE ( WM_APP_BASE+408 )
54 #define WM_STATS_ETA ( WM_APP_BASE+409 )
55 #define WM_STATS_RATEBS ( WM_APP_BASE+410 )
56
57 #define NAME_STR_MAX 2048
58 static char statname[NAME_STR_MAX + 1];
59 static unsigned long statsize = 0;
60 static unsigned long statdone = 0;
61 static unsigned long stateta = 0;
62 static unsigned long statratebs = 0;
63 static int statperct = 0;
64 static unsigned long statelapsed = 0;
65
66 static HWND gui_hwnd = NULL;
67
68 static void send_msg(HWND h, UINT message, WPARAM wParam)
69 {
70 while (!PostMessage(h, message, wParam, 0))
71 SleepEx(1000, TRUE);
72 }
73
74 void gui_send_char(int is_stderr, int c)
75 {
76 unsigned int msg_id = WM_STD_OUT_CHAR;
77 if (is_stderr)
78 msg_id = WM_STD_ERR_CHAR;
79 send_msg(gui_hwnd, msg_id, (WPARAM) c);
80 }
81
82 void gui_send_errcount(int list, int errs)
83 {
84 unsigned int msg_id = WM_RET_ERR_CNT;
85 if (list)
86 msg_id = WM_LS_RET_ERR_CNT;
87 while (!PostMessage(gui_hwnd, msg_id, (WPARAM) errs, 0))
88 SleepEx(1000, TRUE);
89 }
90
91 void gui_update_stats(char *name, unsigned long size,
92 int percentage, unsigned long elapsed,
93 unsigned long done, unsigned long eta,
94 unsigned long ratebs)
95 {
96 unsigned int i;
97
98 if (strcmp(name, statname) != 0) {
99 for (i = 0; i < strlen(name); ++i)
100 send_msg(gui_hwnd, WM_STATS_CHAR, (WPARAM) name[i]);
101 send_msg(gui_hwnd, WM_STATS_CHAR, (WPARAM) '\n');
102 strcpy(statname, name);
103 }
104 if (statsize != size) {
105 send_msg(gui_hwnd, WM_STATS_SIZE, (WPARAM) size);
106 statsize = size;
107 }
108 if (statdone != done) {
109 send_msg(gui_hwnd, WM_STATS_DONE, (WPARAM) done);
110 statdone = done;
111 }
112 if (stateta != eta) {
113 send_msg(gui_hwnd, WM_STATS_ETA, (WPARAM) eta);
114 stateta = eta;
115 }
116 if (statratebs != ratebs) {
117 send_msg(gui_hwnd, WM_STATS_RATEBS, (WPARAM) ratebs);
118 statratebs = ratebs;
119 }
120 if (statelapsed != elapsed) {
121 send_msg(gui_hwnd, WM_STATS_ELAPSED, (WPARAM) elapsed);
122 statelapsed = elapsed;
123 }
124 if (statperct != percentage) {
125 send_msg(gui_hwnd, WM_STATS_PERCENT, (WPARAM) percentage);
126 statperct = percentage;
127 }
128 }
129
130 void gui_enable(char *arg)
131 {
132 gui_hwnd = (HWND) atoi(arg);
133 }
134
135 /* ----------------------------------------------------------------------
136 * File access abstraction.
137 */
138
139 /*
140 * Set local current directory. Returns NULL on success, or else an
141 * error message which must be freed after printing.
142 */
143 char *psftp_lcd(char *dir)
144 {
145 char *ret = NULL;
146
147 if (!SetCurrentDirectory(dir)) {
148 LPVOID message;
149 int i;
150 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
151 FORMAT_MESSAGE_FROM_SYSTEM |
152 FORMAT_MESSAGE_IGNORE_INSERTS,
153 NULL, GetLastError(),
154 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
155 (LPTSTR)&message, 0, NULL);
156 i = strcspn((char *)message, "\n");
157 ret = dupprintf("%.*s", i, (LPCTSTR)message);
158 LocalFree(message);
159 }
160
161 return ret;
162 }
163
164 /*
165 * Get local current directory. Returns a string which must be
166 * freed.
167 */
168 char *psftp_getcwd(void)
169 {
170 char *ret = snewn(256, char);
171 int len = GetCurrentDirectory(256, ret);
172 if (len > 256)
173 ret = sresize(ret, len, char);
174 GetCurrentDirectory(len, ret);
175 return ret;
176 }
177
178 #define TIME_POSIX_TO_WIN(t, ft) (*(LONGLONG*)&(ft) = \
179 ((LONGLONG) (t) + (LONGLONG) 11644473600) * (LONGLONG) 10000000)
180 #define TIME_WIN_TO_POSIX(ft, t) ((t) = (unsigned long) \
181 ((*(LONGLONG*)&(ft)) / (LONGLONG) 10000000 - (LONGLONG) 11644473600))
182
183 struct RFile {
184 HANDLE h;
185 };
186
187 RFile *open_existing_file(char *name, unsigned long *size,
188 unsigned long *mtime, unsigned long *atime)
189 {
190 HANDLE h;
191 RFile *ret;
192
193 h = CreateFile(name, GENERIC_READ, FILE_SHARE_READ, NULL,
194 OPEN_EXISTING, 0, 0);
195 if (h == INVALID_HANDLE_VALUE)
196 return NULL;
197
198 ret = snew(RFile);
199 ret->h = h;
200
201 if (size)
202 *size = GetFileSize(h, NULL);
203
204 if (mtime || atime) {
205 FILETIME actime, wrtime;
206 GetFileTime(h, NULL, &actime, &wrtime);
207 if (atime)
208 TIME_WIN_TO_POSIX(actime, *atime);
209 if (mtime)
210 TIME_WIN_TO_POSIX(wrtime, *mtime);
211 }
212
213 return ret;
214 }
215
216 int read_from_file(RFile *f, void *buffer, int length)
217 {
218 int ret, read;
219 ret = ReadFile(f->h, buffer, length, &read, NULL);
220 if (!ret)
221 return -1; /* error */
222 else
223 return read;
224 }
225
226 void close_rfile(RFile *f)
227 {
228 CloseHandle(f->h);
229 sfree(f);
230 }
231
232 struct WFile {
233 HANDLE h;
234 };
235
236 WFile *open_new_file(char *name)
237 {
238 HANDLE h;
239 WFile *ret;
240
241 h = CreateFile(name, GENERIC_WRITE, 0, NULL,
242 CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
243 if (h == INVALID_HANDLE_VALUE)
244 return NULL;
245
246 ret = snew(WFile);
247 ret->h = h;
248
249 return ret;
250 }
251
252 int write_to_file(WFile *f, void *buffer, int length)
253 {
254 int ret, written;
255 ret = WriteFile(f->h, buffer, length, &written, NULL);
256 if (!ret)
257 return -1; /* error */
258 else
259 return written;
260 }
261
262 void set_file_times(WFile *f, unsigned long mtime, unsigned long atime)
263 {
264 FILETIME actime, wrtime;
265 TIME_POSIX_TO_WIN(atime, actime);
266 TIME_POSIX_TO_WIN(mtime, wrtime);
267 SetFileTime(f->h, NULL, &actime, &wrtime);
268 }
269
270 void close_wfile(WFile *f)
271 {
272 CloseHandle(f->h);
273 sfree(f);
274 }
275
276 int file_type(char *name)
277 {
278 DWORD attr;
279 attr = GetFileAttributes(name);
280 /* We know of no `weird' files under Windows. */
281 if (attr == (DWORD)-1)
282 return FILE_TYPE_NONEXISTENT;
283 else if (attr & FILE_ATTRIBUTE_DIRECTORY)
284 return FILE_TYPE_DIRECTORY;
285 else
286 return FILE_TYPE_FILE;
287 }
288
289 struct DirHandle {
290 HANDLE h;
291 char *name;
292 };
293
294 DirHandle *open_directory(char *name)
295 {
296 HANDLE h;
297 WIN32_FIND_DATA fdat;
298 char *findfile;
299 DirHandle *ret;
300
301 /* To enumerate files in dir `foo', we search for `foo/*'. */
302 findfile = dupcat(name, "/*", NULL);
303 h = FindFirstFile(findfile, &fdat);
304 if (h == INVALID_HANDLE_VALUE)
305 return NULL;
306 sfree(findfile);
307
308 ret = snew(DirHandle);
309 ret->h = h;
310 ret->name = dupstr(fdat.cFileName);
311 return ret;
312 }
313
314 char *read_filename(DirHandle *dir)
315 {
316 while (!dir->name) {
317 WIN32_FIND_DATA fdat;
318 int ok = FindNextFile(dir->h, &fdat);
319
320 if (!ok)
321 return NULL;
322
323 if (fdat.cFileName[0] == '.' &&
324 (fdat.cFileName[1] == '\0' ||
325 (fdat.cFileName[1] == '.' && fdat.cFileName[2] == '\0')))
326 dir->name = NULL;
327 else
328 dir->name = dupstr(fdat.cFileName);
329 }
330
331 if (dir->name) {
332 char *ret = dir->name;
333 dir->name = NULL;
334 return ret;
335 } else
336 return NULL;
337 }
338
339 void close_directory(DirHandle *dir)
340 {
341 FindClose(dir->h);
342 if (dir->name)
343 sfree(dir->name);
344 sfree(dir);
345 }
346
347 int test_wildcard(char *name, int cmdline)
348 {
349 HANDLE fh;
350 WIN32_FIND_DATA fdat;
351
352 /* First see if the exact name exists. */
353 if (GetFileAttributes(name) != (DWORD)-1)
354 return WCTYPE_FILENAME;
355
356 /* Otherwise see if a wildcard match finds anything. */
357 fh = FindFirstFile(name, &fdat);
358 if (fh == INVALID_HANDLE_VALUE)
359 return WCTYPE_NONEXISTENT;
360
361 FindClose(fh);
362 return WCTYPE_WILDCARD;
363 }
364
365 struct WildcardMatcher {
366 HANDLE h;
367 char *name;
368 char *srcpath;
369 };
370
371 /*
372 * Return a pointer to the portion of str that comes after the last
373 * slash (or backslash or colon, if `local' is TRUE).
374 */
375 static char *stripslashes(char *str, int local)
376 {
377 char *p;
378
379 if (local) {
380 p = strchr(str, ':');
381 if (p) str = p+1;
382 }
383
384 p = strrchr(str, '/');
385 if (p) str = p+1;
386
387 if (local) {
388 p = strrchr(str, '\\');
389 if (p) str = p+1;
390 }
391
392 return str;
393 }
394
395 WildcardMatcher *begin_wildcard_matching(char *name)
396 {
397 HANDLE h;
398 WIN32_FIND_DATA fdat;
399 WildcardMatcher *ret;
400 char *last;
401
402 h = FindFirstFile(name, &fdat);
403 if (h == INVALID_HANDLE_VALUE)
404 return NULL;
405
406 ret = snew(WildcardMatcher);
407 ret->h = h;
408 ret->srcpath = dupstr(name);
409 last = stripslashes(ret->srcpath, 1);
410 *last = '\0';
411 if (fdat.cFileName[0] == '.' &&
412 (fdat.cFileName[1] == '\0' ||
413 (fdat.cFileName[1] == '.' && fdat.cFileName[2] == '\0')))
414 ret->name = NULL;
415 else
416 ret->name = dupcat(ret->srcpath, fdat.cFileName, NULL);
417
418 return ret;
419 }
420
421 char *wildcard_get_filename(WildcardMatcher *dir)
422 {
423 while (!dir->name) {
424 WIN32_FIND_DATA fdat;
425 int ok = FindNextFile(dir->h, &fdat);
426
427 if (!ok)
428 return NULL;
429
430 if (fdat.cFileName[0] == '.' &&
431 (fdat.cFileName[1] == '\0' ||
432 (fdat.cFileName[1] == '.' && fdat.cFileName[2] == '\0')))
433 dir->name = NULL;
434 else
435 dir->name = dupcat(dir->srcpath, fdat.cFileName, NULL);
436 }
437
438 if (dir->name) {
439 char *ret = dir->name;
440 dir->name = NULL;
441 return ret;
442 } else
443 return NULL;
444 }
445
446 void finish_wildcard_matching(WildcardMatcher *dir)
447 {
448 FindClose(dir->h);
449 if (dir->name)
450 sfree(dir->name);
451 sfree(dir->srcpath);
452 sfree(dir);
453 }
454
455 int create_directory(char *name)
456 {
457 return CreateDirectory(name, NULL) != 0;
458 }
459
460 char *dir_file_cat(char *dir, 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;
473 char *do_select(SOCKET skt, int startup)
474 {
475 if (startup)
476 sftp_ssh_socket = skt;
477 else
478 sftp_ssh_socket = INVALID_SOCKET;
479 return NULL;
480 }
481 extern int select_result(WPARAM, LPARAM);
482
483 /*
484 * Initialize the WinSock driver.
485 */
486 static void init_winsock(void)
487 {
488 WORD winsock_ver;
489 WSADATA wsadata;
490
491 winsock_ver = MAKEWORD(1, 1);
492 if (WSAStartup(winsock_ver, &wsadata)) {
493 fprintf(stderr, "Unable to initialise WinSock");
494 cleanup_exit(1);
495 }
496 if (LOBYTE(wsadata.wVersion) != 1 || HIBYTE(wsadata.wVersion) != 1) {
497 fprintf(stderr, "WinSock version is incompatible with 1.1");
498 cleanup_exit(1);
499 }
500 }
501
502 /*
503 * Wait for some network data and process it.
504 */
505 int ssh_sftp_loop_iteration(void)
506 {
507 fd_set readfds;
508
509 if (sftp_ssh_socket == INVALID_SOCKET)
510 return -1; /* doom */
511
512 FD_ZERO(&readfds);
513 FD_SET(sftp_ssh_socket, &readfds);
514 if (select(1, &readfds, NULL, NULL, NULL) < 0)
515 return -1; /* doom */
516
517 select_result((WPARAM) sftp_ssh_socket, (LPARAM) FD_READ);
518 return 0;
519 }
520
521 /* ----------------------------------------------------------------------
522 * Main program. Parse arguments etc.
523 */
524 int main(int argc, char *argv[])
525 {
526 int ret;
527
528 init_winsock();
529 ret = psftp_main(argc, argv);
530 WSACleanup();
531
532 return ret;
533 }