libwebsockets icon indicating copy to clipboard operation
libwebsockets copied to clipboard

How to write response with headers only (no body) using lws_write with LWS_WRITE_HTTP_HEADERS and LWS_WRITE_HTTP_FINAL

Open deionut opened this issue 5 years ago • 1 comments

In case of sending a http response that has no body, only headers, what is the correct way to do it?

  1. call lws_write(aHttpResponse.mLWS, start, p - start, LWS_WRITE_HTTP_HEADERS); to write just the headers (of course after populating the headers buffer with lws_add_http_header_by_name()/lws_add_http_header_by_token()/lws_finalize_http_header())
  2. call lws_callback_on_writable(aHttpResponse.mLWS); to request a new lws_write() callback to write the final (3) step
  3. call something like below just for LWS_WRITE_HTTP_FINAL: unsigned char finalBuff[LWS_PRE]; memset(finalBuff, 0, sizeof(finalBuff)); n = lws_write(aHttpResponse.mLWS, finalBuff + LWS_PRE, 0, LWS_WRITE_HTTP_FINAL);

Is this right? Is there a more direct way? Will lws_write() even consider the payload in the final step 3 if 3rd argument len is 0 (it's strange to ask to write nothing... but still do something :))) Can it not be done in one single step by having a new constant e.g. LWS_WRITE_HTTP_HEADERS_FINAL ?

Thanks.

deionut avatar Apr 09 '21 11:04 deionut

Original http/1 is not a very beautiful protocol, it's legal to not give a Content-length and just keep writing, or write nothing in the body, until you hang up.

Then with connection: keepalive, or http/1.1, it's legal to give a content-length, and pipeline more headers afterwards for a new transaction that runs off the end of the last one, measured by counting out the content-length worth of body.

In h2, it's legal to end the stream (LWS_WRITE_H2_STREAM_END) while giving the headers, this in their own distinct frametype requiring LWS_WRITE_HTTP_HEADERS.

In all these, you may indicate that the body is going through a content-encoding like Brotli. The outgoing body no longer is directly issued by the user code, the compression transform needs to know when to flush its witheld compressed data. This is why LWS_WRITE_HTTP_FINAL exists as a distinct action.

You can see, it's a bit fraught.

If there's no body, the best way is to explicitly set content-length to 0 in your headers, and send the headers with LWS_WRITE_HTTP_HEADERS | LWS_WRITE_H2_STREAM_END.

lws-team avatar Apr 09 '21 12:04 lws-team