1 /* $NetBSD: buffer.c,v 1.1.1.1 2018/04/15 19:32:48 christos Exp $ */ 2 3 /* 4 * Copyright (c) Christos Zoulas 2017. 5 * All Rights Reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 10 * 1. Redistributions of source code must retain the above copyright 11 * notice immediately at the beginning of the file, without modification, 12 * this list of conditions, and the following disclaimer. 13 * 2. Redistributions in binary form must reproduce the above copyright 14 * notice, this list of conditions and the following disclaimer in the 15 * documentation and/or other materials provided with the distribution. 16 * 17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR 21 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 27 * SUCH DAMAGE. 28 */ 29 #include "file.h" 30 31 #ifndef lint 32 #if 0 33 FILE_RCSID("@(#)$File: buffer.c,v 1.4 2018/02/21 21:26:00 christos Exp $") 34 #else 35 __RCSID("$NetBSD: buffer.c,v 1.1.1.1 2018/04/15 19:32:48 christos Exp $"); 36 #endif 37 #endif /* lint */ 38 39 #include "magic.h" 40 #include <unistd.h> 41 #include <string.h> 42 #include <stdlib.h> 43 #include <sys/stat.h> 44 45 void 46 buffer_init(struct buffer *b, int fd, const void *data, size_t len) 47 { 48 b->fd = fd; 49 if (b->fd == -1 || fstat(b->fd, &b->st) == -1) 50 memset(&b->st, 0, sizeof(b->st)); 51 b->fbuf = data; 52 b->flen = len; 53 b->eoff = 0; 54 b->ebuf = NULL; 55 b->elen = 0; 56 } 57 58 void 59 buffer_fini(struct buffer *b) 60 { 61 free(b->ebuf); 62 } 63 64 int 65 buffer_fill(const struct buffer *bb) 66 { 67 struct buffer *b = CCAST(struct buffer *, bb); 68 69 if (b->elen != 0) 70 return b->elen == (size_t)~0 ? -1 : 0; 71 72 if (!S_ISREG(b->st.st_mode)) 73 goto out; 74 75 b->elen = (size_t)b->st.st_size < b->flen ? 76 (size_t)b->st.st_size : b->flen; 77 if ((b->ebuf = malloc(b->elen)) == NULL) 78 goto out; 79 80 b->eoff = b->st.st_size - b->elen; 81 if (pread(b->fd, b->ebuf, b->elen, b->eoff) == -1) { 82 free(b->ebuf); 83 goto out; 84 } 85 86 return 0; 87 out: 88 b->elen = (size_t)~0; 89 return -1; 90 } 91