Annotation of src/usr.bin/mg/autoexec.c, Revision 1.9
1.9 ! deraadt 1: /* $OpenBSD: autoexec.c,v 1.8 2005/08/09 00:53:47 kjell Exp $ */
1.1 vincent 2: /* this file is in the public domain */
3: /* Author: Vincent Labrecque <vincent@openbsd.org> April 2002 */
4:
5: #include "def.h"
6: #include "funmap.h"
7:
8: #include <fnmatch.h>
9:
10: struct autoexec {
11: SLIST_ENTRY(autoexec) next; /* link in the linked list */
12: const char *pattern; /* Pattern to match to filenames */
13: PF fp;
14: };
15:
16: static SLIST_HEAD(, autoexec) autos;
17: static int ready;
18:
19: /*
20: * Return a NULL terminated array of function pointers to be called
21: * when we open a file that matches <fname>. The list must be free(ed)
22: * after use.
23: */
24: PF *
25: find_autoexec(const char *fname)
26: {
1.6 db 27: PF *pfl, *npfl;
28: int have, used;
1.1 vincent 29: struct autoexec *ae;
30:
31: if (!ready)
32: return (NULL);
33:
34: pfl = NULL;
35: have = 0;
36: used = 0;
37: SLIST_FOREACH(ae, &autos, next) {
38: if (fnmatch(ae->pattern, fname, 0) == 0) {
39: if (used >= have) {
1.3 vincent 40: npfl = realloc(pfl, (have + 8 + 1) * sizeof(PF));
41: if (npfl == NULL)
1.1 vincent 42: panic("out of memory");
1.3 vincent 43: pfl = npfl;
44: have += 8;
1.1 vincent 45: }
46: pfl[used++] = ae->fp;
47: }
48: }
49: if (used) {
50: pfl[used] = NULL;
51: pfl = realloc(pfl, (used + 1) * sizeof(PF));
52: }
53: return (pfl);
54: }
55:
56: int
57: add_autoexec(const char *pattern, const char *func)
58: {
1.9 ! deraadt 59: PF fp;
1.1 vincent 60: struct autoexec *ae;
61:
62: if (!ready) {
63: SLIST_INIT(&autos);
64: ready = 1;
65: }
66: fp = name_function(func);
67: if (fp == NULL)
68: return (FALSE);
1.6 db 69: ae = malloc(sizeof(*ae));
1.1 vincent 70: if (ae == NULL)
71: return (FALSE);
72: ae->fp = fp;
73: ae->pattern = strdup(pattern);
74: if (ae->pattern == NULL) {
75: free(ae);
76: return (FALSE);
77: }
78: SLIST_INSERT_HEAD(&autos, ae, next);
79:
80: return (TRUE);
81: }
82:
83: int
84: auto_execute(int f, int n)
85: {
1.6 db 86: char patbuf[128], funcbuf[128], *patp, *funcp;
87: int s;
1.2 deraadt 88:
1.8 kjell 89: if ((patp = eread("Filename pattern: ", patbuf, sizeof(patbuf),
90: EFNEW | EFCR)) == NULL)
1.6 db 91: return (ABORT);
1.4 vincent 92: else if (patp[0] == '\0')
1.6 db 93: return (FALSE);
1.8 kjell 94: if ((funcp = eread("Execute: ", funcbuf, sizeof(funcbuf),
95: EFNEW | EFCR)) == NULL)
1.6 db 96: return (ABORT);
1.4 vincent 97: else if (funcp[0] == '\0')
1.6 db 98: return (FALSE);
1.4 vincent 99: if ((s = add_autoexec(patp, funcp)) != TRUE)
1.1 vincent 100: return (s);
101: return (TRUE);
102: }