Annotation of src/usr.bin/mg/autoexec.c, Revision 1.6
1.6 ! db 1: /* $OpenBSD: autoexec.c,v 1.5 2005/03/10 16:58:57 deraadt 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 <sys/queue.h>
9:
10: #include <fnmatch.h>
11:
12: struct autoexec {
13: SLIST_ENTRY(autoexec) next; /* link in the linked list */
14: const char *pattern; /* Pattern to match to filenames */
15: PF fp;
16: };
17:
18: static SLIST_HEAD(, autoexec) autos;
19: static int ready;
20:
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.3 vincent 42: npfl = realloc(pfl, (have + 8 + 1) * sizeof(PF));
43: if (npfl == NULL)
1.1 vincent 44: panic("out of memory");
1.3 vincent 45: pfl = npfl;
46: have += 8;
1.1 vincent 47: }
48: pfl[used++] = ae->fp;
49: }
50: }
51: if (used) {
52: pfl[used] = NULL;
53: pfl = realloc(pfl, (used + 1) * sizeof(PF));
54: }
55: return (pfl);
56: }
57:
58: int
59: add_autoexec(const char *pattern, const char *func)
60: {
1.6 ! db 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:
85: int
86: auto_execute(int f, int n)
87: {
1.6 ! db 88: char patbuf[128], funcbuf[128], *patp, *funcp;
! 89: int s;
1.2 deraadt 90:
1.6 ! db 91: if ((patp = ereply("Filename pattern: ", patbuf, sizeof(patbuf))) == NULL)
! 92: return (ABORT);
1.4 vincent 93: else if (patp[0] == '\0')
1.6 ! db 94: return (FALSE);
! 95: if ((funcp = ereply("Execute: ", funcbuf, sizeof(funcbuf))) == NULL)
! 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: }