VirtualBox

source: kBuild/trunk/src/kmk/kmkbuiltin/install.c@ 3583

Last change on this file since 3583 was 3583, checked in by bird, 2 years ago

kmk_install: Shut up annoying messages about different mode preventing hard linking of a file.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 35.0 KB
Line 
1/*
2 * Copyright (c) 1987, 1993
3 * The Regents of the University of California. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#if 0 /*ndef lint*/
35static const char copyright[] =
36"@(#) Copyright (c) 1987, 1993\n\
37 The Regents of the University of California. All rights reserved.\n";
38#endif /* not lint */
39
40#if 0
41#ifndef lint
42static char sccsid[] = "@(#)xinstall.c 8.1 (Berkeley) 7/21/93";
43#endif /* not lint */
44
45#include <sys/cdefs.h>
46__FBSDID("$FreeBSD: src/usr.bin/xinstall/xinstall.c,v 1.66 2005/01/25 14:34:57 ssouhlal Exp $");
47#endif
48
49#define FAKES_NO_GETOPT_H
50#include "config.h"
51#ifndef _MSC_VER
52# include <sys/param.h>
53# if !defined(__HAIKU__) && !defined(__gnu_hurd__)
54# include <sys/mount.h>
55# endif
56# include <sys/wait.h>
57# include <sys/time.h>
58#endif /* !_MSC_VER */
59#include <sys/stat.h>
60
61#include <ctype.h>
62#include "err.h"
63#include <errno.h>
64#include <fcntl.h>
65#include <grp.h>
66#include <paths.h>
67#include <pwd.h>
68#include <stdio.h>
69#include <stdlib.h>
70#include <string.h>
71#ifndef __HAIKU__
72# include <sysexits.h>
73#endif
74#ifdef __NetBSD__
75# include <util.h>
76# define strtofflags(a, b, c) string_to_flags(a, b, c)
77#endif
78#include <unistd.h>
79#if defined(__EMX__) || defined(_MSC_VER)
80# include <process.h>
81#endif
82#include "getopt_r.h"
83#ifdef __sun__
84# include "solfakes.h"
85#endif
86#ifdef _MSC_VER
87# include "mscfakes.h"
88#endif
89#ifdef __HAIKU__
90# include "haikufakes.h"
91#endif
92#include "kmkbuiltin.h"
93#include "k/kDefs.h" /* for K_OS */
94#include "dos2unix.h"
95
96
97extern void * bsd_setmode(const char *p);
98extern mode_t bsd_getmode(const void *bbox, mode_t omode);
99
100#ifndef MAXBSIZE
101# define MAXBSIZE 0x20000
102#endif
103
104#define MAX_CMP_SIZE (16 * 1024 * 1024)
105
106#define DIRECTORY 0x01 /* Tell install it's a directory. */
107#define SETFLAGS 0x02 /* Tell install to set flags. */
108#define NOCHANGEBITS (UF_IMMUTABLE | UF_APPEND | SF_IMMUTABLE | SF_APPEND)
109#define BACKUP_SUFFIX ".old"
110
111#ifndef O_BINARY
112# define O_BINARY 0
113#endif
114
115#ifndef EFTYPE
116# define EFTYPE EINVAL
117#endif
118
119#if defined(__WIN32__) || defined(__WIN64__) || defined(__OS2__)
120# define IS_SLASH(ch) ((ch) == '/' || (ch) == '\\')
121#else
122# define IS_SLASH(ch) ((ch) == '/')
123#endif
124
125
126/*********************************************************************************************************************************
127* Structures and Typedefs *
128*********************************************************************************************************************************/
129typedef struct INSTALLINSTANCE
130{
131 PKMKBUILTINCTX pCtx;
132
133 gid_t gid;
134 uid_t uid;
135 int dobackup, docompare, dodir, dopreserve, dostrip, nommap, safecopy, verbose, mode_given;
136 mode_t mode;
137 const char *suffix;
138 int ignore_perm_errors;
139 int hard_link_files_when_possible;
140 int verbose_hard_link_refusal;
141 int verbose_hard_link_mode_mismatch;
142 int dos2unix;
143} INSTALLINSTANCE;
144typedef INSTALLINSTANCE *PINSTALLINSTANCE;
145
146enum
147{
148 kInstOpt_Help = 261,
149 kInstOpt_Version,
150 kInstOpt_Verbose,
151 kInstOpt_Quiet,
152 kInstOpt_IgnorePermErrors,
153 kInstOpt_NoIgnorePermErrors,
154 kInstOpt_HardLinkFilesWhenPossible,
155 kInstOpt_NoHardLinkFilesWhenPossible,
156 kInstOpt_Dos2Unix,
157 kInstOpt_Unix2Dos,
158 kInstOpt_VerboseHardLinkRefusal,
159 kInstOpt_QuietHardLinkRefusal,
160 kInstOpt_VerboseHardLinkModeMismatch,
161 kInstOpt_QuietHardLinkModeMismatch
162};
163
164
165/*********************************************************************************************************************************
166* Global Variables *
167*********************************************************************************************************************************/
168static struct option long_options[] =
169{
170 { "help", no_argument, 0, kInstOpt_Help },
171 { "version", no_argument, 0, kInstOpt_Version },
172 { "quiet", no_argument, 0, kInstOpt_Quiet },
173 { "ignore-perm-errors", no_argument, 0, kInstOpt_IgnorePermErrors },
174 { "no-ignore-perm-errors", no_argument, 0, kInstOpt_NoIgnorePermErrors },
175 { "hard-link-files-when-possible", no_argument, 0, kInstOpt_HardLinkFilesWhenPossible },
176 { "no-hard-link-files-when-possible", no_argument, 0, kInstOpt_NoHardLinkFilesWhenPossible },
177 { "verbose-hard-link-refusal", no_argument, 0, kInstOpt_VerboseHardLinkRefusal },
178 { "quiet-hard-link-refusal", no_argument, 0, kInstOpt_QuietHardLinkRefusal },
179 { "verbose-hard-link-mode-mismatch", no_argument, 0, kInstOpt_VerboseHardLinkModeMismatch },
180 { "quiet-hard-link-mode-mismatch", no_argument, 0, kInstOpt_QuietHardLinkModeMismatch },
181 { "dos2unix", no_argument, 0, kInstOpt_Dos2Unix },
182 { "unix2dos", no_argument, 0, kInstOpt_Unix2Dos },
183#if 1 /* GNU coreutils compatibility: */
184 { "compare", no_argument, 0, 'C' },
185 { "directory", no_argument, 0, 'd' },
186 { "group", required_argument, 0, 'g' },
187 { "mode", required_argument, 0, 'm' },
188 { "owner", required_argument, 0, 'o' },
189 { "strip", no_argument, 0, 's' },
190 { "suffix", required_argument, 0, 'S' },
191 { "verbose", no_argument, 0, 'v' },
192#endif
193 { 0, 0, 0, 0 },
194};
195
196
197static int copy(PINSTALLINSTANCE, int, const char *, int *, const char *);
198static int compare(int, size_t, int, size_t);
199static int create_newfile(PINSTALLINSTANCE, const char *, int, struct stat *);
200static int create_tempfile(const char *, char *, size_t);
201static int install(PINSTALLINSTANCE, const char *, const char *, u_long, u_int);
202static int install_dir(PINSTALLINSTANCE, char *);
203static u_long numeric_id(PINSTALLINSTANCE, const char *, const char *);
204static int strip(PINSTALLINSTANCE, const char *);
205static int usage(PKMKBUILTINCTX, int);
206static char *last_slash(const char *);
207static KBOOL needs_dos2unix_conversion(const char *pszFilename);
208static KBOOL needs_unix2dos_conversion(const char *pszFilename);
209
210int
211kmk_builtin_install(int argc, char *argv[], char ** envp, PKMKBUILTINCTX pCtx)
212{
213 INSTALLINSTANCE This;
214 struct getopt_state_r gos;
215 struct stat from_sb, to_sb;
216 mode_t *set;
217 u_long fset = 0;
218 int ch, no_target;
219 u_int iflags;
220 char *flags;
221 const char *group, *owner, *to_name;
222 (void)envp;
223
224 /* Initialize global instance data. */
225 This.pCtx = pCtx;
226 This.mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
227 This.suffix = BACKUP_SUFFIX;
228 This.gid = 0;
229 This.uid = 0;
230 This.dobackup = 0;
231 This.docompare = 0;
232 This.dodir = 0;
233 This.dopreserve = 0;
234 This.dostrip = 0;
235 This.nommap = 0;
236 This.safecopy = 0;
237 This.verbose = 0;
238 This.mode_given = 0;
239 This.ignore_perm_errors = geteuid() != 0;
240 This.hard_link_files_when_possible = 0;
241 This.verbose_hard_link_refusal = 0;
242 This.verbose_hard_link_mode_mismatch = 0;
243 This.dos2unix = 0;
244
245 iflags = 0;
246 group = owner = NULL;
247 getopt_initialize_r(&gos, argc, argv, "B:bCcdf:g:Mm:o:pSsv", long_options, envp, pCtx);
248 while ((ch = getopt_long_r(&gos, NULL)) != -1)
249 switch(ch) {
250 case 'B':
251 This.suffix = gos.optarg;
252 /* FALLTHROUGH */
253 case 'b':
254 This.dobackup = 1;
255 break;
256 case 'C':
257 This.docompare = 1;
258 break;
259 case 'c':
260 /* For backwards compatibility. */
261 break;
262 case 'd':
263 This.dodir = 1;
264 break;
265 case 'f':
266#if defined(UF_IMMUTABLE) && K_OS != K_OS_GNU_KFBSD && K_OS != K_OS_GNU_HURD
267 flags = optarg;
268 if (strtofflags(&flags, &fset, NULL))
269 return errx(pCtx, EX_USAGE, "%s: invalid flag", flags);
270 iflags |= SETFLAGS;
271#else
272 (void)flags;
273#endif
274 break;
275 case 'g':
276 group = gos.optarg;
277 break;
278 case 'M':
279 This.nommap = 1;
280 break;
281 case 'm':
282 if (!(set = bsd_setmode(gos.optarg)))
283 return errx(pCtx, EX_USAGE, "invalid file mode: %s", gos.optarg);
284 This.mode = bsd_getmode(set, 0);
285 free(set);
286 This.mode_given = 1;
287 break;
288 case 'o':
289 owner = gos.optarg;
290 break;
291 case 'p':
292 This.docompare = This.dopreserve = 1;
293 break;
294 case 'S':
295 This.safecopy = 1;
296 This.verbose_hard_link_refusal = 0;
297 break;
298 case 's':
299 This.dostrip = 1;
300 This.verbose_hard_link_refusal = 0;
301 break;
302 case 'v':
303 case kInstOpt_Verbose:
304 This.verbose = 1;
305 break;
306 case kInstOpt_Quiet:
307 This.verbose = 0;
308 break;
309 case kInstOpt_Help:
310 usage(pCtx, 0);
311 return 0;
312 case kInstOpt_Version:
313 return kbuild_version(argv[0]);
314 case kInstOpt_IgnorePermErrors:
315 This.ignore_perm_errors = 1;
316 break;
317 case kInstOpt_NoIgnorePermErrors:
318 This.ignore_perm_errors = 0;
319 break;
320 case kInstOpt_HardLinkFilesWhenPossible:
321 This.hard_link_files_when_possible = 1;
322 break;
323 case kInstOpt_NoHardLinkFilesWhenPossible:
324 This.hard_link_files_when_possible = 0;
325 break;
326 case kInstOpt_VerboseHardLinkRefusal:
327 This.verbose_hard_link_refusal = 1;
328 break;
329 case kInstOpt_QuietHardLinkRefusal:
330 This.verbose_hard_link_refusal = 0;
331 break;
332 case kInstOpt_VerboseHardLinkModeMismatch:
333 This.verbose_hard_link_mode_mismatch = 1;
334 break;
335 case kInstOpt_QuietHardLinkModeMismatch:
336 This.verbose_hard_link_mode_mismatch = 0;
337 break;
338 case kInstOpt_Dos2Unix:
339 This.dos2unix = 1;
340 This.verbose_hard_link_refusal = 0;
341 break;
342 case kInstOpt_Unix2Dos:
343 This.dos2unix = -1;
344 This.verbose_hard_link_refusal = 0;
345 break;
346 case '?':
347 default:
348 return usage(pCtx, 1);
349 }
350 argc -= gos.optind;
351 argv += gos.optind;
352
353 /* some options make no sense when creating directories */
354 if (This.dostrip && This.dodir) {
355 warnx(pCtx, "-d and -s may not be specified together");
356 return usage(pCtx, 1);
357 }
358
359 /* must have at least two arguments, except when creating directories */
360 if (argc == 0 || (argc == 1 && !This.dodir))
361 return usage(pCtx, 1);
362
363 /* and unix2dos doesn't combine well with a couple of other options. */
364 if (This.dos2unix != 0) {
365 if (This.docompare) {
366 warnx(pCtx, "-C/-p and --dos2unix/unix2dos may not be specified together");
367 return usage(pCtx, 1);
368 }
369 if (This.dostrip) {
370 warnx(pCtx, "-s and --dos2unix/unix2dos may not be specified together");
371 return usage(pCtx, 1);
372 }
373 }
374
375 /* need to make a temp copy so we can compare stripped version */
376 if (This.docompare && This.dostrip)
377 This.safecopy = 1;
378
379 /* get group and owner id's */
380 if (group != NULL) {
381#ifndef _MSC_VER
382 struct group *gp;
383 if ((gp = getgrnam(group)) != NULL)
384 This.gid = gp->gr_gid;
385 else
386#endif
387 {
388 This.gid = (gid_t)numeric_id(&This, group, "group");
389 if (This.gid == (gid_t)-1)
390 return 1;
391 }
392 } else
393 This.gid = (gid_t)-1;
394
395 if (owner != NULL) {
396#ifndef _MSC_VER
397 struct passwd *pp;
398 if ((pp = getpwnam(owner)) != NULL)
399 This.uid = pp->pw_uid;
400 else
401#endif
402 {
403 This.uid = (uid_t)numeric_id(&This, owner, "user");
404 if (This.uid == (uid_t)-1)
405 return 1;
406 }
407 } else
408 This.uid = (uid_t)-1;
409
410 if (This.dodir) {
411 for (; *argv != NULL; ++argv) {
412 int rc = install_dir(&This, *argv);
413 if (rc)
414 return rc;
415 }
416 return EX_OK;
417 /* NOTREACHED */
418 }
419
420 no_target = stat(to_name = argv[argc - 1], &to_sb);
421 if (!no_target && S_ISDIR(to_sb.st_mode)) {
422 for (; *argv != to_name; ++argv) {
423 int rc = install(&This, *argv, to_name, fset, iflags | DIRECTORY);
424 if (rc)
425 return rc;
426 }
427 return EX_OK;
428 }
429
430 /* can't do file1 file2 directory/file */
431 if (argc != 2) {
432 warnx(pCtx, "wrong number or types of arguments");
433 return usage(pCtx, 1);
434 }
435
436 if (!no_target) {
437 if (stat(*argv, &from_sb))
438 return err(pCtx, EX_OSERR, "%s", *argv);
439 if (!S_ISREG(to_sb.st_mode)) {
440 errno = EFTYPE;
441 return err(pCtx, EX_OSERR, "%s", to_name);
442 }
443 if (to_sb.st_dev == from_sb.st_dev &&
444 to_sb.st_dev != 0 &&
445 to_sb.st_ino == from_sb.st_ino &&
446 to_sb.st_ino != 0 &&
447 !This.hard_link_files_when_possible)
448 return errx(pCtx, EX_USAGE,
449 "%s and %s are the same file", *argv, to_name);
450 }
451 return install(&This, *argv, to_name, fset, iflags);
452}
453
454#ifdef KMK_BUILTIN_STANDALONE
455mode_t g_fUMask;
456int main(int argc, char **argv, char **envp)
457{
458 KMKBUILTINCTX Ctx = { "kmk_install", NULL };
459 umask(g_fUMask = umask(0077));
460 return kmk_builtin_install(argc, argv, envp, &Ctx);
461}
462#endif
463
464static u_long
465numeric_id(PINSTALLINSTANCE pThis, const char *name, const char *type)
466{
467 u_long val;
468 char *ep;
469
470 /*
471 * XXX
472 * We know that uid_t's and gid_t's are unsigned longs.
473 */
474 errno = 0;
475 val = strtoul(name, &ep, 10);
476 if (errno)
477 return err(pThis->pCtx, -1, "%s", name);
478 if (*ep != '\0')
479 return errx(pThis->pCtx, -1, "unknown %s %s", type, name);
480 return (val);
481}
482
483/*
484 * install --
485 * build a path name and install the file
486 */
487static int
488install(PINSTALLINSTANCE pThis, const char *from_name, const char *to_name, u_long fset, u_int flags)
489{
490 struct stat from_sb, temp_sb, to_sb;
491 struct timeval tvb[2];
492 int devnull, files_match, from_fd, serrno, target;
493 int tempcopy, temp_fd, to_fd;
494 char backup[MAXPATHLEN], *p, pathbuf[MAXPATHLEN], tempfile[MAXPATHLEN];
495 int rc = EX_OK;
496
497 files_match = 0;
498 from_fd = -1;
499 to_fd = -1;
500 temp_fd = -1;
501
502 /* If try to install NULL file to a directory, fails. */
503 if (flags & DIRECTORY
504#if defined(__EMX__) || defined(_MSC_VER)
505 || ( stricmp(from_name, _PATH_DEVNULL)
506 && stricmp(from_name, "nul")
507# ifdef __EMX__
508 && stricmp(from_name, "/dev/nul")
509# endif
510 )
511#else
512 || strcmp(from_name, _PATH_DEVNULL)
513#endif
514 ) {
515 if (stat(from_name, &from_sb))
516 return err(pThis->pCtx, EX_OSERR, "%s", from_name);
517 if (!S_ISREG(from_sb.st_mode)) {
518 errno = EFTYPE;
519 return err(pThis->pCtx, EX_OSERR, "%s", from_name);
520 }
521 /* Build the target path. */
522 if (flags & DIRECTORY) {
523 (void)snprintf(pathbuf, sizeof(pathbuf), "%s/%s",
524 to_name,
525 (p = last_slash(from_name)) ? ++p : from_name);
526 to_name = pathbuf;
527 }
528 devnull = 0;
529 } else {
530 devnull = 1;
531 }
532
533 target = stat(to_name, &to_sb) == 0;
534
535 /* Only install to regular files. */
536 if (target && !S_ISREG(to_sb.st_mode)) {
537 errno = EFTYPE;
538 warn(pThis->pCtx, "%s", to_name);
539 return EX_OK;
540 }
541
542 /* Only copy safe if the target exists. */
543 tempcopy = pThis->safecopy && target;
544
545 /* Try hard linking if wanted and possible. */
546 if (pThis->hard_link_files_when_possible)
547 {
548#ifdef KBUILD_OS_OS2
549 const char *why_not = "not supported on OS/2";
550#else
551 const char *why_not = NULL;
552 if (devnull) {
553 why_not = "/dev/null";
554 } else if (pThis->dostrip) {
555 why_not = "strip (-s)";
556 } else if (pThis->docompare) {
557 why_not = "compare (-C)";
558 } else if (pThis->dobackup) {
559 why_not = "backup (-b/-B)";
560 } else if (pThis->safecopy) {
561 why_not = "safe copy (-S)";
562 } else if (lstat(from_name, &temp_sb)) {
563 why_not = "lstat on source failed";
564 } else if (S_ISLNK(temp_sb.st_mode)) {
565 why_not = "symlink";
566 } else if (!S_ISREG(temp_sb.st_mode)) {
567 why_not = "not regular file";
568# if defined(KBUILD_OS_WINDOWS) || defined(KBUILD_OS_OS2)
569 } else if ((pThis->mode & S_IWUSR) != (from_sb.st_mode & S_IWUSR)) {
570# else
571 } else if (pThis->mode != (from_sb.st_mode & ALLPERMS)) {
572# endif
573 if ( pThis->verbose_hard_link_mode_mismatch
574 || pThis->verbose_hard_link_refusal)
575 kmk_builtin_ctx_printf(pThis->pCtx, 0,
576 "install: warning: Not hard linking, mode differs: 0%03o, desires 0%03o\n"
577 "install: src path '%s'\n"
578 "install: dst path '%s'\n",
579 (from_sb.st_mode & ALLPERMS), pThis->mode, from_name, to_name);
580 why_not = NULL;
581 } else if (pThis->uid != (uid_t)-1 && pThis->uid != from_sb.st_uid) {
582 why_not = "uid mismatch";
583 } else if (pThis->gid != (gid_t)-1 && pThis->gid != from_sb.st_gid) {
584 why_not = "gid mismatch";
585 } else if (pThis->dos2unix > 0 && needs_dos2unix_conversion(from_name)) {
586 why_not = "dos2unix";
587 } else if (pThis->dos2unix < 0 && needs_unix2dos_conversion(from_name)) {
588 why_not = "unix2dos";
589 } else {
590 int rcLink = link(from_name, to_name);
591 if (rcLink != 0 && errno == EEXIST) {
592 unlink(to_name);
593 rcLink = link(from_name, to_name);
594 }
595 if (rcLink == 0) {
596 if (pThis->verbose)
597 kmk_builtin_ctx_printf(pThis->pCtx, 0,
598 "install: %s -> %s (hardlinked)\n", from_name, to_name);
599 goto l_done;
600 }
601 if (pThis->verbose)
602 kmk_builtin_ctx_printf(pThis->pCtx, 0, "install: hard linking '%s' to '%s' failed: %s\n",
603 to_name, from_name, strerror(errno));
604 why_not = NULL;
605 }
606#endif
607 if (why_not && pThis->verbose_hard_link_refusal)
608 kmk_builtin_ctx_printf(pThis->pCtx, 0, "install: not hard linking '%s' to '%s' because: %s\n",
609 to_name, from_name, why_not);
610
611 /* Can't hard link or we failed, continue as nothing happend. */
612 }
613
614 if (!devnull && (from_fd = open(from_name, O_RDONLY | O_BINARY | KMK_OPEN_NO_INHERIT, 0)) < 0)
615 return err(pThis->pCtx, EX_OSERR, "%s", from_name);
616
617 /* If we don't strip, we can compare first. */
618 if (pThis->docompare && !pThis->dostrip && target) {
619 if ((to_fd = open(to_name, O_RDONLY | O_BINARY | KMK_OPEN_NO_INHERIT, 0)) < 0) {
620 rc = err(pThis->pCtx, EX_OSERR, "%s", to_name);
621 goto l_done;
622 }
623 if (devnull)
624 files_match = to_sb.st_size == 0;
625 else
626 files_match = !compare(from_fd, (size_t)from_sb.st_size,
627 to_fd, (size_t)to_sb.st_size);
628
629 /* Close "to" file unless we match. */
630 if (!files_match) {
631 (void)close(to_fd);
632 to_fd = -1;
633 }
634 }
635
636 if (!files_match) {
637 if (tempcopy) {
638 to_fd = create_tempfile(to_name, tempfile,
639 sizeof(tempfile));
640 if (to_fd < 0) {
641 rc = err(pThis->pCtx, EX_OSERR, "%s", tempfile);
642 goto l_done;
643 }
644 } else {
645 if ((to_fd = create_newfile(pThis, to_name, target, &to_sb)) < 0) {
646 rc = err(pThis->pCtx, EX_OSERR, "%s", to_name);
647 goto l_done;
648 }
649 if (pThis->verbose)
650 kmk_builtin_ctx_printf(pThis->pCtx, 0, "install: %s -> %s\n", from_name, to_name);
651 }
652 if (!devnull) {
653 rc = copy(pThis, from_fd, from_name, &to_fd, tempcopy ? tempfile : to_name);
654 if (rc)
655 goto l_done;
656 }
657 }
658
659 if (pThis->dostrip) {
660#if defined(__EMX__) || defined(_MSC_VER)
661 /* close before we strip. */
662 close(to_fd);
663 to_fd = -1;
664#endif
665 rc = strip(pThis, tempcopy ? tempfile : to_name);
666 if (rc)
667 goto l_done;
668
669 /*
670 * Re-open our fd on the target, in case we used a strip
671 * that does not work in-place -- like GNU binutils strip.
672 */
673#if !defined(__EMX__) && !defined(_MSC_VER)
674 close(to_fd);
675#endif
676 to_fd = open(tempcopy ? tempfile : to_name, O_RDONLY | O_BINARY | KMK_OPEN_NO_INHERIT, 0);
677 if (to_fd < 0) {
678 rc = err(pThis->pCtx, EX_OSERR, "stripping %s", to_name);
679 goto l_done;
680 }
681 }
682
683 /*
684 * Compare the stripped temp file with the target.
685 */
686 if (pThis->docompare && pThis->dostrip && target) {
687 temp_fd = to_fd;
688
689 /* Re-open to_fd using the real target name. */
690 if ((to_fd = open(to_name, O_RDONLY | O_BINARY | KMK_OPEN_NO_INHERIT, 0)) < 0) {
691 rc = err(pThis->pCtx, EX_OSERR, "%s", to_name);
692 goto l_done;
693 }
694
695 if (fstat(temp_fd, &temp_sb)) {
696 serrno = errno;
697 (void)unlink(tempfile);
698 errno = serrno;
699 rc = err(pThis->pCtx, EX_OSERR, "%s", tempfile);
700 goto l_done;
701 }
702
703 if (compare(temp_fd, (size_t)temp_sb.st_size,
704 to_fd, (size_t)to_sb.st_size) == 0) {
705 /*
706 * If target has more than one link we need to
707 * replace it in order to snap the extra links.
708 * Need to preserve target file times, though.
709 */
710#if !defined(_MSC_VER) && !defined(__EMX__)
711 if (to_sb.st_nlink != 1) {
712 tvb[0].tv_sec = to_sb.st_atime;
713 tvb[0].tv_usec = 0;
714 tvb[1].tv_sec = to_sb.st_mtime;
715 tvb[1].tv_usec = 0;
716 (void)utimes(tempfile, tvb);
717 } else
718#endif
719 {
720
721 files_match = 1;
722 (void)unlink(tempfile);
723 }
724 (void) close(temp_fd);
725 temp_fd = -1;
726 }
727 }
728
729 /*
730 * Move the new file into place if doing a safe copy
731 * and the files are different (or just not compared).
732 */
733 if (tempcopy && !files_match) {
734#ifdef UF_IMMUTABLE
735 /* Try to turn off the immutable bits. */
736 if (to_sb.st_flags & NOCHANGEBITS)
737 (void)chflags(to_name, to_sb.st_flags & ~NOCHANGEBITS);
738#endif
739 if (pThis->dobackup) {
740 if ( (size_t)snprintf(backup, MAXPATHLEN, "%s%s", to_name, pThis->suffix)
741 != strlen(to_name) + strlen(pThis->suffix)) {
742 unlink(tempfile);
743 rc = errx(pThis->pCtx, EX_OSERR, "%s: backup filename too long",
744 to_name);
745 goto l_done;
746 }
747 if (pThis->verbose)
748 kmk_builtin_ctx_printf(pThis->pCtx, 0, "install: %s -> %s\n", to_name, backup);
749 if (rename(to_name, backup) < 0) {
750 serrno = errno;
751 unlink(tempfile);
752 errno = serrno;
753 rc = err(pThis->pCtx, EX_OSERR, "rename: %s to %s", to_name,
754 backup);
755 goto l_done;
756 }
757 }
758 if (pThis->verbose)
759 kmk_builtin_ctx_printf(pThis->pCtx, 0, "install: %s -> %s\n", from_name, to_name);
760 if (rename(tempfile, to_name) < 0) {
761 serrno = errno;
762 unlink(tempfile);
763 errno = serrno;
764 rc = err(pThis->pCtx, EX_OSERR, "rename: %s to %s", tempfile, to_name);
765 goto l_done;
766 }
767
768 /* Re-open to_fd so we aren't hosed by the rename(2). */
769 (void) close(to_fd);
770 if ((to_fd = open(to_name, O_RDONLY | O_BINARY | KMK_OPEN_NO_INHERIT, 0)) < 0) {
771 rc = err(pThis->pCtx, EX_OSERR, "%s", to_name);
772 goto l_done;
773 }
774 }
775
776 /*
777 * Preserve the timestamp of the source file if necessary.
778 */
779 if (pThis->dopreserve && !files_match && !devnull) {
780 tvb[0].tv_sec = from_sb.st_atime;
781 tvb[0].tv_usec = 0;
782 tvb[1].tv_sec = from_sb.st_mtime;
783 tvb[1].tv_usec = 0;
784 (void)utimes(to_name, tvb);
785 }
786
787 if (fstat(to_fd, &to_sb) == -1) {
788 serrno = errno;
789 (void)unlink(to_name);
790 errno = serrno;
791 rc = err(pThis->pCtx, EX_OSERR, "%s", to_name);
792 goto l_done;
793 }
794
795 /*
796 * Set owner, group, mode for target; do the chown first,
797 * chown may lose the setuid bits.
798 */
799#ifdef UF_IMMUTABLE
800 if ((pThis->gid != (gid_t)-1 && pThis->gid != to_sb.st_gid) ||
801 (pThis->uid != (uid_t)-1 && pThis->uid != to_sb.st_uid) ||
802 (pThis->mode != (to_sb.st_mode & ALLPERMS))) {
803 /* Try to turn off the immutable bits. */
804 if (to_sb.st_flags & NOCHANGEBITS)
805 (void)fchflags(to_fd, to_sb.st_flags & ~NOCHANGEBITS);
806 }
807#endif
808
809 if ((pThis->gid != (gid_t)-1 && pThis->gid != to_sb.st_gid) ||
810 (pThis->uid != (uid_t)-1 && pThis->uid != to_sb.st_uid))
811 if (fchown(to_fd, pThis->uid, pThis->gid) == -1) {
812 if (errno == EPERM && pThis->ignore_perm_errors) {
813 warn(pThis->pCtx, "%s: ignoring chown uid=%d gid=%d failure",
814 to_name, (int)pThis->uid, (int)pThis->gid);
815 } else {
816 serrno = errno;
817 (void)unlink(to_name);
818 errno = serrno;
819 rc = err(pThis->pCtx, EX_OSERR,"%s: chown/chgrp", to_name);
820 goto l_done;
821 }
822 }
823
824 if (pThis->mode != (to_sb.st_mode & ALLPERMS))
825 if (fchmod(to_fd, pThis->mode)) {
826 serrno = errno;
827 if (serrno == EPERM && pThis->ignore_perm_errors) {
828 fchmod(to_fd, pThis->mode & (ALLPERMS & ~0007000));
829 errno = errno;
830 warn(pThis->pCtx, "%s: ignoring chmod 0%o failure", to_name, (int)(pThis->mode & ALLPERMS));
831 } else {
832 serrno = errno;
833 (void)unlink(to_name);
834 errno = serrno;
835 rc = err(pThis->pCtx, EX_OSERR, "%s: chmod", to_name);
836 goto l_done;
837 }
838 }
839
840 /*
841 * If provided a set of flags, set them, otherwise, preserve the
842 * flags, except for the dump flag.
843 * NFS does not support flags. Ignore EOPNOTSUPP flags if we're just
844 * trying to turn off UF_NODUMP. If we're trying to set real flags,
845 * then warn if the the fs doesn't support it, otherwise fail.
846 */
847#ifdef UF_IMMUTABLE
848 if ( !devnull
849 && (flags & SETFLAGS || (from_sb.st_flags & ~UF_NODUMP) != to_sb.st_flags)
850 && fchflags(to_fd, flags & SETFLAGS ? fset : from_sb.st_flags & ~UF_NODUMP)) {
851 if (flags & SETFLAGS) {
852 if (errno == EOPNOTSUPP)
853 warn(pThis->pCtx, "%s: chflags", to_name);
854 else {
855 serrno = errno;
856 (void)unlink(to_name);
857 errno = serrno;
858 rc = err(pThis->pCtx, EX_OSERR, "%s: chflags", to_name);
859 goto l_done;
860 }
861 }
862 }
863#endif
864
865l_done:
866 if (to_fd >= 0)
867 (void)close(to_fd);
868 if (temp_fd >= 0)
869 (void)close(temp_fd);
870 if (from_fd >= 0 && !devnull)
871 (void)close(from_fd);
872 return rc;
873}
874
875/*
876 * compare --
877 * compare two files; non-zero means files differ
878 */
879static int
880compare(int from_fd, size_t from_len, int to_fd, size_t to_len)
881{
882 char buf1[MAXBSIZE];
883 char buf2[MAXBSIZE];
884 int n1, n2;
885 int rv;
886
887 if (from_len != to_len)
888 return 1;
889
890 if (from_len <= MAX_CMP_SIZE) {
891 rv = 0;
892 lseek(from_fd, 0, SEEK_SET);
893 lseek(to_fd, 0, SEEK_SET);
894 while (rv == 0) {
895 n1 = read(from_fd, buf1, sizeof(buf1));
896 if (n1 == 0)
897 break; /* EOF */
898 else if (n1 > 0) {
899 n2 = read(to_fd, buf2, n1);
900 if (n2 == n1)
901 rv = memcmp(buf1, buf2, n1);
902 else
903 rv = 1; /* out of sync */
904 } else
905 rv = 1; /* read failure */
906 }
907 lseek(from_fd, 0, SEEK_SET);
908 lseek(to_fd, 0, SEEK_SET);
909 } else
910 rv = 1; /* don't bother in this case */
911
912 return rv;
913}
914
915/*
916 * create_tempfile --
917 * create a temporary file based on path and open it
918 */
919int
920create_tempfile(const char *path, char *temp, size_t tsize)
921{
922 static char s_szTemplate[] = "INS@XXXXXX";
923 const char *p = last_slash(path);
924 if (p) {
925 size_t cchDir = ++p - path;
926 if (cchDir + sizeof(s_szTemplate) <= tsize) {
927 memcpy(temp, path, cchDir);
928 memcpy(&temp[cchDir], s_szTemplate, sizeof(s_szTemplate));
929 } else
930 return EOVERFLOW;
931 } else if (tsize >= sizeof(s_szTemplate))
932 memcpy(temp, s_szTemplate, sizeof(s_szTemplate));
933 else
934 return EOVERFLOW;
935
936 return (mkstemp(temp));
937}
938
939/*
940 * create_newfile --
941 * create a new file, overwriting an existing one if necessary
942 */
943int
944create_newfile(PINSTALLINSTANCE pThis, const char *path, int target, struct stat *sbp)
945{
946 char backup[MAXPATHLEN];
947 int saved_errno = 0;
948 int newfd;
949
950 if (target) {
951 /*
952 * Unlink now... avoid ETXTBSY errors later. Try to turn
953 * off the append/immutable bits -- if we fail, go ahead,
954 * it might work.
955 */
956#ifdef UF_IMMUTABLE
957 if (sbp->st_flags & NOCHANGEBITS)
958 (void)chflags(path, sbp->st_flags & ~NOCHANGEBITS);
959#endif
960
961 if (pThis->dobackup) {
962 if ( (size_t)snprintf(backup, MAXPATHLEN, "%s%s", path, pThis->suffix)
963 != strlen(path) + strlen(pThis->suffix)) {
964 errx(pThis->pCtx, EX_OSERR, "%s: backup filename too long", path);
965 errno = ENAMETOOLONG;
966 return -1;
967 }
968 (void)snprintf(backup, MAXPATHLEN, "%s%s", path, pThis->suffix);
969 if (pThis->verbose)
970 kmk_builtin_ctx_printf(pThis->pCtx, 0, "install: %s -> %s\n", path, backup);
971 if (rename(path, backup) < 0) {
972 err(pThis->pCtx, EX_OSERR, "rename: %s to %s", path, backup);
973 return -1;
974 }
975 } else
976 if (unlink(path) < 0)
977 saved_errno = errno;
978 }
979
980 newfd = open(path, O_CREAT | O_RDWR | O_TRUNC | O_BINARY | KMK_OPEN_NO_INHERIT, S_IRUSR | S_IWUSR);
981 if (newfd < 0 && saved_errno != 0)
982 errno = saved_errno;
983 return newfd;
984}
985
986/*
987 * Write error handler.
988 */
989static int write_error(PINSTALLINSTANCE pThis, int *ptr_to_fd, const char *to_name, int nw)
990{
991 int serrno = errno;
992 (void)close(*ptr_to_fd);
993 *ptr_to_fd = -1;
994 (void)unlink(to_name);
995 errno = nw > 0 ? EIO : serrno;
996 return err(pThis->pCtx, EX_OSERR, "%s", to_name);
997}
998
999/*
1000 * Read error handler.
1001 */
1002static int read_error(PINSTALLINSTANCE pThis, const char *from_name, int *ptr_to_fd, const char *to_name)
1003{
1004 int serrno = errno;
1005 (void)close(*ptr_to_fd);
1006 *ptr_to_fd = -1;
1007 (void)unlink(to_name);
1008 errno = serrno;
1009 return err(pThis->pCtx, EX_OSERR, "%s", from_name);
1010}
1011
1012/*
1013 * copy --
1014 * copy from one file to another
1015 */
1016static int
1017copy(PINSTALLINSTANCE pThis, int from_fd, const char *from_name, int *ptr_to_fd, const char *to_name)
1018{
1019 KBOOL fPendingCr = K_FALSE;
1020 KSIZE cchDst;
1021 int nr, nw;
1022 char buf[MAXBSIZE];
1023 int to_fd = *ptr_to_fd;
1024
1025 /* Rewind file descriptors. */
1026 if (lseek(from_fd, (off_t)0, SEEK_SET) == (off_t)-1)
1027 return err(pThis->pCtx, EX_OSERR, "lseek: %s", from_name);
1028 if (lseek(to_fd, (off_t)0, SEEK_SET) == (off_t)-1)
1029 return err(pThis->pCtx, EX_OSERR, "lseek: %s", to_name);
1030
1031 if (pThis->dos2unix == 0) {
1032 /*
1033 * Copy bytes, no conversion.
1034 */
1035 while ((nr = read(from_fd, buf, sizeof(buf))) > 0)
1036 if ((nw = write(to_fd, buf, nr)) != nr)
1037 return write_error(pThis, ptr_to_fd, to_name, nw);
1038 } else if (pThis->dos2unix > 0) {
1039 /*
1040 * CRLF -> LF is a reduction, so we can work with full buffers.
1041 */
1042 while ((nr = read(from_fd, buf, sizeof(buf))) > 0) {
1043 if ( fPendingCr
1044 && buf[0] != '\n'
1045 && (nw = write(to_fd, "\r", 1)) != 1)
1046 return write_error(pThis, ptr_to_fd, to_name, nw);
1047
1048 fPendingCr = dos2unix_convert_to_unix(buf, nr, buf, &cchDst);
1049
1050 nw = write(to_fd, buf, cchDst);
1051 if (nw != (int)cchDst)
1052 return write_error(pThis, ptr_to_fd, to_name, nw);
1053 }
1054 } else {
1055 /*
1056 * LF -> CRLF is an expansion, so we work with half buffers, reading
1057 * into the upper half of the buffer and expanding into the full buffer.
1058 * The conversion will never expand to more than the double size.
1059 *
1060 * Note! We do not convert valid CRLF line endings. This gives us
1061 * valid DOS text, but no round-trip conversion.
1062 */
1063 char * const pchSrc = &buf[sizeof(buf) / 2];
1064 while ((nr = read(from_fd, pchSrc, sizeof(buf) / 2)) > 0) {
1065 if ( fPendingCr
1066 && pchSrc[0] != '\n'
1067 && (nw = write(to_fd, "\r", 1))!= 1)
1068 return write_error(pThis, ptr_to_fd, to_name, nw);
1069
1070 fPendingCr = dos2unix_convert_to_dos(pchSrc, nr, buf, &cchDst);
1071
1072 nw = write(to_fd, buf, cchDst);
1073 if (nw != (int)cchDst)
1074 return write_error(pThis, ptr_to_fd, to_name, nw);
1075 }
1076 }
1077
1078 /* Check for read error. */
1079 if (nr != 0)
1080 return read_error(pThis, from_name, ptr_to_fd, to_name);
1081
1082 /* When converting, we might have a pending final CR to write. */
1083 if ( fPendingCr
1084 && (nw = write(to_fd, "\r", 1))!= 1)
1085 return write_error(pThis, ptr_to_fd, to_name, nw);
1086
1087 return EX_OK;
1088}
1089
1090/*
1091 * strip --
1092 * use strip(1) to strip the target file
1093 */
1094static int
1095strip(PINSTALLINSTANCE pThis, const char *to_name)
1096{
1097#if defined(__EMX__) || defined(_MSC_VER)
1098 const char *stripbin = getenv("STRIPBIN");
1099 if (stripbin == NULL)
1100 stripbin = "strip";
1101 (void)pThis;
1102 return spawnlp(P_WAIT, stripbin, stripbin, to_name, NULL);
1103#else
1104 const char *stripbin;
1105 int serrno, status;
1106 pid_t pid;
1107
1108 pid = fork();
1109 switch (pid) {
1110 case -1:
1111 serrno = errno;
1112 (void)unlink(to_name);
1113 errno = serrno;
1114 return err(pThis->pCtx, EX_TEMPFAIL, "fork");
1115 case 0:
1116 stripbin = getenv("STRIPBIN");
1117 if (stripbin == NULL)
1118 stripbin = "strip";
1119 execlp(stripbin, stripbin, to_name, (char *)NULL);
1120 err(pThis->pCtx, EX_OSERR, "exec(%s)", stripbin);
1121 exit(EX_OSERR);
1122 default:
1123 if (waitpid(pid, &status, 0) == -1 || status) {
1124 serrno = errno;
1125 (void)unlink(to_name);
1126 errno = serrno;
1127 return err(pThis->pCtx, EX_SOFTWARE, "waitpid");
1128 /* NOTREACHED */
1129 }
1130 }
1131 return 0;
1132#endif
1133}
1134
1135/*
1136 * install_dir --
1137 * build directory heirarchy
1138 */
1139static int
1140install_dir(PINSTALLINSTANCE pThis, char *path)
1141{
1142 char *p;
1143 struct stat sb;
1144 int ch;
1145
1146 for (p = path;; ++p)
1147 if ( !*p
1148 || ( p != path
1149 && IS_SLASH(*p)
1150#if defined(_MSC_VER) /* stat("C:") fails (VC++ v10). Just skip it since it's unnecessary. */
1151 && (p - path != 2 || p[-1] != ':')
1152#endif
1153 )) {
1154 ch = *p;
1155 *p = '\0';
1156 if (stat(path, &sb)) {
1157 if (errno != ENOENT || mkdir(path, 0755) < 0) {
1158 return err(pThis->pCtx, EX_OSERR, "mkdir %s", path);
1159 /* NOTREACHED */
1160 } else if (pThis->verbose)
1161 kmk_builtin_ctx_printf(pThis->pCtx, 0, "install: mkdir %s\n", path);
1162 } else if (!S_ISDIR(sb.st_mode))
1163 return errx(pThis->pCtx, EX_OSERR, "%s exists but is not a directory", path);
1164 if (!(*p = ch))
1165 break;
1166 }
1167
1168 if ((pThis->gid != (gid_t)-1 || pThis->uid != (uid_t)-1) && chown(path, pThis->uid, pThis->gid))
1169 warn(pThis->pCtx, "chown %u:%u %s", pThis->uid, pThis->gid, path);
1170 if (chmod(path, pThis->mode))
1171 warn(pThis->pCtx, "chmod %o %s", pThis->mode, path);
1172 return EX_OK;
1173}
1174
1175/*
1176 * usage --
1177 * print a usage message and die
1178 */
1179static int
1180usage(PKMKBUILTINCTX pCtx, int fIsErr)
1181{
1182 kmk_builtin_ctx_printf(pCtx, fIsErr,
1183"usage: %s [-bCcpSsv] [--[no-]hard-link-files-when-possible]\n"
1184" [--verbose-hard-link-refusal] [--verbose-hard-link-mode-mismatch]\n"
1185" [--[no-]ignore-perm-errors] [-B suffix] [-f flags] [-g group]\n"
1186" [-m mode] [-o owner] [--dos2unix|--unix2dos] file1 file2\n"
1187" or: %s [-bCcpSsv] [--[no-]ignore-perm-errors] [-B suffix] [-f flags]\n"
1188" [-g group] [-m mode] [-o owner] file1 ... fileN directory\n"
1189" or: %s -d [-v] [-g group] [-m mode] [-o owner] directory ...\n"
1190" or: %s --help\n"
1191" or: %s --version\n",
1192 pCtx->pszProgName, pCtx->pszProgName, pCtx->pszProgName,
1193 pCtx->pszProgName, pCtx->pszProgName);
1194 return EX_USAGE;
1195}
1196
1197/* figures out where the last slash or colon is. */
1198static char *
1199last_slash(const char *path)
1200{
1201#if defined(__WIN32__) || defined(__WIN64__) || defined(__OS2__)
1202 char *p = (char *)strrchr(path, '/');
1203 if (p)
1204 {
1205 char *p2 = strrchr(p, '\\');
1206 if (p2)
1207 p = p2;
1208 }
1209 else
1210 {
1211 p = (char *)strrchr(path, '\\');
1212 if (!p && isalpha(path[0]) && path[1] == ':')
1213 p = (char *)&path[1];
1214 }
1215 return p;
1216#else
1217 return strrchr(path, '/');
1218#endif
1219}
1220
1221/**
1222 * Checks if @a pszFilename actually needs dos2unix conversion.
1223 *
1224 * @returns boolean.
1225 * @param pszFilename The name of the file to check.
1226 */
1227static KBOOL needs_dos2unix_conversion(const char *pszFilename)
1228{
1229 KU32 fStyle = 0;
1230 int iErr = dos2unix_analyze_file(pszFilename, &fStyle, NULL, NULL);
1231 return iErr != 0
1232 || (fStyle & (DOS2UNIX_STYLE_MASK | DOS2UNIX_F_BINARY)) != DOS2UNIX_STYLE_UNIX;
1233}
1234
1235/**
1236 * Checks if @a pszFilename actually needs unix2dos conversion.
1237 *
1238 * @returns boolean.
1239 * @param pszFilename The name of the file to check.
1240 */
1241static KBOOL needs_unix2dos_conversion(const char *pszFilename)
1242{
1243 KU32 fStyle = 0;
1244 int iErr = dos2unix_analyze_file(pszFilename, &fStyle, NULL, NULL);
1245 return iErr != 0
1246 || (fStyle & (DOS2UNIX_STYLE_MASK | DOS2UNIX_F_BINARY)) != DOS2UNIX_STYLE_DOS;
1247}
1248
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette