sq_mongoose.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <stdarg.h>
  5. #include <time.h>
  6. #include "squirrel.h"
  7. #include "sqstdblobimpl.h"
  8. SQ_OPT_STRING_STRLEN();
  9. #ifdef USE_SQ_SQLITE3
  10. #include "lsqlite3.h"
  11. #endif
  12. #ifdef USE_AXTLS
  13. #ifdef __cplusplus
  14. extern "C" {
  15. #endif
  16. void * SSL_CTX_new(void *);
  17. #ifdef __cplusplus
  18. }
  19. #endif
  20. #endif
  21. #define USE_MG_MD5 1
  22. #include "mongoose.h"
  23. #define PRINT_FILE_LINE printf("%s %d\n", __FILE__,__LINE__);
  24. #ifdef UNUSED
  25. #elif defined(__GNUC__)
  26. # define UNUSED(x) UNUSED_ ## x __attribute__((unused))
  27. #elif defined(__LCLINT__)
  28. # define UNUSED(x) /*@unused@*/ x
  29. #else
  30. # define UNUSED(x) x
  31. #endif
  32. #define MARK() do { \
  33. printf("%s:%d (%s)\n", __FILE__, __LINE__, __FUNCTION__); \
  34. } while (0)
  35. typedef struct SQ_Mg_Context SQ_Mg_Context;
  36. typedef struct SQ_MG_Callback SQ_MG_Callback;
  37. struct SQ_MG_Callback {
  38. size_t size;
  39. char buf[1];
  40. };
  41. static SQ_MG_Callback *SQ_MG_Callback_malloc(size_t x){
  42. SQ_MG_Callback *p = (SQ_MG_Callback *)sq_malloc(sizeof(SQ_MG_Callback)+x);
  43. if(p) p->size = x;
  44. return p;
  45. }
  46. static void SQ_MG_Callback_free(SQ_MG_Callback *p){
  47. if(p) sq_free(p, sizeof(SQ_MG_Callback)+p->size);
  48. }
  49. struct SQ_Mg_Context {
  50. HSQUIRRELVM v;
  51. struct mg_context *ctx;
  52. SQ_MG_Callback *master_plugin;
  53. SQ_MG_Callback *master_plugin_exit;
  54. SQ_MG_Callback *user_callback;
  55. SQ_MG_Callback *user_callback_setup;
  56. SQ_MG_Callback *user_callback_exit;
  57. };
  58. static const SQChar sq_mg_context_TAG[] = "sq_mg_conn_class";
  59. #define GET_mg_context_INSTANCE() \
  60. SQ_Mg_Context *self; \
  61. if((_rc_ = sq_getinstanceup(v,1,(SQUserPointer*)&self,(void*)sq_mg_context_TAG)) < 0) return _rc_;
  62. static const SQChar sq_mg_user_callback[] = "mg_user_callback";
  63. static const SQChar sq_http_request_TAG[] = "HttpRequest";
  64. #define GET_http_request_INSTANCE() \
  65. struct mg_connection *conn; \
  66. if((_rc_ = sq_getinstanceup(v,1,(SQUserPointer*)&conn,(void*)sq_http_request_TAG)) < 0) return _rc_;
  67. static SQRESULT sq_http_request_releasehook(SQUserPointer p, SQInteger size, HSQUIRRELVM v)
  68. {
  69. return 1;
  70. }
  71. static SQRESULT sq_http_request_constructor(HSQUIRRELVM v)
  72. {
  73. //SQ_FUNC_VARS_NO_TOP(v);
  74. struct mg_connection *conn = 0;
  75. sq_setinstanceup(v, 1, conn);
  76. sq_setreleasehook(v,1, sq_http_request_releasehook);
  77. return 1;
  78. }
  79. static SQRESULT
  80. sq_http_request_print(HSQUIRRELVM v)
  81. {
  82. SQ_FUNC_VARS(v);
  83. GET_http_request_INSTANCE();
  84. SQInteger i, write_count = 0;
  85. for (i = 2; i <= _top_; ++i) {
  86. sq_tostring(v, i);
  87. SQ_GET_STRING(v, -1, value);
  88. write_count += mg_write(conn, value, value_size);
  89. sq_poptop(v);
  90. }
  91. sq_pushinteger(v, write_count);
  92. return 1;
  93. }
  94. #ifdef USE_SQ_LSQLITE3
  95. static SQRESULT
  96. sq_http_request_vm_print(HSQUIRRELVM v)
  97. {
  98. GET_http_request_INSTANCE();
  99. lsqlite3_sdb_vm *svm = (lsqlite3_sdb_vm *)luaL_checkudata(v, 1,
  100. lsqlite3_sqlite_vm_meta);
  101. SQInteger idx = luaL_checkint(v,2);
  102. SQInteger len = sqlite3_column_bytes(svm->vm, idx);
  103. if(len) sq_pushinteger(v, mg_write(conn, sqlite3_column_text(svm->vm, idx), len));
  104. else sq_pushinteger(v, 0);
  105. return 1;
  106. }
  107. #endif
  108. static SQRESULT
  109. sq_http_request_write(HSQUIRRELVM v)
  110. {
  111. SQ_FUNC_VARS(v);
  112. GET_http_request_INSTANCE();
  113. SQ_GET_STRING(v, 2, buf);
  114. SQ_OPT_INTEGER(v, 3, write_size, buf_size);
  115. sq_pushinteger(v, mg_write(conn, buf, write_size));
  116. return 1;
  117. }
  118. static SQRESULT
  119. sq_http_request_read(HSQUIRRELVM v)
  120. {
  121. SQ_FUNC_VARS(v);
  122. GET_http_request_INSTANCE();
  123. SQ_OPT_INTEGER(v, 2, n, 1024*2000);
  124. size_t rlen; /* how much to read */
  125. size_t nr; /* number of chars actually read */
  126. rlen = 8192; /* try to read that much each time */
  127. SQBlob blob(0, rlen);
  128. if (rlen > n) rlen = n; /* cannot read more than asked */
  129. char *p = sq_getscratchpad(v,rlen);
  130. do {
  131. nr = mg_read(conn, p, rlen);
  132. blob.Write(p, nr);
  133. n -= nr; /* still have to read `n' chars */
  134. } while (n > 0 && nr == rlen); /* until end of count or eof */
  135. sq_pushstring(v, (const SQChar *)blob.GetBuf(), blob.Len()); /* close buffer */
  136. return 1;
  137. }
  138. static SQRESULT
  139. sq_http_request_send_file(HSQUIRRELVM v)
  140. {
  141. SQ_FUNC_VARS_NO_TOP(v);
  142. GET_http_request_INSTANCE();
  143. SQ_GET_STRING(v, 2, file_path);
  144. mg_send_file(conn, file_path);
  145. return 0;
  146. }
  147. static SQRESULT
  148. sq_http_request_write_blob(HSQUIRRELVM v)
  149. {
  150. SQ_FUNC_VARS_NO_TOP(v);
  151. GET_http_request_INSTANCE();
  152. SQBlob *blob = NULL;
  153. { if(SQ_FAILED(sq_getinstanceup(v,2,(SQUserPointer*)&blob,(SQUserPointer)SQBlob::SQBlob_TAG)))
  154. return sq_throwerror(v,_SC("invalid type tag")); }
  155. if(!blob || !blob->IsValid())
  156. return sq_throwerror(v,_SC("the blob is invalid"));
  157. sq_pushinteger(v, mg_write(conn, (const SQChar*)blob->GetBuf(), blob->Len()));
  158. return 1;
  159. }
  160. static SQRESULT
  161. sq_http_request_get_header(HSQUIRRELVM v)
  162. {
  163. SQ_FUNC_VARS_NO_TOP(v);
  164. GET_http_request_INSTANCE();
  165. SQ_GET_STRING(v, 2, name);
  166. sq_pushstring(v, mg_get_header(conn, name), -1);
  167. return 1;
  168. }
  169. static SQRESULT
  170. sq_http_request_get_cookie(HSQUIRRELVM v)
  171. {
  172. SQ_FUNC_VARS_NO_TOP(v);
  173. GET_http_request_INSTANCE();
  174. SQ_GET_STRING(v, 2, cookie_name);
  175. const char *start;
  176. int len = mg_find_cookie(conn, cookie_name, &start);
  177. if(len > 0) sq_pushstring(v, start, len);
  178. else sq_pushnull(v);
  179. return 1;
  180. }
  181. static SQRESULT
  182. sq_http_request_get_var(HSQUIRRELVM v)
  183. {
  184. SQ_FUNC_VARS_NO_TOP(v);
  185. GET_http_request_INSTANCE();
  186. SQ_GET_STRING(v, 2, data);
  187. SQ_GET_STRING(v, 3, name);
  188. const char *start;
  189. size_t buffer_len;
  190. int var_len = mg_find_var(data, data_size, name, &start);
  191. if(var_len > 0){
  192. buffer_len = var_len+1;
  193. char *buffer = sq_getscratchpad(v,buffer_len);
  194. if(buffer){
  195. var_len = mg_url_decode(start, var_len, buffer, buffer_len, 1);
  196. sq_pushstring(v, buffer, var_len);
  197. return 1;
  198. }
  199. }
  200. sq_pushnull(v);
  201. return 1;
  202. }
  203. static SQRESULT
  204. sq_http_request_handle_cgi_request(HSQUIRRELVM v)
  205. {
  206. SQ_FUNC_VARS_NO_TOP(v);
  207. GET_http_request_INSTANCE();
  208. SQ_GET_STRING(v, 2, prog);
  209. mg_handle_cgi_request(conn, prog);
  210. return 0;
  211. }
  212. static SQRESULT
  213. sq_http_request_get_option(HSQUIRRELVM v)
  214. {
  215. SQ_FUNC_VARS_NO_TOP(v);
  216. GET_http_request_INSTANCE();
  217. SQ_GET_STRING(v, 2, name);
  218. SQ_Mg_Context *sq_mg_ctx = (SQ_Mg_Context *) mg_get_user_data(conn);
  219. sq_pushstring(v, mg_get_option(sq_mg_ctx->ctx, name), -1);
  220. return 1;
  221. }
  222. //Digest authentication functions
  223. #define MAX_USER_LEN 20
  224. #define MAX_NONCE_LEN 36 //extra bytes for zero terminator
  225. #define MAX_SESSIONS 5
  226. #define SESSION_TTL 3600
  227. #define SESSION_REQUEST_TTL 120
  228. enum e_session_state {e_session_invalid, e_session_sent_request, e_session_authorized};
  229. struct st_session_t
  230. {
  231. int state;
  232. char nonce[MAX_NONCE_LEN];
  233. char user[MAX_USER_LEN]; // Authenticated user
  234. long last_nc;
  235. time_t last_access; // last_access time
  236. long remote_ip; // Client's IP address
  237. };
  238. static struct st_session_t sessions[MAX_SESSIONS]; // Current sessions
  239. // Protects messages, sessions, last_message_id
  240. static mg_thread_mutex_t session_rwlock;
  241. //should be called only after locking session_rwlock
  242. static struct st_session_t *my_get_session_only_after_lock(const char *nonce){
  243. int i;
  244. for(i=0; i < MAX_SESSIONS; ++i){
  245. //printf("%s : %s\n", sessions[i].nonce, ah->nonce);
  246. if(strcmp(sessions[i].nonce, nonce) == 0){
  247. return &sessions[i];
  248. }
  249. }
  250. return 0;
  251. }
  252. // Check the user's password, return 1 if OK
  253. static SQBool my_check_password(const struct mg_request_info *request_info, const char *my_tmp_password)
  254. {
  255. md5_buf_t ha2, expected_response;
  256. struct mg_auth_header *ah = request_info->ah;
  257. // Some of the parameters may be NULL
  258. if (request_info->request_method == NULL ||
  259. //strcmp(ri->request_method, "PUT") == 0 ||
  260. //strcmp(ri->request_method, "DELETE") == 0 ||
  261. ah == NULL ||
  262. ah->nonce == NULL || ah->nc == NULL ||
  263. ah->cnonce == NULL || ah->qop == NULL || ah->uri == NULL ||
  264. ah->response == NULL)
  265. {
  266. return SQFalse;
  267. }
  268. // NOTE(lsm): due to a bug in MSIE, we do not compare the URI
  269. // TODO(lsm): check for authentication timeout
  270. if (// strcmp(ah->uri, conn->request_info.uri) != 0 ||
  271. strlen(ah->response) != 32
  272. )
  273. {
  274. return SQFalse;
  275. }
  276. mg_md5(ha2, request_info->request_method, ":", ah->uri, NULL);
  277. mg_md5(expected_response, my_tmp_password /*ah->ha1*/, ":", ah->nonce, ":", ah->nc,
  278. ":", ah->cnonce, ":", ah->qop, ":", ha2, NULL);
  279. SQBool result = mg_strcasecmp(ah->response, expected_response) == 0;
  280. //printf("%s : %s : %s\n", my_tmp_password, ah->response, expected_response);
  281. if(result) //lets check timeout and other issues
  282. {
  283. struct st_session_t *session_found = 0;
  284. result = SQFalse;
  285. mg_thread_mutex_lock(&session_rwlock);
  286. session_found = my_get_session_only_after_lock(ah->nonce);
  287. if(session_found)
  288. {
  289. do
  290. {
  291. //mobile ip is a pain for security
  292. if( /*(ses.remote_ip != request_info->remote_ip) ||*/
  293. ((time(NULL) - session_found->last_access) > SESSION_TTL)
  294. ) break;
  295. if(session_found->state == e_session_sent_request)
  296. {
  297. session_found->state = e_session_authorized;
  298. snprintf(session_found->user, sizeof(session_found->user), "%s", ah->user);
  299. }
  300. else if(strcmp(session_found->user, ah->user) != 0) break;
  301. long recived_nc = strtol(ah->nc, 0, 16);
  302. time_t received_time = time(NULL);
  303. /*
  304. //printf("%d : %lu : %lu : %lu : %lu\n", request_info->remote_port, ses.last_nc, recived_nc, ses.last_access, received_time);
  305. if((ses.last_nc+1) != recived_nc){
  306. //lets see if we can manage out of order sent by some browsers
  307. if((received_time - ses.last_access) > 2) break;
  308. //inside a window of 2 seconds we tolerate nc out of order
  309. if(ses.last_nc > recived_nc) recived_nc = ses.last_nc;
  310. }
  311. */
  312. session_found->last_access = received_time;
  313. session_found->last_nc = recived_nc;
  314. result = SQTrue;
  315. } while(0);
  316. if(!result){
  317. session_found->state = e_session_invalid;
  318. session_found->nonce[0] = '\0';
  319. }
  320. }
  321. else {
  322. //dbg_msg("Session not found ! : %s : %s\n", ah->nonce, request_info->uri);
  323. }
  324. mg_thread_mutex_unlock(&session_rwlock);
  325. }
  326. return result;
  327. }
  328. static SQRESULT
  329. sq_http_request_check_password(HSQUIRRELVM v)
  330. {
  331. SQ_FUNC_VARS_NO_TOP(v);
  332. GET_http_request_INSTANCE();
  333. SQ_GET_STRING(v, 2, my_tmp_password);
  334. const struct mg_request_info *request_info = mg_get_request_info(conn);
  335. sq_pushbool(v, my_check_password(request_info, my_tmp_password));
  336. return 1;
  337. }
  338. // Close user session return 1 if closed
  339. static SQBool my_close_session(const struct mg_request_info *request_info)
  340. {
  341. SQBool result = SQFalse;
  342. struct st_session_t *session_found = 0;
  343. struct mg_auth_header *ah = request_info->ah;
  344. // Some of the parameters may be NULL
  345. if (request_info->request_method == NULL ||
  346. //strcmp(ri->request_method, "PUT") == 0 ||
  347. //strcmp(ri->request_method, "DELETE") == 0 ||
  348. ah == NULL ||
  349. ah->nonce == NULL || ah->nc == NULL ||
  350. ah->cnonce == NULL || ah->qop == NULL || ah->uri == NULL ||
  351. ah->response == NULL)
  352. {
  353. return 0;
  354. }
  355. mg_thread_mutex_lock(&session_rwlock);
  356. session_found = my_get_session_only_after_lock(ah->nonce);
  357. if(session_found) {
  358. session_found->state = e_session_invalid;
  359. session_found->nonce[0] = '\0';
  360. result = SQTrue;
  361. }
  362. mg_thread_mutex_unlock(&session_rwlock);
  363. return result;
  364. }
  365. static SQRESULT
  366. sq_http_request_close_session(HSQUIRRELVM v)
  367. {
  368. SQ_FUNC_VARS_NO_TOP(v);
  369. GET_http_request_INSTANCE();
  370. const struct mg_request_info *request_info = mg_get_request_info(conn);
  371. sq_pushbool(v, my_close_session(request_info));
  372. return 1;
  373. }
  374. typedef char buf_1024_t[1024];
  375. static const char *my_encode_nonce(buf_1024_t buf, md5_buf_t md5_buf, unsigned long ip)
  376. {
  377. snprintf(buf, sizeof(buf), "%lu:%d:%d:%lu", (unsigned long) time(NULL), rand(), rand(), ip);
  378. mg_md5(md5_buf, buf, NULL);
  379. return md5_buf;
  380. }
  381. static void my_send_authorization_request(struct mg_connection *conn,
  382. const struct mg_request_info *request_info,
  383. const char *authentication_domain,
  384. const char *nonce)
  385. {
  386. md5_buf_t md5_buf;
  387. buf_1024_t buf;
  388. int i;
  389. if (nonce == NULL)
  390. {
  391. nonce = my_encode_nonce(buf, md5_buf, (unsigned long) request_info->remote_ip);
  392. }
  393. struct st_session_t *available_session = NULL;
  394. mg_thread_mutex_lock(&session_rwlock);
  395. for(i=0; i<3; ++i)
  396. {
  397. for(i=0; i < MAX_SESSIONS; ++i){
  398. if(sessions[i].state == e_session_invalid){
  399. available_session = &sessions[i];
  400. }
  401. if(sessions[i].state == e_session_sent_request){
  402. if((time(NULL) - available_session->last_access) > SESSION_REQUEST_TTL){
  403. //if session request bigger than 2 minutes reuse it
  404. available_session = &sessions[i];
  405. }
  406. }
  407. }
  408. if(available_session){
  409. available_session->state = e_session_sent_request;
  410. available_session->last_access = time(NULL);
  411. available_session->last_nc = 0;
  412. available_session->remote_ip = request_info->remote_ip;
  413. snprintf(available_session->nonce, sizeof(available_session->nonce),
  414. "%s", nonce);
  415. break;
  416. }
  417. else
  418. {
  419. nonce = my_encode_nonce(buf, md5_buf, (unsigned long) request_info->remote_ip);
  420. }
  421. }
  422. mg_thread_mutex_unlock(&session_rwlock);
  423. if(available_session) {
  424. i = snprintf(buf, sizeof(buf),
  425. "HTTP/1.1 401 Unauthorized\r\n"
  426. "Content-Length: 0\r\n"
  427. "WWW-Authenticate: Digest qop=\"auth\", "
  428. "realm=\"%s\", nonce=\"%s\"\r\n\r\n",
  429. authentication_domain, nonce);
  430. } else {
  431. i = snprintf(buf, sizeof(buf),
  432. "HTTP/1.1 503 Service Temporary Unavailable\r\n"
  433. "Content-Length: 0\r\n\r\n");
  434. }
  435. mg_write(conn, buf, i);
  436. }
  437. static SQRESULT
  438. sq_http_request_send_authorization_request(HSQUIRRELVM v)
  439. {
  440. SQ_FUNC_VARS_NO_TOP(v);
  441. GET_http_request_INSTANCE();
  442. SQ_GET_STRING(v, 2, authentication_domain);
  443. const struct mg_request_info *request_info = mg_get_request_info(conn);
  444. my_send_authorization_request(conn, request_info, authentication_domain, NULL);
  445. return 0;
  446. }
  447. #define _DECL_FUNC(name,nparams,tycheck) {_SC(#name), sq_http_request_##name,nparams,tycheck}
  448. static SQRegFunction mg_http_request_methods[] =
  449. {
  450. _DECL_FUNC(constructor, 1, _SC("x")),
  451. _DECL_FUNC(print, -2, _SC("x n|s")),
  452. _DECL_FUNC(read, 2, _SC("xi")),
  453. _DECL_FUNC(write, 3, _SC("xsi")),
  454. _DECL_FUNC(write_blob, -2, _SC("xxi")),
  455. _DECL_FUNC(get_var, 3, _SC("xs")),
  456. _DECL_FUNC(get_cookie, 2, _SC("xs")),
  457. _DECL_FUNC(get_header, 2, _SC("xs")),
  458. _DECL_FUNC(send_file, 2, _SC("xs")),
  459. _DECL_FUNC(handle_cgi_request, 2, _SC("xs")),
  460. _DECL_FUNC(get_option, 2, _SC("xs")),
  461. _DECL_FUNC(check_password, 2, _SC("xs")),
  462. _DECL_FUNC(close_session, 1, _SC("x")),
  463. _DECL_FUNC(send_authorization_request, 2, _SC("xs")),
  464. {0,0}
  465. };
  466. #undef _DECL_FUNC
  467. /***********/
  468. // helper function to extract a single mg_config value from a Lua table
  469. static void
  470. fetchfield(HSQUIRRELVM v, int idx, const char *key, char **value, const char *d)
  471. {
  472. const char *s;
  473. sq_pushstring(v, key, -1);
  474. if(sq_rawget(v, idx) == SQ_OK){
  475. if(sq_gettype(v, -1) != OT_NULL){
  476. sq_tostring(v, -1);
  477. sq_getstring(v, -1, &s);
  478. *value = mg_strdup(s);
  479. sq_pop(v, 2); //retrieved value and converted value
  480. return;
  481. }
  482. }
  483. *value = NULL;
  484. }
  485. // initializes an options string array from a Lua table
  486. static SQRESULT
  487. fetchoptions(HSQUIRRELVM v, int idx, const char **options)
  488. {
  489. struct {
  490. const char *key;
  491. const char *value;
  492. } OPTIONS[] = {
  493. { "cgi_extensions", ".cgi,.pl,.php" },
  494. { "cgi_environment", NULL },
  495. { "put_delete_passwords_file", NULL },
  496. { "cgi_interpreter", NULL },
  497. { "protect_uri", NULL },
  498. { "authentication_domain", "mydomain.com" },
  499. { "ssi_extensions", ".shtml,.shtm" },
  500. { "access_log_file", NULL },
  501. { "ssl_chain_file", NULL },
  502. { "enable_directory_listing", "yes" },
  503. { "error_log_file", NULL },
  504. { "global_passwords_file", NULL },
  505. { "index_files", "index.html,index.htm,index.cgi" },
  506. { "enable_keep_alive", "no" },
  507. { "access_control_list", NULL },
  508. { "max_request_size", "16384" },
  509. { "extra_mime_types", NULL },
  510. { "listening_ports", "8080" },
  511. { "document_root", "." },
  512. { "ssl_certificate", NULL },
  513. { "num_threads", "10" },
  514. { "run_as_user", NULL },
  515. { NULL, NULL }
  516. };
  517. char *value;
  518. int i, j;
  519. if(sq_gettype(v, idx) != OT_TABLE) return sq_throwerror(v, "a table is needed to retrieve options");
  520. for (i = 0, j = 0; OPTIONS[i].key; ++i) {
  521. fetchfield(v, idx, OPTIONS[i].key, &value, OPTIONS[i].value);
  522. if (NULL != value) {
  523. options[j++] = mg_strdup(OPTIONS[i].key);
  524. options[j++] = value;
  525. }
  526. }
  527. options[j] = NULL;
  528. return 0;
  529. }
  530. /***********/
  531. static const char sq_mongoose_TAG[] = "Mongoose";
  532. static SQBool show_errors_on_stdout = SQFalse;
  533. static void sq_mongoose_release_references(SQ_Mg_Context *self){
  534. SQ_MG_Callback_free(self->master_plugin);
  535. SQ_MG_Callback_free(self->master_plugin_exit);
  536. SQ_MG_Callback_free(self->user_callback);
  537. SQ_MG_Callback_free(self->user_callback_setup);
  538. SQ_MG_Callback_free(self->user_callback_exit);
  539. }
  540. static SQRESULT sq_mongoose_releasehook(SQUserPointer p, SQInteger size, HSQUIRRELVM v)
  541. {
  542. SQ_Mg_Context *self = (SQ_Mg_Context *)p;
  543. if(self){
  544. if(self->ctx){
  545. mg_stop(self->ctx);
  546. sq_mongoose_release_references(self);
  547. self->ctx = 0;
  548. }
  549. sq_free(self, sizeof(SQ_Mg_Context));
  550. }
  551. return 0;
  552. }
  553. static SQRESULT sq_mongoose_constructor(HSQUIRRELVM v)
  554. {
  555. //SQ_FUNC_VARS_NO_TOP(v);
  556. SQ_Mg_Context *sq_mg_ctx = (SQ_Mg_Context *)sq_malloc(sizeof(SQ_Mg_Context));
  557. memset(sq_mg_ctx, 0, sizeof(SQ_Mg_Context));
  558. sq_setinstanceup(v, 1, sq_mg_ctx);
  559. sq_setreleasehook(v,1, sq_mongoose_releasehook);
  560. return 1;
  561. }
  562. #define GET_mongoose_INSTANCE() \
  563. SQ_Mg_Context *self; \
  564. if((_rc_ = sq_getinstanceup(v,1,(SQUserPointer*)&self,(void*)sq_mongoose_TAG)) < 0) return _rc_;
  565. static SQRESULT
  566. sq_mongoose_show_errors_on_stdout(HSQUIRRELVM v)
  567. {
  568. SQ_FUNC_VARS_NO_TOP(v);
  569. SQ_GET_BOOL(v, 2, onOff);
  570. show_errors_on_stdout = onOff;
  571. return 0;
  572. }
  573. static SQRESULT
  574. sq_mongoose_modify_passwords_file(HSQUIRRELVM v)
  575. {
  576. SQ_FUNC_VARS_NO_TOP(v);
  577. SQ_GET_STRING(v, 2, passwords_file_name);
  578. SQ_GET_STRING(v, 3, domain);
  579. SQ_GET_STRING(v, 4, user);
  580. SQ_GET_STRING(v, 5, password);
  581. sq_pushinteger(v, mg_modify_passwords_file(passwords_file_name,
  582. domain, user, password));
  583. return 1;
  584. }
  585. static SQRESULT
  586. sq_mongoose_version(HSQUIRRELVM v)
  587. {
  588. sq_pushstring(v, mg_version(), -1);
  589. return 1;
  590. }
  591. SQInteger blob_write(SQUserPointer file,SQUserPointer p,SQInteger size);
  592. // creates a reference dispatching callbacks to squirrel functions
  593. static SQRESULT
  594. fetchcallback(HSQUIRRELVM v, const char *key, SQ_MG_Callback **sq_cb)
  595. {
  596. if(!sq_cb) return sq_throwerror(v, "inavlid SQ_MG_Callback parameter value (NULL)");
  597. if(sq_gettype(v, -1) != OT_TABLE) return sq_throwerror(v, "table expected to fetch callbacks");
  598. sq_pushstring(v, key, -1);
  599. sq_rawget(v, -2);
  600. if (sq_gettype(v, -1) == OT_CLOSURE){
  601. SQBlob b(0,8192);
  602. if(SQ_SUCCEEDED(sq_writeclosure(v,blob_write,&b))) {
  603. *sq_cb = SQ_MG_Callback_malloc(b.Len());
  604. if(*sq_cb) memcpy((*sq_cb)->buf, b.GetBuf(), b.Len());
  605. sq_poptop(v);
  606. }
  607. }
  608. else
  609. {
  610. sq_pop(v, 1);
  611. return sq_throwerror(v, "closure expected for callbacks");
  612. }
  613. return SQ_OK;
  614. }
  615. static void *
  616. user_callback_proxy(enum mg_event event,
  617. struct mg_connection *conn,
  618. const struct mg_request_info *ri);
  619. // creates a new server using a configuration table
  620. static SQRESULT
  621. sq_mongoose_start(HSQUIRRELVM v)
  622. {
  623. SQ_FUNC_VARS_NO_TOP(v);
  624. GET_mongoose_INSTANCE();
  625. _rc_ = 1; //assumes succeed
  626. const char *options[64];
  627. SQInteger i;
  628. if(self->ctx) return sq_throwerror(v, _SC("mongoose already running or stoped incorrectly"));
  629. // store the Squirrel vm for use in callback proxies
  630. self->v = v;
  631. // prepare the mg_config structure from the squirrel table argument
  632. memset(options, 0, sizeof (options));
  633. fetchoptions(v, 2, options);
  634. fetchcallback(v, "master_plugin", &self->master_plugin);
  635. fetchcallback(v, "master_plugin_exit", &self->master_plugin_exit);
  636. fetchcallback(v, "user_callback", &self->user_callback);
  637. fetchcallback(v, "user_callback_setup", &self->user_callback_setup);
  638. fetchcallback(v, "user_callback_exit", &self->user_callback_exit);
  639. self->ctx = mg_start(user_callback_proxy, self, options);
  640. // free the options string list memory
  641. for (i = 0; options[i]; ++i)
  642. free((void *) options[i]);
  643. // throw an error if the server did not start
  644. if (self->ctx == NULL) {
  645. sq_mongoose_release_references(self);
  646. _rc_ = sq_throwerror(v, "could not start mongoose");
  647. }
  648. // return the context so it can be stopped later
  649. return _rc_;
  650. }
  651. static SQRESULT
  652. sq_mongoose_stop(HSQUIRRELVM v)
  653. {
  654. SQ_FUNC_VARS_NO_TOP(v);
  655. GET_mongoose_INSTANCE();
  656. if(self->ctx){
  657. mg_stop(self->ctx);
  658. sq_mongoose_release_references(self);
  659. self->ctx = 0;
  660. }
  661. return 0;
  662. }
  663. #define _DECL_FUNC(name,nparams,tycheck) {_SC(#name), sq_mongoose_##name,nparams,tycheck}
  664. static SQRegFunction sq_mongoose_methods[] =
  665. {
  666. _DECL_FUNC(constructor, 1, _SC("x")),
  667. _DECL_FUNC(start, -1, _SC("x")),
  668. _DECL_FUNC(stop, 1, _SC("x")),
  669. _DECL_FUNC(modify_passwords_file, 1, _SC("x")),
  670. _DECL_FUNC(version, 1, _SC("x")),
  671. _DECL_FUNC(show_errors_on_stdout, 2, _SC("xb")),
  672. {0,0}
  673. };
  674. #undef _DECL_FUNC
  675. static SQRESULT
  676. sq_mg_url_decode_base(HSQUIRRELVM v, SQInteger is_form_url_encoded)
  677. {
  678. SQ_FUNC_VARS_NO_TOP(v);
  679. SQ_GET_STRING(v, 2, src);
  680. int dst_len = src_size +1;
  681. char *dst = sq_getscratchpad(v,dst_len);
  682. dst_len = mg_url_decode(src, src_size, dst, dst_len, is_form_url_encoded);
  683. sq_pushstring(v, dst, dst_len);
  684. return 1;
  685. }
  686. static SQRESULT
  687. sq_mg_url_decode(HSQUIRRELVM v)
  688. {
  689. return sq_mg_url_decode_base(v, 1);
  690. }
  691. static SQRESULT
  692. sq_mg_uri_decode(HSQUIRRELVM v)
  693. {
  694. return sq_mg_url_decode_base(v, 0);
  695. }
  696. static SQRESULT
  697. sq_mg_url_encode(HSQUIRRELVM v)
  698. {
  699. SQ_FUNC_VARS_NO_TOP(v);
  700. SQ_GET_STRING(v, 2, src);
  701. char *dst = mg_url_encode(src);
  702. sq_pushstring(v, dst, -1);
  703. free(dst);
  704. return 1;
  705. }
  706. static SQRESULT
  707. sq_mg_md5(HSQUIRRELVM v)
  708. {
  709. SQ_FUNC_VARS(v);
  710. char buf[32 + 1];
  711. unsigned char hash[16];
  712. MD5_CTX ctx;
  713. MD5Init(&ctx);
  714. for (int i = 2; i <= _top_; ++i) {
  715. SQ_GET_STRING(v, i, p);
  716. MD5Update(&ctx, (const unsigned char *) p, p_size);
  717. }
  718. MD5Final(hash, &ctx);
  719. mg_bin2str(buf, hash, sizeof(hash));
  720. sq_pushstring(v, buf, -1);
  721. return 1;
  722. }
  723. static SQRESULT
  724. sq_mg_debug_print(HSQUIRRELVM v)
  725. {
  726. SQ_FUNC_VARS(v);
  727. SQInteger i, write_count = 0;
  728. for (i = 2; i <= _top_; ++i) {
  729. sq_tostring(v, i);
  730. SQ_GET_STRING(v, -1, value);
  731. write_count += fwrite(value, 1, value_size, stderr);
  732. sq_poptop(v);
  733. }
  734. sq_pushinteger(v, write_count);
  735. return 1;
  736. }
  737. #ifdef JNI_ENABLE_LOG
  738. #include <android/log.h>
  739. /*
  740. ** A callback for the android_log() SQIntegererface.
  741. */
  742. static void jniLog(int iErrCode, const char *zMsg){
  743. __android_log_print(ANDROID_LOG_ERROR,"jniLuaServerLog","(%d) %s\n", iErrCode, zMsg);
  744. }
  745. static SQRESULT sq_mg_jniLog(HSQUIRRELVM v)
  746. {
  747. SQ_FUNC_VARS_NO_TOP(v);
  748. SQ_GET_INTEGER(v, 2, code);
  749. SQ_GET_STRING(v, 3, error_message);
  750. jniLog(code, error_message);
  751. return 0;
  752. }
  753. #endif
  754. #define _DECL_FUNC(name,nparams,tycheck) {_SC(#name), sq_mg_##name,nparams,tycheck, SQTrue}
  755. static SQRegFunction sq_mg_methods[] =
  756. {
  757. _DECL_FUNC(url_decode, 2, _SC(".s")),
  758. _DECL_FUNC(uri_decode, 2, _SC(".s")),
  759. _DECL_FUNC(url_encode, 2, _SC(".s")),
  760. _DECL_FUNC(md5, -2, _SC(".s")),
  761. #ifdef JNI_ENABLE_LOG
  762. _DECL_FUNC(jniLog, -2, _SC(".s")),
  763. #endif
  764. _DECL_FUNC(debug_print, -2, _SC(".s")),
  765. {0,0}
  766. };
  767. #undef _DECL_FUNC
  768. static void reg_string(HSQUIRRELVM v, const char *name, const char *val) {
  769. sq_pushstring(v, name, -1);
  770. if(val) sq_pushstring(v, val, -1);
  771. else sq_pushnull(v);
  772. sq_rawset(v, -3);
  773. }
  774. static void reg_integer(HSQUIRRELVM v, const char *name, int val) {
  775. sq_pushstring(v, name, -1);
  776. sq_pushinteger(v, val);
  777. sq_rawset(v, -3);
  778. }
  779. // pushes request info on the Lua stack as a table
  780. static void
  781. push_request(HSQUIRRELVM v, const struct mg_request_info *ri)
  782. {
  783. int i;
  784. sq_pushliteral(v, _SC("info"));
  785. sq_get(v, -2);
  786. #define NEWSLOT_STR(ks) reg_string(v, #ks, ri->ks);
  787. NEWSLOT_STR(request_method);
  788. NEWSLOT_STR(uri);
  789. NEWSLOT_STR(http_version);
  790. NEWSLOT_STR(query_string);
  791. NEWSLOT_STR(remote_user);
  792. NEWSLOT_STR(log_message);
  793. #define NEWSLOT_INT(ks) reg_integer(v, #ks, ri->ks);
  794. NEWSLOT_INT(remote_ip);
  795. NEWSLOT_INT(remote_port);
  796. NEWSLOT_INT(status_code);
  797. NEWSLOT_INT(is_ssl);
  798. #undef NEWSLOT_STR
  799. #undef NEWSLOT_INT
  800. sq_pushliteral(v, "http_headers");
  801. sq_newtable(v);
  802. for (i = 0; i < ri->num_headers; ++i) {
  803. reg_string(v, ri->http_headers[i].name, ri->http_headers[i].value);
  804. }
  805. sq_newslot(v, -3, SQFalse);
  806. sq_poptop(v); //remove data table
  807. }
  808. static SQInteger
  809. sq_mg_pcall_master_plugin(HSQUIRRELVM v)
  810. {
  811. #if 0
  812. SQ_FUNC_VARS_NO_TOP(v);
  813. GET_MG_CONNECION();
  814. SQ_GET_STRING(v, 2, func_name);
  815. const SQChar *error_message = _SC("No master plugin installed !");
  816. HSQUIRRELVM master_plugin = (HSQUIRRELVM) mg_lock_master_plugin(conn);
  817. if(master_plugin){
  818. int master_plugin_saved_top = sq_gettop(master_plugin);
  819. //sq_pushcfunction(master_plugin, traceback); /* push traceback function */
  820. //int error_func = sq_gettop(master_plugin);
  821. sq_pushstring(master_plugin, func_name, func_name_size);
  822. sq_getonroottable(master_plugin);
  823. if(sq_gettype(master_plugin, -1) == OT_CLOSURE){
  824. sq_pushroottable(master_plugin);
  825. int arg_top = sq_gettop (v);
  826. /* Push arguments to dst stack */
  827. int idx = 4;
  828. copy_values_between_vms (master_plugin, v, arg_top-idx, idx);
  829. if (sq_pcall (master_plugin, arg_top-idx+1, SQTrue, SQTrue) == SQ_OK) {
  830. /* run OK? */
  831. int ret_top = sq_gettop (master_plugin);
  832. /* Push status = OK */
  833. sq_pushbool (v, SQTrue);
  834. /* Return values to src */
  835. //copy_values_between_vms (v, master_plugin, master_plugin_saved_top+2, ret_top);
  836. /* pops debug.traceback and result from dst state */
  837. //sq_settop(master_plugin, master_plugin_saved_top);
  838. /*unlock master plugin*/
  839. mg_unlock_master_plugin(conn);
  840. /* Return true (success) plus return values */
  841. return 1;
  842. }
  843. error_message = sq_tostring (master_plugin, -1);
  844. } else error_message = "Attempt to call an invalid function on master plugin !";
  845. /* pops debug.traceback and result from dst state */
  846. sq_settop(master_plugin, master_plugin_saved_top);
  847. /*unlock master plugin*/
  848. mg_unlock_master_plugin(conn);
  849. }
  850. return sq_throwerror(v, error_message);
  851. #endif
  852. }
  853. static void write_error_message(struct mg_connection *conn,
  854. const char * error_msg, SQInteger error_len){
  855. #define PRE_TAG_OPEN "<pre>"
  856. #define PRE_TAG_CLOSE "</pre>"
  857. mg_write(conn, PRE_TAG_OPEN, sizeof(PRE_TAG_OPEN));
  858. if(error_len < 0) error_len = strlen(error_msg);
  859. mg_write(conn, error_msg, error_len);
  860. mg_write(conn, PRE_TAG_CLOSE, sizeof(PRE_TAG_CLOSE));
  861. }
  862. #ifdef __cplusplus
  863. extern "C" {
  864. #endif
  865. SQUIRREL_API SQRESULT sqext_register_SQLite3(HSQUIRRELVM v);
  866. SQUIRREL_API SQRESULT sqext_register_base64(HSQUIRRELVM v);
  867. SQUIRREL_API SQRESULT sqext_register_mix(HSQUIRRELVM v);
  868. SQUIRREL_API SQRESULT sqstd_register_bloblib(HSQUIRRELVM v);
  869. SQUIRREL_API SQRESULT sqstd_register_iolib(HSQUIRRELVM v);
  870. SQUIRREL_API SQInteger sqstd_register_systemlib(HSQUIRRELVM v);
  871. SQUIRREL_API SQRESULT sqstd_register_mathlib(HSQUIRRELVM v);
  872. SQUIRREL_API SQRESULT sqstd_register_stringlib(HSQUIRRELVM v);
  873. SQUIRREL_API SQRESULT sqext_register_Sq_Fpdf(HSQUIRRELVM v);
  874. SQUIRREL_API SQRESULT sqext_register_sqfs(HSQUIRRELVM v);
  875. SQUIRREL_API void sqstd_seterrorhandlers(HSQUIRRELVM v);
  876. SQUIRREL_API void sqstd_printcallstack(HSQUIRRELVM v);
  877. SQUIRREL_API SQRESULT sqext_register_sq_socket(HSQUIRRELVM v);
  878. #ifdef __cplusplus
  879. } /*extern "C"*/
  880. #endif
  881. void sq_printfunc(HSQUIRRELVM v,const SQChar *s,...)
  882. {
  883. va_list vl;
  884. va_start(vl, s);
  885. vfprintf(stdout, s, vl);
  886. va_end(vl);
  887. }
  888. void sq_errorfunc(HSQUIRRELVM v,const SQChar *s,...)
  889. {
  890. va_list vl;
  891. va_start(vl, s);
  892. vfprintf(stderr, s, vl);
  893. va_end(vl);
  894. }
  895. #define INT_CONST(v,num) sq_pushstring(v,_SC(#num),-1);sq_pushinteger(v,num);sq_newslot(v,-3,SQTrue);
  896. static HSQUIRRELVM my_new_squirrel(struct mg_context *ctx) {
  897. HSQUIRRELVM v = sq_open(1024);
  898. if(!v) return 0;
  899. sqstd_seterrorhandlers(v); //registers the default error handlers
  900. sq_setprintfunc(v, sq_printfunc, sq_errorfunc); //sets the print function
  901. sq_pushroottable(v);
  902. sqstd_register_bloblib(v);
  903. sqstd_register_iolib(v);
  904. sqstd_register_systemlib(v);
  905. sqstd_register_mathlib(v);
  906. sqstd_register_stringlib(v);
  907. sqext_register_base64(v);
  908. sqext_register_Sq_Fpdf(v);
  909. sqext_register_SQLite3(v);
  910. sqext_register_sqfs(v);
  911. sqext_register_mix(v);
  912. sqext_register_sq_socket(v);
  913. sq_pushstring(v,sq_http_request_TAG, -1);
  914. sq_newclass(v,SQFalse);
  915. sq_settypetag(v,-1,(void*)sq_http_request_TAG);
  916. sq_insert_reg_funcs(v, mg_http_request_methods);
  917. sq_pushstring(v, _SC("info"), -1);
  918. sq_newtable(v);
  919. sq_newslot(v,-3,SQFalse);
  920. sq_newslot(v,-3,SQFalse);
  921. sq_insert_reg_funcs(v, sq_mg_methods);
  922. sq_pushliteral(v, "APP_ROOT_FOLDER");
  923. sq_pushstring(v, mg_get_option(ctx, "document_root"), -1);
  924. sq_newslot(v, -3, SQFalse);
  925. sq_poptop(v); //remove roottable
  926. return v;
  927. }
  928. SQInteger blob_read(SQUserPointer file,SQUserPointer p,SQInteger size);
  929. SQInteger loadstring(HSQUIRRELVM v, const char * bcode, SQInteger bcode_size)
  930. {
  931. SQBlob b(0, bcode_size);
  932. b.Write(bcode, bcode_size);
  933. b.Seek(0, SQ_SEEK_SET);
  934. SQInteger rc = sq_readclosure(v, blob_read, &b);
  935. return rc < 0 ? rc : 1;
  936. }
  937. // dispatches a callback to a Lua function if one is registered
  938. static void *
  939. user_callback_proxy(enum mg_event event,
  940. struct mg_connection *conn,
  941. const struct mg_request_info *ri)
  942. {
  943. HSQUIRRELVM v;
  944. int e;
  945. switch(event){
  946. case MG_NEW_MASTER_PLUGIN: {
  947. SQ_Mg_Context *sq_mg_ctx = (SQ_Mg_Context *) conn;
  948. SQ_MG_Callback *cb = sq_mg_ctx->master_plugin;
  949. v = my_new_squirrel((struct mg_context *)ri);
  950. if(!v) return 0;
  951. if(cb){
  952. if (loadstring(v, cb->buf, cb->size) == 1) {
  953. sq_pushroottable(v);
  954. if(sq_call(v, 1, SQFalse, SQTrue) != SQ_OK){
  955. sq_errorfunc(v, "sq_call failed %d\n%s", __LINE__, sq_getlasterror_str(v));
  956. }
  957. sq_poptop(v); //remove function from stack
  958. }
  959. }
  960. return v;
  961. }
  962. break;
  963. case MG_FREE_MASTER_PLUGIN:
  964. v = (HSQUIRRELVM)conn;
  965. if(v) {
  966. SQ_Mg_Context *sq_mg_ctx = (SQ_Mg_Context *) ri;
  967. SQ_MG_Callback *cb = sq_mg_ctx->master_plugin_exit;
  968. if(cb){
  969. if (loadstring(v, cb->buf, cb->size) == 1) {
  970. sq_pushroottable(v);
  971. if(sq_call(v, 1, SQFalse, SQFalse) != SQ_OK){
  972. sq_errorfunc(v, "sq_call failed %d\n%s", __LINE__, sq_getlasterror_str(v));
  973. }
  974. sq_poptop(v); //remove function from stack
  975. }
  976. else sq_errorfunc(v, "sq_call failed %d\n%s", __LINE__, sq_getlasterror_str(v));
  977. }
  978. sq_close(v);
  979. }
  980. return 0;
  981. break;
  982. case MG_NEW_PLUGIN:{
  983. SQ_Mg_Context *sq_mg_ctx = (SQ_Mg_Context *) mg_get_user_data(conn);
  984. if(!sq_mg_ctx) return 0;
  985. SQ_MG_Callback *cb = sq_mg_ctx->user_callback;
  986. if (cb) {
  987. v = my_new_squirrel((struct mg_context *)ri);
  988. if(!v) return 0;
  989. SQInteger top = sq_gettop(v);
  990. SQ_MG_Callback *cb_setup = sq_mg_ctx->user_callback_setup;
  991. if(cb_setup){
  992. if (loadstring(v, cb_setup->buf, cb_setup->size) == 1) {
  993. sq_pushroottable(v);
  994. if(sq_call(v, 1, SQFalse, SQFalse) != SQ_OK){
  995. sq_errorfunc(v, "sq_call failed %d\n%s", __LINE__, sq_getlasterror_str(v));
  996. }
  997. sq_poptop(v); //remove function from stack
  998. }
  999. else sq_errorfunc(v, "sq_call failed %d\n%s", __LINE__, sq_getlasterror_str(v));
  1000. }
  1001. sq_pushroottable(v);
  1002. sq_pushstring(v, sq_mg_user_callback, -1);
  1003. if (loadstring(v, cb->buf, cb->size) == 1) {
  1004. sq_newslot(v, -3, SQFalse);
  1005. }
  1006. else sq_errorfunc(v, "sq_call failed %d\n%s", __LINE__, sq_getlasterror_str(v));
  1007. sq_settop(v, top); //remove everithing left on stack while working here
  1008. return v;
  1009. }
  1010. }
  1011. return 0;
  1012. case MG_FREE_PLUGIN:
  1013. v = (HSQUIRRELVM)mg_get_plugin(conn);
  1014. if(v){
  1015. SQ_Mg_Context *sq_mg_ctx = (SQ_Mg_Context *) ri;
  1016. if(sq_mg_ctx){
  1017. SQ_MG_Callback *cb = sq_mg_ctx->user_callback_exit;
  1018. if(cb){
  1019. if (loadstring(v, cb->buf, cb->size) == 1) {
  1020. sq_pushroottable(v);
  1021. if(sq_call(v, 1, SQFalse, SQFalse) != SQ_OK){
  1022. sq_errorfunc(v, "sq_call failed %d\n%s", __LINE__, sq_getlasterror_str(v));
  1023. }
  1024. sq_poptop(v); //remove function from stack
  1025. }
  1026. else sq_errorfunc(v, "sq_call failed %d\n%s", __LINE__, sq_getlasterror_str(v));
  1027. }
  1028. }
  1029. sq_close(v);
  1030. }
  1031. return NULL;
  1032. case MG_INIT_SSL:
  1033. #ifdef USE_AXTLS
  1034. //lua_pushstring(L, "MG_INIT_SSL");
  1035. *((void**)conn) = SSL_CTX_new(0);
  1036. return 0;
  1037. #endif
  1038. case MG_NEW_REQUEST:
  1039. case MG_HTTP_ERROR:
  1040. case MG_EVENT_LOG:{
  1041. v = (HSQUIRRELVM) mg_get_plugin(conn);
  1042. if (v) {
  1043. SQInteger saved_top = sq_gettop(v);
  1044. //SQ_Mg_Context *sq_mg_ctx = (SQ_Mg_Context *) mg_get_user_data(conn);
  1045. sq_pushstring(v, sq_mg_user_callback, -1);
  1046. if(sq_getonroottable(v) != SQ_OK) {
  1047. write_error_message(conn, "failed to find mg_user_callback", -1);
  1048. return NULL;
  1049. }
  1050. sq_pushroottable(v);
  1051. #define CASE(n) case n: sq_pushstring(v, #n, -1);break
  1052. switch(event){
  1053. CASE(MG_INIT_SSL);
  1054. CASE(MG_HTTP_ERROR);
  1055. CASE(MG_EVENT_LOG);
  1056. CASE(MG_NEW_REQUEST);
  1057. default:
  1058. sq_pushnull(v);
  1059. }
  1060. sq_pushstring(v, sq_http_request_TAG, -1);
  1061. if(sq_getonroottable(v) == SQ_OK){
  1062. sq_pushroottable(v);
  1063. if(sq_call(v, 1, SQTrue, SQFalse) == SQ_OK){
  1064. sq_remove(v, -2); //remove class
  1065. sq_setinstanceup(v, -1, conn);
  1066. }
  1067. }
  1068. push_request(v, ri);
  1069. if(sq_call(v, 3, SQTrue, SQTrue) != SQ_OK) {
  1070. write_error_message(conn, sq_getlasterror_str(v), -1);
  1071. e = 0;
  1072. } else {
  1073. SQBool bval;
  1074. if(sq_getbool(v, -1, &bval) == SQ_OK) e = bval == SQTrue ? 1 : 0;
  1075. else e = 0;
  1076. }
  1077. sq_settop(v, saved_top);
  1078. return (void *) e;
  1079. }
  1080. }
  1081. default:
  1082. return NULL;
  1083. }
  1084. return NULL;
  1085. }
  1086. #ifdef __cplusplus
  1087. extern "C" {
  1088. #endif
  1089. SQRESULT sqext_register_mongoose(HSQUIRRELVM v)
  1090. {
  1091. sq_insert_reg_funcs(v, sq_mg_methods);
  1092. sq_pushstring(v,sq_mongoose_TAG, -1);
  1093. sq_newclass(v,SQFalse);
  1094. sq_settypetag(v,-1,(void*)sq_mongoose_TAG);
  1095. sq_insert_reg_funcs(v, sq_mongoose_methods);
  1096. sq_newslot(v,-3,SQTrue);
  1097. return 1;
  1098. }
  1099. #ifdef __cplusplus
  1100. }
  1101. #endif