Build: avoid compiling code for unused transports, routers, authenticators
[exim.git] / src / src / routers / queryprogram.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) The Exim Maintainers 2020 - 2023 */
6 /* Copyright (c) University of Cambridge 1995 - 2018 */
7 /* See the file NOTICE for conditions of use and distribution. */
8 /* SPDX-License-Identifier: GPL-2.0-or-later */
9
10 #include "../exim.h"
11
12 #ifdef ROUTER_QUERYPROGRAM      /* Remainder of file */
13 #include "rf_functions.h"
14 #include "queryprogram.h"
15
16
17
18 /* Options specific to the queryprogram router. */
19
20 optionlist queryprogram_router_options[] = {
21   { "*expand_command_group", opt_bool | opt_hidden,
22       OPT_OFF(queryprogram_router_options_block, expand_cmd_gid) },
23   { "*expand_command_user", opt_bool | opt_hidden,
24       OPT_OFF(queryprogram_router_options_block, expand_cmd_uid) },
25   { "*set_command_group",   opt_bool | opt_hidden,
26       OPT_OFF(queryprogram_router_options_block, cmd_gid_set) },
27   { "*set_command_user",    opt_bool | opt_hidden,
28       OPT_OFF(queryprogram_router_options_block, cmd_uid_set) },
29   { "command",      opt_stringptr,
30       OPT_OFF(queryprogram_router_options_block, command) },
31   { "command_group",opt_expand_gid,
32       OPT_OFF(queryprogram_router_options_block, cmd_gid) },
33   { "command_user", opt_expand_uid,
34       OPT_OFF(queryprogram_router_options_block, cmd_uid) },
35   { "current_directory", opt_stringptr,
36       OPT_OFF(queryprogram_router_options_block, current_directory) },
37   { "timeout",      opt_time,
38       OPT_OFF(queryprogram_router_options_block, timeout) }
39 };
40
41 /* Size of the options list. An extern variable has to be used so that its
42 address can appear in the tables drtables.c. */
43
44 int queryprogram_router_options_count =
45   sizeof(queryprogram_router_options)/sizeof(optionlist);
46
47
48 #ifdef MACRO_PREDEF
49
50 /* Dummy entries */
51 queryprogram_router_options_block queryprogram_router_option_defaults = {0};
52 void queryprogram_router_init(router_instance *rblock) {}
53 int queryprogram_router_entry(router_instance *rblock, address_item *addr,
54   struct passwd *pw, int verify, address_item **addr_local,
55   address_item **addr_remote, address_item **addr_new,
56   address_item **addr_succeed) {return 0;}
57
58 #else   /*!MACRO_PREDEF*/
59
60
61 /* Default private options block for the queryprogram router. */
62
63 queryprogram_router_options_block queryprogram_router_option_defaults = {
64   NULL,         /* command */
65   60*60,        /* timeout */
66   (uid_t)(-1),  /* cmd_uid */
67   (gid_t)(-1),  /* cmd_gid */
68   FALSE,        /* cmd_uid_set */
69   FALSE,        /* cmd_gid_set */
70   US"/",        /* current_directory */
71   NULL,         /* expand_cmd_gid */
72   NULL          /* expand_cmd_uid */
73 };
74
75
76
77 /*************************************************
78 *          Initialization entry point            *
79 *************************************************/
80
81 /* Called for each instance, after its options have been read, to enable
82 consistency checks to be done, or anything else that needs to be set up. */
83
84 void
85 queryprogram_router_init(router_instance *rblock)
86 {
87 queryprogram_router_options_block *ob =
88   (queryprogram_router_options_block *)(rblock->options_block);
89
90 /* A command must be given */
91
92 if (!ob->command)
93   log_write(0, LOG_PANIC_DIE|LOG_CONFIG_FOR, "%s router:\n  "
94     "a command specification is required", rblock->name);
95
96 /* A uid/gid must be supplied */
97
98 if (!ob->cmd_uid_set && !ob->expand_cmd_uid)
99   log_write(0, LOG_PANIC_DIE|LOG_CONFIG_FOR, "%s router:\n  "
100     "command_user must be specified", rblock->name);
101 }
102
103
104
105 /*************************************************
106 *    Process a set of generated new addresses    *
107 *************************************************/
108
109 /* This function sets up a set of newly generated child addresses and puts them
110 on the new address chain.
111
112 Arguments:
113   rblock                  router block
114   addr_new                new address chain
115   addr                    original address
116   generated               list of generated addresses
117   addr_prop               the propagated data block, containing errors_to,
118                             header change stuff, and address_data
119
120 Returns:         nothing
121 */
122
123 static void
124 add_generated(router_instance *rblock, address_item **addr_new,
125   address_item *addr, address_item *generated,
126   address_item_propagated *addr_prop)
127 {
128 while (generated != NULL)
129   {
130   BOOL ignore_error = addr->prop.ignore_error;
131   address_item *next = generated;
132
133   generated = next->next;
134
135   next->parent = addr;
136   next->prop = *addr_prop;
137   next->prop.ignore_error = next->prop.ignore_error || ignore_error;
138   next->start_router = rblock->redirect_router;
139
140   next->next = *addr_new;
141   *addr_new = next;
142
143   if (addr->child_count == USHRT_MAX)
144     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "%s router generated more than %d "
145       "child addresses for <%s>", rblock->name, USHRT_MAX, addr->address);
146   addr->child_count++;
147
148   DEBUG(D_route)
149     debug_printf("%s router generated %s\n", rblock->name, next->address);
150   }
151 }
152
153
154
155
156 /*************************************************
157 *              Main entry point                  *
158 *************************************************/
159
160 /* See local README for interface details. This router returns:
161
162 DECLINE
163   . DECLINE returned
164   . self = DECLINE
165
166 PASS
167   . PASS returned
168   . timeout of host lookup and pass_on_timeout set
169   . self = PASS
170
171 DEFER
172   . verifying the errors address caused a deferment or a big disaster such
173       as an expansion failure (rf_get_errors_address)
174   . expanding a headers_{add,remove} string caused a deferment or another
175       expansion error (rf_get_munge_headers)
176   . a problem in rf_get_transport: no transport when one is needed;
177       failed to expand dynamic transport; failed to find dynamic transport
178   . bad lookup type
179   . problem looking up host (rf_lookup_hostlist)
180   . self = DEFER or FREEZE
181   . failure to set up uid/gid for running the command
182   . failure of transport_set_up_command: too many arguments, expansion fail
183   . failure to create child process
184   . child process crashed or timed out or didn't return data
185   . :defer: in data
186   . DEFER or FREEZE returned
187   . problem in redirection data
188   . unknown transport name or trouble expanding router transport
189
190 FAIL
191   . :fail: in data
192   . FAIL returned
193   . self = FAIL
194
195 OK
196   . address added to addr_local or addr_remote for delivery
197   . new addresses added to addr_new
198 */
199
200 int
201 queryprogram_router_entry(
202   router_instance *rblock,        /* data for this instantiation */
203   address_item *addr,             /* address we are working on */
204   struct passwd *pw,              /* passwd entry after check_local_user */
205   int verify,                     /* v_none/v_recipient/v_sender/v_expn */
206   address_item **addr_local,      /* add it to this if it's local */
207   address_item **addr_remote,     /* add it to this if it's remote */
208   address_item **addr_new,        /* put new addresses on here */
209   address_item **addr_succeed)    /* put old address here on success */
210 {
211 int fd_in, fd_out, len, rc;
212 pid_t pid;
213 struct passwd *upw = NULL;
214 uschar buffer[1024];
215 const uschar **argvptr;
216 uschar *rword, *rdata, *s;
217 address_item_propagated addr_prop;
218 queryprogram_router_options_block *ob =
219   (queryprogram_router_options_block *)(rblock->options_block);
220 uschar *current_directory = ob->current_directory;
221 ugid_block ugid;
222 uid_t curr_uid = getuid();
223 gid_t curr_gid = getgid();
224 uid_t uid = ob->cmd_uid;
225 gid_t gid = ob->cmd_gid;
226 uid_t *puid = &uid;
227 gid_t *pgid = &gid;
228
229 DEBUG(D_route) debug_printf("%s router called for %s: domain = %s\n",
230   rblock->name, addr->address, addr->domain);
231
232 ugid.uid_set = ugid.gid_set = FALSE;
233
234 /* Set up the propagated data block with the current address_data and the
235 errors address and extra header stuff. */
236
237 bzero(&addr_prop, sizeof(addr_prop));
238 addr_prop.address_data = deliver_address_data;
239 tree_dup((tree_node **)&addr_prop.variables, addr->prop.variables);
240
241 rc = rf_get_errors_address(addr, rblock, verify, &addr_prop.errors_address);
242 if (rc != OK) return rc;
243
244 rc = rf_get_munge_headers(addr, rblock, &addr_prop.extra_headers,
245   &addr_prop.remove_headers);
246 if (rc != OK) return rc;
247
248 /* Get the fixed or expanded uid under which the command is to run
249 (initialization ensures that one or the other is set). */
250
251 if (  !ob->cmd_uid_set
252    && !route_find_expanded_user(ob->expand_cmd_uid, rblock->name, US"router",
253         &upw, &uid, &(addr->message)))
254     return DEFER;
255
256 /* Get the fixed or expanded gid, or take the gid from the passwd entry. */
257
258 if (!ob->cmd_gid_set)
259   if (ob->expand_cmd_gid)
260     {
261     if (route_find_expanded_group(ob->expand_cmd_gid, rblock->name,
262         US"router", &gid, &(addr->message)))
263       return DEFER;
264     }
265   else if (upw)
266     gid = upw->pw_gid;
267   else
268     {
269     addr->message = string_sprintf("command_user set without command_group "
270       "for %s router", rblock->name);
271     return DEFER;
272     }
273
274 DEBUG(D_route) debug_printf("requires uid=%ld gid=%ld current_directory=%s\n",
275   (long int)uid, (long int)gid, current_directory);
276
277 /* If we are not running as root, we will not be able to change uid/gid. */
278
279 if (curr_uid != root_uid && (uid != curr_uid || gid != curr_gid))
280   {
281   DEBUG(D_route)
282     {
283     debug_printf("not running as root: cannot change uid/gid\n");
284     debug_printf("subprocess will run with uid=%ld gid=%ld\n",
285       (long int)curr_uid, (long int)curr_gid);
286     }
287   puid = pgid = NULL;
288   }
289
290 /* Set up the command to run */
291
292 GET_OPTION("command");
293 if (!transport_set_up_command(&argvptr, /* anchor for arg list */
294     ob->command,                        /* raw command */
295     TSUC_EXPAND_ARGS,                   /* arguments expanded but must not be tainted */
296     0,                                  /* not relevant when... */
297     NULL,                               /* no transporting address */
298     US"queryprogram router",            /* for error messages */
299     &addr->message))                    /* where to put error message */
300   return DEFER;
301
302 /* Create the child process, making it a group leader. */
303
304 if ((pid = child_open_uid(argvptr, NULL, 0077, puid, pgid, &fd_in, &fd_out,
305                           current_directory, TRUE, US"queryprogram-cmd")) < 0)
306   {
307   addr->message = string_sprintf("%s router couldn't create child process: %s",
308     rblock->name, strerror(errno));
309   return DEFER;
310   }
311
312 /* Nothing is written to the standard input. */
313
314 (void)close(fd_in);
315
316 /* Wait for the process to finish, applying the timeout, and inspect its return
317 code. */
318
319 if ((rc = child_close(pid, ob->timeout)) != 0)
320   {
321   if (rc > 0)
322     addr->message = string_sprintf("%s router: command returned non-zero "
323       "code %d", rblock->name, rc);
324
325   else if (rc == -256)
326     {
327     addr->message = string_sprintf("%s router: command timed out",
328       rblock->name);
329     killpg(pid, SIGKILL);       /* Kill the whole process group */
330     }
331
332   else if (rc == -257)
333     addr->message = string_sprintf("%s router: wait() failed: %s",
334       rblock->name, strerror(errno));
335
336   else
337     addr->message = string_sprintf("%s router: command killed by signal %d",
338       rblock->name, -rc);
339
340   return DEFER;
341   }
342
343 /* Read the pipe to get the command's output, and then close it. */
344
345 len = read(fd_out, buffer, sizeof(buffer) - 1);
346 (void)close(fd_out);
347
348 /* Failure to return any data is an error. */
349
350 if (len <= 0)
351   {
352   addr->message = string_sprintf("%s router: command failed to return data",
353     rblock->name);
354   return DEFER;
355   }
356
357 /* Get rid of leading and trailing white space, and pick off the first word of
358 the result. */
359
360 while (len > 0 && isspace(buffer[len-1])) len--;
361 buffer[len] = 0;
362
363 DEBUG(D_route) debug_printf("command wrote: %s\n", buffer);
364
365 rword = buffer;
366 while (isspace(*rword)) rword++;
367 rdata = rword;
368 while (*rdata && !isspace(*rdata)) rdata++;
369 if (*rdata) *rdata++ = 0;
370
371 /* The word must be a known yield name. If it is "REDIRECT", the rest of the
372 line is redirection data, as for a .forward file. It may not contain filter
373 data, and it may not contain anything other than addresses (no files, no pipes,
374 no specials). */
375
376 if (strcmpic(rword, US"REDIRECT") == 0)
377   {
378   int filtertype;
379   redirect_block redirect;
380   address_item *generated = NULL;
381
382   redirect.string = rdata;
383   redirect.isfile = FALSE;
384
385   rc = rda_interpret(&redirect,  /* redirection data */
386     RDO_BLACKHOLE |              /* forbid :blackhole: */
387       RDO_FAIL    |              /* forbid :fail: */
388       RDO_INCLUDE |              /* forbid :include: */
389       RDO_REWRITE,               /* rewrite generated addresses */
390     NULL,                        /* :include: directory not relevant */
391     NULL,                        /* sieve vacation directory not relevant */
392     NULL,                        /* sieve enotify mailto owner not relevant */
393     NULL,                        /* sieve useraddress not relevant */
394     NULL,                        /* sieve subaddress not relevant */
395     &ugid,                       /* uid/gid (but not set) */
396     &generated,                  /* where to hang the results */
397     &addr->message,              /* where to put messages */
398     NULL,                        /* don't skip syntax errors */
399     &filtertype,                 /* not used; will always be FILTER_FORWARD */
400     string_sprintf("%s router", rblock->name));
401
402   switch (rc)
403     {
404     /* FF_DEFER and FF_FAIL can arise only as a result of explicit commands.
405     If a configured message was supplied, allow it to be  included in an SMTP
406     response after verifying. */
407
408     case FF_DEFER:
409       if (!addr->message) addr->message = US"forced defer";
410       else addr->user_message = addr->message;
411       return DEFER;
412
413     case FF_FAIL:
414       add_generated(rblock, addr_new, addr, generated, &addr_prop);
415       if (!addr->message) addr->message = US"forced rejection";
416       else addr->user_message = addr->message;
417       return FAIL;
418
419     case FF_DELIVERED:
420       break;
421
422     case FF_NOTDELIVERED:    /* an empty redirection list is bad */
423       addr->message = US"no addresses supplied";
424     /* Fall through */
425
426     case FF_ERROR:
427     default:
428       addr->basic_errno = ERRNO_BADREDIRECT;
429       addr->message = string_sprintf("error in redirect data: %s", addr->message);
430       return DEFER;
431     }
432
433   /* Handle the generated addresses, if any. */
434
435   add_generated(rblock, addr_new, addr, generated, &addr_prop);
436
437   /* Put the original address onto the succeed queue so that any retry items
438   that get attached to it get processed. */
439
440   addr->next = *addr_succeed;
441   *addr_succeed = addr;
442
443   return OK;
444   }
445
446 /* Handle other returns that are not ACCEPT */
447
448 if (strcmpic(rword, US"accept") != 0)
449   {
450   if (strcmpic(rword, US"decline") == 0) return DECLINE;
451   if (strcmpic(rword, US"pass") == 0) return PASS;
452   addr->message = string_copy(rdata);                /* data is a message */
453   if (strcmpic(rword, US"fail") == 0)
454     {
455     setflag(addr, af_pass_message);
456     return FAIL;
457     }
458   if (strcmpic(rword, US"freeze") == 0) addr->special_action = SPECIAL_FREEZE;
459   else if (strcmpic(rword, US"defer") != 0)
460     {
461     addr->message = string_sprintf("bad command yield: %s %s", rword, rdata);
462     log_write(0, LOG_PANIC, "%s router: %s", rblock->name, addr->message);
463     }
464   return DEFER;
465   }
466
467 /* The command yielded "ACCEPT". The rest of the string is a number of keyed
468 fields from which we can fish out values using the equivalent of the "extract"
469 expansion function. */
470
471 if ((s = expand_getkeyed(US"data", rdata)) && *s)
472   addr_prop.address_data = string_copy(s);
473
474 /* If we found a transport name, find the actual transport */
475
476 if ((s = expand_getkeyed(US"transport", rdata)) && *s)
477   {
478   transport_instance *transport;
479   for (transport = transports; transport; transport = transport->next)
480     if (Ustrcmp(transport->name, s) == 0) break;
481   if (!transport)
482     {
483     addr->message = string_sprintf("unknown transport name %s yielded by "
484       "command", s);
485     log_write(0, LOG_PANIC, "%s router: %s", rblock->name, addr->message);
486     return DEFER;
487     }
488   addr->transport = transport;
489   }
490
491 /* No transport given; get the transport from the router configuration. It may
492 be fixed or expanded, but there will be an error if it is unset, requested by
493 the last argument not being NULL. */
494
495 else
496   {
497   if (!rf_get_transport(rblock->transport_name, &rblock->transport, addr,
498        rblock->name, US"transport"))
499     return DEFER;
500   addr->transport = rblock->transport;
501   }
502
503 /* See if a host list is given, and if so, look up the addresses. */
504
505 if ((s = expand_getkeyed(US"hosts", rdata)) && *s)
506   {
507   int lookup_type = LK_DEFAULT;
508   uschar * ss = expand_getkeyed(US"lookup", rdata);
509
510   if (ss && *ss)
511     {
512     if (Ustrcmp(ss, "byname") == 0) lookup_type = LK_BYNAME;
513     else if (Ustrcmp(ss, "bydns") == 0) lookup_type = LK_BYDNS;
514     else
515       {
516       addr->message = string_sprintf("bad lookup type \"%s\" yielded by "
517         "command", ss);
518       log_write(0, LOG_PANIC, "%s router: %s", rblock->name, addr->message);
519       return DEFER;
520       }
521     }
522
523   host_build_hostlist(&(addr->host_list), s, FALSE);  /* pro tem no randomize */
524
525   rc = rf_lookup_hostlist(rblock, addr, rblock->ignore_target_hosts,
526     lookup_type, hff_defer, addr_new);
527   if (rc != OK) return rc;
528   }
529 lookup_value = NULL;
530
531 /* Put the errors address, extra headers, and address_data into this address */
532
533 addr->prop = addr_prop;
534
535 /* Queue the address for local or remote delivery. */
536
537 return rf_queue_add(addr, addr_local, addr_remote, rblock, pw) ? OK : DEFER;
538 }
539
540 #endif  /*!MACRO_PREDEF*/
541 #endif  /*ROUTER_QUERYPROGRAM*/
542 /* End of routers/queryprogram.c */