示例#1
0
		void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length)
		{
			if (!(val is TimeSpan))
				throw new MySqlException("Only TimeSpan objects can be serialized by MySqlTimeSpan");

			TimeSpan ts = (TimeSpan)val;
			bool negative = ts.TotalMilliseconds < 0;
			ts = ts.Duration();

			if (binary)
			{
				packet.WriteByte(8);
				packet.WriteByte((byte)(negative ? 1 : 0));
				packet.WriteInteger(ts.Days, 4);
				packet.WriteByte((byte)ts.Hours);
				packet.WriteByte((byte)ts.Minutes);
				packet.WriteByte((byte)ts.Seconds);
			}
			else
			{
				String s = String.Format("'{0}{1} {2:00}:{3:00}:{4:00}.{5}'",
					negative ? "-" : "", ts.Days, ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds);

				packet.WriteStringNoNull(s);
			}
		}
示例#2
0
 public void WriteValue(MySqlPacket packet, bool binary, object value, int length)
 {
   ulong v = (value is UInt64) ? (UInt64)value : Convert.ToUInt64(value);
   if (binary)
     packet.WriteInteger((long)v, 8);
   else
     packet.WriteStringNoNull(v.ToString());
 }
示例#3
0
 void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length)
 {
   ulong v = (val is ulong) ? (ulong)val : Convert.ToUInt64(val);
   if (binary)
     packet.WriteInteger((long)v, 8);
   else
     packet.WriteStringNoNull(v.ToString());
 }
示例#4
0
 void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length)
 {
   var v = (val is Int64) ? (Int64)val : Convert.ToInt64(val);
   if (binary)
     packet.WriteInteger(v, 8);
   else
     packet.WriteStringNoNull(v.ToString());
 }
示例#5
0
 void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length)
 {
   int v = (val is Int32) ? (int)val : Convert.ToInt32(val);
   if (binary)
     packet.WriteInteger((long)v, 2);
   else
     packet.WriteStringNoNull(v.ToString());
 }
示例#6
0
		void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length)
		{
			byte v = (val is byte) ? (byte)val : Convert.ToByte(val);
			if (binary)
				packet.WriteByte(v);
			else
				packet.WriteStringNoNull(v.ToString());
		}
示例#7
0
 void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length)
 {
   var v = (val is double) ? (double)val : Convert.ToDouble(val);
   if (binary)
     packet.Write(BitConverter.GetBytes(v));
   else
     packet.WriteStringNoNull(v.ToString("R", CultureInfo.InvariantCulture));
 }
        public override void ExecuteStatement(MySqlPacket packetToExecute)
        {
            base.ExecuteStatement(packetToExecute);
            int pos = packetToExecute.Position;
            packetToExecute.Position = 1;
            int statementId = packetToExecute.ReadInteger(4);
            packetToExecute.Position = pos;

            MySqlTrace.TraceEvent(TraceEventType.Information, MySqlTraceEventType.StatementExecuted,
                Resources.TraceStatementExecuted, driverId, statementId, ThreadID);
        }
示例#9
0
        public MySqlStream(Encoding encoding)
        {
            // we have no idea what the real value is so we start off with the max value
              // The real value will be set in NativeDriver.Configure()
              maxPacketSize = ulong.MaxValue;

              // we default maxBlockSize to MaxValue since we will get the 'real' value in
              // the authentication handshake and we know that value will not exceed
              // true maxBlockSize prior to that.
              maxBlockSize = Int32.MaxValue;

              packet = new MySqlPacket(encoding);
        }
示例#10
0
    void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length)
    {
      string v = val.ToString();
      if (length > 0)
      {
        length = Math.Min(length, v.Length);
        v = v.Substring(0, length);
      }

      if (binary)
        packet.WriteLenString(v);
      else
        packet.WriteStringNoNull("'" + MySqlHelper.EscapeString(v) + "'");
    }
    public override void SendQuery(MySqlPacket p)
    {
      rowSizeInBytes = 0;
      string cmdText = Encoding.GetString(p.Buffer, 5, p.Length - 5);
      string normalized_query = null;

      if (cmdText.Length > 300)
      {
        QueryNormalizer normalizer = new QueryNormalizer();
        normalized_query = normalizer.Normalize(cmdText);
        cmdText = cmdText.Substring(0, 300);
      }

      base.SendQuery(p);

      MySqlTrace.TraceEvent(TraceEventType.Information, MySqlTraceEventType.QueryOpened,
          Resources.TraceQueryOpened, driverId, ThreadID, cmdText);
      if (normalized_query != null)
        MySqlTrace.TraceEvent(TraceEventType.Information, MySqlTraceEventType.QueryNormalized,
            Resources.TraceQueryNormalized, driverId, ThreadID, normalized_query);
    }
示例#12
0
 void IMySqlValue.SkipValue(MySqlPacket packet)
 {
   int len = packet.ReadByte();
   packet.Position += len;
 }
示例#13
0
    void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object value, int length)
    {
      MySqlDateTime dtValue;

      var valueAsString = value as string;

      if (value is DateTime)
        dtValue = new MySqlDateTime(type, (DateTime)value);
      else if (valueAsString != null)
        dtValue = Parse(valueAsString);
      else if (value is MySqlDateTime)
        dtValue = (MySqlDateTime)value;
      else
        throw new MySqlException("Unable to serialize date/time value.");

      if (!binary)
      {
        SerializeText(packet, dtValue);
        return;
      }

      if (dtValue.Millisecond > 0)
        packet.WriteByte(11);
      else
        packet.WriteByte(7);

      packet.WriteInteger(dtValue.Year, 2);
      packet.WriteByte((byte)dtValue.Month);
      packet.WriteByte((byte)dtValue.Day);
      if (type == MySqlDbType.Date)
      {
        packet.WriteByte(0);
        packet.WriteByte(0);
        packet.WriteByte(0);
      }
      else
      {
        packet.WriteByte((byte)dtValue.Hour);
        packet.WriteByte((byte)dtValue.Minute);
        packet.WriteByte((byte)dtValue.Second);
      }

      if (dtValue.Millisecond > 0)
      {
        long val = dtValue.Millisecond < 1000 ?  dtValue.Millisecond * 1000 : dtValue.Millisecond;
        for (var x = 0; x < 4; x++)
        {
          packet.WriteByte((byte)(val & 0xff));
          val >>= 8;
        }
      }
    }
        private static void EscapeByteArray(byte[] bytes, int length, MySqlPacket packet)
        {
            for (int x = 0; x < length; x++)
            {
                byte b = bytes[x];
                if (b == '\0')
                {
                    packet.WriteByte((byte)'\\');
                    packet.WriteByte((byte)'0');
                }

                else if (b == '\\' || b == '\'' || b == '\"')
                {
                    packet.WriteByte((byte)'\\');
                    packet.WriteByte(b);
                }
                else
                    packet.WriteByte(b);
            }
        }
 void IMySqlValue.SkipValue(MySqlPacket packet)
 {
     int len = packet.ReadFieldLength();
     packet.Position += len;
 }
        IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal)
        {
            if (nullVal)
                return new MySqlByte(true);

            if (length == -1)
                return new MySqlByte((sbyte)packet.ReadByte());
            else
            {
                string s = packet.ReadString(length);
                MySqlByte b = new MySqlByte(SByte.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture));
                b.TreatAsBoolean = TreatAsBoolean;
                return b;
            }
        }
    public virtual void Prepare()
    {
      // strip out names from parameter markers
      string text;
      List<string> parameter_names = PrepareCommandText(out text);

      // ask our connection to send the prepare command
      MySqlField[] paramList = null;
      statementId = Driver.PrepareStatement(text, ref paramList);

      // now we need to assign our field names since we stripped them out
      // for the prepare
      for (int i = 0; i < parameter_names.Count; i++)
      {
        //paramList[i].ColumnName = (string) parameter_names[i];
        string parameterName = (string)parameter_names[i];
        MySqlParameter p = Parameters.GetParameterFlexible(parameterName, false);
        if (p == null)
          throw new InvalidOperationException(
              String.Format(Resources.ParameterNotFoundDuringPrepare, parameterName));
        p.Encoding = paramList[i].Encoding;
        parametersToSend.Add(p);
      }

      // now prepare our null map
      int numNullBytes = 0;
      if (paramList != null && paramList.Length > 0)
      {
        nullMap = new BitArray(paramList.Length);
        numNullBytes = (nullMap.Count + 7) / 8;
      }

      packet = new MySqlPacket(Driver.Encoding);

      // write out some values that do not change run to run
      packet.WriteByte(0);
      packet.WriteInteger(statementId, 4);
      packet.WriteByte((byte)0); // flags; always 0 for 4.1
      packet.WriteInteger(1, 4); // interation count; 1 for 4.1
      nullMapPosition = packet.Position;
      packet.Position += numNullBytes;  // leave room for our null map
      packet.WriteByte(1); // rebound flag
      // write out the parameter types
      foreach (MySqlParameter p in parametersToSend)
        packet.WriteInteger(p.GetPSType(), 2);
      dataPosition = packet.Position;
    }
 void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length)
 {
   decimal v = (val is decimal) ? (decimal)val : Convert.ToDecimal(val);
   string valStr = v.ToString(CultureInfo.InvariantCulture);
   if (binary)
     packet.WriteLenString(valStr);
   else
     packet.WriteStringNoNull(valStr);
 }
示例#19
0
 internal MySqlPacket ReadPacket()
 {
     return(packet = stream.ReadPacket());
 }
示例#20
0
 internal void SendPacket(MySqlPacket p)
 {
     stream.SendPacket(p);
 }
示例#21
0
 private void ReadEOF()
 {
     packet = stream.ReadPacket();
     CheckEOF();
 }
示例#22
0
        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);
            packet.Position += 13;
            string seedPart2 = packet.ReadString();
            encryptionSeed += seedPart2;

            // 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();

            // 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;
        }
示例#23
0
 public virtual void ExecuteStatement(MySqlPacket packetToExecute)
 {
     handler.ExecuteStatement(packetToExecute);
 }
示例#24
0
        public void Open()
        {
            try
            {
                this.baseStream = StreamCreator.GetStream(this.Settings);
                if (this.Settings.IncludeSecurityAsserts)
                {
                    MySqlSecurityPermission.CreatePermissionSet(false).Assert();
                }
            }
            catch (SecurityException)
            {
                throw;
            }
            catch (Exception inner)
            {
                throw new MySqlException(Resources.UnableToConnectToHost, 1042, inner);
            }
            if (this.baseStream == null)
            {
                throw new MySqlException(Resources.UnableToConnectToHost, 1042);
            }
            this.stream = new MySqlStream(this.baseStream, this.Encoding, false);
            this.stream.ResetTimeout((int)(this.Settings.ConnectionTimeout * 1000u));
            this.packet = this.stream.ReadPacket();
            this.packet.ReadByte();
            string versionString = this.packet.ReadString();

            this.version = DBVersion.Parse(versionString);
            if (!this.version.isAtLeast(5, 0, 0))
            {
                throw new NotSupportedException(Resources.ServerTooOld);
            }
            this.threadId       = this.packet.ReadInteger(4);
            this.encryptionSeed = this.packet.ReadString();
            int         num         = 16777215;
            ClientFlags clientFlags = (ClientFlags)0uL;

            if (this.packet.HasMoreData)
            {
                clientFlags = (ClientFlags)((long)this.packet.ReadInteger(2));
            }
            this.owner.ConnectionCharSetIndex = (int)this.packet.ReadByte();
            this.serverStatus = (ServerStatusFlags)this.packet.ReadInteger(2);
            uint num2 = (uint)this.packet.ReadInteger(2);

            clientFlags          |= (ClientFlags)(num2 << 16);
            this.packet.Position += 11;
            string str = this.packet.ReadString();

            this.encryptionSeed += str;
            string authMethod;

            if ((clientFlags & ClientFlags.PLUGIN_AUTH) != (ClientFlags)0uL)
            {
                authMethod = this.packet.ReadString();
            }
            else
            {
                authMethod = "mysql_native_password";
            }
            this.SetConnectionFlags(clientFlags);
            this.packet.Clear();
            this.packet.WriteInteger((long)((int)this.connectionFlags), 4);
            if ((clientFlags & ClientFlags.SSL) == (ClientFlags)0uL)
            {
                if (this.Settings.SslMode != MySqlSslMode.None && this.Settings.SslMode != MySqlSslMode.Preferred)
                {
                    string msg = string.Format(Resources.NoServerSSLSupport, this.Settings.Server);
                    throw new MySqlException(msg);
                }
            }
            else if (this.Settings.SslMode != MySqlSslMode.None)
            {
                this.stream.SendPacket(this.packet);
                this.StartSSL();
                this.packet.Clear();
                this.packet.WriteInteger((long)((int)this.connectionFlags), 4);
            }
            this.packet.WriteInteger((long)num, 4);
            this.packet.WriteByte(8);
            this.packet.Write(new byte[23]);
            this.Authenticate(authMethod, false);
            if ((this.connectionFlags & ClientFlags.COMPRESS) != (ClientFlags)0uL)
            {
                this.stream = new MySqlStream(this.baseStream, this.Encoding, true);
            }
            this.packet.Version      = this.version;
            this.stream.MaxBlockSize = num;
        }
示例#25
0
        private void InternalBindParameters(string sql, MySqlParameterCollection parameters, MySqlPacket packet)
        {
            bool sqlServerMode = this.command.Connection.Settings.SqlServerMode;

            if (packet == null)
            {
                packet         = new MySqlPacket(this.Driver.Encoding);
                packet.Version = this.Driver.Version;
                packet.WriteByte(0);
            }
            MySqlTokenizer mySqlTokenizer = new MySqlTokenizer(sql);

            mySqlTokenizer.ReturnComments = true;
            mySqlTokenizer.SqlServerMode  = sqlServerMode;
            int    num  = 0;
            string text = mySqlTokenizer.NextToken();
            int    num2 = 0;

            while (text != null)
            {
                packet.WriteStringNoNull(sql.Substring(num, mySqlTokenizer.StartIndex - num));
                num = mySqlTokenizer.StopIndex;
                if (MySqlTokenizer.IsParameter(text))
                {
                    if ((!parameters.containsUnnamedParameters && text.Length == 1 && num2 > 0) || (parameters.containsUnnamedParameters && text.Length > 1))
                    {
                        throw new MySqlException(Resources.MixedParameterNamingNotAllowed);
                    }
                    parameters.containsUnnamedParameters = (text.Length == 1);
                    if (this.SerializeParameter(parameters, packet, text, num2))
                    {
                        text = null;
                    }
                    num2++;
                }
                if (text != null)
                {
                    if (sqlServerMode && mySqlTokenizer.Quoted && text.StartsWith("[", StringComparison.Ordinal))
                    {
                        text = string.Format("`{0}`", text.Substring(1, text.Length - 2));
                    }
                    packet.WriteStringNoNull(text);
                }
                text = mySqlTokenizer.NextToken();
            }
            this.buffers.Add(packet);
        }
示例#26
0
 public virtual void SendQuery(MySqlPacket p)
 {
     handler.SendQuery(p);
     firstResult = true;
 }
示例#27
0
        public void Open()
        {
            // connect to one of our specified hosts
            try
            {
                var streamTask = StreamCreator.GetStream(Settings);
                streamTask.Wait();
                baseStream = streamTask.Result;

#if !CF && !RT && !NETSTANDARD1_3
                if (Settings.IncludeSecurityAsserts)
                {
                    MySqlSecurityPermission.CreatePermissionSet(false).Assert();
                }
#endif
            }
            catch (System.Security.SecurityException)
            {
                throw;
            }
            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();
            owner.isFabric = versionString.EndsWith("fabric", StringComparison.OrdinalIgnoreCase);
            version        = DBVersion.Parse(versionString);
            if (!owner.isFabric && !version.isAtLeast(5, 0, 0))
            {
                throw new NotSupportedException(Resources.ServerTooOld);
            }
            threadId = packet.ReadInteger(4);

            byte[] seedPart1 = packet.ReadStringAsBytes();

            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;
            byte[] seedPart2 = packet.ReadStringAsBytes();
            encryptionSeed = new byte[seedPart1.Length + seedPart2.Length];
            seedPart1.CopyTo(encryptionSeed, 0);
            seedPart2.CopyTo(encryptionSeed, seedPart1.Length);

            string authenticationMethod = "";
            if ((serverCaps & ClientFlags.PLUGIN_AUTH) != 0)
            {
                authenticationMethod = packet.ReadString();
            }
            else
            {
                // Some MySql versions like 5.1, don't give name of plugin, default to native password.
                authenticationMethod = "mysql_native_password";
            }

            // based on our settings, set our connection flags
            SetConnectionFlags(serverCaps);

            packet.Clear();
            packet.WriteInteger((int)connectionFlags, 4);
            packet.WriteInteger(maxSinglePacket, 4);
            packet.WriteByte(33); //character set utf-8
            packet.Write(new byte[23]);

#if !CF && !RT
            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);
                packet.WriteInteger(maxSinglePacket, 4);
                packet.WriteByte(33); //character set utf-8
                packet.Write(new byte[23]);
            }
#endif

#if RT
            if (Settings.SslMode != MySqlSslMode.None)
            {
                throw new NotImplementedException("SSL not supported in this WinRT release.");
            }
#endif

            Authenticate(authenticationMethod, 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;
        }
    IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal)
    {
      if (nullVal)
        return new MySqlDecimal(true);

      string s = String.Empty;
      if (length == -1)
        s = packet.ReadLenString();
      else
        s = packet.ReadString(length);
      return new MySqlDecimal(s);
    }
示例#29
0
        private void InternalBindParameters(string sql, MySqlParameterCollection parameters, MySqlPacket packet)
        {
            bool sqlServerMode = command.Connection.Settings.SqlServerMode;

            if (packet == null)
            {
                packet = new MySqlPacket(Driver.Encoding)
                {
                    Version = Driver.Version
                };
                packet.WriteByte(0);
            }

            MySqlTokenizer tokenizer = new MySqlTokenizer(sql)
            {
                ReturnComments = true,
                SqlServerMode  = sqlServerMode
            };

            int    pos            = 0;
            string token          = tokenizer.NextToken();
            int    parameterCount = 0;

            while (token != null)
            {
                // serialize everything that came before the token (i.e. whitespace)
                packet.WriteStringNoNull(sql.Substring(pos, tokenizer.StartIndex - pos));
                pos = tokenizer.StopIndex;

                if (MySqlTokenizer.IsParameter(token))
                {
                    if ((!parameters.containsUnnamedParameters && token.Length == 1 && parameterCount > 0) || parameters.containsUnnamedParameters && token.Length > 1)
                    {
                        throw new MySqlException(Resources.MixedParameterNamingNotAllowed);
                    }

                    parameters.containsUnnamedParameters = token.Length == 1;
                    if (SerializeParameter(parameters, packet, token, parameterCount))
                    {
                        token = null;
                    }
                    parameterCount++;
                }

                if (token != null)
                {
                    if (sqlServerMode && tokenizer.Quoted && token.StartsWith("[", StringComparison.Ordinal))
                    {
                        token = String.Format("`{0}`", token.Substring(1, token.Length - 2));
                    }
                    packet.WriteStringNoNull(token);
                }
                token = tokenizer.NextToken();
            }
            _buffers.Add(packet);
        }
示例#30
0
        public void SendPacket(MySqlPacket packet)
        {
            byte[] buffer = packet.Buffer;
            int length = packet.Position-4;

            if ((ulong)length > maxPacketSize)
                throw new MySqlException(Resources.QueryTooLarge, (int)MySqlErrorCode.PacketTooLarge);

            int offset = 0;
            while (length > 0)
            {
                int lenToSend = length > maxBlockSize ? maxBlockSize : length;
                buffer[offset] = (byte)(lenToSend & 0xff);
                buffer[offset+1] = (byte)((lenToSend >> 8) & 0xff);
                buffer[offset+2] = (byte)((lenToSend >> 16) & 0xff);
                buffer[offset+3] = sequenceByte++;

                outStream.Write(buffer, offset, lenToSend + 4);
                outStream.Flush();
                length -= lenToSend;
                offset += lenToSend;
            }
        }
示例#31
0
 internal MySqlPacket ReadPacket()
 {
     return(this.packet = this.stream.ReadPacket());
 }
        IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal)
        {
            MySqlBinary b;
            if (nullVal)
                b = new MySqlBinary(type, true);
            else
            {
                if (length == -1)
                    length = (long)packet.ReadFieldLength();

                byte[] newBuff = new byte[length];
                packet.Read(newBuff, 0, (int)length);
                b = new MySqlBinary(type, newBuff);
            }
            return b;
        }
示例#33
0
 void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object v, int length)
 {
     uint val = (v is uint) ? (uint)v : Convert.ToUInt32(v);
     if (binary)
         packet.WriteInteger((long)val, is24Bit ? 3 : 4);
     else
         packet.WriteStringNoNull(val.ToString());
 }
        void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length)
        {
            byte[] buffToWrite = (val as byte[]);
            if (buffToWrite == null)
            {
                char[] valAsChar = (val as Char[]);
                if (valAsChar != null)
                    buffToWrite = packet.Encoding.GetBytes(valAsChar);
                else
                {
                    string s = val.ToString();
                    if (length == 0)
                        length = s.Length;
                    else
                        s = s.Substring(0, length);
                    buffToWrite = packet.Encoding.GetBytes(s);
                }
            }

            // we assume zero length means write all of the value
            if (length == 0)
                length = buffToWrite.Length;

            if (buffToWrite == null)
                throw new MySqlException("Only byte arrays and strings can be serialized by MySqlBinary");

            if (binary)
            {
                packet.WriteLength(length);
                packet.Write(buffToWrite, 0, length);
            }
            else
            {
                if (packet.Version.isAtLeast(4, 1, 0))
                    packet.WriteStringNoNull("_binary ");

                packet.WriteByte((byte)'\'');
                EscapeByteArray(buffToWrite, length, packet);
                packet.WriteByte((byte)'\'');
            }
        }
示例#35
0
 private void ReadEOF()
 {
     this.packet = this.stream.ReadPacket();
     this.CheckEOF();
 }
示例#36
0
    private void SerializeText(MySqlPacket packet, MySqlDateTime value)
    {
      var val = String.Empty;

      val = String.Format("{0:0000}-{1:00}-{2:00}",
                value.Year, value.Month, value.Day);
      if (type != MySqlDbType.Date)
      {
        val = value.Millisecond > 0 ? String.Format("{0} {1:00}:{2:00}:{3:00}.{4:000}", val,
          value.Hour, value.Minute, value.Second, value.Millisecond) : String.Format("{0} {1:00}:{2:00}:{3:00} ", val,
          value.Hour, value.Minute, value.Second);
      }

      packet.WriteStringNoNull("'" + val + "'");
    }
示例#37
0
        private void InternalBindParameters(string sql, MySqlParameterCollection parameters, 
            MySqlPacket packet)
        {
            bool sqlServerMode = command.Connection.Settings.SqlServerMode;

            if (packet == null)
            {
                packet = new MySqlPacket(Driver.Encoding);
                packet.Version = Driver.Version;
                packet.WriteByte(0);
            }

            MySqlTokenizer tokenizer = new MySqlTokenizer(sql);
            tokenizer.ReturnComments = true;
            tokenizer.SqlServerMode = sqlServerMode;

            int pos = 0;
            string token = tokenizer.NextToken();
            while (token != null)
            {
                // serialize everything that came before the token (i.e. whitespace)
                packet.WriteStringNoNull(sql.Substring(pos, tokenizer.StartIndex - pos));
                pos = tokenizer.StopIndex;
                if (MySqlTokenizer.IsParameter(token))
                {
                    if (SerializeParameter(parameters, packet, token))
                        token = null;
                }
                if (token != null)
                {
                    if (sqlServerMode && tokenizer.Quoted && token.StartsWith("["))
                        token = String.Format("`{0}`", token.Substring(1, token.Length - 2));
                    packet.WriteStringNoNull(token);
                }
                token = tokenizer.NextToken();
            }
            buffers.Add(packet);
        }
示例#38
0
    IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal)
    {

      if (nullVal) return new MySqlDateTime(type, true);

      if (length >= 0)
      {
        var value = packet.ReadString(length);
        return ParseMySql(value);
      }

      long bufLength = packet.ReadByte();
      int year = 0, month = 0, day = 0;
      int hour = 0, minute = 0, second = 0, millisecond = 0;
      if (bufLength >= 4)
      {
        year = packet.ReadInteger(2);
        month = packet.ReadByte();
        day = packet.ReadByte();
      }

      if (bufLength > 4)
      {
        hour = packet.ReadByte();
        minute = packet.ReadByte();
        second = packet.ReadByte();
      }

      if (bufLength > 7)
      {
        millisecond = packet.Read3ByteInt();
        packet.ReadByte();
      }

      return new MySqlDateTime(type, year, month, day, hour, minute, second, millisecond);
    }
示例#39
0
 /// <summary>
 /// Serializes the given parameter to the given memory stream
 /// </summary>
 /// <remarks>
 /// <para>This method is called by PrepareSqlBuffers to convert the given
 /// parameter to bytes and write those bytes to the given memory stream.
 /// </para>
 /// </remarks>
 /// <returns>True if the parameter was successfully serialized, false otherwise.</returns>
 private bool SerializeParameter(MySqlParameterCollection parameters,
                                 MySqlPacket packet, string parmName)
 {
     MySqlParameter parameter = parameters.GetParameterFlexible(parmName, false);
     if (parameter == null)
     {
         // if we are allowing user variables and the parameter name starts with @
         // then we can't throw an exception
         if (parmName.StartsWith("@") && ShouldIgnoreMissingParameter(parmName))
             return false;
         throw new MySqlException(
             String.Format(Resources.ParameterMustBeDefined, parmName));
     }
     parameter.Serialize(packet, false, Connection.Settings);
     return true;
 }
示例#40
0
		void IMySqlValue.SkipValue(MySqlPacket packet)
		{
			packet.ReadByte();
		}
        IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal)
        {
            if (nullVal)
                return new MySqlString(type, true);

            string s = String.Empty;
            if (length == -1)
                s = packet.ReadLenString();
            else
                s = packet.ReadString(length);
            MySqlString str = new MySqlString(type, s);
            return str;
        }
示例#42
0
		IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal)
		{
			if (nullVal)
				return new MySqlUByte(true);

			if (length == -1)
				return new MySqlUByte((byte)packet.ReadByte());
			else
				return new MySqlUByte(Byte.Parse(packet.ReadString(length)));
		}
示例#43
0
        public void Open()
        {
            // connect to one of our specified hosts
            try
            {
#if !CF
                if (Settings.ConnectionProtocol == MySqlConnectionProtocol.SharedMemory)
                {
                    var str = new SharedMemoryStream(Settings.SharedMemoryName);
                    str.Open(Settings.ConnectionTimeout);
                    baseStream = str;
                }
                else
                {
#endif
                var pipeName = Settings.PipeName;
                if (Settings.ConnectionProtocol != MySqlConnectionProtocol.NamedPipe)
                {
                    pipeName = null;
                }
                var sc = new StreamCreator(Settings.Server, Settings.Port, pipeName,
                                           Settings.Keepalive, Version);
#if !CF
                MySqlSecurityPermission.CreatePermissionSet(false).Assert();
#endif
                baseStream = sc.GetStream(Settings.ConnectionTimeout);
#if !CF
            }
#endif
            }
            catch (SecurityException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new MySqlException(Resources.UnableToConnectToHost,
                                         (int)MySqlErrorCode.UnableToConnectToHost, ex);
            }
            if (baseStream == null)
            {
                throw new MySqlException(Resources.UnableToConnectToHost,
                                         (int)MySqlErrorCode.UnableToConnectToHost);
            }

            var 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();
            var 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.
            var serverCapsHigh = (uint)packet.ReadInteger(2);
            serverCaps |= (ClientFlags)(serverCapsHigh << 16);

            packet.Position += 11;
            var seedPart2 = packet.ReadString();
            encryptionSeed += seedPart2;

            var authenticationMethod = "";
            if ((serverCaps & ClientFlags.PLUGIN_AUTH) != 0)
            {
                authenticationMethod = packet.ReadString();
            }
            else
            {
                // Some MySql versions like 5.1, don't give name of plugin, default to native password.
                authenticationMethod = "mysql_native_password";
            }

            // 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.
                    var 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(authenticationMethod, 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;
        }