запросы и разбор файлов apache

391
steve

Я только что столкнулся с интересной ситуацией на работе, которая, черт возьми, задела мое понимание того, как apache2 выполняет php-файлы.

У меня сложилось впечатление, что apache2 определит правильный тип файла и запустит его через правильный анализатор файлов. Это позволило бы парсеру выполнить фактическое выполнение, и из-за этого я понял, что php-файлы, выполняемые apache, должны иметь только права на чтение.

пример:

возьми простой php файл с 744 правами

#!/usr/bin/php <?php echo "test"; ?> 

выполнение этого с ./test.php выдает разрешение, в котором отказано.

но выполнение его с / usr / bin / php test.php работает нормально.

измените права на 755, и он работает правильно с ./test.php

Похоже, это то же самое, что происходит, когда apache запускает файл. это возвращает запрещенную ошибку.

итак, наконец, вот вопросы.

Как apache на самом деле обрабатывает и передает запросы на файлы?

Как он передает файл правильному парсеру?

Зачем ему нужны права на исполнение? Очевидно, синтаксический анализатор не только читает файл, как я первоначально ожидал.

Будьте нежны, пожалуйста .. Я ДУМАЛ, что я знал это.

0
Кто владеет файлом: вы, пользователь root или пользователь Apache (обычно это www-data)? Breakthrough 11 лет назад 0

1 ответ на вопрос

1
Rich Homolka

1) The execute perms on the file mean nothing to apache. That's just for the kernel to know how to execute the file if you try to exec it (say, through the shell). As long as you have read perms where apache can read it, you're fine.

EDIT the read perms were the important thing - apache needs execute perms on the directories all the way up to the root. For a directory, execute means searchable, and apache needs search perms on the directory to look for the file.

2) Apache doesn't 'pass off' the files. It doesn't execute them. You have an embedded interpreter in apache that can handle PHP files. This happens within the apache process. It gets configured this way:

You add the module:

LoadModule php5_module libexec/libphp5.so 

The module is compiled/created to know how to deal with parsing php. It is linked with the php interpreter, and basically consists of glue code for PHP to talk to apache, in the manner apache expects. The PHP module specifically knows how to deal with two MIME types, application/x-httpd-php and application/x-httpd-php-source. So, now you have to tell apache how to connect php files to the module. This is typically done with:

<IfModule mod_php5.c> AddType application/x-httpd-php .php AddType application/x-httpd-php-source .phps </IfModule> 

So, now we told apache to pass .php files to the PHP processor. Is going by suffix the only way? No, you could configure any directories to have all PHP files, or the entire server. But this makes the most sense. Also, notice that we don't care about the shebang line (#!/usr/bin/php). We're configured for file extension only.

3) OK, so why do you have the forbidden error? I don't know. There are many reasons why this could be. Have you checked the error log? Do you have the proper perms on the filesystem directory, where the apache process can read dirs all the way up to root? Do you have the proper perms in the config files? I'd check the error logs.

SECOND EDIT

I think I understand your confusion...

There are two ways of generating dynamic content through apache. One is through an embedded interpreter, like PHP. Perl and python are also common embedded interpreters. The webserver has the interpreter loading into the httpd process, using a glue module (mod_php, mod_perl, etc). The code is not "executed" but it is loaded, parsed and interpreted within the httpd process.

The second way is through a CGI script. In this case, apache does execute the file. The glue in this case is environment variables (apache sets some flags) and possibly standard input to the script. To send back to apache, you send content on standard out, which apache adds light decorations and sends to the client, and you send errors on stderr, which apache appends to it's error_log. The CGI spec dictates the rules on how this "glue" works. In this case, you are executing a file, so the execute permissions on the file are important to apache.

CGI is less common than it used to be. The advantages of CGI are that it's an isolated process from the webserver. It can't cause any damage to it (well, as long as parses the output securely). The disadvantages are the isolation. I need to fork/exec for every run (though there are some schemes called fastCGI that help this). PHP (among some others) also has a different coding model, where you add a bit of code to HTML, instead of writing a huge script and pushing out HTML from there. This makes it easier for most people to write, which is a big part of why PHP is so popular on the web.

Это имеет много смысла. Что я не понимаю, так это запрещенная ошибка. разрешения были 744 рекурсивно через каталог. Мне действительно нужно было установить его на 755, прежде чем он начал функционировать. steve 11 лет назад 0
@steve Если в справочнике DIRECTORY нет бита выполнения, проблема заключается в поиске файлов. Тогда я мог видеть вашу проблему, apache не мог найти файл из-за директории. Пермь файла должна быть только для чтения. Rich Homolka 11 лет назад 1
@steve Ха, спасибо, но не уверен в этом. только что был вокруг некоторое время Я использую Apache с 1996 года или около того, возможно, чуть раньше. Установка веб-серверов в целом с 1993 года. Rich Homolka 11 лет назад 0

Похожие вопросы