Web.hx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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 ) addPair(buf, "expires=", DateTools.format(expire, "%a, %d-%b-%Y %H:%M:%S GMT"));
  172. addPair(buf, "domain=", domain);
  173. addPair(buf, "path=", path);
  174. if( secure ) addPair(buf, "secure", "");
  175. if( httpOnly ) addPair(buf, "HttpOnly", "");
  176. var v = buf.toString();
  177. _set_cookie(untyped key.__s, untyped v.__s);
  178. }
  179. static function addPair( buf : StringBuf, name:String, value:String ) {
  180. if( value == null ) return;
  181. buf.add("; ");
  182. buf.add(name);
  183. buf.add(value);
  184. }
  185. /**
  186. Returns an object with the authorization sent by the client (Basic scheme only).
  187. **/
  188. public static function getAuthorization() : { user : String, pass : String } {
  189. var h = getClientHeader("Authorization");
  190. var reg = ~/^Basic ([^=]+)=*$/;
  191. if( h != null && reg.match(h) ){
  192. var val = reg.matched(1);
  193. untyped val = new String(_base_decode(val.__s,"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".__s));
  194. var a = val.split(":");
  195. if( a.length != 2 ){
  196. throw "Unable to decode authorization.";
  197. }
  198. return {user: a[0],pass: a[1]};
  199. }
  200. return null;
  201. }
  202. /**
  203. Get the current script directory in the local filesystem.
  204. **/
  205. public static function getCwd() {
  206. return new String(_get_cwd());
  207. }
  208. /**
  209. Set the main entry point function used to handle requests.
  210. Setting it back to null will disable code caching.
  211. **/
  212. public static function cacheModule( f : Void -> Void ) {
  213. _set_main(f);
  214. }
  215. /**
  216. Get the multipart parameters as an hashtable. The data
  217. cannot exceed the maximum size specified.
  218. **/
  219. public static function getMultipart( maxSize : Int ) : Map<String,String> {
  220. var h = new haxe.ds.StringMap();
  221. var buf : haxe.io.BytesBuffer = null;
  222. var curname = null;
  223. parseMultipart(function(p,_) {
  224. if( curname != null )
  225. h.set(curname,neko.Lib.stringReference(buf.getBytes()));
  226. curname = p;
  227. buf = new haxe.io.BytesBuffer();
  228. maxSize -= p.length;
  229. if( maxSize < 0 )
  230. throw "Maximum size reached";
  231. },function(str,pos,len) {
  232. maxSize -= len;
  233. if( maxSize < 0 )
  234. throw "Maximum size reached";
  235. buf.addBytes(str,pos,len);
  236. });
  237. if( curname != null )
  238. h.set(curname,neko.Lib.stringReference(buf.getBytes()));
  239. return h;
  240. }
  241. /**
  242. Parse the multipart data. Call `onPart` when a new part is found
  243. with the part name and the filename if present
  244. and `onData` when some part data is read. You can this way
  245. directly save the data on hard drive in the case of a file upload.
  246. **/
  247. public static function parseMultipart( onPart : String -> String -> Void, onData : haxe.io.Bytes -> Int -> Int -> Void ) : Void {
  248. _parse_multipart(
  249. function(p,f) { onPart(new String(p),if( f == null ) null else new String(f)); },
  250. function(buf,pos,len) { onData(untyped new haxe.io.Bytes(__dollar__ssize(buf),buf),pos,len); }
  251. );
  252. }
  253. /**
  254. Flush the data sent to the client. By default on Apache, outgoing data is buffered so
  255. this can be useful for displaying some long operation progress.
  256. **/
  257. public static function flush() : Void {
  258. _flush();
  259. }
  260. /**
  261. Get the HTTP method used by the client. This API requires Neko 1.7.1+.
  262. **/
  263. public static function getMethod() : String {
  264. return new String(_get_http_method());
  265. }
  266. /**
  267. Write a message into the web server log file. This API requires Neko 1.7.1+.
  268. **/
  269. public static function logMessage( msg : String ) {
  270. _log_message(untyped msg.__s);
  271. }
  272. public static var isModNeko(default,null) : Bool;
  273. public static var isTora(default,null) : Bool;
  274. static var _set_main : Dynamic;
  275. static var _get_host_name : Dynamic;
  276. static var _get_client_ip : Dynamic;
  277. static var _get_uri : Dynamic;
  278. static var _cgi_redirect : Dynamic;
  279. static var _cgi_set_header : Dynamic;
  280. static var _set_return_code : Dynamic;
  281. static var _get_client_header : Dynamic;
  282. static var _get_params_string : Dynamic;
  283. static var _get_post_data : Dynamic;
  284. static var _get_params : Dynamic;
  285. static var _get_cookies : Dynamic;
  286. static var _set_cookie : Dynamic;
  287. static var _get_cwd : Dynamic;
  288. static var _parse_multipart : Dynamic;
  289. static var _flush : Dynamic;
  290. static var _get_client_headers : Dynamic;
  291. static var _get_http_method : Dynamic;
  292. static var _base_decode = Lib.load("std","base_decode",2);
  293. static var _log_message : Dynamic;
  294. static function __init__() {
  295. var get_env = Lib.load("std","get_env",1);
  296. var ver = untyped get_env("MOD_NEKO".__s);
  297. untyped isModNeko = (ver != null);
  298. if( isModNeko ) {
  299. var lib = "mod_neko"+if( ver == untyped "1".__s ) "" else ver;
  300. _set_main = Lib.load(lib,"cgi_set_main",1);
  301. _get_host_name = Lib.load(lib,"get_host_name",0);
  302. _get_client_ip = Lib.load(lib,"get_client_ip",0);
  303. _get_uri = Lib.load(lib,"get_uri",0);
  304. _cgi_redirect = Lib.load(lib,"redirect",1);
  305. _cgi_set_header = Lib.load(lib,"set_header",2);
  306. _set_return_code = Lib.load(lib,"set_return_code",1);
  307. _get_client_header = Lib.load(lib,"get_client_header",1);
  308. _get_params_string = Lib.load(lib,"get_params_string",0);
  309. _get_post_data = Lib.load(lib,"get_post_data",0);
  310. _get_params = Lib.load(lib,"get_params",0);
  311. _get_cookies = Lib.load(lib,"get_cookies",0);
  312. _set_cookie = Lib.load(lib,"set_cookie",2);
  313. _get_cwd = Lib.load(lib,"cgi_get_cwd",0);
  314. _get_http_method = Lib.loadLazy(lib,"get_http_method",0);
  315. _parse_multipart = Lib.loadLazy(lib,"parse_multipart_data",2);
  316. _flush = Lib.loadLazy(lib,"cgi_flush",0);
  317. _get_client_headers = Lib.loadLazy(lib,"get_client_headers",0);
  318. _log_message = Lib.loadLazy(lib,"log_message",1);
  319. isTora = try Lib.load(lib,"tora_infos",0) != null catch( e : Dynamic) false;
  320. } else {
  321. var a0 = untyped __dollar__loader.args[0];
  322. if( a0 != null ) a0 = new String(a0);
  323. _set_main = function(f) { };
  324. _get_host_name = function() { return untyped "localhost".__s; };
  325. _get_client_ip = function() { return untyped "127.0.0.1".__s; };
  326. _get_uri = function() {
  327. return untyped (if( a0 == null ) "/" else a0).__s;
  328. };
  329. _cgi_redirect = function(v) { Lib.print("Location: "+v+"\n"); };
  330. _cgi_set_header = function(h,v) { };
  331. _set_return_code = function(i) { };
  332. _get_client_header = function(h) { return null; };
  333. _get_client_headers = function() { return null; };
  334. _get_params_string = function() {
  335. return untyped (if( a0 == null ) "" else a0).__s;
  336. };
  337. _get_post_data = function() { return null; };
  338. _get_params = function() {
  339. var l = null;
  340. if( a0 == null )
  341. return null;
  342. for( p in a0.split(";") ) {
  343. var k = p.split("=");
  344. if( k.length == 2 )
  345. l = untyped [k[0].__s,k[1].__s,l];
  346. }
  347. return l;
  348. };
  349. _get_cookies = function() { return null; }
  350. _set_cookie = function(k,v) { };
  351. _get_cwd = Lib.load("std","get_cwd",0);
  352. _get_http_method = function() return untyped "GET".__s;
  353. _parse_multipart = function(a,b) { throw "Not supported"; };
  354. _flush = function() { };
  355. _log_message = function(s) { };
  356. isTora = false;
  357. }
  358. }
  359. }