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