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