1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
|
// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
//
// MySQL Connector/NET is licensed under the terms of the GPLv2
// <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
// MySQL Connectors. There are special exceptions to the terms and
// conditions of the GPLv2 as it is applied to this software, see the
// FLOSS License Exception
// <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using MySql.Data.Common;
using MySql.Data.Types;
using System.Security.Cryptography.X509Certificates;
using MySql.Data.MySqlClient.Properties;
using System.Text;
#if !CF
using System.Net.Security;
using System.Security.Authentication;
using System.Globalization;
#endif
namespace MySql.Data.MySqlClient
{
/// <summary>
/// Summary description for Driver.
/// </summary>
internal class NativeDriver : IDriver
{
private DBVersion version;
private int threadId;
protected String encryptionSeed;
protected ServerStatusFlags serverStatus;
protected MySqlStream stream;
protected Stream baseStream;
private BitArray nullMap;
private MySqlPacket packet;
private ClientFlags connectionFlags;
private Driver owner;
private int warnings;
// Windows authentication method string, used by the protocol.
// Also known as "client plugin name".
const string AuthenticationWindowsPlugin = "authentication_windows_client";
// Predefined username for IntegratedSecurity
const string AuthenticationWindowsUser = "auth_windows";
public NativeDriver(Driver owner)
{
this.owner = owner;
threadId = -1;
}
public ClientFlags Flags
{
get { return connectionFlags; }
}
public int ThreadId
{
get { return threadId; }
}
public DBVersion Version
{
get { return version; }
}
public ServerStatusFlags ServerStatus
{
get { return serverStatus; }
}
public int WarningCount
{
get { return warnings; }
}
public MySqlPacket Packet
{
get { return packet; }
}
private MySqlConnectionStringBuilder Settings
{
get { return owner.Settings; }
}
private Encoding Encoding
{
get { return owner.Encoding; }
}
private void HandleException(MySqlException ex)
{
if (ex.IsFatal)
owner.Close();
}
private void ReadOk(bool read)
{
try
{
if (read)
packet = stream.ReadPacket();
byte marker = (byte) packet.ReadByte();
if (marker != 0)
{
throw new MySqlException("Out of sync with server", true, null);
}
packet.ReadFieldLength(); /* affected rows */
packet.ReadFieldLength(); /* last insert id */
if (packet.HasMoreData)
{
serverStatus = (ServerStatusFlags) packet.ReadInteger(2);
packet.ReadInteger(2); /* warning count */
if (packet.HasMoreData)
{
packet.ReadLenString(); /* message */
}
}
}
catch (MySqlException ex)
{
HandleException(ex);
throw;
}
}
/// <summary>
/// Sets the current database for the this connection
/// </summary>
/// <param name="dbName"></param>
public void SetDatabase(string dbName)
{
byte[] dbNameBytes = Encoding.GetBytes(dbName);
packet.Clear();
packet.WriteByte((byte)DBCmd.INIT_DB);
packet.Write(dbNameBytes);
ExecutePacket(packet);
ReadOk(true);
}
public void Configure()
{
stream.MaxPacketSize = (ulong)owner.MaxPacketSize;
stream.Encoding = Encoding;
}
public void Open()
{
// connect to one of our specified hosts
try
{
#if !CF
if (Settings.ConnectionProtocol == MySqlConnectionProtocol.SharedMemory)
{
SharedMemoryStream str = new SharedMemoryStream(Settings.SharedMemoryName);
str.Open(Settings.ConnectionTimeout);
baseStream = str;
}
else
{
#endif
string pipeName = Settings.PipeName;
if (Settings.ConnectionProtocol != MySqlConnectionProtocol.NamedPipe)
pipeName = null;
StreamCreator sc = new StreamCreator(Settings.Server, Settings.Port, pipeName,
Settings.Keepalive);
baseStream = sc.GetStream(Settings.ConnectionTimeout);
#if !CF
}
#endif
}
catch (Exception ex)
{
throw new MySqlException(Resources.UnableToConnectToHost,
(int) MySqlErrorCode.UnableToConnectToHost, ex);
}
if (baseStream == null)
throw new MySqlException(Resources.UnableToConnectToHost,
(int)MySqlErrorCode.UnableToConnectToHost);
int maxSinglePacket = 255*255*255;
stream = new MySqlStream(baseStream, Encoding, false);
stream.ResetTimeout((int)Settings.ConnectionTimeout*1000);
// read off the welcome packet and parse out it's values
packet = stream.ReadPacket();
int protocol = packet.ReadByte();
string versionString = packet.ReadString();
version = DBVersion.Parse(versionString);
if (!version.isAtLeast(5, 0, 0))
throw new NotSupportedException(Resources.ServerTooOld);
threadId = packet.ReadInteger(4);
encryptionSeed = packet.ReadString();
maxSinglePacket = (256*256*256) - 1;
// read in Server capabilities if they are provided
ClientFlags serverCaps = 0;
if (packet.HasMoreData)
serverCaps = (ClientFlags) packet.ReadInteger(2);
/* New protocol with 16 bytes to describe server characteristics */
owner.ConnectionCharSetIndex = (int)packet.ReadByte();
serverStatus = (ServerStatusFlags) packet.ReadInteger(2);
// Since 5.5, high bits of server caps are stored after status.
// Previously, it was part of reserved always 0x00 13-byte filler.
uint serverCapsHigh = (uint)packet.ReadInteger(2);
serverCaps |= (ClientFlags)(serverCapsHigh << 16);
packet.Position += 11;
string seedPart2 = packet.ReadString();
encryptionSeed += seedPart2;
string authenticationMethod = "";
if ((serverCaps & ClientFlags.PLUGIN_AUTH)!=0)
{
authenticationMethod = packet.ReadString();
}
// based on our settings, set our connection flags
SetConnectionFlags(serverCaps);
packet.Clear();
packet.WriteInteger((int) connectionFlags, 4);
#if !CF
if ((serverCaps & ClientFlags.SSL) ==0)
{
if ((Settings.SslMode != MySqlSslMode.None)
&& (Settings.SslMode != MySqlSslMode.Preferred))
{
// Client requires SSL connections.
string message = String.Format(Resources.NoServerSSLSupport,
Settings.Server);
throw new MySqlException(message);
}
}
else if (Settings.SslMode != MySqlSslMode.None)
{
stream.SendPacket(packet);
StartSSL();
packet.Clear();
packet.WriteInteger((int) connectionFlags, 4);
}
#endif
packet.WriteInteger(maxSinglePacket, 4);
packet.WriteByte(8);
packet.Write(new byte[23]);
Authenticate(false);
// if we are using compression, then we use our CompressedStream class
// to hide the ugliness of managing the compression
if ((connectionFlags & ClientFlags.COMPRESS) != 0)
stream = new MySqlStream(baseStream, Encoding, true);
// give our stream the server version we are connected to.
// We may have some fields that are read differently based
// on the version of the server we are connected to.
packet.Version = version;
stream.MaxBlockSize = maxSinglePacket;
}
#if !CF
#region SSL
/// <summary>
/// Retrieve client SSL certificates. Dependent on connection string
/// settings we use either file or store based certificates.
/// </summary>
private X509CertificateCollection GetClientCertificates()
{
X509CertificateCollection certs = new X509CertificateCollection();
// Check for file-based certificate
if (Settings.CertificateFile != null)
{
if (!Version.isAtLeast(5, 1, 0))
throw new MySqlException(Properties.Resources.FileBasedCertificateNotSupported);
X509Certificate2 clientCert = new X509Certificate2(Settings.CertificateFile,
Settings.CertificatePassword);
certs.Add(clientCert);
return certs;
}
if (Settings.CertificateStoreLocation == MySqlCertificateStoreLocation.None)
return certs;
StoreLocation location =
(Settings.CertificateStoreLocation == MySqlCertificateStoreLocation.CurrentUser) ?
StoreLocation.CurrentUser : StoreLocation.LocalMachine;
// Check for store-based certificate
X509Store store = new X509Store(StoreName.My, location);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
if (Settings.CertificateThumbprint == null)
{
// Return all certificates from the store.
certs.AddRange(store.Certificates);
return certs;
}
// Find certificate with given thumbprint
certs.AddRange(store.Certificates.Find(X509FindType.FindByThumbprint,
Settings.CertificateThumbprint, true));
if (certs.Count == 0)
{
throw new MySqlException("Certificate with Thumbprint " +
Settings.CertificateThumbprint + " not found");
}
return certs;
}
private void StartSSL()
{
RemoteCertificateValidationCallback sslValidateCallback =
new RemoteCertificateValidationCallback(ServerCheckValidation);
SslStream ss = new SslStream(baseStream, true, sslValidateCallback, null);
X509CertificateCollection certs = GetClientCertificates();
ss.AuthenticateAsClient(Settings.Server, certs, SslProtocols.Default, false);
baseStream = ss;
stream = new MySqlStream(ss, Encoding, false);
stream.SequenceByte = 2;
}
private bool ServerCheckValidation(object sender, X509Certificate certificate,
X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
if (Settings.SslMode == MySqlSslMode.Preferred ||
Settings.SslMode == MySqlSslMode.Required)
{
//Tolerate all certificate errors.
return true;
}
if (Settings.SslMode == MySqlSslMode.VerifyCA &&
sslPolicyErrors == SslPolicyErrors.RemoteCertificateNameMismatch)
{
// Tolerate name mismatch in certificate, if full validation is not requested.
return true;
}
return false;
}
#endregion
#endif
#region Authentication
/// <summary>
/// Return the appropriate set of connection flags for our
/// server capabilities and our user requested options.
/// </summary>
private void SetConnectionFlags(ClientFlags serverCaps)
{
// allow load data local infile
ClientFlags flags = ClientFlags.LOCAL_FILES;
if (!Settings.UseAffectedRows)
flags |= ClientFlags.FOUND_ROWS;
flags |= ClientFlags.PROTOCOL_41;
// Need this to get server status values
flags |= ClientFlags.TRANSACTIONS;
// user allows/disallows batch statements
if (Settings.AllowBatch)
flags |= ClientFlags.MULTI_STATEMENTS;
// We always allow multiple result sets
flags |= ClientFlags.MULTI_RESULTS;
// if the server allows it, tell it that we want long column info
if ((serverCaps & ClientFlags.LONG_FLAG) != 0)
flags |= ClientFlags.LONG_FLAG;
// if the server supports it and it was requested, then turn on compression
if ((serverCaps & ClientFlags.COMPRESS) != 0 && Settings.UseCompression)
flags |= ClientFlags.COMPRESS;
flags |= ClientFlags.LONG_PASSWORD; // for long passwords
// did the user request an interactive session?
if (Settings.InteractiveSession)
flags |= ClientFlags.INTERACTIVE;
// if the server allows it and a database was specified, then indicate
// that we will connect with a database name
if ((serverCaps & ClientFlags.CONNECT_WITH_DB) != 0 &&
Settings.Database != null && Settings.Database.Length > 0)
flags |= ClientFlags.CONNECT_WITH_DB;
// if the server is requesting a secure connection, then we oblige
if ((serverCaps & ClientFlags.SECURE_CONNECTION) != 0)
flags |= ClientFlags.SECURE_CONNECTION;
#if !CF
// if the server is capable of SSL and the user is requesting SSL
if ((serverCaps & ClientFlags.SSL) != 0 && Settings.SslMode != MySqlSslMode.None)
flags |= ClientFlags.SSL;
#endif
// if the server supports output parameters, then we do too
if ((serverCaps & ClientFlags.PS_MULTI_RESULTS) != 0)
flags |= ClientFlags.PS_MULTI_RESULTS;
if(Settings.IntegratedSecurity)
{
if ((serverCaps & ClientFlags.PLUGIN_AUTH) != 0)
flags |= ClientFlags.PLUGIN_AUTH;
}
connectionFlags = flags;
}
private void AuthenticateSSPI()
{
string targetName = ""; // target name (required by Kerberos)
// First packet sent by server should include target name (for
// Kerberos) as UTF8 string. It might however be prepended by junk
// at the start of the string (0xfe"authentication_win_client"\0,
// see Bug#57442), this junk will be ignored. Target name can also
// be an empty string if server is not running in a domain environment,
// in this case authentication will fallback to NTLM.
// Note that 0xfe byte at the start could also indicate that windows
// authentication is not supported by srver, we throw an exception
// if this happens.
packet = stream.ReadPacket();
byte b = packet.ReadByte();
if (b == 0xfe)
{
string authMethod = packet.ReadString();
if (authMethod.Equals(AuthenticationWindowsPlugin))
{
targetName = packet.ReadString(Encoding.UTF8);
}
else
{
// User has requested Windows authentication, bail out.
throw new MySqlException("unexpected authentication method " +
authMethod);
}
}
else
{
targetName = Encoding.UTF8.GetString(packet.Buffer, 0, packet.Buffer.Length);
}
// Do SSPI authentication handshake
SSPI sspi = new SSPI(targetName, stream.BaseStream, stream.SequenceByte);
sspi.AuthenticateClient();
// read ok packet.
packet = stream.ReadPacket();
ReadOk(false);
}
/// <summary>
/// Perform an authentication against a 4.1.1 server
/// <param name="reset">
/// True, if this function is called as part of CHANGE_USER request
/// (connection reset)
/// False, for first-time logon
/// </param>
/// </summary>
private void AuthenticateNew(bool reset)
{
if ((connectionFlags & ClientFlags.SECURE_CONNECTION) == 0)
AuthenticateOld();
packet.Write(Crypt.Get411Password(Settings.Password, encryptionSeed));
if ((connectionFlags & ClientFlags.CONNECT_WITH_DB) != 0 && Settings.Database != null)
packet.WriteString(Settings.Database);
else
packet.WriteString(""); // Add a null termination to the string.
if (Settings.IntegratedSecurity)
{
// Append authentication method after the database name in the
// handshake authentication packet.If we're sending CHANGE_USER
// also write charset number after database name prior to plugin name
if (reset)
{
packet.WriteInteger(8, 2); // Charset number
}
packet.WriteString(AuthenticationWindowsPlugin);
stream.SendPacket(packet);
AuthenticateSSPI();
return;
}
else
{
stream.SendPacket(packet);
}
// this result means the server wants us to send the password using
// old encryption
packet = stream.ReadPacket();
if (packet.IsLastPacket)
{
packet.Clear();
packet.WriteString(Crypt.EncryptPassword(
Settings.Password, encryptionSeed.Substring(0, 8), true));
stream.SendPacket(packet);
ReadOk(true);
}
ReadOk(false);
}
private void AuthenticateOld()
{
packet.WriteString(Crypt.EncryptPassword(
Settings.Password, encryptionSeed, true));
if ((connectionFlags & ClientFlags.CONNECT_WITH_DB) != 0 && Settings.Database != null)
packet.WriteString(Settings.Database);
stream.SendPacket(packet);
ReadOk(true);
}
public void Authenticate(bool reset)
{
if (Settings.IntegratedSecurity)
{
packet.WriteString(AuthenticationWindowsUser);
}
else
{
// write the user id to the auth packet
packet.WriteString(Settings.UserID);
}
AuthenticateNew(reset);
}
#endregion
public void Reset()
{
warnings = 0;
stream.Encoding = this.Encoding;
stream.SequenceByte = 0;
packet.Clear();
packet.WriteByte((byte)DBCmd.CHANGE_USER);
Authenticate(true);
}
/// <summary>
/// Query is the method that is called to send all queries to the server
/// </summary>
public void SendQuery(MySqlPacket queryPacket)
{
warnings = 0;
queryPacket.Buffer[4] = (byte)DBCmd.QUERY;
ExecutePacket(queryPacket);
// the server will respond in one of several ways with the first byte indicating
// the type of response.
// 0 == ok packet. This indicates non-select queries
// 0xff == error packet. This is handled in stream.OpenPacket
// > 0 = number of columns in select query
// We don't actually read the result here since a single query can generate
// multiple resultsets and we don't want to duplicate code. See ReadResult
// Instead we set our internal server status flag to indicate that we have a query waiting.
// This flag will be maintained by ReadResult
serverStatus |= ServerStatusFlags.AnotherQuery;
}
public void Close(bool isOpen)
{
try
{
if (isOpen)
{
try
{
packet.Clear();
packet.WriteByte((byte)DBCmd.QUIT);
ExecutePacket(packet);
}
catch (Exception)
{
// Eat exception here. We should try to closing
// the stream anyway.
}
}
if (stream != null)
stream.Close();
stream = null;
}
catch (Exception)
{
// we are just going to eat any exceptions
// generated here
}
}
public bool Ping()
{
try
{
packet.Clear();
packet.WriteByte((byte)DBCmd.PING);
ExecutePacket(packet);
ReadOk(true);
return true;
}
catch (Exception)
{
return false;
}
}
public int GetResult(ref int affectedRow, ref int insertedId)
{
try
{
packet = stream.ReadPacket();
}
catch (TimeoutException)
{
// Do not reset serverStatus, allow to reenter, e.g when
// ResultSet is closed.
throw;
}
catch (Exception)
{
serverStatus = 0;
throw;
}
int fieldCount = (int)packet.ReadFieldLength();
if (-1 == fieldCount)
{
string filename = packet.ReadString();
SendFileToServer(filename);
return GetResult(ref affectedRow, ref insertedId);
}
else if (fieldCount == 0)
{
// the code to read last packet will set these server status vars
// again if necessary.
serverStatus &= ~(ServerStatusFlags.AnotherQuery |
ServerStatusFlags.MoreResults);
affectedRow = (int)packet.ReadFieldLength();
insertedId = (int)packet.ReadFieldLength();
serverStatus = (ServerStatusFlags)packet.ReadInteger(2);
warnings += packet.ReadInteger(2);
if (packet.HasMoreData)
{
packet.ReadLenString(); //TODO: server message
}
}
return fieldCount;
}
/// <summary>
/// Sends the specified file to the server.
/// This supports the LOAD DATA LOCAL INFILE
/// </summary>
/// <param name="filename"></param>
private void SendFileToServer(string filename)
{
byte[] buffer = new byte[8196];
long len = 0;
try
{
using (FileStream fs = new FileStream(filename, FileMode.Open,
FileAccess.Read))
{
len = fs.Length;
while (len > 0)
{
int count = fs.Read(buffer, 4, (int)(len > 8192 ? 8192 : len));
stream.SendEntirePacketDirectly(buffer, count);
len -= count;
}
stream.SendEntirePacketDirectly(buffer, 0);
}
}
catch (Exception ex)
{
throw new MySqlException("Error during LOAD DATA LOCAL INFILE", ex);
}
}
private void ReadNullMap(int fieldCount)
{
// if we are binary, then we need to load in our null bitmap
nullMap = null;
byte[] nullMapBytes = new byte[(fieldCount + 9)/8];
packet.ReadByte();
packet.Read(nullMapBytes, 0, nullMapBytes.Length);
nullMap = new BitArray(nullMapBytes);
}
public IMySqlValue ReadColumnValue(int index, MySqlField field, IMySqlValue valObject)
{
long length = -1;
bool isNull;
if (nullMap != null)
isNull = nullMap[index + 2];
else
{
length = packet.ReadFieldLength();
isNull = length == -1;
}
packet.Encoding = field.Encoding;
packet.Version = version;
return valObject.ReadValue(packet, length, isNull);
}
public void SkipColumnValue(IMySqlValue valObject)
{
int length = -1;
if (nullMap == null)
{
length = (int)packet.ReadFieldLength();
if (length == -1) return;
}
if (length > -1)
packet.Position += length;
else
valObject.SkipValue(packet);
}
public void GetColumnsData(MySqlField[] columns)
{
for (int i = 0; i < columns.Length; i++)
GetColumnData(columns[i]);
ReadEOF();
}
private void GetColumnData(MySqlField field)
{
stream.Encoding = Encoding;
packet = stream.ReadPacket();
field.Encoding = Encoding;
field.CatalogName = packet.ReadLenString();
field.DatabaseName = packet.ReadLenString();
field.TableName = packet.ReadLenString();
field.RealTableName = packet.ReadLenString();
field.ColumnName = packet.ReadLenString();
field.OriginalColumnName = packet.ReadLenString();
packet.ReadByte();
field.CharacterSetIndex = packet.ReadInteger(2);
field.ColumnLength = packet.ReadInteger(4);
MySqlDbType type = (MySqlDbType)packet.ReadByte();
ColumnFlags colFlags;
if ((connectionFlags & ClientFlags.LONG_FLAG) != 0)
colFlags = (ColumnFlags)packet.ReadInteger(2);
else
colFlags = (ColumnFlags)packet.ReadByte();
field.Scale = (byte)packet.ReadByte();
if (packet.HasMoreData)
{
packet.ReadInteger(2); // reserved
}
if (type == MySqlDbType.Decimal || type == MySqlDbType.NewDecimal)
{
field.Precision = (byte)(field.ColumnLength - 2);
if ((colFlags & ColumnFlags.UNSIGNED) != 0)
field.Precision++;
}
field.SetTypeAndFlags(type, colFlags);
}
private void ExecutePacket(MySqlPacket packetToExecute)
{
try
{
warnings = 0;
stream.SequenceByte = 0;
stream.SendPacket(packetToExecute);
}
catch (MySqlException ex)
{
HandleException(ex);
throw;
}
}
public void ExecuteStatement(MySqlPacket packetToExecute)
{
warnings = 0;
packetToExecute.Buffer[4] = (byte)DBCmd.EXECUTE;
ExecutePacket(packetToExecute);
serverStatus |= ServerStatusFlags.AnotherQuery;
}
private void CheckEOF()
{
if (!packet.IsLastPacket)
throw new MySqlException("Expected end of data packet");
packet.ReadByte(); // read off the 254
if (packet.HasMoreData)
{
warnings += packet.ReadInteger(2);
serverStatus = (ServerStatusFlags)packet.ReadInteger(2);
// if we are at the end of this cursor based resultset, then we remove
// the last row sent status flag so our next fetch doesn't abort early
// and we remove this command result from our list of active CommandResult objects.
// if ((serverStatus & ServerStatusFlags.LastRowSent) != 0)
// {
// serverStatus &= ~ServerStatusFlags.LastRowSent;
// commandResults.Remove(lastCommandResult);
// }
}
}
private void ReadEOF()
{
packet = stream.ReadPacket();
CheckEOF();
}
public int PrepareStatement(string sql, ref MySqlField[] parameters)
{
//TODO: check this
//ClearFetchedRow();
packet.Length = sql.Length*4 + 5;
byte[] buffer = packet.Buffer;
int len = Encoding.GetBytes(sql, 0, sql.Length, packet.Buffer, 5);
packet.Position = len + 5;
buffer[4] = (byte)DBCmd.PREPARE;
ExecutePacket(packet);
packet = stream.ReadPacket();
int marker = packet.ReadByte();
if (marker != 0)
throw new MySqlException("Expected prepared statement marker");
int statementId = packet.ReadInteger(4);
int numCols = packet.ReadInteger(2);
int numParams = packet.ReadInteger(2);
//TODO: find out what this is needed for
packet.ReadInteger(3);
if (numParams > 0)
{
parameters = owner.GetColumns(numParams);
// we set the encoding for each parameter back to our connection encoding
// since we can't trust what is coming back from the server
for (int i = 0; i < parameters.Length; i++)
parameters[i].Encoding = Encoding;
}
if (numCols > 0)
{
while (numCols-- > 0)
{
packet = stream.ReadPacket();
//TODO: handle streaming packets
}
ReadEOF();
}
return statementId;
}
// private void ClearFetchedRow()
// {
// if (lastCommandResult == 0) return;
//TODO
/* CommandResult result = (CommandResult)commandResults[lastCommandResult];
result.ReadRemainingColumns();
stream.OpenPacket();
if (! stream.IsLastPacket)
throw new MySqlException("Cursor reading out of sync");
ReadEOF(false);
lastCommandResult = 0;*/
// }
/// <summary>
/// FetchDataRow is the method that the data reader calls to see if there is another
/// row to fetch. In the non-prepared mode, it will simply read the next data packet.
/// In the prepared mode (statementId > 0), it will
/// </summary>
public bool FetchDataRow(int statementId, int columns)
{
/* ClearFetchedRow();
if (!commandResults.ContainsKey(statementId)) return false;
if ( (serverStatus & ServerStatusFlags.LastRowSent) != 0)
return false;
stream.StartPacket(9, true);
stream.WriteByte((byte)DBCmd.FETCH);
stream.WriteInteger(statementId, 4);
stream.WriteInteger(1, 4);
stream.Flush();
lastCommandResult = statementId;
*/
packet = stream.ReadPacket();
if (packet.IsLastPacket)
{
CheckEOF();
return false;
}
nullMap = null;
if (statementId > 0)
ReadNullMap(columns);
return true;
}
public void CloseStatement(int statementId)
{
packet.Clear();
packet.WriteByte((byte)DBCmd.CLOSE_STMT);
packet.WriteInteger((long)statementId, 4);
stream.SequenceByte = 0;
stream.SendPacket(packet);
}
/// <summary>
/// Execution timeout, in milliseconds. When the accumulated time for network IO exceeds this value
/// TimeoutException is thrown. This timeout needs to be reset for every new command
/// </summary>
///
public void ResetTimeout(int timeout)
{
if (stream != null)
stream.ResetTimeout(timeout);
}
}
}
|