]> andersk Git - openssh.git/blob - scp.c
- (djm) OpenBSD CVS sync:
[openssh.git] / scp.c
1 /*
2  * scp - secure remote copy.  This is basically patched BSD rcp which
3  * uses ssh to do the data transfer (instead of using rcmd).
4  *
5  * NOTE: This version should NOT be suid root.  (This uses ssh to
6  * do the transfer and ssh has the necessary privileges.)
7  *
8  * 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi>
9  *
10  * As far as I am concerned, the code I have written for this software
11  * can be used freely for any purpose.  Any derived versions of this
12  * software must be clearly marked as such, and if the derived work is
13  * incompatible with the protocol description in the RFC file, it must be
14  * called by a name other than "ssh" or "Secure Shell".
15  */
16 /*
17  * Copyright (c) 1999 Theo de Raadt. All rights reserved.
18  * Copyright (c) 1999 Aaron Campbell. All rights reserved.
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  * 1. Redistributions of source code must retain the above copyright
24  *    notice, this list of conditions and the following disclaimer.
25  * 2. Redistributions in binary form must reproduce the above copyright
26  *    notice, this list of conditions and the following disclaimer in the
27  *    documentation and/or other materials provided with the distribution.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
30  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
31  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
32  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
33  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
34  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
38  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39  */
40
41 /*
42  * Parts from:
43  *
44  * Copyright (c) 1983, 1990, 1992, 1993, 1995
45  *      The Regents of the University of California.  All rights reserved.
46  *
47  * Redistribution and use in source and binary forms, with or without
48  * modification, are permitted provided that the following conditions
49  * are met:
50  * 1. Redistributions of source code must retain the above copyright
51  *    notice, this list of conditions and the following disclaimer.
52  * 2. Redistributions in binary form must reproduce the above copyright
53  *    notice, this list of conditions and the following disclaimer in the
54  *    documentation and/or other materials provided with the distribution.
55  * 3. All advertising materials mentioning features or use of this software
56  *    must display the following acknowledgement:
57  *      This product includes software developed by the University of
58  *      California, Berkeley and its contributors.
59  * 4. Neither the name of the University nor the names of its contributors
60  *    may be used to endorse or promote products derived from this software
61  *    without specific prior written permission.
62  *
63  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
64  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
65  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
66  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
67  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
68  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
69  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
70  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
71  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
72  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
73  * SUCH DAMAGE.
74  *
75  */
76
77 #include "includes.h"
78 RCSID("$OpenBSD: scp.c,v 1.40 2000/09/21 11:11:42 markus Exp $");
79
80 #include "ssh.h"
81 #include "xmalloc.h"
82
83 #define _PATH_CP "cp"
84
85 /* For progressmeter() -- number of seconds before xfer considered "stalled" */
86 #define STALLTIME       5
87
88 /* Progress meter bar */
89 #define BAR \
90         "************************************************************"\
91         "************************************************************"\
92         "************************************************************"\
93         "************************************************************"
94 #define MAX_BARLENGTH (sizeof(BAR) - 1)
95
96 /* Visual statistics about files as they are transferred. */
97 void progressmeter(int);
98
99 /* Returns width of the terminal (for progress meter calculations). */
100 int getttywidth(void);
101 int do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout, int argc);
102
103 /* Time a transfer started. */
104 static struct timeval start;
105
106 /* Number of bytes of current file transferred so far. */
107 volatile unsigned long statbytes;
108
109 /* Total size of current file. */
110 off_t totalbytes = 0;
111
112 /* Name of current file being transferred. */
113 char *curfile;
114
115 /* This is set to non-zero if IPv4 is desired. */
116 int IPv4 = 0;
117
118 /* This is set to non-zero if IPv6 is desired. */
119 int IPv6 = 0;
120
121 /* This is set to non-zero to enable verbose mode. */
122 int verbose_mode = 0;
123
124 /* This is set to non-zero if compression is desired. */
125 int compress_flag = 0;
126
127 /* This is set to zero if the progressmeter is not desired. */
128 int showprogress = 1;
129
130 /* This is set to non-zero if running in batch mode (that is, password
131    and passphrase queries are not allowed). */
132 int batchmode = 0;
133
134 /* This is set to the cipher type string if given on the command line. */
135 char *cipher = NULL;
136
137 /* This is set to the RSA authentication identity file name if given on
138    the command line. */
139 char *identity = NULL;
140
141 /* This is the port to use in contacting the remote site (is non-NULL). */
142 char *port = NULL;
143
144 /* This is the program to execute for the secured connection. ("ssh" or -S) */
145 char *ssh_program = SSH_PROGRAM;
146
147 /*
148  * This function executes the given command as the specified user on the
149  * given host.  This returns < 0 if execution fails, and >= 0 otherwise. This
150  * assigns the input and output file descriptors on success.
151  */
152
153 int
154 do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout, int argc)
155 {
156         int pin[2], pout[2], reserved[2];
157
158         if (verbose_mode)
159                 fprintf(stderr, "Executing: host %s, user %s, command %s\n",
160                     host, remuser ? remuser : "(unspecified)", cmd);
161
162         /*
163          * Reserve two descriptors so that the real pipes won't get
164          * descriptors 0 and 1 because that will screw up dup2 below.
165          */
166         pipe(reserved);
167
168         /* Create a socket pair for communicating with ssh. */
169         if (pipe(pin) < 0)
170                 fatal("pipe: %s", strerror(errno));
171         if (pipe(pout) < 0)
172                 fatal("pipe: %s", strerror(errno));
173
174         /* Free the reserved descriptors. */
175         close(reserved[0]);
176         close(reserved[1]);
177
178         /* For a child to execute the command on the remote host using ssh. */
179         if (fork() == 0) {
180                 char *args[100];        /* XXX careful */
181                 unsigned int i;
182
183                 /* Child. */
184                 close(pin[1]);
185                 close(pout[0]);
186                 dup2(pin[0], 0);
187                 dup2(pout[1], 1);
188                 close(pin[0]);
189                 close(pout[1]);
190
191                 i = 0;
192                 args[i++] = ssh_program;
193                 args[i++] = "-x";
194                 args[i++] = "-oFallBackToRsh no";
195                 if (IPv4)
196                         args[i++] = "-4";
197                 if (IPv6)
198                         args[i++] = "-6";
199                 if (verbose_mode)
200                         args[i++] = "-v";
201                 if (compress_flag)
202                         args[i++] = "-C";
203                 if (batchmode)
204                         args[i++] = "-oBatchMode yes";
205                 if (cipher != NULL) {
206                         args[i++] = "-c";
207                         args[i++] = cipher;
208                 }
209                 if (identity != NULL) {
210                         args[i++] = "-i";
211                         args[i++] = identity;
212                 }
213                 if (port != NULL) {
214                         args[i++] = "-p";
215                         args[i++] = port;
216                 }
217                 if (remuser != NULL) {
218                         args[i++] = "-l";
219                         args[i++] = remuser;
220                 }
221                 args[i++] = host;
222                 args[i++] = cmd;
223                 args[i++] = NULL;
224
225                 execvp(ssh_program, args);
226                 perror(ssh_program);
227                 exit(1);
228         }
229         /* Parent.  Close the other side, and return the local side. */
230         close(pin[0]);
231         *fdout = pin[1];
232         close(pout[1]);
233         *fdin = pout[0];
234         return 0;
235 }
236
237 void
238 fatal(const char *fmt,...)
239 {
240         va_list ap;
241         char buf[1024];
242
243         va_start(ap, fmt);
244         vsnprintf(buf, sizeof(buf), fmt, ap);
245         va_end(ap);
246         fprintf(stderr, "%s\n", buf);
247         exit(255);
248 }
249
250 typedef struct {
251         int cnt;
252         char *buf;
253 } BUF;
254
255 extern int iamremote;
256
257 BUF *allocbuf(BUF *, int, int);
258 char *colon(char *);
259 void lostconn(int);
260 void nospace(void);
261 int okname(char *);
262 void run_err(const char *,...);
263 void verifydir(char *);
264
265 struct passwd *pwd;
266 uid_t userid;
267 int errs, remin, remout;
268 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
269
270 #define CMDNEEDS        64
271 char cmd[CMDNEEDS];             /* must hold "rcp -r -p -d\0" */
272
273 int response(void);
274 void rsource(char *, struct stat *);
275 void sink(int, char *[]);
276 void source(int, char *[]);
277 void tolocal(int, char *[]);
278 void toremote(char *, int, char *[]);
279 void usage(void);
280
281 int
282 main(argc, argv)
283         int argc;
284         char *argv[];
285 {
286         int ch, fflag, tflag;
287         char *targ;
288         extern char *optarg;
289         extern int optind;
290
291         fflag = tflag = 0;
292         while ((ch = getopt(argc, argv, "dfprtvBCc:i:P:q46S:")) != EOF)
293                 switch (ch) {
294                 /* User-visible flags. */
295                 case '4':
296                         IPv4 = 1;
297                         break;
298                 case '6':
299                         IPv6 = 1;
300                         break;
301                 case 'p':
302                         pflag = 1;
303                         break;
304                 case 'P':
305                         port = optarg;
306                         break;
307                 case 'r':
308                         iamrecursive = 1;
309                         break;
310                 case 'S':
311                         ssh_program = optarg;
312                         break;
313
314                 /* Server options. */
315                 case 'd':
316                         targetshouldbedirectory = 1;
317                         break;
318                 case 'f':       /* "from" */
319                         iamremote = 1;
320                         fflag = 1;
321                         break;
322                 case 't':       /* "to" */
323                         iamremote = 1;
324                         tflag = 1;
325                         break;
326                 case 'c':
327                         cipher = optarg;
328                         break;
329                 case 'i':
330                         identity = optarg;
331                         break;
332                 case 'v':
333                         verbose_mode = 1;
334                         break;
335                 case 'B':
336                         batchmode = 1;
337                         break;
338                 case 'C':
339                         compress_flag = 1;
340                         break;
341                 case 'q':
342                         showprogress = 0;
343                         break;
344                 case '?':
345                 default:
346                         usage();
347                 }
348         argc -= optind;
349         argv += optind;
350
351         if ((pwd = getpwuid(userid = getuid())) == NULL)
352                 fatal("unknown user %d", (int) userid);
353
354         if (!isatty(STDERR_FILENO))
355                 showprogress = 0;
356
357         remin = STDIN_FILENO;
358         remout = STDOUT_FILENO;
359
360         if (fflag) {    
361                 /* Follow "protocol", send data. */
362                 (void) response();
363                 source(argc, argv);
364                 exit(errs != 0);
365         }
366         if (tflag) {
367                 /* Receive data. */
368                 sink(argc, argv);
369                 exit(errs != 0);
370         }
371         if (argc < 2)
372                 usage();
373         if (argc > 2)
374                 targetshouldbedirectory = 1;
375
376         remin = remout = -1;
377         /* Command to be executed on remote system using "ssh". */
378         (void) sprintf(cmd, "scp%s%s%s%s", verbose_mode ? " -v" : "",
379             iamrecursive ? " -r" : "", pflag ? " -p" : "",
380             targetshouldbedirectory ? " -d" : "");
381
382         (void) signal(SIGPIPE, lostconn);
383
384         if ((targ = colon(argv[argc - 1])))     /* Dest is remote host. */
385                 toremote(targ, argc, argv);
386         else {
387                 tolocal(argc, argv);    /* Dest is local host. */
388                 if (targetshouldbedirectory)
389                         verifydir(argv[argc - 1]);
390         }
391         exit(errs != 0);
392 }
393
394 char *
395 cleanhostname(host)
396         char *host;
397 {
398         if (*host == '[' && host[strlen(host) - 1] == ']') {
399                 host[strlen(host) - 1] = '\0';
400                 return (host + 1);
401         } else
402                 return host;
403 }
404
405 void
406 toremote(targ, argc, argv)
407         char *targ, *argv[];
408         int argc;
409 {
410         int i, len;
411         char *bp, *host, *src, *suser, *thost, *tuser;
412
413         *targ++ = 0;
414         if (*targ == 0)
415                 targ = ".";
416
417         if ((thost = strchr(argv[argc - 1], '@'))) {
418                 /* user@host */
419                 *thost++ = 0;
420                 tuser = argv[argc - 1];
421                 if (*tuser == '\0')
422                         tuser = NULL;
423                 else if (!okname(tuser))
424                         exit(1);
425         } else {
426                 thost = argv[argc - 1];
427                 tuser = NULL;
428         }
429
430         for (i = 0; i < argc - 1; i++) {
431                 src = colon(argv[i]);
432                 if (src) {      /* remote to remote */
433                         *src++ = 0;
434                         if (*src == 0)
435                                 src = ".";
436                         host = strchr(argv[i], '@');
437                         len = strlen(ssh_program) + strlen(argv[i]) +
438                             strlen(src) + (tuser ? strlen(tuser) : 0) +
439                             strlen(thost) + strlen(targ) + CMDNEEDS + 32;
440                         bp = xmalloc(len);
441                         if (host) {
442                                 *host++ = 0;
443                                 host = cleanhostname(host);
444                                 suser = argv[i];
445                                 if (*suser == '\0')
446                                         suser = pwd->pw_name;
447                                 else if (!okname(suser))
448                                         continue;
449                                 (void) sprintf(bp,
450                                     "%s%s -x -o'FallBackToRsh no' -n -l %s %s %s %s '%s%s%s:%s'",
451                                      ssh_program, verbose_mode ? " -v" : "",
452                                      suser, host, cmd, src,
453                                      tuser ? tuser : "", tuser ? "@" : "",
454                                      thost, targ);
455                         } else {
456                                 host = cleanhostname(argv[i]);
457                                 (void) sprintf(bp,
458                                     "exec %s%s -x -o'FallBackToRsh no' -n %s %s %s '%s%s%s:%s'",
459                                      ssh_program, verbose_mode ? " -v" : "",
460                                      host, cmd, src,
461                                      tuser ? tuser : "", tuser ? "@" : "",
462                                      thost, targ);
463                         }
464                         if (verbose_mode)
465                                 fprintf(stderr, "Executing: %s\n", bp);
466                         (void) system(bp);
467                         (void) xfree(bp);
468                 } else {        /* local to remote */
469                         if (remin == -1) {
470                                 len = strlen(targ) + CMDNEEDS + 20;
471                                 bp = xmalloc(len);
472                                 (void) sprintf(bp, "%s -t %s", cmd, targ);
473                                 host = cleanhostname(thost);
474                                 if (do_cmd(host, tuser, bp, &remin,
475                                     &remout, argc) < 0)
476                                         exit(1);
477                                 if (response() < 0)
478                                         exit(1);
479                                 (void) xfree(bp);
480                         }
481                         source(1, argv + i);
482                 }
483         }
484 }
485
486 void
487 tolocal(argc, argv)
488         int argc;
489         char *argv[];
490 {
491         int i, len;
492         char *bp, *host, *src, *suser;
493
494         for (i = 0; i < argc - 1; i++) {
495                 if (!(src = colon(argv[i]))) {  /* Local to local. */
496                         len = strlen(_PATH_CP) + strlen(argv[i]) +
497                             strlen(argv[argc - 1]) + 20;
498                         bp = xmalloc(len);
499                         (void) sprintf(bp, "exec %s%s%s %s %s", _PATH_CP,
500                             iamrecursive ? " -r" : "", pflag ? " -p" : "",
501                             argv[i], argv[argc - 1]);
502                         if (verbose_mode)
503                                 fprintf(stderr, "Executing: %s\n", bp);
504                         if (system(bp))
505                                 ++errs;
506                         (void) xfree(bp);
507                         continue;
508                 }
509                 *src++ = 0;
510                 if (*src == 0)
511                         src = ".";
512                 if ((host = strchr(argv[i], '@')) == NULL) {
513                         host = argv[i];
514                         suser = NULL;
515                 } else {
516                         *host++ = 0;
517                         suser = argv[i];
518                         if (*suser == '\0')
519                                 suser = pwd->pw_name;
520                         else if (!okname(suser))
521                                 continue;
522                 }
523                 host = cleanhostname(host);
524                 len = strlen(src) + CMDNEEDS + 20;
525                 bp = xmalloc(len);
526                 (void) sprintf(bp, "%s -f %s", cmd, src);
527                 if (do_cmd(host, suser, bp, &remin, &remout, argc) < 0) {
528                         (void) xfree(bp);
529                         ++errs;
530                         continue;
531                 }
532                 xfree(bp);
533                 sink(1, argv + argc - 1);
534                 (void) close(remin);
535                 remin = remout = -1;
536         }
537 }
538
539 void
540 source(argc, argv)
541         int argc;
542         char *argv[];
543 {
544         struct stat stb;
545         static BUF buffer;
546         BUF *bp;
547         off_t i;
548         int amt, fd, haderr, indx, result;
549         char *last, *name, buf[2048];
550
551         for (indx = 0; indx < argc; ++indx) {
552                 name = argv[indx];
553                 statbytes = 0;
554                 if ((fd = open(name, O_RDONLY, 0)) < 0)
555                         goto syserr;
556                 if (fstat(fd, &stb) < 0) {
557 syserr:                 run_err("%s: %s", name, strerror(errno));
558                         goto next;
559                 }
560                 switch (stb.st_mode & S_IFMT) {
561                 case S_IFREG:
562                         break;
563                 case S_IFDIR:
564                         if (iamrecursive) {
565                                 rsource(name, &stb);
566                                 goto next;
567                         }
568                         /* FALLTHROUGH */
569                 default:
570                         run_err("%s: not a regular file", name);
571                         goto next;
572                 }
573                 if ((last = strrchr(name, '/')) == NULL)
574                         last = name;
575                 else
576                         ++last;
577                 curfile = last;
578                 if (pflag) {
579                         /*
580                          * Make it compatible with possible future
581                          * versions expecting microseconds.
582                          */
583                         (void) sprintf(buf, "T%lu 0 %lu 0\n",
584                             (unsigned long) stb.st_mtime,
585                             (unsigned long) stb.st_atime);
586                         (void) atomicio(write, remout, buf, strlen(buf));
587                         if (response() < 0)
588                                 goto next;
589                 }
590 #define FILEMODEMASK    (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
591                 (void) sprintf(buf, "C%04o %lu %s\n",
592                              (unsigned int) (stb.st_mode & FILEMODEMASK),
593                                (unsigned long) stb.st_size,
594                                last);
595                 if (verbose_mode) {
596                         fprintf(stderr, "Sending file modes: %s", buf);
597                         fflush(stderr);
598                 }
599                 (void) atomicio(write, remout, buf, strlen(buf));
600                 if (response() < 0)
601                         goto next;
602                 if ((bp = allocbuf(&buffer, fd, 2048)) == NULL) {
603 next:                   (void) close(fd);
604                         continue;
605                 }
606                 if (showprogress) {
607                         totalbytes = stb.st_size;
608                         progressmeter(-1);
609                 }
610                 /* Keep writing after an error so that we stay sync'd up. */
611                 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
612                         amt = bp->cnt;
613                         if (i + amt > stb.st_size)
614                                 amt = stb.st_size - i;
615                         if (!haderr) {
616                                 result = atomicio(read, fd, bp->buf, amt);
617                                 if (result != amt)
618                                         haderr = result >= 0 ? EIO : errno;
619                         }
620                         if (haderr)
621                                 (void) atomicio(write, remout, bp->buf, amt);
622                         else {
623                                 result = atomicio(write, remout, bp->buf, amt);
624                                 if (result != amt)
625                                         haderr = result >= 0 ? EIO : errno;
626                                 statbytes += result;
627                         }
628                 }
629                 if (showprogress)
630                         progressmeter(1);
631
632                 if (close(fd) < 0 && !haderr)
633                         haderr = errno;
634                 if (!haderr)
635                         (void) atomicio(write, remout, "", 1);
636                 else
637                         run_err("%s: %s", name, strerror(haderr));
638                 (void) response();
639         }
640 }
641
642 void
643 rsource(name, statp)
644         char *name;
645         struct stat *statp;
646 {
647         DIR *dirp;
648         struct dirent *dp;
649         char *last, *vect[1], path[1100];
650
651         if (!(dirp = opendir(name))) {
652                 run_err("%s: %s", name, strerror(errno));
653                 return;
654         }
655         last = strrchr(name, '/');
656         if (last == 0)
657                 last = name;
658         else
659                 last++;
660         if (pflag) {
661                 (void) sprintf(path, "T%lu 0 %lu 0\n",
662                     (unsigned long) statp->st_mtime,
663                     (unsigned long) statp->st_atime);
664                 (void) atomicio(write, remout, path, strlen(path));
665                 if (response() < 0) {
666                         closedir(dirp);
667                         return;
668                 }
669         }
670         (void) sprintf(path, "D%04o %d %.1024s\n",
671             (unsigned int) (statp->st_mode & FILEMODEMASK), 0, last);
672         if (verbose_mode)
673                 fprintf(stderr, "Entering directory: %s", path);
674         (void) atomicio(write, remout, path, strlen(path));
675         if (response() < 0) {
676                 closedir(dirp);
677                 return;
678         }
679         while ((dp = readdir(dirp))) {
680                 if (dp->d_ino == 0)
681                         continue;
682                 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
683                         continue;
684                 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
685                         run_err("%s/%s: name too long", name, dp->d_name);
686                         continue;
687                 }
688                 (void) sprintf(path, "%s/%s", name, dp->d_name);
689                 vect[0] = path;
690                 source(1, vect);
691         }
692         (void) closedir(dirp);
693         (void) atomicio(write, remout, "E\n", 2);
694         (void) response();
695 }
696
697 void
698 sink(argc, argv)
699         int argc;
700         char *argv[];
701 {
702         static BUF buffer;
703         struct stat stb;
704         enum {
705                 YES, NO, DISPLAYED
706         } wrerr;
707         BUF *bp;
708         off_t i, j;
709         int amt, count, exists, first, mask, mode, ofd, omode;
710         off_t size;
711         int setimes, targisdir, wrerrno = 0;
712         char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
713         int dummy_usec;
714         struct timeval tv[2];
715
716 #define SCREWUP(str)    { why = str; goto screwup; }
717
718         setimes = targisdir = 0;
719         mask = umask(0);
720         if (!pflag)
721                 (void) umask(mask);
722         if (argc != 1) {
723                 run_err("ambiguous target");
724                 exit(1);
725         }
726         targ = *argv;
727         if (targetshouldbedirectory)
728                 verifydir(targ);
729
730         (void) atomicio(write, remout, "", 1);
731         if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
732                 targisdir = 1;
733         for (first = 1;; first = 0) {
734                 cp = buf;
735                 if (atomicio(read, remin, cp, 1) <= 0)
736                         return;
737                 if (*cp++ == '\n')
738                         SCREWUP("unexpected <newline>");
739                 do {
740                         if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
741                                 SCREWUP("lost connection");
742                         *cp++ = ch;
743                 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
744                 *cp = 0;
745
746                 if (buf[0] == '\01' || buf[0] == '\02') {
747                         if (iamremote == 0)
748                                 (void) atomicio(write, STDERR_FILENO,
749                                              buf + 1, strlen(buf + 1));
750                         if (buf[0] == '\02')
751                                 exit(1);
752                         ++errs;
753                         continue;
754                 }
755                 if (buf[0] == 'E') {
756                         (void) atomicio(write, remout, "", 1);
757                         return;
758                 }
759                 if (ch == '\n')
760                         *--cp = 0;
761
762 #define getnum(t) (t) = 0; \
763   while (*cp >= '0' && *cp <= '9') (t) = (t) * 10 + (*cp++ - '0');
764                 cp = buf;
765                 if (*cp == 'T') {
766                         setimes++;
767                         cp++;
768                         getnum(tv[1].tv_sec);
769                         if (*cp++ != ' ')
770                                 SCREWUP("mtime.sec not delimited");
771                         getnum(dummy_usec);
772                         tv[1].tv_usec = 0;
773                         if (*cp++ != ' ')
774                                 SCREWUP("mtime.usec not delimited");
775                         getnum(tv[0].tv_sec);
776                         if (*cp++ != ' ')
777                                 SCREWUP("atime.sec not delimited");
778                         getnum(dummy_usec);
779                         tv[0].tv_usec = 0;
780                         if (*cp++ != '\0')
781                                 SCREWUP("atime.usec not delimited");
782                         (void) atomicio(write, remout, "", 1);
783                         continue;
784                 }
785                 if (*cp != 'C' && *cp != 'D') {
786                         /*
787                          * Check for the case "rcp remote:foo\* local:bar".
788                          * In this case, the line "No match." can be returned
789                          * by the shell before the rcp command on the remote is
790                          * executed so the ^Aerror_message convention isn't
791                          * followed.
792                          */
793                         if (first) {
794                                 run_err("%s", cp);
795                                 exit(1);
796                         }
797                         SCREWUP("expected control record");
798                 }
799                 mode = 0;
800                 for (++cp; cp < buf + 5; cp++) {
801                         if (*cp < '0' || *cp > '7')
802                                 SCREWUP("bad mode");
803                         mode = (mode << 3) | (*cp - '0');
804                 }
805                 if (*cp++ != ' ')
806                         SCREWUP("mode not delimited");
807
808                 for (size = 0; *cp >= '0' && *cp <= '9';)
809                         size = size * 10 + (*cp++ - '0');
810                 if (*cp++ != ' ')
811                         SCREWUP("size not delimited");
812                 if (targisdir) {
813                         static char *namebuf;
814                         static int cursize;
815                         size_t need;
816
817                         need = strlen(targ) + strlen(cp) + 250;
818                         if (need > cursize)
819                                 namebuf = xmalloc(need);
820                         (void) sprintf(namebuf, "%s%s%s", targ,
821                             *targ ? "/" : "", cp);
822                         np = namebuf;
823                 } else
824                         np = targ;
825                 curfile = cp;
826                 exists = stat(np, &stb) == 0;
827                 if (buf[0] == 'D') {
828                         int mod_flag = pflag;
829                         if (exists) {
830                                 if (!S_ISDIR(stb.st_mode)) {
831                                         errno = ENOTDIR;
832                                         goto bad;
833                                 }
834                                 if (pflag)
835                                         (void) chmod(np, mode);
836                         } else {
837                                 /* Handle copying from a read-only
838                                    directory */
839                                 mod_flag = 1;
840                                 if (mkdir(np, mode | S_IRWXU) < 0)
841                                         goto bad;
842                         }
843                         vect[0] = np;
844                         sink(1, vect);
845                         if (setimes) {
846                                 setimes = 0;
847                                 if (utimes(np, tv) < 0)
848                                         run_err("%s: set times: %s",
849                                                 np, strerror(errno));
850                         }
851                         if (mod_flag)
852                                 (void) chmod(np, mode);
853                         continue;
854                 }
855                 omode = mode;
856                 mode |= S_IWRITE;
857                 if ((ofd = open(np, O_WRONLY | O_CREAT | O_TRUNC, mode)) < 0) {
858 bad:                    run_err("%s: %s", np, strerror(errno));
859                         continue;
860                 }
861                 (void) atomicio(write, remout, "", 1);
862                 if ((bp = allocbuf(&buffer, ofd, 4096)) == NULL) {
863                         (void) close(ofd);
864                         continue;
865                 }
866                 cp = bp->buf;
867                 wrerr = NO;
868
869                 if (showprogress) {
870                         totalbytes = size;
871                         progressmeter(-1);
872                 }
873                 statbytes = 0;
874                 for (count = i = 0; i < size; i += 4096) {
875                         amt = 4096;
876                         if (i + amt > size)
877                                 amt = size - i;
878                         count += amt;
879                         do {
880                                 j = atomicio(read, remin, cp, amt);
881                                 if (j <= 0) {
882                                         run_err("%s", j ? strerror(errno) :
883                                                 "dropped connection");
884                                         exit(1);
885                                 }
886                                 amt -= j;
887                                 cp += j;
888                                 statbytes += j;
889                         } while (amt > 0);
890                         if (count == bp->cnt) {
891                                 /* Keep reading so we stay sync'd up. */
892                                 if (wrerr == NO) {
893                                         j = atomicio(write, ofd, bp->buf, count);
894                                         if (j != count) {
895                                                 wrerr = YES;
896                                                 wrerrno = j >= 0 ? EIO : errno;
897                                         }
898                                 }
899                                 count = 0;
900                                 cp = bp->buf;
901                         }
902                 }
903                 if (showprogress)
904                         progressmeter(1);
905                 if (count != 0 && wrerr == NO &&
906                     (j = atomicio(write, ofd, bp->buf, count)) != count) {
907                         wrerr = YES;
908                         wrerrno = j >= 0 ? EIO : errno;
909                 }
910 #if 0
911                 if (ftruncate(ofd, size)) {
912                         run_err("%s: truncate: %s", np, strerror(errno));
913                         wrerr = DISPLAYED;
914                 }
915 #endif
916                 if (pflag) {
917                         if (exists || omode != mode)
918                                 if (fchmod(ofd, omode))
919                                         run_err("%s: set mode: %s",
920                                                 np, strerror(errno));
921                 } else {
922                         if (!exists && omode != mode)
923                                 if (fchmod(ofd, omode & ~mask))
924                                         run_err("%s: set mode: %s",
925                                                 np, strerror(errno));
926                 }
927                 if (close(ofd) == -1) {
928                         wrerr = YES;
929                         wrerrno = errno;
930                 }
931                 (void) response();
932                 if (setimes && wrerr == NO) {
933                         setimes = 0;
934                         if (utimes(np, tv) < 0) {
935                                 run_err("%s: set times: %s",
936                                         np, strerror(errno));
937                                 wrerr = DISPLAYED;
938                         }
939                 }
940                 switch (wrerr) {
941                 case YES:
942                         run_err("%s: %s", np, strerror(wrerrno));
943                         break;
944                 case NO:
945                         (void) atomicio(write, remout, "", 1);
946                         break;
947                 case DISPLAYED:
948                         break;
949                 }
950         }
951 screwup:
952         run_err("protocol error: %s", why);
953         exit(1);
954 }
955
956 int
957 response()
958 {
959         char ch, *cp, resp, rbuf[2048];
960
961         if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
962                 lostconn(0);
963
964         cp = rbuf;
965         switch (resp) {
966         case 0:         /* ok */
967                 return (0);
968         default:
969                 *cp++ = resp;
970                 /* FALLTHROUGH */
971         case 1:         /* error, followed by error msg */
972         case 2:         /* fatal error, "" */
973                 do {
974                         if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
975                                 lostconn(0);
976                         *cp++ = ch;
977                 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
978
979                 if (!iamremote)
980                         (void) atomicio(write, STDERR_FILENO, rbuf, cp - rbuf);
981                 ++errs;
982                 if (resp == 1)
983                         return (-1);
984                 exit(1);
985         }
986         /* NOTREACHED */
987 }
988
989 void
990 usage()
991 {
992         (void) fprintf(stderr, "usage: scp "
993             "[-pqrvC46] [-S ssh] [-P port] [-c cipher] [-i identity] f1 f2; or:\n"
994             "       scp [options] f1 ... fn directory\n");
995         exit(1);
996 }
997
998 void
999 run_err(const char *fmt,...)
1000 {
1001         static FILE *fp;
1002         va_list ap;
1003
1004         ++errs;
1005         if (fp == NULL && !(fp = fdopen(remout, "w")))
1006                 return;
1007         (void) fprintf(fp, "%c", 0x01);
1008         (void) fprintf(fp, "scp: ");
1009         va_start(ap, fmt);
1010         (void) vfprintf(fp, fmt, ap);
1011         va_end(ap);
1012         (void) fprintf(fp, "\n");
1013         (void) fflush(fp);
1014
1015         if (!iamremote) {
1016                 va_start(ap, fmt);
1017                 vfprintf(stderr, fmt, ap);
1018                 va_end(ap);
1019                 fprintf(stderr, "\n");
1020         }
1021 }
1022
1023 char *
1024 colon(cp)
1025         char *cp;
1026 {
1027         int flag = 0;
1028
1029         if (*cp == ':')         /* Leading colon is part of file name. */
1030                 return (0);
1031         if (*cp == '[')
1032                 flag = 1;
1033
1034         for (; *cp; ++cp) {
1035                 if (*cp == '@' && *(cp+1) == '[')
1036                         flag = 1;
1037                 if (*cp == ']' && *(cp+1) == ':' && flag)
1038                         return (cp+1);
1039                 if (*cp == ':' && !flag)
1040                         return (cp);
1041                 if (*cp == '/')
1042                         return (0);
1043         }
1044         return (0);
1045 }
1046
1047 void
1048 verifydir(cp)
1049         char *cp;
1050 {
1051         struct stat stb;
1052
1053         if (!stat(cp, &stb)) {
1054                 if (S_ISDIR(stb.st_mode))
1055                         return;
1056                 errno = ENOTDIR;
1057         }
1058         run_err("%s: %s", cp, strerror(errno));
1059         exit(1);
1060 }
1061
1062 int
1063 okname(cp0)
1064         char *cp0;
1065 {
1066         int c;
1067         char *cp;
1068
1069         cp = cp0;
1070         do {
1071                 c = *cp;
1072                 if (c & 0200)
1073                         goto bad;
1074                 if (!isalpha(c) && !isdigit(c) && c != '_' && c != '-')
1075                         goto bad;
1076         } while (*++cp);
1077         return (1);
1078
1079 bad:    fprintf(stderr, "%s: invalid user name\n", cp0);
1080         return (0);
1081 }
1082
1083 BUF *
1084 allocbuf(bp, fd, blksize)
1085         BUF *bp;
1086         int fd, blksize;
1087 {
1088         size_t size;
1089         struct stat stb;
1090
1091         if (fstat(fd, &stb) < 0) {
1092                 run_err("fstat: %s", strerror(errno));
1093                 return (0);
1094         }
1095         if (stb.st_blksize == 0)
1096                 size = blksize;
1097         else
1098                 size = blksize + (stb.st_blksize - blksize % stb.st_blksize) %
1099                     stb.st_blksize;
1100         if (bp->cnt >= size)
1101                 return (bp);
1102         if (bp->buf == NULL)
1103                 bp->buf = xmalloc(size);
1104         else
1105                 bp->buf = xrealloc(bp->buf, size);
1106         bp->cnt = size;
1107         return (bp);
1108 }
1109
1110 void
1111 lostconn(signo)
1112         int signo;
1113 {
1114         if (!iamremote)
1115                 fprintf(stderr, "lost connection\n");
1116         exit(1);
1117 }
1118
1119
1120 void
1121 alarmtimer(int wait)
1122 {
1123         struct itimerval itv;
1124
1125         itv.it_value.tv_sec = wait;
1126         itv.it_value.tv_usec = 0;
1127         itv.it_interval = itv.it_value;
1128         setitimer(ITIMER_REAL, &itv, NULL);
1129 }
1130
1131 void
1132 updateprogressmeter(int ignore)
1133 {
1134         int save_errno = errno;
1135
1136         progressmeter(0);
1137         errno = save_errno;
1138 }
1139
1140 int
1141 foregroundproc()
1142 {
1143         static pid_t pgrp = -1;
1144         int ctty_pgrp;
1145
1146         if (pgrp == -1)
1147                 pgrp = getpgrp();
1148
1149 #ifdef HAVE_CYGWIN
1150         /*
1151          * Cygwin only supports tcgetpgrp() for getting the controlling tty
1152          * currently.
1153          */
1154         return ((ctty_pgrp = tcgetpgrp(STDOUT_FILENO)) != -1 &&
1155                 ctty_pgrp == pgrp);
1156 #else
1157         return ((ioctl(STDOUT_FILENO, TIOCGPGRP, &ctty_pgrp) != -1 &&
1158                  ctty_pgrp == pgrp));
1159 #endif
1160 }
1161
1162 void
1163 progressmeter(int flag)
1164 {
1165         static const char prefixes[] = " KMGTP";
1166         static struct timeval lastupdate;
1167         static off_t lastsize;
1168         struct timeval now, td, wait;
1169         off_t cursize, abbrevsize;
1170         double elapsed;
1171         int ratio, barlength, i, remaining;
1172         char buf[256];
1173
1174         if (flag == -1) {
1175                 (void) gettimeofday(&start, (struct timezone *) 0);
1176                 lastupdate = start;
1177                 lastsize = 0;
1178         }
1179         if (foregroundproc() == 0)
1180                 return;
1181
1182         (void) gettimeofday(&now, (struct timezone *) 0);
1183         cursize = statbytes;
1184         if (totalbytes != 0) {
1185                 ratio = 100.0 * cursize / totalbytes;
1186                 ratio = MAX(ratio, 0);
1187                 ratio = MIN(ratio, 100);
1188         } else
1189                 ratio = 100;
1190
1191         snprintf(buf, sizeof(buf), "\r%-20.20s %3d%% ", curfile, ratio);
1192
1193         barlength = getttywidth() - 51;
1194         barlength = (barlength <= MAX_BARLENGTH)?barlength:MAX_BARLENGTH;
1195         if (barlength > 0) {
1196                 i = barlength * ratio / 100;
1197                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1198                          "|%.*s%*s|", i, BAR, barlength - i, "");
1199         }
1200         i = 0;
1201         abbrevsize = cursize;
1202         while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
1203                 i++;
1204                 abbrevsize >>= 10;
1205         }
1206         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " %5d %c%c ",
1207              (int) abbrevsize, prefixes[i], prefixes[i] == ' ' ? ' ' :
1208                  'B');
1209
1210         timersub(&now, &lastupdate, &wait);
1211         if (cursize > lastsize) {
1212                 lastupdate = now;
1213                 lastsize = cursize;
1214                 if (wait.tv_sec >= STALLTIME) {
1215                         start.tv_sec += wait.tv_sec;
1216                         start.tv_usec += wait.tv_usec;
1217                 }
1218                 wait.tv_sec = 0;
1219         }
1220         timersub(&now, &start, &td);
1221         elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
1222
1223         if (statbytes <= 0 || elapsed <= 0.0 || cursize > totalbytes) {
1224                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1225                          "   --:-- ETA");
1226         } else if (wait.tv_sec >= STALLTIME) {
1227                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1228                          " - stalled -");
1229         } else {
1230                 if (flag != 1)
1231                         remaining =
1232                             (int)(totalbytes / (statbytes / elapsed) - elapsed);
1233                 else
1234                         remaining = elapsed;
1235
1236                 i = remaining / 3600;
1237                 if (i)
1238                         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1239                             "%2d:", i);
1240                 else
1241                         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1242                             "   ");
1243                 i = remaining % 3600;
1244                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1245                     "%02d:%02d%s", i / 60, i % 60,
1246                     (flag != 1) ? " ETA" : "    ");
1247         }
1248         atomicio(write, fileno(stdout), buf, strlen(buf));
1249
1250         if (flag == -1) {
1251                 struct sigaction sa;
1252                 sa.sa_handler = updateprogressmeter;
1253                 sigemptyset((sigset_t *)&sa.sa_mask);
1254 #ifdef SA_RESTART
1255                 sa.sa_flags = SA_RESTART;
1256 #endif
1257                 sigaction(SIGALRM, &sa, NULL);
1258                 alarmtimer(1);
1259         } else if (flag == 1) {
1260                 alarmtimer(0);
1261                 atomicio(write, fileno(stdout), "\n", 1);
1262                 statbytes = 0;
1263         }
1264 }
1265
1266 int
1267 getttywidth(void)
1268 {
1269         struct winsize winsize;
1270
1271         if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) != -1)
1272                 return (winsize.ws_col ? winsize.ws_col : 80);
1273         else
1274                 return (80);
1275 }
This page took 0.136505 seconds and 5 git commands to generate.