git repos / sago_web_git

src/cgi.h

browsing at commit = 118f7b3050759438e47061859b2ee856af44ebfc

raw · blame · history

/*
MIT License

Copyright (c) 2026 Poul Sander

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

*/

#pragma once

#include <functional>
#include <ostream>
#include <string>
#include <utility>
#include <vector>

// Parsed CGI header block (the body is streamed separately).
struct CgiResult {
    int status = 200; // from a "Status:" header, or 200 if absent
    std::vector<std::pair<std::string, std::string>> headers;
};

// Forks and execs `argv` with exactly the environment in `env` (each entry
// "KEY=value"). The child's stdin is connected to `input_fd` (or /dev/null when
// input_fd < 0). Its stdout is parsed as a CGI response: once the header block
// up to the first blank line is parsed, `on_headers` is called with it and must
// return the stream to receive the body; the remaining bytes are then streamed
// there. Splitting it this way lets the caller set HTTP status/headers before
// any body is written. Throws std::runtime_error if the child cannot be spawned
// or exits non-zero.
void run_cgi(const std::vector<std::string> &argv,
             const std::vector<std::string> &env, int input_fd,
             const std::function<std::ostream &(const CgiResult &)> &on_headers);