Exemplo n.º 1
0
        private static BroadcastScheduler InitScheduler(Settings settins, IBroadcastDatabase db, FileStore store, Playback playback)
        {
            BroadcastScheduler scheduler;

            try
            {
                scheduler = new BroadcastScheduler(db, store, playback, (int)settins.SCHEDULER_CHECK_INTERVAL);
            }
            catch
            {
                ProgramOutput.Error("Cannot initialize scheduler. Please check the scheduler parameters in config file.");
                return(null);
            }
            MasterContainer.AddService <BroadcastScheduler>(scheduler);

            return(scheduler);
        }
Exemplo n.º 2
0
        private static IAuthorizator InitAuthorizator(Settings settings)
        {
            // Init LDAP authorizator
            var authorizator = InitLdap(settings, delegate(LdapCredentials creds)
            {
#if DEBUG
                var auth = new DummyAuthorizator();
#else
                var auth = new LdapAuthorizator(creds);
                auth.Connect();
#endif

                return(auth);
            });

            var authorizatorCache = new AuthorizatorCache(authorizator, (int)settings.SECURITY_CACHE_EXPIRATION);

            MasterContainer.AddService <IAuthorizator>(authorizatorCache);

            // Load LDAP permission binding from def file
            var permissionCfgFile = Properties.Settings.Default.LDAP_PERMISSION_DEF_FILE;

            string[] permissionCfg;
            try
            {
                permissionCfg = File.ReadAllLines(permissionCfgFile);
            }
            catch (Exception ex)
            {
                ProgramOutput.Error("Cannot process LDAP permission binding file {0}, because of following reason:\r\n{1}", permissionCfgFile, ex.Message);
                return(null);
            }
            try
            {
                PermissionAttributeEditor.AddAttribFromConfig(permissionCfg, LdapAuthorizator.LDAP_GROUP_ATTRIBUTE,
                                                              (groupName) => groupName.ToString());
            }
            catch
            {
                ProgramOutput.Error("Cannot process LDAP permission binding file {0}. Invalid syntax.");
                return(null);
            }
            ProgramOutput.Error("Authorizator initialized, LDAP connection to {0} up.", authorizator.ConnectedServer);

            return(authorizatorCache);
        }
Exemplo n.º 3
0
        public void EndGameScoring_ThreePlayerScore_DisplayWinner()
        {
            Player[] players = new Player[3];

            players[0] = new Player("Will", false, new Caravan(1, 3, 0, 1));

            players[0].AcquiredOrder.Add(new Order(20, new Caravan(0, 0, 0, 5)));
            players[0].AcquiredOrder.Add(new Order(19, new Caravan(0, 0, 1, 4)));
            players[0].AcquiredOrder.Add(new Order(16, new Caravan(0, 0, 4, 1)));
            players[0].AcquiredOrder.Add(new Order(15, new Caravan(2, 2, 0, 2)));
            players[0].AcquiredOrder.Add(new Order(14, new Caravan(0, 1, 1, 2)));

            players[0].ExtraPoints.Add(0);
            players[0].ExtraPoints.Add(1);
            players[0].ExtraPoints.Add(3);
            players[0].ExtraPoints.Add(0);
            players[0].ExtraPoints.Add(1);

            players[1] = new Player("Ben", false, new Caravan(0, 2, 2, 2));

            players[1].AcquiredOrder.Add(new Order(20, new Caravan(1, 0, 2, 3)));
            players[1].AcquiredOrder.Add(new Order(18, new Caravan(1, 1, 3, 1)));
            players[1].AcquiredOrder.Add(new Order(17, new Caravan(2, 0, 2, 2)));
            players[1].AcquiredOrder.Add(new Order(16, new Caravan(1, 3, 1, 1)));

            players[1].ExtraPoints.Add(1);
            players[1].ExtraPoints.Add(1);
            players[1].ExtraPoints.Add(1);
            players[1].ExtraPoints.Add(0);

            players[2] = new Player("Ben", false, new Caravan(5, 0, 0, 0));

            players[2].AcquiredOrder.Add(new Order(15, new Caravan(2, 2, 0, 2)));
            players[2].AcquiredOrder.Add(new Order(12, new Caravan(1, 1, 1, 1)));
            players[2].AcquiredOrder.Add(new Order(13, new Caravan(2, 2, 2, 0)));

            players[2].ExtraPoints.Add(3);
            players[2].ExtraPoints.Add(1);
            players[2].ExtraPoints.Add(0);

            Assert.Equal(93, ProgramOutput.EndGameScoring(players));
        }
Exemplo n.º 4
0
        private static IAuthenticator InitAuthenticator(Settings settings)
        {
            var authenticator = InitLdap(settings, delegate(LdapCredentials creds)
            {
#if DEBUG
                var auth = new DummyAuthenticator();
#else
                var auth = new LdapAuthenticator(creds);
                auth.Connect();
#endif

                return(auth);
            });
            var authenticatorCache = new AuthenticatorCache(authenticator, (int)settings.SECURITY_CACHE_EXPIRATION);

            MasterContainer.AddService <IAuthenticator>(authenticatorCache);
            ProgramOutput.Info("Authenticator initialized, LDAP connection to {0} up.", authenticator.ConnectedServer);

            return(authenticatorCache);
        }
Exemplo n.º 5
0
        private static T InitLdap <T>(Settings settings, Func <LdapCredentials, T> init) where T : class
        {
            var creds = new LdapCredentials(settings.LDAP_USERNAME, settings.LDAP_PASSWORD, settings.LDAP_DOMAIN, settings.LDAP_OU);

            try
            {
                return(init(creds));
            }
            catch (System.DirectoryServices.AccountManagement.PrincipalServerDownException ex)
            {
                ProgramOutput.Error("LDAP server could not be contacted. Please ensure that machine DNS settings and DNS server is propely configured to reach domain controller. Also make sure that server is on the network.", ex);
                return(null);
            }
            catch (System.Security.Authentication.AuthenticationException ex)
            {
                ProgramOutput.Error("Connection to LDAP server failed, because of invalid credentials. Please check config file.", ex);
                return(null);
            }
            catch (Exception ex)
            {
                ProgramOutput.Error("Cannot init LDAP connection.", ex);
                return(null);
            }
        }
Exemplo n.º 6
0
        private static FileStore InitFileStore(Settings settings)
        {
            string    path = settings.FILE_STORE_ROOT;
            FileStore store;

            try
            {
                store = new FileStore(path);
            }
            catch (UnauthorizedAccessException)
            {
                ProgramOutput.Error("Cannot init audio file store at location {0}. Permission denied.", path);
                return(null);
            }
            catch
            {
                ProgramOutput.Error("Cannot init audio file store at location {0}. Please check that the path is valid.", path);
                return(null);
            }
            MasterContainer.AddService <FileStore>(store);
            ProgramOutput.Info("Audio file store set to location: {0}.", store.PathRoot);

            return(store);
        }
Exemplo n.º 7
0
 public void StartMessage_Passing()
 {
     ProgramOutput.StartMessage();
 }
Exemplo n.º 8
0
 public void PromptEnterName_Index2_Passing()
 {
     ProgramOutput.PromptEnterName(2);
 }
Exemplo n.º 9
0
        public void PrintPlayerState_Passing()
        {
            Player player = new Player("Jack", false, new Caravan(2, 0, 0, 0));

            ProgramOutput.PrintPlayerState(player);
        }
Exemplo n.º 10
0
 public void InvalidInputWarning_ReturnsFalse()
 {
     Assert.False(ProgramOutput.InvalidInputWarning(""));
 }
Exemplo n.º 11
0
    private void Server_DataRecieved(string host, byte[] requestData)
    {
        // Match host session
        var session = sessions.GetSession(host);

        if (session == null)
        {
            if (UnknownSession != null)
            {
                UnknownSession(string.Format("Session not found for host: {0}.", host));
            }

            return;
        }

        // Commit request session phase
        Request request = null;

        if (session.CurrentPhase == SessionPhase.Hello)
        {
            request = MatchRequest <HelloRequest>(requestData);
            if (request == null)
            {
                return;
            }
        }
        else if (session.CurrentPhase == SessionPhase.Encryption)
        {
            var data = DecryptRequest(requestData, asymetricCrypter);
            if (data == null)
            {
                return;
            }

            request = MatchRequest <KeyExchangeRequest>(data);
        }
        else if (session.CurrentPhase == SessionPhase.Authentication)
        {
            var data = DecryptRequest(requestData, session.Crpter);
            if (data == null)
            {
                return;
            }

            request = MatchRequest <AuthenticateRequest>(data);
        }
        else
        {
            var data = DecryptRequest(requestData, session.Crpter);
            if (data == null)
            {
                return;
            }

            request = MatchRequest <Request>(data);
        }
        request.Session = session;

        Response response = null;

        // Authenitacate request user
        AuthenticationResult result = AuthenticationResult.Denied;

        if (request.RequiresAuthentication)
        {
            string password = session.Crpter.DecryptString(request.User.PasswordEnc);
            result = authenticator.Authenticate(request.User, password);
        }
        if (!request.RequiresAuthentication || result == AuthenticationResult.Granted)
        {
            // Check user permissions for request (authorize request user)
            Permission[] permissions = null;
            if (request.RequiresAuthorization)
            {
                permissions = authorizator.ListPermissions(request.User);
            }

            if (!request.RequiresAuthorization || request.MatchesPermissions(permissions))
            {
                try
                {
                    // EXECUTE REQUEST
                    ProgramOutput.Info("Executing request: {0}...", request.ToString());
                    response = request.Execute();
                }
                catch (Exception ex)
                {
                    response = new CannotExecuteResponse(ex);
                    if (ExecuteError != null)
                    {
                        ExecuteError(request, ex);
                    }
                }
            }
            else
            {
                response = new AccessDeniedResponse();
                if (AccessDenied != null)
                {
                    AccessDenied(request);
                }
            }
        }
        else if (result == AuthenticationResult.Denied)
        {
            response = new UnauthorizedResponse(request.User);
            if (Unauthorized != null)
            {
                Unauthorized(request);
            }
        }

        if (!(request is GoodbyeRequest))
        {
            // Serialize response
            byte[] responseData = null;
            try
            {
                responseData = formatter.Format(response);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                if (InvalidResponse != null)
                {
                    InvalidResponse(request);
                }
                return;
            }

            // Encrypt response
            if (session.CurrentPhase == SessionPhase.Authentication || session.CurrentPhase == SessionPhase.Established)
            {
                responseData = EncryptResponse(responseData, session.Crpter);
            }
            if (responseData == null)
            {
                return;
            }

            // Send response
            try
            {
                ProgramOutput.Info("Responding: {0}, status code: {1}", response, response.Code);
                server.SendMessage(host, responseData);
            }
            catch (SocketException)
            {
                if (NetProblem != null)
                {
                    NetProblem(request);
                }
                return;
            }

            session.NextPhase();
        }
    }
Exemplo n.º 12
0
        /// <summary>
        /// </summary>
        /// <param name="nodeToRemove"></param>
        /// <exception cref="ArgumentNullException">
        /// <para><paramref name="nodeToRemove"/> is <see langword="null"/>.</para>
        /// </exception>
        public void RemoveNode(NodeBase nodeToRemove)
        {
            if (nodeToRemove == null)
            {
                throw new ArgumentNullException("nodeToRemove");
            }

            /* Disconnect from other nodes. */

            for (Int32 i = 0; i < _nodes.Count; i++)
            {
                NodeBase currentNode = _nodes[i];

                for (Int32 j = 0; j < currentNode.InputsLength; j++)
                {
                    if (currentNode.GetInput(j).Connection != null)
                    {
                        if (Object.ReferenceEquals(nodeToRemove, currentNode.GetInput(j).Connection.Node))
                        {
                            currentNode.GetInput(j).Connection = null;
                        }
                    }
                }
            }

            /* If it is a program output, disconnect the parent connection. */

            ProgramOutput programOutput = nodeToRemove as ProgramOutput;

            if (programOutput != null)
            {
                _lastRemovedOutputIndex = programOutput.OutputIndex;
            }

            _nodes.Remove(nodeToRemove);

            ProgramInput programInput = nodeToRemove as ProgramInput;

            if (programInput != null)
            {
                Int32 inputCount = 1;
                _lastRemovedInputIndex = programInput.InputIndex;

                for (Int32 i = 0; i < _nodes.Count; i++)
                {
                    ProgramInput currentProgramInput = _nodes[i] as ProgramInput;

                    if (currentProgramInput != null)
                    {
                        if (currentProgramInput.InputIndex > _lastRemovedInputIndex)
                        {
                            programInput.InputIndex = programInput.InputIndex - 1;
                        }

                        inputCount++;
                    }
                }
            }

            programOutput = nodeToRemove as ProgramOutput;

            if (programOutput != null)
            {
                Int32 outputCount = 0;

                for (Int32 i = 0; i < _nodes.Count; i++)
                {
                    ProgramOutput currentProgramOutput = _nodes[i] as ProgramOutput;

                    if (currentProgramOutput != null)
                    {
                        if (currentProgramOutput.OutputIndex > _lastRemovedOutputIndex)
                        {
                            currentProgramOutput.OutputIndex = currentProgramOutput.OutputIndex - 1;
                        }

                        outputCount++;
                    }
                }

                if (nodeToRemove.ContainingProgram.ParentNode != null)
                {
                    NodePort removedPort = nodeToRemove.ContainingProgram.ParentNode.GetOutput(outputCount);

                    foreach (NodeBase node in nodeToRemove.ContainingProgram.ParentNode.ContainingProgram.Nodes)
                    {
                        for (Int32 i = 0; i < node.InputsLength; i++)
                        {
                            if (node.GetInput(i).Connection != null)
                            {
                                if (Object.ReferenceEquals(node.GetInput(i).Connection, removedPort))
                                {
                                    node.GetInput(i).Connection = null;
                                }
                            }
                        }
                    }
                }
            }

            UpdateParentNode();
        }
Exemplo n.º 13
0
        private static void LogIncident(Request request, Exception ex)
        {
            string message = (ex == null) ? request.ToString() : string.Format("{0}: {1}", (request != null) ? request.ToString() : "", ex.Message);

            ProgramOutput.Error(message);
        }
Exemplo n.º 14
0
 public void ValidInputMessage_Passing()
 {
     ProgramOutput.ValidInputMessage("");
 }
Exemplo n.º 15
0
        public CompileResult CompileProject(SourceProject project)
        {
            // Set active project
            this.m_currentProject = project;

            // Meta data generation
            this.m_thisLog           = new();
            this.m_externalBindables = new();
            this.m_timer             = Stopwatch.StartNew();

            // Parse all files
            AST[] asts = new AST[this.m_currentProject.Sources.Length];
            for (int i = 0; i < this.m_currentProject.Sources.Length; i++)
            {
                var parseResult = ParseFile(this.m_currentProject.Sources[i], out AST ast);
                if (!parseResult)
                {
                    Log.WriteLine($"Failed to parse {this.m_currentProject.Sources[i].Name} :\n\t{"Some currently un-generated error!"}");
                    Log.WriteLine();
                    return(parseResult);
                }
                asts[i] = ast;
            }

            // Create the global domain and import external references
            Domain globalDomain = Domain.GetGlobalDomain();
            var    result       = ImportReferences(globalDomain, this.m_currentProject);

            if (!result)
            {
                return(this.FatalError(result));
            }

            // Detect types
            result = StaticTypeDetector.Detect(asts, globalDomain);
            if (!result)
            {
                return(this.FatalError(result));
            }

            // Define types
            result = StaticTypeDefiner.DefineAllTypes(asts, globalDomain);
            if (!result)
            {
                return(this.FatalError(result));
            }

            // Solve potential inheritance problems etc.
            result = InheritanceSolver.Solve(asts, globalDomain);
            if (!result)
            {
                return(this.FatalError(result));
            }

            // TODO: Run static checks

            // Verify variables
            VarsVerifier vVerifier = new VarsVerifier();

            for (int i = 0; i < asts.Length; i++)
            {
                result = vVerifier.Vars(asts[i]);
                if (!result)
                {
                    return(this.FatalError(result));
                }
            }

            // Verify control paths
            ControlpathVerifier pathVerifier = new ControlpathVerifier();

            for (int i = 0; i < asts.Length; i++)
            {
                result = pathVerifier.Verify(asts[i]);
                if (!result)
                {
                    return(this.FatalError(result));
                }
            }

            // Run static  typecheck
            Typechecker typechecker = new Typechecker();

            for (int i = 0; i < asts.Length; i++)
            {
                result = typechecker.Typecheck(asts[i], globalDomain);
                if (!result)
                {
                    return(this.FatalError(result));
                }
            }

            // Compile Application
            ASTCompiler astCompiler = new ASTCompiler(asts);

            result = astCompiler.Compile();
            if (!result)
            {
                return(this.FatalError(result));
            }

            // Apply linking
            Linker linker = new Linker(astCompiler, globalDomain, this.m_externalBindables);

            result = linker.Link();
            if (!result)
            {
                return(this.FatalError(result));
            }

            // Stop timer
            this.m_timer.Stop();

            // Get compile output
            ProgramOutput compilerOutput = this.GetCompileOutput(astCompiler, linker, globalDomain);

            // If successful compile, save, otherwise log error
            if (compilerOutput is not null)
            {
                compilerOutput.Save(project.Output);
                compilerOutput.SaveAsText(project.Output.Replace(".bin", ".txt").Replace(".hlib", ".txt"));
                Log.WriteLine($"Compiled \"{project.Name}\" successfully in {this.m_timer.ElapsedMilliseconds / 1000.0}s.");
                Log.WriteLine();
                this.m_thisLog.SaveAndClose(project.Output.Replace(".bin", ".log").Replace(".hlib", ".log"));
                return(new CompileResult(true));
            }
            else
            {
                Log.WriteLine($"Compile Error \"{project.Name}\" : {result}");
                Log.WriteLine();
                this.m_thisLog.SaveAndClose(project.Output.Replace(".bin", ".log").Replace(".hlib", ".log"));
                return(new CompileResult(false));
            }
        }
Exemplo n.º 16
0
 public void WelcomeMessage_Passing()
 {
     ProgramOutput.WelcomeMessage();
 }
Exemplo n.º 17
0
        static void EnableConsole()
        {
            var console = new ConsoleOutput();

            ProgramOutput.RegisterOutput(console);
        }