1 /* $OpenBSD: ex_source.c,v 1.7 2009/10/27 23:59:47 deraadt 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_source -- :source file
31 * Execute ex commands from a file.
32 *
33 * PUBLIC: int ex_source(SCR *, EXCMD *);
34 */
35 int
ex_source(sp,cmdp)36 ex_source(sp, cmdp)
37 SCR *sp;
38 EXCMD *cmdp;
39 {
40 struct stat sb;
41 int fd, len;
42 char *bp, *name;
43
44 name = cmdp->argv[0]->bp;
45 if ((fd = open(name, O_RDONLY, 0)) < 0 || fstat(fd, &sb))
46 goto err;
47
48 /*
49 * XXX
50 * I'd like to test to see if the file is too large to malloc. Since
51 * we don't know what size or type off_t's or size_t's are, what the
52 * largest unsigned integral type is, or what random insanity the local
53 * C compiler will perpetrate, doing the comparison in a portable way
54 * is flatly impossible. So, put an fairly unreasonable limit on it,
55 * I don't want to be dropping core here.
56 */
57 #define MEGABYTE 1048576
58 if (sb.st_size > MEGABYTE) {
59 errno = ENOMEM;
60 goto err;
61 }
62
63 MALLOC(sp, bp, char *, (size_t)sb.st_size + 1);
64 if (bp == NULL) {
65 (void)close(fd);
66 return (1);
67 }
68 bp[sb.st_size] = '\0';
69
70 /* Read the file into memory. */
71 len = read(fd, bp, (int)sb.st_size);
72 (void)close(fd);
73 if (len == -1 || len != sb.st_size) {
74 if (len != sb.st_size)
75 errno = EIO;
76 free(bp);
77 err: msgq_str(sp, M_SYSERR, name, "%s");
78 return (1);
79 }
80
81 /* Put it on the ex queue. */
82 return (ex_run_str(sp, name, bp, (size_t)sb.st_size, 1, 1));
83 }
84