diff options
Diffstat (limited to 'libmysql')
-rw-r--r-- | libmysql/CMakeLists.txt | 201 | ||||
-rw-r--r-- | libmysql/authentication_win/CMakeLists.txt | 38 | ||||
-rw-r--r-- | libmysql/authentication_win/common.cc | 510 | ||||
-rw-r--r-- | libmysql/authentication_win/common.h | 324 | ||||
-rw-r--r-- | libmysql/authentication_win/handshake.cc | 289 | ||||
-rw-r--r-- | libmysql/authentication_win/handshake.h | 181 | ||||
-rw-r--r-- | libmysql/authentication_win/handshake_client.cc | 393 | ||||
-rw-r--r-- | libmysql/authentication_win/log_client.cc | 65 | ||||
-rw-r--r-- | libmysql/authentication_win/plugin_client.cc | 68 | ||||
-rw-r--r-- | libmysql/get_password.c | 70 | ||||
-rw-r--r-- | libmysql/libmysql.c | 42 | ||||
-rw-r--r-- | libmysql/libmysql.def | 1 | ||||
-rw-r--r-- | libmysql/libmysql_rpm_version.in | 62 | ||||
-rw-r--r-- | libmysql/rpm_support.cc | 41 |
14 files changed, 363 insertions, 1922 deletions
diff --git a/libmysql/CMakeLists.txt b/libmysql/CMakeLists.txt index 962ab529de1..bbd534666c0 100644 --- a/libmysql/CMakeLists.txt +++ b/libmysql/CMakeLists.txt @@ -1,4 +1,5 @@ -# Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2006, 2013, Oracle and/or its affiliates. +# Copyright (c) 2009, 2013, SkySQL Ab. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -17,14 +18,13 @@ INCLUDE_DIRECTORIES( ${CMAKE_SOURCE_DIR}/include ${CMAKE_SOURCE_DIR}/libmysql ${CMAKE_SOURCE_DIR}/regex - ${CMAKE_SOURCE_DIR}/sql ${CMAKE_SOURCE_DIR}/strings ${SSL_INCLUDE_DIRS} ${SSL_INTERNAL_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR}) ADD_DEFINITIONS(${SSL_DEFINES}) -SET(CLIENT_API_FUNCTIONS +SET(CLIENT_API_FUNCTIONS_5_1 get_tty_password handle_options load_defaults @@ -59,6 +59,7 @@ mysql_field_count mysql_field_seek mysql_field_tell mysql_free_result +mysql_get_parameters mysql_get_client_info mysql_get_host_info mysql_get_proto_info @@ -130,22 +131,196 @@ mysql_server_init mysql_server_end mysql_set_character_set mysql_get_character_set_info -mysql_stmt_next_result +) -CACHE INTERNAL "Functions exported by client API" +SET(CLIENT_API_FUNCTIONS_5_5 +mysql_stmt_next_result +# Client plugins +mysql_client_find_plugin +mysql_client_register_plugin +mysql_load_plugin +mysql_load_plugin_v +mysql_plugin_options +# Async API +mysql_get_timeout_value +mysql_get_timeout_value_ms +mysql_get_socket +mysql_autocommit_cont +mysql_autocommit_start +mysql_change_user_cont +mysql_change_user_start +mysql_close_cont +mysql_close_start +mysql_commit_cont +mysql_commit_start +mysql_fetch_row_cont +mysql_fetch_row_start +mysql_free_result_cont +mysql_free_result_start +mysql_kill_cont +mysql_kill_start +mysql_list_dbs_cont +mysql_list_dbs_start +mysql_list_fields_cont +mysql_list_fields_start +mysql_list_processes_cont +mysql_list_processes_start +mysql_list_tables_cont +mysql_list_tables_start +mysql_next_result_cont +mysql_next_result_start +mysql_ping_cont +mysql_ping_start +mysql_query_cont +mysql_query_start +mysql_read_query_result_cont +mysql_read_query_result_start +mysql_real_connect_cont +mysql_real_connect_start +mysql_real_query_cont +mysql_real_query_start +mysql_refresh_cont +mysql_refresh_start +mysql_rollback_cont +mysql_rollback_start +mysql_select_db_cont +mysql_select_db_start +mysql_send_query_cont +mysql_send_query_start +mysql_set_character_set_cont +mysql_set_character_set_start +mysql_set_server_option_cont +mysql_set_server_option_start +mysql_shutdown_cont +mysql_shutdown_start +mysql_stat_cont +mysql_stat_start +mysql_stmt_close_cont +mysql_stmt_close_start +mysql_stmt_execute_cont +mysql_stmt_execute_start +mysql_stmt_fetch_cont +mysql_stmt_fetch_start +mysql_stmt_free_result_cont +mysql_stmt_free_result_start +mysql_stmt_next_result_cont +mysql_stmt_next_result_start +mysql_stmt_prepare_cont +mysql_stmt_prepare_start +mysql_stmt_reset_cont +mysql_stmt_reset_start +mysql_stmt_send_long_data_cont +mysql_stmt_send_long_data_start +mysql_stmt_store_result_cont +mysql_stmt_store_result_start +mysql_store_result_cont +mysql_store_result_start +#dynamic columns api +dynamic_column_create +dynamic_column_create_many +dynamic_column_update +dynamic_column_update_many +dynamic_column_delete +dynamic_column_exists +dynamic_column_list +dynamic_column_get +dynamic_column_prepare_decimal +) +SET(CLIENT_API_FUNCTIONS + ${CLIENT_API_FUNCTIONS_5_1} + ${CLIENT_API_FUNCTIONS_5_5} + CACHE INTERNAL + "Client functions" ) +IF(CMAKE_SYSTEM_NAME MATCHES "Linux") + # When building RPM, or DEB package on Debian, use ELF symbol versioning + # for compatibility with distribution packages, so client shared library can + # painlessly replace the one supplied by the distribution. + + # Also list of exported symbols in distributions may differ from what is considered + # official API. Define CLIENT_API_EXTRA for the set of symbols, that required to + # be exported on different platforms. + + IF(RPM) + # Fedora & Co declared following functions as part of API + SET(CLIENT_API_EXTRA + mysql_default_charset_info + mysql_get_charset + mysql_get_charset_by_csname + mysql_net_realloc + mysql_client_errors + + # Also export the non-renamed variants + # (in case someone wants to rebuild mysqli-php or something similar) + # See MDEV-4127 + default_charset_info + get_charset + get_charset_by_csname + net_realloc + client_errors + THR_KEY_mysys + ) + + # Add special script to fix symbols renames by Fedora + SET(CLIENT_SOURCES_EXTRA rpm_support.cc) + SET(VERSION_SCRIPT_TEMPLATE + ${CMAKE_CURRENT_SOURCE_DIR}/libmysql_rpm_version.in) + ELSEIF(DEB) + # libmyodbc on Ubuntu is using functions below + # If we don't export them, linker would just remove + # them (they are not used inside libmysqlclient) + SET(CLIENT_API_EXTRA + strfill + init_dynamic_string + ) + # MySQL supplied with Ubuntu does not have versioning, bug Debian does. + IF(DEB MATCHES "debian") + SET(VERSION_SCRIPT_TEMPLATE ${CMAKE_CURRENT_SOURCE_DIR}/libmysql.ver.in) + ENDIF() + ENDIF() + + IF(VERSION_SCRIPT_TEMPLATE) + # Generate version script. + # Create semicolon separated lists of functions to export from + # Since RPM packages use separate versioning for 5.1 API + # and 5.5 API (libmysqlclient_16 vs libmysqlclient_18), + # we need 2 lists. + SET (CLIENT_API_5_1_LIST) + FOREACH (f ${CLIENT_API_FUNCTIONS_5_1}) + SET(CLIENT_API_5_1_LIST "${CLIENT_API_5_1_LIST}\n${f};") + ENDFOREACH() + + SET (CLIENT_API_5_5_LIST) + FOREACH (f ${CLIENT_API_FUNCTIONS_5_5}) + SET(CLIENT_API_5_5_LIST "${CLIENT_API_5_5_LIST}\n${f};") + ENDFOREACH() + + CONFIGURE_FILE( + ${VERSION_SCRIPT_TEMPLATE} + ${CMAKE_CURRENT_BINARY_DIR}/libmysql.version + @ONLY@ + ) + SET(VERSION_SCRIPT_LINK_FLAGS + "-Wl,--version-script=${CMAKE_CURRENT_BINARY_DIR}/libmysql.version") + ENDIF() + +ENDIF() + + SET(CLIENT_SOURCES get_password.c libmysql.c errmsg.c ../sql-common/client.c + ../sql-common/mysql_async.c ../sql-common/my_time.c ../sql-common/client_plugin.c ../sql/net_serv.cc ../sql-common/pack.c ../sql/password.c + ${CLIENT_SOURCES_EXTRA} ) ADD_CONVENIENCE_LIBRARY(clientlib ${CLIENT_SOURCES}) DTRACE_INSTRUMENT(clientlib) @@ -153,16 +328,6 @@ ADD_DEPENDENCIES(clientlib GenError) SET(LIBS clientlib dbug strings vio mysys ${ZLIB_LIBRARY} ${SSL_LIBRARIES} ${LIBDL}) -# -# On Windows platform client library includes the client-side -# Windows Native Authentication plugin. -# -IF(WIN32) - ADD_DEFINITIONS(-DAUTHENTICATION_WIN) - ADD_SUBDIRECTORY(authentication_win) - LIST(APPEND LIBS auth_win_client) -ENDIF() - # Merge several convenience libraries into one big mysqlclient # and link them together into shared library. MERGE_LIBRARIES(mysqlclient STATIC ${LIBS} COMPONENT Development) @@ -190,7 +355,7 @@ IF(UNIX) ENDIF() IF(NOT DISABLE_SHARED) - MERGE_LIBRARIES(libmysql SHARED ${LIBS} EXPORTS ${CLIENT_API_FUNCTIONS} COMPONENT SharedLibraries) + MERGE_LIBRARIES(libmysql SHARED ${LIBS} EXPORTS ${CLIENT_API_FUNCTIONS} ${CLIENT_API_EXTRA} COMPONENT SharedLibraries) IF(UNIX) # libtool compatability IF(CMAKE_SYSTEM_NAME MATCHES "FreeBSD" OR APPLE) @@ -205,13 +370,13 @@ IF(NOT DISABLE_SHARED) OUTPUT_NAME mysqlclient VERSION "${OS_SHARED_LIB_VERSION}" SOVERSION "${SHARED_LIB_MAJOR_VERSION}") - IF(LINK_FLAG_NO_UNDEFINED) + IF(LINK_FLAG_NO_UNDEFINED OR VERSION_SCRIPT_LINK_FLAGS) GET_TARGET_PROPERTY(libmysql_link_flags libmysql LINK_FLAGS) IF(NOT libmysql_link_flag) SET(libmysql_link_flags) ENDIF() SET_TARGET_PROPERTIES(libmysql PROPERTIES LINK_FLAGS - "${libmysql_link_flags} ${LINK_FLAG_NO_UNDEFINED}") + "${libmysql_link_flags} ${LINK_FLAG_NO_UNDEFINED} ${VERSION_SCRIPT_LINK_FLAGS}") ENDIF() # clean direct output needs to be set several targets have the same name #(mysqlclient in this case) diff --git a/libmysql/authentication_win/CMakeLists.txt b/libmysql/authentication_win/CMakeLists.txt deleted file mode 100644 index 8cf8862e46f..00000000000 --- a/libmysql/authentication_win/CMakeLists.txt +++ /dev/null @@ -1,38 +0,0 @@ -# Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; version 2 of the License. -# -# 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. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -# -# Configuration for building Windows Authentication Plugin (client-side) -# - -ADD_DEFINITIONS(-DSECURITY_WIN32) -ADD_DEFINITIONS(-DDEBUG_ERRROR_LOG) # no error logging in production builds -ADD_DEFINITIONS(-DWINAUTH_USE_DBUG_LIB) # it is OK to use dbug library in statically - # linked plugin - -SET(HEADERS common.h handshake.h) -SET(PLUGIN_SOURCES plugin_client.cc handshake_client.cc log_client.cc common.cc handshake.cc) - -ADD_CONVENIENCE_LIBRARY(auth_win_client ${PLUGIN_SOURCES} ${HEADERS}) -TARGET_LINK_LIBRARIES(auth_win_client Secur32) - -# In IDE, group headers in a separate folder. - -SOURCE_GROUP(Headers REGULAR_EXPRESSION ".*h$") - -INSTALL_DEBUG_SYMBOLS(auth_win_client) -IF(MSVC) - INSTALL_DEBUG_TARGET(auth_win_client DESTINATION ${INSTALL_LIBDIR}/debug) -ENDIF() diff --git a/libmysql/authentication_win/common.cc b/libmysql/authentication_win/common.cc deleted file mode 100644 index 30a8e0b3b13..00000000000 --- a/libmysql/authentication_win/common.cc +++ /dev/null @@ -1,510 +0,0 @@ -/* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - 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. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ - -#include "common.h" -#include <sddl.h> // for ConvertSidToStringSid() -#include <secext.h> // for GetUserNameEx() - - -template <> void error_log_print<error_log_level::INFO>(const char *fmt, ...); -template <> void error_log_print<error_log_level::WARNING>(const char *fmt, ...); -template <> void error_log_print<error_log_level::ERROR>(const char *fmt, ...); - -/** - Option indicating desired level of logging. Values: - - 0 - no logging - 1 - log only error messages - 2 - additionally log warnings - 3 - additionally log info notes - 4 - also log debug messages - - Value of this option should be taken into account in the - implementation of error_log_vprint() function (see - log_client.cc). - - Note: No error or debug messages are logged in production code - (see logging macros in common.h). -*/ -int opt_auth_win_log_level= 2; - - -/** Connection class **************************************************/ - -/** - Create connection out of an active MYSQL_PLUGIN_VIO object. - - @param[in] vio pointer to a @c MYSQL_PLUGIN_VIO object used for - connection - it can not be NULL -*/ - -Connection::Connection(MYSQL_PLUGIN_VIO *vio): m_vio(vio), m_error(0) -{ - DBUG_ASSERT(vio); -} - - -/** - Write data to the connection. - - @param[in] blob data to be written - - @return 0 on success, VIO error code on failure. - - @note In case of error, VIO error code is stored in the connection object - and can be obtained with @c error() method. -*/ - -int Connection::write(const Blob &blob) -{ - m_error= m_vio->write_packet(m_vio, blob.ptr(), blob.len()); - -#ifndef DBUG_OFF - if (m_error) - DBUG_PRINT("error", ("vio write error %d", m_error)); -#endif - - return m_error; -} - - -/** - Read data from connection. - - @return A Blob containing read packet or null Blob in case of error. - - @note In case of error, VIO error code is stored in the connection object - and can be obtained with @c error() method. -*/ - -Blob Connection::read() -{ - unsigned char *ptr; - int len= m_vio->read_packet(m_vio, &ptr); - - if (len < 0) - { - m_error= true; - return Blob(); - } - - return Blob(ptr, len); -} - - -/** Sid class *****************************************************/ - - -/** - Create Sid object corresponding to a given account name. - - @param[in] account_name name of a Windows account - - The account name can be in any form accepted by @c LookupAccountName() - function. - - @note In case of errors created object is invalid and its @c is_valid() - method returns @c false. -*/ - -Sid::Sid(const wchar_t *account_name): m_data(NULL) -#ifndef DBUG_OFF -, m_as_string(NULL) -#endif -{ - DWORD sid_size= 0, domain_size= 0; - bool success; - - // Determine required buffer sizes - - success= LookupAccountNameW(NULL, account_name, NULL, &sid_size, - NULL, &domain_size, &m_type); - - if (!success && GetLastError() != ERROR_INSUFFICIENT_BUFFER) - { -#ifndef DBUG_OFF - Error_message_buf error_buf; - DBUG_PRINT("error", ("Could not determine SID buffer size, " - "LookupAccountName() failed with error %X (%s)", - GetLastError(), get_last_error_message(error_buf))); -#endif - return; - } - - // Query for SID (domain is ignored) - - wchar_t *domain= new wchar_t[domain_size]; - m_data= (TOKEN_USER*) new BYTE[sid_size + sizeof(TOKEN_USER)]; - m_data->User.Sid= (BYTE*)m_data + sizeof(TOKEN_USER); - - success= LookupAccountNameW(NULL, account_name, - m_data->User.Sid, &sid_size, - domain, &domain_size, - &m_type); - - if (!success || !is_valid()) - { -#ifndef DBUG_OFF - Error_message_buf error_buf; - DBUG_PRINT("error", ("Could not determine SID of '%S', " - "LookupAccountName() failed with error %X (%s)", - account_name, GetLastError(), - get_last_error_message(error_buf))); -#endif - goto fail; - } - - goto end; - -fail: - if (m_data) - delete [] m_data; - m_data= NULL; - -end: - if (domain) - delete [] domain; -} - - -/** - Create Sid object corresponding to a given security token. - - @param[in] token security token of a Windows account - - @note In case of errors created object is invalid and its @c is_valid() - method returns @c false. -*/ - -Sid::Sid(HANDLE token): m_data(NULL) -#ifndef DBUG_OFF -, m_as_string(NULL) -#endif -{ - DWORD req_size= 0; - bool success; - - // Determine required buffer size - - success= GetTokenInformation(token, TokenUser, NULL, 0, &req_size); - if (!success && GetLastError() != ERROR_INSUFFICIENT_BUFFER) - { -#ifndef DBUG_OFF - Error_message_buf error_buf; - DBUG_PRINT("error", ("Could not determine SID buffer size, " - "GetTokenInformation() failed with error %X (%s)", - GetLastError(), get_last_error_message(error_buf))); -#endif - return; - } - - m_data= (TOKEN_USER*) new BYTE[req_size]; - success= GetTokenInformation(token, TokenUser, m_data, req_size, &req_size); - - if (!success || !is_valid()) - { - delete [] m_data; - m_data= NULL; -#ifndef DBUG_OFF - if (!success) - { - Error_message_buf error_buf; - DBUG_PRINT("error", ("Could not read SID from security token, " - "GetTokenInformation() failed with error %X (%s)", - GetLastError(), get_last_error_message(error_buf))); - } -#endif - } -} - - -Sid::~Sid() -{ - if (m_data) - delete [] m_data; -#ifndef DBUG_OFF - if (m_as_string) - LocalFree(m_as_string); -#endif -} - -/// Check if Sid object is valid. -bool Sid::is_valid(void) const -{ - return m_data && m_data->User.Sid && IsValidSid(m_data->User.Sid); -} - - -#ifndef DBUG_OFF - -/** - Produces string representation of the SID. - - @return String representation of the SID or NULL in case of errors. - - @note Memory allocated for the string is automatically freed in Sid's - destructor. -*/ - -const char* Sid::as_string() -{ - if (!m_data) - return NULL; - - if (!m_as_string) - { - bool success= ConvertSidToStringSid(m_data->User.Sid, &m_as_string); - - if (!success) - { -#ifndef DBUG_OFF - Error_message_buf error_buf; - DBUG_PRINT("error", ("Could not get textual representation of a SID, " - "ConvertSidToStringSid() failed with error %X (%s)", - GetLastError(), get_last_error_message(error_buf))); -#endif - m_as_string= NULL; - return NULL; - } - } - - return m_as_string; -} - -#endif - - -bool Sid::operator ==(const Sid &other) -{ - if (!is_valid() || !other.is_valid()) - return false; - - return EqualSid(m_data->User.Sid, other.m_data->User.Sid); -} - - -/** Generating User Principal Name *************************/ - -/** - Call Windows API functions to get UPN of the current user and store it - in internal buffer. -*/ - -UPN::UPN(): m_buf(NULL) -{ - wchar_t buf1[MAX_SERVICE_NAME_LENGTH]; - - // First we try to use GetUserNameEx. - - m_len= sizeof(buf1)/sizeof(wchar_t); - - if (!GetUserNameExW(NameUserPrincipal, buf1, (PULONG)&m_len)) - { - if (GetLastError()) - { -#ifndef DBUG_OFF - Error_message_buf error_buf; - DBUG_PRINT("note", ("When determining UPN" - ", GetUserNameEx() failed with error %X (%s)", - GetLastError(), get_last_error_message(error_buf))); -#endif - if (ERROR_MORE_DATA == GetLastError()) - ERROR_LOG(INFO, ("Buffer overrun when determining UPN:" - " need %ul characters but have %ul", - m_len, sizeof(buf1)/sizeof(WCHAR))); - } - - m_len= 0; // m_len == 0 indicates invalid UPN - return; - } - - /* - UPN is stored in buf1 in wide-char format - convert it to utf8 - for sending over network. - */ - - m_buf= wchar_to_utf8(buf1, &m_len); - - if(!m_buf) - ERROR_LOG(ERROR, ("Failed to convert UPN to utf8")); - - // Note: possible error would be indicated by the fact that m_buf is NULL. - return; -} - - -UPN::~UPN() -{ - if (m_buf) - free(m_buf); -} - - -/** - Convert a wide-char string to utf8 representation. - - @param[in] string null-terminated wide-char string to be converted - @param[in,out] len length of the string to be converted or 0; on - return length (in bytes, excluding terminating - null character) of the converted string - - If len is 0 then the length of the string will be computed by this function. - - @return Pointer to a buffer containing utf8 representation or NULL in - case of error. - - @note The returned buffer must be freed with @c free() call. -*/ - -char* wchar_to_utf8(const wchar_t *string, size_t *len) -{ - char *buf= NULL; - size_t str_len= len && *len ? *len : wcslen(string); - - /* - A conversion from utf8 to wchar_t will never take more than 3 bytes per - character, so a buffer of length 3 * str_len schould be sufficient. - We check that assumption with an assertion later. - */ - - size_t buf_len= 3 * str_len; - - buf= (char*)malloc(buf_len + 1); - if (!buf) - { - DBUG_PRINT("error",("Out of memory when converting string '%S' to utf8", - string)); - return NULL; - } - - int res= WideCharToMultiByte(CP_UTF8, // convert to UTF-8 - 0, // conversion flags - string, // input buffer - str_len, // its length - buf, buf_len, // output buffer and its size - NULL, NULL); // default character (not used) - - if (res) - { - buf[res]= '\0'; - if (len) - *len= res; - return buf; - } - - // res is 0 which indicates error - -#ifndef DBUG_OFF - Error_message_buf error_buf; - DBUG_PRINT("error", ("Could not convert string '%S' to utf8" - ", WideCharToMultiByte() failed with error %X (%s)", - string, GetLastError(), - get_last_error_message(error_buf))); -#endif - - // Let's check our assumption about sufficient buffer size - DBUG_ASSERT(ERROR_INSUFFICIENT_BUFFER != GetLastError()); - - return NULL; -} - - -/** - Convert an utf8 string to a wide-char string. - - @param[in] string null-terminated utf8 string to be converted - @param[in,out] len length of the string to be converted or 0; on - return length (in chars) of the converted string - - If len is 0 then the length of the string will be computed by this function. - - @return Pointer to a buffer containing wide-char representation or NULL in - case of error. - - @note The returned buffer must be freed with @c free() call. -*/ - -wchar_t* utf8_to_wchar(const char *string, size_t *len) -{ - size_t buf_len; - - /* - Note: length (in bytes) of an utf8 string is always bigger than the - number of characters in this string. Hence a buffer of size len will - be sufficient. We add 1 for the terminating null character. - */ - - buf_len= len && *len ? *len : strlen(string); - wchar_t *buf= (wchar_t*)malloc((buf_len+1)*sizeof(wchar_t)); - - if (!buf) - { - DBUG_PRINT("error",("Out of memory when converting utf8 string '%s'" - " to wide-char representation", string)); - return NULL; - } - - size_t res; - res= MultiByteToWideChar(CP_UTF8, // convert from UTF-8 - 0, // conversion flags - string, // input buffer - buf_len, // its size - buf, buf_len); // output buffer and its size - if (res) - { - buf[res]= '\0'; - if (len) - *len= res; - return buf; - } - - // error in MultiByteToWideChar() - -#ifndef DBUG_OFF - Error_message_buf error_buf; - DBUG_PRINT("error", ("Could not convert UPN from UTF-8" - ", MultiByteToWideChar() failed with error %X (%s)", - GetLastError(), get_last_error_message(error_buf))); -#endif - - // Let's check our assumption about sufficient buffer size - DBUG_ASSERT(ERROR_INSUFFICIENT_BUFFER != GetLastError()); - - return NULL; -} - - -/** Error handling ****************************************************/ - - -/** - Returns error message corresponding to the last Windows error given - by GetLastError(). - - @note Error message is overwritten by next call to - @c get_last_error_message(). -*/ - -const char* get_last_error_message(Error_message_buf buf) -{ - int error= GetLastError(); - - buf[0]= '\0'; - FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, - NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPTSTR)buf, sizeof(buf), NULL ); - - return buf; -} diff --git a/libmysql/authentication_win/common.h b/libmysql/authentication_win/common.h deleted file mode 100644 index 415294b1ed9..00000000000 --- a/libmysql/authentication_win/common.h +++ /dev/null @@ -1,324 +0,0 @@ -/* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - 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. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ - -#ifndef COMMON_H -#define COMMON_H - -#include <my_global.h> -#include <windows.h> -#include <sspi.h> // for CtxtHandle -#include <mysql/plugin_auth.h> // for MYSQL_PLUGIN_VIO - -/// Maximum length of the target service name. -#define MAX_SERVICE_NAME_LENGTH 1024 - - -/** Debugging and error reporting infrastructure ***************************/ - -/* - Note: We use plugin local logging and error reporting mechanisms until - WL#2940 (plugin service: error reporting) is available. -*/ - -#undef INFO -#undef WARNING -#undef ERROR - -struct error_log_level -{ - typedef enum {INFO, WARNING, ERROR} type; -}; - -extern "C" int opt_auth_win_log_level; -unsigned int get_log_level(void); -void set_log_level(unsigned int); - - -/* - If DEBUG_ERROR_LOG is defined then error logging happens only - in debug-copiled code. Otherwise ERROR_LOG() expands to - error_log_print() even in production code. - - Note: Macro ERROR_LOG() can use printf-like format string like this: - - ERROR_LOG(Level, ("format string", args)); - - The implementation should handle it correctly. Currently it is passed - to fprintf() (see error_log_vprint() function). -*/ - -#if defined(DEBUG_ERROR_LOG) && defined(DBUG_OFF) -#define ERROR_LOG(Level, Msg) do {} while (0) -#else -#define ERROR_LOG(Level, Msg) error_log_print< error_log_level::Level > Msg -#endif - - -void error_log_vprint(error_log_level::type level, - const char *fmt, va_list args); - -template <error_log_level::type Level> -void error_log_print(const char *fmt, ...) -{ - va_list args; - va_start(args, fmt); - error_log_vprint(Level, fmt, args); - va_end(args); -} - -typedef char Error_message_buf[1024]; -const char* get_last_error_message(Error_message_buf); - - -/* - Internal implementation of debug message printing which does not use - dbug library. This is invoked via macro: - - DBUG_PRINT_DO(Keyword, ("format string", args)); - - This is supposed to be used as an implementation of DBUG_PRINT() macro, - unless the dbug library implementation is used or debug messages are disabled. -*/ - -#ifndef DBUG_OFF - -#define DBUG_PRINT_DO(Keyword, Msg) \ - do { \ - if (4 > get_log_level()) break; \ - fprintf(stderr, "winauth: %s: ", Keyword); \ - debug_msg Msg; \ - } while (0) - -inline -void debug_msg(const char *fmt, ...) -{ - va_list args; - va_start(args, fmt); - vfprintf(stderr, fmt, args); - fputc('\n', stderr); - fflush(stderr); - va_end(args); -} - -#else -#define DBUG_PRINT_DO(K, M) do {} while (0) -#endif - - -#ifndef WINAUTH_USE_DBUG_LIB - -#undef DBUG_PRINT -#define DBUG_PRINT(Keyword, Msg) DBUG_PRINT_DO(Keyword, Msg) - -/* - Redefine few more debug macros to make sure that no symbols from - dbug library are used. -*/ - -#undef DBUG_ENTER -#define DBUG_ENTER(X) do {} while (0) - -#undef DBUG_RETURN -#define DBUG_RETURN(X) return (X) - -#undef DBUG_ASSERT -#ifndef DBUG_OFF -#define DBUG_ASSERT(X) assert (X) -#else -#define DBUG_ASSERT(X) do {} while (0) -#endif - -#undef DBUG_DUMP -#define DBUG_DUMP(A,B,C) do {} while (0) - -#endif - - -/** Blob class *************************************************************/ - -typedef unsigned char byte; - -/** - Class representing a region of memory (e.g., a string or binary buffer). - - @note This class does not allocate memory. It merely describes a region - of memory which must be allocated externally (if it is dynamic memory). -*/ - -class Blob -{ - byte *m_ptr; ///< Pointer to the first byte of the memory region. - size_t m_len; ///< Length of the memory region. - -public: - - Blob(): m_ptr(NULL), m_len(0) - {} - - Blob(const byte *ptr, const size_t len) - : m_ptr(const_cast<byte*>(ptr)), m_len(len) - {} - - Blob(const char *str): m_ptr((byte*)str) - { - m_len= strlen(str); - } - - byte* ptr() const - { - return m_ptr; - } - - size_t len() const - { - return m_len; - } - - byte& operator[](unsigned pos) const - { - static byte out_of_range= 0; // alas, no exceptions... - return pos < len() ? m_ptr[pos] : out_of_range; - } - - bool is_null() const - { - return m_ptr == NULL; - } - - void trim(size_t l) - { - m_len= l; - } -}; - - -/** Connection class *******************************************************/ - -/** - Convenience wrapper around MYSQL_PLUGIN_VIO object providing basic - read/write operations. -*/ - -class Connection -{ - MYSQL_PLUGIN_VIO *m_vio; ///< Pointer to @c MYSQL_PLUGIN_VIO structure. - - /** - If non-zero, indicates that connection is broken. If this has happened - because of failed operation, stores non-zero error code from that failure. - */ - int m_error; - -public: - - Connection(MYSQL_PLUGIN_VIO *vio); - int write(const Blob&); - Blob read(); - - int error() const - { - return m_error; - } -}; - - -/** Sid class **************************************************************/ - -/** - Class for storing and manipulating Windows security identifiers (SIDs). -*/ - -class Sid -{ - TOKEN_USER *m_data; ///< Pointer to structure holding identifier's data. - SID_NAME_USE m_type; ///< Type of identified entity. - -public: - - Sid(const wchar_t*); - Sid(HANDLE sec_token); - ~Sid(); - - bool is_valid(void) const; - - bool is_group(void) const - { - return m_type == SidTypeGroup - || m_type == SidTypeWellKnownGroup - || m_type == SidTypeAlias; - } - - bool is_user(void) const - { - return m_type == SidTypeUser; - } - - bool operator==(const Sid&); - - operator PSID() const - { - return (PSID)m_data->User.Sid; - } - -#ifndef DBUG_OFF - -private: - char *m_as_string; ///< Cached string representation of the SID. -public: - const char* as_string(); - -#endif -}; - - -/** UPN class **************************************************************/ - -/** - An object of this class obtains and stores User Principal Name of the - account under which current process is running. -*/ - -class UPN -{ - char *m_buf; ///< Pointer to UPN in utf8 representation. - size_t m_len; ///< Length of the name. - -public: - - UPN(); - ~UPN(); - - bool is_valid() const - { - return m_len > 0; - } - - const Blob as_blob() const - { - return m_len ? Blob((byte*)m_buf, m_len) : Blob(); - } - - const char* as_string() const - { - return (const char*)m_buf; - } - -}; - - -char* wchar_to_utf8(const wchar_t*, size_t*); -wchar_t* utf8_to_wchar(const char*, size_t*); - -#endif diff --git a/libmysql/authentication_win/handshake.cc b/libmysql/authentication_win/handshake.cc deleted file mode 100644 index 8e6af8408ae..00000000000 --- a/libmysql/authentication_win/handshake.cc +++ /dev/null @@ -1,289 +0,0 @@ -/* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - 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. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ - -#include "handshake.h" - - -/** Handshake class implementation **********************************/ - -/** - Create common part of handshake context. - - @param[in] ssp name of the SSP (Security Service Provider) to - be used for authentication - @param[in] side is this handshake object used for server- or - client-side handshake - - Prepare for handshake using the @c ssp security module. We use - "Negotiate" which picks best available module. Parameter @c side - tells if this is preparing for server or client side authentication - and is used to prepare appropriate credentials. -*/ - -Handshake::Handshake(const char *ssp, side_t side) -: m_atts(0L), m_error(0), m_complete(FALSE), - m_have_credentials(false), m_have_sec_context(false) -#ifndef DBUG_OFF - , m_ssp_info(NULL) -#endif -{ - SECURITY_STATUS ret; - - // Obtain credentials for the authentication handshake. - - ret= AcquireCredentialsHandle(NULL, (SEC_CHAR*)ssp, - side == SERVER ? SECPKG_CRED_INBOUND : SECPKG_CRED_OUTBOUND, - NULL, NULL, NULL, NULL, &m_cred, &m_expire); - - if (ret != SEC_E_OK) - { - DBUG_PRINT("error", ("AcqireCredentialsHandle() failed" - " with error %X", ret)); - ERROR_LOG(ERROR, ("Could not obtain local credentials" - " required for authentication")); - m_error= ret; - } - - m_have_credentials= true; -} - - -Handshake::~Handshake() -{ - if (m_have_credentials) - FreeCredentialsHandle(&m_cred); - if (m_have_sec_context) - DeleteSecurityContext(&m_sctx); - m_output.free(); - -#ifndef DBUG_OFF - if (m_ssp_info) - FreeContextBuffer(m_ssp_info); -#endif -} - - -/** - Read and process data packets from the other end of a connection. - - @param[IN] con a connection to read packets from - - Packets are read and processed until authentication handshake is - complete. It is assumed that the peer will send at least one packet. - Packets are processed with @c process_data() method. If new data is - generated during packet processing, this data is sent to the peer and - another round of packet exchange starts. - - @return 0 on success. - - @note In case of error, appropriate error message is logged. -*/ -int Handshake::packet_processing_loop() -{ - m_round= 0; - - do { - ++m_round; - // Read packet send by the peer - - DBUG_PRINT("info", ("Waiting for packet")); - Blob packet= read_packet(); - if (error()) - { - ERROR_LOG(ERROR, ("Error reading packet in round %d", m_round)); - return 1; - } - DBUG_PRINT("info", ("Got packet of length %d", packet.len())); - - /* - Process received data, possibly generating new data to be sent. - */ - - Blob new_data= process_data(packet); - - if (error()) - { - ERROR_LOG(ERROR, ("Error processing packet in round %d", m_round)); - return 1; - } - - /* - If new data has been generated, send it to the peer. Otherwise - handshake must be completed. - */ - - if (!new_data.is_null()) - { - DBUG_PRINT("info", ("Round %d started", m_round)); - - DBUG_PRINT("info", ("Sending packet of length %d", new_data.len())); - int ret= write_packet(new_data); - if (ret) - { - ERROR_LOG(ERROR, ("Error writing packet in round %d", m_round)); - return 1; - } - DBUG_PRINT("info", ("Data sent")); - } - else if (!is_complete()) - { - ERROR_LOG(ERROR, ("No data to send in round %d" - " but handshake is not complete", m_round)); - return 1; - } - - /* - To protect against malicious clients, break handshake exchange if - too many rounds. - */ - - if (m_round > MAX_HANDSHAKE_ROUNDS) - { - ERROR_LOG(ERROR, ("Authentication handshake could not be completed" - " after %d rounds", m_round)); - return 1; - } - - } while(!is_complete()); - - ERROR_LOG(INFO, ("Handshake completed after %d rounds", m_round)); - return 0; -} - - -#ifndef DBUG_OFF - -/** - Get name of the security package which was used in authentication. - - This method should be called only after handshake was completed. It is - available only in debug builds. - - @return Name of security package or NULL if it can not be obtained. -*/ - -const char* Handshake::ssp_name() -{ - if (!m_ssp_info && m_complete) - { - SecPkgContext_PackageInfo pinfo; - - int ret= QueryContextAttributes(&m_sctx, SECPKG_ATTR_PACKAGE_INFO, &pinfo); - - if (SEC_E_OK == ret) - { - m_ssp_info= pinfo.PackageInfo; - } - else - DBUG_PRINT("error", - ("Could not obtain SSP info from authentication context" - ", QueryContextAttributes() failed with error %X", ret)); - } - - return m_ssp_info ? m_ssp_info->Name : NULL; -} - -#endif - - -/** - Process result of @c {Initialize,Accept}SecurityContext() function. - - @param[in] ret return code from @c {Initialize,Accept}SecurityContext() - function - - This function analyses return value of Windows - @c {Initialize,Accept}SecurityContext() function. A call to - @c CompleteAuthToken() is done if requested. If authentication is complete, - this fact is marked in the internal state of the Handshake object. - If errors are detected the object is moved to error state. - - @return True if error has been detected. -*/ - -bool Handshake::process_result(int ret) -{ - /* - First check for errors and set the m_complete flag if the result - indicates that handshake is complete. - */ - - switch (ret) - { - case SEC_E_OK: - case SEC_I_COMPLETE_NEEDED: - // Handshake completed - m_complete= true; - break; - - case SEC_I_CONTINUE_NEEDED: - case SEC_I_COMPLETE_AND_CONTINUE: - break; - - default: - m_error= ret; - return true; - } - - m_have_sec_context= true; - - /* - If the result indicates a need for this, complete the authentication - token. - */ - - switch (ret) - { - case SEC_I_COMPLETE_NEEDED: - case SEC_I_COMPLETE_AND_CONTINUE: - ret= CompleteAuthToken(&m_sctx, &m_output); - if (ret != 0) - { - DBUG_PRINT("error", ("CompleteAuthToken() failed with error %X", ret)); - m_error= ret; - return true; - } - default: - break; - } - - return false; -} - - -/** Security_buffer class implementation **********************************/ - - -Security_buffer::Security_buffer(const Blob &blob): m_allocated(false) -{ - init(blob.ptr(), blob.len()); -} - - -Security_buffer::Security_buffer(): m_allocated(true) -{ - init(NULL, 0); -} - - -void Security_buffer::free(void) -{ - if (!m_allocated) - return; - if (!ptr()) - return; - FreeContextBuffer(ptr()); - m_allocated= false; -} diff --git a/libmysql/authentication_win/handshake.h b/libmysql/authentication_win/handshake.h deleted file mode 100644 index adab4715c99..00000000000 --- a/libmysql/authentication_win/handshake.h +++ /dev/null @@ -1,181 +0,0 @@ -/* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - 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. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ - -#ifndef HANDSHAKE_H -#define HANDSHAKE_H - -#include "common.h" - -/** - Name of the SSP (Security Support Provider) to be used for authentication. - - We use "Negotiate" which will find the most secure SSP which can be used - and redirect to that SSP. -*/ -#define SSP_NAME "Negotiate" - -/** - Maximal number of rounds in authentication handshake. - - Server will interrupt authentication handshake with error if client's - identity can not be determined within this many rounds. -*/ -#define MAX_HANDSHAKE_ROUNDS 50 - - -/// Convenience wrapper around @c SecBufferDesc. - -class Security_buffer: public SecBufferDesc -{ - SecBuffer m_buf; ///< A @c SecBuffer instance. - - void init(byte *ptr, size_t len) - { - ulVersion= 0; - cBuffers= 1; - pBuffers= &m_buf; - - m_buf.BufferType= SECBUFFER_TOKEN; - m_buf.pvBuffer= ptr; - m_buf.cbBuffer= len; - } - - /// If @c false, no deallocation will be done in the destructor. - bool m_allocated; - - public: - - Security_buffer(const Blob&); - Security_buffer(); - - ~Security_buffer() - { - free(); - } - - byte* ptr() const - { - return (byte*)m_buf.pvBuffer; - } - - size_t len() const - { - return m_buf.cbBuffer; - } - - bool is_valid() const - { - return ptr() != NULL; - } - - const Blob as_blob() const - { - return Blob(ptr(), len()); - } - - void free(void); -}; - - -/// Common base for Handshake_{server,client}. - -class Handshake -{ -public: - - typedef enum {CLIENT, SERVER} side_t; - - Handshake(const char *ssp, side_t side); - virtual ~Handshake(); - - int Handshake::packet_processing_loop(); - - bool virtual is_complete() const - { - return m_complete; - } - - int error() const - { - return m_error; - } - -protected: - - /// Security context object created during the handshake. - CtxtHandle m_sctx; - - /// Credentials of the principal performing this handshake. - CredHandle m_cred; - - /// Stores expiry date of the created security context. - TimeStamp m_expire; - - /// Stores attributes of the created security context. - ULONG m_atts; - - /** - Round of the handshake (starting from round 1). One round - consist of reading packet from the other side, processing it and - optionally sending a reply (see @c packet_processing_loop()). - */ - unsigned int m_round; - - /// If non-zero, stores error code of the last failed operation. - int m_error; - - /// @c true when handshake is complete. - bool m_complete; - - /// @c true when the principal credentials has been determined. - bool m_have_credentials; - - /// @c true when the security context has been created. - bool m_have_sec_context; - - /// Buffer for data to be send to the other side. - Security_buffer m_output; - - bool process_result(int); - - /** - This method is used inside @c packet_processing_loop to process - data packets received from the other end. - - @param[IN] data data to be processed - - @return A blob with data to be sent to the other end or null blob if - no more data needs to be exchanged. - */ - virtual Blob process_data(const Blob &data) =0; - - /// Read packet from the other end. - virtual Blob read_packet() =0; - - /// Write packet to the other end. - virtual int write_packet(Blob &data) =0; - -#ifndef DBUG_OFF - -private: - SecPkgInfo *m_ssp_info; -public: - const char* ssp_name(); - -#endif -}; - - -#endif diff --git a/libmysql/authentication_win/handshake_client.cc b/libmysql/authentication_win/handshake_client.cc deleted file mode 100644 index c6ddbede6f2..00000000000 --- a/libmysql/authentication_win/handshake_client.cc +++ /dev/null @@ -1,393 +0,0 @@ -/* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - 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. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ - -#include "handshake.h" - -#include <mysql.h> // for MYSQL structure - - -/// Client-side context for authentication handshake - -class Handshake_client: public Handshake -{ - /** - Name of the server's service for which we authenticate. - - The service name is sent by server in the initial packet. If no - service name is used, this member is @c NULL. - */ - SEC_WCHAR *m_service_name; - - /// Buffer for storing service name obtained from server. - SEC_WCHAR m_service_name_buf[MAX_SERVICE_NAME_LENGTH]; - - Connection &m_con; - -public: - - Handshake_client(Connection &con, const char *target, size_t len); - ~Handshake_client(); - - Blob first_packet(); - Blob process_data(const Blob&); - - Blob read_packet(); - int write_packet(Blob &data); -}; - - -/** - Create authentication handshake context for client. - - @param con connection for communication with the peer - @param target name of the target service with which we will authenticate - (can be NULL if not used) - - Some security packages (like Kerberos) require providing explicit name - of the service with which a client wants to authenticate. The server-side - authentication plugin sends this name in the greeting packet - (see @c win_auth_handshake_{server,client}() functions). -*/ - -Handshake_client::Handshake_client(Connection &con, - const char *target, size_t len) -: Handshake(SSP_NAME, CLIENT), m_service_name(NULL), m_con(con) -{ - if (!target || 0 == len) - return; - - // Convert received UPN to internal WCHAR representation. - - m_service_name= utf8_to_wchar(target, &len); - - if (m_service_name) - DBUG_PRINT("info", ("Using target service: %S\n", m_service_name)); - else - { - /* - Note: we ignore errors here - m_target will be NULL, the target name - will not be used and system will fall-back to NTLM authentication. But - we leave trace in error log. - */ - ERROR_LOG(WARNING, ("Could not decode UPN sent by the server" - "; target service name will not be used" - " and Kerberos authentication will not work")); - } -} - - -Handshake_client::~Handshake_client() -{ - if (m_service_name) - free(m_service_name); -} - - -Blob Handshake_client::read_packet() -{ - /* - We do a fake read in the first round because first - packet from the server containing UPN must be read - before the handshake context is created and the packet - processing loop starts. We return an empty blob here - and process_data() function will ignore it. - */ - if (m_round == 1) - return Blob(); - - // Otherwise we read packet from the connection. - - Blob packet= m_con.read(); - m_error= m_con.error(); - if (!m_error && packet.is_null()) - m_error= true; // (no specific error code assigned) - - if (m_error) - return Blob(); - - DBUG_PRINT("dump", ("Got the following bytes")); - DBUG_DUMP("dump", packet.ptr(), packet.len()); - return packet; -} - - - -int Handshake_client::write_packet(Blob &data) -{ - /* - Length of the first data payload send by client authentication plugin is - limited to 255 bytes (because it is wrapped inside client authentication - packet and is length-encoded with 1 byte for the length). - - If the data payload is longer than 254 bytes, then it is sent in two parts: - first part of length 255 will be embedded in the authentication packet, - second part will be sent in the following packet. Byte 255 of the first - part contains information about the total length of the payload. It is a - number of blocks of size 512 bytes which is sufficient to store the - combined packets. - - Server's logic for reading first client's payload is as follows - (see Handshake_server::read_packet()): - 1. Read data from the authentication packet, if it is shorter than 255 bytes - then that is all data sent by client. - 2. If there is 255 bytes of data in the authentication packet, read another - packet and append it to the data, skipping byte 255 of the first packet - which can be used to allocate buffer of appropriate size. - */ - - size_t len2= 0; // length of the second part of first data payload - byte saved_byte; // for saving byte 255 in which data length is stored - - if (m_round == 1 && data.len() > 254) - { - len2= data.len() - 254; - DBUG_PRINT("info", ("Splitting first packet of length %lu" - ", %lu bytes will be sent in a second part", - data.len(), len2)); - /* - Store in byte 255 the number of 512b blocks that are needed to - keep all the data. - */ - unsigned block_count= data.len()/512 + ((data.len() % 512) ? 1 : 0); - -#if !defined(DBUG_OFF) && defined(WINAUTH_USE_DBUG_LIB) - - /* - For testing purposes, use wrong block count to see how server - handles this. - */ - DBUG_EXECUTE_IF("winauth_first_packet_test",{ - block_count= data.len() == 601 ? 0 : - data.len() == 602 ? 1 : - block_count; - }); - -#endif - - DBUG_ASSERT(block_count < (unsigned)0x100); - saved_byte= data[254]; - data[254] = block_count; - - data.trim(255); - } - - DBUG_PRINT("dump", ("Sending the following data")); - DBUG_DUMP("dump", data.ptr(), data.len()); - int ret= m_con.write(data); - - if (ret) - return ret; - - // Write second part if it is present. - if (len2) - { - data[254]= saved_byte; - Blob data2(data.ptr() + 254, len2); - DBUG_PRINT("info", ("Sending second part of data")); - DBUG_DUMP("info", data2.ptr(), data2.len()); - ret= m_con.write(data2); - } - - return ret; -} - - -/** - Process data sent by server. - - @param[in] data blob with data from server - - This method analyses data sent by server during authentication handshake. - If client should continue packet exchange, this method returns data to - be sent to the server next. If no more data needs to be exchanged, an - empty blob is returned and @c is_complete() is @c true. In case of error - an empty blob is returned and @c error() gives non-zero error code. - - When invoked for the first time (in the first round of the handshake) - there is no data from the server (data blob is null) and the intial - packet is generated without an input. - - @return Data to be sent to the server next or null blob if no more data - needs to be exchanged or in case of error. -*/ - -Blob Handshake_client::process_data(const Blob &data) -{ -#if !defined(DBUG_OFF) && defined(WINAUTH_USE_DBUG_LIB) - /* - Code for testing the logic for sending the first client payload. - - A fake data of length given by environment variable TEST_PACKET_LENGTH - (or default 255 bytes) is sent to the server. First 2 bytes of the - payload contain its total length (LSB first). The length of test data - is limited to 2048 bytes. - - Upon receiving test data, server will check that data is correct and - refuse connection. If server detects data errors it will crash on - assertion. - - This code is executed if debug flag "winauth_first_packet_test" is - set, e.g. using client option: - - --debug="d,winauth_first_packet_test" - - The same debug flag must be enabled in the server, e.g. using - statement: - - SET GLOBAL debug= '+d,winauth_first_packet_test'; - */ - - static byte test_buf[2048]; - - if (m_round == 1 - && DBUG_EVALUATE_IF("winauth_first_packet_test", true, false)) - { - const char *env= getenv("TEST_PACKET_LENGTH"); - size_t len= env ? atoi(env) : 0; - if (!len) - len= 255; - if (len > sizeof(test_buf)) - len= sizeof(test_buf); - - // Store data length in first 2 bytes. - byte *ptr= test_buf; - *ptr++= len & 0xFF; - *ptr++= len >> 8; - - // Fill remaining bytes with known values. - for (byte b= 0; ptr < test_buf + len; ++ptr, ++b) - *ptr= b; - - return Blob(test_buf, len); - }; - -#endif - - Security_buffer input(data); - SECURITY_STATUS ret; - - m_output.free(); - - ret= InitializeSecurityContextW( - &m_cred, - m_round == 1 ? NULL : &m_sctx, // partial context - m_service_name, // service name - ASC_REQ_ALLOCATE_MEMORY, // requested attributes - 0, // reserved - SECURITY_NETWORK_DREP, // data representation - m_round == 1 ? NULL : &input, // input data - 0, // reserved - &m_sctx, // context - &m_output, // output data - &m_atts, // attributes - &m_expire); // expire date - - if (process_result(ret)) - { - DBUG_PRINT("error", - ("InitializeSecurityContext() failed with error %X", ret)); - return Blob(); - } - - return m_output.as_blob(); -} - - -/**********************************************************************/ - - -/** - Perform authentication handshake from client side. - - @param[in] vio pointer to @c MYSQL_PLUGIN_VIO instance to be used - for communication with the server - @param[in] mysql pointer to a MySQL connection for which we authenticate - - After reading the initial packet from server, containing its UPN to be - used as service name, client starts packet exchange by sending the first - packet in this exchange. While handshake is not yet completed, client - reads packets sent by the server and process them, possibly generating new - data to be sent to the server. - - This function reports errors. - - @return 0 on success. -*/ - -int win_auth_handshake_client(MYSQL_PLUGIN_VIO *vio, MYSQL *mysql) -{ - DBUG_ENTER("win_auth_handshake_client"); - - /* - Check if we should enable logging. - */ - { - const char *opt= getenv("AUTHENTICATION_WIN_LOG"); - int opt_val= opt ? atoi(opt) : 0; - if (opt && !opt_val) - { - if (!strncasecmp("on", opt, 2)) opt_val= 2; - if (!strncasecmp("yes", opt, 3)) opt_val= 2; - if (!strncasecmp("true", opt, 4)) opt_val= 2; - if (!strncasecmp("debug", opt, 5)) opt_val= 4; - if (!strncasecmp("dbug", opt, 4)) opt_val= 4; - } - set_log_level(opt_val); - } - - ERROR_LOG(INFO, ("Authentication handshake for account %s", mysql->user)); - - // Create connection object. - - Connection con(vio); - DBUG_ASSERT(!con.error()); - - // Read initial packet from server containing service name. - - Blob service_name= con.read(); - - if (con.error() || service_name.is_null()) - { - ERROR_LOG(ERROR, ("Error reading initial packet")); - DBUG_RETURN(CR_ERROR); - } - DBUG_PRINT("info", ("Got initial packet of length %d", service_name.len())); - - // Create authentication handshake context using the given service name. - - Handshake_client hndshk(con, - service_name[0] ? (char *)service_name.ptr() : NULL, - service_name.len()); - if (hndshk.error()) - { - ERROR_LOG(ERROR, ("Could not create authentication handshake context")); - DBUG_RETURN(CR_ERROR); - } - - DBUG_ASSERT(!hndshk.error()); - - /* - Read and process packets from server until handshake is complete. - Note that the first read from server is dummy - (see Handshake_client::read_packet()) as we already have read the - first packet to establish service name. - */ - if (hndshk.packet_processing_loop()) - DBUG_RETURN(CR_ERROR); - - DBUG_ASSERT(!hndshk.error() && hndshk.is_complete()); - - DBUG_RETURN(CR_OK); -} diff --git a/libmysql/authentication_win/log_client.cc b/libmysql/authentication_win/log_client.cc deleted file mode 100644 index ec7210a8a97..00000000000 --- a/libmysql/authentication_win/log_client.cc +++ /dev/null @@ -1,65 +0,0 @@ -/* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - 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. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ - -#include <my_global.h> -#include "common.h" - - -// Client-side logging function - -void error_log_vprint(error_log_level::type level, - const char *fmt, va_list args) -{ - const char *level_string= ""; - int log_level= get_log_level(); - - switch (level) - { - case error_log_level::INFO: - if (3 > log_level) - return; - level_string= "Note"; - break; - case error_log_level::WARNING: - if (2 > log_level) - return; - level_string= "Warning"; - break; - case error_log_level::ERROR: - if (1 > log_level) - return; - level_string= "ERROR"; - break; - } - - fprintf(stderr, "Windows Authentication Plugin %s: ", level_string); - vfprintf(stderr, fmt, args); - fputc('\n', stderr); - fflush(stderr); -} - - -// Trivial implementation of log-level setting storage. - -void set_log_level(unsigned int level) -{ - opt_auth_win_log_level= level; -} - - -unsigned int get_log_level(void) -{ - return opt_auth_win_log_level; -} diff --git a/libmysql/authentication_win/plugin_client.cc b/libmysql/authentication_win/plugin_client.cc deleted file mode 100644 index c7dcb92e62d..00000000000 --- a/libmysql/authentication_win/plugin_client.cc +++ /dev/null @@ -1,68 +0,0 @@ -/* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - 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. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ - -#include <my_global.h> -#include <mysql.h> -#include <mysql/plugin_auth.h> -#include <mysql/client_plugin.h> - -#include "common.h" - -/* - The following MS C++ specific pragma embeds a comment in the resulting - object file. A "lib" comment tells the linker to use the specified - library, thus the dependency is handled automagically. -*/ - -#ifdef _MSC_VER -#pragma comment(lib, "Secur32") -#endif - -static int win_auth_client_plugin_init(char*, size_t, int, va_list) -{ - return 0; -} - - -static int win_auth_client_plugin_deinit() -{ - return 0; -} - - -int win_auth_handshake_client(MYSQL_PLUGIN_VIO *vio, MYSQL *mysql); - - -/* - Client plugin declaration. This is added to mysql_client_builtins[] - in sql-common/client.c -*/ - -extern "C" -st_mysql_client_plugin_AUTHENTICATION win_auth_client_plugin= -{ - MYSQL_CLIENT_AUTHENTICATION_PLUGIN, - MYSQL_CLIENT_AUTHENTICATION_PLUGIN_INTERFACE_VERSION, - "authentication_windows_client", - "Rafal Somla", - "Windows Authentication Plugin - client side", - {0,1,0}, - "GPL", - NULL, - win_auth_client_plugin_init, - win_auth_client_plugin_deinit, - NULL, // option handling - win_auth_handshake_client -}; diff --git a/libmysql/get_password.c b/libmysql/get_password.c index 55b7bf41cee..e704aec8337 100644 --- a/libmysql/get_password.c +++ b/libmysql/get_password.c @@ -26,10 +26,6 @@ #include <m_string.h> #include <m_ctype.h> -#if defined(HAVE_BROKEN_GETPASS) && !defined(HAVE_GETPASSPHRASE) -#undef HAVE_GETPASS -#endif - #ifdef HAVE_GETPASS #ifdef HAVE_PWD_H #include <pwd.h> @@ -64,18 +60,38 @@ #if defined(__WIN__) /* were just going to fake it here and get input from the keyboard */ -char *get_tty_password(const char *opt_message) +void get_tty_password_buff(const char *opt_message, char *to, size_t length) { - char to[80]; - char *pos=to,*end=to+sizeof(to)-1; + HANDLE consoleinput; + DWORD oldstate; + char *pos=to,*end=to+length-1; int i=0; - DBUG_ENTER("get_tty_password"); + + consoleinput= CreateFile("CONIN$", GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ , + NULL, OPEN_EXISTING, 0, NULL); + if (consoleinput == NULL || consoleinput == INVALID_HANDLE_VALUE) + { + /* This is a GUI application or service without console input, bail out. */ + *to= 0; + return; + } _cputs(opt_message ? opt_message : "Enter password: "); + + /* + Switch to raw mode (no line input, no echo input). + Allow Ctrl-C handler with ENABLE_PROCESSED_INPUT. + */ + GetConsoleMode(consoleinput, &oldstate); + SetConsoleMode(consoleinput, ENABLE_PROCESSED_INPUT); for (;;) { char tmp; - tmp=_getch(); - if (tmp == '\b' || (int) tmp == 127) + DWORD chars_read; + if (!ReadConsole(consoleinput, &tmp, 1, &chars_read, NULL)) + break; + if (chars_read == 0) + break; + if (tmp == '\b' || tmp == 127) { if (pos != to) { @@ -84,18 +100,18 @@ char *get_tty_password(const char *opt_message) continue; } } - if (tmp == '\n' || tmp == '\r' || tmp == 3) + if (tmp == '\n' || tmp == '\r') break; if (iscntrl(tmp) || pos == end) continue; _cputs("*"); *(pos++) = tmp; } - while (pos != to && isspace(pos[-1]) == ' ') - pos--; /* Allow dummy space at end */ + /* Reset console mode after password input. */ + SetConsoleMode(consoleinput, oldstate); + CloseHandle(consoleinput); *pos=0; _cputs("\n"); - DBUG_RETURN(my_strdup(to,MYF(MY_FAE))); } #else @@ -140,30 +156,25 @@ static void get_password(char *to,uint length,int fd, my_bool echo) } *(pos++) = tmp; } - while (pos != to && isspace(pos[-1]) == ' ') - pos--; /* Allow dummy space at end */ *pos=0; return; } #endif /* ! HAVE_GETPASS */ -char *get_tty_password(const char *opt_message) +void get_tty_password_buff(const char *opt_message, char *buff, size_t buflen) { #ifdef HAVE_GETPASS char *passbuff; #else /* ! HAVE_GETPASS */ TERMIO org,tmp; #endif /* HAVE_GETPASS */ - char buff[80]; - - DBUG_ENTER("get_tty_password"); #ifdef HAVE_GETPASS passbuff = getpass(opt_message ? opt_message : "Enter password: "); /* copy the password to buff and clear original (static) buffer */ - strnmov(buff, passbuff, sizeof(buff) - 1); + strncpy(buff, passbuff, buflen - 1); #ifdef _PASSWORD_LEN memset(passbuff, 0, _PASSWORD_LEN); #endif @@ -180,7 +191,7 @@ char *get_tty_password(const char *opt_message) tmp.c_cc[VMIN] = 1; tmp.c_cc[VTIME] = 0; tcsetattr(fileno(stdin), TCSADRAIN, &tmp); - get_password(buff, sizeof(buff)-1, fileno(stdin), isatty(fileno(stdout))); + get_password(buff, buflen, fileno(stdin), isatty(fileno(stdout))); tcsetattr(fileno(stdin), TCSADRAIN, &org); #elif defined(HAVE_TERMIO_H) ioctl(fileno(stdin), (int) TCGETA, &org); @@ -189,7 +200,7 @@ char *get_tty_password(const char *opt_message) tmp.c_cc[VMIN] = 1; tmp.c_cc[VTIME]= 0; ioctl(fileno(stdin),(int) TCSETA, &tmp); - get_password(buff,sizeof(buff)-1,fileno(stdin),isatty(fileno(stdout))); + get_password(buff,buflen-1,fileno(stdin),isatty(fileno(stdout))); ioctl(fileno(stdin),(int) TCSETA, &org); #else gtty(fileno(stdin), &org); @@ -197,13 +208,20 @@ char *get_tty_password(const char *opt_message) tmp.sg_flags &= ~ECHO; tmp.sg_flags |= RAW; stty(fileno(stdin), &tmp); - get_password(buff,sizeof(buff)-1,fileno(stdin),isatty(fileno(stdout))); + get_password(buff,buflen-1,fileno(stdin),isatty(fileno(stdout))); stty(fileno(stdin), &org); #endif if (isatty(fileno(stdout))) fputc('\n',stdout); #endif /* HAVE_GETPASS */ - - DBUG_RETURN(my_strdup(buff,MYF(MY_FAE))); } #endif /*__WIN__*/ + +#ifndef MYSQL_DYNAMIC_PLUGIN +char *get_tty_password(const char *opt_message) +{ + char buff[80]; + get_tty_password_buff(opt_message, buff, sizeof(buff)); + return my_strdup(buff, MYF(MY_FAE)); +} +#endif diff --git a/libmysql/libmysql.c b/libmysql/libmysql.c index d6bdea3df1f..e66a757424e 100644 --- a/libmysql/libmysql.c +++ b/libmysql/libmysql.c @@ -1,11 +1,13 @@ -/* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. +/* Copyright (c) 2000, 2013, Oracle and/or its affiliates + Copyright (c) 2009, 2013, Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation. There are special exceptions to the terms and conditions of the GPL as it - is applied to this software. + is applied to this software. View the full text of the exception in file + EXCEPTIONS-CLIENT in the directory of this software distribution. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -202,22 +204,30 @@ void STDCALL mysql_server_end() mysql_client_plugin_deinit(); + finish_client_errs(); + vio_end(); #ifdef EMBEDDED_LIBRARY end_embedded_server(); #endif - finish_client_errs(); - vio_end(); /* If library called my_init(), free memory allocated by it */ if (!org_my_init_done) { my_end(0); } +#ifdef NOT_NEEDED + /* + The following is not needed as if the program explicitely called + my_init() then we can assume it will also call my_end(). + The reason to not also do it here is in that case we can't get + statistics from my_end() to debug log. + */ else { free_charsets(); mysql_thread_end(); } +#endif mysql_client_init= org_my_init_done= 0; } @@ -980,6 +990,19 @@ mysql_get_server_info(MYSQL *mysql) } +my_bool STDCALL mariadb_connection(MYSQL *mysql) +{ + return (strstr(mysql->server_version, "MariaDB") || + strstr(mysql->server_version, "-maria-")); +} + +const char * STDCALL +mysql_get_server_name(MYSQL *mysql) +{ + return mariadb_connection(mysql) ? "MariaDB" : "MySQL"; +} + + const char * STDCALL mysql_get_host_info(MYSQL *mysql) { @@ -3177,7 +3200,7 @@ static void fetch_string_with_conversion(MYSQL_BIND *param, char *value, case MYSQL_TYPE_TIME: { MYSQL_TIME *tm= (MYSQL_TIME *)buffer; - str_to_time(value, length, tm, &err); + str_to_time(value, length, tm, 0, &err); *param->error= test(err); break; } @@ -3186,7 +3209,7 @@ static void fetch_string_with_conversion(MYSQL_BIND *param, char *value, case MYSQL_TYPE_TIMESTAMP: { MYSQL_TIME *tm= (MYSQL_TIME *)buffer; - (void) str_to_datetime(value, length, tm, TIME_FUZZY_DATE, &err); + (void) str_to_datetime(value, length, tm, 0, &err); *param->error= test(err) && (param->buffer_type == MYSQL_TYPE_DATE && tm->time_type != MYSQL_TIMESTAMP_DATE); break; @@ -3309,8 +3332,7 @@ static void fetch_long_with_conversion(MYSQL_BIND *param, MYSQL_FIELD *field, case MYSQL_TYPE_DATETIME: { int error; - value= number_to_datetime(value, (MYSQL_TIME *) buffer, TIME_FUZZY_DATE, - &error); + value= number_to_datetime(value, 0, (MYSQL_TIME *) buffer, 0, &error); *param->error= test(error); break; } @@ -3515,7 +3537,7 @@ static void fetch_datetime_with_conversion(MYSQL_BIND *param, fetch_string_with_conversion: */ char buff[MAX_DATE_STRING_REP_LENGTH]; - uint length= my_TIME_to_str(my_time, buff); + uint length= my_TIME_to_str(my_time, buff, field->decimals); /* Resort to string conversion */ fetch_string_with_conversion(param, (char *)buff, length); break; @@ -3992,7 +4014,7 @@ static my_bool setup_one_fetch_function(MYSQL_BIND *param, MYSQL_FIELD *field) field->max_length= MAX_DOUBLE_STRING_REP_LENGTH; break; case MYSQL_TYPE_TIME: - field->max_length= 15; /* 19:23:48.123456 */ + field->max_length= 17; /* -819:23:48.123456 */ param->skip_result= skip_result_with_length; break; case MYSQL_TYPE_DATE: diff --git a/libmysql/libmysql.def b/libmysql/libmysql.def index ce85d2a4086..5a6bee4919f 100644 --- a/libmysql/libmysql.def +++ b/libmysql/libmysql.def @@ -104,3 +104,4 @@ EXPORTS mysql_server_end mysql_set_character_set mysql_get_character_set_info + mysql_get_server_name diff --git a/libmysql/libmysql_rpm_version.in b/libmysql/libmysql_rpm_version.in new file mode 100644 index 00000000000..ff0707cdb75 --- /dev/null +++ b/libmysql/libmysql_rpm_version.in @@ -0,0 +1,62 @@ +# This version script is heavily inspired by Fedora's and Mageia's version scripts for +# MySQL client shared library. It is used in MariaDB for building RPMs. + +libmysqlclient_16 { + global: +@CLIENT_API_5_1_LIST@ + +# some stuff from Mageia, I have no idea why it is there +# But too afraid to throw anything away + _fini; + _init; + my_init; + my_progname; + myodbc_remove_escape; + +# These are documented in Paul DuBois' MySQL book, so we treat them as part +# of the de-facto API. + free_defaults; + handle_options; + load_defaults; + my_print_help; +# pure-ftpd requires this + my_make_scrambled_password; +# fedora18 export + THR_KEY_mysys; +# hydra requires this + scramble; +# DBD::mysql requires this + is_prefix; + local: + *; +}; + +libmysqlclient_18 { + global: + @CLIENT_API_5_5_LIST@ +# +# Ideally the following symbols wouldn't be exported, but various applications +# require them. Fedora limits the namespace damage by prefixing mysql_ +# (see mysql-dubious-exports.patch), which means the symbols are not present +# in libmysqlclient_16. +# +# MariaDB does not do the Fedora-style function renaming via #define in headers, +# however it exports mysql_ prefixed symbols in addition to the "normal" ones. +# +# To ensure successful recompilation of affected projects, as well as drop-in replacement +# for MySQL libraries, provided by distribution, both original symbols and their mysql_ +# prefixed counterparts have to be exported. + +# mysql-connector-odbc requires these + mysql_default_charset_info; + mysql_get_charset; + mysql_get_charset_by_csname; + mysql_net_realloc; + default_charset_info; + get_charset; + get_charset_by_csname; + net_realloc; +# PHP's mysqli.so requires this (via the ER() macro) + mysql_client_errors; + client_errors; +}; diff --git a/libmysql/rpm_support.cc b/libmysql/rpm_support.cc new file mode 100644 index 00000000000..8c9a1e8683d --- /dev/null +++ b/libmysql/rpm_support.cc @@ -0,0 +1,41 @@ +/* + Provide aliases for several symbols, to support drop-in replacement for + MariaDB on Fedora and several derives distributions. + + These distributions redefine several symbols (in a way that is no compatible + with either MySQL or MariaDB) and export it from the client library ( as seen + e.g from this patch) +http://lists.fedoraproject.org/pipermail/scm-commits/2010-December/537257.html + + MariaDB handles compatibility distribution by providing the same symbols from + the client library if it is built with -DRPM + +*/ +#include <errmsg.h> +#include <my_sys.h> +#include <mysql.h> +extern "C" { + +CHARSET_INFO *mysql_default_charset_info = default_charset_info; + +CHARSET_INFO *mysql_get_charset(uint cs_number, myf flags) +{ + return get_charset(cs_number, flags); +} + +CHARSET_INFO *mysql_get_charset_by_csname(const char *cs_name, + uint cs_flags, myf my_flags) +{ + return get_charset_by_csname(cs_name, cs_flags, my_flags); +} + + +my_bool mysql_net_realloc(NET *net, size_t length) +{ + return net_realloc(net,length); +} + +const char **mysql_client_errors = client_errors; + +} /*extern "C" */ + |