This repository has been archived on 2021-03-22. You can view files and clone it, but cannot push or open issues or pull requests.
backend/src/cgi.cpp

112 lines
2.9 KiB
C++

/* This file is part of FediBlock-backend.
* Copyright © 2020 tastytea <tastytea@tastytea.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "cgi.hpp"
#include <cgicc/Cgicc.h>
#include <exception>
#include <filesystem>
#include <fstream>
#include <ios>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
namespace FediBlock
{
using std::cerr;
using std::exception;
using std::getline;
using std::ios;
using std::ofstream;
using std::runtime_error;
using std::string;
using std::string_view;
using std::stringstream;
using std::vector;
namespace fs = std::filesystem;
entry_type parse_formdata()
{
entry_type entry;
try
{
cgicc::Cgicc cgi;
entry.instance = cgi("instance");
entry.tags = string_to_vector(cgi("tags"));
entry.receipts = string_to_vector(cgi("receipts"));
entry.description = cgi("description");
const auto screenshot = cgi.getFile("screenshot");
if (screenshot != cgi.getFiles().end())
{
constexpr size_t size_limit{1024 * 1024 * 2}; // 2 MiB.
if (screenshot->getDataLength() > size_limit)
{
throw runtime_error{"Filesize too big"};
}
string filepath{fs::temp_directory_path()
/ "fediblock-backend-XXXXXX"};
if (mkstemp(&filepath[0]) == -1) // mkstemp() modifies filepath.
{
throw runtime_error{"Could not open temporary file: "
+ filepath};
}
ofstream file{filepath, ios::binary};
if (file.good())
{
screenshot->writeToStream(file);
entry.screenshot_filepath = filepath;
}
else
{
throw runtime_error{"Could not open temporary file: "
+ filepath};
}
}
}
catch (const exception &e)
{
cerr << e.what() << '\n';
// TODO: Make errors visible to the user in a helpful way.
}
return entry;
}
vector<string> string_to_vector(const string_view str)
{
vector<string> vec;
stringstream input(str.data());
string element;
while (getline(input, element, ','))
{
vec.push_back(element);
}
return vec;
}
} // namespace FediBlock