Http.hx 14 KB

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