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.
30 static void unputenv(const char *p) {
31 const char *e = strchr(p, '=');
37 // Windows requires putenv("FOO=") to unset %FOO%
47 // We must keep what we putenv() around in memory.
48 // To do this without memory leaks, keep things in a list and reuse if possible.
49 static list_t list = {};
50 for list_each(char, data, &list) {
51 if(!strcmp(data, var)) {
56 char *data = xstrdup(var);
57 list_insert_tail(&list, data);
62 static void putenv(const char *p) {}
63 static void unputenv(const char *p) {}
66 bool execute_script(const char *name, char **envp) {
68 char scriptname[PATH_MAX];
71 snprintf(scriptname, sizeof scriptname, "%s" SLASH "%s%s", confbase, name, scriptextension);
73 /* First check if there is a script */
76 if(!*scriptextension) {
77 const char *pathext = getenv("PATHEXT") ?: ".COM;.EXE;.BAT;.CMD";
78 char fullname[strlen(scriptname) + strlen(pathext)];
79 char *ext = fullname + strlen(scriptname);
80 strcpy(fullname, scriptname);
82 const char *p = pathext;
85 const char *q = strchr(p, ';');
87 memcpy(ext, p, q - p);
93 if((found = !access(fullname, F_OK)))
102 if(access(scriptname, F_OK))
105 logger(DEBUG_STATUS, LOG_INFO, "Executing script %s", name);
107 /* Set environment */
109 for(int i = 0; envp[i]; i++)
112 if(scriptinterpreter)
113 xasprintf(&command, "%s \"%s\"", scriptinterpreter, scriptname);
115 xasprintf(&command, "\"%s\"", scriptname);
117 int status = system(command);
121 /* Unset environment */
123 for(int i = 0; envp[i]; i++)
128 if(WIFEXITED(status)) { /* Child exited by itself */
129 if(WEXITSTATUS(status)) {
130 logger(DEBUG_ALWAYS, LOG_ERR, "Script %s exited with non-zero status %d",
131 name, WEXITSTATUS(status));
134 } else if(WIFSIGNALED(status)) { /* Child was killed by a signal */
135 logger(DEBUG_ALWAYS, LOG_ERR, "Script %s was killed by signal %d (%s)",
136 name, WTERMSIG(status), strsignal(WTERMSIG(status)));
138 } else { /* Something strange happened */
139 logger(DEBUG_ALWAYS, LOG_ERR, "Script %s terminated abnormally", name);
144 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));