]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - bin/rcp/rcp.c
This commit was generated by cvs2svn to compensate for changes in r95504,
[FreeBSD/FreeBSD.git] / bin / rcp / rcp.c
1 /*
2  * Copyright (c) 1983, 1990, 1992, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 #ifndef lint
35 static char const copyright[] =
36 "@(#) Copyright (c) 1983, 1990, 1992, 1993\n\
37         The Regents of the University of California.  All rights reserved.\n";
38 #endif /* not lint */
39
40 #ifndef lint
41 #if 0
42 static char sccsid[] = "@(#)rcp.c       8.2 (Berkeley) 4/2/94";
43 #endif
44 static const char rcsid[] =
45   "$FreeBSD$";
46 #endif /* not lint */
47
48 #include <sys/param.h>
49 #include <sys/stat.h>
50 #include <sys/time.h>
51 #include <sys/socket.h>
52 #include <netinet/in.h>
53 #include <netinet/in_systm.h>
54 #include <netinet/ip.h>
55
56 #include <ctype.h>
57 #include <dirent.h>
58 #include <err.h>
59 #include <errno.h>
60 #include <fcntl.h>
61 #include <libutil.h>
62 #include <limits.h>
63 #include <netdb.h>
64 #include <pwd.h>
65 #include <signal.h>
66 #include <stdio.h>
67 #include <stdlib.h>
68 #include <string.h>
69 #include <string.h>
70 #include <unistd.h>
71
72 #include "pathnames.h"
73 #include "extern.h"
74
75 #ifdef KERBEROS
76 #include <openssl/des.h>
77 #include <krb.h>
78 #include "bsd_locl.h"
79
80 char    dst_realm_buf[REALM_SZ];
81 char    *dest_realm = NULL;
82 int     use_kerberos = 1;
83 CREDENTIALS     cred;
84 Key_schedule    schedule;
85 extern  char    *krb_realmofhost();
86 #ifdef CRYPT
87 int     doencrypt = 0;
88 #define OPTIONS "dfKk:prtx"
89 #else
90 #define OPTIONS "dfKk:prt"
91 #endif
92 #else
93 #define OPTIONS "dfprt"
94 #endif
95
96 struct passwd *pwd;
97 u_short port;
98 uid_t   userid;
99 int errs, rem;
100 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
101
102 static int argc_copy;
103 static char **argv_copy;
104
105 #define CMDNEEDS        64
106 char cmd[CMDNEEDS];             /* must hold "rcp -r -p -d\0" */
107
108 #ifdef KERBEROS
109 int      kerberos(char **, char *, char *, char *);
110 void     oldw(const char *, ...) __printflike(1, 2);
111 #endif
112 int      response(void);
113 void     rsource(char *, struct stat *);
114 void     run_err(const char *, ...) __printflike(1, 2);
115 void     sink(int, char *[]);
116 void     source(int, char *[]);
117 void     tolocal(int, char *[]);
118 void     toremote(char *, int, char *[]);
119 void     usage(void);
120
121 int
122 main(int argc, char *argv[])
123 {
124         struct servent *sp;
125         int ch, fflag, i, tflag;
126         char *targ, *shell;
127 #ifdef KERBEROS
128         char *k;
129 #endif
130
131         /*
132          * Prepare for execing ourselves.
133          */
134         argc_copy = argc + 1;
135         argv_copy = malloc((argc_copy + 1) * sizeof(*argv_copy));
136         if (argv_copy == NULL)
137                 err(1, "malloc");
138         argv_copy[0] = argv[0];
139         argv_copy[1] = "-K";
140         for (i = 1; i < argc; ++i) {
141                 argv_copy[i + 1] = strdup(argv[i]);
142                 if (argv_copy[i + 1] == NULL)
143                         errx(1, "strdup: out of memory");
144         }
145         argv_copy[argc + 1] = NULL;
146
147         fflag = tflag = 0;
148         while ((ch = getopt(argc, argv, OPTIONS)) != -1)
149                 switch(ch) {                    /* User-visible flags. */
150                 case 'K':
151 #ifdef KERBEROS
152                         use_kerberos = 0;
153 #endif
154                         break;
155 #ifdef  KERBEROS
156                 case 'k':
157                         dest_realm = dst_realm_buf;
158                         (void)strncpy(dst_realm_buf, optarg, REALM_SZ - 1);
159                         dst_realm_buf[REALM_SZ - 1] = '\0';
160                         break;
161 #ifdef CRYPT
162                 case 'x':
163                         doencrypt = 1;
164                         /* des_set_key(cred.session, schedule); */
165                         break;
166 #endif
167 #endif
168                 case 'p':
169                         pflag = 1;
170                         break;
171                 case 'r':
172                         iamrecursive = 1;
173                         break;
174                                                 /* Server options. */
175                 case 'd':
176                         targetshouldbedirectory = 1;
177                         break;
178                 case 'f':                       /* "from" */
179                         iamremote = 1;
180                         fflag = 1;
181                         break;
182                 case 't':                       /* "to" */
183                         iamremote = 1;
184                         tflag = 1;
185                         break;
186                 case '?':
187                 default:
188                         usage();
189                 }
190         argc -= optind;
191         argv += optind;
192
193 #ifdef KERBEROS
194         k = auth_getval("auth_list");
195         if (k && !strstr(k, "kerberos"))
196             use_kerberos = 0;
197         if (use_kerberos) {
198 #ifdef CRYPT
199                 shell = doencrypt ? "ekshell" : "kshell";
200 #else
201                 shell = "kshell";
202 #endif
203                 if ((sp = getservbyname(shell, "tcp")) == NULL) {
204                         use_kerberos = 0;
205                         oldw("can't get entry for %s/tcp service", shell);
206                         sp = getservbyname(shell = "shell", "tcp");
207                 }
208         } else
209                 sp = getservbyname(shell = "shell", "tcp");
210 #else
211         sp = getservbyname(shell = "shell", "tcp");
212 #endif
213         if (sp == NULL)
214                 errx(1, "%s/tcp: unknown service", shell);
215         port = sp->s_port;
216
217         if ((pwd = getpwuid(userid = getuid())) == NULL)
218                 errx(1, "unknown user %d", (int)userid);
219
220         rem = STDIN_FILENO;             /* XXX */
221
222         if (fflag) {                    /* Follow "protocol", send data. */
223                 (void)response();
224                 (void)setuid(userid);
225                 source(argc, argv);
226                 exit(errs);
227         }
228
229         if (tflag) {                    /* Receive data. */
230                 (void)setuid(userid);
231                 sink(argc, argv);
232                 exit(errs);
233         }
234
235         if (argc < 2)
236                 usage();
237         if (argc > 2)
238                 targetshouldbedirectory = 1;
239
240         rem = -1;
241         /* Command to be executed on remote system using "rsh". */
242 #ifdef  KERBEROS
243         (void)snprintf(cmd, sizeof(cmd),
244             "rcp%s%s%s%s", iamrecursive ? " -r" : "",
245 #ifdef CRYPT
246             (doencrypt && use_kerberos ? " -x" : ""),
247 #else
248             "",
249 #endif
250             pflag ? " -p" : "", targetshouldbedirectory ? " -d" : "");
251 #else
252         (void)snprintf(cmd, sizeof(cmd), "rcp%s%s%s",
253             iamrecursive ? " -r" : "", pflag ? " -p" : "",
254             targetshouldbedirectory ? " -d" : "");
255 #endif
256
257         (void)signal(SIGPIPE, lostconn);
258
259         if ((targ = colon(argv[argc - 1])))     /* Dest is remote host. */
260                 toremote(targ, argc, argv);
261         else {
262                 tolocal(argc, argv);            /* Dest is local host. */
263                 if (targetshouldbedirectory)
264                         verifydir(argv[argc - 1]);
265         }
266         exit(errs);
267 }
268
269 void
270 toremote(char *targ, int argc, char *argv[])
271 {
272         int i, len, tos;
273         char *bp, *host, *src, *suser, *thost, *tuser;
274
275         *targ++ = 0;
276         if (*targ == 0)
277                 targ = ".";
278
279         if ((thost = strchr(argv[argc - 1], '@'))) {
280                 /* user@host */
281                 *thost++ = 0;
282                 tuser = argv[argc - 1];
283                 if (*tuser == '\0')
284                         tuser = NULL;
285                 else if (!okname(tuser))
286                         exit(1);
287         } else {
288                 thost = argv[argc - 1];
289                 tuser = NULL;
290         }
291
292         for (i = 0; i < argc - 1; i++) {
293                 src = colon(argv[i]);
294                 if (src) {                      /* remote to remote */
295                         *src++ = 0;
296                         if (*src == 0)
297                                 src = ".";
298                         host = strchr(argv[i], '@');
299                         len = strlen(_PATH_RSH) + strlen(argv[i]) +
300                             strlen(src) + (tuser ? strlen(tuser) : 0) +
301                             strlen(thost) + strlen(targ) + CMDNEEDS + 20;
302                         if (!(bp = malloc(len)))
303                                 err(1, NULL);
304                         if (host) {
305                                 *host++ = 0;
306                                 suser = argv[i];
307                                 if (*suser == '\0')
308                                         suser = pwd->pw_name;
309                                 else if (!okname(suser)) {
310                                         ++errs;
311                                         continue;
312                                 }
313                                 (void)snprintf(bp, len,
314                                     "%s %s -l %s -n %s %s '%s%s%s:%s'",
315                                     _PATH_RSH, host, suser, cmd, src,
316                                     tuser ? tuser : "", tuser ? "@" : "",
317                                     thost, targ);
318                         } else
319                                 (void)snprintf(bp, len,
320                                     "exec %s %s -n %s %s '%s%s%s:%s'",
321                                     _PATH_RSH, argv[i], cmd, src,
322                                     tuser ? tuser : "", tuser ? "@" : "",
323                                     thost, targ);
324                         (void)susystem(bp, userid);
325                         (void)free(bp);
326                 } else {                        /* local to remote */
327                         if (rem == -1) {
328                                 len = strlen(targ) + CMDNEEDS + 20;
329                                 if (!(bp = malloc(len)))
330                                         err(1, NULL);
331                                 (void)snprintf(bp, len, "%s -t %s", cmd, targ);
332                                 host = thost;
333 #ifdef KERBEROS
334                                 if (use_kerberos)
335                                         rem = kerberos(&host, bp,
336                                             pwd->pw_name,
337                                             tuser ? tuser : pwd->pw_name);
338                                 else
339 #endif
340                                         rem = rcmd(&host, port, pwd->pw_name,
341                                             tuser ? tuser : pwd->pw_name,
342                                             bp, 0);
343                                 if (rem < 0)
344                                         exit(1);
345                                 tos = IPTOS_THROUGHPUT;
346                                 if (setsockopt(rem, IPPROTO_IP, IP_TOS,
347                                     &tos, sizeof(int)) < 0)
348                                         warn("TOS (ignored)");
349                                 if (response() < 0)
350                                         exit(1);
351                                 (void)free(bp);
352                                 (void)setuid(userid);
353                         }
354                         source(1, argv+i);
355                 }
356         }
357 }
358
359 void
360 tolocal(int argc, char *argv[])
361 {
362         int i, len, tos;
363         char *bp, *host, *src, *suser;
364
365         for (i = 0; i < argc - 1; i++) {
366                 if (!(src = colon(argv[i]))) {          /* Local to local. */
367                         len = strlen(_PATH_CP) + strlen(argv[i]) +
368                             strlen(argv[argc - 1]) + 20;
369                         if (!(bp = malloc(len)))
370                                 err(1, NULL);
371                         (void)snprintf(bp, len, "exec %s%s%s %s %s", _PATH_CP,
372                             iamrecursive ? " -PR" : "", pflag ? " -p" : "",
373                             argv[i], argv[argc - 1]);
374                         if (susystem(bp, userid))
375                                 ++errs;
376                         (void)free(bp);
377                         continue;
378                 }
379                 *src++ = 0;
380                 if (*src == 0)
381                         src = ".";
382                 if ((host = strchr(argv[i], '@')) == NULL) {
383                         host = argv[i];
384                         suser = pwd->pw_name;
385                 } else {
386                         *host++ = 0;
387                         suser = argv[i];
388                         if (*suser == '\0')
389                                 suser = pwd->pw_name;
390                         else if (!okname(suser)) {
391                                 ++errs;
392                                 continue;
393                         }
394                 }
395                 len = strlen(src) + CMDNEEDS + 20;
396                 if ((bp = malloc(len)) == NULL)
397                         err(1, NULL);
398                 (void)snprintf(bp, len, "%s -f %s", cmd, src);
399                 rem =
400 #ifdef KERBEROS
401                     use_kerberos ?
402                         kerberos(&host, bp, pwd->pw_name, suser) :
403 #endif
404                         rcmd(&host, port, pwd->pw_name, suser, bp, 0);
405                 (void)free(bp);
406                 if (rem < 0) {
407                         ++errs;
408                         continue;
409                 }
410                 (void)seteuid(userid);
411                 tos = IPTOS_THROUGHPUT;
412                 if (setsockopt(rem, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
413                         warn("TOS (ignored)");
414                 sink(1, argv + argc - 1);
415                 (void)seteuid(0);
416                 (void)close(rem);
417                 rem = -1;
418         }
419 }
420
421 void
422 source(int argc, char *argv[])
423 {
424         struct stat stb;
425         static BUF buffer;
426         BUF *bp;
427         off_t i;
428         int amt, fd, haderr, indx, result;
429         char *last, *name, buf[BUFSIZ];
430
431         for (indx = 0; indx < argc; ++indx) {
432                 name = argv[indx];
433                 if ((fd = open(name, O_RDONLY, 0)) < 0)
434                         goto syserr;
435                 if (fstat(fd, &stb)) {
436 syserr:                 run_err("%s: %s", name, strerror(errno));
437                         goto next;
438                 }
439                 switch (stb.st_mode & S_IFMT) {
440                 case S_IFREG:
441                         break;
442                 case S_IFDIR:
443                         if (iamrecursive) {
444                                 rsource(name, &stb);
445                                 goto next;
446                         }
447                         /* FALLTHROUGH */
448                 default:
449                         run_err("%s: not a regular file", name);
450                         goto next;
451                 }
452                 if ((last = strrchr(name, '/')) == NULL)
453                         last = name;
454                 else
455                         ++last;
456                 if (pflag) {
457                         /*
458                          * Make it compatible with possible future
459                          * versions expecting microseconds.
460                          */
461                         (void)snprintf(buf, sizeof(buf), "T%ld 0 %ld 0\n",
462                             (long)stb.st_mtimespec.tv_sec,
463                             (long)stb.st_atimespec.tv_sec);
464                         (void)write(rem, buf, strlen(buf));
465                         if (response() < 0)
466                                 goto next;
467                 }
468 #define MODEMASK        (S_ISUID|S_ISGID|S_ISTXT|S_IRWXU|S_IRWXG|S_IRWXO)
469                 (void)snprintf(buf, sizeof(buf), "C%04o %qd %s\n",
470                     stb.st_mode & MODEMASK, stb.st_size, last);
471                 (void)write(rem, buf, strlen(buf));
472                 if (response() < 0)
473                         goto next;
474                 if ((bp = allocbuf(&buffer, fd, BUFSIZ)) == NULL) {
475 next:                   (void)close(fd);
476                         continue;
477                 }
478
479                 /* Keep writing after an error so that we stay sync'd up. */
480                 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
481                         amt = bp->cnt;
482                         if (i + amt > stb.st_size)
483                                 amt = stb.st_size - i;
484                         if (!haderr) {
485                                 result = read(fd, bp->buf, amt);
486                                 if (result != amt)
487                                         haderr = result >= 0 ? EIO : errno;
488                         }
489                         if (haderr)
490                                 (void)write(rem, bp->buf, amt);
491                         else {
492                                 result = write(rem, bp->buf, amt);
493                                 if (result != amt)
494                                         haderr = result >= 0 ? EIO : errno;
495                         }
496                 }
497                 if (close(fd) && !haderr)
498                         haderr = errno;
499                 if (!haderr)
500                         (void)write(rem, "", 1);
501                 else
502                         run_err("%s: %s", name, strerror(haderr));
503                 (void)response();
504         }
505 }
506
507 void
508 rsource(char *name, struct stat *statp)
509 {
510         DIR *dirp;
511         struct dirent *dp;
512         char *last, *vect[1], path[PATH_MAX];
513
514         if (!(dirp = opendir(name))) {
515                 run_err("%s: %s", name, strerror(errno));
516                 return;
517         }
518         last = strrchr(name, '/');
519         if (last == 0)
520                 last = name;
521         else
522                 last++;
523         if (pflag) {
524                 (void)snprintf(path, sizeof(path), "T%ld 0 %ld 0\n",
525                     (long)statp->st_mtimespec.tv_sec,
526                     (long)statp->st_atimespec.tv_sec);
527                 (void)write(rem, path, strlen(path));
528                 if (response() < 0) {
529                         closedir(dirp);
530                         return;
531                 }
532         }
533         (void)snprintf(path, sizeof(path),
534             "D%04o %d %s\n", statp->st_mode & MODEMASK, 0, last);
535         (void)write(rem, path, strlen(path));
536         if (response() < 0) {
537                 closedir(dirp);
538                 return;
539         }
540         while ((dp = readdir(dirp))) {
541                 if (dp->d_ino == 0)
542                         continue;
543                 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
544                         continue;
545                 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path)) {
546                         run_err("%s/%s: name too long", name, dp->d_name);
547                         continue;
548                 }
549                 (void)snprintf(path, sizeof(path), "%s/%s", name, dp->d_name);
550                 vect[0] = path;
551                 source(1, vect);
552         }
553         (void)closedir(dirp);
554         (void)write(rem, "E\n", 2);
555         (void)response();
556 }
557
558 void
559 sink(int argc, char *argv[])
560 {
561         static BUF buffer;
562         struct stat stb;
563         struct timeval tv[2];
564         enum { YES, NO, DISPLAYED } wrerr;
565         BUF *bp;
566         off_t i, j, size;
567         int amt, count, exists, first, mask, mode, ofd, omode;
568         int setimes, targisdir, wrerrno = 0;
569         char ch, *cp, *np, *targ, *why, *vect[1], buf[BUFSIZ];
570
571 #define atime   tv[0]
572 #define mtime   tv[1]
573 #define SCREWUP(str)    { why = str; goto screwup; }
574
575         setimes = targisdir = 0;
576         mask = umask(0);
577         if (!pflag)
578                 (void)umask(mask);
579         if (argc != 1) {
580                 run_err("ambiguous target");
581                 exit(1);
582         }
583         targ = *argv;
584         if (targetshouldbedirectory)
585                 verifydir(targ);
586         (void)write(rem, "", 1);
587         if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
588                 targisdir = 1;
589         for (first = 1;; first = 0) {
590                 cp = buf;
591                 if (read(rem, cp, 1) <= 0)
592                         return;
593                 if (*cp++ == '\n')
594                         SCREWUP("unexpected <newline>");
595                 do {
596                         if (read(rem, &ch, sizeof(ch)) != sizeof(ch))
597                                 SCREWUP("lost connection");
598                         *cp++ = ch;
599                 } while (cp < &buf[BUFSIZ - 1] && ch != '\n');
600                 *cp = 0;
601
602                 if (buf[0] == '\01' || buf[0] == '\02') {
603                         if (iamremote == 0)
604                                 (void)write(STDERR_FILENO,
605                                     buf + 1, strlen(buf + 1));
606                         if (buf[0] == '\02')
607                                 exit(1);
608                         ++errs;
609                         continue;
610                 }
611                 if (buf[0] == 'E') {
612                         (void)write(rem, "", 1);
613                         return;
614                 }
615
616                 if (ch == '\n')
617                         *--cp = 0;
618
619                 cp = buf;
620                 if (*cp == 'T') {
621                         setimes++;
622                         cp++;
623                         mtime.tv_sec = strtol(cp, &cp, 10);
624                         if (!cp || *cp++ != ' ')
625                                 SCREWUP("mtime.sec not delimited");
626                         mtime.tv_usec = strtol(cp, &cp, 10);
627                         if (!cp || *cp++ != ' ')
628                                 SCREWUP("mtime.usec not delimited");
629                         atime.tv_sec = strtol(cp, &cp, 10);
630                         if (!cp || *cp++ != ' ')
631                                 SCREWUP("atime.sec not delimited");
632                         atime.tv_usec = strtol(cp, &cp, 10);
633                         if (!cp || *cp++ != '\0')
634                                 SCREWUP("atime.usec not delimited");
635                         (void)write(rem, "", 1);
636                         continue;
637                 }
638                 if (*cp != 'C' && *cp != 'D') {
639                         /*
640                          * Check for the case "rcp remote:foo\* local:bar".
641                          * In this case, the line "No match." can be returned
642                          * by the shell before the rcp command on the remote is
643                          * executed so the ^Aerror_message convention isn't
644                          * followed.
645                          */
646                         if (first) {
647                                 run_err("%s", cp);
648                                 exit(1);
649                         }
650                         SCREWUP("expected control record");
651                 }
652                 mode = 0;
653                 for (++cp; cp < buf + 5; cp++) {
654                         if (*cp < '0' || *cp > '7')
655                                 SCREWUP("bad mode");
656                         mode = (mode << 3) | (*cp - '0');
657                 }
658                 if (*cp++ != ' ')
659                         SCREWUP("mode not delimited");
660
661                 for (size = 0; isdigit(*cp);)
662                         size = size * 10 + (*cp++ - '0');
663                 if (*cp++ != ' ')
664                         SCREWUP("size not delimited");
665                 if (targisdir) {
666                         static char *namebuf;
667                         static int cursize;
668                         size_t need;
669
670                         need = strlen(targ) + strlen(cp) + 250;
671                         if (need > cursize) {
672                                 if (!(namebuf = malloc(need)))
673                                         run_err("%s", strerror(errno));
674                         }
675                         (void)snprintf(namebuf, need, "%s%s%s", targ,
676                             *targ ? "/" : "", cp);
677                         np = namebuf;
678                 } else
679                         np = targ;
680                 exists = stat(np, &stb) == 0;
681                 if (buf[0] == 'D') {
682                         int mod_flag = pflag;
683                         if (exists) {
684                                 if (!S_ISDIR(stb.st_mode)) {
685                                         errno = ENOTDIR;
686                                         goto bad;
687                                 }
688                                 if (pflag)
689                                         (void)chmod(np, mode);
690                         } else {
691                                 /* Handle copying from a read-only directory */
692                                 mod_flag = 1;
693                                 if (mkdir(np, mode | S_IRWXU) < 0)
694                                         goto bad;
695                         }
696                         vect[0] = np;
697                         sink(1, vect);
698                         if (setimes) {
699                                 setimes = 0;
700                                 if (utimes(np, tv) < 0)
701                                     run_err("%s: set times: %s",
702                                         np, strerror(errno));
703                         }
704                         if (mod_flag)
705                                 (void)chmod(np, mode);
706                         continue;
707                 }
708                 omode = mode;
709                 mode |= S_IWRITE;
710                 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
711 bad:                    run_err("%s: %s", np, strerror(errno));
712                         continue;
713                 }
714                 (void)write(rem, "", 1);
715                 if ((bp = allocbuf(&buffer, ofd, BUFSIZ)) == NULL) {
716                         (void)close(ofd);
717                         continue;
718                 }
719                 cp = bp->buf;
720                 wrerr = NO;
721                 for (count = i = 0; i < size; i += BUFSIZ) {
722                         amt = BUFSIZ;
723                         if (i + amt > size)
724                                 amt = size - i;
725                         count += amt;
726                         do {
727                                 j = read(rem, cp, amt);
728                                 if (j <= 0) {
729                                         run_err("%s", j ? strerror(errno) :
730                                             "dropped connection");
731                                         exit(1);
732                                 }
733                                 amt -= j;
734                                 cp += j;
735                         } while (amt > 0);
736                         if (count == bp->cnt) {
737                                 /* Keep reading so we stay sync'd up. */
738                                 if (wrerr == NO) {
739                                         j = write(ofd, bp->buf, count);
740                                         if (j != count) {
741                                                 wrerr = YES;
742                                                 wrerrno = j >= 0 ? EIO : errno;
743                                         }
744                                 }
745                                 count = 0;
746                                 cp = bp->buf;
747                         }
748                 }
749                 if (count != 0 && wrerr == NO &&
750                     (j = write(ofd, bp->buf, count)) != count) {
751                         wrerr = YES;
752                         wrerrno = j >= 0 ? EIO : errno;
753                 }
754                 if (ftruncate(ofd, size)) {
755                         run_err("%s: truncate: %s", np, strerror(errno));
756                         wrerr = DISPLAYED;
757                 }
758                 if (pflag) {
759                         if (exists || omode != mode)
760                                 if (fchmod(ofd, omode))
761                                         run_err("%s: set mode: %s",
762                                             np, strerror(errno));
763                 } else {
764                         if (!exists && omode != mode)
765                                 if (fchmod(ofd, omode & ~mask))
766                                         run_err("%s: set mode: %s",
767                                             np, strerror(errno));
768                 }
769                 (void)close(ofd);
770                 (void)response();
771                 if (setimes && wrerr == NO) {
772                         setimes = 0;
773                         if (utimes(np, tv) < 0) {
774                                 run_err("%s: set times: %s",
775                                     np, strerror(errno));
776                                 wrerr = DISPLAYED;
777                         }
778                 }
779                 switch(wrerr) {
780                 case YES:
781                         run_err("%s: %s", np, strerror(wrerrno));
782                         break;
783                 case NO:
784                         (void)write(rem, "", 1);
785                         break;
786                 case DISPLAYED:
787                         break;
788                 }
789         }
790 screwup:
791         run_err("protocol error: %s", why);
792         exit(1);
793 }
794
795 #ifdef KERBEROS
796 int
797 kerberos(char **host, char *bp, char *locuser, char *user)
798 {
799         if (use_kerberos) {
800                 setuid(getuid());
801                 rem = KSUCCESS;
802                 errno = 0;
803                 if (dest_realm == NULL)
804                         dest_realm = krb_realmofhost(*host);
805                 rem =
806 #ifdef CRYPT
807                     doencrypt ?
808                         krcmd_mutual(host,
809                             port, user, bp, 0, dest_realm, &cred, schedule) :
810 #endif
811                         krcmd(host, port, user, bp, 0, dest_realm);
812
813                 if (rem < 0) {
814                         if (errno == ECONNREFUSED)
815                             oldw("remote host doesn't support Kerberos");
816                         else if (errno == ENOENT)
817                             oldw("can't provide Kerberos authentication data");
818                         execv(_PATH_RCP, argv_copy);
819                         err(1, "execv: %s", _PATH_RCP);
820                 }
821         } else {
822 #ifdef CRYPT
823                 if (doencrypt)
824                         errx(1,
825                            "the -x option requires Kerberos authentication");
826 #endif
827                 rem = rcmd(host, port, locuser, user, bp, 0);
828         }
829         return (rem);
830 }
831 #endif /* KERBEROS */
832
833 int
834 response(void)
835 {
836         char ch, *cp, resp, rbuf[BUFSIZ];
837
838         if (read(rem, &resp, sizeof(resp)) != sizeof(resp))
839                 lostconn(0);
840
841         cp = rbuf;
842         switch(resp) {
843         case 0:                         /* ok */
844                 return (0);
845         default:
846                 *cp++ = resp;
847                 /* FALLTHROUGH */
848         case 1:                         /* error, followed by error msg */
849         case 2:                         /* fatal error, "" */
850                 do {
851                         if (read(rem, &ch, sizeof(ch)) != sizeof(ch))
852                                 lostconn(0);
853                         *cp++ = ch;
854                 } while (cp < &rbuf[BUFSIZ] && ch != '\n');
855
856                 if (!iamremote)
857                         (void)write(STDERR_FILENO, rbuf, cp - rbuf);
858                 ++errs;
859                 if (resp == 1)
860                         return (-1);
861                 exit(1);
862         }
863         /* NOTREACHED */
864 }
865
866 void
867 usage(void)
868 {
869 #ifdef KERBEROS
870 #ifdef CRYPT
871         (void)fprintf(stderr, "%s\n%s\n",
872             "usage: rcp [-Kpx] [-k realm] f1 f2",
873             "       rcp [-Kprx] [-k realm] f1 ... fn directory");
874 #else
875         (void)fprintf(stderr, "%s\n%s\n",
876             "usage: rcp [-Kp] [-k realm] f1 f2",
877             "       rcp [-Kpr] [-k realm] f1 ... fn directory");
878 #endif
879 #else
880         (void)fprintf(stderr, "%s\n%s\n",
881             "usage: rcp [-p] f1 f2",
882             "       rcp [-pr] f1 ... fn directory");
883 #endif
884         exit(1);
885 }
886
887 #include <stdarg.h>
888
889 #ifdef KERBEROS
890 void
891 oldw(const char *fmt, ...)
892 {
893         va_list ap;
894         va_start(ap, fmt);
895         (void)fprintf(stderr, "rcp: ");
896         (void)vfprintf(stderr, fmt, ap);
897         (void)fprintf(stderr, ", using standard rcp\n");
898         va_end(ap);
899 }
900 #endif
901
902 void
903 run_err(const char *fmt, ...)
904 {
905         static FILE *fp;
906         va_list ap;
907         va_start(ap, fmt);
908
909         ++errs;
910         if (fp == NULL && !(fp = fdopen(rem, "w")))
911                 return;
912         (void)fprintf(fp, "%c", 0x01);
913         (void)fprintf(fp, "rcp: ");
914         (void)vfprintf(fp, fmt, ap);
915         (void)fprintf(fp, "\n");
916         (void)fflush(fp);
917
918         if (!iamremote)
919                 vwarnx(fmt, ap);
920
921         va_end(ap);
922 }