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