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