chiark / gitweb /
Recalculate inqueue/spare for _use_ properly
[innduct.git] / help.c
1 /*
2  *  innduct
3  *  tailing reliable realtime streaming feeder for inn
4  *  help.c - logging and utility functions
5  *
6  *  Copyright (C) 2010 Ian Jackson <ijackson@chiark.greenend.org.uk>
7  * 
8  *  This program is free software: you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation, either version 3 of the License, or
11  *  (at your option) any later version.
12  * 
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  * 
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
20  *
21  *  (I believe that when you compile and link this as part of the inn2
22  *  build, with the Makefile runes I have provided, all the libraries
23  *  and files which end up included in innduct are licence-compatible
24  *  with GPLv3.  If not then please let me know.  -Ian Jackson.)
25  */
26
27 #include "innduct.h"
28
29
30 /* for logging, simulation, debugging, etc. */
31 int simulate_flush= -1;
32 int logv_use_syslog;
33 const char *logv_prefix="";
34
35 /*========== logging ==========*/
36
37 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
38 static void logcore(int sysloglevel, const char *fmt, ...) {
39   VA;
40   if (logv_use_syslog) {
41     vsyslog(sysloglevel,fmt,al);
42   } else {
43     if (self_pid) fprintf(stderr,"[%lu] ",(unsigned long)self_pid);
44     vfprintf(stderr,fmt,al);
45     putc('\n',stderr);
46   }
47   va_end(al);
48 }
49
50 void logv(int sysloglevel, const char *pfx, int errnoval,
51           const char *fmt, va_list al) {
52   char msgbuf[1024]; /* NB do not call xvasprintf here or you'll recurse */
53   vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
54   msgbuf[sizeof(msgbuf)-1]= 0;
55
56   if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
57     sysloglevel= LOG_ERR; /* run by wrong user, probably */
58
59   logcore(sysloglevel, "%s%s: %s%s%s",
60           logv_prefix, pfx, msgbuf,
61           errnoval>=0 ? ": " : "",
62           errnoval>=0 ? strerror(errnoval) : "");
63 }
64
65 #define DEFFATAL(fn, pfx, sysloglevel, err, estatus)    \
66   void fn(const char *fmt, ...) {                       \
67     preterminate();                                     \
68     VA;                                                 \
69     logv(sysloglevel, pfx, err, fmt, al);               \
70     exit(estatus);                                      \
71   }
72
73 #define DEFLOG(fn, pfx, sysloglevel, err)       \
74   void fn(const char *fmt, ...) {               \
75     VA;                                         \
76     logv(sysloglevel, pfx, err, fmt, al);       \
77     va_end(al);                                 \
78   }
79
80 #define INNLOGSET_DEFINE(fn, pfx, sysloglevel)                          \
81   void duct_log_##fn(int l, const char *fmt, va_list al, int errval) {  \
82     logv(sysloglevel, pfx, errval ? errval : -1, fmt, al);              \
83   }
84
85
86 /* We want to extend the set of logging functions from inn, and we
87  * want to prepend the site name to all our messages. */
88
89 DEFFATAL(syscrash,    "critical", LOG_CRIT,    errno, 16);
90 DEFFATAL(crash,       "critical", LOG_CRIT,    -1,    16);
91
92 INNLOGSETS(INNLOGSET_DEFINE)
93
94 DEFLOG(info,          "info",     LOG_INFO,    -1)
95 DEFLOG(dbg,           "debug",    LOG_DEBUG,   -1)
96
97
98 /*========== utility functions etc. ==========*/
99
100 char *xvasprintf(const char *fmt, va_list al) {
101   char *str;
102   int rc= vasprintf(&str,fmt,al);
103   if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
104   return str;
105 }
106
107 char *xasprintf(const char *fmt, ...) {
108   VA;
109   char *str= xvasprintf(fmt,al);
110   va_end(al);
111   return str;
112 }
113
114 int close_perhaps(int *fd) {
115   if (*fd <= 0) return 0;
116   int r= close(*fd);
117   *fd=0;
118   return r;
119 }
120 void xclose(int fd, const char *what, const char *what2) {
121   int r= close(fd);
122   if (r) syscrash("close %s%s",what,what2?what2:"");
123 }
124 void xclose_perhaps(int *fd, const char *what, const char *what2) {
125   if (*fd <= 0) return;
126   xclose(*fd,what,what2);
127   *fd=0;
128 }
129
130 pid_t xfork(const char *what) {
131   pid_t child;
132
133   child= fork();
134   if (child==-1) sysdie("cannot fork for %s",what);
135   dbg("forked %s %ld", what, (unsigned long)child);
136   if (!child) postfork();
137   return child;
138 }
139
140 void on_fd_read_except(int fd, oop_call_fd callback) {
141   loop->on_fd(loop, fd, OOP_READ,      callback, 0);
142   loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
143 }
144 void cancel_fd_read_except(int fd) {
145   loop->cancel_fd(loop, fd, OOP_READ);
146   loop->cancel_fd(loop, fd, OOP_EXCEPTION);
147 }
148
149 void report_child_status(const char *what, int status) {
150   if (WIFEXITED(status)) {
151     int es= WEXITSTATUS(status);
152     if (es)
153       warn("%s: child died with error exit status %d", what, es);
154   } else if (WIFSIGNALED(status)) {
155     int sig= WTERMSIG(status);
156     const char *sigstr= strsignal(sig);
157     const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
158     if (sigstr)
159       warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
160     else
161       warn("%s: child died due to unknown fatal signal %d%s",
162            what, sig, coredump);
163   } else {
164     warn("%s: child died with unknown wait status %d", what,status);
165   }
166 }
167
168 int xwaitpid(pid_t *pid, const char *what) {
169   int status;
170
171   int r= kill(*pid, SIGKILL);
172   if (r) syscrash("cannot kill %s child", what);
173
174   pid_t got= waitpid(*pid, &status, 0);
175   if (got==-1) syscrash("cannot reap %s child", what);
176   if (got==0) crash("cannot reap %s child", what);
177
178   *pid= 0;
179
180   return status;
181 }
182
183 void *zxmalloc(size_t sz) {
184   void *p= xmalloc(sz);
185   memset(p,0,sz);
186   return p;
187 }
188
189 void xunlink(const char *path, const char *what) {
190   int r= unlink(path);
191   if (r) syscrash("can't unlink %s %s", path, what);
192 }
193
194 time_t xtime(void) {
195   time_t now= time(0);
196   if (now==-1) syscrash("time(2) failed");
197   return now;
198 }
199
200 void xsigaction(int signo, const struct sigaction *sa) {
201   int r= sigaction(signo,sa,0);
202   if (r) syscrash("sigaction failed for \"%s\"", strsignal(signo));
203 }
204 void xsigsetdefault(int signo) {
205   struct sigaction sa;
206   memset(&sa,0,sizeof(sa));
207   sa.sa_handler= SIG_DFL;
208   xsigaction(signo,&sa);
209 }
210 void raise_default(int signo) {
211   xsigsetdefault(signo);
212   raise(signo);
213   abort();
214 }
215
216 void xgettimeofday(struct timeval *tv_r) {
217   int r= gettimeofday(tv_r,0);
218   if (r) syscrash("gettimeofday(2) failed");
219 }
220 void xsetnonblock(int fd, int nonb) {
221   int errnoval= oop_fd_nonblock(fd, nonb);
222   if (errnoval) { errno= errnoval; syscrash("setnonblocking"); }
223 }
224
225 void check_isreg(const struct stat *stab, const char *path,
226                  const char *what) {
227   if (!S_ISREG(stab->st_mode))
228     crash("%s %s not a plain file (mode 0%lo)",
229           what, path, (unsigned long)stab->st_mode);
230 }
231
232 void xfstat(int fd, struct stat *stab_r, const char *what) {
233   int r= fstat(fd, stab_r);
234   if (r) syscrash("could not fstat %s", what);
235 }
236
237 void xfstat_isreg(int fd, struct stat *stab_r,
238                   const char *path, const char *what) {
239   xfstat(fd, stab_r, what);
240   check_isreg(stab_r, path, what);
241 }
242
243 void xlstat_isreg(const char *path, struct stat *stab,
244                   int *enoent_r /* 0 means ENOENT is fatal */,
245                   const char *what) {
246   int r= lstat(path, stab);
247   if (r) {
248     if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
249     syscrash("could not lstat %s %s", what, path);
250   }
251   if (enoent_r) *enoent_r= 0;
252   check_isreg(stab, path, what);
253 }
254
255 int samefile(const struct stat *a, const struct stat *b) {
256   assert(S_ISREG(a->st_mode));
257   assert(S_ISREG(b->st_mode));
258   return (a->st_ino == b->st_ino &&
259           a->st_dev == b->st_dev);
260 }
261
262 char *sanitise(const char *input, int len) {
263   static char sanibuf[100]; /* returns pointer to this buffer! */
264
265   const char *p= input;
266   const char *endp= len>=0 ? input+len : 0;
267   char *q= sanibuf;
268   *q++= '`';
269   for (;;) {
270     if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
271     int c= (!endp || p<endp) ? *p++ : 0;
272     if (!c) { *q++= '\''; *q=0; break; }
273     if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
274     sprintf(q,"\\x%02x",c);
275     q += 4;
276   }
277   return sanibuf;
278 }