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.
30 bool execute_script(const char *name, char **envp) {
35 xasprintf(&scriptname, "%s" SLASH "%s%s", confbase, name, scriptextension);
37 /* First check if there is a script */
40 if(!*scriptextension) {
41 const char *pathext = getenv("PATHEXT") ?: ".COM;.EXE;.BAT;.CMD";
42 char fullname[strlen(scriptname) + strlen(pathext)];
43 char *ext = fullname + strlen(scriptname);
44 strcpy(fullname, scriptname);
46 const char *p = pathext;
49 const char *q = strchr(p, ';');
51 memcpy(ext, p, q - p);
57 if((found = !access(fullname, F_OK)))
68 if(access(scriptname, F_OK)) {
73 logger(DEBUG_STATUS, LOG_INFO, "Executing script %s", name);
78 for(int i = 0; envp[i]; i++)
83 xasprintf(&command, "%s \"%s\"", scriptinterpreter, scriptname);
85 xasprintf(&command, "\"%s\"", scriptname);
87 int status = system(command);
92 /* Unset environment */
94 for(int i = 0; envp[i]; i++) {
95 char *e = strchr(envp[i], '=');
97 char p[e - envp[i] + 1];
98 strncpy(p, envp[i], e - envp[i]);
99 p[e - envp[i]] = '\0';
106 if(WIFEXITED(status)) { /* Child exited by itself */
107 if(WEXITSTATUS(status)) {
108 logger(DEBUG_ALWAYS, LOG_ERR, "Script %s exited with non-zero status %d",
109 name, WEXITSTATUS(status));
112 } else if(WIFSIGNALED(status)) { /* Child was killed by a signal */
113 logger(DEBUG_ALWAYS, LOG_ERR, "Script %s was killed by signal %d (%s)",
114 name, WTERMSIG(status), strsignal(WTERMSIG(status)));
116 } else { /* Something strange happened */
117 logger(DEBUG_ALWAYS, LOG_ERR, "Script %s terminated abnormally", name);
122 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));