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