Пример #1
0
        void CheckInTimer_Tick(object sender, System.EventArgs e)
        {
            DebugDetector.AssertCheckRunning();

            MainForm.SetStatusBar("Checking in...");

            var message = string.Empty;
            var ticket  = string.Empty;
            var data    = SessionNegotiator.GenerateCheckInData();
            var result  = SessionNegotiator.CheckIn(data, ref message, ref ticket);

            if (result != CheckInStatus.Ok)
            {
                //Close Allegiance
                AllegianceLoader.ExitAllegiance();

                //Unlock form
                this.Enabled = true;

                MainForm.SetStatusBar(message);
            }
            else
            {
                MainForm.SetStatusBar(string.Format("Checked in at {0:h:mm tt}.", DateTime.Now));
            }

            GC.Collect(); //Now is a decent time to force garbage collection
        }
Пример #2
0
        public LoginForm()
        {
            DebugDetector.AssertCheckRunning();

            InitializeComponent();

            StatusTimer          = new Timer();
            StatusTimer.Interval = StatusClearInterval;
            StatusTimer.Tick    += new EventHandler(StatusTimer_Tick);

            FormInstance = this;
        }
Пример #3
0
        public MainForm(CheckInStatus launcherSignInStatus)
        {
            _launcherSignInStatus = launcherSignInStatus;

            DebugDetector.AssertCheckRunning();

            InitializeComponent();
            FormInstance = this;

            StatusTimer          = new Timer();
            StatusTimer.Interval = StatusClearInterval;
            StatusTimer.Tick    += new EventHandler(StatusTimer_Tick);

            //Bind Events
            _messageListControl.OpenClick     += new EventHandler(_messageListControl_OpenClick);
            _callsignControl.CreateClick      += new EventHandler(_callsignControl_CreateClick);
            _callsignControl.CallsignsLoaded  += new TaskEventHandler <List <Callsign> >(_callsignControl_CallsignsLoaded);
            _playControl.ManageCallsignsClick += new PlayControl.ManageCallsignsClickHandler(_playControl_ManageCallsignsClick);
            _playControl.AllegianceExited     += new PlayControl.AllegianceExitedHandler(_playControl_AllegianceExited);
            _playControl.RequestUpdateCheck   += new PlayControl.RequestUpdateCheckHandler(_playControl_RequestUpdateCheck);
            _playControl.ReloadCallsigns      += new PlayControl.ReloadCallsignsHandler(_playControl_ReloadCallsigns);

            _messageListControl.MessageReceived += new EventHandler(_messageListControl_MessageReceived);

            //Load Preferences from datastore
            LoadPreferences();

            // Reset the cached callsign list so that it will reload from the server when the app is first started,
            // or if the user re-logs in.
            //DataStore.Callsigns = null;

            //Load form data
            _callsignControl.LoadCallsigns(true);
            _messageListControl.LoadMessages();

            //Check for polls
            _pollDisplayControl.PollComplete += new EventHandler(_pollDisplayControl_PollComplete);
            CheckPolls();

            //Auto-Login
            if (DataStore.Preferences.AutoLogin)
            {
                Autologin();
            }
        }
Пример #4
0
        private static ClientService.ClientService Initialize()
        {
            DebugDetector.AssertCheckRunning();

            //For testing, we're accepting untrusted server certificates
            ServicePointManager.ServerCertificateValidationCallback
                = new RemoteCertificateValidationCallback(delegate(object sender,
                                                                   X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
            {
                return(true);
            });

            ClientService.ClientService service = new ClientService.ClientService();
            service.Timeout = _timeout;
            service.Url     = AllegianceRegistry.ClientService;

            return(service);
        }
Пример #5
0
        private static void Initialize()
        {
            try
            {
                //Check if a debugger is attached
                if (DebugDetector.Detect())
                {
                    Log.Write("Debugging CSS is prohibited.");
                    return;
                }

                //See if the client has recently been updated
                if (AutoUpdate.CheckTemporaryProcess())
                {
                    return;
                }

                //Ticket #46 - Prevent multiple instances of the launcher
                var runningProcesses = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName);
                int matchCounter     = 0;
                foreach (var runningProcess in runningProcesses)
                {
                    if (runningProcess.MainModule.FileName.Equals(Process.GetCurrentProcess().MainModule.FileName) == true)
                    {
                        matchCounter++;
                    }
                }

                if (matchCounter > 1)
                {
                    MessageBox.Show("Only one instance of " + Process.GetCurrentProcess().MainModule.FileName + " can be run at a time. Please close other versions of the ACSS Launcher and try again.", "ACSS Launcher Already Running", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    return;
                }

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                using (ServiceHandler.Service)
                {
                    UpdateCheckForm updateCheckForm = new UpdateCheckForm();

                    if (updateCheckForm.HasPendingUpdates == true)
                    {
                        if (updateCheckForm.ShowDialog() != DialogResult.OK)
                        {
                            return;
                        }
                    }

                    // If you need to upgrade things on the end users system during an auto-update push, put them in here.
                    string returnMessage;
                    if (Install.Upgrade.PerformUpgradeTasks(out returnMessage) == false)
                    {
                        MessageBox.Show(returnMessage, "Upgrade canceled.", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                        return;
                    }



                    bool showLoginDialog = false;

                    //Check if the credentials are already stored
                    if (ServiceHandler.CheckLogin() == true)
                    {
                        var launcherStartupProgress = new LauncherStartupProgress();
                        launcherStartupProgress.TopMost = true;

                        var launcherStartupProgressResult = launcherStartupProgress.ShowDialog();

                        if (launcherStartupProgressResult == DialogResult.OK)
                        {
                            StartMainForm();
                        }

                        //else if (launcherStartupProgressResult == DialogResult.Abort)
                        //	return;

                        else
                        {
                            showLoginDialog = true;
                        }
                    }

                    if (ServiceHandler.CheckLogin() == false || showLoginDialog == true)
                    {
                        //Create Login prompt
                        using (var loginForm = new LoginForm())
                        {
                            if (loginForm.ShowDialog() != DialogResult.OK)
                            {
                                return;
                            }

                            var launcherStartupProgress = new LauncherStartupProgress();
                            launcherStartupProgress.TopMost = true;

                            if (launcherStartupProgress.ShowDialog() != DialogResult.OK)
                            {
                                return;
                            }

                            StartMainForm();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                File.WriteAllText("ExceptionLog.txt", ex.ToString());
                throw;
            }
        }
        public static void StartAllegiance(string ticket, LobbyType lobbyType, string alias, TaskDelegate onCompleteDelegate)
        {
            DebugDetector.AssertCheckRunning();

            TaskHandler.RunTask(delegate(object p)
            {
                var param         = p as object[];
                var sessionTicket = param[0] as string;
                var signal        = param[1] as TaskDelegate;
                var succeeded     = false;

                try
                {
                    AllegianceRegistry.OutputDebugString = DataStore.Preferences.DebugLog;
                    AllegianceRegistry.LogToFile         = DataStore.Preferences.DebugLog;
                    AllegianceRegistry.LogChat           = DataStore.Preferences.LogChat;

                    //Create commandline
                    var commandLine = new StringBuilder("-authenticated")
                                      .AppendFormat(" -callsign={0}", alias);

                    if (DataStore.Preferences.DebugLog)
                    {
                        commandLine.Append(" -debug");
                    }

                    if (DataStore.Preferences.LaunchWindowed)
                    {
                        commandLine.Append(" -windowed");
                    }

                    if (DataStore.Preferences.NoMovies)
                    {
                        commandLine.Append(" -nomovies");
                    }

                    //Start Allegiance
                    string lobbyPath = Path.Combine(AllegianceRegistry.LobbyPath, lobbyType.ToString());

                    string allegiancePath = Path.Combine(lobbyPath, "Allegiance.exe");

                    if (DataStore.Preferences.UseDX7Engine == true)
                    {
                        allegiancePath = Path.Combine(lobbyPath, "AllegianceDX7.exe");
                    }


#if DEBUG
                    if (String.IsNullOrEmpty(ConfigurationManager.AppSettings["AllegianceExeOverride"]) == false)
                    {
                        Log.Write("Allegiance path was overridden by configuration setting.");
                        allegiancePath = ConfigurationManager.AppSettings["AllegianceExeOverride"];
                    }
#endif

                    Log.Write("Using: " + allegiancePath + " " + commandLine.ToString() + " to launch...");

                    ProcessHandler process = ProcessHandler.Start(allegiancePath, commandLine.ToString());

                    process.OnExiting += new EventHandler(process_OnExiting);

                    _allegianceProcess        = process;
                    _allegianceProcessMonitor = new ProcessMonitor(_allegianceProcess);

                    // If launching into a lobby, then relay the security token to the allegiance process.
                    if (lobbyType != LobbyType.None)
                    {
                        //Open Pipe
                        using (var reset = new ManualResetEvent(false))
                        {
                            TaskHandler.RunTask(delegate(object value)
                            {
                                var parameters          = value as object[];
                                var localProcessHandler = parameters[0] as ProcessHandler;
                                var localSessionTicket  = parameters[1] as String;
                                var localReset          = parameters[2] as ManualResetEvent;

                                using (var pipe = new Pipe(@"\\.\pipe\allegqueue"))
                                {
                                    pipe.Create();

                                    if (pipe.Connect())
                                    {
                                        Int64 memoryLocation = Int64.Parse(pipe.Read());

                                        localProcessHandler.WriteMemory(memoryLocation, localSessionTicket + (char)0x00 + Process.GetCurrentProcess().Id);

                                        localReset.Set();
                                    }
                                }
                            }, process, sessionTicket, reset);


                            //Wait X seconds, if allegiance does not retrieve the ticket, exit Allegiance.
                            if (!reset.WaitOne(PipeTimeout))
                            {
                                try
                                {
                                    process.ForceClose();

                                    //Connect to the pipe in order to close out the connector thread.
                                    using (var pipe = new Pipe(@"\\.\pipe\allegqueue"))
                                    {
                                        pipe.OpenExisting();
                                        pipe.Read();
                                    }
                                }
                                catch { }
                                finally
                                {
                                    throw new Exception("Allegiance did not respond within the time allotted.");
                                }
                            }

                            // The memory address was retrived from the pipe, write the ticket onto the target process.
                            //process.WriteMemory((Int64) memoryLocation, sessionTicket);
                        }
                    }

                    succeeded = true;
                }
                catch (Exception error)
                {
                    Log.Write(error);
                }
                finally
                {
                    signal(succeeded);
                }
            }, ticket, onCompleteDelegate);
        }
Пример #7
0
        /// <summary>
        /// Perform autoupdate, validate client, negotiate for new session
        /// </summary>
        public static void Login(string aliasInput, string lobbyName, TaskDelegate onCompleteDelegate)
        {
            TaskHandler.RunTask(delegate(object input) {
                DebugDetector.AssertCheckRunning();

                var parameters       = input as object[];
                var signal           = parameters[0] as TaskDelegate;
                var alias            = parameters[1] as string;
                var message          = string.Empty;
                var ticket           = string.Empty;
                var rank             = 0;
                CheckInStatus status = CheckInStatus.InvalidCredentials;

                try
                {
                    //Get available lobbies
                    MainForm.SetStatusBar("Checking lobby status...", 25);
                    var lobbies = ServiceHandler.Service.CheckAvailableLobbies();

                    //Get lobby
                    var lobby = GetLobbyByName(lobbies, lobbyName);

                    //Check auto-update - This is done by the play control/update check control now.
                    //MainForm.SetStatusBar("Checking for updates...", 25);

                    //PendingUpdates pendingUpdates = AutoUpdate.GetPendingUpdateQueues(ServiceHandler.Service);

                    //if (AutoUpdate.ProcessPendingUpdates(pendingUpdates, lobby, new AutoUpdate.AutoupdateProgressCallback(AutoupdateProgressUpdate)))
                    //    return;

                    //Log in, Display 'logging in' status to user
                    MainForm.SetStatusBar("Logging in...", 50);

                    var loginResult = ServiceHandler.Service.Login(new LoginData()
                    {
                        Alias            = alias,
                        LobbyId          = lobby.LobbyId,
                        LobbyIdSpecified = true
                    });

                    if (loginResult.StatusSpecified)
                    {
                        rank = loginResult.Rank;

                        switch (loginResult.Status)
                        {
                        case LoginStatus.Authenticated:

                            //Perform initial check in
                            MainForm.SetStatusBar("Validating Client...", 75);
                            status = ValidateLogin(loginResult.BlackboxData, ref message, ref ticket);

                            // Relog in after linking to pick up any alias changes.
                            if (status == CheckInStatus.AccountLinked)
                            {
                                loginResult = ServiceHandler.Service.Login(new LoginData()
                                {
                                    Alias            = alias,
                                    LobbyId          = lobby.LobbyId,
                                    LobbyIdSpecified = true
                                });
                            }

                            //Set up response
                            alias = loginResult.AcceptedAlias;

                            //if (loginResult.Rank <= 5)
                            //    alias += "(" + loginResult.Rank.ToString() + ")";

                            break;

                        case LoginStatus.AccountLocked:
                            message = "Account Locked";
                            break;

                        case LoginStatus.InvalidCredentials:
                            message = "Username or password was incorrect";
                            break;

                        case LoginStatus.PermissionDenied:
                            message = "Permission was denied to this lobby";
                            break;
                        }
                    }
                    else
                    {
                        message = "An unknown error occurred";
                    }

                    Log.Write(message);
                }
                catch (Exception error)
                {
                    message = "An error occurred";

                    Log.Write(error);
                }

                //Signal the calling thread
                signal(new object[] { status, message, alias, ticket, rank });
            }, onCompleteDelegate, aliasInput);
        }
Пример #8
0
        private void UpdateCheck_Load(object sender, EventArgs e)
        {
            _updateStatusLabel.Text = String.Empty;

            TaskHandler.RunTask(delegate(object input)
            {
                object[] parameters = input as object[];
                UpdateCheckControl formReference = parameters[0] as UpdateCheckControl;

                DebugDetector.AssertCheckRunning();

                if (HasPendingUpdates == true)
                {
                    var signal = new TaskDelegate(delegate(object data)
                    {
                        var updateCount = Convert.ToInt32(data);

                        if (MessageBox.Show(new Form()
                        {
                            TopMost = true
                        }, "Free Allegiance Updater has " + updateCount + " files to download.\nYou will not be able to play until these updates are installed.\nWould you like to do this now?", "New updates found!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                        {
                            MessageBox.Show(new Form()
                            {
                                TopMost = true
                            }, "Please restart the application when you are ready to apply updates.", "Update Canceled", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            Application.Exit();
                        }
                    });

                    if (this.InvokeRequired == true)
                    {
                        this.Invoke(signal, PendingUpdates.PendingUpdateCount);
                    }
                    else
                    {
                        signal(PendingUpdates.PendingUpdateCount);
                    }
                }
                else
                {
                    return;
                }

                //Get available lobbies
                UpdateProgress(String.Empty, "Checking lobby status...", 0);
                var lobbies = ServiceHandler.Service.CheckAvailableLobbies();

                foreach (var lobby in lobbies)
                {
                    if (formReference._abortUpdate == true)
                    {
                        break;
                    }

                    UpdateProgress(lobby.Name, "Checking lobby for updates.", 0);

                    if (AutoUpdate.ProcessPendingUpdates(PendingUpdates, lobby, new AutoUpdate.AutoupdateProgressCallback(UpdateProgress), this))
                    {
                        return;
                    }
                }

                TaskDelegate onUpdateCompleteHandler = delegate(object data)
                {
                    UpdateCheckControl updateCompleteFormReference = data as UpdateCheckControl;

                    if (AutoupdateComplete != null)
                    {
                        AutoupdateComplete(updateCompleteFormReference._abortUpdate);
                    }
                };

                if (formReference.InvokeRequired == true)
                {
                    formReference.Invoke(onUpdateCompleteHandler, formReference);
                }
                else
                {
                    onUpdateCompleteHandler(formReference);
                }
            }, this);
        }
Пример #9
0
 public void SetUp()
 {
     data     = new InMemoryRequestData();
     detector = new DebugDetector(data);
 }
        static void _watcher_Renamed(object sender, RenamedEventArgs e)
        {
            DebugDetector.AssertCheckRunning();

            AssertNotProtected(GetRelativePath(e.FullPath));
        }
        static void _watcher_Changed(object sender, FileSystemEventArgs e)
        {
            DebugDetector.AssertCheckRunning();

            AssertNotProtected(GetRelativePath(e.FullPath));
        }
Пример #12
0
        public static PendingUpdates GetPendingUpdateQueues(ClientService.ClientService service)
        {
            //Initialize Checksum class to use SHA1
            var encryption = new Encryption <SHA1>();

            PendingUpdates returnValue = new PendingUpdates();

            var lobbies = ServiceHandler.Service.CheckAvailableLobbies();

            foreach (LobbyResult lobby in lobbies)
            {
                //Get autoupdate files associated with lobby
                var results = service.CheckForUpdates(lobby.LobbyId, true);
                //var root        = AllegianceRegistry.EXEPath; //Allegiance root directory
                var    autoUpdate  = DataStore.Open("autoupdate.ds", "Ga46^#a042");
                string dataKey     = "Files_" + lobby.LobbyId;
                var    lastResults = autoUpdate[dataKey] as Dictionary <string, FindAutoUpdateFilesResult>;
                List <FindAutoUpdateFilesResult> updateQueue = new List <FindAutoUpdateFilesResult>();

                //Check files which need update
                foreach (var file in results.Files)
                {
                    DebugDetector.AssertCheckRunning();

                    string path;

                    if (string.Equals(file.Filename, GlobalSettings.ClientExecutableName) ||
                        string.Equals(file.Filename, GlobalSettings.ClientExecutablePDB))
                    {
                        path = Path.Combine(AllegianceRegistry.LobbyPath, file.Filename);
                    }
                    else
                    {
                        path = GetLobbyPath(lobby, file.Filename);
                    }

                    //Check that all files exist
                    if (!File.Exists(path))
                    {
                        Log.Write("File did not exist: " + path + ", will update.");
                        updateQueue.Add(file);
                        continue;
                    }

                    if (lastResults == null)
                    {
                        Log.Write("No prior autoupdate records, will updated: " + path);
                        updateQueue.Add(file);
                        continue;
                    }

                    //Check if we don't have a record of the file at all
                    if (!lastResults.ContainsKey(file.Filename))
                    {
                        Log.Write("No record of file in autoupdate history, will update: " + path);
                        updateQueue.Add(file);
                        continue;
                    }

                    //Check that all file versions match
                    if (lastResults.ContainsKey(file.Filename) &&
                        (file.CurrentVersion != lastResults[file.Filename].CurrentVersion))
                    {
                        Log.Write("File version mismatch, will update: " + file.Filename + ", server version: " + file.CurrentVersion + ", local version: " + lastResults[file.Filename].CurrentVersion);

                        updateQueue.Add(file);
                        continue;
                    }

                    //Compare hashes with all protected files to those on-disk
                    if (file.IsProtected)
                    {
                        var checksum = encryption.Calculate(path);
                        if (!string.Equals(file.ValidChecksum, checksum))
                        {
                            Log.Write("File checksum mismatch, will update: " + path + ", server checksum: " + file.ValidChecksum + ", local checksum: " + checksum);

                            updateQueue.Add(file);
                        }
                    }
                }

                returnValue.AutoUpdateBaseAddress.Add(lobby.LobbyId, results.AutoUpdateBaseAddress);
                returnValue.AllFilesInUpdatePackage.Add(lobby.LobbyId, results.Files);
                returnValue.PendingUpdateList.Add(lobby.LobbyId, updateQueue);
            }

            return(returnValue);
        }
Пример #13
0
        public static List <FindAutoUpdateFilesResult> ProcessPendingUpdates(LobbyResult lobby, AutoUpdateResult results)
        {
            //Initialize Checksum class to use SHA1
            var encryption = new Encryption <SHA1>();

            //var root        = AllegianceRegistry.EXEPath; //Allegiance root directory
            var    autoUpdate  = DataStore.Open("autoupdate.ds", "Ga46^#a042");
            string dataKey     = "Files_" + lobby.LobbyId;
            var    lastResults = autoUpdate[dataKey] as Dictionary <string, FindAutoUpdateFilesResult>;
            List <FindAutoUpdateFilesResult> updateQueue = new List <FindAutoUpdateFilesResult>();

            //Check files which need update
            foreach (var file in results.Files)
            {
                DebugDetector.AssertCheckRunning();

                // You can put this in if you are testing the launcher with the production CSS server.
                // Turn off file protection on the launcher on the CSS server's Auto Update version of the launcher,
                // then drop the debug version of the launcher into your local game directory. Then you can
                // launch the launcher from the debugger and work with it.
//#if DEBUG
//                if (file.Filename.EndsWith("Launcher.exe", StringComparison.InvariantCultureIgnoreCase) == true
//                    || file.Filename.EndsWith("Launcher.pdb", StringComparison.InvariantCultureIgnoreCase) == true)
//                    continue;
//#endif

                string path;

                if (string.Equals(file.Filename, GlobalSettings.ClientExecutableName) ||
                    string.Equals(file.Filename, GlobalSettings.ClientExecutablePDB))
                {
                    path = Path.Combine(AllegianceRegistry.LobbyPath, file.Filename);
                }
                else
                {
                    path = GetLobbyPath(lobby, file.Filename);
                }

                //Check that all files exist
                if (!File.Exists(path))
                {
                    Log.Write("File did not exist: " + path + ", will update.");
                    updateQueue.Add(file);
                    continue;
                }

                //Check that all file versions match
                if (lastResults != null && lastResults.ContainsKey(file.Filename) &&
                    (file.CurrentVersion != lastResults[file.Filename].CurrentVersion))
                {
                    Log.Write("File version mismatch, will update: " + file.Filename + ", server version: " + file.CurrentVersion + ", local version: " + lastResults[file.Filename].CurrentVersion);

                    updateQueue.Add(file);
                    continue;
                }

                // Test for checksum match, and if they don't replace the file if:
                // * This is the first time AutoUpdate has run for this installation.
                // * This is the first time this file has been seen by AutoUpdate
                // * The file has the protected flag turned on.
                var checksum = encryption.Calculate(path);
                if (!string.Equals(file.ValidChecksum, checksum))
                {
                    // If there haven't been any updates at all, and the checksums don't match, then overwrite the unknown file. (old installation / left over files from a previous uninstall)
                    if (lastResults == null)
                    {
                        Log.Write("No prior autoupdate records, will updated: " + path);
                        updateQueue.Add(file);
                        continue;
                    }

                    // If there wasn't a prior update applied for the file, and the checksums don't match, then overwrite the unknown file. (An older file is on disk, and was re-added to the auto update system)
                    if (!lastResults.ContainsKey(file.Filename))
                    {
                        Log.Write("No record of file in autoupdate history, will update: " + path);
                        updateQueue.Add(file);
                        continue;
                    }

                    // If the file was changed on the server, but not modified by the user, then update.
                    if (lastResults[file.Filename].DateModified == file.DateModified)
                    {
                        Log.Write("file was not user modified, and a change was detected from AU, will update: " + path);
                        updateQueue.Add(file);
                        continue;
                    }

                    // If the file is protected and the hashes don't match, then update.
                    if (file.IsProtected)
                    {
                        Log.Write("File checksum mismatch, will update: " + path + ", server checksum: " + file.ValidChecksum + ", local checksum: " + checksum);
                        updateQueue.Add(file);
                        continue;
                    }
                }
            }

            return(updateQueue);
        }