Http.hx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. /*
  2. * Copyright (C)2005-2018 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 sys;
  23. import sys.net.Host;
  24. import sys.net.Socket;
  25. class Http extends haxe.http.HttpBase {
  26. public var noShutdown:Bool;
  27. public var cnxTimeout:Float;
  28. public var responseHeaders:Map<String,String>;
  29. var chunk_size:Null<Int>;
  30. var chunk_buf:haxe.io.Bytes;
  31. var file:{ param:String, filename:String, io:haxe.io.Input, size:Int, mimeType:String };
  32. public static var PROXY:{ host:String, port:Int, auth:{ user:String, pass:String } } = null;
  33. public function new(url:String) {
  34. cnxTimeout = 10;
  35. #if php
  36. noShutdown = ! untyped __call__('function_exists', 'stream_socket_shutdown');
  37. #end
  38. super(url);
  39. }
  40. public override function request(?post:Bool) {
  41. var output = new haxe.io.BytesOutput();
  42. var old = onError;
  43. var err = false;
  44. onError = function(e) {
  45. #if neko
  46. responseData = neko.Lib.stringReference(output.getBytes());
  47. #else
  48. responseData = output.getBytes().toString();
  49. #end
  50. err = true;
  51. // Resetting back onError before calling it allows for a second "retry" request to be sent without onError being wrapped twice
  52. onError = old;
  53. onError(e);
  54. }
  55. customRequest(post,output);
  56. if(!err)
  57. #if neko
  58. onData(responseData = neko.Lib.stringReference(output.getBytes()));
  59. #else
  60. onData(responseData = output.getBytes().toString());
  61. #end
  62. }
  63. @:noCompletion
  64. @:deprecated("Use fileTransfer instead")
  65. inline public function fileTransfert(argname:String, filename:String, file:haxe.io.Input, size:Int, mimeType = "application/octet-stream") {
  66. fileTransfer(argname, filename, file, size, mimeType);
  67. }
  68. public function fileTransfer(argname:String, filename:String, file:haxe.io.Input, size:Int, mimeType = "application/octet-stream") {
  69. this.file = { param:argname, filename:filename, io:file, size:size, mimeType:mimeType };
  70. }
  71. public function customRequest(post:Bool, api:haxe.io.Output, ?sock:sys.net.Socket, ?method:String) {
  72. this.responseData = null;
  73. var url_regexp = ~/^(https?:\/\/)?([a-zA-Z\.0-9_-]+)(:[0-9]+)?(.*)$/;
  74. if(!url_regexp.match(url)) {
  75. onError("Invalid URL");
  76. return;
  77. }
  78. var secure = (url_regexp.matched(1) == "https://");
  79. if(sock == null) {
  80. if(secure) {
  81. #if php
  82. sock = new php.net.SslSocket();
  83. #elseif java
  84. sock = new java.net.SslSocket();
  85. #elseif python
  86. sock = new python.net.SslSocket();
  87. #elseif (!no_ssl && (hxssl || hl || cpp || (neko && !(macro || interp))))
  88. sock = new sys.ssl.Socket();
  89. #else
  90. throw "Https is only supported with -lib hxssl";
  91. #end
  92. } else
  93. sock = new Socket();
  94. }
  95. var host = url_regexp.matched(2);
  96. var portString = url_regexp.matched(3);
  97. var request = url_regexp.matched(4);
  98. if(request == "")
  99. request = "/";
  100. var port = if (portString == null || portString == "") secure ? 443:80 else Std.parseInt(portString.substr(1, portString.length - 1));
  101. var multipart = (file != null);
  102. var boundary = null;
  103. var uri = null;
  104. if(multipart) {
  105. post = true;
  106. boundary = Std.string(Std.random(1000))+Std.string(Std.random(1000))+Std.string(Std.random(1000))+Std.string(Std.random(1000));
  107. while(boundary.length < 38)
  108. boundary = "-" + boundary;
  109. var b = new StringBuf();
  110. for(p in params) {
  111. b.add("--");
  112. b.add(boundary);
  113. b.add("\r\n");
  114. b.add('Content-Disposition: form-data; name="');
  115. b.add(p.name);
  116. b.add('"');
  117. b.add("\r\n");
  118. b.add("\r\n");
  119. b.add(p.value);
  120. b.add("\r\n");
  121. }
  122. b.add("--");
  123. b.add(boundary);
  124. b.add("\r\n");
  125. b.add('Content-Disposition: form-data; name="');
  126. b.add(file.param);
  127. b.add('"; filename="');
  128. b.add(file.filename);
  129. b.add('"');
  130. b.add("\r\n");
  131. b.add("Content-Type: "+file.mimeType+"\r\n"+"\r\n");
  132. uri = b.toString();
  133. } else {
  134. for(p in params) {
  135. if(uri == null)
  136. uri = "";
  137. else
  138. uri += "&";
  139. uri += StringTools.urlEncode(p.name)+"="+StringTools.urlEncode(p.value);
  140. }
  141. }
  142. var b = new StringBuf();
  143. if(method != null) {
  144. b.add(method);
  145. b.add(" ");
  146. } else if(post)
  147. b.add("POST ");
  148. else
  149. b.add("GET ");
  150. if(Http.PROXY != null) {
  151. b.add("http://");
  152. b.add(host);
  153. if(port != 80) {
  154. b.add(":");
  155. b.add(port);
  156. }
  157. }
  158. b.add(request);
  159. if(!post && uri != null) {
  160. if(request.indexOf("?",0) >= 0)
  161. b.add("&");
  162. else
  163. b.add("?");
  164. b.add(uri);
  165. }
  166. b.add(" HTTP/1.1\r\nHost: "+host+"\r\n");
  167. if(postData != null)
  168. b.add("Content-Length: "+postData.length+"\r\n");
  169. else if(post && uri != null) {
  170. if(multipart || !Lambda.exists(headers, function(h) return h.name == "Content-Type")) {
  171. b.add("Content-Type: ");
  172. if(multipart) {
  173. b.add("multipart/form-data");
  174. b.add("; boundary=");
  175. b.add(boundary);
  176. } else
  177. b.add("application/x-www-form-urlencoded");
  178. b.add("\r\n");
  179. }
  180. if(multipart)
  181. b.add("Content-Length: "+(uri.length+file.size+boundary.length+6)+"\r\n");
  182. else
  183. b.add("Content-Length: "+uri.length+"\r\n");
  184. }
  185. b.add("Connection: close\r\n");
  186. for(h in headers) {
  187. b.add(h.name);
  188. b.add(": ");
  189. b.add(h.value);
  190. b.add("\r\n");
  191. }
  192. b.add("\r\n");
  193. if(postData != null)
  194. b.add(postData);
  195. else if(post && uri != null)
  196. b.add(uri);
  197. try {
  198. if(Http.PROXY != null)
  199. sock.connect(new Host(Http.PROXY.host),Http.PROXY.port);
  200. else
  201. sock.connect(new Host(host),port);
  202. sock.write(b.toString());
  203. if(multipart) {
  204. var bufsize = 4096;
  205. var buf = haxe.io.Bytes.alloc(bufsize);
  206. while(file.size > 0) {
  207. var size = if(file.size > bufsize) bufsize else file.size;
  208. var len = 0;
  209. try {
  210. len = file.io.readBytes(buf,0,size);
  211. } catch(e:haxe.io.Eof) break;
  212. sock.output.writeFullBytes(buf,0,len);
  213. file.size -= len;
  214. }
  215. sock.write("\r\n");
  216. sock.write("--");
  217. sock.write(boundary);
  218. sock.write("--");
  219. }
  220. readHttpResponse(api,sock);
  221. sock.close();
  222. } catch(e:Dynamic) {
  223. try sock.close() catch(e:Dynamic) { };
  224. onError(Std.string(e));
  225. }
  226. }
  227. function readHttpResponse(api:haxe.io.Output, sock:sys.net.Socket) {
  228. // READ the HTTP header (until \r\n\r\n)
  229. var b = new haxe.io.BytesBuffer();
  230. var k = 4;
  231. var s = haxe.io.Bytes.alloc(4);
  232. sock.setTimeout(cnxTimeout);
  233. while(true) {
  234. var p = sock.input.readBytes(s,0,k);
  235. while(p != k)
  236. p += sock.input.readBytes(s,p,k - p);
  237. b.addBytes(s,0,k);
  238. switch(k) {
  239. case 1:
  240. var c = s.get(0);
  241. if(c == 10)
  242. break;
  243. if(c == 13)
  244. k = 3;
  245. else
  246. k = 4;
  247. case 2:
  248. var c = s.get(1);
  249. if(c == 10) {
  250. if(s.get(0) == 13)
  251. break;
  252. k = 4;
  253. } else if(c == 13)
  254. k = 3;
  255. else
  256. k = 4;
  257. case 3:
  258. var c = s.get(2);
  259. if(c == 10) {
  260. if(s.get(1) != 13)
  261. k = 4;
  262. else if(s.get(0) != 10)
  263. k = 2;
  264. else
  265. break;
  266. } else if(c == 13) {
  267. if(s.get(1) != 10 || s.get(0) != 13)
  268. k = 1;
  269. else
  270. k = 3;
  271. } else
  272. k = 4;
  273. case 4:
  274. var c = s.get(3);
  275. if(c == 10) {
  276. if(s.get(2) != 13)
  277. continue;
  278. else if(s.get(1) != 10 || s.get(0) != 13)
  279. k = 2;
  280. else
  281. break;
  282. } else if(c == 13) {
  283. if(s.get(2) != 10 || s.get(1) != 13)
  284. k = 3;
  285. else
  286. k = 1;
  287. }
  288. }
  289. }
  290. #if neko
  291. var headers = neko.Lib.stringReference(b.getBytes()).split("\r\n");
  292. #else
  293. var headers = b.getBytes().toString().split("\r\n");
  294. #end
  295. var response = headers.shift();
  296. var rp = response.split(" ");
  297. var status = Std.parseInt(rp[1]);
  298. if(status == 0 || status == null)
  299. throw "Response status error";
  300. // remove the two lasts \r\n\r\n
  301. headers.pop();
  302. headers.pop();
  303. responseHeaders = new haxe.ds.StringMap();
  304. var size = null;
  305. var chunked = false;
  306. for(hline in headers) {
  307. var a = hline.split(": ");
  308. var hname = a.shift();
  309. var hval = if(a.length == 1) a[0] else a.join(": ");
  310. hval = StringTools.ltrim(StringTools.rtrim(hval));
  311. responseHeaders.set(hname, hval);
  312. switch(hname.toLowerCase())
  313. {
  314. case "content-length":
  315. size = Std.parseInt(hval);
  316. case "transfer-encoding":
  317. chunked = (hval.toLowerCase() == "chunked");
  318. }
  319. }
  320. onStatus(status);
  321. var chunk_re = ~/^([0-9A-Fa-f]+)[ ]*\r\n/m;
  322. chunk_size = null;
  323. chunk_buf = null;
  324. var bufsize = 1024;
  325. var buf = haxe.io.Bytes.alloc(bufsize);
  326. if(chunked) {
  327. try {
  328. while(true) {
  329. var len = sock.input.readBytes(buf,0,bufsize);
  330. if(!readChunk(chunk_re,api,buf,len))
  331. break;
  332. }
  333. } catch (e:haxe.io.Eof) {
  334. throw "Transfer aborted";
  335. }
  336. } else if(size == null) {
  337. if(!noShutdown)
  338. sock.shutdown(false,true);
  339. try {
  340. while(true) {
  341. var len = sock.input.readBytes(buf,0,bufsize);
  342. api.writeBytes(buf,0,len);
  343. }
  344. } catch(e:haxe.io.Eof) {
  345. }
  346. } else {
  347. api.prepare(size);
  348. try {
  349. while(size > 0) {
  350. var len = sock.input.readBytes(buf,0,if(size > bufsize) bufsize else size);
  351. api.writeBytes(buf,0,len);
  352. size -= len;
  353. }
  354. } catch(e:haxe.io.Eof) {
  355. throw "Transfer aborted";
  356. }
  357. }
  358. if(chunked && (chunk_size != null || chunk_buf != null))
  359. throw "Invalid chunk";
  360. if(status < 200 || status >= 400)
  361. throw "Http Error #"+status;
  362. api.close();
  363. }
  364. function readChunk(chunk_re:EReg, api:haxe.io.Output, buf:haxe.io.Bytes, len) {
  365. if(chunk_size == null) {
  366. if(chunk_buf != null) {
  367. var b = new haxe.io.BytesBuffer();
  368. b.add(chunk_buf);
  369. b.addBytes(buf,0,len);
  370. buf = b.getBytes();
  371. len += chunk_buf.length;
  372. chunk_buf = null;
  373. }
  374. #if neko
  375. if(chunk_re.match(neko.Lib.stringReference(buf))) {
  376. #else
  377. if(chunk_re.match(buf.toString())) {
  378. #end
  379. var p = chunk_re.matchedPos();
  380. if(p.len <= len) {
  381. var cstr = chunk_re.matched(1);
  382. chunk_size = Std.parseInt("0x"+cstr);
  383. if(chunk_size == 0) {
  384. chunk_size = null;
  385. chunk_buf = null;
  386. return false;
  387. }
  388. len -= p.len;
  389. return readChunk(chunk_re,api,buf.sub(p.len,len),len);
  390. }
  391. }
  392. // prevent buffer accumulation
  393. if(len > 10) {
  394. onError("Invalid chunk");
  395. return false;
  396. }
  397. chunk_buf = buf.sub(0,len);
  398. return true;
  399. }
  400. if(chunk_size > len) {
  401. chunk_size -= len;
  402. api.writeBytes(buf,0,len);
  403. return true;
  404. }
  405. var end = chunk_size + 2;
  406. if(len >= end) {
  407. if(chunk_size > 0)
  408. api.writeBytes(buf,0,chunk_size);
  409. len -= end;
  410. chunk_size = null;
  411. if(len == 0)
  412. return true;
  413. return readChunk(chunk_re,api,buf.sub(end,len),len);
  414. }
  415. if(chunk_size > 0)
  416. api.writeBytes(buf,0,chunk_size);
  417. chunk_size -= len;
  418. return true;
  419. }
  420. /**
  421. Makes a synchronous request to `url`.
  422. This creates a new Http instance and makes a GET request by calling its
  423. `request(false)` method.
  424. If `url` is null, the result is unspecified.
  425. **/
  426. public static function requestUrl(url:String):String {
  427. var h = new Http(url);
  428. var r = null;
  429. h.onData = function(d){
  430. r = d;
  431. }
  432. h.onError = function(e){
  433. throw e;
  434. }
  435. h.request(false);
  436. return r;
  437. }
  438. }