Advertisement
Guest User

Untitled

a guest
Feb 13th, 2012
300
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 10.23 KB | None | 0 0
  1. <?php
  2.  
  3. // To run this proxy as a stand-alone script, edit the options below to the appropriate values ( as-is they use the RePress Wordpress options )
  4. // You should normally NOT have to change any of these values
  5.  
  6. /** -- options -- **/
  7.  
  8. $rewritebase = repress_make_rewrite_base();
  9. $remoteservers = json_decode( get_option('repress_remoteservers'), TRUE );
  10. $agentstring = "RePress plugin/" . plugin_get_version() . " (PHP " . phpversion() . " streamer) - please read https://all4xs.net";
  11. if (get_option('repress_push_post') == 'yes') {
  12.     $doPosts = true;
  13. } else {
  14.     $doPosts = false;
  15. }
  16. if (get_option('repress_push_cookie') == 'yes') {
  17.     $doCookies = true;
  18. } else {
  19.     $doCookies = false;
  20. }
  21. if (get_option('repress_secret') !== '') {
  22.     $secret = get_option('repress_secret');
  23. } else {
  24.     $secret = 'repress';        // make something up if you want to support hashed cookies
  25. }
  26. $acceptCookies = array ( '' );
  27.  
  28. $GLOBALS['proxydebug'] = false;     // debugging? will dump all output to flat file.
  29. error_reporting(E_NONE);
  30.  
  31. /** -- end of options -- **/
  32.  
  33.  
  34. /*** Proxy code begins here. ***/
  35.  
  36.  
  37. // Include dependencies
  38.  
  39. // proxyhelp requirement
  40. require_once('proxyhelp/proxify_html_resource.php');
  41. // domain functions
  42. require_once('domains.php');
  43.  
  44. // Attempt to destroy cookies above RePress base
  45.  
  46. require_once("emptycookieredirect.php");
  47.  
  48. /* Process request */
  49.  
  50. logline("Proxy intercepted request: " . $_SERVER['REQUEST_URI']);
  51.  
  52. $hit = false; $extra = ''; $remoteserver = ''; $abbreviation = ''; $text = false;
  53.  
  54. $len = strlen($rewritebase);
  55. if (strncmp($_SERVER['REQUEST_URI'], $rewritebase, $len) == 0) {
  56.  
  57.     logline("$rewritebase/ in url. Seems promising at first sight.");
  58.  
  59.     // strip repress/ part
  60.  
  61.     if (preg_match("/#/", $rewritebase)) { continue; }
  62.     $strippedRepress = preg_replace("#^" . $rewritebase . "[\/]?#", "", $_SERVER['REQUEST_URI']);
  63.  
  64.     // strip everything after first slash
  65.  
  66.     $stripped = preg_replace("/\/.*$/", "", $strippedRepress);
  67.  
  68.     // domain name should be left over
  69.  
  70.     // generic domain name validation regular expression
  71.  
  72.     /** Possible hit. Is the domain one we proxy? **/
  73.  
  74.     // split into subdomains
  75.     $subdomains = explode('.', $stripped);
  76.  
  77.     $illegalPart = false;
  78.  
  79.     foreach ($subdomains as $subdom) {
  80.         if (!is_legal_domain_part($subdom)) {
  81.             logline("ILLEGAL DOMAIN PART $subdom");
  82.             $illegalPart = true;
  83.             break;
  84.         }
  85.     }
  86.  
  87.     if (!$illegalPart) {
  88.  
  89.         foreach ($remoteservers as $hostname) {
  90.  
  91.             // future work: support hash matching in URLs instead of hostnames.
  92.             logline("$hostname -> match checking");
  93.  
  94.             // split the proxied domain into subdomains
  95.             $proxiedSubdomains = explode('.', $hostname);
  96.             $numParts = count($proxiedSubdomains);
  97.  
  98.             $okMatch = true;
  99.  
  100.             if ($numParts > count($subdomains)) {
  101.                 logline("no match: subdomains count of request is less");
  102.                 $okMatch = false;
  103.             } else {
  104.  
  105.                 for ($i = $numParts - 1, $b = count($subdomains) - 1; $i >= 0; $i--,$b--) {
  106.                     if ($proxiedSubdomains[$i] !== $subdomains[$b]) {
  107.                         logline("proxied domain subpart " . $proxiedSubdomains[$i] . " does not match " . $subdomains[$b]);
  108.                         $okMatch = false;
  109.                         break;
  110.                     } else {
  111.                         logline("proxied domain subpart " . $proxiedSubdomains[$i] . " MATCHES " . $subdomains[$b]);
  112.                     }
  113.                 }
  114.  
  115.             }
  116.  
  117.             if ($okMatch) {
  118.                 $hit = true; $remoteserver = $stripped; $abbreviation = $hostname;
  119.  
  120.                 logline("looking for something extra");
  121.  
  122.                 // now strippedRepress looks something like: wikileaks.org[/][....]
  123.  
  124.                 // if no slashes, no extra
  125.                 if (strpos($strippedRepress,'/') == FALSE) {
  126.                     $extra = '';
  127.                 } else {
  128.                     // extra is everything after the first slash
  129.                     $extra = preg_replace("/^.*?\//", "", $strippedRepress);
  130.                 }
  131.  
  132.             }
  133.  
  134.         }
  135.  
  136.     }
  137.  
  138.  
  139.     if ($hit == false) {
  140.         header('HTTP/1.0 404 Not Found');
  141.         exit;       // close, but no cigar.
  142.     }
  143. }
  144.  
  145. if ($hit) {
  146.  
  147.     // try to protect against XSS attacks on Wordpress sessions if running as plugin
  148.     if (function_exists('repress_logout_wordpress_user')) {
  149.         repress_logout_wordpress_user();
  150.     }
  151.  
  152.     // determine net link by stripping the ?GET parameters
  153.     $fopenLink = preg_replace("/\?.*$/", "", "http://$remoteserver/$extra");
  154.  
  155.     logline("Interpreted! hit as follows:");
  156.     logline("Remoteserver = $remoteserver, abbreviation = $abbreviation, extra = $extra and net open link is http://$remoteserver/$extra");
  157.  
  158.     // do we do a POST?
  159.  
  160.     if ($doPosts && is_array($_POST) && count($_POST) > 0) {
  161.         $requestType = 'POST';
  162.     } else {
  163.         $requestType = 'GET';
  164.     }
  165.  
  166.     // do we do cookies?
  167.  
  168.     $cookieHeaders = '';
  169.  
  170.     if ($doCookies && is_array($_COOKIE) && count($_COOKIE) > 0) {
  171.         foreach ($_COOKIE as $name => $val) {
  172.             $encodeName = rawurlencode($name);
  173.             $encodeVal = rawurlencode($val);
  174.             $cookieHeaders .= "Cookie: $encodeName=$encodeVal\r\n";
  175.         }
  176.     }
  177.  
  178.     /* Establish streaming connection to the remote server */
  179.  
  180.     if ($requestType == 'GET') {
  181.         $streamOptions = array(
  182.                       'http'=>array(
  183.                                   'method'=>"GET",
  184.                           'host'=>$remoteserver,
  185.                           'user_agent'=>$agentstring,
  186.                           'header'=>$cookieHeaders
  187.                            )
  188.                       );
  189.     } else {
  190.         $postData = http_build_query($_POST);
  191.  
  192.         $streamOptions = array(
  193.                       'http'=>array(
  194.                                       'method'=>"POST",
  195.                           'host'=>$remoteserver,
  196.                           'user_agent'=>$agentstring,
  197.                           'header'=>"Content-type: application/x-www-form-urlencoded\r\n" .
  198.                                     "Content-Length: " . strlen($postData) . "\r\n" .
  199.                                 $cookieHeaders,
  200.                           'content'=>$postData
  201.                            )
  202.                       );
  203.     }
  204.  
  205.     $context = stream_context_create($streamOptions);
  206.     logline("Open to location " . "http://$remoteserver/$extra");
  207.     $handle = fopen("http://$remoteserver/$extra", "rb", false, $context);
  208.     if ($handle == FALSE) {
  209.         if (isset($GLOBALS['proxydebug']) && $GLOBALS['proxydebug']) {
  210.             echo("Proxy error to: http://$remoteserver/$extra");
  211.         }
  212.         exit;
  213.     }
  214.  
  215.     /* Start working on headers */
  216.     $one_byte = fread($handle, 1); // mh_edit this is used to stop the "bug" reported here https://bugs.php.net/bug.php?id=46896 where the responce headers are missing
  217.     $meta = stream_get_meta_data($handle);
  218.     $headerData = $meta['wrapper_data'];
  219.     if(is_array($headerData) && is_array(@$headerData['headers'])) $headerData = $headerData['headers']; // mh_edit this is added to get to the actual response headers into $headerData
  220.  
  221.     if (preg_match("/HTTP.... 30./", $headerData[0])) $redirect = true;
  222.     else {
  223.         $redirect = false;
  224.     }
  225.  
  226.     $i = 0;
  227.     foreach ($headerData as $line) {
  228.         $i++;
  229.  
  230.         if ($i > 1 && preg_match("/^HTTP\/1../", $line)) {
  231.             // no multiple HTTP headers will be replied
  232.             exit;
  233.         }
  234.  
  235.         // make 302 redirects work
  236.         if ($redirect && !preg_match("#$rewritebase#", $line)) {
  237.  
  238.             // a redirect to root is a redirect to main page here
  239.             $line = preg_replace("#^Location: /#", "Location: $rewritebase/$abbreviation/", $line);
  240.  
  241.             // we localize redirects to all known hosts, and subdomains of those hosts
  242.             foreach ($remoteservers as $knownhost) {
  243.                 $knownhostAbbr = $knownhost;            // future work: support hashing
  244.  
  245.                 // an absolute redirect to a main page
  246.                 $line = preg_replace("#^Location: http://$knownhost#", "Location: $rewritebase/$knownhostAbbr", $line);
  247.                 $line = preg_replace("#^Location: http://$knownhost/#", "Location: $rewritebase/$knownhostAbbr", $line);
  248.                 // an absolute redirect to a lower page
  249.                 $line = preg_replace("#^Location: http://$knownhost/(.*)$#", "Location: $rewritebase/$knownhostAbbr/$1", $line);
  250.  
  251.                 // Support subdomains
  252.  
  253.                 // an absolute redirect to a main page
  254.                 $line = preg_replace("#^Location: http://(.*?)\.$knownhost#", "Location: $rewritebase/$1.$knownhostAbbr", $line);
  255.                 $line = preg_replace("#^Location: http://(.*?)\.$knownhost/#", "Location: $rewritebase/$1.$knownhostAbbr", $line);
  256.                 // an absolute redirect to a lower page
  257.                 $line = preg_replace("#^Location: http://(.*?)\.$knownhost/(.*)$#", "Location: $rewritebase/$1.$knownhostAbbr/$2", $line);
  258.  
  259.             }
  260.         }
  261.  
  262.         // cookie handling
  263.         if (preg_match("/^Set-Cookie: /i", $line)) {
  264.  
  265.             if ($doCookies == false) {
  266.  
  267.                 continue;
  268.  
  269.             }
  270.  
  271.             logline("Found cookie header $line");
  272.  
  273.             // rewrite cookie paths
  274.  
  275.             if (preg_match("#; path=([^;]*)#", $line, $matches)) {
  276.  
  277.                 $pathNow = $matches[1];
  278.  
  279.                 logline("Cookie path found $pathNow");
  280.  
  281.                 if (preg_match("/^/", $pathNow)) {
  282.  
  283.                     $pathNew = "$rewritebase/$abbreviation" . $pathNow;
  284.                     $line = preg_replace("#; path=([^;]*)#", "; path=$pathNew", $line);
  285.  
  286.                     logline("Insecure path. Setting to $pathNew");
  287.                 }
  288.             }
  289.  
  290.         }
  291.  
  292.         // get content type
  293.         if (preg_match("/^Content-Type: text\/.*$/i", $line)) {
  294.             $text = true;
  295.         }
  296.  
  297.         // ignore robots header. we have our own
  298.  
  299.         if (preg_match("/^X-Robots-Tag: /i", $line)) {
  300.             continue;
  301.         }
  302.  
  303.         // pass through headers
  304.  
  305.         logline("Give header: $line");
  306.         header($line);
  307.  
  308.     }
  309.  
  310.     // After a 30x relocation response, exit immediatly
  311.     if ($redirect) {
  312.         logline("EXIT because relocate");
  313.         exit;
  314.     }
  315.  
  316.     // add no robots header
  317.     header("X-Robots-Tag: noindex, nofollow", true);
  318.  
  319.     if ($text) {
  320.  
  321.         /* Read text page and close handle */
  322.         $contents = $one_byte . stream_get_contents($handle); // mh_edit add the one byte read already to $contents
  323.         fclose($handle);
  324.  
  325.     } else {
  326.  
  327.         /* Pass through binary content or non-parsed content */
  328.         echo $one_byte; // mh_edit add the one byte read already to the output stream
  329.         $size = fpassthru($handle)+1; // mh_edit add the one byte read already to the size of the data read
  330.         fclose($handle);
  331.         register_bandwidth_usage($size);
  332.         exit;
  333.  
  334.     }
  335.  
  336.     // Proxy rewrite resource
  337.  
  338.     proxyhelp_init_for_repress($rewritebase, $abbreviation, $remoteservers);
  339.  
  340.     $contents = proxify_html_resource($contents);
  341.  
  342.     /* Push text. */
  343.  
  344.     $size = strlen($contents);
  345.     register_bandwidth_usage($size);
  346.     echo $contents;
  347.  
  348.     /* Done. */
  349.  
  350.     exit;
  351.  
  352. }
  353.  
  354. function register_bandwidth_usage($size) {
  355.  
  356.     if ( function_exists('repress_register_bandwidth_usage') ) {
  357.         repress_register_bandwidth_usage($size);
  358.     }
  359.  
  360. }
  361.  
  362. /** Log and debug functions **/
  363.  
  364. function logline($line) {
  365.     if (!$GLOBALS['proxydebug']) { return; }
  366.  
  367.     if (!is_link("/tmp/repress.module.debug.log")) {
  368.         $f = fopen("/tmp/repress.module.debug.log", "a");
  369.         fputs($f, $line . "\n");
  370.         fclose($f);
  371.     }
  372. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement