-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.php
More file actions
260 lines (231 loc) · 9.79 KB
/
Copy pathindex.php
File metadata and controls
260 lines (231 loc) · 9.79 KB
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
<?php
/**
* m65filehost — plain-HTTP mirror / parser for https://files.mega65.org
*
* Any path/query on this host is proxied 1:1 to the pinned upstream host.
* Text responses (JSON/HTML/CSS/JS) are rewritten so every referenced URL
* points back at this mirror, letting HTTP-only clients (e.g. MEGA65
* ethernet firmware) fetch files.mega65.org content without TLS.
*
* Binary files stream through byte-for-byte; Range requests pass through.
*/
error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE);
const UPSTREAM_HOST = 'files.mega65.org';
const UPSTREAM_BASE = 'https://files.mega65.org';
const MAX_REDIRECTS = 5;
const MAX_TEXT_REWRITE_BYTES = 8388608;
if (!function_exists('curl_init')) {
http_response_code(500);
header('Content-Type: text/plain; charset=utf-8');
header('Cache-Control: no-store');
exit("m65filehost: the PHP cURL extension is required.\n");
}
// ---- Mirror base (scheme + host the client actually used) ----------------
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] !== ''
? $_SERVER['HTTP_HOST'] : 'm65filehost.twistedpair.se';
$base = $scheme . '://' . $host;
// ---- Request details -----------------------------------------------------
$path = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
if (preg_match('~^https?://~i', $path)) {
$path = '/' . preg_replace('~^https?://[^/]*~i', '', $path);
}
$method = isset($_SERVER['REQUEST_METHOD']) ? strtoupper($_SERVER['REQUEST_METHOD']) : 'GET';
$reqBody = file_get_contents('php://input');
set_time_limit(0);
// ---- Client request headers worth forwarding ------------------------------
$reqHeaders = array();
if (isset($_SERVER['HTTP_RANGE'])) $reqHeaders[] = 'Range: ' . $_SERVER['HTTP_RANGE'];
if (isset($_SERVER['HTTP_IF_RANGE'])) $reqHeaders[] = 'If-Range: ' . $_SERVER['HTTP_IF_RANGE'];
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']))$reqHeaders[] = 'If-Modified-Since: ' . $_SERVER['HTTP_IF_MODIFIED_SINCE'];
if (isset($_SERVER['HTTP_IF_NONE_MATCH'])) $reqHeaders[] = 'If-None-Match: ' . $_SERVER['HTTP_IF_NONE_MATCH'];
if (isset($_SERVER['HTTP_CONTENT_TYPE'])) $reqHeaders[] = 'Content-Type: ' . $_SERVER['HTTP_CONTENT_TYPE'];
if (isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] !== '')
$reqHeaders[] = 'User-Agent: ' . $_SERVER['HTTP_USER_AGENT'];
$reqHeaders[] = 'Accept-Encoding: identity'; // keep bodies uncompressed so rewriting stays valid
// Response headers we never relay (hop-by-hop, re-derived, or irrelevant).
$skipHeaders = array(
'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
'te', 'trailer', 'transfer-encoding', 'upgrade',
'content-length', 'content-encoding', 'cache-control', 'expires', 'pragma',
'set-cookie', 'x-powered-by', 'status',
);
function resolveLocation($url, $loc)
{
if (preg_match('~^https?://~i', $loc)) return $loc;
if ($loc === '' || $loc[0] === '#') return $url;
if ($loc[0] === '/') return $loc;
$parts = parse_url($url);
$scheme = isset($parts['scheme']) ? $parts['scheme'] : 'http';
$hostP = isset($parts['host']) ? $parts['host'] : '';
$dir = '/';
if (isset($parts['path']) && ($p = $parts['path']) !== '') {
$pos = strrpos($p, '/');
$dir = ($pos === false) ? '/' : substr($p, 0, $pos + 1);
}
return $scheme . '://' . $hostP . $dir . $loc;
}
function rewriteText($body, $base, $rewriteRelative)
{
// Absolute upstream URLs must always point back at this mirror.
if (strpos($body, UPSTREAM_BASE) !== false) {
$body = str_replace(UPSTREAM_BASE, $base, $body);
}
// Relative "../" refs are only rewritten for page-level documents (all
// filehost pages live in /html/ so "../" == site root). CSS/JS keep their
// own "../" untouched: they are served from the same paths on the mirror,
// so they resolve identically client-side.
if ($rewriteRelative) {
if (strpos($body, '../') !== false) {
$body = str_replace('../', $base . '/', $body); // HTML refs
}
if (strpos($body, '..\\/') !== false) {
$body = str_replace('..\\/', $base . '/', $body); // JSON-escaped "../files/..."
}
}
return $body;
}
// ---- Upstream fetch with manual, host-pinned redirect handling -----------
$url = UPSTREAM_BASE . $path;
$respCode = 0;
$respHeaders = array();
$tmp = null;
for ($hop = 0; $hop <= MAX_REDIRECTS; $hop++) {
if ($tmp) fclose($tmp);
$tmp = fopen('php://temp/maxmemory:2097152', 'w+b');
if ($tmp === false) {
http_response_code(500);
header('Content-Type: text/plain; charset=utf-8');
exit("m65filehost: could not create temp stream.\n");
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
if (defined('CURLOPT_PROTOCOLS_STR')) {
curl_setopt($ch, CURLOPT_PROTOCOLS_STR, 'http,https');
} else {
curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
}
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
curl_setopt($ch, CURLOPT_TIMEOUT, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
if ($reqHeaders) curl_setopt($ch, CURLOPT_HTTPHEADER, $reqHeaders);
$curHeaders = array();
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($curl, $line) use (&$curHeaders) {
$curHeaders[] = rtrim($line);
return strlen($line);
});
$tmpRef = $tmp;
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($curl, $data) use ($tmpRef) {
fwrite($tmpRef, $data);
return strlen($data);
});
if ($method === 'HEAD') {
curl_setopt($ch, CURLOPT_NOBODY, true);
} elseif ($method === 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $reqBody);
} elseif ($method === 'GET') {
curl_setopt($ch, CURLOPT_HTTPGET, true);
} else {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
if ($reqBody !== '') curl_setopt($ch, CURLOPT_POSTFIELDS, $reqBody);
}
curl_exec($ch);
$err = curl_error($ch);
$code = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
if ($err !== '') {
http_response_code(502);
header('Content-Type: text/plain; charset=utf-8');
header('Cache-Control: no-store');
exit("m65filehost: upstream fetch failed: {$err}\n");
}
$loc = '';
foreach ($curHeaders as $h) {
if (stripos($h, 'Location:') === 0) { $loc = trim(substr($h, 9)); break; }
}
$isRedirect = ($code >= 300 && $code < 400 && $loc !== '');
if ($isRedirect && $hop < MAX_REDIRECTS) {
$abs = resolveLocation($url, $loc);
$parts = parse_url($abs);
$rh = isset($parts['host']) ? strtolower($parts['host']) : '';
if ($rh !== UPSTREAM_HOST) {
break; // external redirect: relay it (Location rewritten below)
}
if ($code === 301 || $code === 302 || $code === 303) {
$method = 'GET';
$reqBody = '';
}
$url = $abs;
continue;
}
$respCode = $code;
$respHeaders = $curHeaders;
break;
}
// ---- Build response headers to relay -------------------------------------
$respType = '';
$upLen = '';
$forward = array();
foreach ($respHeaders as $line) {
if (strpos($line, 'HTTP/') === 0) continue;
$colon = strpos($line, ':');
if ($colon === false) continue;
$name = strtolower(trim(substr($line, 0, $colon)));
$val = trim(substr($line, $colon + 1));
if ($name === 'content-length') { $upLen = $val; continue; }
if (in_array($name, $skipHeaders)) continue;
if ($name === 'content-type') { $respType = $val; }
if ($name === 'location') {
$val = str_replace(UPSTREAM_BASE, $base, $val);
}
if (!array_key_exists($name, $forward)) $forward[$name] = $val;
}
$httpCode = $respCode !== 0 ? $respCode : 502;
http_response_code($httpCode);
if (strpos($path, '/files/') === 0) {
header('Cache-Control: public, max-age=600');
} elseif (strpos($path, '/php/') === 0) {
header('Cache-Control: no-store');
} else {
header('Cache-Control: no-cache');
}
foreach ($forward as $name => $val) {
header($name . ': ' . $val);
}
// Upstream sends no Content-Type for raw files (.d81/.crt etc.). Emit
// octet-stream so Apache/Varnish don't default downloads to text/html.
if ($respType === '') {
header('Content-Type: application/octet-stream');
}
// Relative "../" rewriting only for page-level documents, never CSS/JS
// (those are served from identical paths, so their refs resolve client-side).
$ctype = strtolower(trim(strtok($respType, ';')));
$rewriteRelative = ($ctype === 'text/html' || strpos($ctype, 'json') !== false);
$parseMode = $rewriteRelative
&& $httpCode >= 200 && $httpCode < 300
&& ($upLen === '' || (int) $upLen <= MAX_TEXT_REWRITE_BYTES);
// ---- Emit body ------------------------------------------------------------
if ($httpCode >= 400) {
rewind($tmp);
$body = stream_get_contents($tmp);
header('Content-Length: ' . strlen($body));
if ($method !== 'HEAD' && $body !== '') echo $body;
} elseif ($method === 'HEAD') {
if ($upLen !== '') header('Content-Length: ' . $upLen);
} elseif ($parseMode) {
rewind($tmp);
$body = stream_get_contents($tmp);
$body = rewriteText($body, $base, $rewriteRelative);
header('Content-Length: ' . strlen($body));
echo $body;
} else {
if ($upLen !== '') header('Content-Length: ' . $upLen);
rewind($tmp);
fpassthru($tmp);
}
fclose($tmp);