Microsoft MVP성태의 닷넷 이야기
VC++: 48. 윈도우에서 Apache Module - Content Handler 컴파일 [링크 복사], [링크+제목 복사],
조회: 20739
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 3개 있습니다.)
윈도우에서 Apache Module - Content Handler 컴파일 (VC++)

지난번에 만들어 본 모듈은 다음과 같이 httpd.conf에 SetHandler로 설정되는 유형이었습니다.

<Location /example-info>
    SetHandler example-handler
</Location>

그런데, 여기서 궁금함이 생겼습니다. 예전에 알아본 PHP의 경우에는 다음과 같이 추가를 AddType으로 추가를 했었는데, 그럼 그 둘 간에는 어떤 차이가 있냐는 것인데요.

AddType application/x-httpd-php .php

검색해 보니, PHP와 같은 경우를 별도로 "Content Handler"라고 부르는 것 같습니다. 궁금하니 어쩔 수 없습니다, 한번 만들어 봐야지. ^^ 이를 위해 검색해 보니 다음의 글이 눈에 띕니다.

2. Apache Content Handler
; http://woorie.net/entry/2-Apache-Content-Handler

위의 글에 Content Handler에 대한 소스 코드가 실려 있는데, 기존 모듈의 소스 코드와 차이점이 없어 보입니다. 안 좋은 소식이라면, 이 예제는 아파치 2.0 미만의 버전과 호환이 되는 것 같았습니다. 어쨌든 중요한 것은 뭔가 크게 다르지 않다는 것! ^^

#include "httpd.h" 
#include "http_config.h" 
#include "http_protocol.h" 
#include "ap_config.h" 

/* The sample content handler */ 
static int turbo08_handler(request_rec *r) 
{ 
    r->content_type = "text/html"; 
    ap_send_http_header(r); 

    if (!r->header_only) 
        ap_rputs("The sample page from mod_turbo08.c\n", r); 

    return OK; 
} 

/* Dispatch list of content handlers */ 
static const handler_rec turbo08_handlers[] = 
    { 
        { "turbo08", turbo08_handler }, 
        { NULL, NULL } 
    }; 

/* Dispatch list for API hooks */ 
module MODULE_VAR_EXPORT turbo08_module = 
    { 
        STANDARD_MODULE_STUFF, 
        NULL, /* module initializer */ 
        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 */ 
        turbo08_handlers, /* [#8] MIME-typed-dispatched handlers */ 
        NULL, /* [#1] URI to filename translation */ 
        NULL, /* [#4] validate user id from request */ 
        NULL, /* [#5] check if the user is ok _here_ */ 
        NULL, /* [#3] check access by host address */ 
        NULL, /* [#6] determine MIME type */ 
        NULL, /* [#7] pre-run fixups */ 
        NULL, /* [#9] log a transaction */ 
        NULL, /* [#2] header parser */ 
        NULL, /* child_init */ 
        NULL, /* child_exit */ 
        NULL /* [#0] post read-request */ 
    };

이해도를 높이기 위해 직접 제작을 해볼텐데요. ^^ 예전 글에서는 아파치에서 기본 제공되는 experimental 예제를 복사해서 했지만, 이번에는 Visual Studio 2008을 이용해서 바닥부터 프로젝트를 만들어 컴파일해 보겠습니다.

우선, Win32 Project를 생성하고 (제 경우에는 프로젝트 이름을 MyContentHandler로 명명) DLL 응용 프로그램 유형으로 시작했습니다.

how_to_build_apache_content_handler_1.png

물론, 프로젝트 속성을 몇 가지 바꿔주어야 합니다.

"General" / "Character Set"
==> Not Set

"Debugging" / "Command"
==> D:\httpd_build\Apache22\bin\httpd.exe

"C/C++" / "Additional Include Directories" - 아파치 헤더 파일 경로 설정
==> ../../include,../../srclib/apr/include,../../srclib/apr-util/include

"Linker" / "Output File" - 디버그하기 편리하도록 아파치 모듈 폴더에 곧바로 출력
==> ..\..\..\Apache22\modules\mycontenthandler_module.so

그다음, 기본 생성된 파일을 변경합니다.

  • stdafx.h 파일의 "#include windows.h" 라인을 주석 처리
  • dllmain.cpp 파일 제거

생성되어 있던 MyContentHandler.h 파일에 다음과 같이 헤더 파일 및 export 심벌 선언을 추가해 주고,

#include "httpd.h"
#include "http_config.h"
#include "http_core.h"
#include "http_log.h"
#include "http_main.h"
#include "http_protocol.h"
#include "http_request.h"
#include "util_script.h"
#include "http_connection.h"

#include "apr_strings.h"

#include 

#pragma comment(lib, "../lib/libhttpd.lib")
#pragma comment(lib, "../lib/libapr-1.lib")
#pragma comment(lib, "../lib/libaprutil-1.lib")

extern "C"
{
    extern module AP_MODULE_DECLARE_DATA mycontenthandler_module;
}

MyContentHandler.cpp 파일에는 다음과 같이 코드를 추가해줍니다.

#include "stdafx.h"
#include "MyContentHandler.h"

static void x_register_hooks(apr_pool_t *p)
{
}

module AP_MODULE_DECLARE_DATA mycontenthandler_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 */ 
    x_register_hooks, /* dispatched handlers */ 
};

여기까지 일단 빌드를 하고, depends.exe로 결과를 확인해 봅니다. 반드시 아래와 같이 mycontenthandler_module이 export 되어 있어야 합니다.

how_to_build_apache_content_handler_2.png




돌아가는 분위기를 보아하니, Content Handler라고 해서 특별한 점은 없어 보입니다. 즉, 지난번에 알아본 핸들러와도 소스 코드 구조 면에서 완전히 일치합니다. 단지, httpd.conf 파일에 어떻게 등록하느냐에 따라서 그것이 Content Handler라고 불리는 것 같습니다. 어디... 확인을 해봐야겠지요. ^^ 이를 위해 간단한 x_handler 함수를 만들어 두고 x_register_hooks에서 등록시켜 줍니다.

static int x_handler(request_rec *r)
{
    return OK;
}

static void x_register_hooks(apr_pool_t *p)
{
    ap_hook_handler(x_handler, NULL, NULL, APR_HOOK_MIDDLE);
}

남은 작업은 [아파치 설치 폴더]/conf/httpd.conf 파일에 다음과 같이 Content Handler를 등록해 주는 것입니다.

LoadModule mycontenthandler_module modules/mycontenthandler_module.so

AddType mycontenthandler_module myext

위와 같이 해주고, (Shift + F2 디버깅 상태에서) 웹 브라우저로 "http://localhost:65000/test.txt"라고 방문했더니 제가 예상했던 것과는 다르게, 원하는 확장자(myext)가 아님(txt)에도 불구하고 mycontenthandler_module.so 모듈에 정의된 x_handler가 호출되는 것이 확인되었습니다.

비효율적이라고 생각되었지만, 어쨌든 이제 다시 한번 궁금한 점이 생깁니다. 도대체 그럼, x_handler에서는 test.txt로 요청이 들어왔는지, test.myext로 요청이 들어왔는지 어떻게 구분하고 반응을 해야 하는 걸까요?

아파치는 AddType 정의가 추가된 경우, 그곳에 등록된 확장자(위의 예에서는 myext)로 요청이 들어오면 AddType의 첫 번째 인자(위의 예에서는 mycontenthandler)로 주어진 문자열을 x_handler 메서드의 첫 번째 파라미터인 request_rec의 handler 멤버에 설정을 해줍니다.

아래는, 제가 "Shift + F2" 디버깅상에서 확인한 결과입니다.

[그림 1: test.txt로 방문한 경우, r->handler == "text/plain"]
how_to_build_apache_content_handler_3.png

[그림 2: test.myext로 방문한 경우, r->handler == "mycontenthandler_module"]
how_to_build_apache_content_handler_4.png

따라서, 자신이 담당해야 할 확장자로 들어온 요청은 AddType에 지정된 첫 번째 문자열 값이 r->handler에 들어왔을 때를 기준으로 구분을 하면 되므로, 다음과 같이 코드를 작성해 줄 수 있습니다.

static int x_handler(request_rec *r)
{
    if (strcmp(r->handler, "mycontenthandler_module"))
    {
        return DECLINED;
    }

    ap_set_content_type(r, "text/html");

    if (r->header_only) 
    {
        return OK;
    }

    ap_rputs("test is good!", r); 

    return OK;
}

이쯤에서 다시 PHP 모듈 등록 방식으로 돌아가 볼까요?

AddType application/x-httpd-php .php

아하~~~ 이제야 눈에 들어오는 군요. 아파치는 .php 확장자로 요청이 들어온 경우에는 "LoadModule"로 등록된 모든 모듈의 x_handler를 호출하면서 r->handler에 "application/x-httpd-php" 문자열을 전달해 줄 것이고, 그중에서 php5apache2_2.dll 안에 정의된 x_handler 동격의 함수에서 다음과 같은 처리 코드를 가지고 시작할 거라고 예상해 볼 수 있습니다.

static int x_handler(request_rec *r)
{
    if (strcmp(r->handler, "application/x-httpd-php"))
    {
        return DECLINED;
    }

... [생략] ...
    return OK;
}




마지막으로 정리해 보면, 결국 일반 모듈이나 Content Handler라고 불리는 모듈이나 제작 방식은 동일하고, 단순히 httpd.conf 파일에 SetHandler로 등록하느냐, AddType으로 등록하느냐에 대한 차이만 있는 것입니다. (아마도, 다른 AddEncoding/AddHandler 등의 모듈도 제작 방식은 동일할 것 같습니다.)

저 같은 아파치 초보자는 여기까지 개념을 잡는 것도 오래 걸리는 군요. ^^

(첨부한 파일은 위의 예제 코드를 담고 있는 VC++ 프로젝트입니다.)



[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/28/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13557정성태2/18/20242080Windows: 258. Task Scheduler의 Author 속성 값을 변경하는 방법
13556정성태2/17/20242149Windows: 257. Windows - Symbolic (hard/soft) Link 및 Junction 차이점
13555정성태2/15/20242414닷넷: 2216. C# - SemaphoreSlim 사용 시 주의점
13554정성태2/15/20242117VS.NET IDE: 189. Visual Studio - 닷넷 소스코드 디컴파일 찾기가 안 될 때
13553정성태2/14/20242154닷넷: 2215. windbg - thin/fat lock 없이 동작하는 Monitor.Wait + Pulse
13552정성태2/13/20242062닷넷: 2214. windbg - Monitor.Enter의 thin lock과 fat lock
13551정성태2/12/20242383닷넷: 2213. ASP.NET/Core 웹 응용 프로그램 - 2차 스레드의 예외로 인한 비정상 종료
13550정성태2/11/20242588Windows: 256. C# - Server socket이 닫히면 Accept 시켰던 자식 소켓이 닫힐까요?
13549정성태2/3/20242985개발 환경 구성: 706. C# - 컨테이너에서 실행하기 위한 (소켓) 콘솔 프로젝트 구성
13548정성태2/1/20242741개발 환경 구성: 705. "Docker Desktop for Windows" - ASP.NET Core 응용 프로그램의 소켓 주소 바인딩(IPv4/IPv6 loopback, Any)
13547정성태1/31/20242475개발 환경 구성: 704. Visual Studio - .NET 8 프로젝트부터 dockerfile에 추가된 "USER app" 설정
13546정성태1/30/20242304Windows: 255. (디버거의 영향 등으로) 대상 프로세스가 멈추면 Socket KeepAlive로 연결이 끊길까요?
13545정성태1/30/20242202닷넷: 2212. ASP.NET Core - 우선순위에 따른 HTTP/HTTPS 호스트:포트 바인딩 방법
13544정성태1/30/20242222오류 유형: 894. Microsoft.Data.SqlClient - Could not load file or assembly 'System.Security.Permissions, ...'
13543정성태1/30/20242273Windows: 254. Windows - 기본 사용 중인 5357 포트 비활성화는 방법
13542정성태1/30/20242278오류 유형: 893. Visual Studio - Web Application을 실행하지 못하는 IISExpress - 두 번째 이야기
13541정성태1/29/20242400VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20242516Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
13539정성태1/26/20242489개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20242721닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/20242774닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/20242782닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/20242728닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/20242482닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/20242644닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/20242606닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...