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