blog20100901

2013/08/20 - プログラミング言語 Perl にまつわる etc. - Perl monger
参考 : perldoc, perldoc.jp, search.cpan.org, perldoc.perl.org ...
「 初めての Perl 第 6 版 」(オライリー・ジャパン発行 ISBN978-4-87311-567-2) 」
「 続・初めての Perl 改訂版 」(オライリー・ジャパン発行 ISBN4-87311-305-9) 」
「 Effective Perl 第 2 版 」(翔泳社発行 ISBN978-4-7981-3981-4) 」 ... etc,.

Perl Perl_7 mod_perl 翻訳 Web Server

Perl mp2 翻訳 入力 and 出力 フィルタ (d198)

目次 - Perl Index


Theme



Perl について、復習を兼ねて断片的な情報を掲載して行く連載その d198 回。

今回は、「 mod_perl Home / The mod_perl Web Site / Documentation / mod_perl 2.0 Documentation / User's guide / Part V: mod_perl Handlers / Input and Output Filters 」を翻訳して確認します。

正確な内容は 原文 を確認してください。誤解や誤訳がある場合はご指摘ください。




説明 : Description



This chapter discusses mod_perl's input and output filter handlers.
このチャプタは mod_perl のインプットとアウトプットフィルタのハンドラを論じます。
If all you need is to lookup the filtering API proceed directly to the Apache2::Filter and Apache2::FilterRec manpages.

あなたが必要なのがフィルタリング API を探すことだけなら直接 Apache2::FilterApache2::FilterRec の man ページに進んでください。


フィルタの紹介 : Introducing Filters



You certainly already know how filters work, because you encounter filters so often in real life. If you are unfortunate to live in smog-filled cities like Saigon or Bangkok you are probably used to wear a dust filter mask:

あなたはもちろんどのようにフィルタが機能するか知っています, あなたは実生活でよくフィルタにエンカウントするからです。あなたが不運にもスモッグに満ちた都市に住むならあなたは多分防塵マスクの着用に慣れているでしょう:

dust mask
A quotation from Input and Output Filters


If you are smoker, chances are that you smoke cigarettes with filters:

あなたがスモーカーなら, フィルタ付きの煙草を吸う機会があるでしょう:

cigarrette filter
A quotation from Input and Output Filters


If you are a coffee gourmand, you have certainly tried a filter coffee:

あなたがコーヒー通なら, あなたは確実にフィルタコーヒーを試したでしょう:

coffee machine
A quotation from Input and Output Filters


The shower that you use, may have a water filter:

あなたが使うそのシャワーは, ウォーターフィルタをもっているかもしれません:

shower filter
A quotation from Input and Output Filters


When the sun is too bright, you protect your eyes by wearing sun goggles with UV filter:

太陽がとてもまぶしいなら, あなたはあなたの目を UV フィルタ付きのサンゴーグルをつけて保護します:

sun goggles
A quotation from Input and Output Filters


If are a photographer you can't go a step without using filter lenses:

フォトグラファーならあなたはフィルタレンズを使うことなしに次のステップができません:

photo camera
A quotation from Input and Output Filters


If you love music, you might be unaware of it, but your super-modern audio system is literally loaded with various electronic filters:

あなたが音楽を愛しているなら, あなたはそれを知らないかもですが, あなたの超モダンなオーディオシステムは文字通りさまざまなエレクトロニックフィルタを搭載しています:

LP player
A quotation from Input and Output Filters


There are many more places in our lives where filters are used. The purpose of all filters is to apply some transformation to what's coming into the filter, letting something different out of the filter. Certainly in some cases it's possible to modify the source itself, but that makes things unflexible, and but most of the time we have no control over the source. The advantage of using filters to modify something is that they can be replaced when requirements change Filters also can be stacked, which allows us to make each filter do simple transformations. For example by combining several different filters, we can apply multiple transformations. In certain situations combining several filters of the same kind let's us achieve a better quality output.

私たちが住んでいる場所でフィルタが使われている場所はもっとたくさんの場所があります。すべてのフィルタの目的はフィルタに入って来るものに何らかの変換を適用して, 何か違うものをフィルタから出すことです。たしかにいくつかのケースではソース自体を修正できますが, それは柔軟性を欠くものになり, 大抵の場合で私たちはソースのコントロールができません。何かを修正するためにフィルタを使うアドバンテージは要求が変更されたときにそれらをリプレイスできることです。またフィルタはスタックすることもできるので, 私たちは各フィルタがシンプルな変換を行うようにできます。例えばいくつかの異なるフィルタを組み合わせることで, 私たちは複数の変換を適用できます。特定の状況での同じ種類のいくつかのフィルタを組み合わせは私たちがより良いクオリティの出力をできるようにします。
The mod_perl filters are not any different, they receive some data, modify it and send it out. In the case of filtering the output of the response handler, we could certainly change the response handler's logic to do something different, since we control the response handler. But this may make the code unnecessary complex. If we can apply transformations to the response handler's output, it certainly gives us more flexibility and simplifies things. For example if a response needs to be compressed before sent out, it'd be very inconvenient and inefficient to code in the response handler itself. Using a filter for that purpose is a perfect solution. Similarly, in certain cases, using an input filter to transform the incoming request data is the most wise solution. Think of the same example of having the incoming data coming compressed.

mod_perl フィルタは何も違いません, それらは何かのデータを受けとり, それを変更し外に送ります。レスポンスハンドラの出力をフィルタリングするケースでは, レスポンスハンドラのロジックを何か異なるものを行うように, 私たちはきっと変更するでしょう, 私たちがレスポンスハンドラを制御するからです。しかしこれはコードを不必要に複雑にするかもしれません。私たちがレスポンスハンドラの出力に変換を適用できるなら, それはより柔軟性がありシンプルになったものを私たちに確実に与えます。例えばレスポンスが送信されるまえに圧縮されることを必要とする場合, レスポンスハンドラ自身にコード化するのはとても不便で非効率になるでしょう。その目的でフィルタを使うのはパーフェクトなソリューションです。同様に, 特定のケースで, インカミングのリクエストデータの変換にインプットフィルタを使うのは賢いソリューションです。インカミングデータが圧縮される同じ例を考えてみてください。
Just like with real life filters, you can pipe several filters to modify each other's output. You can also customize a selection of different filters at run time.

実生活のフィルタと同じように, あなたはお互いの出力を修正するためにいくつかのフィルタをパイプできます。
またあなたはランタイムでいろいろなフィルタの選択をカスタマイズできます。
Without much further ado, let's write a simple but useful obfuscation filter for our HTML documents.

面倒な話はおわりにして, 私たちの HTML ドキュメントのためにシンプルだが便利な難読化フィルタを書いてみましょう。
We are going to use a very simple obfuscation -- turn an HTML document into a one liner, which will make it harder to read its source without a special processing. To accomplish that we are going to remove characters \012 (\n) and \015 (\r), which depending on the platform alone or as a combination represent the end of line and a carriage return.

私たちはとてもシンプルな難読化を使います -- HTML ドキュメントを 1 行にする, これは特別な処理なしにそのソースが読みにくくなります。それをするために私たちは \012 (\n) と \015 (\r) を削除します, これはプラットフォームに応じて単独でまたは組み合わせで行末 (# end of line) とキャリッジリターンを表します。
And here is the filter handler code:

そしてこちらがフィルタハンドラのコードです:

#file:MyApache2/FilterObfuscate.pm
#--------------------------------
package MyApache2::FilterObfuscatte;

use strict;
use warnings;

use Apache2::Filter ();
use Apache2::RequestRec ();
use APR::Table ();

use Apache2::Const -compile => qw(OK);

use constant BUFF_LEN => 1024;

sub handler {
my $f = shift;

unless ($f->ctx) {
$f->r->headers_out->unset('Content-Length');
$f->ctx(1);
}

while ($f->read(my $buffer, BUFF_LEN)) {
$buffer =~ s/[\r\n]//g;
$f->print($buffer);
}

return Apache2::Const::OK;
}
1;

The directives below configure Apache to apply the MyApache2::FilterObfuscate filter to all requests that get mapped to files with an ".html" extension:

以下のディレクティブは ".html" 拡張子のファイルにマップされたすべてのリクエストに MyApache2::FilterObfuscate フィルタを適用するために Apache を構成します:

<Files ~ "\.html">
PerlOutputFilterHandler MyApache2::FilterObfuscate
</Files>

Filters are expected to return Apache2::Const::OK or Apache2::Const::DECLINED. But instead of receiving $r (the request object) as the first argument, they receive $f (the filter object). The filter object is described later in this chapter.

フィルタは Apache2::Const::OK か Apache2::Const::DECLINED をリターンすることを期待されています。しかし最初の引数として $r (リクエストオブジェクト) を受けとるかわりに, それは $f (フィルタオブジェクト) を受けとります。フィルタオブジェクトはこのチャプタの後半で説明されています。
The filter starts by unsetting the Content-Length response header, because it modifies the length of the response body (shrinks it). If the response handler sets the Content-Length header and the filter doesn't unset it, the client may have problems receiving the response since it will expect more data than it was sent. Setting the Content-Length Header below describes how to set the Content-Length header if you need to.

このフィルタは Content-Length レスポンスヘッダのアンセッティングでスタートします, それはレスポンスボディの長さを修正するからです (短くする)。レスポンスハンドラが Content-Length ヘッダをセットしてフィルタがそれをアンセットしない場合, クライアントは送信されるよりもより多くのデータを期待するのでそのレスポンスの受け取りで問題をもつかもしれません。あなたが必要とするなら以下の Setting the Content-Length Header でどのように Content-Length ヘッダをセットするかを説明します。
The core of this filter is a read-modify-print expression in a while loop. The logic is very simple: read at most BUFF_LEN characters of data into $buffer, apply the regex to remove any occurences of \n and \r in it, and print the resulting data out. The input data may come from a response handler, or from an upstream filter. The output data goes to the next filter in the output chain. Even though in this example we haven't configured any more filters, internally Apache itself uses several core filters to manipulate the data and send it out to the client.

このフィルタのコアは while ループの 読み込み-修正-出力の式です。このロジックはとてもシンプルです: 最大で BUFF_LEN 分の文字のデータを $buffer に読み込み, その中で発生するすべての \n と \r を削除するために正規表現を適用し, 結果のデータを出力します。インプットデータはレスポンスハンドラから, またはアップストリームのフィルタからくるかもしれません。アウトプットデータはアウトプットチェーンの次のフィルタに行きます。この例では私たちはこれ以上の構成されたフィルタをもっていませんが, 内部的に Apache 自身はデータを操作してクライアントにそれを送信するためにいくつかのコアフィルタを使っています。
As we are going to explain in detail in the following sections, the same filter may be called many times during a single request, every time receiving a subsequent chunk of data. For example if the POSTed request data is 64k long, an input filter could be invoked 8 times, each time receiving 8k of data. The same may happen during the response phase, where an upstream filter may split 64k of output in 8, 8k chunks. The while loop that we just saw is going to read each of these 8k in 8 calls, since it requests 1k on every read() call.

私たちが次のセクションで詳細に説明するように, サブシークエンスのデータチャンク (# データの塊り) を受けとるたびに, 同じフィルタがひとつのリクエストの間に何度も呼ばれるかもしれません。例えばリクエストデータが 64k の長さで POST された場合, インプットフィルタは 8 回呼びだされることになり, 各回で 8 k のデータを受けとります。アップストリームのフィルタが 64k を 8k のチャンクで, 8 回の出力に分割していたらレスポンスフェーズでも同じことが起こるかもしれません。私たちが見た while ループは 8 回のコールでそれぞれ 8k 読み込みます, それが常に read() のコールで 1k をリクエストするからです。
Since it's enough to unset the Content-Length header when the filter is called the first time, we need to have some flag telling us whether we have done the job. The method ctx() provides this functionality:

フィルタが最初に呼ばれたときに Content-Length ハンドラをアンセットすれば十分なので, 私たちは私たちが仕事を終えたかどうかを私たちに伝える何らかのフラグを必要とします。メソッド ctx() はこの機能を提供します:

unless ($f->ctx) {
$f->r->headers_out->unset('Content-Length');
$f->ctx(1);
}

The unset() call will be made only on the first filter call for each request. You can store any kind of a Perl data structure in $f->ctx and retrieve it later in subsequent filter invocations of the same request. There are several examples using this method in the following sections.

unset() のコールは各リクエストの最初のフィルタのコールでのみになります。あなたは Perl データ構造のあらゆる種類を $f->ctx に格納して同じリクエストのそれに続くフィルタの呼び出しの中で後で取得できます。続くセクションにこのメソッドをつかった例がいくつかあります。
To be truly useful, the MyApache2::FilterObfuscate filter logic should take into account situations where removing new line characters will make the document render incorrectly in the browser. As we mentioned above, this is the case if there are multi-line <pre>...</pre> entries. Since this increases the complexity of the filter, we will disregard this requirement for now.

本当に役立つようにするために, MyApache2::FilterObfuscate フィルタロジックは改行文字を削除した場合にブラウザでドキュメントが不正確にレンダリングされる状況を考慮にいれなければなりません。私たちが上で述べたように, これはマルチラインの <pre>...</pre> エントリがあった場合のケースです。これはフィルタの複雑さを増すので, 私たちは今はこの要件を無視します。
A positive side-effect of this obfuscation algorithm is that it reduces the amount of the data sent to the client. The Apache::Clean module, available from the CPAN, provides a production-ready implementation of this technique which takes into account the HTML markup specifics.

この難読化アルゴリズムのポジティブな副作用はクライアントに送るデータの量が減少することです。Apache::Clean モジュールは, CPAN から利用可能な, HTML マークアップの仕様を考慮にいれたこのテクニックのプロダクションレディの実装を提供します。
mod_perl I/O filtering follows the Perl principle of making simple things easy and difficult things possible. You have seen that it's trivial to write simple filters. As you read through this chapter you will see that much more difficult things are possible, and that the code is more elaborate.

mod_perl I/O フィルタリングは簡単なものをシンプルに難しいものを可能にするという Perl の原則をフォローします。あなたはシンプルなフィルタを書くのは些細なことだということを見ました。あなたがこのチャプタを読み通すとあなたはより難しいことが可能で, そのコードはより入り組んだものになることが分かります。


I/O フィルタリングのコンセプト : I/O Filtering Concepts



Before introducing the APIs, mod_perl provides for Apache Filtering, there are several important concepts to understand.

mod_perl が提供する Apache フィルタリングための, API を導入する前に, いくつか理解しておくべき重要なコンセプトがあります。


データ操作のための 2 つのメソッド : Two Methods for Manipulating Data



mod_perl provides two interfaces to filtering: a direct bucket brigades manipulation interface and a simpler, stream-oriented interface. Apache 2.0 considers all incoming and outgoing data as chunks of information, disregarding their kind and source or storage methods. These data chunks are stored in buckets, which form bucket brigades. Input and output filters massage the data in these bucket brigades. Response and protocol handlers also receive and send data using bucket brigades, though in most cases this is hidden behind wrappers, such as read() and print().

mod_perl はフィルタリングのための 2 つのインターフェイスを提供します: ダイレクト bucket brigades マニピュレーション (# バケツリレー操作) インターフェイスとよりシンプルな, ストリーム指向のインターフェイスです。Apache2.0 はすべてのインカミングとアウトゴーイングデータを情報のチャンク (# 塊り) として見做し, それらの種類とソースまたはスレージメソッドを無視します。これらのデータチャンクは bucket (# バケツ) に格納され, bucket bridades (# バケツリレー) を形成します。インプットとアウトプットフィルタはそれらの bucket brigades でデータをマッサージ (# 操作) します。またレスポンスとプロトコルハンドラは bucket brigedes を使って受信と送信をしますが, ほとんどのケースでこれは read() や print() のような, ラッパーの背後に隠されています。
mod_perl 2.0 filters can directly manipulate the bucket brigades or use the simplified streaming interface where the filter object acts similar to a filehandle, which can be read from and printed to.

mod_perl 2.0 フィルタは bucket brigades の直接的な操作やフィルタオブジェクトが読み込んだり出力したりといった, ファイルハンドルと似た動作をするよりシンプルなストリーミングインターフェイスを使えます。
Even though you don't use bucket brigades directly when you use the streaming filter interface (which works on bucket brigades behind the scenes), it's still important to understand bucket brigades. For example you need to know that an output filter will be invoked as many times as the number of bucket brigades sent from an upstream filter or a content handler. Or you need to know that the end of stream indicator (EOS) is sometimes sent in a separate bucket brigade, so it shouldn't be a surprise that the filter was invoked even though no real data went through. As we delve into the filter details you will see that understanding bucket brigades, will help to understand how filters work.

あなたがストリーミングインターフェイス (bucket brigades の舞台裏で機能する) を使うときにあなたが直接 bucket brigades を使わないとしても, bucket birgades の理解は依然として重要です。例えばアウトプットフィルタがアップストリームのフィルタやコンテンツハンドラから送られた bucket brigades の数だけ何度も呼びだされることをあなたは知る必要があります。またはストリーム終了インジケータ (# EOS : the End Of Stream) が別の bucket brigade でときおり送られることをあなたは知る必要がります, ですからフィルタが呼び出されたのに実データが何も通過しないことに驚いてはいけません。私たちはフィルタの詳細を掘り下げるのであなたは bucket brigades を理解すると, どのようにフィルタが機能するかの理解を助けることがわかります。
Moreover you will need to understand bucket brigades if you plan to implement protocol modules.

そのうえあなたがプロトコルモジュールの実装を計画しているならあなたは bucket brigades を理解する必要があるでしょう。


HTTP リクエストとコネクションのフィルタ比較 : HTTP Request Versus Connection Filters



HTTP request filters are applied when Apache serves an HTTP request. HTTP request input filters get invoked on the body of the HTTP request only if the body is consumed by the content handler. HTTP request headers are not passed through the HTTP request input filters. HTTP response output filters get invoked on the body of the HTTP response if the content handler has generated one. HTTP response headers are not passed through the HTTP response output filters.

HTTP リクエストフィルタは Apache が HTTP リクエストをサーブするときに適用されます。HTTP リクエストインプットフィルタはボディがコンテンツハンドラで消費される場合のみ HTTP リクエストのボディで呼びだされます。HTTP リクエストハンドラは HTTP リクエストインプットフィルタを通りません。HTTP レスポンスアウトプットフィルタはコンテンツハンドラがそれを生成した場合のみ HTTP レスポンスのボディで呼びだされます。HTTP レスポンスハンドラは HTTP レスポンスアウトプットフィルタを通りません。
It is also possible to apply filters at the connection level. A connection may be configured to serve one or more HTTP requests, or handle other protocols. Connection filters see all the incoming and outgoing data. If an HTTP request is served, connection filters can modify the HTTP headers and the body of request and response. If a different protocol is served over the connection (e.g., IMAP), the data could have a completely different pattern than the HTTP protocol (headers + body). Thus, the only difference between connection filters and request filters is that connection filters see everything from the request, i.e., the headers and the body, whereas request filters see only the body.

コネクションレベルでもフィルタを適用することは可能です。コネクションは 1 つ以上の HTTP リクエストをサーブする, または他のプロトコルを処理するために構成されるはずです。コネクションフィルタはすべてのインカミングとアウトゴーイングデータを見ます。HTTP リクエストがサーブされた場合, コネクションフィルタは HTTP ハンドラとリクエストとレスポンスとのボディを修正できます。コネクション上で異なるプロトコルがサーブされた場合 (e.g., IMAP), データは HTTP プロトコル (headers + body) とは完全に異なるパターンを持っているかもしれません。ですから, コネクションフィルタとリクエストフィルタの間での唯一の違いはコネクションフィルタがリクエストからのすべてを見ることです, i.g., ヘッダとそのボディですが, リクエストフィルタはボディのみを見ます。
mod_perl 2.0 may support several other Apache filter types in the future.

mod_perl 2.0 は将来的に他の Apache フィルタタイプをいくつかサポートするかもしれません。


フィルタハンドラの複数呼びだし : Multiple Invocations of Filter Handlers



Unlike other Apache handlers, filter handlers may get invoked more than once during the same request. Filters get invoked as many times as the number of bucket brigades sent from an upstream filter or a content provider.

他の Apache ハンドラと違い, フィルタハンドラは同じリクエストの間に 1 回以上呼びだされるかもしれません。フィルタはアップストリームフィルタやコンテンツプロバイダから送られた bucket brigades の数だけ何度も呼びだされます。
For example, a content generation handler may send a string, then force a flush, and then send more data:

例えば, コンテンツジェネレーションハンドラは文字列を送り, それからフラッシュを強制し, その後さらにデータを送信するかもしれません:

# assuming buffered STDOUT ($|==0)
$r->print("foo");
$r->rflush;
$r->print("bar");

In this case, Apache will generate one bucket brigade with two buckets. There are several types of buckets which contain data; in this example, the data type is transient:

このケースで, Apache は 2 つの buckets でひとつの bucket brigade を生成します。データを含む buckets にはいくつかのデータタイプがあります; この例では, データタイプは transient (# 一時的) です:

bucket tyep data
----------------------
1st transient foo
2nd flush

Apache sends this bucket brigade to the filter chain. Then, assuming no more data is sent after print("bar"), it will create a last bucket brigade, with one bucket, containing data:

Apache はこの bucket brigade をフィルタチェーンに送信します。それから, print("bar") の後で送信するデータはないと仮定して, データを含む, 最後の bucket brigade を, ひとつの bucket で作成し:

bucket tyep data
----------------------
1st transient bar

and send it to the filter chain. Finally it will send yet another bucket brigade with the EOS bucket indicating that there will be no more data sent:

それからフィルタチェーンに送信されます。最後にもう送るデータがないことを示す EOS bucket をもつさらに別の bucket brigade を送信します:

bucket tyep data
----------------------
1st eos

EOS buckets are valid for request filters. For connection filters, you will get one only in the response filters and only at the end of the connection. You can see a sample workaround for this situation in the module Apache2::Filter::HTTPHeadersFixup available on the CPAN.

EOS buckets はリクエストフィルタに有効です。コネクションフィルタでは, あなたはレスポンスフィルタでありコネクションの終わりでのみそれをゲットします。あなたは CPAN で利用可能なモジュール Apache2::Filter::HTTPHeadersFixup でこの状況の回避策のサンプルを見ることができます。
Note that the EOS bucket may come attached to the last bucket brigade with data, instead of coming in its own bucket brigade. The location depends on the other Apache modules manipulating the buckets and can vary. Filters should never assume that the EOS bucket is arriving alone in a bucket brigade. Therefore the first output filter will be invoked two or three times (three times if EOS is coming in its own brigade), depending on the number of bucket brigades sent by the response handler.

EOS bucket は独自の bucket brigade で来るかわりに, 最後の bucket brigade にデータを付属して来るかもしれないことに注意して下さい。ロケーションは他の Apache モジュールが操作する buckets に依存していて変わることがあります。フィルタは単独の bukect brigade で EOS bucket が到着することを決して想定してはいけません。したがって最初のアウトプットフィルタはレスポンスハンドラにより bucket brigades が送信された回数によって, 2 または 3 回 (EOS が独自の brigade で来ると 3 回) 呼びだされます。
An upstream filter can modify the bucket brigades, by inserting extra bucket brigades or even by collecting the data from multiple bucket brigades and sending it along in just one brigade. Therefore, when coding a filter, never assume that the filter is always going to be invoked once, or any fixed number of times. Neither can you assume how the data is going to come in. To accommodate these situations, a typical filter handler may need to split its logic in three parts.

アップストリームフィルタは追加の bucket brigades を追加することや複数の bucket brigades からデータを収集しそれをひとつの brigade で一緒に送信することで bucket brigades を修正できます。したがって, フィルタをコーディングするとき, フィルタが常に 1 度, または固定回数呼びだされることを決して想定してはいけません。あなたはデータがどのようにやってくるかも想定することはできません。これらの状況に対応するためには, 典型的なフィルタハンドラはそのロジックを 3 つの部分に分割する必要があります。
To illustrate, below is some pseudo-code that represents all three parts, i.e., initialization, processing, and finalization. This is a typical stream-oriented filter handler.

説明のために, 以下は 3 つすべてのパートを表す疑似コードです, i.e., 初期化, 処理, それから最終処理です。これは典型的なストリーム指向のフィルタハンドラです。

sub handler {
my $f = shift;

# runs on first invocation
unless ($f->ctx) {
init($f);
$f->ctx(1);
}

# runs on all invocations
process($f);

# runs on the last invocation
if ($f->seen_eos) {
finalize($f);
}

return Apache2::Const::OK;
}
sub init { ... }
sub process { ... }
sub finalize { ... }

The following diagram depicts all three parts:

次のダイアグラムは 3 つのパートすべてを描写します:

filter flow logic
A quotation from Input and Output Filters


Let's explain each part using this pseudo-filter.

この疑似フィルタを使って各パートの説明をしましょう。


  1. Initialization : 初期化
    During initialization, the filter runs code that you want executed only once, even if there are multiple invocations of the filter (this is during a single request). The filter context ($f->ctx) is used as a flag to accomplish this task. For each new request the filter context is created before the filter is called for the first time, and it is destroyed at the end of the request.

    初期化の間, 複数のフィルタの呼び出し (これはひとつのリクエストの間でです) があったとしても, フィルタはあなたが 1 度だけ実行したいコードを実行します。フィルタコンテキスト ($f->ctx) はこのタスクをやるためのフラグとして使われます。新しいリクエストそれぞれでフィルタコンテキストは最初にフィルタが呼ばれる前に作成されて, それはリクエストの最後で破棄されます。

    unless ($f->ctx) {
    init($f);
    $f->ctx(1);
    }

    When the filter is invoked for the first time $f->ctx returns undef and the custom function init() is called. This function could, for example, retrieve some configuration data set in httpd.conf or initialize some data structure to a default value.

    フィルタが最初の回で呼びだされたとき $f->ctx は undef をリターンしカスタムファンクションの init() が呼びだされます。このファンクションは, 例えば, httpd.conf の何らかの構成データセットを取得したり何らかのデータ構造をデフォルト値に初期化したりできます。
    To make sure that init() won't be called on the following invocations, we must set the filter context before the first invocation is completed:

    init() が続く呼びだしでコールされないようにするために, 私たちは最初の呼びだしが完了する前にフィルタコンテキストをセットしなければなりません:

    $f->ctx(1);

    In practice, the context is not just used as a flag, but to store real data. You can use it to hold any data structure and pass it between successive filter invocations. For example, the following filter handler counts the number of times it was invoked during a single request:

    実際には, コンテクストはフラグとしてだけではなく, 実データの格納にも使われます。あなたはこれをデータ構造を保持してそれを連続するフィルタ呼びだしの間で渡すことに使えます。例えば, 次のフィルタハンドラはひとつのリクエストの間にそれが呼びだされた回数をカウントします:

    sub handler {
    my $f = shift;

    my $ctx = $f->ctx;
    $ctx->{invoked}++;
    $f->ctx($ctx);
    warn "filter was invoked $ctx->{invoked} times\n";

    return Apache2::Const::DECLINED;
    }

    Since this filter handler doesn't consume the data from the upstream filter, it's important that this handler return Apache2::Const::DECLINED, in which case mod_perl passes the current bucket brigade to the next filter. If this handler returns Apache2::Const::OK, the data will be lost, and if that data included a special EOS token, this may cause problems.

    このフィルタハンドラはアップストリームからのデータを消費しないので, このハンドラが Apache2::Const::DECLINED をリターンしていることが重要で, このケースで mod_perl は現在の bucket brigade を次のフィルタに渡します。このハンドラが Apache2::Const::OK をリターンすると, データはロストされ, そのデータが特別な EOS トークンを含んでいたなら, これは問題を発生させるかもしれません。
    Unsetting the Content-Length header for filters that modify the response body length is a good example of code to run in the initialization phase:

    レスポンスボディの長さを変更するフィルタのために Content-Length をアンセッティングするのは初期化フェーズで実行するコードのグッドな例です:

    unless ($f->ctx) {
    $f->r->headers_out->unset('Content-Length');
    $f->ctx(1);
    }

    We will see more initialization examples later in this chapter.

    私たちはこのチャプタの後半でより多くの初期化の例を見ます。


  2. Processing : 処理
    The next part:

    次のパート:

    process($f);

    is unconditionally invoked on every filter invocation. That's where the incoming data is read, modified and sent out to the next filter in the filter chain. Here is an example that lowers the case of the characters passing through:

    これはすべてのフィルタの呼びだしで無条件に呼びだされます。ここでインカミングデータは読み込み, 修正されフィルタチェーンの次のフィルタに送り出されます。こちらが通過する文字を小さくする例です。

    use constant READ_SIZE => 1024;
    sub process {
    my $f = shift;
    while ($f->read(my $data, READ_SIZE)) {
    $f->print(lc $data);
    }
    }

    Here the filter operates only on a single bucket brigade. Since it manipulates every character separately the logic is simple.

    ここでフィルタはひとつの bucket brigade でのみ作動します。すべての文字を別々に操作するのでロジックはシンプルです。
    In more complicated situations, a filter may need to buffer data before the transformation can be applied. For example, if the filter operates on HTML tokens (e.g., '>img src="me.jpg">'), it's possible that one brigade will include the beginning of the token ('>img ') and the remainder of the token ('src="me.jpg">') will come in the next bucket brigade (on the next filter invocation). To operate on the token as a whole, you would need to capture each piece over several invocations. To do so, you can store the unprocessed data in the filter context and then access it again on the next invocation.

    より複雑なシチュエーションでは, フィルタは変換を適用する前にバッファデータを必要とするかもしれません。例えば, フィルタが HTML トークン (e.g., '>img src="me.jpg">') 上で作動する場合, ひとつの brigade はトークンの開始 ('>img ') を含み残りのトークン ('src="me.jpg">') は次の bucket brigade で来る可能性があります (次のフィルタの呼びだしで)。トークン全体を操作するために, あなたはいくつかの呼び出しでの各ピースのキャプチャする必要があるでしょう。それを行うに, あなたは未処理のデータをフィルタコンテキストに格納しそれから次の呼びだしでそれに再びアクセスします。
    Another good example of the need to buffer data is a filter that performs data compression, because compression is usually effective only when applied to relatively big chunks of data. If a single bucket brigade doesn't contain enough data, the filter may need to buffer the data in the filter context until it collects enough to compress it.

    バッファデータを必要とするもうひとつのグッドな例はデータ圧縮を実行するフィルタです, 圧縮は通常比較的大きなデータチャンクに適用されたときにだけ効果的だからです。ひとつの bucket brigade が十分なデータを持っていなかった場合, フィルタは圧縮するのに十分なデータを集めるまでフィルタコンテキストでそのバッファを必要とするはずです。


  3. Finalization : 最終処理
    Finally, some filters need to know when they are invoked forfr the last time, in order to perform various cleanups and/or flush any remaining data. As mentioned earlier, Apache indicates this event by a special end of stream "token", represented by a bucket of type EOS. If the filter is using the streaming interface, rather than manipulating the bucket brigades directly, and it was calling read() in a while loop, it can check for the EOS token using the $f->seen_eos method:

    最後に, 一部のフィルタは様々なクリーンアップを実行する and/or 残ったデータをフラッシュするために, それらが最後に呼びだされときを知る必要があります。前述したように, Apache はタイプ EOS の bucket で表現される, 特別なストリーム終了 "トークン" でこのイベントを示します。フィルタが bucket brigade を直接操作するのではなく, ストリームインターフェイスで使われていて, while ループ内で read() を呼びだしていた場合, $f->seen_eos メソッドを使て EOS トークンをチェックできます:

    if ($f->seen_eos) {
    finalize($f);
    }

    This check should be done at the end of the filter handler because the EOS token can come attached to the tail of some data or all alone such that the last invocation gets only the EOS token. If this test is performed at the beginning of the handler and the EOS bucket was sent in together with the data, the EOS event may be missed and the filter won't function properly.

    このチェックは EOS トークンは何らかのデータの末尾に付属しているまたは EOS トークンのみをゲットする最後の呼びだしのような単独でくることができるのでフィルタハンドラの最後で行われる必要があります。このテストがハンドラの開始で実行され EOS bucket がデータと一緒に送信されると, EOS イベントは見逃されてフィルタが正しく機能しないかもしれません。
    Filters that directly manipulate bucket brigades must manually look for a bucket whose type is EOS. There are examples of this method later in the chapter.

    bucket brigades を直接操作するフィルタはタイプが EOS の bucket を手動で探さなければなりません。チャプタの後半にこのメソッドの例があります。


While not all filters need to perform all of these steps, this is a good model to keep in mind while working on your filter handlers. Since filters are called multiple times per request, you will likely use these steps, with initialization, processing, and finishing, on all but the simplest filters.

全てのフィルタがこれらのステップを実行する必要はありませんが, これはあなたのフィルタハンドラが働くときに覚えておくとよいモデルです。フィルタはリクエストごとに複数回呼ばれるので, あなたはよほどシンプルではないすべてのフィルタでこれらの初期化, 処理, それから最終処理のステップを使うでしょう。


コールをブロックする : Blocking Calls



All filters (excluding the core filter that reads from the network and the core filter that writes to it) block at least once when invoked. Depending on whether this is an input or an output filter, the blocking happens when the bucket brigade is requested from the upstream filter or when the bucket brigade is passed to the downstream filter.

すべてのフィルタ (ネットワークから読み取るコアフィルタとそれに書き込みをするコアフィルタを除く) は呼びだされたときに少なくとも一度はブロックします。これがインプットかアウトプットのフィルタかに応じて, bucket brigade がアップストリームフィルタからリクエストされたときまたは bucket brigade がダウンストリームフィルタに渡されたときにブロッキングは発生します。
Input and output filters differ in the ways they acquire the bucket brigades, and thus in how blocking is handled. Each type is described separately below. Although you can't see the difference when using the streaming API, it's important to understand how things work underneath. Therefore the examples below are transparent filters, passing data through them unmodified. Instead of reading the data in and printing it out, the bucket brigades are passed as is. This makes it easier to observe the blocking behavior.

インプットとアウトプットフィルタはそれらが bucket brigades を獲得するやり方, したがってどのようにブロッキングが処理されるかが違います。各タイプは以下で個別に説明されています。あなたがストリーミング API を使っているときは違いが見えませんが, その直下でどのように物事が機能しているかを理解することは重要です。したがって以下の例は透過的なフィルタで, データは修正されずに通り抜けます。その中でデータを読んでそれ外にを出力するかわりに, bucket brigades がそのまま渡されます。これはブロッキングの振る舞いの観察を簡単にします。
The first example is a transparent input filter:

最初の例は透過的なインプットフィルタです:

#file:MyApache2/FilterTransparent.pm (first part)
#-----------------------------------------------
package MyApache2::FilterTransparent;

use Apache2::Filter ();

use Apache2::Const -compile => qw(OK);
use APR::Const -compile => ':common';

sub in {
my ($f, $bb, $mode, $block, $readbytes) = @_;

my $rv = $f->next->get_brigade($bb, $mode, $block, $readbytes);
return $rv unless $rv == APR::Const::SUCCESS;

return Apache2::Const::OK;
}

When the input filter in() is invoked, it first asks the upstream filter for the next bucket brigade (using the get_brigade() call). That upstream filter is in turn going to ask for the bucket brigade from the next upstream filter and so on up the chain, until the last filter (called core_in), the one that reads from the network, is reached. The core_in filter reads, using a socket, a portion of the incoming data from the network, processes it, and sends it to its downstream filter. That filter processes the data and send it to its downstream filter, etc., until it reaches the first filter that requested the data. (In reality some other handler triggers the request for the bucket brigade, such as an HTTP response handler or a protocol module, but for this discussion it's sufficient to assume that it's the first filter that issues the get_brigade() call.)

インプットフィルタ in() が呼びだされたとき, それは最初にアップストリームフィルタに次の bucket brigade を要請します (get_brigade() のコールを使って)。 そのアップストリームフィルタはネットワークから呼ばれる, 最後のフィルタ (core_in と呼ばれる) がリーチするまで, 次のアップストリームフィルタなど上のチェーンに, bucket brigade を順番に要請します。core_in フィルタは, ネットワークからのインカミングデータの一部を, ソケットを使って読み, それを処理し, ダウンストリームフィルタにそれを送ります。そのフィルタはデータを処理してそのデータをリクエストした最初のフィルタにリーチするまでダウンストリームフィルタ, etc. に送信します。(実際には HTTP レスポンスハンドラやプロトコルモジュールのような一部の他のハンドラが, bucket brigade のリクエストをトリガしますが, この議論ではそれが get_brigade() をコールする最初のフィルタという想定で十分です。)
The following diagram depicts a typical input filter data flow in addition to the program control flow.

次のダイアグラムはプログラムのコントロールフローに加えて典型的なインプットフィルタのデータフローを描写します。

input filter data flow
A quotation from Input and Output Filters


The black- and white-headed arrows show when the control is passed from one filter to another. In addition, the black-headed arrows show the actual data flow. The diagram includes some pseudo-code, in Perl for the mod_perl filters and in C for the internal Apache filters. You don't have to understand C to understand this diagram. What's important to understand is that when input filters are invoked, they first call each other via the get_brigade() call and then block (notice the brick wall on the diagram), waiting for the call to return. When this call returns, all upstream filters have already completed their filtering task on the bucket brigade.

黒と白の頭の矢印はあるフィルタから他へとそのコントロールが渡されるときを示しています。加えて, 黒い頭の矢印は実際のデータフローを示しています。このダイアグラムは mod_perl フィルタの Perl と内部の Apache フィルタの C の, 疑似コードをいくつか含みます。あなたはこのダイアグラムを理解するために C を理解する必要はありません。理解すべき重要なことは, インプットフィルタが呼びだされたとき, それらは get_brigade() コールを介して最初にお互いをコールしそれからブロックし (ダイアグラムのレンガの壁に注目), コールがリターンするまで待つことです。このコールがリターンしたとき, すべてのアップストリームフィルタは bucket brigade でのフィルタリングのタスクをすでに完了しています。
As mentioned earlier, the streaming interface hides the details, but the first $f->read() call will block as the layer under it performs the get_brigade() call.

前述のとおり, ストリーミングのインターフェイスは詳細を隠しますが, 最初の $f->read() コールは下のレイヤが get_brigade() コールを実行するとブロックします。
The diagram shows only part of the actual input filter chain for an HTTP request. The ... indicates that there are more filters in between the mod_perl filter and http_in.

ダイアグラムは HTTP リクエストの実際のインプットフィルタチェーンの部分のみを示しています。その ... は mod_perl と http_in の間にもっとフィルタがあることを示します。
Now let's look at what happens in the output filters chain. Here the first filter acquires the bucket brigades containing the response data from the content handler (or another protocol handler if we aren't talking HTTP). It may then make some modification and pass the data to the next filter (using the pass_brigade() call), which in turn applies its modifications and sends the bucket brigade to the next filter, etc. This continues all the way down to the last filter (called core) which writes the data to the network via the socket the client is listening to.

こんどはアウトプットフィルタチェーンで何が起こるかを見てみましょう。ここで最初のフィルタはコンテンツハンドラ (or 私たちが HTTP を話さな場合は別のプロトコルハンドラ) からのレスポンスデータを含む bucket brigade を獲得します。それからそれはいくつか修正をして次のフィルタにパスするかもしれません (pass_brigade() コールを使って), その次はその修正を適用して次のフィルタに bucket brigade を送ります, etc。これはずっと続きますクライアントがリッスンしているソケットを介してネットワークにデータを書き込む最後のフィルタ (core と呼ばれる) に至るまで。
Even though the output filters don't have to wait to acquire the bucket brigade (since the upstream filter passes it to them as an argument), they still block in a similar fashion to input filters, since they have to wait for the pass_brigade() call to return. In this case, they are waiting to pass the data along rather than waiting to receive it.

アウトプットフィルタは bucket brigade を獲得するために待つ必要はありません (アップストリームフィルタがそれを引数としてそれらに渡すため) が, インプットフィルタと同じ流儀でそれらはブロックをします, それらは pass_brigade() コールがリターンするのを待たなければならないからです。この場合, それらはデータの受信を待つのではなくそれを一緒に渡すために待ちます。
Here is an example of a transparent output filter:

こちらが透過的なアウトプットフィルタの例です:

#file:MyApache2/FilterTransparent.pm (continued)
#-----------------------------------------------
sub out {
my ($f, $bb) = @_;

my $rv = $f->next->pass_brigade($bb);
retunr $rv unless $rv == APR::Const::SUCCESS;

retunr Apache2::Const::OK;
}
1;

The out() filter passes $bb to the downstream filter unmodified. If you add print statements before and after the pass_brigade() call and configure the same filter twice, the print will show the blocking call.

out() フィルタは $bb を修正せずにダウンストリームに渡します。あなたが pass_brigade() コールの前後にprint 文を追加して同じフィルタを 2 回構成すると, その print はブロッキングのコールを表示します。
The following diagram depicts a typical output filter data flow in addition to the program control flow:

次のダイアグラムはプログラムコントロールのフローに加えて典型的なアウトプットフィルタのデータフローを描写します:

output filter data flow
A quotation from Input and Output Filters


Similar to the input filters chain diagram, the arrows show the program control flow and in addition the black-headed arrows show the data flow. Again, it uses Perl pseudo-code for the mod_perl filter and C pseudo-code for the Apache filters and the brick walls represent the waiting. The diagram shows only part of the real HTTP response filters chain, where ...stands for the omitted filters.

インプットフィルタのチェーンのダイアグラムと同様に, 矢印はプログラムコントロールのフローを示し加えて黒い頭の矢印はそのデータフローを示します。再び, mod_perl フィルタに Perl の疑似コードを Apache フィルタに C の疑似コードを使いレンガの壁は待機 (# waiting) を表します。ダイアグラムは現実の HTTP レスポンスフィルタチェーンの一部のみを示していて, ここで ... は省略されたフィルタを表します。


mod_perl フィルタ 宣言と構成 : mod_perl Filters Declaration and Configuration



Now that we have laid out some basic concepts involved in filter use, we can look at how mod_perl filters are declared and configured.

私たちはフィルタの使用に伴ういくつかの基本的なコンセプトを提示したので, 私たちは mod_perl フィルタがどのように宣言され構成されるかを見れるようになりました。


フィルタの優先タイプ : Filter Priority Types



When Apache filters are configured they are inserted into the filters chain according to their priority type. In most cases when using one or two filters things will just work, however if you find that the order of filter invocation is wrong, you should consider the filter priority type. Unfortunately this information is available only in the Apache source code, unless it's documented in the module man pages. Numerical definitions of priority types, such as AP_FTYPE_CONTENT_SET and AP_FTYPE_RESOURCE, can be found in the Apache source distribution in include/util_filter.h.

Apache フィルタが構成されるとそのプライオリティタイプに従ってそれらはフィルタチェーンに挿入されます。ほとんどのケースでひとつかふたつのフィルタを使うときそれはちゃんと機能します, しかしあなたがフィルタ呼びだしの順番が間違っていることを見つけたら, あなたはフィルタのプライオリティタイプを考慮しなければなりません。残念ながらこの情報はモジュールの man ページでそれがドキュメント化されていない限りは, Apache のソースコードでのみ利用可能です。AP_FTYPE_CONTENT_SET や AP_FTYPE_RESOURCE のような, プライオリティタイプの数値の定義は, include/util_filter.h で配布される Apache ソース内で見つけられます。
As of this writing Apache comes with two core filters: DEFLATE and INCLUDES. Regardless of your configuration directives, e.g.,:

これを書いている時点で Apache は 2 つのコアフィルタを搭載しています: DEFLATE と INCLUDES。あなたの構成ディレクティブに関わらずです, e.g.,:

SetOutputFilter DEFLATE
SetOutputFilter INCLUDES

the INCLUDES filter will be inserted in the filters chain before the DEFLATE filter, even though it was configured after it. This is because the DEFLATE filter is of type AP_FTYPE_CONTENT_SET (20), whereas the INCLUDES filter is of type AP_FTYPE_RESOURCE (10).

INCLUDES フィルタは DEFLATE フィルタの前にフィルタのチェーンに挿入されます, それはその後で構成されているのにです。これは DEFLATE フィルタが AP_FTYPE_CONTENT_SET (20) のタイプで, 一方 INCLUDES フィルタは AP_FTYPE_RESOURSE (10) のタイプだからです。
As of this writing mod_perl provides two kind of filters with fixed priority type (the type is defined by the filter handler's attribute):

これを書いている時点で mod_perl は固定されたプライオリティタイプで 2 種類のフィルタを提供しています (タイプはフィルタハンドラのアトリビュートで定義されています):

Handler's Attribute Priority Value
-------------------------------------------------
FilterRequestHandler AP_FTYPE_RESOURCE 10
FilterConnectionHandler AP_FTYPE_PROTOCOL 30

Therefore FilterRequestHandler filters (10) will always be invoked before the DEFLATE filter (20), whereas FilterConnectionHandler filters (30) will be invoked after it. When two filters have the same priority (e.g., the INCLUDES filter (10) has the same priority as FilterRequestHandler filters (10)), they are run in the order they are configured. Therefore filters are inserted according to the configuration order when PerlSetOutputFilter or PerlSetInputFilter are used.

したがって FilterRequestHandler フィルタ (10) は常に DEFLATE フィルタ (20) の前で呼びだされ, 一方 FilterConnectionHandler フィルタ (30) はその後で呼びだされます。2 つのフィルタが同じプライオリティを持っている場合 (e.g., INCLUDES フィルタ (10) は FilterRequestHandler フィルタ (10) と同じプライオリティをもっている), それらはそれらが構成された順番で走ります。ですから PerlSetOutputFilterPerlSetInputFilter が使われたときフィルタは構成された順番にしたがって挿入されます。


PerlInputFilterHandler



The PerlInputFilterHandler directive registers a filter, and inserts it into the relevant input filters chain.

PerlInputFilterHandler ディレクティブはフィルタを登録し, それを関連するインプットフィルタチェーンにインサートします。

This handler is of type VOID.

このハンドラは VOID のタイプです。

The handler's configuration scope is DIR.


このハンドラの構成スコープは DIR です。

Arguments



PerlInputFilterHander handlers are passed two arguments: an Apache2::Filter object; and an APR::Brigade object;

PerlInputFilterHandler ハンドラは 2 つの引数を渡されます: Apache2::Filter オブジェクト; それと APR::Brigade オブジェクトです:
See the examples that follow in this chapter for further explanation.

さらなる説明はこのチャプタに続く例を参照してください。


Return



Filters are expected to return Apache2::Const::OK or Apache2::Const::DECLINED. See the examples that follow in this chapter for further explanation.

フィルタは Apache2::Const::OK か Apache2::Const::DECLINED のリターンを期待されています。さらなる説明はこのチャプタに続く例を参照してください。


Examples



PerlInputFilterHandler handlers are automatically AutoLoaded, since they need to be compiled before the filter attributes can be accessed. Therefore if the filter handler subroutine is not called handler, you must preload the module containing the filter subroutine at server startup. A filter handler can be configured not to be AutoLoaded, using the - prefix. For example:

PerlInputFilterHandler ハンドラは自動的に AutoLoad されます, それらはフィルタアトリビュートがアクセスする前にコンパイルされる必要があるからです。したがってフィルタハンドラサブルーチンがハンドラを呼ばない場合, あなたはサーバスタートアップでそのフィルタサブルーチンを含むモジュールをプレロードしなければなりません。フィルタハンドラは - プレフィクスを使って AutoLoad されないように構成できます。例えば:

PerlInputFilterHandler -MyApache2::FilterTest::lc

The following sections include several examples that use the PerlInputFilterHandler handler.

次のセクションは PerlInputFilterHandler ハンドラを使ういくつかの例を含んでいます。


PerlOutputFilterHandler



The PerlOutputFilterHandler directive registers a filter, and inserts it into the relevant output filters chain.

PerlOutputFilterHandler ディレクティブはフィルタを登録して, それを関連するアウトプットフィルタのチェーンにインサートします。

This handler is of type VOID.

このハンドラは VOID のタイプです。

The handler's configuration scope is DIR.


このハンドラの構成スコープは DIR です。

Arguments



PerlOutputFilterHandler handlers are passed five arguments: an Apache2::Filter object; and an APR::Brigade object; an Apache2::Const :input_mode constant; an APR::Const :read_type constant; and the number of bytes to read.

PerlInputFilterHandler ハンドラは 5 つの引数を渡されます: Apache2::Filter オブジェクト; それと APR::Brigade オブジェクト; Apache2::Const :input_mode 定数; APR::Const :read_type 定数; それから読み取るバイト数です。
See the examples that follow in this chapter for further explanation.

さらなる説明はこのチャプタに続く例を参照してください。


Return




Examples



The following sections include several examples that use the PerlOutputFilterHandler handler.

次のセクションは PerlOutputFilterHandler ハンドラを使ういくつかの例を含んでいます。
Similar to PerlInputFilterHandler, PerlOutputFilterHandler handlers are automatically AutoLoaded.

PerlInputFilterHandler と同様に, PerlOutputFilterHandler ハンドラは自動的に AutoLoad されます。


PerlSetInputFilter



The SetInputFilter directive, documented at http://httpd.apache.org/docs-2.0/mod/core.html#setinputfilter, sets the filter or filters which will process client requests and POST input when they are received by the server (in addition to any filters configured earlier).

http://httpd.apache.org/docs-2.0/mod/core.html#setinputfilter でドキュメント化されている, SetInputFilter ディレクティブは, サーバによってクライアントリクエストや POST インプットを受信したときにそれらを処理するフィルタやフィルタ (# 複数) をセットします (その前に構成されたフィルタに加えて)。
To mix mod_perl and non-mod_perl input filters of the same priority nothing special should be done. For example if we have an imaginary Apache filter FILTER_FOO and mod_perl filter MyApache2::FilterInputFoo, this configuration:

同じプライオリティの mod_perl と非 mod_perl のインプットフィルタをミックスするために行うべき特別なことはありません。例えば私たちが架空の Apache フィルタ FILTER_FOO と mod_perl フィルタ MyApache2::FilterInputFoo を持っているなら, この構成はこうなります:

SetInputFilter FILTER_FOO
PerlInputFilterHandler MyApache2::FilterInputFoo

will add both filters. However the order of their invocation might not be as you expect. To make the invocation order the same as the insertion order, replace SetInputFilter with PerlSetInputFilter, like so:

これは両方のフィルタを追加します。しかしこれらの呼びだしの順番はあなたの期待どおりにならないかもしれません。呼びだしの順番をインサート順と同じにするには, SetInputFilter を PerlSetInputFilter でリプレイスします, このように:

PerlSetInputFilter FILTER_FOO
PerlInputFilterHandler MyApache2::FilterInputFoo

Now the FILTER_FOO filter will always be executed before the MyApache2::FilterInputFoo filter, since it was configured before MyApache2::FilterInputFoo (i.e., it'll apply its transformations on the incoming data last). The diagram below shows the input filters chain and the data flow from the network to the response handler for the presented configuration:

これで FILTER_FOO フィルタは常に MyApache2::FilterInputFoo の前で実行されるようになりました, それが MyApache2::FilterFoo の前で構成されたからです (i.e., 最後にインカミングデータの変化を適用します)。次のダイアグラムは提示された構成のネットワークからレスポンスハンドラへのインプットフィルタチェーンとデータフローを示します:

response handler
/\
||
FILTER_FOO
/\
||
MyApache2::FilterInputFoo
/\
||
core input filters
/\
||
network

As explained in the section Filter Priority Types this directive won't affect filters of different priority. For example assuming that MyApache2::FilterInputFoo is a FilterRequestHandler filter, the configurations:

Filter Priority Types セクションで説明したようにこのディレクティブは異なるプライオリティのフィルタには影響しません。例えば MyApache2::FilterInputFoo が FilterRequestHandler フィルタだと想定すると, その構成:

PerlInputFilterHandler MyApache2::FilterInputFoo
PerlSetInputFilter DEFLATE

and

PerlInputFilterHandler MyApache2::FilterInputFoo
PerlSetInputFilter DEFLATE

are equivalent, because mod_deflate's DEFLATE filter has a higher priority than MyApache2::FilterInputFoo. Thefore, it will always be inserted into the filter chain after MyApache2::FilterInputFoo, (i.e. the DEFLATE filter will apply its transformations on the incoming data first). The diagram below shows the input filters chain and the data flow from the network to the response handler for the presented configuration:

これは同等です, mod_deflate の DEFLATE フィルが MyApache2::FilterInputFoo よりも高いプライオリティを持っているからです。したがって, それは常に MyApache2::FilterInputFoo の後のフィルタチェーンにインサートされます, (i.e. DEFLATE フィルタはインカミングデータにその変換を最初に適用します)。以下のダイアグラムは提示された構成のネットワークからレスポンスハンドラへのインプットフィルタチェーンとデータフローを示します:

response handler
/\
||
MyApache2::FilterInputFoo
/\
||
DEFLATE
/\
||
core input filters
/\
||
network

SetInputFilter's ; semantics are supported as well. For example, in the following configuration:

SetInputFilter の ; セマンティクスもサポートされています。例えば, 次の構成では:

PerlInputFilterHandler MyApache2::FilterInputFoo
PerlSetInputFilter FILTER_FOO;FILTER_BAR

MyApache2::FilterOutputFoo will be executed first, followed by FILTER_FOO and finally by FILTER_BAR (again, assuming that all three filters have the same priority).

MyApache2::FilterOutputFoo は最初に実行され, FILTER_FOO が続き最後が FILTER_BAR になります (再び, 3 つすべてのフィルタが同じプライオリティをもっていると想定します)。


PerlSetOutputFilter



The SetOutputFilter directive, documented at http://httpd.apache.org/docs-2.0/mod/core.html#setoutputfilter sets the filters which will process responses from the server before they are sent to the client (in addition to any filters configured earlier).

http://httpd.apache.org/docs-2.0/core.html#setoutputfilter でドキュメント化されている, SetOutputFilter ディレクティブは,サーバからのレスポンスがクライアントに送信される前にそれらを処理するフィルタをセットします (前で構成されたフィルタに加えて)。
To mix mod_perl and non-mod_perl input filters of the same priority nothing special should be done. This configuration:

同じプライオリティの mod_perl と非 mod_perl のインプットフィルタをミックスするために行うべき特別なことはありません。この構成はこうです:

SetOutputFilter INCLUDES
PerlOutputFilterHandler MyApache2::FilterOutputFoo

As with input filters, to preserve the insertion order replace SetOutputFilter with PerlSetOutputFilter, like so:

インプットフィルタのように, インサートされる順番を保つには SetOutputFilter を PerlSetOutputFilter でリプレイスします, このように:

PerlSetOutputFilter INCLUDES
PerlOutputFilterHandler MyApache2::FilterOutputFoo

Now mod_include's INCLUDES filter will always be executed before the MyApache2::FilterOutputFoo filter. The diagram below shows the output filters chain and the data flow from the response handler to the network for the presented configuration:

これで mod_include の INCLUDES フィルタは常に MyApache2::FilterOutputFoo フィルタの前で実行されるようになりました。以下のダイアグラムは提示された構成でレスポンスハンドラからネットワークへのアウトプットフィルタチェーンとデータフローを示します:

response handler
||
\/
INCLUDES
||
\/
MyApache2::FilterOutputFoo
||
\/
core output filters
||
\/
network

SetOutputFilter's ; semantics are supported as well. For example, in the following configuration:

SetOutputFilter の ; セマンティクスもサポートされています。例えば, 次の構成では:

PerlOutputFilterHandler MyApache2::FilterOutputFoo
PerlSetOutputFilter INCLUDES;FILTER_FOO

MyApache2::FilterOutputFoo will be executed first, followed by INCLUDES and finally by FILTER_FOO (again, assuming that all three filters have the same priority).

MyApache2::FilterOutputFoo は最初に実行され, 続いて INCLUDES 最後が FILTER_FOO です (再び, 3 つのフィルタすべてが同じプライオリティをもっていると想定します)。
As explained in the PerlSetInputFilter section, if filters have different priorities, the insertion order might be different. For example in the following configuration:

PerlSetInputFilter セクションで説明したとおり, フィルタが異なるプライオリティの場合, インサートされる順番は異なるかもしれません。例えば次の構成では:

PerlSetOutputFilter DEFLATE
PerlSetOutputFilter INCLUDES
PerlOutputFilterHandler MyApache2::FilterOutputFoo

mod_include's INCLUDES filter will be always executed before the MyApache2::FilterOutputFoo filter. The latter will be followed by mod_deflate's DEFLATE filter, even though it was configured before the other two filters. This is because it has a higher priority. And the corresponding diagram looks like so:

mod_include の INCLUDES フィルタは常に MyApache2::FilterOutputFoo の前で実行されます。後者が他の 2 つのフィルタの前で構成されていたとしても, それは mod_deflate の DEFLATE フィルタに続きます。これはそれがより高いプライオリティを持っているからです。それから対応するダイアグラムのルックスはこのようになります:

response handler
||
\/
INCLUDES
||
\/
MyApache2::FilterOutputFoo
||
\/
DEFLATE
||
\/
core output filters
||
\/
network



アウトプットフィルタを動的に追加する : Adding OutputFilters Dynamically



If you have the need to add output filters dymically during the request, mod_perl 2.0 offers you the possibility to push filter callbacks at request time. For example here is how to add an output filter during the Fixup phase:

あなたがリクエストの間に動的に追加する必要があるアウトプットフィルタをもっているなら, mod_perl 2.0 はリクエストタイムにフィルタコールバックをプッシュするための実現性を提供します。例えばこちらは Fixup フェーズにアウトプットフィルタを追加するやり方です:

<Files *\.html>
PerlFixupHandler MyApacche2::AddFilterDyn
</Files>

And the corresponding module is:

それから対応するモジュールがこれです:

#file:MyApache2/AddFilterDyn.pm
#------------------------------
package MyApache2::AddFilterDyn;

use Apache2::Filter;
use MyApache2::FilterObfuscate;

use Apache2::Const -compile => qw(OK);

sub handler {
my $r = shift;

$r->add_output_filter(\&MyApache2::FilterObfuscate::handler);

return Apache2::Const::OK;
}

1;

You can also add connection filters dynamically. For more information refer to the Apache2::Filter manpages add_input_filter and add_output_filter.

あなたはコネクションフィルタも動的に追加できます。詳細は Apache2::Filter man ページの add_input_filteradd_output_filter を参照してください。


HTTP Request vs. Connection Filters



mod_perl 2.0 supports connection and HTTP request filtering. mod_perl filter handlers specify the type of the filter using the method attributes.

mod_perl 2.0 はコネクションと HTTP リクエストのフィルタリングをサポートしています。mod_perl フィルタハンドラはメソッドアトリビュートを使ってフィルタのタイプを指定します。
HTTP request filter handlers are declared using the FilterRequestHandler attribute. Consider the following request input and output filters skeleton:

HTTP リクエストフィルタハンドラは FilterRequestHandler アトリビュートを使って宣言されます。次のリクエストインプット and アウトプットフィルタのスケルトンを考えます:

package MyApache2::FilterRequestFoo;
use base qw(Apache2::Filter);

sub input : FilterRequestHandler {
my ($f, $bb, $mode, $block, $readbytes) = @_;
#...
}

sub output : FilterRequestHandler {
my ($f, $bb) = @_;
#...
}

If the attribute is not specified, the default FilterRequestHandler attribute is assumed. Filters specifying subroutine attributes must subclass Apache2::Filter, others only need to:

アトリビュートが指定されていない場合, デフォルトの FilterRequestHandler アトリビュートが想定されます。サブルーチンアトリビュートを指定するフィルタは Apaceh2::Filter のサブクラスでなければならず, その他はこれだけが必要です:

use Apache2::Filter ();

Request filters are usually configured in the <Location> or equivalent sections:

リクエストフィルタは通常 <location> または同等のセクションで構成されます:

PerlModule MyApache2::FilterRequestFoo
PerlModule MyApache2::NiceResponse
<Location /filter_foo>
SetHandler modperl
PerlResponseHandler MyApache2::NiceResponse
PerlInputFilterHandler MyApache2::FilterRequestFoo::input
PerlOutputFilterHandler MyApache2::FilterRequestFoo::output
</Location>

Now we have the request input and output filters configured.

これで私たちは構成されたインプット and アウトプットフィルタをもちました。
The connection filter handler uses the FilterConnectionHandler attribute. Here is a similar example for the connection input and output filters.

コネクションフィルタハンドラは FilterConnectionHandler アトリビュートを使います。こちらがコネクションインプット and アウトプットフィルタの同様の例です。

Package MyApache2::FilterConnectionBar;
use base qw(Apache2::Filter);

sub input : FilterConnectionHandler {
my ($f, $bb, $mode, $block, $readbytes) = @_;
#...
}

sub output : FilterConnectionHandler {
my ($f, $bb) = @_;
#...
}

1;

With connection filters, unlike the request flters, the configuration must be done outside the <Location> or equivalent sections, usually within the <VirtualHost> or the global server configuration:

コネクションフィルタでは, リクエストフィルタとは違い, その構成は <Location> や同等のセクションの外側で行われなければならず, 通常は <VirtualHodt> やグローバルサーバ構成です:

Listen 8005
<VirtualHost _default_:8005>
PerlModule MyApache2::FilterConnectionBar
PerlModule MyApache2::NiceResponse

PerlInputFilterHandler MyApache2::FilterConnectionBar::input
PerlOutputFilterHandler MyApache2::FilterConnectionBar::output
<Location />
SetHandler modperl
PerlResponseHandler MyApache2::NiceResponse
</Location>

</VirtualHost>

This configures the connection input and output filters.

これはコネクションインプット and アウトプットフィルタを構成します。
As can be seen from the above examples, the only difference between connection filters and request filters is that that connection filters see everything from the request, i.e., the headers and the body, whereas request filters see only the body.

上記の例で見られるように, コネクションフィルタとリクエストフィルタの間の唯一の違いはコネクションフィルタはリクエストからのすべてのもを見ます, i.e., ヘッダとボディ, 一方リクエストフィルタはボディだけです。


フィルタ初期化フェーズ : Filter Initialization Phase



There is one more callback in the filter framework. And that's FilterInitHandler. This init callback runs immediately after the filter handler is inserted into the filter chain, before it is invoked for the first time. Here is a skeleton of an init handler:

フィルタフレームワークにはもうひとつコールバックがあります。そしてそれは FilterInitHandler です。この init コールバックはフィルタハンドラがフィルタチェーンにインサートされたあとすぐで, それが最初に呼びだされる前に走ります。こちらが init ハンドラのスケルトンです:

sub init : FilterInitHandler {
my $f = shift;
#...
return Apache2::Const::OK;
}

The attribute FilterInitHandler marks the Perl function as suitable to be used as a filter initialization callback.

アトリビュート FilterInitHandler はフィルタの初期化コールバックとしての利用に適しているものとして Perl ファンクションをマークします。
For example you may decide to dynamically remove a filter before it had a chance to run, if some condition is true:

例えばあなたは何らかの条件が true の場合, それが実行する機会を得る前にフィルタの動的な削除を決定することもできます:

sub init : FilterInitHandler {
my $f = shift;
$f->remove() if should_remove_filter();
return Apache2::Const::OK;
}

Not all Apache2::Filter methods can be used in the init handler, because it's not a filter. Hence you can use methods that operate on the filter itself, such as remove() and ctx() or retrieve request information, such as r() and c(). You cannot use methods that operate on data, such as read() and print().

すべての Apache2::Filter メソッドが init ハンドラで使えるわけではありません, それはフィルタではないからです。ですからあなたは remove() や ctc() のような, フィルタ自体を操作するものやリクエストインフォメーションを取得する, r() や c() のようなメソッドを使えます。あなたは read() や print() のようなデータの操作をするメソッドは使えません。
In order to hook an init filter handler, the real filter has to assign this callback using the FilterHasInitHandler function which accepts a reference to the callback function, similar to push_handlers(). The callback function referred to must have the FilterInitHandler attribute. For example:

init フィルタハンドラをフックするために, 実際のハンドラは push_handlers() と同様に, コールバックファンクションへのリファレンスを受けいれる, FilterHasInitHandler ファンクションを使ってこのコールバックをアサインしなければなりません。参照されるコールバックファンクションは FilterInitHandler アトリビュートをもっていなければなりません。例えば:

package MyApache2::FilterBar;
use base qw(Apache2::Filter);
sub init : FilterInitHandler { ... }
sub filter : FilterRequestHandler FilterHasInitHandler(\&init) {
my ($f, $bb) = @_;
# ...
return Apache2::Const::OK;
}

While attributes are parsed during compilation (it's really a sort of source filter), the argument to the FilterHasInitHandler() attribute is compiled at a later stage once the module is compiled.

アトリビュートはコンパイルの間にパースされます (実際にはある種のソースフィルタです) が, FilterHasInitHandler() アトリビュートへの引数はモジュールがコンパイルされた後のステージでコンパイルされます。
The argument to FilterHasInitHandler() can be any Perl code which when eval()'ed returns a code reference. For example:

FilterHasInitHandler() への引数は eval() されたときにコードリファレンスをリターンする Perl コードにできます。

package MyApache2::OtherFilter;
use base qw(Apache2::Filter);
sub init : FilterInitHandler { ... }

package MyAapche2::FilterBar;
use MyApache2::OtherFilter;
use base qw(Apache2::Filter);
sub get_pre_hanlder { \&MyApache2::OtherFilter::init }
sub filter : FilterHasInitHandler(get_pre_handler()) { ... }

Here the MyApache2::FilterBar::filter handler is configured to run the MyApache2::OtherFilter::init init handler.

ここで MyApache2::FilterBar::filter ハンドラは MyApache2::OtherFilter::init init ハンドラを実行するために構成されています。
Notice that the argument to FilterHasInitHandler() is always eval()'ed in the package of the real filter handler (not the init handler). So the above code leads to the following evaluation:

FilterHasInitHandler() への引数は実際のフィルタハンドラ (init ハンドラでなく) のパッケージで常に eval() されることに注意して下さい。ですから上記コードは次の評価を導きます:

$init_sub = eval "package MyApache2::FilterBar; get_pre_handler()";

This part is actually done in C, using the eval_pv() C call.

このパートは実際には C で行われます, C コール eval_pv() を使って。
Currently only one initialization callback can be registered per filter handler.

現在フィルタハンドラごとに登録できる初期化コールバックはひとつだけです。


全部入りフィルタ : All-in-One Filter



Before we delve into the details of how to write filters that do something with the data, lets first write a simple filter that does nothing but snooping on the data that goes through it. We are going to develop the MyApache2::FilterSnoop handler which can snoop on request and connection filters, in input and output modes.

私たちがデータに何かを行うフィルタの書き方を詳細を掘り下げる前に, 何もしないがそれを通り抜けるデータをスヌーピングする (# 覗き見る) シンプルなフィルタを最初に書いてみましょう。
私たちはインプットとアウトプットモードで, リクエストとコネクションのフィルタをスヌープできる MyApache2::FilterSnoop ハンドラを開発することにします。
First we create a simple response handler that dumps the request's args and content as strings:

最初に私たちはリクエストの args と content を文字列としてダンプするシンプルなレスポンスハンドラを作成します:

#file:MyApache2/Dump.pm
#---------------------
package MyApache2::Dump;

use strict;
use warnings;

use Apache2::RequestRec ();
use Apache2::RequestIO ();
use Apache2::Filter ();
use APR::Brigade ();
use APR::Bucket ();

use Apache2::Const -compile => qw(OK M_POST);

sub handler {
my $r = shift;
$r->content_type('text/plain');

$r->print("args:\n", $r->args, "\n");

if ($r->method_number == Apache2::Const::M_POST) {
my $data = content($r);
$r->print("content:\n$data\n");
}

return Apache2::Const::OK;
}

use Apache2::Connection ();

use Apache2::Const -compile => qw(MODE_READBYTES);
use APR::Const -compile => qw(SUCCESS BLOCK_READ);

use constant IOBUFSIZE => 8192;

sub content {
my $r = shift;

my $bb = APR::Brigade->new($r->pool, $r->connection->bucket_alloc);

my $data = '';
my $seen_eos = 0;
do {
$r->input_filters->get_brigade($bb, Apache2::Const::MODE_READBYTES,
APR::Const::BLOCK_READ, IOBUFSIZE);

for (my $b = $bb->first; $b; $b = $bb->next($b)) {
if ($b->is_eos) {
$seen_eos++;
last;
}

if ($b->read(my $buf)) {
$data .= $buf;
}

$b->remove; # optimization to reuse memory
}
} while (!$seen_eos);

$bb->destroy;

return $data;
}

1;

which is configured as:

これはこのように構成されます:

PerlModule MyApache2::Dump
<Location /dump>
SetHandler modperl
PerlResponseHandler MyApache2::Dump
</Location>

If we issue the following request:

私たちが次のリクエストを発行すると:

% echo "mod_perl rules" | POST 'http://localhost:8002/dump?foo=1&bar=2'

the response will be:

レスポンスはこうなります:

args:
foo=1&bar=2
content:
mod_perl rules

As you can see it simply dumped the query string and the posted data.

ご覧の通りこれはシンプルにクエリストリングとポストされたデータをダンプします。
Now let's write the snooping filter:

ではスヌーピングフィルタを書くことにしましょう:

#file:MyApache2/FilterSnoop.pm
#----------------------------
package MyApache2::FilterSnoop;

use strict;
use warnings;

use base qw(Apache2::Filter);
use Apache2::FilterRec ();
use APR::Brigade ();
use APR::Bucket ();
use APR::BucketType ();

use Apache2::Const -compile => qw(OK DECLINED);
use APR::Const -compile => ':common';

sub connection : FilterConnectionHandler { snoop("connection", @_) }
sub request : FilterRequestHandler { snoop("request", @_) }

sub snoop {
my $type = shift;
my ($f, $bb, $mode, $block, $readbytes) = @_; # filter args

# $mode, $block, $readbytes are passed only for input filters
my $stream = defined $mode ? "input" : "output";

# read the data and pass-through the bucket brigades unchanged
if (defined $mode) {
# input filter
my $rv = $f->next->get_brigade($bb, $mode, $block, $readbytes);
return $rv unless $rv == APR::Const::SUCCESS;
bb_dump($type, $stream, $bb);
}
else {
# output filter
bb_dump($type, $stream, $bb);
my $rv = $f->next->pass_brigade($bb);
return $rv unless $rv == APR::Const::SUCCESS;
}

return Apache2::Const::OK;
}

sub bb_dump {
my ($type, $stream, $bb) = @_;

my @data;
for (my $b = $bb->first; $b; $b = $bb->next($b)) {
$b->read(my $bdata);
push @data, $b->type->name, $bdata;
}

# send the sniffed info to STDERR so not to interfere with normal
# output
my $direction = $stream eq 'output' ? ">>>" : "<<<";
print STDERR "\n$direction $type $stream filter\n";

my $c = 1;
while (my ($btype, $data) = splice @data, 0, 2) {
print STDERR " o bucket $c: $btype\n";
print STDERR "[$data]\n";
$c++;
}
}
1;

Recall that there are two types of two filter handlers, one for connection and another for request filtering:

2 つのタイプの 2 つのフィルタハンドラの , ひとつはコネクションでもうひとつはリクエストのフィルタリングがあることを思い出してください:

sub connection : FilterConnectionHandler { snoop("connection", @_) }
sub request : FilterRequestHandler { snoop("request", @_) }

Both handlers forward their arguments to the snoop() function, which does the real work. These two subroutines are added in order to assign the two different attributes. In addition, the functions pass the filter type to snoop() as the first argument, which gets shifted off @_. The rest of @_ are the arguments that were originally passed to the filter handler.

両方のハンドラはその引数を snoop() ファンクションに転送し, これが実際の作業を行います。これらの 2 つのサブルーチンは 2 つの異なるアトリビュートをアサインするために追加されます。加えて, ファンクションは @_ から shift できるように, フィルタタイプを最初の引数として snoop() に渡します。@_ の残りは元々フィルタハンドラに渡されていた引数です。
It's easy to know whether a filter handler is running in the input or the output mode. Although the arguments $f and $bb are always passed, the arguments $mode, $block, and $readbytes are passed only to input filter handlers.

フィルタハンドラがインプット or アウトプットモードのどちらで実行されているかは簡単にわかります。引数 $f と $bb は常にパスされますが, 引数 $mode, $block, それから $readbytes はインプットフィルタハンドラでのみ渡されます。
If we are in input mode, in the same call we retrieve the bucket brigade from the previous filter on the input filters stack and immediately link it to the $bb variable which makes the bucket brigade available to the next input filter when the filter handler returns. If we forget to perform this linking our filter will become a black hole into which data simply disappears. Next we call bb_dump() which dumps the type of the filter and the contents of the bucket brigade to STDERR, without influencing the normal data flow.

私たちがインプットモードの場合, 同じ呼びだしで私たちはインプットフィルタのスタックの前のフィルタから bucket brigade を取得してすぐにそれを $bb 変数にリンクしフィルタハンドラが return したときに次のインプットフィルタで bucket brigade を利用できるようにします。私たちがこのリンクの実行を忘れると私たちのフィルタはブラックホールになってデータはシンプルに消えることになります。次に私たちはノーマルのデータフローに影響することなく, フィルタのタイプと bucket brigade のコンテンツを STDERR にダンプするbb_dump() をコールします。
If we are in output mode, the $bb variable already points to the current bucket brigade. Therefore we can read the contents of the brigade right away, and then we pass the brigade to the next filter.

私たちがアウトプットモードの場合, $bb 変数はすでに現在の bucket brigade を指し示しています。したがって私たちはすぐに brigade のコンテンツを読むことができて, それから私たちは次のフィルタに brigade を渡します。
Let's snoop on connection and request filter levels in both directions by applying the following configuration:

次の構成を適用してコネクションとリクエストのフィルタレベルの両方向で覗き見しましょう:

Listen 8008
<VirtualHost _default_:8008>
PerlModuel MyApache2::FilterSnoop
PerlModuel MyApache2::Dump

# Connection filters
PerlInputFilterHandler MyApache2::FilterSnoop::connection
PerlOutputFilterHandler MyApache2::FilterSnoop::connection

<Location /dump>
SetHandler modperl
PerlResponseHandler MyApache2::Dump
# Request filters
PerlInputFilterHandler MyApache2::FilterSnoop::request
PerlOutputFilterHandler MyApache2::FilterSnoop::request
</Location>

</VirtualHost>

Notice that we use a virtual host because we want to install connection filters.

私たちはコネクションフィルタをインストールしたいので私たちがバーチャルホストを使っていることに注目してください。
If we issue the following request:

私たちが次のリクエストを発行した場合は:

% echo "mod_perl rules" | POST 'http://localhost:8008/dump?foo=1&bar=2'

we get the same response as before we installed MyApache2::FilterSnoop because our snooping filter didn't change anything. The output didn't change, but there was some new information printed to the error_log. We present it all here, in order to understand how filters work.

私たちは私たちのスヌーピングフィルタが何も変更しないので私たちが MyApache2::FilterSnoop をインストールする前と同じレスポンスをゲットします。アウトプットは変更されませんが, いくつかの新しい情報が error_log に出力されます。私たちはフィルタがどのように機能するかを理解するために, そのすべてをここで提示します。
First we can see the connection input filter at work, as it processes the HTTP headers. We can see that for this request each header is put into a separate brigade with a single bucket. The data is conveniently enclosed by [] so you can see the new line characters as well.

最初に私たちは HTTP ヘッダを処理する時点で, コネクションインプットフィルタが機能しているのを見ることができます。私たちはそれでこのリクエストのための各ヘッダがひとつの bucket で別々の brigade に置かれていることを見れます。データは都合よく [] で囲まれているのであなたは改行文字も見ることができます。

<<< connection input filter
o buket 1: HEAP
[POST /dump?foo=1&bar=2 HTTP/1.1
]

<<< connection input filter
o buket 1: HEAP
[TE: deflate,gzip;q=0.3
]

<<< connection input filter
o buket 1: HEAP
[Connection: TE, close
]

<<< connection input filter
o buket 1: HEAP
[Host: localhost:8008
]

<<< connection input filter
o buket 1: HEAP
[User-Agent: lqp-request/2.01
]

<<< connection input filter
o buket 1: HEAP
[Content-Length: 14
]

<<< connection input filter
o buket 1: HEAP
[Content-Type: application/x-www-form-urlencoded
]

<<< connection input filter
o buket 1: HEAP
[
]

Here the HTTP header has been terminated by a double new line. So far all the buckets were of the HEAP type, meaning that they were allocated from the heap memory. Notice that the HTTP request input filters will never see the bucket brigades with HTTP headers because they are consumed by the last core connection filter.

ここで HTTP ヘッダは 2 つの改行で終了しています。これまでのところすべての buckets は HEAP のタイプで, それはこれらがヒープメモリから割り当てされていたことを意味します。HTTP リクエストインプットフィルタは最後のコアコネクションフィルタによって消費されるので HTTP ヘッダをもつ bucket brigades を決して見ないことに注目してください。
The following two entries are generated when MyApache2::Dump::handler reads the POSTed content:

次の 2 つのエントリは MyApache2::Dump::handler が POST されたコンテンツを読んだときに生成されます:

<<< connection input filter
o bucket 1:HEAP
[mod_perl_rules]
<<< request input filter
o bucket 1:HEAP
[mod_perl rules]
o bucket 2:EOS
[]

As shown earlier, the connection input filter is run before the request input filter. Since our connection input filter was passing the data through unmodified and no other custom connection input filter was configured, the request input filter sees the same data. The last bucket in the brigade received by the request input filter is of type EOS, meaning that all the input data from the current request has been received.

前で示したとおり, コネクションインプットフィルタはリクエストインプットフィルタの前に走ります。私たちのコネクションインプットフィルタは修正せずにデータを渡すことと他のカスタムインプットフィルタが構成されていないことから, リクエストインプットフィルタと同じデータを見ます。リクエストインプットフィルタによって受信された brigade の最後の bucket は EOS のタイプで, それは現在のリクエストからのすべてのインプットデータが受信されたことを意味します。
Next we can see that MyApache2::Dump::handler has generated its response. However we can see that only the request output filter gets run at this point:

次に私たちは MyApache2::Dump::handler がそのレスポンスを生成したことを見ます。しかし私たちはこの時点でリクエストアウトプットフィルタだけが実行されていることを見ます:

>>> request out filter
o bucket 1: TRANSIENT
[args:
foo=1&bar=2
content:
mod_perl rules
]

This happens because Apache hasn't yet sent the response HTTP headers to the client. The request filter sees a bucket brigade with a single bucket of type TRANSIENT which is allocated from the stack memory.

これは Apache がクライアントにまだレスポンス HTTP ヘッダを送っていないので発生します。このリクエストフィルタは TRANSIENT のタイプの単一の bucket をもつ bucket brigade を見ていてこれはスタックメモリから割り当てされています。
The moment the first bucket brigade of the response body has entered the connection output filters, Apache injects a bucket brigade with the HTTP headers. Therefore we can see that the connection output filter is filtering the brigade with HTTP headers (notice that the request output filters don't see it):

レスポンスボディの最初の bucket brigade がコネクションアウトプットフィルタに入った瞬間に, Apache は HTTP ヘッダを bucket brigade に注入します。したがって私たちはそのコネクションアウトプットフィルタが HTTP ヘッダでその brigade をフィルタリングすることを見ます (リクエストフィルタはそれを見ないことに注意してください):

>>> connection output filter
o bucket 1: HEAP
[HTTP/1.1 200 OK
Date: Tue, 07 Mar 2006 10:59:08 GMT
Server: Apache/2.0.55 (Unix) mod_perl/2.000002
Perl/v5.8.4 mod_ssl/2.0.55 OpenSSL/0.9.7c DAV/2
Connection: close
Transfer-Encoding: chunked
Content-Type: text/plain; charset=ISO-8859-1

]

This is followed by the first response body's brigade:

これに最初のレスポンスボディの brigade が続きます:

>>> connection output filter
o bucket 1: TRANSIENT
[2b
]
o bucket 2: TRANSIENT
[args:
foo=1&bar=2
content:
mod_perl rules

]
o bucket 3: IMMORTAL
[
]

If the response is large, the request and connection filters will filter chunks of the response one by one. These chunks are typically 8k in size, but this size can vary.

レスポンスが大きい場合, リクエスト and コネクションのフィルタはレスポンスのチャンク (# 塊り) を 1 つずつフィルタします。これらのチャンクのサイズは典型的には 8k ですが, このサイズは変わります。
Finally, Apache sends a series of bucket brigades to finish off the response, including the end of stream meta-bucket to tell filters that they shouldn't expect any more data, and flush buckets to flush the data, to make sure that any buffered output is sent to the client:

最後に, Apache はフィルタがもうデータを期待しないように伝えるために, ストリームの終わりのメタ bucket を含む一連の bucket brigades を送信してレスポンスを終了させて, buckets をフラッシュしてデータをフラッシュし, バッファされたアウトプットが確実にクライアントに送信されるようにします:

>>> connection outpu filter
o bucket 1: IMMORTAL
[0

]
o bucket 2: EOS
[]

>>> connection output filter
o bucket 1: FLUSH
[]

>>> connection output filter
o bucket 1: FLUSH
[]

This module helps to illustrate that each filter handler can be called many times during each request and connection. It is called for each bucket brigade. Also it is important to mention that HTTP request input filters are invoked only if there is some POSTed data to read and it's consumed by a content handler.

このモジュールは各リクエストとコネクションの間に何度でも各フィルタハンドラを呼びだせることの説明に役立ちます。これは各 bucket brigade で呼びだされます。また HTTP リクエストインプットフィルタが読みとる何らかの POST されたデータがありそれがコンテンツハンドラによって消費される場合にのみ呼びだされることに言及するのは重要です。


インプットフィルタ : Input Filters



mod_perl supports Connection and HTTP Request input filters. In the following sections we will look at each of these in turn.

mod_perl は ConnectionHTTP Request インプットフィルタをサポートします。続くセクションで私たちはこれらを順に見ていきます。


コネクションインプット : Connection Input Filters



Let's say that we want to test how our handlers behave when they are requested as HEAD requests, rather than GET requests. We can alter the request headers at the incoming connection level with the alteration transparent to all handlers.

私たちは GET リクエストではなく, 私たちのハンドラが HEAD リクエストとしてリクエストされた時にどのように振る舞うかをテストしたいとします。私たちはすべてのハンドラへの透過的な変更を用いてインカミングコネクションレベルでリクエストハンドラを変更出来ます。

This example's filter handler looks for data like:

この例のフィルタハンドラはこのようなデータを探し:

GET /perl/test.pl HTTP/1.1

and turns it into:

そしてそれをこのようにかえます:

HEAD /perl/test.pl HTTP/1.1

The following input filter handler does that by directly manipulating the bucket brigades:

次のインプットフィルタハンドラは bucket brigades を直接捜査してそれを行います:

#file:MyApache2/InputFilterGET2HEAD.pm
#------------------------------------
package MyApache2::InputFilterGET2HEAD;o

use strict;
use warnings;

use base qw(Apache2::Filter);

use APR::Brigade ();
use APR::Bucket ();

use Apache2::Const -compile => qw(OK DECLINED);
use APR::Const -compile => ':common';

sub handler : FilterConnectionHandler {
my ($f, $bb, $mode, $block, $readbytes) = @_;

return Apache2::Const::DECLINED if $f->ctx;

my $rv = $f->next->get_brigade($bb, $mode, $block, $readbytes);
return $rv unless $rv == APR::Const::SUCCESS;

for (my $b = $bb->first; $b; $b = $bb->next($b)) {
$b->read(my $data);
warn("data: $data\n");

if ($data and $data =~ s|^GET|HEAD|) {
my $nb = APR::Bucket->new($bb->bucket_alloc, $data);
$b->insert_after($nb);
$b->remove; # no longer needed
$f->ctx(1); # flag that that we have done the job
last;
}
}

return Apache2::Const::OK;
}
1;

The filter handler is called for each bucket brigade, which then includes buckets with data. The gist of any input filter handler is to request the bucket brigade from the upstream filter, and return it to the downstream filter using the second argument $bb. It's important to remember that you can call methods on this argument, but you shouldn't assign to this argument, or the chain will be broken.

フィルタハンドラは各 bucket brigade で呼ばれ, それはデータをもつ buckets を含みます。インプットフィルタハンドラの要点はアップストリームフィルタから bucket brigade をリクエストして, それを 2 番目の引数 $bb を使ってダウンストリームフィルタリターンすることです。あなたはこの引数でメソッドをコールできることを覚えておくことは重要ですが, あなたはこの引数にアサインするべきではありません, でなければチェーンが壊れます。
There are two techniques to choose from to retrieve-modify-return bucket brigades:

bucket brigades を取得-修正-リターンするために選択する 2 つのテクニックがあります:


  1. Create a new empty bucket brigade $ctx_bb, pass it to the upstream filter via get_brigade() and wait for this call to return. When it returns, $ctx_bb will be populated with buckets. Now the filter should move the bucket from $ctx_bb to $bb, on the way modifying the buckets if needed. Once the buckets are moved, and the filter returns, the downstream filter will receive the populated bucket brigade.

    空の bucket brigade $ctx_bb を作成して, それを get_brigade() を介してアップストリームフィルタに渡してこのコールのリターンを待ちます。それがリターンされると, $ctx_bb は buckets が入れられています。これでフィルタは bucket を $ctx_bb から $bb に移動し, 途中で必要なら buckets を修正するようになります。buckets が移動されて, フィルタがリターンすると, ダウンストリームフィルタはデータが入れられた bucket brigade を受けとります。


  2. Pass $bb to the upstream filter using get_brigade() so it will be populated with buckets. Once get_brigade() returns, the filter can go through the buckets and modify them in place, or it can do nothing and just return (in which case, the downstream filter will receive the bucket brigade unmodified).

    get_brigade() を使って $bb をアップストリームフィルタに渡してそれに bucket が入れられるようにします。get_brigade() がリターンされると, フィルタは buckets を検討してそこでそれらは修正するか, 何も行わずにただリターンします (このケースでは, ダウンストリームフィルタは修正されていない bucket brigade を受けとります)。


Both techniques allow addition and removal of buckets. Though the second technique is more efficient since it doesn't have the overhead of create the new brigade and moving the bucket from one brigade to another. In this example we have chosen to use the second technique, in the next example we will see the first technique.

どちらのテクニックも bucket の追加と削除を可能にします。けれども 2 番目のテクニックは新しい brigade の作成とある brigade から他に bucket を移動するオーバヘッドをもたないのでより効率的です。この例で私たちは 2 番目のテクニックを選択していて, 次の例で私たちは最初のテクニックを見ます。
Our filter has to perform the substitution of only one HTTP header (which normally resides in one bucket), so we have to make sure that no other data gets mangled (e.g. there could be POSTED data and it may match /^GET/ in one of the buckets). We use $f->ctx as a flag here. When it's undefined the filter knows that it hasn't done the required substitution, though once it completes the job it sets the context to 1.

私たちのフィルタはひとつの HTTP ヘッダのみの置換を実行しなければならないので (それは普通ひとつの bucket に存在します), 私たちは他のデータがズタズタにされないようにしなければなりません (e.g. POSTED データがありそれが buckets のひとつの /^GET/ にマッチするかもしれません)。私たちはここでのフラグとして $f->ctx を使います。それが未定義のときフィルタは必要とされる置換が行われていないことを知りますが, そのジョブが完了するとコンテキストを 1 にセットします。
Using the information stored in the context, the filter can immediately return Apache2::Const::DECLINED when it's invoked after the substitution job has been done:

コンテキストに格納された情報を使って, フィルタは置換のジョブが行われた後にそれが呼びだされたときにすぐ Apache2::Const::DECLINED をリターンできます:

return Apache2::Const::DECLINED if $f->ctx;

In that case mod_perl will call get_brigade() internally which will pass the bucket brigade to the downstream filter. Alternatively the filter could do:

このケースで mod_perl は bucket brigade をダウンストリームフィルタに渡すために内部的に get_brigade() をコールします。あるいはフィルタはこれを行えます:

my $rv = $f->next->get_brigade($bb, $mode, $block, $readbytes);
return $rv unless $rv == APR::Const::SUCCESS;
return Apache2::Const::OK if $f->ctx;

but this is a bit less efficient.

しかしこれは少し効率がわるいです。
[META: the most efficient thing to do is to remove the filter itself once the job is done, so it won't be even invoked after the job has been done.

[META: もっとも効率的にそれを行うにはそのジョブが完了したフィルタ自体を削除することなので, ジョブが完了した後でそれが呼びだされることもないようにします。

if ($f->ctx) {
$f->remove;
return Apache2::Const::DECLINED;
}

However, this can't be used with Apache 2.0.49 and lower, since it has a bug when trying to remove the edge connection filter (it doesn't remove it). Most likely that problem will be not fixed in the 2.0 series due to design flows. I don't know if it's going to be fixed in 2.1 series.]

しかし, これは Apache 2.0.49 以下では使えません, それはエッジコネクションフィルタの削除を試みるときのバグを持っているからです (その削除が行われません)。問題は設計フローに起因して 2.0 シリーズで修正されない可能性が高いです。2.1 で修正されることになるか私はわかりません。]
If the job wasn't done yet, the filter calls get_brigade, which populates the $bb bucket brigade. Next, the filter steps through the buckets looking for the bucket that matches the regex: /^GET/. If a match is found, a new bucket is created with the modified data (s/^GET/HEAD/. Now it has to be inserted in place of the old bucket. In our example we insert the new bucket after the bucket that we have just modified and immediately remove that bucket that we don't need anymore:

まだジョブがまだ行われていない場合, フィルタは $bb bucket brigade を放り込む get_brigade をコールします。次にフィルタは buckets を通って (# ステップスルーして) この正規表現にマッチする bucket を探します: /^GET/。マッチするものが見つかると, 修正されたデータ (s/^GET/HEAD/) で新しい bucket が作成されます。ここでそれは古い bucket の場所にインサートされなければなりません。私たちの例で私たちは私たちがちょうど修正した bucket の後に新しい bucket をインサートして私たちがもう必要としない bucket をすぐに削除します:

$b->insert_after($nb);
$b->remove; # no longer needed

Finally we set the context to 1, so we know not to apply the substitution on the following data, and break from the for loop.

最後に私たちはコンテキストを 1 にセットしますので, 私たちは続くデータで置換を適用しないことを知り, for ループから離脱します。
The handler returns Apache2::Const::OK indicating that everything was fine. The downstream filter will receive the bucket brigade with one bucket modified.

ハンドラはすべてが正常だったことを示す Apache2::Const::OK をリターンします。ダウンストリームフィルタはひとつの bucket が修正された bucket brigade を受けとります。
Now let's check that the handler works properly. For example, consider the following response handler:

ではハンドラが適切に機能していることをチェックましょう。例えば, 次のレスポンスハンドラを考えてみます:

#file:MyApache2/RequestType.pm
#----------------------------
package MyApache2::RequestType;

use strict;
use warnings;

use Apache2::RequestIO ();
use Apache2::RequestRec ();
use Apache2::Response ();

use Apache2::Const -compile => 'OK';

sub handler {
my $r = shift;

$r->content_type('text/plain');
my $response = "the request type was " . $r->method;
$r->set_content_length(lenght $response);
$r->print($response);

return Apache2::Const::OK;
}

1;

This handler returns to the client the request type it has issued. For a HEAD request Apache will discard the response body, but it will still set the correct Content-Length header, which will be 24 for a GET request and 25 for a HEAD request. Therefore, if this response handler is configured as:

このハンドラは発行されたリクエストタイプをクライアントにリターンします。HEAD リクエストで Apache はレスポンスボディを破棄しますが, それはまだ GET リクエストで 24 で HEAD リクエストで 25 となる, 正しい Content-Length ハンドラをセットします。したがって, このレスポンスハンドラが構成されていると:

Listen 8005
<VirtualHost _default_:8005>
<Location />
SetHandler modperl
PerlResponseHandler +MyApache2::RequestType
</Location>
</VirtualHost>

and a GET request is issued to /:

そして GET リクエストが / に発行されます:

panic% perl -MLWP::UserAgent -le \
'$r = LWP::UserAgent->new()->get("http://localhost:8005/"); \
perin $r->headers->content_length . ": ". $r->content'
24: the request tyep was GET

the response body will be:

レスポンスボディはこうなります:

the request type was GET

and the Content-Length header will be set to 24. This is what we would expect since the request was processed normally. However, if we enable the MyApache2::InputFilterGET2HEAD input connection filter:

そして Content-Length ヘッダは 24 にセットされます。リクエストは普通に処理されるのでこれは私たちが予期していたものです。しかし, 私たちが MyApache2::InputFilterGET2HEAD インプットコネクションフィルタを有効にした場合は:

Listen 8005
<VirtualHost _default_:8005>
PerlInputFilterHandler +MyApache2::InputFilterGET2HEAD

<Location />
SetHandler modperl
PerlResponseHandler +MyApache2::RequestType
</Location>
</VirtualHost>

and issue the same GET request, we get only:

そして同じ GET リクエストを発行すると, 私たちこれだけをゲットします:

25:

This means the body was discarded by Apache, because our filter turned the GET request into a HEAD request. If Apache wasn't discarding the body on HEAD, the response would be:

これは Apache によってボディが破棄されたことを意味します, 私たちのフィルタが GET リクエストを HEAD リクエストに変更したからです。もし Apache が HEAD でボディを破棄しないなら, レスポンスはこうなるでしょう:

the request type was HEAD

That's why the content length is reported as 25 and not 24 as in the real GET request. So the content length of 25 and lack of body text in the response confirm that our filter is acting as we expected.

それはコンテンツの長さが実際の GET リクエストで 24 ではなく 25 でリポートされるからです。ですからコンテンツの長さ 25 とボディテキストが欠如ししたレスポンスで私たちのフィルタが私たちの期待した通りに動いていることを確認できます。


HTTP リクエストインプット : HTTP Request Input Filters



Request filters are really non-different from connection filters, other than that they are working on request and response bodies and have an access to a request object.

リクエストフィルタはリクエストとレスポンスボディで機能することとリクエストオブジェクトへのアクセスをもっていること以外は, コネクションフィルタと実際には違いません。


バケツリレーベースのインプット : Bucket Brigade-based Input Filters



As we have seen, filters can be either bucket brigade based, or stream oriented. Here we look at a request input filter that lowercases the request's body by directly manipulating the bucket brigade: MyApache2::InputRequestFilterLC.

私たちが見てきたように, フィルタは bucket brigade ベース, またはストリーム指向のいずれかになります。ここで私たちは bucket brigade を直接操作することでリクエストのボディを小文字にするリクエストインプットフィルタを見てみます: MyApache2::InputRequestFilter です。

#file:MyApache2/InputRequestFilterLC.pm
#-------------------------------------
packege MyApache2::InputRequestFilterLC;

use strict;
use warnings;

use base qw(Apache2::Filter);

use Apache2::Connection ();
use APR::Brigade ();
use APR::Bucket ();

use Apache2::Const -compile => 'OK';
use APR::Const -compile => ':common';

sub handler : FilterRequestHandler {
my ($f, $bb, $mode, $block, $readbytes) = @_;

my $c = $f->c;
my $bb_ctx = APR::Brigade->new($c->pool, $c->bucket_alloc);
my $rv = $f->next->get_brigade($bb_ctx, $mode, $block, $readbytes);
return $rv unless $rv == APR::Const::SUCCESS;

while (!$bb_ctx->is_empty) {
my $b = $bb_ctx->first;

if ($b->is_eos) {
$bb->insert_tail($b);
last;
}

my $len = $b->read(my $data);
$b = APR::Bucket->new($bb->bucket_alloc, lc $data) if $len;

$b->remove;
$bb->insert_tail($b);
}

return Apache2::Const::OK;
}

1;

As promised, in this filter handler we have used the first technique of bucket brigade modification. The handler creates a temporary bucket brigade (ctx_bb), populates it with data using get_brigade(), and then moves buckets from it to the bucket brigade $bb. This bucket brigade is then retrieved by the downstream filter when our handler returns.

約束したとおり, このフィルタハンドラで私たちは bucket brigade 修正の最初のテクニックを使いました。ハンドラは一時的な bucket brigade (ctx_bb) を作成し, get_brigade() を使ってそれにデータを入れ込んで, bucket をそこから bucket brigade $bb に移動します。この bucket brigade はその後私たちのハンドラがリターンしたときにダウンストリームフィルタによって取得されます。
This filter doesn't need to know whether it was invoked for the first time or whether it has already done something. It's a stateless handler, since it has to lower case everything that passes through it. Notice that this filter can't be used as the connection filter for HTTP requests, since it will invalidate the incoming request headers. For example the first header line:

このフィルタはそれが最初に呼びだされたかどうかまたはそれが既に何かを行ったかどうかを知る必要はありません。これはステートレスハンドラ (# 状態を考慮しないハンドラ) です, これはこれを通過するすべてのものを小文字にする必要があるからです。このフィルタは HTTP リクエストのコネクションフィルタとしては使えないことに注意して下さい, これはインカミングのリクエストヘッダを無効にするからです。例えば最初のこのヘッダ行は:

GET /perl/TEST.pl HTTP/1.1

becomes:

こうなります:

get /perl/test.pl http/1.1

which invalidates the request method, the URL and the protocol.

これでリクエストメソッド, URL それからプロトコルが無効になります。
To test, we can use the MyApache2::Dump response handler, presented earlier, which dumps the query string and the content body as a response. Configure the server as follows:

テストのために, 私たちは前に提示した, MyApache2::Dump レスポンスハンドラを使い, クエリストリングとコンテンツボディをレスポンスとしてダンプします。サーバを次のように構成します:

<Location /lc_input>
SetHandler modperl
PerlResponseHandler +MyApache2::Dump
PerlInputFilterHandler +MyApache2::InputRequestFilterLC
</Location>

Now when issuing a POST request:

そうしてこの POST リクエストを発行すると:

% echo "mOd_pErl RuLeS" | POST 'http://localhost:8002/lc_input?FoO=1&BAR=2'

we get a response:

私たちはこのレスポンスをゲットします:

args:
FoO=1&BAR=2
content:
mod_perl rules

We can see that our filter has lowercased the POSTed body before the content handler received it. And you can see that the query string wasn't changed.

私たちはコンテンツハンドラがそれを受けとる前に私たちのフィルタが POST されたボディを小文字にしたことを見ることができます。そしてあなたはクエリストリングが変更されていないことも見ます。
We have devoted so much attention to bucket brigade filters, even though they are simple to manipulate, because it is important to understand how the filters work underneath. This understanding is essential when you need to debug filters or to optimize them. There are cases when a bucket brigade filter may be more efficient than the stream-oriented version. For example if the filter applies a transformation to selected buckets, certain buckets may contain open filehandles or pipes, rather than real data. When you call read(), as shown above, the buckets will be forced to read that data in. But if you didn't want to modify these buckets you could pass them as they are and let Apache perform faster techniques for sending data from the file handles or pipes.

私たちは bucket brigade フィルタに熱心に注目しています, それらの操作はシンプルですが, 裏でフィルタがどのように機能しているかを理解することが重要だからです。この理解はあなたがフィルタをデバッグしたりそれらを最適化する必要があるときに不可欠です。bucket brigade フィルタがストリーム指向フィルタよりも効率的なケースがあります。例えばフィルタが選択された buckets に変換を適用する場合, 特定の buckets は実際のデータではなく, オープンファイルハンドルやパイプを含んでいる場合があります。
あなたが上で示したように, read() をコールすると, buckets はそのデータを強制的に読むようになります。しかしあなたがこれらの buckets を修正したくない場合あなたはこれらをそのまま渡してファイルハンドラやパイプからデータを送信するためにより高速なテクニックを Apache に実行させることができます。
The call to $b->read(), or any other operation that internally forces the bucket to read the information into the memory (like the length() op), makes the data handling less efficient because it creates more work. Therefore care should be taken so not to read the data in unless it's really necessary, and sometimes you can gain this efficiency only by working with the bucket brigades.

$b->read() の呼びだし, または内部で bucket に情報のメモリへの読み込みを強制する他のオペレーション (length() 操作のような) は, より多くの仕事を作るのでデータハンドリングの効率を低下させます。したがって本当に必要でない限りデータを読み込まないように注意しなければならず, ときおりあなたは bucket brigades で作業するだけのことでこの効率性を得ることができます。


ストリーム指向のインプット : Stream-oriented Input Filters



Let's now look at the same filter implemented using the stream-oriented API.

ではストリーム指向 API を使って実装した同じフィルタを見てみることにしましょう。

#file:MyApache2/InputRequestFilterLC2.pm
#--------------------------------------
package MyApache2::InputRequestFilterLC2;

use strict;
use warnings;

use base qw(Apache2::Filter);

use Apache2::Const -compile => 'OK';

use constant BUFF_LEN => 1024;

sub handler : FilterRequestHandler {
my $f = shift;

while ($f->read(my $buffer, BUFF_LEN)) {
$f->print(lc $buffer);
}

Apache2::Const::OK;
}
1;

The logic is very simple here. The filter reads in a loop and prints the modified data, which at some point will be sent to the next filter. The data transmission is triggered every time the internal mod_perl buffer is filled or when the filter returns.

ここでロジックはとてもシンプルです。フィルタはループ内で読み込んで修正したデータを出力します, それはある時点で次のフィルタに送られます。データの伝送は mod_perl バッファが満たされるかフィルタがリターンするたびにトリガされます。
read() populates $buffer to a maximum of BUFF_LEN characters (1024 in our example). Assuming that the current bucket brigade contains 2050 chars, read() will get the first 1024 characters, then 1024 characters more and finally the remaining 2 characters. Note that even though the response handler may have sent more than 2050 characters, every filter invocation operates on a single bucket brigade so you have to wait for the next invocation to get more input. Earlier we showed that you can force the generation of several bucket brigades in the content handler by using rflush(). For example:

read() は $buffer に BUFF_LEN の最大まで (私たちの例では 1024) を入れ込みます。現在の bucket brigade が 2050 文字を含んでいると想定すると, read() は最初の 1024 文字, それからまた 1024 文字を最後に残りの 2 文字をゲットします。レスポンスハンドラは 2050 文字以上の送信をできますが, すべてのフィルタ呼びだしは単一の bucket brigade で動作するのであなたは次の呼び出しがより多くのインプットをゲットするのを待たなければならないことに注意して下さい。
前に私たちはあなたがコンテンツハンドラで rflush() を使うことでいくつかの bucket brigades を強制的に生成できることを示しました。例えば:

$r->print("string");
$r->rflush();
$r->print("another string");

It's only possible to get more than one bucket brigade from the same filter handler invocation if the filter is not using the streaming interface. In that case you can call get_brigade() as many times as needed or until EOS is received.

同じフィルタハンドラの呼び出しから 1 つ以上の bucket brigade をゲットするのはフィルタがストリーミングインターフェイスを使っていない場合でのみ可能です。そのケースであなたは get_brigade() を必要な回数または EOS を受けとるまでコールすることができます。
The configuration section is nearly identical for the two types of filters:

構成セクションは 2 つのタイプのフィルタでほとんど同じです:

<Location /lc_input2>
SetHandler modperl
PerlResponseHandler +MyApache2::Dump
PerlInputFilterHandler +MyApache2::InputRequestFilterLC2
</Location>

When issuing a POST request:

この POST リクエストを発行すると:

$ echo "mOd_pErl RuLeS" | POST 'http://localhost:8002/lc_input2?FoO=1&BAR=2'

we get the response:

私たちはこのレスポンスをゲットします:

args:
FoO=1&BAR=2
content:
mod_perl rules

As before, we see that our filter has lowercased the POSTed body before the content handler received it and the query string wasn't changed.

前と同様に, 私たちは私たちのフィルタがコンテンツハンドラがそれを受けとる前に POST されたボディを小文字してありクエリストリングは変更されていないこと見ます。


アウトプットフィルタ : Output Filters



As discussed above in the section HTTP Request vs. Connection Filters, mod_perl supports Connection and HTTP Request output filters. In the following sections we will look at each of these in turn.

上のセクション HTTP Request vs. Connection Filters で論じたように, mod_perl はコネクションHTTP リクエストのアウトプットフィルタをサポートします。次のセクションで私たちはこれらをそれぞれ順番に見ていきます。
mod_perl supports Connection and HTTP Request output filters. The differences between connection filters and HTTP request filters are described above in the section HTTP Request vs. Connection Filters.

mod_perl はコネクションと HTTP リクエストアウトプットフィルタをサポートします。コネクションフィルタと HTTP リクエストフィルタの間の違いは上記のセクション HTTP Request vs. Connection Filters で論じられています。


コネクションアウトプット : Connection Output Filters



Connection filters filter all the data that is going through the server. Therefore if the connection is of the HTTP request type, connection output filters see the headers and the body of the response, whereas request output filters see only the response body.

コネクションフィルタはサーバを通過するすべてのデータをフィルタします。したがってコネクションが HTTP リクエストのタイプの場合, コネクションアウトプットフィルタはレスポンスのヘッダとボディを見ます, 一方でリクエストアウトプットフィルタはレスポンスボディのみを見ます。
META: for now see the request output filter explanations and examples, connection output filter examples will be added soon. Interesting ideas for such filters are welcome (possible ideas: mangling output headers for HTTP requests, pretty much anything for protocol modules).

META: 今のところリクエストアウトプットフィルタの説明と例を見てください, コネクションアウトプットフィルタの例はもうすぐ追加されます。そうしたフィルタのための興味深いアイデアは歓迎です (考えられるアイデア: HTTP リクエストのアウトプットヘッダをマングリング (# わちゃわちゃ) する, プロトコルモジュールのほとんどすべて)。


HTTP リクエストアウトプット : HTTP Request Output Filters



As mentioned earlier, output filters can be written using the bucket brigades manipulation or the simplified stream-oriented interface. This section will show examples of both.

以前言及したように, アウトプットフィルタは bucket brigades の操作かシンプル化されたストリーム指向のインターフェイスを使って書けます。このセクションは両方の例を示します。
In order to generate output that can be manipulated by the two types of output filters, we will first develop a response handler that sends two lines of output: numerals 1234567890 and the English alphabet in a single string:

2 つのタイプのアウトプットフィルタで操作できるアウトプットを生成するために, 私たちは最初に 2 行のアウトプットを送るレスポンスハンドラを開発します: 数字 1234567890 とひとつの文字列で英語のアルファベット:

#file:MyApache2/SendAlphaNum.pm
#-------------------------------
package MyApache2::SendAlphaNum;

use strict;
use warnings;

use Apache2::RequestRec ();
use Apache2::RequestIO ();

use Apache2::Const -compile => qw(OK);

sub handler {
my $r = shift;

$r->content_type('text/plain');

$r->print(1..9, "0\n");
$r->print('a'..'z', "\n");

return Apache2::Const::OK;
}
1;

In the examples below, we'll create a filter handler to reverse every line of the response body, preserving the new line characters in their places. Since we want to reverse characters only in the response body, without breaking the HTTP headers, we will use the HTTP request output filter rather than a connection output filter.

以下の例で, 私たちはレスポンスボディのすべての行を反転し, 改行文字をその場に保全するフィルタハンドラを作成します。私たちは HTTP ヘッダを壊すことなく, レスポンスボディでのみ文字列を反転したいので, 私たちはコネクションアウトプットフィルタでなく HTTP リクエストアウトプットフィルタを使います。

ストリーム指向のアウトプット : Stream-oriented Output Filters



The first filter implementation uses the stream-oriented filtering API:

最初のフィルタはストリーム指向のフィルタリング API を使って実装します:

#file:MyApache2/FilterReverse1.pm
#----------------------------
package MyApache2::FilterReverse1;

use strict;
use warnings;

use base qw(Apache2::Filter);

use Apache2::Const -compile => qw(OK);

use constant BUFF_LEN => 1024;

sub handler : FilterRequestHandler {
my $f = shift;

while ($f->read(my $buffer, BUFF_LEN)) {
for (split "\n", $buffer) {
$f->print(scalar reverse $_);
$f->print("\n");
}
}

return Apache2::Const::OK;
}
1;

Next, we add the following configuration to httpd.conf:

次に, 私たちは次の構成を httpd.conf に追加します:

PerlModule MyApache2::FilterReverse1
PerlModule MyApache2::SendAlphaNum
<Location /reverse1>
SetHandler modperl
PerlResponseHandler MyApache2::SendAlphaNum
PerlOutputFilterHandler MyApache2::FilterReverse1
</Location>

Now when a request to /reverse1 is sent, the response handler MyApache2::SendAlphaNum::handler() sends:

これで /revers1 にリクエストを送ると, レスポンスハンドラ MyApachce2::SendAlphaNum::handler() がこれを送ります:

1234567890
abcdefghijklmnopqrstuvwxyz

as a response. The output filter handler MyApache2::FilterReverse1::handler reverses the lines, so the client gets:

レスポンスとして。アウトプットフィルタハンドラ MyApache2::FilterReverse1::handler はその行を反転するので, クライアントはこれをゲットします:

0987654321
zyxwvutsrqponmlkjihgfedcba

The Apache2::Filter module loads the read() and print() methods which encapsulate the stream-oriented filtering interface.

Apache2::Filter モジュールはストリーム指向のフィルタリングインターフェイスをカプセル化する read() と print() メソッドをロードします。
The reversing filter is quite simple: in the loop it reads the data in the readline() mode in chunks up to the buffer length (1024 in our example), and then prints each line reversed while preserving the new line control characters at the end of each line. Behind the scenes $f->read() retrieves the incoming brigade and gets the data from it, and $f->print() appends to the new brigade which is then sent to the next filter in the stack. read() breaks the while loop when the brigade is emptied or the end of stream is received.

反転フィルタは非常にシンプルです: ループでは readline() モードでバッファ長 (私たちの例では 1024) までチャンクでデータを読み込み, それから各行の終わりで改行制御文字を保全しながら各行を反転して出力します。舞台裏で $f->read() はインカミングの brigade を取得してそこからデータをゲットし, $f->print() がその後にスタックの次のフィルタに送られる新しい brigade に追加します。read() は brigade が空になるかストリームの終わりを受信すると while ループを抜けだします。
While this code is simple and easy to explain, there are cases it won't handle correctly. For example, it will have problems if the input lines are longer than 1,024 characters. It also doesn't account for the different line terminators on different platforms (e.g., "\n", "\r", or "\r\n"). Moreover a single line may be split across two or even more bucket brigades, so we have to store the unprocessed string in the filter context so it can be used on the following invocations. Below is an example of a more complete handler, which takes care of these issues:

このコードはシンプルで説明が簡単ですが, これが正しく処理されないケースがあります。例えば, インプット行が 1,024 文字より長い場合に問題をもちます。またこれは異なるプラットフォームでの異なるラインターミネータを考慮していません (e.g., "\n", "\r", や "\r\n")。さらに単一の行が 2 つ以上の bucket brigades にわたって分割されるかもしれないので, 私たちは次の呼び出しで使えるようにフィルタコンテキストに未処理の文字列を格納しなければなりません。以下はこれらの問題に対処するより完全なハンドラの例です:

sub handler {
my $f = shift;

my $leftover = $f->ctx;
while ($f->read(my $buffer, BUFF_LEN)) {
$buffer = $leftover . $buffer if defined $leftover;
$leftover = undef;
while ($buffer =~ /([^\r\n]*)([\r\n]*)/g) {
$leftover = $1, last unless $2;
$f->print(scalar(reverse $1), $2);
}
}

if ($f->seen_eos) {
$f->print(scalar reverse $leftover) if defined $leftover;
}
else {
$f->ctx($leftover) if defined $leftover;
}

return Apache2::Const::OK;
}

The handler uses the $leftover variable to store unprocessed data as long as it fails to assemble a complete line or there is an incomplete line following the new line token. On the next handler invocation this data is then prepended to the next chunk that is read. When the filter is invoked for the last time, signaled by the $f->seen_eos method, it unconditionally reverses and sends the data down the stream, which is then flushed down to the client.

このハンドラは完全な行の組み立てに失敗したり改行トークンに続く不完全な行がある限り未処理のデータを格納するために $leftover 変数を使います。次のハンドラ呼びだしでこのデータはその後に次に読み込むチャンクの前に追加されます。$f->seen_eos メソッドによる合図で, フィルタが最後に呼ばれたとき, これはデータを無条件に反転しストリームに送りだされ, その後にクライアントにフラッシュされます (# 一度に流される )。


バケツリレーベースのアウトプット : Bucket Brigade-based Output Filters



The following filter implementation uses the bucket brigades API to accomplish exactly the same task as the first filter.

次のフィルタは最初のフィルタとまったく同じタスクを成すために bucket brigade API を使い実装しています。

#file:MyApache2/FilterReverse2.pm
#--------------------------------
package MyApache2::FilterReverse2;

use strict;
use warnings;

use base qw(Apache2::Filter);

use APR::Brigade ();
use APR::Bucket ();

use Apache2::Const -compile => 'OK';
use APR::Const -compile => ':common';

sub handler : FilterRequestHandler {
my ($f, $bb) = @_;

my $bb_ctx = APR::Brigade->new($f->c->pool, $f->c->bucket_alloc);

while (!$bb->is_empty) {
my $b = $bb->first;

$b->remove;

if ($b->is_eos) {
$bb_ctx->insert_tail($b);
last;
}

if ($b->read(my $data)) {
$data = join "",
map {scalar(revers $_), "\n"} split "\n", $data;
$b = APR::Bucket->new($bb->bucket_alloc, $data);
}

$bb_ctx->insert_tail($b);
}

my $rv = $f->next->pass_brigade($bb_ctx);
return $rv unless $rv == APR::Const::SUCCESS;

return Apache2::Const::OK;
}
1;

Below is the corresponding configuration for httpd.conf:

以下は httpd.conf の対応する構成です:

PerlModule MyApache2::FilterReverse2
PerlModule MyApache2::SendAlphaNum
<Location /reverse2>
SetHandler modperl
PerlResponseHandler MyApache2::SendAlphaNum
PerlOutputFilterHandler MyApache2::FilterReverse2
</Location>

Now when a request to /reverse2 is made, the client gets:

これで /reverse2 へのリクエストが作られると, クライアントはこれをゲットします:

0987654321
zyxwvutsrqponmlkjihgfedcba

as expected.

期待したとおりです。
The bucket brigades output filter version is just a bit more complicated than the stream-oriented one. The handler receives the incoming bucket brigade $bb as its second argument. When the handler finishes it must pass a brigade to the next filter in the stack, so we create a new bucket brigade into which we put the modified buckets and which eventually we pass to the next filter.

bucket brigades アウトプットフィルタのバージョンはストリーム指向のものよりちょっとだけ複雑です。ハンドラはインカミングの bucket brigade $bb を 2 番目の引数として受けとります。ハンドラが終了するときそれはスタックの次の brigade に渡さなければならないので, 私たちは新しい bucket brigade を作成してその中に私たちは修正した buckets をプットして最終的にそれを私たちは次のフィルタに渡します。
The core of the handler removes buckets from the head of the bucket brigade $bb, while buckets are available, reads the data from the buckets, then reverses and puts the data into a newly created bucket. The new bucket is then inserted on the end of the new bucket brigade using the insert_tail() method. If we see a bucket which designates the end of stream, we insert that bucket on the tail of the new bucket brigade and break the loop. Finally we pass the created brigade with modified data to the next filter and return.

ハンドラのコアは bucket brigade の先頭から buckets を取り除き, bucket が利用可能の間に, その buckets からデータを読み込み, それから反転して新しく作成した bucket にプットします。その新しい bucket はそれから insert_tail() メソッドを使って新しい bucket brigade の最後にインサートされます。私たちはストリームの最後を示す bucket を見ると, 私たちは新しい bucket brigade の末尾に bucket をインサートしてループを抜けだします。最後に私たちは作成した brigade を修正したデータで次のフィルタに渡してリターンします。
Similar to the original version of MyApache2::FilterReverse1::handler, this filter is not smart enough to handle incomplete lines. The filter could be made more foolproof by building a better matching rule, and using the $leftover buffer as demonstrated in the previous section. This left as an exercise for the reader.

MyApache2::FilterReverse1::handler と同様に, このフィルタは不完全な行を処理するほどにはスマートではありません。前のセクションで実演したようによりよいマッチングルールを構築して, $leftover バッファを使うことでフィルタはより間違いのないものにできます。これは読み手ののためのエクササイズとして残されています。


フィルタアプリケーション : Filter Applications



The following sections provide various filter applications and their implementation.

次のセクションは様々なフィルタアプリケーションとその実装を提供します。


データアンダーランの処理 : Handling Data Underruns



Sometimes filters need to read at least N bytes before they can apply their transformation. It's quite possible that reading one bucket brigade is not enough, but that two or more are needed. This situation is sometimes referred to as an underrun.

フィルタはそれがその変換を適用する前に少なくとも N バイトの読み込みを必要とする場合があります。その読み込みにはひとつの bucket brigade では不十分で, 2 つ以上を必要とする可能性がかなりあります。このシチュエーションはアンダーランとして言及されることがあります。
Let's take an input filter as an example. When the filter realizes that it doesn't have enough data in the current bucket brigade, it can store the read data in the filter context, and wait for the next invocation of itself, which may or may not satisfy its needs. While it is gathering the data from the bucket brigades, it must return an empty bucket brigade to the upstream input filter. However, this is not the most efficient technique to resolve underruns.

例としてインプットフィルタを取り上げましょう。フィルタが現在の bucket brigade が十分なデータをもっていないと認識したとき, フィルタコンテキストに読んだデータを格納して, その次の呼びだしを待つことができます, これでニーズが満たされることもそうでないこともあります。bucket brigades からデータを集めている間は, 空の bucket brigade をアップストリームのインプットフィルタにリターンしなければなりません。しかし, これはアンダーランを解決するもっとも効果的なテクニックではありません。
Instead of returning an empty bucket brigade, the input filter can request extra bucket brigades until the underrun condition gets resolved. Note that this solution is transparent to any filters before or after the current filter.

空の bucket brigade をリターンする代わりに, インプットフィルタはアンダーランの条件が解決するまで追加の bucket brigades をリクエストできます。このソリューションは現在のフィルタの前後のフィルタに透過的であることに注意してください。
Consider this HTTP request:

この HTTP リクエストを考えます:

$ perl -MLWP::UserAgent -le ' \
$r = LWP::UserAgent->new()->post("http://localhost:8011/", \
[content => "x" x (40 * 1024 + 7)]); \
print $r->is_success ? $r->content : "failed: " . $r->code'
read 40975 chars

This client POSTs just a little bit more than 40kb of data to the server. Normally Apache splits incoming POSTed data into 8kb chunks, putting each chunk into a separate bucket brigade. Therefore we expect to get 5 brigades of 8kb, and one brigade with just a few bytes (a total of 6 bucket brigades).

このクライアントは 40kb をちょっとだけ超えるデータをサーバに POST します。普通 Apache はインカミングの POST されたデータを 8kb のチャンクに分割して, 各チャンクを別々の bucket brigade に配置します。したがって私たちは 8kb の 5 brigades と, 数バイトだけのひとつの brigade (合計 6 bucket brigades) をゲットすることを期待します。
Now let's assume our example filter needs to have 1024*16 + 5 bytes to have a complete token before it can start its processing. The extra 5 bytes are just so we don't perfectly fit into 8kb bucket brigades, making the example closer to real situations. Having 40,975 bytes of input and a token size of 16,389 bytes, we will have 2 full tokens and a remainder of 8,197 bytes.

ここで私たちの例のフィルタがその処理をスタートする前に完全なトークンをもつために 1024*16 + 5 バイトもつ必要があると想定しましょう。追加の 5 バイトは私たちが 8kb の bucket brigades に完全にフィットしないようにするためで, この例をリアルのシチュエーションに近いものにします。インプットの 40,975 バイトと 16,389 バイトのトークサイズがあるので, 私たちは 2 つの完全なトークンと残りの 8,197 バイトを持つことになります。
Before showing any code, let's look at the filter debug output to better explain what we expect to happen:

コードを示す前に, 私たちが期待することをよりよく説明するフィルタのデバッグのアウトプット見てみましょう:

filter called
asking for a bb
asking for a bb
asking for a bb
storing the remainder: 7611 bytes

filter called
asking for a bb
asking for a bb
storing the remainder: 7222 bytes

filter called
asking for a bb
seen eos, flushing the remaining: 8197 bytes

We can see that the filter was invoked three times. The first time it has consumed three bucket brigades, collecting one full token of 16,389 bytes with a remainder of 7,611 bytes to be processed on the next invocation. The second time it needed only two more bucket brigades and this time, after completing the second token, 7,222 bytes remained. Finally on the third invocation it consumed the last bucket brigade for a total of six, just as we expected. However, it didn't have enough for the third token and since EOS has been seen (no more data expected), it has flushed the remaining 8,197 bytes as we calculated earlier.

私たちはフィルタが 3 回呼びだされたことを見ることができます。初回でそれは 3 つの bucket brigades を消費して, 16,389 バイトのひとつの完全なトークンを収集し残りの 7,611 バイトを次の呼びだしで処理します。2 回目ではさらに 2 つのみの bucket brigades が必要とされ, この回では 2 つめのトークンが完了した後に, 7222 バイトが残りました。最後の 3 回目の呼びだしで私たちの期待どおり, 合計 6 個めの最後の bucket が消費されます。しかし, それは 3 つめのトークンには十分ではなく EOS が確認されたので (これ以上のデータが期待されない), 私たちが前に計算したように残りの 8,197 バイトがフラッシュされます。
It is clear from the debugging output that the filter was invoked only three times, instead of six times (there were six bucket brigades). Notice that the upstream input filter, if there is one, isn't aware that there were six bucket brigades, since it saw only three. Our example filter didn't do much with those tokens, so it has only repackaged data from 8kb per bucket brigade, to 16,389 bytes per bucket brigade. But of course in a real implementation some transformation would be applied on these tokens.

フィルタが 6 回ではなく, 3 回のみ呼びだされたことがデバッグのアウトプットから明らかです (6 つの bucket brigades がありました)。アップストリームのインプットフィルタが, もしあっても, 6 つの bucket brigades があることに気づかないことに注意して下さい, それは 3 つしか見ないからです。私たちの例のフィルタはこれらのトークンでたいしたことは行っておらず, bucket brigade ごとに 8kb から, bucket brigade ごとに 16,389 バイトにデータを再パッケージしただけです。しかしもちろんリアルの実装ではこれらのトークンに何らかの変換が適用されるでしょう。
Now let's look at the implementation details. First let's look at the response() handler, which is the first part of the module:

では実装の詳細を見てみましょう。最初に response() ハンドラを見ます, それはモジュールの最初の部分です:

#file:MyApache2/Underrun.pm
#-------------------------
package MyApache2::Underrun;

use strict;
use warnings;

use constant IOBUFSIZE => 8192;

use Apache2::Const -compile => qw(MODE_READBYTES OK M_POST);
use APR::Const -compile => qw(SUCCESS BLOCK_READ);

sub response {
my $r = shift;

$r->content_type('text/plain');

if ($r->method_number == Apache2::Const::M_POST) {
my $data = read_post($r);
#warn "HANDLER READ: $data\n";
my $length = length $data;
$r->print("read $length chars");
}

return Apache2::Const::OK;
}

sub read_post {
my $r = shift;

my $bb = APR::Brigade->new($r->pool, $r->connection->bucket_alloc);

my $data = '';
my $seen_eos = 0;
do {
$r->input_filters->get_brigade($bb, Apache2::Const::MODE_READBYTES,
APR::Const::BLOCK_READ, IOBUFSIZE);

for (my $b = $bb->first; $b; $b = $bb->next($b)) {
if ($b->is_eos) {
$seen_eos++;
last;
}

if ($b->read(my $buf)) {
$data .= $buf;
}

$b->remove; # optimization to reuse memory
}
} while (!$seen_eos);

$bb->destroy;

return $data;
}

The response() handler is trivial -- it reads the POSTed data and prints how many bytes it has read. read_post() sucks in all POSTed data without parsing it.

response() ハンドラはたいしたことはありません -- それは POST されたデータを読んで読んだバイトがいくつだったかを出力します。read_post() はすべての POST されたデータをパースすることなく吸い込みます。
Now comes the filter (which lives in the same package):

こんどはフィルタです (同じパッケージ内にあります):

#file:MyApache2/Underrun.pm (continued)
#-------------------------------------
use Apache2::Filter ();

use Apache2::Const -compile => qw(OK M_POST);

use constant TOKEN_SIZE => 1024*16 + 5; # ~16k

sub filter {
my ($f, $bb, $mode, $block, $readbytes) = @_;
my $ba = $f->r->connection->bucket_alloc;
my $ctx = $f->ctx;
my $buffer = defined $ctx ? $ctx : '';
$ctx = ''; # reset
my $seen_eos = 0;
my $data;
warn "\nfilter called\n";

# fetch and consume bucket brigades until we have at least TOKEN_SIZE
# bytes to work with
do {
my $tbb = APR::Brigade->new($f->r->pool, $ba);
my $rv = $f->next->get_brigade($tbb, $mode, $block, $readbytes);
warn "asking for a bb\n";
($data, $seen_eos) = flatten_bb($tbb);
$tbb->destroy;
$buffer .= $data;
} while (!$seen_eos && length($buffer) < TOKEN_SIZE);

# now create a bucket per chunk of TOKEN_SIZE size and put the remainder
# in ctx
for (split_buffer($buffer)) {
if (length($_) == TOKEN_SIZE) {
$bb->insert_tail(APR::Bucket->new($ba, $_));
}
else {
$ctx .= $_;
}
}

my $len = length($ctx);
if ($seen_eos) {
# flush the remainder
$bb->insert_tail(APR::Bucket->new($ba, $ctx));
$bb->insert_tail(APR::Bucket::eos_create($ba));
warn "seen eos, flushting the remaining: $len bytes\n";
}
else {
# wil re-use the remainder on the next invocation
$f->ctx($ctx);
warn "storing the remainder: $len bytes\n";
}

return Apache2::Const::OK;
}

# split a string into tokens of TOKEN_SIZE bytes and a remainder
sub split_buffer {
my $buffer = shift;
if ($] < 5.007) {
my @tokens = $buffer =~ /(.{@{[TOKEN_SIZE]}}|.+)/g;
return @tokens;
}
else {
# available only since 5.7.x+
retunr unpack "(A" . TOKEN_SIZE . ")*", $buffer;
}
}

sub flatten_bb {
my ($bb) = shift;

my $seen_eos = 0;

my @data;
for (my $b = $bb->first; $b; $b = $bb->next($b)) {
$seen_eos++, last if $b->is_eos;
$b->read(my $bdata);
push @data, $bdata;
}
retunr (join('', @data), $seen_eos);
}

1;

The filter calls get_brigade() in a do-while loop until it reads enough data or sees EOS. Notice that it may get underruns several times, and then suddenly receive a lot of data at once, which will be enough for more than one minimal size token, so we have to take this into an account. Once the underrun condition is satisfied (we have at least one complete token) the tokens are put into a bucket brigade and returned to the upstream filter for processing, keeping any remainders in the filter context for the next invocations or flushing all the remaining data if EOS is seen.

フィルタは十分なデータを読みこむか EOS を見るまで do-while ループで get_brigade() をコールします。それは何回かアンダーランしてから, 一度に突然多くのデータを受けとるかもしれず, これはひとつ以上の最小サイズのトークンに十分な量なので, 私たちはこれを考慮しなければならないことに注意してください。アンダーランの条件が満たされると (私たちは少なくともひとつの完全なトークンをもちます) トークンは bucket brigade に置かれて処理のためにアップストリームフィルタにリターンされ, 次の呼びだしのためにフィルタコンテキストの残りを維持するかまたは EOS が見られるとすべての残りのデータをフラッシュします。
Note that this example cannot be implemented with streaming filters because each invocation gives the filter exactly one bucket brigade to work with. The streaming interface does not currently provide a facility to fetch extra brigades.

各呼びだしは共に機能する bucket brigade をひとつだけフィルタに与えるのでこの例はストリーミングフィルタで実装できないことに注意してください。ストリーミングインターフェイスは追加の brigades をフェッチする能力を現在提供していません。
Here is the Apache configuration for this example:

こちらがこの例のための Apachce の構成です:

PerlModule MyApache2::Underrun
<Location />
PerlInputFilterHandler MyApache2::Underrun::filter
SetHandler modperl
PerlResponseHandler MyApache2::Underrun::response
</Location>



リクエストアウトプットフィルタで Content-Length ヘッダをセッティングする : Setting the Content-Length Header in Request Output Filters



Earlier we have stated that a filter that modifies the content's length must unset the Content-Length HTTP header. However sometimes it's desirable to have this header set, for example when dealing with proxies.

前にコンテンツの長さを修正したフィルタは Content-Lenght HTTP ヘッダをアンセットしなければならないと私たちは述べました。しかしこのヘッダをセットしておくことが望ましい場合があります, 例えばプロクシで処理するときです。
Since the headers are sent before the data, all the data must first be buffered and processed. You cannot accomplish this task with the streaming filter API since it passes FLUSH buckets through. As soon as the FLUSH bucket is received by the core filter that sends the headers, it generates the headers and sends those out. Therefore the bucket brigade API must be used here to have a complete control over what's going through. Here is a possible implementation:

ヘッダはデータの前に送られるので, すべてのデータは最初にバッファされて処理されなければなりません。あなたはストリーミングフィルタ API でこのタスクを成すことはできませんそれは FLUSH buckets を通過するからです。FLUSH bucket がヘッダを送るコアフィルタによって受信されるとすぐに, ヘッダを生成してそれらを送りだします。したがって何が通るかの完全なコントロールをもつために bucket brigade API はここで使われなければなりません。こちらが可能な実装です:

#file:MyApache2/FilterChangeLength.pm
#-------------------------------------
package MyApache2::FilterChangeLength;

use strict;
use warnings FATAL => 'all';

use Apache2::RequestRec ();

use APR::Table ();
use APR::Bucket ();
use APR::Brigade ();

use base qw(Apache2::Filter);

use Apache2::Const -compile => qw(OK);
use APR::Const -compile => ':common';

sub handler {
my ($filter, $bb) = @_;

my $ctx = $filter->ctx;

# no need to unset the C-L header, since this filter makes sure to
# correct it before any headers go out.
# unless ($ctx) {
# $filter->r->headers_out->unset('Content-Length');
#}

my $data = exists $ctx->{data} ? $ctx->{data} : '';
$ctx->{invoked}++;
my ($bdata, $seen_eos) = flatten_bb($bb);
$bdata =~ s/-//g;
$data .= $bdata if $bdata;

if ($seen_eos) {
my $len = length $data;
$filter->r->headers_out->set('Content-Length', $len);
$filter->print($data) if $data;
}
else {
# store context for all but the last invocation
$ctx->{data} = $data;
$filter->ctx($ctx);
}

return Apache2::Const::OK;
}

sub flatten_bb {
my ($bb) = shift;

my $seen_eos = 0;

my @data;
for (my $b = $bb->first; $b; $b = $bb->next($b)) {
$seen_eos++, last if $b->is_eos;
$b->read(my $bdata);
push @data, $bdata;
}
return (join('', @data), $seen_eos);
}

1;

In this module we use flatten_bb() to read the data from the buckets and signal when the EOS is received. The filter simply collects the data, storing it in the filter context. When it receives EOS it sets the Content-Length header and sends the data out.

このモジュールで私たちはbucket からのデータの読み込みと EOS が受信されたときのシグナルに flatten_bb() を使います。フィルタはシンプルにデータを収集して, そのフィルタコンテキストに格納します。EOS を受信すると Content-Length ヘッダをセットしてデータを送りだします。
The configuration is straightforward:

構成は単純です:

PerlOutputFilterHandler MyApache2::FilterChangeLength



フィルタのチップスとトリック : Filter Tips and Tricks



Various tips to use in filters.

フィルタで使うさまざまなチップス。


Content-Type レスポンスヘッダの変更 : Altering the Content-Type Response Header



Let's say that you want to modify the Content-Type header in the request output filter:

あなたがリクエストアウトプットフィルタで Content-Type ヘッダを修正したいということにします:

sub handler : FilterRequestHandler {
my $f = shift;
...
$f->r->content_type("text/html; charset=$charset");
...

Request filters have an access to the request object, so we simply modify it.

リクエストフィルタはリクエストオブジェクトへのアクセスをもつので, あなたはシンプルにそれを修正します。


行儀のよいフィルタを書く : Writing Well-Behaving Filters



Filter writers must follow the following rules:

フィルタの書き手は次のルールに従わなければなりません:


KeepAlive コネクション上でのコネクションフィルタ : Connection Filters over KeepAlive Connections



Whenever a new HTTP request is processed, request filters get their context ($f->ctx) reset. This is also true for the connection filter context, as long as the connection is not a keepalive) connection. When the connection is kept alive, there could be many requests processed during a single connection and the same filter context will persist through all of them, until the maximum number of KeepAlive requests over the same connection is reached or until the client breaks the connection.

新しい HTTP リクエストが処理されるたびに, リクエストフィルタはそれらのコンテキスト ($f->ctx) をリセットします。これはコネクションフィルタのコンテキストのコネクションにも当てはまります (コネクションが keepalive でない限りは)。コネクションがキープアライブされているときは, 単一のコネクションのあいだに多くのリクエストが処理されるかもしれず同じコネクション上で KeepAlive リクエストの最大数に達するかクライアントがそのコネクションを切断するまで, 同じフィルタコンテキストはそれらすべてを通じて持続します。
Sometimes it's desirable to reset the whole context or parts of it before a HTTP request is processed. For example Apache2::Filter::HTTPHeadersFixup needs to know when it should start and stop processing HTTP headers. It keeps the state in the filter's context. The problem is that whenever a new HTTP request is coming in, it needs to be able to reset the state machine. If it doesn't, it will process the HTTP headers of the first request and miss the rest of the requests.

HTTP リクエストが処理される前にコンテキスト全体やその一部をリセットすることが望ましい場合があります。例えば Apache2::Filter::HTTPHeadersFixup はそれがいつ HTTP ヘッダの処理をスタートしてストップするべきかを知る必要があります。それはフィルタコンテキストで状態をキープします。問題は新しい HTTP リクエストがくるたびに, それがステートマシンをリセットできるようにする必要があることです。それを行わないと, 最初のリクエストの HTTP ヘッダを処理してリクエストの残りを見逃します。
So let's say we have a hypothetical module MyApache2::Filter::StateMachine which implements an input connection filter and it processes incoming data as long as the state flag is down. Once that flag goes up, the filter switches to the pass-through-unmodified mode. Here is a skeleton of the module:

では私たちがインプットコネクションフィルタの実装で状態フラグがダウンしている限りはインカミングのデータを処理する仮定のモジュール MyApache2::Filter::StateMachine をもっているということにしましょう。そのフラグが上がると, フィルタはパススルー未修整モードにスイッチします。こちらがモジュールのスケルトンです:

#file:MyApache2/Filter/StateMachine.pm
#------------------------------------
packeage MyApache2::Filter::StateMachine;

use base qw(Apache2::Filter);
use Apache2::Connection ();

use Apache2::Const -compile => qw(OK DECLINED CONN_KEEPALIVE);

sub handler : FilterConnectionHandler {
my ($f, $bb, $mode, $block, $readbytes) = @_;

my $ctx = context($f);

# pass through unmodified
return Apache2::Const::DECLINED if $ctx->{state};

# get data, do some processing, send it out
process(); # your code comes here

# change the sate if some condition is reached
$ctx->{state}++ if $done_condition;

return Apache2::Const::OK;
}

sub context {
my ($f) = shift;

my $ctx = $f->ctx;
unless ($ctx) {
$ctx = {
state => 0,
};

$f->ctx($ctx);
}

return $ctx;
}
1;

To make this module work properly over KeepAlive connections, we want to reset the state flag at the very beginning of the new request. To accomplish this, all we need to do is to change the context wrapper to be:

このモジュールを KeepAlive コネクション上で適切に機能させるに, 私たちは新しいリクエストのかなり最初でステートフラグをリセットします。これをするために, 私たちが行う必要のあるすべてはコンテキストラッパーをこのように変更するだけです:

sub context {
my ($f) = shift;

my $ctx = $f->ctx;
unless ($ctx) {
$ctx = {
state => 0,
keepalives => $f->c->keepalives,
};

$f->ctx($ctx);
return $ctx;
}

my $c = $f->c;
if ($c->keepalive == Apache2::Const::CONN_KEEPALIVE &&
$ctx->{state} && $c->keepalives > $ctx->{keepalives}) {

$ctx->{state} = 0;
$ctx->{keepalives} = $c->keepalives;
}

return $ctx;
}

The only difference from the previous implementation is that we maintain one more state, which stores the number of requests served over the current connection. When Apache reports more served requests than we have in the context that means that we have a new request coming in. So we reset the state flag and store the new value of the served connections.

前の実装との唯一の違いは私たちが現在のコネクション上でサーブされたリクエストの数を格納する, もうひとつのステートを維持することです。Apache が私たちがコンテキストでもっているよりも多くのサーブされたリクエストをリポートするときそれは私たちが新しく来るリクエストをもつことを意味します。ですから私たちはステートフラグをリセットしてサーブされたコネクションの新しい値を格納します。
For a more complete real-world implementation, see: http://search.cpan.org/dist/Apache-Filter-HTTPHeadersFixup/

より完全な実世界の実装は, これを参照してください: http://search.cpan.org/dist/Apache-Filter-HTTPHeadersFixup/


HTTP ヘッダの調整 : Adjusting HTTP Headers



The following information is relevant for HTTP filters

次の情報は HTTP フィルタに関連しています


  • Unsetting the Content-Length header

    Content-Lnegth ヘッダをアンセットする
    HTTP response filters modifying the length of the body they process must unset the Content-Length header. For example, a compression filter modifies the body length, whereas a lowercasing filter doesn't; therefore the former has to unset the header, and the latter doesn't have to.

    それが処理するボディの長さを修正する HTTP レスポンスフィルタは Content-Length ヘッダをアンセットしなければなりません。例えば, 圧縮フィルタはボディの長さを修正します, 一方で小文字化するフィルタはそうではありません; したがって前者はヘッダをアンセットしなければならず, 後者はそうする必要はありません。
    The header must be unset before any output is sent from the filter. If this rule is not followed, an HTTP response header with incorrect Content-Length value might be sent.

    ヘッダはアウトプットがフィルタから送られる前にアンセットされなければなりません。このルールに従っていないなら, 不正な Content-Length の値で HTTP レスポンスヘッダが送信されるかもしれません。
    Since you want to run this code once during the multiple filter invocations, use the ctx() method to set the flag:

    あなたはこのコードを複数のフィルタの呼びだしの間に 1 度呼びだしたいはずなので, フラグのセットに ctx() メソッドを使います:

    unless ($f->ctx) {
    $f->r->headers_out->unset('Content-Length');
    $f->ctx(1);
    }



  • META: Same goes for last-modified/etags, which may need to be unset, "vary" might need to be added if you want caching to work properly (depending on what your filter does.

    META: last-modified/etags でも同じです, これらはアンセットが必要かもしれず, キャッシュを適切に機能させるために "vary" の追加が必要かもしれません (あなたのフィルタが何を行うかによります)。




他の問題 : Other issues



META: to be written. Meanwhile collecting important inputs from various sources.

META: いずれ書かれます。その間にさまざまなソースからの重要なインプットを収集します。
[
If a filter desires to store the incoming buckets for post processing. It must check whether the bucket type is transient. If it is -- the data must be copied away. If not -- the buckets may contain corrupted data when used later. The right thing is accomplished transparently by apr_bucket_setaside, for which we need to provide a perl glue.

フィルタが後の処理のためにインカミング buckets を格納することを希求する場合。それは bucket タイプが transient (# 一時的なもの) かをチェックする必要がある。もしそうなら -- データはコピーされなければならない。もしそうでないなら -- buckets は後で使われるときに破損したデータを含んでいるかもしれない。正しいことは apr_bucket_setaside によって透過的に行われ, このために私たちは perl の接着剤の提供する必要がある。
]
[
This one will be expanded by Geoff at some point:

これはある時点で Geoff により拡張される:
HTTP output filter developers are ought to handle conditional GETs properly... (mostly for the reason of efficiency?)

HTTP アウトプットフィルタの開発者は条件付き GET を適切に処理しなければならない... (主に効率が理由 ?)
]
[
talk about issues like not losing meta-buckets. e.g. if the filter runs a switch statement and propagates buckets types that were known at the time of writing, it may drop buckets of new types which may be added later, so it's important to ensure that there is a default cause where the bucket is passed as is.

メタ bucket を失わないようにする的な論点について話をする。e.g. フィルタが switch 構文を実行して書き込み時に知られた buckets タイプを伝播すると, 後で追加されるかもしれない新しいタイプの buckets がドロップするかもしれないため, bucket がそのまま渡されるデフォルトの原因がそこにあることを確認することが重要。
of course mention the fact where things like EOS buckets must be passed, or the whole chain will be broken. Or if some filter decides to inject an EOS bucket by itself, it should probably consume and destroy the rest of the incoming bb. need to check on this issue.

もちろん EOS buckets のようなものが渡されなければならないという事実について言及する, そうでなければチェーン全体が壊れる。または一部のフィルタがそれ自身で EOS bucket の注入を決めた場合, それは多分インカミングの bb の残りを消費して破棄する。この問題のチェックが必要。
]
[
Need to document somewhere (concepts?) that the buckets should never be modified directly, because the filter can't know ho else could be referencing it at the same time. (shared mem/cache/memory mapped files are examples on where you don't want to modify the data). Instead the data should be moved into a new bucket.

他に誰が同時にそれを参照しているかをフィルタは知らないため, buckets は直接変更されてはならないことをどこか (コンセプトで ?) でドキュメントにする必要がある。(共有された メモリ/キャッシュ/メモリにマップされたファイルがあなたがデータを修正したくない場合の例)。かわりにデータは新しい bucket に移動されなければならない。
Also it looks like we need to $b->destroy (need to add the API) in addition to $b->remove. Which can be done in one stroke using $b->delete (need to add the API).

また私たちは $b->remove に加えて $b->destroy (API の追加が必要) を必要とするように見える。これは $b->delete を使って一気に行える (API の追加が必要)。
]
[
Mention mod_bucketeer as filter debugging tool (in addition to FilterSnoop)

フィルタデバッグツールとして mod_bucketeer に言及する (FilterSnoop に加えて)
]


効率的なフィルタを書く : Writing Efficient Filters



As of this writing, the Apache network input filter reads in 8000B chunks (not 8192B) and makes each bucket 8000B in size. Based on this, the most efficient reading technique is:

これを書いている時点で, Apache ネットワークのインプットフィルタは 8000B (8192B ではない) のチャンク (# 塊り) で読み込み各 bucket を 8000B のサイズにします。これに基づいた, 最も効率的な読み込みのテクニックがこれです:

use constant BUFF_LEN => 8000;
while ($f->read(my $buffer, BUFF_LEN)) {
# manip $buffer
$f->print($buffer);
}

however if there is some filter in between, it may change the size of the buckets. Also this number may change in the future.

しかし間に何らかのフィルタがあると, それは bucket のサイズを変更するかもしれません。またこの数は将来変更されるかもしれません。
Hmm, I've also seen it read in 7819 chunks. I suppose this is not very reliable. But it's probably a good idea to ask at least 8k, so if a bucket brigade has < 8k, nothing will need to be stored in the internal buffer. i.e. read() will return less than asked for.

ウーム, 私は 7819 チャンクでの読み込みを見ました。これはあまり信頼できないと私は思います。しかし少なくとも 8k を求めることはたぶん良いアイデアで, bucket brigade が < 8k をもっていた場合は, 内部バッファには何も格納する必要はありません。i.e. read() は求められたよりも少ないものをリターンします。
]
[
Bucket Brigades are used to make the data flow between filters and handlers more efficient. e.g. a file handle can be put in a bucket and the read from the file can be postponed to the very moment when the data is sent to the client, thus saving a lot of memory and CPU cycles. though filters writers should be aware that if they call $b->read(), or any other operation that internally forces the bucket to read the information into the memory (like the length() op) and thus making the data handling inefficient. therefore a care should be taken so not to read the data in, unless it's really necessary.

Bucket Brigades はフィルタとハンドラ間のデータフローをより効率的にするために使われます。e.g. ファイルハンドルは bucket に置けてそのファイルからの読み込みをデータがクライアントに送信される瞬間に延期できるので, 多くのメモリと CPU サイクルを節約できます。しかしながらフィルタの書き手はそれらが $b-%gt;reas(), または bucket にメモリへの情報の読み込みを内部的に強制する何か他の操作 (length() 操作のような) をコールするとデータ処理は非効率になることに注意しなければなりません。したがってそれが本当に必要とされない限りは, データを読みこまないようにケアする必要があります。
]


CPAN モジュール : CPAN Modules



Several modules are available on the CPAN that implement mod_perl 2.0 filters. As with all code on the CPAN, the source code is fully available, so you can download these modules and see exactly how they work.

mod_perl 2.0 フィルタの実装のいくつかのモジュールあ CPAN で利用可能です。CPAN のすべてのコードのように, ソースコードは完全に利用可能なので, あなたはこれらのモジュールをダウンロードしてそれらがどのように機能するかを正確に見ることができます。

  • Apache::Clean - Interface into HTML::Clean for mod_perl 2.0 : mod_perl 2.0 の HTML::Clean へのインターフェイス

    http://search.cpan.org/dist/Apache-Clean/


  • Apache::Filter::HTTPHeadersFixup - Manipulate Apache 2 HTTP Headers : Apache 2 HTTP ヘッダの操作

    http://search.cpan.org/dist/Apache-Filter-HTTPHeadersFixup/





メンテナ : Maintainers


Maintainer is the person(s) you should contact with updates, corrections and patches.
  • Stas Bekman [http://stason.org/]



作者 : Authors



Only the major authors are listed above. For contributors see the Changes file.


NEXT



次回は、「 General Handler Issues 」を「 mod_perl 」公式サイト (https://perl.apache.org/index.html) より確認します。


参考情報は書籍「 続・初めての Perl 改訂版 」, 「 Effective Perl 第 2 版 」を中心に perldoc, Wikipedia および各 Web サイト。それと詳しい先輩。

目次 - Perl Index










































同じカテゴリー(Perl)の記事
 Perl mp2 翻訳 Web コンテンツ圧縮の FAQ (d228) (2023-10-11 23:49)
 Perl mp2 翻訳 既知のブラウザのバグの回避策をいくつか (d227) (2023-05-26 15:41)
 Perl mp2 翻訳 Perl と Apache でのキュートなトリック (d226) (2023-05-19 17:05)
 Perl mp2 翻訳 テンプレートシステムの選択 (d225) (2022-08-15 22:23)
 Perl mp2 翻訳 大規模 E コマースサイトの構築 (d224) (2022-06-15 20:43)
 Perl mp2 翻訳 チュートリアル (d223) (2022-06-15 20:42)
上の画像に書かれている文字を入力して下さい
 
<ご注意>
書き込まれた内容は公開され、ブログの持ち主だけが削除できます。

Llama
リャマ
TI-DA
てぃーだブログ
プロフィール
セラ (perlackline)
セラ (perlackline)
QRコード
QRCODE
オーナーへメッセージ

PAGE TOP ▲