sq_mongoose.cpp 41 KB

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