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