TYPO3  7.6
Socket.php
Go to the documentation of this file.
1 <?php
22 require_once 'HTTP/Request2/Adapter.php';
23 
25 require_once 'HTTP/Request2/SocketWrapper.php';
26 
41 {
45  const REGEXP_TOKEN = '[^\x00-\x1f\x7f-\xff()<>@,;:\\\\"/\[\]?={}\s]+';
46 
50  const REGEXP_QUOTED_STRING = '"(?>[^"\\\\]+|\\\\.)*"';
51 
57  protected static $sockets = array();
58 
71  protected static $challenges = array();
72 
78  protected $socket;
79 
84  protected $serverChallenge;
85 
90  protected $proxyChallenge;
91 
97  protected $chunkLength = 0;
98 
107  protected $redirectCountdown = null;
108 
113  protected $expect100Continue = false;
114 
124  {
125  $this->request = $request;
126 
127  try {
128  $keepAlive = $this->connect();
129  $headers = $this->prepareHeaders();
130  $this->socket->write($headers);
131  // provide request headers to the observer, see request #7633
132  $this->request->setLastEvent('sentHeaders', $headers);
133 
134  if (!$this->expect100Continue) {
135  $this->writeBody();
136  $response = $this->readResponse();
137 
138  } else {
139  $response = $this->readResponse();
140  if (!$response || 100 == $response->getStatus()) {
141  $this->expect100Continue = false;
142  // either got "100 Continue" or timed out -> send body
143  $this->writeBody();
144  $response = $this->readResponse();
145  }
146  }
147 
148 
149  if ($jar = $request->getCookieJar()) {
150  $jar->addCookiesFromResponse($response, $request->getUrl());
151  }
152 
153  if (!$this->canKeepAlive($keepAlive, $response)) {
154  $this->disconnect();
155  }
156 
157  if ($this->shouldUseProxyDigestAuth($response)) {
158  return $this->sendRequest($request);
159  }
160  if ($this->shouldUseServerDigestAuth($response)) {
161  return $this->sendRequest($request);
162  }
163  if ($authInfo = $response->getHeader('authentication-info')) {
164  $this->updateChallenge($this->serverChallenge, $authInfo);
165  }
166  if ($proxyInfo = $response->getHeader('proxy-authentication-info')) {
167  $this->updateChallenge($this->proxyChallenge, $proxyInfo);
168  }
169 
170  } catch (Exception $e) {
171  $this->disconnect();
172  }
173 
174  unset($this->request, $this->requestBody);
175 
176  if (!empty($e)) {
177  $this->redirectCountdown = null;
178  throw $e;
179  }
180 
181  if (!$request->getConfig('follow_redirects') || !$response->isRedirect()) {
182  $this->redirectCountdown = null;
183  return $response;
184  } else {
185  return $this->handleRedirect($request, $response);
186  }
187  }
188 
195  protected function connect()
196  {
197  $secure = 0 == strcasecmp($this->request->getUrl()->getScheme(), 'https');
198  $tunnel = HTTP_Request2::METHOD_CONNECT == $this->request->getMethod();
199  $headers = $this->request->getHeaders();
200  $reqHost = $this->request->getUrl()->getHost();
201  if (!($reqPort = $this->request->getUrl()->getPort())) {
202  $reqPort = $secure? 443: 80;
203  }
204 
205  $httpProxy = $socksProxy = false;
206  if (!($host = $this->request->getConfig('proxy_host'))) {
207  $host = $reqHost;
208  $port = $reqPort;
209  } else {
210  if (!($port = $this->request->getConfig('proxy_port'))) {
212  'Proxy port not provided',
214  );
215  }
216  if ('http' == ($type = $this->request->getConfig('proxy_type'))) {
217  $httpProxy = true;
218  } elseif ('socks5' == $type) {
219  $socksProxy = true;
220  } else {
222  "Proxy type '{$type}' is not supported"
223  );
224  }
225  }
226 
227  if ($tunnel && !$httpProxy) {
229  "Trying to perform CONNECT request without proxy",
231  );
232  }
233  if ($secure && !in_array('ssl', stream_get_transports())) {
235  'Need OpenSSL support for https:// requests',
237  );
238  }
239 
240  // RFC 2068, section 19.7.1: A client MUST NOT send the Keep-Alive
241  // connection token to a proxy server...
242  if ($httpProxy && !$secure && !empty($headers['connection'])
243  && 'Keep-Alive' == $headers['connection']
244  ) {
245  $this->request->setHeader('connection');
246  }
247 
248  $keepAlive = ('1.1' == $this->request->getConfig('protocol_version') &&
249  empty($headers['connection'])) ||
250  (!empty($headers['connection']) &&
251  'Keep-Alive' == $headers['connection']);
252 
253  $options = array();
254  if ($ip = $this->request->getConfig('local_ip')) {
255  $options['socket'] = array(
256  'bindto' => (false === strpos($ip, ':') ? $ip : '[' . $ip . ']') . ':0'
257  );
258  }
259  if ($secure || $tunnel) {
260  $options['ssl'] = array();
261  foreach ($this->request->getConfig() as $name => $value) {
262  if ('ssl_' == substr($name, 0, 4) && null !== $value) {
263  if ('ssl_verify_host' == $name) {
264  if ($value) {
265  $options['ssl']['CN_match'] = $reqHost;
266  }
267  } else {
268  $options['ssl'][substr($name, 4)] = $value;
269  }
270  }
271  }
272  ksort($options['ssl']);
273  }
274 
275  // Use global request timeout if given, see feature requests #5735, #8964
276  if ($timeout = $this->request->getConfig('timeout')) {
277  $deadline = time() + $timeout;
278  } else {
279  $deadline = null;
280  }
281 
282  // Changing SSL context options after connection is established does *not*
283  // work, we need a new connection if options change
284  $remote = ((!$secure || $httpProxy || $socksProxy)? 'tcp://': 'ssl://')
285  . $host . ':' . $port;
286  $socketKey = $remote . (
287  ($secure && $httpProxy || $socksProxy)
288  ? "->{$reqHost}:{$reqPort}" : ''
289  ) . (empty($options)? '': ':' . serialize($options));
290  unset($this->socket);
291 
292  // We use persistent connections and have a connected socket?
293  // Ensure that the socket is still connected, see bug #16149
294  if ($keepAlive && !empty(self::$sockets[$socketKey])
295  && !self::$sockets[$socketKey]->eof()
296  ) {
297  $this->socket =& self::$sockets[$socketKey];
298 
299  } else {
300  if ($socksProxy) {
301  require_once 'HTTP/Request2/SOCKS5.php';
302 
303  $this->socket = new HTTP_Request2_SOCKS5(
304  $remote, $this->request->getConfig('connect_timeout'),
305  $options, $this->request->getConfig('proxy_user'),
306  $this->request->getConfig('proxy_password')
307  );
308  // handle request timeouts ASAP
309  $this->socket->setDeadline($deadline, $this->request->getConfig('timeout'));
310  $this->socket->connect($reqHost, $reqPort);
311  if (!$secure) {
312  $conninfo = "tcp://{$reqHost}:{$reqPort} via {$remote}";
313  } else {
314  $this->socket->enableCrypto();
315  $conninfo = "ssl://{$reqHost}:{$reqPort} via {$remote}";
316  }
317 
318  } elseif ($secure && $httpProxy && !$tunnel) {
319  $this->establishTunnel();
320  $conninfo = "ssl://{$reqHost}:{$reqPort} via {$remote}";
321 
322  } else {
323  $this->socket = new HTTP_Request2_SocketWrapper(
324  $remote, $this->request->getConfig('connect_timeout'), $options
325  );
326  }
327  $this->request->setLastEvent('connect', empty($conninfo)? $remote: $conninfo);
328  self::$sockets[$socketKey] =& $this->socket;
329  }
330  $this->socket->setDeadline($deadline, $this->request->getConfig('timeout'));
331  return $keepAlive;
332  }
333 
344  protected function establishTunnel()
345  {
346  $donor = new self;
347  $connect = new HTTP_Request2(
348  $this->request->getUrl(), HTTP_Request2::METHOD_CONNECT,
349  array_merge($this->request->getConfig(), array('adapter' => $donor))
350  );
351  $response = $connect->send();
352  // Need any successful (2XX) response
353  if (200 > $response->getStatus() || 300 <= $response->getStatus()) {
355  'Failed to connect via HTTPS proxy. Proxy response: ' .
356  $response->getStatus() . ' ' . $response->getReasonPhrase()
357  );
358  }
359  $this->socket = $donor->socket;
360  $this->socket->enableCrypto();
361  }
362 
372  protected function canKeepAlive($requestKeepAlive, HTTP_Request2_Response $response)
373  {
374  // Do not close socket on successful CONNECT request
375  if (HTTP_Request2::METHOD_CONNECT == $this->request->getMethod()
376  && 200 <= $response->getStatus() && 300 > $response->getStatus()
377  ) {
378  return true;
379  }
380 
381  $lengthKnown = 'chunked' == strtolower($response->getHeader('transfer-encoding'))
382  || null !== $response->getHeader('content-length')
383  // no body possible for such responses, see also request #17031
384  || HTTP_Request2::METHOD_HEAD == $this->request->getMethod()
385  || in_array($response->getStatus(), array(204, 304));
386  $persistent = 'keep-alive' == strtolower($response->getHeader('connection')) ||
387  (null === $response->getHeader('connection') &&
388  '1.1' == $response->getVersion());
389  return $requestKeepAlive && $lengthKnown && $persistent;
390  }
391 
395  protected function disconnect()
396  {
397  if (!empty($this->socket)) {
398  $this->socket = null;
399  $this->request->setLastEvent('disconnect');
400  }
401  }
402 
416  protected function handleRedirect(
418  ) {
419  if (is_null($this->redirectCountdown)) {
420  $this->redirectCountdown = $request->getConfig('max_redirects');
421  }
422  if (0 == $this->redirectCountdown) {
423  $this->redirectCountdown = null;
424  // Copying cURL behaviour
426  'Maximum (' . $request->getConfig('max_redirects') . ') redirects followed',
428  );
429  }
430  $redirectUrl = new Net_URL2(
431  $response->getHeader('location'),
432  array(Net_URL2::OPTION_USE_BRACKETS => $request->getConfig('use_brackets'))
433  );
434  // refuse non-HTTP redirect
435  if ($redirectUrl->isAbsolute()
436  && !in_array($redirectUrl->getScheme(), array('http', 'https'))
437  ) {
438  $this->redirectCountdown = null;
440  'Refusing to redirect to a non-HTTP URL ' . $redirectUrl->__toString(),
442  );
443  }
444  // Theoretically URL should be absolute (see http://tools.ietf.org/html/rfc2616#section-14.30),
445  // but in practice it is often not
446  if (!$redirectUrl->isAbsolute()) {
447  $redirectUrl = $request->getUrl()->resolve($redirectUrl);
448  }
449  $redirect = clone $request;
450  $redirect->setUrl($redirectUrl);
451  if (303 == $response->getStatus()
452  || (!$request->getConfig('strict_redirects')
453  && in_array($response->getStatus(), array(301, 302)))
454  ) {
455  $redirect->setMethod(HTTP_Request2::METHOD_GET);
456  $redirect->setBody('');
457  }
458 
459  if (0 < $this->redirectCountdown) {
460  $this->redirectCountdown--;
461  }
462  return $this->sendRequest($redirect);
463  }
464 
484  {
485  // no sense repeating a request if we don't have credentials
486  if (401 != $response->getStatus() || !$this->request->getAuth()) {
487  return false;
488  }
489  if (!$challenge = $this->parseDigestChallenge($response->getHeader('www-authenticate'))) {
490  return false;
491  }
492 
493  $url = $this->request->getUrl();
494  $scheme = $url->getScheme();
495  $host = $scheme . '://' . $url->getHost();
496  if ($port = $url->getPort()) {
497  if ((0 == strcasecmp($scheme, 'http') && 80 != $port)
498  || (0 == strcasecmp($scheme, 'https') && 443 != $port)
499  ) {
500  $host .= ':' . $port;
501  }
502  }
503 
504  if (!empty($challenge['domain'])) {
505  $prefixes = array();
506  foreach (preg_split('/\\s+/', $challenge['domain']) as $prefix) {
507  // don't bother with different servers
508  if ('/' == substr($prefix, 0, 1)) {
509  $prefixes[] = $host . $prefix;
510  }
511  }
512  }
513  if (empty($prefixes)) {
514  $prefixes = array($host . '/');
515  }
516 
517  $ret = true;
518  foreach ($prefixes as $prefix) {
519  if (!empty(self::$challenges[$prefix])
520  && (empty($challenge['stale']) || strcasecmp('true', $challenge['stale']))
521  ) {
522  // probably credentials are invalid
523  $ret = false;
524  }
525  self::$challenges[$prefix] =& $challenge;
526  }
527  return $ret;
528  }
529 
549  {
550  if (407 != $response->getStatus() || !$this->request->getConfig('proxy_user')) {
551  return false;
552  }
553  if (!($challenge = $this->parseDigestChallenge($response->getHeader('proxy-authenticate')))) {
554  return false;
555  }
556 
557  $key = 'proxy://' . $this->request->getConfig('proxy_host') .
558  ':' . $this->request->getConfig('proxy_port');
559 
560  if (!empty(self::$challenges[$key])
561  && (empty($challenge['stale']) || strcasecmp('true', $challenge['stale']))
562  ) {
563  $ret = false;
564  } else {
565  $ret = true;
566  }
567  self::$challenges[$key] = $challenge;
568  return $ret;
569  }
570 
600  protected function parseDigestChallenge($headerValue)
601  {
602  $authParam = '(' . self::REGEXP_TOKEN . ')\\s*=\\s*(' .
603  self::REGEXP_TOKEN . '|' . self::REGEXP_QUOTED_STRING . ')';
604  $challenge = "!(?<=^|\\s|,)Digest ({$authParam}\\s*(,\\s*|$))+!";
605  if (!preg_match($challenge, $headerValue, $matches)) {
606  return false;
607  }
608 
609  preg_match_all('!' . $authParam . '!', $matches[0], $params);
610  $paramsAry = array();
611  $knownParams = array('realm', 'domain', 'nonce', 'opaque', 'stale',
612  'algorithm', 'qop');
613  for ($i = 0; $i < count($params[0]); $i++) {
614  // section 3.2.1: Any unrecognized directive MUST be ignored.
615  if (in_array($params[1][$i], $knownParams)) {
616  if ('"' == substr($params[2][$i], 0, 1)) {
617  $paramsAry[$params[1][$i]] = substr($params[2][$i], 1, -1);
618  } else {
619  $paramsAry[$params[1][$i]] = $params[2][$i];
620  }
621  }
622  }
623  // we only support qop=auth
624  if (!empty($paramsAry['qop'])
625  && !in_array('auth', array_map('trim', explode(',', $paramsAry['qop'])))
626  ) {
628  "Only 'auth' qop is currently supported in digest authentication, " .
629  "server requested '{$paramsAry['qop']}'"
630  );
631  }
632  // we only support algorithm=MD5
633  if (!empty($paramsAry['algorithm']) && 'MD5' != $paramsAry['algorithm']) {
635  "Only 'MD5' algorithm is currently supported in digest authentication, " .
636  "server requested '{$paramsAry['algorithm']}'"
637  );
638  }
639 
640  return $paramsAry;
641  }
642 
651  protected function updateChallenge(&$challenge, $headerValue)
652  {
653  $authParam = '!(' . self::REGEXP_TOKEN . ')\\s*=\\s*(' .
654  self::REGEXP_TOKEN . '|' . self::REGEXP_QUOTED_STRING . ')!';
655  $paramsAry = array();
656 
657  preg_match_all($authParam, $headerValue, $params);
658  for ($i = 0; $i < count($params[0]); $i++) {
659  if ('"' == substr($params[2][$i], 0, 1)) {
660  $paramsAry[$params[1][$i]] = substr($params[2][$i], 1, -1);
661  } else {
662  $paramsAry[$params[1][$i]] = $params[2][$i];
663  }
664  }
665  // for now, just update the nonce value
666  if (!empty($paramsAry['nextnonce'])) {
667  $challenge['nonce'] = $paramsAry['nextnonce'];
668  $challenge['nc'] = 1;
669  }
670  }
671 
683  protected function createDigestResponse($user, $password, $url, &$challenge)
684  {
685  if (false !== ($q = strpos($url, '?'))
686  && $this->request->getConfig('digest_compat_ie')
687  ) {
688  $url = substr($url, 0, $q);
689  }
690 
691  $a1 = md5($user . ':' . $challenge['realm'] . ':' . $password);
692  $a2 = md5($this->request->getMethod() . ':' . $url);
693 
694  if (empty($challenge['qop'])) {
695  $digest = md5($a1 . ':' . $challenge['nonce'] . ':' . $a2);
696  } else {
697  $challenge['cnonce'] = 'Req2.' . rand();
698  if (empty($challenge['nc'])) {
699  $challenge['nc'] = 1;
700  }
701  $nc = sprintf('%08x', $challenge['nc']++);
702  $digest = md5(
703  $a1 . ':' . $challenge['nonce'] . ':' . $nc . ':' .
704  $challenge['cnonce'] . ':auth:' . $a2
705  );
706  }
707  return 'Digest username="' . str_replace(array('\\', '"'), array('\\\\', '\\"'), $user) . '", ' .
708  'realm="' . $challenge['realm'] . '", ' .
709  'nonce="' . $challenge['nonce'] . '", ' .
710  'uri="' . $url . '", ' .
711  'response="' . $digest . '"' .
712  (!empty($challenge['opaque'])?
713  ', opaque="' . $challenge['opaque'] . '"':
714  '') .
715  (!empty($challenge['qop'])?
716  ', qop="auth", nc=' . $nc . ', cnonce="' . $challenge['cnonce'] . '"':
717  '');
718  }
719 
729  protected function addAuthorizationHeader(&$headers, $requestHost, $requestUrl)
730  {
731  if (!($auth = $this->request->getAuth())) {
732  return;
733  }
734  switch ($auth['scheme']) {
736  $headers['authorization'] = 'Basic ' . base64_encode(
737  $auth['user'] . ':' . $auth['password']
738  );
739  break;
740 
742  unset($this->serverChallenge);
743  $fullUrl = ('/' == $requestUrl[0])?
744  $this->request->getUrl()->getScheme() . '://' .
745  $requestHost . $requestUrl:
746  $requestUrl;
747  foreach (array_keys(self::$challenges) as $key) {
748  if ($key == substr($fullUrl, 0, strlen($key))) {
749  $headers['authorization'] = $this->createDigestResponse(
750  $auth['user'], $auth['password'],
751  $requestUrl, self::$challenges[$key]
752  );
753  $this->serverChallenge =& self::$challenges[$key];
754  break;
755  }
756  }
757  break;
758 
759  default:
761  "Unknown HTTP authentication scheme '{$auth['scheme']}'"
762  );
763  }
764  }
765 
774  protected function addProxyAuthorizationHeader(&$headers, $requestUrl)
775  {
776  if (!$this->request->getConfig('proxy_host')
777  || !($user = $this->request->getConfig('proxy_user'))
778  || (0 == strcasecmp('https', $this->request->getUrl()->getScheme())
779  && HTTP_Request2::METHOD_CONNECT != $this->request->getMethod())
780  ) {
781  return;
782  }
783 
784  $password = $this->request->getConfig('proxy_password');
785  switch ($this->request->getConfig('proxy_auth_scheme')) {
787  $headers['proxy-authorization'] = 'Basic ' . base64_encode(
788  $user . ':' . $password
789  );
790  break;
791 
793  unset($this->proxyChallenge);
794  $proxyUrl = 'proxy://' . $this->request->getConfig('proxy_host') .
795  ':' . $this->request->getConfig('proxy_port');
796  if (!empty(self::$challenges[$proxyUrl])) {
797  $headers['proxy-authorization'] = $this->createDigestResponse(
798  $user, $password,
799  $requestUrl, self::$challenges[$proxyUrl]
800  );
801  $this->proxyChallenge =& self::$challenges[$proxyUrl];
802  }
803  break;
804 
805  default:
807  "Unknown HTTP authentication scheme '" .
808  $this->request->getConfig('proxy_auth_scheme') . "'"
809  );
810  }
811  }
812 
813 
820  protected function prepareHeaders()
821  {
822  $headers = $this->request->getHeaders();
823  $url = $this->request->getUrl();
824  $connect = HTTP_Request2::METHOD_CONNECT == $this->request->getMethod();
825  $host = $url->getHost();
826 
827  $defaultPort = 0 == strcasecmp($url->getScheme(), 'https')? 443: 80;
828  if (($port = $url->getPort()) && $port != $defaultPort || $connect) {
829  $host .= ':' . (empty($port)? $defaultPort: $port);
830  }
831  // Do not overwrite explicitly set 'Host' header, see bug #16146
832  if (!isset($headers['host'])) {
833  $headers['host'] = $host;
834  }
835 
836  if ($connect) {
837  $requestUrl = $host;
838 
839  } else {
840  if (!$this->request->getConfig('proxy_host')
841  || 'http' != $this->request->getConfig('proxy_type')
842  || 0 == strcasecmp($url->getScheme(), 'https')
843  ) {
844  $requestUrl = '';
845  } else {
846  $requestUrl = $url->getScheme() . '://' . $host;
847  }
848  $path = $url->getPath();
849  $query = $url->getQuery();
850  $requestUrl .= (empty($path)? '/': $path) . (empty($query)? '': '?' . $query);
851  }
852 
853  if ('1.1' == $this->request->getConfig('protocol_version')
854  && extension_loaded('zlib') && !isset($headers['accept-encoding'])
855  ) {
856  $headers['accept-encoding'] = 'gzip, deflate';
857  }
858  if (($jar = $this->request->getCookieJar())
859  && ($cookies = $jar->getMatching($this->request->getUrl(), true))
860  ) {
861  $headers['cookie'] = (empty($headers['cookie'])? '': $headers['cookie'] . '; ') . $cookies;
862  }
863 
864  $this->addAuthorizationHeader($headers, $host, $requestUrl);
865  $this->addProxyAuthorizationHeader($headers, $requestUrl);
866  $this->calculateRequestLength($headers);
867  if ('1.1' == $this->request->getConfig('protocol_version')) {
868  $this->updateExpectHeader($headers);
869  } else {
870  $this->expect100Continue = false;
871  }
872 
873  $headersStr = $this->request->getMethod() . ' ' . $requestUrl . ' HTTP/' .
874  $this->request->getConfig('protocol_version') . "\r\n";
875  foreach ($headers as $name => $value) {
876  $canonicalName = implode('-', array_map('ucfirst', explode('-', $name)));
877  $headersStr .= $canonicalName . ': ' . $value . "\r\n";
878  }
879  return $headersStr . "\r\n";
880  }
881 
898  protected function updateExpectHeader(&$headers)
899  {
900  $this->expect100Continue = false;
901  $expectations = array();
902  if (isset($headers['expect'])) {
903  if ('' === $headers['expect']) {
904  // empty 'Expect' header is technically invalid, so just get rid of it
905  unset($headers['expect']);
906  return;
907  }
908  // build regexp to parse the value of existing Expect header
909  $expectParam = ';\s*' . self::REGEXP_TOKEN . '(?:\s*=\s*(?:'
910  . self::REGEXP_TOKEN . '|'
911  . self::REGEXP_QUOTED_STRING . '))?\s*';
912  $expectExtension = self::REGEXP_TOKEN . '(?:\s*=\s*(?:'
913  . self::REGEXP_TOKEN . '|'
914  . self::REGEXP_QUOTED_STRING . ')\s*(?:'
915  . $expectParam . ')*)?';
916  $expectItem = '!(100-continue|' . $expectExtension . ')!A';
917 
918  $pos = 0;
919  $length = strlen($headers['expect']);
920 
921  while ($pos < $length) {
922  $pos += strspn($headers['expect'], " \t", $pos);
923  if (',' === substr($headers['expect'], $pos, 1)) {
924  $pos++;
925  continue;
926 
927  } elseif (!preg_match($expectItem, $headers['expect'], $m, 0, $pos)) {
929  "Cannot parse value '{$headers['expect']}' of Expect header",
931  );
932 
933  } else {
934  $pos += strlen($m[0]);
935  if (strcasecmp('100-continue', $m[0])) {
936  $expectations[] = $m[0];
937  }
938  }
939  }
940  }
941 
942  if (1024 < $this->contentLength) {
943  $expectations[] = '100-continue';
944  $this->expect100Continue = true;
945  }
946 
947  if (empty($expectations)) {
948  unset($headers['expect']);
949  } else {
950  $headers['expect'] = implode(',', $expectations);
951  }
952  }
953 
959  protected function writeBody()
960  {
961  if (in_array($this->request->getMethod(), self::$bodyDisallowed)
962  || 0 == $this->contentLength
963  ) {
964  return;
965  }
966 
967  $position = 0;
968  $bufferSize = $this->request->getConfig('buffer_size');
969  $headers = $this->request->getHeaders();
970  $chunked = isset($headers['transfer-encoding']);
971  while ($position < $this->contentLength) {
972  if (is_string($this->requestBody)) {
973  $str = substr($this->requestBody, $position, $bufferSize);
974  } elseif (is_resource($this->requestBody)) {
975  $str = fread($this->requestBody, $bufferSize);
976  } else {
977  $str = $this->requestBody->read($bufferSize);
978  }
979  if (!$chunked) {
980  $this->socket->write($str);
981  } else {
982  $this->socket->write(dechex(strlen($str)) . "\r\n{$str}\r\n");
983  }
984  // Provide the length of written string to the observer, request #7630
985  $this->request->setLastEvent('sentBodyPart', strlen($str));
986  $position += strlen($str);
987  }
988 
989  // write zero-length chunk
990  if ($chunked) {
991  $this->socket->write("0\r\n\r\n");
992  }
993  $this->request->setLastEvent('sentBody', $this->contentLength);
994  }
995 
1002  protected function readResponse()
1003  {
1004  $bufferSize = $this->request->getConfig('buffer_size');
1005  // http://tools.ietf.org/html/rfc2616#section-8.2.3
1006  // ...the client SHOULD NOT wait for an indefinite period before sending the request body
1007  $timeout = $this->expect100Continue ? 1 : null;
1008 
1009  do {
1010  try {
1012  $this->socket->readLine($bufferSize, $timeout), true, $this->request->getUrl()
1013  );
1014  do {
1015  $headerLine = $this->socket->readLine($bufferSize);
1016  $response->parseHeaderLine($headerLine);
1017  } while ('' != $headerLine);
1018 
1019  } catch (HTTP_Request2_MessageException $e) {
1020  if (HTTP_Request2_Exception::TIMEOUT === $e->getCode()
1022  ) {
1023  return null;
1024  }
1025  throw $e;
1026  }
1027  if ($this->expect100Continue && 100 == $response->getStatus()) {
1028  return $response;
1029  }
1030  } while (in_array($response->getStatus(), array(100, 101)));
1031 
1032  $this->request->setLastEvent('receivedHeaders', $response);
1033 
1034  // No body possible in such responses
1035  if (HTTP_Request2::METHOD_HEAD == $this->request->getMethod()
1036  || (HTTP_Request2::METHOD_CONNECT == $this->request->getMethod()
1037  && 200 <= $response->getStatus() && 300 > $response->getStatus())
1038  || in_array($response->getStatus(), array(204, 304))
1039  ) {
1040  return $response;
1041  }
1042 
1043  $chunked = 'chunked' == $response->getHeader('transfer-encoding');
1044  $length = $response->getHeader('content-length');
1045  $hasBody = false;
1046  if ($chunked || null === $length || 0 < intval($length)) {
1047  // RFC 2616, section 4.4:
1048  // 3. ... If a message is received with both a
1049  // Transfer-Encoding header field and a Content-Length header field,
1050  // the latter MUST be ignored.
1051  $toRead = ($chunked || null === $length)? null: $length;
1052  $this->chunkLength = 0;
1053 
1054  while (!$this->socket->eof() && (is_null($toRead) || 0 < $toRead)) {
1055  if ($chunked) {
1056  $data = $this->readChunked($bufferSize);
1057  } elseif (is_null($toRead)) {
1058  $data = $this->socket->read($bufferSize);
1059  } else {
1060  $data = $this->socket->read(min($toRead, $bufferSize));
1061  $toRead -= strlen($data);
1062  }
1063  if ('' == $data && (!$this->chunkLength || $this->socket->eof())) {
1064  break;
1065  }
1066 
1067  $hasBody = true;
1068  if ($this->request->getConfig('store_body')) {
1069  $response->appendBody($data);
1070  }
1071  if (!in_array($response->getHeader('content-encoding'), array('identity', null))) {
1072  $this->request->setLastEvent('receivedEncodedBodyPart', $data);
1073  } else {
1074  $this->request->setLastEvent('receivedBodyPart', $data);
1075  }
1076  }
1077  }
1078 
1079  if ($hasBody) {
1080  $this->request->setLastEvent('receivedBody', $response);
1081  }
1082  return $response;
1083  }
1084 
1093  protected function readChunked($bufferSize)
1094  {
1095  // at start of the next chunk?
1096  if (0 == $this->chunkLength) {
1097  $line = $this->socket->readLine($bufferSize);
1098  if (!preg_match('/^([0-9a-f]+)/i', $line, $matches)) {
1100  "Cannot decode chunked response, invalid chunk length '{$line}'",
1102  );
1103  } else {
1104  $this->chunkLength = hexdec($matches[1]);
1105  // Chunk with zero length indicates the end
1106  if (0 == $this->chunkLength) {
1107  $this->socket->readLine($bufferSize);
1108  return '';
1109  }
1110  }
1111  }
1112  $data = $this->socket->read(min($this->chunkLength, $bufferSize));
1113  $this->chunkLength -= strlen($data);
1114  if (0 == $this->chunkLength) {
1115  $this->socket->readLine($bufferSize); // Trailing CRLF
1116  }
1117  return $data;
1118  }
1119 }
1120 
1121 ?>