Unique client logging using cookies (ISAPI filter)

Here is a simple example using an ISAPI filter to log unique clients using cookies . It is written in C.

/*
 * Log unique clients by using cookies
 *
 * This ISAPI filter keeps track of unique clients by reading
 * a cookie and setting it if it doesn't exist.
 * It logs every cookie read to a file.
 *
 */

/*  Include ISAPI definitions and constants */
#include <httpfilt.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

/* This function is called when the filter is loaded by the web server */
BOOL WINAPI
GetFilterVersion( HTTP_FILTER_VERSION *pVer )
{
  /*  Set the filter version */
  pVer->dwFilterVersion = HTTP_FILTER_REVISION;
  /*  Set a description string for the filter */
  strncpy( pVer->lpszFilterDesc, "A Cookie Filter", SF_MAX_FILTER_DESC_LEN );
  /* Ask to be notified, when the headers have been processed */
  pVer->dwFlags = SF_NOTIFY_SECURE_PORT |
    SF_NOTIFY_NONSECURE_PORT |
    SF_NOTIFY_PREPROC_HEADERS;
  return TRUE;
}

/*  This function fills (*buffer) with (count) random digits */
static void
RandomBytes( char *buffer, int count )
{
  int i=0;
  for( i=0; i<count; i++ )
    buffer[i] = '0' + (rand() % 10);
  buffer[i] = '\0';
}

/*  This function is called for every HTTP request */
DWORD WINAPI
HttpFilterProc( PHTTP_FILTER_CONTEXT pfc,
		DWORD notificationType,
		VOID *pvNotification )
{
  HTTP_FILTER_PREPROC_HEADERS *headers
    = (HTTP_FILTER_PREPROC_HEADERS *) pvNotification;
  char cookie[256],   url[256];
  int  cookielen=256, urllen=256;

  /* Get header information */
  if( headers->GetHeader( pfc, "Cookie:", cookie, &cookielen ) &&
      headers->GetHeader( pfc, "url", url, &urllen ) &&
      cookielen > 1 && urllen > 1 ) {
    /* We have a cookie, log it */
    int fd = open( "/tmp/cookie.log", O_WRONLY|O_CREAT|O_APPEND, 0755 );
    if ( fd != -1 ) {
      char outbuff[514];
      sprintf( outbuff, "%s %s\n", cookie, url );
      write( fd, outbuff, strlen( outbuff ) );
      close( fd );
    }
  } else {
    /* Set a cookie header with a random cookie */
    char msg[256];
    RandomBytes( cookie, 16 );
    sprintf( msg, "Set-Cookie: %s\r\n", cookie );
    pfc->AddResponseHeaders( pfc, msg, 0 );
  }
  /* Return, instructing the server to notify the next module */
  return SF_STATUS_REQ_NEXT_NOTIFICATION;
}
Content Manager [Administrator] 16 December 2005  Permalink  
Download Free Trial

Recent Articles

Other Resources



www.zeus.com