/*********************************************************************
 *
 * This is based on code created by Peter Harvey,
 * (pharvey@codebydesign.com).
 *
 * Modified and extended by Nick Gorham
 * (nick@easysoft.com).
 *
 * Any bugs or problems should be considered the fault of Nick and not
 * Peter.
 *
 * copyright (c) 1999 Nick Gorham
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 **********************************************************************
 *
 * $Id: SQLDriverConnect.c,v 1.2 1999/12/10 01:50:33 harvey Exp $
 *
 * $Log: SQLDriverConnect.c,v $
 * Revision 1.2  1999/12/10 01:50:33  harvey
 * Updated with current sources from unixODBC cvs.
 *
 * Revision 1.10  1999/11/13 23:40:59  ngorham
 *
 * Alter the way DM logging works
 * Upgrade the Postgres driver to 6.4.6
 *
 * Revision 1.9  1999/10/24 23:54:17  ngorham
 *
 * First part of the changes to the error reporting
 *
 * Revision 1.8  1999/10/14 06:49:24  ngorham
 *
 * Remove @all_includes@ from Drivers/MiniSQL/Makefile.am
 *
 * Revision 1.7  1999/09/21 22:34:24  ngorham
 *
 * Improve performance by removing unneeded logging calls when logging is
 * disabled
 *
 * Revision 1.6  1999/08/17 06:20:00  ngorham
 *
 * Remove posibility of returning without clearing the connection mutex.
 *
 * Revision 1.5  1999/08/03 21:47:39  shandyb
 * Moving to automake: changed files in DriverManager
 *
 * Revision 1.4  1999/07/10 21:10:16  ngorham
 *
 * Adjust error sqlstate from driver manager, depending on requested
 * version (ODBC2/3)
 *
 * Revision 1.3  1999/07/04 21:05:07  ngorham
 *
 * Add LGPL Headers to code
 *
 * Revision 1.2  1999/06/30 23:56:54  ngorham
 *
 * Add initial thread safety code
 *
 * Revision 1.1.1.1  1999/05/29 13:41:05  sShandyb
 * first go at it
 *
 * Revision 1.1.1.1  1999/05/27 18:23:17  pharvey
 * Imported sources
 *
 * Revision 1.4  1999/05/09 23:27:11  nick
 * All the API done now
 *
 * Revision 1.3  1999/04/30 16:22:47  nick
 * Another checkpoint
 *
 * Revision 1.2  1999/04/29 20:47:37  nick
 * Another checkpoint
 *
 * Revision 1.1  1999/04/25 23:06:11  nick
 * Initial revision
 *
 *
 **********************************************************************/

#include <string.h>
#include "drivermanager.h"

static char const rcsid[]= "$RCSfile: SQLDriverConnect.c,v $ $Revision: 1.2 $";

static void get_attr( char ** cp, char ** keyword, char ** value )
{
char * ptr;
int len;

    *keyword = *value = NULL;

    ptr = *cp;

    if ( !**cp )
        return;

    while ( **cp && **cp != '=' )
    {
        (*cp)++;
    }

    if ( !**cp )
        return;

    len = *cp - ptr;
    *keyword = malloc( len + 1 );
    memcpy( *keyword, ptr, len );
    (*keyword)[ len ] = '\0';

    (*cp)++;
    ptr = *cp;

    if ( strcmp( *keyword, "DRIVER" ) == 0 ||
            strncmp( *keyword, "SQITarget", 9 ) == 0 )
    {
        if ( **cp && **cp == '{' )
        {
            (*cp)++;
            ptr ++;
            while ( **cp && **cp != '}' )
                (*cp)++;

            len = *cp - ptr;
            *value = malloc( len + 1 );
            memcpy( *value, ptr , len );
            (*value)[ len ] = '\0';
            (*cp)++;
        }
        else
        {
            while ( **cp && **cp != ';' )
                (*cp)++;

            len = *cp - ptr;
            *value = malloc( len + 1 );
            memcpy( *value, ptr, len );
            (*value)[ len ] = '\0';
        }
    }
    else
    {
        while ( **cp && **cp != ';' )
            (*cp)++;

        len = *cp - ptr;
        *value = malloc( len + 1 );
        memcpy( *value, ptr, len );
        (*value)[ len ] = '\0';
    }

    if ( **cp )
        (*cp)++;
}

static struct con_pair * get_pair( char ** cp )
{
char *keyword, *value;
struct con_pair * con_p;

    get_attr( cp, &keyword, &value );
    if ( keyword )
    {
        con_p = malloc( sizeof( *con_p ));
        con_p -> keyword = keyword;
        con_p -> attribute = value;
        return con_p;
    }
    else
    {
        return NULL;
    }
}

static int append_pair( struct con_struct *con_str, char *kword, char *value )
{
struct con_pair *ptr;

    /* check that the keyword is not already in the list */
    if ( con_str -> count > 0 )
    {
        ptr = con_str -> list;
        while( ptr )
        {
            if( strcmp( kword, ptr -> keyword ) == 0 )
            {
                free( ptr -> attribute );
                ptr -> attribute = malloc( strlen( value ) + 1 );
                strcpy( ptr -> attribute, value );
                return 0;
            }
            ptr = ptr -> next;
        }
    }

    ptr = malloc( sizeof( *ptr ));

    ptr -> keyword = malloc( strlen( kword ) + 1 );
    strcpy( ptr -> keyword, kword );

    ptr -> attribute = malloc( strlen( value ) + 1 );
    strcpy( ptr -> attribute, value );

    con_str -> count ++;
    ptr -> next = con_str -> list;
    con_str -> list = ptr;

    return 0;
}

int __parse_connection_string( struct con_struct *con_str,
    char *str, int str_len )
{
struct con_pair *cp;
char *local_str, *ptr;
int got_dsn = 0;    /* if we have a DSN then ignore any DRIVER or FILEDSN */
int got_driver = 0;    /* if we have a DRIVER or FILEDSN then ignore any DSN */

    con_str -> count = 0;
    con_str -> list = NULL;

    if ( str_len != SQL_NTS )
    {
        local_str = malloc( str_len + 1 );
        memcpy( local_str, str, str_len );
        local_str[ str_len ] = '\0';
    }
    else
    {
        local_str = str;
    }

    if ( strlen( local_str ) == 0 ||
        ( strlen( local_str ) == 1 && *local_str == ';' ))
    {
        /* connection-string ::= empty-string [;] */
        if ( str_len != SQL_NTS )
            free( local_str );

        append_pair( con_str, "DSN", "DEFAULT" );
        return 0;
    }

    ptr = local_str;

    while(( cp = get_pair( &ptr )) != NULL )
    {
        if ( strcasecmp( cp -> keyword, "DSN" ) == 0 )
        {
            if ( got_driver )
                continue;

            got_dsn = 1;
        }
        else if ( strcasecmp( cp -> keyword, "DRIVER" ) == 0 ||
            strcmp( cp -> keyword, "FILEDSN" ) == 0 )
        {
            if ( got_dsn )
                continue;

            got_driver = 1;
        }

        append_pair( con_str, cp -> keyword, cp -> attribute );
        free( cp -> keyword );
        free( cp -> attribute );
        free( cp );
    }

    /* if no dsn or DRIVER, then set DSN=DEFAULT */
    if ( !got_driver && !got_dsn )
    {
        append_pair( con_str, "DSN", "DEFAULT" );
    }

    if ( str_len != SQL_NTS )
        free( local_str );

    return 0;
}

char * __get_attribute_value( struct con_struct * con_str, char * keyword )
{
struct con_pair *cp;

    if ( con_str -> count == 0 )
        return NULL;

    cp = con_str -> list;
    while( cp )
    {
        if( strcasecmp( keyword, cp -> keyword ) == 0 )
        {
            if ( cp -> attribute )
                return cp -> attribute;
            else
                return "";
        }
        cp = cp -> next;
    }
    return NULL;
}

void __release_conn( struct con_struct *con_str )
{
    struct con_pair *cp = con_str -> list;
    struct con_pair *save;

    while( cp )
    {
        free( cp -> attribute );
        free( cp -> keyword );
        save = cp;
        cp = cp -> next;
        free( save );
    }
}

SQLRETURN SQLDriverConnect(
    SQLHDBC            hdbc,
    SQLHWND            hwnd,
    SQLCHAR            *conn_str_in,
    SQLSMALLINT        len_conn_str_in,
    SQLCHAR            *conn_str_out,
    SQLSMALLINT        conn_str_out_max,
    SQLSMALLINT        *ptr_conn_str_out,
    SQLUSMALLINT       driver_completion )
{
    DMHDBC connection = (DMHDBC)hdbc;
    struct con_struct con_struct;
    char *driver, *dsn;
    char lib_name[ INI_MAX_PROPERTY_VALUE + 1 ];
    char driver_name[ INI_MAX_PROPERTY_VALUE + 1 ];
    SQLRETURN ret_from_connect;
    SQLCHAR s0[ 20 ], s1[ 2048 ];

    /*
     * check connection
     */

    if ( !__validate_dbc( connection ))
    {
        return SQL_INVALID_HANDLE;
    }

    function_entry( connection );

    if ( connection -> log_handle )
    {
        sprintf( connection -> msg, "\n\t\tEntry:\
            \n\t\t\tConnection = %p\
            \n\t\t\tWindow Hdl = %p\
            \n\t\t\tStr In = %s\
            \n\t\t\tStr Out = %p\
            \n\t\t\tStr Out Max = %d\
            \n\t\t\tStr Out Ptr = %p\
            \n\t\t\tCompletion = %d",
                connection,
                hwnd,
                __string_with_length( s1, conn_str_in, len_conn_str_in ), 
                conn_str_out,
                conn_str_out_max,
                ptr_conn_str_out,
                driver_completion );

        dm_log_write( connection -> log_handle, 
                __get_pid( s0 ), 
                __FILE__, 
                __LINE__, 
                LOG_INFO, 
                LOG_INFO, 
                connection -> msg );
    }

    thread_protect( SQL_HANDLE_DBC, connection );

    if ( len_conn_str_in < 0 && len_conn_str_in != SQL_NTS )
    {
        dm_log_write( connection -> log_handle, 
                __get_pid( s0 ), 
                __FILE__, 
                __LINE__, 
                LOG_INFO, 
                LOG_INFO, 
                "Error: HY090" );

        __post_internal_error( &connection -> error,
                ERROR_HY090, NULL,
                connection -> environment -> requested_version );

        thread_release( SQL_HANDLE_DBC, connection );

        return function_return( connection, SQL_ERROR );
    }

    if ( driver_completion == SQL_DRIVER_PROMPT &&
            hwnd == NULL )
    {
        dm_log_write( connection -> log_handle, 
                __get_pid( s0 ), 
                __FILE__, 
                __LINE__, 
                LOG_INFO, 
                LOG_INFO, 
                "Error: HY092" );

        __post_internal_error( &connection -> error,
                ERROR_HY092, NULL,
                connection -> environment -> requested_version );

        thread_release( SQL_HANDLE_DBC, connection );

        return function_return( connection, SQL_ERROR );
    }

    if ( driver_completion != SQL_DRIVER_PROMPT &&
            driver_completion != SQL_DRIVER_COMPLETE &&
            driver_completion != SQL_DRIVER_COMPLETE_REQUIRED &&
            driver_completion != SQL_DRIVER_NOPROMPT )
    {
        dm_log_write( connection -> log_handle, 
                __get_pid( s0 ), 
                __FILE__, 
                __LINE__, 
                LOG_INFO, 
                LOG_INFO, 
                "Error: HY110" );

        __post_internal_error( &connection -> error,
                ERROR_HY110, NULL,
                connection -> environment -> requested_version );

        thread_release( SQL_HANDLE_DBC, connection );

        return function_return( connection, SQL_ERROR );
    }

    /*
     * check the state of the connection
     */

    if ( connection -> state != STATE_C2 )
    {
        dm_log_write( connection -> log_handle, 
                __get_pid( s0 ), 
                __FILE__, 
                __LINE__, 
                LOG_INFO, 
                LOG_INFO, 
                "Error: 08002" );

        __post_internal_error( &connection -> error,
                ERROR_08002, NULL,
                connection -> environment -> requested_version );

        thread_release( SQL_HANDLE_DBC, connection );

        return function_return( connection, SQL_ERROR );
    }

    /*
     * parse the connection string
     */

    __parse_connection_string( &con_struct,
            conn_str_in, len_conn_str_in );

    /*
     * look for some keywords
     *
     * TO_DO FILEDSN's
     *
     * have we got a DRIVER= attribute
     */

    driver = __get_attribute_value( &con_struct, "DRIVER" );
    if ( driver )
    {
        /*
         * look up the driver in the ini file
         */

        strcpy( driver_name, driver );

        SQLGetPrivateProfileString( driver, "Driver", "",
                lib_name, sizeof( lib_name ), INIDRIVERS );

        if ( lib_name[ 0 ] == '\0' )
        {
            /*
             * at this point a box could pop up to allow the selection of a driver
             *
             * do this later
             */

            dm_log_write( connection -> log_handle, 
                    __get_pid( s0 ), 
                    __FILE__, 
                    __LINE__, 
                    LOG_INFO, 
                    LOG_INFO, 
                    "Error: IM002" );

            __post_internal_error( &connection -> error,
                    ERROR_IM002, NULL,
                    connection -> environment -> requested_version );
            __release_conn( &con_struct );

            thread_release( SQL_HANDLE_DBC, connection );

            return function_return( connection, SQL_ERROR );
        }

        strcpy( connection -> dsn, "" );
    }
    else
    {
        dsn = __get_attribute_value( &con_struct, "DSN" );
        if ( !dsn )
        {
            dm_log_write( connection -> log_handle, 
                    __get_pid( s0 ), 
                    __FILE__, 
                    __LINE__, 
                    LOG_INFO, 
                    LOG_INFO, 
                    "Error: IM002" );

            __post_internal_error( &connection -> error,
                    ERROR_IM002, NULL,
                    connection -> environment -> requested_version );
            __release_conn( &con_struct );

            thread_release( SQL_HANDLE_DBC, connection );

            return function_return( connection, SQL_ERROR );
        }

        if ( strlen( dsn ) > SQL_MAX_DSN_LENGTH )
        {
            dm_log_write( connection -> log_handle, 
                    __get_pid( s0 ), 
                    __FILE__, 
                    __LINE__, 
                    LOG_INFO, 
                    LOG_INFO, 
                    "Error: IM012" );

            __post_internal_error( &connection -> error,
                    ERROR_IM012, NULL,
                    connection -> environment -> requested_version );

            thread_release( SQL_HANDLE_DBC, connection );

            return function_return( connection, SQL_ERROR );
        }

        /*
         * look up the dsn in the ini file
         */

        if ( !__find_lib_name( dsn, lib_name, driver_name ))
        {
            dm_log_write( connection -> log_handle, 
                    __get_pid( s0 ), 
                    __FILE__, 
                    __LINE__, 
                    LOG_INFO, 
                    LOG_INFO, 
                    "Error: IM002" );

            __post_internal_error( &connection -> error,
                    ERROR_IM002, NULL,
                    connection -> environment -> requested_version );
            __release_conn( &con_struct );

            thread_release( SQL_HANDLE_DBC, connection );

            return function_return( connection, SQL_ERROR );
        }

        strcpy( connection -> dsn, dsn );
    }

    __release_conn( &con_struct );

    /*
     * we have now got the name of a lib to load
     */
    if ( !__connect_part_one( connection, lib_name, driver_name ))
    {
        thread_release( SQL_HANDLE_DBC, connection );
        return function_return( connection, SQL_ERROR );
    }

    if ( !CHECK_SQLDRIVERCONNECT( connection ))
    {
        dm_log_write( connection -> log_handle, 
                __get_pid( s0 ), 
                __FILE__, 
                __LINE__, 
                LOG_INFO, 
                LOG_INFO, 
                "Error: IM001" );

        __disconnect_part_one( connection );
        __post_internal_error( &connection -> error,
                ERROR_IM001, NULL,
                connection -> environment -> requested_version );

        thread_release( SQL_HANDLE_DBC, connection );

        return function_return( connection, SQL_ERROR );
    }

    ret_from_connect = SQLDRIVERCONNECT( connection,
            connection -> driver_dbc,
            hwnd,
            conn_str_in,
            len_conn_str_in,
            conn_str_out,
            conn_str_out_max,
            ptr_conn_str_out,
            driver_completion );

    if ( !SQL_SUCCEEDED( ret_from_connect ))
    {
        /*
         * it could be a SQL_NO_DATA
         */

        if ( ret_from_connect == SQL_ERROR )
        {
            SQLCHAR sqlstate[ 6 ];
            SQLINTEGER native_error, ind;
            SQLCHAR message_text[ SQL_MAX_MESSAGE_LENGTH + 1 ];
            SQLRETURN ret;

            /*
             * get the error from the driver before
             * loseing the connection
             */

            ret = SQLERROR( connection,
                    SQL_NULL_HENV,
                    connection -> driver_dbc,
                    SQL_NULL_HSTMT,
                    sqlstate,
                    &native_error,
                    message_text,
                    sizeof( message_text ),
                    &ind );

            if ( SQL_SUCCEEDED( ret ))
            {
                __post_internal_error_ex( &connection -> error,
                        sqlstate,
                        native_error,
                        message_text );
            }
        }

        sprintf( connection -> msg, 
                "\n\t\tExit:[%s]",
                    __get_return_status( ret_from_connect ));

        dm_log_write( connection -> log_handle, 
                __get_pid( s0 ), 
                __FILE__, 
                __LINE__, 
                LOG_INFO, 
                LOG_INFO, 
                connection -> msg );

        __disconnect_part_one( connection );

        thread_release( SQL_HANDLE_DBC, connection );

        return function_return( connection, ret_from_connect );
    }

    /*
     * we should be connected now
     */

    connection -> state = STATE_C4;

    /*
     * did we get the type we wanted
     */

    if ( connection -> driver_version !=
            connection -> environment -> requested_version )
    {
        connection -> driver_version =
            connection -> environment -> requested_version;

        __post_internal_error( &connection -> error,
                ERROR_01000, "Driver does not support the requested version",
                connection -> environment -> requested_version );
        ret_from_connect = SQL_SUCCESS_WITH_INFO;
    }

    if ( !__connect_part_two( connection ))
    {
        __disconnect_part_two( connection );
        __disconnect_part_one( connection );

        thread_release( SQL_HANDLE_DBC, connection );

        return function_return( connection, SQL_ERROR );
    }

    if ( connection -> log_handle )
    {
        if ( conn_str_out && strlen( conn_str_out ) > 64 )
        {
            sprintf( connection -> msg, 
                    "\n\t\tExit:[%s]\
                    \n\t\t\tConnection Out [%.64s...]",
                        __get_return_status( ret_from_connect ),
                        conn_str_out );
        }
        else
        {
            sprintf( connection -> msg, 
                    "\n\t\tExit:[%s]\
                    \n\t\t\tConnection Out [%s]",
                        __get_return_status( ret_from_connect ),
                        conn_str_out ? (char*)conn_str_out : "NULL" );
        }

        dm_log_write( connection -> log_handle, 
                __get_pid( s0 ), 
                __FILE__, 
                __LINE__, 
                LOG_INFO, 
                LOG_INFO, 
                connection -> msg );
    }

    thread_release( SQL_HANDLE_DBC, connection );

    return function_return( connection, ret_from_connect );
}
