debian/rules: Use `git' potty wrapper.
[qmail] / control.c
CommitLineData
2117e02e
MW
1#include "readwrite.h"
2#include "open.h"
3#include "getln.h"
4#include "stralloc.h"
5#include "substdio.h"
6#include "error.h"
7#include "control.h"
8#include "alloc.h"
9#include "scan.h"
10
11static char inbuf[64];
12static stralloc line = {0};
13static stralloc me = {0};
14static int meok = 0;
15
16static void striptrailingwhitespace(sa)
17stralloc *sa;
18{
19 while (sa->len > 0)
20 switch(sa->s[sa->len - 1])
21 {
22 case '\n': case ' ': case '\t':
23 --sa->len;
24 break;
25 default:
26 return;
27 }
28}
29
30int control_init()
31{
32 int r;
33 r = control_readline(&me,"control/me");
34 if (r == 1) meok = 1;
35 return r;
36}
37
38int control_rldef(sa,fn,flagme,def)
39stralloc *sa;
40char *fn;
41int flagme;
42char *def;
43{
44 int r;
45 r = control_readline(sa,fn);
46 if (r) return r;
47 if (flagme) if (meok) return stralloc_copy(sa,&me) ? 1 : -1;
48 if (def) return stralloc_copys(sa,def) ? 1 : -1;
49 return r;
50}
51
52int control_readline(sa,fn)
53stralloc *sa;
54char *fn;
55{
56 substdio ss;
57 int fd;
58 int match;
59
60 fd = open_read(fn);
61 if (fd == -1) { if (errno == error_noent) return 0; return -1; }
62
63 substdio_fdbuf(&ss,read,fd,inbuf,sizeof(inbuf));
64
65 if (getln(&ss,sa,&match,'\n') == -1) { close(fd); return -1; }
66
67 striptrailingwhitespace(sa);
68 close(fd);
69 return 1;
70}
71
72int control_readint(i,fn)
73int *i;
74char *fn;
75{
76 unsigned long u;
77 switch(control_readline(&line,fn))
78 {
79 case 0: return 0;
80 case -1: return -1;
81 }
212b6f5d
MW
82 if (!stralloc_0(&line)) return -1;
83 if (!scan_ulong(line.s,&u)) return 0;
2117e02e
MW
84 *i = u;
85 return 1;
86}
87
88int control_readfile(sa,fn,flagme)
89stralloc *sa;
90char *fn;
91int flagme;
92{
93 substdio ss;
94 int fd;
95 int match;
96
97 if (!stralloc_copys(sa,"")) return -1;
98
99 fd = open_read(fn);
100 if (fd == -1)
101 {
102 if (errno == error_noent)
103 {
104 if (flagme && meok)
105 {
106 if (!stralloc_copy(sa,&me)) return -1;
107 if (!stralloc_0(sa)) return -1;
108 return 1;
109 }
110 return 0;
111 }
112 return -1;
113 }
114
115 substdio_fdbuf(&ss,read,fd,inbuf,sizeof(inbuf));
116
117 for (;;)
118 {
119 if (getln(&ss,&line,&match,'\n') == -1) break;
120 if (!match && !line.len) { close(fd); return 1; }
121 striptrailingwhitespace(&line);
122 if (!stralloc_0(&line)) break;
123 if (line.s[0])
124 if (line.s[0] != '#')
125 if (!stralloc_cat(sa,&line)) break;
126 if (!match) { close(fd); return 1; }
127 }
128 close(fd);
129 return -1;
130}