kristapsdz / kcgi

minimal CGI and FastCGI library for C/C++
https://kristaps.bsd.lv/kcgi
ISC License
271 stars 40 forks source link

How to free `kreq` without flushing HTTP data stream? #78

Open aggsol opened 4 years ago

aggsol commented 4 years ago

Assume while writing data for a normal (e. g. HTTP 200 HTML) response one of the write fails with KCGI_ENOMEM. How can I the free the kreq without writing any HTTP data or discarding any data written previously? Because an error occurred I would now create a new empty response (e.g. HTTP 500).

kristapsdz commented 4 years ago

Good question. kcgi will flush headers as soon as they finish, so even if you have a big send buffer (in struct kopt) and simply terminate on ENOMEM, in effect not sending any data, your web server is still going to get the status code. It shouldn't be too difficult to add a struct kopt option that buffers the entire response, including the headers, which would allow you to terminate without sending any data and relying on the web server to interpret that as a 500. The modification would be in output.c, kdata_body(), where you an already see that I explain why I'm draining the buffer and whether there should be an option for it.

aggsol commented 4 years ago

I worked around it by buffering the whole response and setting up the headers and status at the very last moment and use a single write. Any error prior this will be handled as a well formed HTTP 500. If still something goes wrong then at the end I just throw an exception and let the webserver handle the terminated CGI process.