1 /* $OpenBSD: util.c,v 1.5 2015/01/16 00:05:12 deraadt 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/stat.h> 20 #include <err.h> 21 #include <fcntl.h> 22 #include <stdio.h> 23 #include <stdlib.h> 24 #include <string.h> 25 #include <unistd.h> 26 #include <limits.h> 27 28 #include "installboot.h" 29 30 #define MINIMUM(a, b) (((a) < (b)) ? (a) : (b)) 31 32 #define BUFSIZE 512 33 34 void 35 filecopy(const char *srcfile, const char *dstfile) 36 { 37 struct stat sb; 38 ssize_t sz, n; 39 int sfd, dfd; 40 char *buf; 41 42 if ((buf = malloc(BUFSIZE)) == NULL) 43 err(1, "malloc"); 44 45 sfd = open(srcfile, O_RDONLY); 46 if (sfd == -1) 47 err(1, "open %s", srcfile); 48 if (fstat(sfd, &sb) == -1) 49 err(1, "fstat"); 50 sz = sb.st_size; 51 52 dfd = open(dstfile, O_WRONLY|O_CREAT); 53 if (dfd == -1) 54 err(1, "open %s", dstfile); 55 if (fchown(dfd, 0, 0) == -1) 56 err(1, "chown"); 57 if (fchmod(dfd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) == -1) 58 err(1, "chmod"); 59 60 while (sz > 0) { 61 n = MINIMUM(sz, BUFSIZE); 62 if ((n = read(sfd, buf, n)) == -1) 63 err(1, "read"); 64 sz -= n; 65 if (write(dfd, buf, n) != n) 66 err(1, "write"); 67 } 68 69 ftruncate(dfd, sb.st_size); 70 71 close(dfd); 72 close(sfd); 73 free(buf); 74 } 75 76 char * 77 fileprefix(const char *base, const char *path) 78 { 79 char *r, *s; 80 int n; 81 82 if ((s = malloc(PATH_MAX)) == NULL) 83 err(1, "malloc"); 84 n = snprintf(s, PATH_MAX, "%s/%s", base, path); 85 if (n < 1 || n >= PATH_MAX) 86 err(1, "snprintf"); 87 if ((r = realpath(s, NULL)) == NULL) 88 err(1, "realpath"); 89 free(s); 90 91 return r; 92 } 93