Completed
Pull Request — master (#176)
by Markus
01:52
created

BaseRequest::nssCiphers()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 0
cts 0
cp 0
rs 9.8666
c 0
b 0
f 0
cc 3
nc 3
nop 0
crap 12
1
<?php
2
/*
3
 * hirak/prestissimo
4
 * @author Hiraku NAKANO
5
 * @license MIT https://github.com/hirak/prestissimo
6
 */
7
namespace Hirak\Prestissimo;
8
9
use Composer\Util;
10
use Composer\IO;
11
12
class BaseRequest
13
{
14
    private $scheme;
15
    private $user;
16
    private $pass;
17
    private $host;
18
    private $port;
19
    private $path;
20
    private $query = array();
21
22
    /** @var [string => string] */
23
    private $headers = array();
24
25
    private $capath;
26
    private $cafile;
27
28
    protected static $defaultCurlOptions = array();
29
30
    private static $NSS_CIPHERS = array(
31
        'rsa_3des_sha',
32
        'rsa_des_sha',
33
        'rsa_null_md5',
34
        'rsa_null_sha',
35
        'rsa_rc2_40_md5',
36
        'rsa_rc4_128_md5',
37
        'rsa_rc4_128_sha',
38
        'rsa_rc4_40_md5',
39
        'fips_des_sha',
40
        'fips_3des_sha',
41
        'rsa_des_56_sha',
42
        'rsa_rc4_56_sha',
43
        'rsa_aes_128_sha',
44
        'rsa_aes_256_sha',
45
        'rsa_aes_128_gcm_sha_256',
46
        'dhe_rsa_aes_128_gcm_sha_256',
47
        'ecdh_ecdsa_null_sha',
48
        'ecdh_ecdsa_rc4_128_sha',
49
        'ecdh_ecdsa_3des_sha',
50
        'ecdh_ecdsa_aes_128_sha',
51
        'ecdh_ecdsa_aes_256_sha',
52
        'ecdhe_ecdsa_null_sha',
53
        'ecdhe_ecdsa_rc4_128_sha',
54
        'ecdhe_ecdsa_3des_sha',
55
        'ecdhe_ecdsa_aes_128_sha',
56
        'ecdhe_ecdsa_aes_256_sha',
57
        'ecdh_rsa_null_sha',
58
        'ecdh_rsa_128_sha',
59
        'ecdh_rsa_3des_sha',
60
        'ecdh_rsa_aes_128_sha',
61
        'ecdh_rsa_aes_256_sha',
62
        'ecdhe_rsa_rc4_128_sha',
63
        'ecdhe_rsa_3des_sha',
64
        'ecdhe_rsa_aes_128_sha',
65
        'ecdhe_rsa_aes_256_sha',
66
        'ecdhe_ecdsa_aes_128_gcm_sha_256',
67
        'ecdhe_rsa_aes_128_gcm_sha_256',
68
    );
69
70
    /**
71
     * enable ECC cipher suites in cURL/NSS
72
     * @codeCoverageIgnore
73
     */
74
    public static function nssCiphers()
75
    {
76
        static $cache;
77
        if (isset($cache)) {
78
            return $cache;
79
        }
80
        $ver = curl_version();
81
        if (preg_match('/^NSS.*Basic ECC$/', $ver['ssl_version'])) {
82
            return $cache = implode(',', self::$NSS_CIPHERS);
83
        }
84
        return $cache = false;
85
    }
86
87 4
    protected function getProxy($url)
0 ignored issues
show
Coding Style introduced by
getProxy uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
88
    {
89 4
        if (isset($_SERVER['no_proxy'])) {
90 1
            $pattern = new Util\NoProxyPattern($_SERVER['no_proxy']);
91 1
            if ($pattern->test($url)) {
92 1
                return null;
93
            }
94
        }
95
96
        // @see https://httpoxy.org/
97 4
        if (!defined('PHP_SAPI') || PHP_SAPI !== 'cli') {
98
            return null;
99
        }
100
101 4
        foreach (array('https', 'http') as $scheme) {
102 4
            if ($this->scheme === $scheme) {
103 4
                $label = $scheme . '_proxy';
104 4
                foreach (array(strtoupper($label), $label) as $l) {
105 4
                    if (isset($_SERVER[$l])) {
106 4
                        return $_SERVER[$l];
107
                    }
108
                }
109
            }
110
        }
111 3
        return null;
112
    }
113
114
    /**
115
     * @param $io
116
     * @param bool $useRedirector
117
     * @param $githubDomains
118
     * @param $gitlabDomains
119
     */
120 6
    protected function setupAuthentication(IO\IOInterface $io, $useRedirector, array $githubDomains, array $gitlabDomains)
121
    {
122 6
        if (preg_match('/\.github\.com$/', $this->host)) {
123 1
            $authKey = 'github.com';
124 1
            if ($useRedirector) {
125 1
                if ($this->host === 'api.github.com' && preg_match('%^/repos(/[^/]+/[^/]+/)zipball(.+)$%', $this->path, $_)) {
126 1
                    $this->host = 'codeload.github.com';
127 1
                    $this->path = $_[1] . 'legacy.zip' . $_[2];
128
                }
129
            }
130
        } else {
131 5
            $authKey = $this->host;
132
        }
133 6
        if (!$io->hasAuthentication($authKey)) {
134 4
            if ($this->user || $this->pass) {
135 1
                $io->setAuthentication($authKey, $this->user, $this->pass);
136
            } else {
137 3
                return;
138
            }
139
        }
140
141 3
        $auth = $io->getAuthentication($authKey);
142
143
        // is github
144 3
        if (in_array($authKey, $githubDomains) && 'x-oauth-basic' === $auth['password']) {
145 1
            $this->addParam('access_token', $auth['username']);
146 1
            $this->user = $this->pass = null;
147 1
            return;
148
        }
149
        // is gitlab
150 2
        if (in_array($authKey, $gitlabDomains)) {
151 1 View Code Duplication
            if ('oauth2' === $auth['password']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
152 1
                $this->addHeader('authorization', 'Bearer ' . $auth['username']);
153 1
                $this->user = $this->pass = null;
154 1
                return;
155
            }
156 View Code Duplication
            if ('private-token' === $auth['password']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
157
                $this->addHeader('PRIVATE-TOKEN', $auth['username']);
158
                $this->user = $this->pass = null;
159
                return;
160
            }
161
        }
162
163
        // others, includes bitbucket
164 1
        $this->user = $auth['username'];
165 1
        $this->pass = $auth['password'];
166 1
    }
167
168
    /**
169
     * @return array
170
     */
171 4
    public function getCurlOptions()
172
    {
173 4
        $headers = array();
174 4
        foreach ($this->headers as $key => $val) {
175 1
            $headers[] = strtr(ucwords(strtr($key, '-', ' ')), ' ', '-') . ': ' . $val;
176
        }
177
178 4
        $url = $this->getURL();
179
180
        $curlOpts = array(
181 4
            CURLOPT_URL => $url,
182 4
            CURLOPT_HTTPHEADER => $headers,
183 4
            CURLOPT_USERAGENT => ConfigFacade::getUserAgent(),
184
            //CURLOPT_VERBOSE => true, //for debug
185
        );
186 4
        $curlOpts += static::$defaultCurlOptions;
187
188
        // @codeCoverageIgnoreStart
189
        if ($ciphers = $this->nssCiphers()) {
190
            $curlOpts[CURLOPT_SSL_CIPHER_LIST] = $ciphers;
191
        }
192
        // @codeCoverageIgnoreEnd
193 4
        if ($proxy = $this->getProxy($url)) {
194 1
            $curlOpts[CURLOPT_PROXY] = $proxy;
195
        }
196 4
        if ($this->capath) {
197 1
            $curlOpts[CURLOPT_CAPATH] = $this->capath;
198
        }
199 4
        if ($this->cafile) {
200 1
            $curlOpts[CURLOPT_CAINFO] = $this->cafile;
201
        }
202
203
        // TODO replace with a proper http2 server side feature detect
204 4
        $h2ServerSupported = false;
205
        $hostsWhichSupportHttp2 = array(
206 4
            "gitlab.com",
207
            "packagist.org",
208
            "repo.packagist.org"
209
        );
210 4
        foreach($hostsWhichSupportHttp2 as $http2Host) {
211
            // http2 requires https
212 4
            if (preg_match('{^https://'. preg_quote($http2Host) .'}i', $url)) {
213 1
                $h2ServerSupported = true;
214 4
                break;
215
            }
216
        }
217
218
        // feature detect http2 support in the php client/curl version.
219
        // e.g. codeload.github.com does not yet support http2 though :-/
220 4
        $h2ClientSupported = curl_version()["features"] & CURL_VERSION_HTTP2 !== 0;
221
222 4
        var_dump("checking url..". $url);
0 ignored issues
show
Security Debugging Code introduced by
var_dump('checking url..' . $url); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
223 4
        if ($h2ClientSupported) {
224 4
            var_dump("client supports http2\n");
225
        }
226 4
        if ($h2ServerSupported) {
227 1
            var_dump("server supports http2\n");
228
        }
229
230 4
        if ($h2ServerSupported && $h2ClientSupported) {
231 1
            $curlOpts[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_2_0;
232 1
            var_dump("using http2\n");
233
        }
234
235
236 4
        return $curlOpts;
237
    }
238
239
    /**
240
     * @return string
241
     */
242 7
    public function getURL()
243
    {
244 7
        $url = self::ifOr($this->scheme, '', '://');
245 7
        if ($this->user) {
246 1
            $user = $this->user;
247 1
            $user .= self::ifOr($this->pass, ':');
248 1
            $url .= $user . '@';
249
        }
250 7
        $url .= self::ifOr($this->host);
251 7
        $url .= self::ifOr($this->port, ':');
252 7
        $url .= self::ifOr($this->path);
253 7
        $url .= self::ifOr(http_build_query($this->query), '?');
254 7
        return $url;
255
    }
256
257
    /**
258
     * @return string user/pass/access_token masked url
259
     */
260 1 View Code Duplication
    public function getMaskedURL()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
261
    {
262 1
        $url = self::ifOr($this->scheme, '', '://');
263 1
        $url .= self::ifOr($this->host);
264 1
        $url .= self::ifOr($this->port, ':');
265 1
        $url .= self::ifOr($this->path);
266 1
        return $url;
267
    }
268
269
    /**
270
     * @return string
271
     */
272 2 View Code Duplication
    public function getOriginURL()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
273
    {
274 2
        $url = self::ifOr($this->scheme, '', '://');
275 2
        $url .= self::ifOr($this->host);
276 2
        $url .= self::ifOr($this->port, ':');
277 2
        return $url;
278
    }
279
280 9
    private static function ifOr($str, $pre = '', $post = '')
281
    {
282 9
        if ($str) {
283 9
            return $pre . $str . $post;
284
        }
285 7
        return '';
286
    }
287
288
    /**
289
     * @param string $url
290
     */
291 11
    public function setURL($url)
292
    {
293 11
        $struct = parse_url($url);
294 11
        foreach ($struct as $key => $val) {
0 ignored issues
show
Bug introduced by
The expression $struct of type array<string,string>|false is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
295 11
            if ($key === 'query') {
296 4
                parse_str($val, $this->query);
297
            } else {
298 11
                $this->$key = $val;
299
            }
300
        }
301 11
    }
302
303 1
    public function addParam($key, $val)
304
    {
305 1
        $this->query[$key] = $val;
306 1
    }
307
308 1
    public function addHeader($key, $val)
309
    {
310 1
        $this->headers[strtolower($key)] = $val;
311 1
    }
312
313 7
    public function setCA($path = null, $file = null)
314
    {
315 7
        $this->capath = $path;
316 7
        $this->cafile = $file;
317 7
    }
318
319 1
    public function isHTTP()
320
    {
321 1
        return $this->scheme === 'http' || $this->scheme === 'https';
322
    }
323
}
324