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