Web.hx 12 KB

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