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