]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - bin/rcp/rcp.c
This commit was generated by cvs2svn to compensate for changes in r116520,
[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, len, 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                         len = strlen(_PATH_RSH) + strlen(argv[i]) +
244                             strlen(src) + (tuser ? strlen(tuser) : 0) +
245                             strlen(thost) + strlen(targ) + CMDNEEDS + 20;
246                         if (!(bp = malloc(len)))
247                                 err(1, "malloc");
248                         if (host) {
249                                 *host++ = 0;
250                                 suser = argv[i];
251                                 if (*suser == '\0')
252                                         suser = pwd->pw_name;
253                                 else if (!okname(suser)) {
254                                         ++errs;
255                                         continue;
256                                 }
257                                 (void)snprintf(bp, len,
258                                     "%s %s -l %s -n %s %s '%s%s%s:%s'",
259                                     _PATH_RSH, host, suser, cmd, src,
260                                     tuser ? tuser : "", tuser ? "@" : "",
261                                     thost, targ);
262                         } else
263                                 (void)snprintf(bp, len,
264                                     "exec %s %s -n %s %s '%s%s%s:%s'",
265                                     _PATH_RSH, argv[i], cmd, src,
266                                     tuser ? tuser : "", tuser ? "@" : "",
267                                     thost, targ);
268                         (void)susystem(bp, userid);
269                         (void)free(bp);
270                 } else {                        /* local to remote */
271                         if (rem == -1) {
272                                 len = strlen(targ) + CMDNEEDS + 20;
273                                 if (!(bp = malloc(len)))
274                                         err(1, "malloc");
275                                 (void)snprintf(bp, len, "%s -t %s", cmd, targ);
276                                 host = thost;
277                                 rem = rcmd_af(&host, port,
278                                     pwd->pw_name,
279                                     tuser ? tuser : pwd->pw_name,
280                                     bp, 0, family);
281                                 if (rem < 0)
282                                         exit(1);
283                                 if (family == PF_INET) {
284                                         tos = IPTOS_THROUGHPUT;
285                                         if (setsockopt(rem, IPPROTO_IP, IP_TOS,
286                                             &tos, sizeof(int)) < 0)
287                                                 warn("TOS (ignored)");
288                                 }
289                                 if (response() < 0)
290                                         exit(1);
291                                 (void)free(bp);
292                                 (void)setuid(userid);
293                         }
294                         source(1, argv+i);
295                 }
296         }
297 }
298
299 void
300 tolocal(int argc, char *argv[])
301 {
302         int i, len, tos;
303         char *bp, *host, *src, *suser;
304
305         for (i = 0; i < argc - 1; i++) {
306                 if (!(src = colon(argv[i]))) {          /* Local to local. */
307                         len = strlen(_PATH_CP) + strlen(argv[i]) +
308                             strlen(argv[argc - 1]) + 20;
309                         if (!(bp = malloc(len)))
310                                 err(1, "malloc");
311                         (void)snprintf(bp, len, "exec %s%s%s %s %s", _PATH_CP,
312                             iamrecursive ? " -PR" : "", pflag ? " -p" : "",
313                             argv[i], argv[argc - 1]);
314                         if (susystem(bp, userid))
315                                 ++errs;
316                         (void)free(bp);
317                         continue;
318                 }
319                 *src++ = 0;
320                 if (*src == 0)
321                         src = period;
322                 if ((host = strchr(argv[i], '@')) == NULL) {
323                         host = argv[i];
324                         suser = pwd->pw_name;
325                 } else {
326                         *host++ = 0;
327                         suser = argv[i];
328                         if (*suser == '\0')
329                                 suser = pwd->pw_name;
330                         else if (!okname(suser)) {
331                                 ++errs;
332                                 continue;
333                         }
334                 }
335                 len = strlen(src) + CMDNEEDS + 20;
336                 if ((bp = malloc(len)) == NULL)
337                         err(1, "malloc");
338                 (void)snprintf(bp, len, "%s -f %s", cmd, src);
339                 rem = rcmd_af(&host, port, pwd->pw_name, suser, bp, 0,
340                             family);
341                 (void)free(bp);
342                 if (rem < 0) {
343                         ++errs;
344                         continue;
345                 }
346                 (void)seteuid(userid);
347                 if (family == PF_INET) {
348                         tos = IPTOS_THROUGHPUT;
349                         if (setsockopt(rem, IPPROTO_IP, IP_TOS, &tos,
350                             sizeof(int)) < 0)
351                                 warn("TOS (ignored)");
352                 }
353                 sink(1, argv + argc - 1);
354                 (void)seteuid(0);
355                 (void)close(rem);
356                 rem = -1;
357         }
358 }
359
360 void
361 source(int argc, char *argv[])
362 {
363         struct stat stb;
364         static BUF buffer;
365         BUF *bp;
366         off_t i;
367         int amt, fd, haderr, indx, result;
368         char *last, *name, buf[BUFSIZ];
369
370         for (indx = 0; indx < argc; ++indx) {
371                 name = argv[indx];
372                 if ((fd = open(name, O_RDONLY, 0)) < 0)
373                         goto syserr;
374                 if (fstat(fd, &stb)) {
375 syserr:                 run_err("%s: %s", name, strerror(errno));
376                         goto next;
377                 }
378                 switch (stb.st_mode & S_IFMT) {
379                 case S_IFREG:
380                         break;
381                 case S_IFDIR:
382                         if (iamrecursive) {
383                                 rsource(name, &stb);
384                                 goto next;
385                         }
386                         /* FALLTHROUGH */
387                 default:
388                         run_err("%s: not a regular file", name);
389                         goto next;
390                 }
391                 if ((last = strrchr(name, '/')) == NULL)
392                         last = name;
393                 else
394                         ++last;
395                 if (pflag) {
396                         /*
397                          * Make it compatible with possible future
398                          * versions expecting microseconds.
399                          */
400                         (void)snprintf(buf, sizeof(buf), "T%ld 0 %ld 0\n",
401                             (long)stb.st_mtimespec.tv_sec,
402                             (long)stb.st_atimespec.tv_sec);
403                         (void)write(rem, buf, strlen(buf));
404                         if (response() < 0)
405                                 goto next;
406                 }
407 #define MODEMASK        (S_ISUID|S_ISGID|S_ISTXT|S_IRWXU|S_IRWXG|S_IRWXO)
408                 (void)snprintf(buf, sizeof(buf), "C%04o %jd %s\n",
409                     stb.st_mode & MODEMASK, (intmax_t)stb.st_size, last);
410                 (void)write(rem, buf, strlen(buf));
411                 if (response() < 0)
412                         goto next;
413                 if ((bp = allocbuf(&buffer, fd, BUFSIZ)) == NULL) {
414 next:                   (void)close(fd);
415                         continue;
416                 }
417
418                 /* Keep writing after an error so that we stay sync'd up. */
419                 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
420                         amt = bp->cnt;
421                         if (i + amt > stb.st_size)
422                                 amt = stb.st_size - i;
423                         if (!haderr) {
424                                 result = read(fd, bp->buf, amt);
425                                 if (result != amt)
426                                         haderr = result >= 0 ? EIO : errno;
427                         }
428                         if (haderr)
429                                 (void)write(rem, bp->buf, amt);
430                         else {
431                                 result = write(rem, bp->buf, amt);
432                                 if (result != amt)
433                                         haderr = result >= 0 ? EIO : errno;
434                         }
435                 }
436                 if (close(fd) && !haderr)
437                         haderr = errno;
438                 if (!haderr)
439                         (void)write(rem, "", 1);
440                 else
441                         run_err("%s: %s", name, strerror(haderr));
442                 (void)response();
443         }
444 }
445
446 void
447 rsource(char *name, struct stat *statp)
448 {
449         DIR *dirp;
450         struct dirent *dp;
451         char *last, *vect[1], path[PATH_MAX];
452
453         if (!(dirp = opendir(name))) {
454                 run_err("%s: %s", name, strerror(errno));
455                 return;
456         }
457         last = strrchr(name, '/');
458         if (last == 0)
459                 last = name;
460         else
461                 last++;
462         if (pflag) {
463                 (void)snprintf(path, sizeof(path), "T%ld 0 %ld 0\n",
464                     (long)statp->st_mtimespec.tv_sec,
465                     (long)statp->st_atimespec.tv_sec);
466                 (void)write(rem, path, strlen(path));
467                 if (response() < 0) {
468                         closedir(dirp);
469                         return;
470                 }
471         }
472         (void)snprintf(path, sizeof(path),
473             "D%04o %d %s\n", statp->st_mode & MODEMASK, 0, last);
474         (void)write(rem, path, strlen(path));
475         if (response() < 0) {
476                 closedir(dirp);
477                 return;
478         }
479         while ((dp = readdir(dirp))) {
480                 if (dp->d_ino == 0)
481                         continue;
482                 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
483                         continue;
484                 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path)) {
485                         run_err("%s/%s: name too long", name, dp->d_name);
486                         continue;
487                 }
488                 (void)snprintf(path, sizeof(path), "%s/%s", name, dp->d_name);
489                 vect[0] = path;
490                 source(1, vect);
491         }
492         (void)closedir(dirp);
493         (void)write(rem, "E\n", 2);
494         (void)response();
495 }
496
497 void
498 sink(int argc, char *argv[])
499 {
500         static BUF buffer;
501         struct stat stb;
502         struct timeval tv[2];
503         enum { YES, NO, DISPLAYED } wrerr;
504         BUF *bp;
505         off_t i, j, size;
506         int amt, exists, first, mask, mode, ofd, omode;
507         size_t count;
508         int setimes, targisdir, wrerrno = 0;
509         char ch, *cp, *np, *targ, *vect[1], buf[BUFSIZ], path[PATH_MAX];
510         const char *why;
511
512 #define atime   tv[0]
513 #define mtime   tv[1]
514 #define SCREWUP(str)    { why = str; goto screwup; }
515
516         setimes = targisdir = 0;
517         mask = umask(0);
518         if (!pflag)
519                 (void)umask(mask);
520         if (argc != 1) {
521                 run_err("ambiguous target");
522                 exit(1);
523         }
524         targ = *argv;
525         if (targetshouldbedirectory)
526                 verifydir(targ);
527         (void)write(rem, "", 1);
528         if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
529                 targisdir = 1;
530         for (first = 1;; first = 0) {
531                 cp = buf;
532                 if (read(rem, cp, 1) <= 0)
533                         return;
534                 if (*cp++ == '\n')
535                         SCREWUP("unexpected <newline>");
536                 do {
537                         if (read(rem, &ch, sizeof(ch)) != sizeof(ch))
538                                 SCREWUP("lost connection");
539                         *cp++ = ch;
540                 } while (cp < &buf[BUFSIZ - 1] && ch != '\n');
541                 *cp = 0;
542
543                 if (buf[0] == '\01' || buf[0] == '\02') {
544                         if (iamremote == 0)
545                                 (void)write(STDERR_FILENO,
546                                     buf + 1, strlen(buf + 1));
547                         if (buf[0] == '\02')
548                                 exit(1);
549                         ++errs;
550                         continue;
551                 }
552                 if (buf[0] == 'E') {
553                         (void)write(rem, "", 1);
554                         return;
555                 }
556
557                 if (ch == '\n')
558                         *--cp = 0;
559
560                 cp = buf;
561                 if (*cp == 'T') {
562                         setimes++;
563                         cp++;
564                         mtime.tv_sec = strtol(cp, &cp, 10);
565                         if (!cp || *cp++ != ' ')
566                                 SCREWUP("mtime.sec not delimited");
567                         mtime.tv_usec = strtol(cp, &cp, 10);
568                         if (!cp || *cp++ != ' ')
569                                 SCREWUP("mtime.usec not delimited");
570                         atime.tv_sec = strtol(cp, &cp, 10);
571                         if (!cp || *cp++ != ' ')
572                                 SCREWUP("atime.sec not delimited");
573                         atime.tv_usec = strtol(cp, &cp, 10);
574                         if (!cp || *cp++ != '\0')
575                                 SCREWUP("atime.usec not delimited");
576                         (void)write(rem, "", 1);
577                         continue;
578                 }
579                 if (*cp != 'C' && *cp != 'D') {
580                         /*
581                          * Check for the case "rcp remote:foo\* local:bar".
582                          * In this case, the line "No match." can be returned
583                          * by the shell before the rcp command on the remote is
584                          * executed so the ^Aerror_message convention isn't
585                          * followed.
586                          */
587                         if (first) {
588                                 run_err("%s", cp);
589                                 exit(1);
590                         }
591                         SCREWUP("expected control record");
592                 }
593                 mode = 0;
594                 for (++cp; cp < buf + 5; cp++) {
595                         if (*cp < '0' || *cp > '7')
596                                 SCREWUP("bad mode");
597                         mode = (mode << 3) | (*cp - '0');
598                 }
599                 if (*cp++ != ' ')
600                         SCREWUP("mode not delimited");
601
602                 for (size = 0; isdigit(*cp);)
603                         size = size * 10 + (*cp++ - '0');
604                 if (*cp++ != ' ')
605                         SCREWUP("size not delimited");
606                 if (targisdir) {
607                         if (strlen(targ) + (*targ ? 1 : 0) + strlen(cp)
608                                         >= sizeof(path)) {
609                                 run_err("%s%s%s: name too long", targ,
610                                         *targ ? "/" : "", cp);
611                                 exit(1);
612                         }
613                         (void)snprintf(path, sizeof(path), "%s%s%s", targ,
614                             *targ ? "/" : "", cp);
615                         np = path;
616                 } else
617                         np = targ;
618                 exists = stat(np, &stb) == 0;
619                 if (buf[0] == 'D') {
620                         int mod_flag = pflag;
621                         if (exists) {
622                                 if (!S_ISDIR(stb.st_mode)) {
623                                         errno = ENOTDIR;
624                                         goto bad;
625                                 }
626                                 if (pflag)
627                                         (void)chmod(np, mode);
628                         } else {
629                                 /* Handle copying from a read-only directory */
630                                 mod_flag = 1;
631                                 if (mkdir(np, mode | S_IRWXU) < 0)
632                                         goto bad;
633                         }
634                         vect[0] = np;
635                         sink(1, vect);
636                         if (setimes) {
637                                 setimes = 0;
638                                 if (utimes(np, tv) < 0)
639                                     run_err("%s: set times: %s",
640                                         np, strerror(errno));
641                         }
642                         if (mod_flag)
643                                 (void)chmod(np, mode);
644                         continue;
645                 }
646                 omode = mode;
647                 mode |= S_IWRITE;
648                 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
649 bad:                    run_err("%s: %s", np, strerror(errno));
650                         continue;
651                 }
652                 (void)write(rem, "", 1);
653                 if ((bp = allocbuf(&buffer, ofd, BUFSIZ)) == NULL) {
654                         (void)close(ofd);
655                         continue;
656                 }
657                 cp = bp->buf;
658                 wrerr = NO;
659                 for (count = i = 0; i < size; i += BUFSIZ) {
660                         amt = BUFSIZ;
661                         if (i + amt > size)
662                                 amt = size - i;
663                         count += amt;
664                         do {
665                                 j = read(rem, cp, amt);
666                                 if (j <= 0) {
667                                         run_err("%s", j ? strerror(errno) :
668                                             "dropped connection");
669                                         exit(1);
670                                 }
671                                 amt -= j;
672                                 cp += j;
673                         } while (amt > 0);
674                         if (count == bp->cnt) {
675                                 /* Keep reading so we stay sync'd up. */
676                                 if (wrerr == NO) {
677                                         j = write(ofd, bp->buf, count);
678                                         if (j != (off_t)count) {
679                                                 wrerr = YES;
680                                                 wrerrno = j >= 0 ? EIO : errno;
681                                         }
682                                 }
683                                 count = 0;
684                                 cp = bp->buf;
685                         }
686                 }
687                 if (count != 0 && wrerr == NO &&
688                     (j = write(ofd, bp->buf, count)) != (off_t)count) {
689                         wrerr = YES;
690                         wrerrno = j >= 0 ? EIO : errno;
691                 }
692                 if (ftruncate(ofd, size)) {
693                         run_err("%s: truncate: %s", np, strerror(errno));
694                         wrerr = DISPLAYED;
695                 }
696                 if (pflag) {
697                         if (exists || omode != mode)
698                                 if (fchmod(ofd, omode))
699                                         run_err("%s: set mode: %s",
700                                             np, strerror(errno));
701                 } else {
702                         if (!exists && omode != mode)
703                                 if (fchmod(ofd, omode & ~mask))
704                                         run_err("%s: set mode: %s",
705                                             np, strerror(errno));
706                 }
707                 (void)close(ofd);
708                 (void)response();
709                 if (setimes && wrerr == NO) {
710                         setimes = 0;
711                         if (utimes(np, tv) < 0) {
712                                 run_err("%s: set times: %s",
713                                     np, strerror(errno));
714                                 wrerr = DISPLAYED;
715                         }
716                 }
717                 switch(wrerr) {
718                 case YES:
719                         run_err("%s: %s", np, strerror(wrerrno));
720                         break;
721                 case NO:
722                         (void)write(rem, "", 1);
723                         break;
724                 case DISPLAYED:
725                         break;
726                 }
727         }
728 screwup:
729         run_err("protocol error: %s", why);
730         exit(1);
731 }
732
733 int
734 response(void)
735 {
736         char ch, *cp, resp, rbuf[BUFSIZ];
737
738         if (read(rem, &resp, sizeof(resp)) != sizeof(resp))
739                 lostconn(0);
740
741         cp = rbuf;
742         switch(resp) {
743         case 0:                         /* ok */
744                 return (0);
745         default:
746                 *cp++ = resp;
747                 /* FALLTHROUGH */
748         case 1:                         /* error, followed by error msg */
749         case 2:                         /* fatal error, "" */
750                 do {
751                         if (read(rem, &ch, sizeof(ch)) != sizeof(ch))
752                                 lostconn(0);
753                         *cp++ = ch;
754                 } while (cp < &rbuf[BUFSIZ] && ch != '\n');
755
756                 if (!iamremote)
757                         (void)write(STDERR_FILENO, rbuf, cp - rbuf);
758                 ++errs;
759                 if (resp == 1)
760                         return (-1);
761                 exit(1);
762         }
763         /* NOTREACHED */
764 }
765
766 void
767 usage(void)
768 {
769         (void)fprintf(stderr, "%s\n%s\n",
770             "usage: rcp [-46p] f1 f2",
771             "       rcp [-46pr] f1 ... fn directory");
772         exit(1);
773 }
774
775 #include <stdarg.h>
776
777 void
778 run_err(const char *fmt, ...)
779 {
780         static FILE *fp;
781         va_list ap;
782
783         ++errs;
784         if (fp == NULL && !(fp = fdopen(rem, "w")))
785                 return;
786         (void)fprintf(fp, "%c", 0x01);
787         (void)fprintf(fp, "rcp: ");
788         va_start(ap, fmt);
789         (void)vfprintf(fp, fmt, ap);
790         va_end(ap);
791         (void)fprintf(fp, "\n");
792         (void)fflush(fp);
793
794         if (!iamremote) {
795                 va_start(ap, fmt);
796                 vwarnx(fmt, ap);
797                 va_end(ap);
798         }
799
800         va_end(ap);
801 }