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