1 /* $OpenBSD: ex_source.c,v 1.8 2013/05/03 20:43:25 kili Exp $ */ 2 3 /*- 4 * Copyright (c) 1992, 1993, 1994 5 * The Regents of the University of California. All rights reserved. 6 * Copyright (c) 1992, 1993, 1994, 1995, 1996 7 * Keith Bostic. All rights reserved. 8 * 9 * See the LICENSE file for redistribution information. 10 */ 11 12 #include "config.h" 13 14 #include <sys/types.h> 15 #include <sys/queue.h> 16 #include <sys/stat.h> 17 18 #include <bitstring.h> 19 #include <errno.h> 20 #include <fcntl.h> 21 #include <limits.h> 22 #include <stdio.h> 23 #include <stdlib.h> 24 #include <string.h> 25 #include <unistd.h> 26 27 #include "../common/common.h" 28 29 /* 30 * ex_sourcefd -- :source already opened file 31 * Execute ex commands from the given file descriptor 32 * 33 * PUBLIC: int ex_sourcefd(SCR *, EXCMD *, int); 34 */ 35 int 36 ex_sourcefd(sp, cmdp, fd) 37 SCR *sp; 38 EXCMD *cmdp; 39 int fd; 40 { 41 struct stat sb; 42 int len; 43 char *bp, *name; 44 45 name = cmdp->argv[0]->bp; 46 if (fstat(fd, &sb)) 47 goto err; 48 49 /* 50 * XXX 51 * I'd like to test to see if the file is too large to malloc. Since 52 * we don't know what size or type off_t's or size_t's are, what the 53 * largest unsigned integral type is, or what random insanity the local 54 * C compiler will perpetrate, doing the comparison in a portable way 55 * is flatly impossible. So, put an fairly unreasonable limit on it, 56 * I don't want to be dropping core here. 57 */ 58 #define MEGABYTE 1048576 59 if (sb.st_size > MEGABYTE) { 60 errno = ENOMEM; 61 goto err; 62 } 63 64 MALLOC(sp, bp, char *, (size_t)sb.st_size + 1); 65 if (bp == NULL) { 66 (void)close(fd); 67 return (1); 68 } 69 bp[sb.st_size] = '\0'; 70 71 /* Read the file into memory. */ 72 len = read(fd, bp, (int)sb.st_size); 73 (void)close(fd); 74 if (len == -1 || len != sb.st_size) { 75 if (len != sb.st_size) 76 errno = EIO; 77 free(bp); 78 err: msgq_str(sp, M_SYSERR, name, "%s"); 79 return (1); 80 } 81 82 /* Put it on the ex queue. */ 83 return (ex_run_str(sp, name, bp, (size_t)sb.st_size, 1, 1)); 84 } 85 86 /* 87 * ex_source -- :source file 88 * Execute ex commands from a file. 89 * 90 * PUBLIC: int ex_source(SCR *, EXCMD *); 91 */ 92 int 93 ex_source(sp, cmdp) 94 SCR *sp; 95 EXCMD *cmdp; 96 { 97 char *name; 98 int fd; 99 100 name = cmdp->argv[0]->bp; 101 if ((fd = open(name, O_RDONLY, 0)) >= 0) 102 return (ex_sourcefd(sp, cmdp, fd)); 103 104 msgq_str(sp, M_SYSERR, name, "%s"); 105 return (1); 106 } 107