]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - scp.c
Clean up scp client - re-indent to my coding style and remove
[PuTTY.git] / scp.c
1 /*
2  *  scp.c  -  Scp (Secure Copy) client for PuTTY.
3  *  Joris van Rantwijk, Aug 1999.
4  *
5  *  This is mainly based on ssh-1.2.26/scp.c by Timo Rinne & Tatu Ylonen.
6  *  They, in turn, used stuff from BSD rcp.
7  */
8
9 #include <windows.h>
10 #include <winsock.h>
11 #include <stdlib.h>
12 #include <stdio.h>
13 #include <string.h>
14 #include <time.h>
15
16 #define PUTTY_DO_GLOBALS
17 #include "putty.h"
18 #include "scp.h"
19
20 #define TIME_POSIX_TO_WIN(t, ft) (*(LONGLONG*)&(ft) = \
21         ((LONGLONG) (t) + (LONGLONG) 11644473600) * (LONGLONG) 10000000)
22 #define TIME_WIN_TO_POSIX(ft, t) ((t) = (unsigned long) \
23         ((*(LONGLONG*)&(ft)) / (LONGLONG) 10000000 - (LONGLONG) 11644473600))
24
25 int verbose = 0;
26 static int recursive = 0;
27 static int preserve = 0;
28 static int targetshouldbedirectory = 0;
29 static int statistics = 1;
30 static int errs = 0;
31 static int connection_open = 0;
32
33 static void source(char *src);
34 static void rsource(char *src);
35 static void sink(char *targ);
36
37 /*
38  *  Print an error message and perform a fatal exit.
39  */
40 void fatalbox(char *fmt, ...)
41 {
42     va_list ap;
43     va_start(ap, fmt);
44     fprintf(stderr, "Fatal: ");
45     vfprintf(stderr, fmt, ap);
46     fprintf(stderr, "\n");
47     va_end(ap);
48     exit(1);
49 }
50
51 /*
52  *  Print an error message and exit after closing the SSH link.
53  */
54 static void bump(char *fmt, ...)
55 {
56     va_list ap;
57     va_start(ap, fmt);
58     fprintf(stderr, "Fatal: ");
59     vfprintf(stderr, fmt, ap);
60     fprintf(stderr, "\n");
61     va_end(ap);
62     if (connection_open) {
63         char ch;
64         ssh_send_eof();
65         ssh_recv(&ch, 1);
66     }
67     exit(1);
68 }
69
70 void ssh_get_password(char *prompt, char *str, int maxlen)
71 {
72     HANDLE hin, hout;
73     DWORD savemode;
74     int i;
75
76     hin = GetStdHandle(STD_INPUT_HANDLE);
77     hout = GetStdHandle(STD_OUTPUT_HANDLE);
78     if (hin == INVALID_HANDLE_VALUE || hout == INVALID_HANDLE_VALUE)
79         bump("Cannot get standard input/output handles");
80
81     GetConsoleMode(hin, &savemode);
82     SetConsoleMode(hin, (savemode & (~ENABLE_ECHO_INPUT)) |
83                    ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT);
84
85     WriteFile(hout, prompt, strlen(prompt), &i, NULL);
86     ReadFile(hin, str, maxlen-1, &i, NULL);
87
88     SetConsoleMode(hin, savemode);
89
90     if (i > maxlen) i = maxlen-1; else i = i - 2;
91     str[i] = '\0';
92
93     WriteFile(hout, "\r\n", 2, &i, NULL);
94 }
95
96 /*
97  *  Open an SSH connection to user@host and execute cmd.
98  */
99 static void do_cmd(char *host, char *user, char *cmd)
100 {
101     char *err, *realhost;
102
103     if (host == NULL || host[0] == '\0')
104         bump("Empty host name");
105
106     /* Try to load settings for this host */
107     do_defaults(host);
108     if (cfg.host[0] == '\0') {
109         /* No settings for this host; use defaults */
110         strncpy(cfg.host, host, sizeof(cfg.host)-1);
111         cfg.host[sizeof(cfg.host)-1] = '\0';
112         cfg.port = 22;
113     }
114
115     /* Set username */
116     if (user != NULL && user[0] != '\0') {
117         strncpy(cfg.username, user, sizeof(cfg.username)-1);
118         cfg.username[sizeof(cfg.username)-1] = '\0';
119         cfg.port = 22;
120     } else if (cfg.username[0] == '\0') {
121         bump("Empty user name");
122     }
123
124     if (cfg.protocol != PROT_SSH)
125         cfg.port = 22;
126
127     err = ssh_init(cfg.host, cfg.port, cmd, &realhost);
128     if (err != NULL)
129         bump("ssh_init: %s", err);
130     if (verbose && realhost != NULL)
131         fprintf(stderr, "Connected to %s\n", realhost);
132
133     connection_open = 1;
134 }
135
136 /*
137  *  Update statistic information about current file.
138  */
139 static void print_stats(char *name, unsigned long size, unsigned long done,
140                         time_t start, time_t now)
141 {
142     float ratebs;
143     unsigned long eta;
144     char etastr[10];
145     int pct;
146
147     if (now > start)
148         ratebs = (float) done / (now - start);
149     else
150         ratebs = (float) done;
151
152     if (ratebs < 1.0)
153         eta = size - done;
154     else
155         eta = (unsigned long) ((size - done) / ratebs);
156     sprintf(etastr, "%02d:%02d:%02d",
157             eta / 3600, (eta % 3600) / 60, eta % 60);
158
159     pct = (int) (100.0 * (float) done / size);
160
161     printf("\r%-25.25s | %10ld kB | %5.1f kB/s | ETA: %8s | %3d%%",
162            name, done / 1024, ratebs / 1024.0,
163            etastr, pct);
164
165     if (done == size)
166         printf("\n");
167 }
168
169 /*
170  *  Find a colon in str and return a pointer to the colon.
171  *  This is used to seperate hostname from filename.
172  */
173 static char * colon(char *str)
174 {
175     /* We ignore a leading colon, since the hostname cannot be
176      empty. We also ignore a colon as second character because
177      of filenames like f:myfile.txt. */
178     if (str[0] == '\0' ||
179         str[0] == ':' ||
180         str[1] == ':')
181         return (NULL);
182     while (*str != '\0' &&
183            *str != ':' &&
184            *str != '/' &&
185            *str != '\\')
186         str++;
187     if (*str == ':')
188         return (str);
189     else
190         return (NULL);
191 }
192
193 /*
194  *  Wait for a response from the other side.
195  *  Return 0 if ok, -1 if error.
196  */
197 static int response(void)
198 {
199     char ch, resp, rbuf[2048];
200     int p;
201
202     if (ssh_recv(&resp, 1) <= 0)
203         bump("Lost connection");
204
205     p = 0;
206     switch (resp) {
207       case 0:           /* ok */
208         return (0);
209       default:
210         rbuf[p++] = resp;
211         /* fallthrough */
212       case 1:           /* error */
213       case 2:           /* fatal error */
214         do {
215             if (ssh_recv(&ch, 1) <= 0)
216                 bump("Protocol error: Lost connection");
217             rbuf[p++] = ch;
218         } while (p < sizeof(rbuf) && ch != '\n');
219         rbuf[p-1] = '\0';
220         if (resp == 1)
221             fprintf(stderr, "%s\n", rbuf);
222         else
223             bump("%s", rbuf);
224         errs++;
225         return (-1);
226     }
227 }
228
229 /*
230  *  Send an error message to the other side and to the screen.
231  *  Increment error counter.
232  */
233 static void run_err(const char *fmt, ...)
234 {
235     char str[2048];
236     va_list ap;
237     va_start(ap, fmt);
238     errs++;
239     strcpy(str, "\01scp: ");
240     vsprintf(str+strlen(str), fmt, ap);
241     strcat(str, "\n");
242     ssh_send(str, strlen(str));
243     vfprintf(stderr, fmt, ap);
244     fprintf(stderr, "\n");
245     va_end(ap);
246 }
247
248 /*
249  *  Execute the source part of the SCP protocol.
250  */
251 static void source(char *src)
252 {
253     char buf[2048];
254     unsigned long size;
255     char *last;
256     HANDLE f;
257     DWORD attr;
258     unsigned long i;
259     unsigned long stat_bytes;
260     time_t stat_starttime, stat_lasttime;
261
262     attr = GetFileAttributes(src);
263     if (attr == -1) {
264         run_err("%s: No such file or directory", src);
265         return;
266     }
267
268     if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
269         if (recursive)
270             rsource(src);
271         else
272             run_err("%s: not a regular file", src);
273         return;
274     }
275
276     if ((last = strrchr(src, '/')) == NULL)
277         last = src;
278     else
279         last++;
280     if (strrchr(last, '\\') != NULL)
281         last = strrchr(last, '\\') + 1;
282     if (last == src && strchr(src, ':') != NULL)
283         last = strchr(src, ':') + 1;
284
285     f = CreateFile(src, GENERIC_READ, FILE_SHARE_READ, NULL,
286                    OPEN_EXISTING, 0, 0);
287     if (f == INVALID_HANDLE_VALUE) {
288         run_err("%s: Cannot open file");
289         return;
290     }
291
292     if (preserve) {
293         FILETIME actime, wrtime;
294         unsigned long mtime, atime;
295         GetFileTime(f, NULL, &actime, &wrtime);
296         TIME_WIN_TO_POSIX(actime, atime);
297         TIME_WIN_TO_POSIX(wrtime, mtime);
298         sprintf(buf, "T%lu 0 %lu 0\n", mtime, atime);
299         ssh_send(buf, strlen(buf));
300         if (response())
301             return;
302     }
303
304     size = GetFileSize(f, NULL);
305     sprintf(buf, "C0644 %lu %s\n", size, last);
306     if (verbose)
307         fprintf(stderr, "Sending file modes: %s", buf);
308     ssh_send(buf, strlen(buf));
309     if (response())
310         return;
311
312     if (statistics) {
313         stat_bytes = 0;
314         stat_starttime = time(NULL);
315         stat_lasttime = 0;
316     }
317
318     for (i = 0; i < size; i += 4096) {
319         char transbuf[4096];
320         DWORD j, k = 4096;
321         if (i + k > size) k = size - i;
322         if (! ReadFile(f, transbuf, k, &j, NULL) || j != k) {
323             if (statistics) printf("\n");
324             bump("%s: Read error", src);
325         }
326         ssh_send(transbuf, k);
327         if (statistics) {
328             stat_bytes += k;
329             if (time(NULL) != stat_lasttime ||
330                 i + k == size) {
331                 stat_lasttime = time(NULL);
332                 print_stats(last, size, stat_bytes,
333                             stat_starttime, stat_lasttime);
334             }
335         }
336     }
337     CloseHandle(f);
338
339     ssh_send("", 1);
340     (void) response();
341 }
342
343 /*
344  *  Recursively send the contents of a directory.
345  */
346 static void rsource(char *src)
347 {
348     char buf[2048];
349     char *last;
350     HANDLE dir;
351     WIN32_FIND_DATA fdat;
352     int ok;
353
354     if ((last = strrchr(src, '/')) == NULL)
355         last = src;
356     else
357         last++;
358     if (strrchr(last, '\\') != NULL)
359         last = strrchr(last, '\\') + 1;
360     if (last == src && strchr(src, ':') != NULL)
361         last = strchr(src, ':') + 1;
362
363     /* maybe send filetime */
364
365     sprintf(buf, "D0755 0 %s\n", last);
366     if (verbose)
367         fprintf(stderr, "Entering directory: %s", buf);
368     ssh_send(buf, strlen(buf));
369     if (response())
370         return;
371
372     sprintf(buf, "%s/*", src);
373     dir = FindFirstFile(buf, &fdat);
374     ok = (dir != INVALID_HANDLE_VALUE);
375     while (ok) {
376         if (strcmp(fdat.cFileName, ".") == 0 ||
377             strcmp(fdat.cFileName, "..") == 0) {
378         } else if (strlen(src) + 1 + strlen(fdat.cFileName) >=
379                    sizeof(buf)) {
380             run_err("%s/%s: Name too long", src, fdat.cFileName);
381         } else {
382             sprintf(buf, "%s/%s", src, fdat.cFileName);
383             source(buf);
384         }
385         ok = FindNextFile(dir, &fdat);
386     }
387     FindClose(dir);
388
389     sprintf(buf, "E\n");
390     ssh_send(buf, strlen(buf));
391     (void) response();
392 }
393
394 /*
395  *  Execute the sink part of the SCP protocol.
396  */
397 static void sink(char *targ)
398 {
399     char buf[2048];
400     char namebuf[2048];
401     char ch;
402     int targisdir = 0;
403     int settime = 0;
404     int exists;
405     DWORD attr;
406     HANDLE f;
407     unsigned long mtime, atime;
408     unsigned int mode;
409     unsigned long size, i;
410     int wrerror = 0;
411     unsigned long stat_bytes;
412     time_t stat_starttime, stat_lasttime;
413     char *stat_name;
414
415     attr = GetFileAttributes(targ);
416     if (attr != -1 && (attr & FILE_ATTRIBUTE_DIRECTORY) != 0)
417         targisdir = 1;
418
419     if (targetshouldbedirectory && !targisdir)
420         bump("%s: Not a directory", targ);
421
422     ssh_send("", 1);
423     while (1) {
424         settime = 0;
425         gottime:
426         if (ssh_recv(&ch, 1) <= 0)
427             return;
428         if (ch == '\n')
429             bump("Protocol error: Unexpected newline");
430         i = 0;
431         buf[i++] = ch;
432         do {
433             if (ssh_recv(&ch, 1) <= 0)
434                 bump("Lost connection");
435             buf[i++] = ch;
436         } while (i < sizeof(buf) && ch != '\n');
437         buf[i-1] = '\0';
438         switch (buf[0]) {
439           case '\01':   /* error */
440             fprintf(stderr, "%s\n", buf+1);
441             errs++;
442             continue;
443           case '\02':   /* fatal error */
444             bump("%s", buf+1);
445           case 'E':
446             ssh_send("", 1);
447             return;
448           case 'T':
449             if (sscanf(buf, "T%d %*d %d %*d",
450                        &mtime, &atime) == 2) {
451                 settime = 1;
452                 ssh_send("", 1);
453                 goto gottime;
454             }
455             bump("Protocol error: Illegal time format");
456           case 'C':
457           case 'D':
458             break;
459           default:
460             bump("Protocol error: Expected control record");
461         }
462
463         if (sscanf(buf+1, "%u %u %[^\n]", &mode, &size, namebuf) != 3)
464             bump("Protocol error: Illegal file descriptor format");
465         if (targisdir) {
466             char t[2048];
467             strcpy(t, targ);
468             if (targ[0] != '\0')
469                 strcat(t, "/");
470             strcat(t, namebuf);
471             strcpy(namebuf, t);
472         } else {
473             strcpy(namebuf, targ);
474         }
475         attr = GetFileAttributes(namebuf);
476         exists = (attr != -1);
477
478         if (buf[0] == 'D') {
479             if (exists && (attr & FILE_ATTRIBUTE_DIRECTORY) == 0) {
480                 run_err("%s: Not a directory", namebuf);
481                 continue;
482             }
483             if (!exists) {
484                 if (! CreateDirectory(namebuf, NULL)) {
485                     run_err("%s: Cannot create directory",
486                             namebuf);
487                     continue;
488                 }
489             }
490             sink(namebuf);
491             /* can we set the timestamp for directories ? */
492             continue;
493         }
494
495         f = CreateFile(namebuf, GENERIC_WRITE, 0, NULL,
496                        CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
497         if (f == INVALID_HANDLE_VALUE) {
498             run_err("%s: Cannot create file", namebuf);
499             continue;
500         }
501
502         ssh_send("", 1);
503
504         if (statistics) {
505             stat_bytes = 0;
506             stat_starttime = time(NULL);
507             stat_lasttime = 0;
508             if ((stat_name = strrchr(namebuf, '/')) == NULL)
509                 stat_name = namebuf;
510             else
511                 stat_name++;
512             if (strrchr(stat_name, '\\') != NULL)
513                 stat_name = strrchr(stat_name, '\\') + 1;
514         }
515
516         for (i = 0; i < size; i += 4096) {
517             char transbuf[4096];
518             int j, k = 4096;
519             if (i + k > size) k = size - i;
520             if (ssh_recv(transbuf, k) == 0)
521                 bump("Lost connection");
522             if (wrerror) continue;
523             if (! WriteFile(f, transbuf, k, &j, NULL) || j != k) {
524                 wrerror = 1;
525                 if (statistics)
526                     printf("\r%-25.25s | %50s\n",
527                            stat_name,
528                            "Write error.. waiting for end of file");
529                 continue;
530             }
531             if (statistics) {
532                 stat_bytes += k;
533                 if (time(NULL) > stat_lasttime ||
534                     i + k == size) {
535                     stat_lasttime = time(NULL);
536                     print_stats(stat_name, size, stat_bytes,
537                                 stat_starttime, stat_lasttime);
538                 }
539             }
540         }
541         (void) response();
542
543         if (settime) {
544             FILETIME actime, wrtime;
545             TIME_POSIX_TO_WIN(atime, actime);
546             TIME_POSIX_TO_WIN(mtime, wrtime);
547             SetFileTime(f, NULL, &actime, &wrtime);
548         }
549
550         CloseHandle(f);
551         if (wrerror) {
552             run_err("%s: Write error", namebuf);
553             continue;
554         }
555         ssh_send("", 1);
556     }
557 }
558
559 /*
560  *  We will copy local files to a remote server.
561  */
562 static void toremote(int argc, char *argv[])
563 {
564     char *src, *targ, *host, *user;
565     char *cmd;
566     int i;
567
568     targ = argv[argc-1];
569
570     /* Seperate host from filename */
571     host = targ;
572     targ = colon(targ);
573     if (targ == NULL)
574         bump("targ == NULL in toremote()");
575     *targ++ = '\0';
576     if (*targ == '\0')
577         targ = ".";
578     /* Substitute "." for emtpy target */
579
580     /* Seperate host and username */
581     user = host;
582     host = strrchr(host, '@');
583     if (host == NULL) {
584         host = user;
585         user = NULL;
586     } else {
587         *host++ = '\0';
588         if (*user == '\0')
589             user = NULL;
590     }
591
592     if (argc == 2) {
593         /* Find out if the source filespec covers multiple files
594          if so, we should set the targetshouldbedirectory flag */
595         HANDLE fh;
596         WIN32_FIND_DATA fdat;
597         if (colon(argv[0]) != NULL)
598             bump("%s: Remote to remote not supported", argv[0]);
599         fh = FindFirstFile(argv[0], &fdat);
600         if (fh == INVALID_HANDLE_VALUE)
601             bump("%s: No such file or directory\n", argv[0]);
602         if (FindNextFile(fh, &fdat))
603             targetshouldbedirectory = 1;
604         FindClose(fh);
605     }
606
607     cmd = smalloc(strlen(targ) + 100);
608     sprintf(cmd, "scp%s%s%s%s -t %s",
609             verbose ? " -v" : "",
610             recursive ? " -r" : "",
611             preserve ? " -p" : "",
612             targetshouldbedirectory ? " -d" : "",
613             targ);
614     do_cmd(host, user, cmd);
615     sfree(cmd);
616
617     (void) response();
618
619     for (i = 0; i < argc - 1; i++) {
620         HANDLE dir;
621         WIN32_FIND_DATA fdat;
622         src = argv[i];
623         if (colon(src) != NULL) {
624             fprintf(stderr,
625                     "%s: Remote to remote not supported\n", src);
626             errs++;
627             continue;
628         }
629         dir = FindFirstFile(src, &fdat);
630         if (dir == INVALID_HANDLE_VALUE) {
631             run_err("%s: No such file or directory", src);
632             continue;
633         }
634         do {
635             char *last;
636             char namebuf[2048];
637             if (strlen(src) + strlen(fdat.cFileName) >=
638                 sizeof(namebuf)) {
639                 fprintf(stderr, "%s: Name too long", src);
640                 continue;
641             }
642             strcpy(namebuf, src);
643             if ((last = strrchr(namebuf, '/')) == NULL)
644                 last = namebuf;
645             else
646                 last++;
647             if (strrchr(last, '\\') != NULL)
648                 last = strrchr(last, '\\') + 1;
649             if (last == namebuf && strrchr(namebuf, ':') != NULL)
650                 last = strchr(namebuf, ':') + 1;
651             strcpy(last, fdat.cFileName);
652             source(namebuf);
653         } while (FindNextFile(dir, &fdat));
654         FindClose(dir);
655     }
656 }
657
658 /*
659  *  We will copy files from a remote server to the local machine.
660  */
661 static void tolocal(int argc, char *argv[])
662 {
663     char *src, *targ, *host, *user;
664     char *cmd;
665
666     if (argc != 2)
667         bump("More than one remote source not supported");
668
669     src = argv[0];
670     targ = argv[1];
671
672     /* Seperate host from filename */
673     host = src;
674     src = colon(src);
675     if (src == NULL)
676         bump("Local to local copy not supported");
677     *src++ = '\0';
678     if (*src == '\0')
679         src = ".";
680     /* Substitute "." for empty filename */
681
682     /* Seperate username and hostname */
683     user = host;
684     host = strrchr(host, '@');
685     if (host == NULL) {
686         host = user;
687         user = NULL;
688     } else {
689         *host++ = '\0';
690         if (*user == '\0')
691             user = NULL;
692     }
693
694     cmd = smalloc(strlen(src) + 100);
695     sprintf(cmd, "scp%s%s%s%s -f %s",
696             verbose ? " -v" : "",
697             recursive ? " -r" : "",
698             preserve ? " -p" : "",
699             targetshouldbedirectory ? " -d" : "",
700             src);
701     do_cmd(host, user, cmd);
702     sfree(cmd);
703
704     sink(targ);
705 }
706
707 /*
708  *  Initialize the Win$ock driver.
709  */
710 static void init_winsock()
711 {
712     WORD winsock_ver;
713     WSADATA wsadata;
714
715     winsock_ver = MAKEWORD(1, 1);
716     if (WSAStartup(winsock_ver, &wsadata))
717         bump("Unable to initialise WinSock");
718     if (LOBYTE(wsadata.wVersion) != 1 ||
719         HIBYTE(wsadata.wVersion) != 1)
720         bump("WinSock version is incompatible with 1.1");
721 }
722
723 /*
724  *  Short description of parameters.
725  */
726 static void usage()
727 {
728     printf("PuTTY Secure Copy client\n");
729     printf("%s\n", ver);
730     printf("usage: scp [-p] [-q] [-r] [-v] [user@]host:source target\n");
731     printf("       scp [-p] [-q] [-r] [-v] source [source..]"
732            " [user@]host:target\n");
733     exit(1);
734 }
735
736 /*
737  *  Main program (no, really?)
738  */
739 int main(int argc, char *argv[])
740 {
741     int i;
742
743     init_winsock();
744
745     for (i = 1; i < argc; i++) {
746         if (argv[i][0] != '-')
747             break;
748         if (strcmp(argv[i], "-v") == 0)
749             verbose = 1;
750         else if (strcmp(argv[i], "-r") == 0)
751             recursive = 1;
752         else if (strcmp(argv[i], "-p") == 0)
753             preserve = 1;
754         else if (strcmp(argv[i], "-q") == 0)
755             statistics = 0;
756         else if (strcmp(argv[i], "-h") == 0 ||
757                  strcmp(argv[i], "-?") == 0)
758             usage();
759         else if (strcmp(argv[i], "--") == 0)
760         { i++; break; }
761         else
762             usage();
763     }
764     argc -= i;
765     argv += i;
766
767     if (argc < 2)
768         usage();
769     if (argc > 2)
770         targetshouldbedirectory = 1;
771
772     if (colon(argv[argc-1]) != NULL)
773         toremote(argc, argv);
774     else
775         tolocal(argc, argv);
776
777     if (connection_open) {
778         char ch;
779         ssh_send_eof();
780         ssh_recv(&ch, 1);
781     }
782     WSACleanup();
783     random_save_seed();
784
785     return (errs == 0 ? 0 : 1);
786 }
787
788 /* end */