464xlat: rework process id write logic
authorHans Dedecker <[email protected]>
Thu, 1 Jun 2017 12:19:42 +0000 (14:19 +0200)
committerHans Dedecker <[email protected]>
Fri, 2 Jun 2017 13:34:06 +0000 (15:34 +0200)
Write the process id in the pid file immediately after the 464xlat pid file has
been openend. Before the process id was written when the parent process exits
leaving a window where no valid process id was in place in the 464xlat pid file.
This lead to issues if the 464xlat utility was launched to terminate a running
464xlat utility as it could possibly terminate a random process.
If the parent process exits the pid file is updated with the process id of the
forked 464xlat utility.
Also rework the signal handling of SIGTERM so the running 464xlat utility is
correctly terminated.

Signed-off-by: Hans Dedecker <[email protected]>
nat46/src/464xlatcfg.c

index f1846161db0e0aa6384e493985380b0836685619..0f9ad318126e39a7121e24a71c94b3779433e2a6 100644 (file)
@@ -1,6 +1,7 @@
 /* 464xlatcfg.c
  *
  * Copyright (c) 2015 Steven Barth <[email protected]>
+ * Copyright (c) 2017 Hans Dedecker <[email protected]>
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License version 2
@@ -40,8 +41,9 @@ int main(int argc, const char *argv[])
        snprintf(buf, sizeof(buf), "/var/run/%s.pid", argv[1]);
        FILE *fp = fopen(buf, "r");
        if (fp) {
-               fscanf(fp, "%d", &pid);
-               kill(pid, SIGTERM);
+               if (fscanf(fp, "%d", &pid) == 1)
+                       kill(pid, SIGTERM);
+
                unlink(buf);
                fclose(fp);
        }
@@ -52,7 +54,9 @@ int main(int argc, const char *argv[])
        if (!argv[3] || !argv[4] || !(fp = fopen(buf, "wx")))
                return 1;
 
-       signal(SIGTERM, sighandler);
+       signal(SIGTERM, SIG_DFL);
+       setvbuf(fp, NULL, _IOLBF, 0);
+       fprintf(fp, "%d\n", getpid());
 
        prefix[sizeof(prefix) - 1] = 0;
        strncpy(prefix, argv[3], sizeof(prefix) - 1);
@@ -133,6 +137,7 @@ int main(int argc, const char *argv[])
                fclose(stderr);
                chdir("/");
                setsid();
+               signal(SIGTERM, sighandler);
                pause();
 
                nat46 = fopen("/proc/net/nat46/control", "w");
@@ -141,6 +146,7 @@ int main(int argc, const char *argv[])
                        fclose(nat46);
                }
        } else {
+               rewind(fp);
                fprintf(fp, "%d\n", pid);
        }