| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862 |
- #include "api_server.h"
- #include "../auth/auth.h"
- #include "../files/files.h"
- #include "../software/fastweb/fastweb.h"
- #include "../software/mysql/mysql.h"
- #include "../software/nginx/nginx.h"
- #include "../software/redis/redis.h"
- #include "../ssl/acme.h"
- #include "../store/store.h"
- #include "../system/metrics.h"
- #include "../system/metrics_history.h"
- #include "../system/process.h"
- #include "../system/shell.h"
- #include "../schedule/schedule.h"
- #include "../selfupdate/selfupdate.h"
- #include "../tasks/tasks.h"
- #include "../utils.h"
- #include "../website/website.h"
- #include "../weblog/weblog.h"
- #include "net/http_center.h"
- #include "net/http_request.h"
- #include "net/http_response.h"
- #include "net/http_router.h"
- #include "net/http_subscribe.h"
- #include "net/http_website.h"
- #include "util/json.h"
- #include <atomic>
- #include <cctype>
- #include <chrono>
- #include <cstdint>
- #include <cstdlib>
- #include <csignal>
- #include <filesystem>
- #include <iostream>
- #include <string>
- #include <thread>
- #include <vector>
- namespace ngs {
- namespace api {
- namespace {
- namespace fs = std::filesystem;
- using ylib::network::http::request;
- using ylib::network::http::response;
- using ylib::network::http::websocket_message;
- std::atomic<bool> g_running{true};
- std::atomic<int> g_signal_count{0};
- ylib::network::http::center* g_center = nullptr;
- void stop_background_services() {
- schedule::stop();
- system::shell_shutdown();
- weblog::stop();
- system::history_stop();
- tasks::stop();
- }
- void on_signal(int) {
- // First signal: request graceful shutdown. Second: force-exit in case
- // close()/join is stuck (e.g. listen failed then center->close hangs).
- const int n = g_signal_count.fetch_add(1, std::memory_order_relaxed) + 1;
- g_running.store(false, std::memory_order_relaxed);
- if (n >= 2) {
- _Exit(1);
- }
- }
- void install_signal_handlers() {
- struct sigaction sa {};
- sa.sa_handler = on_signal;
- sigemptyset(&sa.sa_mask);
- sa.sa_flags = 0; // interrupt blocking sleeps (do not set SA_RESTART)
- sigaction(SIGINT, &sa, nullptr);
- sigaction(SIGTERM, &sa, nullptr);
- }
- ylib::json parse_body(request* req) {
- if (!req) {
- return ylib::json();
- }
- const std::string body = req->body().to_string();
- if (body.empty()) {
- return ylib::json();
- }
- try {
- return ylib::json::from(body);
- } catch (...) {
- return ylib::json();
- }
- }
- std::string json_str(const ylib::json& j, const std::string& key,
- const std::string& def = "") {
- if (j.is_empty() || !j.exist(key)) {
- return def;
- }
- return j[key].to<std::string>(true);
- }
- bool json_bool(const ylib::json& j, const std::string& key, bool def = false) {
- if (j.is_empty() || !j.exist(key)) {
- return def;
- }
- return j[key].to<bool>(true);
- }
- int json_int(const ylib::json& j, const std::string& key, int def = 0) {
- if (j.is_empty() || !j.exist(key)) {
- return def;
- }
- return j[key].to<int32>(true);
- }
- int hex_nibble(char c) {
- if (c >= '0' && c <= '9') {
- return c - '0';
- }
- if (c >= 'a' && c <= 'f') {
- return c - 'a' + 10;
- }
- if (c >= 'A' && c <= 'F') {
- return c - 'A' + 10;
- }
- return -1;
- }
- // ylib get_url_param 不解码,需自行处理 %XX / +
- std::string url_decode(const std::string& in) {
- std::string out;
- out.reserve(in.size());
- for (size_t i = 0; i < in.size(); ++i) {
- const char c = in[i];
- if (c == '+') {
- out.push_back(' ');
- continue;
- }
- if (c == '%' && i + 2 < in.size()) {
- const int hi = hex_nibble(in[i + 1]);
- const int lo = hex_nibble(in[i + 2]);
- if (hi >= 0 && lo >= 0) {
- out.push_back(static_cast<char>((hi << 4) | lo));
- i += 2;
- continue;
- }
- }
- out.push_back(c);
- }
- return out;
- }
- std::string url_param(request* req, const std::string& key,
- const std::string& def = "") {
- if (!req) {
- return def;
- }
- std::string value;
- if (req->get_url_param(key, value) && !value.empty()) {
- return url_decode(value);
- }
- return def;
- }
- uint64_t parse_u64(const std::string& s, uint64_t def = 0) {
- if (s.empty()) {
- return def;
- }
- try {
- size_t idx = 0;
- const unsigned long long v = std::stoull(s, &idx, 10);
- if (idx == 0) {
- return def;
- }
- return static_cast<uint64_t>(v);
- } catch (...) {
- return def;
- }
- }
- std::string trim_ascii(const std::string& s) {
- size_t b = 0;
- while (b < s.size() && (s[b] == ' ' || s[b] == '\t')) {
- ++b;
- }
- size_t e = s.size();
- while (e > b && (s[e - 1] == ' ' || s[e - 1] == '\t')) {
- --e;
- }
- return s.substr(b, e - b);
- }
- // Prefer proxy headers when present; otherwise TCP peer address.
- std::string request_client_ip(request* req) {
- if (!req) {
- return "";
- }
- std::string v;
- if (req->header("X-Real-IP", v) || req->header("x-real-ip", v)) {
- v = trim_ascii(v);
- if (!v.empty()) {
- return v;
- }
- }
- if (req->header("X-Forwarded-For", v) ||
- req->header("x-forwarded-for", v)) {
- const auto comma = v.find(',');
- v = trim_ascii(comma == std::string::npos ? v : v.substr(0, comma));
- if (!v.empty()) {
- return v;
- }
- }
- try {
- return trim_ascii(req->remote().address);
- } catch (...) {
- return "";
- }
- }
- std::string b64_decode(const std::string& in) {
- static const int8_t kTable[256] = {
- -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
- -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
- -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,
- 52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,
- -1, 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,-1,-1,-1,-1,-1,
- -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,
- 41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1};
- std::string out;
- out.reserve(in.size() * 3 / 4);
- int val = 0, valb = -8;
- for (unsigned char c : in) {
- if (c == '=' || c == '\n' || c == '\r' || c == ' ') {
- continue;
- }
- const int8_t d = kTable[c];
- if (d < 0) {
- continue;
- }
- val = (val << 6) + d;
- valb += 6;
- if (valb >= 0) {
- out.push_back(static_cast<char>((val >> valb) & 0xFF));
- valb -= 8;
- }
- }
- return out;
- }
- void reply_ok(response* resp, const ylib::json& data = ylib::json(),
- const std::string& msg = "ok") {
- ylib::json out;
- out["code"] = 200;
- out["msg"] = msg;
- out["data"] = data;
- resp->send(out);
- }
- void reply_err(response* resp, const std::string& msg, int code = -1) {
- ylib::json out;
- // ylib: operator=(int32) 会先转 uint64,负数会变成超大数;用 double 保留 -1 等错误码
- out["code"] = static_cast<double>(code);
- out["msg"] = msg;
- out["data"] = ylib::json();
- resp->send(out);
- }
- bool require_method(request* req, response* resp, const std::string& method) {
- if (req->method() == method) {
- return true;
- }
- reply_err(resp, "method not allowed, expect " + method, 405);
- return false;
- }
- std::string request_cookie(request* req) {
- if (!req) {
- return "";
- }
- std::string v;
- if (req->header("Cookie", v) || req->header("cookie", v)) {
- return v;
- }
- return "";
- }
- std::string request_session_token(request* req) {
- return auth::session_from_cookie(request_cookie(req));
- }
- bool request_authed(request* req, std::string* username = nullptr) {
- return auth::session_valid(request_session_token(req), username);
- }
- void set_session_cookie(response* resp, const std::string& token, bool clear) {
- if (!resp || !resp->headers()) {
- return;
- }
- if (clear || token.empty()) {
- (*resp->headers())["Set-Cookie"] =
- "ngs_session=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0";
- return;
- }
- (*resp->headers())["Set-Cookie"] =
- "ngs_session=" + token +
- "; Path=/; HttpOnly; SameSite=Lax; Max-Age=604800";
- }
- bool require_auth(request* req, response* resp) {
- if (request_authed(req)) {
- return true;
- }
- reply_err(resp, "未登录或会话已过期", 401);
- return false;
- }
- using Handler = void (*)(request*, response*);
- void reg(ylib::network::http::router* router, const std::string& path,
- Handler handler, bool auth_required = true) {
- router->subscribe()->add(
- path, "",
- [handler, auth_required](request* req, response* resp, websocket_message*,
- const std::string&, const std::string&) {
- if (auth_required && !require_auth(req, resp)) {
- return;
- }
- handler(req, resp);
- });
- }
- // ---- handlers ----
- std::string trim_copy(std::string s) {
- size_t a = 0;
- while (a < s.size() &&
- std::isspace(static_cast<unsigned char>(s[a]))) {
- ++a;
- }
- size_t b = s.size();
- while (b > a && std::isspace(static_cast<unsigned char>(s[b - 1]))) {
- --b;
- }
- return s.substr(a, b - a);
- }
- std::string panel_display_name() {
- std::string n = trim_copy(store::get_setting("panel.name", ""));
- if (n.empty()) {
- return "NGS";
- }
- if (n.size() > 64) {
- n.resize(64);
- }
- return n;
- }
- ylib::json settings_json() {
- ylib::json data;
- data["panel_name"] = panel_display_name();
- return data;
- }
- void h_ping(request* req, response* resp) {
- if (!require_method(req, resp, "GET")) {
- return;
- }
- ylib::json data;
- data["name"] = "ngs";
- data["panel_name"] = panel_display_name();
- data["listen"] = std::string(kDefaultListenAddr) + ":" +
- std::to_string(kDefaultListenPort);
- reply_ok(resp, data);
- }
- void h_auth_captcha(request* req, response* resp) {
- if (!require_method(req, resp, "GET")) {
- return;
- }
- const auth::CaptchaImage img = auth::create_captcha();
- if (img.bmp.empty() || img.id.empty()) {
- reply_err(resp, "验证码生成失败", 500);
- return;
- }
- if (resp->headers()) {
- (*resp->headers())["Set-Cookie"] =
- "ngs_captcha=" + img.id +
- "; Path=/; HttpOnly; SameSite=Lax; Max-Age=300";
- (*resp->headers())["Content-Type"] = "image/bmp";
- (*resp->headers())["Cache-Control"] = "no-store, no-cache, must-revalidate";
- (*resp->headers())["Pragma"] = "no-cache";
- }
- resp->send(img.bmp);
- }
- void h_auth_login(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- int64_t retry_after = 0;
- if (auth::login_locked(&retry_after)) {
- const int64_t mins = (retry_after + 59) / 60;
- reply_err(resp,
- "登录失败次数过多,已锁定约 " + std::to_string(mins) +
- " 分钟(重启 NGS 可立即解除)",
- 429);
- return;
- }
- auto body = parse_body(req);
- const std::string username = json_str(body, "username");
- const std::string password = json_str(body, "password");
- const std::string captcha = json_str(body, "captcha");
- if (username.empty() || password.empty()) {
- reply_err(resp, "请输入账号和密码", 400);
- return;
- }
- if (captcha.empty()) {
- reply_err(resp, "请输入验证码", 400);
- return;
- }
- const std::string captcha_id =
- auth::captcha_from_cookie(request_cookie(req));
- if (!auth::consume_captcha(captcha_id, captcha)) {
- reply_err(resp, "验证码错误或已过期", 400);
- return;
- }
- if (!auth::verify(username, password)) {
- auth::record_login_failure();
- if (auth::login_locked(&retry_after)) {
- reply_err(resp,
- "账号或密码错误,已连续失败 3 次,登录锁定 10 分钟"
- "(重启 NGS 可立即解除)",
- 429);
- return;
- }
- reply_err(resp, "账号或密码错误", 401);
- return;
- }
- auth::clear_login_failures();
- const std::string token = auth::create_session(username);
- set_session_cookie(resp, token, false);
- ylib::json data;
- data["username"] = username;
- reply_ok(resp, data, "logged in");
- }
- void h_auth_logout(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- auth::destroy_session(request_session_token(req));
- set_session_cookie(resp, "", true);
- reply_ok(resp, ylib::json(), "logged out");
- }
- void h_auth_me(request* req, response* resp) {
- if (!require_method(req, resp, "GET")) {
- return;
- }
- std::string username;
- if (!request_authed(req, &username)) {
- reply_err(resp, "未登录", 401);
- return;
- }
- ylib::json data;
- data["username"] = username;
- reply_ok(resp, data);
- }
- void reply_task_queued(response* resp, const std::string& task_id) {
- ylib::json data;
- data["task_id"] = task_id;
- data["active"] = tasks::active_count();
- reply_ok(resp, data, "task queued");
- }
- ylib::json task_to_json(const tasks::Task& t) {
- ylib::json item;
- item["id"] = t.id;
- item["type"] = t.type;
- item["title"] = t.title;
- item["status"] = tasks::status_str(t.status);
- item["created_at"] = static_cast<double>(t.created_at);
- item["started_at"] = static_cast<double>(t.started_at);
- item["finished_at"] = static_cast<double>(t.finished_at);
- item["message"] = t.message;
- item["log_lines"] = static_cast<double>(t.log_lines);
- return item;
- }
- void h_tasks_list(request* req, response* resp) {
- if (!require_method(req, resp, "GET")) {
- return;
- }
- ylib::json arr;
- for (const auto& t : tasks::list(false)) {
- arr.push_back(task_to_json(t));
- }
- ylib::json data;
- data["active"] = tasks::active_count();
- data["tasks"] = arr;
- reply_ok(resp, data);
- }
- void h_tasks_log(request* req, response* resp) {
- if (!require_method(req, resp, "GET")) {
- return;
- }
- const std::string id = url_param(req, "id");
- size_t off = 0;
- try {
- off = static_cast<size_t>(std::stoul(url_param(req, "offset", "0")));
- } catch (...) {
- off = 0;
- }
- std::vector<std::string> lines;
- size_t next = 0;
- size_t log_base = 0;
- bool truncated = false;
- tasks::Status st = tasks::Status::Pending;
- std::string message, err;
- if (!tasks::get_logs(id, off, lines, next, log_base, truncated, st, message,
- err)) {
- reply_err(resp, err);
- return;
- }
- ylib::json arr;
- for (const auto& line : lines) {
- arr.push_back(line);
- }
- ylib::json data;
- data["id"] = id;
- data["status"] = tasks::status_str(st);
- data["message"] = message;
- data["offset"] = static_cast<double>(truncated ? log_base : off);
- data["next_offset"] = static_cast<double>(next);
- data["log_base"] = static_cast<double>(log_base);
- data["truncated"] = truncated;
- data["lines"] = arr;
- reply_ok(resp, data);
- }
- void h_tasks_clear(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- tasks::clear_finished();
- ylib::json data;
- data["active"] = tasks::active_count();
- reply_ok(resp, data, "cleared");
- }
- ylib::json schedule_job_to_json(const schedule::Job& j) {
- ylib::json item;
- item["id"] = j.id;
- item["name"] = j.name;
- item["enabled"] = j.enabled;
- item["url"] = j.url;
- item["method"] = j.method;
- item["interval"] = j.interval;
- item["unit"] = j.unit;
- item["timeout_sec"] = j.timeout_sec;
- item["continue_when_busy"] = j.continue_when_busy;
- item["created_ms"] = static_cast<double>(j.created_ms);
- item["next_run_ms"] = static_cast<double>(j.next_run_ms);
- item["last_run_ms"] = static_cast<double>(j.last_run_ms);
- item["last_ok"] = j.last_ok;
- item["last_status"] = j.last_status;
- item["last_error"] = j.last_error;
- item["inflight"] = j.inflight;
- item["interval_ms"] =
- static_cast<double>(schedule::interval_to_ms(j.interval, j.unit));
- return item;
- }
- ylib::json schedule_log_to_json(const schedule::LogEntry& e) {
- ylib::json item;
- item["id"] = static_cast<double>(e.id);
- item["job_id"] = e.job_id;
- item["time_ms"] = static_cast<double>(e.time_ms);
- item["ok"] = e.ok;
- item["status_code"] = e.status_code;
- item["duration_ms"] = static_cast<double>(e.duration_ms);
- item["error"] = e.error;
- item["response_preview"] = e.response_preview;
- return item;
- }
- void h_schedule_jobs(request* req, response* resp) {
- if (req->method() == "GET") {
- ylib::json arr;
- for (const auto& j : schedule::list_jobs()) {
- arr.push_back(schedule_job_to_json(j));
- }
- ylib::json data;
- data["jobs"] = arr;
- reply_ok(resp, data);
- return;
- }
- if (!require_method(req, resp, "POST")) {
- return;
- }
- const ylib::json body = parse_body(req);
- schedule::Job job;
- job.id = json_str(body, "id");
- job.name = json_str(body, "name");
- job.enabled = json_bool(body, "enabled", true);
- job.url = json_str(body, "url");
- job.method = json_str(body, "method", "GET");
- job.interval = json_int(body, "interval", 60);
- job.unit = json_str(body, "unit", "sec");
- job.timeout_sec = json_int(body, "timeout_sec", 30);
- job.continue_when_busy = json_bool(body, "continue_when_busy", false);
- std::string err;
- if (!schedule::upsert_job(job, err)) {
- reply_err(resp, err, 400);
- return;
- }
- reply_ok(resp, schedule_job_to_json(job), "saved");
- }
- void h_schedule_jobs_delete(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- const ylib::json body = parse_body(req);
- const std::string id = json_str(body, "id");
- std::string err;
- if (!schedule::delete_job(id, err)) {
- reply_err(resp, err, 400);
- return;
- }
- reply_ok(resp, ylib::json(), "deleted");
- }
- void h_schedule_jobs_enable(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- const ylib::json body = parse_body(req);
- const std::string id = json_str(body, "id");
- const bool enabled = json_bool(body, "enabled", true);
- std::string err;
- if (!schedule::set_enabled(id, enabled, err)) {
- reply_err(resp, err, 400);
- return;
- }
- schedule::Job job;
- if (!schedule::get_job(id, job, err)) {
- reply_err(resp, err, 400);
- return;
- }
- reply_ok(resp, schedule_job_to_json(job), enabled ? "enabled" : "disabled");
- }
- void h_schedule_jobs_run(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- const ylib::json body = parse_body(req);
- const std::string id = json_str(body, "id");
- std::string err;
- if (!schedule::run_now(id, err)) {
- reply_err(resp, err, 400);
- return;
- }
- reply_ok(resp, ylib::json(), "started");
- }
- void h_schedule_logs(request* req, response* resp) {
- if (req->method() == "GET") {
- const std::string job_id = url_param(req, "job_id");
- int limit = 80;
- try {
- limit = std::stoi(url_param(req, "limit", "80"));
- } catch (...) {
- limit = 80;
- }
- std::vector<schedule::LogEntry> logs;
- std::string err;
- if (!schedule::list_logs(job_id, limit, logs, err)) {
- reply_err(resp, err);
- return;
- }
- ylib::json arr;
- for (const auto& e : logs) {
- arr.push_back(schedule_log_to_json(e));
- }
- ylib::json data;
- data["logs"] = arr;
- reply_ok(resp, data);
- return;
- }
- if (!require_method(req, resp, "POST")) {
- return;
- }
- // clear logs
- const ylib::json body = parse_body(req);
- const std::string job_id = json_str(body, "job_id");
- std::string err;
- if (!schedule::clear_logs(job_id, err)) {
- reply_err(resp, err, 400);
- return;
- }
- reply_ok(resp, ylib::json(), "cleared");
- }
- void h_status(request* req, response* resp) {
- if (!require_method(req, resp, "GET")) {
- return;
- }
- ylib::json data;
- ylib::json nginx;
- nginx["installed"] = nginx::is_installed();
- nginx["running"] = nginx::is_running();
- nginx["version"] = nginx::installed_version();
- nginx["conf"] = nginx::conf_file();
- data["nginx"] = nginx;
- ylib::json fw;
- fw["installed"] = fastweb::is_installed();
- fw["version"] = fastweb::installed_version();
- data["fastweb"] = fw;
- ylib::json my;
- my["installed"] = mysql::is_installed();
- my["running"] = mysql::is_running();
- my["version"] = mysql::installed_version();
- my["port"] = mysql::kDefaultPort;
- my["conf"] = mysql::conf_file();
- data["mysql"] = my;
- ylib::json rd;
- rd["installed"] = redis::is_installed();
- rd["running"] = redis::is_running();
- rd["version"] = redis::installed_version();
- rd["port"] = redis::listen_port();
- rd["conf"] = redis::conf_file();
- rd["install_dir"] = redis::install_dir();
- rd["bin"] = redis::bin_path();
- data["redis"] = rd;
- data["sites"] = static_cast<int>(website::list_sites().size());
- data["panel_name"] = panel_display_name();
- reply_ok(resp, data);
- }
- void h_settings(request* req, response* resp) {
- const std::string method = req->method();
- if (method == "GET") {
- reply_ok(resp, settings_json());
- return;
- }
- if (method == "POST") {
- const auto body = parse_body(req);
- std::string name = trim_copy(json_str(body, "panel_name"));
- if (name.empty()) {
- reply_err(resp, "请填写网站名称");
- return;
- }
- if (name.size() > 64) {
- reply_err(resp, "网站名称最多 64 个字符");
- return;
- }
- for (unsigned char c : name) {
- if (c < 0x20) {
- reply_err(resp, "网站名称不能包含控制字符");
- return;
- }
- }
- if (!store::set_setting("panel.name", name)) {
- reply_err(resp, "保存失败");
- return;
- }
- reply_ok(resp, settings_json(), "已保存");
- return;
- }
- reply_err(resp, "method not allowed", 405);
- }
- ylib::json self_info_json(const selfupdate::Info& info) {
- ylib::json data;
- data["source_dir"] = info.source_dir;
- data["binary_dir"] = info.binary_dir;
- data["branch"] = info.branch;
- data["commit"] = info.commit;
- data["commit_short"] = info.commit_short;
- data["commit_date"] = info.commit_date;
- data["subject"] = info.subject;
- data["remote"] = info.remote;
- data["remote_url"] = info.remote_url;
- data["remote_commit"] = info.remote_commit;
- data["remote_commit_short"] = info.remote_commit_short;
- data["ahead"] = info.ahead;
- data["behind"] = info.behind;
- data["dirty"] = info.dirty;
- data["has_repo"] = info.has_repo;
- data["has_remote"] = info.has_remote;
- data["update_available"] = info.update_available;
- data["in_tmux"] = info.in_tmux;
- data["tmux_pane"] = info.tmux_pane;
- data["error"] = info.error;
- return data;
- }
- void h_self_version(request* req, response* resp) {
- if (!require_method(req, resp, "GET")) {
- return;
- }
- selfupdate::Info info;
- std::string err;
- selfupdate::inspect(info, false, &err);
- reply_ok(resp, self_info_json(info));
- }
- void h_self_check(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- selfupdate::Info info;
- std::string err;
- if (!selfupdate::inspect(info, true, &err) && !info.has_repo) {
- reply_err(resp, err.empty() ? "检查更新失败" : err);
- return;
- }
- ylib::json data = self_info_json(info);
- const std::string msg = info.update_available
- ? ("发现 " + std::to_string(info.behind) + " 个新提交")
- : (info.error.empty() ? "已是最新" : info.error);
- reply_ok(resp, data, msg);
- }
- void h_self_update(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- std::string err;
- const std::string id = tasks::enqueue(
- "self.update", "更新面板",
- []() {
- std::string e;
- if (!selfupdate::apply_update(&e)) {
- if (!e.empty()) {
- log_error(e);
- }
- return false;
- }
- return true;
- },
- err);
- if (id.empty()) {
- reply_err(resp, err.empty() ? "enqueue failed" : err);
- return;
- }
- reply_task_queued(resp, id);
- }
- void h_nginx_status(request* req, response* resp) {
- if (!require_method(req, resp, "GET")) {
- return;
- }
- ylib::json data;
- data["installed"] = nginx::is_installed();
- data["running"] = nginx::is_running();
- data["version"] = nginx::installed_version();
- data["install_dir"] = nginx::install_dir();
- data["bin"] = nginx::bin_path();
- data["conf"] = nginx::conf_file();
- reply_ok(resp, data);
- }
- void h_nginx_install(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- auto body = parse_body(req);
- std::string version = json_str(body, "version", nginx::kDefaultVersion);
- std::string err;
- const std::string id = tasks::enqueue(
- "nginx.install", "安装 Nginx " + version,
- [version]() { return nginx::install(version); }, err);
- if (id.empty()) {
- reply_err(resp, err.empty() ? "enqueue failed" : err);
- return;
- }
- reply_task_queued(resp, id);
- }
- void h_nginx_uninstall(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- std::string err;
- const std::string id = tasks::enqueue(
- "nginx.uninstall", "卸载 Nginx", []() { return nginx::uninstall(); },
- err);
- if (id.empty()) {
- reply_err(resp, err.empty() ? "enqueue failed" : err);
- return;
- }
- reply_task_queued(resp, id);
- }
- void h_nginx_start(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- if (!nginx::start()) {
- reply_err(resp, "nginx start failed");
- return;
- }
- reply_ok(resp, ylib::json(), "nginx started");
- }
- void h_nginx_stop(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- if (!nginx::stop()) {
- reply_err(resp, "nginx stop failed");
- return;
- }
- reply_ok(resp, ylib::json(), "nginx stopped");
- }
- void h_nginx_reload(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- if (!nginx::reload()) {
- reply_err(resp, "nginx reload failed");
- return;
- }
- reply_ok(resp, ylib::json(), "nginx reloaded");
- }
- void h_nginx_config(request* req, response* resp) {
- const std::string method = req->method();
- if (method == "GET") {
- nginx::QuickConfig cfg;
- std::string err;
- if (!nginx::read_quick_config(cfg, err)) {
- reply_err(resp, err.empty() ? "read nginx config failed" : err);
- return;
- }
- ylib::json data;
- data["worker_processes"] = cfg.worker_processes;
- data["worker_connections"] = cfg.worker_connections;
- data["keepalive_timeout"] = cfg.keepalive_timeout;
- data["client_max_body_size"] = cfg.client_max_body_size;
- data["gzip"] = cfg.gzip;
- data["conf"] = nginx::conf_file();
- data["running"] = nginx::is_running();
- reply_ok(resp, data);
- return;
- }
- if (method == "POST") {
- auto body = parse_body(req);
- nginx::QuickConfig cfg;
- std::string err;
- if (!nginx::read_quick_config(cfg, err)) {
- reply_err(resp, err.empty() ? "read nginx config failed" : err);
- return;
- }
- if (body.exist("worker_processes")) {
- cfg.worker_processes =
- json_str(body, "worker_processes", cfg.worker_processes);
- }
- if (body.exist("worker_connections")) {
- cfg.worker_connections =
- json_int(body, "worker_connections", cfg.worker_connections);
- }
- if (body.exist("keepalive_timeout")) {
- cfg.keepalive_timeout =
- json_str(body, "keepalive_timeout", cfg.keepalive_timeout);
- }
- if (body.exist("client_max_body_size")) {
- cfg.client_max_body_size =
- json_str(body, "client_max_body_size", cfg.client_max_body_size);
- }
- if (body.exist("gzip")) {
- cfg.gzip = json_bool(body, "gzip", cfg.gzip);
- }
- if (!nginx::apply_quick_config(cfg, err)) {
- reply_err(resp, err.empty() ? "apply nginx config failed" : err);
- return;
- }
- ylib::json data;
- data["worker_processes"] = cfg.worker_processes;
- data["worker_connections"] = cfg.worker_connections;
- data["keepalive_timeout"] = cfg.keepalive_timeout;
- data["client_max_body_size"] = cfg.client_max_body_size;
- data["gzip"] = cfg.gzip;
- data["conf"] = nginx::conf_file();
- data["running"] = nginx::is_running();
- reply_ok(resp, data, "nginx config updated");
- return;
- }
- reply_err(resp, "method not allowed", 405);
- }
- void h_fastweb_status(request* req, response* resp) {
- if (!require_method(req, resp, "GET")) {
- return;
- }
- ylib::json data;
- data["installed"] = fastweb::is_installed();
- data["version"] = fastweb::installed_version();
- data["install_dir"] = fastweb::install_dir();
- data["bin"] = fastweb::bin_path();
- reply_ok(resp, data);
- }
- void h_fastweb_install(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- auto body = parse_body(req);
- const bool debug = json_bool(body, "debug", false);
- std::string err;
- const std::string id = tasks::enqueue(
- "fastweb.install", "安装 Fastweb",
- [debug]() { return fastweb::install(debug); }, err);
- if (id.empty()) {
- reply_err(resp, err.empty() ? "enqueue failed" : err);
- return;
- }
- reply_task_queued(resp, id);
- }
- void h_fastweb_uninstall(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- std::string err;
- const std::string id = tasks::enqueue(
- "fastweb.uninstall", "卸载 Fastweb",
- []() { return fastweb::uninstall(); }, err);
- if (id.empty()) {
- reply_err(resp, err.empty() ? "enqueue failed" : err);
- return;
- }
- reply_task_queued(resp, id);
- }
- void h_fastweb_modules(request* req, response* resp) {
- if (!require_method(req, resp, "GET")) {
- return;
- }
- const std::string site = url_param(req, "site");
- if (site.empty()) {
- reply_err(resp, "缺少 site 参数", 400);
- return;
- }
- std::vector<fastweb::ModuleInfo> list;
- std::string err;
- if (!fastweb::list_modules(site, list, err)) {
- reply_err(resp, err.empty() ? "获取模块列表失败" : err);
- return;
- }
- ylib::json arr;
- for (const auto& m : list) {
- ylib::json item;
- item["id"] = m.id;
- item["name"] = m.name;
- item["name_en"] = m.name_en;
- item["desc"] = m.desc;
- item["doc"] = m.doc;
- item["icon"] = m.icon;
- item["type"] = m.type;
- item["download_type"] = m.download_type;
- item["download_url"] = m.download_url;
- item["installed"] = m.installed;
- arr.push_back(item);
- }
- ylib::json data;
- data["site"] = site;
- data["catalog_url"] = fastweb::kModuleCatalogUrl;
- data["modules"] = arr;
- reply_ok(resp, data);
- }
- void h_fastweb_module_install(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- auto body = parse_body(req);
- const std::string site = json_str(body, "site");
- const std::string name_en = json_str(body, "name_en");
- if (site.empty() || name_en.empty()) {
- reply_err(resp, "请指定 site 与 name_en", 400);
- return;
- }
- std::string err;
- const std::string id = tasks::enqueue(
- "fastweb.module.install", "安装模块 " + name_en,
- [site, name_en]() {
- std::string e;
- return fastweb::install_module(site, name_en, e);
- },
- err);
- if (id.empty()) {
- reply_err(resp, err.empty() ? "enqueue failed" : err);
- return;
- }
- reply_task_queued(resp, id);
- }
- void h_fastweb_module_uninstall(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- auto body = parse_body(req);
- const std::string site = json_str(body, "site");
- const std::string name_en = json_str(body, "name_en");
- if (site.empty() || name_en.empty()) {
- reply_err(resp, "请指定 site 与 name_en", 400);
- return;
- }
- std::string err;
- const std::string id = tasks::enqueue(
- "fastweb.module.uninstall", "卸载模块 " + name_en,
- [site, name_en]() {
- std::string e;
- return fastweb::uninstall_module(site, name_en, e);
- },
- err);
- if (id.empty()) {
- reply_err(resp, err.empty() ? "enqueue failed" : err);
- return;
- }
- reply_task_queued(resp, id);
- }
- void h_mysql_status(request* req, response* resp) {
- if (!require_method(req, resp, "GET")) {
- return;
- }
- ylib::json data;
- data["installed"] = mysql::is_installed();
- data["running"] = mysql::is_running();
- data["version"] = mysql::installed_version();
- data["install_dir"] = mysql::install_dir();
- data["port"] = mysql::kDefaultPort;
- reply_ok(resp, data);
- }
- void h_mysql_install(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- auto body = parse_body(req);
- std::string version = json_str(body, "version", mysql::kDefaultVersion);
- std::string err;
- const std::string id = tasks::enqueue(
- "mysql.install", "安装 MySQL " + version,
- [version]() { return mysql::install(version); }, err);
- if (id.empty()) {
- reply_err(resp, err.empty() ? "enqueue failed" : err);
- return;
- }
- reply_task_queued(resp, id);
- }
- void h_mysql_uninstall(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- std::string err;
- const std::string id = tasks::enqueue(
- "mysql.uninstall", "卸载 MySQL", []() { return mysql::uninstall(); },
- err);
- if (id.empty()) {
- reply_err(resp, err.empty() ? "enqueue failed" : err);
- return;
- }
- reply_task_queued(resp, id);
- }
- void h_mysql_start(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- if (!mysql::start()) {
- reply_err(resp, "mysql start failed");
- return;
- }
- reply_ok(resp, ylib::json(), "mysql started");
- }
- void h_mysql_stop(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- if (!mysql::stop()) {
- reply_err(resp, "mysql stop failed");
- return;
- }
- reply_ok(resp, ylib::json(), "mysql stopped");
- }
- void h_mysql_root_password(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- auto body = parse_body(req);
- std::string password = json_str(body, "password");
- if (password.empty()) {
- reply_err(resp, "password required");
- return;
- }
- if (!mysql::change_root_password(password)) {
- reply_err(resp, "change root password failed");
- return;
- }
- reply_ok(resp, ylib::json(), "root password updated");
- }
- void h_mysql_databases(request* req, response* resp) {
- const std::string method = req->method();
- if (method == "GET") {
- ylib::json arr;
- for (const auto& db : mysql::list_databases()) {
- ylib::json item;
- item["name"] = db.name;
- item["user"] = db.user;
- item["password"] = db.password;
- item["access"] = db.access;
- item["host"] = db.host;
- arr.push_back(item);
- }
- reply_ok(resp, arr);
- return;
- }
- if (method == "POST") {
- auto body = parse_body(req);
- std::string name = json_str(body, "name");
- std::string user = json_str(body, "user");
- std::string password = json_str(body, "password");
- if (name.empty() || user.empty() || password.empty()) {
- reply_err(resp, "name/user/password required");
- return;
- }
- std::string err;
- if (!mysql::create_database(name, user, password, &err)) {
- reply_err(resp, err.empty() ? "create database failed" : err);
- return;
- }
- reply_ok(resp, ylib::json(), "database created");
- return;
- }
- reply_err(resp, "method not allowed", 405);
- }
- void h_mysql_databases_drop(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- auto body = parse_body(req);
- std::string name = json_str(body, "name");
- if (name.empty()) {
- reply_err(resp, "name required");
- return;
- }
- if (!mysql::drop_database(name)) {
- reply_err(resp, "drop database failed");
- return;
- }
- reply_ok(resp, ylib::json(), "database dropped");
- }
- void h_mysql_exec(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- const auto body = parse_body(req);
- const std::string database = json_str(body, "database");
- const std::string sql = json_str(body, "sql");
- if (sql.empty()) {
- reply_err(resp, "请输入 SQL");
- return;
- }
- mysql::QueryResult result;
- std::string err;
- const auto t0 = std::chrono::steady_clock::now();
- if (!mysql::exec_query(database, sql, result, &err)) {
- reply_err(resp, err.empty() ? "执行失败" : err);
- return;
- }
- const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::steady_clock::now() - t0)
- .count();
- ylib::json data;
- ylib::json columns;
- for (const auto& c : result.columns) {
- columns.push_back(c);
- }
- data["columns"] = columns;
- ylib::json rows;
- for (const auto& row : result.rows) {
- ylib::json r;
- for (const auto& cell : row) {
- r.push_back(cell);
- }
- rows.push_back(r);
- }
- data["rows"] = rows;
- data["row_count"] = result.row_count;
- data["truncated"] = result.truncated;
- data["message"] = result.message;
- data["elapsed_ms"] = static_cast<int>(ms);
- reply_ok(resp, data);
- }
- void h_mysql_databases_access(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- auto body = parse_body(req);
- std::string name = json_str(body, "name");
- std::string mode = json_str(body, "mode");
- std::string host = json_str(body, "host");
- if (name.empty() || mode.empty()) {
- reply_err(resp, "name/mode required");
- return;
- }
- if (!mysql::set_database_access(name, mode, host)) {
- reply_err(resp, "set database access failed");
- return;
- }
- reply_ok(resp, ylib::json(), "database access updated");
- }
- ylib::json site_to_json(const website::SiteInfo& s) {
- ylib::json item;
- item["name"] = s.name;
- item["type"] = website::type_key(s.type);
- const auto tokens = website::domain_tokens(s);
- item["domain"] = website::join_domains(tokens);
- ylib::json domains;
- for (const auto& t : tokens) {
- domains.push_back(t);
- }
- item["domains"] = domains;
- item["listen_port"] = s.listen_port;
- item["upstream"] = s.upstream;
- item["running"] = s.running;
- item["conf"] = website::vhost_conf_path(s.name);
- item["root"] = website::site_root_path(s.name);
- const std::string log_dir = website::site_log_dir_path(s.name);
- item["log_dir"] = log_dir;
- item["access_log"] = join_path(log_dir, "access.log");
- item["error_log"] = join_path(log_dir, "error.log");
- item["log_db"] = weblog::db_path(website::site_key(s));
- {
- const weblog::LogUsage u = weblog::usage(website::site_key(s));
- item["log_file_bytes"] = static_cast<int64>(u.file_bytes);
- item["log_db_bytes"] = static_cast<int64>(u.db_bytes);
- item["log_access_bytes"] = static_cast<int64>(u.access_bytes);
- item["log_error_bytes"] = static_cast<int64>(u.error_bytes);
- item["log_bytes"] = static_cast<int64>(u.file_bytes + u.db_bytes);
- }
- item["ssl_enable"] = s.ssl_enable;
- item["ssl_cert"] = s.ssl_cert;
- item["ssl_key"] = s.ssl_key;
- item["ssl_port"] = s.ssl_port;
- item["group_name"] = s.group_name;
- item["sort_order"] = s.sort_order;
- item["ssl_not_before"] = "";
- item["ssl_not_after"] = "";
- item["ssl_days_left"] = -1;
- if (!s.ssl_cert.empty()) {
- const ssl::CertInfo ci = ssl::read_cert_info(s.ssl_cert);
- if (ci.ok) {
- item["ssl_not_before"] = ci.not_before;
- item["ssl_not_after"] = ci.not_after;
- item["ssl_days_left"] = ci.days_left;
- }
- }
- return item;
- }
- void h_websites(request* req, response* resp) {
- const std::string method = req->method();
- if (method == "GET") {
- ylib::json arr;
- for (const auto& s : website::list_sites()) {
- arr.push_back(site_to_json(s));
- }
- reply_ok(resp, arr);
- return;
- }
- if (method == "POST") {
- auto body = parse_body(req);
- website::CreateSiteRequest creq;
- creq.name = json_str(body, "name");
- std::string type = json_str(body, "type", "static");
- if (!website::parse_type_key(type, creq.type)) {
- reply_err(resp, "invalid type, expect static|fastweb");
- return;
- }
- // "proxy" is accepted as alias of static for older clients.
- if (type == "proxy") {
- creq.type = website::SiteType::Static;
- }
- creq.domain = json_str(body, "domain");
- if (body.exist("domains") && body["domains"].is_array()) {
- std::string joined;
- const auto& arr = body["domains"];
- for (uint32 i = 0; i < arr.size(); ++i) {
- std::string d = arr[i].to<std::string>(true);
- if (d.empty()) {
- continue;
- }
- if (!joined.empty()) {
- joined.push_back(' ');
- }
- joined += d;
- }
- if (!joined.empty()) {
- creq.domain = joined;
- }
- }
- creq.listen_port = json_int(body, "listen_port", 0);
- creq.upstream.clear();
- creq.root = json_str(body, "root");
- creq.group_name = json_str(body, "group_name");
- if (creq.name.empty()) {
- reply_err(resp, "name required");
- return;
- }
- if (creq.domain.empty()) {
- reply_err(resp, "domain required");
- return;
- }
- std::string err;
- if (!website::create_site(creq, err)) {
- reply_err(resp, err.empty() ? "create site failed" : err);
- return;
- }
- website::SiteInfo created;
- website::find_site(creq.name, created);
- reply_ok(resp, site_to_json(created), "site created");
- return;
- }
- reply_err(resp, "method not allowed", 405);
- }
- void h_websites_start(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- auto body = parse_body(req);
- std::string name = json_str(body, "name");
- if (name.empty()) {
- reply_err(resp, "name required");
- return;
- }
- std::string err;
- if (!website::start_site(name, err)) {
- reply_err(resp, err.empty() ? "start site failed" : err);
- return;
- }
- reply_ok(resp, ylib::json(), "site started");
- }
- void h_websites_stop(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- auto body = parse_body(req);
- std::string name = json_str(body, "name");
- if (name.empty()) {
- reply_err(resp, "name required");
- return;
- }
- std::string err;
- if (!website::stop_site(name, err)) {
- reply_err(resp, err.empty() ? "stop site failed" : err);
- return;
- }
- reply_ok(resp, ylib::json(), "site stopped");
- }
- void h_websites_restart(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- auto body = parse_body(req);
- std::string name = json_str(body, "name");
- if (name.empty()) {
- reply_err(resp, "name required");
- return;
- }
- std::string err;
- if (!website::restart_site(name, err)) {
- reply_err(resp, err.empty() ? "restart site failed" : err);
- return;
- }
- reply_ok(resp, ylib::json(), "site restarted");
- }
- void h_websites_delete(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- auto body = parse_body(req);
- std::string name = json_str(body, "name");
- if (name.empty()) {
- reply_err(resp, "name required");
- return;
- }
- const bool delete_files = json_bool(body, "delete_files", false);
- std::string err;
- if (!website::delete_site(name, err, delete_files)) {
- reply_err(resp, err.empty() ? "delete site failed" : err);
- return;
- }
- reply_ok(resp, ylib::json(),
- delete_files ? "site and files deleted" : "site deleted");
- }
- void h_websites_update(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- auto body = parse_body(req);
- website::UpdateSiteRequest ureq;
- ureq.name = json_str(body, "name");
- if (ureq.name.empty()) {
- reply_err(resp, "name required");
- return;
- }
- if (body.exist("domains") && body["domains"].is_array()) {
- std::string joined;
- const auto& arr = body["domains"];
- for (uint32 i = 0; i < arr.size(); ++i) {
- std::string d = arr[i].to<std::string>(true);
- if (d.empty()) {
- continue;
- }
- if (!joined.empty()) {
- joined.push_back(' ');
- }
- joined += d;
- }
- ureq.domain = joined;
- } else {
- ureq.domain = json_str(body, "domain");
- }
- ureq.listen_port = json_int(body, "listen_port", 0);
- ureq.update_ssl = body.exist("ssl_enable") || body.exist("ssl_cert") ||
- body.exist("ssl_key") || body.exist("ssl_port");
- ureq.ssl_enable = json_bool(body, "ssl_enable", false);
- ureq.ssl_cert = json_str(body, "ssl_cert");
- ureq.ssl_key = json_str(body, "ssl_key");
- ureq.ssl_port = json_int(body, "ssl_port", 443);
- ureq.update_group = body.exist("group_name");
- ureq.group_name = json_str(body, "group_name");
- std::string err;
- if (!website::update_site(ureq, err)) {
- reply_err(resp, err.empty() ? "update site failed" : err);
- return;
- }
- website::SiteInfo updated;
- website::find_site(ureq.name, updated);
- reply_ok(resp, site_to_json(updated), "site updated");
- }
- void h_websites_reorder(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- auto body = parse_body(req);
- if (!body.exist("items") || !body["items"].is_array()) {
- reply_err(resp, "items array required");
- return;
- }
- std::vector<website::SiteOrderItem> items;
- const auto& arr = body["items"];
- for (uint32 i = 0; i < arr.size(); ++i) {
- const auto& j = arr[i];
- website::SiteOrderItem it;
- it.name = j.exist("name") ? j["name"].to<std::string>() : "";
- it.group_name =
- j.exist("group_name") ? j["group_name"].to<std::string>() : "";
- try {
- it.sort_order =
- j.exist("sort_order") ? j["sort_order"].to<int>() : 0;
- } catch (...) {
- it.sort_order = 0;
- }
- if (it.name.empty()) {
- reply_err(resp, "item.name required");
- return;
- }
- items.push_back(it);
- }
- std::string err;
- if (!website::reorder_sites(items, err)) {
- reply_err(resp, err.empty() ? "reorder failed" : err);
- return;
- }
- ylib::json out;
- for (const auto& s : website::list_sites()) {
- out.push_back(site_to_json(s));
- }
- reply_ok(resp, out, "sites reordered");
- }
- ylib::json url_proxy_to_json(const website::UrlProxyRule& r) {
- ylib::json item;
- item["id"] = r.id;
- item["path"] = r.path;
- item["target_type"] = r.target_type;
- item["target"] = r.target;
- item["host"] = r.host;
- item["remark"] = r.remark;
- return item;
- }
- void h_websites_proxies(request* req, response* resp) {
- const std::string method = req ? req->method() : "";
- if (method == "GET") {
- const std::string name = url_param(req, "name");
- if (name.empty()) {
- reply_err(resp, "name required");
- return;
- }
- std::string err;
- auto rules = website::list_url_proxies(name, err);
- if (!err.empty()) {
- reply_err(resp, err);
- return;
- }
- ylib::json arr;
- for (const auto& r : rules) {
- arr.push_back(url_proxy_to_json(r));
- }
- ylib::json data;
- data["proxies"] = arr;
- reply_ok(resp, data);
- return;
- }
- if (method == "POST") {
- auto body = parse_body(req);
- const std::string name = json_str(body, "name");
- if (name.empty()) {
- reply_err(resp, "name required");
- return;
- }
- website::UrlProxyRule rule;
- rule.path = json_str(body, "path");
- rule.target_type = json_str(body, "target_type", "url");
- rule.target = json_str(body, "target");
- rule.host = json_str(body, "host", "$http_host");
- rule.remark = json_str(body, "remark");
- std::string err;
- if (!website::add_url_proxy(name, rule, err)) {
- reply_err(resp, err.empty() ? "add url proxy failed" : err);
- return;
- }
- auto rules = website::list_url_proxies(name, err);
- ylib::json arr;
- for (const auto& r : rules) {
- arr.push_back(url_proxy_to_json(r));
- }
- ylib::json data;
- data["proxies"] = arr;
- reply_ok(resp, data, "url proxy added");
- return;
- }
- reply_err(resp, "method not allowed", 405);
- }
- void h_websites_proxies_update(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- auto body = parse_body(req);
- const std::string name = json_str(body, "name");
- website::UrlProxyRule rule;
- rule.id = json_str(body, "id");
- rule.path = json_str(body, "path");
- rule.target_type = json_str(body, "target_type", "url");
- rule.target = json_str(body, "target");
- rule.host = json_str(body, "host", "$http_host");
- rule.remark = json_str(body, "remark");
- if (name.empty() || rule.id.empty()) {
- reply_err(resp, "name and id required");
- return;
- }
- std::string err;
- if (!website::update_url_proxy(name, rule, err)) {
- reply_err(resp, err.empty() ? "update url proxy failed" : err);
- return;
- }
- reply_ok(resp, ylib::json(), "url proxy updated");
- }
- void h_websites_proxies_delete(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- auto body = parse_body(req);
- const std::string name = json_str(body, "name");
- const std::string id = json_str(body, "id");
- if (name.empty() || id.empty()) {
- reply_err(resp, "name and id required");
- return;
- }
- std::string err;
- if (!website::delete_url_proxy(name, id, err)) {
- reply_err(resp, err.empty() ? "delete url proxy failed" : err);
- return;
- }
- reply_ok(resp, ylib::json(), "url proxy deleted");
- }
- void h_websites_custom(request* req, response* resp) {
- const std::string method = req->method();
- if (method == "GET") {
- const std::string name = url_param(req, "name");
- if (name.empty()) {
- reply_err(resp, "name required");
- return;
- }
- std::string content;
- std::string err;
- if (!website::get_custom_nginx(name, content, err)) {
- reply_err(resp, err.empty() ? "get custom config failed" : err);
- return;
- }
- ylib::json data;
- data["name"] = name;
- data["content"] = content;
- reply_ok(resp, data);
- return;
- }
- if (method == "POST") {
- auto body = parse_body(req);
- const std::string name = json_str(body, "name");
- if (name.empty()) {
- reply_err(resp, "name required");
- return;
- }
- const std::string content = json_str(body, "content");
- std::string err;
- if (!website::set_custom_nginx(name, content, err)) {
- reply_err(resp, err.empty() ? "save custom config failed" : err);
- return;
- }
- reply_ok(resp, ylib::json(), "custom config saved");
- return;
- }
- reply_err(resp, "method not allowed", 405);
- }
- void h_websites_logs(request* req, response* resp) {
- if (!require_method(req, resp, "GET")) {
- return;
- }
- const std::string name = url_param(req, "name");
- if (name.empty()) {
- reply_err(resp, "name required");
- return;
- }
- website::SiteInfo site;
- if (!website::find_site(name, site)) {
- reply_err(resp, "site not found", 404);
- return;
- }
- const std::string kind = url_param(req, "kind", "access");
- size_t limit = 100;
- try {
- limit = static_cast<size_t>(std::stoul(url_param(req, "limit", "100")));
- } catch (...) {
- limit = 100;
- }
- int64_t before_id = 0;
- try {
- before_id = std::stoll(url_param(req, "before_id", "0"));
- } catch (...) {
- before_id = 0;
- }
- ylib::json arr;
- std::string err;
- if (kind == "error") {
- weblog::ErrorQuery q;
- q.name = name;
- q.limit = limit;
- q.before_id = before_id;
- q.level = url_param(req, "level");
- q.q = url_param(req, "q");
- std::vector<weblog::ErrorRow> rows;
- if (!weblog::query_error(q, rows, err)) {
- reply_err(resp, err.empty() ? "query logs failed" : err);
- return;
- }
- for (const auto& r : rows) {
- ylib::json item;
- item["id"] = static_cast<int64>(r.id);
- item["time"] = r.time;
- item["time_ms"] = static_cast<int64>(r.time_ms);
- item["level"] = r.level;
- item["message"] = r.message;
- item["raw"] = r.raw;
- arr.push_back(item);
- }
- } else {
- weblog::AccessQuery q;
- q.name = name;
- q.limit = limit;
- q.before_id = before_id;
- try {
- q.status = std::stoi(url_param(req, "status", "0"));
- } catch (...) {
- q.status = 0;
- }
- q.ip = url_param(req, "ip");
- q.q = url_param(req, "q");
- std::vector<weblog::AccessRow> rows;
- if (!weblog::query_access(q, rows, err)) {
- reply_err(resp, err.empty() ? "query logs failed" : err);
- return;
- }
- for (const auto& r : rows) {
- ylib::json item;
- item["id"] = static_cast<int64>(r.id);
- item["time"] = r.time;
- item["time_ms"] = static_cast<int64>(r.time_ms);
- item["ip"] = r.ip;
- item["method"] = r.method;
- item["host"] = r.host;
- item["uri"] = r.uri;
- item["args"] = r.args;
- item["status"] = r.status;
- item["bytes_recv"] = static_cast<int64>(r.bytes_recv);
- item["bytes_sent"] = static_cast<int64>(r.bytes_sent);
- item["request_time"] = r.request_time;
- item["upstream_status"] = r.upstream_status;
- item["upstream_addr"] = r.upstream_addr;
- item["referer"] = r.referer;
- item["ua"] = r.ua;
- item["request"] = r.request;
- item["body"] = r.body;
- arr.push_back(item);
- }
- }
- ylib::json data;
- data["name"] = name;
- data["kind"] = kind == "error" ? "error" : "access";
- data["log_db"] = weblog::db_path(website::site_key_by_name(name));
- data["items"] = arr;
- reply_ok(resp, data);
- }
- void h_websites_logs_purge(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- auto body = parse_body(req);
- const std::string name = json_str(body, "name");
- if (name.empty()) {
- reply_err(resp, "name required");
- return;
- }
- website::SiteInfo site;
- if (!website::find_site(name, site)) {
- reply_err(resp, "site not found", 404);
- return;
- }
- weblog::PurgeOptions opt;
- opt.files = json_bool(body, "files", false);
- opt.db = json_bool(body, "db", false);
- std::string err;
- if (!weblog::purge(website::site_key(site), opt, err)) {
- reply_err(resp, err.empty() ? "清理失败" : err);
- return;
- }
- if (opt.files && !nginx::reopen_logs()) {
- log_warn("nginx reopen logs failed after purge site=" + name);
- }
- const weblog::LogUsage u = weblog::usage(website::site_key(site));
- ylib::json data;
- data["name"] = name;
- data["log_file_bytes"] = static_cast<int64>(u.file_bytes);
- data["log_db_bytes"] = static_cast<int64>(u.db_bytes);
- data["log_access_bytes"] = static_cast<int64>(u.access_bytes);
- data["log_error_bytes"] = static_cast<int64>(u.error_bytes);
- data["log_bytes"] = static_cast<int64>(u.file_bytes + u.db_bytes);
- reply_ok(resp, data, "logs purged");
- }
- void h_websites_analytics(request* req, response* resp) {
- if (!require_method(req, resp, "GET")) {
- return;
- }
- const std::string name = url_param(req, "name");
- if (name.empty()) {
- reply_err(resp, "name required");
- return;
- }
- website::SiteInfo site;
- if (!website::find_site(name, site)) {
- reply_err(resp, "site not found", 404);
- return;
- }
- std::string range = url_param(req, "range", "24h");
- if (range.empty()) {
- range = "24h";
- }
- std::string json_body;
- std::string err;
- if (!weblog::analyze(name, range, json_body, err)) {
- reply_err(resp, err.empty() ? "analyze failed" : err);
- return;
- }
- ylib::json data;
- try {
- data = ylib::json::from(json_body);
- } catch (...) {
- reply_err(resp, "invalid analytics payload");
- return;
- }
- data["self_ip"] = request_client_ip(req);
- reply_ok(resp, data);
- }
- void h_websites_ssl_apply(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- auto body = parse_body(req);
- const std::string name = json_str(body, "name");
- if (name.empty()) {
- reply_err(resp, "name required");
- return;
- }
- std::vector<std::string> hosts;
- if (body.exist("domains") && body["domains"].is_array()) {
- const auto& arr = body["domains"];
- for (uint32 i = 0; i < arr.size(); ++i) {
- std::string d = arr[i].to<std::string>(true);
- if (!d.empty()) {
- hosts.push_back(d);
- }
- }
- } else if (body.exist("hosts") && body["hosts"].is_array()) {
- const auto& arr = body["hosts"];
- for (uint32 i = 0; i < arr.size(); ++i) {
- std::string d = arr[i].to<std::string>(true);
- if (!d.empty()) {
- hosts.push_back(d);
- }
- }
- }
- // ACME account contact: md5(<domain>)@qq.com (LE requires public-suffix email).
- // Ignore previously stored invalid/legacy emails.
- std::string email = json_str(body, "email");
- if (!ssl::is_valid_acme_email(email) ||
- email.size() < 8 ||
- email.compare(email.size() - 7, 7, "@qq.com") != 0) {
- std::string domain_hint;
- if (!hosts.empty()) {
- domain_hint = hosts.front();
- } else {
- website::SiteInfo site;
- if (website::find_site(name, site)) {
- domain_hint = website::primary_domain(site.domain);
- }
- }
- email = ssl::default_account_email(domain_hint);
- if (!ssl::is_valid_acme_email(email)) {
- reply_err(resp, "无法生成 ACME 联系邮箱");
- return;
- }
- store::set_setting("ssl_email", email);
- } else if (store::get_setting("ssl_email", "") != email) {
- store::set_setting("ssl_email", email);
- }
- std::string err;
- std::string title = "申请 SSL · " + name;
- if (!hosts.empty()) {
- title += " (" + std::to_string(hosts.size()) + ")";
- }
- const std::string id = tasks::enqueue(
- "ssl.letsencrypt", title,
- [name, email, hosts]() {
- std::string e;
- if (!website::apply_letsencrypt(name, email, hosts, e)) {
- if (!e.empty()) {
- std::cerr << e << "\n";
- log_error(e);
- }
- return false;
- }
- return true;
- },
- err);
- if (id.empty()) {
- reply_err(resp, err.empty() ? "enqueue failed" : err);
- return;
- }
- ylib::json data;
- data["task_id"] = id;
- data["active"] = tasks::active_count();
- reply_ok(resp, data, "task queued");
- }
- void h_system_metrics(request* req, response* resp) {
- if (!require_method(req, resp, "GET")) {
- return;
- }
- const auto m = system::sample();
- ylib::json data;
- ylib::json cpu;
- cpu["percent"] = m.cpu.percent;
- cpu["cores"] = m.cpu.cores;
- data["cpu"] = cpu;
- ylib::json memory;
- memory["total"] = static_cast<int64>(m.memory.total_bytes);
- memory["used"] = static_cast<int64>(m.memory.used_bytes);
- memory["percent"] = m.memory.percent;
- data["memory"] = memory;
- ylib::json disk;
- disk["path"] = m.disk.path;
- disk["device"] = m.disk.device;
- disk["fstype"] = m.disk.fstype;
- disk["total"] = static_cast<int64>(m.disk.total_bytes);
- disk["used"] = static_cast<int64>(m.disk.used_bytes);
- disk["percent"] = m.disk.percent;
- data["disk"] = disk;
- ylib::json disks;
- for (const auto& d : m.disks) {
- ylib::json item;
- item["path"] = d.path;
- item["device"] = d.device;
- item["fstype"] = d.fstype;
- item["total"] = static_cast<int64>(d.total_bytes);
- item["used"] = static_cast<int64>(d.used_bytes);
- item["percent"] = d.percent;
- disks.push_back(item);
- }
- data["disks"] = disks;
- ylib::json network;
- network["rx_bytes"] = static_cast<int64>(m.network.rx_bytes);
- network["tx_bytes"] = static_cast<int64>(m.network.tx_bytes);
- network["rx_bps"] = m.network.rx_bps;
- network["tx_bps"] = m.network.tx_bps;
- data["network"] = network;
- ylib::json gpus;
- for (const auto& g : m.gpus) {
- ylib::json item;
- item["index"] = g.index;
- item["name"] = g.name;
- item["percent"] = g.percent;
- item["mem_used"] = static_cast<int64>(g.mem_used);
- item["mem_total"] = static_cast<int64>(g.mem_total);
- item["mem_percent"] = g.mem_percent;
- item["temperature"] = g.temperature;
- gpus.push_back(item);
- }
- data["gpus"] = gpus;
- reply_ok(resp, data);
- }
- void h_system_processes(request* req, response* resp) {
- if (!require_method(req, resp, "GET")) {
- return;
- }
- const std::string q = url_param(req, "q", "");
- const auto list = system::list_processes(q);
- ylib::json arr;
- for (const auto& p : list) {
- ylib::json item;
- item["pid"] = p.pid;
- item["ppid"] = p.ppid;
- item["user"] = p.user;
- item["state"] = p.state;
- item["name"] = p.name;
- item["cmdline"] = p.cmdline;
- item["cwd"] = p.cwd;
- item["threads"] = p.threads;
- item["rss"] = static_cast<int64>(p.rss_bytes);
- item["vms"] = static_cast<int64>(p.vms_bytes);
- item["mem_percent"] = p.mem_percent;
- item["cpu_percent"] = p.cpu_percent;
- arr.push_back(item);
- }
- ylib::json data;
- data["total"] = static_cast<int>(list.size());
- data["items"] = arr;
- reply_ok(resp, data);
- }
- void h_system_processes_kill(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- auto body = parse_body(req);
- const int pid = json_int(body, "pid", 0);
- int signal = json_int(body, "signal", 15);
- const std::string sig_name = json_str(body, "signal_name");
- if (!sig_name.empty()) {
- if (sig_name == "KILL" || sig_name == "SIGKILL" || sig_name == "9") {
- signal = 9;
- } else if (sig_name == "TERM" || sig_name == "SIGTERM" ||
- sig_name == "15") {
- signal = 15;
- } else if (sig_name == "INT" || sig_name == "SIGINT" ||
- sig_name == "2") {
- signal = 2;
- } else if (sig_name == "HUP" || sig_name == "SIGHUP" ||
- sig_name == "1") {
- signal = 1;
- }
- }
- if (pid <= 0) {
- reply_err(resp, "pid required");
- return;
- }
- std::string err;
- if (!system::kill_process(pid, signal, err)) {
- reply_err(resp, err.empty() ? "kill failed" : err);
- return;
- }
- ylib::json data;
- data["pid"] = pid;
- data["signal"] = signal;
- reply_ok(resp, data, "process signaled");
- }
- void h_shell_ticket(request* req, response* resp) {
- if (!require_method(req, resp, "GET")) {
- return;
- }
- std::string username;
- if (!request_authed(req, &username)) {
- reply_err(resp, "未登录或会话已过期", 401);
- return;
- }
- const std::string ticket = system::shell_issue_ticket(username);
- ylib::json data;
- data["ticket"] = ticket;
- data["ttl_sec"] = 60;
- reply_ok(resp, data);
- }
- void h_system_metrics_history(request* req, response* resp) {
- if (!require_method(req, resp, "GET")) {
- return;
- }
- std::string range = url_param(req, "range", "10m");
- if (range.empty()) {
- range = "10m";
- }
- std::vector<system::HistoryPoint> points;
- std::string err;
- if (!system::history_query(range, points, err)) {
- reply_err(resp, err.empty() ? "query metrics history failed" : err);
- return;
- }
- ylib::json arr;
- for (const auto& p : points) {
- ylib::json item;
- item["time_ms"] = static_cast<int64>(p.time_ms);
- item["cpu_percent"] = p.cpu_percent;
- item["cpu_cores"] = p.cpu_cores;
- item["mem_percent"] = p.mem_percent;
- item["mem_used"] = static_cast<int64>(p.mem_used);
- item["mem_total"] = static_cast<int64>(p.mem_total);
- item["disk_percent"] = p.disk_percent;
- item["disk_used"] = static_cast<int64>(p.disk_used);
- item["disk_total"] = static_cast<int64>(p.disk_total);
- item["net_rx_bps"] = p.net_rx_bps;
- item["net_tx_bps"] = p.net_tx_bps;
- item["net_rx_bytes"] = static_cast<int64>(p.net_rx_bytes);
- item["net_tx_bytes"] = static_cast<int64>(p.net_tx_bytes);
- item["gpu_percent"] = p.gpu_percent;
- item["gpu_mem_used"] = static_cast<int64>(p.gpu_mem_used);
- item["gpu_mem_total"] = static_cast<int64>(p.gpu_mem_total);
- arr.push_back(item);
- }
- ylib::json data;
- data["range"] = range;
- data["items"] = arr;
- reply_ok(resp, data);
- }
- void h_redis_status(request* req, response* resp) {
- if (!require_method(req, resp, "GET")) {
- return;
- }
- ylib::json data;
- data["installed"] = redis::is_installed();
- data["running"] = redis::is_running();
- data["version"] = redis::installed_version();
- data["install_dir"] = redis::install_dir();
- data["bin"] = redis::bin_path();
- data["conf"] = redis::conf_file();
- data["port"] = redis::listen_port();
- reply_ok(resp, data);
- }
- void h_redis_install(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- auto body = parse_body(req);
- std::string version = json_str(body, "version", redis::kDefaultVersion);
- std::string err;
- const std::string id = tasks::enqueue(
- "redis.install", "安装 Redis " + version,
- [version]() { return redis::install(version); }, err);
- if (id.empty()) {
- reply_err(resp, err.empty() ? "enqueue failed" : err);
- return;
- }
- reply_task_queued(resp, id);
- }
- void h_redis_uninstall(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- std::string err;
- const std::string id = tasks::enqueue(
- "redis.uninstall", "卸载 Redis", []() { return redis::uninstall(); },
- err);
- if (id.empty()) {
- reply_err(resp, err.empty() ? "enqueue failed" : err);
- return;
- }
- reply_task_queued(resp, id);
- }
- void h_redis_start(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- if (!redis::start()) {
- reply_err(resp, "redis start failed");
- return;
- }
- reply_ok(resp, ylib::json(), "redis started");
- }
- void h_redis_stop(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- if (!redis::stop()) {
- reply_err(resp, "redis stop failed");
- return;
- }
- reply_ok(resp, ylib::json(), "redis stopped");
- }
- void h_redis_config(request* req, response* resp) {
- const std::string method = req->method();
- if (method == "GET") {
- redis::QuickConfig cfg;
- std::string err;
- if (!redis::read_quick_config(cfg, err)) {
- reply_err(resp, err.empty() ? "read redis config failed" : err);
- return;
- }
- ylib::json data;
- data["bind"] = cfg.bind;
- data["port"] = cfg.port;
- data["requirepass"] = cfg.requirepass;
- data["conf"] = redis::conf_file();
- data["running"] = redis::is_running();
- reply_ok(resp, data);
- return;
- }
- if (method == "POST") {
- redis::QuickConfig cfg;
- std::string err;
- if (!redis::read_quick_config(cfg, err)) {
- reply_err(resp, err.empty() ? "read redis config failed" : err);
- return;
- }
- const auto body = parse_body(req);
- if (body.exist("bind")) {
- cfg.bind = json_str(body, "bind", cfg.bind);
- }
- if (body.exist("port")) {
- cfg.port = json_int(body, "port", cfg.port);
- }
- if (body.exist("requirepass")) {
- cfg.requirepass = json_str(body, "requirepass");
- }
- if (!redis::apply_quick_config(cfg, err)) {
- reply_err(resp, err.empty() ? "apply redis config failed" : err);
- return;
- }
- ylib::json data;
- data["bind"] = cfg.bind;
- data["port"] = cfg.port;
- data["requirepass"] = cfg.requirepass;
- data["conf"] = redis::conf_file();
- data["running"] = redis::is_running();
- reply_ok(resp, data, "redis config updated");
- return;
- }
- reply_err(resp, "method not allowed", 405);
- }
- void h_redis_exec(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- const auto body = parse_body(req);
- const std::string command = json_str(body, "command");
- if (command.empty()) {
- reply_err(resp, "请输入 Redis 命令");
- return;
- }
- std::string output;
- std::string err;
- bool truncated = false;
- const auto t0 = std::chrono::steady_clock::now();
- if (!redis::exec_command(command, output, truncated, err)) {
- reply_err(resp, err.empty() ? "执行失败" : err);
- return;
- }
- const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::steady_clock::now() - t0)
- .count();
- ylib::json data;
- data["output"] = output;
- data["truncated"] = truncated;
- data["elapsed_ms"] = static_cast<int>(ms);
- reply_ok(resp, data);
- }
- void h_files_list(request* req, response* resp) {
- if (!require_method(req, resp, "GET")) {
- return;
- }
- std::string path = url_param(req, "path", "/");
- std::string abs, err;
- if (!files::resolve_path(path, abs, err)) {
- reply_err(resp, err);
- return;
- }
- std::vector<files::Entry> entries;
- if (!files::list_dir(abs, entries, err)) {
- reply_err(resp, err);
- return;
- }
- ylib::json arr;
- for (const auto& e : entries) {
- ylib::json item;
- item["name"] = e.name;
- item["path"] = e.path;
- item["is_dir"] = e.is_dir;
- item["is_symlink"] = e.is_symlink;
- item["size"] = static_cast<int64>(e.size);
- item["mtime"] = static_cast<int64>(e.mtime);
- arr.push_back(item);
- }
- ylib::json data;
- data["path"] = abs;
- data["entries"] = arr;
- reply_ok(resp, data);
- }
- void h_files_mkdir(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- auto body = parse_body(req);
- std::string path = json_str(body, "path");
- std::string err;
- if (!files::mkdir_path(path, err)) {
- reply_err(resp, err);
- return;
- }
- reply_ok(resp, ylib::json(), "directory created");
- }
- void h_files_write(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- auto body = parse_body(req);
- std::string path = json_str(body, "path");
- std::string content = json_str(body, "content");
- std::string err;
- if (!files::write_text(path, content, err)) {
- reply_err(resp, err);
- return;
- }
- reply_ok(resp, ylib::json(), "written");
- }
- void h_files_read(request* req, response* resp) {
- if (!require_method(req, resp, "GET")) {
- return;
- }
- std::string path = url_param(req, "path");
- std::string content, err;
- if (!files::read_text(path, content, err)) {
- reply_err(resp, err);
- return;
- }
- ylib::json data;
- data["path"] = path;
- data["content"] = content;
- reply_ok(resp, data);
- }
- void h_files_tail(request* req, response* resp) {
- if (!require_method(req, resp, "GET")) {
- return;
- }
- std::string path = url_param(req, "path");
- size_t max_bytes = 256ull * 1024ull;
- try {
- max_bytes = static_cast<size_t>(
- std::stoul(url_param(req, "bytes", "262144")));
- } catch (...) {
- }
- if (max_bytes < 1024) {
- max_bytes = 1024;
- }
- if (max_bytes > files::kMaxEditBytes) {
- max_bytes = files::kMaxEditBytes;
- }
- std::string content, err;
- if (!files::read_tail(path, max_bytes, content, err)) {
- reply_err(resp, err);
- return;
- }
- ylib::json data;
- data["path"] = path;
- data["content"] = content;
- reply_ok(resp, data);
- }
- void h_files_rename(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- auto body = parse_body(req);
- std::string from = json_str(body, "from");
- std::string to = json_str(body, "to");
- std::string err;
- if (!files::rename_path(from, to, err)) {
- reply_err(resp, err);
- return;
- }
- reply_ok(resp, ylib::json(), "renamed");
- }
- void h_files_delete(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- auto body = parse_body(req);
- std::string path = json_str(body, "path");
- const bool recursive = json_bool(body, "recursive", false);
- std::string err;
- if (!files::delete_path(path, recursive, err)) {
- reply_err(resp, err);
- return;
- }
- reply_ok(resp, ylib::json(), "deleted");
- }
- void h_files_upload(request* req, response* resp) {
- if (!require_method(req, resp, "POST")) {
- return;
- }
- std::string content_type;
- if (!(req->header("Content-Type", content_type) ||
- req->header("content-type", content_type))) {
- content_type.clear();
- }
- std::string path;
- uint64_t offset = 0;
- uint64_t total = 0;
- std::string bytes;
- const bool binary =
- content_type.find("application/octet-stream") != std::string::npos ||
- (!url_param(req, "path").empty() &&
- content_type.find("json") == std::string::npos);
- if (binary) {
- path = url_param(req, "path");
- offset = parse_u64(url_param(req, "offset", "0"));
- total = parse_u64(url_param(req, "total", "0"));
- bytes = req->body().to_string();
- } else {
- auto body = parse_body(req);
- path = json_str(body, "path");
- offset = parse_u64(json_str(body, "offset"));
- total = parse_u64(json_str(body, "total"));
- const std::string b64 = json_str(body, "content_base64");
- const std::string content = json_str(body, "content");
- bytes = b64.empty() ? content : b64_decode(b64);
- }
- if (path.empty()) {
- reply_err(resp, "path required");
- return;
- }
- std::string err;
- if (!files::write_chunk(path, offset, bytes, total, err)) {
- reply_err(resp, err);
- return;
- }
- ylib::json data;
- data["path"] = path;
- data["offset"] = static_cast<int64>(offset);
- data["written"] = static_cast<int64>(bytes.size());
- const uint64_t next = offset + bytes.size();
- if (total > 0) {
- data["total"] = static_cast<int64>(total);
- data["done"] = next >= total;
- } else {
- data["done"] = true;
- }
- reply_ok(resp, data, "uploaded");
- }
- void h_files_download(request* req, response* resp) {
- if (!require_method(req, resp, "GET")) {
- return;
- }
- std::string path = url_param(req, "path");
- std::string abs, err;
- if (!files::resolve_path(path, abs, err)) {
- reply_err(resp, err);
- return;
- }
- if (!path_exists(abs) || is_dir(abs)) {
- reply_err(resp, "file not found");
- return;
- }
- std::string name = fs::path(abs).filename().string();
- if (name.empty()) {
- name = "download";
- }
- // Keep original filename for browsers (ASCII fallback + RFC5987 UTF-8).
- std::string safe;
- for (unsigned char c : name) {
- if (c == '"' || c == '\\' || c < 0x20) {
- safe.push_back('_');
- } else {
- safe.push_back(static_cast<char>(c));
- }
- }
- std::string encoded;
- static const char* hex = "0123456789ABCDEF";
- for (unsigned char c : name) {
- if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
- (c >= '0' && c <= '9') || c == '.' || c == '_' || c == '-') {
- encoded.push_back(static_cast<char>(c));
- } else {
- encoded.push_back('%');
- encoded.push_back(hex[c >> 4]);
- encoded.push_back(hex[c & 0xF]);
- }
- }
- (*resp->headers())["Content-Disposition"] =
- "attachment; filename=\"" + safe + "\"; filename*=UTF-8''" + encoded;
- (*resp->headers())["Content-Type"] = "application/octet-stream";
- resp->send_file(abs);
- }
- void register_routes(ylib::network::http::router* router) {
- // Public endpoints
- reg(router, "/api/ping", h_ping, false);
- reg(router, "/api/auth/captcha", h_auth_captcha, false);
- reg(router, "/api/auth/login", h_auth_login, false);
- reg(router, "/api/auth/logout", h_auth_logout, false);
- reg(router, "/api/auth/me", h_auth_me, false);
- reg(router, "/api/status", h_status);
- reg(router, "/api/settings", h_settings);
- reg(router, "/api/self/version", h_self_version);
- reg(router, "/api/self/check", h_self_check);
- reg(router, "/api/self/update", h_self_update);
- reg(router, "/api/system/metrics", h_system_metrics);
- reg(router, "/api/system/metrics/history", h_system_metrics_history);
- reg(router, "/api/system/processes", h_system_processes);
- reg(router, "/api/system/processes/kill", h_system_processes_kill);
- router->subscribe()->add(
- R"(/api/shell/ws(?:\?.*)?)", "",
- [](request* req, response* resp, websocket_message* ws, const std::string&,
- const std::string&) {
- // 鉴权在 upgrade 内用 ticket;此处不要 reply_err JSON。
- system::shell_ws_handler(req, resp, ws);
- });
- router->on_close([](uint64 connid, websocket_message*) {
- system::shell_on_conn_close(static_cast<uint64_t>(connid));
- });
- reg(router, "/api/shell/ticket", h_shell_ticket);
- reg(router, "/api/tasks", h_tasks_list);
- reg(router, "/api/tasks/log", h_tasks_log);
- reg(router, "/api/tasks/clear", h_tasks_clear);
- reg(router, "/api/schedule/jobs", h_schedule_jobs);
- reg(router, "/api/schedule/jobs/delete", h_schedule_jobs_delete);
- reg(router, "/api/schedule/jobs/enable", h_schedule_jobs_enable);
- reg(router, "/api/schedule/jobs/run", h_schedule_jobs_run);
- reg(router, "/api/schedule/logs", h_schedule_logs);
- reg(router, "/api/nginx/status", h_nginx_status);
- reg(router, "/api/nginx/install", h_nginx_install);
- reg(router, "/api/nginx/uninstall", h_nginx_uninstall);
- reg(router, "/api/nginx/start", h_nginx_start);
- reg(router, "/api/nginx/stop", h_nginx_stop);
- reg(router, "/api/nginx/reload", h_nginx_reload);
- reg(router, "/api/nginx/config", h_nginx_config);
- reg(router, "/api/fastweb/status", h_fastweb_status);
- reg(router, "/api/fastweb/install", h_fastweb_install);
- reg(router, "/api/fastweb/uninstall", h_fastweb_uninstall);
- reg(router, "/api/fastweb/modules", h_fastweb_modules);
- reg(router, "/api/fastweb/modules/install", h_fastweb_module_install);
- reg(router, "/api/fastweb/modules/uninstall", h_fastweb_module_uninstall);
- reg(router, "/api/mysql/status", h_mysql_status);
- reg(router, "/api/mysql/install", h_mysql_install);
- reg(router, "/api/mysql/uninstall", h_mysql_uninstall);
- reg(router, "/api/mysql/start", h_mysql_start);
- reg(router, "/api/mysql/stop", h_mysql_stop);
- reg(router, "/api/mysql/root/password", h_mysql_root_password);
- reg(router, "/api/mysql/databases", h_mysql_databases);
- reg(router, "/api/mysql/databases/drop", h_mysql_databases_drop);
- reg(router, "/api/mysql/databases/access", h_mysql_databases_access);
- reg(router, "/api/mysql/exec", h_mysql_exec);
- reg(router, "/api/redis/status", h_redis_status);
- reg(router, "/api/redis/install", h_redis_install);
- reg(router, "/api/redis/uninstall", h_redis_uninstall);
- reg(router, "/api/redis/start", h_redis_start);
- reg(router, "/api/redis/stop", h_redis_stop);
- reg(router, "/api/redis/config", h_redis_config);
- reg(router, "/api/redis/exec", h_redis_exec);
- reg(router, "/api/websites", h_websites);
- reg(router, "/api/websites/start", h_websites_start);
- reg(router, "/api/websites/stop", h_websites_stop);
- reg(router, "/api/websites/restart", h_websites_restart);
- reg(router, "/api/websites/delete", h_websites_delete);
- reg(router, "/api/websites/update", h_websites_update);
- reg(router, "/api/websites/reorder", h_websites_reorder);
- reg(router, "/api/websites/proxies", h_websites_proxies);
- reg(router, "/api/websites/proxies/update", h_websites_proxies_update);
- reg(router, "/api/websites/proxies/delete", h_websites_proxies_delete);
- reg(router, "/api/websites/custom", h_websites_custom);
- reg(router, "/api/websites/logs", h_websites_logs);
- reg(router, "/api/websites/logs/purge", h_websites_logs_purge);
- reg(router, "/api/websites/analytics", h_websites_analytics);
- reg(router, "/api/websites/ssl/apply", h_websites_ssl_apply);
- reg(router, "/api/files/list", h_files_list);
- reg(router, "/api/files/mkdir", h_files_mkdir);
- reg(router, "/api/files/write", h_files_write);
- reg(router, "/api/files/read", h_files_read);
- reg(router, "/api/files/tail", h_files_tail);
- reg(router, "/api/files/rename", h_files_rename);
- reg(router, "/api/files/delete", h_files_delete);
- reg(router, "/api/files/upload", h_files_upload);
- reg(router, "/api/files/download", h_files_download);
- const std::string www = panel_www_dir();
- router->other([www](request* req, response* resp, websocket_message* ws) {
- // WebSocket 未命中订阅:绝不能 reply_err JSON,否则握手被 200+JSON 打断。
- if (ws) {
- if (ws->type ==
- ylib::network::http::HTTP_SERVER_WEBSOCKET_TYPE_UPGRADE) {
- resp->send_header(404, "Not Found");
- } else if (ws->type !=
- ylib::network::http::HTTP_SERVER_WEBSOCKET_TYPE_CLOSE) {
- resp->response_done();
- }
- return;
- }
- std::string path = req ? req->filepath() : "/";
- if (path.empty() || path == "/") {
- path = "/index.html";
- }
- if (path.rfind("/api/", 0) == 0) {
- reply_err(resp, "not found", 404);
- return;
- }
- if (path.find("..") != std::string::npos) {
- reply_err(resp, "forbidden", 403);
- return;
- }
- const bool is_asset =
- path.rfind("/assets/", 0) == 0 || path == "/favicon.ico";
- const bool is_login =
- path == "/login.html" || path == "/login" || path == "login.html";
- if (!is_asset && !is_login && !request_authed(req)) {
- resp->redirect("/login.html", false);
- return;
- }
- if (is_login && request_authed(req)) {
- resp->redirect("/", false);
- return;
- }
- while (!path.empty() && path[0] == '/') {
- path.erase(path.begin());
- }
- if (path == "login") {
- path = "login.html";
- }
- std::string file = join_path(www, path);
- if (is_dir(file)) {
- file = join_path(file, "index.html");
- }
- if (path_exists(file) && !is_dir(file)) {
- resp->send_file(file);
- return;
- }
- const std::string index = join_path(www, "index.html");
- if (path_exists(index)) {
- resp->send_file(index);
- return;
- }
- reply_err(resp, "panel not found: " + www, 404);
- });
- }
- } // namespace
- bool run(const std::string& listen_addr, uint16_t listen_port) {
- (void)listen_addr; // ylib HttpServer always binds 0.0.0.0
- ensure_dir(software_root());
- ensure_dir(conf_root());
- ensure_dir(join_path(conf_root(), "ssl"));
- ensure_dir(wwwroot_dir());
- {
- std::string aerr;
- if (!auth::init(aerr)) {
- std::cerr << "apiserver auth init failed: " << aerr << "\n";
- log_error("auth init failed: " + aerr);
- return false;
- }
- }
- if (!store::init()) {
- std::cerr << "apiserver sqlite init failed: " << store::database_path()
- << "\n";
- log_error("sqlite init failed path=" + store::database_path());
- return false;
- }
- tasks::start();
- weblog::start();
- system::history_start();
- schedule::start();
- selfupdate::init(listen_addr, listen_port);
- log_info("ngs apiserver starting listen=" + listen_addr + ":" +
- std::to_string(listen_port));
- install_signal_handlers();
- auto* center = new ylib::network::http::center();
- g_center = center;
- auto fail_cleanup = [&]() {
- // Stop workers first so metrics/tasks do not keep running if close hangs.
- stop_background_services();
- if (center) {
- center->close();
- delete center;
- center = nullptr;
- }
- g_center = nullptr;
- };
- ylib::network::http::start_config config;
- ylib::network::http::website_config ws_config;
- ws_config.name = "ngs-api";
- // domain containing 0.0.0.0 matches any Host header in ylib.
- ylib::network::http::host_config host;
- host.domain = listen_addr.empty() ? kDefaultListenAddr : listen_addr;
- host.port = listen_port;
- host.ssl = false;
- ws_config.host.push_back(host);
- ws_config.router.threadpool.size = 8;
- ws_config.router.threadpool.queuemax = 10000;
- config.max_upload_size = 64 * 1024 * 1024;
- config.websocket_enable = true;
- config.website.push_back(ws_config);
- if (!center->create(config)) {
- std::cerr << "apiserver create failed: " << center->last_error() << "\n";
- log_error("apiserver create failed: " + center->last_error());
- fail_cleanup();
- return false;
- }
- auto* website = center->website_byname(ws_config.name);
- if (!website || !website->router()) {
- std::cerr << "apiserver website/router missing\n";
- log_error("apiserver website/router missing");
- fail_cleanup();
- return false;
- }
- register_routes(website->router());
- if (!center->start()) {
- std::cerr << "apiserver start failed: " << center->last_error() << "\n";
- log_error("apiserver start failed: " + center->last_error());
- fail_cleanup();
- return false;
- }
- // HPSocket may touch signal state during start; reinstall our handlers.
- install_signal_handlers();
- std::cout << "NGS API Server listening on http://" << host.domain << ":"
- << listen_port << "\n";
- std::cout << "Panel: http://127.0.0.1:" << listen_port << "/\n";
- std::cout << "Panel dir: " << panel_www_dir() << "\n";
- std::cout << "Docs: API.md\n";
- std::cout.flush();
- log_info("ngs apiserver listening port=" + std::to_string(listen_port) +
- " panel=" + panel_www_dir());
- while (g_running.load(std::memory_order_relaxed)) {
- std::this_thread::sleep_for(std::chrono::milliseconds(200));
- }
- std::cout << "Shutting down...\n";
- log_info("ngs apiserver stopping");
- stop_background_services();
- center->close();
- delete center;
- g_center = nullptr;
- return true;
- }
- } // namespace api
- } // namespace ngs
|