Web.hx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. /*
  2. * Copyright (C)2005-2019 Haxe Foundation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. */
  22. package neko;
  23. import haxe.ds.List;
  24. /**
  25. This class is used for accessing the local Web server and the current
  26. client request and information.
  27. **/
  28. class Web {
  29. /**
  30. Returns the GET and POST parameters.
  31. **/
  32. public static function getParams() {
  33. var p = _get_params();
  34. var h = new haxe.ds.StringMap<String>();
  35. var k = "";
  36. while (p != null) {
  37. untyped k.__s = p[0];
  38. h.set(k, new String(p[1]));
  39. p = untyped p[2];
  40. }
  41. return h;
  42. }
  43. /**
  44. Returns an Array of Strings built using GET / POST values.
  45. If the URL contains the parameters `[a[]=foo;a[]=hello;a[5]=bar;a[3]=baz]` then
  46. `neko.Web.getParamValues("a")` will return `["foo","hello",null,"baz",null,"bar"]`
  47. **/
  48. public static function getParamValues(param:String):Array<String> {
  49. var reg = new EReg("^" + param + "(\\[|%5B)([0-9]*?)(\\]|%5D)=(.*?)$", "");
  50. var res = new Array<String>();
  51. var explore = function(data:String) {
  52. if (data == null || data.length == 0)
  53. return;
  54. for (part in data.split("&")) {
  55. if (reg.match(part)) {
  56. var idx = reg.matched(2);
  57. var val = StringTools.urlDecode(reg.matched(4));
  58. if (idx == "")
  59. res.push(val);
  60. else
  61. res[Std.parseInt(idx)] = val;
  62. }
  63. }
  64. }
  65. explore(StringTools.replace(getParamsString(), ";", "&"));
  66. explore(getPostData());
  67. if (res.length == 0)
  68. return null;
  69. return res;
  70. }
  71. /**
  72. Returns the local server host name.
  73. **/
  74. public static function getHostName() {
  75. return new String(_get_host_name());
  76. }
  77. /**
  78. Surprisingly returns the client IP address.
  79. **/
  80. public static function getClientIP() {
  81. return new String(_get_client_ip());
  82. }
  83. /**
  84. Returns the original request URL (before any server internal redirections)
  85. **/
  86. public static function getURI() {
  87. return new String(_get_uri());
  88. }
  89. /**
  90. Tell the client to redirect to the given url ("Location" header)
  91. **/
  92. public static function redirect(url:String) {
  93. _cgi_redirect(untyped url.__s);
  94. }
  95. /**
  96. Set an output header value. If some data have been printed, the headers have
  97. already been sent so this will raise an exception.
  98. **/
  99. public static function setHeader(h:String, v:String) {
  100. _cgi_set_header(untyped h.__s, untyped v.__s);
  101. }
  102. /**
  103. Set the HTTP return code. Same remark as setHeader.
  104. **/
  105. public static function setReturnCode(r:Int) {
  106. _set_return_code(r);
  107. }
  108. /**
  109. Retrieve a client header value sent with the request.
  110. **/
  111. public static function getClientHeader(k:String) {
  112. var v = _get_client_header(untyped k.__s);
  113. if (v == null)
  114. return null;
  115. return new String(v);
  116. }
  117. /**
  118. Retrieve all the client headers.
  119. **/
  120. public static function getClientHeaders() {
  121. var v = _get_client_headers();
  122. var a = new List();
  123. while (v != null) {
  124. a.add({header: new String(v[0]), value: new String(v[1])});
  125. v = cast v[2];
  126. }
  127. return a;
  128. }
  129. /**
  130. Returns all the GET parameters String.
  131. **/
  132. public static function getParamsString() {
  133. var p = _get_params_string();
  134. return if (p == null) "" else new String(p);
  135. }
  136. /**
  137. Returns all the POST data. POST Data is always parsed as
  138. being `application/x-www-form-urlencoded` and is stored into
  139. the getParams hashtable. POST Data is maximimized to 256K
  140. unless the content type is `multipart/form-data`. In that
  141. case, you will have to use `getMultipart` or `parseMultipart`
  142. methods.
  143. **/
  144. public static function getPostData() {
  145. var v = _get_post_data();
  146. if (v == null)
  147. return null;
  148. return new String(v);
  149. }
  150. /**
  151. Returns an hashtable of all Cookies sent by the client.
  152. Modifying the hashtable will not modify the cookie, use `setCookie` instead.
  153. **/
  154. public static function getCookies():Map<String, String> {
  155. var p = _get_cookies();
  156. var h = new haxe.ds.StringMap<String>();
  157. var k = "";
  158. while (p != null) {
  159. untyped k.__s = p[0];
  160. h.set(k, new String(p[1]));
  161. p = untyped p[2];
  162. }
  163. return h;
  164. }
  165. /**
  166. Set a Cookie value in the HTTP headers. Same remark as `setHeader`.
  167. **/
  168. public static function setCookie(key:String, value:String, ?expire:Date, ?domain:String, ?path:String, ?secure:Bool, ?httpOnly:Bool) {
  169. var buf = new StringBuf();
  170. buf.add(value);
  171. if (expire != null)
  172. addPair(buf, "expires=", DateTools.format(expire, "%a, %d-%b-%Y %H:%M:%S GMT"));
  173. addPair(buf, "domain=", domain);
  174. addPair(buf, "path=", path);
  175. if (secure)
  176. addPair(buf, "secure", "");
  177. if (httpOnly)
  178. addPair(buf, "HttpOnly", "");
  179. var v = buf.toString();
  180. _set_cookie(untyped key.__s, untyped v.__s);
  181. }
  182. static function addPair(buf:StringBuf, name:String, value:String) {
  183. if (value == null)
  184. return;
  185. buf.add("; ");
  186. buf.add(name);
  187. buf.add(value);
  188. }
  189. /**
  190. Returns an object with the authorization sent by the client (Basic scheme only).
  191. **/
  192. public static function getAuthorization():{user:String, pass:String} {
  193. var h = getClientHeader("Authorization");
  194. var reg = ~/^Basic ([^=]+)=*$/;
  195. if (h != null && reg.match(h)) {
  196. var val = reg.matched(1);
  197. untyped val = new String(_base_decode(val.__s, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".__s));
  198. var a = val.split(":");
  199. if (a.length != 2) {
  200. throw "Unable to decode authorization.";
  201. }
  202. return {user: a[0], pass: a[1]};
  203. }
  204. return null;
  205. }
  206. /**
  207. Get the current script directory in the local filesystem.
  208. **/
  209. public static function getCwd() {
  210. return new String(_get_cwd());
  211. }
  212. /**
  213. Set the main entry point function used to handle requests.
  214. Setting it back to null will disable code caching.
  215. **/
  216. public static function cacheModule(f:Void->Void) {
  217. _set_main(f);
  218. }
  219. /**
  220. Get the multipart parameters as an hashtable. The data
  221. cannot exceed the maximum size specified.
  222. **/
  223. public static function getMultipart(maxSize:Int):Map<String, String> {
  224. var h = new haxe.ds.StringMap();
  225. var buf:haxe.io.BytesBuffer = null;
  226. var curname = null;
  227. parseMultipart(function(p, _) {
  228. if (curname != null)
  229. h.set(curname, neko.Lib.stringReference(buf.getBytes()));
  230. curname = p;
  231. buf = new haxe.io.BytesBuffer();
  232. maxSize -= p.length;
  233. if (maxSize < 0)
  234. throw "Maximum size reached";
  235. }, function(str, pos, len) {
  236. maxSize -= len;
  237. if (maxSize < 0)
  238. throw "Maximum size reached";
  239. buf.addBytes(str, pos, len);
  240. });
  241. if (curname != null)
  242. h.set(curname, neko.Lib.stringReference(buf.getBytes()));
  243. return h;
  244. }
  245. /**
  246. Parse the multipart data. Call `onPart` when a new part is found
  247. with the part name and the filename if present
  248. and `onData` when some part data is read. You can this way
  249. directly save the data on hard drive in the case of a file upload.
  250. **/
  251. public static function parseMultipart(onPart:String->String->Void, onData:haxe.io.Bytes->Int->Int->Void):Void {
  252. _parse_multipart(function(p, f) {
  253. onPart(new String(p), if (f == null) null else new String(f));
  254. }, function(buf, pos, len) {
  255. onData(untyped new haxe.io.Bytes(__dollar__ssize(buf), buf), pos, len);
  256. });
  257. }
  258. /**
  259. Flush the data sent to the client. By default on Apache, outgoing data is buffered so
  260. this can be useful for displaying some long operation progress.
  261. **/
  262. public static function flush():Void {
  263. _flush();
  264. }
  265. /**
  266. Get the HTTP method used by the client. This API requires Neko 1.7.1+.
  267. **/
  268. public static function getMethod():String {
  269. return new String(_get_http_method());
  270. }
  271. /**
  272. Write a message into the web server log file. This API requires Neko 1.7.1+.
  273. **/
  274. public static function logMessage(msg:String) {
  275. _log_message(untyped msg.__s);
  276. }
  277. public static var isModNeko(default, null):Bool;
  278. public static var isTora(default, null):Bool;
  279. static var _set_main:Dynamic;
  280. static var _get_host_name:Dynamic;
  281. static var _get_client_ip:Dynamic;
  282. static var _get_uri:Dynamic;
  283. static var _cgi_redirect:Dynamic;
  284. static var _cgi_set_header:Dynamic;
  285. static var _set_return_code:Dynamic;
  286. static var _get_client_header:Dynamic;
  287. static var _get_params_string:Dynamic;
  288. static var _get_post_data:Dynamic;
  289. static var _get_params:Dynamic;
  290. static var _get_cookies:Dynamic;
  291. static var _set_cookie:Dynamic;
  292. static var _get_cwd:Dynamic;
  293. static var _parse_multipart:Dynamic;
  294. static var _flush:Dynamic;
  295. static var _get_client_headers:Dynamic;
  296. static var _get_http_method:Dynamic;
  297. static var _base_decode = Lib.load("std", "base_decode", 2);
  298. static var _log_message:Dynamic;
  299. static function __init__() {
  300. var get_env = Lib.load("std", "get_env", 1);
  301. var ver = untyped get_env("MOD_NEKO".__s);
  302. untyped isModNeko = (ver != null);
  303. if (isModNeko) {
  304. var lib = "mod_neko" + if (ver == untyped "1".__s) "" else ver;
  305. _set_main = Lib.load(lib, "cgi_set_main", 1);
  306. _get_host_name = Lib.load(lib, "get_host_name", 0);
  307. _get_client_ip = Lib.load(lib, "get_client_ip", 0);
  308. _get_uri = Lib.load(lib, "get_uri", 0);
  309. _cgi_redirect = Lib.load(lib, "redirect", 1);
  310. _cgi_set_header = Lib.load(lib, "set_header", 2);
  311. _set_return_code = Lib.load(lib, "set_return_code", 1);
  312. _get_client_header = Lib.load(lib, "get_client_header", 1);
  313. _get_params_string = Lib.load(lib, "get_params_string", 0);
  314. _get_post_data = Lib.load(lib, "get_post_data", 0);
  315. _get_params = Lib.load(lib, "get_params", 0);
  316. _get_cookies = Lib.load(lib, "get_cookies", 0);
  317. _set_cookie = Lib.load(lib, "set_cookie", 2);
  318. _get_cwd = Lib.load(lib, "cgi_get_cwd", 0);
  319. _get_http_method = Lib.loadLazy(lib, "get_http_method", 0);
  320. _parse_multipart = Lib.loadLazy(lib, "parse_multipart_data", 2);
  321. _flush = Lib.loadLazy(lib, "cgi_flush", 0);
  322. _get_client_headers = Lib.loadLazy(lib, "get_client_headers", 0);
  323. _log_message = Lib.loadLazy(lib, "log_message", 1);
  324. isTora = try Lib.load(lib, "tora_infos", 0) != null catch (e:Dynamic) false;
  325. } else {
  326. var a0 = untyped __dollar__loader.args[0];
  327. if (a0 != null)
  328. a0 = new String(a0);
  329. _set_main = function(f) {};
  330. _get_host_name = function() {
  331. return untyped "localhost".__s;
  332. };
  333. _get_client_ip = function() {
  334. return untyped "127.0.0.1".__s;
  335. };
  336. _get_uri = function() {
  337. return untyped (if (a0 == null) "/" else a0).__s;
  338. };
  339. _cgi_redirect = function(v) {
  340. Lib.print("Location: " + v + "\n");
  341. };
  342. _cgi_set_header = function(h, v) {};
  343. _set_return_code = function(i) {};
  344. _get_client_header = function(h) {
  345. return null;
  346. };
  347. _get_client_headers = function() {
  348. return null;
  349. };
  350. _get_params_string = function() {
  351. return untyped (if (a0 == null) "" else a0).__s;
  352. };
  353. _get_post_data = function() {
  354. return null;
  355. };
  356. _get_params = function() {
  357. var l = null;
  358. if (a0 == null)
  359. return null;
  360. for (p in a0.split(";")) {
  361. var k = p.split("=");
  362. if (k.length == 2)
  363. l = untyped [k[0].__s, k[1].__s, l];
  364. }
  365. return l;
  366. };
  367. _get_cookies = function() {
  368. return null;
  369. }
  370. _set_cookie = function(k, v) {};
  371. _get_cwd = Lib.load("std", "get_cwd", 0);
  372. _get_http_method = function() return untyped "GET".__s;
  373. _parse_multipart = function(a, b) {
  374. throw "Not supported";
  375. };
  376. _flush = function() {};
  377. _log_message = function(s) {};
  378. isTora = false;
  379. }
  380. }
  381. }