Annotation of src/usr.bin/mg/autoexec.c, Revision 1.12
1.12 ! kjell 1: /* $OpenBSD: autoexec.c,v 1.11 2006/12/20 20:16:16 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:
1.11 kjell 19:
20: #define AUTO_GROW 8
1.1 vincent 21: /*
22: * Return a NULL terminated array of function pointers to be called
23: * when we open a file that matches <fname>. The list must be free(ed)
24: * after use.
25: */
26: PF *
27: find_autoexec(const char *fname)
28: {
1.6 db 29: PF *pfl, *npfl;
30: int have, used;
1.1 vincent 31: struct autoexec *ae;
32:
33: if (!ready)
34: return (NULL);
35:
36: pfl = NULL;
37: have = 0;
38: used = 0;
39: SLIST_FOREACH(ae, &autos, next) {
40: if (fnmatch(ae->pattern, fname, 0) == 0) {
41: if (used >= have) {
1.11 kjell 42: npfl = realloc(pfl, (have + AUTO_GROW + 1) *
43: sizeof(PF));
1.3 vincent 44: if (npfl == NULL)
1.1 vincent 45: panic("out of memory");
1.3 vincent 46: pfl = npfl;
1.11 kjell 47: have += AUTO_GROW;
1.1 vincent 48: }
49: pfl[used++] = ae->fp;
50: }
51: }
1.11 kjell 52: if (used)
1.1 vincent 53: pfl[used] = NULL;
1.11 kjell 54:
1.1 vincent 55: return (pfl);
56: }
57:
58: int
59: add_autoexec(const char *pattern, const char *func)
60: {
1.9 deraadt 61: PF fp;
1.1 vincent 62: struct autoexec *ae;
63:
64: if (!ready) {
65: SLIST_INIT(&autos);
66: ready = 1;
67: }
68: fp = name_function(func);
69: if (fp == NULL)
70: return (FALSE);
1.6 db 71: ae = malloc(sizeof(*ae));
1.1 vincent 72: if (ae == NULL)
73: return (FALSE);
74: ae->fp = fp;
75: ae->pattern = strdup(pattern);
76: if (ae->pattern == NULL) {
77: free(ae);
78: return (FALSE);
79: }
80: SLIST_INSERT_HEAD(&autos, ae, next);
81:
82: return (TRUE);
83: }
84:
1.10 kjell 85: /* ARGSUSED */
1.1 vincent 86: int
87: auto_execute(int f, int n)
88: {
1.6 db 89: char patbuf[128], funcbuf[128], *patp, *funcp;
90: int s;
1.2 deraadt 91:
1.8 kjell 92: if ((patp = eread("Filename pattern: ", patbuf, sizeof(patbuf),
93: EFNEW | EFCR)) == NULL)
1.6 db 94: return (ABORT);
1.4 vincent 95: else if (patp[0] == '\0')
1.6 db 96: return (FALSE);
1.8 kjell 97: if ((funcp = eread("Execute: ", funcbuf, sizeof(funcbuf),
1.12 ! kjell 98: EFNEW | EFCR | EFFUNC)) == NULL)
1.6 db 99: return (ABORT);
1.4 vincent 100: else if (funcp[0] == '\0')
1.6 db 101: return (FALSE);
1.4 vincent 102: if ((s = add_autoexec(patp, funcp)) != TRUE)
1.1 vincent 103: return (s);
104: return (TRUE);
105: }