sq_mongoose.cpp 39 KB

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