api_server.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661
  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 "../store/store.h"
  9. #include "../system/metrics.h"
  10. #include "../system/metrics_history.h"
  11. #include "../tasks/tasks.h"
  12. #include "../utils.h"
  13. #include "../website/website.h"
  14. #include "../weblog/weblog.h"
  15. #include "net/http_center.h"
  16. #include "net/http_request.h"
  17. #include "net/http_response.h"
  18. #include "net/http_router.h"
  19. #include "net/http_subscribe.h"
  20. #include "net/http_website.h"
  21. #include "util/json.h"
  22. #include <atomic>
  23. #include <chrono>
  24. #include <cstdint>
  25. #include <csignal>
  26. #include <filesystem>
  27. #include <iostream>
  28. #include <string>
  29. #include <thread>
  30. #include <vector>
  31. namespace ngs {
  32. namespace api {
  33. namespace {
  34. namespace fs = std::filesystem;
  35. using ylib::network::http::request;
  36. using ylib::network::http::response;
  37. using ylib::network::http::websocket_message;
  38. std::atomic<bool> g_running{true};
  39. ylib::network::http::center* g_center = nullptr;
  40. void on_signal(int) {
  41. g_running.store(false, std::memory_order_relaxed);
  42. }
  43. void install_signal_handlers() {
  44. struct sigaction sa {};
  45. sa.sa_handler = on_signal;
  46. sigemptyset(&sa.sa_mask);
  47. sa.sa_flags = 0; // interrupt blocking sleeps (do not set SA_RESTART)
  48. sigaction(SIGINT, &sa, nullptr);
  49. sigaction(SIGTERM, &sa, nullptr);
  50. }
  51. ylib::json parse_body(request* req) {
  52. if (!req) {
  53. return ylib::json();
  54. }
  55. const std::string body = req->body().to_string();
  56. if (body.empty()) {
  57. return ylib::json();
  58. }
  59. try {
  60. return ylib::json::from(body);
  61. } catch (...) {
  62. return ylib::json();
  63. }
  64. }
  65. std::string json_str(const ylib::json& j, const std::string& key,
  66. const std::string& def = "") {
  67. if (j.is_empty() || !j.exist(key)) {
  68. return def;
  69. }
  70. return j[key].to<std::string>(true);
  71. }
  72. bool json_bool(const ylib::json& j, const std::string& key, bool def = false) {
  73. if (j.is_empty() || !j.exist(key)) {
  74. return def;
  75. }
  76. return j[key].to<bool>(true);
  77. }
  78. int json_int(const ylib::json& j, const std::string& key, int def = 0) {
  79. if (j.is_empty() || !j.exist(key)) {
  80. return def;
  81. }
  82. return j[key].to<int32>(true);
  83. }
  84. int hex_nibble(char c) {
  85. if (c >= '0' && c <= '9') {
  86. return c - '0';
  87. }
  88. if (c >= 'a' && c <= 'f') {
  89. return c - 'a' + 10;
  90. }
  91. if (c >= 'A' && c <= 'F') {
  92. return c - 'A' + 10;
  93. }
  94. return -1;
  95. }
  96. // ylib get_url_param 不解码,需自行处理 %XX / +
  97. std::string url_decode(const std::string& in) {
  98. std::string out;
  99. out.reserve(in.size());
  100. for (size_t i = 0; i < in.size(); ++i) {
  101. const char c = in[i];
  102. if (c == '+') {
  103. out.push_back(' ');
  104. continue;
  105. }
  106. if (c == '%' && i + 2 < in.size()) {
  107. const int hi = hex_nibble(in[i + 1]);
  108. const int lo = hex_nibble(in[i + 2]);
  109. if (hi >= 0 && lo >= 0) {
  110. out.push_back(static_cast<char>((hi << 4) | lo));
  111. i += 2;
  112. continue;
  113. }
  114. }
  115. out.push_back(c);
  116. }
  117. return out;
  118. }
  119. std::string url_param(request* req, const std::string& key,
  120. const std::string& def = "") {
  121. if (!req) {
  122. return def;
  123. }
  124. std::string value;
  125. if (req->get_url_param(key, value) && !value.empty()) {
  126. return url_decode(value);
  127. }
  128. return def;
  129. }
  130. std::string b64_decode(const std::string& in) {
  131. static const int8_t kTable[256] = {
  132. -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  133. -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  134. -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,
  135. 52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,
  136. -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,
  137. 15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,
  138. -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,
  139. 41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1};
  140. std::string out;
  141. out.reserve(in.size() * 3 / 4);
  142. int val = 0, valb = -8;
  143. for (unsigned char c : in) {
  144. if (c == '=' || c == '\n' || c == '\r' || c == ' ') {
  145. continue;
  146. }
  147. const int8_t d = kTable[c];
  148. if (d < 0) {
  149. continue;
  150. }
  151. val = (val << 6) + d;
  152. valb += 6;
  153. if (valb >= 0) {
  154. out.push_back(static_cast<char>((val >> valb) & 0xFF));
  155. valb -= 8;
  156. }
  157. }
  158. return out;
  159. }
  160. void reply_ok(response* resp, const ylib::json& data = ylib::json(),
  161. const std::string& msg = "ok") {
  162. ylib::json out;
  163. out["code"] = 200;
  164. out["msg"] = msg;
  165. out["data"] = data;
  166. resp->send(out);
  167. }
  168. void reply_err(response* resp, const std::string& msg, int code = -1) {
  169. ylib::json out;
  170. // ylib: operator=(int32) 会先转 uint64,负数会变成超大数;用 double 保留 -1 等错误码
  171. out["code"] = static_cast<double>(code);
  172. out["msg"] = msg;
  173. out["data"] = ylib::json();
  174. resp->send(out);
  175. }
  176. bool require_method(request* req, response* resp, const std::string& method) {
  177. if (req->method() == method) {
  178. return true;
  179. }
  180. reply_err(resp, "method not allowed, expect " + method, 405);
  181. return false;
  182. }
  183. std::string request_cookie(request* req) {
  184. if (!req) {
  185. return "";
  186. }
  187. std::string v;
  188. if (req->header("Cookie", v) || req->header("cookie", v)) {
  189. return v;
  190. }
  191. return "";
  192. }
  193. std::string request_session_token(request* req) {
  194. return auth::session_from_cookie(request_cookie(req));
  195. }
  196. bool request_authed(request* req, std::string* username = nullptr) {
  197. return auth::session_valid(request_session_token(req), username);
  198. }
  199. void set_session_cookie(response* resp, const std::string& token, bool clear) {
  200. if (!resp || !resp->headers()) {
  201. return;
  202. }
  203. if (clear || token.empty()) {
  204. (*resp->headers())["Set-Cookie"] =
  205. "ngs_session=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0";
  206. return;
  207. }
  208. (*resp->headers())["Set-Cookie"] =
  209. "ngs_session=" + token +
  210. "; Path=/; HttpOnly; SameSite=Lax; Max-Age=604800";
  211. }
  212. bool require_auth(request* req, response* resp) {
  213. if (request_authed(req)) {
  214. return true;
  215. }
  216. reply_err(resp, "未登录或会话已过期", 401);
  217. return false;
  218. }
  219. using Handler = void (*)(request*, response*);
  220. void reg(ylib::network::http::router* router, const std::string& path,
  221. Handler handler, bool auth_required = true) {
  222. router->subscribe()->add(
  223. path, "",
  224. [handler, auth_required](request* req, response* resp, websocket_message*,
  225. const std::string&, const std::string&) {
  226. if (auth_required && !require_auth(req, resp)) {
  227. return;
  228. }
  229. handler(req, resp);
  230. });
  231. }
  232. // ---- handlers ----
  233. void h_ping(request* req, response* resp) {
  234. if (!require_method(req, resp, "GET")) {
  235. return;
  236. }
  237. ylib::json data;
  238. data["name"] = "ngs";
  239. data["listen"] = std::string(kDefaultListenAddr) + ":" +
  240. std::to_string(kDefaultListenPort);
  241. reply_ok(resp, data);
  242. }
  243. void h_auth_login(request* req, response* resp) {
  244. if (!require_method(req, resp, "POST")) {
  245. return;
  246. }
  247. auto body = parse_body(req);
  248. const std::string username = json_str(body, "username");
  249. const std::string password = json_str(body, "password");
  250. if (username.empty() || password.empty()) {
  251. reply_err(resp, "请输入账号和密码", 400);
  252. return;
  253. }
  254. if (!auth::verify(username, password)) {
  255. reply_err(resp, "账号或密码错误", 401);
  256. return;
  257. }
  258. const std::string token = auth::create_session(username);
  259. set_session_cookie(resp, token, false);
  260. ylib::json data;
  261. data["username"] = username;
  262. reply_ok(resp, data, "logged in");
  263. }
  264. void h_auth_logout(request* req, response* resp) {
  265. if (!require_method(req, resp, "POST")) {
  266. return;
  267. }
  268. auth::destroy_session(request_session_token(req));
  269. set_session_cookie(resp, "", true);
  270. reply_ok(resp, ylib::json(), "logged out");
  271. }
  272. void h_auth_me(request* req, response* resp) {
  273. if (!require_method(req, resp, "GET")) {
  274. return;
  275. }
  276. std::string username;
  277. if (!request_authed(req, &username)) {
  278. reply_err(resp, "未登录", 401);
  279. return;
  280. }
  281. ylib::json data;
  282. data["username"] = username;
  283. reply_ok(resp, data);
  284. }
  285. void reply_task_queued(response* resp, const std::string& task_id) {
  286. ylib::json data;
  287. data["task_id"] = task_id;
  288. data["active"] = tasks::active_count();
  289. reply_ok(resp, data, "task queued");
  290. }
  291. ylib::json task_to_json(const tasks::Task& t) {
  292. ylib::json item;
  293. item["id"] = t.id;
  294. item["type"] = t.type;
  295. item["title"] = t.title;
  296. item["status"] = tasks::status_str(t.status);
  297. item["created_at"] = static_cast<double>(t.created_at);
  298. item["started_at"] = static_cast<double>(t.started_at);
  299. item["finished_at"] = static_cast<double>(t.finished_at);
  300. item["message"] = t.message;
  301. item["log_lines"] = static_cast<double>(t.log_lines);
  302. return item;
  303. }
  304. void h_tasks_list(request* req, response* resp) {
  305. if (!require_method(req, resp, "GET")) {
  306. return;
  307. }
  308. ylib::json arr;
  309. for (const auto& t : tasks::list(false)) {
  310. arr.push_back(task_to_json(t));
  311. }
  312. ylib::json data;
  313. data["active"] = tasks::active_count();
  314. data["tasks"] = arr;
  315. reply_ok(resp, data);
  316. }
  317. void h_tasks_log(request* req, response* resp) {
  318. if (!require_method(req, resp, "GET")) {
  319. return;
  320. }
  321. const std::string id = url_param(req, "id");
  322. size_t off = 0;
  323. try {
  324. off = static_cast<size_t>(std::stoul(url_param(req, "offset", "0")));
  325. } catch (...) {
  326. off = 0;
  327. }
  328. std::vector<std::string> lines;
  329. size_t next = 0;
  330. tasks::Status st = tasks::Status::Pending;
  331. std::string message, err;
  332. if (!tasks::get_logs(id, off, lines, next, st, message, err)) {
  333. reply_err(resp, err);
  334. return;
  335. }
  336. ylib::json arr;
  337. for (const auto& line : lines) {
  338. arr.push_back(line);
  339. }
  340. ylib::json data;
  341. data["id"] = id;
  342. data["status"] = tasks::status_str(st);
  343. data["message"] = message;
  344. data["offset"] = static_cast<double>(off);
  345. data["next_offset"] = static_cast<double>(next);
  346. data["lines"] = arr;
  347. reply_ok(resp, data);
  348. }
  349. void h_tasks_clear(request* req, response* resp) {
  350. if (!require_method(req, resp, "POST")) {
  351. return;
  352. }
  353. tasks::clear_finished();
  354. ylib::json data;
  355. data["active"] = tasks::active_count();
  356. reply_ok(resp, data, "cleared");
  357. }
  358. void h_status(request* req, response* resp) {
  359. if (!require_method(req, resp, "GET")) {
  360. return;
  361. }
  362. ylib::json data;
  363. ylib::json nginx;
  364. nginx["installed"] = nginx::is_installed();
  365. nginx["running"] = nginx::is_running();
  366. nginx["version"] = nginx::installed_version();
  367. nginx["conf"] = nginx::conf_file();
  368. data["nginx"] = nginx;
  369. ylib::json fw;
  370. fw["installed"] = fastweb::is_installed();
  371. fw["version"] = fastweb::installed_version();
  372. data["fastweb"] = fw;
  373. ylib::json my;
  374. my["installed"] = mysql::is_installed();
  375. my["running"] = mysql::is_running();
  376. my["version"] = mysql::installed_version();
  377. my["port"] = mysql::kDefaultPort;
  378. my["conf"] = mysql::conf_file();
  379. data["mysql"] = my;
  380. ylib::json rd;
  381. rd["installed"] = redis::is_installed();
  382. rd["running"] = redis::is_running();
  383. rd["version"] = redis::installed_version();
  384. rd["port"] = redis::listen_port();
  385. rd["conf"] = redis::conf_file();
  386. data["redis"] = rd;
  387. data["sites"] = static_cast<int>(website::list_sites().size());
  388. reply_ok(resp, data);
  389. }
  390. void h_nginx_status(request* req, response* resp) {
  391. if (!require_method(req, resp, "GET")) {
  392. return;
  393. }
  394. ylib::json data;
  395. data["installed"] = nginx::is_installed();
  396. data["running"] = nginx::is_running();
  397. data["version"] = nginx::installed_version();
  398. data["install_dir"] = nginx::install_dir();
  399. data["bin"] = nginx::bin_path();
  400. data["conf"] = nginx::conf_file();
  401. reply_ok(resp, data);
  402. }
  403. void h_nginx_install(request* req, response* resp) {
  404. if (!require_method(req, resp, "POST")) {
  405. return;
  406. }
  407. auto body = parse_body(req);
  408. std::string version = json_str(body, "version", nginx::kDefaultVersion);
  409. std::string err;
  410. const std::string id = tasks::enqueue(
  411. "nginx.install", "安装 Nginx " + version,
  412. [version]() { return nginx::install(version); }, err);
  413. if (id.empty()) {
  414. reply_err(resp, err.empty() ? "enqueue failed" : err);
  415. return;
  416. }
  417. reply_task_queued(resp, id);
  418. }
  419. void h_nginx_uninstall(request* req, response* resp) {
  420. if (!require_method(req, resp, "POST")) {
  421. return;
  422. }
  423. std::string err;
  424. const std::string id = tasks::enqueue(
  425. "nginx.uninstall", "卸载 Nginx", []() { return nginx::uninstall(); },
  426. err);
  427. if (id.empty()) {
  428. reply_err(resp, err.empty() ? "enqueue failed" : err);
  429. return;
  430. }
  431. reply_task_queued(resp, id);
  432. }
  433. void h_nginx_start(request* req, response* resp) {
  434. if (!require_method(req, resp, "POST")) {
  435. return;
  436. }
  437. if (!nginx::start()) {
  438. reply_err(resp, "nginx start failed");
  439. return;
  440. }
  441. reply_ok(resp, ylib::json(), "nginx started");
  442. }
  443. void h_nginx_stop(request* req, response* resp) {
  444. if (!require_method(req, resp, "POST")) {
  445. return;
  446. }
  447. if (!nginx::stop()) {
  448. reply_err(resp, "nginx stop failed");
  449. return;
  450. }
  451. reply_ok(resp, ylib::json(), "nginx stopped");
  452. }
  453. void h_nginx_reload(request* req, response* resp) {
  454. if (!require_method(req, resp, "POST")) {
  455. return;
  456. }
  457. if (!nginx::reload()) {
  458. reply_err(resp, "nginx reload failed");
  459. return;
  460. }
  461. reply_ok(resp, ylib::json(), "nginx reloaded");
  462. }
  463. void h_fastweb_status(request* req, response* resp) {
  464. if (!require_method(req, resp, "GET")) {
  465. return;
  466. }
  467. ylib::json data;
  468. data["installed"] = fastweb::is_installed();
  469. data["version"] = fastweb::installed_version();
  470. data["install_dir"] = fastweb::install_dir();
  471. data["bin"] = fastweb::bin_path();
  472. reply_ok(resp, data);
  473. }
  474. void h_fastweb_install(request* req, response* resp) {
  475. if (!require_method(req, resp, "POST")) {
  476. return;
  477. }
  478. auto body = parse_body(req);
  479. const bool debug = json_bool(body, "debug", false);
  480. std::string err;
  481. const std::string id = tasks::enqueue(
  482. "fastweb.install", "安装 Fastweb",
  483. [debug]() { return fastweb::install(debug); }, err);
  484. if (id.empty()) {
  485. reply_err(resp, err.empty() ? "enqueue failed" : err);
  486. return;
  487. }
  488. reply_task_queued(resp, id);
  489. }
  490. void h_fastweb_uninstall(request* req, response* resp) {
  491. if (!require_method(req, resp, "POST")) {
  492. return;
  493. }
  494. std::string err;
  495. const std::string id = tasks::enqueue(
  496. "fastweb.uninstall", "卸载 Fastweb",
  497. []() { return fastweb::uninstall(); }, err);
  498. if (id.empty()) {
  499. reply_err(resp, err.empty() ? "enqueue failed" : err);
  500. return;
  501. }
  502. reply_task_queued(resp, id);
  503. }
  504. void h_mysql_status(request* req, response* resp) {
  505. if (!require_method(req, resp, "GET")) {
  506. return;
  507. }
  508. ylib::json data;
  509. data["installed"] = mysql::is_installed();
  510. data["running"] = mysql::is_running();
  511. data["version"] = mysql::installed_version();
  512. data["install_dir"] = mysql::install_dir();
  513. data["port"] = mysql::kDefaultPort;
  514. reply_ok(resp, data);
  515. }
  516. void h_mysql_install(request* req, response* resp) {
  517. if (!require_method(req, resp, "POST")) {
  518. return;
  519. }
  520. auto body = parse_body(req);
  521. std::string version = json_str(body, "version", mysql::kDefaultVersion);
  522. std::string err;
  523. const std::string id = tasks::enqueue(
  524. "mysql.install", "安装 MySQL " + version,
  525. [version]() { return mysql::install(version); }, err);
  526. if (id.empty()) {
  527. reply_err(resp, err.empty() ? "enqueue failed" : err);
  528. return;
  529. }
  530. reply_task_queued(resp, id);
  531. }
  532. void h_mysql_uninstall(request* req, response* resp) {
  533. if (!require_method(req, resp, "POST")) {
  534. return;
  535. }
  536. std::string err;
  537. const std::string id = tasks::enqueue(
  538. "mysql.uninstall", "卸载 MySQL", []() { return mysql::uninstall(); },
  539. err);
  540. if (id.empty()) {
  541. reply_err(resp, err.empty() ? "enqueue failed" : err);
  542. return;
  543. }
  544. reply_task_queued(resp, id);
  545. }
  546. void h_mysql_start(request* req, response* resp) {
  547. if (!require_method(req, resp, "POST")) {
  548. return;
  549. }
  550. if (!mysql::start()) {
  551. reply_err(resp, "mysql start failed");
  552. return;
  553. }
  554. reply_ok(resp, ylib::json(), "mysql started");
  555. }
  556. void h_mysql_stop(request* req, response* resp) {
  557. if (!require_method(req, resp, "POST")) {
  558. return;
  559. }
  560. if (!mysql::stop()) {
  561. reply_err(resp, "mysql stop failed");
  562. return;
  563. }
  564. reply_ok(resp, ylib::json(), "mysql stopped");
  565. }
  566. void h_mysql_root_password(request* req, response* resp) {
  567. if (!require_method(req, resp, "POST")) {
  568. return;
  569. }
  570. auto body = parse_body(req);
  571. std::string password = json_str(body, "password");
  572. if (password.empty()) {
  573. reply_err(resp, "password required");
  574. return;
  575. }
  576. if (!mysql::change_root_password(password)) {
  577. reply_err(resp, "change root password failed");
  578. return;
  579. }
  580. reply_ok(resp, ylib::json(), "root password updated");
  581. }
  582. void h_mysql_databases(request* req, response* resp) {
  583. const std::string method = req->method();
  584. if (method == "GET") {
  585. ylib::json arr;
  586. for (const auto& db : mysql::list_databases()) {
  587. ylib::json item;
  588. item["name"] = db.name;
  589. item["user"] = db.user;
  590. item["password"] = db.password;
  591. item["access"] = db.access;
  592. item["host"] = db.host;
  593. arr.push_back(item);
  594. }
  595. reply_ok(resp, arr);
  596. return;
  597. }
  598. if (method == "POST") {
  599. auto body = parse_body(req);
  600. std::string name = json_str(body, "name");
  601. std::string user = json_str(body, "user");
  602. std::string password = json_str(body, "password");
  603. if (name.empty() || user.empty() || password.empty()) {
  604. reply_err(resp, "name/user/password required");
  605. return;
  606. }
  607. if (!mysql::create_database(name, user, password)) {
  608. reply_err(resp, "create database failed");
  609. return;
  610. }
  611. reply_ok(resp, ylib::json(), "database created");
  612. return;
  613. }
  614. reply_err(resp, "method not allowed", 405);
  615. }
  616. void h_mysql_databases_drop(request* req, response* resp) {
  617. if (!require_method(req, resp, "POST")) {
  618. return;
  619. }
  620. auto body = parse_body(req);
  621. std::string name = json_str(body, "name");
  622. if (name.empty()) {
  623. reply_err(resp, "name required");
  624. return;
  625. }
  626. if (!mysql::drop_database(name)) {
  627. reply_err(resp, "drop database failed");
  628. return;
  629. }
  630. reply_ok(resp, ylib::json(), "database dropped");
  631. }
  632. void h_mysql_databases_access(request* req, response* resp) {
  633. if (!require_method(req, resp, "POST")) {
  634. return;
  635. }
  636. auto body = parse_body(req);
  637. std::string name = json_str(body, "name");
  638. std::string mode = json_str(body, "mode");
  639. std::string host = json_str(body, "host");
  640. if (name.empty() || mode.empty()) {
  641. reply_err(resp, "name/mode required");
  642. return;
  643. }
  644. if (!mysql::set_database_access(name, mode, host)) {
  645. reply_err(resp, "set database access failed");
  646. return;
  647. }
  648. reply_ok(resp, ylib::json(), "database access updated");
  649. }
  650. ylib::json site_to_json(const website::SiteInfo& s) {
  651. ylib::json item;
  652. item["name"] = s.name;
  653. item["type"] = website::type_key(s.type);
  654. const auto tokens = website::domain_tokens(s);
  655. item["domain"] = website::join_domains(tokens);
  656. ylib::json domains;
  657. for (const auto& t : tokens) {
  658. domains.push_back(t);
  659. }
  660. item["domains"] = domains;
  661. item["listen_port"] = s.listen_port;
  662. item["upstream"] = s.upstream;
  663. item["running"] = s.running;
  664. item["conf"] = website::vhost_conf_path(s.name);
  665. item["root"] = website::site_root_path(s.name);
  666. const std::string log_dir = website::site_log_dir_path(s.name);
  667. item["log_dir"] = log_dir;
  668. item["access_log"] = join_path(log_dir, "access.log");
  669. item["error_log"] = join_path(log_dir, "error.log");
  670. item["log_db"] = weblog::db_path(s.name);
  671. item["ssl_enable"] = s.ssl_enable;
  672. item["ssl_cert"] = s.ssl_cert;
  673. item["ssl_key"] = s.ssl_key;
  674. item["ssl_port"] = s.ssl_port;
  675. return item;
  676. }
  677. void h_websites(request* req, response* resp) {
  678. const std::string method = req->method();
  679. if (method == "GET") {
  680. ylib::json arr;
  681. for (const auto& s : website::list_sites()) {
  682. arr.push_back(site_to_json(s));
  683. }
  684. reply_ok(resp, arr);
  685. return;
  686. }
  687. if (method == "POST") {
  688. auto body = parse_body(req);
  689. website::CreateSiteRequest creq;
  690. creq.name = json_str(body, "name");
  691. std::string type = json_str(body, "type", "static");
  692. if (!website::parse_type_key(type, creq.type)) {
  693. reply_err(resp, "invalid type, expect static|proxy|fastweb");
  694. return;
  695. }
  696. creq.domain = json_str(body, "domain");
  697. if (body.exist("domains") && body["domains"].is_array()) {
  698. std::string joined;
  699. const auto& arr = body["domains"];
  700. for (uint32 i = 0; i < arr.size(); ++i) {
  701. std::string d = arr[i].to<std::string>(true);
  702. if (d.empty()) {
  703. continue;
  704. }
  705. if (!joined.empty()) {
  706. joined.push_back(' ');
  707. }
  708. joined += d;
  709. }
  710. if (!joined.empty()) {
  711. creq.domain = joined;
  712. }
  713. }
  714. creq.listen_port = json_int(body, "listen_port", 0);
  715. creq.upstream = json_str(body, "upstream");
  716. if (creq.name.empty()) {
  717. reply_err(resp, "name required");
  718. return;
  719. }
  720. std::string err;
  721. if (!website::create_site(creq, err)) {
  722. reply_err(resp, err.empty() ? "create site failed" : err);
  723. return;
  724. }
  725. website::SiteInfo created;
  726. website::find_site(creq.name, created);
  727. reply_ok(resp, site_to_json(created), "site created");
  728. return;
  729. }
  730. reply_err(resp, "method not allowed", 405);
  731. }
  732. void h_websites_start(request* req, response* resp) {
  733. if (!require_method(req, resp, "POST")) {
  734. return;
  735. }
  736. auto body = parse_body(req);
  737. std::string name = json_str(body, "name");
  738. if (name.empty()) {
  739. reply_err(resp, "name required");
  740. return;
  741. }
  742. std::string err;
  743. if (!website::start_site(name, err)) {
  744. reply_err(resp, err.empty() ? "start site failed" : err);
  745. return;
  746. }
  747. reply_ok(resp, ylib::json(), "site started");
  748. }
  749. void h_websites_stop(request* req, response* resp) {
  750. if (!require_method(req, resp, "POST")) {
  751. return;
  752. }
  753. auto body = parse_body(req);
  754. std::string name = json_str(body, "name");
  755. if (name.empty()) {
  756. reply_err(resp, "name required");
  757. return;
  758. }
  759. std::string err;
  760. if (!website::stop_site(name, err)) {
  761. reply_err(resp, err.empty() ? "stop site failed" : err);
  762. return;
  763. }
  764. reply_ok(resp, ylib::json(), "site stopped");
  765. }
  766. void h_websites_restart(request* req, response* resp) {
  767. if (!require_method(req, resp, "POST")) {
  768. return;
  769. }
  770. auto body = parse_body(req);
  771. std::string name = json_str(body, "name");
  772. if (name.empty()) {
  773. reply_err(resp, "name required");
  774. return;
  775. }
  776. std::string err;
  777. if (!website::restart_site(name, err)) {
  778. reply_err(resp, err.empty() ? "restart site failed" : err);
  779. return;
  780. }
  781. reply_ok(resp, ylib::json(), "site restarted");
  782. }
  783. void h_websites_delete(request* req, response* resp) {
  784. if (!require_method(req, resp, "POST")) {
  785. return;
  786. }
  787. auto body = parse_body(req);
  788. std::string name = json_str(body, "name");
  789. if (name.empty()) {
  790. reply_err(resp, "name required");
  791. return;
  792. }
  793. const bool delete_files = json_bool(body, "delete_files", false);
  794. std::string err;
  795. if (!website::delete_site(name, err, delete_files)) {
  796. reply_err(resp, err.empty() ? "delete site failed" : err);
  797. return;
  798. }
  799. reply_ok(resp, ylib::json(),
  800. delete_files ? "site and files deleted" : "site deleted");
  801. }
  802. void h_websites_update(request* req, response* resp) {
  803. if (!require_method(req, resp, "POST")) {
  804. return;
  805. }
  806. auto body = parse_body(req);
  807. website::UpdateSiteRequest ureq;
  808. ureq.name = json_str(body, "name");
  809. if (ureq.name.empty()) {
  810. reply_err(resp, "name required");
  811. return;
  812. }
  813. if (body.exist("domains") && body["domains"].is_array()) {
  814. std::string joined;
  815. const auto& arr = body["domains"];
  816. for (uint32 i = 0; i < arr.size(); ++i) {
  817. std::string d = arr[i].to<std::string>(true);
  818. if (d.empty()) {
  819. continue;
  820. }
  821. if (!joined.empty()) {
  822. joined.push_back(' ');
  823. }
  824. joined += d;
  825. }
  826. ureq.domain = joined;
  827. } else {
  828. ureq.domain = json_str(body, "domain");
  829. }
  830. ureq.listen_port = json_int(body, "listen_port", 0);
  831. ureq.update_ssl = body.exist("ssl_enable") || body.exist("ssl_cert") ||
  832. body.exist("ssl_key") || body.exist("ssl_port");
  833. ureq.ssl_enable = json_bool(body, "ssl_enable", false);
  834. ureq.ssl_cert = json_str(body, "ssl_cert");
  835. ureq.ssl_key = json_str(body, "ssl_key");
  836. ureq.ssl_port = json_int(body, "ssl_port", 443);
  837. std::string err;
  838. if (!website::update_site(ureq, err)) {
  839. reply_err(resp, err.empty() ? "update site failed" : err);
  840. return;
  841. }
  842. website::SiteInfo updated;
  843. website::find_site(ureq.name, updated);
  844. reply_ok(resp, site_to_json(updated), "site updated");
  845. }
  846. void h_websites_logs(request* req, response* resp) {
  847. if (!require_method(req, resp, "GET")) {
  848. return;
  849. }
  850. const std::string name = url_param(req, "name");
  851. if (name.empty()) {
  852. reply_err(resp, "name required");
  853. return;
  854. }
  855. website::SiteInfo site;
  856. if (!website::find_site(name, site)) {
  857. reply_err(resp, "site not found", 404);
  858. return;
  859. }
  860. const std::string kind = url_param(req, "kind", "access");
  861. size_t limit = 100;
  862. try {
  863. limit = static_cast<size_t>(std::stoul(url_param(req, "limit", "100")));
  864. } catch (...) {
  865. limit = 100;
  866. }
  867. int64_t before_id = 0;
  868. try {
  869. before_id = std::stoll(url_param(req, "before_id", "0"));
  870. } catch (...) {
  871. before_id = 0;
  872. }
  873. ylib::json arr;
  874. std::string err;
  875. if (kind == "error") {
  876. weblog::ErrorQuery q;
  877. q.name = name;
  878. q.limit = limit;
  879. q.before_id = before_id;
  880. q.level = url_param(req, "level");
  881. std::vector<weblog::ErrorRow> rows;
  882. if (!weblog::query_error(q, rows, err)) {
  883. reply_err(resp, err.empty() ? "query logs failed" : err);
  884. return;
  885. }
  886. for (const auto& r : rows) {
  887. ylib::json item;
  888. item["id"] = static_cast<int64>(r.id);
  889. item["time"] = r.time;
  890. item["time_ms"] = static_cast<int64>(r.time_ms);
  891. item["level"] = r.level;
  892. item["message"] = r.message;
  893. item["raw"] = r.raw;
  894. arr.push_back(item);
  895. }
  896. } else {
  897. weblog::AccessQuery q;
  898. q.name = name;
  899. q.limit = limit;
  900. q.before_id = before_id;
  901. try {
  902. q.status = std::stoi(url_param(req, "status", "0"));
  903. } catch (...) {
  904. q.status = 0;
  905. }
  906. q.ip = url_param(req, "ip");
  907. std::vector<weblog::AccessRow> rows;
  908. if (!weblog::query_access(q, rows, err)) {
  909. reply_err(resp, err.empty() ? "query logs failed" : err);
  910. return;
  911. }
  912. for (const auto& r : rows) {
  913. ylib::json item;
  914. item["id"] = static_cast<int64>(r.id);
  915. item["time"] = r.time;
  916. item["time_ms"] = static_cast<int64>(r.time_ms);
  917. item["ip"] = r.ip;
  918. item["method"] = r.method;
  919. item["host"] = r.host;
  920. item["uri"] = r.uri;
  921. item["args"] = r.args;
  922. item["status"] = r.status;
  923. item["bytes_recv"] = static_cast<int64>(r.bytes_recv);
  924. item["bytes_sent"] = static_cast<int64>(r.bytes_sent);
  925. item["request_time"] = r.request_time;
  926. item["upstream_status"] = r.upstream_status;
  927. item["upstream_addr"] = r.upstream_addr;
  928. item["referer"] = r.referer;
  929. item["ua"] = r.ua;
  930. item["request"] = r.request;
  931. arr.push_back(item);
  932. }
  933. }
  934. ylib::json data;
  935. data["name"] = name;
  936. data["kind"] = kind == "error" ? "error" : "access";
  937. data["log_db"] = weblog::db_path(name);
  938. data["items"] = arr;
  939. reply_ok(resp, data);
  940. }
  941. void h_websites_analytics(request* req, response* resp) {
  942. if (!require_method(req, resp, "GET")) {
  943. return;
  944. }
  945. const std::string name = url_param(req, "name");
  946. if (name.empty()) {
  947. reply_err(resp, "name required");
  948. return;
  949. }
  950. website::SiteInfo site;
  951. if (!website::find_site(name, site)) {
  952. reply_err(resp, "site not found", 404);
  953. return;
  954. }
  955. std::string range = url_param(req, "range", "24h");
  956. if (range.empty()) {
  957. range = "24h";
  958. }
  959. std::string json_body;
  960. std::string err;
  961. if (!weblog::analyze(name, range, json_body, err)) {
  962. reply_err(resp, err.empty() ? "analyze failed" : err);
  963. return;
  964. }
  965. ylib::json data;
  966. try {
  967. data = ylib::json::from(json_body);
  968. } catch (...) {
  969. reply_err(resp, "invalid analytics payload");
  970. return;
  971. }
  972. reply_ok(resp, data);
  973. }
  974. void h_websites_ssl_apply(request* req, response* resp) {
  975. if (!require_method(req, resp, "POST")) {
  976. return;
  977. }
  978. auto body = parse_body(req);
  979. const std::string name = json_str(body, "name");
  980. if (name.empty()) {
  981. reply_err(resp, "name required");
  982. return;
  983. }
  984. std::vector<std::string> hosts;
  985. if (body.exist("domains") && body["domains"].is_array()) {
  986. const auto& arr = body["domains"];
  987. for (uint32 i = 0; i < arr.size(); ++i) {
  988. std::string d = arr[i].to<std::string>(true);
  989. if (!d.empty()) {
  990. hosts.push_back(d);
  991. }
  992. }
  993. } else if (body.exist("hosts") && body["hosts"].is_array()) {
  994. const auto& arr = body["hosts"];
  995. for (uint32 i = 0; i < arr.size(); ++i) {
  996. std::string d = arr[i].to<std::string>(true);
  997. if (!d.empty()) {
  998. hosts.push_back(d);
  999. }
  1000. }
  1001. }
  1002. // Reuse stored ACME account email; generate once if missing.
  1003. std::string email = store::get_setting("ssl_email", "");
  1004. if (email.empty()) {
  1005. const auto now = std::chrono::system_clock::now().time_since_epoch().count();
  1006. email = "ngs-" + std::to_string(now % 1000000000ULL) + "@users.noreply.ngs.local";
  1007. store::set_setting("ssl_email", email);
  1008. }
  1009. std::string err;
  1010. std::string title = "申请 SSL · " + name;
  1011. if (!hosts.empty()) {
  1012. title += " (" + std::to_string(hosts.size()) + ")";
  1013. }
  1014. const std::string id = tasks::enqueue(
  1015. "ssl.letsencrypt", title,
  1016. [name, email, hosts]() {
  1017. std::string e;
  1018. if (!website::apply_letsencrypt(name, email, hosts, e)) {
  1019. if (!e.empty()) {
  1020. std::cerr << e << "\n";
  1021. log_error(e);
  1022. }
  1023. return false;
  1024. }
  1025. return true;
  1026. },
  1027. err);
  1028. if (id.empty()) {
  1029. reply_err(resp, err.empty() ? "enqueue failed" : err);
  1030. return;
  1031. }
  1032. ylib::json data;
  1033. data["task_id"] = id;
  1034. data["active"] = tasks::active_count();
  1035. reply_ok(resp, data, "task queued");
  1036. }
  1037. void h_system_metrics(request* req, response* resp) {
  1038. if (!require_method(req, resp, "GET")) {
  1039. return;
  1040. }
  1041. const auto m = system::sample();
  1042. ylib::json data;
  1043. ylib::json cpu;
  1044. cpu["percent"] = m.cpu.percent;
  1045. cpu["cores"] = m.cpu.cores;
  1046. data["cpu"] = cpu;
  1047. ylib::json memory;
  1048. memory["total"] = static_cast<int64>(m.memory.total_bytes);
  1049. memory["used"] = static_cast<int64>(m.memory.used_bytes);
  1050. memory["percent"] = m.memory.percent;
  1051. data["memory"] = memory;
  1052. ylib::json disk;
  1053. disk["path"] = m.disk.path;
  1054. disk["total"] = static_cast<int64>(m.disk.total_bytes);
  1055. disk["used"] = static_cast<int64>(m.disk.used_bytes);
  1056. disk["percent"] = m.disk.percent;
  1057. data["disk"] = disk;
  1058. ylib::json network;
  1059. network["rx_bytes"] = static_cast<int64>(m.network.rx_bytes);
  1060. network["tx_bytes"] = static_cast<int64>(m.network.tx_bytes);
  1061. network["rx_bps"] = m.network.rx_bps;
  1062. network["tx_bps"] = m.network.tx_bps;
  1063. data["network"] = network;
  1064. reply_ok(resp, data);
  1065. }
  1066. void h_system_metrics_history(request* req, response* resp) {
  1067. if (!require_method(req, resp, "GET")) {
  1068. return;
  1069. }
  1070. std::string range = url_param(req, "range", "10m");
  1071. if (range.empty()) {
  1072. range = "10m";
  1073. }
  1074. std::vector<system::HistoryPoint> points;
  1075. std::string err;
  1076. if (!system::history_query(range, points, err)) {
  1077. reply_err(resp, err.empty() ? "query metrics history failed" : err);
  1078. return;
  1079. }
  1080. ylib::json arr;
  1081. for (const auto& p : points) {
  1082. ylib::json item;
  1083. item["time_ms"] = static_cast<int64>(p.time_ms);
  1084. item["cpu_percent"] = p.cpu_percent;
  1085. item["cpu_cores"] = p.cpu_cores;
  1086. item["mem_percent"] = p.mem_percent;
  1087. item["mem_used"] = static_cast<int64>(p.mem_used);
  1088. item["mem_total"] = static_cast<int64>(p.mem_total);
  1089. item["disk_percent"] = p.disk_percent;
  1090. item["disk_used"] = static_cast<int64>(p.disk_used);
  1091. item["disk_total"] = static_cast<int64>(p.disk_total);
  1092. item["net_rx_bps"] = p.net_rx_bps;
  1093. item["net_tx_bps"] = p.net_tx_bps;
  1094. arr.push_back(item);
  1095. }
  1096. ylib::json data;
  1097. data["range"] = range;
  1098. data["items"] = arr;
  1099. reply_ok(resp, data);
  1100. }
  1101. void h_redis_status(request* req, response* resp) {
  1102. if (!require_method(req, resp, "GET")) {
  1103. return;
  1104. }
  1105. ylib::json data;
  1106. data["installed"] = redis::is_installed();
  1107. data["running"] = redis::is_running();
  1108. data["version"] = redis::installed_version();
  1109. data["install_dir"] = redis::install_dir();
  1110. data["bin"] = redis::bin_path();
  1111. data["conf"] = redis::conf_file();
  1112. data["port"] = redis::listen_port();
  1113. reply_ok(resp, data);
  1114. }
  1115. void h_redis_install(request* req, response* resp) {
  1116. if (!require_method(req, resp, "POST")) {
  1117. return;
  1118. }
  1119. auto body = parse_body(req);
  1120. std::string version = json_str(body, "version", redis::kDefaultVersion);
  1121. std::string err;
  1122. const std::string id = tasks::enqueue(
  1123. "redis.install", "安装 Redis " + version,
  1124. [version]() { return redis::install(version); }, err);
  1125. if (id.empty()) {
  1126. reply_err(resp, err.empty() ? "enqueue failed" : err);
  1127. return;
  1128. }
  1129. reply_task_queued(resp, id);
  1130. }
  1131. void h_redis_uninstall(request* req, response* resp) {
  1132. if (!require_method(req, resp, "POST")) {
  1133. return;
  1134. }
  1135. std::string err;
  1136. const std::string id = tasks::enqueue(
  1137. "redis.uninstall", "卸载 Redis", []() { return redis::uninstall(); },
  1138. err);
  1139. if (id.empty()) {
  1140. reply_err(resp, err.empty() ? "enqueue failed" : err);
  1141. return;
  1142. }
  1143. reply_task_queued(resp, id);
  1144. }
  1145. void h_redis_start(request* req, response* resp) {
  1146. if (!require_method(req, resp, "POST")) {
  1147. return;
  1148. }
  1149. if (!redis::start()) {
  1150. reply_err(resp, "redis start failed");
  1151. return;
  1152. }
  1153. reply_ok(resp, ylib::json(), "redis started");
  1154. }
  1155. void h_redis_stop(request* req, response* resp) {
  1156. if (!require_method(req, resp, "POST")) {
  1157. return;
  1158. }
  1159. if (!redis::stop()) {
  1160. reply_err(resp, "redis stop failed");
  1161. return;
  1162. }
  1163. reply_ok(resp, ylib::json(), "redis stopped");
  1164. }
  1165. void h_files_list(request* req, response* resp) {
  1166. if (!require_method(req, resp, "GET")) {
  1167. return;
  1168. }
  1169. std::string path = url_param(req, "path", "/");
  1170. std::string abs, err;
  1171. if (!files::resolve_path(path, abs, err)) {
  1172. reply_err(resp, err);
  1173. return;
  1174. }
  1175. std::vector<files::Entry> entries;
  1176. if (!files::list_dir(abs, entries, err)) {
  1177. reply_err(resp, err);
  1178. return;
  1179. }
  1180. ylib::json arr;
  1181. for (const auto& e : entries) {
  1182. ylib::json item;
  1183. item["name"] = e.name;
  1184. item["path"] = e.path;
  1185. item["is_dir"] = e.is_dir;
  1186. item["is_symlink"] = e.is_symlink;
  1187. item["size"] = static_cast<int64>(e.size);
  1188. item["mtime"] = static_cast<int64>(e.mtime);
  1189. arr.push_back(item);
  1190. }
  1191. ylib::json data;
  1192. data["path"] = abs;
  1193. data["entries"] = arr;
  1194. reply_ok(resp, data);
  1195. }
  1196. void h_files_mkdir(request* req, response* resp) {
  1197. if (!require_method(req, resp, "POST")) {
  1198. return;
  1199. }
  1200. auto body = parse_body(req);
  1201. std::string path = json_str(body, "path");
  1202. std::string err;
  1203. if (!files::mkdir_path(path, err)) {
  1204. reply_err(resp, err);
  1205. return;
  1206. }
  1207. reply_ok(resp, ylib::json(), "directory created");
  1208. }
  1209. void h_files_write(request* req, response* resp) {
  1210. if (!require_method(req, resp, "POST")) {
  1211. return;
  1212. }
  1213. auto body = parse_body(req);
  1214. std::string path = json_str(body, "path");
  1215. std::string content = json_str(body, "content");
  1216. std::string err;
  1217. if (!files::write_text(path, content, err)) {
  1218. reply_err(resp, err);
  1219. return;
  1220. }
  1221. reply_ok(resp, ylib::json(), "written");
  1222. }
  1223. void h_files_read(request* req, response* resp) {
  1224. if (!require_method(req, resp, "GET")) {
  1225. return;
  1226. }
  1227. std::string path = url_param(req, "path");
  1228. std::string content, err;
  1229. if (!files::read_text(path, content, err)) {
  1230. reply_err(resp, err);
  1231. return;
  1232. }
  1233. ylib::json data;
  1234. data["path"] = path;
  1235. data["content"] = content;
  1236. reply_ok(resp, data);
  1237. }
  1238. void h_files_tail(request* req, response* resp) {
  1239. if (!require_method(req, resp, "GET")) {
  1240. return;
  1241. }
  1242. std::string path = url_param(req, "path");
  1243. size_t max_bytes = 256ull * 1024ull;
  1244. try {
  1245. max_bytes = static_cast<size_t>(
  1246. std::stoul(url_param(req, "bytes", "262144")));
  1247. } catch (...) {
  1248. }
  1249. if (max_bytes < 1024) {
  1250. max_bytes = 1024;
  1251. }
  1252. if (max_bytes > files::kMaxEditBytes) {
  1253. max_bytes = files::kMaxEditBytes;
  1254. }
  1255. std::string content, err;
  1256. if (!files::read_tail(path, max_bytes, content, err)) {
  1257. reply_err(resp, err);
  1258. return;
  1259. }
  1260. ylib::json data;
  1261. data["path"] = path;
  1262. data["content"] = content;
  1263. reply_ok(resp, data);
  1264. }
  1265. void h_files_rename(request* req, response* resp) {
  1266. if (!require_method(req, resp, "POST")) {
  1267. return;
  1268. }
  1269. auto body = parse_body(req);
  1270. std::string from = json_str(body, "from");
  1271. std::string to = json_str(body, "to");
  1272. std::string err;
  1273. if (!files::rename_path(from, to, err)) {
  1274. reply_err(resp, err);
  1275. return;
  1276. }
  1277. reply_ok(resp, ylib::json(), "renamed");
  1278. }
  1279. void h_files_delete(request* req, response* resp) {
  1280. if (!require_method(req, resp, "POST")) {
  1281. return;
  1282. }
  1283. auto body = parse_body(req);
  1284. std::string path = json_str(body, "path");
  1285. const bool recursive = json_bool(body, "recursive", false);
  1286. std::string err;
  1287. if (!files::delete_path(path, recursive, err)) {
  1288. reply_err(resp, err);
  1289. return;
  1290. }
  1291. reply_ok(resp, ylib::json(), "deleted");
  1292. }
  1293. void h_files_upload(request* req, response* resp) {
  1294. if (!require_method(req, resp, "POST")) {
  1295. return;
  1296. }
  1297. auto body = parse_body(req);
  1298. std::string path = json_str(body, "path");
  1299. std::string b64 = json_str(body, "content_base64");
  1300. std::string content = json_str(body, "content");
  1301. std::string bytes = b64.empty() ? content : b64_decode(b64);
  1302. std::string err;
  1303. if (!files::write_bytes(path, bytes, err)) {
  1304. reply_err(resp, err);
  1305. return;
  1306. }
  1307. reply_ok(resp, ylib::json(), "uploaded");
  1308. }
  1309. void h_files_download(request* req, response* resp) {
  1310. if (!require_method(req, resp, "GET")) {
  1311. return;
  1312. }
  1313. std::string path = url_param(req, "path");
  1314. std::string abs, err;
  1315. if (!files::resolve_path(path, abs, err)) {
  1316. reply_err(resp, err);
  1317. return;
  1318. }
  1319. if (!path_exists(abs) || is_dir(abs)) {
  1320. reply_err(resp, "file not found");
  1321. return;
  1322. }
  1323. std::string name = fs::path(abs).filename().string();
  1324. if (name.empty()) {
  1325. name = "download";
  1326. }
  1327. // Keep original filename for browsers (ASCII fallback + RFC5987 UTF-8).
  1328. std::string safe;
  1329. for (unsigned char c : name) {
  1330. if (c == '"' || c == '\\' || c < 0x20) {
  1331. safe.push_back('_');
  1332. } else {
  1333. safe.push_back(static_cast<char>(c));
  1334. }
  1335. }
  1336. std::string encoded;
  1337. static const char* hex = "0123456789ABCDEF";
  1338. for (unsigned char c : name) {
  1339. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  1340. (c >= '0' && c <= '9') || c == '.' || c == '_' || c == '-') {
  1341. encoded.push_back(static_cast<char>(c));
  1342. } else {
  1343. encoded.push_back('%');
  1344. encoded.push_back(hex[c >> 4]);
  1345. encoded.push_back(hex[c & 0xF]);
  1346. }
  1347. }
  1348. (*resp->headers())["Content-Disposition"] =
  1349. "attachment; filename=\"" + safe + "\"; filename*=UTF-8''" + encoded;
  1350. (*resp->headers())["Content-Type"] = "application/octet-stream";
  1351. resp->send_file(abs);
  1352. }
  1353. void register_routes(ylib::network::http::router* router) {
  1354. // Public endpoints
  1355. reg(router, "/api/ping", h_ping, false);
  1356. reg(router, "/api/auth/login", h_auth_login, false);
  1357. reg(router, "/api/auth/logout", h_auth_logout, false);
  1358. reg(router, "/api/auth/me", h_auth_me, false);
  1359. reg(router, "/api/status", h_status);
  1360. reg(router, "/api/system/metrics", h_system_metrics);
  1361. reg(router, "/api/system/metrics/history", h_system_metrics_history);
  1362. reg(router, "/api/tasks", h_tasks_list);
  1363. reg(router, "/api/tasks/log", h_tasks_log);
  1364. reg(router, "/api/tasks/clear", h_tasks_clear);
  1365. reg(router, "/api/nginx/status", h_nginx_status);
  1366. reg(router, "/api/nginx/install", h_nginx_install);
  1367. reg(router, "/api/nginx/uninstall", h_nginx_uninstall);
  1368. reg(router, "/api/nginx/start", h_nginx_start);
  1369. reg(router, "/api/nginx/stop", h_nginx_stop);
  1370. reg(router, "/api/nginx/reload", h_nginx_reload);
  1371. reg(router, "/api/fastweb/status", h_fastweb_status);
  1372. reg(router, "/api/fastweb/install", h_fastweb_install);
  1373. reg(router, "/api/fastweb/uninstall", h_fastweb_uninstall);
  1374. reg(router, "/api/mysql/status", h_mysql_status);
  1375. reg(router, "/api/mysql/install", h_mysql_install);
  1376. reg(router, "/api/mysql/uninstall", h_mysql_uninstall);
  1377. reg(router, "/api/mysql/start", h_mysql_start);
  1378. reg(router, "/api/mysql/stop", h_mysql_stop);
  1379. reg(router, "/api/mysql/root/password", h_mysql_root_password);
  1380. reg(router, "/api/mysql/databases", h_mysql_databases);
  1381. reg(router, "/api/mysql/databases/drop", h_mysql_databases_drop);
  1382. reg(router, "/api/mysql/databases/access", h_mysql_databases_access);
  1383. reg(router, "/api/redis/status", h_redis_status);
  1384. reg(router, "/api/redis/install", h_redis_install);
  1385. reg(router, "/api/redis/uninstall", h_redis_uninstall);
  1386. reg(router, "/api/redis/start", h_redis_start);
  1387. reg(router, "/api/redis/stop", h_redis_stop);
  1388. reg(router, "/api/websites", h_websites);
  1389. reg(router, "/api/websites/start", h_websites_start);
  1390. reg(router, "/api/websites/stop", h_websites_stop);
  1391. reg(router, "/api/websites/restart", h_websites_restart);
  1392. reg(router, "/api/websites/delete", h_websites_delete);
  1393. reg(router, "/api/websites/update", h_websites_update);
  1394. reg(router, "/api/websites/logs", h_websites_logs);
  1395. reg(router, "/api/websites/analytics", h_websites_analytics);
  1396. reg(router, "/api/websites/ssl/apply", h_websites_ssl_apply);
  1397. reg(router, "/api/files/list", h_files_list);
  1398. reg(router, "/api/files/mkdir", h_files_mkdir);
  1399. reg(router, "/api/files/write", h_files_write);
  1400. reg(router, "/api/files/read", h_files_read);
  1401. reg(router, "/api/files/tail", h_files_tail);
  1402. reg(router, "/api/files/rename", h_files_rename);
  1403. reg(router, "/api/files/delete", h_files_delete);
  1404. reg(router, "/api/files/upload", h_files_upload);
  1405. reg(router, "/api/files/download", h_files_download);
  1406. const std::string www = panel_www_dir();
  1407. router->other([www](request* req, response* resp, websocket_message*) {
  1408. std::string path = req ? req->filepath() : "/";
  1409. if (path.empty() || path == "/") {
  1410. path = "/index.html";
  1411. }
  1412. if (path.rfind("/api/", 0) == 0) {
  1413. reply_err(resp, "not found", 404);
  1414. return;
  1415. }
  1416. if (path.find("..") != std::string::npos) {
  1417. reply_err(resp, "forbidden", 403);
  1418. return;
  1419. }
  1420. const bool is_asset =
  1421. path.rfind("/assets/", 0) == 0 || path == "/favicon.ico";
  1422. const bool is_login =
  1423. path == "/login.html" || path == "/login" || path == "login.html";
  1424. if (!is_asset && !is_login && !request_authed(req)) {
  1425. resp->redirect("/login.html", false);
  1426. return;
  1427. }
  1428. if (is_login && request_authed(req)) {
  1429. resp->redirect("/", false);
  1430. return;
  1431. }
  1432. while (!path.empty() && path[0] == '/') {
  1433. path.erase(path.begin());
  1434. }
  1435. if (path == "login") {
  1436. path = "login.html";
  1437. }
  1438. std::string file = join_path(www, path);
  1439. if (is_dir(file)) {
  1440. file = join_path(file, "index.html");
  1441. }
  1442. if (path_exists(file) && !is_dir(file)) {
  1443. resp->send_file(file);
  1444. return;
  1445. }
  1446. const std::string index = join_path(www, "index.html");
  1447. if (path_exists(index)) {
  1448. resp->send_file(index);
  1449. return;
  1450. }
  1451. reply_err(resp, "panel not found: " + www, 404);
  1452. });
  1453. }
  1454. } // namespace
  1455. bool run(const std::string& listen_addr, uint16_t listen_port) {
  1456. (void)listen_addr; // ylib HttpServer always binds 0.0.0.0
  1457. ensure_dir(software_root());
  1458. ensure_dir(conf_root());
  1459. ensure_dir(wwwroot_dir());
  1460. {
  1461. std::string aerr;
  1462. if (!auth::init(aerr)) {
  1463. std::cerr << "apiserver auth init failed: " << aerr << "\n";
  1464. log_error("auth init failed: " + aerr);
  1465. return false;
  1466. }
  1467. }
  1468. if (!store::init()) {
  1469. std::cerr << "apiserver sqlite init failed: " << store::database_path()
  1470. << "\n";
  1471. log_error("sqlite init failed path=" + store::database_path());
  1472. return false;
  1473. }
  1474. tasks::start();
  1475. weblog::start();
  1476. system::history_start();
  1477. log_info("ngs apiserver starting listen=" + listen_addr + ":" +
  1478. std::to_string(listen_port));
  1479. install_signal_handlers();
  1480. auto* center = new ylib::network::http::center();
  1481. g_center = center;
  1482. ylib::network::http::start_config config;
  1483. ylib::network::http::website_config ws_config;
  1484. ws_config.name = "ngs-api";
  1485. // domain containing 0.0.0.0 matches any Host header in ylib.
  1486. ylib::network::http::host_config host;
  1487. host.domain = listen_addr.empty() ? kDefaultListenAddr : listen_addr;
  1488. host.port = listen_port;
  1489. host.ssl = false;
  1490. ws_config.host.push_back(host);
  1491. ws_config.router.threadpool.size = 8;
  1492. ws_config.router.threadpool.queuemax = 10000;
  1493. config.max_upload_size = 64 * 1024 * 1024;
  1494. config.websocket_enable = false;
  1495. config.website.push_back(ws_config);
  1496. if (!center->create(config)) {
  1497. std::cerr << "apiserver create failed: " << center->last_error() << "\n";
  1498. log_error("apiserver create failed: " + center->last_error());
  1499. delete center;
  1500. g_center = nullptr;
  1501. return false;
  1502. }
  1503. auto* website = center->website_byname(ws_config.name);
  1504. if (!website || !website->router()) {
  1505. std::cerr << "apiserver website/router missing\n";
  1506. log_error("apiserver website/router missing");
  1507. center->close();
  1508. delete center;
  1509. g_center = nullptr;
  1510. return false;
  1511. }
  1512. register_routes(website->router());
  1513. if (!center->start()) {
  1514. std::cerr << "apiserver start failed: " << center->last_error() << "\n";
  1515. log_error("apiserver start failed: " + center->last_error());
  1516. center->close();
  1517. delete center;
  1518. g_center = nullptr;
  1519. return false;
  1520. }
  1521. // HPSocket may touch signal state during start; reinstall our handlers.
  1522. install_signal_handlers();
  1523. std::cout << "NGS API Server listening on http://" << host.domain << ":"
  1524. << listen_port << "\n";
  1525. std::cout << "Panel: http://127.0.0.1:" << listen_port << "/\n";
  1526. std::cout << "Panel dir: " << panel_www_dir() << "\n";
  1527. std::cout << "Docs: API.md\n";
  1528. std::cout.flush();
  1529. log_info("ngs apiserver listening port=" + std::to_string(listen_port) +
  1530. " panel=" + panel_www_dir());
  1531. while (g_running.load(std::memory_order_relaxed)) {
  1532. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  1533. }
  1534. std::cout << "Shutting down...\n";
  1535. log_info("ngs apiserver stopping");
  1536. weblog::stop();
  1537. system::history_stop();
  1538. tasks::stop();
  1539. center->close();
  1540. delete center;
  1541. g_center = nullptr;
  1542. return true;
  1543. }
  1544. } // namespace api
  1545. } // namespace ngs