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