]> andersk Git - openssh.git/blob - scp.c
Hopefully things did not get mixed around too much. It compiles under
[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.51 2001/01/21 19:05:55 markus 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) sprintf(cmd, "scp%s%s%s%s", verbose_mode ? " -v" : "",
330             iamrecursive ? " -r" : "", pflag ? " -p" : "",
331             targetshouldbedirectory ? " -d" : "");
332
333         (void) signal(SIGPIPE, lostconn);
334
335         if ((targ = colon(argv[argc - 1])))     /* Dest is remote host. */
336                 toremote(targ, argc, argv);
337         else {
338                 tolocal(argc, argv);    /* Dest is local host. */
339                 if (targetshouldbedirectory)
340                         verifydir(argv[argc - 1]);
341         }
342         exit(errs != 0);
343 }
344
345 char *
346 cleanhostname(host)
347         char *host;
348 {
349         if (*host == '[' && host[strlen(host) - 1] == ']') {
350                 host[strlen(host) - 1] = '\0';
351                 return (host + 1);
352         } else
353                 return host;
354 }
355
356 void
357 toremote(targ, argc, argv)
358         char *targ, *argv[];
359         int argc;
360 {
361         int i, len;
362         char *bp, *host, *src, *suser, *thost, *tuser;
363
364         *targ++ = 0;
365         if (*targ == 0)
366                 targ = ".";
367
368         if ((thost = strchr(argv[argc - 1], '@'))) {
369                 /* user@host */
370                 *thost++ = 0;
371                 tuser = argv[argc - 1];
372                 if (*tuser == '\0')
373                         tuser = NULL;
374                 else if (!okname(tuser))
375                         exit(1);
376         } else {
377                 thost = argv[argc - 1];
378                 tuser = NULL;
379         }
380
381         for (i = 0; i < argc - 1; i++) {
382                 src = colon(argv[i]);
383                 if (src) {      /* remote to remote */
384                         *src++ = 0;
385                         if (*src == 0)
386                                 src = ".";
387                         host = strchr(argv[i], '@');
388                         len = strlen(ssh_program) + strlen(argv[i]) +
389                             strlen(src) + (tuser ? strlen(tuser) : 0) +
390                             strlen(thost) + strlen(targ) + CMDNEEDS + 32;
391                         bp = xmalloc(len);
392                         if (host) {
393                                 *host++ = 0;
394                                 host = cleanhostname(host);
395                                 suser = argv[i];
396                                 if (*suser == '\0')
397                                         suser = pwd->pw_name;
398                                 else if (!okname(suser))
399                                         continue;
400                                 sprintf(bp,
401                                     "%s%s -x -o'FallBackToRsh no' -n -l %s %s %s %s '%s%s%s:%s'",
402                                     ssh_program, verbose_mode ? " -v" : "",
403                                     suser, host, cmd, src,
404                                     tuser ? tuser : "", tuser ? "@" : "",
405                                     thost, targ);
406                         } else {
407                                 host = cleanhostname(argv[i]);
408                                 sprintf(bp,
409                                     "exec %s%s -x -o'FallBackToRsh no' -n %s %s %s '%s%s%s:%s'",
410                                     ssh_program, verbose_mode ? " -v" : "",
411                                     host, cmd, src,
412                                     tuser ? tuser : "", tuser ? "@" : "",
413                                     thost, targ);
414                         }
415                         if (verbose_mode)
416                                 fprintf(stderr, "Executing: %s\n", bp);
417                         (void) system(bp);
418                         (void) xfree(bp);
419                 } else {        /* local to remote */
420                         if (remin == -1) {
421                                 len = strlen(targ) + CMDNEEDS + 20;
422                                 bp = xmalloc(len);
423                                 (void) sprintf(bp, "%s -t %s", cmd, targ);
424                                 host = cleanhostname(thost);
425                                 if (do_cmd(host, tuser, bp, &remin,
426                                     &remout, argc) < 0)
427                                         exit(1);
428                                 if (response() < 0)
429                                         exit(1);
430                                 (void) xfree(bp);
431                         }
432                         source(1, argv + i);
433                 }
434         }
435 }
436
437 void
438 tolocal(argc, argv)
439         int argc;
440         char *argv[];
441 {
442         int i, len;
443         char *bp, *host, *src, *suser;
444
445         for (i = 0; i < argc - 1; i++) {
446                 if (!(src = colon(argv[i]))) {  /* Local to local. */
447                         len = strlen(_PATH_CP) + strlen(argv[i]) +
448                             strlen(argv[argc - 1]) + 20;
449                         bp = xmalloc(len);
450                         (void) sprintf(bp, "exec %s%s%s %s %s", _PATH_CP,
451                             iamrecursive ? " -r" : "", pflag ? " -p" : "",
452                             argv[i], argv[argc - 1]);
453                         if (verbose_mode)
454                                 fprintf(stderr, "Executing: %s\n", bp);
455                         if (system(bp))
456                                 ++errs;
457                         (void) xfree(bp);
458                         continue;
459                 }
460                 *src++ = 0;
461                 if (*src == 0)
462                         src = ".";
463                 if ((host = strchr(argv[i], '@')) == NULL) {
464                         host = argv[i];
465                         suser = NULL;
466                 } else {
467                         *host++ = 0;
468                         suser = argv[i];
469                         if (*suser == '\0')
470                                 suser = pwd->pw_name;
471                         else if (!okname(suser))
472                                 continue;
473                 }
474                 host = cleanhostname(host);
475                 len = strlen(src) + CMDNEEDS + 20;
476                 bp = xmalloc(len);
477                 (void) sprintf(bp, "%s -f %s", cmd, src);
478                 if (do_cmd(host, suser, bp, &remin, &remout, argc) < 0) {
479                         (void) xfree(bp);
480                         ++errs;
481                         continue;
482                 }
483                 xfree(bp);
484                 sink(1, argv + argc - 1);
485                 (void) close(remin);
486                 remin = remout = -1;
487         }
488 }
489
490 void
491 source(argc, argv)
492         int argc;
493         char *argv[];
494 {
495         struct stat stb;
496         static BUF buffer;
497         BUF *bp;
498         off_t i;
499         int amt, fd, haderr, indx, result;
500         char *last, *name, buf[2048];
501
502         for (indx = 0; indx < argc; ++indx) {
503                 name = argv[indx];
504                 statbytes = 0;
505                 if ((fd = open(name, O_RDONLY, 0)) < 0)
506                         goto syserr;
507                 if (fstat(fd, &stb) < 0) {
508 syserr:                 run_err("%s: %s", name, strerror(errno));
509                         goto next;
510                 }
511                 switch (stb.st_mode & S_IFMT) {
512                 case S_IFREG:
513                         break;
514                 case S_IFDIR:
515                         if (iamrecursive) {
516                                 rsource(name, &stb);
517                                 goto next;
518                         }
519                         /* FALLTHROUGH */
520                 default:
521                         run_err("%s: not a regular file", name);
522                         goto next;
523                 }
524                 if ((last = strrchr(name, '/')) == NULL)
525                         last = name;
526                 else
527                         ++last;
528                 curfile = last;
529                 if (pflag) {
530                         /*
531                          * Make it compatible with possible future
532                          * versions expecting microseconds.
533                          */
534                         (void) sprintf(buf, "T%lu 0 %lu 0\n",
535                             (u_long) stb.st_mtime,
536                             (u_long) stb.st_atime);
537                         (void) atomicio(write, remout, buf, strlen(buf));
538                         if (response() < 0)
539                                 goto next;
540                 }
541 #define FILEMODEMASK    (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
542                 sprintf(buf, "C%04o %lu %s\n",
543                     (u_int) (stb.st_mode & FILEMODEMASK),
544                     (u_long) stb.st_size, last);
545                 if (verbose_mode) {
546                         fprintf(stderr, "Sending file modes: %s", buf);
547                         fflush(stderr);
548                 }
549                 (void) atomicio(write, remout, buf, strlen(buf));
550                 if (response() < 0)
551                         goto next;
552                 if ((bp = allocbuf(&buffer, fd, 2048)) == NULL) {
553 next:                   (void) close(fd);
554                         continue;
555                 }
556                 if (showprogress) {
557                         totalbytes = stb.st_size;
558                         progressmeter(-1);
559                 }
560                 /* Keep writing after an error so that we stay sync'd up. */
561                 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
562                         amt = bp->cnt;
563                         if (i + amt > stb.st_size)
564                                 amt = stb.st_size - i;
565                         if (!haderr) {
566                                 result = atomicio(read, fd, bp->buf, amt);
567                                 if (result != amt)
568                                         haderr = result >= 0 ? EIO : errno;
569                         }
570                         if (haderr)
571                                 (void) atomicio(write, remout, bp->buf, amt);
572                         else {
573                                 result = atomicio(write, remout, bp->buf, amt);
574                                 if (result != amt)
575                                         haderr = result >= 0 ? EIO : errno;
576                                 statbytes += result;
577                         }
578                 }
579                 if (showprogress)
580                         progressmeter(1);
581
582                 if (close(fd) < 0 && !haderr)
583                         haderr = errno;
584                 if (!haderr)
585                         (void) atomicio(write, remout, "", 1);
586                 else
587                         run_err("%s: %s", name, strerror(haderr));
588                 (void) response();
589         }
590 }
591
592 void
593 rsource(name, statp)
594         char *name;
595         struct stat *statp;
596 {
597         DIR *dirp;
598         struct dirent *dp;
599         char *last, *vect[1], path[1100];
600
601         if (!(dirp = opendir(name))) {
602                 run_err("%s: %s", name, strerror(errno));
603                 return;
604         }
605         last = strrchr(name, '/');
606         if (last == 0)
607                 last = name;
608         else
609                 last++;
610         if (pflag) {
611                 (void) sprintf(path, "T%lu 0 %lu 0\n",
612                     (u_long) statp->st_mtime,
613                     (u_long) statp->st_atime);
614                 (void) atomicio(write, remout, path, strlen(path));
615                 if (response() < 0) {
616                         closedir(dirp);
617                         return;
618                 }
619         }
620         (void) sprintf(path, "D%04o %d %.1024s\n",
621             (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
622         if (verbose_mode)
623                 fprintf(stderr, "Entering directory: %s", path);
624         (void) atomicio(write, remout, path, strlen(path));
625         if (response() < 0) {
626                 closedir(dirp);
627                 return;
628         }
629         while ((dp = readdir(dirp))) {
630                 if (dp->d_ino == 0)
631                         continue;
632                 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
633                         continue;
634                 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
635                         run_err("%s/%s: name too long", name, dp->d_name);
636                         continue;
637                 }
638                 (void) sprintf(path, "%s/%s", name, dp->d_name);
639                 vect[0] = path;
640                 source(1, vect);
641         }
642         (void) closedir(dirp);
643         (void) atomicio(write, remout, "E\n", 2);
644         (void) response();
645 }
646
647 void
648 sink(argc, argv)
649         int argc;
650         char *argv[];
651 {
652         static BUF buffer;
653         struct stat stb;
654         enum {
655                 YES, NO, DISPLAYED
656         } wrerr;
657         BUF *bp;
658         off_t i, j;
659         int amt, count, exists, first, mask, mode, ofd, omode;
660         off_t size;
661         int setimes, targisdir, wrerrno = 0;
662         char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
663         int dummy_usec;
664         struct timeval tv[2];
665
666 #define SCREWUP(str)    { why = str; goto screwup; }
667
668         setimes = targisdir = 0;
669         mask = umask(0);
670         if (!pflag)
671                 (void) umask(mask);
672         if (argc != 1) {
673                 run_err("ambiguous target");
674                 exit(1);
675         }
676         targ = *argv;
677         if (targetshouldbedirectory)
678                 verifydir(targ);
679
680         (void) atomicio(write, remout, "", 1);
681         if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
682                 targisdir = 1;
683         for (first = 1;; first = 0) {
684                 cp = buf;
685                 if (atomicio(read, remin, cp, 1) <= 0)
686                         return;
687                 if (*cp++ == '\n')
688                         SCREWUP("unexpected <newline>");
689                 do {
690                         if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
691                                 SCREWUP("lost connection");
692                         *cp++ = ch;
693                 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
694                 *cp = 0;
695
696                 if (buf[0] == '\01' || buf[0] == '\02') {
697                         if (iamremote == 0)
698                                 (void) atomicio(write, STDERR_FILENO,
699                                     buf + 1, strlen(buf + 1));
700                         if (buf[0] == '\02')
701                                 exit(1);
702                         ++errs;
703                         continue;
704                 }
705                 if (buf[0] == 'E') {
706                         (void) atomicio(write, remout, "", 1);
707                         return;
708                 }
709                 if (ch == '\n')
710                         *--cp = 0;
711
712 #define getnum(t) (t) = 0; \
713   while (*cp >= '0' && *cp <= '9') (t) = (t) * 10 + (*cp++ - '0');
714                 cp = buf;
715                 if (*cp == 'T') {
716                         setimes++;
717                         cp++;
718                         getnum(tv[1].tv_sec);
719                         if (*cp++ != ' ')
720                                 SCREWUP("mtime.sec not delimited");
721                         getnum(dummy_usec);
722                         tv[1].tv_usec = 0;
723                         if (*cp++ != ' ')
724                                 SCREWUP("mtime.usec not delimited");
725                         getnum(tv[0].tv_sec);
726                         if (*cp++ != ' ')
727                                 SCREWUP("atime.sec not delimited");
728                         getnum(dummy_usec);
729                         tv[0].tv_usec = 0;
730                         if (*cp++ != '\0')
731                                 SCREWUP("atime.usec not delimited");
732                         (void) atomicio(write, remout, "", 1);
733                         continue;
734                 }
735                 if (*cp != 'C' && *cp != 'D') {
736                         /*
737                          * Check for the case "rcp remote:foo\* local:bar".
738                          * In this case, the line "No match." can be returned
739                          * by the shell before the rcp command on the remote is
740                          * executed so the ^Aerror_message convention isn't
741                          * followed.
742                          */
743                         if (first) {
744                                 run_err("%s", cp);
745                                 exit(1);
746                         }
747                         SCREWUP("expected control record");
748                 }
749                 mode = 0;
750                 for (++cp; cp < buf + 5; cp++) {
751                         if (*cp < '0' || *cp > '7')
752                                 SCREWUP("bad mode");
753                         mode = (mode << 3) | (*cp - '0');
754                 }
755                 if (*cp++ != ' ')
756                         SCREWUP("mode not delimited");
757
758                 for (size = 0; *cp >= '0' && *cp <= '9';)
759                         size = size * 10 + (*cp++ - '0');
760                 if (*cp++ != ' ')
761                         SCREWUP("size not delimited");
762                 if (targisdir) {
763                         static char *namebuf;
764                         static int cursize;
765                         size_t need;
766
767                         need = strlen(targ) + strlen(cp) + 250;
768                         if (need > cursize)
769                                 namebuf = xmalloc(need);
770                         (void) sprintf(namebuf, "%s%s%s", targ,
771                             *targ ? "/" : "", cp);
772                         np = namebuf;
773                 } else
774                         np = targ;
775                 curfile = cp;
776                 exists = stat(np, &stb) == 0;
777                 if (buf[0] == 'D') {
778                         int mod_flag = pflag;
779                         if (exists) {
780                                 if (!S_ISDIR(stb.st_mode)) {
781                                         errno = ENOTDIR;
782                                         goto bad;
783                                 }
784                                 if (pflag)
785                                         (void) chmod(np, mode);
786                         } else {
787                                 /* Handle copying from a read-only
788                                    directory */
789                                 mod_flag = 1;
790                                 if (mkdir(np, mode | S_IRWXU) < 0)
791                                         goto bad;
792                         }
793                         vect[0] = np;
794                         sink(1, vect);
795                         if (setimes) {
796                                 setimes = 0;
797                                 if (utimes(np, tv) < 0)
798                                         run_err("%s: set times: %s",
799                                                 np, strerror(errno));
800                         }
801                         if (mod_flag)
802                                 (void) chmod(np, mode);
803                         continue;
804                 }
805                 omode = mode;
806                 mode |= S_IWRITE;
807                 if ((ofd = open(np, O_WRONLY | O_CREAT | O_TRUNC, mode)) < 0) {
808 bad:                    run_err("%s: %s", np, strerror(errno));
809                         continue;
810                 }
811                 (void) atomicio(write, remout, "", 1);
812                 if ((bp = allocbuf(&buffer, ofd, 4096)) == NULL) {
813                         (void) close(ofd);
814                         continue;
815                 }
816                 cp = bp->buf;
817                 wrerr = NO;
818
819                 if (showprogress) {
820                         totalbytes = size;
821                         progressmeter(-1);
822                 }
823                 statbytes = 0;
824                 for (count = i = 0; i < size; i += 4096) {
825                         amt = 4096;
826                         if (i + amt > size)
827                                 amt = size - i;
828                         count += amt;
829                         do {
830                                 j = read(remin, cp, amt);
831                                 if (j == -1 && (errno == EINTR || errno == EAGAIN)) {
832                                         continue;
833                                 } else if (j <= 0) {
834                                         run_err("%s", j ? strerror(errno) :
835                                                 "dropped connection");
836                                         exit(1);
837                                 }
838                                 amt -= j;
839                                 cp += j;
840                                 statbytes += j;
841                         } while (amt > 0);
842                         if (count == bp->cnt) {
843                                 /* Keep reading so we stay sync'd up. */
844                                 if (wrerr == NO) {
845                                         j = atomicio(write, ofd, bp->buf, count);
846                                         if (j != count) {
847                                                 wrerr = YES;
848                                                 wrerrno = j >= 0 ? EIO : errno;
849                                         }
850                                 }
851                                 count = 0;
852                                 cp = bp->buf;
853                         }
854                 }
855                 if (showprogress)
856                         progressmeter(1);
857                 if (count != 0 && wrerr == NO &&
858                     (j = atomicio(write, ofd, bp->buf, count)) != count) {
859                         wrerr = YES;
860                         wrerrno = j >= 0 ? EIO : errno;
861                 }
862 #if 0
863                 if (ftruncate(ofd, size)) {
864                         run_err("%s: truncate: %s", np, strerror(errno));
865                         wrerr = DISPLAYED;
866                 }
867 #endif
868                 if (pflag) {
869                         if (exists || omode != mode)
870 #ifdef HAVE_FCHMOD
871                                 if (fchmod(ofd, omode))
872 #else /* HAVE_FCHMOD */
873                                 if (chmod(np, omode))
874 #endif /* HAVE_FCHMOD */
875                                         run_err("%s: set mode: %s",
876                                                 np, strerror(errno));
877                 } else {
878                         if (!exists && omode != mode)
879 #ifdef HAVE_FCHMOD
880                                 if (fchmod(ofd, omode & ~mask))
881 #else /* HAVE_FCHMOD */
882                                 if (chmod(np, omode & ~mask))
883 #endif /* HAVE_FCHMOD */
884                                         run_err("%s: set mode: %s",
885                                                 np, strerror(errno));
886                 }
887                 if (close(ofd) == -1) {
888                         wrerr = YES;
889                         wrerrno = errno;
890                 }
891                 (void) response();
892                 if (setimes && wrerr == NO) {
893                         setimes = 0;
894                         if (utimes(np, tv) < 0) {
895                                 run_err("%s: set times: %s",
896                                         np, strerror(errno));
897                                 wrerr = DISPLAYED;
898                         }
899                 }
900                 switch (wrerr) {
901                 case YES:
902                         run_err("%s: %s", np, strerror(wrerrno));
903                         break;
904                 case NO:
905                         (void) atomicio(write, remout, "", 1);
906                         break;
907                 case DISPLAYED:
908                         break;
909                 }
910         }
911 screwup:
912         run_err("protocol error: %s", why);
913         exit(1);
914 }
915
916 int
917 response()
918 {
919         char ch, *cp, resp, rbuf[2048];
920
921         if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
922                 lostconn(0);
923
924         cp = rbuf;
925         switch (resp) {
926         case 0:         /* ok */
927                 return (0);
928         default:
929                 *cp++ = resp;
930                 /* FALLTHROUGH */
931         case 1:         /* error, followed by error msg */
932         case 2:         /* fatal error, "" */
933                 do {
934                         if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
935                                 lostconn(0);
936                         *cp++ = ch;
937                 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
938
939                 if (!iamremote)
940                         (void) atomicio(write, STDERR_FILENO, rbuf, cp - rbuf);
941                 ++errs;
942                 if (resp == 1)
943                         return (-1);
944                 exit(1);
945         }
946         /* NOTREACHED */
947 }
948
949 void
950 usage()
951 {
952         (void) fprintf(stderr, "usage: scp "
953             "[-pqrvC46] [-S ssh] [-P port] [-c cipher] [-i identity] f1 f2; or:\n"
954             "       scp [options] f1 ... fn directory\n");
955         exit(1);
956 }
957
958 void
959 run_err(const char *fmt,...)
960 {
961         static FILE *fp;
962         va_list ap;
963
964         ++errs;
965         if (fp == NULL && !(fp = fdopen(remout, "w")))
966                 return;
967         (void) fprintf(fp, "%c", 0x01);
968         (void) fprintf(fp, "scp: ");
969         va_start(ap, fmt);
970         (void) vfprintf(fp, fmt, ap);
971         va_end(ap);
972         (void) fprintf(fp, "\n");
973         (void) fflush(fp);
974
975         if (!iamremote) {
976                 va_start(ap, fmt);
977                 vfprintf(stderr, fmt, ap);
978                 va_end(ap);
979                 fprintf(stderr, "\n");
980         }
981 }
982
983 char *
984 colon(cp)
985         char *cp;
986 {
987         int flag = 0;
988
989         if (*cp == ':')         /* Leading colon is part of file name. */
990                 return (0);
991         if (*cp == '[')
992                 flag = 1;
993
994         for (; *cp; ++cp) {
995                 if (*cp == '@' && *(cp+1) == '[')
996                         flag = 1;
997                 if (*cp == ']' && *(cp+1) == ':' && flag)
998                         return (cp+1);
999                 if (*cp == ':' && !flag)
1000                         return (cp);
1001                 if (*cp == '/')
1002                         return (0);
1003         }
1004         return (0);
1005 }
1006
1007 void
1008 verifydir(cp)
1009         char *cp;
1010 {
1011         struct stat stb;
1012
1013         if (!stat(cp, &stb)) {
1014                 if (S_ISDIR(stb.st_mode))
1015                         return;
1016                 errno = ENOTDIR;
1017         }
1018         run_err("%s: %s", cp, strerror(errno));
1019         exit(1);
1020 }
1021
1022 int
1023 okname(cp0)
1024         char *cp0;
1025 {
1026         int c;
1027         char *cp;
1028
1029         cp = cp0;
1030         do {
1031                 c = *cp;
1032                 if (c & 0200)
1033                         goto bad;
1034                 if (!isalpha(c) && !isdigit(c) &&
1035                     c != '_' && c != '-' && c != '.' && c != '+')
1036                         goto bad;
1037         } while (*++cp);
1038         return (1);
1039
1040 bad:    fprintf(stderr, "%s: invalid user name\n", cp0);
1041         return (0);
1042 }
1043
1044 BUF *
1045 allocbuf(bp, fd, blksize)
1046         BUF *bp;
1047         int fd, blksize;
1048 {
1049         size_t size;
1050 #ifdef HAVE_ST_BLKSIZE
1051         struct stat stb;
1052
1053         if (fstat(fd, &stb) < 0) {
1054                 run_err("fstat: %s", strerror(errno));
1055                 return (0);
1056         }
1057         if (stb.st_blksize == 0)
1058                 size = blksize;
1059         else
1060                 size = blksize + (stb.st_blksize - blksize % stb.st_blksize) %
1061                     stb.st_blksize;
1062 #else /* HAVE_ST_BLKSIZE */
1063         size = blksize;
1064 #endif /* HAVE_ST_BLKSIZE */
1065         if (bp->cnt >= size)
1066                 return (bp);
1067         if (bp->buf == NULL)
1068                 bp->buf = xmalloc(size);
1069         else
1070                 bp->buf = xrealloc(bp->buf, size);
1071         bp->cnt = size;
1072         return (bp);
1073 }
1074
1075 void
1076 lostconn(signo)
1077         int signo;
1078 {
1079         if (!iamremote)
1080                 fprintf(stderr, "lost connection\n");
1081         exit(1);
1082 }
1083
1084
1085 void
1086 alarmtimer(int wait)
1087 {
1088         struct itimerval itv;
1089
1090         itv.it_value.tv_sec = wait;
1091         itv.it_value.tv_usec = 0;
1092         itv.it_interval = itv.it_value;
1093         setitimer(ITIMER_REAL, &itv, NULL);
1094 }
1095
1096 void
1097 updateprogressmeter(int ignore)
1098 {
1099         int save_errno = errno;
1100
1101         progressmeter(0);
1102         errno = save_errno;
1103 }
1104
1105 int
1106 foregroundproc()
1107 {
1108         static pid_t pgrp = -1;
1109         int ctty_pgrp;
1110
1111         if (pgrp == -1)
1112                 pgrp = getpgrp();
1113
1114 #ifdef HAVE_CYGWIN
1115         /*
1116          * Cygwin only supports tcgetpgrp() for getting the controlling tty
1117          * currently.
1118          */
1119         return ((ctty_pgrp = tcgetpgrp(STDOUT_FILENO)) != -1 &&
1120                 ctty_pgrp == pgrp);
1121 #else
1122         return ((ioctl(STDOUT_FILENO, TIOCGPGRP, &ctty_pgrp) != -1 &&
1123                  ctty_pgrp == pgrp));
1124 #endif
1125 }
1126
1127 void
1128 progressmeter(int flag)
1129 {
1130         static const char prefixes[] = " KMGTP";
1131         static struct timeval lastupdate;
1132         static off_t lastsize;
1133         struct timeval now, td, wait;
1134         off_t cursize, abbrevsize;
1135         double elapsed;
1136         int ratio, barlength, i, remaining;
1137         char buf[256];
1138
1139         if (flag == -1) {
1140                 (void) gettimeofday(&start, (struct timezone *) 0);
1141                 lastupdate = start;
1142                 lastsize = 0;
1143         }
1144         if (foregroundproc() == 0)
1145                 return;
1146
1147         (void) gettimeofday(&now, (struct timezone *) 0);
1148         cursize = statbytes;
1149         if (totalbytes != 0) {
1150                 ratio = 100.0 * cursize / totalbytes;
1151                 ratio = MAX(ratio, 0);
1152                 ratio = MIN(ratio, 100);
1153         } else
1154                 ratio = 100;
1155
1156         snprintf(buf, sizeof(buf), "\r%-20.20s %3d%% ", curfile, ratio);
1157
1158         barlength = getttywidth() - 51;
1159         barlength = (barlength <= MAX_BARLENGTH)?barlength:MAX_BARLENGTH;
1160         if (barlength > 0) {
1161                 i = barlength * ratio / 100;
1162                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1163                          "|%.*s%*s|", i, BAR, barlength - i, "");
1164         }
1165         i = 0;
1166         abbrevsize = cursize;
1167         while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
1168                 i++;
1169                 abbrevsize >>= 10;
1170         }
1171         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " %5d %c%c ",
1172             (int) abbrevsize, prefixes[i], prefixes[i] == ' ' ? ' ' : 'B');
1173
1174         timersub(&now, &lastupdate, &wait);
1175         if (cursize > lastsize) {
1176                 lastupdate = now;
1177                 lastsize = cursize;
1178                 if (wait.tv_sec >= STALLTIME) {
1179                         start.tv_sec += wait.tv_sec;
1180                         start.tv_usec += wait.tv_usec;
1181                 }
1182                 wait.tv_sec = 0;
1183         }
1184         timersub(&now, &start, &td);
1185         elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
1186
1187         if (flag != 1 &&
1188             (statbytes <= 0 || elapsed <= 0.0 || cursize > totalbytes)) {
1189                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1190                     "   --:-- ETA");
1191         } else if (wait.tv_sec >= STALLTIME) {
1192                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1193                     " - stalled -");
1194         } else {
1195                 if (flag != 1)
1196                         remaining = (int)(totalbytes / (statbytes / elapsed) -
1197                             elapsed);
1198                 else
1199                         remaining = elapsed;
1200
1201                 i = remaining / 3600;
1202                 if (i)
1203                         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1204                             "%2d:", i);
1205                 else
1206                         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1207                             "   ");
1208                 i = remaining % 3600;
1209                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1210                     "%02d:%02d%s", i / 60, i % 60,
1211                     (flag != 1) ? " ETA" : "    ");
1212         }
1213         atomicio(write, fileno(stdout), buf, strlen(buf));
1214
1215         if (flag == -1) {
1216                 struct sigaction sa;
1217                 sa.sa_handler = updateprogressmeter;
1218                 sigemptyset((sigset_t *)&sa.sa_mask);
1219 #ifdef SA_RESTART
1220                 sa.sa_flags = SA_RESTART;
1221 #endif
1222                 sigaction(SIGALRM, &sa, NULL);
1223                 alarmtimer(1);
1224         } else if (flag == 1) {
1225                 alarmtimer(0);
1226                 atomicio(write, fileno(stdout), "\n", 1);
1227                 statbytes = 0;
1228         }
1229 }
1230
1231 int
1232 getttywidth(void)
1233 {
1234         struct winsize winsize;
1235
1236         if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) != -1)
1237                 return (winsize.ws_col ? winsize.ws_col : 80);
1238         else
1239                 return (80);
1240 }
1241
1242 void
1243 addargs(char *fmt, ...)
1244 {
1245         va_list ap;
1246         char buf[1024];
1247
1248         va_start(ap, fmt);
1249         vsnprintf(buf, sizeof(buf), fmt, ap);
1250         va_end(ap);
1251
1252         if (args.list == NULL) {
1253                 args.nalloc = 32;
1254                 args.num = 0;
1255                 args.list = xmalloc(args.nalloc * sizeof(char *));
1256         } else if (args.num+2 >= args.nalloc) {
1257                 args.nalloc *= 2;
1258                 args.list = xrealloc(args.list, args.nalloc * sizeof(char *));
1259         }
1260         args.list[args.num++] = xstrdup(buf);
1261         args.list[args.num] = NULL;
1262 }
This page took 0.160183 seconds and 5 git commands to generate.