1 /* $OpenBSD: util.c,v 1.2 2014/01/18 03:07:05 jsing Exp $ */ 2 3 /* 4 * Copyright (c) 2014 Joel Sing <jsing@openbsd.org> 5 * 6 * Permission to use, copy, modify, and distribute this software for any 7 * purpose with or without fee is hereby granted, provided that the above 8 * copyright notice and this permission notice appear in all copies. 9 * 10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 17 */ 18 19 #include <sys/param.h> 20 #include <sys/stat.h> 21 #include <err.h> 22 #include <fcntl.h> 23 #include <stdio.h> 24 #include <stdlib.h> 25 #include <string.h> 26 #include <unistd.h> 27 28 #include "installboot.h" 29 30 #define BUFSIZE 2048 31 32 void 33 filecopy(const char *srcfile, const char *dstfile) 34 { 35 char *buf, tempfile[MAXPATHLEN]; 36 struct stat sb; 37 ssize_t sz, n; 38 int sfd, dfd; 39 40 if ((buf = malloc(BUFSIZE)) == NULL) 41 err(1, "malloc"); 42 43 sfd = open(srcfile, O_RDONLY); 44 if (sfd == -1) 45 err(1, "open"); 46 if (fstat(sfd, &sb) == -1) 47 err(1, "fstat"); 48 sz = sb.st_size; 49 50 snprintf(tempfile, sizeof(tempfile), "%s.XXXXXXXX", dstfile); 51 dfd = mkstemp(tempfile); 52 if (dfd == -1) 53 err(1, "mkstemp"); 54 55 if (chown(tempfile, 0, 0) == -1) 56 err(1, "chown"); 57 if (chmod(tempfile, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) == -1) 58 err(1, "chmod"); 59 60 if (verbose) 61 fprintf(stderr, "Copying %s to %s\n", srcfile, tempfile); 62 63 while (sz > 0) { 64 n = MIN(sz, BUFSIZE); 65 if ((n = read(sfd, buf, n)) == -1) 66 err(1, "read"); 67 sz -= n; 68 if (write(dfd, buf, n) != n) 69 err(1, "write"); 70 } 71 72 close(dfd); 73 close(sfd); 74 free(buf); 75 76 if (verbose) 77 fprintf(stderr, "Renaming %s to %s\n", tempfile, dstfile); 78 79 if (rename(tempfile, dstfile) == -1) 80 err(1, "rename"); 81 } 82 83 char * 84 fileprefix(const char *base, const char *path) 85 { 86 char *r, *s; 87 int n; 88 89 if ((s = malloc(PATH_MAX)) == NULL) 90 err(1, "malloc"); 91 n = snprintf(s, PATH_MAX, "%s/%s", base, path); 92 if (n < 1 || n >= PATH_MAX) 93 err(1, "snprintf"); 94 if ((r = realpath(s, NULL)) == NULL) 95 err(1, "realpath"); 96 free(s); 97 98 return r; 99 } 100