New logging functions which log to both syslog and STDERR.
[guacd.git] / src / daemon.c
index 5855214..9a3de23 100644 (file)
@@ -43,6 +43,7 @@
 #include <sys/types.h>
 
 #include <sys/socket.h>
+#include <netdb.h>
 #include <netinet/in.h>
 
 #include <errno.h>
 #include "client.h"
 #include "log.h"
 
-typedef struct client_thread_data {
-
-    int fd;
-
-} client_thread_data;
-
-
-void* start_client_thread(void* data) {
+void guacd_handle_connection(int fd) {
 
     guac_client* client;
     guac_client_plugin* plugin;
     guac_instruction* select;
     guac_instruction* connect;
 
-    /* Get thread data */
-    client_thread_data* thread_data = (client_thread_data*) data;
-
     /* Open guac_socket */
-    guac_socket* socket = guac_socket_open(thread_data->fd);
+    guac_socket* socket = guac_socket_open(fd);
 
     /* Get protocol from select instruction */
     select = guac_protocol_expect_instruction(
@@ -84,8 +75,7 @@ void* start_client_thread(void* data) {
 
         /* Free resources */
         guac_socket_close(socket);
-        free(data);
-        return NULL;
+        return;
     }
 
     /* Validate args to select */
@@ -97,8 +87,7 @@ void* start_client_thread(void* data) {
 
         /* Free resources */
         guac_socket_close(socket);
-        free(data);
-        return NULL;
+        return;
     }
 
     syslog(LOG_INFO, "Protocol \"%s\" selected", select->argv[0]);
@@ -114,8 +103,7 @@ void* start_client_thread(void* data) {
 
         /* Free resources */
         guac_socket_close(socket);
-        free(data);
-        return NULL;
+        return;
     }
 
     /* Send args response */
@@ -129,8 +117,7 @@ void* start_client_thread(void* data) {
             guacd_log_guac_error("Error closing client plugin");
 
         guac_socket_close(socket);
-        free(data);
-        return NULL;
+        return;
     }
 
     /* Get args from connect instruction */
@@ -145,13 +132,14 @@ void* start_client_thread(void* data) {
             guacd_log_guac_error("Error closing client plugin");
 
         guac_socket_close(socket);
-        free(data);
-        return NULL;
+        return;
     }
 
     /* Load and init client */
     client = guac_client_plugin_get_client(plugin, socket,
-            connect->argc, connect->argv); 
+            connect->argc, connect->argv,
+            guacd_client_log_info, guacd_client_log_error);
+
     guac_instruction_free(connect);
 
     if (client == NULL) {
@@ -162,17 +150,12 @@ void* start_client_thread(void* data) {
             guacd_log_guac_error("Error closing client plugin");
 
         guac_socket_close(socket);
-        free(data);
-        return NULL;
+        return;
     }
 
-    /* Set up logging in client */
-    client->log_info_handler  = guacd_log_info;
-    client->log_error_handler = guacd_log_error;
-
     /* Start client threads */
     syslog(LOG_INFO, "Starting client");
-    if (guac_start_client(client))
+    if (guacd_client_start(client))
         syslog(LOG_ERR, "Client finished abnormally");
     else
         syslog(LOG_INFO, "Client finished normally");
@@ -184,10 +167,8 @@ void* start_client_thread(void* data) {
 
     /* Close socket */
     guac_socket_close(socket);
-    close(thread_data->fd);
 
-    free(data);
-    return NULL;
+    return;
 
 }
 
@@ -195,46 +176,63 @@ int main(int argc, char* argv[]) {
 
     /* Server */
     int socket_fd;
-    struct sockaddr_in server_addr;
+    struct addrinfo* addresses;
+    struct addrinfo* current_address;
+    char bound_address[1024];
+    char bound_port[64];
     int opt_on = 1;
 
+    struct addrinfo hints = {
+        .ai_family   = AF_UNSPEC,
+        .ai_socktype = SOCK_STREAM,
+        .ai_protocol = IPPROTO_TCP
+    };
+
     /* Client */
     struct sockaddr_in client_addr;
     socklen_t client_addr_len;
     int connected_socket_fd;
 
     /* Arguments */
-    int listen_port = 4822; /* Default port */
+    char* listen_address = NULL; /* Default address of INADDR_ANY */
+    char* listen_port = "4822";  /* Default port */
+    char* pidfile = NULL;
     int opt;
 
-    char* pidfile = NULL;
+    /* General */
+    int retval;
 
     /* Daemon Process */
     pid_t daemon_pid;
 
     /* Parse arguments */
-    while ((opt = getopt(argc, argv, "l:p:")) != -1) {
+    while ((opt = getopt(argc, argv, "l:b:p:")) != -1) {
         if (opt == 'l') {
-            listen_port = atoi(optarg);
-            if (listen_port <= 0) {
-                fprintf(stderr, "Invalid port: %s\n", optarg);
-                exit(EXIT_FAILURE);
-            }
+            listen_port = strdup(optarg);
+        }
+        else if (opt == 'b') {
+            listen_address = strdup(optarg);
         }
         else if (opt == 'p') {
             pidfile = strdup(optarg);
         }
         else {
-            fprintf(stderr, "USAGE: %s [-l LISTENPORT] [-p PIDFILE]\n", argv[0]);
+
+            fprintf(stderr, "USAGE: %s"
+                    " [-l LISTENPORT]"
+                    " [-b LISTENADDRESS]"
+                    " [-p PIDFILE]\n", argv[0]);
+
             exit(EXIT_FAILURE);
         }
     }
 
-    /* Get binding address */
-    memset(&server_addr, 0, sizeof(server_addr)); /* Zero struct */
-    server_addr.sin_family = AF_INET;
-    server_addr.sin_addr.s_addr = INADDR_ANY;
-    server_addr.sin_port = htons(listen_port);
+    /* Get addresses for binding */
+    if ((retval = getaddrinfo(listen_address, listen_port, &hints, &addresses))) {
+        fprintf(stderr, "Error parsing given address or port: %s\n",
+                gai_strerror(retval));
+        exit(EXIT_FAILURE);
+    }
 
     /* Get socket */
     socket_fd = socket(AF_INET, SOCK_STREAM, 0);
@@ -243,16 +241,54 @@ int main(int argc, char* argv[]) {
         exit(EXIT_FAILURE);
     }
 
+    /* Allow socket reuse */
     if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, (void*) &opt_on, sizeof(opt_on))) {
         fprintf(stderr, "Warning: Unable to set socket options for reuse: %s\n", strerror(errno));
     }
 
-    /* Bind socket to address */
-    if (bind(socket_fd, (struct sockaddr*) &server_addr,
-                sizeof(server_addr)) < 0) {
-        fprintf(stderr, "Error binding socket: %s\n", strerror(errno));
+    /* Attempt binding of each address until success */
+    current_address = addresses;
+    while (current_address != NULL) {
+
+        int retval;
+
+        /* Resolve hostname */
+        if ((retval = getnameinfo(current_address->ai_addr,
+                current_address->ai_addrlen,
+                bound_address, sizeof(bound_address),
+                bound_port, sizeof(bound_port),
+                NI_NUMERICHOST | NI_NUMERICSERV)))
+            fprintf(stderr, "Unable to resolve host: %s\n",
+                    gai_strerror(retval));
+
+        /* Attempt to bind socket to address */
+        if (bind(socket_fd,
+                    current_address->ai_addr,
+                    current_address->ai_addrlen) == 0) {
+
+            fprintf(stderr, "Successfully bound socket to "
+                    "host %s, port %s\n", bound_address, bound_port);
+
+            /* Done if successful bind */
+            break;
+
+        }
+
+        /* Otherwise log error */
+        else
+            fprintf(stderr, "Error binding socket to "
+                    "host %s, port %s: %s\n",
+                    bound_address, bound_port, strerror(errno));
+
+        current_address = current_address->ai_next;
+
+    }
+
+    /* If unable to bind to anything, fail */
+    if (current_address == NULL) {
+        fprintf(stderr, "Unable to bind socket to any addresses.\n");
         exit(EXIT_FAILURE);
-    } 
+    }
 
     /* Fork into background */
     daemon_pid = fork();
@@ -289,9 +325,6 @@ int main(int argc, char* argv[]) {
     /* Open log */
     openlog(NULL, LOG_PID, LOG_DAEMON);
 
-    /* Otherwise, this is the daemon */
-    syslog(LOG_INFO, "Listening on port %i", listen_port);
-
     /* Ignore SIGPIPE */
     if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
         syslog(LOG_ERR, "Could not set handler for SIGPIPE to ignore. SIGPIPE may cause termination of the daemon.");
@@ -302,11 +335,17 @@ int main(int argc, char* argv[]) {
         syslog(LOG_ERR, "Could not set handler for SIGCHLD to ignore. Child processes may pile up in the process table.");
     }
 
+    /* Log listening status */
+    syslog(LOG_INFO,
+            "Listening on host %s, port %s", bound_address, bound_port);
+
+    /* Free addresses */
+    freeaddrinfo(addresses);
+
     /* Daemon loop */
     for (;;) {
 
         pid_t child_pid;
-        client_thread_data* data;
 
         /* Listen for connections */
         if (listen(socket_fd, 5) < 0) {
@@ -322,9 +361,6 @@ int main(int argc, char* argv[]) {
             return 3;
         }
 
-        data = malloc(sizeof(client_thread_data));
-        data->fd = connected_socket_fd;
-
         /* 
          * Once connection is accepted, send child into background.
          *
@@ -342,7 +378,8 @@ int main(int argc, char* argv[]) {
 
         /* If child, start client, and exit when finished */
         else if (child_pid == 0) {
-            start_client_thread(data);
+            guacd_handle_connection(connected_socket_fd);
+            close(connected_socket_fd);
             return 0;
         }