1 /* $OpenBSD: util.c,v 1.4 2014/06/09 15:50:08 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 512 31 32 void 33 filecopy(const char *srcfile, const char *dstfile) 34 { 35 struct stat sb; 36 ssize_t sz, n; 37 int sfd, dfd; 38 char *buf; 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 %s", srcfile); 46 if (fstat(sfd, &sb) == -1) 47 err(1, "fstat"); 48 sz = sb.st_size; 49 50 dfd = open(dstfile, O_WRONLY|O_CREAT); 51 if (dfd == -1) 52 err(1, "open %s", dstfile); 53 if (fchown(dfd, 0, 0) == -1) 54 err(1, "chown"); 55 if (fchmod(dfd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) == -1) 56 err(1, "chmod"); 57 58 while (sz > 0) { 59 n = MIN(sz, BUFSIZE); 60 if ((n = read(sfd, buf, n)) == -1) 61 err(1, "read"); 62 sz -= n; 63 if (write(dfd, buf, n) != n) 64 err(1, "write"); 65 } 66 67 ftruncate(dfd, sb.st_size); 68 69 close(dfd); 70 close(sfd); 71 free(buf); 72 } 73 74 char * 75 fileprefix(const char *base, const char *path) 76 { 77 char *r, *s; 78 int n; 79 80 if ((s = malloc(PATH_MAX)) == NULL) 81 err(1, "malloc"); 82 n = snprintf(s, PATH_MAX, "%s/%s", base, path); 83 if (n < 1 || n >= PATH_MAX) 84 err(1, "snprintf"); 85 if ((r = realpath(s, NULL)) == NULL) 86 err(1, "realpath"); 87 free(s); 88 89 return r; 90 } 91