From edc47252604d38fe6f0e229d5f8a206fbcd9dbce Mon Sep 17 00:00:00 2001
From: Joel Martin <github@martintribe.org>
Date: Fri, 10 Sep 2010 14:31:34 -0500
Subject: [PATCH] proxy: do handshake in forked process too.

---
 utils/websocket.c  | 17 +++++++++++------
 utils/websocket.py |  9 +++++++--
 2 files changed, 18 insertions(+), 8 deletions(-)

diff --git a/utils/websocket.c b/utils/websocket.c
index 1bcc21b..d5ad5aa 100644
--- a/utils/websocket.c
+++ b/utils/websocket.c
@@ -504,12 +504,6 @@ void start_server() {
         }
         handler_msg("got client connection from %s\n",
                     inet_ntoa(cli_addr.sin_addr));
-        ws_ctx = do_handshake(csock);
-        if (ws_ctx == NULL) {
-            close(csock);
-            continue;
-        }
-
         /* base64 is 4 bytes for every 3
          *    20 for WS '\x00' / '\xff' and good measure  */
         dbufsize = (bufsize * 3)/4 - 20;
@@ -520,6 +514,17 @@ void start_server() {
         }
 
         if (pid == 0) {  // handler process
+            ws_ctx = do_handshake(csock);
+            if (ws_ctx == NULL) {
+                close(csock);
+                if (settings.multiprocess) {
+                    handler_msg("No connection after handshake");
+                    break;   // Child process exits
+                } else {
+                    continue;
+                }
+            }
+
             settings.handler(ws_ctx);
             if (pipe_error) {
                 handler_emsg("Closing due to SIGPIPE\n");
diff --git a/utils/websocket.py b/utils/websocket.py
index abc463f..4011d74 100755
--- a/utils/websocket.py
+++ b/utils/websocket.py
@@ -208,14 +208,19 @@ def start_server():
                         settings['listen_host'], settings['listen_port'])
             startsock, address = lsock.accept()
             handler_msg('got client connection from %s' % address[0])
-            csock = do_handshake(startsock)
-            if not csock: continue
 
             if settings['multiprocess']:
                 handler_msg("forking handler process")
                 pid = os.fork()
 
             if pid == 0:  # handler process
+                csock = do_handshake(startsock)
+                if not csock:
+                    if settings['multiprocess']:
+                        handler_msg("No connection after handshake");
+                        break
+                    else:
+                        continue
                 settings['handler'](csock)
             else:         # parent process
                 settings['handler_id'] += 1
-- 
2.18.1