2
0

Http.hx 14 KB

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