+#ifdef HAVE_PUTENV
+static void unputenv(const char *p) {
+ const char *e = strchr(p, '=');
+
+ if(!e) {
+ return;
+ }
+
+ int len = e - p;
+#ifndef HAVE_UNSETENV
+#ifdef HAVE_MINGW
+ // Windows requires putenv("FOO=") to unset %FOO%
+ len++;
+#endif
+#endif
+ char var[len + 1];
+ strncpy(var, p, len);
+ var[len] = 0;
+#ifdef HAVE_UNSETENV
+ unsetenv(var);
+#else
+ // We must keep what we putenv() around in memory.
+ // To do this without memory leaks, keep things in a list and reuse if possible.
+ static list_t list = {0};
+
+ for list_each(char, data, &list) {
+ if(!strcmp(data, var)) {
+ putenv(data);
+ return;
+ }
+ }
+
+ char *data = xstrdup(var);
+ list_insert_tail(&list, data);
+ putenv(data);
+#endif
+}
+#else
+static void putenv(const char *p) {}
+static void unputenv(const char *p) {}
+#endif
+
+static const int min_env_size = 10;
+
+int environment_add(environment_t *env, const char *format, ...) {
+ if(env->n >= env->size) {
+ env->size = env->n ? env->n * 2 : min_env_size;
+ env->entries = xrealloc(env->entries, env->size * sizeof(*env->entries));
+ }
+
+ if(format) {
+ va_list ap;
+ va_start(ap, format);
+ vasprintf(&env->entries[env->n], format, ap);
+ va_end(ap);
+ } else {
+ env->entries[env->n] = NULL;
+ }
+
+ return env->n++;
+}
+
+void environment_update(environment_t *env, int pos, const char *format, ...) {
+ free(env->entries[pos]);
+ va_list ap;
+ va_start(ap, format);
+ vasprintf(&env->entries[pos], format, ap);
+ va_end(ap);
+}
+
+void environment_init(environment_t *env) {
+ env->n = 0;
+ env->size = min_env_size;
+ env->entries = xzalloc(env->size * sizeof(*env->entries));
+
+ if(netname) {
+ environment_add(env, "NETNAME=%s", netname);
+ }
+
+ if(myname) {
+ environment_add(env, "NAME=%s", myname);
+ }
+
+ if(device) {
+ environment_add(env, "DEVICE=%s", device);
+ }
+
+ if(iface) {
+ environment_add(env, "INTERFACE=%s", iface);
+ }
+
+ if(debug_level >= 0) {
+ environment_add(env, "DEBUG=%d", debug_level);
+ }
+}
+
+void environment_exit(environment_t *env) {
+ for(int i = 0; i < env->n; i++) {
+ free(env->entries[i]);
+ }
+
+ free(env->entries);
+}
+
+bool execute_script(const char *name, environment_t *env) {