sq_mongoose.cpp 39 KB

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