1 /*- 2 * Copyright (c) 1992, 1993, 1994 3 * The Regents of the University of California. All rights reserved. 4 * Copyright (c) 1992, 1993, 1994, 1995, 1996 5 * Keith Bostic. All rights reserved. 6 * 7 * See the LICENSE file for redistribution information. 8 */ 9 10 #include "config.h" 11 12 #include <sys/types.h> 13 #include <sys/queue.h> 14 #include <sys/stat.h> 15 16 #include <bitstring.h> 17 #include <errno.h> 18 #include <fcntl.h> 19 #include <limits.h> 20 #include <stdio.h> 21 #include <stdlib.h> 22 #include <string.h> 23 #include <unistd.h> 24 25 #include "../common/common.h" 26 27 /* 28 * ex_source -- :source file 29 * Execute ex commands from a file. 30 * 31 * PUBLIC: int ex_source(SCR *, EXCMD *); 32 */ 33 int 34 ex_source(SCR *sp, EXCMD *cmdp) 35 { 36 struct stat sb; 37 int fd, len; 38 char *bp; 39 char *name, *np; 40 size_t nlen; 41 CHAR_T *wp; 42 size_t wlen; 43 int rc; 44 45 INT2CHAR(sp, cmdp->argv[0]->bp, cmdp->argv[0]->len + 1, name, nlen); 46 if ((fd = open(name, O_RDONLY, 0)) < 0 || 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, (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 np = strdup(name); 83 if (CHAR2INT(sp, bp, (size_t)sb.st_size + 1, wp, wlen)) 84 msgq(sp, M_ERR, "323|Invalid input. Truncated."); 85 /* Put it on the ex queue. */ 86 rc = ex_run_str(sp, np, wp, wlen - 1, 1, 0); 87 free(np); 88 free(bp); 89 return (rc); 90 } 91