SdkStreamHandler.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. <?php
  2. /**
  3. * Copyright (c) 2011-2018 Michael Dowling, https://github.com/mtdowling <mtdowling@gmail.com>
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. * The above copyright notice and this permission notice shall be included in
  11. * all copies or substantial portions of the Software.
  12. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. * THE SOFTWARE.
  19. */
  20. namespace Obs\Internal\Common;
  21. use GuzzleHttp\Exception\RequestException;
  22. use GuzzleHttp\Exception\ConnectException;
  23. use GuzzleHttp\Promise\FulfilledPromise;
  24. use GuzzleHttp\Promise\PromiseInterface;
  25. use GuzzleHttp\Psr7;
  26. use GuzzleHttp\TransferStats;
  27. use Psr\Http\Message\RequestInterface;
  28. use Psr\Http\Message\ResponseInterface;
  29. use Psr\Http\Message\StreamInterface;
  30. class SdkStreamHandler
  31. {
  32. private $lastHeaders = [];
  33. public function __invoke(RequestInterface $request, array $options)
  34. {
  35. if (isset($options['delay'])) {
  36. usleep($options['delay'] * 1000);
  37. }
  38. $startTime = isset($options['on_stats']) ? microtime(true) : null;
  39. try {
  40. $request = $request->withoutHeader('Expect');
  41. if (0 === $request->getBody()->getSize()) {
  42. $request = $request->withHeader('Content-Length', 0);
  43. }
  44. return $this->createResponse(
  45. $request,
  46. $options,
  47. $this->createStream($request, $options),
  48. $startTime
  49. );
  50. } catch (\InvalidArgumentException $e) {
  51. throw $e;
  52. } catch (\Exception $e) {
  53. $message = $e->getMessage();
  54. if (strpos($message, 'getaddrinfo')
  55. || strpos($message, 'Connection refused')
  56. || strpos($message, "couldn't connect to host")
  57. ) {
  58. $e = new ConnectException($e->getMessage(), $request, $e);
  59. }
  60. $e = RequestException::wrapException($request, $e);
  61. $this->invokeStats($options, $request, $startTime, null, $e);
  62. return \GuzzleHttp\Promise\rejection_for($e);
  63. }
  64. }
  65. private function invokeStats(
  66. array $options,
  67. RequestInterface $request,
  68. $startTime,
  69. ResponseInterface $response = null,
  70. $error = null
  71. ) {
  72. if (isset($options['on_stats'])) {
  73. $stats = new TransferStats(
  74. $request,
  75. $response,
  76. microtime(true) - $startTime,
  77. $error,
  78. []
  79. );
  80. call_user_func($options['on_stats'], $stats);
  81. }
  82. }
  83. private function createResponse(
  84. RequestInterface $request,
  85. array $options,
  86. $stream,
  87. $startTime
  88. ) {
  89. $hdrs = $this->lastHeaders;
  90. $this->lastHeaders = [];
  91. $parts = explode(' ', array_shift($hdrs), 3);
  92. $ver = explode('/', $parts[0])[1];
  93. $status = $parts[1];
  94. $reason = isset($parts[2]) ? $parts[2] : null;
  95. $headers = \GuzzleHttp\headers_from_lines($hdrs);
  96. list ($stream, $headers) = $this->checkDecode($options, $headers, $stream);
  97. $stream = Psr7\stream_for($stream);
  98. $sink = $stream;
  99. if (strcasecmp('HEAD', $request->getMethod())) {
  100. $sink = $this->createSink($stream, $options);
  101. }
  102. $response = new Psr7\Response($status, $headers, $sink, $ver, $reason);
  103. if (isset($options['on_headers'])) {
  104. try {
  105. $options['on_headers']($response);
  106. } catch (\Exception $e) {
  107. $msg = 'An error was encountered during the on_headers event';
  108. $ex = new RequestException($msg, $request, $response, $e);
  109. return \GuzzleHttp\Promise\rejection_for($ex);
  110. }
  111. }
  112. if ($sink !== $stream) {
  113. $this->drain(
  114. $stream,
  115. $sink,
  116. $response->getHeaderLine('Content-Length')
  117. );
  118. }
  119. $this->invokeStats($options, $request, $startTime, $response, null);
  120. return new FulfilledPromise($response);
  121. }
  122. private function createSink(StreamInterface $stream, array $options)
  123. {
  124. if (!empty($options['stream'])) {
  125. return $stream;
  126. }
  127. $sink = isset($options['sink'])
  128. ? $options['sink']
  129. : fopen('php://temp', 'r+');
  130. return is_string($sink)
  131. ? new Psr7\LazyOpenStream($sink, 'w+')
  132. : Psr7\stream_for($sink);
  133. }
  134. private function checkDecode(array $options, array $headers, $stream)
  135. {
  136. if (!empty($options['decode_content'])) {
  137. $normalizedKeys = \GuzzleHttp\normalize_header_keys($headers);
  138. if (isset($normalizedKeys['content-encoding'])) {
  139. $encoding = $headers[$normalizedKeys['content-encoding']];
  140. if ($encoding[0] === 'gzip' || $encoding[0] === 'deflate') {
  141. $stream = new Psr7\InflateStream(
  142. Psr7\stream_for($stream)
  143. );
  144. $headers['x-encoded-content-encoding']
  145. = $headers[$normalizedKeys['content-encoding']];
  146. unset($headers[$normalizedKeys['content-encoding']]);
  147. if (isset($normalizedKeys['content-length'])) {
  148. $headers['x-encoded-content-length']
  149. = $headers[$normalizedKeys['content-length']];
  150. $length = (int) $stream->getSize();
  151. if ($length === 0) {
  152. unset($headers[$normalizedKeys['content-length']]);
  153. } else {
  154. $headers[$normalizedKeys['content-length']] = [$length];
  155. }
  156. }
  157. }
  158. }
  159. }
  160. return [$stream, $headers];
  161. }
  162. private function drain(
  163. StreamInterface $source,
  164. StreamInterface $sink,
  165. $contentLength
  166. ) {
  167. Psr7\copy_to_stream(
  168. $source,
  169. $sink,
  170. (strlen($contentLength) > 0 && (int) $contentLength > 0) ? (int) $contentLength : -1
  171. );
  172. $sink->seek(0);
  173. $source->close();
  174. return $sink;
  175. }
  176. private function createResource(callable $callback)
  177. {
  178. $errors = null;
  179. set_error_handler(function ($_, $msg, $file, $line) use (&$errors) {
  180. $errors[] = [
  181. 'message' => $msg,
  182. 'file' => $file,
  183. 'line' => $line
  184. ];
  185. return true;
  186. });
  187. $resource = $callback();
  188. restore_error_handler();
  189. if (!$resource) {
  190. $message = 'Error creating resource: ';
  191. foreach ($errors as $err) {
  192. foreach ($err as $key => $value) {
  193. $message .= "[$key] $value" . PHP_EOL;
  194. }
  195. }
  196. throw new \RuntimeException(trim($message));
  197. }
  198. return $resource;
  199. }
  200. private function createStream(RequestInterface $request, array $options)
  201. {
  202. static $methods;
  203. if (!$methods) {
  204. $methods = array_flip(get_class_methods(__CLASS__));
  205. }
  206. if ($request->getProtocolVersion() == '1.1'
  207. && !$request->hasHeader('Connection')
  208. ) {
  209. $request = $request->withHeader('Connection', 'close');
  210. }
  211. if (!isset($options['verify'])) {
  212. $options['verify'] = true;
  213. }
  214. $params = [];
  215. $context = $this->getDefaultContext($request, $options);
  216. if (isset($options['on_headers']) && !is_callable($options['on_headers'])) {
  217. throw new \InvalidArgumentException('on_headers must be callable');
  218. }
  219. if (!empty($options)) {
  220. foreach ($options as $key => $value) {
  221. $method = "add_{$key}";
  222. if (isset($methods[$method])) {
  223. $this->{$method}($request, $context, $value, $params);
  224. }
  225. }
  226. }
  227. if (isset($options['stream_context'])) {
  228. if (!is_array($options['stream_context'])) {
  229. throw new \InvalidArgumentException('stream_context must be an array');
  230. }
  231. $context = array_replace_recursive(
  232. $context,
  233. $options['stream_context']
  234. );
  235. }
  236. if (isset($options['auth'])
  237. && is_array($options['auth'])
  238. && isset($options['auth'][2])
  239. && 'ntlm' == $options['auth'][2]
  240. ) {
  241. throw new \InvalidArgumentException('Microsoft NTLM authentication only supported with curl handler');
  242. }
  243. $uri = $this->resolveHost($request, $options);
  244. $context = $this->createResource(
  245. function () use ($context, $params) {
  246. return stream_context_create($context, $params);
  247. }
  248. );
  249. return $this->createResource(
  250. function () use ($uri, &$http_response_header, $context, $options) {
  251. $resource = fopen((string) $uri, 'r', null, $context);
  252. $this->lastHeaders = $http_response_header;
  253. if (isset($options['read_timeout'])) {
  254. $readTimeout = $options['read_timeout'];
  255. $sec = (int) $readTimeout;
  256. $usec = ($readTimeout - $sec) * 100000;
  257. stream_set_timeout($resource, $sec, $usec);
  258. }
  259. return $resource;
  260. }
  261. );
  262. }
  263. private function resolveHost(RequestInterface $request, array $options)
  264. {
  265. $uri = $request->getUri();
  266. if (isset($options['force_ip_resolve']) && !filter_var($uri->getHost(), FILTER_VALIDATE_IP)) {
  267. if ('v4' === $options['force_ip_resolve']) {
  268. $records = dns_get_record($uri->getHost(), DNS_A);
  269. if (!isset($records[0]['ip'])) {
  270. throw new ConnectException(sprintf("Could not resolve IPv4 address for host '%s'", $uri->getHost()), $request);
  271. }
  272. $uri = $uri->withHost($records[0]['ip']);
  273. } elseif ('v6' === $options['force_ip_resolve']) {
  274. $records = dns_get_record($uri->getHost(), DNS_AAAA);
  275. if (!isset($records[0]['ipv6'])) {
  276. throw new ConnectException(sprintf("Could not resolve IPv6 address for host '%s'", $uri->getHost()), $request);
  277. }
  278. $uri = $uri->withHost('[' . $records[0]['ipv6'] . ']');
  279. }
  280. }
  281. return $uri;
  282. }
  283. private function getDefaultContext(RequestInterface $request)
  284. {
  285. $headers = '';
  286. foreach ($request->getHeaders() as $name => $value) {
  287. foreach ($value as $val) {
  288. $headers .= "$name: $val\r\n";
  289. }
  290. }
  291. $context = [
  292. 'http' => [
  293. 'method' => $request->getMethod(),
  294. 'header' => $headers,
  295. 'protocol_version' => $request->getProtocolVersion(),
  296. 'ignore_errors' => true,
  297. 'follow_location' => 0,
  298. ],
  299. ];
  300. $body = (string) $request->getBody();
  301. if (!empty($body)) {
  302. $context['http']['content'] = $body;
  303. if (!$request->hasHeader('Content-Type')) {
  304. $context['http']['header'] .= "Content-Type:\r\n";
  305. }
  306. }
  307. $context['http']['header'] = rtrim($context['http']['header']);
  308. return $context;
  309. }
  310. private function add_proxy(RequestInterface $request, &$options, $value, &$params)
  311. {
  312. if (!is_array($value)) {
  313. $options['http']['proxy'] = $value;
  314. } else {
  315. $scheme = $request->getUri()->getScheme();
  316. if (isset($value[$scheme])) {
  317. if (!isset($value['no'])
  318. || !\GuzzleHttp\is_host_in_noproxy(
  319. $request->getUri()->getHost(),
  320. $value['no']
  321. )
  322. ) {
  323. $options['http']['proxy'] = $value[$scheme];
  324. }
  325. }
  326. }
  327. }
  328. private function add_timeout(RequestInterface $request, &$options, $value, &$params)
  329. {
  330. if ($value > 0) {
  331. $options['http']['timeout'] = $value;
  332. }
  333. }
  334. private function add_verify(RequestInterface $request, &$options, $value, &$params)
  335. {
  336. if ($value === true) {
  337. if (PHP_VERSION_ID < 50600) {
  338. $options['ssl']['cafile'] = \GuzzleHttp\default_ca_bundle();
  339. }
  340. } elseif (is_string($value)) {
  341. $options['ssl']['cafile'] = $value;
  342. if (!file_exists($value)) {
  343. throw new \RuntimeException("SSL CA bundle not found: $value");
  344. }
  345. } elseif ($value === false) {
  346. $options['ssl']['verify_peer'] = false;
  347. $options['ssl']['verify_peer_name'] = false;
  348. return;
  349. } else {
  350. throw new \InvalidArgumentException('Invalid verify request option');
  351. }
  352. $options['ssl']['verify_peer'] = true;
  353. $options['ssl']['verify_peer_name'] = true;
  354. $options['ssl']['allow_self_signed'] = false;
  355. }
  356. private function add_cert(RequestInterface $request, &$options, $value, &$params)
  357. {
  358. if (is_array($value)) {
  359. $options['ssl']['passphrase'] = $value[1];
  360. $value = $value[0];
  361. }
  362. if (!file_exists($value)) {
  363. throw new \RuntimeException("SSL certificate not found: {$value}");
  364. }
  365. $options['ssl']['local_cert'] = $value;
  366. }
  367. private function add_progress(RequestInterface $request, &$options, $value, &$params)
  368. {
  369. $this->addNotification(
  370. $params,
  371. function ($code, $a, $b, $c, $transferred, $total) use ($value) {
  372. if ($code == STREAM_NOTIFY_PROGRESS) {
  373. $value($total, $transferred, null, null);
  374. }
  375. }
  376. );
  377. }
  378. private function add_debug(RequestInterface $request, &$options, $value, &$params)
  379. {
  380. if ($value === false) {
  381. return;
  382. }
  383. static $map = [
  384. STREAM_NOTIFY_CONNECT => 'CONNECT',
  385. STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED',
  386. STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT',
  387. STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS',
  388. STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS',
  389. STREAM_NOTIFY_REDIRECTED => 'REDIRECTED',
  390. STREAM_NOTIFY_PROGRESS => 'PROGRESS',
  391. STREAM_NOTIFY_FAILURE => 'FAILURE',
  392. STREAM_NOTIFY_COMPLETED => 'COMPLETED',
  393. STREAM_NOTIFY_RESOLVE => 'RESOLVE',
  394. ];
  395. static $args = ['severity', 'message', 'message_code',
  396. 'bytes_transferred', 'bytes_max'];
  397. $value = \GuzzleHttp\debug_resource($value);
  398. $ident = $request->getMethod() . ' ' . $request->getUri()->withFragment('');
  399. $this->addNotification(
  400. $params,
  401. function () use ($ident, $value, $map, $args) {
  402. $passed = func_get_args();
  403. $code = array_shift($passed);
  404. fprintf($value, '<%s> [%s] ', $ident, $map[$code]);
  405. foreach (array_filter($passed) as $i => $v) {
  406. fwrite($value, $args[$i] . ': "' . $v . '" ');
  407. }
  408. fwrite($value, "\n");
  409. }
  410. );
  411. }
  412. private function addNotification(array &$params, callable $notify)
  413. {
  414. if (!isset($params['notification'])) {
  415. $params['notification'] = $notify;
  416. } else {
  417. $params['notification'] = $this->callArray([
  418. $params['notification'],
  419. $notify
  420. ]);
  421. }
  422. }
  423. private function callArray(array $functions)
  424. {
  425. return function () use ($functions) {
  426. $args = func_get_args();
  427. foreach ($functions as $fn) {
  428. call_user_func_array($fn, $args);
  429. }
  430. };
  431. }
  432. }