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