Browse Source

Refactoring; add get_passed_cfd() function to dinit-client

Add a function to get the file descriptor for the control socket connect
as passed by the parent (usually, from when a dinit service has the
"pass-cs-fd" option set).

The functionality is moved from shutdown.
Davin McCall 1 year ago
parent
commit
713dee22cf
2 changed files with 29 additions and 17 deletions
  1. 25 0
      src/includes/dinit-client.h
  2. 4 17
      src/shutdown.cc

+ 25 - 0
src/includes/dinit-client.h

@@ -337,3 +337,28 @@ inline int connect_to_daemon(const char *control_socket_path)
 
     return socknum;
 }
+
+// Get the file descriptor for the control socket connection as passed to use from parent process
+// (returns -1 if unsuccessful)
+inline int get_passed_cfd()
+{
+    int socknum = -1;
+    char * dinit_cs_fd_env = getenv("DINIT_CS_FD");
+    if (dinit_cs_fd_env != nullptr) {
+        char * endptr;
+        long int cfdnum = strtol(dinit_cs_fd_env, &endptr, 10);
+        if (endptr != dinit_cs_fd_env) {
+            socknum = (int) cfdnum;
+            // Set blocking mode (and validate file descriptor):
+            errno = 0;
+            int sock_flags = fcntl(socknum, F_GETFL, 0);
+            if (sock_flags == -1 && errno != 0) {
+                socknum = 0;
+            }
+            else {
+                fcntl(socknum, F_SETFL, sock_flags & ~O_NONBLOCK);
+            }
+        }
+    }
+    return socknum;
+}

+ 4 - 17
src/shutdown.cc

@@ -310,29 +310,16 @@ int main(int argc, char **argv)
 
     signal(SIGPIPE, SIG_IGN);
     
-    int socknum = 0;
+    int socknum = -1;
     
     if (use_passed_cfd) {
-        char * dinit_cs_fd_env = getenv("DINIT_CS_FD");
-        if (dinit_cs_fd_env != nullptr) {
-            char * endptr;
-            long int cfdnum = strtol(dinit_cs_fd_env, &endptr, 10);
-            if (endptr != dinit_cs_fd_env) {
-                socknum = (int) cfdnum;
-                // Set non-blocking mode:
-                int sock_flags = fcntl(socknum, F_GETFL, 0);
-                fcntl(socknum, F_SETFL, sock_flags & ~O_NONBLOCK);
-            }
-            else {
-                use_passed_cfd = false;
-            }
-        }
-        else {
+        socknum = get_passed_cfd();
+        if (socknum == -1) {
             use_passed_cfd = false;
         }
     }
     
-    if (! use_passed_cfd) {
+    if (!use_passed_cfd) {
         socknum = socket(AF_UNIX, SOCK_STREAM, 0);
         if (socknum == -1) {
             perror("socket");