I want to safely read a line from an std::istream. The stream could be anything, e.g., a connection on a Web server or something processing files submitted by unknown sources. There are many answers starting to do the moral equivalent of this code:
void read(std::istream& in) {
std::string line;
if (std::getline(in, line)) {
// process the line
}
}
Given the possibly dubious source of in, using the above code would lead to a vulnerability: a malicious agent may mount a denial of service attack against this code using a huge line. Thus, I would like to limit the line length to some rather high value, say 4 millions chars. While a few large lines may be encountered, it isn't viable to allocate a buffer for each file and use std::istream::getline().
How can the maximum size of the line be limited, ideally without distorting the code too badly and without allocating large chunks of memory up front?