forked from MISP/MISP
/
HttpSocketExtended.php
223 lines (198 loc) · 6.19 KB
/
HttpSocketExtended.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
<?php
App::uses('HttpSocketResponse', 'Network/Http');
App::uses('HttpSocket', 'Network/Http');
class HttpSocketHttpException extends Exception
{
/** @var HttpSocketResponseExtended */
private $response;
/** @var string|null */
private $url;
/**
* @param HttpSocketResponseExtended $response
* @param string|null $url
*/
public function __construct(HttpSocketResponseExtended $response, $url = null)
{
$this->response = $response;
$this->url = $url;
$message = "Remote server returns HTTP error code $response->code";
if ($url) {
$message .= " for URL $url";
}
if ($response->body) {
$message .= ': ' . substr($response->body, 0, 100);
}
parent::__construct($message, (int)$response->code);
}
/**
* @return HttpSocketResponseExtended
*/
public function getResponse()
{
return $this->response;
}
/**
* Request URL
* @return string|null
*/
public function getUrl()
{
return $this->url;
}
}
class HttpSocketJsonException extends Exception
{
/** @var HttpSocketResponseExtended */
private $response;
public function __construct($message, HttpSocketResponseExtended $response, Throwable $previous = null)
{
$this->response = $response;
parent::__construct($message, 0, $previous);
}
/**
* @return HttpSocketResponseExtended
*/
public function getResponse()
{
return $this->response;
}
}
class HttpSocketResponseExtended extends HttpSocketResponse
{
/**
* @return bool
*/
public function isNotModified()
{
return $this->code == 304;
}
/**
* @param string $message
* @throws SocketException
*/
public function parseResponse($message)
{
parent::parseResponse($message);
if ($this->body === '') {
return; // skip decoding body if is empty
}
$contentEncoding = $this->getHeader('Content-Encoding');
if ($contentEncoding === 'gzip' && function_exists('gzdecode')) {
$this->body = gzdecode($this->body);
if ($this->body === false) {
throw new SocketException("Response should be gzip encoded, but gzip decoding failed.");
}
} else if ($contentEncoding === 'br' && function_exists('brotli_uncompress')) {
$this->body = brotli_uncompress($this->body);
if ($this->body === false) {
throw new SocketException("Response should be brotli encoded, but brotli decoding failed.");
}
} else if ($contentEncoding) {
throw new SocketException("Remote server returns unsupported content encoding '$contentEncoding'.");
}
}
/**
* Decodes JSON string and throws exception if string is not valid JSON.
*
* @return array
* @throws HttpSocketJsonException
*/
public function json()
{
if (strlen($this->body) === 0) {
throw new HttpSocketJsonException('Could not parse empty response as JSON.', $this);
}
try {
return JsonTool::decode($this->body);
} catch (Exception $e) {
$contentType = $this->getHeader('content-type');
throw new HttpSocketJsonException("Could not parse HTTP response as JSON. Received Content-Type $contentType.", $this, $e);
}
}
}
/**
* Supports response compression and also decodes response as JSON
* @method HttpSocketResponseExtended get($uri = null, $query = array(), $request = array())
* @method HttpSocketResponseExtended post($uri = null, $data = array(), $request = array())
* @method HttpSocketResponseExtended head($uri = null, $query = array(), $request = array())
*/
class HttpSocketExtended extends HttpSocket
{
public $responseClass = 'HttpSocketResponseExtended';
/** @var callable */
private $onConnect;
public function __construct($config = array())
{
parent::__construct($config);
if (isset($config['compress']) && $config['compress']) {
$acceptEncoding = $this->acceptedEncodings();
if (!empty($acceptEncoding)) {
$this->config['request']['header']['Accept-Encoding'] = implode(', ', $this->acceptedEncodings());
}
}
}
public function connect()
{
$connected = parent::connect();
if ($this->onConnect) {
$handler = $this->onConnect;
$handler($this);
}
return $connected;
}
/**
* Set callback method, that will be called after connection to remote server is established.
* @param callable $callback
* @return void
*/
public function onConnectHandler(callable $callback)
{
$this->onConnect = $callback;
}
/**
* @return array|null
*/
public function getMetaData()
{
if ($this->connection) {
return stream_get_meta_data($this->connection);
}
return null;
}
/**
* @param array $request
* @return HttpSocketResponseExtended
*/
public function request($request = array())
{
// Reset last error
$this->lastError = [];
/** @var HttpSocketResponseExtended $response */
$response = parent::request($request);
if ($response === false) {
throw new InvalidArgumentException("Invalid argument provided.");
}
// Convert connection timeout to SocketException
if (!empty($this->lastError)) {
throw new SocketException($this->lastError['str']);
}
return $response;
}
/**
* Returns accepted content encodings (compression algorithms)
* @return string[]
*/
private function acceptedEncodings()
{
$supportedEncoding = [];
// Enable brotli compressed responses if PHP has 'brotli_uncompress' method
if (function_exists('brotli_uncompress')) {
$supportedEncoding[] = 'br';
}
// Enable gzipped responses if PHP has 'gzdecode' method
if (function_exists('gzdecode')) {
$supportedEncoding[] = 'gzip';
}
return $supportedEncoding;
}
}