From b2692bc5abacf503e4f67c447d52511cc2cd26a8 Mon Sep 17 00:00:00 2001
From: Simon Ruderich <simon@ruderich.org>
Date: Sun, 27 Feb 2011 14:36:12 +0100
Subject: [PATCH] tlsproxy.c: Free resources when receiving SIGINT.

---
 tlsproxy.c | 34 +++++++++++++++++++++++++++++++---
 1 file changed, 31 insertions(+), 3 deletions(-)

diff --git a/tlsproxy.c b/tlsproxy.c
index 2d16465..157633b 100644
--- a/tlsproxy.c
+++ b/tlsproxy.c
@@ -30,6 +30,8 @@
 #include <netdb.h>
 /* strncmp() */
 #include <string.h>
+/* sigaction() */
+#include <signal.h>
 /* poll() */
 #include <poll.h>
 
@@ -40,10 +42,16 @@
 #define MAX_REQUEST_LINE 4096
 
 
+/* Server should shut down. Set by SIGINT handler. */
+static volatile int done;
+
 /* Proxy hostname and port if specified on the command line. */
 static char *use_proxy_host;
 static char *use_proxy_port;
 
+
+static void sigint_handler(int signal);
+
 static void parse_arguments(int argc, char **argv);
 static void print_usage(const char *argv);
 
@@ -66,6 +74,8 @@ int main(int argc, char **argv) {
     int client_socket, server_socket;
     struct sockaddr_in6 server_in;
 
+    struct sigaction action;
+
     parse_arguments(argc, argv);
 
     port = atoi(argv[argc - 1]);
@@ -75,6 +85,13 @@ int main(int argc, char **argv) {
         return EXIT_FAILURE;
     }
 
+    /* Setup our SIGINT signal handler which allows a "normal" termination of
+     * the server. */
+    sigemptyset(&action.sa_mask);
+    action.sa_handler = sigint_handler;
+    action.sa_flags   = 0;
+    sigaction(SIGINT, &action, NULL);
+
     server_socket = socket(PF_INET6, SOCK_STREAM, 0);
     if (-1 == server_socket) {
         perror("socket()");
@@ -114,18 +131,29 @@ int main(int argc, char **argv) {
     }
 #endif
 
-    for (;;) {
+    while (!done) {
         /* Accept new connection. */
         client_socket = accept(server_socket, NULL, NULL);
         if (-1 == client_socket) {
             perror("accept()");
-            return EXIT_FAILURE;
+            break;
         }
 
         handle_connection(client_socket);
     }
 
-    return EXIT_SUCCESS;
+    close(server_socket);
+
+    free(use_proxy_host);
+    free(use_proxy_port);
+
+    return EXIT_FAILURE;
+}
+
+static void sigint_handler(int signal_number) {
+    (void)signal_number;
+
+    done = 1;
 }
 
 static void parse_arguments(int argc, char **argv) {
-- 
2.49.0