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