common.C 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. /*
  2. This program is free software: you can redistribute it and/or modify
  3. it under the terms of the GNU General Public License as published by
  4. the Free Software Foundation, either version 3 of the License, or
  5. (at your option) any later version.
  6. This program is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. GNU General Public License for more details.
  10. You should have received a copy of the GNU General Public License
  11. along with this program. If not, see <http://www.gnu.org/licenses/>.
  12. * */
  13. /*
  14. * common.C
  15. *
  16. * Created on: Apr 6, 2013
  17. * Author: xaxaxa
  18. */
  19. #include <cpoll/cpoll.H>
  20. #include <string>
  21. #include <string.h>
  22. #include <exception>
  23. #include <sys/mman.h>
  24. #include <sys/stat.h>
  25. #include <unistd.h>
  26. #include <sys/types.h>
  27. #include <stdexcept>
  28. #include <fcntl.h>
  29. #include <dlfcn.h>
  30. #include <libgen.h>
  31. #include <sys/wait.h>
  32. #include "include/common.H"
  33. #include "include/page.H"
  34. #include <errno.h>
  35. #include "include/split.H"
  36. using namespace CP;
  37. using namespace std;
  38. namespace cppsp
  39. {
  40. PThreadMutex dlMutex;
  41. const char* gxx = "g++";
  42. ParserException::ParserException() :
  43. message(strerror(errno)), number(errno) {
  44. }
  45. ParserException::ParserException(int32_t number) :
  46. message(strerror(number)), number(number) {
  47. }
  48. ParserException::ParserException(string message, int32_t number) :
  49. message(message), number(number) {
  50. }
  51. ParserException::~ParserException() throw () {
  52. }
  53. const char* ParserException::what() const throw () {
  54. return message.c_str();
  55. }
  56. CompileException::CompileException() :
  57. message("Compilation error") {
  58. }
  59. CompileException::CompileException(string message) :
  60. message(message) {
  61. }
  62. CompileException::~CompileException() throw () {
  63. }
  64. const char* CompileException::what() const throw () {
  65. return message.c_str();
  66. }
  67. //inline-able memcpy() for copying SHORT STRINGS ONLY
  68. static inline void memcpy2(void* dst, const void* src, int len) {
  69. for (int i = 0; i < len; i++)
  70. ((char*) dst)[i] = ((const char*) src)[i];
  71. }
  72. // "/" + "aaaaa" => "/aaaaa"
  73. // "/asdf/" + "zzz" => "/asdf/zzz"
  74. // "/asdf/" + "zzz/" => "/asdf/zzz/"
  75. // "/asdf" + "zzz" => "/zzz"
  76. // "/asdf/" + "../zzz" => "/zzz"
  77. // "/asdf/" + "a/../x" => "/asdf/x"
  78. // "/asdf/" + "/zzz" => "/zzz"
  79. //the size of buf should be at least strlen(p1)+strlen(p2)
  80. //returns the length of the string written to buf; does NOT write null byte
  81. int combinePath(const char* p1, int l1, const char* p2, int l2, char* buf) {
  82. if (l2 > 0 && p2[0] == '/') {
  83. memcpy2(buf, p2, l2);
  84. return l2;
  85. }
  86. int i = l1;
  87. memcpy2(buf, p1, i);
  88. if (l2 > 0) {
  89. i--;
  90. while (i >= 0 && buf[i] != '/')
  91. i--;
  92. if (i < 0) i = 0;
  93. split spl(p2, l2, '/');
  94. while (spl.read()) {
  95. const char* s = spl.value.data();
  96. int l = spl.value.length();
  97. if (l == 2 && *(const uint16_t*) s == *(const uint16_t*) "..") {
  98. i--;
  99. while (i >= 0 && buf[i] != '/')
  100. i--;
  101. if (i < 0) i = 0;
  102. } else if (l == 1 && *s == '.') {
  103. buf[i] = '/';
  104. i++;
  105. } else {
  106. //while(i>=0 && buf[i]!='/')i--;
  107. buf[i] = '/';
  108. i++;
  109. memcpy2(buf + i, s, l);
  110. i += l;
  111. }
  112. }
  113. //if (l2 > 0 && i > 0 && p2[l2 - 1] != '/' && buf[i - 1] == '/')
  114. }
  115. if (i < 0) i = 0;
  116. return i;
  117. }
  118. int combinePath(const char* p1, const char* p2, char* buf) {
  119. return combinePath(p1, strlen(p1), p2, strlen(p2), buf);
  120. }
  121. //p1 is the "root" directory
  122. //guarantees that the resulting path won't be outside of p1
  123. int combinePathChroot(const char* p1, int l1, const char* p2, int l2, char* buf) {
  124. int i = l1;
  125. memcpy2(buf, p1, i);
  126. static const uint16_t parentDir = *(const uint16_t*) "..";
  127. if (l2 > 0) {
  128. bool first(true);
  129. split spl(p2, l2, '/');
  130. while (spl.read()) {
  131. const char* s = spl.value.data();
  132. int l = spl.value.length();
  133. if (first) {
  134. first = false;
  135. if (l == 0) continue;
  136. }
  137. if (l == 2 && *(const uint16_t*) s == parentDir) {
  138. i--;
  139. while (i >= 0 && buf[i] != '/')
  140. i--;
  141. if (i < l1) i = l1;
  142. } else if (l == 1 && *s == '.') {
  143. if (!(i > 0 && buf[i - 1] == '/')) {
  144. buf[i] = '/';
  145. i++;
  146. }
  147. } else {
  148. //while(i>=0 && buf[i]!='/')i--;
  149. if (!(i > 0 && buf[i - 1] == '/')) {
  150. buf[i] = '/';
  151. i++;
  152. }
  153. memcpy2(buf + i, s, l);
  154. i += l;
  155. }
  156. }
  157. //if (l2 > 0 && i > 0 && p2[l2 - 1] != '/' && buf[i - 1] == '/')
  158. }
  159. if (i < l1) i = l1;
  160. return i;
  161. }
  162. int combinePathChroot(const char* p1, const char* p2, char* buf) {
  163. return combinePathChroot(p1, strlen(p1), p2, strlen(p2), buf);
  164. }
  165. String combinePath(String p1, String p2, StringPool& sp) {
  166. char* tmp = sp.beginAdd(p1.length() + p2.length());
  167. int l = combinePath(p1.data(), p2.data(), tmp);
  168. sp.endAdd(l);
  169. return {tmp,l};
  170. }
  171. String combinePathChroot(String p1, String p2, StringPool& sp) {
  172. char* tmp = sp.beginAdd(p1.length() + p2.length());
  173. int l = combinePathChroot(p1.data(), p2.data(), tmp);
  174. sp.endAdd(l);
  175. return {tmp,l};
  176. }
  177. //parses a cppsp page and generates code (to out) and string table (to st_out)
  178. void doParse(const char* name, const char* in, int inLen, Stream& out, Stream& st_out,
  179. vector<string>& c_opts) {
  180. const char* s = in;
  181. const char* end = s + inLen;
  182. string inherits = "Page";
  183. string classname = (name == NULL ? "__cppsp_unnamed_page" : name);
  184. int st_pos = 0;
  185. int st_len = 0;
  186. //int out_initlen=out.length();
  187. Stream& ms1(out); //declarations outside of the class
  188. MemoryStream ms2; //declarations outside of the render() function
  189. MemoryStream ms3; //code inside render()
  190. StreamWriter sw1(ms1);
  191. StreamWriter sw2(ms2);
  192. StreamWriter sw3(ms3);
  193. sw1.write("#include <cppsp/page.H>\n#include <cpoll/cpoll.H>\n");
  194. sw1.write("#include <cppsp/common.H>\n#include <cppsp/stringutils.H>\n");
  195. sw1.write("#include <rgc.H>\n");
  196. sw1.write("using namespace cppsp;\nusing namespace CP;\n");
  197. int line = 1;
  198. while (true) {
  199. if (s >= end) break;
  200. const char* old_s = s;
  201. s = (const char*) memmem(s, end - s, "<%", 2);
  202. if (s > old_s) {
  203. st_out.write(old_s, s - old_s);
  204. st_len += (s - old_s);
  205. } else if (s == NULL) {
  206. st_out.write(old_s, end - old_s);
  207. st_len += (end - old_s);
  208. sw3.writeF("__writeStringTable(%i,%i);\n", st_pos, st_len - st_pos);
  209. break;
  210. }
  211. for (const char* ch = old_s; ch < s; ch++)
  212. if (*ch == '\n') line++;
  213. s += 2;
  214. if (s >= end) throw ParserException("reached EOF when looking past \"<%\"");
  215. const char* s1 = (const char*) memmem(s, end - s, "%>", 2);
  216. if (s1 == NULL) throw ParserException("reached EOF when looking for matching \"%>\"");
  217. switch (*s) {
  218. case '!':
  219. { //compiler option
  220. c_opts.push_back(string(s + 1, s1 - s - 1));
  221. break;
  222. }
  223. case '@':
  224. { //cppsp options
  225. int nextopt = 0;
  226. split spl(s + 1, s1 - s - 1, ' ');
  227. while (spl.read()) {
  228. const char* s1 = spl.value.data();
  229. int l1 = spl.value.length();
  230. switch (nextopt) {
  231. case 0:
  232. {
  233. if (l1 == 8 && memcmp(s1, "inherits", 8) == 0) nextopt = 1;
  234. else if (l1 == 5 && memcmp(s1, "class", 5) == 0) nextopt = 2;
  235. continue;
  236. }
  237. case 1:
  238. {
  239. inherits = string(s1, l1);
  240. break;
  241. }
  242. case 2:
  243. {
  244. if (name == NULL) classname = string(s1, l1);
  245. break;
  246. }
  247. }
  248. nextopt = 0;
  249. }
  250. break;
  251. }
  252. case '#':
  253. { //declarations outside of the class
  254. sw1.writeF("#line %i\n", line);
  255. sw1.write(s + 1, s1 - s - 1);
  256. break;
  257. }
  258. case '$':
  259. { //declarations outside of the render() function
  260. sw2.writeF("#line %i\n", line);
  261. sw2.write(s + 1, s1 - s - 1);
  262. break;
  263. }
  264. case '=':
  265. {
  266. sw3.writeF("__writeStringTable(%i,%i);\n", st_pos, st_len - st_pos);
  267. st_pos = st_len;
  268. sw3.writeF("#line %i\n", line);
  269. sw3.write("output.write(");
  270. sw3.write(s + 1, s1 - s - 1);
  271. sw3.write(");\n");
  272. break;
  273. }
  274. default:
  275. {
  276. sw3.writeF("__writeStringTable(%i,%i);\n", st_pos, st_len - st_pos);
  277. st_pos = st_len;
  278. sw3.writeF("#line %i\n", line);
  279. sw3.write(s, s1 - s);
  280. break;
  281. }
  282. }
  283. for (const char* ch = s; ch < s1; ch++)
  284. if (*ch == '\n') line++;
  285. s = s1 + 2;
  286. }
  287. sw2.flush();
  288. sw3.flush();
  289. sw1.writeF("class %s: public %s {\npublic:\n", classname.c_str(), inherits.c_str());
  290. sw1.write(ms2.data(), ms2.length());
  291. //the name of the StreamWriter parameter should always be "output" -- this is part of
  292. //the cppsp API and should not ever be changed; users can rely on its name being "output".
  293. sw1.write("virtual void render(StreamWriter& output) override {\n");
  294. sw1.write(ms3.data(), ms3.length());
  295. sw1.write("}\n};\n");
  296. sw1.writeF("extern \"C\" int getObjectSize() {return sizeof(%s);}\n", classname.c_str());
  297. sw1.writeF("extern \"C\" Page* createObject(void* mem) {"
  298. "if(mem==NULL) return new %s(); else return new (mem) %s();}\n", classname.c_str(),
  299. classname.c_str());
  300. sw1.writeF("extern \"C\" Page* createObject1(RGC::Allocator* alloc) {"
  301. "%s* tmp = new (alloc->alloc(sizeof(%s))) %s(); tmp->allocator=alloc; return tmp;}\n",
  302. classname.c_str(), classname.c_str(), classname.c_str());
  303. sw1.flush();
  304. //out.write(ms1.data(), ms1.length());
  305. }
  306. static inline int checkError(int i) {
  307. if (i < 0) throw runtime_error(strerror(errno));
  308. return i;
  309. }
  310. static inline void* checkError(void* p) {
  311. if (p == NULL) throw runtime_error(strerror(errno));
  312. return p;
  313. }
  314. static inline void* checkDLError(void* p) {
  315. if (p == NULL) throw runtime_error(dlerror());
  316. return p;
  317. }
  318. CP::File* compilePage(string wd, string path, string cPath, string txtPath, string output,
  319. const vector<string>& cxxopts, pid_t& pid, string& compilecmd) {
  320. vector<string> c_opts { gxx, gxx, "--std=c++0x", "--shared", "-o", output, cPath };
  321. c_opts.insert(c_opts.end(), cxxopts.begin(), cxxopts.end());
  322. {
  323. File inp(open(path.c_str(), O_RDONLY));
  324. MemoryStream ms;
  325. inp.readToEnd(ms);
  326. ms.flush();
  327. //unlink((path + ".C").c_str());
  328. File out_c(open(cPath.c_str(), O_RDWR | O_CREAT | O_TRUNC, 0666));
  329. File out_s(open(txtPath.c_str(), O_RDWR | O_CREAT | O_TRUNC, 0666));
  330. cppsp::doParse(NULL, (const char*) ms.data(), ms.length(), out_c, out_s, c_opts);
  331. }
  332. const char* cmds[c_opts.size() + 1];
  333. for (int i = 0; i < (int) c_opts.size(); i++) {
  334. cmds[i] = c_opts[i].c_str();
  335. }
  336. cmds[c_opts.size()] = NULL;
  337. int p[2];
  338. checkError(pipe(p));
  339. //unlink((path + ".so").c_str());
  340. pid_t tmp = fork();
  341. if (tmp > 0) {
  342. close(p[1]);
  343. pid = tmp;
  344. for (int i = 1; i < (int) c_opts.size(); i++) {
  345. compilecmd.append(c_opts[i]);
  346. compilecmd.append(" ");
  347. }
  348. return new CP::File(p[0]);
  349. } else if (tmp == 0) {
  350. close(p[0]);
  351. dup2(p[1], 1);
  352. dup2(p[1], 2);
  353. close(p[1]);
  354. chdir(wd.c_str());
  355. execvp(cmds[0], (char**) (cmds + 1));
  356. _exit(1);
  357. } else {
  358. checkError(tmp);
  359. }
  360. return NULL;
  361. }
  362. int tsCompare(struct timespec time1, struct timespec time2) {
  363. if (time1.tv_sec < time2.tv_sec) return (-1); /* Less than. */
  364. else if (time1.tv_sec > time2.tv_sec) return (1); /* Greater than. */
  365. else if (time1.tv_nsec < time2.tv_nsec) return (-1); /* Less than. */
  366. else if (time1.tv_nsec > time2.tv_nsec) return (1); /* Greater than. */
  367. else return (0); /* Equal. */
  368. }
  369. #define CONCAT_TO(in,inLen,out,conc) char out[strlen(conc)+inLen+1];\
  370. memcpy(out,in,inLen);\
  371. memcpy(out+inLen,conc,strlen(conc));\
  372. out[strlen(conc)+inLen]=0;
  373. #define TO_C_STR(in,inLen,out) char out[inLen+1];\
  374. memcpy(out,in,inLen);\
  375. out[inLen]=0;
  376. static inline void pageErr_isDir() {
  377. throw ParserException("requested path is a directory or socket");
  378. }
  379. void loadedPage::readCB(int r) {
  380. if (r <= 0) {
  381. compiling = false;
  382. int status = -1;
  383. waitpid(compilerPID, &status, 0);
  384. //keep a copy of the compiled page
  385. if (status == 0) {
  386. unlink(cPath.c_str());
  387. string dll1 = dllPath + ".1";
  388. link(dllPath.c_str(), dll1.c_str());
  389. rename(dll1.c_str(), (path + ".so").c_str());
  390. string txt1 = txtPath + ".1";
  391. link(txtPath.c_str(), txt1.c_str());
  392. rename(txt1.c_str(), (path + ".txt").c_str());
  393. }
  394. afterCompile(status == 0);
  395. compile_fd = nullptr;
  396. //if (compileCB != nullptr) compileCB(*this);
  397. return;
  398. }
  399. ms.bufferPos += r;
  400. ms.flush();
  401. beginRead();
  402. }
  403. void loadedPage::deleteTmpfiles() {
  404. unlink(txtPath.c_str());
  405. unlink(dllPath.c_str());
  406. }
  407. void loadedPage::afterCompile(bool success) {
  408. if (!success) {
  409. rename(cPath.c_str(), (path + ".C").c_str());
  410. deleteTmpfiles();
  411. CompileException exc;
  412. exc.compilerOutput = string((const char*) ms.data(), ms.length());
  413. auto tmpcb = loadCB;
  414. loadCB.clear();
  415. for (int i = 0; i < (int) tmpcb.size(); i++)
  416. tmpcb[i](nullptr, &exc);
  417. return;
  418. }
  419. try {
  420. if (loaded) doUnload();
  421. doLoad();
  422. } catch (exception& ex) {
  423. deleteTmpfiles();
  424. auto tmpcb = loadCB;
  425. loadCB.clear();
  426. for (int i = 0; i < (int) tmpcb.size(); i++)
  427. tmpcb[i](nullptr, &ex);
  428. return;
  429. }
  430. deleteTmpfiles();
  431. auto tmpcb = loadCB;
  432. loadCB.clear();
  433. for (int i = 0; i < (int) tmpcb.size(); i++)
  434. tmpcb[i](this, nullptr);
  435. }
  436. void loadedPage::beginRead() {
  437. if (ms.bufferSize - ms.bufferPos < 4096) ms.flushBuffer(4096);
  438. compile_fd->read(ms.buffer + ms.bufferPos, ms.bufferSize - ms.bufferPos,
  439. CP::Callback(&loadedPage::readCB, this));
  440. }
  441. void loadedPage::doCompile(Poll& p, string wd, const vector<string>& cxxopts) {
  442. string tmp;
  443. char sss[32];
  444. snprintf(sss, 32, "%i", rand());
  445. txtPath = path + "." + string(sss) + ".txt";
  446. dllPath = path + "." + string(sss) + ".dll";
  447. cPath = path + "." + string(sss) + ".C";
  448. //check if a precompiled page exists; if it exists and is newer than
  449. //the .cppsp, then simply hardlink to it
  450. timespec modif_txt, modif_so, modif_cppsp;
  451. struct stat st;
  452. {
  453. TO_C_STR(path.data(), path.length(), s1);
  454. if (stat(s1, &st) < 0) goto do_comp;
  455. modif_cppsp = st.st_mtim;
  456. }
  457. {
  458. CONCAT_TO(path.data(), path.length(), s1, ".txt");
  459. if (stat(s1, &st) < 0) goto do_comp;
  460. modif_txt = st.st_mtim;
  461. }
  462. {
  463. CONCAT_TO(path.data(), path.length(), s1, ".so");
  464. if (stat(s1, &st) < 0) goto do_comp;
  465. modif_so = st.st_mtim;
  466. }
  467. if (tsCompare(modif_cppsp, modif_txt) <= 0 && tsCompare(modif_cppsp, modif_so) <= 0) {
  468. string txt1 = path + ".txt";
  469. string dll1 = path + ".so";
  470. if (link(txt1.c_str(), txtPath.c_str()) < 0) goto do_comp;
  471. if (link(dll1.c_str(), dllPath.c_str()) < 0) goto do_comp;
  472. afterCompile(true);
  473. return;
  474. }
  475. do_comp: deleteTmpfiles();
  476. CP::File* f;
  477. ms.clear();
  478. try {
  479. f = (CP::File*) checkError(
  480. compilePage(wd, path, cPath, txtPath, dllPath, cxxopts, compilerPID, tmp));
  481. } catch (...) {
  482. deleteTmpfiles();
  483. throw;
  484. }
  485. tmp += "\n";
  486. ms.write(tmp.data(), tmp.length());
  487. p.add(*f);
  488. compile_fd = f;
  489. f->release();
  490. beginRead();
  491. compiling = true;
  492. }
  493. void loadedPage::doLoad() {
  494. ScopeLock sl(dlMutex);
  495. //printf("doLoad(\"%s\");\n",path.c_str());
  496. struct stat st;
  497. checkError(stat(txtPath.c_str(), &st));
  498. stringTableLen = st.st_size;
  499. stringTableFD = checkError(open(txtPath.c_str(), O_RDONLY));
  500. stringTable = (const uint8_t*) checkError(
  501. mmap(NULL, stringTableLen, PROT_READ, MAP_SHARED, stringTableFD, 0));
  502. dlHandle = dlopen(dllPath.c_str(), RTLD_LOCAL | RTLD_LAZY);
  503. if (dlHandle == NULL) throw runtime_error(dlerror());
  504. getObjectSize = (getObjectSize_t) checkDLError(dlsym(dlHandle, "getObjectSize"));
  505. createObject = (createObject_t) checkDLError(dlsym(dlHandle, "createObject"));
  506. createObject1 = (createObject1_t) checkDLError(dlsym(dlHandle, "createObject1"));
  507. initModule_t initModule = (initModule_t) dlsym(dlHandle, "initModule");
  508. if (initModule != NULL) {
  509. initModule(srv);
  510. fprintf(stderr, "module %s loaded\n", path.c_str());
  511. }
  512. loaded = true;
  513. clock_gettime(CLOCK_REALTIME, &lastLoad);
  514. //printf("loaded: dlHandle=%p; createObject=%p\n",dlHandle,(void*)createObject);
  515. }
  516. void loadedPage::doUnload() {
  517. //printf("doUnload(\"%s\");\n",path.c_str());
  518. loaded = false;
  519. if (stringTable != NULL) munmap((void*) stringTable, stringTableLen);
  520. if (stringTableFD != -1) close(stringTableFD);
  521. if (dlHandle != NULL) {
  522. deinitModule_t deinitModule = (deinitModule_t) dlsym(dlHandle, "deinitModule");
  523. if (deinitModule != NULL) {
  524. deinitModule();
  525. fprintf(stderr, "module %s unloaded\n", path.c_str());
  526. }
  527. ScopeLock sl(dlMutex);
  528. checkError(dlclose(dlHandle));
  529. //void* tmp=dlopen((path + ".so").c_str(), RTLD_LOCAL | RTLD_LAZY|RTLD_NOLOAD);
  530. //if(tmp!=NULL) throw runtime_error("unable to unload library");
  531. }
  532. dlHandle = NULL;
  533. stringTable = NULL;
  534. stringTableFD = -1;
  535. //printf("unloaded\n");
  536. }
  537. Page* loadedPage::doCreate(RGC::Allocator* a) {
  538. Page* tmp = createObject1(a);
  539. checkError(tmp);
  540. tmp->__stringTable = stringTable;
  541. tmp->filePath = {path.data(),(int)path.length()};
  542. return tmp;
  543. }
  544. loadedPage::loadedPage() :
  545. dlHandle(NULL), stringTable(NULL), stringTableFD(-1) {
  546. //printf("loadedPage()\n");
  547. compiling = false;
  548. doUnload();
  549. }
  550. loadedPage::~loadedPage() {
  551. //printf("~loadedPage()\n");
  552. doUnload();
  553. }
  554. //returns: 0: no-op; 1: should reload; 2: should recompile
  555. int loadedPage::shouldCompile() {
  556. struct stat st;
  557. {
  558. TO_C_STR(path.data(), path.length(), s1);
  559. checkError(stat(s1, &st));
  560. if (S_ISDIR(st.st_mode) || S_ISSOCK(st.st_mode)) pageErr_isDir();
  561. }
  562. if (!loaded) return 2;
  563. timespec modif_cppsp = st.st_mtim;
  564. /*{
  565. CONCAT_TO(path.data(), path.length(), s1, ".txt");
  566. if (stat(s1, &st) < 0) {
  567. if (errno == ENOENT) return 2;
  568. else checkError(-1);
  569. }
  570. }
  571. timespec modif_txt = st.st_mtim;
  572. {
  573. CONCAT_TO(path.data(), path.length(), s1, ".so");
  574. if (stat(s1, &st) < 0) {
  575. if (errno == ENOENT) return 2;
  576. else checkError(-1);
  577. }
  578. }
  579. timespec modif_so = st.st_mtim;*/
  580. int i = 0;
  581. if (tsCompare(lastLoad, modif_cppsp) < 0) i = 2;
  582. //if(tsCompare(lastLoad, modif_txt)< 0 || tsCompare(lastLoad, modif_so) <0) i=1;
  583. //if(tsCompare(modif_cppsp, modif_txt)> 0 || tsCompare(modif_cppsp, modif_so) >0) i=2;
  584. //printf("shouldCompile(\"%s\") = %i\n",path.c_str(),i);
  585. return i;
  586. }
  587. void staticPage::doLoad() {
  588. struct stat st;
  589. checkError(stat(path.c_str(), &st));
  590. data.len = st.st_size;
  591. int fd = checkError(open(path.c_str(), O_RDONLY));
  592. data.d = (char*) checkError(mmap(NULL, data.len, PROT_READ, MAP_SHARED, fd, 0));
  593. close(fd);
  594. loaded = true;
  595. clock_gettime(CLOCK_REALTIME, &lastLoad);
  596. }
  597. void staticPage::doUnload() {
  598. loaded = false;
  599. if (data.d != NULL) munmap((void*) data.d, data.len);
  600. data = nullptr;
  601. }
  602. bool staticPage::shouldReload() {
  603. struct stat st;
  604. {
  605. TO_C_STR(path.data(), path.length(), s1);
  606. checkError(stat(s1, &st));
  607. if (S_ISDIR(st.st_mode) || S_ISSOCK(st.st_mode)) throw ParserException(
  608. "requested path is a directory or socket");
  609. }
  610. if (!loaded) return true;
  611. timespec modif_cppsp = st.st_mtim;
  612. return (tsCompare(lastLoad, modif_cppsp) < 0);
  613. }
  614. staticPage::staticPage() {
  615. loaded = false;
  616. }
  617. staticPage::~staticPage() {
  618. doUnload();
  619. }
  620. inline void loadedPage::_loadCB::operator()(loadedPage* This, exception* ex) {
  621. if (ex == NULL) {
  622. void* p;
  623. try {
  624. p = doCreate ? This->doCreate(alloc) : This->dlHandle;
  625. } catch (exception& x) {
  626. cb(nullptr, &x);
  627. return;
  628. }
  629. cb(p, nullptr);
  630. } else cb(nullptr, ex);
  631. }
  632. static inline void precheckPage(String path) {
  633. struct stat st;
  634. TO_C_STR(path.data(), path.length(), s1);
  635. checkError(stat(s1, &st));
  636. if (S_ISDIR(st.st_mode) || S_ISSOCK(st.st_mode)) pageErr_isDir();
  637. }
  638. cppspManager::cppspManager() :
  639. threadID(0) {
  640. curRFCTime.d = (char*) malloc(32);
  641. curRFCTime.len = 0;
  642. }
  643. cppspManager::~cppspManager() {
  644. free(curRFCTime.d);
  645. }
  646. String cppspManager::loadStaticPage(String path) {
  647. staticPage* lp1;
  648. auto it = staticCache.find(path);
  649. if (it == staticCache.end()) {
  650. precheckPage(path);
  651. lp1 = new staticPage();
  652. lp1->path = path.toSTDString();
  653. staticCache.insert( { sp.addString(path), lp1 });
  654. } else lp1 = (*it).second;
  655. staticPage& lp(*lp1);
  656. if (likely(lp.loaded & !shouldCheck(lp))) {
  657. return lp.data;
  658. }
  659. if (lp.shouldReload()) {
  660. lp.doUnload();
  661. }
  662. if (!lp.loaded) lp.doLoad();
  663. return lp.data;
  664. }
  665. bool cppspManager::shouldCheck(loadedPage& p) {
  666. timespec tmp1 = curTime;
  667. tmp1.tv_sec -= 2;
  668. if (tsCompare(p.lastCheck, tmp1) < 0) {
  669. p.lastCheck = curTime;
  670. return true;
  671. } else return false;
  672. }
  673. bool cppspManager::shouldCheck(staticPage& p) {
  674. timespec tmp1 = curTime;
  675. tmp1.tv_sec -= 2;
  676. if (tsCompare(p.lastCheck, tmp1) < 0) {
  677. p.lastCheck = curTime;
  678. return true;
  679. } else return false;
  680. }
  681. void cppspManager::loadPage(Poll& p, String wd, String path, RGC::Allocator* a,
  682. Delegate<void(Page*, exception* ex)> cb) {
  683. loadedPage* lp1;
  684. auto it = cache.find(path);
  685. if (unlikely(int(it == cache.end()))) {
  686. //check if file exists; if not, don't construct loadedPage object to avoid DoS
  687. try {
  688. precheckPage(path);
  689. } catch (exception& ex) {
  690. cb(nullptr, &ex);
  691. return;
  692. }
  693. lp1 = new loadedPage();
  694. lp1->path = path.toSTDString();
  695. cache.insert( { sp.addString(path), lp1 });
  696. } else lp1 = (*it).second;
  697. loadedPage& lp(*lp1);
  698. int c = 0;
  699. if (unlikely(lp1->compiling)) {
  700. lp.loadCB.push_back( { a, Delegate<void(void*, exception* ex)>(cb), true });
  701. return;
  702. }
  703. if (likely(lp1->loaded & !shouldCheck(*lp1))) {
  704. xxx: Page* p;
  705. try {
  706. p = lp.doCreate(a);
  707. } catch (exception& ex) {
  708. cb(nullptr, &ex);
  709. }
  710. cb(p, nullptr);
  711. return;
  712. }
  713. try {
  714. c = lp.shouldCompile();
  715. if (likely(lp1->loaded && c==0)) goto xxx;
  716. } catch (exception& ex) {
  717. cb(nullptr, &ex);
  718. return;
  719. }
  720. if (c >= 2) {
  721. lp.loadCB.push_back( { a, Delegate<void(void*, exception* ex)>(cb), true });
  722. try {
  723. lp.doCompile(p, wd.toSTDString(), cxxopts);
  724. } catch (exception& ex) {
  725. lp.loadCB.resize(lp.loadCB.size() - 1);
  726. cb(nullptr, &ex);
  727. }
  728. return;
  729. }
  730. try {
  731. if (c >= 1) {
  732. lp.doUnload();
  733. }
  734. lp.doLoad();
  735. goto xxx;
  736. } catch (exception& ex) {
  737. cb(nullptr, &ex);
  738. }
  739. }
  740. void cppspManager::loadModule(Poll& p, Server* srv, String wd, String path,
  741. Delegate<void(void*, exception* ex)> cb) {
  742. loadedPage* lp1;
  743. auto it = cache.find(path);
  744. if (unlikely(int(it == cache.end()))) {
  745. try {
  746. precheckPage(path);
  747. } catch (exception& ex) {
  748. cb(nullptr, &ex);
  749. return;
  750. }
  751. lp1 = new loadedPage();
  752. lp1->srv = srv;
  753. lp1->path = path.toSTDString();
  754. cache.insert( { sp.addString(path), lp1 });
  755. } else lp1 = (*it).second;
  756. loadedPage& lp(*lp1);
  757. int c = 0;
  758. if (unlikely(lp1->compiling)) {
  759. lp.loadCB.push_back( { nullptr, cb, false });
  760. return;
  761. }
  762. if (likely(lp1->loaded & !shouldCheck(*lp1))) {
  763. xxx: cb(lp1->dlHandle, nullptr);
  764. return;
  765. }
  766. try {
  767. c = lp.shouldCompile();
  768. if (likely(lp1->loaded && c==0)) goto xxx;
  769. } catch (exception& ex) {
  770. cb(nullptr, &ex);
  771. return;
  772. }
  773. if (c >= 2) {
  774. lp.loadCB.push_back( { nullptr, cb, false });
  775. try {
  776. lp.doCompile(p, wd.toSTDString(), cxxopts);
  777. } catch (exception& ex) {
  778. lp.loadCB.resize(lp.loadCB.size() - 1);
  779. cb(nullptr, &ex);
  780. }
  781. return;
  782. }
  783. try {
  784. if (c >= 1) {
  785. lp.doUnload();
  786. }
  787. lp.doLoad();
  788. goto xxx;
  789. } catch (exception& ex) {
  790. cb(nullptr, &ex);
  791. }
  792. }
  793. String loadStaticPage(cppspManager* mgr, String path) {
  794. return mgr->loadStaticPage(path);
  795. }
  796. vector<string>& CXXOpts(cppspManager* mgr) {
  797. return mgr->cxxopts;
  798. }
  799. cppspManager* cppspManager_new() {
  800. return new cppspManager();
  801. }
  802. void setThreadID(cppspManager* mgr, int tid) {
  803. mgr->threadID = tid;
  804. }
  805. void loadPage(cppspManager* mgr, CP::Poll& p, String wd, String path, RGC::Allocator* a,
  806. Delegate<void(Page*, exception* ex)> cb) {
  807. return mgr->loadPage(p, wd, path, a, cb);
  808. }
  809. void cppspManager_delete(cppspManager* mgr) {
  810. delete mgr;
  811. }
  812. void updateTime(cppspManager* mgr) {
  813. clock_gettime(CLOCK_MONOTONIC, &mgr->curTime);
  814. clock_gettime(CLOCK_REALTIME, &mgr->curClockTime);
  815. tm time;
  816. gmtime_r(&mgr->curClockTime.tv_sec, &time);
  817. mgr->curRFCTime.len = rfctime(time, mgr->curRFCTime.d);
  818. }
  819. void loadModule(cppspManager* mgr, CP::Poll& p, Server* srv, String wd, String path,
  820. Delegate<void(void*, exception* ex)> cb) {
  821. mgr->loadModule(p, srv, wd, path, cb);
  822. }
  823. void handleError(exception* ex, cppsp::Response& resp, String path) {
  824. resp.clear();
  825. resp.statusCode = 500;
  826. resp.statusName = "Internal server error";
  827. resp.headers["Content-Type"] = "text/html; charset=UTF-8";
  828. //resp.writeHeaders();
  829. string title = "Server error in " + path.toSTDString();
  830. resp.output.writeF("<html><head><title>%s</title>"
  831. "<style></style></head>", title.c_str());
  832. resp.output.writeF("<body><h1 style=\"color: #aa1111\">%s</h1><hr />"
  833. "<h2 style=\"color: #444\">%s</h2>", title.c_str(), ex->what());
  834. cppsp::CompileException* ce = dynamic_cast<cppsp::CompileException*>(ex);
  835. if (ce != NULL) {
  836. resp.output.write("<pre style=\"color: #000; background: #ffc; padding: 8px;\">");
  837. htmlEscape(String(ce->compilerOutput), resp.output);
  838. resp.output.write("</pre>");
  839. }
  840. resp.output.writeF("</body></html>");
  841. }
  842. }