仕事で久々にapache moduleを開発することになりそうなのでネタ的にこっちをメモっておこうと思う。目的があると続けれる気がする
ターゲットはapache2.2
apache1.3からは仕様が大分変り、もし1.3を2.2に移植するなら新仕様で枠を作りロジックをはめ込んで行くほうが方が早い気がする
先ずは、家でも会社でもapache2.2をインストールしないことには始まらないのでdsoオプションを付けてインストールをする
インストールしたらapxsがbinの下に置かれるのでモジュールの雛形を生成する
モジュール名をmod_psychoにするなら
$ apxs -g -n psycho
で雛形が出来る
確認するとこんな感じ
$ find psychopsychopsycho/.depspsycho/Makefilepsycho/mod_psycho.cpsycho/modules.mk
mod_psycho.c以外は取り敢えずは弄らなくてもokなので、mod_psycho.cに何かロジックを埋め込んでみる。
自動生成された状態はこんな感じ
/*** mod_psycho.c -- Apache sample psycho module** [Autogenerated via ``apxs -n psycho -g'']**** To play with this sample module first compile it into a** DSO file and install it into Apache's modules directory** by running:**** $ apxs -c -i mod_psycho.c**** Then activate it in Apache's httpd.conf file for instance** for the URL /psycho in as follows:**** # httpd.conf** LoadModule psycho_module modules/mod_psycho.so**** SetHandler psycho****** Then after restarting Apache via**** $ apachectl restart**** you immediately can request the URL /psycho and watch for the** output of this module. This can be achieved for instance via:**** $ lynx -mime_header http://localhost/psycho**** The output should be similar to the following one:**** HTTP/1.1 200 OK** Date: Tue, 31 Mar 1998 14:42:22 GMT** Server: Apache/1.3.4 (Unix)** Connection: close** Content-Type: text/html**** The sample page from mod_psycho.c*/#include "httpd.h"#include "http_config.h"#include "http_protocol.h"#include "ap_config.h"/* The sample content handler */static int psycho_handler(request_rec *r){if (strcmp(r->handler, "psycho")) {return DECLINED;}r->content_type = "text/html";if (!r->header_only)ap_rputs("The sample page from mod_psycho.c\n", r);return OK;}static void psycho_register_hooks(apr_pool_t *p){ap_hook_handler(psycho_handler, NULL, NULL, APR_HOOK_MIDDLE);}/* Dispatch list for API hooks */module AP_MODULE_DECLARE_DATA psycho_module = {STANDARD20_MODULE_STUFF,NULL, /* create per-dir config structures */NULL, /* merge per-dir config structures */NULL, /* create per-server config structures */NULL, /* merge per-server config structures */NULL, /* table of config file commands */psycho_register_hooks /* register hooks */};
psycho_handler関数にロジックを埋め込む、、その前に、この関数内を眺めてみる
if (strcmp(r->handler, "psycho")) {return DECLINED;}
これは psycho ハンドラー以外のリクエストなら(httpd.confで記述するsethandler)このモジュールを抜けて次のモジュールに処理を投げる(チェイン?する)という意味。
if (!r->header_only)ap_rputs("The sample page from mod_psycho.c\n", r);
これは、headメソッドでなかったら文字列(ap_rputs内)を返す(表示する)という意味。
次はrequest_rec構造体とメモリ管理をapacheに任すと楽な件を書く