Upstream qmail 1.01
[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 }
82 if (scan_nbblong(line.s,line.len,10,0,&u) == 0) return 0;
83 *i = u;
84 return 1;
85}
86
87int control_readfile(sa,fn,flagme)
88stralloc *sa;
89char *fn;
90int flagme;
91{
92 substdio ss;
93 int fd;
94 int match;
95
96 if (!stralloc_copys(sa,"")) return -1;
97
98 fd = open_read(fn);
99 if (fd == -1)
100 {
101 if (errno == error_noent)
102 {
103 if (flagme && meok)
104 {
105 if (!stralloc_copy(sa,&me)) return -1;
106 if (!stralloc_0(sa)) return -1;
107 return 1;
108 }
109 return 0;
110 }
111 return -1;
112 }
113
114 substdio_fdbuf(&ss,read,fd,inbuf,sizeof(inbuf));
115
116 for (;;)
117 {
118 if (getln(&ss,&line,&match,'\n') == -1) break;
119 if (!match && !line.len) { close(fd); return 1; }
120 striptrailingwhitespace(&line);
121 if (!stralloc_0(&line)) break;
122 if (line.s[0])
123 if (line.s[0] != '#')
124 if (!stralloc_cat(sa,&line)) break;
125 if (!match) { close(fd); return 1; }
126 }
127 close(fd);
128 return -1;
129}