rnewson commented on code in PR #4736:
URL: https://github.com/apache/couchdb/pull/4736#discussion_r1303542422


##########
src/chttpd/src/chttpd_util.erl:
##########
@@ -110,3 +118,125 @@ get_db_info(DbName) ->
     catch
         _Tag:Error -> {error, Error}
     end.
+
+mochiweb_socket_set(Sock) ->
+    put(?MOCHIWEB_SOCKET, Sock).
+
+mochiweb_socket_get() ->
+    get(?MOCHIWEB_SOCKET).
+
+mochiweb_socket_clean() ->
+    erase(?MOCHIWEB_SOCKET).
+
+mochiweb_socket_check_msec() ->
+    MSec = config:get_integer("chttpd", "disconnect_check_msec", 
?DISCONNECT_CHECK_MSEC),
+    % Add some jitter to avoid a stampede in case of a larger number of 
concurrent connection
+    MSec + rand:uniform(MSec).
+
+stop_client_process_if_disconnected(Pid, Sock) ->
+    case is_mochiweb_socket_closed(Sock) of
+        true ->
+            couch_log:warning("client socket ~p disconnected, terminating ~p", 
[Sock, Pid]),
+            exit(Pid, {shutdown, client_disconnected});
+        false ->
+            ok
+    end.
+
+is_mochiweb_socket_closed(undefined) ->
+    false;
+is_mochiweb_socket_closed(Sock) ->
+    OsType = os:type(),
+    case tcp_info_opt(OsType) of
+        {raw, _, _, _} = InfoOpt ->
+            case mochiweb_socket:getopts(Sock, [InfoOpt]) of
+                {ok, [{raw, _, _, <<State:8/native, _/binary>>}]} ->
+                    tcp_is_closed(State, OsType);
+                {ok, []} ->
+                    false;
+                {error, einval} ->
+                    % Already cleaned up
+                    true;
+                {error, _} ->
+                    false
+            end;
+        undefined ->
+            false
+    end.
+
+% All OS-es have the tcpi_state (uint8) as first member of tcp_info struct
+
+tcp_info_opt({unix, linux}) ->
+    %% include/netinet/in.h
+    %%   IPPROTO_TCP = 6
+    %%
+    %% include/netinet/tcp.h
+    %%   #define TCP_INFO 11
+    %%
+    {raw, 6, 11, 1};
+tcp_info_opt({unix, darwin}) ->
+    %% include/netinet/in.h
+    %%   #define IPPROTO_TCP   6
+    %%
+    %% netinet/tcp.h
+    %%   #define TCP_CONNECTION_INFO  0x106
+    %%
+    {raw, 6, 16#106, 1};
+tcp_info_opt({unix, freebsd}) ->
+    %% sys/netinet/in.h
+    %%  #define  IPPROTO_TCP  6 /* tcp */
+    %%
+    %% sys/netinet/tcp.h
+    %%  #define  TCP_INFO    32 /* retrieve tcp_info structure */
+    %%
+    {raw, 6, 32, 1};
+tcp_info_opt({_, _}) ->

Review Comment:
   and we owe a clause for Windows (alas)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to