|
9 | 9 |
|
10 | 10 | // Check that we have a URL |
11 | 11 | if( ! $url) |
12 | | - http_response_code(400) and exit("X-Proxy-Url header missing"); |
| 12 | + failure(400, "X-Proxy-Url header missing"); |
13 | 13 |
|
14 | 14 | // Check that the URL looks like an absolute URL |
15 | 15 | if( ! parse_url($url, PHP_URL_SCHEME)) |
16 | | - http_response_code(403) and exit("Not an absolute URL: $url"); |
| 16 | + failure(403, "Not an absolute URL: $url"); |
17 | 17 |
|
18 | 18 | // Check referer hostname |
19 | 19 | if( ! parse_url($headers['Referer'] ?? null, PHP_URL_HOST) == $_SERVER['HTTP_HOST']) |
20 | | - http_response_code(403) and exit("Invalid referer"); |
| 20 | + failure(403, "Invalid referer"); |
21 | 21 |
|
22 | 22 | // Check whitelist, if not empty |
23 | 23 | if( ! array_reduce($whitelist ?? [], 'is_bad', [$url, false])) |
24 | | - http_response_code(403) and exit("Not whitelisted: $url"); |
| 24 | + failure(403, "Not whitelisted: $url"); |
| 25 | + |
25 | 26 |
|
26 | 27 |
|
27 | 28 | // Remove ignored headers and prepare the rest for resending |
|
32 | 33 | foreach($headers as $key => &$value) |
33 | 34 | $value = ucwords($key, '-').": $value"; |
34 | 35 |
|
| 36 | + |
| 37 | + |
35 | 38 | // Init curl |
36 | 39 | $curl = curl_init(); |
37 | 40 | $maxredirs = $opts[CURLOPT_MAXREDIRS] ?? 20; |
|
79 | 82 | if(curl_errno($curl)) |
80 | 83 | switch(curl_errno($curl)) |
81 | 84 | { |
| 85 | + // Connect timeout => Service Unavailable |
82 | 86 | case 7: |
| 87 | + failure(503, $curl); |
| 88 | + |
| 89 | + // Operation timeout => Gateway Timeout |
83 | 90 | case 28: |
84 | | - http_response_code(504); |
| 91 | + failure(504, $curl); |
85 | 92 |
|
| 93 | + // Other errors => Service Unavailable |
86 | 94 | default: |
87 | | - exit(curl_error($curl)); |
| 95 | + failure(503, $curl); |
88 | 96 | } |
89 | 97 |
|
90 | 98 | // HACK: If for any reason redirection doesn't work, do it manually... |
|
93 | 101 | while($url and --$maxredirs > 0); |
94 | 102 |
|
95 | 103 |
|
| 104 | + |
96 | 105 | // Get curl info and close handler |
97 | 106 | $info = curl_getinfo($curl); |
98 | 107 | curl_close($curl); |
99 | 108 |
|
100 | 109 |
|
| 110 | + |
101 | 111 | // Remove any existing headers |
102 | 112 | header_remove(); |
103 | 113 |
|
|
125 | 135 |
|
126 | 136 |
|
127 | 137 |
|
| 138 | +function failure(int $status, $text) |
| 139 | +{ |
| 140 | + if(is_resource($text)) |
| 141 | + $text = curl_error($text); |
| 142 | + http_response_code($status); |
| 143 | + exit($text); |
| 144 | +} |
| 145 | + |
128 | 146 | function is_bad($carry, array $rule): bool |
129 | 147 | { |
130 | 148 | static $url; |
|
0 commit comments