Http.hx 13 KB

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