Пример #1
0
        internal static void Randomize(bool newDirectory = false)
        {
            if (newDirectory && Directory.Exists(Settings.Instance.Directories.TempCoreDirectory))
            {
                DirectoryHelper.DeleteDirectory(Settings.Instance.Directories.TempCoreDirectory);
            }

            // Set new directory
            if (!Directory.Exists(Settings.Instance.Directories.TempCoreDirectory))
            {
                // Create a random directory to store the core files
                Settings.Instance.Directories.TempCoreDirectory = Path.Combine(Path.GetTempPath(),
                                                                               RandomHelper.RandomString());
                Log.Instance.DoLog(string.Format("Created temporary core directory: \"{0}\"",
                                                 Settings.Instance.Directories.TempCoreDirectory));
            }

            // Copy Elobuddy.Core.dll file
            try
            {
                if (!File.Exists(Settings.Instance.Directories.TempCoreDllPath))
                {
                    Settings.Instance.Directories.TempCoreDllPath =
                        Path.Combine(Settings.Instance.Directories.TempCoreDirectory, "Elobuddy.Core.dll");
                }

                if (
                    !Md5Hash.Compare(Md5Hash.ComputeFromFile(Settings.Instance.Directories.TempCoreDllPath),
                                     Md5Hash.ComputeFromFile(Settings.Instance.Directories.CoreDllPath)))
                {
                    FileHelper.SafeCopyFile(Settings.Instance.Directories.CoreDllPath,
                                            Settings.Instance.Directories.TempCoreDirectory,
                                            Path.GetFileName(Settings.Instance.Directories.TempCoreDllPath));
                    Log.Instance.DoLog(string.Format("Copied EloBuddy.Core.dll to: \"{0}\"",
                                                     Settings.Instance.Directories.TempCoreDllPath));
                }
            }
            catch (Exception)
            {
                // ignored
            }

            // Copy EloBuddy.Sandbox.dll file
            try
            {
                if (!File.Exists(Settings.Instance.Directories.TempSandboxDllPath))
                {
                    Settings.Instance.Directories.TempSandboxDllPath =
                        Path.Combine(Settings.Instance.Directories.TempCoreDirectory,
                                     RandomHelper.RandomString() + ".dll");
                }

                if (
                    !Md5Hash.Compare(
                        Md5Hash.ComputeFromFile(Settings.Instance.Directories.TempSandboxDllPath),
                        Md5Hash.ComputeFromFile(Settings.Instance.Directories.SandboxDllPath)))
                {
                    FileHelper.SafeCopyFile(Settings.Instance.Directories.SandboxDllPath,
                                            Settings.Instance.Directories.TempCoreDirectory,
                                            Path.GetFileName(Settings.Instance.Directories.TempSandboxDllPath));

                    // as requested by finn
                    FileHelper.SafeCopyFile(Settings.Instance.Directories.SandboxDllPath,
                                            Settings.Instance.Directories.TempCoreDirectory);

                    Log.Instance.DoLog(string.Format("Copied EloBuddy.Sandbox.dll to: \"{0}\"",
                                                     Settings.Instance.Directories.TempSandboxDllPath));
                }
            }
            catch (Exception)
            {
                // ignored
            }

            // Copy EloBuddy.dll file
            try
            {
                if (!File.Exists(Settings.Instance.Directories.TempEloBuddyDllPath))
                {
                    Settings.Instance.Directories.TempEloBuddyDllPath =
                        Path.Combine(Settings.Instance.Directories.TempCoreDirectory,
                                     RandomHelper.RandomString() + ".dll");
                }

                if (
                    !Md5Hash.Compare(
                        Md5Hash.ComputeFromFile(Settings.Instance.Directories.TempCoreDirectory),
                        Md5Hash.ComputeFromFile(Settings.Instance.Directories.EloBuddyDllPath)))
                {
                    FileHelper.SafeCopyFile(Settings.Instance.Directories.EloBuddyDllPath,
                                            Settings.Instance.Directories.TempCoreDirectory,
                                            Path.GetFileName(Settings.Instance.Directories.TempEloBuddyDllPath));

                    // as requested by finn
                    FileHelper.SafeCopyFile(Settings.Instance.Directories.EloBuddyDllPath,
                                            Settings.Instance.Directories.TempCoreDirectory);

                    Log.Instance.DoLog(string.Format("Copied EloBuddy.dll to: \"{0}\"",
                                                     Settings.Instance.Directories.TempEloBuddyDllPath));
                }
            }
            catch (Exception)
            {
                // ignored
            }
        }
Пример #2
0
        private int LoginUser(string username, string password)
        {
            string hash = Md5Hash.GetMd5Hash(MD5.Create(), password);

            return(_accountService.SignIn(username, hash));
        }
Пример #3
0
        /// <summary>
        /// Download Document
        /// </summary>
        /// <param name="document">Document</param>
        /// <param name="path">Path</param>
        /// <param name="mode">Mode</param>
        public void DownloadDocument(DocumentInfo document, string path, DocumentDownloadMode mode)
        {
            var request = new DownloadDocumentRequest
            {
                OidDocument = document.OidDocument,
                Version     = document.Version,
                ChunkNumber = 0,
                ChunkSize   = GetChunkSize(),
                Mode        = mode
            };

            // Get the first chunk of data
            DownloadDocumentResponse response = null;

            if (_flowDocsService == null)
            {
                using (var docsProxy = new FlowDocsOperations())
                {
                    response = docsProxy.DownloadDocument(request);
                }
            }
            else
            {
                response = _flowDocsService.DownloadDocument(request);
            }

            var filePath = Path.Combine(path, response.DocumentName);

            document.DocumentName = filePath;
            document.Description  = response.Description;
            document.Owner        = response.Owner;
            document.Path         = response.Path;
            document.MimeType     = response.MimeType;
            document.FileHash     = response.FileHash;

            using (var writer = new FileStream(filePath, FileMode.Create))
            {
                int  chunks  = 0;
                long curSize = response.ChunkSize;
                writer.Write(response.DataField, 0, (int)Math.Min(response.ChunkSize, response.FileSize));
                request.ChunkNumber = ++chunks;

                // Get all the chunks of the document
                while (chunks < response.ChunkTotal)
                {
                    if (_flowDocsService == null)
                    {
                        using (var docsProxy = new FlowDocsOperations())
                        {
                            response = docsProxy.DownloadDocument(request);
                        }
                    }
                    else
                    {
                        response = _flowDocsService.DownloadDocument(request);
                    }

                    int size = response.ChunkSize;
                    if (response.FileSize > 0)
                    {
                        long bytesLeft = response.FileSize - curSize;
                        size = bytesLeft < response.ChunkSize ? (int)bytesLeft : response.ChunkSize;
                    }

                    writer.Write(response.DataField, 0, size);

                    var hash = Md5Hash.CreateMd5Hash(response.DataField);

                    if (hash != response.FileHash)
                    {
                        throw new Exception(Flow.Library.Properties.Resources.ER_HASH);
                    }

                    curSize            += size;
                    request.ChunkNumber = ++chunks;
                }
            }
        }
Пример #4
0
        public static bool DealLogin(string username, string password, AppLog applog, ref string message)
        {
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                message = "账号或密码不能为空!";
                return(false);
            }

            UserInfo userInfo = null;

            //查看账号是否存在
            if (!Access.GetUserByCard(username, ref userInfo))
            {
                applog.InfoFormat("用户:{0}--->登陆时查询账号异常.", username);
                message = "很抱歉,操作异常请重试!";

                return(false);
            }

            if (userInfo == null)
            {
                applog.InfoFormat("用户:{0}--->登陆账号不存在.", username);
                message = "很抱歉,该账号不存在!";

                return(false);
            }

            /*
             #if Release
             * if (userInfo.Status == "Y")
             * {
             *  applog.InfoFormat("用户:{0}--->该账号已登录.", username);
             *  message="很抱歉,该账号已登录!";
             *
             *  return false;
             * }
             #endif
             */
            //查看密码是否匹配
            if (Md5Hash.VerifyMd5Hash(password, userInfo.LoginPassWord))
            {
                applog.InfoFormat("用户:{0}--->登陆成功.", username);

                /*
                 * //更新状态
                 * if (!Access.UpdateStatus_Y(username))
                 * {
                 *  applog.InfoFormat("用户:{0}--->登陆时修改状态异常:{1}", username);
                 *  message = "很抱歉,操作异常请重试!";
                 *
                 *  return false;
                 * }
                 *
                 * applog.InfoFormat("用户:{0}--->更新在线状态为:Y.", username);
                 * */
                return(true);
            }
            else
            {
                applog.InfoFormat("用户:{0}--->密码错误.", username);
                message = "很抱歉,密码输入不正确!";

                return(false);
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="fileToWrite"></param>
        /// <param name="token"></param>
        public void Write(EdataFile edataFile, CancellationToken token)
        {
            //Uważać tu na ścieżke jaka ma edata pełną czy relatywną..
            //No i dodatkowo od tego momentu może być pusta. A z racji tego że tylko możemy podmieniać edata nie pasuje
            //dodawać dodatkowy argument ścieżki do zapisu, bo to jasno wskazywało by że możemy zapisywać do dowolnej lokacji
            // a tak naprawde można tylko podmieniać edata.
            if (!File.Exists(edataFile.Path))
            {
                throw new ArgumentException(
                          String.Format("A following Edata file: \"{0}\" doesn't exist", edataFile.Path),
                          "edataFile");
            }

            //Cancel if requested;
            token.ThrowIfCancellationRequested();

            var edataContentFiles = edataFile.ContentFiles.OfType <EdataContentFile>();

            //Wypieprzyć z tąd wszystkie zależności od starych metod, i stworzyć nowe metody zapisu poszczegołnych elementów
            //realizujące nową koncepcję wykorzystujaca model wpsiów słownika i być może w przyszłosci samego słownika.

            //W przypadku konieczności odbudowy słownika trzeba poszerzyć określenie czy można użyć ReplacemnetWrite
            //Jeśli nie ma nowego pliku, i słownik mieści sie w miejsce starego, to można użyć replacement write
            //Jeśli natomiast dodano nowy plik, lub słownik nie miesci sie na miejsce starego to trzeba zbudować plik Edata od zera.

            //Update na dobrą sprawę można założyć, że jeśli nie ma zmian w plikach to słownik zawszę będzie się mieścił w miejsce starego.
            if (!AnyContentFileExceedsAvailableSpace(edataFile) &&
                !edataFile.HasContentFilesCollectionChanged)
            {
                using (var sourceEdata = new FileStream(edataFile.Path, FileMode.Open))
                {
                    //Taka uwaga: Nie robić canceli w trakcie zapisu czy to nagłowka czy słownika, zeby w przypadku przerwania bez backapu zminimalizwoać
                    //            szanse na uszkodzenie modyifkowane go pliku.

                    //W tym przypadku używamy starego rozmieszczenia danych żeby nie odbudowywac pliku od nowa.
                    var header = edataFile.Header;

                    var  dictRoot   = CreateDictionaryEntries(edataContentFiles);
                    uint dictOffset = header.DictOffset;
                    uint dictLength = ComputeDictionaryLength(dictRoot);
                    uint dictEnd    = dictOffset + dictLength;

                    WriteLoadedContentByReplace(sourceEdata, edataContentFiles, token);

                    AssignContentFilesInfoToDictEntries(edataContentFiles, dictRoot);

                    //Clear the old part of file up to content.
                    WritePadding(sourceEdata, 0, header.FileOffset);

                    var dictWriteInfo = WriteDictionary(sourceEdata, dictRoot, dictOffset);

                    header.Checksum_V2 = Md5Hash.GetHash(dictWriteInfo.Checksum);
                    header.DictLength  = dictWriteInfo.Length;

                    WriteHeader(sourceEdata, header, 0);
                }
            }
            else
            {
                //Try in the current dir to avoid double file moving
                String temporaryEdataPath = PathUtilities.GetTemporaryPath(edataFile.Path);
                if ((new FileInfo(edataFile.Path).Length > (new DriveInfo(temporaryEdataPath).AvailableFreeSpace)))
                {
                    temporaryEdataPath = TryGetTemporaryEdataPathWhereFree(edataFile.Path);
                    if (temporaryEdataPath == null)
                    {
                        throw new IOException(
                                  String.Format("Not enough free disk space for rebuilding the \"{0}\" file.",
                                                edataFile.Path));
                    }
                }

                //To avoid too many nested try catches.
                FileStream sourceEdata = null;
                FileStream newEdata    = null;
                try
                {
                    sourceEdata = new FileStream(edataFile.Path, FileMode.Open);
                    newEdata    = new FileStream(temporaryEdataPath, FileMode.Create);

                    //W tym przypadku rozmieszczamy wszystko od zera wg wartości obliczonych.
                    var  dictRoot   = CreateDictionaryEntries(edataContentFiles);
                    uint dictOffset = GetDictionaryOffset();
                    uint dictLength = ComputeDictionaryLength(dictRoot);
                    uint dictEnd    = dictOffset + dictLength;

                    uint fileOffset = GetFileOffset(dictEnd);

                    var contentWriteInfo = WriteNotLoadedContent(sourceEdata, newEdata, edataContentFiles, fileOffset, token);

                    AssignContentFilesInfoToDictEntries(edataContentFiles, dictRoot);

                    WritePadding(newEdata, 0, fileOffset);

                    var dictWriteInfo = WriteDictionary(newEdata, dictRoot, dictOffset);

                    var header = edataFile.Header;
                    header.Checksum_V2 = Md5Hash.GetHash(dictWriteInfo.Checksum);
                    header.DictOffset  = dictOffset;
                    header.DictLength  = dictWriteInfo.Length;
                    header.FileOffset  = fileOffset;
                    header.FileLenght  = contentWriteInfo.Length;

                    WriteHeader(newEdata, header, 0);

                    //Free file handles before the file move and delete
                    CloseEdataFilesStreams(sourceEdata, newEdata);

                    //Replace temporary file
                    File.Delete(edataFile.Path);
                    File.Move(temporaryEdataPath, edataFile.Path);
                }
                finally
                {
                    //Spr czy zostały już zwolnione...?
                    CloseEdataFilesStreams(sourceEdata, newEdata);

                    if (File.Exists(temporaryEdataPath))
                    {
                        File.Delete(temporaryEdataPath);
                    }
                }
            }
        }
Пример #6
0
        /// <summary>
        /// 处理登陆
        /// </summary>
        /// <param name="message">账号+密码</param>
        public void DealLogin(User user, string message)
        {
            //账号+密码
            string[] msg     = message.Split(MessageTypes.NSP.ToCharArray());
            ILogger  ilogger = ILogger.GetInstance();

            UserInfo userInfo = null;

            //查看账号是否存在
            try
            {
                userInfo = Access.GetUserByCard(msg[0]);
            }
            catch (Exception ex)
            {
                ilogger.Logger(string.Format("用户:{0}--->登陆时查询账号异常:{1}", user.client.Client.RemoteEndPoint, ex.Message));
                Console.WriteLine("用户:{0}--->登陆时查询账号异常:{1}", user.client.Client.RemoteEndPoint, ex.Message);
                SendMsg(user, MessageTypes.LOG + MessageTypes.PSP + "0" + MessageTypes.PSP + "很抱歉,操作异常请重试!");

                return;
            }

            if (userInfo == null)
            {
                ilogger.Logger(string.Format("用户:{0}--->登陆账号不存在.", user.client.Client.RemoteEndPoint));
                Console.WriteLine("用户:{0}--->登陆账号不存在.", user.client.Client.RemoteEndPoint);
                SendMsg(user, MessageTypes.LOG + MessageTypes.PSP + "0" + MessageTypes.PSP + "很抱歉,该账号不存在!");

                return;
            }

            if (userInfo.UserStatus == "Y")
            {
                ilogger.Logger(string.Format("用户:{0}--->该账号已登录.", user.client.Client.RemoteEndPoint));
                Console.WriteLine("用户:{0}--->该账号已登录.", user.client.Client.RemoteEndPoint);
                SendMsg(user, MessageTypes.LOG + MessageTypes.PSP + "0" + MessageTypes.PSP + "很抱歉,该账号已登录!");

                return;
            }

            //查看密码是否匹配
            if (Md5Hash.VerifyMd5Hash(msg[1], userInfo.PassWord))
            {
                ilogger.Logger(string.Format("用户:{0}--->登陆成功.", user.client.Client.RemoteEndPoint));
                Console.WriteLine("用户:{0}--->登陆成功.", user.client.Client.RemoteEndPoint);

                //更新状态
                try
                {
                    Access.UpdateStatus_Y(msg[0]);
                }
                catch (Exception ex)
                {
                    ilogger.Logger(string.Format("用户:{0}--->登陆时修改状态异常:{1}", user.client.Client.RemoteEndPoint, ex.Message));
                    Console.WriteLine("用户:{0}--->登陆时修改状态异常:{1}", user.client.Client.RemoteEndPoint, ex.Message);
                    SendMsg(user, MessageTypes.LOG + MessageTypes.PSP + "0" + MessageTypes.PSP + "很抱歉,操作异常请重试!");

                    return;
                }

                ilogger.Logger(string.Format("用户:{0}--->更新在线状态为:Y.", user.client.Client.RemoteEndPoint));
                Console.WriteLine("用户:{0}--->更新在线状态为:Y.", user.client.Client.RemoteEndPoint);
                SendMsg(user, MessageTypes.LOG + MessageTypes.PSP + "1" + MessageTypes.PSP
                        + userInfo.UserID + MessageTypes.NSP + userInfo.CardWord + MessageTypes.NSP + userInfo.UserName + MessageTypes.NSP + userInfo.UserPicture);
            }
            else
            {
                ilogger.Logger(string.Format("用户:{0}--->密码错误.", user.client.Client.RemoteEndPoint));
                Console.WriteLine("用户:{0}--->密码错误.", user.client.Client.RemoteEndPoint);
                SendMsg(user, MessageTypes.LOG + MessageTypes.PSP + "0" + MessageTypes.PSP + "很抱歉,密码输入有误!");
            }
        }
Пример #7
0
        internal static void PatchFilesUpdateRoutine(UpdateWindow ui, Dictionary <string, object> args)
        {
            var updateData = (UpdateData)args["updateData"];

            if (updateData != null)
            {
                //-----------------------------
                // Update patch files
                //-----------------------------
                var       currentPatchHash = Riot.GetCurrentPatchHash().ToLower();
                PatchData patch;
                updateData.Patches.TryGetValue(currentPatchHash, out patch);

                if (patch != null && !DeveloperHelper.IsDeveloper)
                {
                    var currentProgress = 0;
                    ui.Status  = MultiLanguage.Text.UpdateStatusPatchFiles;
                    ui.Details = "";

                    foreach (var keyPair in patch.Files)
                    {
                        var path     = keyPair.Key;
                        var filename = Path.GetFileName(path);
                        currentProgress += 1;

                        ui.CurrentProgress       = 0;
                        ui.OveralCurrentProgress = currentProgress;
                        ui.OveralMaxProgress     = patch.Files.Count + 1;
                        ui.Details = string.Format(MultiLanguage.Text.UpdateDetailsCheckingFile, filename);

                        if (!Md5Hash.Compare(Md5Hash.ComputeFromFile(path), keyPair.Value.MD5))
                        {
                            if (!string.IsNullOrEmpty(keyPair.Value.Download))
                            {
                                ui.Details = string.Format(MultiLanguage.Text.UpdateDetailsDownloadingFile, filename);

                                if (!DownloadFile(keyPair.Value.Download, path))
                                {
                                    ExitDownloadError(filename);
                                }
                            }
                            else if (File.Exists(path))
                            {
                                File.Delete(path);
                            }
                        }
                    }
                    ui.OveralCurrentProgress = ui.OveralMaxProgress;
                }

                // Set patch update result
                LoaderUpdate.LeagueHash    = currentPatchHash;
                LoaderUpdate.LeagueVersion = string.IsNullOrEmpty(currentPatchHash)
                    ? string.Empty
                    : Riot.GetCurrentPatchVersionInfo().FileVersion;
                LoaderUpdate.UpToDate = DeveloperHelper.IsDeveloper || patch != null;

                if (patch != null && LoaderUpdate.UpToDate)
                {
                    LoaderUpdate.CoreHash = Md5Hash.ComputeFromFile(Settings.Instance.Directories.CoreDllPath);

                    if (args.ContainsKey("coreData"))
                    {
                        var jsonNews = (CoreNewsList)args["coreData"];
                        var coreItem = jsonNews.News.FirstOrDefault(n => n.Hash != null && n.Hash.Any(h => Md5Hash.Compare(h, LoaderUpdate.CoreHash)));
                        LoaderUpdate.CoreBuild = coreItem != null ? coreItem.Build : "Unknown";
                    }
                    else
                    {
                        LoaderUpdate.CoreBuild = "Unknown";
                    }
                }

                Log.Instance.DoLog(string.Format("League hash detected: \"{0}\"", currentPatchHash));
                Log.Instance.DoLog(string.Format("EloBuddy updated for current patch: {0}", patch != null));
                Log.Instance.DoLog(string.Format("Update status: \"{0}\"", LoaderUpdate.StatusString));
            }
        }
Пример #8
0
 public bool Match(string start) => Md5Hash.StartsWith(start);
Пример #9
0
        private void ClientInitRequest(NetIncomingMessage inc)
        {
            DebugConsole.Log("Received client init request");
            if (ConnectedClients.Find(c => c.Connection == inc.SenderConnection) != null)
            {
                //this client was already authenticated
                //another init request means they didn't get any update packets yet
                DebugConsole.Log("Client already connected, ignoring...");
                return;
            }

            UnauthenticatedClient unauthClient = unauthenticatedClients.Find(uc => uc.Connection == inc.SenderConnection);

            if (unauthClient == null)
            {
                //client did not ask for nonce first, can't authorize
                inc.SenderConnection.Disconnect(DisconnectReason.AuthenticationRequired.ToString());
                if (unauthClient.SteamID > 0)
                {
                    Steam.SteamManager.StopAuthSession(unauthClient.SteamID);
                }
                return;
            }

            if (serverSettings.HasPassword && inc.SenderConnection != OwnerConnection)
            {
                //decrypt message and compare password
                string clPw = inc.ReadString();
                if (!serverSettings.IsPasswordCorrect(clPw, unauthClient.Nonce))
                {
                    unauthClient.FailedAttempts++;
                    if (unauthClient.FailedAttempts > 3)
                    {
                        //disconnect and ban after too many failed attempts
                        serverSettings.BanList.BanPlayer("Unnamed", unauthClient.Connection.RemoteEndPoint.Address, "DisconnectMessage.TooManyFailedLogins", duration: null);
                        DisconnectUnauthClient(inc, unauthClient, DisconnectReason.TooManyFailedLogins, "");

                        Log(inc.SenderConnection.RemoteEndPoint.Address.ToString() + " has been banned from the server (too many wrong passwords)", ServerLog.MessageType.Error);
                        DebugConsole.NewMessage(inc.SenderConnection.RemoteEndPoint.Address.ToString() + " has been banned from the server (too many wrong passwords)", Color.Red);
                        return;
                    }
                    else
                    {
                        //not disconnecting the player here, because they'll still use the same connection and nonce if they try logging in again
                        NetOutgoingMessage reject = server.CreateMessage();
                        reject.Write((byte)ServerPacketHeader.AUTH_FAILURE);
                        reject.Write("Wrong password! You have " + Convert.ToString(4 - unauthClient.FailedAttempts) + " more attempts before you're banned from the server.");
                        Log(inc.SenderConnection.RemoteEndPoint.Address.ToString() + " failed to join the server (incorrect password)", ServerLog.MessageType.Error);
                        DebugConsole.NewMessage(inc.SenderConnection.RemoteEndPoint.Address.ToString() + " failed to join the server (incorrect password)", Color.Red);
                        CompressOutgoingMessage(reject);
                        server.SendMessage(reject, unauthClient.Connection, NetDeliveryMethod.Unreliable);
                        unauthClient.AuthTimer = 10.0f;
                        return;
                    }
                }
            }
            string clVersion = inc.ReadString();

            UInt16        contentPackageCount  = inc.ReadUInt16();
            List <string> contentPackageNames  = new List <string>();
            List <string> contentPackageHashes = new List <string>();

            for (int i = 0; i < contentPackageCount; i++)
            {
                string packageName = inc.ReadString();
                string packageHash = inc.ReadString();
                contentPackageNames.Add(packageName);
                contentPackageHashes.Add(packageHash);
                if (contentPackageCount == 0)
                {
                    DebugConsole.Log("Client is using content package " +
                                     (packageName ?? "null") + " (" + (packageHash ?? "null" + ")"));
                }
            }

            if (contentPackageCount == 0)
            {
                DebugConsole.Log("Client did not list any content packages.");
            }

            string clName = Client.SanitizeName(inc.ReadString());

            if (string.IsNullOrWhiteSpace(clName))
            {
                DisconnectUnauthClient(inc, unauthClient, DisconnectReason.NoName, "");

                Log(inc.SenderConnection.RemoteEndPoint.Address.ToString() + " couldn't join the server (no name given)", ServerLog.MessageType.Error);
                DebugConsole.NewMessage(inc.SenderConnection.RemoteEndPoint.Address.ToString() + " couldn't join the server (no name given)", Color.Red);
                return;
            }

            if (clVersion != GameMain.Version.ToString())
            {
                DisconnectUnauthClient(inc, unauthClient, DisconnectReason.InvalidVersion,
                                       $"DisconnectMessage.InvalidVersion~[version]={GameMain.Version.ToString()}~[clientversion]={clVersion}");

                Log(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (wrong game version)", ServerLog.MessageType.Error);
                DebugConsole.NewMessage(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (wrong game version)", Color.Red);
                return;
            }

            //check if the client is missing any of the content packages the server requires
            List <ContentPackage> missingPackages = new List <ContentPackage>();

            foreach (ContentPackage contentPackage in GameMain.SelectedPackages)
            {
                if (!contentPackage.HasMultiplayerIncompatibleContent)
                {
                    continue;
                }
                bool packageFound = false;
                for (int i = 0; i < contentPackageCount; i++)
                {
                    if (contentPackageNames[i] == contentPackage.Name && contentPackageHashes[i] == contentPackage.MD5hash.Hash)
                    {
                        packageFound = true;
                        break;
                    }
                }
                if (!packageFound)
                {
                    missingPackages.Add(contentPackage);
                }
            }

            if (missingPackages.Count == 1)
            {
                DisconnectUnauthClient(inc, unauthClient, DisconnectReason.MissingContentPackage, $"DisconnectMessage.MissingContentPackage~[missingcontentpackage]={GetPackageStr(missingPackages[0])}");
                Log(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (missing content package " + GetPackageStr(missingPackages[0]) + ")", ServerLog.MessageType.Error);
                return;
            }
            else if (missingPackages.Count > 1)
            {
                List <string> packageStrs = new List <string>();
                missingPackages.ForEach(cp => packageStrs.Add(GetPackageStr(cp)));
                DisconnectUnauthClient(inc, unauthClient, DisconnectReason.MissingContentPackage, $"DisconnectMessage.MissingContentPackages~[missingcontentpackages]={string.Join(", ", packageStrs)}");
                Log(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (missing content packages " + string.Join(", ", packageStrs) + ")", ServerLog.MessageType.Error);
                return;
            }

            string GetPackageStr(ContentPackage contentPackage)
            {
                return("\"" + contentPackage.Name + "\" (hash " + contentPackage.MD5hash.ShortHash + ")");
            }

            //check if the client is using any contentpackages that are not compatible with the server
            List <Pair <string, string> > incompatiblePackages = new List <Pair <string, string> >();

            for (int i = 0; i < contentPackageNames.Count; i++)
            {
                if (!GameMain.Config.SelectedContentPackages.Any(cp => cp.Name == contentPackageNames[i] && cp.MD5hash.Hash == contentPackageHashes[i]))
                {
                    incompatiblePackages.Add(new Pair <string, string>(contentPackageNames[i], contentPackageHashes[i]));
                }
            }

            if (incompatiblePackages.Count == 1)
            {
                DisconnectUnauthClient(inc, unauthClient, DisconnectReason.IncompatibleContentPackage,
                                       $"DisconnectMessage.IncompatibleContentPackage~[incompatiblecontentpackage]={GetPackageStr2(incompatiblePackages[0])}");
                Log(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (incompatible content package " + GetPackageStr2(incompatiblePackages[0]) + ")", ServerLog.MessageType.Error);
                return;
            }
            else if (incompatiblePackages.Count > 1)
            {
                List <string> packageStrs = new List <string>();
                incompatiblePackages.ForEach(cp => packageStrs.Add(GetPackageStr2(cp)));
                DisconnectUnauthClient(inc, unauthClient, DisconnectReason.IncompatibleContentPackage,
                                       $"DisconnectMessage.IncompatibleContentPackages~[incompatiblecontentpackages]={string.Join(", ", packageStrs)}");
                Log(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (incompatible content packages " + string.Join(", ", packageStrs) + ")", ServerLog.MessageType.Error);
                return;
            }

            string GetPackageStr2(Pair <string, string> nameAndHash)
            {
                return("\"" + nameAndHash.First + "\" (hash " + Md5Hash.GetShortHash(nameAndHash.Second) + ")");
            }

            if (inc.SenderConnection != OwnerConnection && !serverSettings.Whitelist.IsWhiteListed(clName, inc.SenderConnection.RemoteEndPoint.Address))
            {
                DisconnectUnauthClient(inc, unauthClient, DisconnectReason.NotOnWhitelist, "");
                Log(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (not in whitelist)", ServerLog.MessageType.Error);
                DebugConsole.NewMessage(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (not in whitelist)", Color.Red);
                return;
            }
            if (!Client.IsValidName(clName, this))
            {
                DisconnectUnauthClient(inc, unauthClient, DisconnectReason.InvalidName, "");
                Log(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (invalid name)", ServerLog.MessageType.Error);
                DebugConsole.NewMessage(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (invalid name)", Color.Red);
                return;
            }
            if (inc.SenderConnection != OwnerConnection && Homoglyphs.Compare(clName.ToLower(), Name.ToLower()))
            {
                DisconnectUnauthClient(inc, unauthClient, DisconnectReason.NameTaken, "");
                Log(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (name taken by the server)", ServerLog.MessageType.Error);
                DebugConsole.NewMessage(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (name taken by the server)", Color.Red);
                return;
            }
            Client nameTaken = ConnectedClients.Find(c => Homoglyphs.Compare(c.Name.ToLower(), clName.ToLower()));

            if (nameTaken != null)
            {
                if (nameTaken.Connection.RemoteEndPoint.Address.ToString() == inc.SenderEndPoint.Address.ToString())
                {
                    //both name and IP address match, replace this player's connection
                    nameTaken.Connection.Disconnect(DisconnectReason.SessionTaken.ToString());
                    nameTaken.Connection = unauthClient.Connection;
                    nameTaken.InitClientSync(); //reinitialize sync ids because this is a new connection
                    unauthenticatedClients.Remove(unauthClient);
                    unauthClient = null;
                    return;
                }
                else
                {
                    //can't authorize this client
                    DisconnectUnauthClient(inc, unauthClient, DisconnectReason.NameTaken, "");
                    Log(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (name already taken)", ServerLog.MessageType.Error);
                    DebugConsole.NewMessage(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (name already taken)", Color.Red);
                    return;
                }
            }

            //new client
            Client newClient = new Client(clName, GetNewClientID());

            newClient.InitClientSync();
            newClient.Connection = unauthClient.Connection;
            newClient.SteamID    = unauthClient.SteamID;
            unauthenticatedClients.Remove(unauthClient);
            unauthClient = null;
            ConnectedClients.Add(newClient);

            var previousPlayer = previousPlayers.Find(p => p.MatchesClient(newClient));

            if (previousPlayer != null)
            {
                foreach (Client c in previousPlayer.KickVoters)
                {
                    if (!connectedClients.Contains(c))
                    {
                        continue;
                    }
                    newClient.AddKickVote(c);
                }
            }

            LastClientListUpdateID++;

            if (newClient.Connection == OwnerConnection)
            {
                newClient.GivePermission(ClientPermissions.All);
                newClient.PermittedConsoleCommands.AddRange(DebugConsole.Commands);

                GameMain.Server.UpdateClientPermissions(newClient);
                GameMain.Server.SendConsoleMessage("Granted all permissions to " + newClient.Name + ".", newClient);
            }

            GameMain.Server.SendChatMessage($"ServerMessage.JoinedServer~[client]={clName}", ChatMessageType.Server, null);
            serverSettings.ServerDetailsChanged = true;

            if (previousPlayer != null && previousPlayer.Name != newClient.Name)
            {
                GameMain.Server.SendChatMessage($"ServerMessage.PreviousClientName~[client]={clName}~[previousname]={previousPlayer.Name}", ChatMessageType.Server, null);
                previousPlayer.Name = newClient.Name;
            }

            var savedPermissions = serverSettings.ClientPermissions.Find(cp =>
                                                                         cp.SteamID > 0 ?
                                                                         cp.SteamID == newClient.SteamID :
                                                                         newClient.IPMatches(cp.IP));

            if (savedPermissions != null)
            {
                newClient.SetPermissions(savedPermissions.Permissions, savedPermissions.PermittedCommands);
            }
            else
            {
                var defaultPerms = PermissionPreset.List.Find(p => p.Name == "None");
                if (defaultPerms != null)
                {
                    newClient.SetPermissions(defaultPerms.Permissions, defaultPerms.PermittedCommands);
                }
                else
                {
                    newClient.SetPermissions(ClientPermissions.None, new List <DebugConsole.Command>());
                }
            }
        }
Пример #10
0
 /// <summary>
 /// Handling of entities collection change
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected virtual void EntitiesCollectionDirty(object sender, EventArgs e)
 {
     Md5HashData = null;
 }
Пример #11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="edataFile"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public virtual byte[] Write(EdataFile edataFile, CancellationToken token)
        {
            //Cancel if requested;
            token.ThrowIfCancellationRequested();

            var edataContentFiles = edataFile.ContentFiles.OfType <EdataContentFile>();

            using (MemoryStream edataStream = new MemoryStream())
            {
                if (!AnyContentFileExceedsAvailableSpace(edataFile) &&
                    !edataFile.HasContentFilesCollectionChanged)
                {
                    var header = edataFile.Header;

                    var  dictRoot   = CreateDictionaryEntries(edataContentFiles);
                    uint dictOffset = header.DictOffset;
                    uint dictLength = ComputeDictionaryLength(dictRoot);
                    uint dictEnd    = dictOffset + dictLength;

                    //Clear the old part of file up to content.
                    WritePadding(edataStream, 0, header.FileOffset);

                    WriteLoadedContentByReplace(edataStream, edataContentFiles, token);

                    AssignContentFilesInfoToDictEntries(edataContentFiles, dictRoot);

                    var dictWriteInfo = WriteDictionary(edataStream, dictRoot, dictOffset);

                    header.Checksum_V2 = Md5Hash.GetHash(dictWriteInfo.Checksum);
                    header.DictLength  = dictWriteInfo.Length;

                    WriteHeader(edataStream, header, 0);
                }
                else
                {
                    //W tym przypadku rozmieszczamy wszystko od zera wg wartości obliczonych.
                    var  dictRoot   = CreateDictionaryEntries(edataContentFiles);
                    uint dictOffset = GetDictionaryOffset();
                    uint dictLength = ComputeDictionaryLength(dictRoot);
                    uint dictEnd    = dictOffset + dictLength;

                    uint fileOffset = GetFileOffset(dictEnd);

                    WritePadding(edataStream, 0, fileOffset);

                    var contentWriteInfo = WriteLoadedContent(edataStream, edataContentFiles, fileOffset, token);

                    AssignContentFilesInfoToDictEntries(edataContentFiles, dictRoot);

                    var dictWriteInfo = WriteDictionary(edataStream, dictRoot, dictOffset);

                    var header = edataFile.Header;
                    header.Checksum_V2 = Md5Hash.GetHash(dictWriteInfo.Checksum);
                    header.DictOffset  = dictOffset;
                    header.DictLength  = dictWriteInfo.Length;
                    header.FileOffset  = fileOffset;
                    header.FileLenght  = contentWriteInfo.Length;

                    WriteHeader(edataStream, header, 0);
                }

                return(edataStream.ToArray());
            }
        }
Пример #12
0
 /// <summary>
 /// Handling of whole chunk blocks buffer change
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected virtual void BlockBufferChanged(object sender, ChunkDataProviderBufferChangedEventArgs e)
 {
     Md5HashData = null;
 }
Пример #13
0
 /// <summary>
 /// Gets md5 hash of the chunk data (blocks and entities)
 /// </summary>
 /// <returns></returns>
 public Md5Hash GetMd5Hash()
 {
     return(Md5HashData ?? (Md5HashData = Md5Hash.Calculate(GetBytesForHash())));
 }
        private string GetHeaderValue()
        {
            var value = $"security-key-{DateTime.Now.Day}";

            return(Md5Hash.CreateMD5(value));
        }
Пример #15
0
        public string GetEtag()
        {
            var serialized = JsonConvert.SerializeObject(this);

            return(Md5Hash.ForString(serialized)); // Quick and dirty way of getting a hash
        }
Пример #16
0
 /// <summary>
 /// 密码加密
 /// </summary>
 /// <param name="password"></param>
 /// <returns></returns>
 private string EncodePassword(string password)
 {
     return(Md5Hash.Md5(DESEncrypt.Encrypt(password.ToLower(),
                                           ConstParameters.MemLoginUserKey).ToLower(), 32).ToLower());
 }
Пример #17
0
        /// <summary>
        /// 处理注册
        /// </summary>
        /// <param name="message">账号+昵称+密码+头像+邮箱+验证码</param>
        public void DealRegister(User user, string message)
        {
            //账号+昵称+密码+头像+邮箱+验证码
            string[] msg     = message.Split(MessageTypes.NSP.ToCharArray());
            ILogger  ilogger = ILogger.GetInstance();

            //邮箱和注册码匹配
            if (user.userRMail == msg[4] && user.regNum == msg[5])
            {
                //进行注册
                ilogger.Logger(string.Format("用户:{0}--->开始注册...", user.client.Client.RemoteEndPoint));
                Console.WriteLine("用户:{0}--->开始注册...", user.client.Client.RemoteEndPoint);

                int result = 0;

                try
                {
                    result = Access.CardIsExist(msg[0]);
                }
                catch (Exception ex)
                {
                    ilogger.Logger(string.Format("用户:{0}--->注册时查询账号异常:{1}", user.client.Client.RemoteEndPoint, ex.Message));
                    Console.WriteLine("用户:{0}--->注册时查询账号异常:{1}", user.client.Client.RemoteEndPoint, ex.Message);
                    SendMsg(user, MessageTypes.REG + MessageTypes.PSP + "0" + MessageTypes.PSP + "很抱歉,操作异常请重试!");

                    return;
                }

                //账号被注册
                if (result != 0)
                {
                    ilogger.Logger(string.Format("用户:{0}--->账号已被注册.", user.client.Client.RemoteEndPoint));
                    Console.WriteLine("用户:{0}--->账号已被注册.", user.client.Client.RemoteEndPoint);
                    SendMsg(user, MessageTypes.REG + MessageTypes.PSP + "0" + MessageTypes.PSP + "很抱歉,该账号已被注册!");

                    return;
                }

                try
                {
                    UserInfo userInfo = new UserInfo()
                    {
                        CardWord = msg[0], UserName = msg[1], PassWord = Md5Hash.GetMd5Hash(msg[2]), UserPicture = msg[3], UserMail = msg[4], RegTime = DateTime.Now
                    };
                    Access.InsertUser(userInfo);
                }
                catch (Exception ex)
                {
                    ilogger.Logger(string.Format("用户:{0}--->注册异常:{1}", user.client.Client.RemoteEndPoint, ex.Message));
                    Console.WriteLine("用户:{0}--->注册异常:{1}", user.client.Client.RemoteEndPoint, ex.Message);
                    SendMsg(user, MessageTypes.REG + MessageTypes.PSP + "0" + MessageTypes.PSP + "很抱歉,操作异常请重试!");

                    return;
                }

                ilogger.Logger(string.Format("用户:{0}--->注册成功...", user.client.Client.RemoteEndPoint));
                Console.WriteLine("用户:{0}--->注册成功...", user.client.Client.RemoteEndPoint);
                SendMsg(user, MessageTypes.REG + MessageTypes.PSP + "0" + MessageTypes.PSP + "恭喜您,注册成功!");

                return;
            }

            ilogger.Logger(string.Format("用户:{0}--->邮箱与注册码不匹配.", user.client.Client.RemoteEndPoint));
            Console.WriteLine("用户:{0}--->邮箱与注册码不匹配.", user.client.Client.RemoteEndPoint);
            SendMsg(user, MessageTypes.REG + MessageTypes.PSP + "0" + MessageTypes.PSP + "很抱歉,邮箱与注册码不匹配!");
        }
Пример #18
0
 public void SubmitForm(SysUser userEntity, SysUserLogOn userLogOnEntity, string userId)
 {
     using (var db = base.BeginTransaction())
     {
         try
         {
             if (!string.IsNullOrEmpty(userId))
             {
                 userEntity.Id = userId;
                 this.Update(userEntity);
             }
             else
             {
                 userLogOnEntity.Id            = userEntity.Id;
                 userLogOnEntity.UserId        = userEntity.Id;
                 userLogOnEntity.UserSecretkey = Md5Hash.Md5(Common.CreateNo(), 16).ToLower();
                 userLogOnEntity.UserPassword  = Md5Hash.Md5(DESEncrypt.Encrypt(Md5Hash.Md5(userLogOnEntity.UserPassword, 32).ToLower(), userLogOnEntity.UserSecretkey).ToLower(), 32).ToLower();
                 this.Insert(userEntity);
                 SysUserLogOnRespository.Insert(userLogOnEntity);
             }
             this.Commit();
         }
         catch (Exception ex)
         {
             this.Rollback();
             Console.WriteLine(ex.ToString());
         }
     }
 }
        public string GetEtag()
        {
            var serialized = JsonConvert.SerializeObject(this);

            return(Md5Hash.ForString(serialized)); //hash ktory bude pouzity v ETag headery
        }
Пример #20
0
        private new void Update()
        {
            try
            {
                Status("Load update info...");
                // get update index
                var req = WebRequest.Create("http://update.utopiarealms.com/index.update");

                using (var response = req.GetResponse())
                    using (var stream = response.GetResponseStream())
                        using (var zs = new GZipStream(stream, CompressionMode.Decompress))
                        {
                            var reader = new BinaryReader(zs);
                            _updateFile = new UpdateFile();
                            _updateFile.Load(reader);
                        }

                var indexPath = Path.Combine(_basePath, "update.index");

                UpdateFile previousUpdate = null;

                if (File.Exists(indexPath))
                {
                    using (var fs = File.OpenRead(indexPath))
                        using (var zs = new GZipStream(fs, CompressionMode.Decompress))
                        {
                            var reader = new BinaryReader(zs);
                            previousUpdate = new UpdateFile();
                            previousUpdate.Load(reader);
                        }
                }

                Status("Check files to update...");

                var files = new List <UpdateFileInfo>();

                foreach (var file in _updateFile.Files)
                {
                    var filePath = Path.Combine(_basePath, file.SystemPath);

                    if (File.Exists(filePath))
                    {
                        using (var fs = File.OpenRead(filePath))
                        {
                            var hash = Md5Hash.Calculate(fs);
                            if (hash.ToString() == file.Md5Hash && fs.Length == file.Length)
                            {
                                continue;
                            }
                        }
                    }

                    files.Add(file);
                }

                float index = 0f;
                foreach (var file in files)
                {
                    Status("Updating " + file.SystemPath, index / files.Count);
                    try
                    {
                        var filePath = Path.Combine(_basePath, file.SystemPath);
                        if (!Directory.Exists(Path.GetDirectoryName(filePath)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(filePath));
                        }

                        var fileReq = WebRequest.Create(file.DownloadUri);

                        using (var response = fileReq.GetResponse())
                            using (var fs = File.OpenWrite(filePath))
                            {
                                fs.SetLength(0);
                                using (var stream = response.GetResponseStream())
                                {
                                    if (file.Compressed)
                                    {
                                        using (var zip = new GZipStream(stream, CompressionMode.Decompress))
                                        {
                                            zip.CopyTo(fs);
                                        }
                                    }
                                    else
                                    {
                                        stream.CopyTo(fs);
                                    }
                                }
                            }
                    }
                    catch (Exception x)
                    {
                        MessageBox.Show(x.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Application.Exit();
                    }

                    index++;
                }

                // delete removed files
                if (previousUpdate != null)
                {
                    foreach (var removedFile in _updateFile.GetRemovedFiles(previousUpdate))
                    {
                        var fullPath = Path.Combine(_basePath, removedFile);
                        if (File.Exists(fullPath))
                        {
                            File.Delete(fullPath);
                        }
                    }
                }

                if (File.Exists(indexPath))
                {
                    File.Delete(indexPath);
                }

                // save index for future update
                using (var fs = File.OpenWrite(indexPath))
                    using (var zs = new GZipStream(fs, CompressionMode.Compress))
                    {
                        var writer = new BinaryWriter(zs);
                        _updateFile.Save(writer);
                    }

                // save current token
                File.WriteAllText(Path.Combine(_basePath, "update.token"), _updateFile.UpdateToken);

                StartGame();
            }
            catch (Exception x)
            {
                MessageBox.Show(string.Format("Exception occured: {0}\nPlease post this information to the forum at http://utopiarealms.com", x.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public void ReadMessage(IReadMessage inc)
        {
            System.Diagnostics.Debug.Assert(!activeTransfers.Any(t =>
                                                                 t.Status == FileTransferStatus.Error ||
                                                                 t.Status == FileTransferStatus.Canceled ||
                                                                 t.Status == FileTransferStatus.Finished), "List of active file transfers contains entires that should have been removed");

            byte transferMessageType = inc.ReadByte();

            switch (transferMessageType)
            {
            case (byte)FileTransferMessageType.Initiate:
            {
                byte transferId       = inc.ReadByte();
                var  existingTransfer = activeTransfers.Find(t => t.ID == transferId);
                finishedTransfers.RemoveAll(t => t.First == transferId);
                byte fileType = inc.ReadByte();
                //ushort chunkLen = inc.ReadUInt16();
                int    fileSize = inc.ReadInt32();
                string fileName = inc.ReadString();

                if (existingTransfer != null)
                {
                    if (fileType != (byte)existingTransfer.FileType ||
                        fileSize != existingTransfer.FileSize ||
                        fileName != existingTransfer.FileName)
                    {
                        GameMain.Client.CancelFileTransfer(transferId);
                        DebugConsole.ThrowError("File transfer error: file transfer initiated with an ID that's already in use");
                    }
                    else         //resend acknowledgement packet
                    {
                        GameMain.Client.UpdateFileTransfer(transferId, 0);
                    }
                    return;
                }

                if (!ValidateInitialData(fileType, fileName, fileSize, out string errorMsg))
                {
                    GameMain.Client.CancelFileTransfer(transferId);
                    DebugConsole.ThrowError("File transfer failed (" + errorMsg + ")");
                    return;
                }

                if (GameSettings.VerboseLogging)
                {
                    DebugConsole.Log("Received file transfer initiation message: ");
                    DebugConsole.Log("  File: " + fileName);
                    DebugConsole.Log("  Size: " + fileSize);
                    DebugConsole.Log("  ID: " + transferId);
                }

                string downloadFolder = downloadFolders[(FileTransferType)fileType];
                if (!Directory.Exists(downloadFolder))
                {
                    try
                    {
                        Directory.CreateDirectory(downloadFolder);
                    }
                    catch (Exception e)
                    {
                        DebugConsole.ThrowError("Could not start a file transfer: failed to create the folder \"" + downloadFolder + "\".", e);
                        return;
                    }
                }

                FileTransferIn newTransfer = new FileTransferIn(inc.Sender, Path.Combine(downloadFolder, fileName), (FileTransferType)fileType)
                {
                    ID       = transferId,
                    Status   = FileTransferStatus.Receiving,
                    FileSize = fileSize
                };

                int maxRetries = 4;
                for (int i = 0; i <= maxRetries; i++)
                {
                    try
                    {
                        newTransfer.OpenStream();
                    }
                    catch (System.IO.IOException e)
                    {
                        if (i < maxRetries)
                        {
                            DebugConsole.NewMessage("Failed to initiate a file transfer {" + e.Message + "}, retrying in 250 ms...", Color.Red);
                            Thread.Sleep(250);
                        }
                        else
                        {
                            DebugConsole.NewMessage("Failed to initiate a file transfer {" + e.Message + "}", Color.Red);
                            GameMain.Client.CancelFileTransfer(transferId);
                            newTransfer.Status = FileTransferStatus.Error;
                            OnTransferFailed(newTransfer);
                            return;
                        }
                    }
                }
                activeTransfers.Add(newTransfer);

                GameMain.Client.UpdateFileTransfer(transferId, 0);         //send acknowledgement packet
            }
            break;

            case (byte)FileTransferMessageType.TransferOnSameMachine:
            {
                byte   transferId = inc.ReadByte();
                byte   fileType   = inc.ReadByte();
                string filePath   = inc.ReadString();

                if (GameSettings.VerboseLogging)
                {
                    DebugConsole.Log("Received file transfer message on the same machine: ");
                    DebugConsole.Log("  File: " + filePath);
                    DebugConsole.Log("  ID: " + transferId);
                }

                if (!File.Exists(filePath))
                {
                    DebugConsole.ThrowError("File transfer on the same machine failed, file \"" + filePath + "\" not found.");
                    GameMain.Client.CancelFileTransfer(transferId);
                    return;
                }

                FileTransferIn directTransfer = new FileTransferIn(inc.Sender, filePath, (FileTransferType)fileType)
                {
                    ID       = transferId,
                    Status   = FileTransferStatus.Finished,
                    FileSize = 0
                };

                Md5Hash.RemoveFromCache(directTransfer.FilePath);
                OnFinished(directTransfer);
            }
            break;

            case (byte)FileTransferMessageType.Data:
            {
                byte transferId = inc.ReadByte();

                var activeTransfer = activeTransfers.Find(t => t.Connection == inc.Sender && t.ID == transferId);
                if (activeTransfer == null)
                {
                    //it's possible for the server to send some extra data
                    //before it acknowledges that the download is finished,
                    //so let's suppress the error message in that case
                    finishedTransfers.RemoveAll(t => t.Second + 5.0 < Timing.TotalTime);
                    if (!finishedTransfers.Any(t => t.First == transferId))
                    {
                        GameMain.Client.CancelFileTransfer(transferId);
                        DebugConsole.ThrowError("File transfer error: received data without a transfer initiation message");
                    }
                    return;
                }

                int offset      = inc.ReadInt32();
                int bytesToRead = inc.ReadUInt16();
                if (offset != activeTransfer.Received)
                {
                    DebugConsole.Log($"Received {bytesToRead} bytes of the file {activeTransfer.FileName} (ignoring: offset {offset}, waiting for {activeTransfer.Received})");
                    GameMain.Client.UpdateFileTransfer(activeTransfer.ID, activeTransfer.Received);
                    return;
                }

                if (activeTransfer.Received + bytesToRead > activeTransfer.FileSize)
                {
                    GameMain.Client.CancelFileTransfer(transferId);
                    DebugConsole.ThrowError("File transfer error: Received more data than expected (total received: " + activeTransfer.Received +
                                            ", msg received: " + (inc.LengthBytes - inc.BytePosition) +
                                            ", msg length: " + inc.LengthBytes +
                                            ", msg read: " + inc.BytePosition +
                                            ", filesize: " + activeTransfer.FileSize);
                    activeTransfer.Status = FileTransferStatus.Error;
                    StopTransfer(activeTransfer);
                    return;
                }

                try
                {
                    activeTransfer.ReadBytes(inc, bytesToRead);
                }
                catch (Exception e)
                {
                    GameMain.Client.CancelFileTransfer(transferId);
                    DebugConsole.ThrowError("File transfer error: " + e.Message);
                    activeTransfer.Status = FileTransferStatus.Error;
                    StopTransfer(activeTransfer, true);
                    return;
                }

                GameMain.Client.UpdateFileTransfer(activeTransfer.ID, activeTransfer.Received, reliable: activeTransfer.Status == FileTransferStatus.Finished);
                if (activeTransfer.Status == FileTransferStatus.Finished)
                {
                    activeTransfer.Dispose();

                    if (ValidateReceivedData(activeTransfer, out string errorMessage))
                    {
                        finishedTransfers.Add(new Pair <int, double>(transferId, Timing.TotalTime));
                        StopTransfer(activeTransfer);
                        Md5Hash.RemoveFromCache(activeTransfer.FilePath);
                        OnFinished(activeTransfer);
                    }
                    else
                    {
                        new GUIMessageBox("File transfer aborted", errorMessage);

                        activeTransfer.Status = FileTransferStatus.Error;
                        StopTransfer(activeTransfer, true);
                    }
                }
            }
            break;

            case (byte)FileTransferMessageType.Cancel:
            {
                byte transferId       = inc.ReadByte();
                var  matchingTransfer = activeTransfers.Find(t => t.Connection == inc.Sender && t.ID == transferId);
                if (matchingTransfer != null)
                {
                    new GUIMessageBox("File transfer cancelled", "The server has cancelled the transfer of the file \"" + matchingTransfer.FileName + "\".");
                    StopTransfer(matchingTransfer);
                }
                break;
            }
            }
        }
Пример #22
0
 protected string GetPackageStr(ClientContentPackage contentPackage)
 {
     return("\"" + contentPackage.Name + "\" (hash " + Md5Hash.GetShortHash(contentPackage.Hash) + ")");
 }
Пример #23
0
        public async Task <IActionResult> CheckLogin(string username, string password, string code)
        {
            SysLog logEntity = new SysLog();

            logEntity.ModuleName = "系统登录";
            logEntity.Type       = DbLogType.Login.ToString();
            try
            {
                if (WebHelper.GetSession(ConstParameters.VerifyCodeKeyName).IsEmpty() ||
                    Md5Hash.Md5(code.ToLower(), 16) != WebHelper.GetSession(ConstParameters.VerifyCodeKeyName).ToString())
                {
                    throw new Exception("验证码错误,请重新输入");
                }

                var userEntity = _SysUserService.CheckLogin(username, password);
                if (userEntity != null)
                {
                    //登录已重写
                    var          identity = new ClaimsIdentity(SysManageAuthAttribute.SysManageAuthScheme); // 指定身份认证类型
                    List <Claim> claims   = new List <Claim>()
                    {
                        new Claim(ClaimTypes.Sid, userEntity.Id),       // 用户Id
                        new Claim(ClaimTypes.Name, userEntity.Account), // 用户账号
                        new Claim(ClaimTypes.GivenName, userEntity.RealName),
                        new Claim(ClaimTypes.PrimarySid, userEntity.OrganizeId),
                        new Claim(ClaimTypes.PrimaryGroupSid, userEntity.DepartmentId),
                        new Claim(ClaimTypes.Role, userEntity.RoleId ?? ""),
                        new Claim(ClaimTypes.Dns, Net.Ip ?? "")
                    };
                    var isSystem = false;
                    if (userEntity.Account == "admin")
                    {
                        isSystem = true;
                    }
                    identity.AddClaims(claims);
                    identity.AddClaim(new Claim(ClaimTypes.IsPersistent, isSystem.ToString()));
                    var principal = new ClaimsPrincipal(identity);
                    //过期时间20分钟
                    //var authProperty = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTime.UtcNow.AddMinutes(20) };
                    await HttpContext.SignInAsync(SysManageAuthAttribute.SysManageAuthScheme,
                                                  principal);

                    logEntity.Account     = userEntity.Account;
                    logEntity.NickName    = userEntity.RealName;
                    logEntity.Result      = true;
                    logEntity.Description = "登录成功";
                    _ISysLogService.WriteSysLog(logEntity);
                }
                return(Content(new AjaxResult {
                    state = ResultType.success.ToString(), message = "登录成功。"
                }.ToJson()));
            }
            catch (Exception ex)
            {
                logEntity.Account     = username;
                logEntity.NickName    = username;
                logEntity.Result      = false;
                logEntity.Description = "登录失败," + ex.Message;
                _ISysLogService.WriteSysLog(logEntity);
                return(Content(new AjaxResult {
                    state = ResultType.error.ToString(), message = ex.Message
                }.ToJson()));
            }
        }
Пример #24
0
        public string GetEtag()
        {
            string serialized = JsonSerializer.Serialize(this);

            return(Md5Hash.ForString(serialized));
        }
Пример #25
0
        public string GetEtag()
        {
            var serialized = JsonConvert.SerializeObject(this);

            return(Md5Hash.ForString(serialized));
        }
Пример #26
0
 protected string GetPackageStr(ServerContentPackage contentPackage)
 {
     return($"\"{contentPackage.Name}\" (hash {Md5Hash.GetShortHash(contentPackage.Hash)})");
 }