
/******************************************************************************
**
**  Copyright (C) 2001  - the shmoo group -
**
**  This program is free software; you can redistribute it and/or
**  modify it, however, you cannot sell it.
**
**  This program is distributed in the hope that it will be useful,
**  but WITHOUT ANY WARRANTY; without even the implied warranty of
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
**
**  You should have received a copy of the license attached to the
**  use of this software.  If not, visit www.shmoo.com/osiris for
**  details.
**
******************************************************************************/

/******************************************************************************
**
**    The Shmoo Group (TSG)
**
**    File:      filter_file.c
**    Author:    Brian Wotring
**
**    Date:      March 14, 2002.
**    Project:   osiris
**
******************************************************************************/

#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>

#include <sys/types.h>
#include <sys/stat.h>

#include "utilities.h"
#include "strcasestr.h"

#ifdef HAVE_REGEX_H
#include <regex.h>
#endif

#include "scan_record.h"
#include "filter.h"

#ifdef HAVE_REGEX_H

#define REGEX_FLAGS   (REG_EXTENDED|REG_ICASE)

osi_bool name_regex( const char *name, const char *pattern )
{
    regex_t preg;
    regmatch_t results;

    if( name != NULL && pattern != NULL )
    {
        if( strlen( pattern ) == 1 && pattern[0] == '*' )
        {
            return TRUE;
        }

        memset( &preg, 0, sizeof( preg ) );
        memset( &results, 0, sizeof( results ) );

        if( regcomp( &preg, pattern, REGEX_FLAGS ) == 0 )
        {
            if( regexec( &preg, name, 1, &results, 0 ) == 0 )
            {
                return TRUE;
            }
        }
    }

    return FALSE;
}

#endif

osi_bool filter_file( const char *file_path, FILTER_CONTEXT *context )
{
    char *file;

    if( ( file_path == NULL ) || ( context == NULL ) || 
        ( context->filter_argument == NULL ) )
    {
        return FALSE;
    }

    /* case insensitive systems use case insensitive search. */

#if defined(WIN32) || defined(SYSTEM_DARWIN)
    file = strcasestr( file_path, context->filter_argument );
#else
    file = strstr( file_path, context->filter_argument );
#endif

    if( file == NULL )
    {
        return FALSE;
    }

#ifdef HAVE_REGEX_H
    return name_regex( file, context->filter_argument );
#endif

    if( strlen( file ) == strlen( context->filter_argument ) )
    {
        return TRUE;
    }

    return FALSE;
}

