api_server.cpp 61 KB

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