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