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