Http.hx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. #if php
  104. sock = new php.net.Socket();
  105. #else
  106. sock = new Socket();
  107. #end
  108. }
  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. function writeBody(body:Null<BytesOutput>, fileInput:Null<Input>, fileSize:Int, boundary:Null<String>, sock:Socket) {
  242. if (body != null) {
  243. var bytes = body.getBytes();
  244. sock.output.writeFullBytes(bytes, 0, bytes.length);
  245. }
  246. if (boundary != null) {
  247. var bufsize = 4096;
  248. var buf = haxe.io.Bytes.alloc(bufsize);
  249. while (fileSize > 0) {
  250. var size = if (fileSize > bufsize) bufsize else fileSize;
  251. var len = 0;
  252. try {
  253. len = fileInput.readBytes(buf, 0, size);
  254. } catch (e:haxe.io.Eof)
  255. break;
  256. sock.output.writeFullBytes(buf, 0, len);
  257. fileSize -= len;
  258. }
  259. sock.output.writeString("\r\n");
  260. sock.output.writeString("--");
  261. sock.output.writeString(boundary);
  262. sock.output.writeString("--");
  263. }
  264. }
  265. function readHttpResponse(api:haxe.io.Output, sock:sys.net.Socket) {
  266. // READ the HTTP header (until \r\n\r\n)
  267. var b = new haxe.io.BytesBuffer();
  268. var k = 4;
  269. var s = haxe.io.Bytes.alloc(4);
  270. sock.setTimeout(cnxTimeout);
  271. while (true) {
  272. var p = sock.input.readBytes(s, 0, k);
  273. while (p != k)
  274. p += sock.input.readBytes(s, p, k - p);
  275. b.addBytes(s, 0, k);
  276. switch (k) {
  277. case 1:
  278. var c = s.get(0);
  279. if (c == 10)
  280. break;
  281. if (c == 13)
  282. k = 3;
  283. else
  284. k = 4;
  285. case 2:
  286. var c = s.get(1);
  287. if (c == 10) {
  288. if (s.get(0) == 13)
  289. break;
  290. k = 4;
  291. } else if (c == 13)
  292. k = 3;
  293. else
  294. k = 4;
  295. case 3:
  296. var c = s.get(2);
  297. if (c == 10) {
  298. if (s.get(1) != 13)
  299. k = 4;
  300. else if (s.get(0) != 10)
  301. k = 2;
  302. else
  303. break;
  304. } else if (c == 13) {
  305. if (s.get(1) != 10 || s.get(0) != 13)
  306. k = 1;
  307. else
  308. k = 3;
  309. } else
  310. k = 4;
  311. case 4:
  312. var c = s.get(3);
  313. if (c == 10) {
  314. if (s.get(2) != 13)
  315. continue;
  316. else if (s.get(1) != 10 || s.get(0) != 13)
  317. k = 2;
  318. else
  319. break;
  320. } else if (c == 13) {
  321. if (s.get(2) != 10 || s.get(1) != 13)
  322. k = 3;
  323. else
  324. k = 1;
  325. }
  326. }
  327. }
  328. #if neko
  329. var headers = neko.Lib.stringReference(b.getBytes()).split("\r\n");
  330. #else
  331. var headers = b.getBytes().toString().split("\r\n");
  332. #end
  333. var response = headers.shift();
  334. var rp = response.split(" ");
  335. var status = Std.parseInt(rp[1]);
  336. if (status == 0 || status == null)
  337. throw "Response status error";
  338. // remove the two lasts \r\n\r\n
  339. headers.pop();
  340. headers.pop();
  341. responseHeaders = new haxe.ds.StringMap();
  342. var size = null;
  343. var chunked = false;
  344. for (hline in headers) {
  345. var a = hline.split(": ");
  346. var hname = a.shift();
  347. var hval = if (a.length == 1) a[0] else a.join(": ");
  348. hval = StringTools.ltrim(StringTools.rtrim(hval));
  349. responseHeaders.set(hname, hval);
  350. switch (hname.toLowerCase()) {
  351. case "content-length":
  352. size = Std.parseInt(hval);
  353. case "transfer-encoding":
  354. chunked = (hval.toLowerCase() == "chunked");
  355. }
  356. }
  357. onStatus(status);
  358. var chunk_re = ~/^([0-9A-Fa-f]+)[ ]*\r\n/m;
  359. chunk_size = null;
  360. chunk_buf = null;
  361. var bufsize = 1024;
  362. var buf = haxe.io.Bytes.alloc(bufsize);
  363. if (chunked) {
  364. try {
  365. while (true) {
  366. var len = sock.input.readBytes(buf, 0, bufsize);
  367. if (!readChunk(chunk_re, api, buf, len))
  368. break;
  369. }
  370. } catch (e:haxe.io.Eof) {
  371. throw "Transfer aborted";
  372. }
  373. } else if (size == null) {
  374. if (!noShutdown)
  375. sock.shutdown(false, true);
  376. try {
  377. while (true) {
  378. var len = sock.input.readBytes(buf, 0, bufsize);
  379. if (len == 0)
  380. break;
  381. api.writeBytes(buf, 0, len);
  382. }
  383. } catch (e:haxe.io.Eof) {}
  384. } else {
  385. api.prepare(size);
  386. try {
  387. while (size > 0) {
  388. var len = sock.input.readBytes(buf, 0, if (size > bufsize) bufsize else size);
  389. api.writeBytes(buf, 0, len);
  390. size -= len;
  391. }
  392. } catch (e:haxe.io.Eof) {
  393. throw "Transfer aborted";
  394. }
  395. }
  396. if (chunked && (chunk_size != null || chunk_buf != null))
  397. throw "Invalid chunk";
  398. if (status < 200 || status >= 400)
  399. throw "Http Error #" + status;
  400. api.close();
  401. }
  402. function readChunk(chunk_re:EReg, api:haxe.io.Output, buf:haxe.io.Bytes, len) {
  403. if (chunk_size == null) {
  404. if (chunk_buf != null) {
  405. var b = new haxe.io.BytesBuffer();
  406. b.add(chunk_buf);
  407. b.addBytes(buf, 0, len);
  408. buf = b.getBytes();
  409. len += chunk_buf.length;
  410. chunk_buf = null;
  411. }
  412. #if neko
  413. if (chunk_re.match(neko.Lib.stringReference(buf))) {
  414. #else
  415. if (chunk_re.match(buf.toString())) {
  416. #end
  417. var p = chunk_re.matchedPos();
  418. if (p.len <= len) {
  419. var cstr = chunk_re.matched(1);
  420. chunk_size = Std.parseInt("0x" + cstr);
  421. if (chunk_size == 0) {
  422. chunk_size = null;
  423. chunk_buf = null;
  424. return false;
  425. }
  426. len -= p.len;
  427. return readChunk(chunk_re, api, buf.sub(p.len, len), len);
  428. }
  429. }
  430. // prevent buffer accumulation
  431. if (len > 10) {
  432. onError("Invalid chunk");
  433. return false;
  434. }
  435. chunk_buf = buf.sub(0, len);
  436. return true;
  437. }
  438. if (chunk_size > len) {
  439. chunk_size -= len;
  440. api.writeBytes(buf, 0, len);
  441. return true;
  442. }
  443. var end = chunk_size + 2;
  444. if (len >= end) {
  445. if (chunk_size > 0)
  446. api.writeBytes(buf, 0, chunk_size);
  447. len -= end;
  448. chunk_size = null;
  449. if (len == 0)
  450. return true;
  451. return readChunk(chunk_re, api, buf.sub(end, len), len);
  452. }
  453. if (chunk_size > 0)
  454. api.writeBytes(buf, 0, chunk_size);
  455. chunk_size -= len;
  456. return true;
  457. }
  458. /**
  459. Makes a synchronous request to `url`.
  460. This creates a new Http instance and makes a GET request by calling its
  461. `request(false)` method.
  462. If `url` is null, the result is unspecified.
  463. **/
  464. public static function requestUrl(url:String):String {
  465. var h = new Http(url);
  466. var r = null;
  467. h.onData = function(d) {
  468. r = d;
  469. }
  470. h.onError = function(e) {
  471. throw e;
  472. }
  473. h.request(false);
  474. return r;
  475. }
  476. }