+bool detach(void) {
+ setup_signals();
+
+ /* First check if we can open a fresh new pidfile */
+
+#ifndef HAVE_MINGW
+ if(!write_pidfile())
+ return false;
+
+ /* If we succeeded in doing that, detach */
+
+ closelogger();
+#endif
+
+ if(do_detach) {
+#ifndef HAVE_MINGW
+ if(daemon(0, 0)) {
+ fprintf(stderr, "Couldn't detach from terminal: %s",
+ strerror(errno));
+ return false;
+ }
+
+ /* Now UPDATE the pid in the pidfile, because we changed it... */
+
+ if(!write_pid(pidfilename)) {
+ fprintf(stderr, "Could not write pid file %s: %s\n", pidfilename, strerror(errno));
+ return false;
+ }
+#else
+ if(!statushandle)
+ exit(install_service());
+#endif
+ }
+
+ openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
+
+ logger(LOG_NOTICE, "tincd %s (%s %s) starting, debug level %d",
+ VERSION, __DATE__, __TIME__, debug_level);
+
+ xalloc_fail_func = memory_full;
+
+ return true;
+}
+
+bool execute_script(const char *name, char **envp) {
+#ifdef HAVE_SYSTEM
+ int status, len;
+ char *scriptname;
+ int i;
+
+#ifndef HAVE_MINGW
+ len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
+#else
+ len = xasprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
+#endif
+ if(len < 0)
+ return false;
+
+ scriptname[len - 1] = '\0';
+
+#ifndef HAVE_TUNEMU
+ /* First check if there is a script */
+
+ if(access(scriptname + 1, F_OK)) {
+ free(scriptname);
+ return true;
+ }
+#endif
+
+ ifdebug(STATUS) logger(LOG_INFO, "Executing script %s", name);
+
+#ifdef HAVE_PUTENV
+ /* Set environment */
+
+ for(i = 0; envp[i]; i++)
+ putenv(envp[i]);
+#endif
+
+ scriptname[len - 1] = '\"';
+ status = system(scriptname);
+
+ free(scriptname);
+
+ /* Unset environment */
+
+ for(i = 0; envp[i]; i++) {
+ char *e = strchr(envp[i], '=');
+ if(e) {
+ char p[e - envp[i] + 1];
+ strncpy(p, envp[i], e - envp[i]);
+ p[e - envp[i]] = '\0';
+ putenv(p);
+ }
+ }
+
+#ifdef WEXITSTATUS
+ if(status != -1) {
+ if(WIFEXITED(status)) { /* Child exited by itself */
+ if(WEXITSTATUS(status)) {
+ logger(LOG_ERR, "Script %s exited with non-zero status %d",
+ name, WEXITSTATUS(status));
+ return false;
+ }
+ } else if(WIFSIGNALED(status)) { /* Child was killed by a signal */
+ logger(LOG_ERR, "Script %s was killed by signal %d (%s)",
+ name, WTERMSIG(status), strsignal(WTERMSIG(status)));
+ return false;
+ } else { /* Something strange happened */
+ logger(LOG_ERR, "Script %s terminated abnormally", name);
+ return false;
+ }
+ } else {
+ logger(LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));
+ return false;
+ }
+#endif
+#endif
+ return true;