Ejemplo n.º 1
0
 function main()
 {
     global $real_uri, $vhost, $add_errmsg, $pri_err, $query_string;
     static $detable, $detimer;
     $t = time();
     $tmax = access_query("dosevasivetimer", 0) or $tmax = 10;
     $dmax = access_query("dosevasivemaxreqs", 0) or $dmax = 5;
     if ($t > $detimer + $tmax) {
         // Clean table on timer
         $detable = array();
         $detimer = $t;
     }
     if ($detable[$vhost . $real_uri . $query_string] >= $dmax) {
         // Discard request with DosEvasiveError if requested more than DosEvasiveMaxReqs in DocEvasiveTimer seconds
         $e = access_query("dosevasiveerror", 0) or $e = 403;
         $pri_err = $e;
         $add_errmsg = "You are not allowed to request a resource more than <b>" . (int) $dmax . "</b> times in <b>" . (int) $tmax . "</b> seconds.<br><br>";
         if ($bt = access_query("dosevasiveblocktime", 0)) {
             if (strtolower($bt) == "perm") {
                 nw_block_ip_address($GLOBALS["remote_ip"], "PERM", "mod_dosevasive");
             } else {
                 nw_block_ip_address($GLOBALS["remote_ip"], "TEMP", "mod_dosevasive", time() + $bt);
             }
         }
     }
     // Update url table
     $detable[$vhost . $real_uri . $query_string]++;
 }
Ejemplo n.º 2
0
 function main()
 {
     global $http_uri, $docroot, $rq_file, $rq_err, $path_info;
     $this->uri = false;
     if ($this->modtype == "parser_" . trim(access_query("_parseext", "_" . strtolower($rq_file["extension"])))) {
         if (!($f = fopen($docroot . DIRECTORY_SEPARATOR . $http_uri, NW_BSAFE_READ_OPEN))) {
             $rq_err = 500;
         }
         $bin = fread($f, 2048);
         fclose($f);
         if (substr($bin, 0, 20) == "LÀF") {
             $lnk = $this->decode_windows_visual_shortcut($bin);
             $this->uri = $lnk["path"];
             // .$lnk["file"]
         } else {
             list($uri, $uu) = explode("\n", $bin, 2);
             $this->uri = trim($uri);
         }
         #-- change immediately for directories
         if (!strpos($this->uri, "://") && is_dir($this->uri)) {
             $docroot = rtrim($this->uri, "/");
             $http_uri = $path_info;
             $rq_file = pathinfo($uri);
             $path_info = "";
         }
     }
 }
Ejemplo n.º 3
0
 function main()
 {
     global $conf, $pri_err, $pri_redir, $add_errmsg, $pri_redir_code;
     $maxload = (double) access_query("loadlimit", 0);
     $action = access_query("loadlimitaction", 0) or $action = "error";
     $pl = @file("/proc/loadavg");
     $lg = explode(" ", $pl[0]);
     $loadavg = (double) $lg[0];
     if ($loadavg > $maxload) {
         switch ($action) {
             case "redir":
                 $pri_redir = $this->nsv_str_replace(access_query("loadlimitredirect", 0));
                 $pri_redir_code = 307;
                 break;
             case "error":
                 $err = access_query("loadlimiterror", 0) or $err = 503;
                 $pri_err = $err;
                 $msg = access_query("loadlimiterrormessage", 0) or $msg = "Server load is too high (<b>%CUR_LOAD/%MAX_LOAD</b>), try again in a few moments.";
                 $msg = str_replace("%CUR_LOAD", sprintf("%.1f", $loadavg), $msg);
                 $msg = str_replace("%MAX_LOAD", sprintf("%.1f", $maxload), $msg);
                 $add_errmsg = $msg . "<br><br>";
                 break;
         }
     }
 }
Ejemplo n.º 4
0
 function auth($user, $pass, $args)
 {
     $host = access_query("authpgsqlhost", 0);
     $dbuser = access_query("authpgsqluser", 0);
     $dbpass = access_query("authpgsqlpass", 0);
     $dbname = access_query("authpgsqldb", 0);
     $tbname = access_query("authpgsqltable", 0);
     $lname = access_query("authpgsqllogincolumn", 0);
     $pname = access_query("authpgsqlpasscolumn", 0);
     $ps = trim($pass);
     switch (strtolower(access_query("authpgsqlpasstype", 0))) {
         case "md5":
             $pstr = md5($ps);
             break;
         case "plain":
         default:
             $pstr = $ps;
     }
     if (is_callable("pg_connect")) {
         if ($cid = @pg_connect("host={$host} user={$dbuser} password={$dbpass} dbname={$dbname}")) {
             if ($q = @pg_query($cid, "SELECT * FROM {$tbname} WHERE {$lname} = '{$user}' AND {$pname} = '{$pstr}'")) {
                 $r = pg_num_rows($q);
                 pg_free_result($q);
                 $auth = $r > 0;
             } else {
                 techo("WARN: mod_auth_pgsql could not fetch '{$lname}' and '{$pname}' from table '{$tbname}'", NW_EL_WARNING);
             }
         } else {
             techo("WARN: mod_auth_pgsql could not connect to database '{$dbname}@{$host}'", NW_EL_WARNING);
         }
     } else {
         techo("WARN: postgresql extension not built in your PHP binary", NW_EL_WARNING);
     }
     return $auth;
 }
 function options()
 {
     $methods = array();
     foreach (access_query("methodhandler") as $m_h) {
         $methods[] = strtok($method, " ");
     }
     return $methods;
 }
Ejemplo n.º 6
0
 function main()
 {
     global $http_action, $out_add_headers;
     $ml = $http_action == "HEAD" ? $GLOBALS["hlf"] : $GLOBALS["lf"];
     if (is_a($ml, "static_response") && $ml->str && access_query("digestmd5", 0)) {
         $out_add_headers["Content-MD5"] = base64_encode(pack("H*", md5($ml->str)));
     }
 }
 function auth($user, $pass, $args)
 {
     foreach (access_query("authsimpleuserpass") as $asup) {
         $lp = explode(" ", $asup);
         if ($lp[0] == $user && $lp[1] == $pass) {
             $auth = true;
             break;
         }
     }
     return $auth;
 }
 function auth($user, $pass, $args)
 {
     $authfile = file(access_query("authnwauthfilename", 0));
     $authcount = count($authfile);
     for ($a = 1; $a <= $authcount; $a++) {
         $lp = explode(":", trim($authfile[$a]));
         $authdata["users"][$lp[0]]["login"] = $lp[0];
         $authdata["users"][$lp[0]]["des-password"] = $lp[1];
     }
     $hash = $authdata["users"][$user]["des-password"];
     $thash = crypt($pass, substr($hash, 0, 2));
     return $hash === $thash;
 }
 function auth($user, $pass, $args)
 {
     $allowed = array_merge(array("anonymous"), explode(" ", implode(" ", access_query("authanonymousnames"))));
     $r = false;
     if (in_array($user, $allowed) && $this->preg_email($pass)) {
         if (access_query("authanonymoussmtpcheck", 0)) {
             $r = $this->check_email($pass);
         } else {
             $r = true;
         }
     }
     return $r;
 }
 function auth($user, $pass, $args)
 {
     foreach (access_query("authsvnfile") as $asvn) {
         $file = fopen($asvn, "r");
         while (!feof($file)) {
             $lp = explode("=", ereg_replace(" *", "", chop(fgets($file, 4096))));
             if ($lp[0] == $user && $lp[1] == $pass) {
                 $auth = true;
                 break;
             }
         }
     }
     return $auth;
 }
Ejemplo n.º 11
0
 function auth($user, $pass, $args)
 {
     if ($this->ldapless_php) {
         return false;
     } else {
         if ($ldsrvs = access_query("authldapserver")) {
             foreach ($ldsrvs as $ld_srv) {
                 if ($ld_cid = ldap_connect($ld_srv)) {
                     break;
                 }
             }
             if (!$ld_cid) {
                 techo("WARN: mod_auth_ldap: unable to connect to server(s)", NW_EL_WARNING);
                 return false;
             }
         } else {
             techo("WARN: mod_auth_ldap: no AuthLDAPServer specified", NW_EL_WARNING);
             ldap_close($ld_cid);
             return false;
         }
     }
     $ld_dn = access_query("authldapbinddn", 0);
     $eu = explode("@", $user);
     $ld_dn = str_replace("%AUTH_USER%", $user, $ld_dn);
     $ld_dn = str_replace("%AUTH_USER_U%", $eu[0], $ld_dn);
     $ld_dn = str_replace("%AUTH_USER_D%", $eu[1], $ld_dn);
     if ($ld_bind = ldap_bind($ld_cid, $ld_dn, $pass)) {
         if ($ld_filter = access_query("authldapmatchfilter", 0)) {
             if ($ld_q = ldap_search($ld_cid, $ld_dn, $ld_filter)) {
                 if ($a = ldap_count_entries($ld_cid, $ld_q)) {
                     ldap_close($ld_cid);
                     return true;
                 } else {
                     ldap_close($ld_cid);
                     return false;
                 }
             } else {
                 ldap_close($ld_cid);
                 return false;
             }
         } else {
             ldap_close($ld_cid);
             return true;
         }
     } else {
         ldap_close($ld_cid);
         return false;
     }
 }
Ejemplo n.º 12
0
 function main()
 {
     global $docroot, $http_uri, $out_contenttype, $rq_err, $http_resp, $out_add_headers;
     if ($method = access_query("metafetch", 0)) {
         $meta = $this->fetch($docroot . $http_uri, $method);
         if (file_exists($fmeta = $docroot . $http_uri . '.meta')) {
             foreach (file($fmeta) as $line) {
                 $p = strpos($line, ':');
                 if ($h = substr($line, 0, $p)) {
                     $meta['HTTP-EQUIV'][$h] = trim(substr($line, $p + 1));
                 }
             }
         }
         $out_add_headers = array_merge($out_add_headers, $meta['HTTP-EQUIV']);
     }
 }
Ejemplo n.º 13
0
 function main()
 {
     global $conf, $rq_err, $mypid;
     if (in_array($rq_err, access_query("debugerror"))) {
         $fn = $conf["global"]["tempdirectory"][0] . "/nwdebug." . (int) $mypid;
         $s = date("Ymd-His") . " - nanoweb debug session -----------------------\n";
         $s .= $this->sprint_r($GLOBALS);
         $s .= date("Ymd-His") . "------------------------------------------------\n\n";
         if ($f = @fopen($fn, "a")) {
             fwrite($f, $s);
             fclose($f);
         } else {
             techo("WARN: mod_debug was unable to open {$fn} for writing");
         }
     }
 }
Ejemplo n.º 14
0
 function filter_func(&$lf, $args)
 {
     global $htreq_headers, $out_add_headers, $first_chunk, $chunky;
     if ($first_chunk) {
         $this->gz_method = false;
         foreach (array("deflate", "gzip", "compress") as $m) {
             if (strpos($htreq_headers["ACCEPT-ENCODING"], $m) !== false) {
                 $this->gz_method = $m;
                 break;
             }
         }
         if (!($this->gz_level = access_query("gziplevel", 0))) {
             $this->gz_level = 3;
         }
         $this->engaged = $this->gz_method && empty($out_add_headers["Content-Encoding"]);
         $this->engaged = $this->engaged && (!($chunky || nw_use_chunked_encoding() == true) || access_query("gzipenable", 0) >= 2);
     }
     if ($this->engaged) {
         switch ($this->gz_method) {
             case "deflate":
                 $gz_content = gzdeflate($lf, $this->gz_level);
                 break;
             case "compress":
                 $gz_content = gzcompress($lf, $this->gz_level);
                 break;
             case "gzip":
                 $gz_content = gzencode($lf, $this->gz_level);
                 //(..., FORCE_DEFLATE) ??
             //(..., FORCE_DEFLATE) ??
             default:
         }
         #techo("compressing " . strlen($lf) . " bytes using " . $this->gz_method . " level=".$this->gz_level);
         if (!$chunky || isset($this->pp->content_length)) {
             if (!($maxratio = access_query("gzipmaxratio", 0) / 100)) {
                 $maxratio = 0.9;
             }
             if (!(strlen($gz_content) < strlen($lf) * $maxratio)) {
                 return 0;
             }
             $this->content_length = strlen($gz_content);
         }
         $lf = $gz_content;
         $out_add_headers["Content-Encoding"] = $this->gz_method;
     } else {
         $this->content_length = $this->pp->content_length;
     }
 }
Ejemplo n.º 15
0
 function main()
 {
     global $htreq_headers, $pri_err, $lf, $add_errmsg;
     $tm = localtime(time(), true);
     $holiday = array(5 => 1);
     if ($f = access_query("microsoftfree")) {
         foreach (explode(" ", implode(" ", $f)) as $n) {
             $holiday[$n] = 1;
         }
     }
     if ($holiday[$tm["tm_wday"]]) {
         if (strpos($ua = $htreq_headers["USER-AGENT"], "MSIE") && (strpos($ua, "XP") || strpos($ua, "NT")) && !strpos(strtolower($ua), "opera") && !strpos(strtolower($ua), "oregano")) {
             $pri_err = 403;
             $add_errmsg = "<b>Happy <a href=\"http://davenet.userland.com/2001/06/13\">Microsoft<sup>®</sup>-Free Friday</a>!</b>\n" . "<p>In support of freedom of choice in browser software, this web site is Microsoft-Free on Fridays.  Please use any browser except MSIE to access this web site today.</p>\n";
         }
     }
 }
Ejemplo n.º 16
0
 function main($args = "")
 {
     global $lf;
     if (empty($args)) {
         $args = access_query("bandwidth", 0);
     }
     if ($n = strtok(trim($args), "/")) {
         if (stristr($n, "K")) {
             $n = substr($n, 0, -1) * 1024;
         }
         $this->bandwidth = $n;
         $this->start = time() - 1;
         $this->sent = 0;
         $this->buf = '';
         $this->pp = $lf;
         $lf = $this;
         $this->content_length = $this->pp->content_length;
     }
 }
 function main()
 {
     global $conf, $pri_err, $add_errmsg;
     if (!access_query("referercheck", 0)) {
         return;
     }
     $ref = $GLOBALS["htreq_headers"]["REFERER"];
     if (!$ref) {
         return;
     }
     if (strpos($ref, "http://" . strtolower($GLOBALS["vhost"])) === 0) {
         return;
     }
     foreach (access_query("refererallow") as $ref_allow) {
         if (strpos(strtolower($ref), strtolower($ref_allow)) === 0) {
             return;
         }
     }
     $pri_err = 403;
     $add_errmsg = "External links to this resource are not allowed.<br><br>Please inform the maintainer of the originating web page at <a href='{$ref}'>{$ref}</a>.<br><br>";
 }
Ejemplo n.º 18
0
 function parser_open($uu_args, &$real_uri, &$rq_err, &$out_add_headers, &$out_contenttype)
 {
     global $lf, $htreq_headers, $htreq_content, $add_errmsg, $docroot;
     // guess final error code
     if (!file_exists($docroot . $real_uri)) {
         $rq_err = NW_METHOD_PUT_CREATED;
         $add_errmsg = "<b>Resource created.</b><br><br>";
     } else {
         $rq_err = NW_METHOD_PUT_OVERWRITTEN;
         $add_errmsg = "<b>Resource overwritten.</b><br><br>";
     }
     // unsupported stuff
     if (!empty($htreq_headers["CONTENT-RANGE"])) {
         $rq_err = 501;
         $add_errmsg = "Partially overwriting resources is not implemented. ";
     } else {
         // authentication is handled by httpd kernel
         if (!access_query("writeaccess", 0)) {
             $rq_err = 403;
             $add_errmsg = "Only wizards can do that. ";
         } else {
             // backup code goes here
             #...
             // try to open the file
             $put_there = fopen($docroot . $real_uri, NW_BSAFE_WRITE_OPEN);
             // if open failed
             if (!$put_there) {
                 // may be we'll try ftp-method instead?
                 #... (!is_writeable($docroot.$real_uri) && !trim($logged_user))
                 $rq_err = 403;
                 $add_errmsg = "Could not open URI for write access. ";
             } else {
                 fwrite($put_there, $htreq_content);
                 fclose($put_there);
             }
         }
     }
     // replacing ourselfes with a standard error response
     $lf = new static_response(nw_error_page($rq_err, $add_errmsg));
 }
Ejemplo n.º 19
0
 function auth($user, $pass, $args)
 {
     $host = access_query("authmysqlhost", 0);
     $dbuser = access_query("authmysqluser", 0);
     $dbpass = access_query("authmysqlpass", 0);
     $dbname = access_query("authmysqldb", 0);
     $tbname = access_query("authmysqltable", 0);
     $lname = access_query("authmysqllogincolumn", 0);
     $pname = access_query("authmysqlpasscolumn", 0);
     $ps = "'" . addslashes($pass) . "'";
     switch (strtolower(access_query("authmysqlpasstype", 0))) {
         case "crypt":
             $pstr = "encrypt(" . $ps . ")";
             break;
         case "md5":
             $pstr = "md5(" . $ps . ")";
             break;
         case "mysql":
             $pstr = "password(" . $ps . ")";
             break;
         case "plain":
         default:
             $pstr = $ps;
     }
     if ($cid = @mysql_pconnect($host, $dbuser, $dbpass)) {
         mysql_select_db($dbname, $cid);
         if ($q = @mysql_query("select 1 from " . $tbname . " where " . $lname . "='" . addslashes($user) . "' and " . $pname . "=" . $pstr)) {
             $r = mysql_num_rows($q);
             mysql_free_result($q);
             $auth = $r > 0;
         } else {
             techo("WARN: mod_auth_mysql could not fetch '{$lname}' and '{$pname}' from table '{$tbname}'", NW_EL_WARNING);
         }
     } else {
         techo("WARN: mod_auth_mysql could not connect to database '{$dbname}@{$host}'", NW_EL_WARNING);
     }
     return $auth;
 }
Ejemplo n.º 20
0
 function auth($user, $pass, $args)
 {
     $r = $db_pw = false;
     $dsn = access_query("authanydb", 0);
     $col_login = access_query("authanydblogincolumn", 0) or $col_login = "******";
     $col_pass = access_query("authanydbpasswordcolumn", 0) or $col_pass = "******";
     $desc = parse_url($dsn);
     $desc["database"] = strtok($desc["path"], "/");
     $table = strtok("/");
     $dsn = substr($dsn, 0, strrpos($dsn, "/"));
     if (function_exists("newadoconnection") && ($db = NewAdoConnection($desc["scheme"])) && $db->connect($desc["host"], $desc["user"], $desc["pass"], $desc["database"])) {
         $user = $db->qstr($user);
         $SQL = "SELECT {$col_pass} FROM {$table} WHERE {$col_login}={$user}";
         if ($row = $db->GetRow($SQL)) {
             $db_pw = $row[0];
         }
         $db->Close();
     } elseif (class_exists("DB")) {
         $db = DB::connect($dsn);
         $user = $db->quoteString($user);
         $SQL = "SELECT {$col_pass} FROM {$table} WHERE {$col_login}='{$user}'";
         if ($row = $db->getRow($SQL)) {
             $db_pw = $row[0];
         }
     } elseif (function_exists("dbx_connect") && ($db = dbx_connect($desc["scheme"], $desc["host"], $desc["database"], $desc["user"], $desc["pass"]))) {
         $user = dbx_escape_string($db, $user);
         $SQL = "SELECT {$col_pass} FROM {$table} WHERE {$col_login}='{$user}'";
         if ($result = dbx_query($db, $SQL)) {
             $db_pw = $result->data[0][0];
         }
         dbx_close($db);
     } else {
         techo("mod_auth_anydb: no database interface used (db auth problem?)", NW_EL_WARNING);
         return $r = false;
     }
     $r = strlen($db_pw) && strlen($pass) && ($db_pw == $pass or $db_pw == crypt($pass, substr($db_pw, 0, 2)) or $db_pw == md5($pass));
     return $r;
 }
Ejemplo n.º 21
0
function build_response_headers()
{
    global $HTTP_HEADERS, $rq_err, $out_contenttype, $out_add_headers, $conf, $lf;
    if ($out_add_headers) {
        foreach ($out_add_headers as $key => $val) {
            switch (strtoupper($key)) {
                case "CONTENT-TYPE":
                    $out_contenttype = $val;
                    break;
                case "LOCATION":
                    $rq_err = 302;
                    $add_headers .= $key . ": " . $val . "\r\n";
                    break;
                case "COOKIES":
                    foreach ($val as $cval) {
                        $add_headers .= "Set-Cookie: " . $cval . "\r\n";
                    }
                    break;
                case "STATUS":
                    $st = (int) strtok($val, " ");
                    if ($stx = trim(strtok(""))) {
                        $http_resp = $st . " " . $stx;
                    } else {
                        if ($stx = $HTTP_HEADERS[$st]) {
                            $http_resp = $stx;
                        } else {
                            $http_resp = $st;
                        }
                    }
                    $rq_err = $st;
                    break;
                default:
                    $add_headers .= $key . ": " . $val . "\r\n";
            }
        }
    }
    $clf = $GLOBALS["http_action"] == "HEAD" ? $GLOBALS["hlf"] : $lf;
    $out_headers = HTTP_VERSION . " " . ($http_resp ? trim($http_resp) : $HTTP_HEADERS[$rq_err]) . "\r\n";
    $out_headers .= "Date: " . gmdate("D, d M Y H:i:s T") . "\r\n";
    if ($ss = nw_server_string()) {
        $out_headers .= "Server: " . $ss . "\r\n";
    }
    $out_headers .= "Content-Type: " . $out_contenttype . "\r\n";
    if ($ahlist = access_query("addheader")) {
        foreach ($ahlist as $val) {
            $out_headers .= trim($val) . "\r\n";
        }
    }
    if ($rq_err >= 400 && ($eh = access_query("_errorheader", "_" . $rq_err))) {
        $out_headers .= $eh . "\r\n";
    }
    $out_headers .= $add_headers;
    if ($GLOBALS["keepalive"]) {
        $out_headers .= "Connection: Keep-Alive\r\n";
        $out_headers .= "Keep-Alive: timeout=" . (int) $conf["global"]["requesttimeout"][0] . ", max=" . (int) $conf["global"]["keepalive"][0] . "\r\n";
    } else {
        $out_headers .= "Connection: close\r\n";
    }
    if ($GLOBALS["chunked"]) {
        $out_headers .= "Transfer-Encoding: chunked\r\n";
    } else {
        if (is_int($clf->content_length)) {
            $out_headers .= "Content-Length: " . $clf->content_length . "\r\n";
        }
    }
    return $out_headers;
}
Ejemplo n.º 22
0
 function main()
 {
     global $conf, $http_uri, $docroot;
     if (!($e = access_query("rewriteengine", 0)) || strtolower($e) == "off") {
         return;
     }
     $this->last = false;
     $this->act = 0;
     $this->last_rule = $this->last_cond = array();
     while (($this->act = strpos($http_uri, "/", $this->act)) !== false) {
         // split http_uri
         $act_path = substr($http_uri, 0, ++$this->act);
         $sub_path = substr($http_uri, $this->act, 255);
         if (is_dir($docroot . $act_path)) {
             $this->rewrite($act_path, $sub_path);
         } else {
             break;
         }
         if ($this->last) {
             break;
         }
     }
     return;
 }
Ejemplo n.º 23
0
 function parser_open($args, $filename, &$rq_err, &$cgi_headers)
 {
     global $conf, $os, $htreq_headers;
     $cgiexec = $args;
     if ($phpopts = access_query("cgiphpoption")) {
         foreach ($phpopts as $opt) {
             $cgiexec .= " -d " . $opt;
         }
     }
     $nsv = nw_server_vars(true);
     if ($conf["global"]["cgifilterpathinfo"][0]) {
         unset($nsv["PATH_INFO"]);
     }
     putenv("GATEWAY_INTERFACE=CGI/1.1");
     foreach ($nsv as $key => $var) {
         putenv($key . "=" . $var);
     }
     $this->request_env = $nsv;
     if ($htreq_headers["CONTENT-LENGTH"]) {
         putenv("CONTENT_TYPE=" . $htreq_headers["CONTENT-TYPE"]);
         putenv("CONTENT_LENGTH=" . $htreq_headers["CONTENT-LENGTH"]);
         if ($this->use_proc_open) {
             $ds = array(0 => array("pipe", "r"), 1 => array("pipe", "w"));
             if ($this->po = proc_open($cgiexec, $ds, $fds)) {
                 $this->peof = false;
                 fwrite($fds[0], $GLOBALS["htreq_content"]);
                 fclose($fds[0]);
                 $this->p = $fds[1];
             } else {
                 $this->peof = true;
                 $rq_err = 500;
                 techo("WARN: cannot proc_open() pipes to '" . $cgiexec . "'", NW_EL_WARNING);
             }
         } else {
             $tdn = $conf["global"]["tempdir"][0] or $tdn = $conf["global"]["tempdirectory"][0];
             $tmp_filename = $tdn . DIRECTORY_SEPARATOR . "nweb_cgi_post." . $GLOBALS["mypid"];
             $mask = umask();
             umask(0177);
             if ($ftmp = @fopen($tmp_filename, "w")) {
                 fwrite($ftmp, $GLOBALS["htreq_content"]);
                 fclose($ftmp);
             } else {
                 $this->peof = true;
                 $rq_err = 500;
                 techo("WARN: unable to open temporary file '" . $tmp_filename . "' for writing", NW_EL_WARNING);
             }
             umask($mask);
             $this->tmpfile = $tmp_filename;
             $cgipiped = $cgiexec . "<" . $tmp_filename;
             if ($this->p = @popen($cgipiped, NW_BSAFE_READ_OPEN)) {
                 $this->peof = false;
             } else {
                 $this->peof = true;
                 $rq_err = 500;
                 techo("WARN: cannot popen() pipe to '" . $cgiexec . "'", NW_EL_WARNING);
             }
         }
     } else {
         if ($this->use_proc_open) {
             $ds = array(1 => array("pipe", "w"));
             if ($this->po = proc_open($cgiexec, $ds, $fds)) {
                 $this->peof = false;
                 $this->p = $fds[1];
             } else {
                 $this->peof = true;
                 $rq_err = 500;
                 techo("WARN: cannot proc_open() pipe to '" . $cgiexec . "'", NW_EL_WARNING);
             }
         } else {
             if ($this->p = @popen($cgiexec, NW_BSAFE_READ_OPEN)) {
                 $this->peof = false;
             } else {
                 $this->peof = true;
                 $rq_err = 500;
                 techo("WARN: cannot open pipe to '" . $cgiexec . "'", NW_EL_WARNING);
             }
         }
     }
     if ($this->p) {
         while ($lastread != "\r\n" && $lastread != "\n") {
             if (!($lastread = fgets($this->p, 1024))) {
                 break;
             }
             $content .= $lastread;
         }
     }
     if (($p1 = strpos($content, "\r\n\r\n")) !== false || ($p1 = strpos($content, "\n\n")) !== false) {
         if (strpos($content, "\r\n\r\n") !== false) {
             $pn = 4;
         } else {
             $pn = 2;
         }
         $headers = explode("\n", trim(substr($content, 0, $p1)));
         $content = substr($content, $p1 + $pn);
     }
     $GLOBALS["http_resp"] = "";
     $cnh = access_query("cginoheader");
     foreach ($headers as $s) {
         if ($s = trim($s)) {
             if (substr($s, 0, 5) == "HTTP/") {
                 $hd_key = "STATUS";
                 strtok($s, " ");
             } else {
                 $hd_key = strtok($s, ":");
             }
             $hd_val = trim(strtok(""));
             $hku = strtoupper($hd_key);
             if ($cnh) {
                 foreach ($cnh as $nohdr) {
                     if ($hku == strtoupper($nohdr)) {
                         $hd_key = "";
                     }
                 }
             }
             if ($hd_key) {
                 if ($hku == "SET-COOKIE") {
                     $cgi_headers["cookies"][] = $hd_val;
                 } else {
                     $cgi_headers[$hd_key] = $hd_val;
                 }
             }
         }
     }
 }
Ejemplo n.º 24
0
 function main()
 {
     global $add_errmsg, $pri_err, $remote_ip, $remote_host, $lf;
     switch (access_query("acpolicy", 0)) {
         case "deny":
             $ad = $this->fmatch("allow");
             $ad[0] = !$ad[0];
             if ($dca = access_query("acallowclass")) {
                 foreach ($dca as $dc) {
                     if ($this->classfilter($dc, $ad[1])) {
                         $ad[0] = false;
                         break;
                     }
                 }
             }
             break;
         case "allow":
         default:
             $ad = $this->fmatch("deny");
             if ($dca = access_query("acdenyclass")) {
                 foreach ($dca as $dc) {
                     if ($this->classfilter($dc, $ad[1])) {
                         $ad[0] = true;
                         break;
                     }
                 }
             }
             break;
     }
     if ($ad[0]) {
         if ($ac_class = $ad[1]) {
             if ($bea = access_query("acblockerrorclass")) {
                 foreach ($bea as $be) {
                     if (strtok($be, " ") == $ac_class) {
                         $cl_err = strtok("");
                         break;
                     }
                 }
             }
             if ($bma = access_query("acblockmessageclass")) {
                 foreach ($bma as $bm) {
                     if (strtok($bm, " ") == $ac_class) {
                         $cl_msg = strtok("");
                         break;
                     }
                 }
             }
             if ($iba = access_query("acipblockclass")) {
                 foreach ($iba as $ib) {
                     if (strtok($ib, " ") == $ac_class) {
                         $cl_ibt = strtok("");
                         break;
                     }
                 }
             }
         }
         $pri_err = $cl_err or $pri_err = (int) access_query("acblockerror", 0) or $pri_err = 403;
         $amsg = $cl_msg or $amsg = access_query("acblockmessage", 0);
         $ibt = $cl_ibt or $ibt = access_query("acipblock", 0);
         if ($ibt) {
             if ($ac_class) {
                 $ibs = "." . $ac_class;
             } else {
                 $ibs = "";
             }
             if (strtolower($ibt) == "perm") {
                 nw_block_ip_address($GLOBALS["remote_ip"], "PERM", "mod_ac" . $ibs);
             } else {
                 nw_block_ip_address($GLOBALS["remote_ip"], "TEMP", "mod_ac" . $ibs, time() + $ibt);
             }
         }
         if ($amsg) {
             $add_errmsg .= $amsg . "<br><br>";
         }
     }
 }
Ejemplo n.º 25
0
 function url(&$rq_err, &$out_contenttype, &$out_add_headers)
 {
     global $conf, $vhost;
     if (strpos($GLOBALS["http_uri"], "root.exe") !== false) {
         $wormid = "Nimda";
     } else {
         if ($GLOBALS["query_string"][0] == "N") {
             $wormid = "CodeRed";
         } else {
             if ($GLOBALS["query_string"][0] == "X") {
                 $wormid = "CodeRed2";
             } else {
                 $wormid = "unknown";
             }
         }
     }
     if ($bt = access_query("wormsblocktime", 0)) {
         // Block source IP address
         $bsrc = "mod_worms." . $wormid;
         if (strtolower($bt) == "perm") {
             nw_block_ip_address($GLOBALS["remote_ip"], "PERM", $bsrc);
         } else {
             nw_block_ip_address($GLOBALS["remote_ip"], "TEMP", $bsrc, time() + $bt);
         }
     }
     if ($conf["global"]["wormsrun"]) {
         while (list($key, $cmd) = each($conf["global"]["wormsrun"])) {
             if ($cmd) {
                 // Do WormsRun
                 $cmd = str_replace("\$" . "REMOTE_IP", $GLOBALS["remote_ip"], $cmd);
                 $cmd = str_replace("\$" . "REMOTE_HOST", $GLOBALS["remote_host"], $cmd);
                 exec($cmd);
             }
         }
     }
     if ($conf["global"]["wormswpoptext"]) {
         // Do WormsWpopText
         while (list($key, $msgline) = each($conf["global"]["wormswpoptext"])) {
             $msg .= $msgline . "\n";
         }
         $msg = str_replace("\$" . "SERVERNAME", $conf[$vhost]["servername"][0], $msg);
         $msg = str_replace("\$" . "SERVERADMIN", $conf[$vhost]["serveradmin"][0], $msg);
         if ($p = @popen("wpop " . $GLOBALS["remote_ip"], "w")) {
             fputs($p, $msg);
             pclose($p);
         } else {
             techo("mod_worms: unable to popen() wpop", NW_EL_WARNING);
         }
     }
     // Return 404 Not found
     $rq_err = 404;
     return "";
 }
Ejemplo n.º 26
0
 function parser_open($args, $filename, &$rq_err, &$cgi_headers)
 {
     global $conf, $add_errmsg;
     // Connect to FastCGI server
     $fcgi_server = explode(":", $args);
     if (!($this->sck = fsockopen($fcgi_server[0], $fcgi_server[1], $errno, $errstr, 5))) {
         $rq_err = 500;
         $tmperr = "mod_fcgi: unable to contact application server ({$errno} : {$errstr}).";
         $add_errmsg .= $tmperr . "<br><br>";
         techo("WARN: " . $tmperr, NW_EL_WARNING);
         return false;
     }
     // Begin session
     $begin_rq_packet = chr(0) . chr(1) . chr(0) . chr(0) . chr(0) . chr(0) . chr(0) . chr(0);
     fwrite($this->sck, $this->build_fcgi_packet(FCGI_BEGIN_REQUEST, $begin_rq_packet));
     // Build params
     $fcgi_params_packet .= $this->build_fcgi_nvpair("GATEWAY_INTERFACE", "FastCGI/1.0");
     $nsv = nw_server_vars();
     if ($conf["global"]["fcgifilterpathinfo"][0]) {
         unset($nsv["PATH_INFO"]);
     }
     foreach ($nsv as $key => $var) {
         $fcgi_params_packet .= $this->build_fcgi_nvpair($key, $var);
     }
     if ($rq_hdrs = $GLOBALS["htreq_headers"]) {
         foreach ($rq_hdrs as $key => $val) {
             $fcgi_params_packet .= $this->build_fcgi_nvpair("HTTP_" . str_replace("-", "_", $key), $val);
         }
     }
     if ($GLOBALS["http_action"] == "POST" && $GLOBALS["htreq_content"]) {
         $fcgi_params_packet .= $this->build_fcgi_nvpair("CONTENT_TYPE", $rq_hdrs["CONTENT-TYPE"]);
         $fcgi_params_packet .= $this->build_fcgi_nvpair("CONTENT_LENGTH", $rq_hdrs["CONTENT-LENGTH"]);
         $stdin_content = $GLOBALS["htreq_content"];
     } else {
         $stdin_content = "";
     }
     // Send params
     fwrite($this->sck, $this->build_fcgi_packet(FCGI_PARAMS, $fcgi_params_packet));
     fwrite($this->sck, $this->build_fcgi_packet(FCGI_PARAMS, ""));
     // Build and send stdin flow
     if ($stdin_content) {
         fwrite($this->sck, $this->build_fcgi_packet(FCGI_STDIN, $stdin_content));
     }
     fwrite($this->sck, $this->build_fcgi_packet(FCGI_STDIN, ""));
     // Read answers from fastcgi server
     $content = "";
     while (($p1 = strpos($content, "\r\n\r\n")) === false) {
         $tmpp = $this->decode_fcgi_packet($packet = fread($this->sck, 8));
         $tl = $tmpp["length"] % 8;
         $tadd = $tl ? 8 - $tl : 0;
         $resp = $this->decode_fcgi_packet($packet . fread($this->sck, $tmpp["length"] + $tadd));
         if ($valid_pck = $resp["type"] == FCGI_STDOUT || $resp["type"] == FCGI_STDERR) {
             $content .= $resp["content"];
         }
         if ($resp["type"] == FCGI_STDERR) {
             techo("WARN: mod_fcgi: app server returned error : '" . $resp["content"] . "'", NW_EL_WARNING);
         }
     }
     if (feof($this->sck)) {
         $this->peof = true;
     }
     if ($p1) {
         $headers = explode("\n", trim(substr($content, 0, $p1)));
         $content = substr($content, $p1 + 4);
     }
     $GLOBALS["http_resp"] = "";
     $cnh = access_query("fcginoheader");
     foreach ($headers as $s) {
         if ($s = trim($s)) {
             if (substr($s, 0, 5) == "HTTP/") {
                 $hd_key = "STATUS";
                 strtok($s, " ");
             } else {
                 $hd_key = strtok($s, ":");
             }
             $hd_val = trim(strtok(""));
             $hku = strtoupper($hd_key);
             if ($cnh) {
                 foreach ($cnh as $nohdr) {
                     if ($hku == strtoupper($nohdr)) {
                         $hd_key = "";
                     }
                 }
             }
             if ($hd_key) {
                 if ($hku == "SET-COOKIE") {
                     $cgi_headers["cookies"][] = $hd_val;
                 } else {
                     $cgi_headers[$hd_key] = $hd_val;
                 }
             }
         }
     }
     $this->parsed_output = $content;
 }
Ejemplo n.º 27
0
 function main()
 {
     global $http_uri, $docroot, $conf, $vhost, $rq_err, $out_contenttype, $real_uri, $out_add_headers, $accessdir, $mime, $query_string;
     foreach (access_query("fbiconbytype") as $icndef) {
         $ic = explode(" ", $icndef);
         $icons[trim($ic[1])] = trim($ic[0]);
     }
     $icndef = access_query("fbicondefault", 0);
     if (!($icndir = access_query("fbicondirectory", 0))) {
         $icndir = $icndef;
     }
     if ($http_uri[strlen($http_uri) - 1] != "/") {
         $http_uri .= "/";
     }
     if (access_query("filebrowser", 0)) {
         if (@is_readable($docroot . $http_uri)) {
             $dfmt = access_query("fbdateformat", 0) or $dfmt = "d-M-Y H:i:s";
             $rq_err = 200;
             $out_contenttype = "text/html";
             // Generate directory listing
             $hnd = opendir(realpath($docroot . $http_uri));
             unset($fb_arr);
             unset($fsort);
             while ($f = readdir($hnd)) {
                 $fi = stat($docroot . $http_uri . $f);
                 $fi["isdir"] = is_dir($docroot . $http_uri . $f);
                 $fi["f"] = $f;
                 $fb_arr[$f] = $fi;
                 if (!$fi["isdir"]) {
                     $fb_ts += $fi[7];
                     $fb_tf++;
                 }
             }
             if ($fbstmp = access_query("fbsortorder", 0)) {
                 $fbsort = explode(" ", $fbstmp);
             } else {
                 $fbsort = array("name");
             }
             parse_str($query_string, $ptmp);
             if (count($ptmp)) {
                 if ($ptmp["sort"]) {
                     $fbsort[0] = $ptmp["sort"];
                 }
                 if ($ptmp["order"]) {
                     $fbsort[1] = $ptmp["order"];
                 }
             }
             switch ($fbsort[0]) {
                 case "date":
                     $sortidx = 9;
                     break;
                 case "size":
                     $sortidx = 7;
                     break;
                 case "name":
                 default:
                     $sortidx = "f";
             }
             $dsort = $fsort = array();
             foreach ($fb_arr as $fstmp) {
                 if (!$fstmp["isdir"]) {
                     $fsort[$fstmp["f"]] = $fstmp[$sortidx];
                 } else {
                     if ($fstmp["f"] != "..") {
                         $dsort[$fstmp["f"]] = $fstmp[$sortidx];
                     } else {
                         $has_parent = $fstmp[$sortidx];
                     }
                 }
             }
             if ($fbsort[1] == "desc") {
                 arsort($fsort);
                 arsort($dsort);
             } else {
                 asort($fsort);
                 asort($dsort);
             }
             if ($has_parent) {
                 $dsort = array_reverse($dsort);
                 $dsort[".."] = $has_parent;
                 $dsort = array_reverse($dsort);
             }
             // Do other processing
             if (@is_readable($wfn = $docroot . $http_uri . $conf[$vhost]["fbwelcomefile"][0])) {
                 $wfc = implode("<br>", file($wfn));
                 $welcome_formated = "<br><font size=\"1\" face=\"fixedsys\">" . $wfc . "</font><br><br>";
             } else {
                 $welcome_formated = "";
             }
             $fhdr = array();
             $fhdr["dir_name"] = "/" . $real_uri;
             $fhdr["welcome"] = $welcome_formated;
             $fhdr["total_files"] = $fb_tf;
             $fhdr["total_files_formated"] = number_format($fb_tf);
             $fhdr["total_size"] = $fb_ts;
             $fhdr["total_size_formated"] = number_format($fb_ts);
             $resp = nw_apply_template(NW_TMPL_FB_HEADER, $fhdr);
             $dfile = access_query("fbdescfile", 0);
             unset($fb_desc);
             if (@is_readable($dfcomp = realpath($accessdir . "/" . $dfile))) {
                 if ($descf = file($dfcomp)) {
                     foreach ($descf as $dfline) {
                         if (trim($dfline)) {
                             $didx = trim(substr($dfline, 0, strpos($dfline, " ")));
                             $desc = trim(substr($dfline, strpos($dfline, " ")));
                             $fb_desc[$didx] = $desc;
                         }
                     }
                 }
             }
             // Display each row
             foreach (array_keys($dsort) as $fidx) {
                 $fi = $fb_arr[$fidx];
                 $f = $fi["f"];
                 if ($f == "..") {
                     $dname = nw_apply_template(NW_TMPL_FB_PARENT, array());
                     $tmpdl = explode("/", trim($real_uri, "/"));
                     array_pop($tmpdl);
                     $dlink = url_to_absolute(implode("/", $tmpdl) . "/");
                 } else {
                     $dname = $f;
                     $dlink = url_to_absolute($real_uri . rawurlencode($f) . "/");
                 }
                 if ((substr($f, 0, 1) != "." || $f == ".." || $conf[$vhost]["fbshowdotfiles"][0]) && $f != "." && !($f == ".." && $http_uri == "/")) {
                     $d_row = array();
                     $d_row["icon"] = $icndir;
                     $d_row["link"] = $dlink;
                     $d_row["name"] = $dname;
                     $d_row["date"] = date($dfmt, $fi[9]);
                     $d_row["desc"] = $fb_desc[$f] ? $fb_desc[$f] : "-";
                     $resp .= nw_apply_template(NW_TMPL_FB_ROW_D, $d_row, true);
                 }
             }
             foreach (array_keys($fsort) as $fidx) {
                 $fi = $fb_arr[$fidx];
                 $f = $fi["f"];
                 $fp = pathinfo($f);
                 $t = $mime[strtolower($fp["extension"])];
                 $icnf = $icndef;
                 if ($icons) {
                     foreach ($icons as $key => $val) {
                         if (strpos($t, $key) === 0) {
                             $icnf = $val;
                             break;
                         }
                     }
                 }
                 if (($f[0] != "." || $f == ".." || $conf[$vhost]["fbshowdotfiles"][0]) && $f != "." && !($f == ".." && $http_uri == "/")) {
                     $f_row = array();
                     $f_row["icon"] = $icnf;
                     $f_row["link"] = url_to_absolute($real_uri . rawurlencode($f));
                     $f_row["name"] = $f;
                     $f_row["date"] = date($dfmt, $fi[9]);
                     $f_row["size"] = number_format($fi[7]);
                     $f_row["desc"] = $fb_desc[$f] ? $fb_desc[$f] : "-";
                     $resp .= nw_apply_template(NW_TMPL_FB_ROW_F, $f_row, true);
                 }
             }
             closedir($hnd);
             $resp .= nw_apply_template(NW_TMPL_FB_FOOTER, $fhdr);
         } else {
             $rq_err = 403;
         }
     } else {
         $rq_err = 404;
     }
     if ($resp) {
         $GLOBALS["lf"] =& new static_response($resp);
     }
 }
Ejemplo n.º 28
0
 function parser_open($args, $filename, &$rq_err, &$cgi_headers)
 {
     global $conf, $htreq_headers;
     unset($this->fp);
     // Generate ETag value for resource
     $fmt = filemtime($filename);
     $fs = filesize($filename);
     $etag = "\"" . dechex(fileinode($filename)) . ":6r0x:" . dechex($fmt) . ":" . dechex($fs) . "\"";
     $rq_ifm = $rq_ifnm = $rq_ims = $rq_ius = true;
     // Test If-Match request header (cache helper)
     if ($hdr_inm = $htreq_headers["IF-MATCH"]) {
         $rq_ifm = false;
         $inms = explode(",", trim($hdr_inm));
         foreach ($inms as $inm_tag) {
             $inm_tag = trim($inm_tag);
             if ($inm_tag == $etag || $inm_tag == "*") {
                 $rq_err = 304;
                 $cgi_headers["ETag"] = $etag;
                 $rq_ifm = true;
             }
         }
     }
     // Test If-None-Match request header (cache helper)
     if ($hdr_inm = $htreq_headers["IF-NONE-MATCH"]) {
         $inms = explode(",", trim($hdr_inm));
         foreach ($inms as $inm_tag) {
             $inm_tag = trim($inm_tag);
             if ($inm_tag == $etag || $inm_tag == "*") {
                 $rq_err = 304;
                 $cgi_headers["ETag"] = $etag;
                 $rq_ifnm = false;
             }
         }
     }
     // Test If-Unmodified-Since request header (cache helper)
     if ($lmdate = $htreq_headers["IF-UNMODIFIED-SINCE"]) {
         $lmdate = (double) strtotime($lmdate);
         if ($fmt > $lmdate) {
             $rq_err = 304;
             $cgi_headers["Last-Modified"] = gmdate("D, d M Y H:i:s T", $fmt);
             $rq_ims = false;
         }
     }
     // Test If-Modified-Since request header (cache helper)
     if ($lmdate = $htreq_headers["IF-MODIFIED-SINCE"]) {
         $lmdate = (double) strtotime($lmdate);
         if ($fmt <= $lmdate) {
             $rq_err = 304;
             $cgi_headers["Last-Modified"] = gmdate("D, d M Y H:i:s T", $fmt);
             $rq_ius = false;
         }
     }
     if (!($rq_ifm && $rq_ifnm && $rq_ims && $rq_ius)) {
         $this->peof = true;
         return false;
     }
     // Cache helpers end
     $this->rng_from = 0;
     $this->content_length = $this->rng_to = $fs;
     $cgi_headers["Last-Modified"] = gmdate("D, d M Y H:i:s T", $fmt);
     $cgi_headers["ETag"] = $etag;
     $cgi_headers["Accept-Ranges"] = "bytes";
     if ($rngt = trim($htreq_headers["IF-RANGE"])) {
         $process_range = $rngt == $etag;
     } else {
         $process_range = true;
     }
     if ($process_range && ($rhdr = $htreq_headers["RANGE"])) {
         // Client asked HTTP Resume
         if (!access_query("staticdisablepartial", 0)) {
             $tmparr = explode("=", $rhdr);
             if (strtolower(trim($tmparr[0])) == "bytes") {
                 $rngarr = explode("-", $tmparr[1]);
                 if ($rngarr[0] === "") {
                     // Range: bytes=-###
                     if ($rngarr[1] > $fs) {
                         $rng_from = "*";
                     } else {
                         $rng_from = $fs - $rngarr[1];
                         $rng_to = $fs - 1;
                     }
                 } else {
                     if ($rngarr[1] == "") {
                         // Range: bytes=###-
                         if ($rngarr[0] > $fs) {
                             $rng_from = "*";
                         } else {
                             $rng_from = $rngarr[0];
                             $rng_to = $fs - 1;
                         }
                     } else {
                         // Range: bytes=###-###
                         if ($rngarr[0] > $fs || $rngarr[1] > $fs || $rngarr[0] > $rngarr[1]) {
                             $rng_from = "*";
                         } else {
                             $rng_from = $rngarr[0];
                             $rng_to = $rngarr[1];
                         }
                     }
                 }
             } else {
                 // Ranges unit not supported
                 $rng_from = "*";
             }
             if ($rng_from === "*") {
                 // Send all content with 416
                 $rq_err = 416;
                 $cgi_headers["Content-Range"] = "*";
             } else {
                 // Send partial content
                 $rq_err = 206;
                 $this->rng_from = $rng_from;
                 $this->rng_to = $rng_to;
                 $this->content_length = $rng_to - $rng_from + 1;
                 $cgi_headers["Content-Range"] = "bytes " . $rng_from . "-" . $rng_to . "/" . $fs;
             }
         } else {
             // Partial content has been disabled in conf
             $rq_err = 416;
             $cgi_headers["Content-Range"] = "*";
         }
     }
     if ($this->fp = @fopen($filename, NW_BSAFE_READ_OPEN)) {
         if ($this->rng_from) {
             fseek($this->fp, $rng_from);
             $this->cur_ptr = $rng_from;
         } else {
             $this->cur_ptr = 0;
         }
         $this->peof = false;
         // Return a static_response if possible
         if ($this->content_length <= $conf["global"]["staticbuffersize"][0]) {
             $content = fread($this->fp, $this->content_length);
             $this->parser_close();
             return new static_response($content);
         }
     } else {
         $rq_err = 404;
         $this->peof = true;
     }
 }
Ejemplo n.º 29
0
 function main()
 {
     global $http_uri, $rq_file, $conf, $docroot, $htreq_headers, $mime, $mime_enc, $out_add_headers, $pri_err;
     if (access_query("reflectrewriting", 0)) {
         global $real_uri;
     }
     // quick skip
     $enabled = strtolower(trim(access_query("multiviews", 0)));
     if ($enabled === "0" || $enabled == "off" || file_exists($docroot . $http_uri) && !is_dir($docroot . $http_uri)) {
         return;
     }
     // determine file name to be worked on
     $file = $http_uri;
     if ($last_slash = strrpos($file, "/")) {
         $act_path = substr($file, 0, $last_slash + 1);
         $file = substr($file, $last_slash + 1);
     }
     if ($file) {
         $allowed_filenames = array($file);
     } else {
         $allowed_filenames = explode(" ", access_query("directoryindex", 0));
     }
     // find files with same basename and different extensions
     $alternative_files = array();
     $dir = opendir($docroot . $act_path);
     while ($filename = readdir($dir)) {
         foreach ($allowed_filenames as $filebn) {
             if (!$filebn) {
                 continue;
             }
             $filebn .= ".";
             if (substr($filename, 0, strlen($filebn)) == $filebn) {
                 $alternative_files[] = $filename;
             }
         }
     }
     closedir($dir);
     if (empty($alternative_files)) {
         return 2;
     }
     // quick skip2
     #print_r($alternative_files);
     // fetch priorities
     $qualities = array_merge(array("php" => 0.75, "shtml" => 0.72, "html" => 0.71, "xhtml" => 0.7, "png" => 0.33, "jpeg" => 0.32, "gif" => 0.31), $this->parseQualities(implode(", ", access_query("otherpriority")), 1.3, 1.1), $this->parseQualities(@$htreq_headers["ACCEPT-FEATURES"], 1.15, 1), $this->parseQualities(strtr(access_query("languagepriority", 0), " ", ","), 0.8, 1.2), $this->parseQualities(@$htreq_headers["ACCEPT-LANGUAGE"], 1, 1.03), $this->parseQualities(@$htreq_headers["ACCEPT"], 1, 1.02), $this->parseQualities(strpos(@$htreq_headers["ACCEPT-ENCODING"], "gzip") !== false ? "gz" : "", 1.5, 1));
     // other algorithm flags
     $accept_all = strpos(@$htreq_headers["ACCEPT"], "*/*") !== false;
     $http10 = $GLOBALS['http_version'] < "1.1";
     $agent_negotiate = strpos($htreq_headers["NEGOTIATE"], "vlist") !== false || strpos($htreq_headers["NEGOTIATE"], "trans") !== false;
     // will contain variants and their attributes
     $alternates = array();
     // go thru filename extensions, and sum qualities
     foreach ($alternative_files as $filename) {
         $q_mime = -1;
         $q_enc = $q_lang = $q_features = $q_else = +1;
         $file_extensions = array_slice(explode('.', $filename), 1);
         foreach ($file_extensions as $ext) {
             $ext_q = $qualities[$ext];
             if (empty($ext_q) && $ext_q !== 0) {
                 if ($accept_all) {
                     $ext_q = 0.1;
                 } else {
                     $ext_q = 0.001;
                 }
             }
             if (@$mime[$ext]) {
                 $alternates[$filename]["type"] = $mime[$ext];
                 $q_mime += $ext_q + ($q_mime < 0 ? +1 : +0);
             } elseif (@$mime_enc[$ext]) {
                 $alternates[$filename]["encoding"] = $mime_enc[$ext];
                 $q_enc *= $ext_q;
             } elseif (strlen($ext) == 2) {
                 $alternates[$filename]["language"] = $ext;
                 $q_lang = $ext_q;
             } else {
                 $q_else *= 0.9;
             }
             if ($feature = $this->negotiate_features[$ext]) {
                 $alternates[$filename]["feature"] .= " {$feature};+1.2-0.9";
                 $q_features *= $qualities[$feature] ? 1.2 : 0.9;
                 $q_else /= 0.9;
             }
         }
         if ($q_mime < 0) {
             $q_mime = 0.005;
         }
         $alternates[$filename]["q"] = $q_mime * $q_enc * $q_lang * $q_features * $q_else;
     }
     // sort
     uasort($alternates, 'mod_multiviews_uarsort_by_q');
     #print_r($alternates);
     // return selected variant
     list($file) = array_keys($alternates);
     $real_uri = $http_uri = $act_path . $file;
     $rq_file = pathinfo($http_uri);
     // fallback output
     $out_add_headers["TCN"] = "adhoc";
     $out_add_headers["Vary"] = "negotiate";
     // server-driven negotiation
     if (!$agent_negotiation) {
         $out_add_headers["Content-Location"] = $file;
         if (!$http10) {
             $out_add_headers["TCN"] = "choice";
         }
         $out_add_headers["Vary"] = "negotiate, accept, accept-language, accept-features";
         foreach ($mime_enc as $ext => $encoding) {
             // report file's encoding
             if (strpos($file, ".{$ext}")) {
                 $out_add_headers["Content-Encoding"] = $encoding;
                 $GLOBALS["out_encoded"] = true;
             }
         }
     } else {
         $out_add_headers["TCN"] = "list";
         $GLOBALS["pri_err"] = $http10 ? 200 : 300;
         // HTTP 300 Choose Yourself
         $GLOBALS["out_contenttype"] = "text/html";
         $GLOBALS["add_errmsg"] = "The document you requested exists in different variants, and your browser gives you the opportunity to select one of them (or just does not support transparent content negotiation):<BR><UL>";
         foreach ($alternative_files as $f => $q) {
             $GLOBALS["add_errmsg"] .= '<LI><A HREF="' . url_to_absolute($act_path . $f) . '">' . $f . '</A></LI>';
         }
         $GLOBALS["add_errmsg"] .= "</UL>";
         if ($http10) {
             $out_add_headers["Refresh"] = "10; URL=" . url_to_absolute($http_uri);
         }
     }
     // add alternates-header
     $ah = " ";
     foreach ($alternates as $filename => $a) {
         $qstr = substr($a["q"], 0, 5);
         if (strpos($qstr, ".") === false) {
             $qstr .= ".";
         }
         while (strlen($qstr) < 5) {
             $qstr .= "0";
         }
         $ah .= '{ "' . $filename . '" ' . $qstr;
         unset($a["q"]);
         foreach ($a as $desc => $value) {
             $ah .= ' {' . $desc . ' ' . $value . '}';
         }
         $ah .= " },\n\t";
     }
     $ah .= "proxy-rvsa=1.0";
     $out_add_headers["Alternates"] = $ah;
     if ($GLOBALS['path_info']) {
         // may help(?)
         $out_add_headers["Content-Base"] = "/" . ($act_path ? "{$act_path}/" : "");
     }
     if ($http10) {
         $out_add_headers["Vary"] = "*";
     }
     if (is_dir($docroot . $http_uri) && !is_file($docroot . $http_uri . "/index.html") || strpos($file, ".var") !== false) {
         // very rare error / 506 Variant Also Negotiates
         $GLOBALS["pri_err"] = 506;
     }
 }
Ejemplo n.º 30
0
 function main()
 {
     global $pfilters, $lf, $out_contenttype, $chunky, $keepalive, $http_version;
     $used_filters = array();
     $chunky = !isset($lf->content_length) || $lf->content_length == NW_PLF_MAGIC;
     $hbn = basename($GLOBALS["http_uri"]);
     $hbnext = array_flip(explode(".", $hbn));
     // assign filters
     if (access_query("filterenable", 0)) {
         foreach (access_query("filter") as $filter_rule) {
             // split rule into: [ mime/ext _ filter _ fargs ]
             list($mimematch, $filter_rule) = explode(" ", ltrim($filter_rule), 2);
             @(list($fname, $fargs) = explode(" ", ltrim($filter_rule), 2));
             $fargs = trim($fargs);
             // check for missing mime match
             if (empty($fname) || empty($pfilters[strtolower($fname)])) {
                 if (strpos($mimematch, "/") === false && strpos($mimematch, "|") === false && strpos($mimematch, "*") === false && strpos($mimematch, ".") === false) {
                     $fargs = $fname . " " . $fargs;
                     $fname = $mimematch;
                     $mimematch = "*/*";
                 }
             }
             // is filter available
             $fname = strtolower($fname);
             if (empty($pfilters[$fname])) {
                 techo("filter '{$fname}' not available", NW_EL_ERROR);
                 continue;
             }
             // match mime / extension
             @(list($mime, $uu) = explode(";", $out_contenttype, 2));
             $mime = trim($mime);
             $no_match = true;
             foreach (explode("|", $mimematch) as $match) {
                 $ext = ltrim($match, ".");
                 if ($match == $mime || $match == "*/*" || $match == "*" || strpos($match, '*') !== false && strpos($mime, rtrim($match, "*")) !== false || $hbn == $match || isset($hbnext[$ext])) {
                     $no_match = false;
                     break;
                 }
             }
             if ($no_match) {
                 continue;
             }
             // most filters _may_ be used once only
             if (@$used_filters[$fname]++ && !($pfilters[$fname][1] & NW_PFILTER_MORE)) {
                 continue;
             }
             // convert to parser object (this should have been done already in the core)
             if (!is_object($lf)) {
                 $lf = new static_response($lf);
             }
             // real-static or parsed/chunked
             $fflags = $pfilters[$fname][1];
             if (NW_PFILTER_IMMEDIATE & $fflags || NW_PFILTER_STATIC & $fflags && is_a($lf, "static_response")) {
                 // filter content on the fly / immediate
                 $GLOBALS["first_chunk"] = true;
                 $pfilters[$fname][0]->filter_func($lf->str, $fargs);
                 $lf->content_length = strlen($lf->str);
                 techo("filter '{$fname}' run on static \$lf content", NW_EL_DEBUG);
             } elseif (($fflags & NW_PFILTER_ALL) >= NW_PFILTER_PARSED) {
                 if ($chunky && !($fflags & NW_PFILTER_CHUNKY)) {
                     continue;
                 }
                 // create wrapper around current $lf
                 $newf = $pfilters[$fname][0];
                 $newf->pp = $lf;
                 $newf->args = $fargs;
                 $newf->fflags = $fflags;
                 $newf->content_length = $lf->content_length;
                 $lf = $newf;
                 unset($newf);
                 techo("filter object '{$fname}' wrapped around current \$lf object", NW_EL_DEBUG);
             }
         }
     }
     #foreach(filter_rule)
     core_modules_hook("after_pfilters");
 }