2 script.c -- call an external script
3 Copyright (C) 1999-2005 Ivo Timmermans,
4 2000-2013 Guus Sliepen <guus@tinc-vpn.org>
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.
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.
16 You should have received a copy of the GNU General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
29 bool execute_script(const char *name, char **envp) {
34 xasprintf(&scriptname, "%s" SLASH "%s%s", confbase, name, scriptextension);
36 /* First check if there is a script */
39 if(!*scriptextension) {
40 const char *pathext = getenv("PATHEXT") ?: ".COM;.EXE;.BAT;.CMD";
41 char fullname[strlen(scriptname) + strlen(pathext)];
42 char *ext = fullname + strlen(scriptname);
43 strcpy(fullname, scriptname);
45 const char *p = pathext;
48 const char *q = strchr(p, ';');
50 memcpy(ext, p, q - p);
56 if((found = !access(fullname, F_OK)))
67 if(access(scriptname, F_OK)) {
72 logger(DEBUG_STATUS, LOG_INFO, "Executing script %s", name);
77 for(int i = 0; envp[i]; i++)
82 xasprintf(&command, "%s \"%s\"", scriptinterpreter, scriptname);
84 xasprintf(&command, "\"%s\"", scriptname);
86 int status = system(command);
91 /* Unset environment */
93 for(int i = 0; envp[i]; i++) {
94 char *e = strchr(envp[i], '=');
96 char p[e - envp[i] + 1];
97 strncpy(p, envp[i], e - envp[i]);
98 p[e - envp[i]] = '\0';
105 if(WIFEXITED(status)) { /* Child exited by itself */
106 if(WEXITSTATUS(status)) {
107 logger(DEBUG_ALWAYS, LOG_ERR, "Script %s exited with non-zero status %d",
108 name, WEXITSTATUS(status));
111 } else if(WIFSIGNALED(status)) { /* Child was killed by a signal */
112 logger(DEBUG_ALWAYS, LOG_ERR, "Script %s was killed by signal %d (%s)",
113 name, WTERMSIG(status), strsignal(WTERMSIG(status)));
115 } else { /* Something strange happened */
116 logger(DEBUG_ALWAYS, LOG_ERR, "Script %s terminated abnormally", name);
121 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));