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