deleted rootfs and auth_service

This commit is contained in:
wt committed 2024-12-15 01:58:36 +07:00
1 parent b694830190
commit 85652a4e99
156 files changed
-2051

No files matched your search

+66
View File
@@ -0,0 +1,66 @@
#include "OpenRouter.hpp"
#include <colors.h>
#include "../settings/settings.hpp"
#include "../system/system.hpp"
#include <syslog.h>
#include "../security/cors.hpp"
OpenRouter::OpenRouter()
{
this->srv.Post("/api/settings/telnet/get", api::settings::get_telnet);
this->srv.Post("/api/settings/telnet/set", api::settings::set_telnet);
this->srv.Post("/api/settings/telnet/port/get", api::settings::get_telnet_port);
this->srv.Post("/api/settings/telnet/port/set", api::settings::set_telnet_port);
this->srv.Post("/api/settings/ssh/status/get", api::settings::get_ssh_status);
this->srv.Post("/api/settings/ssh/status/set", api::settings::set_ssh_status);
this->srv.Post("/api/settings/ssh/keys/get", api::settings::get_ssh_keys);
this->srv.Post("/api/settings/ssh/keys/set", api::settings::set_ssh_keys);
this->srv.Post("/api/settings/ssh/port/get", api::settings::get_ssh_port);
this->srv.Post("/api/settings/ssh/port/set", api::settings::set_ssh_port);
this->srv.Post("/api/settings/dns/get", api::settings::get_dns);
this->srv.Post("/api/settings/dns/set", api::settings::set_dns);
this->srv.Post("/api/settings/dns/servers/get", api::settings::get_dns_servers);
this->srv.Post("/api/settings/dns/servers/set", api::settings::set_dns_servers);
this->srv.Post("/api/settings/dns/domains/get", api::settings::get_local_domains);
this->srv.Post("/api/settings/dns/domains/set", api::settings::set_local_domains);
this->srv.Post("/api/settings/ftp/get", api::settings::get_ftp);
this->srv.Post("/api/settings/ftp/set", api::settings::set_ftp);
this->srv.Post("/api/settings/wifi/status/get", api::settings::get_wifi_status);
this->srv.Post("/api/settings/wifi/status/set", api::settings::set_wifi_status);
this->srv.Post("/api/settings/wifi/name/get", api::settings::get_wifi_name);
this->srv.Post("/api/settings/wifi/name/set", api::settings::set_wifi_name);
this->srv.Post("/api/settings/wifi/password/get", api::settings::get_wifi_password);
this->srv.Post("/api/settings/wifi/password/set", api::settings::set_wifi_password);
this->srv.Post("/api/settings/wifi/qr/get", api::settings::get_wifi_qr);
this->srv.Post("/api/settings/wifi/channel/get", api::settings::get_wifi_channel);
this->srv.Post("/api/settings/wifi/channel/set", api::settings::set_wifi_channel);
this->srv.Post("/api/reboot", api::system::reboot);
this->srv.Get("/api/syslog", api::system::get_syslog);
#ifdef __linux__
this->srv.Get("/api/uptime", api::system::get_uptime);
#endif // __linux__
this->srv.Options("/(.*)", api::security::set_cors_headers);
this->srv.set_mount_point("/", "../src/web");
this->srv.set_mount_point("/js", "../src/web/js");
this->srv.set_mount_point("/css", "../src/web/css");
}
OpenRouter::~OpenRouter() = default;
int OpenRouter::serve(const std::string &ip, int port, int socket_flags)
{
std::cout << GREEN << "Starting" << RESET << " server on [ " << YELLOW
<< "0.0.0.0" << RESET << ":" << CYAN << "43244" << RESET << " ]" << std::endl;
syslog(LOG_INFO, "openrouter administration software started.");
this->srv.listen(ip, port, socket_flags);
return 0;
}
+20
View File
@@ -0,0 +1,20 @@
#ifndef OPENROUTER_HPP
#define OPENROUTER_HPP
#include <iostream>
#include <httplib.h>
#define CORS_ENABLE
class OpenRouter
{
private:
httplib::Server srv;
public:
OpenRouter();
~OpenRouter();
int serve(const std::string &ip, int port, int socket_flags = 0);
};
#endif // OPENROUTER_HPP
+25
View File
@@ -0,0 +1,25 @@
#include "auth.hpp"
#include <sstream>
#include <httplib.h>
#include "../routes.hpp"
#include <json.hpp>
#include "../types.hpp"
bool authenticate(const std::string &token)
{
httplib::Client cli(AUTH_SERVICE);
std::stringstream body;
body << R"({"token":")" << token << R"("})";
httplib::Result res = cli.Post("/api/access", body.str(), JSON_TYPE);
if (res->status == httplib::OK_200)
{
nlohmann::json resjson = nlohmann::json::parse(res->body);
if (resjson["access"] == "reject")
{
return false;
}
return true;
}
return false;
}
+8
View File
@@ -0,0 +1,8 @@
#ifndef AUTH_HPP
#define AUTH_HPP
#include <iostream>
bool authenticate(const std::string &token);
#endif // AUTH_HPP
+17
View File
@@ -0,0 +1,17 @@
#ifndef HELPERS_HPP
#define HELPERS_HPP
#include <httplib.h>
#include <json.hpp>
static bool check_body(const httplib::Request &request)
{
if (request.body.empty())
return false;
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (json_body["token"] == nullptr)
return false;
return true;
}
#endif // HELPERS_HPP
+830
View File
@@ -0,0 +1,830 @@
/*
* QR Code generator library (C++)
*
* Copyright (c) Project Nayuki. (MIT License)
* https://www.nayuki.io/page/qr-code-generator-library
*
* 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.
*/
#include <algorithm>
#include <cassert>
#include <climits>
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <utility>
#include "qrcodegen.hpp"
using std::int8_t;
using std::uint8_t;
using std::size_t;
using std::vector;
namespace qrcodegen {
/*---- Class QrSegment ----*/
QrSegment::Mode::Mode(int mode, int cc0, int cc1, int cc2) :
modeBits(mode) {
numBitsCharCount[0] = cc0;
numBitsCharCount[1] = cc1;
numBitsCharCount[2] = cc2;
}
int QrSegment::Mode::getModeBits() const {
return modeBits;
}
int QrSegment::Mode::numCharCountBits(int ver) const {
return numBitsCharCount[(ver + 7) / 17];
}
const QrSegment::Mode QrSegment::Mode::NUMERIC (0x1, 10, 12, 14);
const QrSegment::Mode QrSegment::Mode::ALPHANUMERIC(0x2, 9, 11, 13);
const QrSegment::Mode QrSegment::Mode::BYTE (0x4, 8, 16, 16);
const QrSegment::Mode QrSegment::Mode::KANJI (0x8, 8, 10, 12);
const QrSegment::Mode QrSegment::Mode::ECI (0x7, 0, 0, 0);
QrSegment QrSegment::makeBytes(const vector<uint8_t> &data) {
if (data.size() > static_cast<unsigned int>(INT_MAX))
throw std::length_error("Data too long");
BitBuffer bb;
for (uint8_t b : data)
bb.appendBits(b, 8);
return QrSegment(Mode::BYTE, static_cast<int>(data.size()), std::move(bb));
}
QrSegment QrSegment::makeNumeric(const char *digits) {
BitBuffer bb;
int accumData = 0;
int accumCount = 0;
int charCount = 0;
for (; *digits != '\0'; digits++, charCount++) {
char c = *digits;
if (c < '0' || c > '9')
throw std::domain_error("String contains non-numeric characters");
accumData = accumData * 10 + (c - '0');
accumCount++;
if (accumCount == 3) {
bb.appendBits(static_cast<uint32_t>(accumData), 10);
accumData = 0;
accumCount = 0;
}
}
if (accumCount > 0) // 1 or 2 digits remaining
bb.appendBits(static_cast<uint32_t>(accumData), accumCount * 3 + 1);
return QrSegment(Mode::NUMERIC, charCount, std::move(bb));
}
QrSegment QrSegment::makeAlphanumeric(const char *text) {
BitBuffer bb;
int accumData = 0;
int accumCount = 0;
int charCount = 0;
for (; *text != '\0'; text++, charCount++) {
const char *temp = std::strchr(ALPHANUMERIC_CHARSET, *text);
if (temp == nullptr)
throw std::domain_error("String contains unencodable characters in alphanumeric mode");
accumData = accumData * 45 + static_cast<int>(temp - ALPHANUMERIC_CHARSET);
accumCount++;
if (accumCount == 2) {
bb.appendBits(static_cast<uint32_t>(accumData), 11);
accumData = 0;
accumCount = 0;
}
}
if (accumCount > 0) // 1 character remaining
bb.appendBits(static_cast<uint32_t>(accumData), 6);
return QrSegment(Mode::ALPHANUMERIC, charCount, std::move(bb));
}
vector<QrSegment> QrSegment::makeSegments(const char *text) {
// Select the most efficient segment encoding automatically
vector<QrSegment> result;
if (*text == '\0'); // Leave result empty
else if (isNumeric(text))
result.push_back(makeNumeric(text));
else if (isAlphanumeric(text))
result.push_back(makeAlphanumeric(text));
else {
vector<uint8_t> bytes;
for (; *text != '\0'; text++)
bytes.push_back(static_cast<uint8_t>(*text));
result.push_back(makeBytes(bytes));
}
return result;
}
QrSegment QrSegment::makeEci(long assignVal) {
BitBuffer bb;
if (assignVal < 0)
throw std::domain_error("ECI assignment value out of range");
else if (assignVal < (1 << 7))
bb.appendBits(static_cast<uint32_t>(assignVal), 8);
else if (assignVal < (1 << 14)) {
bb.appendBits(2, 2);
bb.appendBits(static_cast<uint32_t>(assignVal), 14);
} else if (assignVal < 1000000L) {
bb.appendBits(6, 3);
bb.appendBits(static_cast<uint32_t>(assignVal), 21);
} else
throw std::domain_error("ECI assignment value out of range");
return QrSegment(Mode::ECI, 0, std::move(bb));
}
QrSegment::QrSegment(const Mode &md, int numCh, const std::vector<bool> &dt) :
mode(&md),
numChars(numCh),
data(dt) {
if (numCh < 0)
throw std::domain_error("Invalid value");
}
QrSegment::QrSegment(const Mode &md, int numCh, std::vector<bool> &&dt) :
mode(&md),
numChars(numCh),
data(std::move(dt)) {
if (numCh < 0)
throw std::domain_error("Invalid value");
}
int QrSegment::getTotalBits(const vector<QrSegment> &segs, int version) {
int result = 0;
for (const QrSegment &seg : segs) {
int ccbits = seg.mode->numCharCountBits(version);
if (seg.numChars >= (1L << ccbits))
return -1; // The segment's length doesn't fit the field's bit width
if (4 + ccbits > INT_MAX - result)
return -1; // The sum will overflow an int type
result += 4 + ccbits;
if (seg.data.size() > static_cast<unsigned int>(INT_MAX - result))
return -1; // The sum will overflow an int type
result += static_cast<int>(seg.data.size());
}
return result;
}
bool QrSegment::isNumeric(const char *text) {
for (; *text != '\0'; text++) {
char c = *text;
if (c < '0' || c > '9')
return false;
}
return true;
}
bool QrSegment::isAlphanumeric(const char *text) {
for (; *text != '\0'; text++) {
if (std::strchr(ALPHANUMERIC_CHARSET, *text) == nullptr)
return false;
}
return true;
}
const QrSegment::Mode &QrSegment::getMode() const {
return *mode;
}
int QrSegment::getNumChars() const {
return numChars;
}
const std::vector<bool> &QrSegment::getData() const {
return data;
}
const char *QrSegment::ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
/*---- Class QrCode ----*/
int QrCode::getFormatBits(Ecc ecl) {
switch (ecl) {
case Ecc::LOW : return 1;
case Ecc::MEDIUM : return 0;
case Ecc::QUARTILE: return 3;
case Ecc::HIGH : return 2;
default: throw std::logic_error("Unreachable");
}
}
QrCode QrCode::encodeText(const char *text, Ecc ecl) {
vector<QrSegment> segs = QrSegment::makeSegments(text);
return encodeSegments(segs, ecl);
}
QrCode QrCode::encodeBinary(const vector<uint8_t> &data, Ecc ecl) {
vector<QrSegment> segs{QrSegment::makeBytes(data)};
return encodeSegments(segs, ecl);
}
QrCode QrCode::encodeSegments(const vector<QrSegment> &segs, Ecc ecl,
int minVersion, int maxVersion, int mask, bool boostEcl) {
if (!(MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= MAX_VERSION) || mask < -1 || mask > 7)
throw std::invalid_argument("Invalid value");
// Find the minimal version number to use
int version, dataUsedBits;
for (version = minVersion; ; version++) {
int dataCapacityBits = getNumDataCodewords(version, ecl) * 8; // Number of data bits available
dataUsedBits = QrSegment::getTotalBits(segs, version);
if (dataUsedBits != -1 && dataUsedBits <= dataCapacityBits)
break; // This version number is found to be suitable
if (version >= maxVersion) { // All versions in the range could not fit the given data
std::ostringstream sb;
if (dataUsedBits == -1)
sb << "Segment too long";
else {
sb << "Data length = " << dataUsedBits << " bits, ";
sb << "Max capacity = " << dataCapacityBits << " bits";
}
throw data_too_long(sb.str());
}
}
assert(dataUsedBits != -1);
// Increase the error correction level while the data still fits in the current version number
for (Ecc newEcl : {Ecc::MEDIUM, Ecc::QUARTILE, Ecc::HIGH}) { // From low to high
if (boostEcl && dataUsedBits <= getNumDataCodewords(version, newEcl) * 8)
ecl = newEcl;
}
// Concatenate all segments to create the data bit string
BitBuffer bb;
for (const QrSegment &seg : segs) {
bb.appendBits(static_cast<uint32_t>(seg.getMode().getModeBits()), 4);
bb.appendBits(static_cast<uint32_t>(seg.getNumChars()), seg.getMode().numCharCountBits(version));
bb.insert(bb.end(), seg.getData().begin(), seg.getData().end());
}
assert(bb.size() == static_cast<unsigned int>(dataUsedBits));
// Add terminator and pad up to a byte if applicable
size_t dataCapacityBits = static_cast<size_t>(getNumDataCodewords(version, ecl)) * 8;
assert(bb.size() <= dataCapacityBits);
bb.appendBits(0, std::min(4, static_cast<int>(dataCapacityBits - bb.size())));
bb.appendBits(0, (8 - static_cast<int>(bb.size() % 8)) % 8);
assert(bb.size() % 8 == 0);
// Pad with alternating bytes until data capacity is reached
for (uint8_t padByte = 0xEC; bb.size() < dataCapacityBits; padByte ^= 0xEC ^ 0x11)
bb.appendBits(padByte, 8);
// Pack bits into bytes in big endian
vector<uint8_t> dataCodewords(bb.size() / 8);
for (size_t i = 0; i < bb.size(); i++)
dataCodewords.at(i >> 3) |= (bb.at(i) ? 1 : 0) << (7 - (i & 7));
// Create the QR Code object
return QrCode(version, ecl, dataCodewords, mask);
}
QrCode::QrCode(int ver, Ecc ecl, const vector<uint8_t> &dataCodewords, int msk) :
// Initialize fields and check arguments
version(ver),
errorCorrectionLevel(ecl) {
if (ver < MIN_VERSION || ver > MAX_VERSION)
throw std::domain_error("Version value out of range");
if (msk < -1 || msk > 7)
throw std::domain_error("Mask value out of range");
size = ver * 4 + 17;
size_t sz = static_cast<size_t>(size);
modules = vector<vector<bool> >(sz, vector<bool>(sz)); // Initially all light
isFunction = vector<vector<bool> >(sz, vector<bool>(sz));
// Compute ECC, draw modules
drawFunctionPatterns();
const vector<uint8_t> allCodewords = addEccAndInterleave(dataCodewords);
drawCodewords(allCodewords);
// Do masking
if (msk == -1) { // Automatically choose best mask
long minPenalty = LONG_MAX;
for (int i = 0; i < 8; i++) {
applyMask(i);
drawFormatBits(i);
long penalty = getPenaltyScore();
if (penalty < minPenalty) {
msk = i;
minPenalty = penalty;
}
applyMask(i); // Undoes the mask due to XOR
}
}
assert(0 <= msk && msk <= 7);
mask = msk;
applyMask(msk); // Apply the final choice of mask
drawFormatBits(msk); // Overwrite old format bits
isFunction.clear();
isFunction.shrink_to_fit();
}
int QrCode::getVersion() const {
return version;
}
int QrCode::getSize() const {
return size;
}
QrCode::Ecc QrCode::getErrorCorrectionLevel() const {
return errorCorrectionLevel;
}
int QrCode::getMask() const {
return mask;
}
bool QrCode::getModule(int x, int y) const {
return 0 <= x && x < size && 0 <= y && y < size && module(x, y);
}
void QrCode::drawFunctionPatterns() {
// Draw horizontal and vertical timing patterns
for (int i = 0; i < size; i++) {
setFunctionModule(6, i, i % 2 == 0);
setFunctionModule(i, 6, i % 2 == 0);
}
// Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
drawFinderPattern(3, 3);
drawFinderPattern(size - 4, 3);
drawFinderPattern(3, size - 4);
// Draw numerous alignment patterns
const vector<int> alignPatPos = getAlignmentPatternPositions();
size_t numAlign = alignPatPos.size();
for (size_t i = 0; i < numAlign; i++) {
for (size_t j = 0; j < numAlign; j++) {
// Don't draw on the three finder corners
if (!((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0)))
drawAlignmentPattern(alignPatPos.at(i), alignPatPos.at(j));
}
}
// Draw configuration data
drawFormatBits(0); // Dummy mask value; overwritten later in the constructor
drawVersion();
}
void QrCode::drawFormatBits(int msk) {
// Calculate error correction code and pack bits
int data = getFormatBits(errorCorrectionLevel) << 3 | msk; // errCorrLvl is uint2, msk is uint3
int rem = data;
for (int i = 0; i < 10; i++)
rem = (rem << 1) ^ ((rem >> 9) * 0x537);
int bits = (data << 10 | rem) ^ 0x5412; // uint15
assert(bits >> 15 == 0);
// Draw first copy
for (int i = 0; i <= 5; i++)
setFunctionModule(8, i, getBit(bits, i));
setFunctionModule(8, 7, getBit(bits, 6));
setFunctionModule(8, 8, getBit(bits, 7));
setFunctionModule(7, 8, getBit(bits, 8));
for (int i = 9; i < 15; i++)
setFunctionModule(14 - i, 8, getBit(bits, i));
// Draw second copy
for (int i = 0; i < 8; i++)
setFunctionModule(size - 1 - i, 8, getBit(bits, i));
for (int i = 8; i < 15; i++)
setFunctionModule(8, size - 15 + i, getBit(bits, i));
setFunctionModule(8, size - 8, true); // Always dark
}
void QrCode::drawVersion() {
if (version < 7)
return;
// Calculate error correction code and pack bits
int rem = version; // version is uint6, in the range [7, 40]
for (int i = 0; i < 12; i++)
rem = (rem << 1) ^ ((rem >> 11) * 0x1F25);
long bits = static_cast<long>(version) << 12 | rem; // uint18
assert(bits >> 18 == 0);
// Draw two copies
for (int i = 0; i < 18; i++) {
bool bit = getBit(bits, i);
int a = size - 11 + i % 3;
int b = i / 3;
setFunctionModule(a, b, bit);
setFunctionModule(b, a, bit);
}
}
void QrCode::drawFinderPattern(int x, int y) {
for (int dy = -4; dy <= 4; dy++) {
for (int dx = -4; dx <= 4; dx++) {
int dist = std::max(std::abs(dx), std::abs(dy)); // Chebyshev/infinity norm
int xx = x + dx, yy = y + dy;
if (0 <= xx && xx < size && 0 <= yy && yy < size)
setFunctionModule(xx, yy, dist != 2 && dist != 4);
}
}
}
void QrCode::drawAlignmentPattern(int x, int y) {
for (int dy = -2; dy <= 2; dy++) {
for (int dx = -2; dx <= 2; dx++)
setFunctionModule(x + dx, y + dy, std::max(std::abs(dx), std::abs(dy)) != 1);
}
}
void QrCode::setFunctionModule(int x, int y, bool isDark) {
size_t ux = static_cast<size_t>(x);
size_t uy = static_cast<size_t>(y);
modules .at(uy).at(ux) = isDark;
isFunction.at(uy).at(ux) = true;
}
bool QrCode::module(int x, int y) const {
return modules.at(static_cast<size_t>(y)).at(static_cast<size_t>(x));
}
vector<uint8_t> QrCode::addEccAndInterleave(const vector<uint8_t> &data) const {
if (data.size() != static_cast<unsigned int>(getNumDataCodewords(version, errorCorrectionLevel)))
throw std::invalid_argument("Invalid argument");
// Calculate parameter numbers
int numBlocks = NUM_ERROR_CORRECTION_BLOCKS[static_cast<int>(errorCorrectionLevel)][version];
int blockEccLen = ECC_CODEWORDS_PER_BLOCK [static_cast<int>(errorCorrectionLevel)][version];
int rawCodewords = getNumRawDataModules(version) / 8;
int numShortBlocks = numBlocks - rawCodewords % numBlocks;
int shortBlockLen = rawCodewords / numBlocks;
// Split data into blocks and append ECC to each block
vector<vector<uint8_t> > blocks;
const vector<uint8_t> rsDiv = reedSolomonComputeDivisor(blockEccLen);
for (int i = 0, k = 0; i < numBlocks; i++) {
vector<uint8_t> dat(data.cbegin() + k, data.cbegin() + (k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1)));
k += static_cast<int>(dat.size());
const vector<uint8_t> ecc = reedSolomonComputeRemainder(dat, rsDiv);
if (i < numShortBlocks)
dat.push_back(0);
dat.insert(dat.end(), ecc.cbegin(), ecc.cend());
blocks.push_back(std::move(dat));
}
// Interleave (not concatenate) the bytes from every block into a single sequence
vector<uint8_t> result;
for (size_t i = 0; i < blocks.at(0).size(); i++) {
for (size_t j = 0; j < blocks.size(); j++) {
// Skip the padding byte in short blocks
if (i != static_cast<unsigned int>(shortBlockLen - blockEccLen) || j >= static_cast<unsigned int>(numShortBlocks))
result.push_back(blocks.at(j).at(i));
}
}
assert(result.size() == static_cast<unsigned int>(rawCodewords));
return result;
}
void QrCode::drawCodewords(const vector<uint8_t> &data) {
if (data.size() != static_cast<unsigned int>(getNumRawDataModules(version) / 8))
throw std::invalid_argument("Invalid argument");
size_t i = 0; // Bit index into the data
// Do the funny zigzag scan
for (int right = size - 1; right >= 1; right -= 2) { // Index of right column in each column pair
if (right == 6)
right = 5;
for (int vert = 0; vert < size; vert++) { // Vertical counter
for (int j = 0; j < 2; j++) {
size_t x = static_cast<size_t>(right - j); // Actual x coordinate
bool upward = ((right + 1) & 2) == 0;
size_t y = static_cast<size_t>(upward ? size - 1 - vert : vert); // Actual y coordinate
if (!isFunction.at(y).at(x) && i < data.size() * 8) {
modules.at(y).at(x) = getBit(data.at(i >> 3), 7 - static_cast<int>(i & 7));
i++;
}
// If this QR Code has any remainder bits (0 to 7), they were assigned as
// 0/false/light by the constructor and are left unchanged by this method
}
}
}
assert(i == data.size() * 8);
}
void QrCode::applyMask(int msk) {
if (msk < 0 || msk > 7)
throw std::domain_error("Mask value out of range");
size_t sz = static_cast<size_t>(size);
for (size_t y = 0; y < sz; y++) {
for (size_t x = 0; x < sz; x++) {
bool invert;
switch (msk) {
case 0: invert = (x + y) % 2 == 0; break;
case 1: invert = y % 2 == 0; break;
case 2: invert = x % 3 == 0; break;
case 3: invert = (x + y) % 3 == 0; break;
case 4: invert = (x / 3 + y / 2) % 2 == 0; break;
case 5: invert = x * y % 2 + x * y % 3 == 0; break;
case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break;
case 7: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break;
default: throw std::logic_error("Unreachable");
}
modules.at(y).at(x) = modules.at(y).at(x) ^ (invert & !isFunction.at(y).at(x));
}
}
}
long QrCode::getPenaltyScore() const {
long result = 0;
// Adjacent modules in row having same color, and finder-like patterns
for (int y = 0; y < size; y++) {
bool runColor = false;
int runX = 0;
std::array<int,7> runHistory = {};
for (int x = 0; x < size; x++) {
if (module(x, y) == runColor) {
runX++;
if (runX == 5)
result += PENALTY_N1;
else if (runX > 5)
result++;
} else {
finderPenaltyAddHistory(runX, runHistory);
if (!runColor)
result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3;
runColor = module(x, y);
runX = 1;
}
}
result += finderPenaltyTerminateAndCount(runColor, runX, runHistory) * PENALTY_N3;
}
// Adjacent modules in column having same color, and finder-like patterns
for (int x = 0; x < size; x++) {
bool runColor = false;
int runY = 0;
std::array<int,7> runHistory = {};
for (int y = 0; y < size; y++) {
if (module(x, y) == runColor) {
runY++;
if (runY == 5)
result += PENALTY_N1;
else if (runY > 5)
result++;
} else {
finderPenaltyAddHistory(runY, runHistory);
if (!runColor)
result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3;
runColor = module(x, y);
runY = 1;
}
}
result += finderPenaltyTerminateAndCount(runColor, runY, runHistory) * PENALTY_N3;
}
// 2*2 blocks of modules having same color
for (int y = 0; y < size - 1; y++) {
for (int x = 0; x < size - 1; x++) {
bool color = module(x, y);
if ( color == module(x + 1, y) &&
color == module(x, y + 1) &&
color == module(x + 1, y + 1))
result += PENALTY_N2;
}
}
// Balance of dark and light modules
int dark = 0;
for (const vector<bool> &row : modules) {
for (bool color : row) {
if (color)
dark++;
}
}
int total = size * size; // Note that size is odd, so dark/total != 1/2
// Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)%
int k = static_cast<int>((std::abs(dark * 20L - total * 10L) + total - 1) / total) - 1;
assert(0 <= k && k <= 9);
result += k * PENALTY_N4;
assert(0 <= result && result <= 2568888L); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4
return result;
}
vector<int> QrCode::getAlignmentPatternPositions() const {
if (version == 1)
return vector<int>();
else {
int numAlign = version / 7 + 2;
int step = (version == 32) ? 26 :
(version * 4 + numAlign * 2 + 1) / (numAlign * 2 - 2) * 2;
vector<int> result;
for (int i = 0, pos = size - 7; i < numAlign - 1; i++, pos -= step)
result.insert(result.begin(), pos);
result.insert(result.begin(), 6);
return result;
}
}
int QrCode::getNumRawDataModules(int ver) {
if (ver < MIN_VERSION || ver > MAX_VERSION)
throw std::domain_error("Version number out of range");
int result = (16 * ver + 128) * ver + 64;
if (ver >= 2) {
int numAlign = ver / 7 + 2;
result -= (25 * numAlign - 10) * numAlign - 55;
if (ver >= 7)
result -= 36;
}
assert(208 <= result && result <= 29648);
return result;
}
int QrCode::getNumDataCodewords(int ver, Ecc ecl) {
return getNumRawDataModules(ver) / 8
- ECC_CODEWORDS_PER_BLOCK [static_cast<int>(ecl)][ver]
* NUM_ERROR_CORRECTION_BLOCKS[static_cast<int>(ecl)][ver];
}
vector<uint8_t> QrCode::reedSolomonComputeDivisor(int degree) {
if (degree < 1 || degree > 255)
throw std::domain_error("Degree out of range");
// Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.
// For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array {255, 8, 93}.
vector<uint8_t> result(static_cast<size_t>(degree));
result.at(result.size() - 1) = 1; // Start off with the monomial x^0
// Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
// and drop the highest monomial term which is always 1x^degree.
// Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
uint8_t root = 1;
for (int i = 0; i < degree; i++) {
// Multiply the current product by (x - r^i)
for (size_t j = 0; j < result.size(); j++) {
result.at(j) = reedSolomonMultiply(result.at(j), root);
if (j + 1 < result.size())
result.at(j) ^= result.at(j + 1);
}
root = reedSolomonMultiply(root, 0x02);
}
return result;
}
vector<uint8_t> QrCode::reedSolomonComputeRemainder(const vector<uint8_t> &data, const vector<uint8_t> &divisor) {
vector<uint8_t> result(divisor.size());
for (uint8_t b : data) { // Polynomial division
uint8_t factor = b ^ result.at(0);
result.erase(result.begin());
result.push_back(0);
for (size_t i = 0; i < result.size(); i++)
result.at(i) ^= reedSolomonMultiply(divisor.at(i), factor);
}
return result;
}
uint8_t QrCode::reedSolomonMultiply(uint8_t x, uint8_t y) {
// Russian peasant multiplication
int z = 0;
for (int i = 7; i >= 0; i--) {
z = (z << 1) ^ ((z >> 7) * 0x11D);
z ^= ((y >> i) & 1) * x;
}
assert(z >> 8 == 0);
return static_cast<uint8_t>(z);
}
int QrCode::finderPenaltyCountPatterns(const std::array<int,7> &runHistory) const {
int n = runHistory.at(1);
assert(n <= size * 3);
bool core = n > 0 && runHistory.at(2) == n && runHistory.at(3) == n * 3 && runHistory.at(4) == n && runHistory.at(5) == n;
return (core && runHistory.at(0) >= n * 4 && runHistory.at(6) >= n ? 1 : 0)
+ (core && runHistory.at(6) >= n * 4 && runHistory.at(0) >= n ? 1 : 0);
}
int QrCode::finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, std::array<int,7> &runHistory) const {
if (currentRunColor) { // Terminate dark run
finderPenaltyAddHistory(currentRunLength, runHistory);
currentRunLength = 0;
}
currentRunLength += size; // Add light border to final run
finderPenaltyAddHistory(currentRunLength, runHistory);
return finderPenaltyCountPatterns(runHistory);
}
void QrCode::finderPenaltyAddHistory(int currentRunLength, std::array<int,7> &runHistory) const {
if (runHistory.at(0) == 0)
currentRunLength += size; // Add light border to initial run
std::copy_backward(runHistory.cbegin(), runHistory.cend() - 1, runHistory.end());
runHistory.at(0) = currentRunLength;
}
bool QrCode::getBit(long x, int i) {
return ((x >> i) & 1) != 0;
}
/*---- Tables of constants ----*/
const int QrCode::PENALTY_N1 = 3;
const int QrCode::PENALTY_N2 = 3;
const int QrCode::PENALTY_N3 = 40;
const int QrCode::PENALTY_N4 = 10;
const int8_t QrCode::ECC_CODEWORDS_PER_BLOCK[4][41] = {
// Version: (note that index 0 is for padding, and is set to an illegal value)
//0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
{-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Low
{-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28}, // Medium
{-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Quartile
{-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // High
};
const int8_t QrCode::NUM_ERROR_CORRECTION_BLOCKS[4][41] = {
// Version: (note that index 0 is for padding, and is set to an illegal value)
//0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
{-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25}, // Low
{-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49}, // Medium
{-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68}, // Quartile
{-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81}, // High
};
data_too_long::data_too_long(const std::string &msg) :
std::length_error(msg) {}
/*---- Class BitBuffer ----*/
BitBuffer::BitBuffer()
: std::vector<bool>() {}
void BitBuffer::appendBits(std::uint32_t val, int len) {
if (len < 0 || len > 31 || val >> len != 0)
throw std::domain_error("Value out of range");
for (int i = len - 1; i >= 0; i--) // Append bit by bit
this->push_back(((val >> i) & 1) != 0);
}
}
+549
View File
@@ -0,0 +1,549 @@
/*
* QR Code generator library (C++)
*
* Copyright (c) Project Nayuki. (MIT License)
* https://www.nayuki.io/page/qr-code-generator-library
*
* 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 <array>
#include <cstdint>
#include <stdexcept>
#include <string>
#include <vector>
namespace qrcodegen {
/*
* A segment of character/binary/control data in a QR Code symbol.
* Instances of this class are immutable.
* The mid-level way to create a segment is to take the payload data
* and call a static factory function such as QrSegment::makeNumeric().
* The low-level way to create a segment is to custom-make the bit buffer
* and call the QrSegment() constructor with appropriate values.
* This segment class imposes no length restrictions, but QR Codes have restrictions.
* Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.
* Any segment longer than this is meaningless for the purpose of generating QR Codes.
*/
class QrSegment final {
/*---- Public helper enumeration ----*/
/*
* Describes how a segment's data bits are interpreted. Immutable.
*/
public: class Mode final {
/*-- Constants --*/
public: static const Mode NUMERIC;
public: static const Mode ALPHANUMERIC;
public: static const Mode BYTE;
public: static const Mode KANJI;
public: static const Mode ECI;
/*-- Fields --*/
// The mode indicator bits, which is a uint4 value (range 0 to 15).
private: int modeBits;
// Number of character count bits for three different version ranges.
private: int numBitsCharCount[3];
/*-- Constructor --*/
private: Mode(int mode, int cc0, int cc1, int cc2);
/*-- Methods --*/
/*
* (Package-private) Returns the mode indicator bits, which is an unsigned 4-bit value (range 0 to 15).
*/
public: int getModeBits() const;
/*
* (Package-private) Returns the bit width of the character count field for a segment in
* this mode in a QR Code at the given version number. The result is in the range [0, 16].
*/
public: int numCharCountBits(int ver) const;
};
/*---- Static factory functions (mid level) ----*/
/*
* Returns a segment representing the given binary data encoded in
* byte mode. All input byte vectors are acceptable. Any text string
* can be converted to UTF-8 bytes and encoded as a byte mode segment.
*/
public: static QrSegment makeBytes(const std::vector<std::uint8_t> &data);
/*
* Returns a segment representing the given string of decimal digits encoded in numeric mode.
*/
public: static QrSegment makeNumeric(const char *digits);
/*
* Returns a segment representing the given text string encoded in alphanumeric mode.
* The characters allowed are: 0 to 9, A to Z (uppercase only), space,
* dollar, percent, asterisk, plus, hyphen, period, slash, colon.
*/
public: static QrSegment makeAlphanumeric(const char *text);
/*
* Returns a list of zero or more segments to represent the given text string. The result
* may use various segment modes and switch modes to optimize the length of the bit stream.
*/
public: static std::vector<QrSegment> makeSegments(const char *text);
/*
* Returns a segment representing an Extended Channel Interpretation
* (ECI) designator with the given assignment value.
*/
public: static QrSegment makeEci(long assignVal);
/*---- Public static helper functions ----*/
/*
* Tests whether the given string can be encoded as a segment in numeric mode.
* A string is encodable iff each character is in the range 0 to 9.
*/
public: static bool isNumeric(const char *text);
/*
* Tests whether the given string can be encoded as a segment in alphanumeric mode.
* A string is encodable iff each character is in the following set: 0 to 9, A to Z
* (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.
*/
public: static bool isAlphanumeric(const char *text);
/*---- Instance fields ----*/
/* The mode indicator of this segment. Accessed through getMode(). */
private: const Mode *mode;
/* The length of this segment's unencoded data. Measured in characters for
* numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.
* Always zero or positive. Not the same as the data's bit length.
* Accessed through getNumChars(). */
private: int numChars;
/* The data bits of this segment. Accessed through getData(). */
private: std::vector<bool> data;
/*---- Constructors (low level) ----*/
/*
* Creates a new QR Code segment with the given attributes and data.
* The character count (numCh) must agree with the mode and the bit buffer length,
* but the constraint isn't checked. The given bit buffer is copied and stored.
*/
public: QrSegment(const Mode &md, int numCh, const std::vector<bool> &dt);
/*
* Creates a new QR Code segment with the given parameters and data.
* The character count (numCh) must agree with the mode and the bit buffer length,
* but the constraint isn't checked. The given bit buffer is moved and stored.
*/
public: QrSegment(const Mode &md, int numCh, std::vector<bool> &&dt);
/*---- Methods ----*/
/*
* Returns the mode field of this segment.
*/
public: const Mode &getMode() const;
/*
* Returns the character count field of this segment.
*/
public: int getNumChars() const;
/*
* Returns the data bits of this segment.
*/
public: const std::vector<bool> &getData() const;
// (Package-private) Calculates the number of bits needed to encode the given segments at
// the given version. Returns a non-negative number if successful. Otherwise returns -1 if a
// segment has too many characters to fit its length field, or the total bits exceeds INT_MAX.
public: static int getTotalBits(const std::vector<QrSegment> &segs, int version);
/*---- Private constant ----*/
/* The set of all legal characters in alphanumeric mode, where
* each character value maps to the index in the string. */
private: static const char *ALPHANUMERIC_CHARSET;
};
/*
* A QR Code symbol, which is a type of two-dimension barcode.
* Invented by Denso Wave and described in the ISO/IEC 18004 standard.
* Instances of this class represent an immutable square grid of dark and light cells.
* The class provides static factory functions to create a QR Code from text or binary data.
* The class covers the QR Code Model 2 specification, supporting all versions (sizes)
* from 1 to 40, all 4 error correction levels, and 4 character encoding modes.
*
* Ways to create a QR Code object:
* - High level: Take the payload data and call QrCode::encodeText() or QrCode::encodeBinary().
* - Mid level: Custom-make the list of segments and call QrCode::encodeSegments().
* - Low level: Custom-make the array of data codeword bytes (including
* segment headers and final padding, excluding error correction codewords),
* supply the appropriate version number, and call the QrCode() constructor.
* (Note that all ways require supplying the desired error correction level.)
*/
class QrCode final {
/*---- Public helper enumeration ----*/
/*
* The error correction level in a QR Code symbol.
*/
public: enum class Ecc {
LOW = 0 , // The QR Code can tolerate about 7% erroneous codewords
MEDIUM , // The QR Code can tolerate about 15% erroneous codewords
QUARTILE, // The QR Code can tolerate about 25% erroneous codewords
HIGH , // The QR Code can tolerate about 30% erroneous codewords
};
// Returns a value in the range 0 to 3 (unsigned 2-bit integer).
private: static int getFormatBits(Ecc ecl);
/*---- Static factory functions (high level) ----*/
/*
* Returns a QR Code representing the given Unicode text string at the given error correction level.
* As a conservative upper bound, this function is guaranteed to succeed for strings that have 2953 or fewer
* UTF-8 code units (not Unicode code points) if the low error correction level is used. The smallest possible
* QR Code version is automatically chosen for the output. The ECC level of the result may be higher than
* the ecl argument if it can be done without increasing the version.
*/
public: static QrCode encodeText(const char *text, Ecc ecl);
/*
* Returns a QR Code representing the given binary data at the given error correction level.
* This function always encodes using the binary segment mode, not any text mode. The maximum number of
* bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.
* The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.
*/
public: static QrCode encodeBinary(const std::vector<std::uint8_t> &data, Ecc ecl);
/*---- Static factory functions (mid level) ----*/
/*
* Returns a QR Code representing the given segments with the given encoding parameters.
* The smallest possible QR Code version within the given range is automatically
* chosen for the output. Iff boostEcl is true, then the ECC level of the result
* may be higher than the ecl argument if it can be done without increasing the
* version. The mask number is either between 0 to 7 (inclusive) to force that
* mask, or -1 to automatically choose an appropriate mask (which may be slow).
* This function allows the user to create a custom sequence of segments that switches
* between modes (such as alphanumeric and byte) to encode text in less space.
* This is a mid-level API; the high-level API is encodeText() and encodeBinary().
*/
public: static QrCode encodeSegments(const std::vector<QrSegment> &segs, Ecc ecl,
int minVersion=1, int maxVersion=40, int mask=-1, bool boostEcl=true); // All optional parameters
/*---- Instance fields ----*/
// Immutable scalar parameters:
/* The version number of this QR Code, which is between 1 and 40 (inclusive).
* This determines the size of this barcode. */
private: int version;
/* The width and height of this QR Code, measured in modules, between
* 21 and 177 (inclusive). This is equal to version * 4 + 17. */
private: int size;
/* The error correction level used in this QR Code. */
private: Ecc errorCorrectionLevel;
/* The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive).
* Even if a QR Code is created with automatic masking requested (mask = -1),
* the resulting object still has a mask value between 0 and 7. */
private: int mask;
// Private grids of modules/pixels, with dimensions of size*size:
// The modules of this QR Code (false = light, true = dark).
// Immutable after constructor finishes. Accessed through getModule().
private: std::vector<std::vector<bool> > modules;
// Indicates function modules that are not subjected to masking. Discarded when constructor finishes.
private: std::vector<std::vector<bool> > isFunction;
/*---- Constructor (low level) ----*/
/*
* Creates a new QR Code with the given version number,
* error correction level, data codeword bytes, and mask number.
* This is a low-level API that most users should not use directly.
* A mid-level API is the encodeSegments() function.
*/
public: QrCode(int ver, Ecc ecl, const std::vector<std::uint8_t> &dataCodewords, int msk);
/*---- Public instance methods ----*/
/*
* Returns this QR Code's version, in the range [1, 40].
*/
public: int getVersion() const;
/*
* Returns this QR Code's size, in the range [21, 177].
*/
public: int getSize() const;
/*
* Returns this QR Code's error correction level.
*/
public: Ecc getErrorCorrectionLevel() const;
/*
* Returns this QR Code's mask, in the range [0, 7].
*/
public: int getMask() const;
/*
* Returns the color of the module (pixel) at the given coordinates, which is false
* for light or true for dark. The top left corner has the coordinates (x=0, y=0).
* If the given coordinates are out of bounds, then false (light) is returned.
*/
public: bool getModule(int x, int y) const;
/*---- Private helper methods for constructor: Drawing function modules ----*/
// Reads this object's version field, and draws and marks all function modules.
private: void drawFunctionPatterns();
// Draws two copies of the format bits (with its own error correction code)
// based on the given mask and this object's error correction level field.
private: void drawFormatBits(int msk);
// Draws two copies of the version bits (with its own error correction code),
// based on this object's version field, iff 7 <= version <= 40.
private: void drawVersion();
// Draws a 9*9 finder pattern including the border separator,
// with the center module at (x, y). Modules can be out of bounds.
private: void drawFinderPattern(int x, int y);
// Draws a 5*5 alignment pattern, with the center module
// at (x, y). All modules must be in bounds.
private: void drawAlignmentPattern(int x, int y);
// Sets the color of a module and marks it as a function module.
// Only used by the constructor. Coordinates must be in bounds.
private: void setFunctionModule(int x, int y, bool isDark);
// Returns the color of the module at the given coordinates, which must be in range.
private: bool module(int x, int y) const;
/*---- Private helper methods for constructor: Codewords and masking ----*/
// Returns a new byte string representing the given data with the appropriate error correction
// codewords appended to it, based on this object's version and error correction level.
private: std::vector<std::uint8_t> addEccAndInterleave(const std::vector<std::uint8_t> &data) const;
// Draws the given sequence of 8-bit codewords (data and error correction) onto the entire
// data area of this QR Code. Function modules need to be marked off before this is called.
private: void drawCodewords(const std::vector<std::uint8_t> &data);
// XORs the codeword modules in this QR Code with the given mask pattern.
// The function modules must be marked and the codeword bits must be drawn
// before masking. Due to the arithmetic of XOR, calling applyMask() with
// the same mask value a second time will undo the mask. A final well-formed
// QR Code needs exactly one (not zero, two, etc.) mask applied.
private: void applyMask(int msk);
// Calculates and returns the penalty score based on state of this QR Code's current modules.
// This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
private: long getPenaltyScore() const;
/*---- Private helper functions ----*/
// Returns an ascending list of positions of alignment patterns for this version number.
// Each position is in the range [0,177), and are used on both the x and y axes.
// This could be implemented as lookup table of 40 variable-length lists of unsigned bytes.
private: std::vector<int> getAlignmentPatternPositions() const;
// Returns the number of data bits that can be stored in a QR Code of the given version number, after
// all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
// The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.
private: static int getNumRawDataModules(int ver);
// Returns the number of 8-bit data (i.e. not error correction) codewords contained in any
// QR Code of the given version number and error correction level, with remainder bits discarded.
// This stateless pure function could be implemented as a (40*4)-cell lookup table.
private: static int getNumDataCodewords(int ver, Ecc ecl);
// Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be
// implemented as a lookup table over all possible parameter values, instead of as an algorithm.
private: static std::vector<std::uint8_t> reedSolomonComputeDivisor(int degree);
// Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials.
private: static std::vector<std::uint8_t> reedSolomonComputeRemainder(const std::vector<std::uint8_t> &data, const std::vector<std::uint8_t> &divisor);
// Returns the product of the two given field elements modulo GF(2^8/0x11D).
// All inputs are valid. This could be implemented as a 256*256 lookup table.
private: static std::uint8_t reedSolomonMultiply(std::uint8_t x, std::uint8_t y);
// Can only be called immediately after a light run is added, and
// returns either 0, 1, or 2. A helper function for getPenaltyScore().
private: int finderPenaltyCountPatterns(const std::array<int,7> &runHistory) const;
// Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore().
private: int finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, std::array<int,7> &runHistory) const;
// Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore().
private: void finderPenaltyAddHistory(int currentRunLength, std::array<int,7> &runHistory) const;
// Returns true iff the i'th bit of x is set to 1.
private: static bool getBit(long x, int i);
/*---- Constants and tables ----*/
// The minimum version number supported in the QR Code Model 2 standard.
public: static constexpr int MIN_VERSION = 1;
// The maximum version number supported in the QR Code Model 2 standard.
public: static constexpr int MAX_VERSION = 40;
// For use in getPenaltyScore(), when evaluating which mask is best.
private: static const int PENALTY_N1;
private: static const int PENALTY_N2;
private: static const int PENALTY_N3;
private: static const int PENALTY_N4;
private: static const std::int8_t ECC_CODEWORDS_PER_BLOCK[4][41];
private: static const std::int8_t NUM_ERROR_CORRECTION_BLOCKS[4][41];
};
/*---- Public exception class ----*/
/*
* Thrown when the supplied data does not fit any QR Code version. Ways to handle this exception include:
* - Decrease the error correction level if it was greater than Ecc::LOW.
* - If the encodeSegments() function was called with a maxVersion argument, then increase
* it if it was less than QrCode::MAX_VERSION. (This advice does not apply to the other
* factory functions because they search all versions up to QrCode::MAX_VERSION.)
* - Split the text data into better or optimal segments in order to reduce the number of bits required.
* - Change the text or binary data to be shorter.
* - Change the text to fit the character set of a particular segment mode (e.g. alphanumeric).
* - Propagate the error upward to the caller/user.
*/
class data_too_long : public std::length_error {
public: explicit data_too_long(const std::string &msg);
};
/*
* An appendable sequence of bits (0s and 1s). Mainly used by QrSegment.
*/
class BitBuffer final : public std::vector<bool> {
/*---- Constructor ----*/
// Creates an empty bit buffer (length 0).
public: BitBuffer();
/*---- Method ----*/
// Appends the given number of low-order bits of the given value
// to this buffer. Requires 0 <= len <= 31 and val < 2^len.
public: void appendBits(std::uint32_t val, int len);
};
}
+30
View File
@@ -0,0 +1,30 @@
#include "qrtosvg.hpp"
#include <sstream>
#include <climits>
std::string toSvgString(const qrcodegen::QrCode &qr, int border) {
if (border < 0)
throw std::domain_error("Border must be non-negative");
if (border > INT_MAX / 2 || border * 2 > INT_MAX - qr.getSize())
throw std::overflow_error("Border too large");
std::ostringstream sb;
sb << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
sb << "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n";
sb << "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" viewBox=\"0 0 ";
sb << (qr.getSize() + border * 2) << " " << (qr.getSize() + border * 2) << "\" stroke=\"none\">\n";
sb << "\t<rect width=\"100%\" height=\"100%\" fill=\"#FFFFFF\"/>\n";
sb << "\t<path d=\"";
for (int y = 0; y < qr.getSize(); y++) {
for (int x = 0; x < qr.getSize(); x++) {
if (qr.getModule(x, y)) {
if (x != 0 || y != 0)
sb << " ";
sb << "M" << (x + border) << "," << (y + border) << "h1v1h-1z";
}
}
}
sb << "\" fill=\"#000000\"/>\n";
sb << "</svg>\n";
return sb.str();
}
+9
View File
@@ -0,0 +1,9 @@
#ifndef QRTOSVG_HPP
#define QRTOSVG_HPP
#include <string>
#include "qrcodegen.hpp"
std::string toSvgString(const qrcodegen::QrCode &qr, int border);
#endif // RTOSVG_HPP
+77
View File
@@ -0,0 +1,77 @@
#ifndef C_COLORS_H
#define C_COLORS_H
// reset
#define RESET "\033[0m"
// regular colrs
#define GREEN "\033[0;32m" // GREEN
#define BLUE "\033[0;34m" // BLUE
#define YELLOW "\033[1;33m" // YELLOW
#define RED "\033[0;31m" // RED
#define BLACK "\033[0;30m" // BLACK
#define PURPLE "\033[0;35m" // PURPLE
#define CYAN "\033[0;36m" // CYAN
#define WHITE "\033[0;37m" // WHITE
// bold
#define BBLACK "\033[1;30m" // BLACK
#define BRED "\033[1;31m" // RED
#define BGREEN "\033[1;32m" // GREEN
#define BYELLOW "\033[1;33m" // YELLOW
#define BBLUE "\033[1;34m" // BLUE
#define BPURPLE "\033[1;35m" // PURPLE
#define BCYAN "\033[1;36m" // CYAN
#define BWHITE "\033[1;37m" // WHITE
// Underline
#define UBLACK "\033[4;30m" // BLACK
#define URED "\033[4;31m" // RED
#define UGREEN "\033[4;32m" // GREEN
#define UYELLOW "\033[4;33m" // YELLOW
#define UBLUE "\033[4;34m" // BLUE
#define UPURPLE "\033[4;35m" // PURPLE
#define UCYAN "\033[4;36m" // CYAN
#define UWHITE "\033[4;37m" // WHITE
// Background
#define ON_BLACK "\033[40m" // BLACK
#define ON_RED "\033[41m" // RED
#define ON_GREEN "\033[42m" // GREEN
#define ON_YELLOW "\033[43m" // YELLOW
#define ON_BLUE "\033[44m" // BLUE
#define ON_PURPLE "\033[45m" // PURPLE
#define ON_CYAN "\033[46m" // CYAN
#define ON_WHITE "\033[47m" // WHITE
// High Intensity
#define IBLACK "\033[0;90m" // BLACK
#define IRED "\033[0;91m" // RED
#define IGREEN "\033[0;92m" // GREEN
#define IYELLOW "\033[0;93m" // YELLOW
#define IBLUE "\033[0;94m" // BLUE
#define IPURPLE "\033[0;95m" // PURPLE
#define ICYAN "\033[0;96m" // CYAN
#define IWHITE "\033[0;97m" // WHITE
// Bold High Intensity
#define BIBLACK "\033[1;90m" // BLACK
#define BIRED "\033[1;91m" // RED
#define BIGREEN "\033[1;92m" // GREEN
#define BIYELLOW "\033[1;93m" // YELLOW
#define BIBLUE "\033[1;94m" // BLUE
#define BIPURPLE "\033[1;95m" // PURPLE
#define BICYAN "\033[1;96m" // CYAN
#define BIWHITE "\033[1;97m" // WHITE
// High Intensity backgrounds
#define ON_IBLACK "\033[0;100m" // BLACK
#define ON_IRED "\033[0;101m" // RED
#define ON_IGREEN "\033[0;102m" // GREEN
#define ON_IYELLOW "\033[0;103m" // YELLOW
#define ON_IBLUE "\033[0;104m" // BLUE
#define ON_IPURPLE "\033[0;105m" // PURPLE
#define ON_ICYAN "\033[0;106m" // CYAN
#define ON_IWHITE "\033[0;107m" // WHITE
#endif // C_COLORS_H
+9834
View File
File diff suppressed because it is too large. Load diff
+24766
View File
File diff suppressed because it is too large. Load diff
+7
View File
@@ -0,0 +1,7 @@
#include "OpenRouter/OpenRouter.hpp"
int main()
{
OpenRouter router;
return router.serve("127.0.0.1", 43244);
}
+6
View File
@@ -0,0 +1,6 @@
#ifndef ROUTES_HPP
#define ROUTES_HPP
#define AUTH_SERVICE "http://localhost:43243"
#endif // ROUTES_HPP
+16
View File
@@ -0,0 +1,16 @@
#include "cors.hpp"
#include <colors.h>
namespace api
{
namespace security
{
void set_cors_headers(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << " " << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
response.set_header("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
response.set_header("Access-Control-Allow-Headers", "Authorization,X-Custom,Content-Type");
}
}
}
+19
View File
@@ -0,0 +1,19 @@
#ifndef CORS_HPP
#define CORS_HPP
#include <httplib.h>
#ifdef CORS_ENABLE
namespace api
{
namespace security
{
// function to set cors headers
void set_cors_headers(const httplib::Request &request, httplib::Response &response);
}
}
#endif // CORS_ENABLE
#endif // CORS_HPP
+21
View File
@@ -0,0 +1,21 @@
#ifndef DNS_HPP
#define DNS_HPP
#include <httplib.h>
namespace api
{
namespace settings
{
void get_dns(const httplib::Request &request, httplib::Response &response);
void set_dns(const httplib::Request &request, httplib::Response &response);
void get_dns_servers(const httplib::Request &request, httplib::Response &response);
void set_dns_servers(const httplib::Request &request, httplib::Response &response);
void get_local_domains(const httplib::Request &request, httplib::Response &response);
void set_local_domains(const httplib::Request &request, httplib::Response &response);
}
}
#endif // DNS_HPP
+87
View File
@@ -0,0 +1,87 @@
#include "dns.hpp"
#include <colors.h>
#include <json.hpp>
#include "../../types.hpp"
#include <syslog.h>
#include "../../auth/auth.hpp"
#include "../../helpers.hpp"
#define DNS_REQUIRED_STRING R"({"required":"[token,enabled]"})"
namespace api
{
namespace settings
{
void get_dns(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ifstream dnsfile("/etc/openrouter/dns");
int dns_enabled;
dnsfile >> dns_enabled;
dnsfile.close();
std::stringstream responsedata;
responsedata << R"({"enabled":")" << dns_enabled << R"("})";
response.set_content(responsedata.str(), JSON_TYPE);
}
void set_dns(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (json_body["enabled"] == nullptr)
{
response.set_content(DNS_REQUIRED_STRING, JSON_TYPE);
return;
}
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ofstream dnsfileout("/etc/openrouter/dns");
std::string new_dns_enabled = json_body["enabled"];
if (new_dns_enabled == "0")
{
system("rc stop dnsmasq");
system("rc del dnsmasq");
syslog(LOG_INFO, "%s", "DNS is disabled");
}
else
{
system("rc restart dnsmasq");
system("rc add dnsmasq");
syslog(LOG_INFO, "%s", "DNS is enabled");
}
dnsfileout << stoi(new_dns_enabled);
dnsfileout.close();
std::ifstream dnsfile("/etc/openrouter/dns");
int dns_enabled;
dnsfile >> dns_enabled;
dnsfile.close();
std::stringstream responsedata;
responsedata << R"({"enabled":")" << dns_enabled << R"("})";
response.set_content(responsedata.str(), JSON_TYPE);
}
}
}
+91
View File
@@ -0,0 +1,91 @@
#include "dns.hpp"
#include <colors.h>
#include <json.hpp>
#include "../../types.hpp"
#include <syslog.h>
#include "../../auth/auth.hpp"
#include "../../helpers.hpp"
namespace api
{
namespace settings
{
void get_local_domains(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ifstream domainsfile("/etc/dnsmasq.conf.d/hosts");
std::stringstream responsedata;
responsedata << R"({"domains":[)";
std::string ip_string = "";
std::string domain_string = "";
int iter = 0;
while (!domainsfile.eof())
{
domainsfile >> ip_string;
domainsfile >> domain_string;
if (domain_string.empty())
{
continue;
}
responsedata << R"({"ip":")" << ip_string << R"(","domain":")" << domain_string << R"("},)";
ip_string = "";
domain_string = "";
iter++;
}
if (iter != 0)
{
responsedata.str(responsedata.str().erase(responsedata.str().size() - 1, 1) + "]}");
}
else
{
responsedata << "]}";
}
domainsfile.close();
response.set_content(responsedata.str(), JSON_TYPE);
}
void set_local_domains(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ofstream domainsfile("/etc/dnsmasq.conf.d/hosts");
nlohmann::json domains = json_body["domains"];
for (nlohmann::json_abi_v3_11_3::json domain : domains)
{
std::string ip = domain["ip"];
std::string dom = domain["domain"];
domainsfile << ip << " " << dom << "\n";
}
domainsfile.close();
system("rc restart dnsmasq");
syslog(LOG_INFO, "%s", "DNS local domains changed");
std::string responsedata = R"({"success":"true"})";
response.set_content(responsedata, JSON_TYPE);
}
}
}
+87
View File
@@ -0,0 +1,87 @@
#include "dns.hpp"
#include <colors.h>
#include <json.hpp>
#include "../../types.hpp"
#include <syslog.h>
#include "../../auth/auth.hpp"
#include "../../helpers.hpp"
namespace api
{
namespace settings
{
void get_dns_servers(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ifstream dnsserversfile("/etc/dnsmasq.conf.d/resolv.conf");
std::stringstream responsedata;
responsedata << R"({"servers":[)";
std::string dns_server_string = "";
int iter = 0;
while (std::getline(dnsserversfile, dns_server_string))
{
dns_server_string.erase(0, 11);
responsedata << "\"" << dns_server_string << R"(",)";
dns_server_string = "";
iter++;
}
if (iter != 0)
{
responsedata.str(responsedata.str().erase(responsedata.str().size() - 1, 1) + "]}");
}
else
{
responsedata << "]}";
}
dnsserversfile.close();
response.set_content(responsedata.str(), JSON_TYPE);
}
void set_dns_servers(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ofstream dnsserversfile("/etc/dnsmasq.conf.d/resolv.conf");
nlohmann::json servers = json_body["servers"];
for (const nlohmann::json_abi_v3_11_3::json &server : servers)
{
std::string srv = server;
if (server == "")
{
continue;
}
dnsserversfile << "nameserver " << srv << "\n";
}
dnsserversfile.close();
system("rc restart dnsmasq");
syslog(LOG_INFO, "%s", "DNS servers changed");
std::string responsedata = R"({"success":"true"})";
response.set_content(responsedata, JSON_TYPE);
}
}
}
+87
View File
@@ -0,0 +1,87 @@
#include "ftp.hpp"
#include <colors.h>
#include <json.hpp>
#include "../../types.hpp"
#include <syslog.h>
#include "../../auth/auth.hpp"
#include "../../helpers.hpp"
#define FTP_REQUIRED_STRING R"({"required":"[token,enabled]"})"
namespace api
{
namespace settings
{
void get_ftp(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ifstream ftpfile("/etc/openrouter/ftp");
int ftp_enabled;
ftpfile >> ftp_enabled;
ftpfile.close();
std::stringstream responsedata;
responsedata << R"({"enabled":")" << ftp_enabled << R"("})";
response.set_content(responsedata.str(), JSON_TYPE);
}
void set_ftp(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (json_body["enabled"] == nullptr)
{
response.set_content(FTP_REQUIRED_STRING, JSON_TYPE);
return;
}
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ofstream ftpfileout("/etc/openrouter/ftp");
std::string new_ftp_enabled = json_body["enabled"];
if (new_ftp_enabled == "0")
{
system("rc stop ftp");
system("rc del ftp");
syslog(LOG_INFO, "%s", "Ftp is disabled");
}
else
{
system("rc start ftp");
system("rc add ftp");
syslog(LOG_INFO, "%s", "Ftp is enabled");
}
ftpfileout << stoi(new_ftp_enabled);
ftpfileout.close();
std::ifstream ftpfile("/etc/openrouter/ftp");
int ftp_enabled;
ftpfile >> ftp_enabled;
ftpfile.close();
std::stringstream responsedata;
responsedata << R"({"enabled":")" << ftp_enabled << R"("})";
response.set_content(responsedata.str(), JSON_TYPE);
}
}
}
+15
View File
@@ -0,0 +1,15 @@
#ifndef FTP_HPP
#define FTP_HPP
#include <httplib.h>
namespace api
{
namespace settings
{
void get_ftp(const httplib::Request &request, httplib::Response &response);
void set_ftp(const httplib::Request &request, httplib::Response &response);
}
}
#endif // FTP_HPP
+10
View File
@@ -0,0 +1,10 @@
#ifndef SETTINGS_HPP
#define SETTINGS_HPP
#include "wifi/wifi.hpp"
#include "telnet/telnet.hpp"
#include "ssh/ssh.hpp"
#include "ftp/ftp.hpp"
#include "dns/dns.hpp"
#endif // SETTINGS_HPP
+87
View File
@@ -0,0 +1,87 @@
#include "ssh.hpp"
#include <colors.h>
#include <json.hpp>
#include "../../types.hpp"
#include <syslog.h>
#include "../../auth/auth.hpp"
#include "../../helpers.hpp"
#define KEYS_PATH "/root/.ssh/authorized_keys"
namespace api
{
namespace settings
{
void get_ssh_keys(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ifstream keysfile(KEYS_PATH);
std::stringstream responsedata;
responsedata << R"({"keys":[)";
std::string key_string = "";
int iter = 0;
while (std::getline(keysfile, key_string))
{
if (key_string.empty())
{
continue;
}
responsedata << R"(")" << key_string << R"(",)";
key_string = "";
iter++;
}
if (iter != 0)
{
responsedata.str(responsedata.str().erase(responsedata.str().size() - 1, 1) + "]}");
}
else
{
responsedata << "]}";
}
keysfile.close();
response.set_content(responsedata.str(), JSON_TYPE);
}
void set_ssh_keys(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ofstream keysfile(KEYS_PATH);
nlohmann::json keys = json_body["keys"];
for (std::string key : keys)
{
keysfile << key << "\n";
}
keysfile.close();
system("rc restart ssh");
syslog(LOG_INFO, "%s", "SSH keys changed");
std::string responsedata = R"({"success":"true"})";
response.set_content(responsedata, JSON_TYPE);
}
}
}
+91
View File
@@ -0,0 +1,91 @@
#include "ssh.hpp"
#include <colors.h>
#include "../../types.hpp"
#include <json.hpp>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <syslog.h>
#include "../../auth/auth.hpp"
#include "../../helpers.hpp"
#define SSH_PORT_REQUIRED_STRING R"({"required":"[token,port]"})"
#define SSH_PORT_PATH "/etc/openrouter/ssh/port"
namespace api
{
namespace settings
{
void get_ssh_port(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ifstream sshportfile(SSH_PORT_PATH);
int ssh_port;
sshportfile >> ssh_port;
sshportfile.close();
std::stringstream responsedata;
responsedata << R"({"port":")" << ssh_port << R"("})";
response.set_content(responsedata.str(), JSON_TYPE);
}
void set_ssh_port(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (json_body["port"] == nullptr)
{
response.set_content(SSH_PORT_REQUIRED_STRING, JSON_TYPE);
return;
}
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ifstream oldsshportfile(SSH_PORT_PATH);
int old_ssh_port;
oldsshportfile >> old_ssh_port;
oldsshportfile.close();
std::ofstream sshportfileout(SSH_PORT_PATH);
std::string new_ssh_port = json_body["port"];
sshportfileout << stoi(new_ssh_port);
sshportfileout.close();
std::stringstream systemrequest;
systemrequest << "sed -i \"/Port " << old_ssh_port << "/s//Port " << new_ssh_port << "/\" /etc/ssh/sshd_config";
std::cout << systemrequest.str() << std::endl;
system(systemrequest.str().c_str());
system("rc restart ssh");
std::string syslogstring = "SSH port changed to " + new_ssh_port;
syslog(LOG_INFO, "%s", syslogstring.c_str());
std::ifstream sshportfile(SSH_PORT_PATH);
int ssh_port;
sshportfile >> ssh_port;
sshportfile.close();
std::stringstream responsedata;
responsedata << R"({"port":")" << ssh_port << R"("})";
response.set_content(responsedata.str(), JSON_TYPE);
}
}
}
+21
View File
@@ -0,0 +1,21 @@
#ifndef SSH_HPP
#define SSH_HPP
#include <httplib.h>
namespace api
{
namespace settings
{
void get_ssh_status(const httplib::Request &request, httplib::Response &response);
void set_ssh_status(const httplib::Request &request, httplib::Response &response);
void get_ssh_keys(const httplib::Request &request, httplib::Response &response);
void set_ssh_keys(const httplib::Request &request, httplib::Response &response);
void get_ssh_port(const httplib::Request &request, httplib::Response &response);
void set_ssh_port(const httplib::Request &request, httplib::Response &response);
}
}
#endif // SSH_HPP
+87
View File
@@ -0,0 +1,87 @@
#include "ssh.hpp"
#include <colors.h>
#include <json.hpp>
#include "../../types.hpp"
#include <syslog.h>
#include "../../auth/auth.hpp"
#include "../../helpers.hpp"
#define SSH_REQUIRED_STRING R"({"required":"[token,status]"})"
namespace api
{
namespace settings
{
void get_ssh_status(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ifstream sshstatusfile("/etc/openrouter/ssh/status");
int ssh_status;
sshstatusfile >> ssh_status;
sshstatusfile.close();
std::stringstream responsedata;
responsedata << R"({"status":")" << ssh_status << R"("})";
response.set_content(responsedata.str(), JSON_TYPE);
}
void set_ssh_status(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (json_body["status"] == nullptr)
{
response.set_content(SSH_REQUIRED_STRING, JSON_TYPE);
return;
}
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ofstream sshfileout("/etc/openrouter/ssh/status");
std::string new_ssh_status = json_body["status"];
if (new_ssh_status == "0")
{
system("rc stop ssh");
system("rc del ssh");
syslog(LOG_INFO, "%s", "SSH is disabled");
}
else
{
system("rc start ssh");
system("rc add ssh");
syslog(LOG_INFO, "%s", "SSH is enabled");
}
sshfileout << stoi(new_ssh_status);
sshfileout.close();
std::ifstream sshfile("/etc/openrouter/ssh/status");
int ssh_status;
sshfile >> ssh_status;
sshfile.close();
std::stringstream responsedata;
responsedata << R"({"status":")" << ssh_status << R"("})";
response.set_content(responsedata.str(), JSON_TYPE);
}
}
}
+91
View File
@@ -0,0 +1,91 @@
#include "telnet.hpp"
#include <colors.h>
#include "../../types.hpp"
#include <json.hpp>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <syslog.h>
#include "../../auth/auth.hpp"
#include "../../helpers.hpp"
#define TELNET_REQUIRED_STRING R"({"required":"[token,enabled]"})"
namespace api
{
namespace settings
{
void get_telnet(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ifstream telnetfile("/etc/openrouter/telnet/enabled");
int telnet_enabled;
telnetfile >> telnet_enabled;
telnetfile.close();
std::stringstream responsedata;
responsedata << R"({"enabled":")" << telnet_enabled << R"("})";
response.set_content(responsedata.str(), JSON_TYPE);
}
void set_telnet(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (json_body["enabled"] == nullptr)
{
response.set_content(TELNET_REQUIRED_STRING, JSON_TYPE);
return;
}
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ofstream telnetfileout("/etc/openrouter/telnet/enabled");
std::string new_telnet_enabled = json_body["enabled"];
if (new_telnet_enabled == "0")
{
system("rc stop telnet");
system("rc del telnet");
syslog(LOG_INFO, "%s", "Telnet is disabled");
}
else
{
system("rc start telnet");
system("rc add telnet");
syslog(LOG_INFO, "%s", "Telnet is enabled");
}
telnetfileout << stoi(new_telnet_enabled);
telnetfileout.close();
std::ifstream telnetfile("/etc/openrouter/telnet/enabled");
int telnet_enabled;
telnetfile >> telnet_enabled;
telnetfile.close();
std::stringstream responsedata;
responsedata << R"({"enabled":")" << telnet_enabled << R"("})";
response.set_content(responsedata.str(), JSON_TYPE);
}
}
}
+82
View File
@@ -0,0 +1,82 @@
#include "telnet.hpp"
#include <colors.h>
#include "../../types.hpp"
#include <json.hpp>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <syslog.h>
#include "../../auth/auth.hpp"
#include "../../helpers.hpp"
#define TELNET_PORT_REQUIRED_STRING R"({"required":"[token,port]"})"
namespace api
{
namespace settings
{
void get_telnet_port(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ifstream telnetportfile("/etc/openrouter/telnet/port");
int telnet_port;
telnetportfile >> telnet_port;
telnetportfile.close();
std::stringstream responsedata;
responsedata << R"({"port":")" << telnet_port << R"("})";
response.set_content(responsedata.str(), JSON_TYPE);
}
void set_telnet_port(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (json_body["port"] == nullptr)
{
response.set_content(TELNET_PORT_REQUIRED_STRING, JSON_TYPE);
return;
}
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ofstream telnetportfileout("/etc/openrouter/telnet/port");
std::string new_telnet_port = json_body["port"];
telnetportfileout << stoi(new_telnet_port);
telnetportfileout.close();
system("rc restart telnet");
std::string syslogstring = "Telnet port changed to " + new_telnet_port;
syslog(LOG_INFO, "%s", syslogstring.c_str());
std::ifstream telnetportfile("/etc/openrouter/telnet/port");
int telnet_port;
telnetportfile >> telnet_port;
telnetportfile.close();
std::stringstream responsedata;
responsedata << R"({"port":")" << telnet_port << R"("})";
response.set_content(responsedata.str(), JSON_TYPE);
}
}
}
+18
View File
@@ -0,0 +1,18 @@
#ifndef SETTINGS_TELNET_HPP
#define SETTINGS_TELNET_HPP
#include <httplib.h>
namespace api
{
namespace settings
{
void get_telnet(const httplib::Request &request, httplib::Response &response);
void set_telnet(const httplib::Request &request, httplib::Response &response);
void get_telnet_port(const httplib::Request &request, httplib::Response &response);
void set_telnet_port(const httplib::Request &request, httplib::Response &response);
}
}
#endif // SETTINGS_TELNET_HPP
+115
View File
@@ -0,0 +1,115 @@
#include "wifi.hpp"
#include <colors.h>
#include "../../types.hpp"
#include <json.hpp>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <syslog.h>
#include "../../auth/auth.hpp"
#include "../../helpers.hpp"
#define WIFI_CHANNEL_REQUIRED_STRING R"({"required":"[token,channel]"})"
namespace api
{
namespace settings
{
void get_wifi_channel(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ifstream wifisettingsfile(WIFI_SETTINGS_PATH);
std::string wifi_channel;
std::string wifisettingsbuffer;
while (std::getline(wifisettingsfile, wifisettingsbuffer))
{
if (wifisettingsbuffer.find("channel=") == 0)
{
wifi_channel = wifisettingsbuffer;
wifi_channel.erase(0, 8);
break;
}
}
wifisettingsfile.close();
std::stringstream responsedata;
responsedata << R"({"channel":")" << wifi_channel << R"("})";
response.set_content(responsedata.str(), JSON_TYPE);
}
void set_wifi_channel(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (json_body["channel"] == nullptr)
{
response.set_content(WIFI_CHANNEL_REQUIRED_STRING, JSON_TYPE);
return;
}
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ifstream wifisettingsfile(WIFI_SETTINGS_PATH);
std::string old_channel;
std::string wifisettingsbuffer;
while (std::getline(wifisettingsfile, wifisettingsbuffer))
{
if (wifisettingsbuffer.find("channel=") == 0)
{
old_channel = wifisettingsbuffer;
old_channel.erase(0, 8);
break;
}
}
wifisettingsfile.close();
std::string new_channel = json_body["channel"];
std::stringstream systemrequest;
systemrequest << "sed -i \"/channel=" << old_channel << "/s//channel=" << new_channel << "/\" /etc/hostapd/hostapd.conf";
std::cout << systemrequest.str() << std::endl;
system(systemrequest.str().c_str());
system("rc restart hostapd");
std::string syslogstring = "WIFI channel changed to " + new_channel;
syslog(LOG_INFO, "%s", syslogstring.c_str());
std::ifstream changedwifisettingsfile(WIFI_SETTINGS_PATH);
std::string wifi_channel;
std::string changedwifisettingsbuffer;
while (std::getline(changedwifisettingsfile, changedwifisettingsbuffer))
{
if (changedwifisettingsbuffer.find("channel=") == 0)
{
wifi_channel = changedwifisettingsbuffer;
wifi_channel.erase(0, 8);
break;
}
}
changedwifisettingsfile.close();
std::stringstream responsedata;
responsedata << R"({"channel":")" << wifi_channel << R"("})";
response.set_content(responsedata.str(), JSON_TYPE);
}
}
}
+115
View File
@@ -0,0 +1,115 @@
#include "wifi.hpp"
#include <colors.h>
#include "../../types.hpp"
#include <json.hpp>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <syslog.h>
#include "../../auth/auth.hpp"
#include "../../helpers.hpp"
#define WIFI_NAME_REQUIRED_STRING R"({"required":"[token,name]"})"
namespace api
{
namespace settings
{
void get_wifi_name(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ifstream wifisettingsfile(WIFI_SETTINGS_PATH);
std::string wifi_name;
std::string wifisettingsbuffer;
while (std::getline(wifisettingsfile, wifisettingsbuffer))
{
if (wifisettingsbuffer.find("ssid=") == 0)
{
wifi_name = wifisettingsbuffer;
wifi_name.erase(0, 5);
break;
}
}
wifisettingsfile.close();
std::stringstream responsedata;
responsedata << R"({"name":")" << wifi_name << R"("})";
response.set_content(responsedata.str(), JSON_TYPE);
}
void set_wifi_name(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (json_body["name"] == nullptr)
{
response.set_content(WIFI_NAME_REQUIRED_STRING, JSON_TYPE);
return;
}
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ifstream wifisettingsfile(WIFI_SETTINGS_PATH);
std::string old_wifi_name;
std::string wifisettingsbuffer;
while (std::getline(wifisettingsfile, wifisettingsbuffer))
{
if (wifisettingsbuffer.find("ssid=") == 0)
{
old_wifi_name = wifisettingsbuffer;
old_wifi_name.erase(0, 5);
break;
}
}
wifisettingsfile.close();
std::string new_wifi_name = json_body["name"];
std::stringstream systemrequest;
systemrequest << "sed -i \"/ssid=" << old_wifi_name << "/s//ssid=" << new_wifi_name << "/\" /etc/hostapd/hostapd.conf";
std::cout << systemrequest.str() << std::endl;
system(systemrequest.str().c_str());
system("rc restart hostapd");
std::string syslogstring = "WIFI name changed to " + new_wifi_name;
syslog(LOG_INFO, "%s", syslogstring.c_str());
std::ifstream changedwifisettingsfile(WIFI_SETTINGS_PATH);
std::string wifi_name;
std::string changedwifisettingsbuffer;
while (std::getline(changedwifisettingsfile, changedwifisettingsbuffer))
{
if (changedwifisettingsbuffer.find("ssid=") == 0)
{
wifi_name = changedwifisettingsbuffer;
wifi_name.erase(0, 5);
break;
}
}
changedwifisettingsfile.close();
std::stringstream responsedata;
responsedata << R"({"name":")" << wifi_name << R"("})";
response.set_content(responsedata.str(), JSON_TYPE);
}
}
}
+112
View File
@@ -0,0 +1,112 @@
#include "wifi.hpp"
#include <colors.h>
#include "../../types.hpp"
#include <json.hpp>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <syslog.h>
#include "../../auth/auth.hpp"
#include "../../helpers.hpp"
#define WIFI_PASSWORD_REQUIRED_STRING R"({"required":"[token,password,newpassword]"})"
namespace api
{
namespace settings
{
void get_wifi_password(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ifstream wifisettingsfile(WIFI_SETTINGS_PATH);
std::string wifi_password;
std::string wifisettingsbuffer;
while (std::getline(wifisettingsfile, wifisettingsbuffer))
{
if (wifisettingsbuffer.find("wpa_passphrase=") == 0)
{
wifi_password = wifisettingsbuffer;
wifi_password.erase(0, 15);
break;
}
}
wifisettingsfile.close();
std::stringstream responsedata;
responsedata << R"({"password":")" << wifi_password << R"("})";
response.set_content(responsedata.str(), JSON_TYPE);
}
void set_wifi_password(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (json_body["password"] == nullptr)
{
response.set_content(WIFI_PASSWORD_REQUIRED_STRING, JSON_TYPE);
return;
}
if (json_body["newpassword"] == nullptr)
{
response.set_content(WIFI_PASSWORD_REQUIRED_STRING, JSON_TYPE);
return;
}
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ifstream wifisettingsfile(WIFI_SETTINGS_PATH);
std::string old_wifi_password;
std::string wifisettingsbuffer;
while (std::getline(wifisettingsfile, wifisettingsbuffer))
{
if (wifisettingsbuffer.find("wpa_passphrase=") == 0)
{
old_wifi_password = wifisettingsbuffer;
old_wifi_password.erase(0, 15);
break;
}
}
wifisettingsfile.close();
std::string req_old_password = json_body["password"];
if (old_wifi_password != req_old_password)
{
response.set_content(R"({"status":"reject"})", JSON_TYPE);
return;
}
std::string new_wifi_password = json_body["newpassword"];
std::stringstream systemrequest;
systemrequest << "sed -i \"/wpa_passphrase=" << old_wifi_password << "/s//wpa_passphrase=" << new_wifi_password << "/\" /etc/hostapd/hostapd.conf";
system(systemrequest.str().c_str());
system("rc restart hostapd");
std::string syslogstring = "WIFI password changed";
syslog(LOG_INFO, "%s", syslogstring.c_str());
std::stringstream responsedata;
responsedata << R"({"success":"ok"})";
response.set_content(responsedata.str(), JSON_TYPE);
}
}
}
+58
View File
@@ -0,0 +1,58 @@
#include "wifi.hpp"
#include <colors.h>
#include <json.hpp>
#include "../../types.hpp"
#include <QR-Code-generator/qrcodegen.hpp>
#include <QR-Code-generator/qrtosvg.hpp>
#include "../../auth/auth.hpp"
#include "../../helpers.hpp"
namespace api
{
namespace settings
{
void get_wifi_qr(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ifstream wifisettingsfile(WIFI_SETTINGS_PATH);
std::string wifi_name;
std::string wifi_password;
std::string wifisettingsbuffer;
while (std::getline(wifisettingsfile, wifisettingsbuffer))
{
if (wifisettingsbuffer.find("ssid=") == 0)
{
wifi_name = wifisettingsbuffer;
wifi_name.erase(0, 5);
}
if (wifisettingsbuffer.find("wpa_passphrase=") == 0)
{
wifi_password = wifisettingsbuffer;
wifi_password.erase(0, 15);
break;
}
}
wifisettingsfile.close();
std::stringstream toqrstring;
toqrstring << "WIFI:T:WPA;P:" << wifi_password << ";S:" << wifi_name << ";";
qrcodegen::QrCode qr0 = qrcodegen::QrCode::encodeText(toqrstring.str().c_str(), qrcodegen::QrCode::Ecc::MEDIUM);
std::string responsedata = toSvgString(qr0, 4);
response.set_content(responsedata, SVG_TYPE);
}
}
}
+87
View File
@@ -0,0 +1,87 @@
#include "wifi.hpp"
#include <colors.h>
#include <json.hpp>
#include "../../types.hpp"
#include <syslog.h>
#include "../../auth/auth.hpp"
#include "../../helpers.hpp"
#define WIFI_REQUIRED_STRING R"({"required":"[token,status]"})"
namespace api
{
namespace settings
{
void get_wifi_status(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ifstream wifistatusfile("/etc/openrouter/wifi/status");
int wifi_status;
wifistatusfile >> wifi_status;
wifistatusfile.close();
std::stringstream responsedata;
responsedata << R"({"status":")" << wifi_status << R"("})";
response.set_content(responsedata.str(), JSON_TYPE);
}
void set_wifi_status(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (!check_body(request))
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (json_body["status"] == nullptr)
{
response.set_content(WIFI_REQUIRED_STRING, JSON_TYPE);
return;
}
if (!authenticate(json_body["token"]))
{
response.set_content(R"({"access":"reject"})", JSON_TYPE);
return;
}
std::ofstream wififileout("/etc/openrouter/wifi/status");
std::string new_wifi_status = json_body["status"];
if (new_wifi_status == "0")
{
system("rc stop hostapd");
system("rc del hostapd");
syslog(LOG_INFO, "%s", "WIFI is disabled");
}
else
{
system("rc start hostapd");
system("rc add hostapd");
syslog(LOG_INFO, "%s", "WIFI is enabled");
}
wififileout << stoi(new_wifi_status);
wififileout.close();
std::ifstream wififile("/etc/openrouter/wifi/status");
int wifi_status;
wififile >> wifi_status;
wififile.close();
std::stringstream responsedata;
responsedata << R"({"status":")" << wifi_status << R"("})";
response.set_content(responsedata.str(), JSON_TYPE);
}
}
}
+28
View File
@@ -0,0 +1,28 @@
#ifndef WIFI_HPP
#define WIFI_HPP
#include <httplib.h>
#define WIFI_SETTINGS_PATH "/etc/hostapd/hostapd.conf"
namespace api
{
namespace settings
{
void get_wifi_status(const httplib::Request &request, httplib::Response &response);
void set_wifi_status(const httplib::Request &request, httplib::Response &response);
void get_wifi_name(const httplib::Request &request, httplib::Response &response);
void set_wifi_name(const httplib::Request &request, httplib::Response &response);
void get_wifi_password(const httplib::Request &request, httplib::Response &response);
void set_wifi_password(const httplib::Request &request, httplib::Response &response);
void get_wifi_qr(const httplib::Request &request, httplib::Response &response);
void get_wifi_channel(const httplib::Request &request, httplib::Response &response);
void set_wifi_channel(const httplib::Request &request, httplib::Response &response);
}
}
#endif // WIFI_HPP
+35
View File
@@ -0,0 +1,35 @@
#include "reboot.hpp"
#include <json.hpp>
#include <colors.h>
#include "../types.hpp"
#include "../../auth/auth.hpp"
namespace api
{
namespace system
{
void reboot(const httplib::Request &request, httplib::Response &response)
{
std::cout << GREEN << request.path << RESET << " " << request.method << std::endl;
response.set_header("Access-Control-Allow-Origin", "*");
if (request.body.empty())
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (json_body["token"] == nullptr)
{
response.set_content(ACCESS_REQUIRED_STRING, JSON_TYPE);
return;
}
if (authenticate(json_body["token"]))
{
std::system("reboot");
}
response.set_content(R"({"access":"reject"})", JSON_TYPE);
}
}
}
+14
View File
@@ -0,0 +1,14 @@
#ifndef REBOOT_HPP
#define REBOOT_HPP
#include <httplib.h>
namespace api
{
namespace system
{
void reboot(const httplib::Request &request, httplib::Response &response);
}
}
#endif // REBOOT_HPP
+23
View File
@@ -0,0 +1,23 @@
#include "syslog.hpp"
#include "../types.hpp"
#include <json.hpp>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#define SYSLOG_FILE "/var/log/messages"
namespace api
{
namespace system
{
void get_syslog(const httplib::Request &request, httplib::Response &response)
{
std::stringstream responsedata;
std::ifstream syslogfile(SYSLOG_FILE);
responsedata << syslogfile.rdbuf();
syslogfile.close();
response.set_content(responsedata.str(), PLAIN_TEXT_TYPE);
}
}
}
+14
View File
@@ -0,0 +1,14 @@
#ifndef SYSLOG_HPP
#define SYSLOG_HPP
#include <httplib.h>
namespace api
{
namespace system
{
void get_syslog(const httplib::Request &request, httplib::Response &response);
}
}
#endif // SYSLOG_HPP
+10
View File
@@ -0,0 +1,10 @@
#ifndef SYSTEM_HPP
#define SYSTEM_HPP
#ifdef __linux__
#include "uptime/uptime.hpp"
#endif // __linux__
#include "syslog/syslog.hpp"
#include "reboot/reboot.hpp"
#endif // SYSTEM_HPP
+37
View File
@@ -0,0 +1,37 @@
#include "uptime.hpp"
#ifdef __linux__
#include <sys/sysinfo.h>
#endif // __linux__
#include <sstream>
#include "../types.hpp"
namespace api
{
namespace system
{
void get_uptime(const httplib::Request &request, httplib::Response &response)
{
#ifdef __linux__
struct sysinfo x;
if (sysinfo(&x) == 0)
{
// std::cout << static_cast<unsigned long long>(x.uptime)/3600ULL << "h "
// << static_cast<unsigned long long>(x.uptime)/60ULL%60ULL << "m "
// << static_cast<unsigned long long>(x.uptime)%60ULL << "s "
// << std::endl;
std::stringstream responsedata;
responsedata << R"({"uptime":{"hour":")"
<< static_cast<unsigned long long>(x.uptime) / 3600ULL
<< R"(","minute":")"
<< static_cast<unsigned long long>(x.uptime) / 60ULL % 60ULL
<< R"(","second":")"
<< static_cast<unsigned long long>(x.uptime) % 60ULL
<< R"("}})";
response.set_content(responsedata.str(), JSON_TYPE);
return;
}
response.set_content(R"({"error":"unknown"})", JSON_TYPE);
#endif // __linux__
}
}
}
+14
View File
@@ -0,0 +1,14 @@
#ifndef UPTIME_HPP
#define UPTIME_HPP
#include <httplib.h>
namespace api
{
namespace system
{
void get_uptime(const httplib::Request &request, httplib::Response &response);
}
}
#endif // UPTIME_HPP
+12
View File
@@ -0,0 +1,12 @@
#ifndef TYPES_H
#define TYPES_H
#define ACCESS_REQUIRED_STRING R"({"required":"[token]"})"
#define JWT_SECRET_KEY "secret"
#define STRING403 R"({"status":"403"})"
#define JSON_TYPE "application/json"
#define PLAIN_TEXT_TYPE "text/plain"
#define SVG_TYPE "image/svg+xml"
#endif // TYPES_H
Binary file not shown.

After

Width:  |  Height:  |  Size: 686 KiB

+19
View File
@@ -0,0 +1,19 @@
button {
padding: 10px;
border-radius: 10px;
border: none;
transition: 0.3s;
cursor: pointer;
}
button:hover {
opacity: 0.6;
}
.linkbutton {
background: transparent;
}
.linkbutton:hover {
text-decoration: underline;
}
+130
View File
@@ -0,0 +1,130 @@
.form {
position: absolute;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
pointer-events: none;
padding: 10px;
transform: scale(0.5);
opacity: 0;
transition: 0.3s;
position: absolute;
margin: auto;
}
.form.active {
pointer-events: all;
opacity: 1;
transform: scale(1);
}
.form.active>.formbody {
transform: scale(1);
}
.formbody {
width: 50%;
height: 50%;
display: flex;
flex-direction: column;
gap: 10px;
align-items: center;
justify-content: center;
background-color: gray;
/* opacity: 0.7; */
border-radius: 20px;
padding: 10px;
}
.formheader {
width: 100%;
text-align: center;
}
.forminputbody {
width: 50%;
display: flex;
flex-direction: column;
}
.forminputbody.confirmform {
display: flex;
flex-direction: row;
align-items: center;
gap: 10px;
}
.forminputbody.confirmform>button {
width: 100%;
}
.forminputlabel {
text-align: center;
font-style: normal;
font-size: 20px;
margin: 5px 0;
}
.forminput {
padding: 10px;
border-radius: 10px;
border: 2px solid;
transition: 0.2s;
background-color: inherit;
}
.forminput>option {
background-color: inherit;
color: black;
}
.forminput:focus {
border: 5px solid;
}
.formbutton {
padding: 10px;
border-radius: 10px;
border: none;
cursor: pointer;
transition: 0.3s;
}
.formbutton:hover {
opacity: 0.6;
}
@media screen and (max-width: 800px) {
.forminputbody {
width: 100%;
}
}
@media screen and (max-width: 800px) {
.formbody {
height: 60%;
}
}
@media screen and (max-width: 500px) {
.formbody {
width: 100%;
}
}
@media screen and (max-width: 300px) {
.formbody {
height: 60%;
width: 100%;
}
}
@media screen and (max-width: 500px) {
.formheader {
font-size: 20px;
}
}
+87
View File
@@ -0,0 +1,87 @@
header {
width: 100vw;
height: 50px;
padding: 10px;
margin: 5px;
display: grid;
grid-template-columns: 32% 32% 32%;
align-items: center;
justify-content: space-between;
}
.links {
justify-self: start;
display: flex;
align-items: center;
gap: 10px;
}
#headermenubutton {
position: absolute;
top: 0;
left: 0;
width: 0;
height: 0;
overflow: hidden;
padding: 0;
margin: 0;
transition: 0.3s;
}
.userbuttons {
justify-self: end;
display: flex;
align-items: center;
gap: 10px;
}
header>h1 {
justify-self: center;
display: flex;
align-items: center;
}
#openroutericon {
max-width: 50px;
max-height: 50px;
border-radius: 10px;
margin: 0 5px;
}
@media screen and (max-width: 400px) {
header>h1 {
font-size: 15px;
}
.userbuttons>h1 {
font-size: 15px;
}
}
@media screen and (max-width: 600px) {
.links {
position: absolute;
top: 10px;
left: 10;
height: 0;
overflow: hidden;
flex-direction: column;
transition: 0.3s;
}
.links.active {
height: max-content;
background-color: gray;
z-index: 10;
border-radius: 10px;
}
#headermenubutton {
position: relative;
width: fit-content;
height: fit-content;
overflow: hidden;
padding: 10px;
/* margin: 0; */
}
}
+34
View File
@@ -0,0 +1,34 @@
:root {
color-scheme: light dark;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
width: 100vw;
height: 100vh;
}
.adminpanel {
position: relative;
width: 100%;
height: 100%;
transform: scale(0.5);
opacity: 0;
transition: 0.3s;
}
.adminpanel.active {
transform: scale(1);
opacity: 1;
}
.section {
position: relative;
overflow: hidden;
height: calc(100vh - 50px);
}
+27
View File
@@ -0,0 +1,27 @@
.infosection {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
pointer-events: none;
transition: 0.3s;
padding: 10px;
}
.infosection.active {
opacity: 1;
pointer-events: all;
}
.inforect {
background-color: gray;
max-width: 500px;
border-radius: 10px;
display: grid;
grid-template-columns: repeat(2, minmax(50px, 500px));
align-items: center;
padding: 10px;
margin: 10px;
}
+64
View File
@@ -0,0 +1,64 @@
.loader {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 0;
pointer-events: none;
display: grid;
z-index: 12;
backdrop-filter: blur(5px);
transition: 0.3s;
}
.loader>h1 {
opacity: 0;
width: 100%;
padding: 10px;
text-align: center;
}
.loadertip {
width: 0;
height: 0;
padding: 0;
margin: 0;
border-radius: 50%;
place-self: center;
z-index: 12;
position: relative;
transition: 0.3s;
}
.progress {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border-top: 5px solid #56C1F9;
border-radius: 50%;
animation: loading 2s infinite ease-in-out;
}
.loader.active {
width: 100vw;
height: 100vh;
}
.loader.active > .loadertip {
width: 100px;
height: 100px;
border-bottom: 5px solid gray;
animation: loading 2s infinite ease-in-out;
}
.loader.active>h1 {
opacity: 1;
}
@keyframes loading {
100% {
transform: rotate(360deg);
}
}
+53
View File
@@ -0,0 +1,53 @@
.notificationsection {
width: max-content;
height: 100vh;
position: fixed;
top: 0;
right: 0;
pointer-events: none;
z-index: 1;
}
.notification {
width: max-content;
height: 0;
overflow: hidden;
pointer-events: none;
z-index: 10;
border-radius: 10px;
/* position: fixed; */
top: 0;
right: 0;
transition: 0.3s;
cursor: pointer;
opacity: 0.8;
margin: 10px;
padding: 0 10px;
}
.notificationtextbox {
width: 100%;
height: 100%;
display: grid;
justify-items: center;
align-items: center;
pointer-events: none;
}
.notificationtext {
width: 100%;
text-align: center;
pointer-events: none;
}
.notification.active.error {
pointer-events: all;
height: 10%;
background-color: rgb(233, 70, 70);
}
.notification.active.success {
pointer-events: all;
height: 10%;
background-color: rgb(76, 209, 76);
}
+241
View File
@@ -0,0 +1,241 @@
.checkbox-wrapper-2 .ikxBAC {
appearance: none;
background-color: #dfe1e4;
border-radius: 72px;
border-style: none;
flex-shrink: 0;
height: 20px;
margin: 0;
position: relative;
width: 30px;
transition: 0.3s;
}
.checkbox-wrapper-2 .ikxBAC::before {
bottom: -6px;
content: "";
left: -6px;
position: absolute;
right: -6px;
top: -6px;
transition: 0.3s;
cursor: pointer;
}
.checkbox-wrapper-2 .ikxBAC,
.checkbox-wrapper-2 .ikxBAC::after {
transition: 300ms;
}
.checkbox-wrapper-2 .ikxBAC::after {
background-color: #fff;
border-radius: 50%;
content: "";
height: 14px;
left: 3px;
position: absolute;
top: 3px;
width: 14px;
cursor: pointer;
}
.checkbox-wrapper-2 input[type=checkbox] {
cursor: default;
}
.checkbox-wrapper-2 .ikxBAC:hover {
background-color: #c9cbcd;
transition-duration: 0s;
}
.checkbox-wrapper-2 .ikxBAC:checked {
background-color: green;
}
.checkbox-wrapper-2 .ikxBAC:checked::after {
background-color: #fff;
left: 13px;
}
.checkbox-wrapper-2 :focus:not(.focus-visible) {
outline: 0;
}
.checkbox-wrapper-2 .ikxBAC:checked:hover {
background-color: hsl(from green h s 20%);
}
.settingssection {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: calc(100vh - 50px);
padding: 10px;
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 10px;
transition: 0.3s;
opacity: 0;
pointer-events: none;
overflow-y: auto;
}
.settingssection.active {
opacity: 1;
pointer-events: all;
}
.settingrect {
width: 24%;
height: max-content;
background-color: gray;
padding: 20px;
border-radius: 20px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 10px;
}
.settingrectheader {
width: 100%;
display: flex;
justify-content: space-between;
}
.settingrectbody {
position: relative;
width: 100%;
max-height: 0;
overflow: auto;
transition: 0.3s;
display: flex;
flex-direction: column;
gap: 10px;
}
.settingrectbody.active {
max-height: 500px;
overflow-y: auto;
}
.settingrectbody>table {
position: relative;
width: 100%;
text-align: left;
transition: 0.3s;
}
.settingrectfooter {
width: 100%;
display: flex;
align-items: center;
gap: 10px;
}
.settingrectfooter.onebutton {
gap: 0;
}
.settingrectfooterbutton {
width: 100%;
}
.hiddenbutton {
width: 0;
overflow: hidden;
padding: 0;
margin: 0;
}
.hiddenbutton.active {
position: relative;
width: 100%;
padding: 10px;
}
.settingrectbody>table {
position: relative;
width: 100%;
border: 2px solid ;
border-radius: 10px;
margin: 10px 0;
}
thead>tr>th {
border-bottom: 2px solid;
padding: 10px;
width: 50%;
}
.one {
border: 2px solid;
padding: 10px;
border-radius: 10px;
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
}
.three {
width: 33%;
}
/* tbody>tr>th.one {
border: 2px solid;
padding: 10px;
border-radius: 10px;
display: flex;
align-items: center;
justify-content: space-between;
} */
tbody>tr>th {
border: 2px solid;
padding: 10px;
border-radius: 10px;
width: 50%;
max-width:425px;
overflow-x: auto;
/* display: flex;
align-items: center;
justify-content: space-between; */
}
#wifiqrimg {
width: 0;
height: 0;
overflow: hidden;
transition: 0.3s;
}
#wifiqrimg.active {
width: 100px;
height: 100px;
}
@media screen and (max-width: 1200px) {
.settingrect {
width: 50%;
}
.settingssection {
/* flex-direction: column; */
/* align-items: center; */
}
}
@media screen and (max-width: 600px) {
.settingrect {
width: 75%;
}
}
@media screen and (max-width: 400px) {
.settingrect {
width: 100%;
}
}
+32
View File
@@ -0,0 +1,32 @@
.syslogsection {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
pointer-events: none;
transition: 0.3s;
padding: 10px;
}
.syslogsection.active {
opacity: 1;
pointer-events: all;
}
.syslogheader {
display: flex;
align-items: center;
gap: 10px;
}
.syslogdata {
width: 100%;
max-height: 85vh;
padding: 10px;
border-radius: 10px;
/* background-color: rgb(175, 175, 175); */
margin: 10px 0;
overflow-y: auto;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 264 KiB

+274
View File
@@ -0,0 +1,274 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/index.css">
<link rel="stylesheet" href="css/form.css">
<link rel="stylesheet" href="css/settings.css">
<link rel="stylesheet" href="css/notification.css">
<link rel="stylesheet" href="css/header.css">
<link rel="stylesheet" href="css/button.css">
<link rel="stylesheet" href="css/loader.css">
<link rel="stylesheet" href="css/syslog.css">
<link rel="stylesheet" href="css/info.css">
<title>Openrouter Admin</title>
</head>
<body>
<section class="adminpanel">
<!-- header -->
<header class="header">
<button id="headermenubutton">&#9636;</button>
<div class="links">
<button class="linkbutton" id="syslogbutton">Syslog</button>
<button class="linkbutton" id="settingsbutton">Settings</button>
<button class="linkbutton" id="infobutton">Info</button>
<button class="linkbutton" id="rebootbutton">Reboot</button>
</div>
<h1><img id="openroutericon" src="favicon.ico" alt="icon">Openrouter Admin</h1>
<div class="userbuttons">
<h1 class="headerusername"></h1>
<button class="exitbutton">Exit</button>
</div>
</header>
<!-- header -->
<!-- settings block -->
<div class="section">
<section class="settingssection">
<!-- telnet settings -->
<div class="settingrect ">
<div class="settingrectheader">
<h2>Telnet</h2>
<div class="checkbox-wrapper-2">
<input type="checkbox" class="sc-gJwTLC ikxBAC" id="telnetenable">
</div>
</div>
<div class="settingrectbody telnetsettingbody">
<div style="display:flex;align-items:center;justify-content:space-between;">
<label for="telnetportinput" class="forminputlabel">Port</label>
<input type="text" id="telnetportinput" class="forminput">
</div>
</div>
<div class="settingrectfooter">
<!-- <button class="settingrectfooterbutton hiddenbutton" id="add_telnet_user_button">Add telnet user</button> -->
<button class="settingrectfooterbutton" id="set_telnet_settings">Confirm</button>
</div>
</div>
<!-- telnet settings -->
<!-- DNS settings -->
<div class="settingrect ">
<div class="settingrectheader">
<h2>DNS</h2>
<div class="checkbox-wrapper-2">
<input type="checkbox" class="sc-gJwTLC ikxBAC" id="dnsenable">
</div>
</div>
<div class="settingrectbody" id="dnssettingsbody">
<table class="dnsservers">
<thead>
<tr>
<th>DNS servers</th>
</tr>
</thead>
<tbody id="dnsserverstablebody">
</tbody>
</table>
<h3>Domains Table</h3>
<table class="domains">
<thead>
<tr>
<th class="three">IP</th>
<th class="three">Domain</th>
<!-- <th class="three">Del</th> -->
</tr>
</thead>
<tbody id="domainsstablebody">
</tbody>
</table>
</div>
<div class="settingrectfooter">
<button id="add_local_domain_button" class="hiddenbutton settingrectfooterbutton">Add Local
Domain</button>
<button id="add_dns_server_button" class="hiddenbutton settingrectfooterbutton">Add DNS
server</button>
<button class="settingrectfooterbutton" id="set_dns_settings">Confirm</button>
</div>
</div>
<!-- DNS settings -->
<!-- ftp settings -->
<div class="settingrect ">
<div class="settingrectheader">
<h2>Ftp</h2>
<div class="checkbox-wrapper-2">
<input type="checkbox" class="sc-gJwTLC ikxBAC" id="ftpenable">
</div>
</div>
<div class="settingrectfooter">
<!-- <button>Add Ftp server</button> -->
<button class="settingrectfooterbutton" id="set_ftp_settings">Confirm</button>
</div>
</div>
<!-- ftp settings -->
<!-- ssh settings -->
<div class="settingrect ">
<div class="settingrectheader">
<h2>SSH</h2>
<div class="checkbox-wrapper-2">
<input type="checkbox" class="sc-gJwTLC ikxBAC" id="sshenable">
</div>
</div>
<div class="settingrectbody" id="sshsettingsbody">
<div style="display:flex;align-items:center;justify-content:space-between;">
<label for="sshportinput" class="forminputlabel">Port</label>
<input type="text" id="sshportinput" class="forminput">
</div>
<table class="sshkeys">
<thead>
<tr>
<th>SSH keys</th>
</tr>
</thead>
<tbody id="sshkeystablebody">
</tbody>
</table>
</div>
<div class="settingrectfooter onebutton">
<button id="add_ssh_key" class="hiddenbutton settingrectfooterbutton">Add SSH key</button>
<button class="settingrectfooterbutton" id="set_ssh_settings">Confirm</button>
</div>
</div>
<!-- ssh settings -->
<!-- Wi-Fi settings -->
<div class="settingrect ">
<div class="settingrectheader">
<h2>WIFI</h2>
<div class="checkbox-wrapper-2">
<input type="checkbox" class="sc-gJwTLC ikxBAC" id="wifistatus">
</div>
</div>
<div class="settingrectbody" id="wifisettingsbody">
<div style="display:flex;align-items:center;justify-content:space-between;">
<label for="SSID" class="forminputlabel">SSID</label>
<input type="text" id="SSID" class="forminput">
</div>
<div style="display:flex;align-items:center;justify-content:space-between;">
<label for="wifipassword" class="forminputlabel">Old password</label>
<button id="showpasswordbutton">Show</button>
<input type="password" id="wifipassword" class="forminput">
</div>
<div style="display:flex;align-items:center;justify-content:space-between;">
<label for="newwifipassword" class="forminputlabel">New password</label>
<button id="shownewpasswordbutton">Show</button>
<input type="password" id="newwifipassword" class="forminput">
</div>
<div style="display:flex;align-items:center;justify-content:space-between;">
<label for="wifichannel" class="forminputlabel">WIFI channel</label>
<select id="wifichannel" class="forminput">
<option class="channeloption" value="1" style="color: black">1</option>
<option class="channeloption" value="6">6</option>
<option class="channeloption" value="11">11</option>
</select>
</div>
<div style="display:flex;align-items:center;justify-content:space-between;">
<label for="wifiqr" class="forminputlabel">Show qr code</label>
<div class="checkbox-wrapper-2">
<input type="checkbox" class="sc-gJwTLC ikxBAC" id="wifiqr">
</div>
<div id="wifiqrimg"></div>
</div>
</div>
<div class="settingrectfooter onebutton">
<button class="settingrectfooterbutton" id="setwifisettings">Confirm</button>
</div>
</div>
<!-- Wi-Fi settings -->
</section>
<!-- syslog block -->
<section class="syslogsection">
<div class="syslogheader">
<h2 class="syslogheader">Syslog</h2>
<button id="openrouterfilter">openrouter</button>
<button id="authservicefilter">auth_service</button>
<button id="refreshbutton">&#8634;</button>
<label for="realtimesyslog">Realtime</label>
<input type="checkbox" id="realtimesyslog">
</div>
<div class="syslogdata"></div>
</section>
<!-- syslog block -->
<section class="infosection">
<div class="inforect">
<label for="infoversion">Version: </label>
<p id="version">0.1.1</p>
</div>
<div class="inforect">
<label for="infouptime">Uptime: </label>
<p id="uptime"></p>
</div>
</section>
</div>
<!-- settings block -->
</section>
<!-- notification block -->
<div class="notificationsection"></div>
<!-- notification block -->
<!-- login form -->
<div class="form loginform">
<form class="formbody loginformbody">
<h1 class="formheader">OpenRouter Login</h1>
<div class="forminputbody">
<label for="loginusernameinput" class="forminputlabel">Username</label>
<input type="text" required id="loginusernameinput" class="forminput">
</div>
<div class="forminputbody">
<label for="loginpasswordinput" class="forminputlabel">Username</label>
<input type="password" required id="loginpasswordinput" class="forminput">
</div>
<div class="forminputbody">
<button class="formbutton">Login</button>
</div>
</form>
</div>
<!-- login form -->
<!-- confirm form -->
<div class="form" id="confirmform">
<div class="formbody confirmformbody">
<h1 class="formheader" id="confirmformheader">Confirm DNS settings?</h1>
<div class="forminputbody confirmform" id="confirmformbuttons">
<button class="formbutton" id="cancel">Cancel</button>
<button class="formbutton" id="confirm">Confirm</button>
</div>
</div>
</div>
<!-- confirm form -->
<!-- loader -->
<div class="loader">
<h1 id="loaderheader">Reboting</h1>
<div class="loadertip">
<div class="progress"></div>
</div>
</div>
<!-- loader -->
<script src="js/header.js"></script>
<script src="js/routes.js"></script>
<script src="js/notification.js"></script>
<script src="js/loader.js"></script>
<script src="js/settings/confirm.js"></script>
<script src="js/settings/telnet.js"></script>
<script src="js/settings/dns.js"></script>
<script src="js/settings/ftp.js"></script>
<script src="js/settings/ssh.js"></script>
<script src="js/settings/wifi.js"></script>
<script src="js/settings/settings.js"></script>
<script src="js/reboot.js"></script>
<script src="js/syslog.js"></script>
<script src="js/info/uptime.js"></script>
<script src="js/login.js"></script>
</body>
</html>
+55
View File
@@ -0,0 +1,55 @@
const settingssection = document.querySelector('.settingssection')
const settingsbutton = document.querySelector('#settingsbutton')
const syslogsection = document.querySelector('.syslogsection')
const syslogbutton = document.querySelector('#syslogbutton')
const infobutton = document.querySelector('#infobutton')
const infosection = document.querySelector('.infosection')
const headermenubutton = document.querySelector('#headermenubutton')
const headerlinks = document.querySelector('.links')
// const header = document.querySelector('.header')
let uptimeintervalid
settingsbutton.addEventListener('click', () => {
settingssection.classList.add('active')
syslogsection.classList.remove('active')
infosection.classList.remove('active')
clearInterval(uptimeintervalid)
get_all_settings()
})
syslogbutton.addEventListener('click', () => {
syslogsection.classList.add('active')
settingssection.classList.remove('active')
infosection.classList.remove('active')
clearInterval(uptimeintervalid)
get_syslog_data()
})
headermenubutton.addEventListener('click', () => {
if (headerlinks.classList.contains('active')) {
headerlinks.classList.remove('active')
return
}
headerlinks.classList.add('active')
})
window.addEventListener('click', (e) => {
if (e.target.id !== "headermenubutton" && !e.target.classList.contains('links')) {
headerlinks.classList.remove('active')
}
})
infobutton.addEventListener('click', () => {
syslogsection.classList.remove('active')
settingssection.classList.remove('active')
infosection.classList.add('active')
uptimeintervalid = setInterval(get_uptime, 1000)
})
// if (window.screenX > 600) {
// header.removeChild(headermenubutton)
// } else {
// header.prepend(headermenubutton)
// }
+23
View File
@@ -0,0 +1,23 @@
const uptime = document.querySelector('#uptime')
const get_uptime = () => {
fetch(routes.uptime()).then(data => data.json()).then(jsondata => {
if (jsondata.uptime.hour === '0' && jsondata.uptime.minute === '0') {
uptime.innerHTML = jsondata.uptime.second + "s "
return
}
if (jsondata.uptime.hour === '0') {
uptime.innerHTML = jsondata.uptime.minute + "m " + jsondata.uptime.second + "s "
return
}
uptime.innerHTML = jsondata.uptime.hour + "h " + jsondata.uptime.minute + "m " + jsondata.uptime.second + "s "
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
window.addEventListener('load', () => {
if (infosection.classList.contains('active')) {
uptimeintervalid = setInterval(get_uptime, 1000)
}
})
+13
View File
@@ -0,0 +1,13 @@
const loader = document.querySelector('.loader')
const loaderheader = document.querySelector('#loaderheader')
const defaultloaderheader = ""
const start_loader = (header = defaultloaderheader) => {
loaderheader.innerHTML = header
loader.classList.add('active')
}
const stop_loader = () => {
loader.classList.remove('active')
}
+68
View File
@@ -0,0 +1,68 @@
const loginform = document.querySelector('.loginform')
const loginformbody = document.querySelector('.loginformbody')
const loginusername = document.querySelector("#loginusernameinput")
const loginpassword = document.querySelector("#loginpasswordinput")
const exitbutton = document.querySelector('.exitbutton')
const adminpanelsection = document.querySelector('.adminpanel')
const headerusername = document.querySelector('.headerusername')
if (localStorage.getItem("token") === null) {
adminpanelsection.classList.remove('active')
loginform.classList.add('active')
} else {
adminpanelsection.classList.add('active')
infosection.classList.add('active')
headerusername.innerHTML = JSON.parse(localStorage.getItem('userdata')).username
}
loginformbody.addEventListener('submit', (e) => {
e.preventDefault()
login(loginusername.value, loginpassword.value)
})
const login = async (username, password) => {
const response = await fetch(routes.login(), {
method: 'POST',
body: `{"username":"${username}","password":"${password}"}`
}).then(data => data.json()).then(jsondata => jsondata).catch((error) => {
if (error.message === "Unexpected end of JSON input") {
notification(`Ошибка на сервере: Создайте файл users.json и запишите в него первого пользователя`, "error")
} else {
notification(`Ошибка на сервере: ${error}`, "error")
}
})
if (response.status === "403") {
notification("Неправильный логин или пароль", "error")
}
if (response.token) {
notification("Успешно", "success")
loginform.classList.remove("active")
localStorage.setItem("token", response.token)
get_all_settings()
adminpanelsection.classList.add('active')
await get_user_data()
loginusername.value = ""
loginpassword.value = ""
settingssection.classList.add('active')
}
}
const get_user_data = async () => {
const response = await fetch(routes.user(), {
method: "POST",
body: `{"token":"${localStorage.getItem("token")}"}`
}).then(data => data.json()).then(jsondata => jsondata).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
if (response.id) {
headerusername.innerHTML = response.username
localStorage.setItem("userdata", JSON.stringify(response))
}
}
exitbutton.addEventListener('click', () => {
localStorage.clear()
loginform.classList.add('active')
notification('Вы вышли', "success")
adminpanelsection.classList.remove('active')
})
+40
View File
@@ -0,0 +1,40 @@
const notificationsection = document.querySelector('.notificationsection')
// const notificationtext = document.querySelector('.notificationtext')
const notification = (text, type) => {
const notificationbox = document.createElement('div')
const notificationtextbox = document.createElement('div')
const notificationtext = document.createElement('h3')
notificationtext.classList.add('notificationtext')
notificationtextbox.append(notificationtext)
notificationtextbox.classList.add('notificationtextbox')
notificationbox.append(notificationtextbox)
notificationbox.classList.add('notification')
notificationbox.addEventListener('click', () => {
notificationbox.classList.remove('active')
})
notificationsection.append(notificationbox)
if (type === "error") {
notificationbox.classList.remove('success')
notificationbox.classList.add('error')
} else {
notificationbox.classList.remove('error')
notificationbox.classList.add('success')
}
notificationtext.innerHTML = text
setTimeout(() => {
notificationbox.classList.add('active')
}, 300)
setTimeout(() => {
notificationbox.classList.remove('active')
setTimeout(() => {
notificationsection.removeChild(notificationbox)
}, 200)
}, 3000)
}
// const closenotification = () => {
// notificationbox.classList.remove('active')
// }
// notificationbox.addEventListener('click', closenotification)
+28
View File
@@ -0,0 +1,28 @@
const rebootbutton = document.querySelector('#rebootbutton')
rebootbutton.addEventListener('click', () => {
if (confirm("Confirm reboot?")) {
reboot()
}
})
const reboot = () => {
loader.classList.add('active')
fetch(routes.reboot(), {
method: 'POST',
body: `{"token":"${localStorage.getItem("token")}"}`
}).then(data => data.json()).then(jsondata => {
}).catch((error) => {
start_loader("Rebooting")
setTimeout(waitreboot, 2000)
})
}
const waitreboot = () => {
fetch(routes.uptime()).then(res => res.json()).then(jsondata => {
stop_loader()
}).catch((error) => {
waitreboot()
})
}
+43
View File
@@ -0,0 +1,43 @@
const host = window.location.origin
const prefix = 'api'
const routes = {
login: () => [host, prefix, 'token'].join('/'),
user: () => [host, prefix, 'users', 'user'].join('/'),
telnet_status: () => [host, prefix, 'settings', 'telnet', 'get'].join('/'),
telnet_status_set: () => [host, prefix, 'settings', 'telnet', 'set'].join('/'),
telnet_port_get: () => [host, prefix, 'settings', 'telnet', 'port', 'get'].join('/'),
telnet_port_set: () => [host, prefix, 'settings', 'telnet', 'port', 'set'].join('/'),
ssh_status_get: () => [host, prefix, 'settings', 'ssh', 'status', 'get'].join('/'),
ssh_status_set: () => [host, prefix, 'settings', 'ssh', 'status', 'set'].join('/'),
ssh_keys_get: () => [host, prefix, 'settings', 'ssh', 'keys', 'get'].join('/'),
ssh_keys_set: () => [host, prefix, 'settings', 'ssh', 'keys', 'set'].join('/'),
ssh_port_get: () => [host, prefix, 'settings', 'ssh', 'port', 'get'].join('/'),
ssh_port_set: () => [host, prefix, 'settings', 'ssh', 'port', 'set'].join('/'),
dns_status: () => [host, prefix, 'settings', 'dns', 'get'].join('/'),
dns_status_set: () => [host, prefix, 'settings', 'dns', 'set'].join('/'),
dns_servers_get: () => [host, prefix, 'settings', 'dns', 'servers', 'get'].join('/'),
dns_servers_set: () => [host, prefix, 'settings', 'dns', 'servers', 'set'].join('/'),
dns_local_domains_get: () => [host, prefix, 'settings', 'dns', 'domains', 'get'].join('/'),
dns_local_domains_set: () => [host, prefix, 'settings', 'dns', 'domains', 'set'].join('/'),
ftp_status: () => [host, prefix, 'settings', 'ftp', 'get'].join('/'),
ftp_status_set: () => [host, prefix, 'settings', 'ftp', 'set'].join('/'),
wifi_status_get: () => [host, prefix, 'settings', 'wifi', 'status', 'get'].join('/'),
wifi_status_set: () => [host, prefix, 'settings', 'wifi', 'status', 'set'].join('/'),
wifi_name_get: () => [host, prefix, 'settings', 'wifi', 'name', 'get'].join('/'),
wifi_name_set: () => [host, prefix, 'settings', 'wifi', 'name', 'set'].join('/'),
wifi_password_get: () => [host, prefix, 'settings', 'wifi', 'password', 'get'].join('/'),
wifi_password_set: () => [host, prefix, 'settings', 'wifi', 'password', 'set'].join('/'),
wifi_qr_get: () => [host, prefix, 'settings', 'wifi', 'qr', 'get'].join('/'),
wifi_channel_get: () => [host, prefix, 'settings', 'wifi', 'channel', 'get'].join('/'),
wifi_channel_set: () => [host, prefix, 'settings', 'wifi', 'channel', 'set'].join('/'),
reboot: () => [host, prefix, 'reboot'].join('/'),
syslog: () => [host, prefix, 'syslog'].join('/'),
uptime: () => [host, prefix, 'uptime'].join('/'),
}
+33
View File
@@ -0,0 +1,33 @@
const confirmform = document.querySelector('#confirmform')
const confirmformheader = document.querySelector('#confirmformheader')
const cancelbutton = document.querySelector('#cancel')
const confirmformbuttons = document.querySelector('#confirmformbuttons')
const defaultcancelreqfunc = () => {
confirmform.classList.remove('active')
}
const get_confirm_form = (header, reqfunc = defaultcancelreqfunc, cancelreqfunc = defaultcancelreqfunc) => {
confirmformheader.innerHTML = header
confirmform.classList.add('active')
var confirmbutton = document.createElement('button')
confirmbutton.classList.add('formbutton')
confirmbutton.id = "confirm"
confirmbutton.innerHTML = "Confirm"
confirmbutton.addEventListener('click', () => {
reqfunc()
confirmform.classList.remove('active')
})
confirmformbuttons.replaceChild(confirmbutton, document.querySelector('#confirm'))
var cancelbutton = document.createElement('button')
cancelbutton.classList.add('formbutton')
cancelbutton.id = "cancel"
cancelbutton.innerHTML = "Cancel"
cancelbutton.addEventListener('click', () => {
cancelreqfunc()
confirmform.classList.remove('active')
})
confirmformbuttons.replaceChild(cancelbutton, document.querySelector('#cancel'))
}
+197
View File
@@ -0,0 +1,197 @@
const dnsenabled = document.querySelector('#dnsenable')
const setdnssettingsbutton = document.querySelector('#set_dns_settings')
const dnssettingbody = document.querySelector('#dnssettingsbody')
const dnsserverstablebody = document.querySelector('#dnsserverstablebody')
const adddnsserverbutton = document.querySelector('#add_dns_server_button')
const localdomainstablebody = document.querySelector('#domainsstablebody')
const addlocaldomainbutton = document.querySelector('#add_local_domain_button')
let dnsservers = []
let localdomains = []
const get_dns_enabled_status = () => {
fetch(routes.dns_status(), {
method: 'POST',
body: `{"token":"${localStorage.getItem("token")}"}`
}).then(res => res.json()).then(jsondata => {
if (jsondata.enabled === '1') {
dnsenabled.checked = true
dnssettingbody.classList.add('active')
adddnsserverbutton.classList.add('active')
addlocaldomainbutton.classList.add('active')
return;
} else {
adddnsserverbutton.parentElement.classList.add('onebutton')
}
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
const set_dns_enabled_status = () => {
fetch(routes.dns_status_set(), {
method: 'POST',
body: `{"token":"${localStorage.getItem("token")}","enabled":"${dnsenabled.checked ? 1 : 0}"}`
}).then(res => res.json()).then(jsondata => {
if (jsondata.enabled === '1') {
dnsenabled.checked = true
dnssettingbody.classList.add('active')
adddnsserverbutton.classList.add('active')
}
notification("Настройки dns сохранены", "success")
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
const set_dns_settings = () => {
set_dns_enabled_status()
if (dnsenabled.checked) {
set_dns_server()
set_local_domains()
}
}
setdnssettingsbutton.addEventListener('click', () => {
if (confirm("Confirm DNS settings?")) {
set_dns_settings()
}
})
dnsenabled.addEventListener('click', () => {
if (dnsenabled.checked) {
dnssettingbody.classList.add('active')
adddnsserverbutton.classList.add('active')
addlocaldomainbutton.classList.add('active')
adddnsserverbutton.parentElement.classList.remove('onebutton')
get_dns_server()
} else {
dnssettingbody.classList.remove('active')
adddnsserverbutton.classList.remove('active')
addlocaldomainbutton.classList.remove('active')
adddnsserverbutton.parentElement.classList.add('onebutton')
}
})
const get_dns_server = () => {
fetch(routes.dns_servers_get(), {
method: 'POST',
body: `{"token":"${localStorage.getItem("token")}"}`
}).then(res => res.json()).then(jsondata => {
dnsservers = jsondata.servers
dnsserverstablebody.innerHTML = ""
for (const server in jsondata.servers) {
dnsserverstablebody.innerHTML += `<tr>
<th class="one">
${jsondata.servers[server]}
<button class="deldnsserverbutton" id="${jsondata.servers[server]}">Del</button>
</th>
</tr>`
}
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
const set_dns_server = () => {
start_loader("Load DNS")
fetch(routes.dns_servers_set(), {
method: 'POST',
body: `{"token":"${localStorage.getItem('token')}","servers":${JSON.stringify(dnsservers)}}`
}).then(data => data.json()).then(jsondata => {
stop_loader()
if (jsondata.success) {
get_dns_server()
notification("Настройки dns сохранены", "success")
} else {
notification("Неизвестная ошибка", "error")
}
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
adddnsserverbutton.addEventListener('click', () => {
const dnsserver = prompt('Get your DNS server:')
if (dnsserver === null) return
if (confirm('Confirm DNS settings? (add DNS server)')) {
dnsservers.push(dnsserver)
set_dns_server()
}
})
dnsserverstablebody.addEventListener('click', (e) => {
if (e.target.classList.contains('deldnsserverbutton')) {
dnsservers.splice(dnsservers.indexOf(e.target.id), 1)
if (confirm(`Confirm DNS settings? (delete DNS server: ${e.target.id})`)) {
set_dns_server()
}
get_dns_server()
}
})
// ---------------------- local domains ---------------------------
const get_local_domains = () => {
fetch(routes.dns_local_domains_get(), {
method: 'POST',
body: `{"token":"${localStorage.getItem('token')}"}`
}).then(data => data.json()).then(jsondata => {
localdomains = jsondata.domains
localdomainstablebody.innerHTML = ""
for (const domain in jsondata.domains) {
localdomainstablebody.innerHTML += `<tr>
<th class="three">${jsondata.domains[domain].ip}</th>
<th class="three" style="display:flex;align-items:center;justify-content:space-between;width:100%">
${jsondata.domains[domain].domain}
<button class="deldomain" id="${jsondata.domains[domain].domain}">Del</button>
</th>
</tr>`
}
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
const set_local_domains = (domains = localdomains) => {
start_loader()
fetch(routes.dns_local_domains_set(), {
method: 'POST',
body: `{"token":"${localStorage.getItem('token')}","domains":${JSON.stringify(domains)}}`
}).then(data => data.json()).then(jsondata => {
stop_loader()
if (jsondata.success) {
get_local_domains()
notification("Настройки dns сохранены", "success")
} else {
notification("Неизвестная ошибка", "error")
}
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
addlocaldomainbutton.addEventListener('click', () => {
const domainip = prompt('Get localdomain IP:')
if (domainip === null) return
const domain = prompt('Get domain:')
if (domainip === null || domain === null) return
if (confirm(`Confirm DNS settings? (Add Local Domain: ${domainip} ${domain})`)) {
localdomains.push({ "ip": domainip, "domain": domain })
set_local_domains()
}
})
localdomainstablebody.addEventListener('click', (e) => {
if (e.target.classList.contains('deldomain')) {
localdomains.splice(localdomains.indexOf(localdomains.find(dom => dom.domain === e.target.id)), 1)
if (confirm(`Confirm DNS settings? (delete Local Domain: ${e.target.id})`)) {
set_local_domains()
}
get_local_domains()
}
})
// ------------------------- local domains end --------------------
+38
View File
@@ -0,0 +1,38 @@
const ftpenabled = document.querySelector('#ftpenable')
const setftpsettingsbutton = document.querySelector('#set_ftp_settings')
const get_ftp_enabled_status = () => {
fetch(routes.ftp_status(), {
method: 'POST',
body: `{"token":"${localStorage.getItem("token")}"}`
}).then(res => res.json()).then(jsondata => {
if (jsondata.enabled === '1') {
ftpenabled.checked = true
// ftpsettingbody.classList.add('active')
return;
}
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
const set_ftp_enabled_status = () => {
fetch(routes.ftp_status_set(), {
method: 'POST',
body: `{"token":"${localStorage.getItem("token")}","enabled":"${ftpenabled.checked ? 1 : 0}"}`
}).then(res => res.json()).then(jsondata => {
if (jsondata.enabled === '1') {
ftpenabled.checked = true
// ftpsettingbody.classList.add('active')
}
notification("Настройки ftp сохранены", "success")
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
setftpsettingsbutton.addEventListener('click', () => {
if (confirm("Confirm ftp settings?")) {
set_ftp_enabled_status()
}
})
+19
View File
@@ -0,0 +1,19 @@
const get_all_settings = () => {
get_dns_enabled_status()
get_dns_server()
get_local_domains()
get_ftp_enabled_status()
get_telnet_enabled_status()
get_telnet_port()
get_ssh_status()
get_ssh_keys()
get_ssh_port()
get_wifi_status()
get_wifi_name()
get_wifi_channel()
// get_wifi_password()
}
+142
View File
@@ -0,0 +1,142 @@
const sshenable = document.querySelector('#sshenable')
const set_ssh_settings = document.querySelector('#set_ssh_settings')
const sshsettingsbody = document.querySelector('#sshsettingsbody')
const sshkeystablebody = document.querySelector('#sshkeystablebody')
const sshportinput = document.querySelector('#sshportinput')
const add_ssh_key_button = document.querySelector('#add_ssh_key')
let sshkeys = []
// -------------------- SSH status --------------------------------
const get_ssh_status = () => {
fetch(routes.ssh_status_get(), {
method: 'POST',
body: `{"token":"${localStorage.getItem("token")}"}`
}).then(data => data.json()).then(jsondata => {
if (jsondata.status === '1') {
sshenable.checked = true
sshsettingsbody.classList.add('active')
add_ssh_key_button.classList.add('active')
add_ssh_key_button.parentElement.classList.remove('onebutton')
}
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
const set_ssh_status = () => {
fetch(routes.ssh_status_set(), {
method: 'POST',
body: `{"token":"${localStorage.getItem("token")}","status":"${sshenable.checked ? 1 : 0}"}`
}).then(res => res.json()).then(jsondata => {
if (jsondata.status === '1') {
sshenable.checked = true
// telnetsettingbody.classList.add('active')
}
notification("Настройки SSH сохранены", "success")
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
// -------------------------------- end SSH status ---------------------------------------
set_ssh_settings.addEventListener('click', () => {
if (confirm("Confirm SSH settings?")) {
set_ssh_status()
set_ssh_port()
}
})
sshenable.addEventListener('click', () => {
if (sshenable.checked) {
sshsettingsbody.classList.add('active')
add_ssh_key_button.classList.add('active')
add_ssh_key_button.parentElement.classList.remove('onebutton')
return
}
sshsettingsbody.classList.remove('active')
add_ssh_key_button.classList.remove('active')
add_ssh_key_button.parentElement.classList.add('onebutton')
})
// -------------------- SSH keys ---------------------------------
const get_ssh_keys = () => {
fetch(routes.ssh_keys_get(), {
method: 'POST',
body: `{"token":"${localStorage.getItem("token")}"}`
}).then(data => data.json()).then(jsondata => {
sshkeys = jsondata.keys
sshkeystablebody.innerHTML = ""
for (const key in sshkeys) {
sshkeystablebody.innerHTML += `<tr>
<td class="one" style="flex-direction:column;align-items:start;">
${sshkeys[key]}
<button class="delsshkeybutton" id="${key}">Del</button>
</td>
</tr>`
}
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
const set_ssh_keys = () => {
start_loader()
fetch(routes.ssh_keys_set(), {
method: 'POST',
body: `{"token":"${localStorage.getItem("token")}","keys":${JSON.stringify(sshkeys)}}`
}).then(data => data.json()).then(jsondata => {
stop_loader()
if (jsondata.success) {
get_ssh_keys()
notification("Настройки SSH сохранены", "success")
} else {
notification("Неизвестная ошибка", "error")
}
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
// ------------------- end SSH keys ------------------------------
sshkeystablebody.addEventListener('click', (e) => {
if (e.target.classList.contains('delsshkeybutton')) {
if (confirm(`Confirm SSH settings?: (delete SSH key)`)) {
sshkeys.splice(e.target.id)
set_ssh_keys()
}
}
})
add_ssh_key_button.addEventListener('click', () => {
const sshkey = prompt('Get your SSH key:')
if (sshkey === null) return
if (confirm('Confirm SSH settings? (add SSH key)')) {
sshkeys.push(sshkey)
set_ssh_keys()
}
})
// -------------------- SSH port ----------------------
const get_ssh_port = () => {
fetch(routes.ssh_port_get(), {
method: 'POST',
body: `{"token":"${localStorage.getItem("token")}"}`
}).then(data => data.json()).then(jsondata => {
sshportinput.value = jsondata.port
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
const set_ssh_port = () => {
fetch(routes.ssh_port_set(), {
method: 'POST',
body: `{"token":"${localStorage.getItem("token")}","port":"${sshportinput.value}"}`
}).then(data => data.json()).then(jsondata => {
sshportinput.value = jsondata.port
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
// ------------------- end SSH port -------------------
+90
View File
@@ -0,0 +1,90 @@
const telnetenabled = document.querySelector('#telnetenable')
const telnetsettingbody = document.querySelector('.telnetsettingbody')
const settelnetsettingsbutton = document.querySelector('#set_telnet_settings')
// const addtelnetuserbutton = document.querySelector('#add_telnet_user_button')
const telnetportinput = document.querySelector('#telnetportinput')
const get_telnet_enabled_status = () => {
fetch(routes.telnet_status(), {
method: 'POST',
body: `{"token":"${localStorage.getItem("token")}"}`
}).then(res => res.json()).then(jsondata => {
if (jsondata.enabled === '1') {
telnetenabled.checked = true
// addtelnetuserbutton.classList.add('active')
// addtelnetuserbutton.parentElement.classList.remove('onebutton')
telnetsettingbody.classList.add('active')
return;
} else {
// addtelnetuserbutton.parentElement.classList.add('onebutton')
}
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
const set_telnet_enabled_status = () => {
fetch(routes.telnet_status_set(), {
method: 'POST',
body: `{"token":"${localStorage.getItem("token")}","enabled":"${telnetenabled.checked ? 1 : 0}"}`
}).then(res => res.json()).then(jsondata => {
if (jsondata.enabled === '1') {
telnetenabled.checked = true
// telnetsettingbody.classList.add('active')
}
notification("Настройки telnet сохранены", "success")
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
telnetenabled.addEventListener('click', () => {
if (telnetenabled.checked) {
// addtelnetuserbutton.classList.add('active')
// addtelnetuserbutton.parentElement.classList.remove('onebutton')
telnetsettingbody.classList.add('active')
} else {
telnetsettingbody.classList.remove('active')
// addtelnetuserbutton.classList.remove('active')
// addtelnetuserbutton.parentElement.classList.add('onebutton')
}
})
const set_telnet_settings = () => {
set_telnet_enabled_status()
if (telnetenabled.checked) {
set_telnet_port()
}
}
settelnetsettingsbutton.addEventListener('click', () => {
if (confirm("Confirm telnet settings?")) {
set_telnet_settings()
}
})
const get_telnet_port = () => {
fetch(routes.telnet_port_get(), {
method: 'POST',
body: `{"token":"${localStorage.getItem("token")}"}`
}).then(data => data.json()).then(jsondata => {
telnetportinput.value = jsondata.port
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
const set_telnet_port = () => {
start_loader()
fetch(routes.telnet_port_set(), {
method: 'POST',
body: `{"token":"${localStorage.getItem("token")}","port":"${telnetportinput.value}"}`
}).then(data => data.json()).then(jsondata => {
stop_loader()
telnetportinput.value = jsondata.port
}).catch((error) => {
stop_loader()
notification(`Ошибка на сервере: ${error}`, "error")
})
}
+188
View File
@@ -0,0 +1,188 @@
const wifistatus = document.querySelector('#wifistatus')
const wifisettingsbody = document.querySelector('#wifisettingsbody')
const wifissid = document.querySelector('#SSID')
const wifipassword = document.querySelector('#wifipassword')
const showpasswordbutton = document.querySelector('#showpasswordbutton')
const setwifisettings = document.querySelector('#setwifisettings')
const shownewpasswordbutton = document.querySelector('#shownewpasswordbutton')
const newwifipassword = document.querySelector('#newwifipassword')
const wifiqr = document.querySelector('#wifiqr')
const wifiqrimg = document.querySelector("#wifiqrimg")
const channelselect = document.querySelector('#wifichannel')
let old_wifi_name = ""
const get_wifi_status = () => {
fetch(routes.wifi_status_get(), {
method: 'POST',
body: `{"token":"${localStorage.getItem('token')}"}`
}).then(data => data.json()).then(jsondata => {
if (jsondata.status == "1") {
wifistatus.checked = true
wifisettingsbody.classList.add('active')
} else {
wifistatus.checked = false
}
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
const set_wifi_status = () => {
fetch(routes.wifi_status_set(), {
method: 'POST',
body: `{"token":"${localStorage.getItem('token')}","status":"${wifistatus.checked ? "1" : "0"}"}`
}).then(data => data.json()).then(jsondata => {
if (jsondata.status === "1") {
wifistatus.checked = true
wifisettingsbody.classList.add('active')
notification("Настройки WIFI оспешно сорранены", "success")
return
}
wifistatus.checked = false
wifisettingsbody.classList.remove('active')
notification("Настройки WIFI оспешно сорранены", "success")
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
const get_wifi_name = () => {
fetch(routes.wifi_name_get(), {
method: 'POST',
body: `{"token":"${localStorage.getItem('token')}"}`
}).then(data => data.json()).then(jsondata => {
wifissid.value = jsondata.name
old_wifi_name = jsondata.name
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
const set_wifi_name = () => {
fetch(routes.wifi_name_set(), {
method: 'POST',
body: `{"token":"${localStorage.getItem('token')}","name":"${wifissid.value}"}`
}).then(data => data.json()).then(jsondata => {
wifissid.value = jsondata.name
old_wifi_name = jsondata.name
notification("Имя WIFI оспешно сорранено", "success")
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
const get_wifi_password = () => {
fetch(routes.wifi_password_get(), {
method: 'POST',
body: `{"token":"${localStorage.getItem('token')}"}`
}).then(data => data.json()).then(jsondata => {
wifipassword.value = jsondata.password
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
const set_wifi_password = () => {
fetch(routes.wifi_password_set(), {
method: 'POST',
body: `{"token":"${localStorage.getItem('token')}","password":"${wifipassword.value}","newpassword":"${newwifipassword.value}"}`
}).then(data => data.json()).then(jsondata => {
if (jsondata.status === "reject") {
notification("Неверный пароль", "error")
return
}
notification("Пароль WIFI оспешно сорранен", "success")
wifipassword.value = ""
newwifipassword.value = ""
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
const set_wifi_settings = () => {
if (confirm("Confirm wifi settings?")) {
start_loader()
set_wifi_status()
if (wifistatus.checked) {
set_wifi_channel()
if (old_wifi_name !== wifissid.value) {
set_wifi_name()
}
if (wifipassword.value !== "" && newwifipassword.value !== "") {
set_wifi_password()
}
}
stop_loader()
}
}
setwifisettings.addEventListener('click', set_wifi_settings)
wifistatus.addEventListener('click', () => {
if (wifistatus.checked) {
wifisettingsbody.classList.add('active')
return
}
wifisettingsbody.classList.remove('active')
})
showpasswordbutton.addEventListener('click', () => {
if (wifipassword.type == "password") {
wifipassword.type = "text"
return
}
wifipassword.type = "password"
})
shownewpasswordbutton.addEventListener('click', () => {
if (newwifipassword.type == "password") {
newwifipassword.type = "text"
return
}
newwifipassword.type = "password"
})
const get_wifi_qr_code = () => {
fetch(routes.wifi_qr_get(), {
method: 'POST',
body: `{"token":"${localStorage.getItem('token')}"}`
}).then(data => data.text()).then(svgdata => {
wifiqrimg.innerHTML = svgdata
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
wifiqr.addEventListener('click', () => {
if (wifiqr.checked) {
get_wifi_qr_code()
wifiqrimg.innerHTML =
wifiqrimg.classList.add('active')
return
}
wifiqrimg.classList.remove('active')
wifiqrimg.innerHTML = ""
})
const get_wifi_channel = () => {
fetch(routes.wifi_channel_get(), {
method: 'POST',
body: `{"token":"${localStorage.getItem('token')}"}`
}).then(data => data.json()).then(jsondata => {
channelselect.value = jsondata.channel
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
const set_wifi_channel = () => {
fetch(routes.wifi_channel_set(), {
method: 'POST',
body: `{"token":"${localStorage.getItem('token')}","channel":"${channelselect.value}"}`
}).then(data => data.json()).then(jsondata => {
channelselect.value = jsondata.channel
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
+84
View File
@@ -0,0 +1,84 @@
const syslogdata = document.querySelector('.syslogdata')
const refreshbutton = document.querySelector('#refreshbutton')
const openrouterfilter = document.querySelector('#openrouterfilter')
const authservicefilter = document.querySelector('#authservicefilter')
const realtimesyslogchekbox = document.querySelector('#realtimesyslog')
let openrouterfilterenable = false
let authservicefilerenable = false
const get_syslog_data = () => {
fetch(routes.syslog(), {
method: 'GET',
// body: `{"token":"${localStorage.getItem("token")}"}`
}).then(data => data.text()).then(textdata => {
if (openrouterfilterenable) {
openrouterfilterfunc(textdata)
return
}
if (authservicefilerenable) {
authservicefilterfunc(textdata)
return
}
syslogdata.innerHTML = textdata.replace(/\n/g, '<br>')
}).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
}
refreshbutton.addEventListener('click', () => {
openrouterfilterenable = false
authservicefilerenable = false
get_syslog_data()
})
openrouterfilter.addEventListener('click', () => {
openrouterfilterenable = true
get_syslog_data()
})
authservicefilter.addEventListener('click', () => {
authservicefilerenable = true
openrouterfilterenable = false
get_syslog_data()
})
const openrouterfilterfunc = (textdata) => {
let syslogalldata = textdata.replace(/\n/g, '<br>')
syslogalldata = syslogalldata.split("<br>")
syslogalldata = syslogalldata.filter(data => {
return data.includes("openrouter:")
})
syslogdata.innerHTML = ""
for (const data in syslogalldata) {
syslogdata.innerHTML += syslogalldata[data] + "<br>"
}
return
}
const authservicefilterfunc = (textdata) => {
let syslogalldata = textdata.replace(/\n/g, '<br>')
syslogalldata = syslogalldata.split("<br>")
syslogalldata = syslogalldata.filter(data => {
return data.includes("auth_service:")
})
syslogdata.innerHTML = ""
for (const data in syslogalldata) {
syslogdata.innerHTML += syslogalldata[data] + "<br>"
}
return
}
let syslogRealtimeIntervalId
realtimesyslogchekbox.addEventListener('click', () => {
if (realtimesyslogchekbox.checked) {
syslogRealtimeIntervalId = setInterval(get_syslog_data, 1000)
// let socket = new WebSocket("ws://192.168.122.76/syslog");
// socket.onmessage = function(event) {
// console.log(event.data)
// };
} else {
clearInterval(syslogRealtimeIntervalId)
}
})