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 #ifndef lint 13 static const char sccsid[] = "$Id: ex_source.c,v 10.17 2011/12/19 16:17:06 zy Exp $"; 14 #endif /* not lint */ 15 16 #include <sys/types.h> 17 #include <sys/queue.h> 18 #include <sys/stat.h> 19 20 #include <bitstring.h> 21 #include <errno.h> 22 #include <fcntl.h> 23 #include <limits.h> 24 #include <stdio.h> 25 #include <stdlib.h> 26 #include <string.h> 27 #include <unistd.h> 28 29 #include "../common/common.h" 30 31 /* 32 * ex_source -- :source file 33 * Execute ex commands from a file. 34 * 35 * PUBLIC: int ex_source __P((SCR *, EXCMD *)); 36 */ 37 int 38 ex_source(SCR *sp, EXCMD *cmdp) 39 { 40 struct stat sb; 41 int fd, len; 42 char *bp; 43 char *name, *np; 44 size_t nlen; 45 CHAR_T *wp; 46 size_t wlen; 47 int rc; 48 49 INT2CHAR(sp, cmdp->argv[0]->bp, cmdp->argv[0]->len + 1, name, nlen); 50 if ((fd = open(name, O_RDONLY, 0)) < 0 || fstat(fd, &sb)) 51 goto err; 52 53 /* 54 * XXX 55 * I'd like to test to see if the file is too large to malloc. Since 56 * we don't know what size or type off_t's or size_t's are, what the 57 * largest unsigned integral type is, or what random insanity the local 58 * C compiler will perpetrate, doing the comparison in a portable way 59 * is flatly impossible. So, put an fairly unreasonable limit on it, 60 * I don't want to be dropping core here. 61 */ 62 #define MEGABYTE 1048576 63 if (sb.st_size > MEGABYTE) { 64 errno = ENOMEM; 65 goto err; 66 } 67 68 MALLOC(sp, bp, char *, (size_t)sb.st_size + 1); 69 if (bp == NULL) { 70 (void)close(fd); 71 return (1); 72 } 73 bp[sb.st_size] = '\0'; 74 75 /* Read the file into memory. */ 76 len = read(fd, bp, (int)sb.st_size); 77 (void)close(fd); 78 if (len == -1 || len != sb.st_size) { 79 if (len != sb.st_size) 80 errno = EIO; 81 free(bp); 82 err: msgq_str(sp, M_SYSERR, name, "%s"); 83 return (1); 84 } 85 86 np = strdup(name); 87 if (CHAR2INT(sp, bp, (size_t)sb.st_size + 1, wp, wlen)) 88 msgq(sp, M_ERR, "323|Invalid input. Truncated."); 89 /* Put it on the ex queue. */ 90 rc = ex_run_str(sp, np, wp, wlen - 1, 1, 0); 91 if (np != NULL) 92 free(np); 93 free(bp); 94 return (rc); 95 } 96