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