chiark / gitweb /
infer_url() now attempts to spot https
[disorder] / lib / macros-builtin.c
1 /*
2  * This file is part of DisOrder
3  * Copyright (C) 2008 Richard Kettlewell
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18  * USA
19  */
20
21 /** @file lib/macros-builtin.c
22  * @brief Built-in expansions
23  *
24  * This is a grab-bag of non-domain-specific expansions.  Documentation will be
25  * generated from the comments at the head of each function.
26  */
27
28 #include <config.h>
29 #include "types.h"
30
31 #include <stdio.h>
32 #include <string.h>
33 #include <errno.h>
34 #include <assert.h>
35 #include <unistd.h>
36 #include <fcntl.h>
37 #include <sys/stat.h>
38 #include <sys/wait.h>
39
40 #include "hash.h"
41 #include "mem.h"
42 #include "macros.h"
43 #include "sink.h"
44 #include "syscalls.h"
45 #include "log.h"
46 #include "wstat.h"
47 #include "kvp.h"
48 #include "split.h"
49 #include "printf.h"
50 #include "vector.h"
51
52 static struct vector include_path;
53
54 /** @brief Return 1 if @p s is 'true' else 0 */
55 int mx_str2bool(const char *s) {
56   return !strcmp(s, "true");
57 }
58
59 /** @brief Return "true" if @p n is nonzero else "false" */
60 const char *mx_bool2str(int n) {
61   return n ? "true" : "false";
62 }
63
64 /** @brief Write a boolean result */
65 int mx_bool_result(struct sink *output, int result) {
66   if(sink_writes(output, mx_bool2str(result)) < 0)
67     return -1;
68   else
69     return 0;
70 }
71
72 /** @brief Search the include path */
73 char *mx_find(const char *name) {
74   char *path;
75   int n;
76   
77   if(name[0] == '/') {
78     if(access(name, O_RDONLY) < 0) {
79       error(errno, "cannot read %s", name);
80       return 0;
81     }
82     path = xstrdup(name);
83   } else {
84     /* Search the include path */
85     for(n = 0; n < include_path.nvec; ++n) {
86       byte_xasprintf(&path, "%s/%s", include_path.vec[n], name);
87       if(access(path, O_RDONLY) == 0)
88         break;
89     }
90     if(n >= include_path.nvec) {
91       error(0, "cannot find '%s' in search path", name);
92       return 0;
93     }
94   }
95   return path;
96 }
97
98 /* @include{TEMPLATE}@
99  *
100  * Includes TEMPLATE.
101  *
102  * TEMPLATE can be an absolute filename starting with a '/'; only the file with
103  * exactly this name will be included.
104  *
105  * Alternatively it can be a relative filename, not starting with a '/'.  In
106  * this case the file will be searched for in the include path.  When searching
107  * paths, unreadable files are treated as if they do not exist (rather than
108  * matching then producing an error).
109  *
110  * If the name chosen ends ".tmpl" then the file will be expanded as a
111  * template.  Anything else is included byte-for-byte without further
112  * modification.
113  *
114  * Only regular files are allowed (no devices, sockets or name pipes).
115  */
116 static int exp_include(int attribute((unused)) nargs,
117                        char **args,
118                        struct sink *output,
119                        void *u) {
120   const char *path;
121   int fd, n;
122   char buffer[4096];
123   struct stat sb;
124
125   if(!(path = mx_find(args[0]))) {
126     if(sink_printf(output, "[[cannot find '%s']]", args[0]) < 0)
127       return 0;
128     return 0;
129   }
130   /* If it's a template expand it */
131   if(strlen(path) >= 5 && !strncmp(path + strlen(path) - 5, ".tmpl", 5))
132     return mx_expand_file(path, output, u);
133   /* Read the raw file.  As with mx_expand_file() we insist that the file is a
134    * regular file. */
135   if((fd = open(path, O_RDONLY)) < 0)
136     fatal(errno, "error opening %s", path);
137   if(fstat(fd, &sb) < 0)
138     fatal(errno, "error statting %s", path);
139   if(!S_ISREG(sb.st_mode))
140     fatal(0, "%s: not a regular file", path);
141   while((n = read(fd, buffer, sizeof buffer)) > 0) {
142     if(sink_write(output, buffer, n) < 0) {
143       xclose(fd);
144       return -1;
145     }
146   }
147   if(n < 0)
148     fatal(errno, "error reading %s", path);
149   xclose(fd);
150   return 0;
151 }
152
153 /* @include{COMMAND}@
154  *
155  * Executes COMMAND via the shell (using "sh -c") and copies its
156  * standard output to the template output.  The shell command output
157  * is not expanded or modified in any other way.
158  *
159  * The shell command's standard error is copied to the error log.
160  *
161  * If the shell exits nonzero then this is reported to the error log
162  * but otherwise no special action is taken.
163  */
164 static int exp_shell(int attribute((unused)) nargs,
165                      char **args,
166                      struct sink *output,
167                      void attribute((unused)) *u) {
168   int w, p[2], n;
169   char buffer[4096];
170   pid_t pid;
171   
172   xpipe(p);
173   if(!(pid = xfork())) {
174     exitfn = _exit;
175     xclose(p[0]);
176     xdup2(p[1], 1);
177     xclose(p[1]);
178     execlp("sh", "sh", "-c", args[0], (char *)0);
179     fatal(errno, "error executing sh");
180   }
181   xclose(p[1]);
182   while((n = read(p[0], buffer, sizeof buffer))) {
183     if(n < 0) {
184       if(errno == EINTR)
185         continue;
186       else
187         fatal(errno, "error reading from pipe");
188     }
189     if(output->write(output, buffer, n) < 0)
190       return -1;
191   }
192   xclose(p[0]);
193   while((n = waitpid(pid, &w, 0)) < 0 && errno == EINTR)
194     ;
195   if(n < 0)
196     fatal(errno, "error calling waitpid");
197   if(w)
198     error(0, "shell command '%s' %s", args[0], wstat(w));
199   return 0;
200 }
201
202 /* @if{CONDITION}{IF-TRUE}{IF-FALSE}@
203  *
204  * If CONDITION is "true" then evaluates to IF-TRUE.  Otherwise
205  * evaluates to IF-FALSE.  The IF-FALSE part is optional.
206  */
207 static int exp_if(int nargs,
208                   const struct mx_node **args,
209                   struct sink *output,
210                   void *u) {
211   char *s;
212   int rc;
213
214   if((rc = mx_expandstr(args[0], &s, u, "argument #0 (CONDITION)")))
215     return rc;
216   if(mx_str2bool(s))
217     return mx_expand(args[1], output, u);
218   else if(nargs > 2)
219     return mx_expand(args[2], output, u);
220   else
221     return 0;
222 }
223
224 /* @and{BRANCH}{BRANCH}...@
225  *
226  * Expands to "true" if all the branches are "true" otherwise to "false".  If
227  * there are no brances then the result is "true".  Only as many branches as
228  * necessary to compute the answer are evaluated (starting from the first one),
229  * so if later branches have side effects they may not take place.
230  */
231 static int exp_and(int nargs,
232                    const struct mx_node **args,
233                    struct sink *output,
234                    void *u) {
235   int n, result = 1, rc;
236   char *s, *argname;
237
238   for(n = 0; n < nargs; ++n) {
239     byte_xasprintf(&argname, "argument #%d", n);
240     if((rc = mx_expandstr(args[n], &s, u, argname)))
241       return rc;
242     if(!mx_str2bool(s)) {
243       result = 0;
244       break;
245     }
246   }
247   return mx_bool_result(output, result);
248 }
249
250 /* @or{BRANCH}{BRANCH}...@
251  *
252  * Expands to "true" if any of the branches are "true" otherwise to "false".
253  * If there are no brances then the result is "false".  Only as many branches
254  * as necessary to compute the answer are evaluated (starting from the first
255  * one), so if later branches have side effects they may not take place.
256  */
257 static int exp_or(int nargs,
258                   const struct mx_node **args,
259                   struct sink *output,
260                   void *u) {
261   int n, result = 0, rc;
262   char *s, *argname;
263
264   for(n = 0; n < nargs; ++n) {
265     byte_xasprintf(&argname, "argument #%d", n);
266     if((rc = mx_expandstr(args[n], &s, u, argname)))
267       return rc;
268     if(mx_str2bool(s)) {
269       result = 1;
270       break;
271     }
272   }
273   return mx_bool_result(output, result);
274 }
275
276 /* @not{CONDITION}@
277  *
278  * Expands to "true" unless CONDITION is "true" in which case "false".
279  */
280 static int exp_not(int attribute((unused)) nargs,
281                    char **args,
282                    struct sink *output,
283                    void attribute((unused)) *u) {
284   return mx_bool_result(output, !mx_str2bool(args[0]));
285 }
286
287 /* @#{...}@
288  *
289  * Expands to nothing.  The argument(s) are not fully evaluated, and no side
290  * effects occur.
291  */
292 static int exp_comment(int attribute((unused)) nargs,
293                        const struct mx_node attribute((unused)) **args,
294                        struct sink attribute((unused)) *output,
295                        void attribute((unused)) *u) {
296   return 0;
297 }
298
299 /* @urlquote{STRING}@
300  *
301  * URL-quotes a string, i.e. replaces any characters not safe to use unquoted
302  * in a URL with %-encoded form.
303  */
304 static int exp_urlquote(int attribute((unused)) nargs,
305                         char **args,
306                         struct sink *output,
307                         void attribute((unused)) *u) {
308   if(sink_writes(output, urlencodestring(args[0])) < 0)
309     return -1;
310   else
311     return 0;
312 }
313
314 /* @eq{S1}{S2}...@
315  *
316  * Expands to "true" if all the arguments are identical, otherwise to "false"
317  * (i.e. if any pair of arguments differs).
318  *
319  * If there are no arguments then expands to "true".  Evaluates all arguments
320  * (with their side effects) even if that's not strictly necessary to discover
321  * the result.
322  */
323 static int exp_eq(int nargs,
324                   char **args,
325                   struct sink *output,
326                   void attribute((unused)) *u) {
327   int n, result = 1;
328   
329   for(n = 1; n < nargs; ++n) {
330     if(strcmp(args[n], args[0])) {
331       result = 0;
332       break;
333     }
334   }
335   return mx_bool_result(output, result);
336 }
337
338 /* @ne{S1}{S2}...@
339  *
340  * Expands to "true" if all of the arguments differ from one another, otherwise
341  * to "false" (i.e. if any value appears more than once).
342  *
343  * If there are no arguments then expands to "true".  Evaluates all arguments
344  * (with their side effects) even if that's not strictly necessary to discover
345  * the result.
346  */
347 static int exp_ne(int nargs,
348                   char **args,
349                   struct sink *output,
350                   void  attribute((unused))*u) {
351   hash *h = hash_new(sizeof (char *));
352   int n, result = 1;
353
354   for(n = 0; n < nargs; ++n)
355     if(hash_add(h, args[n], "", HASH_INSERT)) {
356       result = 0;
357       break;
358     }
359   return mx_bool_result(output, result);
360 }
361
362 /* @discard{...}@
363  *
364  * Expands to nothing.  Unlike the comment expansion @#{...}, side effects of
365  * arguments are not suppressed.  So this can be used to surround a collection
366  * of macro definitions with whitespace, free text commentary, etc.
367  */
368 static int exp_discard(int attribute((unused)) nargs,
369                        char attribute((unused)) **args,
370                        struct sink attribute((unused)) *output,
371                        void attribute((unused)) *u) {
372   return 0;
373 }
374
375 /* @define{NAME}{ARG1 ARG2...}{DEFINITION}@
376  *
377  * Define a macro.  The macro will be called NAME and will act like an
378  * expansion.  When it is expanded, the expansion is replaced by DEFINITION,
379  * with each occurence of @ARG1@ etc replaced by the parameters to the
380  * expansion.
381  */
382 static int exp_define(int attribute((unused)) nargs,
383                       const struct mx_node **args,
384                       struct sink attribute((unused)) *output,
385                       void attribute((unused)) *u) {
386   char **as, *name, *argnames;
387   int rc, nas;
388   
389   if((rc = mx_expandstr(args[0], &name, u, "argument #0 (NAME)")))
390     return rc;
391   if((rc = mx_expandstr(args[1], &argnames, u, "argument #1 (ARGS)")))
392     return rc;
393   as = split(argnames, &nas, 0, 0, 0);
394   mx_register_macro(name, nas, as, args[2]);
395   return 0;
396 }
397
398 /** @brief Register built-in expansions */
399 void mx_register_builtin(void) {
400   mx_register_magic("#", 0, INT_MAX, exp_comment);
401   mx_register_magic("and", 0, INT_MAX, exp_and);
402   mx_register_magic("define", 3, 3, exp_define);
403   mx_register_magic("if", 2, 3, exp_if);
404   mx_register_magic("or", 0, INT_MAX, exp_or);
405   mx_register("discard", 0, INT_MAX, exp_discard);
406   mx_register("eq", 0, INT_MAX, exp_eq);
407   mx_register("include", 1, 1, exp_include);
408   mx_register("ne", 0, INT_MAX, exp_ne);
409   mx_register("not", 1, 1, exp_not);
410   mx_register("shell", 1, 1, exp_shell);
411   mx_register("urlquote", 1, 1, exp_urlquote);
412 }
413
414 /** @brief Add a directory to the search path
415  * @param s Directory to add
416  */
417 void mx_search_path(const char *s) {
418   vector_append(&include_path, xstrdup(s));
419 }
420
421 /*
422 Local Variables:
423 c-basic-offset:2
424 comment-column:40
425 fill-column:79
426 indent-tabs-mode:nil
427 End:
428 */