3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 class PhpHttpRequest
extends MWHttpRequest
{
23 private $fopenErrors = [];
25 public function __construct() {
26 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
27 throw new RuntimeException( __METHOD__
. ': allow_url_fopen needs to be enabled for ' .
28 'pure PHP http requests to work. If possible, curl should be used instead. See ' .
29 'https://www.php.net/curl.'
33 parent
::__construct( ...func_get_args() );
40 protected function urlToTcp( $url ) {
41 $parsedUrl = parse_url( $url );
43 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
47 * Returns an array with a 'capath' or 'cafile' key
48 * that is suitable to be merged into the 'ssl' sub-array of
49 * a stream context options array.
50 * Uses the 'caInfo' option of the class if it is provided, otherwise uses the system
51 * default CA bundle if PHP supports that, or searches a few standard locations.
53 * @throws DomainException
55 protected function getCertOptions() {
58 if ( $this->caInfo
) {
59 $certLocations = [ 'manual' => $this->caInfo
];
62 foreach ( $certLocations as $key => $cert ) {
63 if ( is_dir( $cert ) ) {
64 $certOptions['capath'] = $cert;
66 } elseif ( is_file( $cert ) ) {
67 $certOptions['cafile'] = $cert;
69 } elseif ( $key === 'manual' ) {
70 // fail more loudly if a cert path was manually configured and it is not valid
71 throw new DomainException( "Invalid CA info passed: $cert" );
79 * Custom error handler for dealing with fopen() errors.
80 * fopen() tends to fire multiple errors in succession, and the last one
81 * is completely useless (something like "fopen: failed to open stream")
82 * so normal methods of handling errors programmatically
83 * like get_last_error() don't work.
86 * @param string $errstr
88 public function errorHandler( $errno, $errstr ) {
89 $n = count( $this->fopenErrors
) +
1;
90 $this->fopenErrors +
= [ "errno$n" => $errno, "errstr$n" => $errstr ];
94 * @see MWHttpRequest::execute
98 public function execute() {
101 if ( is_array( $this->postData
) ) {
102 $this->postData
= wfArrayToCgi( $this->postData
);
105 if ( $this->parsedUrl
['scheme'] != 'http'
106 && $this->parsedUrl
['scheme'] != 'https' ) {
107 $this->status
->fatal( 'http-invalid-scheme', $this->parsedUrl
['scheme'] );
110 $this->reqHeaders
['Accept'] = "*/*";
111 $this->reqHeaders
['Connection'] = 'Close';
112 if ( $this->method
== 'POST' ) {
113 // Required for HTTP 1.0 POSTs
114 $this->reqHeaders
['Content-Length'] = strlen( $this->postData
);
115 if ( !isset( $this->reqHeaders
['Content-Type'] ) ) {
116 $this->reqHeaders
['Content-Type'] = "application/x-www-form-urlencoded";
120 // Set up PHP stream context
123 'method' => $this->method
,
124 'header' => implode( "\r\n", $this->getHeaderList() ),
125 'protocol_version' => '1.1',
126 'max_redirects' => $this->followRedirects ?
$this->maxRedirects
: 0,
127 'ignore_errors' => true,
128 'timeout' => $this->timeout
,
129 // Curl options in case curlwrappers are installed
130 'curl_verify_ssl_host' => $this->sslVerifyHost ?
2 : 0,
131 'curl_verify_ssl_peer' => $this->sslVerifyCert
,
134 'verify_peer' => $this->sslVerifyCert
,
135 'SNI_enabled' => true,
136 'ciphers' => 'HIGH:!SSLv2:!SSLv3:-ADH:-kDH:-kECDH:-DSS',
137 'disable_compression' => true,
141 if ( $this->proxy
) {
142 $options['http']['proxy'] = $this->urlToTcp( $this->proxy
);
143 $options['http']['request_fulluri'] = true;
146 if ( $this->postData
) {
147 $options['http']['content'] = $this->postData
;
150 if ( $this->sslVerifyHost
) {
151 $options['ssl']['peer_name'] = $this->parsedUrl
['host'];
154 $options['ssl'] +
= $this->getCertOptions();
156 $context = stream_context_create( $options );
158 $this->headerList
= [];
164 if ( $this->profiler
) {
165 $profileSection = $this->profiler
->scopedProfileIn(
166 __METHOD__
. '-' . $this->profileName
171 $this->fopenErrors
= [];
172 set_error_handler( [ $this, 'errorHandler' ] );
173 $fh = fopen( $url, "r", false, $context );
174 restore_error_handler();
180 $result = stream_get_meta_data( $fh );
181 $this->headerList
= $result['wrapper_data'];
182 $this->parseHeader();
184 if ( !$this->followRedirects
) {
188 # Handle manual redirection
189 if ( !$this->isRedirect() ||
$reqCount > $this->maxRedirects
) {
192 # Check security of URL
193 $url = $this->getResponseHeader( "Location" );
195 if ( !Http
::isValidURI( $url ) ) {
196 $this->logger
->debug( __METHOD__
. ": insecure redirection\n" );
200 if ( $this->profiler
) {
201 $this->profiler
->scopedProfileOut( $profileSection );
206 if ( $fh === false ) {
207 if ( $this->fopenErrors
) {
208 $this->logger
->warning( __CLASS__
209 . ': error opening connection: {errstr1}', $this->fopenErrors
);
211 $this->status
->fatal( 'http-request-error' );
212 return Status
::wrap( $this->status
); // TODO B/C; move this to callers
215 if ( $result['timed_out'] ) {
216 $this->status
->fatal( 'http-timed-out', $this->url
);
217 return Status
::wrap( $this->status
); // TODO B/C; move this to callers
220 // If everything went OK, or we received some error code
221 // get the response body content.
222 if ( $this->status
->isOK() ||
(int)$this->respStatus
>= 300 ) {
223 while ( !feof( $fh ) ) {
224 $buf = fread( $fh, 8192 );
226 if ( $buf === false ) {
227 $this->status
->fatal( 'http-read-error' );
232 call_user_func( $this->callback
, $fh, $buf );
238 return Status
::wrap( $this->status
); // TODO B/C; move this to callers