2 script.c -- call an external script
3 Copyright (C) 1999-2005 Ivo Timmermans,
4 2000-2015 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) {
31 char scriptname[PATH_MAX];
34 snprintf(scriptname, sizeof 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)))
65 if(access(scriptname, F_OK))
68 logger(DEBUG_STATUS, LOG_INFO, "Executing script %s", name);
73 for(int i = 0; envp[i]; i++)
78 xasprintf(&command, "%s \"%s\"", scriptinterpreter, scriptname);
80 xasprintf(&command, "\"%s\"", scriptname);
82 int status = system(command);
86 /* Unset environment */
88 for(int i = 0; envp[i]; i++) {
89 char *e = strchr(envp[i], '=');
91 char p[e - envp[i] + 1];
92 strncpy(p, envp[i], e - envp[i]);
93 p[e - envp[i]] = '\0';
100 if(WIFEXITED(status)) { /* Child exited by itself */
101 if(WEXITSTATUS(status)) {
102 logger(DEBUG_ALWAYS, LOG_ERR, "Script %s exited with non-zero status %d",
103 name, WEXITSTATUS(status));
106 } else if(WIFSIGNALED(status)) { /* Child was killed by a signal */
107 logger(DEBUG_ALWAYS, LOG_ERR, "Script %s was killed by signal %d (%s)",
108 name, WTERMSIG(status), strsignal(WTERMSIG(status)));
110 } else { /* Something strange happened */
111 logger(DEBUG_ALWAYS, LOG_ERR, "Script %s terminated abnormally", name);
116 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));