Commit message: New Pre Source
CVE: CVE-2018-7485
CWE: CWE-119
Vulnerability description: The SQLWriteFileDSN function in odbcinst/SQLWriteFileDSN.c in unixODBC 2.3.5 has strncpy arguments in the wrong order, which allows attackers to cause a denial of service or possibly have unspecified other impact.

Project: unixODBC
File: SQLCreateDataSource.c

void _single_copy_from_wide( SQLCHAR *out, LPCWSTR in, int len )
{
    while ( len >= 0 )
    {
        *out = *in;
        out++;
        in++;
        len --;
    }
}

Project: unixODBC
File: SQLCreateDataSource.c

BOOL INSTAPI SQLCreateDataSourceW( HWND hwndParent, LPCWSTR lpszDSN )
{
    BOOL ret;
    char *ms = _multi_string_alloc_and_copy( lpszDSN );

    inst_logClear();

    ret = SQLCreateDataSource( hwndParent, ms );

    free( ms );

    return ret;
}

Project: unixODBC
File: iusql.c

static void WriteHeaderDelimited( SQLHSTMT hStmt, char cDelimiter )
{
    SQLINTEGER      nCol                            = 0;
    SQLSMALLINT     nColumns                        = 0;
    SQLTCHAR            szColumnName[MAX_DATA_WIDTH+1]; 

    szColumnName[ 0 ]   = 0;    

    if ( SQLNumResultCols( hStmt, &nColumns ) != SQL_SUCCESS )
        nColumns = -1;

    for ( nCol = 1; nCol <= nColumns; nCol++ )
    {
        SQLColAttribute( hStmt, nCol, SQL_DESC_LABEL, szColumnName, sizeof(szColumnName), NULL, NULL );
        fputs((char*) uc_to_ascii( szColumnName ), stdout );
        if ( nCol < nColumns )
            putchar( cDelimiter );
    }
    putchar( '\n' );
}

Project: unixODBC
File: SQLCreateDataSource.c

char* _multi_string_alloc_and_copy( LPCWSTR in )
{
    char *chr;
    int len = 0;

    if ( !in )
    {
        return NULL;
    }

    while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
    {
        len ++;
    }

    chr = malloc( len + 2 );

    len = 0;
    while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
    {
        chr[ len ] = 0xFF & in[ len ];
        len ++;
    }
    chr[ len ++ ] = '\0';
    chr[ len ++ ] = '\0';

    return chr;
}

Project: unixODBC
File: iusql.c

static int OpenDatabase( SQLHENV *phEnv, SQLHDBC *phDbc, char *szDSN, char *szUID, char *szPWD )
{
    SQLCHAR dsn[ 1024 ], uid[ 1024 ], pwd[ 1024 ];
    SQLTCHAR cstr[ 1024 ];
    char zcstr[ 1024 ], tmp[ 1024 ];
    int i;
    size_t zclen;

    if ( SQLAllocEnv( phEnv ) != SQL_SUCCESS )
    {
        fprintf( stderr, "[ISQL]ERROR: Could not SQLAllocEnv\n" );
        return 0;
    }

    if ( SQLAllocConnect( *phEnv, phDbc ) != SQL_SUCCESS )
    {
        if ( bVerbose ) DumpODBCLog( hEnv, 0, 0 );
        fprintf( stderr, "[ISQL]ERROR: Could not SQLAllocConnect\n" );
        SQLFreeEnv( *phEnv );
        return 0;
    }

    if ( szDSN )
    {
        size_t DSNlen=strlen( szDSN );
        for ( i = 0; i < DSNlen; i ++ )
        {
            dsn[ i ] = szDSN[ i ];
        }
        dsn[ i ] = '\0';
    }
    else
    {
        dsn[ 0 ] = '\0';
    }

    if ( szUID )
    {
        size_t UIDlen=strlen( szUID );
        for ( i = 0; i < UIDlen; i ++ )
        {
            uid[ i ] = szUID[ i ];
        }
        uid[ i ] = '\0';
    }
    else
    {
        uid[ 0 ] = '\0';
    }

    if ( szPWD )
    {
        size_t PWDlen=strlen( szPWD );
        for ( i = 0; i < PWDlen; i ++ )
        {
            pwd[ i ] = szPWD[ i ];
        }
        pwd[ i ] = '\0';
    }
    else
    {
        pwd[ 0 ] = '\0';
    }

    sprintf( zcstr, "DSN=%s", dsn );
    if ( szUID )
    {
        sprintf( tmp, ";UID=%s", uid );
        strcat( zcstr, tmp );
    }
    if ( szPWD )
    {
        sprintf( tmp, ";PWD=%s", pwd );
        strcat( zcstr, tmp );
    }

    zclen=strlen( zcstr );
    for ( i = 0; i < zclen; i ++ )
    {
        cstr[ i ] = zcstr[ i ];
    }
    cstr[ i ] = 0;

    if ( !SQL_SUCCEEDED( SQLDriverConnect( *phDbc, NULL, cstr, SQL_NTS, NULL, 0, NULL, SQL_DRIVER_NOPROMPT  )))
    {
        if ( bVerbose ) DumpODBCLog( hEnv, hDbc, 0 );
        fprintf( stderr, "[ISQL]ERROR: Could not SQLDriverConnect\n" );
        SQLFreeConnect( *phDbc );
        SQLFreeEnv( *phEnv );
        return 0;
    }
    if ( bVerbose ) DumpODBCLog( hEnv, hDbc, 0 );

    return 1;
}

Project: unixODBC
File: SQLCreateDataSource.c

BOOL SQLCreateDataSource( HWND hWnd, LPCSTR pszDS )
{
    HODBCINSTWND  hODBCInstWnd = (HODBCINSTWND)hWnd;
    char          szName[FILENAME_MAX];
    char          szNameAndExtension[FILENAME_MAX];
    char          szPathAndName[FILENAME_MAX];
    void *        hDLL;
    BOOL          (*pSQLCreateDataSource)(HWND, LPCSTR);

    inst_logClear();

    /* ODBC specification states that hWnd is mandatory. */
    if ( !hWnd )
    {
        inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_INVALID_HWND, "" );
        return FALSE;
    }

    /* initialize libtool */
    if ( lt_dlinit() )
    {
        inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_GENERAL_ERR, "lt_dlinit() failed" );
        return FALSE;
    }

    /* get plugin name */
    _appendUIPluginExtension( szNameAndExtension, _getUIPluginName( szName, hODBCInstWnd->szUI ) );

    /* lets try loading the plugin using an implicit path */
    hDLL = lt_dlopen( szNameAndExtension );
    if ( hDLL )
    {
        /* change the name, as it avoids it finding it in the calling lib */
        pSQLCreateDataSource = (BOOL (*)(HWND, LPCSTR))lt_dlsym( hDLL, "ODBCCreateDataSource" );
        if ( pSQLCreateDataSource )
            return pSQLCreateDataSource( ( *(hODBCInstWnd->szUI) ? hODBCInstWnd->hWnd : NULL ), pszDS );
        else
            inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_GENERAL_ERR, (char*)lt_dlerror() );
    }
    else
    {
        /* try with explicit path */
        _prependUIPluginPath( szPathAndName, szNameAndExtension );
        hDLL = lt_dlopen( szPathAndName );
        if ( hDLL )
        {
            /* change the name, as it avoids linker finding it in the calling lib */
            pSQLCreateDataSource = (BOOL (*)(HWND,LPCSTR))lt_dlsym( hDLL, "ODBCCreateDataSource" );
            if ( pSQLCreateDataSource )
                return pSQLCreateDataSource( ( *(hODBCInstWnd->szUI) ? hODBCInstWnd->hWnd : NULL ), pszDS );
            else
                inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_GENERAL_ERR, (char*)lt_dlerror() );
        }
    }

    /* report failure to caller */
    inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_GENERAL_ERR, "" );

    return FALSE;
}

Project: unixODBC
File: iusql.c

static void WriteBodyHTMLTable( SQLHSTMT hStmt )
{
    SQLINTEGER      nCol                            = 0;
    SQLSMALLINT     nColumns                        = 0;
    SQLLEN          nIndicator                      = 0;
    SQLTCHAR        szColumnValue[MAX_DATA_WIDTH+1];
    SQLRETURN       nReturn                         = 0;
    SQLRETURN       ret;

    szColumnValue[ 0 ]  = 0;

    if ( SQLNumResultCols( hStmt, &nColumns ) != SQL_SUCCESS )
        nColumns = -1;

    while ( (ret = SQLFetch( hStmt )) == SQL_SUCCESS ) /* ROWS */
    {
        printf( "<tr>\n" );

        for ( nCol = 1; nCol <= nColumns; nCol++ ) /* COLS */
        {
            printf( "<td>\n" );
            printf( "<font face=Arial,Helvetica>\n" );

            nReturn = SQLGetData( hStmt, nCol, SQL_C_WCHAR, (SQLPOINTER)szColumnValue, sizeof(szColumnValue), &nIndicator );
            if ( nReturn == SQL_SUCCESS && nIndicator != SQL_NULL_DATA )
            {
                uc_to_ascii( szColumnValue );
                fputs((char*) szColumnValue, stdout );
            }
            else if ( nReturn == SQL_ERROR )
            {
                ret = SQL_ERROR;
                break;
            }
            else
                printf( "%s\n", "" );

            printf( "</font>\n" );
            printf( "</td>\n" );
        }
        if (ret != SQL_SUCCESS)
            break;
        printf( "</tr>\n" );
    }
}

Project: unixODBC
File: SQLSetDescFieldW.c

SQLRETURN SQLSetDescFieldW( SQLHDESC descriptor_handle,
           SQLSMALLINT rec_number, 
           SQLSMALLINT field_identifier,
           SQLPOINTER value, 
           SQLINTEGER buffer_length )
{
    /*
     * not quite sure how the descriptor can be
     * allocated to a statement, all the documentation talks
     * about state transitions on statement states, but the
     * descriptor may be allocated with more than one statement
     * at one time. Which one should I check ?
     */
    DMHDESC descriptor = (DMHDESC) descriptor_handle;
    SQLRETURN ret;
    SQLCHAR s1[ 100 + LOG_MESSAGE_LEN ];
    int isStrField = 0;

    /*
     * check descriptor
     */

    if ( !__validate_desc( descriptor ))
    {
        dm_log_write( __FILE__, 
                    __LINE__, 
                    LOG_INFO, 
                    LOG_INFO, 
                    "Error: SQL_INVALID_HANDLE" );

#ifdef WITH_HANDLE_REDIRECT
		{
			DMHDESC parent_desc;

			parent_desc = find_parent_handle( descriptor, SQL_HANDLE_DESC );

			if ( parent_desc ) {
        		dm_log_write( __FILE__, 
                	__LINE__, 
                    	LOG_INFO, 
                    	LOG_INFO, 
                    	"Info: found parent handle" );

				if ( CHECK_SQLSETDESCFIELDW( parent_desc -> connection ))
				{
        			dm_log_write( __FILE__, 
                		__LINE__, 
                   		 	LOG_INFO, 
                   		 	LOG_INFO, 
                   		 	"Info: calling redirected driver function" );

                	return  SQLSETDESCFIELDW( parent_desc -> connection,
							descriptor,
							rec_number,
							field_identifier,
							value,
							buffer_length );
				}
			}
		}
#endif
        return SQL_INVALID_HANDLE;
    }

    function_entry( descriptor );

    if ( log_info.log_flag )
    {
        sprintf( descriptor -> msg, "\n\t\tEntry:\
\n\t\t\tDescriptor = %p\
\n\t\t\tRec Number = %d\
\n\t\t\tField Ident = %s\
\n\t\t\tValue = %p\
\n\t\t\tBuffer Length = %d",
                descriptor,
                rec_number,
                __desc_attr_as_string( s1, field_identifier ),
                value, 
                (int)buffer_length );

        dm_log_write( __FILE__, 
                __LINE__, 
                LOG_INFO, 
                LOG_INFO, 
                descriptor -> msg );
    }

    thread_protect( SQL_HANDLE_DESC, descriptor );

    if ( descriptor -> connection -> state < STATE_C4 )
    {
        dm_log_write( __FILE__, 
                __LINE__, 
                LOG_INFO, 
                LOG_INFO, 
                "Error: HY010" );

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

        return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR );
    }

    /*
     * check status of statements associated with this descriptor
     */

    if( __check_stmt_from_desc( descriptor, STATE_S8 ) ||
        __check_stmt_from_desc( descriptor, STATE_S9 ) ||
        __check_stmt_from_desc( descriptor, STATE_S10 ) ||
        __check_stmt_from_desc( descriptor, STATE_S11 ) ||
        __check_stmt_from_desc( descriptor, STATE_S12 ) ||
        __check_stmt_from_desc( descriptor, STATE_S13 ) ||
        __check_stmt_from_desc( descriptor, STATE_S14 ) ||
        __check_stmt_from_desc( descriptor, STATE_S15 )) {

        dm_log_write( __FILE__, 
                __LINE__, 
                LOG_INFO, 
                LOG_INFO, 
                "Error: HY010" );

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

        return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR );
    }

    if ( rec_number < 0 )
    {
        __post_internal_error( &descriptor -> error,
                ERROR_07009, NULL,
                descriptor -> connection -> environment -> requested_version );

        return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR );
    }

    switch ( field_identifier )
    {
    /* Fixed-length fields: buffer_length is ignored */
    case SQL_DESC_ALLOC_TYPE:
    case SQL_DESC_ARRAY_SIZE:
    case SQL_DESC_ARRAY_STATUS_PTR:
    case SQL_DESC_BIND_OFFSET_PTR:
    case SQL_DESC_BIND_TYPE:
    case SQL_DESC_COUNT:
    case SQL_DESC_ROWS_PROCESSED_PTR:
    case SQL_DESC_AUTO_UNIQUE_VALUE:
    case SQL_DESC_CASE_SENSITIVE:
    case SQL_DESC_CONCISE_TYPE:
    case SQL_DESC_DATA_PTR:
    case SQL_DESC_DATETIME_INTERVAL_CODE:
    case SQL_DESC_DATETIME_INTERVAL_PRECISION:
    case SQL_DESC_DISPLAY_SIZE:
    case SQL_DESC_FIXED_PREC_SCALE:
    case SQL_DESC_INDICATOR_PTR:
    case SQL_DESC_LENGTH:
    case SQL_DESC_NULLABLE:
    case SQL_DESC_NUM_PREC_RADIX:
    case SQL_DESC_OCTET_LENGTH:
    case SQL_DESC_OCTET_LENGTH_PTR:
    case SQL_DESC_PARAMETER_TYPE:
    case SQL_DESC_PRECISION:
    case SQL_DESC_ROWVER:
    case SQL_DESC_SCALE:
    case SQL_DESC_SEARCHABLE:
    case SQL_DESC_TYPE:
    case SQL_DESC_UNNAMED:
    case SQL_DESC_UNSIGNED:
    case SQL_DESC_UPDATABLE:
        isStrField = 0;
        break;
    /* Pointer to data: buffer_length must be valid */
    case SQL_DESC_BASE_COLUMN_NAME:
    case SQL_DESC_BASE_TABLE_NAME:
    case SQL_DESC_CATALOG_NAME:
    case SQL_DESC_LABEL:
    case SQL_DESC_LITERAL_PREFIX:
    case SQL_DESC_LITERAL_SUFFIX:
    case SQL_DESC_LOCAL_TYPE_NAME:
    case SQL_DESC_NAME:
    case SQL_DESC_SCHEMA_NAME:
    case SQL_DESC_TABLE_NAME:
    case SQL_DESC_TYPE_NAME:
        isStrField = 1;
        break;
    default:
        isStrField = buffer_length != SQL_IS_POINTER && buffer_length != SQL_IS_INTEGER
            && buffer_length != SQL_IS_UINTEGER && buffer_length != SQL_IS_SMALLINT &&
            buffer_length != SQL_IS_USMALLINT;
    }
    
    if ( isStrField && buffer_length < 0 && buffer_length != SQL_NTS)
    {
        __post_internal_error( &descriptor -> error,
            ERROR_HY090, NULL,
            descriptor -> connection -> environment -> requested_version );

        return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR );
    }

    if ( field_identifier == SQL_DESC_COUNT && (intptr_t)value < 0 )
    {
        __post_internal_error( &descriptor -> error,
                ERROR_07009, NULL,
                descriptor -> connection -> environment -> requested_version );

        return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR );
    }

    if ( field_identifier == SQL_DESC_PARAMETER_TYPE && (intptr_t)value != SQL_PARAM_INPUT
        && (intptr_t)value != SQL_PARAM_OUTPUT && (intptr_t)value != SQL_PARAM_INPUT_OUTPUT &&
        (intptr_t)value != SQL_PARAM_INPUT_OUTPUT_STREAM && (intptr_t)value != SQL_PARAM_OUTPUT_STREAM )
    {
        __post_internal_error( &descriptor -> error,
                ERROR_HY105, NULL,
                descriptor -> connection -> environment -> requested_version );

        return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR );
    }

    if ( descriptor -> connection -> unicode_driver ||
		    CHECK_SQLSETDESCFIELDW( descriptor -> connection ))
	{
    	if ( !CHECK_SQLSETDESCFIELDW( descriptor -> connection ))
    	{
        	dm_log_write( __FILE__, 
                __LINE__, 
                LOG_INFO, 
                LOG_INFO, 
                "Error: IM001" );

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

        	return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR );
		}

    	ret = SQLSETDESCFIELDW( descriptor -> connection,
            	descriptor -> driver_desc,
            	rec_number, 
            	field_identifier,
            	value, 
            	buffer_length );
	
    	if ( log_info.log_flag )
    	{
        	sprintf( descriptor -> msg, 
                	"\n\t\tExit:[%s]",
                    	__get_return_status( ret, s1 ));
	
        	dm_log_write( __FILE__, 
                	__LINE__, 
                	LOG_INFO, 
                	LOG_INFO, 
                	descriptor -> msg );
    	}
	}
	else
	{
		SQLCHAR *ascii_str = NULL;

    	if ( !CHECK_SQLSETDESCFIELD( descriptor -> connection ))
    	{
        	dm_log_write( __FILE__, 
                __LINE__, 
                LOG_INFO, 
                LOG_INFO, 
                "Error: IM001" );

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

        	return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR );
		}

		/*
		 * is it a char arg...
		 */

		switch ( field_identifier )
		{
			case SQL_DESC_NAME:		/* This is the only R/W SQLCHAR* type */
        		ascii_str = (SQLCHAR*) unicode_to_ansi_alloc( value, buffer_length, descriptor -> connection, NULL );
				value = ascii_str;
				buffer_length = strlen((char*) ascii_str );
				break;

			default:
				break;
		}

    	ret = SQLSETDESCFIELD( descriptor -> connection,
            	descriptor -> driver_desc,
            	rec_number, 
            	field_identifier,
            	value, 
            	buffer_length );
	
    	if ( log_info.log_flag )
    	{
        	sprintf( descriptor -> msg, 
                	"\n\t\tExit:[%s]",
                    	__get_return_status( ret, s1 ));
	
        	dm_log_write( __FILE__, 
                	__LINE__, 
                	LOG_INFO, 
                	LOG_INFO, 
                	descriptor -> msg );
    	}

		if ( ascii_str ) 
		{
			free( ascii_str );
		}
	}

    return function_return( SQL_HANDLE_DESC, descriptor, ret );
}

Project: unixODBC
File: SQLWriteFileDSN.c

BOOL SQLWriteFileDSN(			LPCSTR	pszFileName,
								LPCSTR	pszAppName,
								LPCSTR	pszKeyName,
								LPCSTR	pszString )
{
	HINI	hIni;
	char	szFileName[ODBC_FILENAME_MAX+1];

	if ( pszFileName[0] == '/' )
	{
		strncpy( szFileName, pszFileName, sizeof(szFileName) - 5 );
	}
	else
	{	
		char szPath[ODBC_FILENAME_MAX+1];
		*szPath = '\0';
		_odbcinst_FileINI( szPath );
		snprintf( szFileName, sizeof(szFileName) - 5, "%s/%s", szPath, pszFileName );
	}

    if ( strlen( szFileName ) < 4 || strcmp( szFileName + strlen( szFileName ) - 4, ".dsn" ))
    {
        strcat( szFileName, ".dsn" );
    }

#ifdef __OS2__
	if ( iniOpen( &hIni, szFileName, "#;", '[', ']', '=', TRUE, 0L ) != INI_SUCCESS )
#else
	if ( iniOpen( &hIni, szFileName, "#;", '[', ']', '=', TRUE ) != INI_SUCCESS )
#endif
	{
       	inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_INVALID_PATH, "" );
		return FALSE;
	}

	/* delete section */
	if ( pszString == NULL && pszKeyName == NULL )
	{
		if ( iniObjectSeek( hIni, (char *)pszAppName ) == INI_SUCCESS )
        {
			iniObjectDelete( hIni );
        }
	}
	/* delete entry */
	else if	( pszString == NULL )
	{
		if ( iniPropertySeek( hIni, (char *)pszAppName, (char *)pszKeyName, "" ) == INI_SUCCESS )
        {
			iniPropertyDelete( hIni );
        }
	}
	else
	{
		/* add section */
		if ( iniObjectSeek( hIni, (char *)pszAppName ) != INI_SUCCESS )
        {
			iniObjectInsert( hIni, (char *)pszAppName );
        }
		/* update entry */
		if ( iniPropertySeek( hIni, (char *)pszAppName, (char *)pszKeyName, "" ) == INI_SUCCESS )
		{
			iniObjectSeek( hIni, (char *)pszAppName );
			iniPropertyUpdate( hIni, (char *)pszKeyName, (char *)pszString );
		}
		/* add entry */
		else
		{
			iniObjectSeek( hIni, (char *)pszAppName );
			iniPropertyInsert( hIni, (char *)pszKeyName, (char *)pszString );
		}
	}

	if ( iniCommit( hIni ) != INI_SUCCESS )
	{
		iniClose( hIni );
        inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_REQUEST_FAILED, "" );
		return FALSE;
	}

	iniClose( hIni );

	return TRUE;
}

Project: unixODBC
File: SQLCreateDataSource.c

void _multi_string_copy_to_wide( SQLWCHAR *out, LPCSTR in, int len )
{
    while ( len > 0 && ( in[ 0 ] || in[ 1 ] ))
    {
        *out = *in;
        out++;
        in++;
        len --;
    }
    *out++ = 0;
    *out++ = 0;
}

Project: unixODBC
File: iusql.c

static int ExecuteHelp( SQLHDBC hDbc, char *szSQL, char cDelimiter, int bColumnNames, int bHTMLTable )
{
    char            szTable[250]                        = "";
    SQLHSTMT        hStmt;
    SQLTCHAR        szSepLine[32001];   
    SQLLEN          nRows               = 0;

    szSepLine[ 0 ] = 0;

    /****************************
     * EXECUTE SQL
     ***************************/
    if ( SQLAllocStmt( hDbc, &hStmt ) != SQL_SUCCESS )
    {
        if ( bVerbose ) DumpODBCLog( hEnv, hDbc, 0 );
        fprintf( stderr, "[ISQL]ERROR: Could not SQLAllocStmt\n" );
        return 0;
    }

    if ( iniElement( szSQL, ' ', '\0', 1, szTable, sizeof(szTable) ) == INI_SUCCESS )
    {
        SQLWCHAR tname[ 1024 ];

        ansi_to_unicode( szTable, tname );
        /* COLUMNS */
        if ( SQLColumns( hStmt, NULL, 0, NULL, 0, tname, SQL_NTS, NULL, 0 ) != SQL_SUCCESS )
        {
            if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt );
            fprintf( stderr, "[ISQL]ERROR: Could not SQLColumns\n" );
            SQLFreeStmt( hStmt, SQL_DROP );
            return 0;
        }
    }
    else
    {
        /* TABLES */
        if ( SQLTables( hStmt, NULL, 0, NULL, 0, NULL, 0, NULL, 0 ) != SQL_SUCCESS )
        {
            if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt );
            fprintf( stderr, "[ISQL]ERROR: Could not SQLTables\n" );
            SQLFreeStmt( hStmt, SQL_DROP );
            return 0;
        }
    }

    /****************************
     * WRITE HEADER
     ***************************/
    if ( bHTMLTable )
        WriteHeaderHTMLTable( hStmt );
    else if ( cDelimiter == 0 )
        UWriteHeaderNormal( hStmt, szSepLine );
    else if ( cDelimiter && bColumnNames )
        WriteHeaderDelimited( hStmt, cDelimiter );

    /****************************
     * WRITE BODY
     ***************************/
    if ( bHTMLTable )
        WriteBodyHTMLTable( hStmt );
    else if ( cDelimiter == 0 )
        nRows = WriteBodyNormal( hStmt );
    else
        WriteBodyDelimited( hStmt, cDelimiter );

    /****************************
     * WRITE FOOTER
     ***************************/
    if ( bHTMLTable )
        WriteFooterHTMLTable( hStmt );
    else if ( cDelimiter == 0 )
        UWriteFooterNormal( hStmt, szSepLine, nRows );

    /****************************
     * CLEANUP
     ***************************/
    SQLFreeStmt( hStmt, SQL_DROP );

    return 1;
}

Project: unixODBC
File: iusql.c

static int DumpODBCLog( SQLHENV hEnv, SQLHDBC hDbc, SQLHSTMT hStmt )
{
    SQLTCHAR        szError[501];
    SQLTCHAR        szSqlState[10];
    SQLINTEGER  nNativeError;
    SQLSMALLINT nErrorMsg;

    if ( hStmt )
    {
        while ( SQLError( hEnv, hDbc, hStmt, szSqlState, &nNativeError, szError, 500, &nErrorMsg ) == SQL_SUCCESS )
        {
            printf( "%s\n", uc_to_ascii( szError ));
        }
    }

    if ( hDbc )
    {
        while ( SQLError( hEnv, hDbc, 0, szSqlState, &nNativeError, szError, 500, &nErrorMsg ) == SQL_SUCCESS )
        {
            printf( "%s\n", uc_to_ascii( szError ));
        }
    }

    if ( hEnv )
    {
        while ( SQLError( hEnv, 0, 0, szSqlState, &nNativeError, szError, 500, &nErrorMsg ) == SQL_SUCCESS )
        {
            printf( "%s\n", uc_to_ascii( szError ));
        }
    }

    return 1;
}

Project: unixODBC
File: SQLSetDescField.c

SQLRETURN SQLSetDescFieldA( SQLHDESC descriptor_handle,
           SQLSMALLINT rec_number, 
           SQLSMALLINT field_identifier,
           SQLPOINTER value, 
           SQLINTEGER buffer_length )
{
    return SQLSetDescField( descriptor_handle,
           rec_number, 
           field_identifier,
           value, 
           buffer_length );
}

Project: unixODBC
File: iusql.c

static SQLLEN WriteBodyNormal( SQLHSTMT hStmt )
{
    SQLINTEGER      nCol                            = 0;
    SQLSMALLINT     nColumns                        = 0;
    SQLLEN          nIndicator                      = 0;
    SQLTCHAR        szColumn[MAX_DATA_WIDTH+20];
    SQLTCHAR        szColumnValue[MAX_DATA_WIDTH+1];
    SQLTCHAR        szColumnName[MAX_DATA_WIDTH+1]; 
    SQLULEN         nMaxLength                      = 10;
    SQLRETURN       nReturn                         = 0;
    SQLRETURN       ret;
    SQLLEN          nRows                           = 0;

    szColumn[ 0 ]       = 0;
    szColumnValue[ 0 ]  = 0;
    szColumnName[ 0 ]   = 0;    

    if ( SQLNumResultCols( hStmt, &nColumns ) != SQL_SUCCESS )
        nColumns = -1;

    /* ROWS */
    while (( ret = SQLFetch( hStmt )) == SQL_SUCCESS )
    {
        /* COLS */
        for ( nCol = 1; nCol <= nColumns; nCol++ )
        {
            SQLColAttribute( hStmt, nCol, SQL_DESC_LABEL, szColumnName, sizeof(szColumnName), NULL, NULL );
            SQLColAttribute( hStmt, nCol, SQL_DESC_DISPLAY_SIZE, NULL, 0, NULL, (SQLLEN*)&nMaxLength );

            uc_to_ascii( szColumnName );

            if ( nMaxLength > MAX_DATA_WIDTH ) nMaxLength = MAX_DATA_WIDTH;
            nReturn = SQLGetData( hStmt, nCol, SQL_C_WCHAR, (SQLPOINTER)szColumnValue, sizeof(szColumnValue), &nIndicator );
            szColumnValue[MAX_DATA_WIDTH] = '\0';
            uc_to_ascii( szColumnValue );

            if ( nReturn == SQL_SUCCESS && nIndicator != SQL_NULL_DATA )
            {
                if ( strlen((char*)szColumnValue) < max( nMaxLength, strlen((char*)szColumnName )))
                {
                    int i;
                    size_t maxlen=max( nMaxLength, strlen((char*)szColumnName ));
                    strcpy((char*) szColumn, "| " );
                    strcat((char*) szColumn, (char*) szColumnValue );

                    for ( i = strlen((char*) szColumnValue ); i < maxlen; i ++ )
                    {
                        strcat((char*) szColumn, " " );
                    }
                }
                else
                {
                    strcpy((char*) szColumn, "| " );
                    strcat((char*) szColumn, (char*) szColumnValue );
                }
            }
            else if ( nReturn == SQL_ERROR )
            {
                ret = SQL_ERROR;
                break;
            }
            else
            {
                sprintf((char*)  szColumn, "| %-*s", (int)max( nMaxLength, strlen((char*) szColumnName) ), "" );
            }
            fputs((char*)  szColumn, stdout );
        }
        if (ret != SQL_SUCCESS)
            break;
        printf( "|\n" );
        nRows++;
    } 
    if ( ret == SQL_ERROR )
    {
        if ( bVerbose ) DumpODBCLog( 0, 0, hStmt );
    }

    return nRows;
}

Project: unixODBC
File: iusql.c

static char * uc_to_ascii( SQLWCHAR *uc )
{
    char *ascii = (char *)uc;
    int i;

    for ( i = 0; uc[ i ]; i ++ )
    {
        ascii[ i ] = uc[ i ] & 0x00ff;
    }

    ascii[ i ] = 0;

    return ascii;
}

Project: unixODBC
File: SQLCreateDataSource.c

void _single_copy_to_wide( SQLWCHAR *out, LPCSTR in, int len )
{
    while ( len >= 0 )
    {
        *out = *in;
        out++;
        in++;
        len --;
    }
}

Project: unixODBC
File: SQLCreateDataSource.c

SQLWCHAR* _multi_string_alloc_and_expand( LPCSTR in )
{
    SQLWCHAR *chr;
    int len = 0;

    if ( !in )
    {
        return NULL;
    }
    
    while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
    {
        len ++;
    }

    chr = malloc(sizeof( SQLWCHAR ) * ( len + 2 ));

    len = 0;
    while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
    {
        chr[ len ] = in[ len ];
        len ++;
    }
    chr[ len ++ ] = 0;
    chr[ len ++ ] = 0;

    return chr;
}

Project: unixODBC
File: SQLCreateDataSource.c

SQLWCHAR* _single_string_alloc_and_expand( LPCSTR in )
{
    SQLWCHAR *chr;
    int len = 0;

    if ( !in )
    {
        return NULL;
    }

    while ( in[ len ] != 0 )
    {
        len ++;
    }

    chr = malloc( sizeof( SQLWCHAR ) * ( len + 1 ));

    len = 0;
    while ( in[ len ] != 0 )
    {
        chr[ len ] = in[ len ];
        len ++;
    }
    chr[ len ++ ] = 0;

    return chr;
}

Project: unixODBC
File: iusql.c

static void WriteBodyDelimited( SQLHSTMT hStmt, char cDelimiter )
{
    SQLINTEGER      nCol                            = 0;
    SQLSMALLINT     nColumns                        = 0;
    SQLLEN          nIndicator                      = 0;
    SQLTCHAR            szColumnValue[MAX_DATA_WIDTH+1];
    SQLRETURN       nReturn                         = 0;
    SQLRETURN       ret;

    szColumnValue[ 0 ]  = 0;

    if ( SQLNumResultCols( hStmt, &nColumns ) != SQL_SUCCESS )
        nColumns = -1;

    /* ROWS */
    while (( ret = SQLFetch( hStmt )) == SQL_SUCCESS )
    {
        /* COLS */
        for ( nCol = 1; nCol <= nColumns; nCol++ )
        {
            nReturn = SQLGetData( hStmt, nCol, SQL_C_WCHAR, (SQLPOINTER)szColumnValue, sizeof(szColumnValue), &nIndicator );
            if ( nReturn == SQL_SUCCESS && nIndicator != SQL_NULL_DATA )
            {
                uc_to_ascii( szColumnValue );
                fputs((char*) szColumnValue, stdout );
                if ( nCol < nColumns )
                    putchar( cDelimiter );
            }
            else if ( nReturn == SQL_ERROR )
            {
                ret = SQL_ERROR;
                break;
            }
            else
            {
                if ( nCol < nColumns )
                    putchar( cDelimiter );
            }
        }
        if (ret != SQL_SUCCESS)
            break;
        printf( "\n" );
    }
    if ( ret == SQL_ERROR )
    {
        if ( bVerbose ) DumpODBCLog( 0, 0, hStmt );
    }
}

Project: unixODBC
File: iusql.c

static void WriteFooterHTMLTable( SQLHSTMT hStmt )
{
    printf( "</table>\n" );
}

Project: unixODBC
File: SQLCreateDataSource.c

void _single_string_copy_to_wide( SQLWCHAR *out, LPCSTR in, int len )
{
    while ( len > 0 && *in )
    {
        *out = *in;
        out++;
        in++;
        len --;
    }
    *out = 0;
}

Project: unixODBC
File: SQLCreateDataSource.c

char* _single_string_alloc_and_copy( LPCWSTR in )
{
    char *chr;
    int len = 0;

    if ( !in )
    {
        return NULL;
    }

    while ( in[ len ] != 0 )
    {
        len ++;
    }

    chr = malloc( len + 1 );

    len = 0;
    while ( in[ len ] != 0 )
    {
        chr[ len ] = 0xFF & in[ len ];
        len ++;
    }
    chr[ len ++ ] = '\0';

    return chr;
}

Project: unixODBC
File: iusql.c

static void WriteHeaderHTMLTable( SQLHSTMT hStmt )
{
    SQLINTEGER      nCol                            = 0;
    SQLSMALLINT     nColumns                        = 0;
    SQLTCHAR        szColumnName[MAX_DATA_WIDTH+1]; 

    szColumnName[ 0 ] = 0;

    printf( "<table BORDER>\n" );
    printf( "<tr BGCOLOR=#000099>\n" );

    if ( SQLNumResultCols( hStmt, &nColumns ) != SQL_SUCCESS )
        nColumns = -1;

    for ( nCol = 1; nCol <= nColumns; nCol++ )
    {
        SQLColAttribute( hStmt, nCol, SQL_DESC_LABEL, szColumnName, sizeof(szColumnName), NULL, NULL );

        printf( "<td>\n" );
        printf( "<font face=Arial,Helvetica><font color=#FFFFFF>\n" );
        printf( "%s\n", uc_to_ascii( szColumnName ));
        printf( "</font></font>\n" );
        printf( "</td>\n" );
    }
    printf( "</tr>\n" );
}

Project: unixODBC
File: iusql.c

static void ansi_to_unicode( char *szSQL, SQLWCHAR *szUcSQL )
{
    int i;

    for ( i = 0; szSQL[ i ]; i ++ )
    {
        szUcSQL[ i ] = szSQL[ i ];
    }
    szUcSQL[ i ] = 0;
}

Project: unixODBC
File: iusql.c

int main( int argc, char *argv[] )
{
    int     nArg, count;
    int     bHTMLTable                  = 0;
    int     bBatch                      = 0;
    int     cDelimiter                  = 0;
    int     bColumnNames                = 0;
    char    *szDSN;
    char    *szUID;
    char    *szPWD;
    char    *szSQL;
    char    *pEscapeChar;
    int     buffer_size = 9000;

    szDSN = NULL;
    szUID = NULL;
    szPWD = NULL;

    if ( argc < 2 )
    {
        fputs( szSyntax, stderr );
        exit( 1 );
    }

#ifdef HAVE_SETLOCALE
    /*
     * Default locale
     */
    setlocale( LC_ALL, "" );
#endif

    /****************************
     * PARSE ARGS
     ***************************/
    for ( nArg = 1, count = 1 ; nArg < argc; nArg++ )
    {
        if ( argv[nArg][0] == '-' )
        {
            /* Options */
            switch ( argv[nArg][1] )
            {
                case 'd':
                    cDelimiter = argv[nArg][2];
                    break;
                case 's':
                    buffer_size = atoi( &(argv[nArg][2]) );
                    break;
                case 'w':
                    bHTMLTable = 1;
                    break;
                case 'b':
                    bBatch = 1;
                    break;
                case 'c':
                    bColumnNames = 1;
                    break;
                case 'v':
                    bVerbose = 1;
                    break;
                case 'e':
                    buseED = 1;
                    break;
                case '-':
                    printf( "unixODBC " VERSION "\n" );
                    exit(0);
#ifdef HAVE_STRTOL
                case 'x':
                    cDelimiter = strtol( argv[nArg]+2, NULL, 0 );
                    break;
#endif
#ifdef HAVE_SETLOCALE
                case 'l':
                    if ( !setlocale( LC_ALL, argv[nArg]+2 ))
                    {
                        fprintf( stderr, "isql: can't set locale to '%s'\n", argv[nArg]+2 );
                        exit ( -1 );
                    }
                    break;
#endif
                default:
                    fputs( szSyntax, stderr );
                    exit( 1 );
            }
            continue;
        }
        else if ( count == 1 )
            szDSN = argv[nArg];
        else if ( count == 2 )
            szUID = argv[nArg];
        else if ( count == 3 )
            szPWD = argv[nArg];
        count++;
    }

    szSQL = calloc( 1, buffer_size + 1 );

    /****************************
     * CONNECT
     ***************************/
    if ( !OpenDatabase( &hEnv, &hDbc, szDSN, szUID, szPWD ) )
        exit( 1 );

    /****************************
     * EXECUTE
     ***************************/
    if ( !bBatch )
    {
        printf( "+---------------------------------------+\n" );
        printf( "| Connected!                            |\n" );
        printf( "|                                       |\n" );
        printf( "| sql-statement                         |\n" );
        printf( "| help [tablename]                      |\n" );
        printf( "| quit                                  |\n" );
        printf( "|                                       |\n" );
        printf( "+---------------------------------------+\n" );
    }
    do
    {
        if ( !bBatch )
#ifndef HAVE_READLINE
            printf( "SQL> " );
#else
        {
            char *line;
            int malloced;

            line=readline("SQL> ");
            if ( !line )        /* EOF - ctrl D */
            {
                malloced = 1;
                line = strdup( "quit" );
            }
            else
            {
                malloced = 0;
            }
            strncpy(szSQL, line, buffer_size );
            add_history(line);
            if ( malloced )
            {
                free(line);
            }
        }
        else
#endif
        {
            char *line;
            int malloced;

            line = fgets( szSQL, buffer_size, stdin );
            if ( !line )        /* EOF - ctrl D */
            {
                malloced = 1;
                line = strdup( "quit" );
            }
            else
            {
                malloced = 0;
            }
            strncpy(szSQL, line, buffer_size );
            if ( malloced )
            {
                free(line);
            }
        }

        /* strip away escape chars */
        while ( (pEscapeChar=(char*)strchr(szSQL, '\n')) != NULL || (pEscapeChar=(char*)strchr(szSQL, '\r')) != NULL )
            *pEscapeChar = ' ';

        if ( szSQL[1] != '\0' )
        {
            if ( strncmp( szSQL, "quit", 4 ) == 0 )
                szSQL[1] = '\0';
            else if ( strncmp( szSQL, "help", 4 ) == 0 )
                ExecuteHelp( hDbc, szSQL, cDelimiter, bColumnNames, bHTMLTable );
            else if (memcmp(szSQL, "--", 2) != 0)
                ExecuteSQL( hDbc, szSQL, cDelimiter, bColumnNames, bHTMLTable );
        }

    } while ( szSQL[1] != '\0' );

    /****************************
     * DISCONNECT
     ***************************/
    CloseDatabase( hEnv, hDbc );

    exit( 0 );
}

Project: unixODBC
File: iusql.c

static int ExecuteSQL( SQLHDBC hDbc, char *szSQL, char cDelimiter, int bColumnNames, int bHTMLTable )
{
    SQLHSTMT        hStmt;
    SQLTCHAR        szSepLine[32001];   
    SQLTCHAR        szUcSQL[32001]; 
    SQLSMALLINT     cols;
    SQLINTEGER      ret;
    SQLLEN          nRows                   = 0;

    szSepLine[ 0 ] = 0;

    ansi_to_unicode( szSQL, szUcSQL );

    /****************************
     * EXECUTE SQL
     ***************************/
    if ( SQLAllocStmt( hDbc, &hStmt ) != SQL_SUCCESS )
    {
        if ( bVerbose ) DumpODBCLog( hEnv, hDbc, 0 );
        fprintf( stderr, "[ISQL]ERROR: Could not SQLAllocStmt\n" );
        return 0;
    }

    if ( buseED ) {
        ret = SQLExecDirect( hStmt, szUcSQL, SQL_NTS );

        if ( ret == SQL_NO_DATA )
        {
            fprintf( stderr, "[ISQL]INFO: SQLExecDirect returned SQL_NO_DATA\n" );
        }
        else if ( ret == SQL_SUCCESS_WITH_INFO )
        {
            if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt );
            fprintf( stderr, "[ISQL]INFO: SQLExecDirect returned SQL_SUCCESS_WITH_INFO\n" );
        }
        else if ( ret != SQL_SUCCESS )
        {
            if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt );
            fprintf( stderr, "[ISQL]ERROR: Could not SQLExecDirect\n" );
            SQLFreeStmt( hStmt, SQL_DROP );
            return 0;
        }
    }
    else {
        if ( SQLPrepare( hStmt, szUcSQL, SQL_NTS ) != SQL_SUCCESS )
        {
            if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt );
            fprintf( stderr, "[ISQL]ERROR: Could not SQLPrepare\n" );
            SQLFreeStmt( hStmt, SQL_DROP );
            return 0;
        }
    
        ret =  SQLExecute( hStmt );
    
        if ( ret == SQL_NO_DATA )
        {
            fprintf( stderr, "[ISQL]INFO: SQLExecute returned SQL_NO_DATA\n" );
        }
        else if ( ret == SQL_SUCCESS_WITH_INFO )
        {
            if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt );
            fprintf( stderr, "[ISQL]INFO: SQLExecute returned SQL_SUCCESS_WITH_INFO\n" );
        }
        else if ( ret != SQL_SUCCESS )
        {
            if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt );
            fprintf( stderr, "[ISQL]ERROR: Could not SQLExecute\n" );
            SQLFreeStmt( hStmt, SQL_DROP );
            return 0;
        }
    }

    do 
    {
        /*
         * check to see if it has generated a result set
         */

        if ( SQLNumResultCols( hStmt, &cols ) != SQL_SUCCESS )
        {
            if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt );
            fprintf( stderr, "[ISQL]ERROR: Could not SQLNumResultCols\n" );
            SQLFreeStmt( hStmt, SQL_DROP );
            return 0;
        }

        if ( cols > 0 )
        {
            /****************************
             * WRITE HEADER
             ***************************/
            if ( bHTMLTable )
                WriteHeaderHTMLTable( hStmt );
            else if ( cDelimiter == 0 )
                UWriteHeaderNormal( hStmt, szSepLine );
            else if ( cDelimiter && bColumnNames )
                WriteHeaderDelimited( hStmt, cDelimiter );

            /****************************
             * WRITE BODY
             ***************************/
            if ( bHTMLTable )
                WriteBodyHTMLTable( hStmt );
            else if ( cDelimiter == 0 )
                nRows = WriteBodyNormal( hStmt );
            else
                WriteBodyDelimited( hStmt, cDelimiter );
        }

        /****************************
         * WRITE FOOTER
         ***************************/
        if ( bHTMLTable )
            WriteFooterHTMLTable( hStmt );
        else if ( cDelimiter == 0 )
            UWriteFooterNormal( hStmt, szSepLine, nRows );
    }
    while ( SQL_SUCCEEDED( SQLMoreResults( hStmt )));

    /****************************
     * CLEANUP
     ***************************/
    SQLFreeStmt( hStmt, SQL_DROP );

    return 1;
}

Project: unixODBC
File: SQLWriteFileDSN.c

BOOL INSTAPI SQLWriteFileDSNW(LPCWSTR  lpszFileName,
                              LPCWSTR  lpszAppName,
                              LPCWSTR  lpszKeyName,
                              LPCWSTR  lpszString)
{
	BOOL ret;
	char *file;
	char *app;
	char *key;
	char *str;

	file = lpszFileName ? _single_string_alloc_and_copy( lpszFileName ) : (char*)NULL;
	app = lpszAppName ? _single_string_alloc_and_copy( lpszAppName ) : (char*)NULL;
	key = lpszKeyName ? _single_string_alloc_and_copy( lpszKeyName ) : (char*)NULL;
	str = lpszString ? _single_string_alloc_and_copy( lpszString ) : (char*)NULL;

	ret = SQLWriteFileDSN( file, app, key, str );

	if ( file )
		free( file );
	if ( app )
		free( app );
	if ( key )
		free( key );
	if ( str )
		free( str );

	return ret;
}

Project: unixODBC
File: iusql.c

void UWriteHeaderNormal( SQLHSTMT hStmt, SQLTCHAR *szSepLine )
{
    SQLINTEGER      nCol                            = 0;
    SQLSMALLINT     nColumns                        = 0;
    SQLULEN         nMaxLength                      = 10;
    SQLTCHAR            szColumn[MAX_DATA_WIDTH+20];    
    SQLTCHAR            szColumnName[MAX_DATA_WIDTH+1]; 
    SQLTCHAR            szHdrLine[32001];   

    szColumn[ 0 ]       = 0;    
    szColumnName[ 0 ]   = 0;    
    szHdrLine[ 0 ]      = 0;    

    if ( SQLNumResultCols( hStmt, &nColumns ) != SQL_SUCCESS )
        nColumns = -1;

    for ( nCol = 1; nCol <= nColumns; nCol++ )
    {
        SQLColAttribute( hStmt, nCol, SQL_DESC_DISPLAY_SIZE, NULL, 0, NULL, (SQLLEN*)&nMaxLength );
        SQLColAttribute( hStmt, nCol, SQL_DESC_LABEL, szColumnName, sizeof(szColumnName), NULL, NULL );
        if ( nMaxLength > MAX_DATA_WIDTH ) nMaxLength = MAX_DATA_WIDTH;

        uc_to_ascii( szColumnName );

        /* SEP */
        memset( szColumn, '\0', sizeof(szColumn) );
        memset( szColumn, '-', max( nMaxLength, strlen((char*)szColumnName) ) + 1 );
        strcat((char*) szSepLine, "+" );
        strcat((char*) szSepLine,(char*) szColumn );

        /* HDR */
        sprintf((char*) szColumn, "| %-*s", (int)max( nMaxLength, strlen((char*)szColumnName) ), (char*)szColumnName );
        strcat((char*) szHdrLine,(char*) szColumn );
    }
    strcat((char*) szSepLine, "+\n" );
    strcat((char*) szHdrLine, "|\n" );

    puts((char*) szSepLine );
    puts((char*) szHdrLine );
    puts((char*) szSepLine );
}

Project: unixODBC
File: iusql.c

void UWriteFooterNormal( SQLHSTMT hStmt, SQLTCHAR   *szSepLine, SQLLEN nRows )
{
    SQLLEN  nRowsAffected   = -1;

    puts( (char*)szSepLine );

    SQLRowCount( hStmt, &nRowsAffected );
    printf( "SQLRowCount returns %ld\n", nRowsAffected );

    if ( nRows )
    {
        printf( "%ld rows fetched\n", nRows );
    }
}

Project: unixODBC
File: SQLSetDescField.c

SQLRETURN SQLSetDescField( SQLHDESC descriptor_handle,
           SQLSMALLINT rec_number, 
           SQLSMALLINT field_identifier,
           SQLPOINTER value, 
           SQLINTEGER buffer_length )
{
    /*
     * not quite sure how the descriptor can be
     * allocated to a statement, all the documentation talks
     * about state transitions on statement states, but the
     * descriptor may be allocated with more than one statement
     * at one time. Which one should I check ?
     */
    DMHDESC descriptor = (DMHDESC) descriptor_handle;
    SQLRETURN ret;
    SQLCHAR s1[ 100 + LOG_MESSAGE_LEN ];
    int isStrField = 0;

    /*
     * check descriptor
     */

    if ( !__validate_desc( descriptor ))
    {
        dm_log_write( __FILE__, 
                    __LINE__, 
                    LOG_INFO, 
                    LOG_INFO, 
                    "Error: SQL_INVALID_HANDLE" );

        return SQL_INVALID_HANDLE;
    }

    function_entry( descriptor );

    if ( log_info.log_flag )
    {
        sprintf( descriptor -> msg, "\n\t\tEntry:\
\n\t\t\tDescriptor = %p\
\n\t\t\tRec Number = %d\
\n\t\t\tField Ident = %s\
\n\t\t\tValue = %p\
\n\t\t\tBuffer Length = %d",
                descriptor,
                rec_number,
                __desc_attr_as_string( s1, field_identifier ),
                value, 
                (int)buffer_length );

        dm_log_write( __FILE__, 
                __LINE__, 
                LOG_INFO, 
                LOG_INFO, 
                descriptor -> msg );
    }

    thread_protect( SQL_HANDLE_DESC, descriptor );

    if ( descriptor -> connection -> state < STATE_C4 )
    {
        dm_log_write( __FILE__, 
                __LINE__, 
                LOG_INFO, 
                LOG_INFO, 
                "Error: HY010" );

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

        return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR );
    }

    /*
     * check status of statements associated with this descriptor
     */

    if( __check_stmt_from_desc( descriptor, STATE_S8 ) ||
        __check_stmt_from_desc( descriptor, STATE_S9 ) ||
        __check_stmt_from_desc( descriptor, STATE_S10 ) ||
        __check_stmt_from_desc( descriptor, STATE_S11 ) ||
        __check_stmt_from_desc( descriptor, STATE_S12 ) ||
        __check_stmt_from_desc( descriptor, STATE_S13 ) ||
        __check_stmt_from_desc( descriptor, STATE_S14 ) ||
        __check_stmt_from_desc( descriptor, STATE_S15 )) {

        dm_log_write( __FILE__, 
                __LINE__, 
                LOG_INFO, 
                LOG_INFO, 
                "Error: HY010" );

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

        return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR );
    }


    if ( rec_number < 0 )
    {
        __post_internal_error( &descriptor -> error,
                ERROR_07009, NULL,
                descriptor -> connection -> environment -> requested_version );

        return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR );
    }

    switch ( field_identifier )
    {
    /* Fixed-length fields: buffer_length is ignored */
    case SQL_DESC_ALLOC_TYPE:
    case SQL_DESC_ARRAY_SIZE:
    case SQL_DESC_ARRAY_STATUS_PTR:
    case SQL_DESC_BIND_OFFSET_PTR:
    case SQL_DESC_BIND_TYPE:
    case SQL_DESC_COUNT:
    case SQL_DESC_ROWS_PROCESSED_PTR:
    case SQL_DESC_AUTO_UNIQUE_VALUE:
    case SQL_DESC_CASE_SENSITIVE:
    case SQL_DESC_CONCISE_TYPE:
    case SQL_DESC_DATA_PTR:
    case SQL_DESC_DATETIME_INTERVAL_CODE:
    case SQL_DESC_DATETIME_INTERVAL_PRECISION:
    case SQL_DESC_DISPLAY_SIZE:
    case SQL_DESC_FIXED_PREC_SCALE:
    case SQL_DESC_INDICATOR_PTR:
    case SQL_DESC_LENGTH:
    case SQL_DESC_NULLABLE:
    case SQL_DESC_NUM_PREC_RADIX:
    case SQL_DESC_OCTET_LENGTH:
    case SQL_DESC_OCTET_LENGTH_PTR:
    case SQL_DESC_PARAMETER_TYPE:
    case SQL_DESC_PRECISION:
    case SQL_DESC_ROWVER:
    case SQL_DESC_SCALE:
    case SQL_DESC_SEARCHABLE:
    case SQL_DESC_TYPE:
    case SQL_DESC_UNNAMED:
    case SQL_DESC_UNSIGNED:
    case SQL_DESC_UPDATABLE:
        isStrField = 0;
        break;
    /* Pointer to data: buffer_length must be valid */
    case SQL_DESC_BASE_COLUMN_NAME:
    case SQL_DESC_BASE_TABLE_NAME:
    case SQL_DESC_CATALOG_NAME:
    case SQL_DESC_LABEL:
    case SQL_DESC_LITERAL_PREFIX:
    case SQL_DESC_LITERAL_SUFFIX:
    case SQL_DESC_LOCAL_TYPE_NAME:
    case SQL_DESC_NAME:
    case SQL_DESC_SCHEMA_NAME:
    case SQL_DESC_TABLE_NAME:
    case SQL_DESC_TYPE_NAME:
        isStrField = 1;
        break;
    default:
        isStrField = buffer_length != SQL_IS_POINTER && buffer_length != SQL_IS_INTEGER
            && buffer_length != SQL_IS_UINTEGER && buffer_length != SQL_IS_SMALLINT &&
            buffer_length != SQL_IS_USMALLINT;
    }
    
    if ( isStrField && buffer_length < 0 && buffer_length != SQL_NTS)
    {
        __post_internal_error( &descriptor -> error,
            ERROR_HY090, NULL,
            descriptor -> connection -> environment -> requested_version );

        return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR );
    }

    if ( field_identifier == SQL_DESC_COUNT && (intptr_t)value < 0 )
    {
        __post_internal_error( &descriptor -> error,
                ERROR_07009, NULL,
                descriptor -> connection -> environment -> requested_version );

        return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR );
    }
    
    if ( field_identifier == SQL_DESC_PARAMETER_TYPE && (intptr_t)value != SQL_PARAM_INPUT
        && (intptr_t)value != SQL_PARAM_OUTPUT && (intptr_t)value != SQL_PARAM_INPUT_OUTPUT &&
        (intptr_t)value != SQL_PARAM_INPUT_OUTPUT_STREAM && (intptr_t)value != SQL_PARAM_OUTPUT_STREAM )
    {
        __post_internal_error( &descriptor -> error,
                ERROR_HY105, NULL,
                descriptor -> connection -> environment -> requested_version );

        return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR );
    }

    if ( CHECK_SQLSETDESCFIELD( descriptor -> connection ))
    {
      ret = SQLSETDESCFIELD( descriptor -> connection,
              descriptor -> driver_desc,
              rec_number, 
              field_identifier,
              value, 
              buffer_length );
    }
    else if ( CHECK_SQLSETDESCFIELDW( descriptor -> connection ))
    {
      SQLWCHAR *s1 = NULL;

        if (isStrField)
      {
        s1 = ansi_to_unicode_alloc( value, buffer_length, descriptor -> connection, NULL );
            if (SQL_NTS != buffer_length)
            {
                buffer_length *= sizeof(SQLWCHAR);
            }
      }
      else
      {
              s1 = value;
      }
      ret = SQLSETDESCFIELDW( descriptor -> connection,
                descriptor -> driver_desc,
                rec_number, 
                field_identifier,
                s1, 
                buffer_length );
       
        if (isStrField)
       {
        if (s1)
          free(s1); 
       }
    }
    else 
	{
        dm_log_write( __FILE__, 
                __LINE__, 
                LOG_INFO, 
                LOG_INFO, 
                "Error: IM001" );

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

        return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR );
    }

    if ( log_info.log_flag )
    {
        sprintf( descriptor -> msg, 
                "\n\t\tExit:[%s]",
                    __get_return_status( ret, s1 ));

        dm_log_write( __FILE__, 
                __LINE__, 
                LOG_INFO, 
                LOG_INFO, 
                descriptor -> msg );
    }

    return function_return( SQL_HANDLE_DESC, descriptor, ret );
}

Project: unixODBC
File: iusql.c

int CloseDatabase( SQLHENV hEnv, SQLHDBC hDbc )
{
    SQLDisconnect( hDbc );
    SQLFreeConnect( hDbc );
    SQLFreeEnv( hEnv );

    return 1;
}