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