rublon-ssh/PAM/ssh/include/rublon/utils.hpp
rublon-bwi c3127e8b58
Bwi/bugfix (#7)
* generate user enrolement message
* Fix bugs found during testing
2024-01-25 16:30:12 +01:00

197 lines
5.4 KiB
C++

#pragma once
#include "tl/expected.hpp"
#include <algorithm>
#include <array>
#include <cctype>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <map>
#include <memory>
#include <memory_resource>
#include <sstream>
#include <string_view>
#include <alloca.h>
#include <cassert>
#include <security/pam_appl.h>
#include <security/pam_modules.h>
#include <sys/stat.h>
#include <syslog.h>
#include <unistd.h>
#include <utility>
#include <rublon/memory.hpp>
namespace rublon {
inline bool fileGood(const std::filesystem::path & path) {
std::ifstream file(path);
return file.good();
}
template < typename T >
inline bool readFile(const std::filesystem::path & path, T & destination) {
if(not fileGood(path))
return false;
std::ifstream file(path);
file.seekg(0, std::ios::end);
size_t size = file.tellg();
destination.resize(size);
file.seekg(0);
file.read(&destination[0], size);
return true;
}
enum class LogLevel { Debug, Info, Warning, Error };
inline auto dateStr() {
std::array< char, 32 > date;
time_t now;
time(&now);
strftime(date.data(), date.size(), "%FT%TZ", gmtime(&now));
return date;
}
constexpr const char * LogLevelNames[]{"Debug", "Info", "Warning", "Error"};
constexpr LogLevel g_level = LogLevel::Debug;
constexpr bool syncLogFile = true;
namespace details {
constexpr const char * logPath() {
constexpr auto path = "/var/log/rublon-ssh.log";
return path;
}
inline bool logExists() noexcept {
return std::unique_ptr< FILE, int (*)(FILE *) >(fopen(logPath(), "r"), fclose).get();
}
inline void initLog() noexcept {
if(not logExists()) {
auto fp = fopen(logPath(), "w");
if(fp) {
fclose(fp);
chmod(logPath(), S_IRUSR | S_IWUSR | S_IRGRP);
}
}
}
inline void doLog(LogLevel level, const char * line) noexcept {
auto fp = std::unique_ptr< FILE, int (*)(FILE *) >(fopen(logPath(), "a+"), fclose);
if(fp) {
/// TODO add transaction ID
fprintf(fp.get(), "%s [%s] %s\n", dateStr().data(), LogLevelNames[( int ) level], line);
if(syncLogFile)
sync();
}
}
} // namespace details
inline void log(LogLevel level, const char * line) noexcept {
if(level < g_level)
return;
details::doLog(level, line);
}
template < typename... Ti >
void log(LogLevel level, const char * fmt, Ti &&... ti) noexcept {
if(level < g_level)
return;
constexpr auto maxEntryLength = 1000;
std::array< char, maxEntryLength > line;
snprintf(line.data(), maxEntryLength, fmt, std::forward< Ti >(ti)...);
details::doLog(level, line.data());
}
class PrintUser {
public:
template < typename Printer >
PrintUser(Printer & p) : _impl{std::make_unique< ModelImpl >(p)} {}
private:
struct model {
virtual ~model();
virtual void print(std::string_view line) const = 0;
};
template < typename Printer_T >
struct ModelImpl : public model {
ModelImpl(Printer_T & printer) : _printer{printer} {}
void print(std::string_view line) const override {
_printer.print(line);
}
Printer_T & _printer;
};
std::unique_ptr< model > _impl;
};
namespace conv {
inline bool to_bool(std::string_view value) {
auto * buf = ( char * ) alloca(value.size() + 1);
buf[value.size()] = '\0';
auto asciitolower = [](char in) { return in - ((in <= 'Z' && in >= 'A') ? ('Z' - 'z') : 0); };
std::transform(value.cbegin(), value.cend(), buf, asciitolower);
return strcmp(buf, "true") == 0;
}
enum class Error { OutOfRange, NotANumber };
inline tl::expected< std::uint32_t, Error > to_uint32(std::string_view userinput) noexcept {
try {
return std::stoi(userinput.data());
} catch(const std::invalid_argument & e) {
return tl::make_unexpected(Error::NotANumber);
} catch(const std::out_of_range & e) {
return tl::make_unexpected(Error::OutOfRange);
}
}
} // namespace conv
namespace details {
static inline std::string_view ltrim(std::string_view s) {
while(s.length() && std::isspace(*s.begin()))
s.remove_prefix(1);
return s;
}
static inline std::string_view rtrim(std::string_view s) {
while(s.length() && std::isspace(*s.rbegin()))
s.remove_suffix(1);
return s;
}
static inline std::string_view trim(std::string_view s) {
return ltrim(rtrim(s));
}
template < typename Headers >
inline void headers(std::string_view data, Headers & headers) {
memory::StrictMonotonic_4k_HeapResource stackResource;
std::pmr::string tmp{&stackResource};
std::istringstream resp{};
resp.rdbuf()->pubsetbuf(const_cast< char * >(data.data()), data.size());
while(std::getline(resp, tmp) && !(trim(tmp).empty())) {
auto line = std::string_view(tmp);
auto index = tmp.find(':', 0);
if(index != std::string::npos) {
headers.insert({//
typename Headers::key_type{trim(line.substr(0, index)), headers.get_allocator()},
typename Headers::mapped_type{trim(line.substr(index + 1)), headers.get_allocator()}});
}
}
}
} // namespace details
} // namespace rublon