public override async Task ExecuteRequest()
        {
            using (AsyncConnectionBase connection = new AsyncConnectionBase(Gateway.ServerHost, Gateway.ServerPort, 0, 0))
            {
                byte[] fileNameBytes = Encoding.UTF8.GetBytes(FileName);

                DataBuffer buf = new DataBuffer();
                buf.InsertInt16(20);     // Length
                buf.InsertInt16(0x0200); // Protocol version
                buf.InsertDwordString("IX86");
                buf.InsertDwordString(Product.ProductCode);
                if (_ad)
                {
                    buf.InsertInt32(_adId);
                    buf.InsertDwordString(_adExt);
                }
                else
                {
                    buf.InsertInt64(0);
                }

                bool connected = await connection.ConnectAsync();

                if (!connected)
                {
                    throw new IOException("Battle.net refused the connection.");
                }

                await connection.SendAsync(new byte[] { 2 });

                byte[] outgoingData = buf.UnderlyingStream.ToArray();
                await connection.SendAsync(outgoingData);

                byte[] incomingData = new byte[4];
                incomingData = await connection.ReceiveAsync(incomingData, 0, 4);

                if (incomingData == null)
                {
                    throw new IOException("Battle.net rejected the request.");
                }

                int serverToken = BitConverter.ToInt32(incomingData, 0);

                buf = new DataBuffer();
                buf.InsertInt32(0); // No resuming
                if (FileTime.HasValue)
                {
                    buf.InsertInt64(FileTime.Value.ToFileTimeUtc());
                }
                else
                {
                    buf.InsertInt64(0);
                }
                int clientToken = new Random().Next();
                buf.InsertInt32(clientToken);

                buf.InsertInt32(_key.Key.Length);
                buf.InsertInt32(_key.Product);
                buf.InsertInt32(_key.Value1);
                buf.InsertInt32(0);
                buf.InsertByteArray(_key.GetHash(clientToken, serverToken));
                buf.InsertByteArray(fileNameBytes);
                buf.InsertByte(0);

                outgoingData = buf.UnderlyingStream.ToArray();
                await connection.SendAsync(outgoingData);

                incomingData = new byte[8];
                incomingData = await connection.ReceiveAsync(incomingData, 0, 8);

                if (incomingData == null)
                {
                    throw new IOException("Battle.net rejected the file request.");
                }

                int remainingHeaderSize = BitConverter.ToInt32(incomingData, 0) - 8;
                int fileSize            = BitConverter.ToInt32(incomingData, 4);
                this.FileSize = fileSize;
                incomingData  = new byte[remainingHeaderSize];
                incomingData  = await connection.ReceiveAsync(incomingData, 0, remainingHeaderSize);

                if (incomingData == null)
                {
                    throw new IOException("Battle.net did not send a complete file header.");
                }

                DataReader reader = new DataReader(incomingData);
                reader.Seek(8); // banner id / extension
                long   fileTime = reader.ReadInt64();
                string name     = reader.ReadCString();
                if (string.Compare(name, FileName, StringComparison.OrdinalIgnoreCase) != 0 || FileSize == 0)
                {
                    throw new FileNotFoundException("The specified file was not found by Battle.net.");
                }

                incomingData = new byte[fileSize];
                incomingData = await connection.ReceiveAsync(incomingData, 0, fileSize);

                if (incomingData == null)
                {
                    throw new IOException("Battle.net did not send the file data.");
                }

                File.WriteAllBytes(LocalFileName, incomingData);
                DateTime time = DateTime.FromFileTimeUtc(fileTime);
                File.SetLastWriteTimeUtc(LocalFileName, time);
            }
        }
        public override void ExecuteRequest()
        {
            DataBuffer buf1 = new DataBuffer();

            buf1.InsertInt16(20);
            buf1.InsertInt16(0x0200);
            buf1.InsertDwordString("IX86");
            buf1.InsertDwordString(Product);
            if (m_ad)
            {
                buf1.InsertInt32(m_adId);
                buf1.InsertDwordString(m_adExt);
            }
            else
            {
                buf1.InsertInt64(0);
            }

            Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            sck.Connect(Server, 6112);

            sck.Send(new byte[] { 2 });
            sck.Send(buf1.GetData(), 0, buf1.Count, SocketFlags.None);

            NetworkStream ns          = new NetworkStream(sck, false);
            DataReader    rdr         = new DataReader(ns, 4);
            int           serverToken = rdr.ReadInt32();

            DataBuffer buf2 = new DataBuffer();

            buf2.InsertInt32(0); // no resuming
            if (FileTime.HasValue)
            {
                buf2.InsertInt64(FileTime.Value.ToFileTimeUtc());
            }
            else
            {
                buf2.InsertInt64(0);
            }

            int clientToken = new Random().Next();

            buf2.InsertInt32(clientToken);

            buf2.InsertInt32(m_key.Key.Length);
            buf2.InsertInt32(m_key.Product);
            buf2.InsertInt32(m_key.Value1);
            buf2.InsertInt32(0);
            buf2.InsertByteArray(m_key.GetHash(clientToken, serverToken));
            buf2.InsertCString(FileName);

            sck.Send(buf2.GetData(), 0, buf2.Count, SocketFlags.None);

            rdr = new DataReader(ns, 4);
            int msg2Size = rdr.ReadInt32() - 4;

            rdr = new DataReader(ns, msg2Size);

            this.FileSize = rdr.ReadInt32();
            rdr.Seek(8);
            long     fileTime = rdr.ReadInt64();
            DateTime time     = DateTime.FromFileTimeUtc(fileTime);
            string   name     = rdr.ReadCString();

            if (string.Compare(name, FileName, StringComparison.OrdinalIgnoreCase) != 0 || FileSize == 0)
            {
                throw new FileNotFoundException(Resources.bnftp_filenotfound);
            }

            byte[] data = ReceiveLoop(sck, FileSize);
            sck.Close();

            FileStream fs = new FileStream(LocalFileName, FileMode.OpenOrCreate, FileAccess.Write);

            fs.Write(data, 0, FileSize);
            fs.Flush();
            fs.Close();
        }
        private void HandleAuthInfo(ParseData data)
        {
            try
            {
                DataReader dr = new DataReader(data.Data);
                if (m_pingPck != null)
                {
                    Send(m_pingPck);
                    m_pingPck = null;
                }
                m_received0x50 = true;

                m_loginType          = dr.ReadUInt32();
                m_srvToken           = dr.ReadUInt32();
                m_udpVal             = dr.ReadUInt32();
                m_mpqFiletime        = dr.ReadInt64();
                m_versioningFilename = dr.ReadCString();
                m_usingLockdown      = m_versioningFilename.StartsWith("LOCKDOWN", StringComparison.OrdinalIgnoreCase);

                int    crResult = -1, exeVer = -1;
                string exeInfo = null;

                if (!m_usingLockdown)
                {
                    m_valString = dr.ReadCString();
                    int mpqNum = CheckRevision.ExtractMPQNumber(m_versioningFilename);
                    crResult = CheckRevision.DoCheckRevision(m_valString, new string[] { m_settings.GameExe, m_settings.GameFile2, m_settings.GameFile3 }, mpqNum);
                    exeVer   = CheckRevision.GetExeInfo(m_settings.GameExe, out exeInfo);
                }
                else
                {
                    m_ldValStr = dr.ReadNullTerminatedByteArray();
                    string dllName = m_versioningFilename.Replace(".mpq", ".dll");

                    BnFtpVersion1Request req = new BnFtpVersion1Request(m_settings.Client, m_versioningFilename, null);
                    req.Server        = m_settings.Gateway.ServerHost;
                    req.LocalFileName = Path.Combine(Path.GetTempPath(), m_versioningFilename);
                    req.ExecuteRequest();

                    string ldPath = null;
                    using (MpqArchive arch = MpqServices.OpenArchive(req.LocalFileName))
                    {
                        if (arch.ContainsFile(dllName))
                        {
                            ldPath = Path.Combine(Path.GetTempPath(), dllName);
                            arch.SaveToPath(dllName, Path.GetTempPath(), false);
                        }
                    }

                    m_ldDigest = CheckRevision.DoLockdownCheckRevision(m_ldValStr, new string[] { m_settings.GameExe, m_settings.GameFile2, m_settings.GameFile3 },
                                                                       ldPath, m_settings.ImageFile, ref exeVer, ref crResult);
                }

                m_prodCode = m_settings.Client;

                if (m_prodCode == "WAR3" ||
                    m_prodCode == "W3XP")
                {
                    m_w3srv = dr.ReadByteArray(128);

                    if (!NLS.ValidateServerSignature(m_w3srv, RemoteEP.Address.GetAddressBytes()))
                    {
                        OnError(new ErrorEventArgs(ErrorType.Warcraft3ServerValidationFailure, Strings.War3ServerValidationFailed, false));
                        //Close();
                        //return;
                    }
                }

                BattleNetClientResources.IncomingBufferPool.FreeBuffer(data.Data);

                CdKey key1, key2 = null;
                key1 = new CdKey(m_settings.CdKey1);
                if (m_prodCode == "D2XP" || m_prodCode == "W3XP")
                {
                    key2 = new CdKey(m_settings.CdKey2);
                }

                m_clientToken = unchecked ((uint)new Random().Next());

                byte[] key1Hash = key1.GetHash(m_clientToken, m_srvToken);
                if (m_warden != null)
                {
                    try
                    {
                        if (!m_warden.InitWarden(BitConverter.ToInt32(key1Hash, 0)))
                        {
                            m_warden.UninitWarden();
                            OnError(new ErrorEventArgs(ErrorType.WardenModuleFailure, "The Warden module failed to initialize.  You will not be immediately disconnected; however, you may be disconnected after a short period of time.", false));
                            m_warden = null;
                        }
                    }
                    catch (Win32Exception we)
                    {
                        OnError(new ErrorEventArgs(ErrorType.WardenModuleFailure, "The Warden module failed to initialize.  You will not be immediately disconnected; however, you may be disconnected after a short period of time.", false));
                        OnError(new ErrorEventArgs(ErrorType.WardenModuleFailure, string.Format(CultureInfo.CurrentCulture, "Additional information: {0}", we.Message), false));
                        m_warden.UninitWarden();
                        m_warden = null;
                    }
                }

                BncsPacket pck0x51 = new BncsPacket((byte)BncsPacketId.AuthCheck);
                pck0x51.Insert(m_clientToken);
                pck0x51.Insert(exeVer);
                pck0x51.Insert(crResult);
                if (m_prodCode == "D2XP" || m_prodCode == "W3XP")
                {
                    pck0x51.Insert(2);
                }
                else
                {
                    pck0x51.Insert(1);
                }
                pck0x51.Insert(false);
                pck0x51.Insert(key1.Key.Length);
                pck0x51.Insert(key1.Product);
                pck0x51.Insert(key1.Value1);
                pck0x51.Insert(0);
                pck0x51.Insert(key1Hash);
                if (key2 != null)
                {
                    pck0x51.Insert(key2.Key.Length);
                    pck0x51.Insert(key2.Product);
                    pck0x51.Insert(key2.Value1);
                    pck0x51.Insert(0);
                    pck0x51.Insert(key2.GetHash(m_clientToken, m_srvToken));
                }

                if (m_usingLockdown)
                {
                    pck0x51.InsertByteArray(m_ldDigest);
                    pck0x51.InsertByte(0);
                }
                else
                {
                    pck0x51.InsertCString(exeInfo);
                }

                pck0x51.InsertCString(m_settings.CdKeyOwner);

                Send(pck0x51);
            }
            catch (Exception ex)
            {
                OnError(new ErrorEventArgs(ErrorType.General, "There was an error while initializing your client.  Refer to the exception message for more information.\n" + ex.ToString(), true));
                Close();
            }
        }
        private async void HandleAuthInfo(BncsReader dr)
        {
            try
            {
                //DataReader dr = new DataReader(data.Data);
                //if (m_pingPck != null)
                //{
                //    Send(m_pingPck);
                //    m_pingPck = null;
                //}
                _received0x50 = true;

                _loginType          = dr.ReadUInt32();
                _srvToken           = dr.ReadInt32();
                _udpVal             = dr.ReadUInt32();
                _mpqFileTime        = dr.ReadInt64();
                _versioningFilename = dr.ReadCString();
                _usingLockdown      = _versioningFilename.StartsWith("LOCKDOWN", StringComparison.OrdinalIgnoreCase);

                int    crResult = -1, exeVer = -1;
                string exeInfo = null;

                if (!_usingLockdown)
                {
                    _valString = dr.ReadCString();
                    int mpqNum = CheckRevision.ExtractMPQNumber(_versioningFilename);
                    crResult = CheckRevision.DoCheckRevision(_valString, new Stream[] { File.OpenRead(_settings.GameExe), File.OpenRead(_settings.GameFile2), File.OpenRead(_settings.GameFile3) }, mpqNum);
                    exeVer   = CheckRevision.GetExeInfo(_settings.GameExe, out exeInfo);
                }
                else
                {
                    _ldValStr = dr.ReadNullTerminatedByteArray();
                    string dllName = _versioningFilename.Replace(".mpq", ".dll");

                    BnFtpVersion1Request req = new BnFtpVersion1Request(_settings.Client, _versioningFilename, null);
                    req.Gateway       = _settings.Gateway;
                    req.LocalFileName = Path.Combine(Path.GetTempPath(), _versioningFilename);
                    await req.ExecuteRequest();

                    string ldPath = null;
                    using (MpqArchive arch = MpqServices.OpenArchive(req.LocalFileName))
                    {
                        if (arch.ContainsFile(dllName))
                        {
                            ldPath = Path.Combine(Path.GetTempPath(), dllName);
                            arch.SaveToPath(dllName, Path.GetTempPath(), false);
                        }
                    }

                    _ldDigest = CheckRevision.DoLockdownCheckRevision(_ldValStr, new string[] { _settings.GameExe, _settings.GameFile2, _settings.GameFile3 },
                                                                      ldPath, _settings.ImageFile, ref exeVer, ref crResult);
                }

                string prodCode = _settings.Client.ProductCode;

                if (prodCode == "WAR3" || prodCode == "W3XP")
                {
                    _w3srv = dr.ReadByteArray(128);

                    if (!NLS.ValidateServerSignature(_w3srv, _connection.RemoteEP.Address.GetAddressBytes()))
                    {
                        //OnError(new ErrorEventArgs(ErrorType.Warcraft3ServerValidationFailure, Strings.War3ServerValidationFailed, false));
                        //Close();
                        //return;
                    }
                }

                //    BattleNetClientResources.IncomingBufferPool.FreeBuffer(data.Data);

                CdKey key1 = _settings.CdKey1, key2 = _settings.CdKey2;
                _clientToken = new Random().Next();

                byte[] key1Hash = key1.GetHash(_clientToken, _srvToken);
                if (WardenHandler != null)
                {
                    try
                    {
                        if (!WardenHandler.InitWarden(BitConverter.ToInt32(key1Hash, 0)))
                        {
                            WardenHandler.UninitWarden();
                            //OnError(new ErrorEventArgs(ErrorType.WardenModuleFailure, "The Warden module failed to initialize.  You will not be immediately disconnected; however, you may be disconnected after a short period of time.", false));
                            WardenHandler = null;
                        }
                    }
                    catch (Win32Exception we)
                    {
                        //OnError(new ErrorEventArgs(ErrorType.WardenModuleFailure, "The Warden module failed to initialize.  You will not be immediately disconnected; however, you may be disconnected after a short period of time.", false));
                        //OnError(new ErrorEventArgs(ErrorType.WardenModuleFailure, string.Format(CultureInfo.CurrentCulture, "Additional information: {0}", we.Message), false));
                        WardenHandler.UninitWarden();
                        WardenHandler = null;
                    }
                }

                BncsPacket pck0x51 = new BncsPacket(BncsPacketId.AuthCheck, _connection.NetworkBuffers.Acquire());
                pck0x51.InsertInt32(_clientToken);
                pck0x51.InsertInt32(exeVer);
                pck0x51.InsertInt32(crResult);
                if (prodCode == "D2XP" || prodCode == "W3XP")
                {
                    pck0x51.InsertInt32(2);
                }
                else
                {
                    pck0x51.InsertInt32(1);
                }
                pck0x51.InsertBoolean(false);
                pck0x51.InsertInt32(key1.Key.Length);
                pck0x51.InsertInt32(key1.Product);
                pck0x51.InsertInt32(key1.Value1);
                pck0x51.InsertInt32(0);
                pck0x51.InsertByteArray(key1Hash);
                if (key2 != null)
                {
                    pck0x51.InsertInt32(key2.Key.Length);
                    pck0x51.InsertInt32(key2.Product);
                    pck0x51.InsertInt32(key2.Value1);
                    pck0x51.InsertInt32(0);
                    pck0x51.InsertByteArray(key2.GetHash(_clientToken, _srvToken));
                }

                if (_usingLockdown)
                {
                    pck0x51.InsertByteArray(_ldDigest);
                    pck0x51.InsertByte(0);
                }
                else
                {
                    pck0x51.InsertCString(exeInfo);
                }

                pck0x51.InsertCString(_settings.CdKeyOwner);

                await pck0x51.SendAsync(_connection);
            }
            catch (Exception ex)
            {
                //OnError(new ErrorEventArgs(ErrorType.General, "There was an error while initializing your client.  Refer to the exception message for more information.\n" + ex.ToString(), true));
                Disconnect();

                Console.WriteLine(ex.ToString());
            }
        }
Example #5
0
        private static void Parse0x50(ClientSocket cs, Receiver receiver)
        {
            receiver.SkipLength(4); // Int32 logonType = receiver.GetInt32();
            cs.ServerToken = receiver.GetInt32();
            cs.ClientToken = receiver.GetInt32();
            receiver.SkipLength(8); // long mpqFiletime = receiver.GetInt64();
            string mpqFilename = receiver.GetNTString();

            byte[] checksumFormula = receiver.GetNTBytes();

            int crResult = -1, exeVer = -1, checkRevisionPass = 0;

            mpqFilename = mpqFilename.Substring(0,
                                                (mpqFilename.Length - 4)) + ".dll";

            byte[] exeInfo = CheckRevision.DoLockdownCheckRevision(checksumFormula,
                                                                   KryX2.Settings.GeneratedSettings.HashFiles,
                                                                   KryX2.Settings.GeneratedSettings.LockdownPath, mpqFilename, KryX2.Settings.GeneratedSettings.StarBin,
                                                                   ref exeVer, ref crResult);

            if (crResult == -1 || exeVer == -1)
            //if (checkRevisionPass != 1 || exeVer == 0)
            {
                //bad hashes perhaps
                Chat.Add(Color.Yellow, "CheckrevisionPass " + checkRevisionPass.ToString() + NewLine);
                Chat.Add(Color.White, "Exeversoin " + exeVer.ToString() + Environment.NewLine);
                //Chat.Add(Color.White, "No hashes or cr result is bad " + crResult + " / " + exeVer + NewLine);
                return;
            }


            CdKey cdkey;

            byte[] key1Hash;
            try
            {
                cdkey    = new CdKey(cs.CdKey);
                key1Hash = cdkey.GetHash(cs.ClientToken, cs.ServerToken);
            }
            catch
            {
                Chat.Add(Color.Yellow, "Couldn't decode key." + NewLine);
                return;
            }

            Builder builder = new Builder();

            builder.InsertInt32(cs.ClientToken);
            builder.InsertInt32(exeVer);
            builder.InsertInt32(crResult);
            builder.InsertInt32(1);  //keys used
            builder.InsertInt32(0);  //spawn?
            builder.InsertInt32(13); //key length
            builder.InsertInt32(cdkey.Product);
            builder.InsertInt32(cdkey.Value1);
            builder.InsertInt32(0);
            builder.InsertByteArray(key1Hash);
            builder.InsertByteArray(exeInfo);
            builder.InsertByte(0);
            builder.InsertNTString(RandomName()); //in use by
            builder.SendPacket(cs, 0x51);
        }