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