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