Http.hx 13 KB

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