caterpillar/index.php

69 lines
2.2 KiB
PHP
Raw Normal View History

2022-10-05 17:20:02 +00:00
<?php
// HTTP proxy implementation with PHP socket
2022-10-05 17:27:51 +00:00
// Namhyeon Go <gnh1201@gmail.com>
2022-10-07 04:55:07 +00:00
// Created at: 2022-10-06
2022-11-25 10:32:17 +00:00
// Updated at: 2022-11-25
2022-10-05 17:20:02 +00:00
2022-11-25 12:37:34 +00:00
define("PHP_HTTPPROXY_VERSION", "0.1.3");
2022-10-07 04:48:58 +00:00
if (strpos($_SERVER['HTTP_USER_AGENT'], "php-httpproxy/") !== 0) {
2022-11-25 13:19:31 +00:00
exit('<!DOCTYPE html><html><head><title>It works!</title><meta charset="utf-8"></head><body><h1>It works!</h1><p><a href="https://github.com/gnh1201/php-httpproxy">Download the client</a></p><hr><p>php-httpproxy/' . PHP_HTTPPROXY_VERSION . ' (Server; PHP ' . phpversion() . '; abuse@catswords.net)</p></body></html>');
2022-10-07 04:48:58 +00:00
}
2022-10-05 17:25:44 +00:00
ini_set("default_socket_timeout", 1); // must be. because of `feof()` works
2022-10-06 03:40:40 +00:00
ini_set("max_execution_time", 0);
2022-10-05 17:20:02 +00:00
2022-10-06 12:03:05 +00:00
function parse_headers($str) { // Parses HTTP headers into an array
2022-10-06 12:48:49 +00:00
// https://stackoverflow.com/questions/16934409/curl-as-proxy-deal-with-https-connect-method
// https://stackoverflow.com/questions/12433958/how-to-parse-response-headers-in-php
2022-10-06 12:03:05 +00:00
$headers = array();
2022-10-05 17:20:02 +00:00
2022-10-06 12:03:05 +00:00
$lines = preg_split("'\r?\n'", $str);
2022-10-06 02:05:59 +00:00
2022-10-06 12:03:05 +00:00
$first_line = array_shift($lines);
$headers['@method'] = explode(' ', $first_line);
2022-10-06 02:39:40 +00:00
2022-10-06 12:03:05 +00:00
foreach ($lines as $line) {
if (!preg_match('/^([^:]+):(.*)$/', $line, $out)) continue;
$headers[$out[1]] = trim($out[2]);
}
2022-10-05 17:20:02 +00:00
2022-10-06 12:03:05 +00:00
return $headers;
}
2022-10-05 17:20:02 +00:00
2022-10-06 12:03:05 +00:00
$data = json_decode(file_get_contents('php://input'), true);
$buffer_size = $data['chunksize'];
2022-10-05 17:20:02 +00:00
2022-10-06 12:03:05 +00:00
$relay_data = base64_decode($data['data']);
$relay_headers = parse_headers($relay_data);
$relay_port = intval($data['port']);
$relay_scheme = $data['scheme'];
$relay_hostname = $data['server'];
2022-11-25 10:32:17 +00:00
if ($relay_scheme == "https") {
$relay_hostname = "tls://" . $relay_hostname;
}
2022-10-06 12:03:05 +00:00
switch ($relay_headers['@method'][0]) {
2022-11-25 10:32:17 +00:00
case "CONNECT":
2022-10-06 12:03:05 +00:00
echo sprintf("%s 200 Connection Established\r\n\r\n", $relay_headers['@method'][2]);
break;
2022-11-25 10:32:17 +00:00
default:
2022-10-06 12:03:05 +00:00
$fp = fsockopen($relay_hostname, $relay_port, $errno, $errstr, 1);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
fwrite($fp, $relay_data);
$buf = null;
while (!feof($fp) && $buf !== false) {
$buf = fgets($fp, $buffer_size);
echo $buf;
}
fclose($fp);
}
2022-11-25 10:32:17 +00:00
}