sq_mongoose.cpp 39 KB

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