[Libwebsockets] force closing http 1.1 or http2 connection from user side

andy at warmcat.com andy at warmcat.com
Tue Apr 20 21:41:47 CEST 2021



On April 20, 2021 7:21:17 PM UTC, sas spss <sas2016spss at gmail.com> wrote:
>When the server found an invalid authentication header / cookie in a
>http1.1 keep alive or http2 connectiion, the server wants to close the
>TCP
>connection right away to prevent file descriptors being used up by this
>kind of spam (fake API calls).

For h1, the transaction is directly on the tcp conn, so closing one is closing the other.

>According to the libwebsocket doc, I called lws_callback_on_writable (
>wsi
>) to trigger a writable callback. And then inside of the actual
>callback,
>under "case LWS_CALLBACK_HTTP_WRITEABLE", I return -1 for closing
>connection.

You can do that, but there is a simpler way

https://libwebsockets.org/git/libwebsockets/tree/include/libwebsockets/lws-timeout-timer.h#n116-117

Usually you want the _ASYNC version to close it next time around the event loop.

>In my test with "curl --http1.1 url1 url2 ",  the url1 request has
>invalid
>authentication header which triggers above return -1 in writable
>callback.
>But curl shows url2 still being served with debug message "re-using
>existing connection ...".

Not sure I understand that... returning -1 on writeable for h1 will close it. H1 keepalive is really fragile, everything has to have been consumed just right to be able to chain on anotjer transaction.

>So it seems the TCP connection is not closed and still being used as
>keep-alive connection. Is this the expected behavior ?

Check the verbose logs.  And use the latest version.

 If yes, what's
>the
>best way to close the connection as quickly as possible so the server
>can
>recycle the file descriptor from many of the un-authenticated requests
>?

For h1 what you're doing should work afaik.

>In another situation, like regular user login error, which server does
>want
>to send a response with http code 401 back to browser before close
>connection.  I can't close the connection right after composing the
>http
>response since there are still data (http code 401, etc) in send
>buffer. I
>tried to return -1 in writable callback under  "case
>LWS_CALLBACK_HTTP_DROP_PROTOCOL", but that doesn't seem to close the
>TCP
>connect either and still allow the next request in keep-alive
>connection
>being served.
>
>In 2nd situation, what's the best way to schedule closing the TCP
>connection after the current HTTP response being sent ?

The link earlier shows how to do it without having to close the second part yourself.

-Andy

>Thanks a lot,
>
>Joe


More information about the Libwebsockets mailing list