Fix more booleans
[freeradius.git] / src / main / exec.c
1 /*
2  *   This program is free software; you can redistribute it and/or modify
3  *   it under the terms of the GNU General Public License as published by
4  *   the Free Software Foundation; either version 2 of the License, or
5  *   (at your option) any later version.
6  *
7  *   This program is distributed in the hope that it will be useful,
8  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  *   GNU General Public License for more details.
11  *
12  *   You should have received a copy of the GNU General Public License
13  *   along with this program; if not, write to the Free Software
14  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
15  */
16
17 /*
18  * $Id$
19  *
20  * @file exec.c
21  * @brief Execute external programs.
22  *
23  * @copyright 2000-2004,2006  The FreeRADIUS server project
24  */
25
26 RCSID("$Id$")
27
28 #include <freeradius-devel/radiusd.h>
29 #include <freeradius-devel/rad_assert.h>
30
31 #include <sys/file.h>
32
33 #include <fcntl.h>
34 #include <ctype.h>
35
36 #ifdef HAVE_SYS_WAIT_H
37 #       include <sys/wait.h>
38 #endif
39 #ifndef WEXITSTATUS
40 #       define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
41 #endif
42 #ifndef WIFEXITED
43 #       define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
44 #endif
45
46 #define MAX_ARGV (256)
47
48 #define USEC 1000000
49 static void tv_sub(struct timeval *end, struct timeval *start,
50                    struct timeval *elapsed)
51 {
52         elapsed->tv_sec = end->tv_sec - start->tv_sec;
53         if (elapsed->tv_sec > 0) {
54                 elapsed->tv_sec--;
55                 elapsed->tv_usec = USEC;
56         } else {
57                 elapsed->tv_usec = 0;
58         }
59         elapsed->tv_usec += end->tv_usec;
60         elapsed->tv_usec -= start->tv_usec;
61
62         if (elapsed->tv_usec >= USEC) {
63                 elapsed->tv_usec -= USEC;
64                 elapsed->tv_sec++;
65         }
66 }
67
68
69 /** Start a process
70  *
71  * @param cmd Command to execute. This is parsed into argv[] parts,
72  *      then each individual argv part is xlat'ed.
73  * @param request Current reuqest
74  * @param exec_wait set to 1 if you want to read from or write to child
75  * @param[in,out] input_fd pointer to int, receives the stdin file.
76  *      descriptor. Set to NULL and the child will have /dev/null on stdin
77  * @param[in,out] output_fd pinter to int, receives the stdout file
78  *      descriptor. Set to NULL and child will have /dev/null on stdout.
79  * @param input_pairs list of value pairs - these will be put into
80  *      the environment variables of the child.
81  * @param shell_escape values before passing them as arguments.
82  * @return PID of the child process, -1 on error.
83  */
84 pid_t radius_start_program(char const *cmd, REQUEST *request, bool exec_wait,
85                            int *input_fd, int *output_fd,
86                            VALUE_PAIR *input_pairs, bool shell_escape)
87 {
88 #ifndef __MINGW32__
89         char *p;
90         VALUE_PAIR *vp;
91         int n;
92         int to_child[2] = {-1, -1};
93         int from_child[2] = {-1, -1};
94         pid_t pid;
95 #endif
96         int argc;
97         int i;
98         char *argv[MAX_ARGV];
99         char argv_buf[4096];
100 #define MAX_ENVP 1024
101         char *envp[MAX_ENVP];
102
103         argc = rad_expand_xlat(request, cmd, MAX_ARGV, argv, true, sizeof(argv_buf), argv_buf);
104         if (argc <= 0) {
105                 RDEBUG("invalid command line '%s'.", cmd);
106                 return -1;
107         }
108
109
110 #ifndef NDEBUG
111         if (debug_flag > 2) {
112                 RDEBUG3("executing cmd %s", cmd);
113                 for (i = 0; i < argc; i++) {
114                         RDEBUG3("\t[%d] %s", i, argv[i]);
115                 }
116         }
117 #endif
118
119 #ifndef __MINGW32__
120         /*
121          *      Open a pipe for child/parent communication, if necessary.
122          */
123         if (exec_wait) {
124                 if (input_fd) {
125                         if (pipe(to_child) != 0) {
126                                 RDEBUG("Couldn't open pipe to child: %s", fr_syserror(errno));
127                                 return -1;
128                         }
129                 }
130                 if (output_fd) {
131                         if (pipe(from_child) != 0) {
132                                 RDEBUG("Couldn't open pipe from child: %s", fr_syserror(errno));
133                                 /* safe because these either need closing or are == -1 */
134                                 close(to_child[0]);
135                                 close(to_child[1]);
136                                 return -1;
137                         }
138                 }
139         }
140
141         envp[0] = NULL;
142
143         if (input_pairs) {
144                 vp_cursor_t cursor;
145                 int envlen;
146                 char buffer[1024];
147
148                 /*
149                  *      Set up the environment variables in the
150                  *      parent, so we don't call libc functions that
151                  *      hold mutexes.  They might be locked when we fork,
152                  *      and will remain locked in the child.
153                  */
154                 envlen = 0;
155
156                 for (vp = paircursor(&cursor, &input_pairs); vp; vp = pairnext(&cursor)) {
157                         /*
158                          *      Hmm... maybe we shouldn't pass the
159                          *      user's password in an environment
160                          *      variable...
161                          */
162                         snprintf(buffer, sizeof(buffer), "%s=", vp->da->name);
163                         if (shell_escape) {
164                                 for (p = buffer; *p != '='; p++) {
165                                         if (*p == '-') {
166                                                 *p = '_';
167                                         } else if (isalpha((int) *p)) {
168                                                 *p = toupper(*p);
169                                         }
170                                 }
171                         }
172
173                         n = strlen(buffer);
174                         vp_prints_value(buffer+n, sizeof(buffer) - n, vp, shell_escape ? '"' : 0);
175
176                         envp[envlen++] = strdup(buffer);
177
178                         /*
179                          *      Don't add too many attributes.
180                          */
181                         if (envlen == (MAX_ENVP - 1)) break;
182                 }
183                 envp[envlen] = NULL;
184         }
185
186         if (exec_wait) {
187                 pid = rad_fork();       /* remember PID */
188         } else {
189                 pid = fork();           /* don't wait */
190         }
191
192         if (pid == 0) {
193                 int devnull;
194
195                 /*
196                  *      Child process.
197                  *
198                  *      We try to be fail-safe here. So if ANYTHING
199                  *      goes wrong, we exit with status 1.
200                  */
201
202                 /*
203                  *      Open STDIN to /dev/null
204                  */
205                 devnull = open("/dev/null", O_RDWR);
206                 if (devnull < 0) {
207                         RDEBUG("Failed opening /dev/null: %s\n", fr_syserror(errno));
208
209                         /*
210                          *      Where the status code is interpreted as a module rcode
211                          *      one is subtracted from it, to allow 0 to equal success
212                          *
213                          *      2 is RLM_MODULE_FAIL + 1
214                          */
215                         exit(2);
216                 }
217
218                 /*
219                  *      Only massage the pipe handles if the parent
220                  *      has created them.
221                  */
222                 if (exec_wait) {
223                         if (input_fd) {
224                                 close(to_child[1]);
225                                 dup2(to_child[0], STDIN_FILENO);
226                         } else {
227                                 dup2(devnull, STDIN_FILENO);
228                         }
229
230                         if (output_fd) {
231                                 close(from_child[0]);
232                                 dup2(from_child[1], STDOUT_FILENO);
233                         } else {
234                                 dup2(devnull, STDOUT_FILENO);
235                         }
236
237                 } else {        /* no pipe, STDOUT should be /dev/null */
238                         dup2(devnull, STDIN_FILENO);
239                         dup2(devnull, STDOUT_FILENO);
240                 }
241
242                 /*
243                  *      If we're not debugging, then we can't do
244                  *      anything with the error messages, so we throw
245                  *      them away.
246                  *
247                  *      If we are debugging, then we want the error
248                  *      messages to go to the STDERR of the server.
249                  */
250                 if (debug_flag == 0) {
251                         dup2(devnull, STDERR_FILENO);
252                 }
253                 close(devnull);
254
255                 /*
256                  *      The server may have MANY FD's open.  We don't
257                  *      want to leave dangling FD's for the child process
258                  *      to play funky games with, so we close them.
259                  */
260                 closefrom(3);
261
262                 /*
263                  *      I swear the signature for execve is wrong and should take 'char const * const argv[]'.
264                  */
265                 execve(argv[0], argv, envp);
266                 printf("Failed to execute \"%s\": %s", argv[0], fr_syserror(errno)); /* fork output will be captured */
267
268                 /*
269                  *      Where the status code is interpreted as a module rcode
270                  *      one is subtracted from it, to allow 0 to equal success
271                  *
272                  *      2 is RLM_MODULE_FAIL + 1
273                  */
274                 exit(2);
275         }
276
277         /*
278          *      Free child environment variables
279          */
280         for (i = 0; envp[i] != NULL; i++) {
281                 free(envp[i]);
282         }
283
284         /*
285          *      Parent process.
286          */
287         if (pid < 0) {
288                 RDEBUG("Couldn't fork %s: %s", argv[0], fr_syserror(errno));
289                 if (exec_wait) {
290                         /* safe because these either need closing or are == -1 */
291                         close(to_child[0]);
292                         close(to_child[1]);
293                         close(from_child[0]);
294                         close(from_child[1]);
295                 }
296                 return -1;
297         }
298
299         /*
300          *      We're not waiting, exit, and ignore any child's status.
301          */
302         if (exec_wait) {
303                 /*
304                  *      Close the ends of the pipe(s) the child is using
305                  *      return the ends of the pipe(s) our caller wants
306                  *
307                  */
308                 if (input_fd) {
309                         *input_fd = to_child[1];
310                         close(to_child[0]);
311                 }
312                 if (output_fd) {
313                         *output_fd = from_child[0];
314                         close(from_child[1]);
315                 }
316         }
317
318         return pid;
319 #else
320         if (exec_wait) {
321                 RDEBUG("Wait is not supported");
322                 return -1;
323         }
324
325         {
326                 /*
327                  *      The _spawn and _exec families of functions are
328                  *      found in Windows compiler libraries for
329                  *      portability from UNIX. There is a variety of
330                  *      functions, including the ability to pass
331                  *      either a list or array of parameters, to
332                  *      search in the PATH or otherwise, and whether
333                  *      or not to pass an environment (a set of
334                  *      environment variables). Using _spawn, you can
335                  *      also specify whether you want the new process
336                  *      to close your program (_P_OVERLAY), to wait
337                  *      until the new process is finished (_P_WAIT) or
338                  *      for the two to run concurrently (_P_NOWAIT).
339
340                  *      _spawn and _exec are useful for instances in
341                  *      which you have simple requirements for running
342                  *      the program, don't want the overhead of the
343                  *      Windows header file, or are interested
344                  *      primarily in portability.
345                  */
346
347                 /*
348                  *      FIXME: check return code... what is it?
349                  */
350                 _spawnve(_P_NOWAIT, argv[0], argv, envp);
351         }
352
353         return 0;
354 #endif
355 }
356
357 /** Read from the child process.
358  *
359  * @param request The current request.
360  * @param fd file descriptor to read from.
361  * @param pid pid of child, will be reaped if it dies.
362  * @param timeout amount of time to wait, in seconds.
363  * @param answer buffer to write into.
364  * @param left length of buffer.
365  * @return -1 on error, or length of output.
366  */
367 int radius_readfrom_program(REQUEST *request, int fd, pid_t pid, int timeout,
368                             char *answer, int left)
369 {
370         int done = 0;
371 #ifndef __MINGW32__
372         int status;
373         struct timeval start;
374 #ifdef O_NONBLOCK
375         bool nonblock = true;
376 #endif
377
378 #ifdef O_NONBLOCK
379         /*
380          *      Try to set it non-blocking.
381          */
382         do {
383                 int flags;
384
385                 if ((flags = fcntl(fd, F_GETFL, NULL)) < 0)  {
386                         nonblock = false;
387                         break;
388                 }
389
390                 flags |= O_NONBLOCK;
391                 if( fcntl(fd, F_SETFL, flags) < 0) {
392                         nonblock = false;
393                         break;
394                 }
395         } while (0);
396 #endif
397
398
399         /*
400          *      Read from the pipe until we doesn't get any more or
401          *      until the message is full.
402          */
403         gettimeofday(&start, NULL);
404         while (1) {
405                 int rcode;
406                 fd_set fds;
407                 struct timeval when, elapsed, wake;
408
409                 FD_ZERO(&fds);
410                 FD_SET(fd, &fds);
411
412                 gettimeofday(&when, NULL);
413                 tv_sub(&when, &start, &elapsed);
414                 if (elapsed.tv_sec >= timeout) goto too_long;
415
416                 when.tv_sec = timeout;
417                 when.tv_usec = 0;
418                 tv_sub(&when, &elapsed, &wake);
419
420                 rcode = select(fd + 1, &fds, NULL, NULL, &wake);
421                 if (rcode == 0) {
422                 too_long:
423                         RDEBUG("Child PID %u is taking too much time: forcing failure and killing child.", pid);
424                         kill(pid, SIGTERM);
425                         close(fd); /* should give SIGPIPE to child, too */
426
427                         /*
428                          *      Clean up the child entry.
429                          */
430                         rad_waitpid(pid, &status);
431                         return -1;
432                 }
433                 if (rcode < 0) {
434                         if (errno == EINTR) continue;
435                         break;
436                 }
437
438 #ifdef O_NONBLOCK
439                 /*
440                  *      Read as many bytes as possible.  The kernel
441                  *      will return the number of bytes available.
442                  */
443                 if (nonblock) {
444                         status = read(fd, answer + done, left);
445                 } else
446 #endif
447                         /*
448                          *      There's at least 1 byte ready: read it.
449                          */
450                         status = read(fd, answer + done, 1);
451
452                 /*
453                  *      Nothing more to read: stop.
454                  */
455                 if (status == 0) {
456                         break;
457                 }
458
459                 /*
460                  *      Error: See if we have to continue.
461                  */
462                 if (status < 0) {
463                         /*
464                          *      We were interrupted: continue reading.
465                          */
466                         if (errno == EINTR) {
467                                 continue;
468                         }
469
470                         /*
471                          *      There was another error.  Most likely
472                          *      The child process has finished, and
473                          *      exited.
474                          */
475                         break;
476                 }
477
478                 done += status;
479                 left -= status;
480                 if (left <= 0) break;
481         }
482 #endif  /* __MINGW32__ */
483
484         /* Strip trailing new lines */
485         while ((done > 0) && (answer[done - 1] == '\n')) {
486                 answer[--done] = '\0';
487         }
488
489         return done;
490 }
491
492 /** Execute a program.
493  *
494  * @param[in] request Current request.
495  * @param[in] cmd Command to execute. This is parsed into argv[] parts, then each individual argv part
496  *      is xlat'ed.
497  * @param[in] exec_wait set to 1 if you want to read from or write to child.
498  * @param[in] shell_escape values before passing them as arguments.
499  * @param[in] user_msg buffer to append plaintext (non valuepair) output.
500  * @param[in] msg_len length of user_msg buffer.
501  * @param[in] timeout amount of time to wait, in seconds.
502  * @param[in] input_pairs list of value pairs - these will be available in the environment of the child.
503  * @param[out] output_pairs list of value pairs - child stdout will be parsed and added into this list
504  *      of value pairs.
505  * @return 0 if exec_wait==0, exit code if exec_wait!=0, -1 on error.
506  */
507 int radius_exec_program(REQUEST *request, char const *cmd, bool exec_wait, bool shell_escape,
508                         char *user_msg, size_t msg_len, int timeout,
509                         VALUE_PAIR *input_pairs, VALUE_PAIR **output_pairs)
510
511 {
512         pid_t pid;
513         int from_child;
514 #ifndef __MINGW32__
515         char *p;
516         pid_t child_pid;
517         int comma = 0;
518         int status, ret = 0;
519         ssize_t len;
520         char answer[4096];
521 #endif
522
523         RDEBUG2("Executing: %s", cmd);
524
525         if (user_msg) *user_msg = '\0';
526
527         pid = radius_start_program(cmd, request, exec_wait, NULL, &from_child, input_pairs, shell_escape);
528         if (pid < 0) {
529                 return -1;
530         }
531
532         if (!exec_wait) {
533                 return 0;
534         }
535
536 #ifndef __MINGW32__
537         len = radius_readfrom_program(request, from_child, pid, timeout, answer, sizeof(answer));
538         if (len < 0) {
539                 /*
540                  *      Failure - radius_readfrom_program will
541                  *      have called close(from_child) for us
542                  */
543                 DEBUG("Failed to read from child output");
544                 return -1;
545
546         }
547         answer[len] = '\0';
548
549         /*
550          *      Make sure that the writer can't block while writing to
551          *      a pipe that no one is reading from anymore.
552          */
553         close(from_child);
554
555         if (len == 0) {
556                 goto wait;
557         }
558
559         /*
560          *      Parse the output, if any.
561          */
562         if (output_pairs) {
563                 /*
564                  *      HACK: Replace '\n' with ',' so that
565                  *      userparse() can parse the buffer in
566                  *      one go (the proper way would be to
567                  *      fix userparse(), but oh well).
568                  */
569                 for (p = answer; *p; p++) {
570                         if (*p == '\n') {
571                                 *p = comma ? ' ' : ',';
572                                 p++;
573                                 comma = 0;
574                         }
575                         if (*p == ',') {
576                                 comma++;
577                         }
578                 }
579
580                 /*
581                  *      Replace any trailing comma by a NUL.
582                  */
583                 if (answer[len - 1] == ',') {
584                         answer[--len] = '\0';
585                 }
586
587                 if (userparse(request, answer, output_pairs) == T_OP_INVALID) {
588                         REDEBUG("Failed parsing output from: %s: %s", cmd, fr_strerror());
589                         strlcpy(user_msg, answer, len);
590                         ret = -1;
591                 }
592         /*
593          *      We've not been told to extract output pairs,
594          *      just copy the programs output to the user_msg
595          *      buffer.
596          */
597
598         } else if (user_msg) {
599                 strlcpy(user_msg, answer, msg_len);
600         }
601
602         /*
603          *      Call rad_waitpid (should map to waitpid on non-threaded
604          *      or single-server systems).
605          */
606 wait:
607         child_pid = rad_waitpid(pid, &status);
608         if (child_pid == 0) {
609                 REDEBUG("Timeout waiting for child");
610
611                 return -2;
612         }
613
614         if (child_pid == pid) {
615                 if (WIFEXITED(status)) {
616                         status = WEXITSTATUS(status);
617                         if ((status != 0) || (ret < 0)) {
618                                 REDEBUG("Program returned code (%d) and output '%s'", status, answer);
619                         } else {
620                                 RDEBUG("Program returned code (%d) and output '%s'", status, answer);
621                         }
622
623                         return ret < 0 ? ret : status;
624                 }
625         }
626
627         REDEBUG("Abnormal child exit: %s", fr_syserror(errno));
628 #endif  /* __MINGW32__ */
629
630         return -1;
631 }