api_server.cpp 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862
  1. #include "api_server.h"
  2. #include "../auth/auth.h"
  3. #include "../files/files.h"
  4. #include "../software/fastweb/fastweb.h"
  5. #include "../software/mysql/mysql.h"
  6. #include "../software/nginx/nginx.h"
  7. #include "../software/redis/redis.h"
  8. #include "../ssl/acme.h"
  9. #include "../store/store.h"
  10. #include "../system/metrics.h"
  11. #include "../system/metrics_history.h"
  12. #include "../system/process.h"
  13. #include "../system/shell.h"
  14. #include "../schedule/schedule.h"
  15. #include "../selfupdate/selfupdate.h"
  16. #include "../tasks/tasks.h"
  17. #include "../utils.h"
  18. #include "../website/website.h"
  19. #include "../weblog/weblog.h"
  20. #include "net/http_center.h"
  21. #include "net/http_request.h"
  22. #include "net/http_response.h"
  23. #include "net/http_router.h"
  24. #include "net/http_subscribe.h"
  25. #include "net/http_website.h"
  26. #include "util/json.h"
  27. #include <atomic>
  28. #include <cctype>
  29. #include <chrono>
  30. #include <cstdint>
  31. #include <cstdlib>
  32. #include <csignal>
  33. #include <filesystem>
  34. #include <iostream>
  35. #include <string>
  36. #include <thread>
  37. #include <vector>
  38. namespace ngs {
  39. namespace api {
  40. namespace {
  41. namespace fs = std::filesystem;
  42. using ylib::network::http::request;
  43. using ylib::network::http::response;
  44. using ylib::network::http::websocket_message;
  45. std::atomic<bool> g_running{true};
  46. std::atomic<int> g_signal_count{0};
  47. ylib::network::http::center* g_center = nullptr;
  48. void stop_background_services() {
  49. schedule::stop();
  50. system::shell_shutdown();
  51. weblog::stop();
  52. system::history_stop();
  53. tasks::stop();
  54. }
  55. void on_signal(int) {
  56. // First signal: request graceful shutdown. Second: force-exit in case
  57. // close()/join is stuck (e.g. listen failed then center->close hangs).
  58. const int n = g_signal_count.fetch_add(1, std::memory_order_relaxed) + 1;
  59. g_running.store(false, std::memory_order_relaxed);
  60. if (n >= 2) {
  61. _Exit(1);
  62. }
  63. }
  64. void install_signal_handlers() {
  65. struct sigaction sa {};
  66. sa.sa_handler = on_signal;
  67. sigemptyset(&sa.sa_mask);
  68. sa.sa_flags = 0; // interrupt blocking sleeps (do not set SA_RESTART)
  69. sigaction(SIGINT, &sa, nullptr);
  70. sigaction(SIGTERM, &sa, nullptr);
  71. }
  72. ylib::json parse_body(request* req) {
  73. if (!req) {
  74. return ylib::json();
  75. }
  76. const std::string body = req->body().to_string();
  77. if (body.empty()) {
  78. return ylib::json();
  79. }
  80. try {
  81. return ylib::json::from(body);
  82. } catch (...) {
  83. return ylib::json();
  84. }
  85. }
  86. std::string json_str(const ylib::json& j, const std::string& key,
  87. const std::string& def = "") {
  88. if (j.is_empty() || !j.exist(key)) {
  89. return def;
  90. }
  91. return j[key].to<std::string>(true);
  92. }
  93. bool json_bool(const ylib::json& j, const std::string& key, bool def = false) {
  94. if (j.is_empty() || !j.exist(key)) {
  95. return def;
  96. }
  97. return j[key].to<bool>(true);
  98. }
  99. int json_int(const ylib::json& j, const std::string& key, int def = 0) {
  100. if (j.is_empty() || !j.exist(key)) {
  101. return def;
  102. }
  103. return j[key].to<int32>(true);
  104. }
  105. int hex_nibble(char c) {
  106. if (c >= '0' && c <= '9') {
  107. return c - '0';
  108. }
  109. if (c >= 'a' && c <= 'f') {
  110. return c - 'a' + 10;
  111. }
  112. if (c >= 'A' && c <= 'F') {
  113. return c - 'A' + 10;
  114. }
  115. return -1;
  116. }
  117. // ylib get_url_param 不解码,需自行处理 %XX / +
  118. std::string url_decode(const std::string& in) {
  119. std::string out;
  120. out.reserve(in.size());
  121. for (size_t i = 0; i < in.size(); ++i) {
  122. const char c = in[i];
  123. if (c == '+') {
  124. out.push_back(' ');
  125. continue;
  126. }
  127. if (c == '%' && i + 2 < in.size()) {
  128. const int hi = hex_nibble(in[i + 1]);
  129. const int lo = hex_nibble(in[i + 2]);
  130. if (hi >= 0 && lo >= 0) {
  131. out.push_back(static_cast<char>((hi << 4) | lo));
  132. i += 2;
  133. continue;
  134. }
  135. }
  136. out.push_back(c);
  137. }
  138. return out;
  139. }
  140. std::string url_param(request* req, const std::string& key,
  141. const std::string& def = "") {
  142. if (!req) {
  143. return def;
  144. }
  145. std::string value;
  146. if (req->get_url_param(key, value) && !value.empty()) {
  147. return url_decode(value);
  148. }
  149. return def;
  150. }
  151. uint64_t parse_u64(const std::string& s, uint64_t def = 0) {
  152. if (s.empty()) {
  153. return def;
  154. }
  155. try {
  156. size_t idx = 0;
  157. const unsigned long long v = std::stoull(s, &idx, 10);
  158. if (idx == 0) {
  159. return def;
  160. }
  161. return static_cast<uint64_t>(v);
  162. } catch (...) {
  163. return def;
  164. }
  165. }
  166. std::string trim_ascii(const std::string& s) {
  167. size_t b = 0;
  168. while (b < s.size() && (s[b] == ' ' || s[b] == '\t')) {
  169. ++b;
  170. }
  171. size_t e = s.size();
  172. while (e > b && (s[e - 1] == ' ' || s[e - 1] == '\t')) {
  173. --e;
  174. }
  175. return s.substr(b, e - b);
  176. }
  177. // Prefer proxy headers when present; otherwise TCP peer address.
  178. std::string request_client_ip(request* req) {
  179. if (!req) {
  180. return "";
  181. }
  182. std::string v;
  183. if (req->header("X-Real-IP", v) || req->header("x-real-ip", v)) {
  184. v = trim_ascii(v);
  185. if (!v.empty()) {
  186. return v;
  187. }
  188. }
  189. if (req->header("X-Forwarded-For", v) ||
  190. req->header("x-forwarded-for", v)) {
  191. const auto comma = v.find(',');
  192. v = trim_ascii(comma == std::string::npos ? v : v.substr(0, comma));
  193. if (!v.empty()) {
  194. return v;
  195. }
  196. }
  197. try {
  198. return trim_ascii(req->remote().address);
  199. } catch (...) {
  200. return "";
  201. }
  202. }
  203. std::string b64_decode(const std::string& in) {
  204. static const int8_t kTable[256] = {
  205. -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  206. -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  207. -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,
  208. 52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,
  209. -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,
  210. 15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,
  211. -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,
  212. 41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1};
  213. std::string out;
  214. out.reserve(in.size() * 3 / 4);
  215. int val = 0, valb = -8;
  216. for (unsigned char c : in) {
  217. if (c == '=' || c == '\n' || c == '\r' || c == ' ') {
  218. continue;
  219. }
  220. const int8_t d = kTable[c];
  221. if (d < 0) {
  222. continue;
  223. }
  224. val = (val << 6) + d;
  225. valb += 6;
  226. if (valb >= 0) {
  227. out.push_back(static_cast<char>((val >> valb) & 0xFF));
  228. valb -= 8;
  229. }
  230. }
  231. return out;
  232. }
  233. void reply_ok(response* resp, const ylib::json& data = ylib::json(),
  234. const std::string& msg = "ok") {
  235. ylib::json out;
  236. out["code"] = 200;
  237. out["msg"] = msg;
  238. out["data"] = data;
  239. resp->send(out);
  240. }
  241. void reply_err(response* resp, const std::string& msg, int code = -1) {
  242. ylib::json out;
  243. // ylib: operator=(int32) 会先转 uint64,负数会变成超大数;用 double 保留 -1 等错误码
  244. out["code"] = static_cast<double>(code);
  245. out["msg"] = msg;
  246. out["data"] = ylib::json();
  247. resp->send(out);
  248. }
  249. bool require_method(request* req, response* resp, const std::string& method) {
  250. if (req->method() == method) {
  251. return true;
  252. }
  253. reply_err(resp, "method not allowed, expect " + method, 405);
  254. return false;
  255. }
  256. std::string request_cookie(request* req) {
  257. if (!req) {
  258. return "";
  259. }
  260. std::string v;
  261. if (req->header("Cookie", v) || req->header("cookie", v)) {
  262. return v;
  263. }
  264. return "";
  265. }
  266. std::string request_session_token(request* req) {
  267. return auth::session_from_cookie(request_cookie(req));
  268. }
  269. bool request_authed(request* req, std::string* username = nullptr) {
  270. return auth::session_valid(request_session_token(req), username);
  271. }
  272. void set_session_cookie(response* resp, const std::string& token, bool clear) {
  273. if (!resp || !resp->headers()) {
  274. return;
  275. }
  276. if (clear || token.empty()) {
  277. (*resp->headers())["Set-Cookie"] =
  278. "ngs_session=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0";
  279. return;
  280. }
  281. (*resp->headers())["Set-Cookie"] =
  282. "ngs_session=" + token +
  283. "; Path=/; HttpOnly; SameSite=Lax; Max-Age=604800";
  284. }
  285. bool require_auth(request* req, response* resp) {
  286. if (request_authed(req)) {
  287. return true;
  288. }
  289. reply_err(resp, "未登录或会话已过期", 401);
  290. return false;
  291. }
  292. using Handler = void (*)(request*, response*);
  293. void reg(ylib::network::http::router* router, const std::string& path,
  294. Handler handler, bool auth_required = true) {
  295. router->subscribe()->add(
  296. path, "",
  297. [handler, auth_required](request* req, response* resp, websocket_message*,
  298. const std::string&, const std::string&) {
  299. if (auth_required && !require_auth(req, resp)) {
  300. return;
  301. }
  302. handler(req, resp);
  303. });
  304. }
  305. // ---- handlers ----
  306. std::string trim_copy(std::string s) {
  307. size_t a = 0;
  308. while (a < s.size() &&
  309. std::isspace(static_cast<unsigned char>(s[a]))) {
  310. ++a;
  311. }
  312. size_t b = s.size();
  313. while (b > a && std::isspace(static_cast<unsigned char>(s[b - 1]))) {
  314. --b;
  315. }
  316. return s.substr(a, b - a);
  317. }
  318. std::string panel_display_name() {
  319. std::string n = trim_copy(store::get_setting("panel.name", ""));
  320. if (n.empty()) {
  321. return "NGS";
  322. }
  323. if (n.size() > 64) {
  324. n.resize(64);
  325. }
  326. return n;
  327. }
  328. ylib::json settings_json() {
  329. ylib::json data;
  330. data["panel_name"] = panel_display_name();
  331. return data;
  332. }
  333. void h_ping(request* req, response* resp) {
  334. if (!require_method(req, resp, "GET")) {
  335. return;
  336. }
  337. ylib::json data;
  338. data["name"] = "ngs";
  339. data["panel_name"] = panel_display_name();
  340. data["listen"] = std::string(kDefaultListenAddr) + ":" +
  341. std::to_string(kDefaultListenPort);
  342. reply_ok(resp, data);
  343. }
  344. void h_auth_captcha(request* req, response* resp) {
  345. if (!require_method(req, resp, "GET")) {
  346. return;
  347. }
  348. const auth::CaptchaImage img = auth::create_captcha();
  349. if (img.bmp.empty() || img.id.empty()) {
  350. reply_err(resp, "验证码生成失败", 500);
  351. return;
  352. }
  353. if (resp->headers()) {
  354. (*resp->headers())["Set-Cookie"] =
  355. "ngs_captcha=" + img.id +
  356. "; Path=/; HttpOnly; SameSite=Lax; Max-Age=300";
  357. (*resp->headers())["Content-Type"] = "image/bmp";
  358. (*resp->headers())["Cache-Control"] = "no-store, no-cache, must-revalidate";
  359. (*resp->headers())["Pragma"] = "no-cache";
  360. }
  361. resp->send(img.bmp);
  362. }
  363. void h_auth_login(request* req, response* resp) {
  364. if (!require_method(req, resp, "POST")) {
  365. return;
  366. }
  367. int64_t retry_after = 0;
  368. if (auth::login_locked(&retry_after)) {
  369. const int64_t mins = (retry_after + 59) / 60;
  370. reply_err(resp,
  371. "登录失败次数过多,已锁定约 " + std::to_string(mins) +
  372. " 分钟(重启 NGS 可立即解除)",
  373. 429);
  374. return;
  375. }
  376. auto body = parse_body(req);
  377. const std::string username = json_str(body, "username");
  378. const std::string password = json_str(body, "password");
  379. const std::string captcha = json_str(body, "captcha");
  380. if (username.empty() || password.empty()) {
  381. reply_err(resp, "请输入账号和密码", 400);
  382. return;
  383. }
  384. if (captcha.empty()) {
  385. reply_err(resp, "请输入验证码", 400);
  386. return;
  387. }
  388. const std::string captcha_id =
  389. auth::captcha_from_cookie(request_cookie(req));
  390. if (!auth::consume_captcha(captcha_id, captcha)) {
  391. reply_err(resp, "验证码错误或已过期", 400);
  392. return;
  393. }
  394. if (!auth::verify(username, password)) {
  395. auth::record_login_failure();
  396. if (auth::login_locked(&retry_after)) {
  397. reply_err(resp,
  398. "账号或密码错误,已连续失败 3 次,登录锁定 10 分钟"
  399. "(重启 NGS 可立即解除)",
  400. 429);
  401. return;
  402. }
  403. reply_err(resp, "账号或密码错误", 401);
  404. return;
  405. }
  406. auth::clear_login_failures();
  407. const std::string token = auth::create_session(username);
  408. set_session_cookie(resp, token, false);
  409. ylib::json data;
  410. data["username"] = username;
  411. reply_ok(resp, data, "logged in");
  412. }
  413. void h_auth_logout(request* req, response* resp) {
  414. if (!require_method(req, resp, "POST")) {
  415. return;
  416. }
  417. auth::destroy_session(request_session_token(req));
  418. set_session_cookie(resp, "", true);
  419. reply_ok(resp, ylib::json(), "logged out");
  420. }
  421. void h_auth_me(request* req, response* resp) {
  422. if (!require_method(req, resp, "GET")) {
  423. return;
  424. }
  425. std::string username;
  426. if (!request_authed(req, &username)) {
  427. reply_err(resp, "未登录", 401);
  428. return;
  429. }
  430. ylib::json data;
  431. data["username"] = username;
  432. reply_ok(resp, data);
  433. }
  434. void reply_task_queued(response* resp, const std::string& task_id) {
  435. ylib::json data;
  436. data["task_id"] = task_id;
  437. data["active"] = tasks::active_count();
  438. reply_ok(resp, data, "task queued");
  439. }
  440. ylib::json task_to_json(const tasks::Task& t) {
  441. ylib::json item;
  442. item["id"] = t.id;
  443. item["type"] = t.type;
  444. item["title"] = t.title;
  445. item["status"] = tasks::status_str(t.status);
  446. item["created_at"] = static_cast<double>(t.created_at);
  447. item["started_at"] = static_cast<double>(t.started_at);
  448. item["finished_at"] = static_cast<double>(t.finished_at);
  449. item["message"] = t.message;
  450. item["log_lines"] = static_cast<double>(t.log_lines);
  451. return item;
  452. }
  453. void h_tasks_list(request* req, response* resp) {
  454. if (!require_method(req, resp, "GET")) {
  455. return;
  456. }
  457. ylib::json arr;
  458. for (const auto& t : tasks::list(false)) {
  459. arr.push_back(task_to_json(t));
  460. }
  461. ylib::json data;
  462. data["active"] = tasks::active_count();
  463. data["tasks"] = arr;
  464. reply_ok(resp, data);
  465. }
  466. void h_tasks_log(request* req, response* resp) {
  467. if (!require_method(req, resp, "GET")) {
  468. return;
  469. }
  470. const std::string id = url_param(req, "id");
  471. size_t off = 0;
  472. try {
  473. off = static_cast<size_t>(std::stoul(url_param(req, "offset", "0")));
  474. } catch (...) {
  475. off = 0;
  476. }
  477. std::vector<std::string> lines;
  478. size_t next = 0;
  479. size_t log_base = 0;
  480. bool truncated = false;
  481. tasks::Status st = tasks::Status::Pending;
  482. std::string message, err;
  483. if (!tasks::get_logs(id, off, lines, next, log_base, truncated, st, message,
  484. err)) {
  485. reply_err(resp, err);
  486. return;
  487. }
  488. ylib::json arr;
  489. for (const auto& line : lines) {
  490. arr.push_back(line);
  491. }
  492. ylib::json data;
  493. data["id"] = id;
  494. data["status"] = tasks::status_str(st);
  495. data["message"] = message;
  496. data["offset"] = static_cast<double>(truncated ? log_base : off);
  497. data["next_offset"] = static_cast<double>(next);
  498. data["log_base"] = static_cast<double>(log_base);
  499. data["truncated"] = truncated;
  500. data["lines"] = arr;
  501. reply_ok(resp, data);
  502. }
  503. void h_tasks_clear(request* req, response* resp) {
  504. if (!require_method(req, resp, "POST")) {
  505. return;
  506. }
  507. tasks::clear_finished();
  508. ylib::json data;
  509. data["active"] = tasks::active_count();
  510. reply_ok(resp, data, "cleared");
  511. }
  512. ylib::json schedule_job_to_json(const schedule::Job& j) {
  513. ylib::json item;
  514. item["id"] = j.id;
  515. item["name"] = j.name;
  516. item["enabled"] = j.enabled;
  517. item["url"] = j.url;
  518. item["method"] = j.method;
  519. item["interval"] = j.interval;
  520. item["unit"] = j.unit;
  521. item["timeout_sec"] = j.timeout_sec;
  522. item["continue_when_busy"] = j.continue_when_busy;
  523. item["created_ms"] = static_cast<double>(j.created_ms);
  524. item["next_run_ms"] = static_cast<double>(j.next_run_ms);
  525. item["last_run_ms"] = static_cast<double>(j.last_run_ms);
  526. item["last_ok"] = j.last_ok;
  527. item["last_status"] = j.last_status;
  528. item["last_error"] = j.last_error;
  529. item["inflight"] = j.inflight;
  530. item["interval_ms"] =
  531. static_cast<double>(schedule::interval_to_ms(j.interval, j.unit));
  532. return item;
  533. }
  534. ylib::json schedule_log_to_json(const schedule::LogEntry& e) {
  535. ylib::json item;
  536. item["id"] = static_cast<double>(e.id);
  537. item["job_id"] = e.job_id;
  538. item["time_ms"] = static_cast<double>(e.time_ms);
  539. item["ok"] = e.ok;
  540. item["status_code"] = e.status_code;
  541. item["duration_ms"] = static_cast<double>(e.duration_ms);
  542. item["error"] = e.error;
  543. item["response_preview"] = e.response_preview;
  544. return item;
  545. }
  546. void h_schedule_jobs(request* req, response* resp) {
  547. if (req->method() == "GET") {
  548. ylib::json arr;
  549. for (const auto& j : schedule::list_jobs()) {
  550. arr.push_back(schedule_job_to_json(j));
  551. }
  552. ylib::json data;
  553. data["jobs"] = arr;
  554. reply_ok(resp, data);
  555. return;
  556. }
  557. if (!require_method(req, resp, "POST")) {
  558. return;
  559. }
  560. const ylib::json body = parse_body(req);
  561. schedule::Job job;
  562. job.id = json_str(body, "id");
  563. job.name = json_str(body, "name");
  564. job.enabled = json_bool(body, "enabled", true);
  565. job.url = json_str(body, "url");
  566. job.method = json_str(body, "method", "GET");
  567. job.interval = json_int(body, "interval", 60);
  568. job.unit = json_str(body, "unit", "sec");
  569. job.timeout_sec = json_int(body, "timeout_sec", 30);
  570. job.continue_when_busy = json_bool(body, "continue_when_busy", false);
  571. std::string err;
  572. if (!schedule::upsert_job(job, err)) {
  573. reply_err(resp, err, 400);
  574. return;
  575. }
  576. reply_ok(resp, schedule_job_to_json(job), "saved");
  577. }
  578. void h_schedule_jobs_delete(request* req, response* resp) {
  579. if (!require_method(req, resp, "POST")) {
  580. return;
  581. }
  582. const ylib::json body = parse_body(req);
  583. const std::string id = json_str(body, "id");
  584. std::string err;
  585. if (!schedule::delete_job(id, err)) {
  586. reply_err(resp, err, 400);
  587. return;
  588. }
  589. reply_ok(resp, ylib::json(), "deleted");
  590. }
  591. void h_schedule_jobs_enable(request* req, response* resp) {
  592. if (!require_method(req, resp, "POST")) {
  593. return;
  594. }
  595. const ylib::json body = parse_body(req);
  596. const std::string id = json_str(body, "id");
  597. const bool enabled = json_bool(body, "enabled", true);
  598. std::string err;
  599. if (!schedule::set_enabled(id, enabled, err)) {
  600. reply_err(resp, err, 400);
  601. return;
  602. }
  603. schedule::Job job;
  604. if (!schedule::get_job(id, job, err)) {
  605. reply_err(resp, err, 400);
  606. return;
  607. }
  608. reply_ok(resp, schedule_job_to_json(job), enabled ? "enabled" : "disabled");
  609. }
  610. void h_schedule_jobs_run(request* req, response* resp) {
  611. if (!require_method(req, resp, "POST")) {
  612. return;
  613. }
  614. const ylib::json body = parse_body(req);
  615. const std::string id = json_str(body, "id");
  616. std::string err;
  617. if (!schedule::run_now(id, err)) {
  618. reply_err(resp, err, 400);
  619. return;
  620. }
  621. reply_ok(resp, ylib::json(), "started");
  622. }
  623. void h_schedule_logs(request* req, response* resp) {
  624. if (req->method() == "GET") {
  625. const std::string job_id = url_param(req, "job_id");
  626. int limit = 80;
  627. try {
  628. limit = std::stoi(url_param(req, "limit", "80"));
  629. } catch (...) {
  630. limit = 80;
  631. }
  632. std::vector<schedule::LogEntry> logs;
  633. std::string err;
  634. if (!schedule::list_logs(job_id, limit, logs, err)) {
  635. reply_err(resp, err);
  636. return;
  637. }
  638. ylib::json arr;
  639. for (const auto& e : logs) {
  640. arr.push_back(schedule_log_to_json(e));
  641. }
  642. ylib::json data;
  643. data["logs"] = arr;
  644. reply_ok(resp, data);
  645. return;
  646. }
  647. if (!require_method(req, resp, "POST")) {
  648. return;
  649. }
  650. // clear logs
  651. const ylib::json body = parse_body(req);
  652. const std::string job_id = json_str(body, "job_id");
  653. std::string err;
  654. if (!schedule::clear_logs(job_id, err)) {
  655. reply_err(resp, err, 400);
  656. return;
  657. }
  658. reply_ok(resp, ylib::json(), "cleared");
  659. }
  660. void h_status(request* req, response* resp) {
  661. if (!require_method(req, resp, "GET")) {
  662. return;
  663. }
  664. ylib::json data;
  665. ylib::json nginx;
  666. nginx["installed"] = nginx::is_installed();
  667. nginx["running"] = nginx::is_running();
  668. nginx["version"] = nginx::installed_version();
  669. nginx["conf"] = nginx::conf_file();
  670. data["nginx"] = nginx;
  671. ylib::json fw;
  672. fw["installed"] = fastweb::is_installed();
  673. fw["version"] = fastweb::installed_version();
  674. data["fastweb"] = fw;
  675. ylib::json my;
  676. my["installed"] = mysql::is_installed();
  677. my["running"] = mysql::is_running();
  678. my["version"] = mysql::installed_version();
  679. my["port"] = mysql::kDefaultPort;
  680. my["conf"] = mysql::conf_file();
  681. data["mysql"] = my;
  682. ylib::json rd;
  683. rd["installed"] = redis::is_installed();
  684. rd["running"] = redis::is_running();
  685. rd["version"] = redis::installed_version();
  686. rd["port"] = redis::listen_port();
  687. rd["conf"] = redis::conf_file();
  688. rd["install_dir"] = redis::install_dir();
  689. rd["bin"] = redis::bin_path();
  690. data["redis"] = rd;
  691. data["sites"] = static_cast<int>(website::list_sites().size());
  692. data["panel_name"] = panel_display_name();
  693. reply_ok(resp, data);
  694. }
  695. void h_settings(request* req, response* resp) {
  696. const std::string method = req->method();
  697. if (method == "GET") {
  698. reply_ok(resp, settings_json());
  699. return;
  700. }
  701. if (method == "POST") {
  702. const auto body = parse_body(req);
  703. std::string name = trim_copy(json_str(body, "panel_name"));
  704. if (name.empty()) {
  705. reply_err(resp, "请填写网站名称");
  706. return;
  707. }
  708. if (name.size() > 64) {
  709. reply_err(resp, "网站名称最多 64 个字符");
  710. return;
  711. }
  712. for (unsigned char c : name) {
  713. if (c < 0x20) {
  714. reply_err(resp, "网站名称不能包含控制字符");
  715. return;
  716. }
  717. }
  718. if (!store::set_setting("panel.name", name)) {
  719. reply_err(resp, "保存失败");
  720. return;
  721. }
  722. reply_ok(resp, settings_json(), "已保存");
  723. return;
  724. }
  725. reply_err(resp, "method not allowed", 405);
  726. }
  727. ylib::json self_info_json(const selfupdate::Info& info) {
  728. ylib::json data;
  729. data["source_dir"] = info.source_dir;
  730. data["binary_dir"] = info.binary_dir;
  731. data["branch"] = info.branch;
  732. data["commit"] = info.commit;
  733. data["commit_short"] = info.commit_short;
  734. data["commit_date"] = info.commit_date;
  735. data["subject"] = info.subject;
  736. data["remote"] = info.remote;
  737. data["remote_url"] = info.remote_url;
  738. data["remote_commit"] = info.remote_commit;
  739. data["remote_commit_short"] = info.remote_commit_short;
  740. data["ahead"] = info.ahead;
  741. data["behind"] = info.behind;
  742. data["dirty"] = info.dirty;
  743. data["has_repo"] = info.has_repo;
  744. data["has_remote"] = info.has_remote;
  745. data["update_available"] = info.update_available;
  746. data["in_tmux"] = info.in_tmux;
  747. data["tmux_pane"] = info.tmux_pane;
  748. data["error"] = info.error;
  749. return data;
  750. }
  751. void h_self_version(request* req, response* resp) {
  752. if (!require_method(req, resp, "GET")) {
  753. return;
  754. }
  755. selfupdate::Info info;
  756. std::string err;
  757. selfupdate::inspect(info, false, &err);
  758. reply_ok(resp, self_info_json(info));
  759. }
  760. void h_self_check(request* req, response* resp) {
  761. if (!require_method(req, resp, "POST")) {
  762. return;
  763. }
  764. selfupdate::Info info;
  765. std::string err;
  766. if (!selfupdate::inspect(info, true, &err) && !info.has_repo) {
  767. reply_err(resp, err.empty() ? "检查更新失败" : err);
  768. return;
  769. }
  770. ylib::json data = self_info_json(info);
  771. const std::string msg = info.update_available
  772. ? ("发现 " + std::to_string(info.behind) + " 个新提交")
  773. : (info.error.empty() ? "已是最新" : info.error);
  774. reply_ok(resp, data, msg);
  775. }
  776. void h_self_update(request* req, response* resp) {
  777. if (!require_method(req, resp, "POST")) {
  778. return;
  779. }
  780. std::string err;
  781. const std::string id = tasks::enqueue(
  782. "self.update", "更新面板",
  783. []() {
  784. std::string e;
  785. if (!selfupdate::apply_update(&e)) {
  786. if (!e.empty()) {
  787. log_error(e);
  788. }
  789. return false;
  790. }
  791. return true;
  792. },
  793. err);
  794. if (id.empty()) {
  795. reply_err(resp, err.empty() ? "enqueue failed" : err);
  796. return;
  797. }
  798. reply_task_queued(resp, id);
  799. }
  800. void h_nginx_status(request* req, response* resp) {
  801. if (!require_method(req, resp, "GET")) {
  802. return;
  803. }
  804. ylib::json data;
  805. data["installed"] = nginx::is_installed();
  806. data["running"] = nginx::is_running();
  807. data["version"] = nginx::installed_version();
  808. data["install_dir"] = nginx::install_dir();
  809. data["bin"] = nginx::bin_path();
  810. data["conf"] = nginx::conf_file();
  811. reply_ok(resp, data);
  812. }
  813. void h_nginx_install(request* req, response* resp) {
  814. if (!require_method(req, resp, "POST")) {
  815. return;
  816. }
  817. auto body = parse_body(req);
  818. std::string version = json_str(body, "version", nginx::kDefaultVersion);
  819. std::string err;
  820. const std::string id = tasks::enqueue(
  821. "nginx.install", "安装 Nginx " + version,
  822. [version]() { return nginx::install(version); }, err);
  823. if (id.empty()) {
  824. reply_err(resp, err.empty() ? "enqueue failed" : err);
  825. return;
  826. }
  827. reply_task_queued(resp, id);
  828. }
  829. void h_nginx_uninstall(request* req, response* resp) {
  830. if (!require_method(req, resp, "POST")) {
  831. return;
  832. }
  833. std::string err;
  834. const std::string id = tasks::enqueue(
  835. "nginx.uninstall", "卸载 Nginx", []() { return nginx::uninstall(); },
  836. err);
  837. if (id.empty()) {
  838. reply_err(resp, err.empty() ? "enqueue failed" : err);
  839. return;
  840. }
  841. reply_task_queued(resp, id);
  842. }
  843. void h_nginx_start(request* req, response* resp) {
  844. if (!require_method(req, resp, "POST")) {
  845. return;
  846. }
  847. if (!nginx::start()) {
  848. reply_err(resp, "nginx start failed");
  849. return;
  850. }
  851. reply_ok(resp, ylib::json(), "nginx started");
  852. }
  853. void h_nginx_stop(request* req, response* resp) {
  854. if (!require_method(req, resp, "POST")) {
  855. return;
  856. }
  857. if (!nginx::stop()) {
  858. reply_err(resp, "nginx stop failed");
  859. return;
  860. }
  861. reply_ok(resp, ylib::json(), "nginx stopped");
  862. }
  863. void h_nginx_reload(request* req, response* resp) {
  864. if (!require_method(req, resp, "POST")) {
  865. return;
  866. }
  867. if (!nginx::reload()) {
  868. reply_err(resp, "nginx reload failed");
  869. return;
  870. }
  871. reply_ok(resp, ylib::json(), "nginx reloaded");
  872. }
  873. void h_nginx_config(request* req, response* resp) {
  874. const std::string method = req->method();
  875. if (method == "GET") {
  876. nginx::QuickConfig cfg;
  877. std::string err;
  878. if (!nginx::read_quick_config(cfg, err)) {
  879. reply_err(resp, err.empty() ? "read nginx config failed" : err);
  880. return;
  881. }
  882. ylib::json data;
  883. data["worker_processes"] = cfg.worker_processes;
  884. data["worker_connections"] = cfg.worker_connections;
  885. data["keepalive_timeout"] = cfg.keepalive_timeout;
  886. data["client_max_body_size"] = cfg.client_max_body_size;
  887. data["gzip"] = cfg.gzip;
  888. data["conf"] = nginx::conf_file();
  889. data["running"] = nginx::is_running();
  890. reply_ok(resp, data);
  891. return;
  892. }
  893. if (method == "POST") {
  894. auto body = parse_body(req);
  895. nginx::QuickConfig cfg;
  896. std::string err;
  897. if (!nginx::read_quick_config(cfg, err)) {
  898. reply_err(resp, err.empty() ? "read nginx config failed" : err);
  899. return;
  900. }
  901. if (body.exist("worker_processes")) {
  902. cfg.worker_processes =
  903. json_str(body, "worker_processes", cfg.worker_processes);
  904. }
  905. if (body.exist("worker_connections")) {
  906. cfg.worker_connections =
  907. json_int(body, "worker_connections", cfg.worker_connections);
  908. }
  909. if (body.exist("keepalive_timeout")) {
  910. cfg.keepalive_timeout =
  911. json_str(body, "keepalive_timeout", cfg.keepalive_timeout);
  912. }
  913. if (body.exist("client_max_body_size")) {
  914. cfg.client_max_body_size =
  915. json_str(body, "client_max_body_size", cfg.client_max_body_size);
  916. }
  917. if (body.exist("gzip")) {
  918. cfg.gzip = json_bool(body, "gzip", cfg.gzip);
  919. }
  920. if (!nginx::apply_quick_config(cfg, err)) {
  921. reply_err(resp, err.empty() ? "apply nginx config failed" : err);
  922. return;
  923. }
  924. ylib::json data;
  925. data["worker_processes"] = cfg.worker_processes;
  926. data["worker_connections"] = cfg.worker_connections;
  927. data["keepalive_timeout"] = cfg.keepalive_timeout;
  928. data["client_max_body_size"] = cfg.client_max_body_size;
  929. data["gzip"] = cfg.gzip;
  930. data["conf"] = nginx::conf_file();
  931. data["running"] = nginx::is_running();
  932. reply_ok(resp, data, "nginx config updated");
  933. return;
  934. }
  935. reply_err(resp, "method not allowed", 405);
  936. }
  937. void h_fastweb_status(request* req, response* resp) {
  938. if (!require_method(req, resp, "GET")) {
  939. return;
  940. }
  941. ylib::json data;
  942. data["installed"] = fastweb::is_installed();
  943. data["version"] = fastweb::installed_version();
  944. data["install_dir"] = fastweb::install_dir();
  945. data["bin"] = fastweb::bin_path();
  946. reply_ok(resp, data);
  947. }
  948. void h_fastweb_install(request* req, response* resp) {
  949. if (!require_method(req, resp, "POST")) {
  950. return;
  951. }
  952. auto body = parse_body(req);
  953. const bool debug = json_bool(body, "debug", false);
  954. std::string err;
  955. const std::string id = tasks::enqueue(
  956. "fastweb.install", "安装 Fastweb",
  957. [debug]() { return fastweb::install(debug); }, err);
  958. if (id.empty()) {
  959. reply_err(resp, err.empty() ? "enqueue failed" : err);
  960. return;
  961. }
  962. reply_task_queued(resp, id);
  963. }
  964. void h_fastweb_uninstall(request* req, response* resp) {
  965. if (!require_method(req, resp, "POST")) {
  966. return;
  967. }
  968. std::string err;
  969. const std::string id = tasks::enqueue(
  970. "fastweb.uninstall", "卸载 Fastweb",
  971. []() { return fastweb::uninstall(); }, err);
  972. if (id.empty()) {
  973. reply_err(resp, err.empty() ? "enqueue failed" : err);
  974. return;
  975. }
  976. reply_task_queued(resp, id);
  977. }
  978. void h_fastweb_modules(request* req, response* resp) {
  979. if (!require_method(req, resp, "GET")) {
  980. return;
  981. }
  982. const std::string site = url_param(req, "site");
  983. if (site.empty()) {
  984. reply_err(resp, "缺少 site 参数", 400);
  985. return;
  986. }
  987. std::vector<fastweb::ModuleInfo> list;
  988. std::string err;
  989. if (!fastweb::list_modules(site, list, err)) {
  990. reply_err(resp, err.empty() ? "获取模块列表失败" : err);
  991. return;
  992. }
  993. ylib::json arr;
  994. for (const auto& m : list) {
  995. ylib::json item;
  996. item["id"] = m.id;
  997. item["name"] = m.name;
  998. item["name_en"] = m.name_en;
  999. item["desc"] = m.desc;
  1000. item["doc"] = m.doc;
  1001. item["icon"] = m.icon;
  1002. item["type"] = m.type;
  1003. item["download_type"] = m.download_type;
  1004. item["download_url"] = m.download_url;
  1005. item["installed"] = m.installed;
  1006. arr.push_back(item);
  1007. }
  1008. ylib::json data;
  1009. data["site"] = site;
  1010. data["catalog_url"] = fastweb::kModuleCatalogUrl;
  1011. data["modules"] = arr;
  1012. reply_ok(resp, data);
  1013. }
  1014. void h_fastweb_module_install(request* req, response* resp) {
  1015. if (!require_method(req, resp, "POST")) {
  1016. return;
  1017. }
  1018. auto body = parse_body(req);
  1019. const std::string site = json_str(body, "site");
  1020. const std::string name_en = json_str(body, "name_en");
  1021. if (site.empty() || name_en.empty()) {
  1022. reply_err(resp, "请指定 site 与 name_en", 400);
  1023. return;
  1024. }
  1025. std::string err;
  1026. const std::string id = tasks::enqueue(
  1027. "fastweb.module.install", "安装模块 " + name_en,
  1028. [site, name_en]() {
  1029. std::string e;
  1030. return fastweb::install_module(site, name_en, e);
  1031. },
  1032. err);
  1033. if (id.empty()) {
  1034. reply_err(resp, err.empty() ? "enqueue failed" : err);
  1035. return;
  1036. }
  1037. reply_task_queued(resp, id);
  1038. }
  1039. void h_fastweb_module_uninstall(request* req, response* resp) {
  1040. if (!require_method(req, resp, "POST")) {
  1041. return;
  1042. }
  1043. auto body = parse_body(req);
  1044. const std::string site = json_str(body, "site");
  1045. const std::string name_en = json_str(body, "name_en");
  1046. if (site.empty() || name_en.empty()) {
  1047. reply_err(resp, "请指定 site 与 name_en", 400);
  1048. return;
  1049. }
  1050. std::string err;
  1051. const std::string id = tasks::enqueue(
  1052. "fastweb.module.uninstall", "卸载模块 " + name_en,
  1053. [site, name_en]() {
  1054. std::string e;
  1055. return fastweb::uninstall_module(site, name_en, e);
  1056. },
  1057. err);
  1058. if (id.empty()) {
  1059. reply_err(resp, err.empty() ? "enqueue failed" : err);
  1060. return;
  1061. }
  1062. reply_task_queued(resp, id);
  1063. }
  1064. void h_mysql_status(request* req, response* resp) {
  1065. if (!require_method(req, resp, "GET")) {
  1066. return;
  1067. }
  1068. ylib::json data;
  1069. data["installed"] = mysql::is_installed();
  1070. data["running"] = mysql::is_running();
  1071. data["version"] = mysql::installed_version();
  1072. data["install_dir"] = mysql::install_dir();
  1073. data["port"] = mysql::kDefaultPort;
  1074. reply_ok(resp, data);
  1075. }
  1076. void h_mysql_install(request* req, response* resp) {
  1077. if (!require_method(req, resp, "POST")) {
  1078. return;
  1079. }
  1080. auto body = parse_body(req);
  1081. std::string version = json_str(body, "version", mysql::kDefaultVersion);
  1082. std::string err;
  1083. const std::string id = tasks::enqueue(
  1084. "mysql.install", "安装 MySQL " + version,
  1085. [version]() { return mysql::install(version); }, err);
  1086. if (id.empty()) {
  1087. reply_err(resp, err.empty() ? "enqueue failed" : err);
  1088. return;
  1089. }
  1090. reply_task_queued(resp, id);
  1091. }
  1092. void h_mysql_uninstall(request* req, response* resp) {
  1093. if (!require_method(req, resp, "POST")) {
  1094. return;
  1095. }
  1096. std::string err;
  1097. const std::string id = tasks::enqueue(
  1098. "mysql.uninstall", "卸载 MySQL", []() { return mysql::uninstall(); },
  1099. err);
  1100. if (id.empty()) {
  1101. reply_err(resp, err.empty() ? "enqueue failed" : err);
  1102. return;
  1103. }
  1104. reply_task_queued(resp, id);
  1105. }
  1106. void h_mysql_start(request* req, response* resp) {
  1107. if (!require_method(req, resp, "POST")) {
  1108. return;
  1109. }
  1110. if (!mysql::start()) {
  1111. reply_err(resp, "mysql start failed");
  1112. return;
  1113. }
  1114. reply_ok(resp, ylib::json(), "mysql started");
  1115. }
  1116. void h_mysql_stop(request* req, response* resp) {
  1117. if (!require_method(req, resp, "POST")) {
  1118. return;
  1119. }
  1120. if (!mysql::stop()) {
  1121. reply_err(resp, "mysql stop failed");
  1122. return;
  1123. }
  1124. reply_ok(resp, ylib::json(), "mysql stopped");
  1125. }
  1126. void h_mysql_root_password(request* req, response* resp) {
  1127. if (!require_method(req, resp, "POST")) {
  1128. return;
  1129. }
  1130. auto body = parse_body(req);
  1131. std::string password = json_str(body, "password");
  1132. if (password.empty()) {
  1133. reply_err(resp, "password required");
  1134. return;
  1135. }
  1136. if (!mysql::change_root_password(password)) {
  1137. reply_err(resp, "change root password failed");
  1138. return;
  1139. }
  1140. reply_ok(resp, ylib::json(), "root password updated");
  1141. }
  1142. void h_mysql_databases(request* req, response* resp) {
  1143. const std::string method = req->method();
  1144. if (method == "GET") {
  1145. ylib::json arr;
  1146. for (const auto& db : mysql::list_databases()) {
  1147. ylib::json item;
  1148. item["name"] = db.name;
  1149. item["user"] = db.user;
  1150. item["password"] = db.password;
  1151. item["access"] = db.access;
  1152. item["host"] = db.host;
  1153. arr.push_back(item);
  1154. }
  1155. reply_ok(resp, arr);
  1156. return;
  1157. }
  1158. if (method == "POST") {
  1159. auto body = parse_body(req);
  1160. std::string name = json_str(body, "name");
  1161. std::string user = json_str(body, "user");
  1162. std::string password = json_str(body, "password");
  1163. if (name.empty() || user.empty() || password.empty()) {
  1164. reply_err(resp, "name/user/password required");
  1165. return;
  1166. }
  1167. std::string err;
  1168. if (!mysql::create_database(name, user, password, &err)) {
  1169. reply_err(resp, err.empty() ? "create database failed" : err);
  1170. return;
  1171. }
  1172. reply_ok(resp, ylib::json(), "database created");
  1173. return;
  1174. }
  1175. reply_err(resp, "method not allowed", 405);
  1176. }
  1177. void h_mysql_databases_drop(request* req, response* resp) {
  1178. if (!require_method(req, resp, "POST")) {
  1179. return;
  1180. }
  1181. auto body = parse_body(req);
  1182. std::string name = json_str(body, "name");
  1183. if (name.empty()) {
  1184. reply_err(resp, "name required");
  1185. return;
  1186. }
  1187. if (!mysql::drop_database(name)) {
  1188. reply_err(resp, "drop database failed");
  1189. return;
  1190. }
  1191. reply_ok(resp, ylib::json(), "database dropped");
  1192. }
  1193. void h_mysql_exec(request* req, response* resp) {
  1194. if (!require_method(req, resp, "POST")) {
  1195. return;
  1196. }
  1197. const auto body = parse_body(req);
  1198. const std::string database = json_str(body, "database");
  1199. const std::string sql = json_str(body, "sql");
  1200. if (sql.empty()) {
  1201. reply_err(resp, "请输入 SQL");
  1202. return;
  1203. }
  1204. mysql::QueryResult result;
  1205. std::string err;
  1206. const auto t0 = std::chrono::steady_clock::now();
  1207. if (!mysql::exec_query(database, sql, result, &err)) {
  1208. reply_err(resp, err.empty() ? "执行失败" : err);
  1209. return;
  1210. }
  1211. const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  1212. std::chrono::steady_clock::now() - t0)
  1213. .count();
  1214. ylib::json data;
  1215. ylib::json columns;
  1216. for (const auto& c : result.columns) {
  1217. columns.push_back(c);
  1218. }
  1219. data["columns"] = columns;
  1220. ylib::json rows;
  1221. for (const auto& row : result.rows) {
  1222. ylib::json r;
  1223. for (const auto& cell : row) {
  1224. r.push_back(cell);
  1225. }
  1226. rows.push_back(r);
  1227. }
  1228. data["rows"] = rows;
  1229. data["row_count"] = result.row_count;
  1230. data["truncated"] = result.truncated;
  1231. data["message"] = result.message;
  1232. data["elapsed_ms"] = static_cast<int>(ms);
  1233. reply_ok(resp, data);
  1234. }
  1235. void h_mysql_databases_access(request* req, response* resp) {
  1236. if (!require_method(req, resp, "POST")) {
  1237. return;
  1238. }
  1239. auto body = parse_body(req);
  1240. std::string name = json_str(body, "name");
  1241. std::string mode = json_str(body, "mode");
  1242. std::string host = json_str(body, "host");
  1243. if (name.empty() || mode.empty()) {
  1244. reply_err(resp, "name/mode required");
  1245. return;
  1246. }
  1247. if (!mysql::set_database_access(name, mode, host)) {
  1248. reply_err(resp, "set database access failed");
  1249. return;
  1250. }
  1251. reply_ok(resp, ylib::json(), "database access updated");
  1252. }
  1253. ylib::json site_to_json(const website::SiteInfo& s) {
  1254. ylib::json item;
  1255. item["name"] = s.name;
  1256. item["type"] = website::type_key(s.type);
  1257. const auto tokens = website::domain_tokens(s);
  1258. item["domain"] = website::join_domains(tokens);
  1259. ylib::json domains;
  1260. for (const auto& t : tokens) {
  1261. domains.push_back(t);
  1262. }
  1263. item["domains"] = domains;
  1264. item["listen_port"] = s.listen_port;
  1265. item["upstream"] = s.upstream;
  1266. item["running"] = s.running;
  1267. item["conf"] = website::vhost_conf_path(s.name);
  1268. item["root"] = website::site_root_path(s.name);
  1269. const std::string log_dir = website::site_log_dir_path(s.name);
  1270. item["log_dir"] = log_dir;
  1271. item["access_log"] = join_path(log_dir, "access.log");
  1272. item["error_log"] = join_path(log_dir, "error.log");
  1273. item["log_db"] = weblog::db_path(website::site_key(s));
  1274. {
  1275. const weblog::LogUsage u = weblog::usage(website::site_key(s));
  1276. item["log_file_bytes"] = static_cast<int64>(u.file_bytes);
  1277. item["log_db_bytes"] = static_cast<int64>(u.db_bytes);
  1278. item["log_access_bytes"] = static_cast<int64>(u.access_bytes);
  1279. item["log_error_bytes"] = static_cast<int64>(u.error_bytes);
  1280. item["log_bytes"] = static_cast<int64>(u.file_bytes + u.db_bytes);
  1281. }
  1282. item["ssl_enable"] = s.ssl_enable;
  1283. item["ssl_cert"] = s.ssl_cert;
  1284. item["ssl_key"] = s.ssl_key;
  1285. item["ssl_port"] = s.ssl_port;
  1286. item["group_name"] = s.group_name;
  1287. item["sort_order"] = s.sort_order;
  1288. item["ssl_not_before"] = "";
  1289. item["ssl_not_after"] = "";
  1290. item["ssl_days_left"] = -1;
  1291. if (!s.ssl_cert.empty()) {
  1292. const ssl::CertInfo ci = ssl::read_cert_info(s.ssl_cert);
  1293. if (ci.ok) {
  1294. item["ssl_not_before"] = ci.not_before;
  1295. item["ssl_not_after"] = ci.not_after;
  1296. item["ssl_days_left"] = ci.days_left;
  1297. }
  1298. }
  1299. return item;
  1300. }
  1301. void h_websites(request* req, response* resp) {
  1302. const std::string method = req->method();
  1303. if (method == "GET") {
  1304. ylib::json arr;
  1305. for (const auto& s : website::list_sites()) {
  1306. arr.push_back(site_to_json(s));
  1307. }
  1308. reply_ok(resp, arr);
  1309. return;
  1310. }
  1311. if (method == "POST") {
  1312. auto body = parse_body(req);
  1313. website::CreateSiteRequest creq;
  1314. creq.name = json_str(body, "name");
  1315. std::string type = json_str(body, "type", "static");
  1316. if (!website::parse_type_key(type, creq.type)) {
  1317. reply_err(resp, "invalid type, expect static|fastweb");
  1318. return;
  1319. }
  1320. // "proxy" is accepted as alias of static for older clients.
  1321. if (type == "proxy") {
  1322. creq.type = website::SiteType::Static;
  1323. }
  1324. creq.domain = json_str(body, "domain");
  1325. if (body.exist("domains") && body["domains"].is_array()) {
  1326. std::string joined;
  1327. const auto& arr = body["domains"];
  1328. for (uint32 i = 0; i < arr.size(); ++i) {
  1329. std::string d = arr[i].to<std::string>(true);
  1330. if (d.empty()) {
  1331. continue;
  1332. }
  1333. if (!joined.empty()) {
  1334. joined.push_back(' ');
  1335. }
  1336. joined += d;
  1337. }
  1338. if (!joined.empty()) {
  1339. creq.domain = joined;
  1340. }
  1341. }
  1342. creq.listen_port = json_int(body, "listen_port", 0);
  1343. creq.upstream.clear();
  1344. creq.root = json_str(body, "root");
  1345. creq.group_name = json_str(body, "group_name");
  1346. if (creq.name.empty()) {
  1347. reply_err(resp, "name required");
  1348. return;
  1349. }
  1350. if (creq.domain.empty()) {
  1351. reply_err(resp, "domain required");
  1352. return;
  1353. }
  1354. std::string err;
  1355. if (!website::create_site(creq, err)) {
  1356. reply_err(resp, err.empty() ? "create site failed" : err);
  1357. return;
  1358. }
  1359. website::SiteInfo created;
  1360. website::find_site(creq.name, created);
  1361. reply_ok(resp, site_to_json(created), "site created");
  1362. return;
  1363. }
  1364. reply_err(resp, "method not allowed", 405);
  1365. }
  1366. void h_websites_start(request* req, response* resp) {
  1367. if (!require_method(req, resp, "POST")) {
  1368. return;
  1369. }
  1370. auto body = parse_body(req);
  1371. std::string name = json_str(body, "name");
  1372. if (name.empty()) {
  1373. reply_err(resp, "name required");
  1374. return;
  1375. }
  1376. std::string err;
  1377. if (!website::start_site(name, err)) {
  1378. reply_err(resp, err.empty() ? "start site failed" : err);
  1379. return;
  1380. }
  1381. reply_ok(resp, ylib::json(), "site started");
  1382. }
  1383. void h_websites_stop(request* req, response* resp) {
  1384. if (!require_method(req, resp, "POST")) {
  1385. return;
  1386. }
  1387. auto body = parse_body(req);
  1388. std::string name = json_str(body, "name");
  1389. if (name.empty()) {
  1390. reply_err(resp, "name required");
  1391. return;
  1392. }
  1393. std::string err;
  1394. if (!website::stop_site(name, err)) {
  1395. reply_err(resp, err.empty() ? "stop site failed" : err);
  1396. return;
  1397. }
  1398. reply_ok(resp, ylib::json(), "site stopped");
  1399. }
  1400. void h_websites_restart(request* req, response* resp) {
  1401. if (!require_method(req, resp, "POST")) {
  1402. return;
  1403. }
  1404. auto body = parse_body(req);
  1405. std::string name = json_str(body, "name");
  1406. if (name.empty()) {
  1407. reply_err(resp, "name required");
  1408. return;
  1409. }
  1410. std::string err;
  1411. if (!website::restart_site(name, err)) {
  1412. reply_err(resp, err.empty() ? "restart site failed" : err);
  1413. return;
  1414. }
  1415. reply_ok(resp, ylib::json(), "site restarted");
  1416. }
  1417. void h_websites_delete(request* req, response* resp) {
  1418. if (!require_method(req, resp, "POST")) {
  1419. return;
  1420. }
  1421. auto body = parse_body(req);
  1422. std::string name = json_str(body, "name");
  1423. if (name.empty()) {
  1424. reply_err(resp, "name required");
  1425. return;
  1426. }
  1427. const bool delete_files = json_bool(body, "delete_files", false);
  1428. std::string err;
  1429. if (!website::delete_site(name, err, delete_files)) {
  1430. reply_err(resp, err.empty() ? "delete site failed" : err);
  1431. return;
  1432. }
  1433. reply_ok(resp, ylib::json(),
  1434. delete_files ? "site and files deleted" : "site deleted");
  1435. }
  1436. void h_websites_update(request* req, response* resp) {
  1437. if (!require_method(req, resp, "POST")) {
  1438. return;
  1439. }
  1440. auto body = parse_body(req);
  1441. website::UpdateSiteRequest ureq;
  1442. ureq.name = json_str(body, "name");
  1443. if (ureq.name.empty()) {
  1444. reply_err(resp, "name required");
  1445. return;
  1446. }
  1447. if (body.exist("domains") && body["domains"].is_array()) {
  1448. std::string joined;
  1449. const auto& arr = body["domains"];
  1450. for (uint32 i = 0; i < arr.size(); ++i) {
  1451. std::string d = arr[i].to<std::string>(true);
  1452. if (d.empty()) {
  1453. continue;
  1454. }
  1455. if (!joined.empty()) {
  1456. joined.push_back(' ');
  1457. }
  1458. joined += d;
  1459. }
  1460. ureq.domain = joined;
  1461. } else {
  1462. ureq.domain = json_str(body, "domain");
  1463. }
  1464. ureq.listen_port = json_int(body, "listen_port", 0);
  1465. ureq.update_ssl = body.exist("ssl_enable") || body.exist("ssl_cert") ||
  1466. body.exist("ssl_key") || body.exist("ssl_port");
  1467. ureq.ssl_enable = json_bool(body, "ssl_enable", false);
  1468. ureq.ssl_cert = json_str(body, "ssl_cert");
  1469. ureq.ssl_key = json_str(body, "ssl_key");
  1470. ureq.ssl_port = json_int(body, "ssl_port", 443);
  1471. ureq.update_group = body.exist("group_name");
  1472. ureq.group_name = json_str(body, "group_name");
  1473. std::string err;
  1474. if (!website::update_site(ureq, err)) {
  1475. reply_err(resp, err.empty() ? "update site failed" : err);
  1476. return;
  1477. }
  1478. website::SiteInfo updated;
  1479. website::find_site(ureq.name, updated);
  1480. reply_ok(resp, site_to_json(updated), "site updated");
  1481. }
  1482. void h_websites_reorder(request* req, response* resp) {
  1483. if (!require_method(req, resp, "POST")) {
  1484. return;
  1485. }
  1486. auto body = parse_body(req);
  1487. if (!body.exist("items") || !body["items"].is_array()) {
  1488. reply_err(resp, "items array required");
  1489. return;
  1490. }
  1491. std::vector<website::SiteOrderItem> items;
  1492. const auto& arr = body["items"];
  1493. for (uint32 i = 0; i < arr.size(); ++i) {
  1494. const auto& j = arr[i];
  1495. website::SiteOrderItem it;
  1496. it.name = j.exist("name") ? j["name"].to<std::string>() : "";
  1497. it.group_name =
  1498. j.exist("group_name") ? j["group_name"].to<std::string>() : "";
  1499. try {
  1500. it.sort_order =
  1501. j.exist("sort_order") ? j["sort_order"].to<int>() : 0;
  1502. } catch (...) {
  1503. it.sort_order = 0;
  1504. }
  1505. if (it.name.empty()) {
  1506. reply_err(resp, "item.name required");
  1507. return;
  1508. }
  1509. items.push_back(it);
  1510. }
  1511. std::string err;
  1512. if (!website::reorder_sites(items, err)) {
  1513. reply_err(resp, err.empty() ? "reorder failed" : err);
  1514. return;
  1515. }
  1516. ylib::json out;
  1517. for (const auto& s : website::list_sites()) {
  1518. out.push_back(site_to_json(s));
  1519. }
  1520. reply_ok(resp, out, "sites reordered");
  1521. }
  1522. ylib::json url_proxy_to_json(const website::UrlProxyRule& r) {
  1523. ylib::json item;
  1524. item["id"] = r.id;
  1525. item["path"] = r.path;
  1526. item["target_type"] = r.target_type;
  1527. item["target"] = r.target;
  1528. item["host"] = r.host;
  1529. item["remark"] = r.remark;
  1530. return item;
  1531. }
  1532. void h_websites_proxies(request* req, response* resp) {
  1533. const std::string method = req ? req->method() : "";
  1534. if (method == "GET") {
  1535. const std::string name = url_param(req, "name");
  1536. if (name.empty()) {
  1537. reply_err(resp, "name required");
  1538. return;
  1539. }
  1540. std::string err;
  1541. auto rules = website::list_url_proxies(name, err);
  1542. if (!err.empty()) {
  1543. reply_err(resp, err);
  1544. return;
  1545. }
  1546. ylib::json arr;
  1547. for (const auto& r : rules) {
  1548. arr.push_back(url_proxy_to_json(r));
  1549. }
  1550. ylib::json data;
  1551. data["proxies"] = arr;
  1552. reply_ok(resp, data);
  1553. return;
  1554. }
  1555. if (method == "POST") {
  1556. auto body = parse_body(req);
  1557. const std::string name = json_str(body, "name");
  1558. if (name.empty()) {
  1559. reply_err(resp, "name required");
  1560. return;
  1561. }
  1562. website::UrlProxyRule rule;
  1563. rule.path = json_str(body, "path");
  1564. rule.target_type = json_str(body, "target_type", "url");
  1565. rule.target = json_str(body, "target");
  1566. rule.host = json_str(body, "host", "$http_host");
  1567. rule.remark = json_str(body, "remark");
  1568. std::string err;
  1569. if (!website::add_url_proxy(name, rule, err)) {
  1570. reply_err(resp, err.empty() ? "add url proxy failed" : err);
  1571. return;
  1572. }
  1573. auto rules = website::list_url_proxies(name, err);
  1574. ylib::json arr;
  1575. for (const auto& r : rules) {
  1576. arr.push_back(url_proxy_to_json(r));
  1577. }
  1578. ylib::json data;
  1579. data["proxies"] = arr;
  1580. reply_ok(resp, data, "url proxy added");
  1581. return;
  1582. }
  1583. reply_err(resp, "method not allowed", 405);
  1584. }
  1585. void h_websites_proxies_update(request* req, response* resp) {
  1586. if (!require_method(req, resp, "POST")) {
  1587. return;
  1588. }
  1589. auto body = parse_body(req);
  1590. const std::string name = json_str(body, "name");
  1591. website::UrlProxyRule rule;
  1592. rule.id = json_str(body, "id");
  1593. rule.path = json_str(body, "path");
  1594. rule.target_type = json_str(body, "target_type", "url");
  1595. rule.target = json_str(body, "target");
  1596. rule.host = json_str(body, "host", "$http_host");
  1597. rule.remark = json_str(body, "remark");
  1598. if (name.empty() || rule.id.empty()) {
  1599. reply_err(resp, "name and id required");
  1600. return;
  1601. }
  1602. std::string err;
  1603. if (!website::update_url_proxy(name, rule, err)) {
  1604. reply_err(resp, err.empty() ? "update url proxy failed" : err);
  1605. return;
  1606. }
  1607. reply_ok(resp, ylib::json(), "url proxy updated");
  1608. }
  1609. void h_websites_proxies_delete(request* req, response* resp) {
  1610. if (!require_method(req, resp, "POST")) {
  1611. return;
  1612. }
  1613. auto body = parse_body(req);
  1614. const std::string name = json_str(body, "name");
  1615. const std::string id = json_str(body, "id");
  1616. if (name.empty() || id.empty()) {
  1617. reply_err(resp, "name and id required");
  1618. return;
  1619. }
  1620. std::string err;
  1621. if (!website::delete_url_proxy(name, id, err)) {
  1622. reply_err(resp, err.empty() ? "delete url proxy failed" : err);
  1623. return;
  1624. }
  1625. reply_ok(resp, ylib::json(), "url proxy deleted");
  1626. }
  1627. void h_websites_custom(request* req, response* resp) {
  1628. const std::string method = req->method();
  1629. if (method == "GET") {
  1630. const std::string name = url_param(req, "name");
  1631. if (name.empty()) {
  1632. reply_err(resp, "name required");
  1633. return;
  1634. }
  1635. std::string content;
  1636. std::string err;
  1637. if (!website::get_custom_nginx(name, content, err)) {
  1638. reply_err(resp, err.empty() ? "get custom config failed" : err);
  1639. return;
  1640. }
  1641. ylib::json data;
  1642. data["name"] = name;
  1643. data["content"] = content;
  1644. reply_ok(resp, data);
  1645. return;
  1646. }
  1647. if (method == "POST") {
  1648. auto body = parse_body(req);
  1649. const std::string name = json_str(body, "name");
  1650. if (name.empty()) {
  1651. reply_err(resp, "name required");
  1652. return;
  1653. }
  1654. const std::string content = json_str(body, "content");
  1655. std::string err;
  1656. if (!website::set_custom_nginx(name, content, err)) {
  1657. reply_err(resp, err.empty() ? "save custom config failed" : err);
  1658. return;
  1659. }
  1660. reply_ok(resp, ylib::json(), "custom config saved");
  1661. return;
  1662. }
  1663. reply_err(resp, "method not allowed", 405);
  1664. }
  1665. void h_websites_logs(request* req, response* resp) {
  1666. if (!require_method(req, resp, "GET")) {
  1667. return;
  1668. }
  1669. const std::string name = url_param(req, "name");
  1670. if (name.empty()) {
  1671. reply_err(resp, "name required");
  1672. return;
  1673. }
  1674. website::SiteInfo site;
  1675. if (!website::find_site(name, site)) {
  1676. reply_err(resp, "site not found", 404);
  1677. return;
  1678. }
  1679. const std::string kind = url_param(req, "kind", "access");
  1680. size_t limit = 100;
  1681. try {
  1682. limit = static_cast<size_t>(std::stoul(url_param(req, "limit", "100")));
  1683. } catch (...) {
  1684. limit = 100;
  1685. }
  1686. int64_t before_id = 0;
  1687. try {
  1688. before_id = std::stoll(url_param(req, "before_id", "0"));
  1689. } catch (...) {
  1690. before_id = 0;
  1691. }
  1692. ylib::json arr;
  1693. std::string err;
  1694. if (kind == "error") {
  1695. weblog::ErrorQuery q;
  1696. q.name = name;
  1697. q.limit = limit;
  1698. q.before_id = before_id;
  1699. q.level = url_param(req, "level");
  1700. q.q = url_param(req, "q");
  1701. std::vector<weblog::ErrorRow> rows;
  1702. if (!weblog::query_error(q, rows, err)) {
  1703. reply_err(resp, err.empty() ? "query logs failed" : err);
  1704. return;
  1705. }
  1706. for (const auto& r : rows) {
  1707. ylib::json item;
  1708. item["id"] = static_cast<int64>(r.id);
  1709. item["time"] = r.time;
  1710. item["time_ms"] = static_cast<int64>(r.time_ms);
  1711. item["level"] = r.level;
  1712. item["message"] = r.message;
  1713. item["raw"] = r.raw;
  1714. arr.push_back(item);
  1715. }
  1716. } else {
  1717. weblog::AccessQuery q;
  1718. q.name = name;
  1719. q.limit = limit;
  1720. q.before_id = before_id;
  1721. try {
  1722. q.status = std::stoi(url_param(req, "status", "0"));
  1723. } catch (...) {
  1724. q.status = 0;
  1725. }
  1726. q.ip = url_param(req, "ip");
  1727. q.q = url_param(req, "q");
  1728. std::vector<weblog::AccessRow> rows;
  1729. if (!weblog::query_access(q, rows, err)) {
  1730. reply_err(resp, err.empty() ? "query logs failed" : err);
  1731. return;
  1732. }
  1733. for (const auto& r : rows) {
  1734. ylib::json item;
  1735. item["id"] = static_cast<int64>(r.id);
  1736. item["time"] = r.time;
  1737. item["time_ms"] = static_cast<int64>(r.time_ms);
  1738. item["ip"] = r.ip;
  1739. item["method"] = r.method;
  1740. item["host"] = r.host;
  1741. item["uri"] = r.uri;
  1742. item["args"] = r.args;
  1743. item["status"] = r.status;
  1744. item["bytes_recv"] = static_cast<int64>(r.bytes_recv);
  1745. item["bytes_sent"] = static_cast<int64>(r.bytes_sent);
  1746. item["request_time"] = r.request_time;
  1747. item["upstream_status"] = r.upstream_status;
  1748. item["upstream_addr"] = r.upstream_addr;
  1749. item["referer"] = r.referer;
  1750. item["ua"] = r.ua;
  1751. item["request"] = r.request;
  1752. item["body"] = r.body;
  1753. arr.push_back(item);
  1754. }
  1755. }
  1756. ylib::json data;
  1757. data["name"] = name;
  1758. data["kind"] = kind == "error" ? "error" : "access";
  1759. data["log_db"] = weblog::db_path(website::site_key_by_name(name));
  1760. data["items"] = arr;
  1761. reply_ok(resp, data);
  1762. }
  1763. void h_websites_logs_purge(request* req, response* resp) {
  1764. if (!require_method(req, resp, "POST")) {
  1765. return;
  1766. }
  1767. auto body = parse_body(req);
  1768. const std::string name = json_str(body, "name");
  1769. if (name.empty()) {
  1770. reply_err(resp, "name required");
  1771. return;
  1772. }
  1773. website::SiteInfo site;
  1774. if (!website::find_site(name, site)) {
  1775. reply_err(resp, "site not found", 404);
  1776. return;
  1777. }
  1778. weblog::PurgeOptions opt;
  1779. opt.files = json_bool(body, "files", false);
  1780. opt.db = json_bool(body, "db", false);
  1781. std::string err;
  1782. if (!weblog::purge(website::site_key(site), opt, err)) {
  1783. reply_err(resp, err.empty() ? "清理失败" : err);
  1784. return;
  1785. }
  1786. if (opt.files && !nginx::reopen_logs()) {
  1787. log_warn("nginx reopen logs failed after purge site=" + name);
  1788. }
  1789. const weblog::LogUsage u = weblog::usage(website::site_key(site));
  1790. ylib::json data;
  1791. data["name"] = name;
  1792. data["log_file_bytes"] = static_cast<int64>(u.file_bytes);
  1793. data["log_db_bytes"] = static_cast<int64>(u.db_bytes);
  1794. data["log_access_bytes"] = static_cast<int64>(u.access_bytes);
  1795. data["log_error_bytes"] = static_cast<int64>(u.error_bytes);
  1796. data["log_bytes"] = static_cast<int64>(u.file_bytes + u.db_bytes);
  1797. reply_ok(resp, data, "logs purged");
  1798. }
  1799. void h_websites_analytics(request* req, response* resp) {
  1800. if (!require_method(req, resp, "GET")) {
  1801. return;
  1802. }
  1803. const std::string name = url_param(req, "name");
  1804. if (name.empty()) {
  1805. reply_err(resp, "name required");
  1806. return;
  1807. }
  1808. website::SiteInfo site;
  1809. if (!website::find_site(name, site)) {
  1810. reply_err(resp, "site not found", 404);
  1811. return;
  1812. }
  1813. std::string range = url_param(req, "range", "24h");
  1814. if (range.empty()) {
  1815. range = "24h";
  1816. }
  1817. std::string json_body;
  1818. std::string err;
  1819. if (!weblog::analyze(name, range, json_body, err)) {
  1820. reply_err(resp, err.empty() ? "analyze failed" : err);
  1821. return;
  1822. }
  1823. ylib::json data;
  1824. try {
  1825. data = ylib::json::from(json_body);
  1826. } catch (...) {
  1827. reply_err(resp, "invalid analytics payload");
  1828. return;
  1829. }
  1830. data["self_ip"] = request_client_ip(req);
  1831. reply_ok(resp, data);
  1832. }
  1833. void h_websites_ssl_apply(request* req, response* resp) {
  1834. if (!require_method(req, resp, "POST")) {
  1835. return;
  1836. }
  1837. auto body = parse_body(req);
  1838. const std::string name = json_str(body, "name");
  1839. if (name.empty()) {
  1840. reply_err(resp, "name required");
  1841. return;
  1842. }
  1843. std::vector<std::string> hosts;
  1844. if (body.exist("domains") && body["domains"].is_array()) {
  1845. const auto& arr = body["domains"];
  1846. for (uint32 i = 0; i < arr.size(); ++i) {
  1847. std::string d = arr[i].to<std::string>(true);
  1848. if (!d.empty()) {
  1849. hosts.push_back(d);
  1850. }
  1851. }
  1852. } else if (body.exist("hosts") && body["hosts"].is_array()) {
  1853. const auto& arr = body["hosts"];
  1854. for (uint32 i = 0; i < arr.size(); ++i) {
  1855. std::string d = arr[i].to<std::string>(true);
  1856. if (!d.empty()) {
  1857. hosts.push_back(d);
  1858. }
  1859. }
  1860. }
  1861. // ACME account contact: md5(<domain>)@qq.com (LE requires public-suffix email).
  1862. // Ignore previously stored invalid/legacy emails.
  1863. std::string email = json_str(body, "email");
  1864. if (!ssl::is_valid_acme_email(email) ||
  1865. email.size() < 8 ||
  1866. email.compare(email.size() - 7, 7, "@qq.com") != 0) {
  1867. std::string domain_hint;
  1868. if (!hosts.empty()) {
  1869. domain_hint = hosts.front();
  1870. } else {
  1871. website::SiteInfo site;
  1872. if (website::find_site(name, site)) {
  1873. domain_hint = website::primary_domain(site.domain);
  1874. }
  1875. }
  1876. email = ssl::default_account_email(domain_hint);
  1877. if (!ssl::is_valid_acme_email(email)) {
  1878. reply_err(resp, "无法生成 ACME 联系邮箱");
  1879. return;
  1880. }
  1881. store::set_setting("ssl_email", email);
  1882. } else if (store::get_setting("ssl_email", "") != email) {
  1883. store::set_setting("ssl_email", email);
  1884. }
  1885. std::string err;
  1886. std::string title = "申请 SSL · " + name;
  1887. if (!hosts.empty()) {
  1888. title += " (" + std::to_string(hosts.size()) + ")";
  1889. }
  1890. const std::string id = tasks::enqueue(
  1891. "ssl.letsencrypt", title,
  1892. [name, email, hosts]() {
  1893. std::string e;
  1894. if (!website::apply_letsencrypt(name, email, hosts, e)) {
  1895. if (!e.empty()) {
  1896. std::cerr << e << "\n";
  1897. log_error(e);
  1898. }
  1899. return false;
  1900. }
  1901. return true;
  1902. },
  1903. err);
  1904. if (id.empty()) {
  1905. reply_err(resp, err.empty() ? "enqueue failed" : err);
  1906. return;
  1907. }
  1908. ylib::json data;
  1909. data["task_id"] = id;
  1910. data["active"] = tasks::active_count();
  1911. reply_ok(resp, data, "task queued");
  1912. }
  1913. void h_system_metrics(request* req, response* resp) {
  1914. if (!require_method(req, resp, "GET")) {
  1915. return;
  1916. }
  1917. const auto m = system::sample();
  1918. ylib::json data;
  1919. ylib::json cpu;
  1920. cpu["percent"] = m.cpu.percent;
  1921. cpu["cores"] = m.cpu.cores;
  1922. data["cpu"] = cpu;
  1923. ylib::json memory;
  1924. memory["total"] = static_cast<int64>(m.memory.total_bytes);
  1925. memory["used"] = static_cast<int64>(m.memory.used_bytes);
  1926. memory["percent"] = m.memory.percent;
  1927. data["memory"] = memory;
  1928. ylib::json disk;
  1929. disk["path"] = m.disk.path;
  1930. disk["device"] = m.disk.device;
  1931. disk["fstype"] = m.disk.fstype;
  1932. disk["total"] = static_cast<int64>(m.disk.total_bytes);
  1933. disk["used"] = static_cast<int64>(m.disk.used_bytes);
  1934. disk["percent"] = m.disk.percent;
  1935. data["disk"] = disk;
  1936. ylib::json disks;
  1937. for (const auto& d : m.disks) {
  1938. ylib::json item;
  1939. item["path"] = d.path;
  1940. item["device"] = d.device;
  1941. item["fstype"] = d.fstype;
  1942. item["total"] = static_cast<int64>(d.total_bytes);
  1943. item["used"] = static_cast<int64>(d.used_bytes);
  1944. item["percent"] = d.percent;
  1945. disks.push_back(item);
  1946. }
  1947. data["disks"] = disks;
  1948. ylib::json network;
  1949. network["rx_bytes"] = static_cast<int64>(m.network.rx_bytes);
  1950. network["tx_bytes"] = static_cast<int64>(m.network.tx_bytes);
  1951. network["rx_bps"] = m.network.rx_bps;
  1952. network["tx_bps"] = m.network.tx_bps;
  1953. data["network"] = network;
  1954. ylib::json gpus;
  1955. for (const auto& g : m.gpus) {
  1956. ylib::json item;
  1957. item["index"] = g.index;
  1958. item["name"] = g.name;
  1959. item["percent"] = g.percent;
  1960. item["mem_used"] = static_cast<int64>(g.mem_used);
  1961. item["mem_total"] = static_cast<int64>(g.mem_total);
  1962. item["mem_percent"] = g.mem_percent;
  1963. item["temperature"] = g.temperature;
  1964. gpus.push_back(item);
  1965. }
  1966. data["gpus"] = gpus;
  1967. reply_ok(resp, data);
  1968. }
  1969. void h_system_processes(request* req, response* resp) {
  1970. if (!require_method(req, resp, "GET")) {
  1971. return;
  1972. }
  1973. const std::string q = url_param(req, "q", "");
  1974. const auto list = system::list_processes(q);
  1975. ylib::json arr;
  1976. for (const auto& p : list) {
  1977. ylib::json item;
  1978. item["pid"] = p.pid;
  1979. item["ppid"] = p.ppid;
  1980. item["user"] = p.user;
  1981. item["state"] = p.state;
  1982. item["name"] = p.name;
  1983. item["cmdline"] = p.cmdline;
  1984. item["cwd"] = p.cwd;
  1985. item["threads"] = p.threads;
  1986. item["rss"] = static_cast<int64>(p.rss_bytes);
  1987. item["vms"] = static_cast<int64>(p.vms_bytes);
  1988. item["mem_percent"] = p.mem_percent;
  1989. item["cpu_percent"] = p.cpu_percent;
  1990. arr.push_back(item);
  1991. }
  1992. ylib::json data;
  1993. data["total"] = static_cast<int>(list.size());
  1994. data["items"] = arr;
  1995. reply_ok(resp, data);
  1996. }
  1997. void h_system_processes_kill(request* req, response* resp) {
  1998. if (!require_method(req, resp, "POST")) {
  1999. return;
  2000. }
  2001. auto body = parse_body(req);
  2002. const int pid = json_int(body, "pid", 0);
  2003. int signal = json_int(body, "signal", 15);
  2004. const std::string sig_name = json_str(body, "signal_name");
  2005. if (!sig_name.empty()) {
  2006. if (sig_name == "KILL" || sig_name == "SIGKILL" || sig_name == "9") {
  2007. signal = 9;
  2008. } else if (sig_name == "TERM" || sig_name == "SIGTERM" ||
  2009. sig_name == "15") {
  2010. signal = 15;
  2011. } else if (sig_name == "INT" || sig_name == "SIGINT" ||
  2012. sig_name == "2") {
  2013. signal = 2;
  2014. } else if (sig_name == "HUP" || sig_name == "SIGHUP" ||
  2015. sig_name == "1") {
  2016. signal = 1;
  2017. }
  2018. }
  2019. if (pid <= 0) {
  2020. reply_err(resp, "pid required");
  2021. return;
  2022. }
  2023. std::string err;
  2024. if (!system::kill_process(pid, signal, err)) {
  2025. reply_err(resp, err.empty() ? "kill failed" : err);
  2026. return;
  2027. }
  2028. ylib::json data;
  2029. data["pid"] = pid;
  2030. data["signal"] = signal;
  2031. reply_ok(resp, data, "process signaled");
  2032. }
  2033. void h_shell_ticket(request* req, response* resp) {
  2034. if (!require_method(req, resp, "GET")) {
  2035. return;
  2036. }
  2037. std::string username;
  2038. if (!request_authed(req, &username)) {
  2039. reply_err(resp, "未登录或会话已过期", 401);
  2040. return;
  2041. }
  2042. const std::string ticket = system::shell_issue_ticket(username);
  2043. ylib::json data;
  2044. data["ticket"] = ticket;
  2045. data["ttl_sec"] = 60;
  2046. reply_ok(resp, data);
  2047. }
  2048. void h_system_metrics_history(request* req, response* resp) {
  2049. if (!require_method(req, resp, "GET")) {
  2050. return;
  2051. }
  2052. std::string range = url_param(req, "range", "10m");
  2053. if (range.empty()) {
  2054. range = "10m";
  2055. }
  2056. std::vector<system::HistoryPoint> points;
  2057. std::string err;
  2058. if (!system::history_query(range, points, err)) {
  2059. reply_err(resp, err.empty() ? "query metrics history failed" : err);
  2060. return;
  2061. }
  2062. ylib::json arr;
  2063. for (const auto& p : points) {
  2064. ylib::json item;
  2065. item["time_ms"] = static_cast<int64>(p.time_ms);
  2066. item["cpu_percent"] = p.cpu_percent;
  2067. item["cpu_cores"] = p.cpu_cores;
  2068. item["mem_percent"] = p.mem_percent;
  2069. item["mem_used"] = static_cast<int64>(p.mem_used);
  2070. item["mem_total"] = static_cast<int64>(p.mem_total);
  2071. item["disk_percent"] = p.disk_percent;
  2072. item["disk_used"] = static_cast<int64>(p.disk_used);
  2073. item["disk_total"] = static_cast<int64>(p.disk_total);
  2074. item["net_rx_bps"] = p.net_rx_bps;
  2075. item["net_tx_bps"] = p.net_tx_bps;
  2076. item["net_rx_bytes"] = static_cast<int64>(p.net_rx_bytes);
  2077. item["net_tx_bytes"] = static_cast<int64>(p.net_tx_bytes);
  2078. item["gpu_percent"] = p.gpu_percent;
  2079. item["gpu_mem_used"] = static_cast<int64>(p.gpu_mem_used);
  2080. item["gpu_mem_total"] = static_cast<int64>(p.gpu_mem_total);
  2081. arr.push_back(item);
  2082. }
  2083. ylib::json data;
  2084. data["range"] = range;
  2085. data["items"] = arr;
  2086. reply_ok(resp, data);
  2087. }
  2088. void h_redis_status(request* req, response* resp) {
  2089. if (!require_method(req, resp, "GET")) {
  2090. return;
  2091. }
  2092. ylib::json data;
  2093. data["installed"] = redis::is_installed();
  2094. data["running"] = redis::is_running();
  2095. data["version"] = redis::installed_version();
  2096. data["install_dir"] = redis::install_dir();
  2097. data["bin"] = redis::bin_path();
  2098. data["conf"] = redis::conf_file();
  2099. data["port"] = redis::listen_port();
  2100. reply_ok(resp, data);
  2101. }
  2102. void h_redis_install(request* req, response* resp) {
  2103. if (!require_method(req, resp, "POST")) {
  2104. return;
  2105. }
  2106. auto body = parse_body(req);
  2107. std::string version = json_str(body, "version", redis::kDefaultVersion);
  2108. std::string err;
  2109. const std::string id = tasks::enqueue(
  2110. "redis.install", "安装 Redis " + version,
  2111. [version]() { return redis::install(version); }, err);
  2112. if (id.empty()) {
  2113. reply_err(resp, err.empty() ? "enqueue failed" : err);
  2114. return;
  2115. }
  2116. reply_task_queued(resp, id);
  2117. }
  2118. void h_redis_uninstall(request* req, response* resp) {
  2119. if (!require_method(req, resp, "POST")) {
  2120. return;
  2121. }
  2122. std::string err;
  2123. const std::string id = tasks::enqueue(
  2124. "redis.uninstall", "卸载 Redis", []() { return redis::uninstall(); },
  2125. err);
  2126. if (id.empty()) {
  2127. reply_err(resp, err.empty() ? "enqueue failed" : err);
  2128. return;
  2129. }
  2130. reply_task_queued(resp, id);
  2131. }
  2132. void h_redis_start(request* req, response* resp) {
  2133. if (!require_method(req, resp, "POST")) {
  2134. return;
  2135. }
  2136. if (!redis::start()) {
  2137. reply_err(resp, "redis start failed");
  2138. return;
  2139. }
  2140. reply_ok(resp, ylib::json(), "redis started");
  2141. }
  2142. void h_redis_stop(request* req, response* resp) {
  2143. if (!require_method(req, resp, "POST")) {
  2144. return;
  2145. }
  2146. if (!redis::stop()) {
  2147. reply_err(resp, "redis stop failed");
  2148. return;
  2149. }
  2150. reply_ok(resp, ylib::json(), "redis stopped");
  2151. }
  2152. void h_redis_config(request* req, response* resp) {
  2153. const std::string method = req->method();
  2154. if (method == "GET") {
  2155. redis::QuickConfig cfg;
  2156. std::string err;
  2157. if (!redis::read_quick_config(cfg, err)) {
  2158. reply_err(resp, err.empty() ? "read redis config failed" : err);
  2159. return;
  2160. }
  2161. ylib::json data;
  2162. data["bind"] = cfg.bind;
  2163. data["port"] = cfg.port;
  2164. data["requirepass"] = cfg.requirepass;
  2165. data["conf"] = redis::conf_file();
  2166. data["running"] = redis::is_running();
  2167. reply_ok(resp, data);
  2168. return;
  2169. }
  2170. if (method == "POST") {
  2171. redis::QuickConfig cfg;
  2172. std::string err;
  2173. if (!redis::read_quick_config(cfg, err)) {
  2174. reply_err(resp, err.empty() ? "read redis config failed" : err);
  2175. return;
  2176. }
  2177. const auto body = parse_body(req);
  2178. if (body.exist("bind")) {
  2179. cfg.bind = json_str(body, "bind", cfg.bind);
  2180. }
  2181. if (body.exist("port")) {
  2182. cfg.port = json_int(body, "port", cfg.port);
  2183. }
  2184. if (body.exist("requirepass")) {
  2185. cfg.requirepass = json_str(body, "requirepass");
  2186. }
  2187. if (!redis::apply_quick_config(cfg, err)) {
  2188. reply_err(resp, err.empty() ? "apply redis config failed" : err);
  2189. return;
  2190. }
  2191. ylib::json data;
  2192. data["bind"] = cfg.bind;
  2193. data["port"] = cfg.port;
  2194. data["requirepass"] = cfg.requirepass;
  2195. data["conf"] = redis::conf_file();
  2196. data["running"] = redis::is_running();
  2197. reply_ok(resp, data, "redis config updated");
  2198. return;
  2199. }
  2200. reply_err(resp, "method not allowed", 405);
  2201. }
  2202. void h_redis_exec(request* req, response* resp) {
  2203. if (!require_method(req, resp, "POST")) {
  2204. return;
  2205. }
  2206. const auto body = parse_body(req);
  2207. const std::string command = json_str(body, "command");
  2208. if (command.empty()) {
  2209. reply_err(resp, "请输入 Redis 命令");
  2210. return;
  2211. }
  2212. std::string output;
  2213. std::string err;
  2214. bool truncated = false;
  2215. const auto t0 = std::chrono::steady_clock::now();
  2216. if (!redis::exec_command(command, output, truncated, err)) {
  2217. reply_err(resp, err.empty() ? "执行失败" : err);
  2218. return;
  2219. }
  2220. const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  2221. std::chrono::steady_clock::now() - t0)
  2222. .count();
  2223. ylib::json data;
  2224. data["output"] = output;
  2225. data["truncated"] = truncated;
  2226. data["elapsed_ms"] = static_cast<int>(ms);
  2227. reply_ok(resp, data);
  2228. }
  2229. void h_files_list(request* req, response* resp) {
  2230. if (!require_method(req, resp, "GET")) {
  2231. return;
  2232. }
  2233. std::string path = url_param(req, "path", "/");
  2234. std::string abs, err;
  2235. if (!files::resolve_path(path, abs, err)) {
  2236. reply_err(resp, err);
  2237. return;
  2238. }
  2239. std::vector<files::Entry> entries;
  2240. if (!files::list_dir(abs, entries, err)) {
  2241. reply_err(resp, err);
  2242. return;
  2243. }
  2244. ylib::json arr;
  2245. for (const auto& e : entries) {
  2246. ylib::json item;
  2247. item["name"] = e.name;
  2248. item["path"] = e.path;
  2249. item["is_dir"] = e.is_dir;
  2250. item["is_symlink"] = e.is_symlink;
  2251. item["size"] = static_cast<int64>(e.size);
  2252. item["mtime"] = static_cast<int64>(e.mtime);
  2253. arr.push_back(item);
  2254. }
  2255. ylib::json data;
  2256. data["path"] = abs;
  2257. data["entries"] = arr;
  2258. reply_ok(resp, data);
  2259. }
  2260. void h_files_mkdir(request* req, response* resp) {
  2261. if (!require_method(req, resp, "POST")) {
  2262. return;
  2263. }
  2264. auto body = parse_body(req);
  2265. std::string path = json_str(body, "path");
  2266. std::string err;
  2267. if (!files::mkdir_path(path, err)) {
  2268. reply_err(resp, err);
  2269. return;
  2270. }
  2271. reply_ok(resp, ylib::json(), "directory created");
  2272. }
  2273. void h_files_write(request* req, response* resp) {
  2274. if (!require_method(req, resp, "POST")) {
  2275. return;
  2276. }
  2277. auto body = parse_body(req);
  2278. std::string path = json_str(body, "path");
  2279. std::string content = json_str(body, "content");
  2280. std::string err;
  2281. if (!files::write_text(path, content, err)) {
  2282. reply_err(resp, err);
  2283. return;
  2284. }
  2285. reply_ok(resp, ylib::json(), "written");
  2286. }
  2287. void h_files_read(request* req, response* resp) {
  2288. if (!require_method(req, resp, "GET")) {
  2289. return;
  2290. }
  2291. std::string path = url_param(req, "path");
  2292. std::string content, err;
  2293. if (!files::read_text(path, content, err)) {
  2294. reply_err(resp, err);
  2295. return;
  2296. }
  2297. ylib::json data;
  2298. data["path"] = path;
  2299. data["content"] = content;
  2300. reply_ok(resp, data);
  2301. }
  2302. void h_files_tail(request* req, response* resp) {
  2303. if (!require_method(req, resp, "GET")) {
  2304. return;
  2305. }
  2306. std::string path = url_param(req, "path");
  2307. size_t max_bytes = 256ull * 1024ull;
  2308. try {
  2309. max_bytes = static_cast<size_t>(
  2310. std::stoul(url_param(req, "bytes", "262144")));
  2311. } catch (...) {
  2312. }
  2313. if (max_bytes < 1024) {
  2314. max_bytes = 1024;
  2315. }
  2316. if (max_bytes > files::kMaxEditBytes) {
  2317. max_bytes = files::kMaxEditBytes;
  2318. }
  2319. std::string content, err;
  2320. if (!files::read_tail(path, max_bytes, content, err)) {
  2321. reply_err(resp, err);
  2322. return;
  2323. }
  2324. ylib::json data;
  2325. data["path"] = path;
  2326. data["content"] = content;
  2327. reply_ok(resp, data);
  2328. }
  2329. void h_files_rename(request* req, response* resp) {
  2330. if (!require_method(req, resp, "POST")) {
  2331. return;
  2332. }
  2333. auto body = parse_body(req);
  2334. std::string from = json_str(body, "from");
  2335. std::string to = json_str(body, "to");
  2336. std::string err;
  2337. if (!files::rename_path(from, to, err)) {
  2338. reply_err(resp, err);
  2339. return;
  2340. }
  2341. reply_ok(resp, ylib::json(), "renamed");
  2342. }
  2343. void h_files_delete(request* req, response* resp) {
  2344. if (!require_method(req, resp, "POST")) {
  2345. return;
  2346. }
  2347. auto body = parse_body(req);
  2348. std::string path = json_str(body, "path");
  2349. const bool recursive = json_bool(body, "recursive", false);
  2350. std::string err;
  2351. if (!files::delete_path(path, recursive, err)) {
  2352. reply_err(resp, err);
  2353. return;
  2354. }
  2355. reply_ok(resp, ylib::json(), "deleted");
  2356. }
  2357. void h_files_upload(request* req, response* resp) {
  2358. if (!require_method(req, resp, "POST")) {
  2359. return;
  2360. }
  2361. std::string content_type;
  2362. if (!(req->header("Content-Type", content_type) ||
  2363. req->header("content-type", content_type))) {
  2364. content_type.clear();
  2365. }
  2366. std::string path;
  2367. uint64_t offset = 0;
  2368. uint64_t total = 0;
  2369. std::string bytes;
  2370. const bool binary =
  2371. content_type.find("application/octet-stream") != std::string::npos ||
  2372. (!url_param(req, "path").empty() &&
  2373. content_type.find("json") == std::string::npos);
  2374. if (binary) {
  2375. path = url_param(req, "path");
  2376. offset = parse_u64(url_param(req, "offset", "0"));
  2377. total = parse_u64(url_param(req, "total", "0"));
  2378. bytes = req->body().to_string();
  2379. } else {
  2380. auto body = parse_body(req);
  2381. path = json_str(body, "path");
  2382. offset = parse_u64(json_str(body, "offset"));
  2383. total = parse_u64(json_str(body, "total"));
  2384. const std::string b64 = json_str(body, "content_base64");
  2385. const std::string content = json_str(body, "content");
  2386. bytes = b64.empty() ? content : b64_decode(b64);
  2387. }
  2388. if (path.empty()) {
  2389. reply_err(resp, "path required");
  2390. return;
  2391. }
  2392. std::string err;
  2393. if (!files::write_chunk(path, offset, bytes, total, err)) {
  2394. reply_err(resp, err);
  2395. return;
  2396. }
  2397. ylib::json data;
  2398. data["path"] = path;
  2399. data["offset"] = static_cast<int64>(offset);
  2400. data["written"] = static_cast<int64>(bytes.size());
  2401. const uint64_t next = offset + bytes.size();
  2402. if (total > 0) {
  2403. data["total"] = static_cast<int64>(total);
  2404. data["done"] = next >= total;
  2405. } else {
  2406. data["done"] = true;
  2407. }
  2408. reply_ok(resp, data, "uploaded");
  2409. }
  2410. void h_files_download(request* req, response* resp) {
  2411. if (!require_method(req, resp, "GET")) {
  2412. return;
  2413. }
  2414. std::string path = url_param(req, "path");
  2415. std::string abs, err;
  2416. if (!files::resolve_path(path, abs, err)) {
  2417. reply_err(resp, err);
  2418. return;
  2419. }
  2420. if (!path_exists(abs) || is_dir(abs)) {
  2421. reply_err(resp, "file not found");
  2422. return;
  2423. }
  2424. std::string name = fs::path(abs).filename().string();
  2425. if (name.empty()) {
  2426. name = "download";
  2427. }
  2428. // Keep original filename for browsers (ASCII fallback + RFC5987 UTF-8).
  2429. std::string safe;
  2430. for (unsigned char c : name) {
  2431. if (c == '"' || c == '\\' || c < 0x20) {
  2432. safe.push_back('_');
  2433. } else {
  2434. safe.push_back(static_cast<char>(c));
  2435. }
  2436. }
  2437. std::string encoded;
  2438. static const char* hex = "0123456789ABCDEF";
  2439. for (unsigned char c : name) {
  2440. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  2441. (c >= '0' && c <= '9') || c == '.' || c == '_' || c == '-') {
  2442. encoded.push_back(static_cast<char>(c));
  2443. } else {
  2444. encoded.push_back('%');
  2445. encoded.push_back(hex[c >> 4]);
  2446. encoded.push_back(hex[c & 0xF]);
  2447. }
  2448. }
  2449. (*resp->headers())["Content-Disposition"] =
  2450. "attachment; filename=\"" + safe + "\"; filename*=UTF-8''" + encoded;
  2451. (*resp->headers())["Content-Type"] = "application/octet-stream";
  2452. resp->send_file(abs);
  2453. }
  2454. void register_routes(ylib::network::http::router* router) {
  2455. // Public endpoints
  2456. reg(router, "/api/ping", h_ping, false);
  2457. reg(router, "/api/auth/captcha", h_auth_captcha, false);
  2458. reg(router, "/api/auth/login", h_auth_login, false);
  2459. reg(router, "/api/auth/logout", h_auth_logout, false);
  2460. reg(router, "/api/auth/me", h_auth_me, false);
  2461. reg(router, "/api/status", h_status);
  2462. reg(router, "/api/settings", h_settings);
  2463. reg(router, "/api/self/version", h_self_version);
  2464. reg(router, "/api/self/check", h_self_check);
  2465. reg(router, "/api/self/update", h_self_update);
  2466. reg(router, "/api/system/metrics", h_system_metrics);
  2467. reg(router, "/api/system/metrics/history", h_system_metrics_history);
  2468. reg(router, "/api/system/processes", h_system_processes);
  2469. reg(router, "/api/system/processes/kill", h_system_processes_kill);
  2470. router->subscribe()->add(
  2471. R"(/api/shell/ws(?:\?.*)?)", "",
  2472. [](request* req, response* resp, websocket_message* ws, const std::string&,
  2473. const std::string&) {
  2474. // 鉴权在 upgrade 内用 ticket;此处不要 reply_err JSON。
  2475. system::shell_ws_handler(req, resp, ws);
  2476. });
  2477. router->on_close([](uint64 connid, websocket_message*) {
  2478. system::shell_on_conn_close(static_cast<uint64_t>(connid));
  2479. });
  2480. reg(router, "/api/shell/ticket", h_shell_ticket);
  2481. reg(router, "/api/tasks", h_tasks_list);
  2482. reg(router, "/api/tasks/log", h_tasks_log);
  2483. reg(router, "/api/tasks/clear", h_tasks_clear);
  2484. reg(router, "/api/schedule/jobs", h_schedule_jobs);
  2485. reg(router, "/api/schedule/jobs/delete", h_schedule_jobs_delete);
  2486. reg(router, "/api/schedule/jobs/enable", h_schedule_jobs_enable);
  2487. reg(router, "/api/schedule/jobs/run", h_schedule_jobs_run);
  2488. reg(router, "/api/schedule/logs", h_schedule_logs);
  2489. reg(router, "/api/nginx/status", h_nginx_status);
  2490. reg(router, "/api/nginx/install", h_nginx_install);
  2491. reg(router, "/api/nginx/uninstall", h_nginx_uninstall);
  2492. reg(router, "/api/nginx/start", h_nginx_start);
  2493. reg(router, "/api/nginx/stop", h_nginx_stop);
  2494. reg(router, "/api/nginx/reload", h_nginx_reload);
  2495. reg(router, "/api/nginx/config", h_nginx_config);
  2496. reg(router, "/api/fastweb/status", h_fastweb_status);
  2497. reg(router, "/api/fastweb/install", h_fastweb_install);
  2498. reg(router, "/api/fastweb/uninstall", h_fastweb_uninstall);
  2499. reg(router, "/api/fastweb/modules", h_fastweb_modules);
  2500. reg(router, "/api/fastweb/modules/install", h_fastweb_module_install);
  2501. reg(router, "/api/fastweb/modules/uninstall", h_fastweb_module_uninstall);
  2502. reg(router, "/api/mysql/status", h_mysql_status);
  2503. reg(router, "/api/mysql/install", h_mysql_install);
  2504. reg(router, "/api/mysql/uninstall", h_mysql_uninstall);
  2505. reg(router, "/api/mysql/start", h_mysql_start);
  2506. reg(router, "/api/mysql/stop", h_mysql_stop);
  2507. reg(router, "/api/mysql/root/password", h_mysql_root_password);
  2508. reg(router, "/api/mysql/databases", h_mysql_databases);
  2509. reg(router, "/api/mysql/databases/drop", h_mysql_databases_drop);
  2510. reg(router, "/api/mysql/databases/access", h_mysql_databases_access);
  2511. reg(router, "/api/mysql/exec", h_mysql_exec);
  2512. reg(router, "/api/redis/status", h_redis_status);
  2513. reg(router, "/api/redis/install", h_redis_install);
  2514. reg(router, "/api/redis/uninstall", h_redis_uninstall);
  2515. reg(router, "/api/redis/start", h_redis_start);
  2516. reg(router, "/api/redis/stop", h_redis_stop);
  2517. reg(router, "/api/redis/config", h_redis_config);
  2518. reg(router, "/api/redis/exec", h_redis_exec);
  2519. reg(router, "/api/websites", h_websites);
  2520. reg(router, "/api/websites/start", h_websites_start);
  2521. reg(router, "/api/websites/stop", h_websites_stop);
  2522. reg(router, "/api/websites/restart", h_websites_restart);
  2523. reg(router, "/api/websites/delete", h_websites_delete);
  2524. reg(router, "/api/websites/update", h_websites_update);
  2525. reg(router, "/api/websites/reorder", h_websites_reorder);
  2526. reg(router, "/api/websites/proxies", h_websites_proxies);
  2527. reg(router, "/api/websites/proxies/update", h_websites_proxies_update);
  2528. reg(router, "/api/websites/proxies/delete", h_websites_proxies_delete);
  2529. reg(router, "/api/websites/custom", h_websites_custom);
  2530. reg(router, "/api/websites/logs", h_websites_logs);
  2531. reg(router, "/api/websites/logs/purge", h_websites_logs_purge);
  2532. reg(router, "/api/websites/analytics", h_websites_analytics);
  2533. reg(router, "/api/websites/ssl/apply", h_websites_ssl_apply);
  2534. reg(router, "/api/files/list", h_files_list);
  2535. reg(router, "/api/files/mkdir", h_files_mkdir);
  2536. reg(router, "/api/files/write", h_files_write);
  2537. reg(router, "/api/files/read", h_files_read);
  2538. reg(router, "/api/files/tail", h_files_tail);
  2539. reg(router, "/api/files/rename", h_files_rename);
  2540. reg(router, "/api/files/delete", h_files_delete);
  2541. reg(router, "/api/files/upload", h_files_upload);
  2542. reg(router, "/api/files/download", h_files_download);
  2543. const std::string www = panel_www_dir();
  2544. router->other([www](request* req, response* resp, websocket_message* ws) {
  2545. // WebSocket 未命中订阅:绝不能 reply_err JSON,否则握手被 200+JSON 打断。
  2546. if (ws) {
  2547. if (ws->type ==
  2548. ylib::network::http::HTTP_SERVER_WEBSOCKET_TYPE_UPGRADE) {
  2549. resp->send_header(404, "Not Found");
  2550. } else if (ws->type !=
  2551. ylib::network::http::HTTP_SERVER_WEBSOCKET_TYPE_CLOSE) {
  2552. resp->response_done();
  2553. }
  2554. return;
  2555. }
  2556. std::string path = req ? req->filepath() : "/";
  2557. if (path.empty() || path == "/") {
  2558. path = "/index.html";
  2559. }
  2560. if (path.rfind("/api/", 0) == 0) {
  2561. reply_err(resp, "not found", 404);
  2562. return;
  2563. }
  2564. if (path.find("..") != std::string::npos) {
  2565. reply_err(resp, "forbidden", 403);
  2566. return;
  2567. }
  2568. const bool is_asset =
  2569. path.rfind("/assets/", 0) == 0 || path == "/favicon.ico";
  2570. const bool is_login =
  2571. path == "/login.html" || path == "/login" || path == "login.html";
  2572. if (!is_asset && !is_login && !request_authed(req)) {
  2573. resp->redirect("/login.html", false);
  2574. return;
  2575. }
  2576. if (is_login && request_authed(req)) {
  2577. resp->redirect("/", false);
  2578. return;
  2579. }
  2580. while (!path.empty() && path[0] == '/') {
  2581. path.erase(path.begin());
  2582. }
  2583. if (path == "login") {
  2584. path = "login.html";
  2585. }
  2586. std::string file = join_path(www, path);
  2587. if (is_dir(file)) {
  2588. file = join_path(file, "index.html");
  2589. }
  2590. if (path_exists(file) && !is_dir(file)) {
  2591. resp->send_file(file);
  2592. return;
  2593. }
  2594. const std::string index = join_path(www, "index.html");
  2595. if (path_exists(index)) {
  2596. resp->send_file(index);
  2597. return;
  2598. }
  2599. reply_err(resp, "panel not found: " + www, 404);
  2600. });
  2601. }
  2602. } // namespace
  2603. bool run(const std::string& listen_addr, uint16_t listen_port) {
  2604. (void)listen_addr; // ylib HttpServer always binds 0.0.0.0
  2605. ensure_dir(software_root());
  2606. ensure_dir(conf_root());
  2607. ensure_dir(join_path(conf_root(), "ssl"));
  2608. ensure_dir(wwwroot_dir());
  2609. {
  2610. std::string aerr;
  2611. if (!auth::init(aerr)) {
  2612. std::cerr << "apiserver auth init failed: " << aerr << "\n";
  2613. log_error("auth init failed: " + aerr);
  2614. return false;
  2615. }
  2616. }
  2617. if (!store::init()) {
  2618. std::cerr << "apiserver sqlite init failed: " << store::database_path()
  2619. << "\n";
  2620. log_error("sqlite init failed path=" + store::database_path());
  2621. return false;
  2622. }
  2623. tasks::start();
  2624. weblog::start();
  2625. system::history_start();
  2626. schedule::start();
  2627. selfupdate::init(listen_addr, listen_port);
  2628. log_info("ngs apiserver starting listen=" + listen_addr + ":" +
  2629. std::to_string(listen_port));
  2630. install_signal_handlers();
  2631. auto* center = new ylib::network::http::center();
  2632. g_center = center;
  2633. auto fail_cleanup = [&]() {
  2634. // Stop workers first so metrics/tasks do not keep running if close hangs.
  2635. stop_background_services();
  2636. if (center) {
  2637. center->close();
  2638. delete center;
  2639. center = nullptr;
  2640. }
  2641. g_center = nullptr;
  2642. };
  2643. ylib::network::http::start_config config;
  2644. ylib::network::http::website_config ws_config;
  2645. ws_config.name = "ngs-api";
  2646. // domain containing 0.0.0.0 matches any Host header in ylib.
  2647. ylib::network::http::host_config host;
  2648. host.domain = listen_addr.empty() ? kDefaultListenAddr : listen_addr;
  2649. host.port = listen_port;
  2650. host.ssl = false;
  2651. ws_config.host.push_back(host);
  2652. ws_config.router.threadpool.size = 8;
  2653. ws_config.router.threadpool.queuemax = 10000;
  2654. config.max_upload_size = 64 * 1024 * 1024;
  2655. config.websocket_enable = true;
  2656. config.website.push_back(ws_config);
  2657. if (!center->create(config)) {
  2658. std::cerr << "apiserver create failed: " << center->last_error() << "\n";
  2659. log_error("apiserver create failed: " + center->last_error());
  2660. fail_cleanup();
  2661. return false;
  2662. }
  2663. auto* website = center->website_byname(ws_config.name);
  2664. if (!website || !website->router()) {
  2665. std::cerr << "apiserver website/router missing\n";
  2666. log_error("apiserver website/router missing");
  2667. fail_cleanup();
  2668. return false;
  2669. }
  2670. register_routes(website->router());
  2671. if (!center->start()) {
  2672. std::cerr << "apiserver start failed: " << center->last_error() << "\n";
  2673. log_error("apiserver start failed: " + center->last_error());
  2674. fail_cleanup();
  2675. return false;
  2676. }
  2677. // HPSocket may touch signal state during start; reinstall our handlers.
  2678. install_signal_handlers();
  2679. std::cout << "NGS API Server listening on http://" << host.domain << ":"
  2680. << listen_port << "\n";
  2681. std::cout << "Panel: http://127.0.0.1:" << listen_port << "/\n";
  2682. std::cout << "Panel dir: " << panel_www_dir() << "\n";
  2683. std::cout << "Docs: API.md\n";
  2684. std::cout.flush();
  2685. log_info("ngs apiserver listening port=" + std::to_string(listen_port) +
  2686. " panel=" + panel_www_dir());
  2687. while (g_running.load(std::memory_order_relaxed)) {
  2688. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  2689. }
  2690. std::cout << "Shutting down...\n";
  2691. log_info("ngs apiserver stopping");
  2692. stop_background_services();
  2693. center->close();
  2694. delete center;
  2695. g_center = nullptr;
  2696. return true;
  2697. }
  2698. } // namespace api
  2699. } // namespace ngs