IIS Filter Programming

Source: Internet
Author: User
Tags php server

Based on VC + + development IIS7 and IIS6 Universal filter


First, IIS6 article


1) New project: After ready to VS6, new project, select the "ISAPI Filter Wizard" project type, the next step, the project directory is out (temporarily we initialize the Filter class command is Ctestfilter).

2) Open the VS initialization project, open the CTestFilter.cpp file, and we can see that there is an auto-generated function:

BOOL ctestfilter::getfilterversion (phttp_filter_version pver)
{
Call default implementation for initialization
Ctestfilter::getfilterversion (Pver);

Clear the flags set by base class
Pver->dwflags &= ~sf_notify_order_mask;

Set The flags we are interested in
pver->dwflags |= sf_notify_order_high| sf_notify_preproc_headers | Sf_notify_send_raw_data;

Load description String
TCHAR sz[sf_max_filter_desc_len+1];
Isapiverify (:: LoadString (AfxGetResourceHandle (),
Ids_filter, SZ, Sf_max_filter_desc_len));
_tcscpy (Pver->lpszfilterdesc, SZ);
return TRUE;
}

don't focus on other code, just focus on the Red Font section, which is used to specify what HTTP content the filter needs to intercept. There are several types of my simple interception, details can be found on MSDN documentation, and I'll just briefly describe the sf_notify_preproc_headers and  sf_notify_send_ Raw_data ,sf_notify_preproc_ The headers represents a single intercept when IIS processes the header request for HTTP, and sf_notify_send_raw_data The represents the interception that is triggered before IIS writes back the response content of HTTP to the client, where you can receive a pointer to response and modify the contents of the response.

3) or using the wizard, to implement the CHttpFilter base class of the various interception methods (need to correspond with the interception events specified in the previous GetFilterVersion method, or IIS will not trigger these methods), Here I would like to introduce the corresponding OnSendRawData (chttpfiltercontext* PFC, Phttp_filter_raw_data prawdata) and onpreprocheaders with the previous step ( chttpfiltercontext* pfc,phttp_filter_preproc_headers pheaders) Two functions, one can easily see the correspondence between these two functions and the previous two interception types. OnPreprocHeaders is designed to handle HTTP headers for the client before IIS processes HTTP requests, where the pheaders is a structured data containing a pointer to the header object. We can get this pointer for preprocessing, and can modify the contents of the headers.

OnSendRawData can be said to be the most powerful of these methods, it can get the response content of IIS, and can modify the contents of response, where prawdata this structural type of the entry contains the response content pointers, Or the code to tell you how this function is going to modify everything:

dword Ctestfilter::onsendrawdata (CHttpFilterContext* PFC, Phttp_filter_raw_data prawdata)
{
// Todo:add your specialized code here and/or call the base class
cstring resp= "Hello Isa Pi!! ";
void* mem= (void*) Pfc->allocmem (resp. GetLength ());//You must use the application memory method provided by ISAPI in order to return the HTTP content properly, the memory requested by the ISAPI method, IIS will automatically help you reclaim
memcpy (Mem,resp. GetBuffer (0), resp. GetLength ());
prawdata->cbinbuffer=resp. GetLength ();
prawdata->cbindata=resp. GetLength ();
prawdata->pvindata=mem;
return sf_status_req_next_notification;
}

After this modification, all client requests become "Hello isqpi!! ", and even the normal HTTP headers have been removed.

4) Deployment: After compiling the project that was just done, We can get a TestFilter.dll file, open the IIS6 admin page, go to the Web site's properties dialog, go to the ISAPI tab, add the DLL file we just generated, and restart the IIS server, Ok,iis will only return "Hello Isapi!! The

650) this.width=650; "src=" Http://www.myexception.cn/img/2014/04/14/095600452.png "style=" margin:0px;padding:0px; Height:auto; "/>

Second, IIS7 article

With the advent of Windows server2008, IIS7 also launched, IIS7 although can also be a very tortuous way to implement the ISAPI interface function, but according to the practice of the situation to open, IIS7 in the use of ISAPI extensions to achieve the interception function, There are often annoying problems that can't be intercepted, and when we look at a lot of data, we find that IIS7 's support for ISAPI is inherently bad, because Microsoft has launched a more powerful interception implementation on the IIS7 platform, the IIS extension module, All of IIS7 's functions are implemented by loading different modules, and we specifically provide a HttpModule module for our interceptor, which is overriding all HTTP requests, Whether you use ASP or ASP or even borrow IIS server PHP server, all requests will go through this module to deal with, no wonder Microsoft will not pay attention to IIS7 to the ISAPI compatibility problem, it will push new things ~

Here's how you can intercept and modify HTTP requests through the IIS module:

1) Environment Preparation: visual Studio2008/2005+iis7+windows server2008.

2) Create a new C + + project: Create a new empty dynamic link library project in vs.

3) Create a new subclass of Chttpmodule Cmyhttpmodule (requires a reference based on the header file httpserv.h) and implement a virtual method OnBeginRequest:

#define _winsockapi_
#include <windows.h>
#include <sal.h>
#include

Class Cmyhttpmodule:public Chttpmodule
{
Public
Request_notification_status
OnBeginRequest (
In Ihttpcontext * Phttpcontext,
In Ihttpeventprovider * pprovider
)
{
Unreferenced_parameter (pprovider);

Create an HRESULT to receive the method return value.
HRESULT hr;

Gets a pointer to the response object.
Ihttpresponse * phttpresponse = Phttpcontext->getresponse ();

if (phttpresponse! = NULL)
{
Clean out the original response content directly.
Phttpresponse->clear ();
Sets the format of the response.
Phttpresponse->setheader (
Httpheadercontenttype, "Text/plain",
(USHORT) strlen ("Text/plain"), TRUE);

Pcstr pszbuffer = "Hello httpmodule!!! ";
Create a block of data.
Http_data_chunk Datachunk;
Set the block type to the HTTP type (subsequent memory cleanup will be done by the IIS container itself).
Datachunk.datachunktype = httpdatachunkfrommemory;
DWORD cbsent;

Assigns a value to a data block.
DataChunk.FromMemory.pBuffer =
(PVOID) Pszbuffer;
DataChunk.FromMemory.BufferLength =
(USHORT) strlen (Pszbuffer);
Inserts a block of data into the response content.
hr = Phttpresponse->writeentitychunks (
&datachunk,1,false,true,&cbsent);

if (FAILED (HR))
{
Phttpresponse->setstatus ("Server Error", 0,hr);
}

return rq_notification_finish_request;
}
return rq_notification_continue;
}
}

4) Create a new factory class that implements the Ihttpmodulefactory interface to register the interception module and intercept mode

Class Cmyhttpmodulefactory:public Ihttpmodulefactory
{
Public
HRESULT
Gethttpmodule (
Out Chttpmodule * * Ppmodule,
In Imoduleallocator * pallocator
)
{
Unreferenced_parameter (Pallocator);

Instantiate a pointer to a module.
Cmyhttpmodule * pmodule = new Cmyhttpmodule;

if (!pmodule)
{
Return HRESULT_FROM_WIN32 (error_not_enough_memory);
}
Else
{
*ppmodule = Pmodule;
Pmodule = NULL;
return S_OK;
}
}

void
Terminate ()
{
Clean up your own memory.
Delete this;
}
};

//the method used to register the module factory.
hresult
__stdcall
registermodule (
Ihttpmoduleregistrationinfo * PMODULEINFO,
)
{
unreferenced_parameter ( Dwserverversion);
unreferenced_parameter (Pglobalinfo);

Set the way to intercept, set here is to return response content to the client before, and our previous IIS6 example, can be set multiple, but must correspond with your httpmodule.
Return Pmoduleinfo->setrequestnotifications (
New Cmyhttpmodulefactory,
Rq_begin_request,
0
);
}

5) Compile and generate a MyHttpModule.dll dynamic link library to add the full path of the saved MyHttpModule.dll to the%windir%\system32\inetsrv\config\ ApplicationHost.config file under the Globalmodules node, restart Iis,ok, which accesses any file in your IIS, and the content returned will be: "Hello httpmodule!!! ”。


This article is from the "8403723" blog, please be sure to keep this source http://8413723.blog.51cto.com/8403723/1760404

IIS Filter Programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.