]> andersk Git - openssh.git/blob - scp.c
change my e-mail to a portable one.
[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.43 2000/10/18 18:23:02 markus 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                                 (void) 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                                 (void) 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                 (void) sprintf(buf, "C%04o %lu %s\n",
561                              (unsigned int) (stb.st_mode & FILEMODEMASK),
562                                (unsigned long) stb.st_size,
563                                last);
564                 if (verbose_mode) {
565                         fprintf(stderr, "Sending file modes: %s", buf);
566                         fflush(stderr);
567                 }
568                 (void) atomicio(write, remout, buf, strlen(buf));
569                 if (response() < 0)
570                         goto next;
571                 if ((bp = allocbuf(&buffer, fd, 2048)) == NULL) {
572 next:                   (void) close(fd);
573                         continue;
574                 }
575                 if (showprogress) {
576                         totalbytes = stb.st_size;
577                         progressmeter(-1);
578                 }
579                 /* Keep writing after an error so that we stay sync'd up. */
580                 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
581                         amt = bp->cnt;
582                         if (i + amt > stb.st_size)
583                                 amt = stb.st_size - i;
584                         if (!haderr) {
585                                 result = atomicio(read, fd, bp->buf, amt);
586                                 if (result != amt)
587                                         haderr = result >= 0 ? EIO : errno;
588                         }
589                         if (haderr)
590                                 (void) atomicio(write, remout, bp->buf, amt);
591                         else {
592                                 result = atomicio(write, remout, bp->buf, amt);
593                                 if (result != amt)
594                                         haderr = result >= 0 ? EIO : errno;
595                                 statbytes += result;
596                         }
597                 }
598                 if (showprogress)
599                         progressmeter(1);
600
601                 if (close(fd) < 0 && !haderr)
602                         haderr = errno;
603                 if (!haderr)
604                         (void) atomicio(write, remout, "", 1);
605                 else
606                         run_err("%s: %s", name, strerror(haderr));
607                 (void) response();
608         }
609 }
610
611 void
612 rsource(name, statp)
613         char *name;
614         struct stat *statp;
615 {
616         DIR *dirp;
617         struct dirent *dp;
618         char *last, *vect[1], path[1100];
619
620         if (!(dirp = opendir(name))) {
621                 run_err("%s: %s", name, strerror(errno));
622                 return;
623         }
624         last = strrchr(name, '/');
625         if (last == 0)
626                 last = name;
627         else
628                 last++;
629         if (pflag) {
630                 (void) sprintf(path, "T%lu 0 %lu 0\n",
631                     (unsigned long) statp->st_mtime,
632                     (unsigned long) statp->st_atime);
633                 (void) atomicio(write, remout, path, strlen(path));
634                 if (response() < 0) {
635                         closedir(dirp);
636                         return;
637                 }
638         }
639         (void) sprintf(path, "D%04o %d %.1024s\n",
640             (unsigned int) (statp->st_mode & FILEMODEMASK), 0, last);
641         if (verbose_mode)
642                 fprintf(stderr, "Entering directory: %s", path);
643         (void) atomicio(write, remout, path, strlen(path));
644         if (response() < 0) {
645                 closedir(dirp);
646                 return;
647         }
648         while ((dp = readdir(dirp))) {
649                 if (dp->d_ino == 0)
650                         continue;
651                 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
652                         continue;
653                 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
654                         run_err("%s/%s: name too long", name, dp->d_name);
655                         continue;
656                 }
657                 (void) sprintf(path, "%s/%s", name, dp->d_name);
658                 vect[0] = path;
659                 source(1, vect);
660         }
661         (void) closedir(dirp);
662         (void) atomicio(write, remout, "E\n", 2);
663         (void) response();
664 }
665
666 void
667 sink(argc, argv)
668         int argc;
669         char *argv[];
670 {
671         static BUF buffer;
672         struct stat stb;
673         enum {
674                 YES, NO, DISPLAYED
675         } wrerr;
676         BUF *bp;
677         off_t i, j;
678         int amt, count, exists, first, mask, mode, ofd, omode;
679         off_t size;
680         int setimes, targisdir, wrerrno = 0;
681         char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
682         int dummy_usec;
683         struct timeval tv[2];
684
685 #define SCREWUP(str)    { why = str; goto screwup; }
686
687         setimes = targisdir = 0;
688         mask = umask(0);
689         if (!pflag)
690                 (void) umask(mask);
691         if (argc != 1) {
692                 run_err("ambiguous target");
693                 exit(1);
694         }
695         targ = *argv;
696         if (targetshouldbedirectory)
697                 verifydir(targ);
698
699         (void) atomicio(write, remout, "", 1);
700         if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
701                 targisdir = 1;
702         for (first = 1;; first = 0) {
703                 cp = buf;
704                 if (atomicio(read, remin, cp, 1) <= 0)
705                         return;
706                 if (*cp++ == '\n')
707                         SCREWUP("unexpected <newline>");
708                 do {
709                         if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
710                                 SCREWUP("lost connection");
711                         *cp++ = ch;
712                 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
713                 *cp = 0;
714
715                 if (buf[0] == '\01' || buf[0] == '\02') {
716                         if (iamremote == 0)
717                                 (void) atomicio(write, STDERR_FILENO,
718                                              buf + 1, strlen(buf + 1));
719                         if (buf[0] == '\02')
720                                 exit(1);
721                         ++errs;
722                         continue;
723                 }
724                 if (buf[0] == 'E') {
725                         (void) atomicio(write, remout, "", 1);
726                         return;
727                 }
728                 if (ch == '\n')
729                         *--cp = 0;
730
731 #define getnum(t) (t) = 0; \
732   while (*cp >= '0' && *cp <= '9') (t) = (t) * 10 + (*cp++ - '0');
733                 cp = buf;
734                 if (*cp == 'T') {
735                         setimes++;
736                         cp++;
737                         getnum(tv[1].tv_sec);
738                         if (*cp++ != ' ')
739                                 SCREWUP("mtime.sec not delimited");
740                         getnum(dummy_usec);
741                         tv[1].tv_usec = 0;
742                         if (*cp++ != ' ')
743                                 SCREWUP("mtime.usec not delimited");
744                         getnum(tv[0].tv_sec);
745                         if (*cp++ != ' ')
746                                 SCREWUP("atime.sec not delimited");
747                         getnum(dummy_usec);
748                         tv[0].tv_usec = 0;
749                         if (*cp++ != '\0')
750                                 SCREWUP("atime.usec not delimited");
751                         (void) atomicio(write, remout, "", 1);
752                         continue;
753                 }
754                 if (*cp != 'C' && *cp != 'D') {
755                         /*
756                          * Check for the case "rcp remote:foo\* local:bar".
757                          * In this case, the line "No match." can be returned
758                          * by the shell before the rcp command on the remote is
759                          * executed so the ^Aerror_message convention isn't
760                          * followed.
761                          */
762                         if (first) {
763                                 run_err("%s", cp);
764                                 exit(1);
765                         }
766                         SCREWUP("expected control record");
767                 }
768                 mode = 0;
769                 for (++cp; cp < buf + 5; cp++) {
770                         if (*cp < '0' || *cp > '7')
771                                 SCREWUP("bad mode");
772                         mode = (mode << 3) | (*cp - '0');
773                 }
774                 if (*cp++ != ' ')
775                         SCREWUP("mode not delimited");
776
777                 for (size = 0; *cp >= '0' && *cp <= '9';)
778                         size = size * 10 + (*cp++ - '0');
779                 if (*cp++ != ' ')
780                         SCREWUP("size not delimited");
781                 if (targisdir) {
782                         static char *namebuf;
783                         static int cursize;
784                         size_t need;
785
786                         need = strlen(targ) + strlen(cp) + 250;
787                         if (need > cursize)
788                                 namebuf = xmalloc(need);
789                         (void) sprintf(namebuf, "%s%s%s", targ,
790                             *targ ? "/" : "", cp);
791                         np = namebuf;
792                 } else
793                         np = targ;
794                 curfile = cp;
795                 exists = stat(np, &stb) == 0;
796                 if (buf[0] == 'D') {
797                         int mod_flag = pflag;
798                         if (exists) {
799                                 if (!S_ISDIR(stb.st_mode)) {
800                                         errno = ENOTDIR;
801                                         goto bad;
802                                 }
803                                 if (pflag)
804                                         (void) chmod(np, mode);
805                         } else {
806                                 /* Handle copying from a read-only
807                                    directory */
808                                 mod_flag = 1;
809                                 if (mkdir(np, mode | S_IRWXU) < 0)
810                                         goto bad;
811                         }
812                         vect[0] = np;
813                         sink(1, vect);
814                         if (setimes) {
815                                 setimes = 0;
816                                 if (utimes(np, tv) < 0)
817                                         run_err("%s: set times: %s",
818                                                 np, strerror(errno));
819                         }
820                         if (mod_flag)
821                                 (void) chmod(np, mode);
822                         continue;
823                 }
824                 omode = mode;
825                 mode |= S_IWRITE;
826                 if ((ofd = open(np, O_WRONLY | O_CREAT | O_TRUNC, mode)) < 0) {
827 bad:                    run_err("%s: %s", np, strerror(errno));
828                         continue;
829                 }
830                 (void) atomicio(write, remout, "", 1);
831                 if ((bp = allocbuf(&buffer, ofd, 4096)) == NULL) {
832                         (void) close(ofd);
833                         continue;
834                 }
835                 cp = bp->buf;
836                 wrerr = NO;
837
838                 if (showprogress) {
839                         totalbytes = size;
840                         progressmeter(-1);
841                 }
842                 statbytes = 0;
843                 for (count = i = 0; i < size; i += 4096) {
844                         amt = 4096;
845                         if (i + amt > size)
846                                 amt = size - i;
847                         count += amt;
848                         do {
849                                 j = read(remin, cp, amt);
850                                 if (j == -1 && (errno == EINTR || errno == EAGAIN)) {
851                                         continue;
852                                 } else if (j <= 0) {
853                                         run_err("%s", j ? strerror(errno) :
854                                                 "dropped connection");
855                                         exit(1);
856                                 }
857                                 amt -= j;
858                                 cp += j;
859                                 statbytes += j;
860                         } while (amt > 0);
861                         if (count == bp->cnt) {
862                                 /* Keep reading so we stay sync'd up. */
863                                 if (wrerr == NO) {
864                                         j = atomicio(write, ofd, bp->buf, count);
865                                         if (j != count) {
866                                                 wrerr = YES;
867                                                 wrerrno = j >= 0 ? EIO : errno;
868                                         }
869                                 }
870                                 count = 0;
871                                 cp = bp->buf;
872                         }
873                 }
874                 if (showprogress)
875                         progressmeter(1);
876                 if (count != 0 && wrerr == NO &&
877                     (j = atomicio(write, ofd, bp->buf, count)) != count) {
878                         wrerr = YES;
879                         wrerrno = j >= 0 ? EIO : errno;
880                 }
881 #if 0
882                 if (ftruncate(ofd, size)) {
883                         run_err("%s: truncate: %s", np, strerror(errno));
884                         wrerr = DISPLAYED;
885                 }
886 #endif
887                 if (pflag) {
888                         if (exists || omode != mode)
889 #ifdef HAVE_FCHMOD
890                                 if (fchmod(ofd, omode))
891 #else /* HAVE_FCHMOD */
892                                 if (chmod(np, omode))
893 #endif /* HAVE_FCHMOD */
894                                         run_err("%s: set mode: %s",
895                                                 np, strerror(errno));
896                 } else {
897                         if (!exists && omode != mode)
898 #ifdef HAVE_FCHMOD
899                                 if (fchmod(ofd, omode & ~mask))
900 #else /* HAVE_FCHMOD */
901                                 if (chmod(np, omode & ~mask))
902 #endif /* HAVE_FCHMOD */
903                                         run_err("%s: set mode: %s",
904                                                 np, strerror(errno));
905                 }
906                 if (close(ofd) == -1) {
907                         wrerr = YES;
908                         wrerrno = errno;
909                 }
910                 (void) response();
911                 if (setimes && wrerr == NO) {
912                         setimes = 0;
913                         if (utimes(np, tv) < 0) {
914                                 run_err("%s: set times: %s",
915                                         np, strerror(errno));
916                                 wrerr = DISPLAYED;
917                         }
918                 }
919                 switch (wrerr) {
920                 case YES:
921                         run_err("%s: %s", np, strerror(wrerrno));
922                         break;
923                 case NO:
924                         (void) atomicio(write, remout, "", 1);
925                         break;
926                 case DISPLAYED:
927                         break;
928                 }
929         }
930 screwup:
931         run_err("protocol error: %s", why);
932         exit(1);
933 }
934
935 int
936 response()
937 {
938         char ch, *cp, resp, rbuf[2048];
939
940         if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
941                 lostconn(0);
942
943         cp = rbuf;
944         switch (resp) {
945         case 0:         /* ok */
946                 return (0);
947         default:
948                 *cp++ = resp;
949                 /* FALLTHROUGH */
950         case 1:         /* error, followed by error msg */
951         case 2:         /* fatal error, "" */
952                 do {
953                         if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
954                                 lostconn(0);
955                         *cp++ = ch;
956                 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
957
958                 if (!iamremote)
959                         (void) atomicio(write, STDERR_FILENO, rbuf, cp - rbuf);
960                 ++errs;
961                 if (resp == 1)
962                         return (-1);
963                 exit(1);
964         }
965         /* NOTREACHED */
966 }
967
968 void
969 usage()
970 {
971         (void) fprintf(stderr, "usage: scp "
972             "[-pqrvC46] [-S ssh] [-P port] [-c cipher] [-i identity] f1 f2; or:\n"
973             "       scp [options] f1 ... fn directory\n");
974         exit(1);
975 }
976
977 void
978 run_err(const char *fmt,...)
979 {
980         static FILE *fp;
981         va_list ap;
982
983         ++errs;
984         if (fp == NULL && !(fp = fdopen(remout, "w")))
985                 return;
986         (void) fprintf(fp, "%c", 0x01);
987         (void) fprintf(fp, "scp: ");
988         va_start(ap, fmt);
989         (void) vfprintf(fp, fmt, ap);
990         va_end(ap);
991         (void) fprintf(fp, "\n");
992         (void) fflush(fp);
993
994         if (!iamremote) {
995                 va_start(ap, fmt);
996                 vfprintf(stderr, fmt, ap);
997                 va_end(ap);
998                 fprintf(stderr, "\n");
999         }
1000 }
1001
1002 char *
1003 colon(cp)
1004         char *cp;
1005 {
1006         int flag = 0;
1007
1008         if (*cp == ':')         /* Leading colon is part of file name. */
1009                 return (0);
1010         if (*cp == '[')
1011                 flag = 1;
1012
1013         for (; *cp; ++cp) {
1014                 if (*cp == '@' && *(cp+1) == '[')
1015                         flag = 1;
1016                 if (*cp == ']' && *(cp+1) == ':' && flag)
1017                         return (cp+1);
1018                 if (*cp == ':' && !flag)
1019                         return (cp);
1020                 if (*cp == '/')
1021                         return (0);
1022         }
1023         return (0);
1024 }
1025
1026 void
1027 verifydir(cp)
1028         char *cp;
1029 {
1030         struct stat stb;
1031
1032         if (!stat(cp, &stb)) {
1033                 if (S_ISDIR(stb.st_mode))
1034                         return;
1035                 errno = ENOTDIR;
1036         }
1037         run_err("%s: %s", cp, strerror(errno));
1038         exit(1);
1039 }
1040
1041 int
1042 okname(cp0)
1043         char *cp0;
1044 {
1045         int c;
1046         char *cp;
1047
1048         cp = cp0;
1049         do {
1050                 c = *cp;
1051                 if (c & 0200)
1052                         goto bad;
1053                 if (!isalpha(c) && !isdigit(c) && c != '_' && c != '-')
1054                         goto bad;
1055         } while (*++cp);
1056         return (1);
1057
1058 bad:    fprintf(stderr, "%s: invalid user name\n", cp0);
1059         return (0);
1060 }
1061
1062 BUF *
1063 allocbuf(bp, fd, blksize)
1064         BUF *bp;
1065         int fd, blksize;
1066 {
1067         size_t size;
1068 #ifdef HAVE_ST_BLKSIZE
1069         struct stat stb;
1070
1071         if (fstat(fd, &stb) < 0) {
1072                 run_err("fstat: %s", strerror(errno));
1073                 return (0);
1074         }
1075         if (stb.st_blksize == 0)
1076                 size = blksize;
1077         else
1078                 size = blksize + (stb.st_blksize - blksize % stb.st_blksize) %
1079                     stb.st_blksize;
1080 #else /* HAVE_ST_BLKSIZE */
1081         size = blksize;
1082 #endif /* HAVE_ST_BLKSIZE */
1083         if (bp->cnt >= size)
1084                 return (bp);
1085         if (bp->buf == NULL)
1086                 bp->buf = xmalloc(size);
1087         else
1088                 bp->buf = xrealloc(bp->buf, size);
1089         bp->cnt = size;
1090         return (bp);
1091 }
1092
1093 void
1094 lostconn(signo)
1095         int signo;
1096 {
1097         if (!iamremote)
1098                 fprintf(stderr, "lost connection\n");
1099         exit(1);
1100 }
1101
1102
1103 void
1104 alarmtimer(int wait)
1105 {
1106         struct itimerval itv;
1107
1108         itv.it_value.tv_sec = wait;
1109         itv.it_value.tv_usec = 0;
1110         itv.it_interval = itv.it_value;
1111         setitimer(ITIMER_REAL, &itv, NULL);
1112 }
1113
1114 void
1115 updateprogressmeter(int ignore)
1116 {
1117         int save_errno = errno;
1118
1119         progressmeter(0);
1120         errno = save_errno;
1121 }
1122
1123 int
1124 foregroundproc()
1125 {
1126         static pid_t pgrp = -1;
1127         int ctty_pgrp;
1128
1129         if (pgrp == -1)
1130                 pgrp = getpgrp();
1131
1132 #ifdef HAVE_CYGWIN
1133         /*
1134          * Cygwin only supports tcgetpgrp() for getting the controlling tty
1135          * currently.
1136          */
1137         return ((ctty_pgrp = tcgetpgrp(STDOUT_FILENO)) != -1 &&
1138                 ctty_pgrp == pgrp);
1139 #else
1140         return ((ioctl(STDOUT_FILENO, TIOCGPGRP, &ctty_pgrp) != -1 &&
1141                  ctty_pgrp == pgrp));
1142 #endif
1143 }
1144
1145 void
1146 progressmeter(int flag)
1147 {
1148         static const char prefixes[] = " KMGTP";
1149         static struct timeval lastupdate;
1150         static off_t lastsize;
1151         struct timeval now, td, wait;
1152         off_t cursize, abbrevsize;
1153         double elapsed;
1154         int ratio, barlength, i, remaining;
1155         char buf[256];
1156
1157         if (flag == -1) {
1158                 (void) gettimeofday(&start, (struct timezone *) 0);
1159                 lastupdate = start;
1160                 lastsize = 0;
1161         }
1162         if (foregroundproc() == 0)
1163                 return;
1164
1165         (void) gettimeofday(&now, (struct timezone *) 0);
1166         cursize = statbytes;
1167         if (totalbytes != 0) {
1168                 ratio = 100.0 * cursize / totalbytes;
1169                 ratio = MAX(ratio, 0);
1170                 ratio = MIN(ratio, 100);
1171         } else
1172                 ratio = 100;
1173
1174         snprintf(buf, sizeof(buf), "\r%-20.20s %3d%% ", curfile, ratio);
1175
1176         barlength = getttywidth() - 51;
1177         barlength = (barlength <= MAX_BARLENGTH)?barlength:MAX_BARLENGTH;
1178         if (barlength > 0) {
1179                 i = barlength * ratio / 100;
1180                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1181                          "|%.*s%*s|", i, BAR, barlength - i, "");
1182         }
1183         i = 0;
1184         abbrevsize = cursize;
1185         while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
1186                 i++;
1187                 abbrevsize >>= 10;
1188         }
1189         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " %5d %c%c ",
1190              (int) abbrevsize, prefixes[i], prefixes[i] == ' ' ? ' ' :
1191                  'B');
1192
1193         timersub(&now, &lastupdate, &wait);
1194         if (cursize > lastsize) {
1195                 lastupdate = now;
1196                 lastsize = cursize;
1197                 if (wait.tv_sec >= STALLTIME) {
1198                         start.tv_sec += wait.tv_sec;
1199                         start.tv_usec += wait.tv_usec;
1200                 }
1201                 wait.tv_sec = 0;
1202         }
1203         timersub(&now, &start, &td);
1204         elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
1205
1206         if (statbytes <= 0 || elapsed <= 0.0 || cursize > totalbytes) {
1207                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1208                          "   --:-- ETA");
1209         } else if (wait.tv_sec >= STALLTIME) {
1210                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1211                          " - stalled -");
1212         } else {
1213                 if (flag != 1)
1214                         remaining =
1215                             (int)(totalbytes / (statbytes / elapsed) - elapsed);
1216                 else
1217                         remaining = elapsed;
1218
1219                 i = remaining / 3600;
1220                 if (i)
1221                         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1222                             "%2d:", i);
1223                 else
1224                         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1225                             "   ");
1226                 i = remaining % 3600;
1227                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1228                     "%02d:%02d%s", i / 60, i % 60,
1229                     (flag != 1) ? " ETA" : "    ");
1230         }
1231         atomicio(write, fileno(stdout), buf, strlen(buf));
1232
1233         if (flag == -1) {
1234                 struct sigaction sa;
1235                 sa.sa_handler = updateprogressmeter;
1236                 sigemptyset((sigset_t *)&sa.sa_mask);
1237 #ifdef SA_RESTART
1238                 sa.sa_flags = SA_RESTART;
1239 #endif
1240                 sigaction(SIGALRM, &sa, NULL);
1241                 alarmtimer(1);
1242         } else if (flag == 1) {
1243                 alarmtimer(0);
1244                 atomicio(write, fileno(stdout), "\n", 1);
1245                 statbytes = 0;
1246         }
1247 }
1248
1249 int
1250 getttywidth(void)
1251 {
1252         struct winsize winsize;
1253
1254         if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) != -1)
1255                 return (winsize.ws_col ? winsize.ws_col : 80);
1256         else
1257                 return (80);
1258 }
1259
1260 void
1261 addargs(char *fmt, ...)
1262 {
1263         va_list ap;
1264         char buf[1024];
1265
1266         va_start(ap, fmt);
1267         vsnprintf(buf, sizeof(buf), fmt, ap);
1268         va_end(ap);
1269
1270         if (args.list == NULL) {
1271                 args.nalloc = 32;
1272                 args.num = 0;
1273                 args.list = xmalloc(args.nalloc * sizeof(char *));
1274         } else if (args.num+2 >= args.nalloc) {
1275                 args.nalloc *= 2;
1276                 args.list = xrealloc(args.list, args.nalloc * sizeof(char *));
1277         }
1278         args.list[args.num++] = xstrdup(buf);
1279         args.list[args.num] = NULL;
1280 }
This page took 0.151121 seconds and 5 git commands to generate.