diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-05-04 18:07:14 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-05-04 18:07:14 +0000 |
commit | a175314c3e5827eb193872241446f2f8f5c9d33c (patch) | |
tree | cd3d60ca99ae00829c52a6ca79150a5b6e62528b /sql-common | |
parent | Initial commit. (diff) | |
download | mariadb-10.5-upstream/1%10.5.12.tar.xz mariadb-10.5-upstream/1%10.5.12.zip |
Adding upstream version 1:10.5.12.upstream/1%10.5.12upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'sql-common')
-rw-r--r-- | sql-common/client.c | 4348 | ||||
-rw-r--r-- | sql-common/client_plugin.c | 511 | ||||
-rw-r--r-- | sql-common/conf_to_src.c | 144 | ||||
-rw-r--r-- | sql-common/errmsg.c | 130 | ||||
-rw-r--r-- | sql-common/my_time.c | 2022 | ||||
-rw-r--r-- | sql-common/my_user.c | 70 | ||||
-rw-r--r-- | sql-common/mysql_async.c | 1995 | ||||
-rw-r--r-- | sql-common/pack.c | 210 |
8 files changed, 9430 insertions, 0 deletions
diff --git a/sql-common/client.c b/sql-common/client.c new file mode 100644 index 00000000..f314c039 --- /dev/null +++ b/sql-common/client.c @@ -0,0 +1,4348 @@ +/* Copyright (c) 2003, 2016, Oracle and/or its affiliates. + Copyright (c) 2009, 2020, MariaDB + + 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-1335 USA */ + +/* + This file is included by both libmysql.c (the MySQL client C API) + and the mysqld server to connect to another MYSQL server. + + The differences for the two cases are: + + - Things that only works for the client: + - Trying to automaticly determinate user name if not supplied to + mysql_real_connect() + - Support for reading local file with LOAD DATA LOCAL + - SHARED memory handling + - Prepared statements + + - Things that only works for the server + - Alarm handling on connect + + In all other cases, the code should be idential for the client and + server. +*/ + +#include <my_global.h> +#include <my_default.h> +#include "mysql.h" +#include "hash.h" + +/* Remove client convenience wrappers */ +#undef max_allowed_packet +#undef net_buffer_length + +#ifdef EMBEDDED_LIBRARY + +#undef MYSQL_SERVER + +#ifndef MYSQL_CLIENT +#define MYSQL_CLIENT +#endif + +#define CLI_MYSQL_REAL_CONNECT STDCALL cli_mysql_real_connect + +#undef net_flush +my_bool net_flush(NET *net); + +#else /*EMBEDDED_LIBRARY*/ +#define CLI_MYSQL_REAL_CONNECT STDCALL mysql_real_connect +#endif /*EMBEDDED_LIBRARY*/ + +#include <my_sys.h> +#include <mysys_err.h> +#include <m_string.h> +#include <m_ctype.h> +#include "mysql_version.h" +#include "mysqld_error.h" +#include "errmsg.h" +#include <violite.h> + +#if !defined(_WIN32) +#include <my_pthread.h> /* because of signal() */ +#endif /* !defined(_WIN32) */ + +#include <sys/stat.h> +#include <signal.h> +#include <time.h> + +#ifdef HAVE_PWD_H +#include <pwd.h> +#endif + +#if !defined(_WIN32) +#ifdef HAVE_SELECT_H +# include <select.h> +#endif +#ifdef HAVE_SYS_SELECT_H +#include <sys/select.h> +#endif +#endif /* !defined(_WIN32) */ +#ifdef HAVE_SYS_UN_H +# include <sys/un.h> +#endif + + +#define CONNECT_TIMEOUT 0 + +#include "client_settings.h" +#include <ssl_compat.h> +#include <sql_common.h> +#include <mysql/client_plugin.h> +#include <my_context.h> +#include <mysql_async.h> + +typedef enum { + ALWAYS_ACCEPT, /* heuristics is disabled, use CLIENT_LOCAL_FILES */ + WAIT_FOR_QUERY, /* heuristics is enabled, not sending files */ + ACCEPT_FILE_REQUEST /* heuristics is enabled, ready to send a file */ +} auto_local_infile_state; + +#define native_password_plugin_name "mysql_native_password" +#define old_password_plugin_name "mysql_old_password" + +PSI_memory_key key_memory_mysql_options; +PSI_memory_key key_memory_MYSQL_DATA; +PSI_memory_key key_memory_MYSQL; +PSI_memory_key key_memory_MYSQL_RES; +PSI_memory_key key_memory_MYSQL_ROW; +PSI_memory_key key_memory_MYSQL_state_change_info; +PSI_memory_key key_memory_MYSQL_HANDSHAKE; + +#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY) +PSI_memory_key key_memory_create_shared_memory; +#endif /* _WIN32 && ! EMBEDDED_LIBRARY */ + +#ifdef HAVE_PSI_INTERFACE +/* + This code is common to the client and server, + and also used in the server when server A connects to server B, + for example with replication. + Therefore, the code is also instrumented. +*/ + +static PSI_memory_info all_client_memory[]= +{ +#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY) + { &key_memory_create_shared_memory, "create_shared_memory", 0}, +#endif /* _WIN32 && ! EMBEDDED_LIBRARY */ + + { &key_memory_mysql_options, "mysql_options", 0}, + { &key_memory_MYSQL_DATA, "MYSQL_DATA", 0}, + { &key_memory_MYSQL, "MYSQL", 0}, + { &key_memory_MYSQL_RES, "MYSQL_RES", 0}, + { &key_memory_MYSQL_ROW, "MYSQL_ROW", 0}, + { &key_memory_MYSQL_state_change_info, "MYSQL_STATE_CHANGE_INFO", 0}, + { &key_memory_MYSQL_HANDSHAKE, "MYSQL_HANDSHAKE", 0} +}; + +void init_client_psi_keys(void) +{ + const char *category= "client"; + int count; + + count= array_elements(all_client_memory); + mysql_memory_register(category, all_client_memory, count); +} + +#endif /* HAVE_PSI_INTERFACE */ + +uint mariadb_deinitialize_ssl= 1; +uint mysql_port=0; +char *mysql_unix_port= 0; +const char *unknown_sqlstate= "HY000"; +const char *not_error_sqlstate= "00000"; +const char *cant_connect_sqlstate= "08001"; + +static void mysql_close_free_options(MYSQL *mysql); +static void mysql_close_free(MYSQL *mysql); +static void mysql_prune_stmt_list(MYSQL *mysql); +static int cli_report_progress(MYSQL *mysql, char *packet, uint length); + +CHARSET_INFO *default_client_charset_info = &my_charset_latin1; + +/* Server error code and message */ +unsigned int mysql_server_last_errno; +char mysql_server_last_error[MYSQL_ERRMSG_SIZE]; + +/** + Convert the connect timeout option to a timeout value for VIO + functions (vio_socket_connect() and vio_io_wait()). + + @param mysql Connection handle (client side). + + @return The timeout value in milliseconds, or -1 if no timeout. +*/ + +static int get_vio_connect_timeout(MYSQL *mysql) +{ + int timeout_ms; + uint timeout_sec; + + /* + A timeout of 0 means no timeout. Also, the connect_timeout + option value is in seconds, while VIO timeouts are measured + in milliseconds. Hence, check for a possible overflow. In + case of overflow, set to no timeout. + */ + timeout_sec= mysql->options.connect_timeout; + + if (!timeout_sec || (timeout_sec > INT_MAX/1000)) + timeout_ms= -1; + else + timeout_ms= (int) (timeout_sec * 1000); + + return timeout_ms; +} + + +/** + Set the internal error message to mysql handler + + @param mysql connection handle (client side) + @param errcode CR_ error code, passed to ER macro to get + error text + @parma sqlstate SQL standard sqlstate +*/ + +void set_mysql_error(MYSQL *mysql, int errcode, const char *sqlstate) +{ + NET *net; + DBUG_ENTER("set_mysql_error"); + DBUG_PRINT("enter", ("error :%d '%s'", errcode, ER(errcode))); + DBUG_ASSERT(mysql != 0); + + if (mysql) + { + net= &mysql->net; + net->last_errno= errcode; + strmov(net->last_error, ER(errcode)); + strmov(net->sqlstate, sqlstate); + } + else + { + mysql_server_last_errno= errcode; + strmov(mysql_server_last_error, ER(errcode)); + } + DBUG_VOID_RETURN; +} + +/** + Clear possible error state of struct NET + + @param net clear the state of the argument +*/ + +void net_clear_error(NET *net) +{ + net->last_errno= 0; + net->last_error[0]= '\0'; + strmov(net->sqlstate, not_error_sqlstate); +} + +/** + Set an error message on the client. + + @param mysql connection handle + @param errcode CR_* errcode, for client errors + @param sqlstate SQL standard sql state, unknown_sqlstate for the + majority of client errors. + @param format error message template, in sprintf format + @param ... variable number of arguments +*/ + +void set_mysql_extended_error(MYSQL *mysql, int errcode, + const char *sqlstate, + const char *format, ...) +{ + NET *net; + va_list args; + DBUG_ENTER("set_mysql_extended_error"); + DBUG_PRINT("enter", ("error :%d '%s'", errcode, format)); + DBUG_ASSERT(mysql != 0); + + net= &mysql->net; + net->last_errno= errcode; + va_start(args, format); + my_vsnprintf(net->last_error, sizeof(net->last_error)-1, + format, args); + va_end(args); + strmov(net->sqlstate, sqlstate); + + DBUG_VOID_RETURN; +} + + + +/* + Create a named pipe connection +*/ + +#ifdef _WIN32 + +HANDLE create_named_pipe(MYSQL *mysql, uint connect_timeout, char **arg_host, + char **arg_unix_socket) +{ + HANDLE hPipe=INVALID_HANDLE_VALUE; + char pipe_name[1024]; + DWORD dwMode; + int i; + char *host= *arg_host, *unix_socket= *arg_unix_socket; + + if ( ! unix_socket || (unix_socket)[0] == 0x00) + unix_socket = mysql_unix_port; + if (!host || !strcmp(host,LOCAL_HOST)) + host=LOCAL_HOST_NAMEDPIPE; + + + pipe_name[sizeof(pipe_name)-1]= 0; /* Safety if too long string */ + strxnmov(pipe_name, sizeof(pipe_name)-1, "\\\\", host, "\\pipe\\", + unix_socket, NullS); + DBUG_PRINT("info",("Server name: '%s'. Named Pipe: %s", host, unix_socket)); + + for (i=0 ; i < 100 ; i++) /* Don't retry forever */ + { + if ((hPipe = CreateFile(pipe_name, + GENERIC_READ | GENERIC_WRITE, + 0, + NULL, + OPEN_EXISTING, + FILE_FLAG_OVERLAPPED, + NULL )) != INVALID_HANDLE_VALUE) + break; + if (GetLastError() != ERROR_PIPE_BUSY) + { + set_mysql_extended_error(mysql, CR_NAMEDPIPEOPEN_ERROR, + unknown_sqlstate, ER(CR_NAMEDPIPEOPEN_ERROR), + host, unix_socket, (ulong) GetLastError()); + return INVALID_HANDLE_VALUE; + } + /* wait for for an other instance */ + if (! WaitNamedPipe(pipe_name, connect_timeout*1000) ) + { + set_mysql_extended_error(mysql, CR_NAMEDPIPEWAIT_ERROR, unknown_sqlstate, + ER(CR_NAMEDPIPEWAIT_ERROR), + host, unix_socket, (ulong) GetLastError()); + return INVALID_HANDLE_VALUE; + } + } + if (hPipe == INVALID_HANDLE_VALUE) + { + set_mysql_extended_error(mysql, CR_NAMEDPIPEOPEN_ERROR, unknown_sqlstate, + ER(CR_NAMEDPIPEOPEN_ERROR), host, unix_socket, + (ulong) GetLastError()); + return INVALID_HANDLE_VALUE; + } + dwMode = PIPE_READMODE_BYTE | PIPE_WAIT; + if ( !SetNamedPipeHandleState(hPipe, &dwMode, NULL, NULL) ) + { + CloseHandle( hPipe ); + set_mysql_extended_error(mysql, CR_NAMEDPIPESETSTATE_ERROR, + unknown_sqlstate, ER(CR_NAMEDPIPESETSTATE_ERROR), + host, unix_socket, (ulong) GetLastError()); + return INVALID_HANDLE_VALUE; + } + *arg_host=host ; *arg_unix_socket=unix_socket; /* connect arg */ + return (hPipe); +} +#endif + + +/** + Read a packet from server. Give error message if socket was down + or packet is an error message + + @retval packet_error An error occurred during reading. + Error message is set. + @retval +*/ +ulong +cli_safe_read(MYSQL *mysql) +{ + ulong reallen = 0; + return cli_safe_read_reallen(mysql, &reallen); +} + +ulong +cli_safe_read_reallen(MYSQL *mysql, ulong* reallen) +{ + NET *net= &mysql->net; + ulong len=0; + +restart: + if (net->vio != 0) + len= my_net_read_packet_reallen(net, 0, reallen); + + if (len == packet_error || len == 0) + { + DBUG_PRINT("error",("Wrong connection or packet. fd: %s len: %lu", + net->vio ? vio_description(net->vio) : NULL, len)); +#ifdef MYSQL_SERVER + if (net->vio && (net->last_errno == ER_NET_READ_INTERRUPTED)) + return (packet_error); +#endif /*MYSQL_SERVER*/ + end_server(mysql); + set_mysql_error(mysql, net->last_errno == ER_NET_PACKET_TOO_LARGE ? + CR_NET_PACKET_TOO_LARGE: CR_SERVER_LOST, unknown_sqlstate); + return (packet_error); + } + if (net->read_pos[0] == 255) + { + if (len > 3) + { + char *pos= (char*) net->read_pos+1; + uint last_errno=uint2korr(pos); + + if (last_errno == 65535 && + (mysql->server_capabilities & CLIENT_PROGRESS_OBSOLETE)) + { + if (cli_report_progress(mysql, pos+2, (uint) (len-3))) + { + /* Wrong packet */ + set_mysql_error(mysql, CR_MALFORMED_PACKET, unknown_sqlstate); + return (packet_error); + } + goto restart; + } + net->last_errno= last_errno; + + pos+=2; + len-=2; + if (protocol_41(mysql) && pos[0] == '#') + { + strmake_buf(net->sqlstate, pos+1); + pos+= SQLSTATE_LENGTH+1; + } + else + { + /* + The SQL state hasn't been received -- it should be reset to HY000 + (unknown error sql state). + */ + + strmov(net->sqlstate, unknown_sqlstate); + } + + (void) strmake(net->last_error,(char*) pos, + MY_MIN((uint) len,(uint) sizeof(net->last_error)-1)); + } + else + set_mysql_error(mysql, CR_UNKNOWN_ERROR, unknown_sqlstate); + /* + Cover a protocol design error: error packet does not + contain the server status. Therefore, the client has no way + to find out whether there are more result sets of + a multiple-result-set statement pending. Luckily, in 5.0 an + error always aborts execution of a statement, wherever it is + a multi-statement or a stored procedure, so it should be + safe to unconditionally turn off the flag here. + */ + mysql->server_status&= ~SERVER_MORE_RESULTS_EXISTS; + + DBUG_PRINT("error",("Got error: %d/%s (%s)", + net->last_errno, + net->sqlstate, + net->last_error)); + return(packet_error); + } + return len; +} + +void free_rows(MYSQL_DATA *cur) +{ + if (cur) + { + free_root(&cur->alloc,MYF(0)); + my_free(cur); + } +} + +my_bool +cli_advanced_command(MYSQL *mysql, enum enum_server_command command, + const uchar *header, ulong header_length, + const uchar *arg, ulong arg_length, my_bool skip_check, + MYSQL_STMT *stmt) +{ + NET *net= &mysql->net; + my_bool result= 1; + my_bool stmt_skip= stmt ? stmt->state != MYSQL_STMT_INIT_DONE : FALSE; + DBUG_ENTER("cli_advanced_command"); + + if (mysql->net.vio == 0) + { /* Do reconnect if possible */ + if (mysql_reconnect(mysql) || stmt_skip) + DBUG_RETURN(1); + } + if (mysql->status != MYSQL_STATUS_READY || + mysql->server_status & SERVER_MORE_RESULTS_EXISTS) + { + DBUG_PRINT("error",("state: %d", mysql->status)); + set_mysql_error(mysql, CR_COMMANDS_OUT_OF_SYNC, unknown_sqlstate); + DBUG_RETURN(1); + } + + net_clear_error(net); + mysql->info=0; + mysql->affected_rows= ~(my_ulonglong) 0; + /* + We don't want to clear the protocol buffer on COM_QUIT, because if + the previous command was a shutdown command, we may have the + response for the COM_QUIT already in the communication buffer + */ + net_clear(&mysql->net, (command != COM_QUIT)); + + if (net_write_command(net,(uchar) command, header, header_length, + arg, arg_length)) + { + DBUG_PRINT("error",("Can't send command to server. Error: %d", + socket_errno)); + if (net->last_errno == ER_NET_PACKET_TOO_LARGE) + { + set_mysql_error(mysql, CR_NET_PACKET_TOO_LARGE, unknown_sqlstate); + goto end; + } + if (net->last_errno == ER_NET_ERROR_ON_WRITE && command == COM_BINLOG_DUMP) + goto end; + end_server(mysql); + if (mysql_reconnect(mysql) || stmt_skip) + goto end; + if (net_write_command(net,(uchar) command, header, header_length, + arg, arg_length)) + { + set_mysql_error(mysql, CR_SERVER_GONE_ERROR, unknown_sqlstate); + goto end; + } + } + result=0; + if (!skip_check) + result= ((mysql->packet_length=cli_safe_read(mysql)) == packet_error ? + 1 : 0); +end: + DBUG_PRINT("exit",("result: %d", result)); + DBUG_RETURN(result); +} + +void free_old_query(MYSQL *mysql) +{ + DBUG_ENTER("free_old_query"); + if (mysql->fields) + free_root(&mysql->field_alloc,MYF(0)); + /* Assume rowlength < 8192 */ + init_alloc_root(PSI_INSTRUMENT_ME, &mysql->field_alloc, 8192, 0, + MYF(mysql->options.use_thread_specific_memory ? + MY_THREAD_SPECIFIC : 0)); + mysql->fields= 0; + mysql->field_count= 0; /* For API */ + mysql->warning_count= 0; + mysql->info= 0; + DBUG_VOID_RETURN; +} + + +/** + Finish reading of a partial result set from the server. + Get the EOF packet, and update mysql->status + and mysql->warning_count. + + @return TRUE if a communication or protocol error, an error + is set in this case, FALSE otherwise. +*/ + +my_bool flush_one_result(MYSQL *mysql) +{ + ulong packet_length; + + DBUG_ASSERT(mysql->status != MYSQL_STATUS_READY); + + do + { + packet_length= cli_safe_read(mysql); + /* + There is an error reading from the connection, + or (sic!) there were no error and no + data in the stream, i.e. no more data from the server. + Since we know our position in the stream (somewhere in + the middle of a result set), this latter case is an error too + -- each result set must end with a EOF packet. + cli_safe_read() has set an error for us, just return. + */ + if (packet_length == packet_error) + return TRUE; + } + while (packet_length > 8 || mysql->net.read_pos[0] != 254); + + /* Analyze EOF packet of the result set. */ + + if (protocol_41(mysql)) + { + char *pos= (char*) mysql->net.read_pos + 1; + mysql->warning_count=uint2korr(pos); + pos+=2; + mysql->server_status=uint2korr(pos); + pos+=2; + } + return FALSE; +} + + +/** + Read a packet from network. If it's an OK packet, flush it. + + @return TRUE if error, FALSE otherwise. In case of + success, is_ok_packet is set to TRUE or FALSE, + based on what we got from network. +*/ + +my_bool opt_flush_ok_packet(MYSQL *mysql, my_bool *is_ok_packet) +{ + ulong packet_length= cli_safe_read(mysql); + + if (packet_length == packet_error) + return TRUE; + + /* cli_safe_read always reads a non-empty packet. */ + DBUG_ASSERT(packet_length); + + *is_ok_packet= mysql->net.read_pos[0] == 0; + if (*is_ok_packet) + { + uchar *pos= mysql->net.read_pos + 1; + + net_field_length_ll(&pos); /* affected rows */ + net_field_length_ll(&pos); /* insert id */ + + mysql->server_status=uint2korr(pos); + pos+=2; + + if (protocol_41(mysql)) + { + mysql->warning_count=uint2korr(pos); + pos+=2; + } + } + return FALSE; +} + + +/* + Flush result set sent from server +*/ + +static void cli_flush_use_result(MYSQL *mysql, my_bool flush_all_results) +{ + /* Clear the current execution status */ + DBUG_ENTER("cli_flush_use_result"); + DBUG_PRINT("warning",("Not all packets read, clearing them")); + + if (flush_one_result(mysql)) + DBUG_VOID_RETURN; /* An error occurred */ + + if (! flush_all_results) + DBUG_VOID_RETURN; + + while (mysql->server_status & SERVER_MORE_RESULTS_EXISTS) + { + my_bool is_ok_packet; + if (opt_flush_ok_packet(mysql, &is_ok_packet)) + DBUG_VOID_RETURN; /* An error occurred. */ + if (is_ok_packet) + { + /* + Indeed what we got from network was an OK packet, and we + know that OK is the last one in a multi-result-set, so + just return. + */ + DBUG_VOID_RETURN; + } + /* + It's a result set, not an OK packet. A result set contains + of two result set subsequences: field metadata, terminated + with EOF packet, and result set data, again terminated with + EOF packet. Read and flush them. + */ + if (flush_one_result(mysql) || flush_one_result(mysql)) + DBUG_VOID_RETURN; /* An error occurred. */ + } + + DBUG_VOID_RETURN; +} + + +/* + Report progress to the client + + RETURN VALUES + 0 ok + 1 error +*/ + +static int cli_report_progress(MYSQL *mysql, char *pkt, uint length) +{ + uint stage, max_stage, proc_length; + double progress; + uchar *packet= (uchar*)pkt; + uchar *start= packet; + + if (length < 5) + return 1; /* Wrong packet */ + + if (!(mysql->options.extension && mysql->options.extension->report_progress)) + return 0; /* No callback, ignore packet */ + + packet++; /* Ignore number of strings */ + stage= (uint) *packet++; + max_stage= (uint) *packet++; + progress= uint3korr(packet)/1000.0; + packet+= 3; + proc_length= net_field_length(&packet); + if (packet + proc_length > start + length) + return 1; /* Wrong packet */ + (*mysql->options.extension->report_progress)(mysql, stage, max_stage, + progress, (char*) packet, + proc_length); + return 0; +} + + +/************************************************************************** + Shut down connection +**************************************************************************/ + +void end_server(MYSQL *mysql) +{ + int save_errno= errno; + DBUG_ENTER("end_server"); + if (mysql->net.vio != 0) + { + DBUG_PRINT("info",("Net: %s", vio_description(mysql->net.vio))); +#ifdef MYSQL_SERVER + slave_io_thread_detach_vio(); +#endif + vio_delete(mysql->net.vio); + mysql->net.vio= 0; /* Marker */ + mysql_prune_stmt_list(mysql); + } + net_end(&mysql->net); + free_old_query(mysql); + errno= save_errno; + DBUG_VOID_RETURN; +} + + +void STDCALL +mysql_free_result(MYSQL_RES *result) +{ + DBUG_ENTER("mysql_free_result"); + DBUG_PRINT("enter",("mysql_res: %p", result)); + if (result) + { + MYSQL *mysql= result->handle; + if (mysql) + { + if (mysql->unbuffered_fetch_owner == &result->unbuffered_fetch_cancelled) + mysql->unbuffered_fetch_owner= 0; + if (mysql->status == MYSQL_STATUS_USE_RESULT) + { + (*mysql->methods->flush_use_result)(mysql, FALSE); + mysql->status=MYSQL_STATUS_READY; + if (mysql->unbuffered_fetch_owner) + *mysql->unbuffered_fetch_owner= TRUE; + } + } + free_rows(result->data); + if (result->fields) + free_root(&result->field_alloc,MYF(0)); + my_free(result->row); + my_free(result); + } + DBUG_VOID_RETURN; +} + +/**************************************************************************** + Get options from my.cnf +****************************************************************************/ + +static const char *default_options[]= +{ + "port","socket","compress","password","pipe", "timeout", "user", + "init-command", "host", "database", "debug", "return-found-rows", + "ssl-key" ,"ssl-cert" ,"ssl-ca" ,"ssl-capath", + "character-sets-dir", "default-character-set", "interactive-timeout", + "connect-timeout", "local-infile", "disable-local-infile", + "ssl-cipher", "max-allowed-packet", "protocol", + "multi-results", "multi-statements", "multi-queries", "secure-auth", + "report-data-truncation", "plugin-dir", "default-auth", + "bind-address", "ssl-crl", "ssl-crlpath", + "enable-cleartext-plugin", + NullS +}; +enum option_id { + OPT_port=1, OPT_socket, OPT_compress, OPT_password, OPT_pipe, OPT_timeout, OPT_user, + OPT_init_command, OPT_host, OPT_database, OPT_debug, OPT_return_found_rows, + OPT_ssl_key, OPT_ssl_cert, OPT_ssl_ca, OPT_ssl_capath, + OPT_character_sets_dir, OPT_default_character_set, OPT_interactive_timeout, + OPT_connect_timeout, OPT_local_infile, OPT_disable_local_infile, + OPT_ssl_cipher, OPT_max_allowed_packet, OPT_protocol, + OPT_multi_results, OPT_multi_statements, OPT_multi_queries, OPT_secure_auth, + OPT_report_data_truncation, OPT_plugin_dir, OPT_default_auth, + OPT_bind_address, OPT_ssl_crl, OPT_ssl_crlpath, + OPT_enable_cleartext_plugin, + OPT_keep_this_one_last +}; + +static char *opt_strdup(const char *from, myf my_flags) +{ + return my_strdup(key_memory_mysql_options, from, my_flags); +} + +static TYPELIB option_types={array_elements(default_options)-1, + "options",default_options, NULL}; + +static int add_init_command(struct st_mysql_options *options, const char *cmd) +{ + char *tmp; + + if (!options->init_commands) + { + options->init_commands= (DYNAMIC_ARRAY*)my_malloc(key_memory_mysql_options, + sizeof(DYNAMIC_ARRAY), + MYF(MY_WME)); + my_init_dynamic_array(key_memory_mysql_options, options->init_commands, + sizeof(char*),5, 5, MYF(0)); + } + + if (!(tmp= opt_strdup(cmd,MYF(MY_WME))) || + insert_dynamic(options->init_commands, &tmp)) + { + my_free(tmp); + return 1; + } + + return 0; +} + + +#define ALLOCATE_EXTENSIONS(OPTS) \ + (OPTS)->extension= (struct st_mysql_options_extention *) \ + my_malloc(key_memory_mysql_options, \ + sizeof(struct st_mysql_options_extention), \ + MYF(MY_WME | MY_ZEROFILL)) \ + + +#define ENSURE_EXTENSIONS_PRESENT(OPTS) \ + do { \ + if (!(OPTS)->extension) \ + ALLOCATE_EXTENSIONS(OPTS); \ + } while (0) + + +#define EXTENSION_SET_STRING_X(OPTS, X, STR, dup) \ + do { \ + if ((OPTS)->extension) \ + my_free((OPTS)->extension->X); \ + else \ + ALLOCATE_EXTENSIONS(OPTS); \ + (OPTS)->extension->X= ((STR) != NULL) ? \ + dup((STR), MYF(MY_WME)) : NULL; \ + } while (0) + +#define EXTENSION_SET_STRING(OPTS, X, STR) \ + EXTENSION_SET_STRING_X(OPTS, X, STR, opt_strdup) + + +#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) +#define SET_SSL_OPTION_X(OPTS, opt_var, arg, dup) \ + my_free((OPTS)->opt_var); \ + (OPTS)->opt_var= arg ? dup(arg, MYF(MY_WME)) : NULL; +#define EXTENSION_SET_SSL_STRING_X(OPTS, X, STR, dup) \ + EXTENSION_SET_STRING_X((OPTS), X, (STR), dup); + +static char *set_ssl_option_unpack_path(const char *arg, myf flags) +{ + char buff[FN_REFLEN + 1]; + unpack_filename(buff, (char *)arg); + return opt_strdup(buff, flags); +} + +#else +#define SET_SSL_OPTION_X(OPTS, opt_var,arg, dup) do { } while(0) +#define EXTENSION_SET_SSL_STRING_X(OPTS, X, STR, dup) do { } while(0) +#endif /* defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) */ + +#define SET_SSL_OPTION(OPTS, opt_var,arg) SET_SSL_OPTION_X(OPTS, opt_var, arg, opt_strdup) +#define EXTENSION_SET_SSL_STRING(OPTS, X, STR) EXTENSION_SET_SSL_STRING_X(OPTS, X, STR, opt_strdup) +#define SET_SSL_PATH_OPTION(OPTS, opt_var,arg) SET_SSL_OPTION_X(OPTS, opt_var, arg, set_ssl_option_unpack_path) +#define EXTENSION_SET_SSL_PATH_STRING(OPTS, X, STR) EXTENSION_SET_SSL_STRING_X(OPTS, X, STR, set_ssl_option_unpack_path) + +void mysql_read_default_options(struct st_mysql_options *options, + const char *filename,const char *group) +{ + int argc; + char *argv_buff[1],**argv; + const char *groups[5]; + DBUG_ENTER("mysql_read_default_options"); + DBUG_PRINT("enter",("file: %s group: %s",filename,group ? group :"NULL")); + + compile_time_assert(OPT_keep_this_one_last == + array_elements(default_options)); + + argc=1; argv=argv_buff; argv_buff[0]= (char*) "client"; + groups[0]= (char*) "client"; + groups[1]= (char*) "client-server"; + groups[2]= (char*) "client-mariadb"; + groups[3]= (char*) group; + groups[4]=0; + + my_load_defaults(filename, groups, &argc, &argv, NULL); + if (argc != 1) /* If some default option */ + { + char **option=argv; + while (*++option) + { + /* DBUG_PRINT("info",("option: %s",option[0])); */ + if (option[0][0] == '-' && option[0][1] == '-') + { + char *end=strcend(*option,'='); + char *opt_arg=0; + if (*end) + { + opt_arg=end+1; + *end=0; /* Remove '=' */ + } + /* Change all '_' in variable name to '-' */ + for (end= *option ; *(end= strcend(end,'_')) ; ) + *end= '-'; + switch (find_type(*option + 2, &option_types, FIND_TYPE_BASIC)) { + case OPT_port: + if (opt_arg) + options->port=atoi(opt_arg); + break; + case OPT_socket: + if (opt_arg) + { + my_free(options->unix_socket); + options->unix_socket=opt_strdup(opt_arg,MYF(MY_WME)); + } + break; + case OPT_compress: + options->compress=1; + options->client_flag|= CLIENT_COMPRESS; + break; + case OPT_password: + if (opt_arg) + { + my_free(options->password); + options->password=opt_strdup(opt_arg,MYF(MY_WME)); + } + break; + case OPT_pipe: + options->protocol = MYSQL_PROTOCOL_PIPE; + break; + case OPT_connect_timeout: + case OPT_timeout: + if (opt_arg) + options->connect_timeout=atoi(opt_arg); + break; + case OPT_user: + if (opt_arg) + { + my_free(options->user); + options->user=opt_strdup(opt_arg,MYF(MY_WME)); + } + break; + case OPT_init_command: + add_init_command(options,opt_arg); + break; + case OPT_host: + if (opt_arg) + { + my_free(options->host); + options->host=opt_strdup(opt_arg,MYF(MY_WME)); + } + break; + case OPT_database: + if (opt_arg) + { + my_free(options->db); + options->db=opt_strdup(opt_arg,MYF(MY_WME)); + } + break; + case OPT_debug: +#ifdef MYSQL_CLIENT + mysql_debug(opt_arg ? opt_arg : "d:t:o,/tmp/client.trace"); + break; +#endif + case OPT_return_found_rows: + options->client_flag|=CLIENT_FOUND_ROWS; + break; + case OPT_ssl_key: + SET_SSL_OPTION(options, ssl_key, opt_arg); + break; + case OPT_ssl_cert: + SET_SSL_OPTION(options, ssl_cert, opt_arg); + break; + case OPT_ssl_ca: + SET_SSL_OPTION(options, ssl_ca, opt_arg); + break; + case OPT_ssl_capath: + SET_SSL_OPTION(options, ssl_capath, opt_arg); + break; + case OPT_ssl_cipher: + SET_SSL_OPTION(options, ssl_cipher, opt_arg); + break; + case OPT_ssl_crl: + EXTENSION_SET_SSL_STRING(options, ssl_crl, opt_arg); + break; + case OPT_ssl_crlpath: + EXTENSION_SET_SSL_STRING(options, ssl_crlpath, opt_arg); + break; + case OPT_character_sets_dir: + my_free(options->charset_dir); + options->charset_dir = opt_strdup(opt_arg, MYF(MY_WME)); + break; + case OPT_default_character_set: + my_free(options->charset_name); + options->charset_name = opt_strdup(opt_arg, MYF(MY_WME)); + break; + case OPT_interactive_timeout: + options->client_flag|= CLIENT_INTERACTIVE; + break; + case OPT_local_infile: + if (!opt_arg || atoi(opt_arg) != 0) + options->client_flag|= CLIENT_LOCAL_FILES; + else + options->client_flag&= ~CLIENT_LOCAL_FILES; + break; + case OPT_disable_local_infile: + options->client_flag&= ~CLIENT_LOCAL_FILES; + break; + case OPT_max_allowed_packet: + if (opt_arg) + options->max_allowed_packet= atoi(opt_arg); + break; + case OPT_protocol: + if (options->protocol != UINT_MAX32 && + (options->protocol= find_type(opt_arg, &sql_protocol_typelib, + FIND_TYPE_BASIC)) <= 0) + { + fprintf(stderr, "Unknown option to protocol: %s\n", opt_arg); + options->protocol= UINT_MAX32; + } + break; + case OPT_multi_results: + options->client_flag|= CLIENT_MULTI_RESULTS; + break; + case OPT_multi_statements: + case OPT_multi_queries: + options->client_flag|= CLIENT_MULTI_STATEMENTS | CLIENT_MULTI_RESULTS; + break; + case OPT_secure_auth: + options->secure_auth= TRUE; + break; + case OPT_report_data_truncation: + options->report_data_truncation= opt_arg ? MY_TEST(atoi(opt_arg)) : 1; + break; + case OPT_plugin_dir: + { + char buff[FN_REFLEN], buff2[FN_REFLEN], *buff2_ptr= buff2; + if (strlen(opt_arg) >= FN_REFLEN) + opt_arg[FN_REFLEN]= '\0'; + if (my_realpath(buff, opt_arg, 0)) + { + DBUG_PRINT("warning",("failed to normalize the plugin path: %s", + opt_arg)); + break; + } + convert_dirname(buff2, buff, NULL); + EXTENSION_SET_STRING(options, plugin_dir, buff2_ptr); + } + break; + case OPT_default_auth: + EXTENSION_SET_STRING(options, default_auth, opt_arg); + break; + case OPT_enable_cleartext_plugin: + break; + default: + DBUG_PRINT("warning",("unknown option: %s",option[0])); + } + } + } + } + free_defaults(argv); + DBUG_VOID_RETURN; +} + + +/************************************************************************** + Get column lengths of the current row + If one uses mysql_use_result, res->lengths contains the length information, + else the lengths are calculated from the offset between pointers. +**************************************************************************/ + +static void cli_fetch_lengths(ulong *to, MYSQL_ROW column, + unsigned int field_count) +{ + ulong *prev_length; + char *start=0; + MYSQL_ROW end; + + prev_length=0; /* Keep gcc happy */ + for (end=column + field_count + 1 ; column != end ; column++, to++) + { + if (!*column) + { + *to= 0; /* Null */ + continue; + } + if (start) /* Found end of prev string */ + *prev_length= (ulong) (*column-start-1); + start= *column; + prev_length= to; + } +} + +/*************************************************************************** + Change field rows to field structs +***************************************************************************/ + +MYSQL_FIELD * +unpack_fields(MYSQL *mysql, MYSQL_DATA *data,MEM_ROOT *alloc,uint fields, + my_bool default_value, uint server_capabilities) +{ + MYSQL_ROWS *row; + MYSQL_FIELD *field,*result; + ulong lengths[9]; /* Max of fields */ + DBUG_ENTER("unpack_fields"); + + field= result= (MYSQL_FIELD*) alloc_root(alloc, + (uint) sizeof(*field)*fields); + if (!result) + { + free_rows(data); /* Free old data */ + set_mysql_error(mysql, CR_OUT_OF_MEMORY, unknown_sqlstate); + DBUG_RETURN(0); + } + bzero((char*) field, (uint) sizeof(MYSQL_FIELD)*fields); + if (server_capabilities & CLIENT_PROTOCOL_41) + { + /* server is 4.1, and returns the new field result format */ + for (row=data->data; row ; row = row->next,field++) + { + uchar *pos; + /* fields count may be wrong */ + if (field >= result + fields) + goto err; + + cli_fetch_lengths(&lengths[0], row->data, default_value ? 8 : 7); + field->catalog= strmake_root(alloc,(char*) row->data[0], lengths[0]); + field->db= strmake_root(alloc,(char*) row->data[1], lengths[1]); + field->table= strmake_root(alloc,(char*) row->data[2], lengths[2]); + field->org_table= strmake_root(alloc,(char*) row->data[3], lengths[3]); + field->name= strmake_root(alloc,(char*) row->data[4], lengths[4]); + field->org_name= strmake_root(alloc,(char*) row->data[5], lengths[5]); + + field->catalog_length= lengths[0]; + field->db_length= lengths[1]; + field->table_length= lengths[2]; + field->org_table_length= lengths[3]; + field->name_length= lengths[4]; + field->org_name_length= lengths[5]; + + /* Unpack fixed length parts */ + if (lengths[6] != 12) + goto err; + + pos= (uchar*) row->data[6]; + field->charsetnr= uint2korr(pos); + field->length= (uint) uint4korr(pos+2); + field->type= (enum enum_field_types) pos[6]; + field->flags= uint2korr(pos+7); + field->decimals= (uint) pos[9]; + + if (IS_NUM(field->type)) + field->flags|= NUM_FLAG; + if (default_value && row->data[7]) + { + field->def=strmake_root(alloc,(char*) row->data[7], lengths[7]); + field->def_length= lengths[7]; + } + else + field->def=0; + field->max_length= 0; + } + } +#ifndef DELETE_SUPPORT_OF_4_0_PROTOCOL + else + { + /* old protocol, for backward compatibility */ + for (row=data->data; row ; row = row->next,field++) + { + if (field >= result + fields) + goto err; + + /* + If any of the row->data[] below is NULL, it can result in a + crash. Error out early as it indicates a malformed packet. + For data[0], data[1] and data[5], strmake_root will handle + NULL values. + */ + if (!row->data[2] || !row->data[3] || !row->data[4]) + { + free_rows(data); + set_mysql_error(mysql, CR_MALFORMED_PACKET, unknown_sqlstate); + DBUG_RETURN(0); + } + + cli_fetch_lengths(&lengths[0], row->data, default_value ? 6 : 5); + field->org_table= field->table= strmake_root(alloc,(char*) row->data[0], lengths[0]); + field->name= strmake_root(alloc,(char*) row->data[1], lengths[1]); + field->length= (uint) uint3korr(row->data[2]); + field->type= (enum enum_field_types) (uchar) row->data[3][0]; + + field->catalog=(char*) ""; + field->db= (char*) ""; + field->catalog_length= 0; + field->db_length= 0; + field->org_table_length= field->table_length= lengths[0]; + field->name_length= lengths[1]; + + if (server_capabilities & CLIENT_LONG_FLAG) + { + field->flags= uint2korr(row->data[4]); + field->decimals=(uint) (uchar) row->data[4][2]; + } + else + { + field->flags= (uint) (uchar) row->data[4][0]; + field->decimals=(uint) (uchar) row->data[4][1]; + } + if (IS_NUM(field->type)) + field->flags|= NUM_FLAG; + if (default_value && row->data[5]) + { + field->def= strmake_root(alloc,(char*) row->data[5], lengths[5]); + field->def_length= lengths[5]; + } + else + field->def=0; + field->max_length= 0; + } + } +#endif /* DELETE_SUPPORT_OF_4_0_PROTOCOL */ + if (field < result + fields) + goto err; + free_rows(data); /* Free old data */ + DBUG_RETURN(result); + +err: + /* malformed packet. signal an error. */ + free_rows(data); + free_root(alloc, MYF(0)); + set_mysql_error(mysql, CR_MALFORMED_PACKET, unknown_sqlstate); + DBUG_RETURN(0); +} + +/* Read all rows (fields or data) from server */ + +MYSQL_DATA *cli_read_rows(MYSQL *mysql,MYSQL_FIELD *mysql_fields, + unsigned int fields) +{ + uint field; + ulong pkt_len; + ulong len; + uchar *cp; + char *to, *end_to; + MYSQL_DATA *result; + MYSQL_ROWS **prev_ptr,*cur; + NET *net = &mysql->net; + DBUG_ENTER("cli_read_rows"); + + if ((pkt_len= cli_safe_read(mysql)) == packet_error) + DBUG_RETURN(0); + if (pkt_len == 0) DBUG_RETURN(0); + if (!(result=(MYSQL_DATA*) my_malloc(key_memory_MYSQL_DATA, sizeof(MYSQL_DATA), + MYF(MY_WME | MY_ZEROFILL)))) + { + set_mysql_error(mysql, CR_OUT_OF_MEMORY, unknown_sqlstate); + DBUG_RETURN(0); + } + /* Assume rowlength < 8192 */ + init_alloc_root(key_memory_MYSQL_DATA, &result->alloc, 8192, 0, + MYF(mysql->options.use_thread_specific_memory ? + MY_THREAD_SPECIFIC : 0)); + result->alloc.min_malloc=sizeof(MYSQL_ROWS); + prev_ptr= &result->data; + result->rows=0; + result->fields=fields; + + /* + The last EOF packet is either a single 254 character or (in MySQL 4.1) + 254 followed by 1-7 status bytes. + + This doesn't conflict with normal usage of 254 which stands for a + string where the length of the string is 8 bytes. (see net_field_length()) + */ + + while (*(cp=net->read_pos) != 254 || pkt_len >= 8) + { + result->rows++; + if (!(cur= (MYSQL_ROWS*) alloc_root(&result->alloc, + sizeof(MYSQL_ROWS))) || + !(cur->data= ((MYSQL_ROW) + alloc_root(&result->alloc, + (fields+1)*sizeof(char *)+pkt_len)))) + { + free_rows(result); + set_mysql_error(mysql, CR_OUT_OF_MEMORY, unknown_sqlstate); + DBUG_RETURN(0); + } + *prev_ptr=cur; + prev_ptr= &cur->next; + to= (char*) (cur->data+fields+1); + end_to=to+pkt_len-1; + for (field=0 ; field < fields ; field++) + { + if ((len=(ulong) net_field_length(&cp)) == NULL_LENGTH) + { /* null field */ + cur->data[field] = 0; + } + else + { + cur->data[field] = to; + if (unlikely(len > (ulong)(end_to-to) || to > end_to)) + { + free_rows(result); + set_mysql_error(mysql, CR_MALFORMED_PACKET, unknown_sqlstate); + DBUG_RETURN(0); + } + memcpy(to,(char*) cp,len); to[len]=0; + to+=len+1; + cp+=len; + if (mysql_fields) + { + if (mysql_fields[field].max_length < len) + mysql_fields[field].max_length=len; + } + } + } + cur->data[field]=to; /* End of last field */ + if ((pkt_len=cli_safe_read(mysql)) == packet_error) + { + free_rows(result); + DBUG_RETURN(0); + } + } + *prev_ptr=0; /* last pointer is null */ + if (pkt_len > 1) /* MySQL 4.1 protocol */ + { + mysql->warning_count= uint2korr(cp+1); + mysql->server_status= uint2korr(cp+3); + DBUG_PRINT("info",("status: %u warning_count: %u", + mysql->server_status, mysql->warning_count)); + } + DBUG_PRINT("exit", ("Got %lu rows", (ulong) result->rows)); + DBUG_RETURN(result); +} + +/* + Read one row. Uses packet buffer as storage for fields. + When next packet is read, the previous field values are destroyed +*/ + + +static int +read_one_row(MYSQL *mysql,uint fields,MYSQL_ROW row, ulong *lengths) +{ + uint field; + ulong pkt_len,len; + uchar *pos, *prev_pos, *end_pos; + NET *net= &mysql->net; + + if ((pkt_len=cli_safe_read(mysql)) == packet_error) + return -1; + if (pkt_len <= 8 && net->read_pos[0] == 254) + { + if (pkt_len > 1) /* MySQL 4.1 protocol */ + { + mysql->warning_count= uint2korr(net->read_pos+1); + mysql->server_status= uint2korr(net->read_pos+3); + } + return 1; /* End of data */ + } + prev_pos= 0; /* allowed to write at packet[-1] */ + pos=net->read_pos; + end_pos=pos+pkt_len; + for (field=0 ; field < fields ; field++) + { + if ((len=(ulong) net_field_length(&pos)) == NULL_LENGTH) + { /* null field */ + row[field] = 0; + *lengths++=0; + } + else + { + if (unlikely(len > (ulong)(end_pos - pos) || pos > end_pos)) + { + set_mysql_error(mysql, CR_UNKNOWN_ERROR, unknown_sqlstate); + return -1; + } + row[field] = (char*) pos; + pos+=len; + *lengths++=len; + } + if (prev_pos) + *prev_pos=0; /* Terminate prev field */ + prev_pos=pos; + } + row[field]=(char*) prev_pos+1; /* End of last field */ + *prev_pos=0; /* Terminate last field */ + return 0; +} + + +/**************************************************************************** + Init MySQL structure or allocate one +****************************************************************************/ + +MYSQL * STDCALL +mysql_init(MYSQL *mysql) +{ + if (mysql_server_init(0, NULL, NULL)) + return 0; + if (!mysql) + { + if (!(mysql=(MYSQL*) my_malloc(key_memory_MYSQL, + sizeof(*mysql), MYF(MY_WME | MY_ZEROFILL)))) + { + set_mysql_error(NULL, CR_OUT_OF_MEMORY, unknown_sqlstate); + return 0; + } + mysql->free_me=1; + } + else + bzero((char*) (mysql), sizeof(*(mysql))); + mysql->options.connect_timeout= CONNECT_TIMEOUT; + mysql->charset=default_client_charset_info; + strmov(mysql->net.sqlstate, not_error_sqlstate); + + /* + Only enable LOAD DATA INFILE by default if configured with + --enable-local-infile + */ + +#if ENABLED_LOCAL_INFILE && !defined(MYSQL_SERVER) + mysql->options.client_flag|= CLIENT_LOCAL_FILES; + mysql->auto_local_infile= ENABLED_LOCAL_INFILE == LOCAL_INFILE_MODE_AUTO + ? WAIT_FOR_QUERY : ALWAYS_ACCEPT; +#endif + + mysql->options.methods_to_use= MYSQL_OPT_GUESS_CONNECTION; + mysql->options.report_data_truncation= TRUE; /* default */ + + /* + By default we don't reconnect because it could silently corrupt data (after + reconnection you potentially lose table locks, user variables, session + variables (transactions but they are specifically dealt with in + mysql_reconnect()). + This is a change: < 5.0.3 mysql->reconnect was set to 1 by default. + How this change impacts existing apps: + - existing apps which relyed on the default will see a behaviour change; + they will have to set reconnect=1 after mysql_real_connect(). + - existing apps which explicitly asked for reconnection (the only way they + could do it was by setting mysql.reconnect to 1 after mysql_real_connect()) + will not see a behaviour change. + - existing apps which explicitly asked for no reconnection + (mysql.reconnect=0) will not see a behaviour change. + */ + mysql->reconnect= 0; + + DBUG_PRINT("mysql",("mysql: %p", mysql)); + return mysql; +} + + +/* + Fill in SSL part of MYSQL structure. + NB! Errors are not reported until you do mysql_real_connect. + use_ssl is set in send_client_reply_packet if any ssl option is set. +*/ + +my_bool STDCALL +mysql_ssl_set(MYSQL *mysql __attribute__((unused)) , + const char *key __attribute__((unused)), + const char *cert __attribute__((unused)), + const char *ca __attribute__((unused)), + const char *capath __attribute__((unused)), + const char *cipher __attribute__((unused))) +{ + my_bool result= 0; + DBUG_ENTER("mysql_ssl_set"); +#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) + result= (mysql_options(mysql, MYSQL_OPT_SSL_KEY, key) | + mysql_options(mysql, MYSQL_OPT_SSL_CERT, cert) | + mysql_options(mysql, MYSQL_OPT_SSL_CA, ca) | + mysql_options(mysql, MYSQL_OPT_SSL_CAPATH, capath) | + mysql_options(mysql, MYSQL_OPT_SSL_CIPHER, cipher) ? + 1 : 0); +#endif /* HAVE_OPENSSL && !EMBEDDED_LIBRARY */ + mysql->options.use_ssl= TRUE; + DBUG_RETURN(result); +} + + +/* + Free strings in the SSL structure and clear 'use_ssl' flag. + NB! Errors are not reported until you do mysql_real_connect. +*/ + +#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) + +static void +mysql_ssl_free(MYSQL *mysql __attribute__((unused))) +{ + struct st_VioSSLFd *ssl_fd= (struct st_VioSSLFd*) mysql->connector_fd; + DBUG_ENTER("mysql_ssl_free"); + + my_free(mysql->options.ssl_key); + my_free(mysql->options.ssl_cert); + my_free(mysql->options.ssl_ca); + my_free(mysql->options.ssl_capath); + my_free(mysql->options.ssl_cipher); + if (mysql->options.extension) + { + my_free(mysql->options.extension->ssl_crl); + my_free(mysql->options.extension->ssl_crlpath); + } + if (ssl_fd) + SSL_CTX_free(ssl_fd->ssl_context); + my_free(mysql->connector_fd); + mysql->options.ssl_key = 0; + mysql->options.ssl_cert = 0; + mysql->options.ssl_ca = 0; + mysql->options.ssl_capath = 0; + mysql->options.ssl_cipher= 0; + if (mysql->options.extension) + { + mysql->options.extension->ssl_crl = 0; + mysql->options.extension->ssl_crlpath = 0; + } + mysql->options.use_ssl = FALSE; + mysql->connector_fd = 0; + DBUG_VOID_RETURN; +} + +#endif /* HAVE_OPENSSL && !EMBEDDED_LIBRARY */ + +/* + Return the SSL cipher (if any) used for current + connection to the server. + + SYNOPSYS + mysql_get_ssl_cipher() + mysql pointer to the mysql connection + +*/ + +const char * STDCALL +mysql_get_ssl_cipher(MYSQL *mysql __attribute__((unused))) +{ + DBUG_ENTER("mysql_get_ssl_cipher"); +#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) + if (mysql->net.vio && mysql->net.vio->ssl_arg) + DBUG_RETURN(SSL_get_cipher_name((SSL*)mysql->net.vio->ssl_arg)); +#endif /* HAVE_OPENSSL && !EMBEDDED_LIBRARY */ + DBUG_RETURN(NULL); +} + + +/* + Check the server's (subject) Common Name against the + hostname we connected to + + SYNOPSIS + ssl_verify_server_cert() + vio pointer to a SSL connected vio + server_hostname name of the server that we connected to + errptr if we fail, we'll return (a pointer to a string + describing) the reason here + + RETURN VALUES + 0 Success + 1 Failed to validate server + + */ + +#if defined(HAVE_OPENSSL) + +#ifdef HAVE_X509_check_host +#include <openssl/x509v3.h> +#endif + +static int ssl_verify_server_cert(Vio *vio, const char* server_hostname, const char **errptr) +{ + SSL *ssl; + X509 *server_cert= NULL; +#ifndef HAVE_X509_check_host + char *cn= NULL; + int cn_loc= -1; + ASN1_STRING *cn_asn1= NULL; + X509_NAME_ENTRY *cn_entry= NULL; + X509_NAME *subject= NULL; +#endif + int ret_validation= 1; + + DBUG_ENTER("ssl_verify_server_cert"); + DBUG_PRINT("enter", ("server_hostname: %s", server_hostname)); + + if (!(ssl= (SSL*)vio->ssl_arg)) + { + *errptr= "No SSL pointer found"; + goto error; + } + + if (!server_hostname) + { + *errptr= "No server hostname supplied"; + goto error; + } + + if (!(server_cert= SSL_get_peer_certificate(ssl))) + { + *errptr= "Could not get server certificate"; + goto error; + } + + if (X509_V_OK != SSL_get_verify_result(ssl)) + { + *errptr= "Failed to verify the server certificate"; + goto error; + } + /* + We already know that the certificate exchanged was valid; the SSL library + handled that. Now we need to verify that the contents of the certificate + are what we expect. + */ + +#ifdef HAVE_X509_check_host + ret_validation= + X509_check_host(server_cert, server_hostname, + strlen(server_hostname), 0, 0) != 1; +#ifndef HAVE_WOLFSSL + if (ret_validation) + { + ret_validation= + X509_check_ip_asc(server_cert, server_hostname, 0) != 1; + } +#endif +#else + subject= X509_get_subject_name(server_cert); + cn_loc= X509_NAME_get_index_by_NID(subject, NID_commonName, -1); + if (cn_loc < 0) + { + *errptr= "Failed to get CN location in the certificate subject"; + goto error; + } + cn_entry= X509_NAME_get_entry(subject, cn_loc); + if (cn_entry == NULL) + { + *errptr= "Failed to get CN entry using CN location"; + goto error; + } + + cn_asn1 = X509_NAME_ENTRY_get_data(cn_entry); + if (cn_asn1 == NULL) + { + *errptr= "Failed to get CN from CN entry"; + goto error; + } + + cn= (char *) ASN1_STRING_get0_data(cn_asn1); + + if ((size_t)ASN1_STRING_length(cn_asn1) != strlen(cn)) + { + *errptr= "NULL embedded in the certificate CN"; + goto error; + } + + DBUG_PRINT("info", ("Server hostname in cert: %s", cn)); + if (!strcmp(cn, server_hostname)) + { + /* Success */ + ret_validation= 0; + } +#endif + *errptr= "SSL certificate validation failure"; + +error: + if (server_cert != NULL) + X509_free (server_cert); + DBUG_RETURN(ret_validation); +} + +#endif /* HAVE_OPENSSL */ + + +/* + Note that the mysql argument must be initialized with mysql_init() + before calling mysql_real_connect ! +*/ + +static my_bool cli_read_query_result(MYSQL *mysql); +static MYSQL_RES *cli_use_result(MYSQL *mysql); + +int cli_read_change_user_result(MYSQL *mysql) +{ + return cli_safe_read(mysql); +} + +static MYSQL_METHODS client_methods= +{ + cli_read_query_result, /* read_query_result */ + cli_advanced_command, /* advanced_command */ + cli_read_rows, /* read_rows */ + cli_use_result, /* use_result */ + cli_fetch_lengths, /* fetch_lengths */ + cli_flush_use_result, /* flush_use_result */ + cli_read_change_user_result /* read_change_user_result */ +#ifndef MYSQL_SERVER + ,cli_list_fields, /* list_fields */ + cli_read_prepare_result, /* read_prepare_result */ + cli_stmt_execute, /* stmt_execute */ + cli_read_binary_rows, /* read_binary_rows */ + cli_unbuffered_fetch, /* unbuffered_fetch */ + NULL, /* free_embedded_thd */ + cli_read_statistics, /* read_statistics */ + cli_read_query_result, /* next_result */ + cli_read_binary_rows /* read_rows_from_cursor */ +#endif +}; + + +#include <my_sys.h> +static int +mysql_autodetect_character_set(MYSQL *mysql) +{ + if (mysql->options.charset_name) + my_free(mysql->options.charset_name); + if (!(mysql->options.charset_name= opt_strdup(my_default_csname(),MYF(MY_WME)))) + return 1; + return 0; +} + + +static void +mysql_set_character_set_with_default_collation(MYSQL *mysql) +{ + const char *save= charsets_dir; + if (mysql->options.charset_dir) + charsets_dir=mysql->options.charset_dir; + + if ((mysql->charset= get_charset_by_csname(mysql->options.charset_name, + MY_CS_PRIMARY, MYF(MY_WME)))) + { + /* Try to set compiled default collation when it's possible. */ + CHARSET_INFO *collation; + if ((collation= + get_charset_by_name(MYSQL_DEFAULT_COLLATION_NAME, MYF(MY_WME))) && + my_charset_same(mysql->charset, collation)) + { + mysql->charset= collation; + } + else + { + /* + Default compiled collation not found, or is not applicable + to the requested character set. + Continue with the default collation of the character set. + */ + } + } + charsets_dir= save; +} + + +C_MODE_START +int mysql_init_character_set(MYSQL *mysql) +{ + /* Set character set */ + if (!mysql->options.charset_name || + !strcmp(mysql->options.charset_name, + MYSQL_AUTODETECT_CHARSET_NAME)) + { + if (mysql_autodetect_character_set(mysql)) + return 1; + } + + mysql_set_character_set_with_default_collation(mysql); + + if (!mysql->charset) + { + if (mysql->options.charset_dir) + set_mysql_extended_error(mysql, CR_CANT_READ_CHARSET, unknown_sqlstate, + ER(CR_CANT_READ_CHARSET), + mysql->options.charset_name, + mysql->options.charset_dir); + else + { + char cs_dir_name[FN_REFLEN]; + get_charsets_dir(cs_dir_name); + set_mysql_extended_error(mysql, CR_CANT_READ_CHARSET, unknown_sqlstate, + ER(CR_CANT_READ_CHARSET), + mysql->options.charset_name, + cs_dir_name); + } + return 1; + } + return 0; +} +C_MODE_END + +/*********** client side authentication support **************************/ + +typedef struct st_mysql_client_plugin_AUTHENTICATION auth_plugin_t; +static int client_mpvio_write_packet(struct st_plugin_vio*, const uchar*, int); +static int native_password_auth_client(MYSQL_PLUGIN_VIO *vio, MYSQL *mysql); +static int old_password_auth_client(MYSQL_PLUGIN_VIO *vio, MYSQL *mysql); + +static auth_plugin_t native_password_client_plugin= +{ + MYSQL_CLIENT_AUTHENTICATION_PLUGIN, + MYSQL_CLIENT_AUTHENTICATION_PLUGIN_INTERFACE_VERSION, + native_password_plugin_name, + "R.J.Silk, Sergei Golubchik", + "Native MySQL authentication", + {1, 0, 0}, + "GPL", + NULL, + NULL, + NULL, + NULL, + native_password_auth_client +}; + +static auth_plugin_t old_password_client_plugin= +{ + MYSQL_CLIENT_AUTHENTICATION_PLUGIN, + MYSQL_CLIENT_AUTHENTICATION_PLUGIN_INTERFACE_VERSION, + old_password_plugin_name, + "R.J.Silk, Sergei Golubchik", + "Old MySQL-3.23 authentication", + {1, 0, 0}, + "GPL", + NULL, + NULL, + NULL, + NULL, + old_password_auth_client +}; + + +struct st_mysql_client_plugin *mysql_client_builtins[]= +{ + (struct st_mysql_client_plugin *)&native_password_client_plugin, + (struct st_mysql_client_plugin *)&old_password_client_plugin, + 0 +}; + + +static uchar * +write_length_encoded_string3(uchar *buf, char *string, size_t length) +{ + buf= net_store_length(buf, length); + memcpy(buf, string, length); + buf+= length; + return buf; +} + + +uchar * +send_client_connect_attrs(MYSQL *mysql, uchar *buf) +{ + /* check if the server supports connection attributes */ + if (mysql->server_capabilities & CLIENT_CONNECT_ATTRS) + { + + /* Always store the length if the client supports it */ + buf= net_store_length(buf, + mysql->options.extension ? + mysql->options.extension->connection_attributes_length : + 0); + + /* check if we have connection attributes */ + if (mysql->options.extension && + my_hash_inited(&mysql->options.extension->connection_attributes)) + { + HASH *attrs= &mysql->options.extension->connection_attributes; + ulong idx; + + /* loop over and dump the connection attributes */ + for (idx= 0; idx < attrs->records; idx++) + { + LEX_STRING *attr= (LEX_STRING *) my_hash_element(attrs, idx); + LEX_STRING *key= attr, *value= attr + 1; + + /* we can't have zero length keys */ + DBUG_ASSERT(key->length); + + buf= write_length_encoded_string3(buf, key->str, key->length); + buf= write_length_encoded_string3(buf, value->str, value->length); + } + } + } + return buf; +} + + +static size_t get_length_store_length(size_t length) +{ + /* as defined in net_store_length */ + #define MAX_VARIABLE_STRING_LENGTH 9 + uchar length_buffer[MAX_VARIABLE_STRING_LENGTH], *ptr; + + ptr= net_store_length(length_buffer, length); + + return ptr - &length_buffer[0]; +} + + +/* this is a "superset" of MYSQL_PLUGIN_VIO, in C++ I use inheritance */ +typedef struct { + int (*read_packet)(struct st_plugin_vio *vio, uchar **buf); + int (*write_packet)(struct st_plugin_vio *vio, const uchar *pkt, int pkt_len); + void (*info)(struct st_plugin_vio *vio, struct st_plugin_vio_info *info); + /* -= end of MYSQL_PLUGIN_VIO =- */ + MYSQL *mysql; + auth_plugin_t *plugin; /**< what plugin we're under */ + const char *db; + struct { + uchar *pkt; /**< pointer into NET::buff */ + uint pkt_len; + } cached_server_reply; + int packets_read, packets_written; /**< counters for send/received packets */ + int mysql_change_user; /**< if it's mysql_change_user() */ + int last_read_packet_len; /**< the length of the last *read* packet */ +} MCPVIO_EXT; + + +/* + Write 1-8 bytes of string length header infromation to dest depending on + value of src_len, then copy src_len bytes from src to dest. + + @param dest Destination buffer of size src_len+8 + @param dest_end One byte past the end of the dest buffer + @param src Source buff of size src_len + @param src_end One byte past the end of the src buffer + + @return pointer dest+src_len+header size or NULL if +*/ + +static uchar *write_length_encoded_string4(uchar *dst, size_t dst_len, + const uchar *src, size_t src_len) +{ + uchar *to= safe_net_store_length(dst, dst_len, src_len); + if (to == NULL) + return NULL; + memcpy(to, src, src_len); + return to + src_len; +} + +/** + sends a COM_CHANGE_USER command with a caller provided payload + + Packet format: + + Bytes Content + ----- ---- + n user name - \0-terminated string + n password + 3.23 scramble - \0-terminated string (9 bytes) + otherwise - length (1 byte) coded + n database name - \0-terminated string + 2 character set number (if the server >= 4.1.x) + n client auth plugin name - \0-terminated string, + (if the server supports plugin auth) + + @retval 0 ok + @retval 1 error +*/ +static int send_change_user_packet(MCPVIO_EXT *mpvio, + const uchar *data, int data_len) +{ + MYSQL *mysql= mpvio->mysql; + char *buff, *end; + int res= 1; + size_t connect_attrs_len= + (mysql->server_capabilities & CLIENT_CONNECT_ATTRS && + mysql->options.extension) ? + mysql->options.extension->connection_attributes_length : 0; + + buff= my_alloca(USERNAME_LENGTH + data_len + 1 + NAME_LEN + 2 + NAME_LEN + + connect_attrs_len + 9 /* for the length of the attrs */); + + end= strmake(buff, mysql->user, USERNAME_LENGTH) + 1; + + if (!data_len) + *end++= 0; + else + { + if (mysql->client_flag & CLIENT_SECURE_CONNECTION) + { + DBUG_ASSERT(data_len <= 255); + if (data_len > 255) + { + set_mysql_error(mysql, CR_MALFORMED_PACKET, unknown_sqlstate); + goto error; + } + *end++= data_len; + } + else + { + DBUG_ASSERT(data_len == SCRAMBLE_LENGTH_323 + 1); + DBUG_ASSERT(data[SCRAMBLE_LENGTH_323] == 0); + } + memcpy(end, data, data_len); + end+= data_len; + } + end= strmake(end, mpvio->db ? mpvio->db : "", NAME_LEN) + 1; + + if (mysql->server_capabilities & CLIENT_PROTOCOL_41) + { + int2store(end, (ushort) mysql->charset->number); + end+= 2; + } + + if (mysql->server_capabilities & CLIENT_PLUGIN_AUTH) + end= strmake(end, mpvio->plugin->name, NAME_LEN) + 1; + + end= (char *) send_client_connect_attrs(mysql, (uchar *) end); + + res= simple_command(mysql, COM_CHANGE_USER, + (uchar*)buff, (ulong)(end-buff), 1); + +error: + my_afree(buff); + return res; +} + +#define MAX_CONNECTION_ATTR_STORAGE_LENGTH 65536 + +/** + sends a client authentication packet (second packet in the 3-way handshake) + + Packet format (when the server is 4.0 or earlier): + + Bytes Content + ----- ---- + 2 client capabilities + 3 max packet size + n user name, \0-terminated + 9 scramble_323, \0-terminated + + Packet format (when the server is 4.1 or newer): + + Bytes Content + ----- ---- + 4 client capabilities + 4 max packet size + 1 charset number + 23 reserved (always 0) + n user name, \0-terminated + n plugin auth data (e.g. scramble), length encoded + n database name, \0-terminated + (if CLIENT_CONNECT_WITH_DB is set in the capabilities) + n client auth plugin name - \0-terminated string, + (if CLIENT_PLUGIN_AUTH is set in the capabilities) + + @retval 0 ok + @retval 1 error +*/ +static int send_client_reply_packet(MCPVIO_EXT *mpvio, + const uchar *data, int data_len) +{ + MYSQL *mysql= mpvio->mysql; + NET *net= &mysql->net; + char *buff, *end; + size_t buff_size; + size_t connect_attrs_len= + (mysql->server_capabilities & CLIENT_CONNECT_ATTRS && + mysql->options.extension) ? + mysql->options.extension->connection_attributes_length : 0; + + DBUG_ASSERT(connect_attrs_len < MAX_CONNECTION_ATTR_STORAGE_LENGTH); + + /* + see end= buff+32 below, fixed size of the packet is 32 bytes. + +9 because data is a length encoded binary where meta data size is max 9. + */ + buff_size= 33 + USERNAME_LENGTH + data_len + 9 + NAME_LEN + NAME_LEN + connect_attrs_len + 9; + buff= my_alloca(buff_size); + + mysql->client_flag|= mysql->options.client_flag; + mysql->client_flag|= CLIENT_CAPABILITIES; + + if (mysql->client_flag & CLIENT_MULTI_STATEMENTS) + mysql->client_flag|= CLIENT_MULTI_RESULTS; + +#ifdef HAVE_OPENSSL + if (mysql->options.ssl_key || mysql->options.ssl_cert || + mysql->options.ssl_ca || mysql->options.ssl_capath || + mysql->options.ssl_cipher) + mysql->options.use_ssl = 1; + if (mysql->options.use_ssl) + mysql->client_flag|= CLIENT_SSL; +#endif /* HAVE_OPENSSL */ + + if (mpvio->db) + mysql->client_flag|= CLIENT_CONNECT_WITH_DB; + + /* Remove options that server doesn't support */ + mysql->client_flag= mysql->client_flag & + (~(CLIENT_COMPRESS | CLIENT_SSL | CLIENT_PROTOCOL_41) + | mysql->server_capabilities); + +#ifndef HAVE_COMPRESS + mysql->client_flag&= ~CLIENT_COMPRESS; +#endif + + if (mysql->client_flag & CLIENT_PROTOCOL_41) + { + /* 4.1 server and 4.1 client has a 32 byte option flag */ + int4store(buff,mysql->client_flag); + int4store(buff+4, net->max_packet_size); + buff[8]= (char) mysql->charset->number; + bzero(buff+9, 32-9); + end= buff+32; + } + else + { + int2store(buff, mysql->client_flag); + int3store(buff+2, net->max_packet_size); + end= buff+5; + } + + /* + If client uses ssl and client also has to verify the server + certificate, a ssl connection is required. + If the server does not support ssl, we abort the connection. + */ + if (mysql->options.use_ssl && + (mysql->client_flag & CLIENT_SSL_VERIFY_SERVER_CERT) && + !(mysql->server_capabilities & CLIENT_SSL)) + { + set_mysql_extended_error(mysql, CR_SSL_CONNECTION_ERROR, unknown_sqlstate, + ER(CR_SSL_CONNECTION_ERROR), + "SSL is required, but the server does not " + "support it"); + goto error; + } + +#ifdef HAVE_OPENSSL + if (mysql->client_flag & CLIENT_SSL) + { + /* Do the SSL layering. */ + struct st_mysql_options *options= &mysql->options; + struct st_VioSSLFd *ssl_fd; + enum enum_ssl_init_error ssl_init_error; + const char *cert_error; + unsigned long ssl_error; +#ifdef EMBEDDED_LIBRARY + DBUG_ASSERT(0); // embedded should not do SSL connect +#endif + + /* + Send mysql->client_flag, max_packet_size - unencrypted otherwise + the server does not know we want to do SSL + */ + if (my_net_write(net, (uchar*)buff, (size_t) (end-buff)) || net_flush(net)) + { + set_mysql_extended_error(mysql, CR_SERVER_LOST, unknown_sqlstate, + ER(CR_SERVER_LOST_EXTENDED), + "sending connection information to server", + errno); + goto error; + } + + /* Create the VioSSLConnectorFd - init SSL and load certs */ + if (!(ssl_fd= new_VioSSLConnectorFd(options->ssl_key, + options->ssl_cert, + options->ssl_ca, + options->ssl_capath, + options->ssl_cipher, + &ssl_init_error, + options->extension ? + options->extension->ssl_crl : NULL, + options->extension ? + options->extension->ssl_crlpath : NULL))) + { + set_mysql_extended_error(mysql, CR_SSL_CONNECTION_ERROR, unknown_sqlstate, + ER(CR_SSL_CONNECTION_ERROR), sslGetErrString(ssl_init_error)); + goto error; + } + mysql->connector_fd= (unsigned char *) ssl_fd; + + /* Connect to the server */ + DBUG_PRINT("info", ("IO layer change in progress...")); + if (sslconnect(ssl_fd, net->vio, + (long) (mysql->options.connect_timeout), &ssl_error)) + { + char buf[512]; + ERR_error_string_n(ssl_error, buf, 512); + buf[511]= 0; + set_mysql_extended_error(mysql, CR_SSL_CONNECTION_ERROR, unknown_sqlstate, + ER(CR_SSL_CONNECTION_ERROR), + buf); + goto error; + } + DBUG_PRINT("info", ("IO layer change done!")); + + /* Verify server cert */ + if ((mysql->client_flag & CLIENT_SSL_VERIFY_SERVER_CERT) && + ssl_verify_server_cert(net->vio, mysql->host, &cert_error)) + { + set_mysql_extended_error(mysql, CR_SSL_CONNECTION_ERROR, unknown_sqlstate, + ER(CR_SSL_CONNECTION_ERROR), cert_error); + goto error; + } + } +#endif /* HAVE_OPENSSL */ + + DBUG_PRINT("info",("Server version = '%s' capabilites: %lu status: %u client_flag: %lu", + mysql->server_version, mysql->server_capabilities, + mysql->server_status, mysql->client_flag)); + + /* This needs to be changed as it's not useful with big packets */ + if (mysql->user[0]) + strmake(end, mysql->user, USERNAME_LENGTH); + else + read_user_name(end); + + /* We have to handle different version of handshake here */ + DBUG_PRINT("info",("user: %s",end)); + end= strend(end) + 1; + if (data_len) + { + if (mysql->server_capabilities & CLIENT_SECURE_CONNECTION) + { + if (mysql->server_capabilities & CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA) + end= (char*)write_length_encoded_string4((uchar*)end, + buff_size, data, data_len); + else + { + if (data_len > 255) + goto error; + *end++= data_len; + memcpy(end, data, data_len); + end+= data_len; + } + if (end == NULL) + goto error; + } + else + { + DBUG_ASSERT(data_len == SCRAMBLE_LENGTH_323 + 1); /* incl. \0 at the end */ + memcpy(end, data, data_len); + end+= data_len; + } + } + else + *end++= 0; + + /* Add database if needed */ + if (mpvio->db && (mysql->server_capabilities & CLIENT_CONNECT_WITH_DB)) + { + end= strmake(end, mpvio->db, NAME_LEN) + 1; + mysql->db= my_strdup(key_memory_MYSQL, mpvio->db, MYF(MY_WME)); + } + + if (mysql->server_capabilities & CLIENT_PLUGIN_AUTH) + end= strmake(end, mpvio->plugin->name, NAME_LEN) + 1; + + end= (char *) send_client_connect_attrs(mysql, (uchar *) end); + + /* Write authentication package */ + if (my_net_write(net, (uchar*) buff, (size_t) (end-buff)) || net_flush(net)) + { + set_mysql_extended_error(mysql, CR_SERVER_LOST, unknown_sqlstate, + ER(CR_SERVER_LOST_EXTENDED), + "sending authentication information", + errno); + goto error; + } + my_afree(buff); + return 0; + +error: + my_afree(buff); + return 1; +} + + +/** + vio->read_packet() callback method for client authentication plugins + + This function is called by a client authentication plugin, when it wants + to read data from the server. +*/ +static int client_mpvio_read_packet(struct st_plugin_vio *mpv, uchar **buf) +{ + MCPVIO_EXT *mpvio= (MCPVIO_EXT*)mpv; + MYSQL *mysql= mpvio->mysql; + ulong pkt_len; + + /* there are cached data left, feed it to a plugin */ + if (mpvio->cached_server_reply.pkt) + { + *buf= mpvio->cached_server_reply.pkt; + mpvio->cached_server_reply.pkt= 0; + mpvio->packets_read++; + return mpvio->cached_server_reply.pkt_len; + } + + if (mpvio->packets_read == 0) + { + /* + the server handshake packet came from the wrong plugin, + or it's mysql_change_user(). Either way, there is no data + for a plugin to read. send a dummy packet to the server + to initiate a dialog. + */ + if (client_mpvio_write_packet(mpv, 0, 0)) + return (int)packet_error; + } + + /* otherwise read the data */ + pkt_len= (*mysql->methods->read_change_user_result)(mysql); + mpvio->last_read_packet_len= pkt_len; + *buf= mysql->net.read_pos; + + /* was it a request to change plugins ? */ + if (pkt_len == packet_error || **buf == 254) + return (int)packet_error; /* if yes, this plugin shan't continue */ + + /* + the server sends \1\255 or \1\254 instead of just \255 or \254 - + for us to not confuse it with an error or "change plugin" packets. + We remove this escaping \1 here. + + See also server_mpvio_write_packet() where the escaping is done. + */ + if (pkt_len && **buf == 1) + { + (*buf)++; + pkt_len--; + } + mpvio->packets_read++; + return pkt_len; +} + + +/** + vio->write_packet() callback method for client authentication plugins + + This function is called by a client authentication plugin, when it wants + to send data to the server. + + It transparently wraps the data into a change user or authentication + handshake packet, if neccessary. +*/ +static int client_mpvio_write_packet(struct st_plugin_vio *mpv, + const uchar *pkt, int pkt_len) +{ + int res; + MCPVIO_EXT *mpvio= (MCPVIO_EXT*)mpv; + + if (mpvio->packets_written == 0) + { + if (mpvio->mysql_change_user) + res= send_change_user_packet(mpvio, pkt, pkt_len); + else + res= send_client_reply_packet(mpvio, pkt, pkt_len); + } + else + { + NET *net= &mpvio->mysql->net; + if (mpvio->mysql->thd) + res= 1; /* no chit-chat in embedded */ + else + res= my_net_write(net, pkt, pkt_len) || net_flush(net); + if (res) + set_mysql_extended_error(mpvio->mysql, CR_SERVER_LOST, unknown_sqlstate, + ER(CR_SERVER_LOST_EXTENDED), + "sending authentication information", + errno); + } + mpvio->packets_written++; + return res; +} + + +/** + fills MYSQL_PLUGIN_VIO_INFO structure with the information about the + connection +*/ +void mpvio_info(Vio *vio, MYSQL_PLUGIN_VIO_INFO *info) +{ + bzero(info, sizeof(*info)); + switch (vio->type) { + case VIO_TYPE_TCPIP: + info->protocol= MYSQL_VIO_TCP; + info->socket= (int)vio_fd(vio); + return; + case VIO_TYPE_SOCKET: + info->protocol= MYSQL_VIO_SOCKET; + info->socket= (int)vio_fd(vio); + return; + case VIO_TYPE_SSL: + { + struct sockaddr addr; + SOCKET_SIZE_TYPE addrlen= sizeof(addr); + if (getsockname(vio_fd(vio), &addr, &addrlen)) + return; + info->protocol= addr.sa_family == AF_UNIX ? + MYSQL_VIO_SOCKET : MYSQL_VIO_TCP; + info->socket= (int)vio_fd(vio); + return; + } +#ifdef _WIN32 + case VIO_TYPE_NAMEDPIPE: + info->protocol= MYSQL_VIO_PIPE; + info->handle= vio->hPipe; + return; +#endif + default: DBUG_ASSERT(0); + } +} + + +static void client_mpvio_info(MYSQL_PLUGIN_VIO *vio, + MYSQL_PLUGIN_VIO_INFO *info) +{ + MCPVIO_EXT *mpvio= (MCPVIO_EXT*)vio; + mpvio_info(mpvio->mysql->net.vio, info); +} + + +/** + Client side of the plugin driver authentication. + + @note this is used by both the mysql_real_connect and mysql_change_user + + @param mysql mysql + @param data pointer to the plugin auth data (scramble) in the + handshake packet + @param data_len the length of the data + @param data_plugin a plugin that data were prepared for + or 0 if it's mysql_change_user() + @param db initial db to use, can be 0 + + @retval 0 ok + @retval 1 error +*/ +int run_plugin_auth(MYSQL *mysql, char *data, uint data_len, + const char *data_plugin, const char *db) +{ + const char *auth_plugin_name; + auth_plugin_t *auth_plugin; + MCPVIO_EXT mpvio; + ulong pkt_length; + int res; + + DBUG_ENTER ("run_plugin_auth"); + /* determine the default/initial plugin to use */ + if (mysql->options.extension && mysql->options.extension->default_auth && + mysql->server_capabilities & CLIENT_PLUGIN_AUTH) + { + auth_plugin_name= mysql->options.extension->default_auth; + if (!(auth_plugin= (auth_plugin_t*) mysql_client_find_plugin(mysql, + auth_plugin_name, MYSQL_CLIENT_AUTHENTICATION_PLUGIN))) + DBUG_RETURN (1); /* oops, not found */ + } + else + { + auth_plugin= mysql->server_capabilities & CLIENT_PROTOCOL_41 ? + &native_password_client_plugin : &old_password_client_plugin; + auth_plugin_name= auth_plugin->name; + } + + DBUG_PRINT ("info", ("using plugin %s", auth_plugin_name)); + + mysql->net.last_errno= 0; /* just in case */ + + if (data_plugin && strcmp(data_plugin, auth_plugin_name)) + { + /* data was prepared for a different plugin, don't show it to this one */ + data= 0; + data_len= 0; + } + + mpvio.mysql_change_user= data_plugin == 0; + mpvio.cached_server_reply.pkt= (uchar*)data; + mpvio.cached_server_reply.pkt_len= data_len; + mpvio.read_packet= client_mpvio_read_packet; + mpvio.write_packet= client_mpvio_write_packet; + mpvio.info= client_mpvio_info; + mpvio.mysql= mysql; + mpvio.packets_read= mpvio.packets_written= 0; + mpvio.db= db; + mpvio.plugin= auth_plugin; + + res= auth_plugin->authenticate_user((struct st_plugin_vio *)&mpvio, mysql); + DBUG_PRINT ("info", ("authenticate_user returned %s", + res == CR_OK ? "CR_OK" : + res == CR_ERROR ? "CR_ERROR" : + res == CR_OK_HANDSHAKE_COMPLETE ? + "CR_OK_HANDSHAKE_COMPLETE" : "error")); + + compile_time_assert(CR_OK == -1); + compile_time_assert(CR_ERROR == 0); + if (res > CR_OK && (mysql->net.last_errno || mysql->net.read_pos[0] != 254)) + { + /* + the plugin returned an error. write it down in mysql, + unless the error code is CR_ERROR and mysql->net.last_errno + is already set (the plugin has done it) + */ + DBUG_PRINT ("info", ("res=%d", res)); + if (res > CR_ERROR) + set_mysql_error(mysql, res, unknown_sqlstate); + else + if (!mysql->net.last_errno) + set_mysql_error(mysql, CR_UNKNOWN_ERROR, unknown_sqlstate); + DBUG_RETURN (1); + } + + /* read the OK packet (or use the cached value in mysql->net.read_pos */ + if (res == CR_OK) + pkt_length= (*mysql->methods->read_change_user_result)(mysql); + else /* res == CR_OK_HANDSHAKE_COMPLETE */ + pkt_length= mpvio.last_read_packet_len; + + DBUG_PRINT ("info", ("OK packet length=%lu", pkt_length)); + if (pkt_length == packet_error) + { + if (mysql->net.last_errno == CR_SERVER_LOST) + set_mysql_extended_error(mysql, CR_SERVER_LOST, unknown_sqlstate, + ER(CR_SERVER_LOST_EXTENDED), + "reading authorization packet", + errno); + DBUG_RETURN (1); + } + + if (mysql->net.read_pos[0] == 254) + { + /* The server asked to use a different authentication plugin */ + if (pkt_length == 1) + { + /* old "use short scramble" packet */ + DBUG_PRINT ("info", ("old use short scramble packet from server")); + auth_plugin_name= old_password_plugin_name; + mpvio.cached_server_reply.pkt= (uchar*)mysql->scramble; + mpvio.cached_server_reply.pkt_len= SCRAMBLE_LENGTH + 1; + } + else + { + /* new "use different plugin" packet */ + uint len; + auth_plugin_name= (char*)mysql->net.read_pos + 1; + len= (uint)strlen(auth_plugin_name); /* safe as my_net_read always appends \0 */ + mpvio.cached_server_reply.pkt_len= pkt_length - len - 2; + mpvio.cached_server_reply.pkt= mysql->net.read_pos + len + 2; + DBUG_PRINT ("info", ("change plugin packet from server for plugin %s", + auth_plugin_name)); + } + + if (!(auth_plugin= (auth_plugin_t *) mysql_client_find_plugin(mysql, + auth_plugin_name, MYSQL_CLIENT_AUTHENTICATION_PLUGIN))) + DBUG_RETURN (1); + + mpvio.plugin= auth_plugin; + res= auth_plugin->authenticate_user((struct st_plugin_vio *)&mpvio, mysql); + + DBUG_PRINT ("info", ("second authenticate_user returned %s", + res == CR_OK ? "CR_OK" : + res == CR_ERROR ? "CR_ERROR" : + res == CR_OK_HANDSHAKE_COMPLETE ? + "CR_OK_HANDSHAKE_COMPLETE" : "error")); + if (res > CR_OK) + { + if (res > CR_ERROR) + set_mysql_error(mysql, res, unknown_sqlstate); + else + if (!mysql->net.last_errno) + set_mysql_error(mysql, CR_UNKNOWN_ERROR, unknown_sqlstate); + DBUG_RETURN (1); + } + + if (res != CR_OK_HANDSHAKE_COMPLETE) + { + /* Read what server thinks about out new auth message report */ + if (cli_safe_read(mysql) == packet_error) + { + if (mysql->net.last_errno == CR_SERVER_LOST) + set_mysql_extended_error(mysql, CR_SERVER_LOST, unknown_sqlstate, + ER(CR_SERVER_LOST_EXTENDED), + "reading final connect information", + errno); + DBUG_RETURN (1); + } + } + } + /* + net->read_pos[0] should always be 0 here if the server implements + the protocol correctly + */ + DBUG_RETURN (mysql->net.read_pos[0] != 0); +} + + +static int +connect_sync_or_async(MYSQL *mysql, NET *net, my_socket fd, + struct sockaddr *name, uint namelen) +{ + int vio_timeout = get_vio_connect_timeout(mysql); + + if (mysql->options.extension && mysql->options.extension->async_context && + mysql->options.extension->async_context->active) + { + my_bool old_mode; + vio_blocking(net->vio, FALSE, &old_mode); + return my_connect_async(mysql->options.extension->async_context, fd, + name, namelen, vio_timeout); + } + + return vio_socket_connect(net->vio, name, namelen, vio_timeout); +} + + +/** set some default attributes */ +static int +set_connect_attributes(MYSQL *mysql, char *buff, size_t buf_len) +{ + int rc= 0; + + /* + Clean up any values set by the client code. We want these options as + consistent as possible + */ + rc+= mysql_options(mysql, MYSQL_OPT_CONNECT_ATTR_DELETE, "_client_name"); + rc+= mysql_options(mysql, MYSQL_OPT_CONNECT_ATTR_DELETE, "_os"); + rc+= mysql_options(mysql, MYSQL_OPT_CONNECT_ATTR_DELETE, "_platform"); + rc+= mysql_options(mysql, MYSQL_OPT_CONNECT_ATTR_DELETE, "_server_host"); + rc+= mysql_options(mysql, MYSQL_OPT_CONNECT_ATTR_DELETE, "_pid"); + rc+= mysql_options(mysql, MYSQL_OPT_CONNECT_ATTR_DELETE, "_thread"); + rc+= mysql_options(mysql, MYSQL_OPT_CONNECT_ATTR_DELETE, "_client_version"); + + /* + Now let's set up some values + */ + rc+= mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, + "_client_name", "libmysql"); + rc+= mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, + "_client_version", PACKAGE_VERSION); + rc+= mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, + "_os", SYSTEM_TYPE); + rc+= mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, + "_platform", MACHINE_TYPE); + rc+= mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, + "_server_host", mysql->host); + snprintf(buff, buf_len, "%lu", (ulong) getpid()); + rc+= mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, "_pid", buff); + +#ifdef _WIN32 + snprintf(buff, buf_len, "%lu", (ulong) GetCurrentThreadId()); + rc+= mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, "_thread", buff); +#endif + + return rc > 0 ? 1 : 0; +} + + +MYSQL * STDCALL +CLI_MYSQL_REAL_CONNECT(MYSQL *mysql,const char *host, const char *user, + const char *passwd, const char *db, + uint port, const char *unix_socket,ulong client_flag) +{ + char buff[NAME_LEN+USERNAME_LENGTH+100]; + int scramble_data_len, UNINIT_VAR(pkt_scramble_len); + char *end,*host_info= 0, *server_version_end, *pkt_end; + char *scramble_data; + const char *scramble_plugin; + ulong pkt_length; + NET *net= &mysql->net; +#ifdef _WIN32 + HANDLE hPipe=INVALID_HANDLE_VALUE; +#endif +#ifdef HAVE_SYS_UN_H + struct sockaddr_un UNIXaddr; +#endif + DBUG_ENTER("mysql_real_connect"); + + DBUG_PRINT("enter",("host: %s db: %s user: %s (client)", + host ? host : "(Null)", + db ? db : "(Null)", + user ? user : "(Null)")); + + /* Test whether we're already connected */ + if (net->vio) + { + set_mysql_error(mysql, CR_ALREADY_CONNECTED, unknown_sqlstate); + DBUG_RETURN(0); + } + + mysql->methods= &client_methods; + mysql->client_flag=0; /* For handshake */ + + /* use default options */ + if (mysql->options.my_cnf_file || mysql->options.my_cnf_group) + { + mysql_read_default_options(&mysql->options, + (mysql->options.my_cnf_file ? + mysql->options.my_cnf_file : "my"), + mysql->options.my_cnf_group); + my_free(mysql->options.my_cnf_file); + my_free(mysql->options.my_cnf_group); + mysql->options.my_cnf_file=mysql->options.my_cnf_group=0; + if (mysql->options.protocol == UINT_MAX32) + goto error; + } + + /* Some empty-string-tests are done because of ODBC */ + if (!host || !host[0]) + host=mysql->options.host; + if (!user || !user[0]) + { + user=mysql->options.user; + if (!user) + user= ""; + } + if (!passwd) + { + passwd=mysql->options.password; +#if !defined(DONT_USE_MYSQL_PWD) && !defined(MYSQL_SERVER) + if (!passwd) + passwd=getenv("MYSQL_PWD"); /* get it from environment */ +#endif + if (!passwd) + passwd= ""; + } + if (!db || !db[0]) + db=mysql->options.db; + if (!port) + port=mysql->options.port; + if (!unix_socket) + unix_socket=mysql->options.unix_socket; + + mysql->server_status=SERVER_STATUS_AUTOCOMMIT; + DBUG_PRINT("info", ("Connecting")); + + /* + Part 0: Grab a socket and connect it to the server + */ + +#if defined(HAVE_SYS_UN_H) + if (!net->vio && + (!mysql->options.protocol || + mysql->options.protocol == MYSQL_PROTOCOL_SOCKET) && + (unix_socket || mysql_unix_port) && + (!host || !strcmp(host,LOCAL_HOST))) + { + my_socket sock= socket(AF_UNIX, SOCK_STREAM, 0); + DBUG_PRINT("info", ("Using socket")); + if (sock == INVALID_SOCKET) + { + set_mysql_extended_error(mysql, CR_SOCKET_CREATE_ERROR, + unknown_sqlstate, + ER(CR_SOCKET_CREATE_ERROR), + socket_errno); + goto error; + } + + net->vio= vio_new(sock, VIO_TYPE_SOCKET, + VIO_LOCALHOST | VIO_BUFFERED_READ); + if (!net->vio) + { + DBUG_PRINT("error",("Unknown protocol %d ", mysql->options.protocol)); + set_mysql_error(mysql, CR_CONN_UNKNOW_PROTOCOL, unknown_sqlstate); + closesocket(sock); + goto error; + } + + host= LOCAL_HOST; + if (!unix_socket) + unix_socket= mysql_unix_port; + host_info= (char*) ER(CR_LOCALHOST_CONNECTION); + DBUG_PRINT("info", ("Using UNIX sock '%s'", unix_socket)); + + bzero((char*) &UNIXaddr, sizeof(UNIXaddr)); + UNIXaddr.sun_family= AF_UNIX; + strmake_buf(UNIXaddr.sun_path, unix_socket); + if (connect_sync_or_async(mysql, net, sock, + (struct sockaddr *) &UNIXaddr, sizeof(UNIXaddr))) + { + DBUG_PRINT("error",("Got error %d on connect to local server", + socket_errno)); + set_mysql_extended_error(mysql, CR_CONNECTION_ERROR, + unknown_sqlstate, + ER(CR_CONNECTION_ERROR), + unix_socket, socket_errno); + vio_delete(net->vio); + net->vio= 0; + goto error; + } + mysql->options.protocol=MYSQL_PROTOCOL_SOCKET; + } +#elif defined(_WIN32) + if (!net->vio && + (mysql->options.protocol == MYSQL_PROTOCOL_PIPE || + (host && !strcmp(host,LOCAL_HOST_NAMEDPIPE)))) + { + if ((hPipe= create_named_pipe(mysql, mysql->options.connect_timeout, + (char**) &host, (char**) &unix_socket)) == + INVALID_HANDLE_VALUE) + { + DBUG_PRINT("error", + ("host: '%s' socket: '%s'", + host ? host : "<null>", + unix_socket ? unix_socket : "<null>")); + if (mysql->options.protocol == MYSQL_PROTOCOL_PIPE || + (host && !strcmp(host,LOCAL_HOST_NAMEDPIPE)) || + (unix_socket && !strcmp(unix_socket,MYSQL_NAMEDPIPE))) + goto error; + /* Try also with TCP/IP */ + } + else + { + net->vio= vio_new_win32pipe(hPipe); + my_snprintf(host_info=buff, sizeof(buff)-1, + ER(CR_NAMEDPIPE_CONNECTION), unix_socket); + } + } +#endif + DBUG_PRINT("info", ("net->vio: %p protocol: %d", + net->vio, mysql->options.protocol)); + if (!net->vio && + (!mysql->options.protocol || + mysql->options.protocol == MYSQL_PROTOCOL_TCP)) + { + struct addrinfo *res_lst, hints, *t_res; + int gai_errno; + char port_buf[NI_MAXSERV]; + my_socket sock= INVALID_SOCKET; + int saved_error= 0, status= -1; + + unix_socket=0; /* This is not used */ + + if (!port) + port= mysql_port; + + if (!host) + host= LOCAL_HOST; + + my_snprintf(host_info=buff, sizeof(buff)-1, ER(CR_TCP_CONNECTION), host); + DBUG_PRINT("info",("Server name: '%s'. TCP sock: %d", host, port)); + DBUG_PRINT("info",("IP '%s'", "client")); + + memset(&hints, 0, sizeof(hints)); + hints.ai_socktype= SOCK_STREAM; + hints.ai_protocol= IPPROTO_TCP; + hints.ai_family= AF_UNSPEC; + + DBUG_PRINT("info",("IPV6 getaddrinfo %s", host)); + my_snprintf(port_buf, NI_MAXSERV, "%d", port); + gai_errno= getaddrinfo(host, port_buf, &hints, &res_lst); + + if (gai_errno != 0) + { + /* + For DBUG we are keeping the right message but for client we default to + historical error message. + */ + DBUG_PRINT("info",("IPV6 getaddrinfo error %d", gai_errno)); + set_mysql_extended_error(mysql, CR_UNKNOWN_HOST, unknown_sqlstate, + ER(CR_UNKNOWN_HOST), host, gai_errno); + + goto error; + } + + /* + A hostname might map to multiple IP addresses (IPv4/IPv6). Go over the + list of IP addresses until a successful connection can be established. + */ + DBUG_PRINT("info", ("Try connect on all addresses for host.")); + for (t_res= res_lst; t_res; t_res= t_res->ai_next) + { + DBUG_PRINT("info", ("Create socket, family: %d type: %d proto: %d", + t_res->ai_family, t_res->ai_socktype, + t_res->ai_protocol)); + sock= socket(t_res->ai_family, t_res->ai_socktype, t_res->ai_protocol); + if (sock == INVALID_SOCKET) + { + saved_error= socket_errno; + continue; + } + + net->vio= vio_new(sock, VIO_TYPE_TCPIP, VIO_BUFFERED_READ); + if (!net->vio) + { + set_mysql_error(mysql, CR_OUT_OF_MEMORY, unknown_sqlstate); + closesocket(sock); + freeaddrinfo(res_lst); + goto error; + } + + DBUG_PRINT("info", ("Connect socket")); + status= connect_sync_or_async(mysql, net, sock, + t_res->ai_addr, (uint)t_res->ai_addrlen); + /* + Here we rely on my_connect() to return success only if the + connect attempt was really successful. Otherwise we would stop + trying another address, believing we were successful. + */ + if (!status) + break; + + /* + Save value as socket errno might be overwritten due to + calling a socket function below. + */ + saved_error= socket_errno; + + DBUG_PRINT("info", ("No success, close socket, try next address.")); + vio_delete(mysql->net.vio); + mysql->net.vio= 0; + } + DBUG_PRINT("info", + ("End of connect attempts, sock: %d status: %d error: %d", + (int)sock, status, saved_error)); + + freeaddrinfo(res_lst); + + if (sock == INVALID_SOCKET) + { + set_mysql_extended_error(mysql, CR_IPSOCK_ERROR, unknown_sqlstate, + ER(CR_IPSOCK_ERROR), saved_error); + goto error; + } + + if (status) + { + DBUG_PRINT("error",("Got error %d on connect to '%s'", saved_error, host)); + set_mysql_extended_error(mysql, CR_CONN_HOST_ERROR, unknown_sqlstate, + ER(CR_CONN_HOST_ERROR), host, saved_error); + goto error; + } + } + + DBUG_PRINT("info", ("net->vio: %p", net->vio)); + if (!net->vio) + { + DBUG_PRINT("error",("Unknown protocol %d ",mysql->options.protocol)); + set_mysql_error(mysql, CR_CONN_UNKNOW_PROTOCOL, unknown_sqlstate); + goto error; + } + + if (mysql->options.extension && mysql->options.extension->async_context) + net->vio->async_context= mysql->options.extension->async_context; + + if (my_net_init(net, net->vio, _current_thd(), MYF(0))) + { + vio_delete(net->vio); + net->vio = 0; + set_mysql_error(mysql, CR_OUT_OF_MEMORY, unknown_sqlstate); + goto error; + } + vio_keepalive(net->vio,TRUE); + + /* If user set read_timeout, let it override the default */ + if (mysql->options.read_timeout) + my_net_set_read_timeout(net, mysql->options.read_timeout); + + /* If user set write_timeout, let it override the default */ + if (mysql->options.write_timeout) + my_net_set_write_timeout(net, mysql->options.write_timeout); + + if (mysql->options.max_allowed_packet) + net->max_packet_size= mysql->options.max_allowed_packet; + + /* Get version info */ + mysql->protocol_version= PROTOCOL_VERSION; /* Assume this */ + if (mysql->options.connect_timeout && + (vio_io_wait(net->vio, VIO_IO_EVENT_READ, + get_vio_connect_timeout(mysql)) < 1)) + { + set_mysql_extended_error(mysql, CR_SERVER_LOST, unknown_sqlstate, + ER(CR_SERVER_LOST_EXTENDED), + "waiting for initial communication packet", + errno); + goto error; + } + + /* + Part 1: Connection established, read and parse first packet + */ + DBUG_PRINT("info", ("Read first packet.")); + + if ((pkt_length=cli_safe_read(mysql)) == packet_error) + { + if (mysql->net.last_errno == CR_SERVER_LOST) + set_mysql_extended_error(mysql, CR_SERVER_LOST, unknown_sqlstate, + ER(CR_SERVER_LOST_EXTENDED), + "reading initial communication packet", + errno); + goto error; + } + pkt_end= (char*)net->read_pos + pkt_length; + /* Check if version of protocol matches current one */ + mysql->protocol_version= net->read_pos[0]; + DBUG_DUMP("packet",(uchar*) net->read_pos,10); + DBUG_PRINT("info",("mysql protocol version %d, server=%d", + PROTOCOL_VERSION, mysql->protocol_version)); + if (mysql->protocol_version != PROTOCOL_VERSION) + { + set_mysql_extended_error(mysql, CR_VERSION_ERROR, unknown_sqlstate, + ER(CR_VERSION_ERROR), mysql->protocol_version, + PROTOCOL_VERSION); + goto error; + } + server_version_end= end= strend((char*) net->read_pos+1); + mysql->thread_id=uint4korr(end+1); + end+=5; + /* + Scramble is split into two parts because old clients do not understand + long scrambles; here goes the first part. + */ + scramble_data= end; + scramble_data_len= SCRAMBLE_LENGTH_323 + 1; + scramble_plugin= old_password_plugin_name; + end+= scramble_data_len; + + if (pkt_end >= end + 1) + mysql->server_capabilities=uint2korr(end); + if (pkt_end >= end + 18) + { + /* New protocol with 16 bytes to describe server characteristics */ + mysql->server_language=end[2]; + mysql->server_status=uint2korr(end+3); + mysql->server_capabilities|= ((unsigned) uint2korr(end+5)) << 16; + pkt_scramble_len= end[7]; + if (pkt_scramble_len < 0) + { + set_mysql_error(mysql, CR_MALFORMED_PACKET, + unknown_sqlstate); /* purecov: inspected */ + goto error; + } + } + end+= 18; + + if (mysql->options.secure_auth && passwd[0] && + !(mysql->server_capabilities & CLIENT_SECURE_CONNECTION)) + { + set_mysql_error(mysql, CR_SECURE_AUTH, unknown_sqlstate); + goto error; + } + + if (mysql_init_character_set(mysql)) + goto error; + + /* Save connection information */ + if (!my_multi_malloc(key_memory_MYSQL, MYF(0), + &mysql->host_info, (uint) strlen(host_info)+1, + &mysql->host, (uint) strlen(host)+1, + &mysql->unix_socket,unix_socket ? + (uint) strlen(unix_socket)+1 : (uint) 1, + &mysql->server_version, + (uint) (server_version_end - (char*) net->read_pos + 1), + NullS) || + !(mysql->user=my_strdup(key_memory_MYSQL, user,MYF(0))) || + !(mysql->passwd=my_strdup(key_memory_MYSQL, passwd,MYF(0)))) + { + set_mysql_error(mysql, CR_OUT_OF_MEMORY, unknown_sqlstate); + goto error; + } + strmov(mysql->host_info,host_info); + strmov(mysql->host,host); + if (unix_socket) + strmov(mysql->unix_socket,unix_socket); + else + mysql->unix_socket=0; + strmov(mysql->server_version,(char*) net->read_pos+1); + mysql->port=port; + + /* + remove the rpl hack from the version string, + see RPL_VERSION_HACK comment + */ + if ((mysql->server_capabilities & CLIENT_PLUGIN_AUTH) && + strncmp(mysql->server_version, RPL_VERSION_HACK, + sizeof(RPL_VERSION_HACK) - 1) == 0) + mysql->server_version+= sizeof(RPL_VERSION_HACK) - 1; + + if (pkt_end >= end + SCRAMBLE_LENGTH - SCRAMBLE_LENGTH_323 + 1) + { + /* + move the first scramble part - directly in the NET buffer - + to get a full continuous scramble. We've read all the header, + and can overwrite it now. + */ + memmove(end - SCRAMBLE_LENGTH_323, scramble_data, + SCRAMBLE_LENGTH_323); + scramble_data= end - SCRAMBLE_LENGTH_323; + if (mysql->server_capabilities & CLIENT_PLUGIN_AUTH) + { + scramble_data_len= pkt_scramble_len; + scramble_plugin= scramble_data + scramble_data_len; + if (scramble_data + scramble_data_len > pkt_end) + { + set_mysql_error(mysql, CR_MALFORMED_PACKET, unknown_sqlstate); + goto error; + } + } + else + { + scramble_data_len= (int)(pkt_end - scramble_data); + scramble_plugin= native_password_plugin_name; + } + } + else + mysql->server_capabilities&= ~CLIENT_SECURE_CONNECTION; + + mysql->client_flag= client_flag; + + set_connect_attributes(mysql, buff, sizeof(buff)); + + /* + Part 2: invoke the plugin to send the authentication data to the server + */ + + if (run_plugin_auth(mysql, scramble_data, scramble_data_len, + scramble_plugin, db)) + goto error; + + /* + Part 3: authenticated, finish the initialization of the connection + */ + + if (mysql->client_flag & CLIENT_COMPRESS) /* We will use compression */ + net->compress=1; + + if (db && !mysql->db && mysql_select_db(mysql, db)) + { + if (mysql->net.last_errno == CR_SERVER_LOST) + set_mysql_extended_error(mysql, CR_SERVER_LOST, unknown_sqlstate, + ER(CR_SERVER_LOST_EXTENDED), + "Setting intital database", + errno); + goto error; + } + + /* + Using init_commands is not supported when connecting from within the + server. + */ +#ifndef MYSQL_SERVER + if (mysql->options.init_commands) + { + DYNAMIC_ARRAY *init_commands= mysql->options.init_commands; + char **ptr= (char**)init_commands->buffer; + char **end_command= ptr + init_commands->elements; + + my_bool reconnect=mysql->reconnect; + mysql->reconnect=0; + + for (; ptr < end_command; ptr++) + { + int status; + + if (mysql_real_query(mysql,*ptr, (ulong) strlen(*ptr))) + goto error; + + do { + if (mysql->fields) + { + MYSQL_RES *res; + if (!(res= cli_use_result(mysql))) + goto error; + mysql_free_result(res); + } + if ((status= mysql_next_result(mysql)) > 0) + goto error; + } while (status == 0); + } + mysql->reconnect=reconnect; + } +#endif + + DBUG_PRINT("exit", ("Mysql handler: %p",mysql)); + DBUG_RETURN(mysql); + +error: + DBUG_PRINT("error",("message: %u/%s (%s)", + net->last_errno, + net->sqlstate, + net->last_error)); + { + /* Free alloced memory */ + end_server(mysql); + mysql_close_free(mysql); + if (!(client_flag & CLIENT_REMEMBER_OPTIONS) && + !(mysql->options.extension && mysql->options.extension->async_context)) + mysql_close_free_options(mysql); + } + DBUG_RETURN(0); +} + + +struct my_hook_data { + MYSQL *orig_mysql; + MYSQL *new_mysql; + /* This is always NULL currently, but restoring does not hurt just in case. */ + Vio *orig_vio; +}; +/* + Callback hook to make the new VIO accessible via the old MYSQL to calling + application when suspending a non-blocking call during automatic reconnect. +*/ +static void +my_suspend_hook(my_bool suspend, void *data) +{ + struct my_hook_data *hook_data= (struct my_hook_data *)data; + if (suspend) + { + hook_data->orig_vio= hook_data->orig_mysql->net.vio; + hook_data->orig_mysql->net.vio= hook_data->new_mysql->net.vio; + } + else + hook_data->orig_mysql->net.vio= hook_data->orig_vio; +} + +my_bool mysql_reconnect(MYSQL *mysql) +{ + MYSQL tmp_mysql; + struct my_hook_data hook_data; + struct mysql_async_context *ctxt= NULL; + DBUG_ENTER("mysql_reconnect"); + DBUG_ASSERT(mysql); + DBUG_PRINT("enter", ("mysql->reconnect: %d", mysql->reconnect)); + + if (!mysql->reconnect || + (mysql->server_status & SERVER_STATUS_IN_TRANS) || !mysql->host_info) + { + /* Allow reconnect next time */ + mysql->server_status&= ~SERVER_STATUS_IN_TRANS; + set_mysql_error(mysql, CR_SERVER_GONE_ERROR, unknown_sqlstate); + DBUG_RETURN(1); + } + mysql_init(&tmp_mysql); + tmp_mysql.options= mysql->options; + tmp_mysql.options.my_cnf_file= tmp_mysql.options.my_cnf_group= 0; + + /* + If we are automatically re-connecting inside a non-blocking API call, we + may need to suspend and yield to the user application during the reconnect. + If so, the user application will need access to the new VIO already then + so that it can correctly wait for I/O to become ready. + To achieve this, we temporarily install a hook that will temporarily put in + the VIO while we are suspended. + (The vio will be put in the original MYSQL permanently once we successfully + reconnect, or be discarded if we fail to reconnect.) + */ + if (mysql->options.extension && + (ctxt= mysql->options.extension->async_context) && + mysql->options.extension->async_context->active) + { + hook_data.orig_mysql= mysql; + hook_data.new_mysql= &tmp_mysql; + hook_data.orig_vio= mysql->net.vio; + my_context_install_suspend_resume_hook(ctxt, my_suspend_hook, &hook_data); + } + if (!mysql_real_connect(&tmp_mysql,mysql->host,mysql->user,mysql->passwd, + mysql->db, mysql->port, mysql->unix_socket, + mysql->client_flag | CLIENT_REMEMBER_OPTIONS)) + { + if (ctxt) + my_context_install_suspend_resume_hook(ctxt, NULL, NULL); + mysql->net.last_errno= tmp_mysql.net.last_errno; + strmov(mysql->net.last_error, tmp_mysql.net.last_error); + strmov(mysql->net.sqlstate, tmp_mysql.net.sqlstate); + DBUG_RETURN(1); + } + if (mysql_set_character_set(&tmp_mysql, mysql->charset->csname)) + { + DBUG_PRINT("error", ("mysql_set_character_set() failed")); + bzero((char*) &tmp_mysql.options,sizeof(tmp_mysql.options)); + mysql_close(&tmp_mysql); + if (ctxt) + my_context_install_suspend_resume_hook(ctxt, NULL, NULL); + mysql->net.last_errno= tmp_mysql.net.last_errno; + strmov(mysql->net.last_error, tmp_mysql.net.last_error); + strmov(mysql->net.sqlstate, tmp_mysql.net.sqlstate); + DBUG_RETURN(1); + } + if (ctxt) + my_context_install_suspend_resume_hook(ctxt, NULL, NULL); + + DBUG_PRINT("info", ("reconnect succeeded")); + tmp_mysql.reconnect= 1; + tmp_mysql.free_me= mysql->free_me; + + /* Move prepared statements (if any) over to the new mysql object */ + tmp_mysql.stmts= mysql->stmts; + mysql->stmts= 0; + + /* Don't free options as these are now used in tmp_mysql */ + bzero((char*) &mysql->options,sizeof(mysql->options)); + mysql->free_me=0; + mysql_close(mysql); + *mysql=tmp_mysql; + net_clear(&mysql->net, 1); + mysql->affected_rows= ~(my_ulonglong) 0; + DBUG_RETURN(0); +} + + +/************************************************************************** + Set current database +**************************************************************************/ + +int STDCALL +mysql_select_db(MYSQL *mysql, const char *db) +{ + int error; + DBUG_ENTER("mysql_select_db"); + DBUG_PRINT("enter",("db: '%s'",db)); + + if ((error=simple_command(mysql,COM_INIT_DB, (const uchar*) db, + (ulong) strlen(db),0))) + DBUG_RETURN(error); + my_free(mysql->db); + mysql->db=my_strdup(key_memory_MYSQL, db,MYF(MY_WME)); + DBUG_RETURN(0); +} + + +/************************************************************************* + Send a QUIT to the server and close the connection + If handle is alloced by mysql connect free it. +*************************************************************************/ + +static void mysql_close_free_options(MYSQL *mysql) +{ + DBUG_ENTER("mysql_close_free_options"); + + my_free(mysql->options.user); + my_free(mysql->options.host); + my_free(mysql->options.password); + my_free(mysql->options.unix_socket); + my_free(mysql->options.db); + my_free(mysql->options.my_cnf_file); + my_free(mysql->options.my_cnf_group); + my_free(mysql->options.charset_dir); + my_free(mysql->options.charset_name); + my_free(mysql->options.client_ip); + if (mysql->options.init_commands) + { + DYNAMIC_ARRAY *init_commands= mysql->options.init_commands; + char **ptr= (char**)init_commands->buffer; + char **end= ptr + init_commands->elements; + for (; ptr<end; ptr++) + my_free(*ptr); + delete_dynamic(init_commands); + my_free(init_commands); + } +#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) + mysql_ssl_free(mysql); +#endif /* HAVE_OPENSSL && !EMBEDDED_LIBRARY */ + if (mysql->options.extension) + { + struct mysql_async_context *ctxt= mysql->options.extension->async_context; + my_free(mysql->options.extension->plugin_dir); + my_free(mysql->options.extension->default_auth); + my_hash_free(&mysql->options.extension->connection_attributes); + if (ctxt) + { + my_context_destroy(&ctxt->async_context); + my_free(ctxt); + } + my_free(mysql->options.extension); + } + bzero((char*) &mysql->options,sizeof(mysql->options)); + DBUG_VOID_RETURN; +} + + +static void mysql_close_free(MYSQL *mysql) +{ + my_free(mysql->host_info); + my_free(mysql->user); + my_free(mysql->passwd); + my_free(mysql->db); +#if defined(EMBEDDED_LIBRARY) || MYSQL_VERSION_ID >= 50100 + my_free(mysql->info_buffer); + mysql->info_buffer= 0; +#endif + /* Clear pointers for better safety */ + mysql->host_info= mysql->user= mysql->passwd= mysql->db= 0; +} + + +/** + For use when the connection to the server has been lost (in which case + the server has discarded all information about prepared statements + associated with the connection). + + Mark all statements in mysql->stmts by setting stmt->mysql= 0 if the + statement has transitioned beyond the MYSQL_STMT_INIT_DONE state, and + unlink the statement from the mysql->stmts list. + + The remaining pruned list of statements (if any) is kept in mysql->stmts. + + @param mysql pointer to the MYSQL object + + @return none +*/ +static void mysql_prune_stmt_list(MYSQL *mysql) +{ + LIST *element= mysql->stmts; + for (; element; element= element->next) + { + MYSQL_STMT *stmt= (MYSQL_STMT *) element->data; + if (stmt->state != MYSQL_STMT_INIT_DONE) + { + stmt->mysql= 0; + stmt->last_errno= CR_SERVER_LOST; + strmov(stmt->last_error, ER(CR_SERVER_LOST)); + strmov(stmt->sqlstate, unknown_sqlstate); + mysql->stmts= list_delete(mysql->stmts, element); + } + } +} + + +/* + Clear connection pointer of every statement: this is necessary + to give error on attempt to use a prepared statement of closed + connection. + + SYNOPSYS + mysql_detach_stmt_list() + stmt_list pointer to mysql->stmts + func_name name of calling function + + NOTE + There is similar code in mysql_reconnect(), so changes here + should also be reflected there. +*/ + +void mysql_detach_stmt_list(LIST **stmt_list __attribute__((unused)), + const char *func_name __attribute__((unused))) +{ +#ifdef MYSQL_CLIENT + /* Reset connection handle in all prepared statements. */ + LIST *element= *stmt_list; + char buff[MYSQL_ERRMSG_SIZE]; + DBUG_ENTER("mysql_detach_stmt_list"); + + my_snprintf(buff, sizeof(buff)-1, ER(CR_STMT_CLOSED), func_name); + for (; element; element= element->next) + { + MYSQL_STMT *stmt= (MYSQL_STMT *) element->data; + set_stmt_error(stmt, CR_STMT_CLOSED, unknown_sqlstate, buff); + stmt->mysql= 0; + /* No need to call list_delete for statement here */ + } + *stmt_list= 0; + DBUG_VOID_RETURN; +#endif /* MYSQL_CLIENT */ +} + + +/* + Close a MySQL connection and free all resources attached to it. + + This function is coded in such that it can be called multiple times + (As some clients call this after mysql_real_connect() fails) +*/ + +/* + mysql_close() can actually block, at least in theory, if the socket buffer + is full when sending the COM_QUIT command. + + On the other hand, the latter part of mysql_close() needs to free the stack + used for non-blocking operation of blocking stuff, so that later part can + _not_ be done non-blocking. + + Therefore, mysql_close_slow_part() is used to run the parts of mysql_close() + that may block. It can be called before mysql_close(), and in that case + mysql_close() is guaranteed not to need to block. */ +void STDCALL mysql_close_slow_part(MYSQL *mysql) +{ + /* If connection is still up, send a QUIT message */ + if (mysql->net.vio != 0) + { + free_old_query(mysql); + mysql->status=MYSQL_STATUS_READY; /* Force command */ + mysql->reconnect=0; + simple_command(mysql,COM_QUIT,(uchar*) 0,0,1); + end_server(mysql); /* Sets mysql->net.vio= 0 */ + } +} + +void STDCALL mysql_close(MYSQL *mysql) +{ + DBUG_ENTER("mysql_close"); + DBUG_PRINT("enter", ("mysql: %p", mysql)); + + if (mysql) /* Some simple safety */ + { + mysql_close_slow_part(mysql); + mysql_close_free_options(mysql); + mysql_close_free(mysql); + mysql_detach_stmt_list(&mysql->stmts, "mysql_close"); +#ifndef MYSQL_SERVER + if (mysql->thd) + { + (*mysql->methods->free_embedded_thd)(mysql); + mysql->thd= 0; + } +#endif + if (mysql->free_me) + my_free(mysql); + } + DBUG_VOID_RETURN; +} + + +static my_bool cli_read_query_result(MYSQL *mysql) +{ + uchar *pos; + ulong field_count; + MYSQL_DATA *fields; + ulong length; +#ifdef MYSQL_CLIENT + my_bool can_local_infile= mysql->auto_local_infile != WAIT_FOR_QUERY; +#endif + DBUG_ENTER("cli_read_query_result"); + + if (mysql->auto_local_infile == ACCEPT_FILE_REQUEST) + mysql->auto_local_infile= WAIT_FOR_QUERY; + + if ((length = cli_safe_read(mysql)) == packet_error) + DBUG_RETURN(1); + free_old_query(mysql); /* Free old result */ +#ifdef MYSQL_CLIENT /* Avoid warn of unused labels*/ +get_info: +#endif + pos=(uchar*) mysql->net.read_pos; + if ((field_count= net_field_length(&pos)) == 0) + { + mysql->affected_rows= net_field_length_ll(&pos); + mysql->insert_id= net_field_length_ll(&pos); + DBUG_PRINT("info",("affected_rows: %lu insert_id: %lu", + (ulong) mysql->affected_rows, + (ulong) mysql->insert_id)); + if (protocol_41(mysql)) + { + mysql->server_status=uint2korr(pos); pos+=2; + mysql->warning_count=uint2korr(pos); pos+=2; + } + else if (mysql->server_capabilities & CLIENT_TRANSACTIONS) + { + /* MySQL 4.0 protocol */ + mysql->server_status=uint2korr(pos); pos+=2; + mysql->warning_count= 0; + } + DBUG_PRINT("info",("status: %u warning_count: %u", + mysql->server_status, mysql->warning_count)); + if (pos < mysql->net.read_pos+length && net_field_length(&pos)) + mysql->info=(char*) pos; + DBUG_RETURN(0); + } +#ifdef MYSQL_CLIENT + if (field_count == NULL_LENGTH) /* LOAD DATA LOCAL INFILE */ + { + int error; + + if (!(mysql->options.client_flag & CLIENT_LOCAL_FILES) || + !can_local_infile) + { + set_mysql_error(mysql, CR_MALFORMED_PACKET, unknown_sqlstate); + DBUG_RETURN(1); + } + + error= handle_local_infile(mysql,(char*) pos); + if ((length= cli_safe_read(mysql)) == packet_error || error) + DBUG_RETURN(1); + goto get_info; /* Get info packet */ + } +#endif + if (!(mysql->server_status & SERVER_STATUS_AUTOCOMMIT)) + mysql->server_status|= SERVER_STATUS_IN_TRANS; + + if (!(fields=cli_read_rows(mysql,(MYSQL_FIELD*)0, protocol_41(mysql) ? 7:5))) + DBUG_RETURN(1); + if (!(mysql->fields=unpack_fields(mysql, fields,&mysql->field_alloc, + (uint) field_count,0, + mysql->server_capabilities))) + DBUG_RETURN(1); + mysql->status= MYSQL_STATUS_GET_RESULT; + mysql->field_count= (uint) field_count; + DBUG_PRINT("exit",("ok")); + DBUG_RETURN(0); +} + + +/* + Send the query and return so we can do something else. + Needs to be followed by mysql_read_query_result() when we want to + finish processing it. +*/ + +int STDCALL +mysql_send_query(MYSQL* mysql, const char* query, ulong length) +{ + DBUG_ENTER("mysql_send_query"); + if (mysql->options.client_flag & CLIENT_LOCAL_FILES && + mysql->auto_local_infile == WAIT_FOR_QUERY && + (*query == 'l' || *query == 'L')) + { + if (strncasecmp(query, STRING_WITH_LEN("load")) == 0) + mysql->auto_local_infile= ACCEPT_FILE_REQUEST; + } + DBUG_RETURN(simple_command(mysql, COM_QUERY, (uchar*) query, length, 1)); +} + +int STDCALL +mysql_real_query(MYSQL *mysql, const char *query, ulong length) +{ + DBUG_ENTER("mysql_real_query"); + DBUG_PRINT("enter",("handle: %p", mysql)); + DBUG_PRINT("query",("Query = '%-.4096s'",query)); + + if (mysql_send_query(mysql,query,length)) + DBUG_RETURN(1); + DBUG_RETURN((int) (*mysql->methods->read_query_result)(mysql)); +} + + +/************************************************************************** + Alloc result struct for buffered results. All rows are read to buffer. + mysql_data_seek may be used. +**************************************************************************/ + +MYSQL_RES * STDCALL mysql_store_result(MYSQL *mysql) +{ + MYSQL_RES *result; + DBUG_ENTER("mysql_store_result"); + + if (!mysql->fields) + DBUG_RETURN(0); + if (mysql->status != MYSQL_STATUS_GET_RESULT) + { + set_mysql_error(mysql, CR_COMMANDS_OUT_OF_SYNC, unknown_sqlstate); + DBUG_RETURN(0); + } + mysql->status=MYSQL_STATUS_READY; /* server is ready */ + if (!(result=(MYSQL_RES*) my_malloc(key_memory_MYSQL_RES, + (uint) (sizeof(MYSQL_RES)+ + sizeof(ulong) * + mysql->field_count), + MYF(MY_WME | MY_ZEROFILL)))) + { + set_mysql_error(mysql, CR_OUT_OF_MEMORY, unknown_sqlstate); + DBUG_RETURN(0); + } + result->methods= mysql->methods; + result->eof=1; /* Marker for buffered */ + result->lengths=(ulong*) (result+1); + if (!(result->data= + (*mysql->methods->read_rows)(mysql,mysql->fields,mysql->field_count))) + { + my_free(result); + DBUG_RETURN(0); + } + mysql->affected_rows= result->row_count= result->data->rows; + result->data_cursor= result->data->data; + result->fields= mysql->fields; + result->field_alloc= mysql->field_alloc; + result->field_count= mysql->field_count; + /* The rest of result members is bzeroed in malloc */ + mysql->fields=0; /* fields is now in result */ + clear_alloc_root(&mysql->field_alloc); + /* just in case this was mistakenly called after mysql_stmt_execute() */ + mysql->unbuffered_fetch_owner= 0; + DBUG_RETURN(result); /* Data fetched */ +} + + +/************************************************************************** + Alloc struct for use with unbuffered reads. Data is fetched by domand + when calling to mysql_fetch_row. + mysql_data_seek is a noop. + + No other queries may be specified with the same MYSQL handle. + There shouldn't be much processing per row because mysql server shouldn't + have to wait for the client (and will not wait more than 30 sec/packet). +**************************************************************************/ + +static MYSQL_RES * cli_use_result(MYSQL *mysql) +{ + MYSQL_RES *result; + DBUG_ENTER("cli_use_result"); + + if (!mysql->fields) + DBUG_RETURN(0); + if (mysql->status != MYSQL_STATUS_GET_RESULT) + { + set_mysql_error(mysql, CR_COMMANDS_OUT_OF_SYNC, unknown_sqlstate); + DBUG_RETURN(0); + } + if (!(result=(MYSQL_RES*) my_malloc(key_memory_MYSQL_RES, + sizeof(*result)+ + sizeof(ulong)*mysql->field_count, + MYF(MY_WME | MY_ZEROFILL)))) + DBUG_RETURN(0); + result->lengths=(ulong*) (result+1); + result->methods= mysql->methods; + if (!(result->row=(MYSQL_ROW) + my_malloc(key_memory_MYSQL_ROW, + sizeof(result->row[0])*(mysql->field_count+1), MYF(MY_WME)))) + { /* Ptrs: to one row */ + my_free(result); + DBUG_RETURN(0); + } + result->fields= mysql->fields; + result->field_alloc= mysql->field_alloc; + result->field_count= mysql->field_count; + result->current_field=0; + result->handle= mysql; + result->current_row= 0; + mysql->fields=0; /* fields is now in result */ + clear_alloc_root(&mysql->field_alloc); + mysql->status=MYSQL_STATUS_USE_RESULT; + mysql->unbuffered_fetch_owner= &result->unbuffered_fetch_cancelled; + DBUG_RETURN(result); /* Data is read to be fetched */ +} + + +my_ulonglong STDCALL mysql_affected_rows(MYSQL *mysql) +{ + return mysql->affected_rows; +} + + +/************************************************************************** + Return next row of the query results +**************************************************************************/ + +MYSQL_ROW STDCALL +mysql_fetch_row(MYSQL_RES *res) +{ + DBUG_ENTER("mysql_fetch_row"); + if (!res->data) + { /* Unbufferred fetch */ + if (!res->eof) + { + MYSQL *mysql= res->handle; + if (mysql->status != MYSQL_STATUS_USE_RESULT) + { + set_mysql_error(mysql, + res->unbuffered_fetch_cancelled ? + CR_FETCH_CANCELED : CR_COMMANDS_OUT_OF_SYNC, + unknown_sqlstate); + } + else if (!(read_one_row(mysql, res->field_count, res->row, res->lengths))) + { + res->row_count++; + DBUG_RETURN(res->current_row=res->row); + } + DBUG_PRINT("info",("end of data")); + res->eof=1; + mysql->status=MYSQL_STATUS_READY; + /* + Reset only if owner points to us: there is a chance that somebody + started new query after mysql_stmt_close(): + */ + if (mysql->unbuffered_fetch_owner == &res->unbuffered_fetch_cancelled) + mysql->unbuffered_fetch_owner= 0; + /* Don't clear handle in mysql_free_result */ + res->handle=0; + } + DBUG_RETURN((MYSQL_ROW) NULL); + } + { + MYSQL_ROW tmp; + if (!res->data_cursor) + { + DBUG_PRINT("info",("end of data")); + DBUG_RETURN(res->current_row=(MYSQL_ROW) NULL); + } + tmp = res->data_cursor->data; + res->data_cursor = res->data_cursor->next; + DBUG_RETURN(res->current_row=tmp); + } +} + + +/************************************************************************** + Get column lengths of the current row + If one uses mysql_use_result, res->lengths contains the length information, + else the lengths are calculated from the offset between pointers. +**************************************************************************/ + +ulong * STDCALL +mysql_fetch_lengths(MYSQL_RES *res) +{ + MYSQL_ROW column; + + if (!(column=res->current_row)) + return 0; /* Something is wrong */ + if (res->data) + (*res->methods->fetch_lengths)(res->lengths, column, res->field_count); + return res->lengths; +} + + +#define ASYNC_CONTEXT_DEFAULT_STACK_SIZE (4096*15) + +int STDCALL +mysql_options(MYSQL *mysql,enum mysql_option option, const void *arg) +{ + struct mysql_async_context *ctxt; + size_t stacksize; + + DBUG_ENTER("mysql_options"); + DBUG_PRINT("enter",("option: %d",(int) option)); + switch (option) { + case MYSQL_OPT_CONNECT_TIMEOUT: + mysql->options.connect_timeout= *(uint*) arg; + break; + case MYSQL_OPT_READ_TIMEOUT: + mysql->options.read_timeout= *(uint*) arg; + break; + case MYSQL_OPT_WRITE_TIMEOUT: + mysql->options.write_timeout= *(uint*) arg; + break; + case MYSQL_OPT_COMPRESS: + mysql->options.compress= 1; /* Remember for connect */ + mysql->options.client_flag|= CLIENT_COMPRESS; + break; + case MYSQL_OPT_NAMED_PIPE: /* This option is depricated */ + mysql->options.protocol=MYSQL_PROTOCOL_PIPE; /* Force named pipe */ + break; + case MYSQL_OPT_LOCAL_INFILE: /* Allow LOAD DATA LOCAL ?*/ + if (!arg || *(uint*) arg) + mysql->options.client_flag|= CLIENT_LOCAL_FILES; + else + mysql->options.client_flag&= ~CLIENT_LOCAL_FILES; + mysql->auto_local_infile= arg && *(uint*)arg == LOCAL_INFILE_MODE_AUTO + ? WAIT_FOR_QUERY : ALWAYS_ACCEPT; + break; + case MYSQL_INIT_COMMAND: + add_init_command(&mysql->options,arg); + break; + case MYSQL_READ_DEFAULT_FILE: + my_free(mysql->options.my_cnf_file); + mysql->options.my_cnf_file= opt_strdup(arg,MYF(MY_WME)); + break; + case MYSQL_READ_DEFAULT_GROUP: + my_free(mysql->options.my_cnf_group); + mysql->options.my_cnf_group= opt_strdup(arg,MYF(MY_WME)); + break; + case MYSQL_SET_CHARSET_DIR: + my_free(mysql->options.charset_dir); + mysql->options.charset_dir= opt_strdup(arg,MYF(MY_WME)); + break; + case MYSQL_SET_CHARSET_NAME: + my_free(mysql->options.charset_name); + mysql->options.charset_name= opt_strdup(arg,MYF(MY_WME)); + break; + case MYSQL_OPT_PROTOCOL: + mysql->options.protocol= *(uint*) arg; + break; + case MYSQL_OPT_USE_REMOTE_CONNECTION: + case MYSQL_OPT_USE_EMBEDDED_CONNECTION: + case MYSQL_OPT_GUESS_CONNECTION: + mysql->options.methods_to_use= option; + break; + case MYSQL_SET_CLIENT_IP: + my_free(mysql->options.client_ip); + mysql->options.client_ip= opt_strdup(arg, MYF(MY_WME)); + break; + case MYSQL_SECURE_AUTH: + mysql->options.secure_auth= *(my_bool *) arg; + break; + case MYSQL_REPORT_DATA_TRUNCATION: + mysql->options.report_data_truncation= MY_TEST(*(my_bool*) arg); + break; + case MYSQL_OPT_RECONNECT: + mysql->reconnect= *(my_bool *) arg; + break; + case MYSQL_OPT_USE_THREAD_SPECIFIC_MEMORY: + mysql->options.use_thread_specific_memory= *(my_bool *) arg; + break; + case MYSQL_OPT_SSL_VERIFY_SERVER_CERT: + if (*(my_bool*) arg) + mysql->options.client_flag|= CLIENT_SSL_VERIFY_SERVER_CERT; + else + mysql->options.client_flag&= ~CLIENT_SSL_VERIFY_SERVER_CERT; + break; + case MYSQL_PLUGIN_DIR: + EXTENSION_SET_STRING(&mysql->options, plugin_dir, arg); + break; + case MYSQL_DEFAULT_AUTH: + EXTENSION_SET_STRING(&mysql->options, default_auth, arg); + break; + case MYSQL_ENABLE_CLEARTEXT_PLUGIN: + break; + case MYSQL_PROGRESS_CALLBACK: + if (!mysql->options.extension) + mysql->options.extension= (struct st_mysql_options_extention *) + my_malloc(key_memory_mysql_options, + sizeof(struct st_mysql_options_extention), + MYF(MY_WME | MY_ZEROFILL)); + if (mysql->options.extension) + mysql->options.extension->report_progress= + (void (*)(const MYSQL *, uint, uint, double, const char *, uint)) arg; + break; + case MYSQL_OPT_NONBLOCK: + if (mysql->options.extension && + (ctxt = mysql->options.extension->async_context) != 0) + { + /* + We must not allow changing the stack size while a non-blocking call is + suspended (as the stack is then in use). + */ + if (ctxt->suspended) + DBUG_RETURN(1); + my_context_destroy(&ctxt->async_context); + my_free(ctxt); + } + if (!(ctxt= (struct mysql_async_context *) + my_malloc(PSI_INSTRUMENT_ME, sizeof(*ctxt), MYF(MY_ZEROFILL)))) + { + set_mysql_error(mysql, CR_OUT_OF_MEMORY, unknown_sqlstate); + DBUG_RETURN(1); + } + stacksize= 0; + if (arg) + stacksize= *(const size_t *)arg; + if (!stacksize) + stacksize= ASYNC_CONTEXT_DEFAULT_STACK_SIZE; + if (my_context_init(&ctxt->async_context, stacksize)) + { + set_mysql_error(mysql, CR_OUT_OF_MEMORY, unknown_sqlstate); + my_free(ctxt); + DBUG_RETURN(1); + } + ENSURE_EXTENSIONS_PRESENT(&(mysql->options)); + mysql->options.extension->async_context= ctxt; + if (mysql->net.vio) + mysql->net.vio->async_context= ctxt; + break; + case MYSQL_OPT_SSL_KEY: + SET_SSL_PATH_OPTION(&mysql->options,ssl_key, arg); + break; + case MYSQL_OPT_SSL_CERT: + SET_SSL_PATH_OPTION(&mysql->options, ssl_cert, arg); + break; + case MYSQL_OPT_SSL_CA: + SET_SSL_PATH_OPTION(&mysql->options,ssl_ca, arg); + break; + case MYSQL_OPT_SSL_CAPATH: + SET_SSL_PATH_OPTION(&mysql->options,ssl_capath, arg); + break; + case MYSQL_OPT_SSL_CIPHER: + SET_SSL_OPTION(&mysql->options,ssl_cipher, arg); + break; + case MYSQL_OPT_SSL_CRL: + EXTENSION_SET_SSL_PATH_STRING(&mysql->options, ssl_crl, arg); + break; + case MYSQL_OPT_SSL_CRLPATH: + EXTENSION_SET_SSL_PATH_STRING(&mysql->options, ssl_crlpath, arg); + break; + case MYSQL_OPT_CONNECT_ATTR_RESET: + ENSURE_EXTENSIONS_PRESENT(&mysql->options); + if (my_hash_inited(&mysql->options.extension->connection_attributes)) + { + my_hash_free(&mysql->options.extension->connection_attributes); + mysql->options.extension->connection_attributes_length= 0; + } + break; + case MYSQL_OPT_CONNECT_ATTR_DELETE: + ENSURE_EXTENSIONS_PRESENT(&mysql->options); + if (my_hash_inited(&mysql->options.extension->connection_attributes)) + { + size_t len; + uchar *elt; + + len= arg ? strlen(arg) : 0; + + if (len) + { + elt= my_hash_search(&mysql->options.extension->connection_attributes, + arg, len); + if (elt) + { + LEX_STRING *attr= (LEX_STRING *) elt; + LEX_STRING *key= attr, *value= attr + 1; + + mysql->options.extension->connection_attributes_length-= + get_length_store_length(key->length) + key->length + + get_length_store_length(value->length) + value->length; + + my_hash_delete(&mysql->options.extension->connection_attributes, + elt); + + } + } + } + break; + case MYSQL_SHARED_MEMORY_BASE_NAME: + default: + DBUG_RETURN(1); + } + DBUG_RETURN(0); +} +/** + A function to return the key from a connection attribute +*/ +uchar * +get_attr_key(LEX_STRING *part, size_t *length, + my_bool not_used __attribute__((unused))) +{ + *length= part[0].length; + return (uchar *) part[0].str; +} + +int STDCALL +mysql_options4(MYSQL *mysql,enum mysql_option option, + const void *arg1, const void *arg2) +{ + DBUG_ENTER("mysql_option"); + DBUG_PRINT("enter",("option: %d",(int) option)); + + switch (option) + { + case MYSQL_OPT_CONNECT_ATTR_ADD: + { + LEX_STRING *elt; + char *key, *value; + size_t key_len= arg1 ? strlen(arg1) : 0, + value_len= arg2 ? strlen(arg2) : 0; + size_t attr_storage_length= key_len + value_len; + + /* we can't have a zero length key */ + if (!key_len) + { + set_mysql_error(mysql, CR_INVALID_PARAMETER_NO, unknown_sqlstate); + DBUG_RETURN(1); + } + + /* calculate the total storage length of the attribute */ + attr_storage_length+= get_length_store_length(key_len); + attr_storage_length+= get_length_store_length(value_len); + + ENSURE_EXTENSIONS_PRESENT(&mysql->options); + + /* + Throw and error if the maximum combined length of the attribute value + will be greater than the maximum that we can safely transmit. + */ + if (attr_storage_length + + mysql->options.extension->connection_attributes_length > + MAX_CONNECTION_ATTR_STORAGE_LENGTH) + { + set_mysql_error(mysql, CR_INVALID_PARAMETER_NO, unknown_sqlstate); + DBUG_RETURN(1); + } + + if (!my_hash_inited(&mysql->options.extension->connection_attributes)) + { + if (my_hash_init(key_memory_mysql_options, + &mysql->options.extension->connection_attributes, + &my_charset_bin, 0, 0, 0, (my_hash_get_key) + get_attr_key, my_free, HASH_UNIQUE)) + { + set_mysql_error(mysql, CR_OUT_OF_MEMORY, unknown_sqlstate); + DBUG_RETURN(1); + } + } + if (!my_multi_malloc(key_memory_mysql_options, MYF(MY_WME), + &elt, 2 * sizeof(LEX_STRING), + &key, key_len + 1, + &value, value_len + 1, + NULL)) + { + set_mysql_error(mysql, CR_OUT_OF_MEMORY, unknown_sqlstate); + DBUG_RETURN(1); + } + elt[0].str= key; elt[0].length= key_len; + elt[1].str= value; elt[1].length= value_len; + if (key_len) + memcpy(key, arg1, key_len); + key[key_len]= 0; + if (value_len) + memcpy(value, arg2, value_len); + value[value_len]= 0; + if (my_hash_insert(&mysql->options.extension->connection_attributes, + (uchar *) elt)) + { + /* can't insert the value */ + my_free(elt); + set_mysql_error(mysql, CR_DUPLICATE_CONNECTION_ATTR, + unknown_sqlstate); + DBUG_RETURN(1); + } + + mysql->options.extension->connection_attributes_length+= + attr_storage_length; + + break; + } + + default: + DBUG_RETURN(1); + } + DBUG_RETURN(0); +} + + +/**************************************************************************** + Functions to get information from the MySQL structure + These are functions to make shared libraries more usable. +****************************************************************************/ + +/* MYSQL_RES */ +my_ulonglong STDCALL mysql_num_rows(MYSQL_RES *res) +{ + return res->row_count; +} + +unsigned int STDCALL mysql_num_fields(MYSQL_RES *res) +{ + return res->field_count; +} + +uint STDCALL mysql_errno(MYSQL *mysql) +{ + return mysql ? mysql->net.last_errno : mysql_server_last_errno; +} + + +const char * STDCALL mysql_error(MYSQL *mysql) +{ + return mysql ? mysql->net.last_error : mysql_server_last_error; +} + + +/* + Get version number for server in a form easy to test on + + SYNOPSIS + mysql_get_server_version() + mysql Connection + + EXAMPLE + MariaDB-4.1.0-alfa -> 40100 + + NOTES + We will ensure that a newer server always has a bigger number. + + RETURN + Signed number > 323000 + Zero if there is no connection +*/ + +ulong STDCALL +mysql_get_server_version(MYSQL *mysql) +{ + ulong major= 0, minor= 0, version= 0; + + if (mysql->server_version) + { + const char *pos= mysql->server_version; + char *end_pos; + /* Skip possible prefix */ + while (*pos && !my_isdigit(&my_charset_latin1, *pos)) + pos++; + major= strtoul(pos, &end_pos, 10); pos=end_pos+1; + minor= strtoul(pos, &end_pos, 10); pos=end_pos+1; + version= strtoul(pos, &end_pos, 10); + } + else + { + set_mysql_error(mysql, CR_COMMANDS_OUT_OF_SYNC, unknown_sqlstate); + } + + return major*10000 + minor*100 + version; +} + + +/* + mysql_set_character_set function sends SET NAMES cs_name to + the server (which changes character_set_client, character_set_result + and character_set_connection) and updates mysql->charset so other + functions like mysql_real_escape will work correctly. +*/ +int STDCALL mysql_set_character_set(MYSQL *mysql, const char *cs_name) +{ + CHARSET_INFO *cs; + const char *save_csdir= charsets_dir; + + if (mysql->options.charset_dir) + charsets_dir= mysql->options.charset_dir; + + if (strlen(cs_name) < MY_CS_NAME_SIZE && + (cs= get_charset_by_csname(cs_name, MY_CS_PRIMARY, MYF(0)))) + { + char buff[MY_CS_NAME_SIZE + 10]; + charsets_dir= save_csdir; + /* Skip execution of "SET NAMES" for pre-4.1 servers */ + if (mysql_get_server_version(mysql) < 40100) + return 0; + sprintf(buff, "SET NAMES %s", cs_name); + if (!mysql_real_query(mysql, buff, (uint) strlen(buff))) + { + mysql->charset= cs; + } + } + else + { + char cs_dir_name[FN_REFLEN]; + get_charsets_dir(cs_dir_name); + set_mysql_extended_error(mysql, CR_CANT_READ_CHARSET, unknown_sqlstate, + ER(CR_CANT_READ_CHARSET), cs_name, cs_dir_name); + } + charsets_dir= save_csdir; + return mysql->net.last_errno; +} + +/** + client authentication plugin that does native MySQL authentication + using a 20-byte (4.1+) scramble +*/ +static int native_password_auth_client(MYSQL_PLUGIN_VIO *vio, MYSQL *mysql) +{ + int pkt_len; + uchar *pkt; + + DBUG_ENTER("native_password_auth_client"); + + + if (((MCPVIO_EXT *)vio)->mysql_change_user) + { + /* + in mysql_change_user() the client sends the first packet. + we use the old scramble. + */ + pkt= (uchar*)mysql->scramble; + pkt_len= SCRAMBLE_LENGTH + 1; + } + else + { + /* read the scramble */ + if ((pkt_len= vio->read_packet(vio, &pkt)) < 0) + DBUG_RETURN(CR_ERROR); + + if (pkt_len != SCRAMBLE_LENGTH + 1) + DBUG_RETURN(CR_SERVER_HANDSHAKE_ERR); + + /* save it in MYSQL */ + memcpy(mysql->scramble, pkt, SCRAMBLE_LENGTH); + mysql->scramble[SCRAMBLE_LENGTH] = 0; + } + + if (mysql->passwd[0]) + { + char scrambled[SCRAMBLE_LENGTH + 1]; + DBUG_PRINT("info", ("sending scramble")); + scramble(scrambled, (char*)pkt, mysql->passwd); + if (vio->write_packet(vio, (uchar*)scrambled, SCRAMBLE_LENGTH)) + DBUG_RETURN(CR_ERROR); + } + else + { + DBUG_PRINT("info", ("no password")); + if (vio->write_packet(vio, 0, 0)) /* no password */ + DBUG_RETURN(CR_ERROR); + } + + DBUG_RETURN(CR_OK); +} + +/** + client authentication plugin that does old MySQL authentication + using an 8-byte (4.0-) scramble +*/ +static int old_password_auth_client(MYSQL_PLUGIN_VIO *vio, MYSQL *mysql) +{ + uchar *pkt; + int pkt_len; + + DBUG_ENTER("old_password_auth_client"); + + if (((MCPVIO_EXT *)vio)->mysql_change_user) + { + /* + in mysql_change_user() the client sends the first packet. + we use the old scramble. + */ + pkt= (uchar*)mysql->scramble; + pkt_len= SCRAMBLE_LENGTH_323 + 1; + } + else + { + /* read the scramble */ + if ((pkt_len= vio->read_packet(vio, &pkt)) < 0) + DBUG_RETURN(CR_ERROR); + + if (pkt_len != SCRAMBLE_LENGTH_323 + 1 && + pkt_len != SCRAMBLE_LENGTH + 1) + DBUG_RETURN(CR_SERVER_HANDSHAKE_ERR); + + /* save it in MYSQL */ + memmove(mysql->scramble, pkt, pkt_len - 1); + mysql->scramble[pkt_len - 1] = 0; + } + + if (mysql->passwd[0]) + { + char scrambled[SCRAMBLE_LENGTH_323 + 1]; + scramble_323(scrambled, (char*)pkt, mysql->passwd); + if (vio->write_packet(vio, (uchar*)scrambled, SCRAMBLE_LENGTH_323 + 1)) + DBUG_RETURN(CR_ERROR); + } + else + if (vio->write_packet(vio, 0, 0)) /* no password */ + DBUG_RETURN(CR_ERROR); + + DBUG_RETURN(CR_OK); +} + + +my_socket STDCALL +mysql_get_socket(const MYSQL *mysql) +{ + if (mysql->net.vio) + return vio_fd(mysql->net.vio); + return INVALID_SOCKET; +} + + +int STDCALL mysql_cancel(MYSQL *mysql) +{ + if (mysql->net.vio) + return vio_shutdown(mysql->net.vio, SHUT_RDWR); + return -1; +} diff --git a/sql-common/client_plugin.c b/sql-common/client_plugin.c new file mode 100644 index 00000000..0a2e39f7 --- /dev/null +++ b/sql-common/client_plugin.c @@ -0,0 +1,511 @@ +/* Copyright (C) 2010 Sergei Golubchik and Monty Program Ab + Copyright (c) 2010, 2011, Oracle and/or its affiliates. + + 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-1335 USA */ + +/** + @file + + Support code for the client side (libmysql) plugins + + Client plugins are somewhat different from server plugins, they are simpler. + + They do not need to be installed or in any way explicitly loaded on the + client, they are loaded automatically on demand. + One client plugin per shared object, soname *must* match the plugin name. + + There is no reference counting and no unloading either. +*/ + +#include <my_global.h> +#include "mysql.h" +#include <my_sys.h> +#include <m_string.h> +#include <my_pthread.h> + +#include <sql_common.h> +#include "errmsg.h" +#include <mysql/client_plugin.h> + +PSI_memory_key key_memory_root; +PSI_memory_key key_memory_load_env_plugins; + +#ifdef HAVE_PSI_INTERFACE +PSI_mutex_key key_mutex_LOCK_load_client_plugin; + +static PSI_mutex_info all_client_plugin_mutexes[]= +{ + {&key_mutex_LOCK_load_client_plugin, "LOCK_load_client_plugin", PSI_FLAG_GLOBAL} +}; + +static PSI_memory_info all_client_plugin_memory[]= +{ + {&key_memory_root, "root", PSI_FLAG_GLOBAL}, + {&key_memory_load_env_plugins, "load_env_plugins", PSI_FLAG_GLOBAL} +}; + +static void init_client_plugin_psi_keys() +{ + const char* category= "sql"; + int count; + + count= array_elements(all_client_plugin_mutexes); + mysql_mutex_register(category, all_client_plugin_mutexes, count); + + count= array_elements(all_client_plugin_memory); + mysql_memory_register(category, all_client_plugin_memory, count); +} +#endif /* HAVE_PSI_INTERFACE */ + +struct st_client_plugin_int { + struct st_client_plugin_int *next; + void *dlhandle; + struct st_mysql_client_plugin *plugin; +}; + +static my_bool initialized= 0; +static MEM_ROOT mem_root; + +#define plugin_declarations_sym "_mysql_client_plugin_declaration_" + +static uint plugin_version[MYSQL_CLIENT_MAX_PLUGINS]= +{ + 0, /* these two are taken by Connector/C */ + 0, /* these two are taken by Connector/C */ + MYSQL_CLIENT_AUTHENTICATION_PLUGIN_INTERFACE_VERSION +}; + +/* + Loaded plugins are stored in a linked list. + The list is append-only, the elements are added to the head (like in a stack). + The elements are added under a mutex, but the list can be read and traversed + without any mutex because once an element is added to the list, it stays + there. The main purpose of a mutex is to prevent two threads from + loading the same plugin twice in parallel. +*/ +struct st_client_plugin_int *plugin_list[MYSQL_CLIENT_MAX_PLUGINS]; +static mysql_mutex_t LOCK_load_client_plugin; + +static int is_not_initialized(MYSQL *mysql, const char *name) +{ + DBUG_ENTER("is_not_initialized"); + + if (initialized) + DBUG_RETURN(0); + + set_mysql_extended_error(mysql, CR_AUTH_PLUGIN_CANNOT_LOAD, + unknown_sqlstate, ER(CR_AUTH_PLUGIN_CANNOT_LOAD), + name, "not initialized"); + DBUG_RETURN(1); +} + +/** + finds a plugin in the list + + @param name plugin name to search for + @param type plugin type + + @note this does NOT necessarily need a mutex, take care! + + @retval a pointer to a found plugin or 0 +*/ +static struct st_mysql_client_plugin * +find_plugin(const char *name, int type) +{ + struct st_client_plugin_int *p; + DBUG_ENTER("find_plugin"); + + DBUG_ASSERT(initialized); + DBUG_ASSERT(type >= 0 && type < MYSQL_CLIENT_MAX_PLUGINS); + if (type < 0 || type >= MYSQL_CLIENT_MAX_PLUGINS) + DBUG_RETURN(0); + + for (p= plugin_list[type]; p; p= p->next) + { + if (strcmp(p->plugin->name, name) == 0) + DBUG_RETURN(p->plugin); + } + DBUG_RETURN(NULL); +} + +/** + verifies the plugin and adds it to the list + + @param mysql MYSQL structure (for error reporting) + @param plugin plugin to install + @param dlhandle a handle to the shared object (returned by dlopen) + or 0 if the plugin was not dynamically loaded + @param argc number of arguments in the 'va_list args' + @param args arguments passed to the plugin initialization function + + @retval a pointer to an installed plugin or 0 +*/ +static struct st_mysql_client_plugin * +add_plugin(MYSQL *mysql, struct st_mysql_client_plugin *plugin, void *dlhandle, + int argc, va_list args) +{ + const char *errmsg; + struct st_client_plugin_int plugin_int, *p; + char errbuf[1024]; + DBUG_ENTER("add_plugin"); + + DBUG_ASSERT(initialized); + + plugin_int.plugin= plugin; + plugin_int.dlhandle= dlhandle; + + if (plugin->type >= MYSQL_CLIENT_MAX_PLUGINS) + { + errmsg= "Unknown client plugin type"; + goto err1; + } + + if (plugin->interface_version < plugin_version[plugin->type] || + (plugin->interface_version >> 8) > + (plugin_version[plugin->type] >> 8)) + { + errmsg= "Incompatible client plugin interface"; + goto err1; + } + + /* Call the plugin initialization function, if any */ + if (plugin->init && plugin->init(errbuf, sizeof(errbuf), argc, args)) + { + errmsg= errbuf; + goto err1; + } + + p= (struct st_client_plugin_int *) + memdup_root(&mem_root, &plugin_int, sizeof(plugin_int)); + + if (!p) + { + errmsg= "Out of memory"; + goto err2; + } + + mysql_mutex_assert_owner(&LOCK_load_client_plugin); + + p->next= plugin_list[plugin->type]; + plugin_list[plugin->type]= p; + net_clear_error(&mysql->net); + + DBUG_RETURN(plugin); + +err2: + if (plugin->deinit) + plugin->deinit(); +err1: + set_mysql_extended_error(mysql, CR_AUTH_PLUGIN_CANNOT_LOAD, unknown_sqlstate, + ER(CR_AUTH_PLUGIN_CANNOT_LOAD), plugin->name, + errmsg); + if (dlhandle) + (void)dlclose(dlhandle); + DBUG_RETURN(NULL); +} + +/** + Loads plugins which are specified in the environment variable + LIBMYSQL_PLUGINS. + + Multiple plugins must be separated by semicolon. This function doesn't + return or log an error. + + The function is be called by mysql_client_plugin_init + + @todo + Support extended syntax, passing parameters to plugins, for example + LIBMYSQL_PLUGINS="plugin1(param1,param2);plugin2;..." + or + LIBMYSQL_PLUGINS="plugin1=int:param1,str:param2;plugin2;..." +*/ +static void load_env_plugins(MYSQL *mysql) +{ + char *plugs, *free_env, *s= getenv("LIBMYSQL_PLUGINS"); + DBUG_ENTER("load_env_plugins"); + + /* no plugins to load */ + if (!s) + DBUG_VOID_RETURN; + + free_env= plugs= my_strdup(key_memory_load_env_plugins, s, MYF(MY_WME)); + + do { + if ((s= strchr(plugs, ';'))) + *s= '\0'; + mysql_load_plugin(mysql, plugs, -1, 0); + plugs= s + 1; + } while (s); + + my_free(free_env); + DBUG_VOID_RETURN; +} + +/********** extern functions to be used by libmysql *********************/ + +/** + Initializes the client plugin layer. + + This function must be called before any other client plugin function. + + @retval 0 successful + @retval != 0 error occurred +*/ +int mysql_client_plugin_init() +{ + MYSQL mysql; + struct st_mysql_client_plugin **builtin; + va_list unused; + DBUG_ENTER("mysql_client_plugin_init"); + + if (initialized) + DBUG_RETURN(0); + +#ifdef HAVE_PSI_INTERFACE + init_client_plugin_psi_keys(); +#endif /* HAVE_PSI_INTERFACE */ + + bzero(&mysql, sizeof(mysql)); /* dummy mysql for set_mysql_extended_error */ + bzero(&unused, sizeof unused); + + mysql_mutex_init(key_mutex_LOCK_load_client_plugin, + &LOCK_load_client_plugin, MY_MUTEX_INIT_SLOW); + init_alloc_root(key_memory_root, &mem_root, 128, 128, MYF(0)); + + bzero(&plugin_list, sizeof(plugin_list)); + + initialized= 1; + + mysql_mutex_lock(&LOCK_load_client_plugin); + + for (builtin= mysql_client_builtins; *builtin; builtin++) + add_plugin(&mysql, *builtin, 0, 0, unused); + + mysql_mutex_unlock(&LOCK_load_client_plugin); + + load_env_plugins(&mysql); + + DBUG_RETURN(0); +} + +/** + Deinitializes the client plugin layer. + + Unloades all client plugins and frees any associated resources. +*/ +void mysql_client_plugin_deinit() +{ + int i; + struct st_client_plugin_int *p; + DBUG_ENTER("mysql_client_plugin_deinit"); + + if (!initialized) + DBUG_VOID_RETURN; + + for (i=0; i < MYSQL_CLIENT_MAX_PLUGINS; i++) + for (p= plugin_list[i]; p; p= p->next) + { + if (p->plugin->deinit) + p->plugin->deinit(); + if (p->dlhandle) + (void)dlclose(p->dlhandle); + } + + bzero(&plugin_list, sizeof(plugin_list)); + initialized= 0; + free_root(&mem_root, MYF(0)); + mysql_mutex_destroy(&LOCK_load_client_plugin); + DBUG_VOID_RETURN; +} + +/************* public facing functions, for client consumption *********/ + +/* see <mysql/client_plugin.h> for a full description */ +struct st_mysql_client_plugin * +mysql_client_register_plugin(MYSQL *mysql, + struct st_mysql_client_plugin *plugin) +{ + DBUG_ENTER("mysql_client_register_plugin"); + + if (is_not_initialized(mysql, plugin->name)) + DBUG_RETURN(NULL); + + mysql_mutex_lock(&LOCK_load_client_plugin); + + /* make sure the plugin wasn't loaded meanwhile */ + if (find_plugin(plugin->name, plugin->type)) + { + set_mysql_extended_error(mysql, CR_AUTH_PLUGIN_CANNOT_LOAD, + unknown_sqlstate, ER(CR_AUTH_PLUGIN_CANNOT_LOAD), + plugin->name, "it is already loaded"); + plugin= NULL; + } + else + { + va_list unused; + bzero(&unused, sizeof unused); + plugin= add_plugin(mysql, plugin, 0, 0, unused); + } + + mysql_mutex_unlock(&LOCK_load_client_plugin); + DBUG_RETURN(plugin); +} + +/* see <mysql/client_plugin.h> for a full description */ +struct st_mysql_client_plugin * +mysql_load_plugin_v(MYSQL *mysql, const char *name, int type, + int argc, va_list args) +{ + const char *errmsg; + char dlpath[FN_REFLEN+1]; + void *sym, *dlhandle; + struct st_mysql_client_plugin *plugin; + DBUG_ENTER("mysql_load_plugin_v"); + + DBUG_PRINT ("entry", ("name=%s type=%d int argc=%d", name, type, argc)); + if (is_not_initialized(mysql, name)) + { + DBUG_PRINT ("leave", ("mysql not initialized")); + DBUG_RETURN (NULL); + } + + mysql_mutex_lock(&LOCK_load_client_plugin); + + /* make sure the plugin wasn't loaded meanwhile */ + if (type >= 0 && find_plugin(name, type)) + { + errmsg= "it is already loaded"; + goto err; + } + + /* Compile dll path */ + strxnmov(dlpath, sizeof(dlpath) - 1, + mysql->options.extension && mysql->options.extension->plugin_dir ? + mysql->options.extension->plugin_dir : PLUGINDIR, "/", + name, SO_EXT, NullS); + + if (strpbrk(name, "()[]!@#$%^&/*;.,'?\\")) + { + errmsg= "invalid plugin name"; + goto err; + } + + DBUG_PRINT ("info", ("dlopeninig %s", dlpath)); + /* Open new dll handle */ + if (!(dlhandle= dlopen(dlpath, RTLD_NOW))) + { + DBUG_PRINT ("info", ("failed to dlopen")); + errmsg= dlerror(); + goto err; + } + + if (!(sym= dlsym(dlhandle, plugin_declarations_sym))) + { + errmsg= "not a plugin"; + goto errc; + } + + plugin= (struct st_mysql_client_plugin*)sym; + + if (type >=0 && type != plugin->type) + { + errmsg= "type mismatch"; + goto errc; + } + + if (strcmp(name, plugin->name)) + { + errmsg= "name mismatch"; + goto errc; + } + + if (type < 0 && find_plugin(name, plugin->type)) + { + errmsg= "it is already loaded"; + goto errc; + } + + plugin= add_plugin(mysql, plugin, dlhandle, argc, args); + + mysql_mutex_unlock(&LOCK_load_client_plugin); + + DBUG_PRINT ("leave", ("plugin loaded ok")); + DBUG_RETURN (plugin); + +errc: + dlclose(dlhandle); +err: + mysql_mutex_unlock(&LOCK_load_client_plugin); + DBUG_PRINT ("leave", ("plugin load error : %s", errmsg)); + set_mysql_extended_error(mysql, CR_AUTH_PLUGIN_CANNOT_LOAD, unknown_sqlstate, + ER(CR_AUTH_PLUGIN_CANNOT_LOAD), name, errmsg); + DBUG_RETURN (NULL); +} + +/* see <mysql/client_plugin.h> for a full description */ +struct st_mysql_client_plugin * +mysql_load_plugin(MYSQL *mysql, const char *name, int type, int argc, ...) +{ + struct st_mysql_client_plugin *p; + va_list args; + DBUG_ENTER("mysql_load_plugin"); + + va_start(args, argc); + p= mysql_load_plugin_v(mysql, name, type, argc, args); + va_end(args); + DBUG_RETURN(p); +} + +/* see <mysql/client_plugin.h> for a full description */ +struct st_mysql_client_plugin * +mysql_client_find_plugin(MYSQL *mysql, const char *name, int type) +{ + struct st_mysql_client_plugin *p; + DBUG_ENTER("mysql_client_find_plugin"); + + DBUG_PRINT ("entry", ("name=%s, type=%d", name, type)); + if (is_not_initialized(mysql, name)) + DBUG_RETURN (NULL); + + if (type < 0 || type >= MYSQL_CLIENT_MAX_PLUGINS) + { + set_mysql_extended_error(mysql, CR_AUTH_PLUGIN_CANNOT_LOAD, unknown_sqlstate, + ER(CR_AUTH_PLUGIN_CANNOT_LOAD), name, + "invalid type"); + } + + if ((p= find_plugin(name, type))) + { + DBUG_PRINT ("leave", ("found %p", p)); + DBUG_RETURN (p); + } + + /* not found, load it */ + p= mysql_load_plugin(mysql, name, type, 0); + DBUG_PRINT ("leave", ("loaded %p", p)); + DBUG_RETURN (p); +} + + +/* see <mysql/client_plugin.h> for a full description */ +int mysql_plugin_options(struct st_mysql_client_plugin *plugin, + const char *option, + const void *value) +{ + DBUG_ENTER("mysql_plugin_options"); + /* does the plugin support options call? */ + if (!plugin || !plugin->options) + DBUG_RETURN(1); + DBUG_RETURN(plugin->options(option, value)); +} diff --git a/sql-common/conf_to_src.c b/sql-common/conf_to_src.c new file mode 100644 index 00000000..57d3ee86 --- /dev/null +++ b/sql-common/conf_to_src.c @@ -0,0 +1,144 @@ +/* Copyright (c) 2000, 2015, 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. + + There are special exceptions to the terms and conditions of the GPL as it + is applied to this software. + + 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-1335 USA */ + +/* can't use -lmysys because this prog is used to create -lstrings */ + + +#include <my_global.h> +#include <ctype.h> +#include <string.h> +#include <unistd.h> + +#define CHARSETS_SUBDIR "sql/share/charsets" +#define CTYPE_TABLE_SIZE 257 +#define TO_LOWER_TABLE_SIZE 256 +#define TO_UPPER_TABLE_SIZE 256 +#define SORT_ORDER_TABLE_SIZE 256 +#define ROW_LEN 16 + +void print_arrays_for(char *set); + +char *prog; +char buf[1024], *p, *endptr; + +int +main(int argc, char **argv) +{ + prog = *argv; + + if (argc < 2) { + fprintf(stderr, "usage: %s source-dir [charset [, charset]]\n", prog); + exit(EXIT_FAILURE); + } + + --argc; ++argv; /* skip program name */ + + if (chdir(*argv) != 0) { + fprintf(stderr, "%s: can't cd to %s\n", prog, *argv); + exit(EXIT_FAILURE); + } + --argc; ++argv; + + if (chdir(CHARSETS_SUBDIR) != 0) { + fprintf(stderr, "%s: can't cd to %s\n", prog, CHARSETS_SUBDIR); + exit(EXIT_FAILURE); + } + + while (argc--) + print_arrays_for(*argv++); + + exit(EXIT_SUCCESS); +} + +void +print_array(FILE *f, const char *set, const char *name, int n) +{ + int i; + char val[100]; + + printf("uchar %s_%s[] = {\n", name, set); + + p = buf; + *buf = '\0'; + for (i = 0; i < n; ++i) + { + /* get a word from f */ + endptr = p; + for (;;) + { + while (isspace(*endptr)) + ++endptr; + if (*endptr && *endptr != '#') /* not comment */ + break; + if ((fgets(buf, sizeof(buf), f)) == NULL) + return; /* XXX: break silently */ + endptr = buf; + } + + p = val; + while (!isspace(*endptr)) + *p++ = *endptr++; + *p = '\0'; + p = endptr; + + /* write the value out */ + + if (i == 0 || i % ROW_LEN == n % ROW_LEN) + printf(" "); + + printf("%3d", (unsigned char) strtol(val, (char **) NULL, 16)); + + if (i < n - 1) + printf(","); + + if ((i+1) % ROW_LEN == n % ROW_LEN) + printf("\n"); + } + + printf("};\n\n"); +} + +void +print_arrays_for(char *set) +{ + FILE *f; + + snprintf(buf, sizeof(buf), "%s.conf", set); + + if ((f = fopen(buf, "r")) == NULL) { + fprintf(stderr, "%s: can't read conf file for charset %s\n", prog, set); + exit(EXIT_FAILURE); + } + + printf("\ +/* The %s character set. Generated automatically by configure and\n\ + * the %s program\n\ + */\n\n", + set, prog); + + /* it would be nice if this used the code in mysys/charset.c, but... */ + print_array(f, set, "ctype", CTYPE_TABLE_SIZE); + print_array(f, set, "to_lower", TO_LOWER_TABLE_SIZE); + print_array(f, set, "to_upper", TO_UPPER_TABLE_SIZE); + print_array(f, set, "sort_order", SORT_ORDER_TABLE_SIZE); + printf("\n"); + + fclose(f); + + return; +} diff --git a/sql-common/errmsg.c b/sql-common/errmsg.c new file mode 100644 index 00000000..47d72170 --- /dev/null +++ b/sql-common/errmsg.c @@ -0,0 +1,130 @@ +/* Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. + Copyright (C) 2020, MariaDB Corporation. + + 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. + + 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-1335 USA */ + +/* Error messages for MySQL clients */ +/* (Error messages for the daemon are in share/language/errmsg.sys) */ + +#include <my_global.h> +#include <my_sys.h> +#include "errmsg.h" + +const char *client_errors[]= +{ + "Unknown error", + "Can't create UNIX socket (%d)", + "Can't connect to local server through socket '%-.100s' (%M)", + "Can't connect to server on '%-.100s' (%M)", + "Can't create TCP/IP socket (%M)", + "Unknown server host '%-.100s' (%d)", + "Server has gone away", + "Protocol mismatch; server version = %d, client version = %d", + "MariaDB client ran out of memory", + "Wrong host info", + "Localhost via UNIX socket", + "%-.100s via TCP/IP", + "Error in server handshake", + "Lost connection to server during query", + "Commands out of sync; you can't run this command now", + "Named pipe: %-.32s", + "Can't wait for named pipe to host: %-.64s pipe: %-.32s (%lu)", + "Can't open named pipe to host: %-.64s pipe: %-.32s (%lu)", + "Can't set state of named pipe to host: %-.64s pipe: %-.32s (%lu)", + "Can't initialize character set %-.32s (path: %-.100s)", + "Got packet bigger than 'max_allowed_packet' bytes", + "Embedded server", + "Error on SHOW SLAVE STATUS:", + "Error on SHOW SLAVE HOSTS:", + "Error connecting to slave:", + "Error connecting to master:", + "SSL connection error: %-.100s", + "Malformed packet", + "This client library is licensed only for use with servers having '%s' license", + "Invalid use of null pointer", + "Statement not prepared", + "No data supplied for parameters in prepared statement", + "Data truncated", + "No parameters exist in the statement", + "Invalid parameter number", + "Can't send long data for non-string/non-binary data types (parameter: %d)", + "Using unsupported buffer type: %d (parameter: %d)", + "Shared memory: %-.100s", + "Can't open shared memory; client could not create request event (%lu)", + "Can't open shared memory; no answer event received from server (%lu)", + "Can't open shared memory; server could not allocate file mapping (%lu)", + "Can't open shared memory; server could not get pointer to file mapping (%lu)", + "Can't open shared memory; client could not allocate file mapping (%lu)", + "Can't open shared memory; client could not get pointer to file mapping (%lu)", + "Can't open shared memory; client could not create %s event (%lu)", + "Can't open shared memory; no answer from server (%lu)", + "Can't open shared memory; cannot send request event to server (%lu)", + "Wrong or unknown protocol", + "Invalid connection handle", + "Connection using old (pre-4.1.1) authentication protocol refused (client option 'secure_auth' enabled)", + "Row retrieval was canceled by mysql_stmt_close() call", + "Attempt to read column without prior row fetch", + "Prepared statement contains no metadata", + "Attempt to read a row while there is no result set associated with the statement", + "This feature is not implemented yet", + "Lost connection to server at '%s', system error: %M", + "Statement closed indirectly because of a preceding %s() call", + "The number of columns in the result set differs from the number of bound buffers. You must reset the statement, rebind the result set columns, and execute the statement again", + "This handle is already connected. Use a separate handle for each connection.", + "Authentication plugin '%s' cannot be loaded: %s", + "There is an attribute with the same name already", + "Authentication plugin '%s' reported error: %s", + "" +}; + +const char** get_client_errmsgs(int nr __attribute__((unused))) +{ + return client_errors; +} + +/* + Register client error messages for use with my_error(). + + SYNOPSIS + init_client_errs() + + RETURN + void +*/ + +void init_client_errs(void) +{ + compile_time_assert(array_elements(client_errors) == + (CR_ERROR_LAST - CR_ERROR_FIRST + 2)); + (void) my_error_register(get_client_errmsgs, CR_ERROR_FIRST, CR_ERROR_LAST); +} + + +/* + Unregister client error messages. + + SYNOPSIS + finish_client_errs() + + RETURN + void +*/ + +void finish_client_errs(void) +{ + (void) my_error_unregister(CR_ERROR_FIRST, CR_ERROR_LAST); +} diff --git a/sql-common/my_time.c b/sql-common/my_time.c new file mode 100644 index 00000000..96674723 --- /dev/null +++ b/sql-common/my_time.c @@ -0,0 +1,2022 @@ +/* + Copyright (c) 2004, 2012, Oracle and/or its affiliates. + Copyright (c) 2010, 2017, MariaDB Corporation. + + 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-1335 USA */ + +#include <my_global.h> +#include <my_time.h> +#include <m_string.h> +#include <m_ctype.h> +/* Windows version of localtime_r() is declared in my_ptrhead.h */ +#include <my_pthread.h> + + +ulonglong log_10_int[20]= +{ + 1, 10, 100, 1000, 10000UL, 100000UL, 1000000UL, 10000000UL, + 100000000ULL, 1000000000ULL, 10000000000ULL, 100000000000ULL, + 1000000000000ULL, 10000000000000ULL, 100000000000000ULL, + 1000000000000000ULL, 10000000000000000ULL, 100000000000000000ULL, + 1000000000000000000ULL, 10000000000000000000ULL +}; + + +/* Position for YYYY-DD-MM HH-MM-DD.FFFFFF AM in default format */ + +static uchar internal_format_positions[]= +{0, 1, 2, 3, 4, 5, 6, (uchar) 255}; + +static char time_separator=':'; + +static ulong const days_at_timestart=719528; /* daynr at 1970.01.01 */ +uchar days_in_month[]= {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0}; + +/* + Offset of system time zone from UTC in seconds used to speed up + work of my_system_gmt_sec() function. +*/ +static long my_time_zone=0; + + +/* Calc days in one year. works with 0 <= year <= 99 */ + +uint calc_days_in_year(uint year) +{ + return ((year & 3) == 0 && (year%100 || (year%400 == 0 && year)) ? + 366 : 365); +} + + +#ifdef DBUG_ASSERT_EXISTS + + +static const ulonglong C_KNOWN_FLAGS= C_TIME_NO_ZERO_IN_DATE | + C_TIME_NO_ZERO_DATE | + C_TIME_INVALID_DATES; + +#define C_FLAGS_OK(flags) (((flags) & ~C_KNOWN_FLAGS) == 0) + +#endif + + +/** + @brief Check datetime value for validity according to flags. + + @param[in] ltime Date to check. + @param[in] not_zero_date ltime is not the zero date + @param[in] flags flags to check + (see str_to_datetime() flags in my_time.h) + @param[out] was_cut set to 2 if value was invalid according to flags. + (Feb 29 in non-leap etc.) This remains unchanged + if value is not invalid. + + @details Here we assume that year and month is ok! + If month is 0 we allow any date. (This only happens if we allow zero + date parts in str_to_datetime()) + Disallow dates with zero year and non-zero month and/or day. + + @return + 0 OK + 1 error +*/ + +my_bool check_date(const MYSQL_TIME *ltime, my_bool not_zero_date, + ulonglong flags, int *was_cut) +{ + DBUG_ASSERT(C_FLAGS_OK(flags)); + if (ltime->time_type == MYSQL_TIMESTAMP_TIME) + return FALSE; + if (not_zero_date) + { + if (((flags & C_TIME_NO_ZERO_IN_DATE) && + (ltime->month == 0 || ltime->day == 0)) || ltime->neg || + (!(flags & C_TIME_INVALID_DATES) && + ltime->month && ltime->day > days_in_month[ltime->month-1] && + (ltime->month != 2 || calc_days_in_year(ltime->year) != 366 || + ltime->day != 29))) + { + *was_cut= 2; + return TRUE; + } + } + else if (flags & C_TIME_NO_ZERO_DATE) + { + /* + We don't set *was_cut here to signal that the problem was a zero date + and not an invalid date + */ + *was_cut|= MYSQL_TIME_WARN_ZERO_DATE; + return TRUE; + } + return FALSE; +} + +static int get_number(uint *val, uint *number_of_fields, const char **str, + const char *end) +{ + const char *s = *str; + + if (s >= end) + return 0; + + if (!my_isdigit(&my_charset_latin1, *s)) + return 1; + *val= *s++ - '0'; + + for (; s < end && my_isdigit(&my_charset_latin1, *s); s++) + *val= *val * 10 + *s - '0'; + *str = s; + (*number_of_fields)++; + return 0; +} + +static int get_digits(uint *val, uint *number_of_fields, const char **str, + const char *end, uint length) +{ + return get_number(val, number_of_fields, str, MY_MIN(end, *str + length)); +} + +static int get_punct(const char **str, const char *end) +{ + if (*str >= end) + return 0; + if (my_ispunct(&my_charset_latin1, **str)) + { + (*str)++; + return 0; + } + return 1; +} + +static int get_date_time_separator(uint *number_of_fields, + my_bool punct_is_date_time_separator, + const char **str, const char *end) +{ + const char *s= *str; + if (s >= end) + return 0; + + if (*s == 'T') + { + (*str)++; + return 0; + } + + /* + now, this is tricky, for backward compatibility reasons. + cast("11:11:11.12.12.12" as datetime) should give 2011-11-11 12:12:12 + but + cast("11:11:11.12.12.12" as time) should give 11:11:11.12 + that is, a punctuation character can be accepted as a date/time separator + only if "punct_is_date_time_separator" is set. + */ + if (my_ispunct(&my_charset_latin1, *s)) + { + if (!punct_is_date_time_separator) + { + /* see above, returning 1 is not enough, we need hard abort here */ + *number_of_fields= 0; + return 1; + } + + (*str)++; + return 0; + } + + if (!my_isspace(&my_charset_latin1, *s)) + return 1; + + do + { + s++; + } while (s < end && my_isspace(&my_charset_latin1, *s)); + *str= s; + return 0; +} + +static int get_maybe_T(const char **str, const char *end) +{ + if (*str < end && **str == 'T') + (*str)++; + return 0; +} + +static uint skip_digits(const char **str, const char *end) +{ + const char *start= *str, *s= *str; + while (s < end && my_isdigit(&my_charset_latin1, *s)) + s++; + *str= s; + return (uint)(s - start); +} + + +/** + Check datetime, date, or normalized time (i.e. time without days) range. + @param ltime Datetime value. + @returns + @retval FALSE on success + @retval TRUE on error +*/ +my_bool check_datetime_range(const MYSQL_TIME *ltime) +{ + /* + In case of MYSQL_TIMESTAMP_TIME hour value can be up to TIME_MAX_HOUR. + In case of MYSQL_TIMESTAMP_DATETIME it cannot be bigger than 23. + */ + return + ltime->year > 9999 || ltime->month > 12 || ltime->day > 31 || + ltime->minute > 59 || ltime->second > 59 || + ltime->second_part > TIME_MAX_SECOND_PART || + (ltime->hour > + (uint) (ltime->time_type == MYSQL_TIMESTAMP_TIME ? TIME_MAX_HOUR : 23)); +} + + +static void get_microseconds(ulong *val, MYSQL_TIME_STATUS *status, + uint *number_of_fields, + const char **str, const char *end) +{ + const char *start= *str; + uint tmp= 0; /* For the case '10:10:10.' */ + if (get_digits(&tmp, number_of_fields, str, end, 6)) + status->warnings|= MYSQL_TIME_WARN_TRUNCATED; + if ((status->precision= (uint)(*str - start)) < 6) + *val= (ulong) (tmp * log_10_int[6 - (*str - start)]); + else + *val= tmp; + if (str[0] < end && my_isdigit(&my_charset_latin1, str[0][0])) + { + /* + We don't need the exact nanoseconds value. + Knowing the first digit is enough for rounding. + */ + status->nanoseconds= 100 * (uint)(str[0][0] - '0'); + } + if (skip_digits(str, end)) + status->warnings|= MYSQL_TIME_NOTE_TRUNCATED; +} + + +static int check_time_range_internal(MYSQL_TIME *ltime, + ulong max_hour, ulong err_hour, + uint dec, int *warning); + +int check_time_range(MYSQL_TIME *ltime, uint dec, int *warning) +{ + return check_time_range_internal(ltime, TIME_MAX_HOUR, UINT_MAX32, + dec, warning); +} + + +static my_bool +set_neg(my_bool neg, MYSQL_TIME_STATUS *st, MYSQL_TIME *ltime) +{ + if ((ltime->neg= neg) && ltime->time_type != MYSQL_TIMESTAMP_TIME) + { + st->warnings|= MYSQL_TIME_WARN_OUT_OF_RANGE; + return TRUE; + } + return FALSE; +} + + + /* Remove trailing spaces and garbage */ +static my_bool get_suffix(const char *str, size_t length, size_t *new_length) +{ + /* + QQ: perhaps 'T' should be considered as a date/time delimiter only + if it's followed by a digit. Learn ISO 8601 details. + */ + my_bool garbage= FALSE; + for ( ; length > 0 ; length--) + { + char ch= str[length - 1]; + if (my_isdigit(&my_charset_latin1, ch) || + my_ispunct(&my_charset_latin1, ch)) + break; + if (my_isspace(&my_charset_latin1, ch)) + continue; + if (ch == 'T') + { + /* 'T' has a meaning only after a digit. Otherwise it's a garbage */ + if (length >= 2 && my_isdigit(&my_charset_latin1, str[length - 2])) + break; + } + garbage= TRUE; + } + *new_length= length; + return garbage; +} + + +static size_t get_prefix(const char *str, size_t length, const char **endptr) +{ + const char *str0= str, *end= str + length; + for (; str < end && my_isspace(&my_charset_latin1, *str) ; str++) + { } + *endptr= str; + return str - str0; +} + + +static size_t get_sign(my_bool *neg, const char *str, size_t length, + const char **endptr) +{ + const char *str0= str; + if (length) + { + if ((*neg= (*str == '-')) || (*str == '+')) + str++; + } + else + *neg= FALSE; + *endptr= str; + return str - str0; +} + + +static my_bool find_body(my_bool *neg, const char *str, size_t length, + MYSQL_TIME *to, int *warn, + const char **new_str, size_t *new_length) +{ + size_t sign_length; + *warn= 0; + length-= get_prefix(str, length, &str); + sign_length= get_sign(neg, str, length, &str); + length-= sign_length; + /* There can be a space after a sign again: '- 10:20:30' or '- 1 10:20:30' */ + length-= get_prefix(str, length, &str); + if (get_suffix(str, length, &length)) + *warn|= MYSQL_TIME_WARN_TRUNCATED; + *new_str= str; + *new_length= length; + if (!length || !my_isdigit(&my_charset_latin1, *str)) + { + *warn|= MYSQL_TIME_WARN_EDOM; + set_zero_time(to, MYSQL_TIMESTAMP_ERROR); + return TRUE; + } + return FALSE; +} + + +typedef struct +{ + uint count_punct; + uint count_colon; + uint count_iso_date_time_separator; +} MYSQL_TIME_USED_CHAR_STATISTICS; + + +static void +mysql_time_used_char_statistics_init(MYSQL_TIME_USED_CHAR_STATISTICS *to, + const char *str, const char *end) +{ + const char *s; + bzero((void *) to, sizeof(MYSQL_TIME_USED_CHAR_STATISTICS)); + for (s= str; s < end; s++) + { + if (my_ispunct(&my_charset_latin1, *s)) + to->count_punct++; + if (*s == ':') + to->count_colon++; + if (*s == 'T') + to->count_iso_date_time_separator++; + } +} + + +static my_bool +is_datetime_body_candidate(const char *str, size_t length, + my_bool allow_dates_delimited, + my_bool allow_dates_numeric) +{ + static uint min_date_length= 5; /* '1-1-1' -> '0001-01-01' */ + uint pos, count_punct= 0; + uint date_time_separator_length= MY_TEST(!allow_dates_delimited); + if (length >= 12) + return TRUE; + /* + The shortest possible DATE is '1-1-1', which is 5 characters. + To make a full datetime it should be at least followed by a space or a 'T'. + To make a date it should be just not less that 5 characters. + */ + if (length < min_date_length + date_time_separator_length && + !allow_dates_numeric) + return FALSE; + for (pos= 0; pos < length; pos++) + { + if (str[pos] == 'T') /* Date/time separator */ + return TRUE; + if (str[pos] == ' ') + { + /* + We found a space. If can be a DATE/TIME separator: + TIME('1-1-1 1:1:1.0) -> '0001-01-01 01:01:01.0' + + But it can be also a DAY/TIME separator: + TIME('1 11') -> 35:00:00 = 1 day 11 hours + TIME('1 111') -> 135:00:00 = 1 day 111 hours + TIME('11 11') -> 275:00:00 = 11 days 11 hours + TIME('111 11') -> 838:59:59 = 111 days 11 hours with overflow + TIME('1111 11') -> 838:59:59 = 1111 days 11 hours with overflow + */ + return count_punct > 0; /* Can be a DATE if already had separators*/ + } + if (my_ispunct(&my_charset_latin1, str[pos])) + { + if (allow_dates_delimited && str[pos] != ':') + return TRUE; + count_punct++; + } + } + return allow_dates_numeric && count_punct == 0; +} + + +static my_bool +str_to_DDhhmmssff_internal(my_bool neg, const char *str, size_t length, + MYSQL_TIME *l_time, + ulong max_hour, ulong err_hour, + MYSQL_TIME_STATUS *status, + const char **endptr); + + +/* + Convert a timestamp string to a MYSQL_TIME value. + + SYNOPSIS + str_to_datetime_or_date_body() + str String to parse + length Length of string + l_time Date is stored here + flags Bitmap of following items + TIME_DATETIME_ONLY Set if we only allow full datetimes. + TIME_NO_ZERO_IN_DATE Don't allow partial dates + TIME_NO_ZERO_DATE Don't allow 0000-00-00 date + TIME_INVALID_DATES Allow 2000-02-31 + punct_is_date_time_separator + Allow punctuation as a date/time separator, + or return a hard error. + status Conversion status + + + DESCRIPTION + At least the following formats are recogniced (based on number of digits) + YYMMDD, YYYYMMDD, YYMMDDHHMMSS, YYYYMMDDHHMMSS + YY-MM-DD, YYYY-MM-DD, YY-MM-DD HH.MM.SS + YYYYMMDDTHHMMSS where T is a the character T (ISO8601) + Also dates where all parts are zero are allowed + + The second part may have an optional .###### fraction part. + + status->warnings is set to: + 0 Value OK + MYSQL_TIME_WARN_TRUNCATED If value was cut during conversion + MYSQL_TIME_WARN_OUT_OF_RANGE check_date(date,flags) considers date invalid + + l_time->time_type is set as follows: + MYSQL_TIMESTAMP_NONE String wasn't a timestamp, like + [DD [HH:[MM:[SS]]]].fraction. + l_time is not changed. + MYSQL_TIMESTAMP_DATE DATE string (YY MM and DD parts ok) + MYSQL_TIMESTAMP_DATETIME Full timestamp + MYSQL_TIMESTAMP_ERROR Timestamp with wrong values. + All elements in l_time is set to 0 + RETURN VALUES + 0 - Ok + 1 - Error +*/ + +#define MAX_DATE_PARTS 8 + +static my_bool +str_to_datetime_or_date_body(const char *str, size_t length, MYSQL_TIME *l_time, + ulonglong flags, + my_bool punct_is_date_time_separator, + MYSQL_TIME_STATUS *status, + uint *number_of_fields, + const char **endptr) +{ + const char *end=str+length, *pos; + uint digits, year_length, not_zero_date; + int warn= 0; + DBUG_ENTER("str_to_datetime_or_date_body"); + DBUG_ASSERT(C_FLAGS_OK(flags)); + bzero(l_time, sizeof(*l_time)); + *number_of_fields= 0; + *endptr= str; + + /* + Calculate number of digits in first part. + If length= 8 or >= 14 then year is of format YYYY. + (YYYY-MM-DD, YYYYMMDD, YYYYYMMDDHHMMSS) + */ + pos= str; + digits= skip_digits(&pos, end); + + if (pos < end && *pos == 'T') /* YYYYYMMDDHHMMSSThhmmss is supported too */ + { + pos++; + digits+= skip_digits(&pos, end); + } + if (pos < end && *pos == '.' && digits >= 12) /* YYYYYMMDDHHMMSShhmmss.uuuuuu is supported too */ + { + pos++; + skip_digits(&pos, end); // ignore the return value + } + + if (pos == end) + { + /* + Found date in internal format + (only numbers like [YY]YYMMDD[T][hhmmss[.uuuuuu]]) + */ + year_length= (digits == 4 || digits == 8 || digits >= 14) ? 4 : 2; + if (get_digits(&l_time->year, number_of_fields, &str, end, year_length) + || get_digits(&l_time->month, number_of_fields, &str, end, 2) + || get_digits(&l_time->day, number_of_fields, &str, end, 2) + || get_maybe_T(&str, end) + || get_digits(&l_time->hour, number_of_fields, &str, end, 2) + || get_digits(&l_time->minute, number_of_fields, &str, end, 2) + || get_digits(&l_time->second, number_of_fields, &str, end, 2)) + warn|= MYSQL_TIME_WARN_TRUNCATED; + } + else + { + const char *start= str; + if (get_number(&l_time->year, number_of_fields, &str, end)) + warn|= MYSQL_TIME_WARN_TRUNCATED; + year_length= (uint)(str - start); + + if (!warn && + (get_punct(&str, end) + || get_number(&l_time->month, number_of_fields, &str, end) + || get_punct(&str, end) + || get_number(&l_time->day, number_of_fields, &str, end) + || get_date_time_separator(number_of_fields, + punct_is_date_time_separator, &str, end) + || get_number(&l_time->hour, number_of_fields, &str, end) + || get_punct(&str, end) + || get_number(&l_time->minute, number_of_fields, &str, end) + || get_punct(&str, end) + || get_number(&l_time->second, number_of_fields, &str, end))) + warn|= MYSQL_TIME_WARN_TRUNCATED; + } + status->warnings|= warn; + + *endptr= str; + /* we're ok if date part is correct. even if the rest is truncated */ + if (*number_of_fields < 3) + { + l_time->time_type= MYSQL_TIMESTAMP_NONE; + status->warnings|= MYSQL_TIME_WARN_TRUNCATED; + DBUG_RETURN(TRUE); + } + + if (!warn && str < end && *str == '.') + { + str++; + get_microseconds(&l_time->second_part, status, + number_of_fields, &str, end); + *endptr= str; + } + + not_zero_date = l_time->year || l_time->month || l_time->day || + l_time->hour || l_time->minute || l_time->second || + l_time->second_part; + + if (year_length == 2 && not_zero_date) + l_time->year+= (l_time->year < YY_PART_YEAR ? 2000 : 1900); + + if (l_time->year > 9999 || l_time->month > 12 || l_time->day > 31 || + l_time->hour > 23 || l_time->minute > 59 || l_time->second > 59) + { + status->warnings|= MYSQL_TIME_WARN_TRUNCATED; + goto err; + } + + if (check_date(l_time, not_zero_date, flags, &status->warnings)) + goto err; + + l_time->time_type= (*number_of_fields <= 3 ? + MYSQL_TIMESTAMP_DATE : MYSQL_TIMESTAMP_DATETIME); + + if (str != end) + status->warnings= MYSQL_TIME_WARN_TRUNCATED; + + DBUG_RETURN(FALSE); + +err: + set_zero_time(l_time, MYSQL_TIMESTAMP_ERROR); + DBUG_RETURN(TRUE); +} + + +/* + Convert a time string to a MYSQL_TIME struct. + + SYNOPSIS + str_to_datetime_or_date_or_time_body() + str A string in full TIMESTAMP format or + [-] DAYS [H]H:MM:SS, [H]H:MM:SS, [M]M:SS, [H]HMMSS, + [M]MSS or [S]S + There may be an optional [.second_part] after seconds + length Length of str + l_time Store result here + status Conversion status + + + NOTES + + Because of the extra days argument, this function can only + work with times where the time arguments are in the above order. + + status->warnings is set as follows: + MYSQL_TIME_WARN_TRUNCATED if the input string was cut during conversion, + and/or + MYSQL_TIME_WARN_OUT_OF_RANGE flag is set if the value is out of range. + + RETURN + FALSE on success + TRUE on error +*/ + +static my_bool +str_to_datetime_or_date_or_time_body(const char *str, size_t length, + MYSQL_TIME *l_time, + ulonglong fuzzydate, + MYSQL_TIME_STATUS *status, + ulong time_max_hour, + ulong time_err_hour, + my_bool allow_dates_delimited, + my_bool allow_dates_numeric) +{ + const char *endptr; + DBUG_ASSERT(C_FLAGS_OK(fuzzydate)); + + /* Check first if this is a full TIMESTAMP */ + if (is_datetime_body_candidate(str, length, + allow_dates_delimited, + allow_dates_numeric)) + { /* Probably full timestamp */ + int warn_copy= status->warnings; /* could already be set by find_body() */ + uint number_of_fields; + (void) str_to_datetime_or_date_body(str, length, l_time, fuzzydate, + FALSE, status, + &number_of_fields, &endptr); + DBUG_ASSERT(endptr >= str); + DBUG_ASSERT(endptr <= str + length); + switch (l_time->time_type) { + case MYSQL_TIMESTAMP_DATETIME: + return FALSE; + case MYSQL_TIMESTAMP_DATE: + { + /* + Successfully parsed as DATE, but it can also be a TIME: + '24:02:03' - continue and parse as TIME + '24:02:03 garbage /////' - continue and parse as TIME + '24:02:03T' - return DATE + '24-02-03' - return DATE + '24/02/03' - return DATE + '11111' - return DATE + */ + MYSQL_TIME_USED_CHAR_STATISTICS used_chars; + mysql_time_used_char_statistics_init(&used_chars, str, endptr); + if (used_chars.count_iso_date_time_separator || !used_chars.count_colon) + return FALSE; + } + break; + case MYSQL_TIMESTAMP_ERROR: + { + MYSQL_TIME_USED_CHAR_STATISTICS used_chars; + /* + Check if it parsed as DATETIME but then failed as out of range: + '2011-02-32 8:46:06.23434' - return error + */ + if (number_of_fields > 3) + return TRUE; + /* + Check if it parsed as DATE but then failed as out of range: + '100000:02:03' - continue and parse as TIME + '100000:02:03T' - return error + '100000/02/03' - return error + '100000-02-03' - return error + */ + mysql_time_used_char_statistics_init(&used_chars, str, endptr); + if (used_chars.count_iso_date_time_separator || !used_chars.count_colon) + return TRUE; + } + break; + case MYSQL_TIMESTAMP_NONE: + { + if (allow_dates_numeric && endptr >= str + length) + { + /* + For backward compatibility this parses as DATE and fails: + EXTRACT(DAY FROM '1111') -- return error + EXTRACT(DAY FROM '1') -- return error + */ + MYSQL_TIME_USED_CHAR_STATISTICS used_chars; + mysql_time_used_char_statistics_init(&used_chars, str, endptr); + if (!used_chars.count_iso_date_time_separator && + !used_chars.count_colon && + !used_chars.count_punct) + return TRUE; + } + /* + - '256 10:30:30' - continue and parse as TIME + - '4294967296:59:59.123456456' - continue and parse as TIME + */ + } + break; + case MYSQL_TIMESTAMP_TIME: + DBUG_ASSERT(0); + break; + } + my_time_status_init(status); + status->warnings= warn_copy; + } + + if (!str_to_DDhhmmssff_internal(FALSE, str, length, l_time, + time_max_hour, time_err_hour, + status, &endptr)) + return FALSE; + + set_zero_time(l_time, MYSQL_TIMESTAMP_ERROR); + return TRUE; +} + + +/* + Convert a string with INTERVAL DAY TO SECOND to MYSQL_TIME. + Input format: [-][DD ]hh:mm:ss.ffffff + + If the input string appears to be a DATETIME, error is returned. +*/ +my_bool str_to_DDhhmmssff(const char *str, size_t length, MYSQL_TIME *ltime, + ulong max_hour, MYSQL_TIME_STATUS *status) +{ + my_bool neg; + const char *endptr; + + my_time_status_init(status); + if (find_body(&neg, str, length, ltime, &status->warnings, &str, &length)) + return TRUE; + + /* Reject anything that might be parsed as a full TIMESTAMP */ + if (is_datetime_body_candidate(str, length, FALSE, FALSE)) + { + uint number_of_fields; + (void) str_to_datetime_or_date_body(str, length, ltime, 0, FALSE, + status, &number_of_fields, &endptr); + if (ltime->time_type > MYSQL_TIMESTAMP_ERROR) + { + status->warnings|= MYSQL_TIME_WARN_TRUNCATED; + ltime->time_type= MYSQL_TIMESTAMP_NONE; + return TRUE; + } + my_time_status_init(status); + } + + /* + Scan DDhhmmssff then reject anything that can remind date/datetime. + For example, in case of '2001-01-01', str_to_DDhhmmssff_internal() + will scan only '2001'. + */ + if (str_to_DDhhmmssff_internal(neg, str, length, ltime, max_hour, + UINT_MAX32, status, &endptr) || + (endptr < str + length && endptr[0] == '-')) + return TRUE; + return FALSE; +} + + +my_bool +str_to_datetime_or_date_or_time(const char *str, size_t length, + MYSQL_TIME *to, ulonglong mode, + MYSQL_TIME_STATUS *status, + ulong time_max_hour, + ulong time_err_hour) +{ + my_bool neg; + DBUG_ASSERT(C_FLAGS_OK(mode)); + my_time_status_init(status); + return + find_body(&neg, str, length, to, &status->warnings, &str, &length) || + str_to_datetime_or_date_or_time_body(str, length, to, mode, status, + time_max_hour, time_err_hour, + FALSE, FALSE) || + set_neg(neg, status, to); +} + + +my_bool +str_to_datetime_or_date_or_interval_hhmmssff(const char *str, size_t length, + MYSQL_TIME *to, ulonglong mode, + MYSQL_TIME_STATUS *status, + ulong time_max_hour, + ulong time_err_hour) +{ + my_bool neg; + DBUG_ASSERT(C_FLAGS_OK(mode)); + my_time_status_init(status); + return + find_body(&neg, str, length, to, &status->warnings, &str, &length) || + str_to_datetime_or_date_or_time_body(str, length, to, mode, status, + time_max_hour, time_err_hour, + TRUE, FALSE) || + set_neg(neg, status, to); +} + + +my_bool +str_to_datetime_or_date_or_interval_day(const char *str, size_t length, + MYSQL_TIME *to, ulonglong mode, + MYSQL_TIME_STATUS *status, + ulong time_max_hour, + ulong time_err_hour) +{ + my_bool neg; + DBUG_ASSERT(C_FLAGS_OK(mode)); + my_time_status_init(status); + /* + For backward compatibility we allow to parse non-delimited + values as DATE rather than as TIME: + EXTRACT(DAY FROM '11111') + */ + return + find_body(&neg, str, length, to, &status->warnings, &str, &length) || + str_to_datetime_or_date_or_time_body(str, length, to, mode, status, + time_max_hour, time_err_hour, + TRUE, TRUE) || + set_neg(neg, status, to); +} + + +my_bool +str_to_datetime_or_date(const char *str, size_t length, MYSQL_TIME *l_time, + ulonglong flags, MYSQL_TIME_STATUS *status) +{ + my_bool neg; + uint number_of_fields; + const char *endptr; + DBUG_ASSERT(C_FLAGS_OK(flags)); + my_time_status_init(status); + return + find_body(&neg, str, length, l_time, &status->warnings, &str, &length) || + str_to_datetime_or_date_body(str, length, l_time, flags, TRUE, + status, &number_of_fields, &endptr) || + set_neg(neg, status, l_time); +} + + + +/** + Convert a string to INTERVAL DAY TO SECOND. + Input format: [DD ]hh:mm:ss.ffffff + + Datetime or date formats are not understood. + + Optional leading spaces and signs must be scanned by the caller. + "str" should point to the first digit. + + @param neg - set the value to be negative + @param str - the input string + @param length - length of "str" + @param[OUT] l_time - write the result here + @param max_hour - if the result hour value appears to be greater than + max_hour, then cut to result to 'max_hour:59:59.999999' + @param err_hour - if the hour appears to be greater than err_hour, + return an error (without cut) + @param status + @param endptr +*/ +static my_bool +str_to_DDhhmmssff_internal(my_bool neg, const char *str, size_t length, + MYSQL_TIME *l_time, + ulong max_hour, ulong err_hour, + MYSQL_TIME_STATUS *status, const char **endptr) +{ + ulong date[5]; + ulonglong value; + const char *end=str + length, *end_of_days; + my_bool found_days, found_hours; + uint UNINIT_VAR(state); + + *endptr= str; + l_time->neg= neg; + /* Not a timestamp. Try to get this as a DAYS TO SECOND string */ + for (value=0; str != end && my_isdigit(&my_charset_latin1,*str) ; str++) + { + value=value*10L + (long) (*str - '0'); + if (value >= 42949672955959ULL) /* i.e. UINT_MAX32 : 59 : 59 */ + { + status->warnings|= MYSQL_TIME_WARN_OUT_OF_RANGE; + goto err; + } + } + + /* Skip all space after 'days' */ + end_of_days= str; + for (; str != end && my_isspace(&my_charset_latin1, str[0]) ; str++) + ; + + found_days=found_hours=0; + if ((uint) (end-str) > 1 && str != end_of_days && + my_isdigit(&my_charset_latin1, *str)) + { /* Found days part */ + date[0]= (ulong) value; + state= 1; /* Assume next is hours */ + found_days= 1; + } + else if ((end-str) > 1 && *str == time_separator && + my_isdigit(&my_charset_latin1, str[1])) + { + date[0]= 0; /* Assume we found hours */ + if (value >= UINT_MAX32) + { + status->warnings|= MYSQL_TIME_WARN_OUT_OF_RANGE; + goto err; + } + date[1]= (ulong) value; + state=2; + found_hours=1; + str++; /* skip ':' */ + } + else + { + /* String given as one number; assume HHMMSS format */ + date[0]= 0; + DBUG_ASSERT(value <= ((ulonglong) UINT_MAX32) * 10000ULL); + date[1]= (ulong) (value/10000); + date[2]= (ulong) (value/100 % 100); + date[3]= (ulong) (value % 100); + state=4; + goto fractional; + } + + /* Read hours, minutes and seconds */ + for (;;) + { + for (value=0; str != end && my_isdigit(&my_charset_latin1,*str) ; str++) + value=value*10L + (long) (*str - '0'); + date[state++]= (ulong) value; + if (state == 4 || (end-str) < 2 || *str != time_separator || + !my_isdigit(&my_charset_latin1,str[1])) + break; + str++; /* Skip time_separator (':') */ + } + + if (state != 4) + { /* Not HH:MM:SS */ + /* Fix the date to assume that seconds was given */ + if (!found_hours && !found_days) + { + bmove_upp((uchar*) (date+4), (uchar*) (date+state), + sizeof(long)*(state-1)); + bzero((uchar*) date, sizeof(long)*(4-state)); + } + else + bzero((uchar*) (date+state), sizeof(long)*(4-state)); + } + +fractional: + /* Get fractional second part */ + if (str < end && *str == '.') + { + uint number_of_fields= 0; + str++; + get_microseconds(&date[4], status, &number_of_fields, &str, end); + } + else + date[4]= 0; + + /* Check for exponent part: E<gigit> | E<sign><digit> */ + /* (may occur as result of %g formatting of time value) */ + if ((end - str) > 1 && + (*str == 'e' || *str == 'E') && + (my_isdigit(&my_charset_latin1, str[1]) || + ((str[1] == '-' || str[1] == '+') && + (end - str) > 2 && + my_isdigit(&my_charset_latin1, str[2])))) + { + status->warnings|= MYSQL_TIME_WARN_TRUNCATED; + goto err; + } + + if (internal_format_positions[7] != 255) + { + /* Read a possible AM/PM */ + while (str != end && my_isspace(&my_charset_latin1, *str)) + str++; + if (str+2 <= end && (str[1] == 'M' || str[1] == 'm')) + { + if (str[0] == 'p' || str[0] == 'P') + { + str+= 2; + date[1]= date[1]%12 + 12; + } + else if (str[0] == 'a' || str[0] == 'A') + str+=2; + } + } + + /* Integer overflow checks */ + if (date[0] > UINT_MAX || date[1] > UINT_MAX || + date[2] > UINT_MAX || date[3] > UINT_MAX || + date[4] > UINT_MAX) + { + status->warnings|= MYSQL_TIME_WARN_OUT_OF_RANGE; + goto err; + } + + if ((ulonglong) date[0] * 24 + date[1] > (ulonglong) UINT_MAX32) + { + status->warnings|= MYSQL_TIME_WARN_OUT_OF_RANGE; + goto err; + } + l_time->year= 0; /* For protocol::store_time */ + l_time->month= 0; + l_time->day= 0; + l_time->hour= date[1] + date[0] * 24; /* Mix days and hours */ + l_time->minute= date[2]; + l_time->second= date[3]; + l_time->second_part= date[4]; + l_time->time_type= MYSQL_TIMESTAMP_TIME; + + *endptr= str; + + /* Check if the value is valid and fits into MYSQL_TIME range */ + if (check_time_range_internal(l_time, max_hour, err_hour, + 6, &status->warnings)) + return TRUE; + + /* Check if there is garbage at end of the MYSQL_TIME specification */ + if (str != end) + status->warnings|= MYSQL_TIME_WARN_TRUNCATED; + return FALSE; + +err: + *endptr= str; + return TRUE; +} + + +/* + Check 'time' value to lie in the MYSQL_TIME range + + SYNOPSIS: + check_time_range_internal() + time pointer to MYSQL_TIME value + ulong max_hour - maximum allowed hour value. if the hour is greater, + cut the time value to 'max_hour:59:59.999999' + ulong err_hour - if hour is greater than this value, return an error + uint dec + warning set MYSQL_TIME_WARN_OUT_OF_RANGE flag if the value is out of range + + DESCRIPTION + If the time value lies outside of the range [-838:59:59, 838:59:59], + set it to the closest endpoint of the range and set + MYSQL_TIME_WARN_OUT_OF_RANGE flag in the 'warning' variable. + + RETURN + 0 time value is valid, but was possibly truncated + 1 time value is invalid +*/ + +int check_time_range_internal(struct st_mysql_time *my_time, + ulong max_hour, ulong err_hour, + uint dec, int *warning) +{ + ulonglong hour; + static ulong max_sec_part[TIME_SECOND_PART_DIGITS+1]= {000000, 900000, 990000, + 999000, 999900, 999990, 999999}; + + if (my_time->minute >= 60 || my_time->second >= 60 || + my_time->hour > err_hour) + { + *warning|= MYSQL_TIME_WARN_TRUNCATED; + return 1; + } + + hour= my_time->hour + (24*my_time->day); + + if (dec == AUTO_SEC_PART_DIGITS) + dec= TIME_SECOND_PART_DIGITS; + + if (hour <= max_hour && + (hour != max_hour || my_time->minute != TIME_MAX_MINUTE || + my_time->second != TIME_MAX_SECOND || + my_time->second_part <= max_sec_part[dec])) + return 0; + + my_time->day= 0; + my_time->hour= max_hour; + my_time->minute= TIME_MAX_MINUTE; + my_time->second= TIME_MAX_SECOND; + my_time->second_part= max_sec_part[dec]; + *warning|= MYSQL_TIME_WARN_OUT_OF_RANGE; + return 0; +} + + +/* + Prepare offset of system time zone from UTC for my_system_gmt_sec() func. + + SYNOPSIS + my_init_time() +*/ +void my_init_time(void) +{ + time_t seconds; + struct tm *l_time,tm_tmp; + MYSQL_TIME my_time; + uint not_used; + + seconds= (time_t) time((time_t*) 0); + localtime_r(&seconds,&tm_tmp); + l_time= &tm_tmp; + my_time_zone= 3600; /* Comp. for -3600 in my_gmt_sec */ + my_time.year= (uint) l_time->tm_year+1900; + my_time.month= (uint) l_time->tm_mon+1; + my_time.day= (uint) l_time->tm_mday; + my_time.hour= (uint) l_time->tm_hour; + my_time.minute= (uint) l_time->tm_min; + my_time.second= (uint) l_time->tm_sec; + my_time.neg= 0; + my_time.second_part= 0; + my_time.time_type= MYSQL_TIMESTAMP_DATETIME; + + my_system_gmt_sec(&my_time, &my_time_zone, ¬_used); /* Init my_time_zone */ +} + + +/* + Handle 2 digit year conversions + + SYNOPSIS + year_2000_handling() + year 2 digit year + + RETURN + Year between 1970-2069 +*/ + +uint year_2000_handling(uint year) +{ + if ((year=year+1900) < 1900+YY_PART_YEAR) + year+=100; + return year; +} + + +/* + Calculate nr of day since year 0 in new date-system (from 1615) + + SYNOPSIS + calc_daynr() + year Year (exact 4 digit year, no year conversions) + month Month + day Day + + NOTES: 0000-00-00 is a valid date, and will return 0 + + RETURN + Days since 0000-00-00 +*/ + +long calc_daynr(uint year,uint month,uint day) +{ + long delsum; + int temp; + int y= year; /* may be < 0 temporarily */ + DBUG_ENTER("calc_daynr"); + + if (y == 0 && month == 0) + DBUG_RETURN(0); /* Skip errors */ + /* Cast to int to be able to handle month == 0 */ + delsum= (long) (365 * y + 31 *((int) month - 1) + (int) day); + if (month <= 2) + y--; + else + delsum-= (long) ((int) month * 4 + 23) / 10; + temp=(int) ((y/100+1)*3)/4; + DBUG_PRINT("exit",("year: %d month: %d day: %d -> daynr: %ld", + y+(month <= 2),month,day,delsum+y/4-temp)); + DBUG_ASSERT(delsum+(int) y/4-temp >= 0); + DBUG_RETURN(delsum+(int) y/4-temp); +} /* calc_daynr */ + +/* + Convert time in MYSQL_TIME representation in system time zone to its + my_time_t form (number of seconds in UTC since begginning of Unix Epoch). + + SYNOPSIS + my_system_gmt_sec() + t - time value to be converted + my_timezone - pointer to long where offset of system time zone + from UTC will be stored for caching + error_code - 0, if the conversion was successful; + ER_WARN_DATA_OUT_OF_RANGE, if t contains datetime value + which is out of TIMESTAMP range; + ER_WARN_INVALID_TIMESTAMP, if t represents value which + doesn't exists (falls into the spring time-gap). + + NOTES + The idea is to cache the time zone offset from UTC (including daylight + saving time) for the next call to make things faster. But currently we + just calculate this offset during startup (by calling my_init_time() + function) and use it all the time. + Time value provided should be legal time value (e.g. '2003-01-01 25:00:00' + is not allowed). + + RETURN VALUE + Time in UTC seconds since Unix Epoch representation. +*/ +my_time_t +my_system_gmt_sec(const MYSQL_TIME *t_src, long *my_timezone, uint *error_code) +{ + uint loop; + time_t tmp= 0; + int shift= 0; + MYSQL_TIME tmp_time; + MYSQL_TIME *t= &tmp_time; + struct tm *l_time,tm_tmp; + long diff, current_timezone; + + /* + Use temp variable to avoid trashing input data, which could happen in + case of shift required for boundary dates processing. + */ + memcpy(&tmp_time, t_src, sizeof(MYSQL_TIME)); + + if (!validate_timestamp_range(t)) + { + *error_code= ER_WARN_DATA_OUT_OF_RANGE; + return 0; + } + *error_code= 0; + + /* + Calculate the gmt time based on current time and timezone + The -1 on the end is to ensure that if have a date that exists twice + (like 2002-10-27 02:00:0 MET), we will find the initial date. + + By doing -3600 we will have to call localtime_r() several times, but + I couldn't come up with a better way to get a repeatable result :( + + We can't use mktime() as it's buggy on many platforms and not thread safe. + + Note: this code assumes that our time_t estimation is not too far away + from real value (we assume that localtime_r(tmp) will return something + within 24 hrs from t) which is probably true for all current time zones. + + Note2: For the dates, which have time_t representation close to + MAX_INT32 (efficient time_t limit for supported platforms), we should + do a small trick to avoid overflow. That is, convert the date, which is + two days earlier, and then add these days to the final value. + + The same trick is done for the values close to 0 in time_t + representation for platfroms with unsigned time_t (QNX). + + To be more verbose, here is a sample (extracted from the code below): + (calc_daynr(2038, 1, 19) - (long) days_at_timestart)*86400L + 4*3600L + would return -2147480896 because of the long type overflow. In result + we would get 1901 year in localtime_r(), which is an obvious error. + + Alike problem raises with the dates close to Epoch. E.g. + (calc_daynr(1969, 12, 31) - (long) days_at_timestart)*86400L + 23*3600L + will give -3600. + + On some platforms, (E.g. on QNX) time_t is unsigned and localtime(-3600) + wil give us a date around 2106 year. Which is no good. + + Theoreticaly, there could be problems with the latter conversion: + there are at least two timezones, which had time switches near 1 Jan + of 1970 (because of political reasons). These are America/Hermosillo and + America/Mazatlan time zones. They changed their offset on + 1970-01-01 08:00:00 UTC from UTC-8 to UTC-7. For these zones + the code below will give incorrect results for dates close to + 1970-01-01, in the case OS takes into account these historical switches. + Luckily, it seems that we support only one platform with unsigned + time_t. It's QNX. And QNX does not support historical timezone data at all. + E.g. there are no /usr/share/zoneinfo/ files or any other mean to supply + historical information for localtime_r() etc. That is, the problem is not + relevant to QNX. + + We are safe with shifts close to MAX_INT32, as there are no known + time switches on Jan 2038 yet :) + */ + if ((t->year == TIMESTAMP_MAX_YEAR) && (t->month == 1) && (t->day > 4)) + { + /* + Below we will pass (uint) (t->day - shift) to calc_daynr. + As we don't want to get an overflow here, we will shift + only safe dates. That's why we have (t->day > 4) above. + */ + t->day-= 2; + shift= 2; + } +#ifdef TIME_T_UNSIGNED + else + { + /* + We can get 0 in time_t representaion only on 1969, 31 of Dec or on + 1970, 1 of Jan. For both dates we use shift, which is added + to t->day in order to step out a bit from the border. + This is required for platforms, where time_t is unsigned. + As far as I know, among the platforms we support it's only QNX. + Note: the order of below if-statements is significant. + */ + + if ((t->year == TIMESTAMP_MIN_YEAR + 1) && (t->month == 1) + && (t->day <= 10)) + { + t->day+= 2; + shift= -2; + } + + if ((t->year == TIMESTAMP_MIN_YEAR) && (t->month == 12) + && (t->day == 31)) + { + t->year++; + t->month= 1; + t->day= 2; + shift= -2; + } + } +#endif + + tmp= (time_t) (((calc_daynr((uint) t->year, (uint) t->month, (uint) t->day) - + (long) days_at_timestart) * SECONDS_IN_24H + + (long) t->hour*3600L + + (long) (t->minute*60 + t->second)) + (time_t) my_time_zone - + 3600); + + current_timezone= my_time_zone; + localtime_r(&tmp,&tm_tmp); + l_time=&tm_tmp; + for (loop=0; + loop < 2 && + (t->hour != (uint) l_time->tm_hour || + t->minute != (uint) l_time->tm_min || + t->second != (uint) l_time->tm_sec); + loop++) + { /* One check should be enough ? */ + /* Get difference in days */ + int days= t->day - l_time->tm_mday; + if (days < -1) + days= 1; /* Month has wrapped */ + else if (days > 1) + days= -1; + diff=(3600L*(long) (days*24+((int) t->hour - (int) l_time->tm_hour)) + + (long) (60*((int) t->minute - (int) l_time->tm_min)) + + (long) ((int) t->second - (int) l_time->tm_sec)); + current_timezone+= diff+3600; /* Compensate for -3600 above */ + tmp+= (time_t) diff; + localtime_r(&tmp,&tm_tmp); + l_time=&tm_tmp; + } + /* + Fix that if we are in the non existing daylight saving time hour + we move the start of the next real hour. + + This code doesn't handle such exotical thing as time-gaps whose length + is more than one hour or non-integer (latter can theoretically happen + if one of seconds will be removed due leap correction, or because of + general time correction like it happened for Africa/Monrovia time zone + in year 1972). + */ + if (loop == 2 && t->hour != (uint) l_time->tm_hour) + { + int days= t->day - l_time->tm_mday; + if (days < -1) + days=1; /* Month has wrapped */ + else if (days > 1) + days= -1; + diff=(3600L*(long) (days*24+((int) t->hour - (int) l_time->tm_hour))+ + (long) (60*((int) t->minute - (int) l_time->tm_min)) + + (long) ((int) t->second - (int) l_time->tm_sec)); + if (diff == 3600) + tmp+=3600 - t->minute*60 - t->second; /* Move to next hour */ + else if (diff == -3600) + tmp-=t->minute*60 + t->second; /* Move to previous hour */ + + *error_code= ER_WARN_INVALID_TIMESTAMP; + } + *my_timezone= current_timezone; + + + /* shift back, if we were dealing with boundary dates */ + tmp+= shift * SECONDS_IN_24H; + + /* + This is possible for dates, which slightly exceed boundaries. + Conversion will pass ok for them, but we don't allow them. + First check will pass for platforms with signed time_t. + instruction above (tmp+= shift*86400L) could exceed + MAX_INT32 (== TIMESTAMP_MAX_VALUE) and overflow will happen. + So, tmp < TIMESTAMP_MIN_VALUE will be triggered. On platfroms + with unsigned time_t tmp+= shift*86400L might result in a number, + larger then TIMESTAMP_MAX_VALUE, so another check will work. + */ + if (!IS_TIME_T_VALID_FOR_TIMESTAMP(tmp)) + { + tmp= 0; + *error_code= ER_WARN_DATA_OUT_OF_RANGE; + } + + return (my_time_t) tmp; +} /* my_system_gmt_sec */ + + +/* Set MYSQL_TIME structure to 0000-00-00 00:00:00.000000 */ + +void set_zero_time(MYSQL_TIME *tm, enum enum_mysql_timestamp_type time_type) +{ + bzero((void*) tm, sizeof(*tm)); + tm->time_type= time_type; +} + + +/* + A formatting routine to print a 2 digit zero padded number. + It prints 2 digits at a time, which gives a performance improvement. + The idea is taken from "class TwoDigitWriter" in MySQL. + + The old implementation printed one digit at a time, using the division + and the remainder operators, which appeared to be slow. + It's cheaper to have a cached array of 2-digit numbers + in their string representation. + + Benchmark results showed a 10% to 23% time reduce for these queries: + SELECT BENCHMARK(10*1000*1000,CONCAT(TIME'10:20:30')); + SELECT BENCHMARK(10*1000*1000,CONCAT(DATE'2001-01-01')); + SELECT BENCHMARK(10*1000*1000,CONCAT(TIMESTAMP'2001-01-01 10:20:30')); + SELECT BENCHMARK(10*1000*1000,CONCAT(TIME'10:20:30.123456')); + SELECT BENCHMARK(10*1000*1000,CONCAT(TIMESTAMP'2001-01-01 10:20:30.123456')); + (depending on the exact data type and fractional precision). + + The array has extra elements for values 100..255. + This is done for safety. If the caller passes a value + outside of the expected range 0..99, the value will be printed as "XX". + + Part2: + + As an additional improvement over "class TwoDigitWriter", we store + the string representations of the numbers in an array uint16[256] + instead of char[512]. This allows to copy data using int2store(), + which copies two bytes at a time on x86 and gives an additional + 7% to 26% time reduce over copying the two bytes separately. + + The total time reduce is 15% to 38% on the above queries. + + The bytes in the following array are swapped: + e.g. 0x3130 in two_digit_numbers[1] means the following: + - 0x31 is '1' (the left byte, the right digit) + - 0x30 is '0' (the right byte, the left digit) + int2store() puts the lower byte first, so the output string becomes '01'. +*/ +static const uint16 two_digit_numbers[256]= +{ + /* 0..99 */ + 0x3030,0x3130,0x3230,0x3330,0x3430,0x3530,0x3630,0x3730,0x3830,0x3930, + 0x3031,0x3131,0x3231,0x3331,0x3431,0x3531,0x3631,0x3731,0x3831,0x3931, + 0x3032,0x3132,0x3232,0x3332,0x3432,0x3532,0x3632,0x3732,0x3832,0x3932, + 0x3033,0x3133,0x3233,0x3333,0x3433,0x3533,0x3633,0x3733,0x3833,0x3933, + 0x3034,0x3134,0x3234,0x3334,0x3434,0x3534,0x3634,0x3734,0x3834,0x3934, + 0x3035,0x3135,0x3235,0x3335,0x3435,0x3535,0x3635,0x3735,0x3835,0x3935, + 0x3036,0x3136,0x3236,0x3336,0x3436,0x3536,0x3636,0x3736,0x3836,0x3936, + 0x3037,0x3137,0x3237,0x3337,0x3437,0x3537,0x3637,0x3737,0x3837,0x3937, + 0x3038,0x3138,0x3238,0x3338,0x3438,0x3538,0x3638,0x3738,0x3838,0x3938, + 0x3039,0x3139,0x3239,0x3339,0x3439,0x3539,0x3639,0x3739,0x3839,0x3939, + /* 100..199 - safety */ + 0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858, + 0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858, + 0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858, + 0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858, + 0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858, + 0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858, + 0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858, + 0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858, + 0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858, + 0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858, + /* 200..255 - safety */ + 0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858, + 0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858, + 0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858, + 0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858, + 0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858,0x5858, + 0x5858,0x5858,0x5858,0x5858,0x5858,0x5858, +}; + +static inline char* fmt_number2(uint8 val, char *out) +{ + int2store(out, two_digit_numbers[val]); + return out + 2; +} + + +/* + We tried the same trick with a char array of 16384 zerofill 4-digit numbers, + with 10000 elements with numbers 0000..9999, and a tail filled with "XXXX". + + Benchmark results for a RelWithDebInfo build: + + SELECT BENCHMARK(10*1000*1000,CONCAT(TIMESTAMP'2001-01-01 10:20:30.123456')); + - 0.379 sec (current) + - 0.369 sec (array) + + SELECT BENCHMARK(10*1000*1000,CONCAT(DATE'2001-01-01')); + - 0.225 sec (current) + - 0.219 sec (array) + + It demonstrated an additional 3% performance imrovement one these queries. + However, as the array size is too huge, we afraid that it will flush data + from the CPU memory cache, which under real load may affect negatively. + + Let's keep using the fmt_number4() version with division and remainder + for now. This can be revised later. We could try some smaller array, + e.g. for YEARs in the range 1970..2098 (fitting into a 256 element array). +*/ +/* +static inline char* fmt_number4(uint16 val, char *out) +{ + const char *src= four_digit_numbers + (val & 0x3FFF) * 4; + memcpy(out, src, 4); + return out + 4; +} +*/ + + +/* + A formatting routine to print a 4 digit zero padded number. +*/ +static inline char* fmt_number4(uint16 val, char *out) +{ + out= fmt_number2((uint8) (val / 100), out); + out= fmt_number2((uint8) (val % 100), out); + return out; +} + + +/* + A formatting routine to print a 6 digit zero padded number. +*/ +static inline char* fmt_number6(uint val, char *out) +{ + out= fmt_number2((uint8) (val / 10000), out); + val%= 10000; + out= fmt_number2((uint8) (val / 100), out); + out= fmt_number2((uint8) (val % 100), out); + return out; +} + + +static char* fmt_usec(uint val, char *out, uint digits) +{ + switch (digits) + { + case 1: + *out++= '0' + (val % 10); + return out; + case 2: + return fmt_number2((uint8) val, out); + case 3: + *out++= '0' + (val / 100) % 10; + return fmt_number2((uint8) (val % 100), out); + case 4: + return fmt_number4((uint16) val, out); + case 5: + *out++= '0' + (val / 10000) % 10; + return fmt_number4((uint16) (val % 10000), out); + case 6: + return fmt_number6(val, out); + } + DBUG_ASSERT(0); + return out; +} + + +static int my_mmssff_to_str(const MYSQL_TIME *ltime, char *to, uint fsp) +{ + char *pos= to; + if (fsp == AUTO_SEC_PART_DIGITS) + fsp= ltime->second_part ? TIME_SECOND_PART_DIGITS : 0; + DBUG_ASSERT(fsp <= TIME_SECOND_PART_DIGITS); + pos= fmt_number2((uint8) ltime->minute, pos); + *pos++= ':'; + pos= fmt_number2((uint8) ltime->second, pos); + if (fsp) + { + *pos++= '.'; + pos= fmt_usec((uint)sec_part_shift(ltime->second_part, fsp), pos, fsp); + } + return (int) (pos - to); +} + + +int my_interval_DDhhmmssff_to_str(const MYSQL_TIME *ltime, char *to, uint fsp) +{ + uint hour= ltime->day * 24 + ltime->hour; + char *pos= to; + DBUG_ASSERT(!ltime->year); + DBUG_ASSERT(!ltime->month); + + if(ltime->neg) + *pos++= '-'; + if (hour >= 24) + { + pos= longlong10_to_str((longlong) hour / 24, pos, 10); + *pos++= ' '; + } + pos= fmt_number2((uint8) (hour % 24), pos); + *pos++= ':'; + pos+= my_mmssff_to_str(ltime, pos, fsp); + *pos= 0; + return (int) (pos-to); +} + + +/* + Functions to convert time/date/datetime value to a string, + using default format. + This functions don't check that given MYSQL_TIME structure members are + in valid range. If they are not, return value won't reflect any + valid date either. + + RETURN + number of characters written to 'to' +*/ + +int my_time_to_str(const MYSQL_TIME *l_time, char *to, uint digits) +{ + uint day= (l_time->year || l_time->month) ? 0 : l_time->day; + uint hour= day * 24 + l_time->hour; + char*pos= to; + + if(l_time->neg) + *pos++= '-'; + + if(hour > 99) + /* Need more than 2 digits for hours in string representation. */ + pos= longlong10_to_str((longlong)hour, pos, 10); + else + pos= fmt_number2((uint8) hour, pos); + + *pos++= ':'; + pos+= my_mmssff_to_str(l_time, pos, digits); + *pos= 0; + return (int) (pos-to); +} + + +int my_date_to_str(const MYSQL_TIME *l_time, char *to) +{ + char *pos=to; + pos= fmt_number4((uint16) l_time->year, pos); + *pos++='-'; + pos= fmt_number2((uint8) l_time->month, pos); + *pos++='-'; + pos= fmt_number2((uint8) l_time->day, pos); + *pos= 0; + return (int)(pos - to); +} + + +int my_datetime_to_str(const MYSQL_TIME *l_time, char *to, uint digits) +{ + char *pos= to; + pos= fmt_number4((uint16) l_time->year, pos); + *pos++='-'; + pos= fmt_number2((uint8) l_time->month, pos); + *pos++='-'; + pos= fmt_number2((uint8) l_time->day, pos); + *pos++=' '; + pos= fmt_number2((uint8) l_time->hour, pos); + *pos++= ':'; + pos+= my_mmssff_to_str(l_time, pos, digits); + *pos= 0; + return (int)(pos - to); +} + + +/* + Convert struct DATE/TIME/DATETIME value to string using built-in + MySQL time conversion formats. + + SYNOPSIS + my_TIME_to_string() + + RETURN + length of string + + NOTE + The string must have at least MAX_DATE_STRING_REP_LENGTH bytes reserved. +*/ + +int my_TIME_to_str(const MYSQL_TIME *l_time, char *to, uint digits) +{ + switch (l_time->time_type) { + case MYSQL_TIMESTAMP_DATETIME: + return my_datetime_to_str(l_time, to, digits); + case MYSQL_TIMESTAMP_DATE: + return my_date_to_str(l_time, to); + case MYSQL_TIMESTAMP_TIME: + return my_time_to_str(l_time, to, digits); + case MYSQL_TIMESTAMP_NONE: + case MYSQL_TIMESTAMP_ERROR: + to[0]='\0'; + return 0; + default: + DBUG_ASSERT(0); + return 0; + } +} + + +/** + Print a timestamp with an optional fractional part: XXXXX[.YYYYY] + + @param tm The timestamp value to print. + @param OUT to The string pointer to print at. + @param dec Precision, in the range 0..6. + @return The length of the result string. +*/ +int my_timeval_to_str(const struct timeval *tm, char *to, uint dec) +{ + char *pos= longlong10_to_str((longlong) tm->tv_sec, to, 10); + if (dec) + { + *pos++= '.'; + pos= fmt_usec((uint) sec_part_shift(tm->tv_usec, dec), pos, dec); + } + *pos= '\0'; + return (int) (pos - to); +} + + +/* + Convert datetime value specified as number to broken-down TIME + representation and form value of DATETIME type as side-effect. + + SYNOPSIS + number_to_datetime_or_date() + nr - datetime value as number + time_res - pointer for structure for broken-down representation + flags - flags to use in validating date, as in str_to_datetime() + was_cut 0 Value ok + 1 If value was cut during conversion + 2 check_date(date,flags) considers date invalid + + DESCRIPTION + Convert a datetime value of formats YYMMDD, YYYYMMDD, YYMMDDHHMSS, + YYYYMMDDHHMMSS to broken-down MYSQL_TIME representation. Return value in + YYYYMMDDHHMMSS format as side-effect. + + This function also checks if datetime value fits in DATETIME range. + + RETURN VALUE + -1 Timestamp with wrong values + anything else DATETIME as integer in YYYYMMDDHHMMSS format + Datetime value in YYYYMMDDHHMMSS format. +*/ + +longlong number_to_datetime_or_date(longlong nr, ulong sec_part, + MYSQL_TIME *time_res, + ulonglong flags, int *was_cut) +{ + long part1,part2; + DBUG_ASSERT(C_FLAGS_OK(flags)); + + *was_cut= 0; + time_res->time_type=MYSQL_TIMESTAMP_DATE; + + if (nr == 0 || nr >= 10000101000000LL) + { + time_res->time_type=MYSQL_TIMESTAMP_DATETIME; + goto ok; + } + if (nr < 101) + goto err; + if (nr <= (YY_PART_YEAR-1)*10000L+1231L) + { + nr= (nr+20000000L)*1000000L; /* YYMMDD, year: 2000-2069 */ + goto ok; + } + if (nr < (YY_PART_YEAR)*10000L+101L) + goto err; + if (nr <= 991231L) + { + nr= (nr+19000000L)*1000000L; /* YYMMDD, year: 1970-1999 */ + goto ok; + } + if (nr < 10000101L) + goto err; + if (nr <= 99991231L) + { + nr= nr*1000000L; + goto ok; + } + if (nr < 101000000L) + goto err; + + time_res->time_type=MYSQL_TIMESTAMP_DATETIME; + + if (nr <= (YY_PART_YEAR-1)*10000000000LL+1231235959LL) + { + nr= nr+20000000000000LL; /* YYMMDDHHMMSS, 2000-2069 */ + goto ok; + } + if (nr < YY_PART_YEAR*10000000000LL+ 101000000LL) + goto err; + if (nr <= 991231235959LL) + nr= nr+19000000000000LL; /* YYMMDDHHMMSS, 1970-1999 */ + + ok: + part1=(long) (nr/1000000LL); + part2=(long) (nr - (longlong) part1*1000000LL); + time_res->year= (int) (part1/10000L); part1%=10000L; + time_res->month= (int) part1 / 100; + time_res->day= (int) part1 % 100; + time_res->hour= (int) (part2/10000L); part2%=10000L; + time_res->minute=(int) part2 / 100; + time_res->second=(int) part2 % 100; + time_res->second_part= sec_part; + time_res->neg= 0; + + if (time_res->year <= 9999 && time_res->month <= 12 && + time_res->day <= 31 && time_res->hour <= 23 && + time_res->minute <= 59 && time_res->second <= 59 && + sec_part <= TIME_MAX_SECOND_PART && + !check_date(time_res, nr || sec_part, flags, was_cut)) + { + if (time_res->time_type == MYSQL_TIMESTAMP_DATE && sec_part != 0) + { + /* Date format, but with fractional digits, e.g. 20010203.5 */ + *was_cut= MYSQL_TIME_NOTE_TRUNCATED; + time_res->second_part= 0; + } + return nr; + } + + /* Don't want to have was_cut get set if NO_ZERO_DATE was violated. */ + if (nr || !(flags & C_TIME_NO_ZERO_DATE)) + *was_cut= MYSQL_TIME_WARN_TRUNCATED; + return -1; + + err: + { + /* reset everything except time_type */ + enum enum_mysql_timestamp_type save= time_res->time_type; + bzero((char*) time_res, sizeof(*time_res)); + time_res->time_type= save; /* Restore range */ + *was_cut= MYSQL_TIME_WARN_TRUNCATED; /* Found invalid date */ + } + return -1; +} + +/* + Convert a pair of integers to a MYSQL_TIME struct. + + @param[in] nr a number to convert + @param[out] ltime Date to check. + @param[out] was_cut MYSQL_TIME_WARN_OUT_OF_RANGE if the value was + modified to fit in the valid range. Otherwise 0. + + @details + Takes a number in the [-]HHHMMSS.uuuuuu, + YYMMDDHHMMSS.uuuuuu, or in the YYYYMMDDHHMMSS.uuuuuu formats. + + @return + 0 time value is valid, but was possibly truncated + -1 time value is invalid +*/ +int number_to_time_only(my_bool neg, ulonglong nr, ulong sec_part, + ulong max_hour, MYSQL_TIME *ltime, int *was_cut) +{ + static const ulonglong TIME_MAX_mmss= TIME_MAX_MINUTE*100 + TIME_MAX_SECOND; + ulonglong time_max_value= max_hour * 10000ULL + TIME_MAX_mmss; + *was_cut= 0; + ltime->year= ltime->month= ltime->day= 0; + ltime->time_type= MYSQL_TIMESTAMP_TIME; + + ltime->neg= neg; + + if (nr > time_max_value) + { + nr= time_max_value; + sec_part= TIME_MAX_SECOND_PART; + *was_cut= MYSQL_TIME_WARN_OUT_OF_RANGE; + } + ltime->hour = (uint)(nr/100/100); + ltime->minute= nr/100%100; + ltime->second= nr%100; + ltime->second_part= sec_part; + + if (ltime->minute < 60 && ltime->second < 60 && sec_part <= TIME_MAX_SECOND_PART) + return 0; + + *was_cut= MYSQL_TIME_WARN_TRUNCATED; + return -1; +} + + +/* Convert time value to integer in YYYYMMDDHHMMSS format */ + +ulonglong TIME_to_ulonglong_datetime(const MYSQL_TIME *my_time) +{ + return ((ulonglong) (my_time->year * 10000UL + + my_time->month * 100UL + + my_time->day) * 1000000ULL + + (ulonglong) (my_time->hour * 10000UL + + my_time->minute * 100UL + + my_time->second)); +} + + +/* Convert MYSQL_TIME value to integer in YYYYMMDD format */ + +ulonglong TIME_to_ulonglong_date(const MYSQL_TIME *my_time) +{ + return (ulonglong) (my_time->year * 10000UL + my_time->month * 100UL + + my_time->day); +} + + +/* + Convert MYSQL_TIME value to integer in HHMMSS format. + This function doesn't take into account time->day member: + it's assumed that days have been converted to hours already. +*/ + +ulonglong TIME_to_ulonglong_time(const MYSQL_TIME *my_time) +{ + return (ulonglong) (my_time->hour * 10000UL + + my_time->minute * 100UL + + my_time->second); +} + + +/* + Convert struct MYSQL_TIME (date and time split into year/month/day/hour/... + to a number in format YYYYMMDDHHMMSS (DATETIME), + YYYYMMDD (DATE) or HHMMSS (TIME). + + SYNOPSIS + TIME_to_ulonglong() + + DESCRIPTION + The function is used when we need to convert value of time item + to a number if it's used in numeric context, i. e.: + SELECT NOW()+1, CURDATE()+0, CURTIME()+0; + SELECT ?+1; + + NOTE + This function doesn't check that given MYSQL_TIME structure members are + in valid range. If they are not, return value won't reflect any + valid date either. +*/ + +ulonglong TIME_to_ulonglong(const MYSQL_TIME *my_time) +{ + switch (my_time->time_type) { + case MYSQL_TIMESTAMP_DATETIME: + return TIME_to_ulonglong_datetime(my_time); + case MYSQL_TIMESTAMP_DATE: + return TIME_to_ulonglong_date(my_time); + case MYSQL_TIMESTAMP_TIME: + return TIME_to_ulonglong_time(my_time); + case MYSQL_TIMESTAMP_NONE: + case MYSQL_TIMESTAMP_ERROR: + return 0; + default: + DBUG_ASSERT(0); + } + return 0; +} + +double TIME_to_double(const MYSQL_TIME *my_time) +{ + double d= (double)TIME_to_ulonglong(my_time); + + if (my_time->time_type == MYSQL_TIMESTAMP_DATE) + return d; + + d+= my_time->second_part/(double)TIME_SECOND_PART_FACTOR; + return my_time->neg ? -d : d; +} diff --git a/sql-common/my_user.c b/sql-common/my_user.c new file mode 100644 index 00000000..4af0f8f0 --- /dev/null +++ b/sql-common/my_user.c @@ -0,0 +1,70 @@ +/* Copyright (c) 2006-2008 MySQL AB, 2009 Sun Microsystems, Inc. + Use is subject to license terms. + + 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-1335 USA */ + +#include <my_global.h> +#include <my_user.h> +#include <m_string.h> +#include <mysql_com.h> + +/* + Parse user value to user name and host name parts. + + SYNOPSIS + user_id_str [IN] User value string (the source). + user_id_len [IN] Length of the user value. + user_name_str [OUT] Buffer to store user name part. + Must be not less than USERNAME_LENGTH + 1. + user_name_len [OUT] A place to store length of the user name part. + host_name_str [OUT] Buffer to store host name part. + Must be not less than HOSTNAME_LENGTH + 1. + host_name_len [OUT] A place to store length of the host name part. + + RETURN + 0 - if only a user was set, no '@' was found + 1 - if both user and host were set +*/ + +int parse_user(const char *user_id_str, size_t user_id_len, + char *user_name_str, size_t *user_name_len, + char *host_name_str, size_t *host_name_len) +{ + char *p= strrchr(user_id_str, '@'); + + if (!p) + { + *user_name_len= user_id_len; + *host_name_len= 0; + } + else + { + *user_name_len= (uint) (p - user_id_str); + *host_name_len= (uint) (user_id_len - *user_name_len - 1); + } + + if (*user_name_len > USERNAME_LENGTH) + *user_name_len= USERNAME_LENGTH; + + if (*host_name_len > HOSTNAME_LENGTH) + *host_name_len= HOSTNAME_LENGTH; + + memcpy(user_name_str, user_id_str, *user_name_len); + memcpy(host_name_str, p + 1, *host_name_len); + + user_name_str[*user_name_len]= 0; + host_name_str[*host_name_len]= 0; + + return p != NULL; +} diff --git a/sql-common/mysql_async.c b/sql-common/mysql_async.c new file mode 100644 index 00000000..a19955c4 --- /dev/null +++ b/sql-common/mysql_async.c @@ -0,0 +1,1995 @@ +/* + Copyright 2011 Kristian Nielsen and Monty Program Ab + + This file is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this. If not, see <http://www.gnu.org/licenses/>. +*/ + +/* + MySQL non-blocking client library functions. +*/ + +#include "my_global.h" +#include "my_sys.h" +#include "mysql.h" +#include "errmsg.h" +#include "sql_common.h" +#include "my_context.h" +#include "violite.h" +#include "mysql_async.h" + + +#ifdef __WIN__ +/* + Windows does not support MSG_DONTWAIT for send()/recv(). So we need to ensure + that the socket is non-blocking at the start of every operation. +*/ +#define WIN_SET_NONBLOCKING(mysql) { \ + my_bool old_mode; \ + if ((mysql)->net.vio) vio_blocking((mysql)->net.vio, FALSE, &old_mode); \ + } +#else +#define WIN_SET_NONBLOCKING(mysql) +#endif + + +void +my_context_install_suspend_resume_hook(struct mysql_async_context *b, + void (*hook)(my_bool, void *), + void *user_data) +{ + b->suspend_resume_hook= hook; + b->suspend_resume_hook_user_data= user_data; +} + + +/* Asynchronous connect(); socket must already be set non-blocking. */ +int +my_connect_async(struct mysql_async_context *b, my_socket fd, + const struct sockaddr *name, uint namelen, int vio_timeout) +{ + int res; + size_socket s_err_size; + + /* Make the socket non-blocking. */ +#ifdef __WIN__ + ulong arg= 1; + ioctlsocket(fd, FIONBIO, (void *)&arg); +#else + fcntl(fd, F_SETFL, O_NONBLOCK); +#endif + + b->events_to_wait_for= 0; + /* + Start to connect asynchronously. + If this will block, we suspend the call and return control to the + application context. The application will then resume us when the socket + polls ready for write, indicating that the connection attempt completed. + */ + res= connect(fd, name, namelen); + if (res != 0) + { +#ifdef __WIN__ + int wsa_err= WSAGetLastError(); + if (wsa_err != WSAEWOULDBLOCK) + return res; + b->events_to_wait_for|= MYSQL_WAIT_EXCEPT; +#else + int err= errno; + if (err != EINPROGRESS && err != EALREADY && err != EAGAIN) + return res; +#endif + b->events_to_wait_for|= MYSQL_WAIT_WRITE; + if (vio_timeout >= 0) + { + b->timeout_value= vio_timeout; + b->events_to_wait_for|= MYSQL_WAIT_TIMEOUT; + } + else + b->timeout_value= 0; + if (b->suspend_resume_hook) + (*b->suspend_resume_hook)(TRUE, b->suspend_resume_hook_user_data); + my_context_yield(&b->async_context); + if (b->suspend_resume_hook) + (*b->suspend_resume_hook)(FALSE, b->suspend_resume_hook_user_data); + if (b->events_occurred & MYSQL_WAIT_TIMEOUT) + return -1; + + s_err_size= sizeof(res); + if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (char*) &res, &s_err_size) != 0) + return -1; + if (res) + { + errno= res; + return -1; + } + } + return res; +} + +#define IS_BLOCKING_ERROR() \ + IF_WIN(WSAGetLastError() != WSAEWOULDBLOCK, \ + (errno != EAGAIN && errno != EINTR)) + +#ifdef _AIX +#ifndef MSG_DONTWAIT +#define MSG_DONTWAIT 0 +#endif +#endif + +ssize_t +my_recv_async(struct mysql_async_context *b, my_socket fd, + unsigned char *buf, size_t size, int timeout) +{ + ssize_t res; + + for (;;) + { + res= recv(fd, buf, (int)size, IF_WIN(0, MSG_DONTWAIT)); + if (res >= 0 || IS_BLOCKING_ERROR()) + return res; + b->events_to_wait_for= MYSQL_WAIT_READ; + if (timeout >= 0) + { + b->events_to_wait_for|= MYSQL_WAIT_TIMEOUT; + b->timeout_value= timeout; + } + if (b->suspend_resume_hook) + (*b->suspend_resume_hook)(TRUE, b->suspend_resume_hook_user_data); + my_context_yield(&b->async_context); + if (b->suspend_resume_hook) + (*b->suspend_resume_hook)(FALSE, b->suspend_resume_hook_user_data); + if (b->events_occurred & MYSQL_WAIT_TIMEOUT) + return -1; + } +} + + +ssize_t +my_send_async(struct mysql_async_context *b, my_socket fd, + const unsigned char *buf, size_t size, int timeout) +{ + ssize_t res; + + for (;;) + { + res= send(fd, buf, (int)size, IF_WIN(0, MSG_DONTWAIT)); + if (res >= 0 || IS_BLOCKING_ERROR()) + return res; + b->events_to_wait_for= MYSQL_WAIT_WRITE; + if (timeout >= 0) + { + b->events_to_wait_for|= MYSQL_WAIT_TIMEOUT; + b->timeout_value= timeout; + } + if (b->suspend_resume_hook) + (*b->suspend_resume_hook)(TRUE, b->suspend_resume_hook_user_data); + my_context_yield(&b->async_context); + if (b->suspend_resume_hook) + (*b->suspend_resume_hook)(FALSE, b->suspend_resume_hook_user_data); + if (b->events_occurred & MYSQL_WAIT_TIMEOUT) + return -1; + } +} + + +my_bool +my_io_wait_async(struct mysql_async_context *b, enum enum_vio_io_event event, + int timeout) +{ + switch (event) + { + case VIO_IO_EVENT_READ: + b->events_to_wait_for = MYSQL_WAIT_READ; + break; + case VIO_IO_EVENT_WRITE: + b->events_to_wait_for = MYSQL_WAIT_WRITE; + break; + case VIO_IO_EVENT_CONNECT: + b->events_to_wait_for = MYSQL_WAIT_WRITE | IF_WIN(0, MYSQL_WAIT_EXCEPT); + break; + } + + if (timeout >= 0) + { + b->events_to_wait_for |= MYSQL_WAIT_TIMEOUT; + b->timeout_value= timeout; + } + if (b->suspend_resume_hook) + (*b->suspend_resume_hook)(TRUE, b->suspend_resume_hook_user_data); + my_context_yield(&b->async_context); + if (b->suspend_resume_hook) + (*b->suspend_resume_hook)(FALSE, b->suspend_resume_hook_user_data); + return (b->events_occurred & MYSQL_WAIT_TIMEOUT) ? 0 : 1; +} + + +#ifdef HAVE_OPENSSL +static my_bool +my_ssl_async_check_result(int res, struct mysql_async_context *b, SSL *ssl) +{ + int ssl_err; + b->events_to_wait_for= 0; + if (res >= 0) + return 1; + ssl_err= SSL_get_error(ssl, res); + if (ssl_err == SSL_ERROR_WANT_READ) + b->events_to_wait_for|= MYSQL_WAIT_READ; + else if (ssl_err == SSL_ERROR_WANT_WRITE) + b->events_to_wait_for|= MYSQL_WAIT_WRITE; + else + return 1; + if (b->suspend_resume_hook) + (*b->suspend_resume_hook)(TRUE, b->suspend_resume_hook_user_data); + my_context_yield(&b->async_context); + if (b->suspend_resume_hook) + (*b->suspend_resume_hook)(FALSE, b->suspend_resume_hook_user_data); + return 0; +} + +int +my_ssl_read_async(struct mysql_async_context *b, SSL *ssl, + void *buf, int size) +{ + int res; + + for (;;) + { + res= SSL_read(ssl, buf, size); + if (my_ssl_async_check_result(res, b, ssl)) + return res; + } +} + +int +my_ssl_write_async(struct mysql_async_context *b, SSL *ssl, + const void *buf, int size) +{ + int res; + + for (;;) + { + res= SSL_write(ssl, buf, size); + if (my_ssl_async_check_result(res, b, ssl)) + return res; + } +} +#endif /* HAVE_OPENSSL */ + +/* + Legacy support of the MariaDB 5.5 version, where timeouts where only in + seconds resolution. Applications that use this will be asked to set a timeout + at the nearest higher whole-seconds value. +*/ +unsigned int STDCALL +mysql_get_timeout_value(const MYSQL *mysql) +{ + unsigned int timeout= mysql->options.extension->async_context->timeout_value; + /* Avoid overflow. */ + if (timeout > UINT_MAX - 999) + return (timeout - 1)/1000 + 1; + else + return (timeout+999)/1000; +} + + +unsigned int STDCALL +mysql_get_timeout_value_ms(const MYSQL *mysql) +{ + return mysql->options.extension->async_context->timeout_value; +} + + +/* + Now create non-blocking definitions for all the calls that may block. + + Each call FOO gives rise to FOO_start() that prepares the MYSQL object for + doing non-blocking calls that can suspend operation mid-way, and then starts + the call itself. And a FOO_start_internal trampoline to assist with running + the real call in a co-routine that can be suspended. And a FOO_cont() that + can continue a suspended operation. +*/ + +#define MK_ASYNC_INTERNAL_BODY(call, invoke_args, mysql_val, ret_type, ok_val)\ + struct call ## _params *parms= (struct call ## _params *)d; \ + ret_type ret; \ + struct mysql_async_context *b= \ + (mysql_val)->options.extension->async_context; \ + \ + ret= call invoke_args; \ + b->ret_result. ok_val = ret; \ + b->events_to_wait_for= 0; + +#define MK_ASYNC_START_BODY(call, mysql_val, parms_assign, err_val, ok_val, extra1) \ + int res; \ + struct mysql_async_context *b; \ + struct call ## _params parms; \ + \ + extra1 \ + b= mysql_val->options.extension->async_context; \ + parms_assign \ + \ + b->active= 1; \ + res= my_context_spawn(&b->async_context, call ## _start_internal, &parms); \ + b->active= b->suspended= 0; \ + if (res > 0) \ + { \ + /* Suspended. */ \ + b->suspended= 1; \ + return b->events_to_wait_for; \ + } \ + if (res < 0) \ + { \ + set_mysql_error((mysql_val), CR_OUT_OF_MEMORY, unknown_sqlstate); \ + *ret= err_val; \ + } \ + else \ + *ret= b->ret_result. ok_val; \ + return 0; + +#define MK_ASYNC_CONT_BODY(mysql_val, err_val, ok_val) \ + int res; \ + struct mysql_async_context *b= \ + (mysql_val)->options.extension->async_context; \ + if (!b->suspended) \ + { \ + set_mysql_error((mysql_val), CR_COMMANDS_OUT_OF_SYNC, unknown_sqlstate); \ + *ret= err_val; \ + return 0; \ + } \ + \ + b->active= 1; \ + b->events_occurred= ready_status; \ + res= my_context_continue(&b->async_context); \ + b->active= 0; \ + if (res > 0) \ + return b->events_to_wait_for; /* (Still) suspended */ \ + b->suspended= 0; \ + if (res < 0) \ + { \ + set_mysql_error((mysql_val), CR_OUT_OF_MEMORY, unknown_sqlstate); \ + *ret= err_val; \ + } \ + else \ + *ret= b->ret_result. ok_val; /* Finished. */ \ + return 0; + +#define MK_ASYNC_INTERNAL_BODY_VOID_RETURN(call, invoke_args, mysql_val) \ + struct call ## _params *parms= (struct call ## _params *)d; \ + struct mysql_async_context *b= \ + (mysql_val)->options.extension->async_context; \ + \ + call invoke_args; \ + b->events_to_wait_for= 0; + +#define MK_ASYNC_START_BODY_VOID_RETURN(call, mysql_val, parms_assign, extra1)\ + int res; \ + struct mysql_async_context *b; \ + struct call ## _params parms; \ + \ + extra1 \ + b= mysql_val->options.extension->async_context; \ + parms_assign \ + \ + b->active= 1; \ + res= my_context_spawn(&b->async_context, call ## _start_internal, &parms); \ + b->active= b->suspended= 0; \ + if (res > 0) \ + { \ + /* Suspended. */ \ + b->suspended= 1; \ + return b->events_to_wait_for; \ + } \ + if (res < 0) \ + set_mysql_error((mysql_val), CR_OUT_OF_MEMORY, unknown_sqlstate); \ + return 0; + +#define MK_ASYNC_CONT_BODY_VOID_RETURN(mysql_val) \ + int res; \ + struct mysql_async_context *b= \ + (mysql_val)->options.extension->async_context; \ + if (!b->suspended) \ + { \ + set_mysql_error((mysql_val), CR_COMMANDS_OUT_OF_SYNC, unknown_sqlstate); \ + return 0; \ + } \ + \ + b->active= 1; \ + b->events_occurred= ready_status; \ + res= my_context_continue(&b->async_context); \ + b->active= 0; \ + if (res > 0) \ + return b->events_to_wait_for; /* (Still) suspended */ \ + b->suspended= 0; \ + if (res < 0) \ + set_mysql_error((mysql_val), CR_OUT_OF_MEMORY, unknown_sqlstate); \ + return 0; + + +/* Structure used to pass parameters from mysql_real_connect_start(). */ +struct mysql_real_connect_params { + MYSQL *mysql; + const char *host; + const char *user; + const char *passwd; + const char *db; + unsigned int port; + const char *unix_socket; + unsigned long client_flags; +}; +static void +mysql_real_connect_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_real_connect, + (parms->mysql, parms->host, parms->user, parms->passwd, parms->db, + parms->port, parms->unix_socket, parms->client_flags), + parms->mysql, + MYSQL *, + r_ptr) +} +int STDCALL +mysql_real_connect_start(MYSQL **ret, MYSQL *mysql, const char *host, + const char *user, const char *passwd, const char *db, + unsigned int port, const char *unix_socket, + unsigned long client_flags) +{ +MK_ASYNC_START_BODY( + mysql_real_connect, + mysql, + { + parms.mysql= mysql; + parms.host= host; + parms.user= user; + parms.passwd= passwd; + parms.db= db; + parms.port= port; + parms.unix_socket= unix_socket; + /* + async wrapper enforce the CLIENT_REMEMBER_OPTIONS flag to be + functional (otherwise it can't operate) + */ + parms.client_flags= client_flags | CLIENT_REMEMBER_OPTIONS; + }, + NULL, + r_ptr, + /* Nothing */) +} +int STDCALL +mysql_real_connect_cont(MYSQL **ret, MYSQL *mysql, int ready_status) +{ +MK_ASYNC_CONT_BODY( + mysql, + NULL, + r_ptr) +} + +/* Structure used to pass parameters from mysql_real_query_start(). */ +struct mysql_real_query_params { + MYSQL *mysql; + const char *stmt_str; + unsigned long length; +}; +static void +mysql_real_query_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_real_query, + (parms->mysql, parms->stmt_str, parms->length), + parms->mysql, + int, + r_int) +} +int STDCALL +mysql_real_query_start(int *ret, MYSQL *mysql, const char *stmt_str, unsigned long length) +{ +MK_ASYNC_START_BODY( + mysql_real_query, + mysql, + { + WIN_SET_NONBLOCKING(mysql) + parms.mysql= mysql; + parms.stmt_str= stmt_str; + parms.length= length; + }, + 1, + r_int, + /* Nothing */) +} +int STDCALL +mysql_real_query_cont(int *ret, MYSQL *mysql, int ready_status) +{ +MK_ASYNC_CONT_BODY( + mysql, + 1, + r_int) +} + +/* Structure used to pass parameters from mysql_fetch_row_start(). */ +struct mysql_fetch_row_params { + MYSQL_RES *result; +}; +static void +mysql_fetch_row_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_fetch_row, + (parms->result), + parms->result->handle, + MYSQL_ROW, + r_ptr) +} +int STDCALL +mysql_fetch_row_start(MYSQL_ROW *ret, MYSQL_RES *result) +{ +MK_ASYNC_START_BODY( + mysql_fetch_row, + result->handle, + { + WIN_SET_NONBLOCKING(result->handle) + parms.result= result; + }, + NULL, + r_ptr, + /* + If we already fetched all rows from server (eg. mysql_store_result()), + then result->handle will be NULL and we cannot suspend. But that is fine, + since in this case mysql_fetch_row cannot block anyway. Just return + directly. + */ + if (!result->handle) + { + *ret= mysql_fetch_row(result); + return 0; + }) +} +int STDCALL +mysql_fetch_row_cont(MYSQL_ROW *ret, MYSQL_RES *result, int ready_status) +{ +MK_ASYNC_CONT_BODY( + result->handle, + NULL, + r_ptr) +} + +/* Structure used to pass parameters from mysql_set_character_set_start(). */ +struct mysql_set_character_set_params { + MYSQL *mysql; + const char *csname; +}; +static void +mysql_set_character_set_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_set_character_set, + (parms->mysql, parms->csname), + parms->mysql, + int, + r_int) +} +int STDCALL +mysql_set_character_set_start(int *ret, MYSQL *mysql, const char *csname) +{ +MK_ASYNC_START_BODY( + mysql_set_character_set, + mysql, + { + WIN_SET_NONBLOCKING(mysql) + parms.mysql= mysql; + parms.csname= csname; + }, + 1, + r_int, + /* Nothing */) +} +int STDCALL +mysql_set_character_set_cont(int *ret, MYSQL *mysql, int ready_status) +{ +MK_ASYNC_CONT_BODY( + mysql, + 1, + r_int) +} + +/* Structure used to pass parameters from mysql_sekect_db_start(). */ +struct mysql_select_db_params { + MYSQL *mysql; + const char *db; +}; +static void +mysql_select_db_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_select_db, + (parms->mysql, parms->db), + parms->mysql, + int, + r_int) +} +int STDCALL +mysql_select_db_start(int *ret, MYSQL *mysql, const char *db) +{ +MK_ASYNC_START_BODY( + mysql_select_db, + mysql, + { + WIN_SET_NONBLOCKING(mysql) + parms.mysql= mysql; + parms.db= db; + }, + 1, + r_int, + /* Nothing */) +} +int STDCALL +mysql_select_db_cont(int *ret, MYSQL *mysql, int ready_status) +{ +MK_ASYNC_CONT_BODY( + mysql, + 1, + r_int) +} + +/* Structure used to pass parameters from mysql_send_query_start(). */ +struct mysql_send_query_params { + MYSQL *mysql; + const char *q; + unsigned long length; +}; +static void +mysql_send_query_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_send_query, + (parms->mysql, parms->q, parms->length), + parms->mysql, + int, + r_int) +} +int STDCALL +mysql_send_query_start(int *ret, MYSQL *mysql, const char *q, unsigned long length) +{ +MK_ASYNC_START_BODY( + mysql_send_query, + mysql, + { + WIN_SET_NONBLOCKING(mysql) + parms.mysql= mysql; + parms.q= q; + parms.length= length; + }, + 1, + r_int, + /* Nothing */) +} +int STDCALL +mysql_send_query_cont(int *ret, MYSQL *mysql, int ready_status) +{ +MK_ASYNC_CONT_BODY( + mysql, + 1, + r_int) +} + +/* Structure used to pass parameters from mysql_store_result_start(). */ +struct mysql_store_result_params { + MYSQL *mysql; +}; +static void +mysql_store_result_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_store_result, + (parms->mysql), + parms->mysql, + MYSQL_RES *, + r_ptr) +} +int STDCALL +mysql_store_result_start(MYSQL_RES **ret, MYSQL *mysql) +{ +MK_ASYNC_START_BODY( + mysql_store_result, + mysql, + { + WIN_SET_NONBLOCKING(mysql) + parms.mysql= mysql; + }, + NULL, + r_ptr, + /* Nothing */) +} +int STDCALL +mysql_store_result_cont(MYSQL_RES **ret, MYSQL *mysql, int ready_status) +{ +MK_ASYNC_CONT_BODY( + mysql, + NULL, + r_ptr) +} + +/* Structure used to pass parameters from mysql_free_result_start(). */ +struct mysql_free_result_params { + MYSQL_RES *result; +}; +static void +mysql_free_result_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY_VOID_RETURN( + mysql_free_result, + (parms->result), + parms->result->handle) +} +int STDCALL +mysql_free_result_start(MYSQL_RES *result) +{ +MK_ASYNC_START_BODY_VOID_RETURN( + mysql_free_result, + result->handle, + { + WIN_SET_NONBLOCKING(result->handle) + parms.result= result; + }, + /* + mysql_free_result() can have NULL in result->handle (this happens when all + rows have been fetched and mysql_fetch_row() returned NULL.) + So we cannot suspend, but it does not matter, as in this case + mysql_free_result() cannot block. + It is also legitimate to have NULL result, which will do nothing. + */ + if (!result || !result->handle) + { + mysql_free_result(result); + return 0; + }) +} +int STDCALL +mysql_free_result_cont(MYSQL_RES *result, int ready_status) +{ +MK_ASYNC_CONT_BODY_VOID_RETURN(result->handle) +} + +/* Structure used to pass parameters from mysql_close_slow_part_start(). */ +struct mysql_close_slow_part_params { + MYSQL *sock; +}; +/* + We need special handling for mysql_close(), as the first part may block, + while the last part needs to free our extra library context stack. + + So we do the first part (mysql_close_slow_part()) non-blocking, but the last + part blocking. +*/ +static void +mysql_close_slow_part_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY_VOID_RETURN( + mysql_close_slow_part, + (parms->sock), + parms->sock) +} +int STDCALL +mysql_close_slow_part_start(MYSQL *sock) +{ +MK_ASYNC_START_BODY_VOID_RETURN( + mysql_close_slow_part, + sock, + { + WIN_SET_NONBLOCKING(sock) + parms.sock= sock; + }, + /* Nothing */) +} +int STDCALL +mysql_close_slow_part_cont(MYSQL *sock, int ready_status) +{ +MK_ASYNC_CONT_BODY_VOID_RETURN(sock) +} +int STDCALL +mysql_close_start(MYSQL *sock) +{ + int res; + + /* It is legitimate to have NULL sock argument, which will do nothing. */ + if (sock) + { + res= mysql_close_slow_part_start(sock); + /* If we need to block, return now and do the rest in mysql_close_cont(). */ + if (res) + return res; + } + mysql_close(sock); + return 0; +} +int STDCALL +mysql_close_cont(MYSQL *sock, int ready_status) +{ + int res; + + res= mysql_close_slow_part_cont(sock, ready_status); + if (res) + return res; + mysql_close(sock); + return 0; +} + +/* + These following are not available inside the server (neither blocking or + non-blocking). +*/ +#ifndef MYSQL_SERVER +/* Structure used to pass parameters from mysql_change_user_start(). */ +struct mysql_change_user_params { + MYSQL *mysql; + const char *user; + const char *passwd; + const char *db; +}; +static void +mysql_change_user_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_change_user, + (parms->mysql, parms->user, parms->passwd, parms->db), + parms->mysql, + my_bool, + r_my_bool) +} +int STDCALL +mysql_change_user_start(my_bool *ret, MYSQL *mysql, const char *user, const char *passwd, const char *db) +{ +MK_ASYNC_START_BODY( + mysql_change_user, + mysql, + { + WIN_SET_NONBLOCKING(mysql) + parms.mysql= mysql; + parms.user= user; + parms.passwd= passwd; + parms.db= db; + }, + TRUE, + r_my_bool, + /* Nothing */) +} +int STDCALL +mysql_change_user_cont(my_bool *ret, MYSQL *mysql, int ready_status) +{ +MK_ASYNC_CONT_BODY( + mysql, + TRUE, + r_my_bool) +} + +/* Structure used to pass parameters from mysql_query_start(). */ +struct mysql_query_params { + MYSQL *mysql; + const char *q; +}; +static void +mysql_query_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_query, + (parms->mysql, parms->q), + parms->mysql, + int, + r_int) +} +int STDCALL +mysql_query_start(int *ret, MYSQL *mysql, const char *q) +{ +MK_ASYNC_START_BODY( + mysql_query, + mysql, + { + WIN_SET_NONBLOCKING(mysql) + parms.mysql= mysql; + parms.q= q; + }, + 1, + r_int, + /* Nothing */) +} +int STDCALL +mysql_query_cont(int *ret, MYSQL *mysql, int ready_status) +{ +MK_ASYNC_CONT_BODY( + mysql, + 1, + r_int) +} + +/* Structure used to pass parameters from mysql_shutdown_start(). */ +struct mysql_shutdown_params { + MYSQL *mysql; + enum mysql_enum_shutdown_level shutdown_level; +}; +static void +mysql_shutdown_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_shutdown, + (parms->mysql, parms->shutdown_level), + parms->mysql, + int, + r_int) +} +int STDCALL +mysql_shutdown_start(int *ret, MYSQL *mysql, enum mysql_enum_shutdown_level shutdown_level) +{ +MK_ASYNC_START_BODY( + mysql_shutdown, + mysql, + { + WIN_SET_NONBLOCKING(mysql) + parms.mysql= mysql; + parms.shutdown_level= shutdown_level; + }, + 1, + r_int, + /* Nothing */) +} +int STDCALL +mysql_shutdown_cont(int *ret, MYSQL *mysql, int ready_status) +{ +MK_ASYNC_CONT_BODY( + mysql, + 1, + r_int) +} + +/* Structure used to pass parameters from mysql_dump_debug_info_start(). */ +struct mysql_dump_debug_info_params { + MYSQL *mysql; +}; +static void +mysql_dump_debug_info_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_dump_debug_info, + (parms->mysql), + parms->mysql, + int, + r_int) +} +int STDCALL +mysql_dump_debug_info_start(int *ret, MYSQL *mysql) +{ +MK_ASYNC_START_BODY( + mysql_dump_debug_info, + mysql, + { + WIN_SET_NONBLOCKING(mysql) + parms.mysql= mysql; + }, + 1, + r_int, + /* Nothing */) +} +int STDCALL +mysql_dump_debug_info_cont(int *ret, MYSQL *mysql, int ready_status) +{ +MK_ASYNC_CONT_BODY( + mysql, + 1, + r_int) +} + +/* Structure used to pass parameters from mysql_refresh_start(). */ +struct mysql_refresh_params { + MYSQL *mysql; + unsigned int refresh_options; +}; +static void +mysql_refresh_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_refresh, + (parms->mysql, parms->refresh_options), + parms->mysql, + int, + r_int) +} +int STDCALL +mysql_refresh_start(int *ret, MYSQL *mysql, unsigned int refresh_options) +{ +MK_ASYNC_START_BODY( + mysql_refresh, + mysql, + { + WIN_SET_NONBLOCKING(mysql) + parms.mysql= mysql; + parms.refresh_options= refresh_options; + }, + 1, + r_int, + /* Nothing */) +} +int STDCALL +mysql_refresh_cont(int *ret, MYSQL *mysql, int ready_status) +{ +MK_ASYNC_CONT_BODY( + mysql, + 1, + r_int) +} + +/* Structure used to pass parameters from mysql_kill_start(). */ +struct mysql_kill_params { + MYSQL *mysql; + unsigned long pid; +}; +static void +mysql_kill_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_kill, + (parms->mysql, parms->pid), + parms->mysql, + int, + r_int) +} +int STDCALL +mysql_kill_start(int *ret, MYSQL *mysql, unsigned long pid) +{ +MK_ASYNC_START_BODY( + mysql_kill, + mysql, + { + WIN_SET_NONBLOCKING(mysql) + parms.mysql= mysql; + parms.pid= pid; + }, + 1, + r_int, + /* Nothing */) +} +int STDCALL +mysql_kill_cont(int *ret, MYSQL *mysql, int ready_status) +{ +MK_ASYNC_CONT_BODY( + mysql, + 1, + r_int) +} + +/* Structure used to pass parameters from mysql_set_server_option_start(). */ +struct mysql_set_server_option_params { + MYSQL *mysql; + enum enum_mysql_set_option option; +}; +static void +mysql_set_server_option_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_set_server_option, + (parms->mysql, parms->option), + parms->mysql, + int, + r_int) +} +int STDCALL +mysql_set_server_option_start(int *ret, MYSQL *mysql, + enum enum_mysql_set_option option) +{ +MK_ASYNC_START_BODY( + mysql_set_server_option, + mysql, + { + WIN_SET_NONBLOCKING(mysql) + parms.mysql= mysql; + parms.option= option; + }, + 1, + r_int, + /* Nothing */) +} +int STDCALL +mysql_set_server_option_cont(int *ret, MYSQL *mysql, int ready_status) +{ +MK_ASYNC_CONT_BODY( + mysql, + 1, + r_int) +} + +/* Structure used to pass parameters from mysql_ping_start(). */ +struct mysql_ping_params { + MYSQL *mysql; +}; +static void +mysql_ping_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_ping, + (parms->mysql), + parms->mysql, + int, + r_int) +} +int STDCALL +mysql_ping_start(int *ret, MYSQL *mysql) +{ +MK_ASYNC_START_BODY( + mysql_ping, + mysql, + { + WIN_SET_NONBLOCKING(mysql) + parms.mysql= mysql; + }, + 1, + r_int, + /* Nothing */) +} +int STDCALL +mysql_ping_cont(int *ret, MYSQL *mysql, int ready_status) +{ +MK_ASYNC_CONT_BODY( + mysql, + 1, + r_int) +} + +/* Structure used to pass parameters from mysql_stat_start(). */ +struct mysql_stat_params { + MYSQL *mysql; +}; +static void +mysql_stat_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_stat, + (parms->mysql), + parms->mysql, + const char *, + r_const_ptr) +} +int STDCALL +mysql_stat_start(const char **ret, MYSQL *mysql) +{ +MK_ASYNC_START_BODY( + mysql_stat, + mysql, + { + WIN_SET_NONBLOCKING(mysql) + parms.mysql= mysql; + }, + NULL, + r_const_ptr, + /* Nothing */) +} +int STDCALL +mysql_stat_cont(const char **ret, MYSQL *mysql, int ready_status) +{ +MK_ASYNC_CONT_BODY( + mysql, + NULL, + r_const_ptr) +} + +/* Structure used to pass parameters from mysql_list_dbs_start(). */ +struct mysql_list_dbs_params { + MYSQL *mysql; + const char *wild; +}; +static void +mysql_list_dbs_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_list_dbs, + (parms->mysql, parms->wild), + parms->mysql, + MYSQL_RES *, + r_ptr) +} +int STDCALL +mysql_list_dbs_start(MYSQL_RES **ret, MYSQL *mysql, const char *wild) +{ +MK_ASYNC_START_BODY( + mysql_list_dbs, + mysql, + { + WIN_SET_NONBLOCKING(mysql) + parms.mysql= mysql; + parms.wild= wild; + }, + NULL, + r_ptr, + /* Nothing */) +} +int STDCALL +mysql_list_dbs_cont(MYSQL_RES **ret, MYSQL *mysql, int ready_status) +{ +MK_ASYNC_CONT_BODY( + mysql, + NULL, + r_ptr) +} + +/* Structure used to pass parameters from mysql_list_tables_start(). */ +struct mysql_list_tables_params { + MYSQL *mysql; + const char *wild; +}; +static void +mysql_list_tables_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_list_tables, + (parms->mysql, parms->wild), + parms->mysql, + MYSQL_RES *, + r_ptr) +} +int STDCALL +mysql_list_tables_start(MYSQL_RES **ret, MYSQL *mysql, const char *wild) +{ +MK_ASYNC_START_BODY( + mysql_list_tables, + mysql, + { + WIN_SET_NONBLOCKING(mysql) + parms.mysql= mysql; + parms.wild= wild; + }, + NULL, + r_ptr, + /* Nothing */) +} +int STDCALL +mysql_list_tables_cont(MYSQL_RES **ret, MYSQL *mysql, int ready_status) +{ +MK_ASYNC_CONT_BODY( + mysql, + NULL, + r_ptr) +} + +/* Structure used to pass parameters from mysql_list_processes_start(). */ +struct mysql_list_processes_params { + MYSQL *mysql; +}; +static void +mysql_list_processes_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_list_processes, + (parms->mysql), + parms->mysql, + MYSQL_RES *, + r_ptr) +} +int STDCALL +mysql_list_processes_start(MYSQL_RES **ret, MYSQL *mysql) +{ +MK_ASYNC_START_BODY( + mysql_list_processes, + mysql, + { + WIN_SET_NONBLOCKING(mysql) + parms.mysql= mysql; + }, + NULL, + r_ptr, + /* Nothing */) +} +int STDCALL +mysql_list_processes_cont(MYSQL_RES **ret, MYSQL *mysql, int ready_status) +{ +MK_ASYNC_CONT_BODY( + mysql, + NULL, + r_ptr) +} + +/* Structure used to pass parameters from mysql_list_fields_start(). */ +struct mysql_list_fields_params { + MYSQL *mysql; + const char *table; + const char *wild; +}; +static void +mysql_list_fields_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_list_fields, + (parms->mysql, parms->table, parms->wild), + parms->mysql, + MYSQL_RES *, + r_ptr) +} +int STDCALL +mysql_list_fields_start(MYSQL_RES **ret, MYSQL *mysql, const char *table, + const char *wild) +{ +MK_ASYNC_START_BODY( + mysql_list_fields, + mysql, + { + WIN_SET_NONBLOCKING(mysql) + parms.mysql= mysql; + parms.table= table; + parms.wild= wild; + }, + NULL, + r_ptr, + /* Nothing */) +} +int STDCALL +mysql_list_fields_cont(MYSQL_RES **ret, MYSQL *mysql, int ready_status) +{ +MK_ASYNC_CONT_BODY( + mysql, + NULL, + r_ptr) +} + +/* Structure used to pass parameters from mysql_read_query_result_start(). */ +struct mysql_read_query_result_params { + MYSQL *mysql; +}; +static void +mysql_read_query_result_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_read_query_result, + (parms->mysql), + parms->mysql, + my_bool, + r_my_bool) +} +int STDCALL +mysql_read_query_result_start(my_bool *ret, MYSQL *mysql) +{ +MK_ASYNC_START_BODY( + mysql_read_query_result, + mysql, + { + WIN_SET_NONBLOCKING(mysql) + parms.mysql= mysql; + }, + TRUE, + r_my_bool, + /* Nothing */) +} +int STDCALL +mysql_read_query_result_cont(my_bool *ret, MYSQL *mysql, int ready_status) +{ +MK_ASYNC_CONT_BODY( + mysql, + TRUE, + r_my_bool) +} + +/* Structure used to pass parameters from mysql_stmt_prepare_start(). */ +struct mysql_stmt_prepare_params { + MYSQL_STMT *stmt; + const char *query; + unsigned long length; +}; +static void +mysql_stmt_prepare_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_stmt_prepare, + (parms->stmt, parms->query, parms->length), + parms->stmt->mysql, + int, + r_int) +} +int STDCALL +mysql_stmt_prepare_start(int *ret, MYSQL_STMT *stmt, const char *query, + unsigned long length) +{ +MK_ASYNC_START_BODY( + mysql_stmt_prepare, + stmt->mysql, + { + WIN_SET_NONBLOCKING(stmt->mysql) + parms.stmt= stmt; + parms.query= query; + parms.length= length; + }, + 1, + r_int, + /* If stmt->mysql==NULL then we will not block so can call directly. */ + if (!stmt->mysql) + { + *ret= mysql_stmt_prepare(stmt, query, length); + return 0; + }) +} +int STDCALL +mysql_stmt_prepare_cont(int *ret, MYSQL_STMT *stmt, int ready_status) +{ +MK_ASYNC_CONT_BODY( + stmt->mysql, + 1, + r_int) +} + +/* Structure used to pass parameters from mysql_stmt_execute_start(). */ +struct mysql_stmt_execute_params { + MYSQL_STMT *stmt; +}; +static void +mysql_stmt_execute_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_stmt_execute, + (parms->stmt), + parms->stmt->mysql, + int, + r_int) +} +int STDCALL +mysql_stmt_execute_start(int *ret, MYSQL_STMT *stmt) +{ +MK_ASYNC_START_BODY( + mysql_stmt_execute, + stmt->mysql, + { + WIN_SET_NONBLOCKING(stmt->mysql) + parms.stmt= stmt; + }, + 1, + r_int, + /* + If eg. mysql_change_user(), stmt->mysql will be NULL. + In this case, we cannot block. + */ + if (!stmt->mysql) + { + *ret= mysql_stmt_execute(stmt); + return 0; + }) +} +int STDCALL +mysql_stmt_execute_cont(int *ret, MYSQL_STMT *stmt, int ready_status) +{ +MK_ASYNC_CONT_BODY( + stmt->mysql, + 1, + r_int) +} + +/* Structure used to pass parameters from mysql_stmt_fetch_start(). */ +struct mysql_stmt_fetch_params { + MYSQL_STMT *stmt; +}; +static void +mysql_stmt_fetch_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_stmt_fetch, + (parms->stmt), + parms->stmt->mysql, + int, + r_int) +} +int STDCALL +mysql_stmt_fetch_start(int *ret, MYSQL_STMT *stmt) +{ +MK_ASYNC_START_BODY( + mysql_stmt_fetch, + stmt->mysql, + { + WIN_SET_NONBLOCKING(stmt->mysql) + parms.stmt= stmt; + }, + 1, + r_int, + /* If stmt->mysql==NULL then we will not block so can call directly. */ + if (!stmt->mysql) + { + *ret= mysql_stmt_fetch(stmt); + return 0; + }) +} +int STDCALL +mysql_stmt_fetch_cont(int *ret, MYSQL_STMT *stmt, int ready_status) +{ +MK_ASYNC_CONT_BODY( + stmt->mysql, + 1, + r_int) +} + +/* Structure used to pass parameters from mysql_stmt_store_result_start(). */ +struct mysql_stmt_store_result_params { + MYSQL_STMT *stmt; +}; +static void +mysql_stmt_store_result_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_stmt_store_result, + (parms->stmt), + parms->stmt->mysql, + int, + r_int) +} +int STDCALL +mysql_stmt_store_result_start(int *ret, MYSQL_STMT *stmt) +{ +MK_ASYNC_START_BODY( + mysql_stmt_store_result, + stmt->mysql, + { + WIN_SET_NONBLOCKING(stmt->mysql) + parms.stmt= stmt; + }, + 1, + r_int, + /* If stmt->mysql==NULL then we will not block so can call directly. */ + if (!stmt->mysql) + { + *ret= mysql_stmt_store_result(stmt); + return 0; + }) +} +int STDCALL +mysql_stmt_store_result_cont(int *ret, MYSQL_STMT *stmt, int ready_status) +{ +MK_ASYNC_CONT_BODY( + stmt->mysql, + 1, + r_int) +} + +/* Structure used to pass parameters from mysql_stmt_close_start(). */ +struct mysql_stmt_close_params { + MYSQL_STMT *stmt; +}; +static void +mysql_stmt_close_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_stmt_close, + (parms->stmt), + parms->stmt->mysql, + my_bool, + r_my_bool) +} +int STDCALL +mysql_stmt_close_start(my_bool *ret, MYSQL_STMT *stmt) +{ +MK_ASYNC_START_BODY( + mysql_stmt_close, + stmt->mysql, + { + WIN_SET_NONBLOCKING(stmt->mysql) + parms.stmt= stmt; + }, + TRUE, + r_my_bool, + /* If stmt->mysql==NULL then we will not block so can call directly. */ + if (!stmt->mysql) + { + *ret= mysql_stmt_close(stmt); + return 0; + }) +} +int STDCALL +mysql_stmt_close_cont(my_bool *ret, MYSQL_STMT *stmt, int ready_status) +{ +MK_ASYNC_CONT_BODY( + stmt->mysql, + TRUE, + r_my_bool) +} + +/* Structure used to pass parameters from mysql_stmt_reset_start(). */ +struct mysql_stmt_reset_params { + MYSQL_STMT *stmt; +}; +static void +mysql_stmt_reset_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_stmt_reset, + (parms->stmt), + parms->stmt->mysql, + my_bool, + r_my_bool) +} +int STDCALL +mysql_stmt_reset_start(my_bool *ret, MYSQL_STMT *stmt) +{ +MK_ASYNC_START_BODY( + mysql_stmt_reset, + stmt->mysql, + { + WIN_SET_NONBLOCKING(stmt->mysql) + parms.stmt= stmt; + }, + TRUE, + r_my_bool, + /* If stmt->mysql==NULL then we will not block so can call directly. */ + if (!stmt->mysql) + { + *ret= mysql_stmt_reset(stmt); + return 0; + }) +} +int STDCALL +mysql_stmt_reset_cont(my_bool *ret, MYSQL_STMT *stmt, int ready_status) +{ +MK_ASYNC_CONT_BODY( + stmt->mysql, + TRUE, + r_my_bool) +} + +/* Structure used to pass parameters from mysql_stmt_free_result_start(). */ +struct mysql_stmt_free_result_params { + MYSQL_STMT *stmt; +}; +static void +mysql_stmt_free_result_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_stmt_free_result, + (parms->stmt), + parms->stmt->mysql, + my_bool, + r_my_bool) +} +int STDCALL +mysql_stmt_free_result_start(my_bool *ret, MYSQL_STMT *stmt) +{ +MK_ASYNC_START_BODY( + mysql_stmt_free_result, + stmt->mysql, + { + WIN_SET_NONBLOCKING(stmt->mysql) + parms.stmt= stmt; + }, + TRUE, + r_my_bool, + /* If stmt->mysql==NULL then we will not block so can call directly. */ + if (!stmt->mysql) + { + *ret= mysql_stmt_free_result(stmt); + return 0; + }) +} +int STDCALL +mysql_stmt_free_result_cont(my_bool *ret, MYSQL_STMT *stmt, int ready_status) +{ +MK_ASYNC_CONT_BODY( + stmt->mysql, + TRUE, + r_my_bool) +} + +/* Structure used to pass parameters from mysql_stmt_send_long_data_start(). */ +struct mysql_stmt_send_long_data_params { + MYSQL_STMT *stmt; + unsigned int param_number; + const char *data; + unsigned long length; +}; +static void +mysql_stmt_send_long_data_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_stmt_send_long_data, + (parms->stmt, parms->param_number, parms->data, parms->length), + parms->stmt->mysql, + my_bool, + r_my_bool) +} +int STDCALL +mysql_stmt_send_long_data_start(my_bool *ret, MYSQL_STMT *stmt, + unsigned int param_number, + const char *data, unsigned long length) +{ +MK_ASYNC_START_BODY( + mysql_stmt_send_long_data, + stmt->mysql, + { + WIN_SET_NONBLOCKING(stmt->mysql) + parms.stmt= stmt; + parms.param_number= param_number; + parms.data= data; + parms.length= length; + }, + TRUE, + r_my_bool, + /* If stmt->mysql==NULL then we will not block so can call directly. */ + if (!stmt->mysql) + { + *ret= mysql_stmt_send_long_data(stmt, param_number, data, length); + return 0; + }) +} +int STDCALL +mysql_stmt_send_long_data_cont(my_bool *ret, MYSQL_STMT *stmt, int ready_status) +{ +MK_ASYNC_CONT_BODY( + stmt->mysql, + TRUE, + r_my_bool) +} + +/* Structure used to pass parameters from mysql_commit_start(). */ +struct mysql_commit_params { + MYSQL *mysql; +}; +static void +mysql_commit_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_commit, + (parms->mysql), + parms->mysql, + my_bool, + r_my_bool) +} +int STDCALL +mysql_commit_start(my_bool *ret, MYSQL *mysql) +{ +MK_ASYNC_START_BODY( + mysql_commit, + mysql, + { + WIN_SET_NONBLOCKING(mysql) + parms.mysql= mysql; + }, + TRUE, + r_my_bool, + /* Nothing */) +} +int STDCALL +mysql_commit_cont(my_bool *ret, MYSQL *mysql, int ready_status) +{ +MK_ASYNC_CONT_BODY( + mysql, + TRUE, + r_my_bool) +} + +/* Structure used to pass parameters from mysql_rollback_start(). */ +struct mysql_rollback_params { + MYSQL *mysql; +}; +static void +mysql_rollback_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_rollback, + (parms->mysql), + parms->mysql, + my_bool, + r_my_bool) +} +int STDCALL +mysql_rollback_start(my_bool *ret, MYSQL *mysql) +{ +MK_ASYNC_START_BODY( + mysql_rollback, + mysql, + { + WIN_SET_NONBLOCKING(mysql) + parms.mysql= mysql; + }, + TRUE, + r_my_bool, + /* Nothing */) +} +int STDCALL +mysql_rollback_cont(my_bool *ret, MYSQL *mysql, int ready_status) +{ +MK_ASYNC_CONT_BODY( + mysql, + TRUE, + r_my_bool) +} + +/* Structure used to pass parameters from mysql_autocommit_start(). */ +struct mysql_autocommit_params { + MYSQL *mysql; + my_bool auto_mode; +}; +static void +mysql_autocommit_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_autocommit, + (parms->mysql, parms->auto_mode), + parms->mysql, + my_bool, + r_my_bool) +} +int STDCALL +mysql_autocommit_start(my_bool *ret, MYSQL *mysql, my_bool auto_mode) +{ +MK_ASYNC_START_BODY( + mysql_autocommit, + mysql, + { + WIN_SET_NONBLOCKING(mysql) + parms.mysql= mysql; + parms.auto_mode= auto_mode; + }, + TRUE, + r_my_bool, + /* Nothing */) +} +int STDCALL +mysql_autocommit_cont(my_bool *ret, MYSQL *mysql, int ready_status) +{ +MK_ASYNC_CONT_BODY( + mysql, + TRUE, + r_my_bool) +} + +/* Structure used to pass parameters from mysql_next_result_start(). */ +struct mysql_next_result_params { + MYSQL *mysql; +}; +static void +mysql_next_result_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_next_result, + (parms->mysql), + parms->mysql, + int, + r_int) +} +int STDCALL +mysql_next_result_start(int *ret, MYSQL *mysql) +{ +MK_ASYNC_START_BODY( + mysql_next_result, + mysql, + { + WIN_SET_NONBLOCKING(mysql) + parms.mysql= mysql; + }, + 1, + r_int, + /* Nothing */) +} +int STDCALL +mysql_next_result_cont(int *ret, MYSQL *mysql, int ready_status) +{ +MK_ASYNC_CONT_BODY( + mysql, + 1, + r_int) +} + +/* Structure used to pass parameters from mysql_stmt_next_result_start(). */ +struct mysql_stmt_next_result_params { + MYSQL_STMT *stmt; +}; +static void +mysql_stmt_next_result_start_internal(void *d) +{ +MK_ASYNC_INTERNAL_BODY( + mysql_stmt_next_result, + (parms->stmt), + parms->stmt->mysql, + int, + r_int) +} +int STDCALL +mysql_stmt_next_result_start(int *ret, MYSQL_STMT *stmt) +{ +MK_ASYNC_START_BODY( + mysql_stmt_next_result, + stmt->mysql, + { + WIN_SET_NONBLOCKING(stmt->mysql) + parms.stmt= stmt; + }, + 1, + r_int, + /* Nothing */) +} +int STDCALL +mysql_stmt_next_result_cont(int *ret, MYSQL_STMT *stmt, int ready_status) +{ +MK_ASYNC_CONT_BODY( + stmt->mysql, + 1, + r_int) +} +#endif + + +/* + The following functions are deprecated, and so have no non-blocking version: + + mysql_connect + mysql_create_db + mysql_drop_db +*/ + +/* + The following functions can newer block, and so do not have special + non-blocking versions: + + mysql_num_rows() + mysql_num_fields() + mysql_eof() + mysql_fetch_field_direct() + mysql_fetch_fields() + mysql_row_tell() + mysql_field_tell() + mysql_field_count() + mysql_affected_rows() + mysql_insert_id() + mysql_errno() + mysql_error() + mysql_sqlstate() + mysql_warning_count() + mysql_info() + mysql_thread_id() + mysql_character_set_name() + mysql_init() + mysql_ssl_set() + mysql_get_ssl_cipher() + mysql_use_result() + mysql_get_character_set_info() + mysql_set_local_infile_handler() + mysql_set_local_infile_default() + mysql_get_server_info() + mysql_get_server_name() + mysql_get_client_info() + mysql_get_client_version() + mysql_get_host_info() + mysql_get_server_version() + mysql_get_proto_info() + mysql_options() + mysql_data_seek() + mysql_row_seek() + mysql_field_seek() + mysql_fetch_lengths() + mysql_fetch_field() + mysql_escape_string() + mysql_hex_string() + mysql_real_escape_string() + mysql_debug() + myodbc_remove_escape() + mysql_thread_safe() + mysql_embedded() + mariadb_connection() + mysql_stmt_init() + mysql_stmt_fetch_column() + mysql_stmt_param_count() + mysql_stmt_attr_set() + mysql_stmt_attr_get() + mysql_stmt_bind_param() + mysql_stmt_bind_result() + mysql_stmt_result_metadata() + mysql_stmt_param_metadata() + mysql_stmt_errno() + mysql_stmt_error() + mysql_stmt_sqlstate() + mysql_stmt_row_seek() + mysql_stmt_row_tell() + mysql_stmt_data_seek() + mysql_stmt_num_rows() + mysql_stmt_affected_rows() + mysql_stmt_insert_id() + mysql_stmt_field_count() + mysql_more_results() + mysql_get_socket() + mysql_get_timeout_value() +*/ diff --git a/sql-common/pack.c b/sql-common/pack.c new file mode 100644 index 00000000..de821f08 --- /dev/null +++ b/sql-common/pack.c @@ -0,0 +1,210 @@ +/* Copyright (c) 2000-2003, 2007 MySQL AB + Use is subject to license terms + + 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-1335 USA */ + +#include <my_global.h> +#include <mysql_com.h> +#include <mysql.h> + +/* Get the length of next field. Change parameter to point at fieldstart */ +ulong net_field_length(uchar **packet) +{ + reg1 uchar *pos= (uchar *)*packet; + if (*pos < 251) + { + (*packet)++; + return (ulong) *pos; + } + if (*pos == 251) + { + (*packet)++; + return NULL_LENGTH; + } + if (*pos == 252) + { + (*packet)+=3; + return (ulong) uint2korr(pos+1); + } + if (*pos == 253) + { + (*packet)+=4; + return (ulong) uint3korr(pos+1); + } + (*packet)+=9; /* Must be 254 when here */ + return (ulong) uint4korr(pos+1); +} + +/* The same as above but returns longlong */ +my_ulonglong net_field_length_ll(uchar **packet) +{ + uchar *pos= *packet; + if (*pos < 251) + { + (*packet)++; + return (my_ulonglong) *pos; + } + if (*pos == 251) + { + (*packet)++; + return (my_ulonglong) NULL_LENGTH; + } + if (*pos == 252) + { + (*packet)+=3; + return (my_ulonglong) uint2korr(pos+1); + } + if (*pos == 253) + { + (*packet)+=4; + return (my_ulonglong) uint3korr(pos+1); + } + DBUG_ASSERT(*pos == 254); + (*packet)+=9; /* Must be 254 when here */ + return (my_ulonglong) uint8korr(pos+1); +} + +my_ulonglong safe_net_field_length_ll(uchar **packet, size_t packet_len) +{ + uchar *pos= *packet; + if (packet_len < 1) + goto err; + if (*pos < 251) + { + (*packet)++; + return (my_ulonglong) *pos; + } + if (*pos == 251) + { + (*packet)++; + return (my_ulonglong) NULL_LENGTH; + } + if (*pos == 252) + { + if (packet_len < 3) + goto err; + (*packet)+=3; + return (my_ulonglong) uint2korr(pos+1); + } + if (*pos == 253) + { + if (packet_len < 4) + goto err; + (*packet)+=4; + return (my_ulonglong) uint3korr(pos+1); + } + if (packet_len < 9 || *pos != 254) + goto err; + (*packet)+=9; + return (my_ulonglong) uint8korr(pos+1); +err: + *packet = NULL; + return 0; +} + +/* + Store an integer with simple packing into a output package + + SYNOPSIS + net_store_length() + packet Store the packed integer here + length integers to store + + NOTES + This is mostly used to store lengths of strings. + + RETURN + Position in 'packet' after the packed length +*/ + +uchar *net_store_length(uchar *packet, ulonglong length) +{ + if (length < 251) + { + *packet= (uchar) length; + return packet+1; + } + /* 251 is reserved for NULL */ + if (length < 65536) + { + *packet++=252; + int2store(packet, (uint) length); + return packet+2; + } + if (length < 16777216) + { + *packet++=253; + int3store(packet, (ulong) length); + return packet+3; + } + *packet++=254; + int8store(packet,length); + return packet+8; +} + +uchar *safe_net_store_length(uchar *packet, size_t packet_len, ulonglong length) +{ + if (length < 251) + { + if (packet_len < 1) + return NULL; + *packet= (uchar) length; + return packet+1; + } + /* 251 is reserved for NULL */ + if (length < 65536) + { + if (packet_len < 3) + return NULL; + *packet++=252; + int2store(packet, (uint) length); + return packet+2; + } + if (length < 16777216) + { + if (packet_len < 4) + return NULL; + *packet++=253; + int3store(packet, (ulong) length); + return packet+3; + } + if (packet_len < 9) + return NULL; + *packet++=254; + int8store(packet,length); + return packet+8; +} + + +/** + The length of space required to store the resulting length-encoded integer + for the given number. This function can be used at places where one needs to + dynamically allocate the buffer for a given number to be stored as length- + encoded integer. + + @param num [IN] the input number + + @return length of buffer needed to store this number [1, 3, 4, 9]. +*/ + +uint net_length_size(ulonglong num) +{ + if (num < (ulonglong) 251LL) + return 1; + if (num < (ulonglong) 65536LL) + return 3; + if (num < (ulonglong) 16777216LL) + return 4; + return 9; +} |