예제 #1
0
        public override CommandResult Execute(string parameter)
        {
            minerLog     = new Logger();
            minerManager = new MinerManager(false);
            //// minerManager.SetLogger(minerLog);

            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval = 1000;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimerWork);
            timer.Start();

            Thread.Sleep(3000);

            /*
             * Task.Factory.StartNew(() => PingMiner());
             *
             * Thread.Sleep(3000);
             *
             * Task.Factory.StartNew(() => PingMiner());
             *
             * Thread.Sleep(3000);
             *
             * Task.Factory.StartNew(() => PingMiner());
             */

            MessageOutput message = MessageOutput.Create("Finished");

            return(CommandResult.CreateResult(message));
        }
예제 #2
0
        public void Run()
        {
            CurrentGame = new GameCore();

            Game.StartGame(CurrentGame);

            CurrentGame.TurnCompleted += Game_TurnCompleted;
            CurrentGame.GameClosed    += Game_GameClosed;

            mapStateOutput  = new MapStateOutput();
            messageOutput   = new MessageOutput(Console.BufferWidth);
            gameStateOutput = new GameStateOutput();
            InputMap        = new InputMapper();

            CurrentGame.StartGame();
            gameRunning = true;

            while (gameRunning)
            {
                ConsoleKeyInfo input = Console.ReadKey(true);

                var action = InputMap.GetActionForKey(input);

                if (action != null)
                {
                    action();
                }
            }
        }
예제 #3
0
        public override void Invoke(AMFContext context)
        {
            MessageOutput messageOutput = context.MessageOutput;

            if ((FluorineConfiguration.Instance.CacheMap != null) && (FluorineConfiguration.Instance.CacheMap.Count > 0))
            {
                for (int i = 0; i < context.AMFMessage.BodyCount; i++)
                {
                    AMFBody bodyAt = context.AMFMessage.GetBodyAt(i);
                    if ((messageOutput.GetResponse(bodyAt) == null) && !bodyAt.IsEmptyTarget)
                    {
                        string target        = bodyAt.Target;
                        IList  parameterList = bodyAt.GetParameterList();
                        string cacheKey      = CacheMap.GenerateCacheKey(target, parameterList);
                        if (FluorineConfiguration.Instance.CacheMap.ContainsValue(cacheKey))
                        {
                            object content = FluorineConfiguration.Instance.CacheMap.Get(cacheKey);
                            if ((log != null) && log.get_IsDebugEnabled())
                            {
                                log.Debug(__Res.GetString("Cache_HitKey", new object[] { bodyAt.Target, cacheKey }));
                            }
                            CachedBody body = new CachedBody(bodyAt, content);
                            messageOutput.AddBody(body);
                        }
                    }
                }
            }
        }
예제 #4
0
        private async void Shutdown_Click(object sender, RoutedEventArgs e)
        {
            if (ShutdownStarted)
            {
                return;
            }

            try
            {
                MessageOutput.Clear();

                ShutdownType = 1;
                Application.Current.Dispatcher.Invoke(() => this.Cursor = System.Windows.Input.Cursors.Wait);
                Application.Current.Dispatcher.Invoke(() => this.CancelShutdownButton.Cursor = System.Windows.Input.Cursors.Arrow);

                var app = new ServerApp(true)
                {
                    BackupWorldFile  = this.BackupWorldFile,
                    ShutdownInterval = this.ShutdownInterval,
                    ShutdownReason   = this.ShutdownReason,
                    OutputLogs       = false,
                    SendAlerts       = true,
                    ServerProcess    = RestartServer ? ServerProcessType.Restart : ServerProcessType.Shutdown,
                    ProgressCallback = (p, m, n) => { TaskUtils.RunOnUIThreadAsync(() => { this.AddMessage(m, n); }).DoNotWait(); },
                };

                var profile       = ProfileSnapshot.Create(Server.Profile);
                var restartServer = RestartServer;
                var updateServer  = UpdateServer;

                _shutdownCancellationSource = new CancellationTokenSource();

                var exitCode = await Task.Run(() => app.PerformProfileShutdown(profile, restartServer, updateServer, _shutdownCancellationSource.Token));

                if (exitCode != ServerApp.EXITCODE_NORMALEXIT && exitCode != ServerApp.EXITCODE_CANCELLED)
                {
                    throw new ApplicationException($"An error occured during the shutdown process - ExitCode: {exitCode}");
                }

                ShutdownType = 0;
                // if restarting or updating the server after the shutdown, delay the form closing
                if (restartServer || updateServer)
                {
                    await Task.Delay(5000);
                }

                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, _globalizer.GetResourceString("ServerSettings_ShutdownServer_FailedTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
                ShutdownType = 0;
            }
            finally
            {
                _shutdownCancellationSource = null;
                Application.Current.Dispatcher.Invoke(() => this.Cursor = null);
                Application.Current.Dispatcher.Invoke(() => this.CancelShutdownButton.Cursor = null);
            }
        }
예제 #5
0
        protected override void InitializeSecurity()
        {
            Dictionary <string, string> message;
            var dhg = new DiffieHellmanGenerator();

            // Stage 1: Send key request
            Send(new Dictionary <string, string>
            {
                { "request", "keys" }
            });

            // Stage 2: Process response
            message = WaitForKey("p");
            if (message == null)
            {
                MessageOutput.Log("Invalid response from server; expected p");
                return;
            }

            //int p = Convert.ToInt32(message["p"]);
            //int g = Convert.ToInt32(message["g"]);
            //var publicKeys = new DiffieHellmanPublicKeystore(p, g);
            var publicKeys = new DiffieHellmanPublicKeystore(message);
            var secretA    = dhg.GenerateSecret();
            var transportA = dhg.GenerateTransport(secretA, publicKeys);

            // Stage 3: Send a, await b
            Send(new Dictionary <string, string>
            {
                { "a", transportA.ToString() }
            });
            message = WaitForKey("b");
            if (message == null)
            {
                MessageOutput.Log("Invalid response from server; expected b");
                return;
            }

            // Stage 4: Calculate shared secret
            var transportB = BigInteger.Parse(message["b"]);

            SharedSecret = dhg.GenerateSharedSecret(secretA, transportB, publicKeys);

            // Stage 5: Send encryption type
            Send(new Dictionary <string, string>
            {
                { "encryption", encryption }
            });
            SetEncryption(encryption);

            MessageOutput.Log("Connection summary:\n " +
                              $"\tp: {publicKeys.P}\n" +
                              $"\tg: {publicKeys.G}\n" +
                              $"\tsecret: {secretA}\n" +
                              $"\ttransport: {transportA}\n" +
                              $"\treceived transport: {transportB}\n" +
                              $"\tshared secret: {SharedSecret}\n" +
                              $"\tencryption: {encryption}");
        }
예제 #6
0
        /// <summary>
        /// Output a message to the user. This differs from Log in that debug info should not be included here.
        /// Instead, only output messages that you expect the user to read.
        /// </summary>
        /// <param name="message">The message to send.</param>
        /// <param name="timestamp">Whether the message should be prefixed with a timestamp of when this method was called.</param>
        public static void Message(string message, bool timestamp = false)
        {
            if (timestamp)
            {
                message = $"[{DateTime.Now:h:mm:ss tt}] {message}";
            }

            MessageOutput?.Invoke(message);
        }
예제 #7
0
        public void AddMessage(string message, bool includeNewLine = true)
        {
            MessageOutput.AppendText(message);
            if (includeNewLine)
            {
                MessageOutput.AppendText(Environment.NewLine);
            }
            MessageOutput.ScrollToEnd();

            Debug.WriteLine(message);
        }
예제 #8
0
 /// <summary>
 ///     Changes encryption used in communication with server.
 /// </summary>
 /// <param name="newEncryption">New encryption name.</param>
 public void ChangeEncryption(string newEncryption)
 {
     encryption = newEncryption;
     Send(new Dictionary <string, string>
     {
         { "encryption", encryption }
     });
     MessageOutput.Log("Client requested encryption change:\n" +
                       $"\tencryption: {encryption}");
     SetEncryption(encryption);
 }
예제 #9
0
 protected override void HandleMessage(Dictionary <string, string> message)
 {
     if (message.ContainsKey("encryption"))
     {
         MessageOutput.Log("Client requested encryption change:\n" +
                           $"\tencryption: {message["encryption"]}");
         SetEncryption(message["encryption"]);
     }
     else
     {
         MessageOutput.HandleMessage(message);
     }
 }
예제 #10
0
        private MessageEvent CreateMessageEvent(DynamoDBEvent.DynamodbStreamRecord record)
        {
            MessageOutput message  = null;
            var           newImage = record.Dynamodb.NewImage;

            if (newImage.Count > 0)
            {
                message = new MessageOutput
                {
                    Author = newImage.ContainsKey("Author") ? newImage["Author"].S : "",
                    Id     = int.Parse(newImage["Id"].N),
                    Text   = newImage.ContainsKey("Text") ? newImage["Text"].S : "",
                    Time   = DateTime.Parse(newImage["Time"].S)
                };
            }

            var messageEvent = new MessageEvent
            {
                Keys = new MessageKeys
                {
                    Id   = int.Parse(record.Dynamodb.Keys["Id"].N),
                    Time = DateTime.Parse(record.Dynamodb.Keys["Time"].S)
                },
                Message = message
            };

            if (record.EventName == OperationType.INSERT)
            {
                messageEvent.Type = MessageEventType.INSERT;
            }

            if (record.EventName == OperationType.REMOVE)
            {
                messageEvent.Type = MessageEventType.REMOVE;
            }

            if (record.EventName == OperationType.MODIFY)
            {
                messageEvent.Type = MessageEventType.MODIFY;
            }

            return(messageEvent);
        }
예제 #11
0
        //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
        //ORIGINAL LINE: @Override public void encodeTrack(MessageOutput stream, AudioTrack track) throws IOException
        public override void encodeTrack(MessageOutput stream, AudioTrack track)
        {
            DataOutput output = stream.startMessage();

            output.write(TRACK_INFO_VERSION);

            AudioTrackInfo trackInfo = track.Info;

            output.writeUTF(trackInfo.title);
            output.writeUTF(trackInfo.author);
            output.writeLong(trackInfo.length);
            output.writeUTF(trackInfo.identifier);
            output.writeBoolean(trackInfo.isStream);
            DataFormatTools.writeNullableText(output, trackInfo.uri);

            encodeTrackDetails(track, output);
            output.writeLong(track.Position);

            stream.commitMessage(TRACK_INFO_VERSIONED);
        }
예제 #12
0
 private CommandResult Detect()
 {
     try
     {
         string newInstanceId = serviceProvider.DetectAvailableInstanceId().ToString();
         return(CommandResult.CreateResult(MessageOutput.Create(newInstanceId)));
     }
     catch (Service.TimeoutException ex)
     {
         throw new TargetExecutionException(DaemonErrorCode.COMMAND_TIME_OUT, ex);
     }
     catch (TargetExecutionException ex)
     {
         throw ex;
     }
     catch (Exception ex)
     {
         throw new TargetExecutionException(DaemonErrorCode.UNKNOWN_ERROR, ex);
     }
 }
예제 #13
0
        public override void Invoke(AMFContext context)
        {
            MessageOutput messageOutput = context.MessageOutput;

            if (FluorineConfiguration.Instance.CacheMap != null && FluorineConfiguration.Instance.CacheMap.Count > 0)
            {
                for (int i = 0; i < context.AMFMessage.BodyCount; i++)
                {
                    AMFBody amfBody = context.AMFMessage.GetBodyAt(i);
                    //Check if response exists.
                    ResponseBody responseBody = messageOutput.GetResponse(amfBody);
                    if (responseBody != null)
                    {
                        //AuthenticationFilter may insert response.
                        continue;
                    }

                    if (!amfBody.IsEmptyTarget)
                    {
                        string source    = amfBody.Target;
                        IList  arguments = amfBody.GetParameterList();
                        string key       = FluorineFx.Configuration.CacheMap.GenerateCacheKey(source, arguments);
                        //Flash message
                        if (FluorineConfiguration.Instance.CacheMap.ContainsValue(key))
                        {
                            object cachedContent = FluorineConfiguration.Instance.CacheMap.Get(key);

                            if (log != null && log.IsDebugEnabled)
                            {
                                log.Debug(__Res.GetString(__Res.Cache_HitKey, amfBody.Target, key));
                            }

                            CachedBody cachedBody = new CachedBody(amfBody, cachedContent);
                            messageOutput.AddBody(cachedBody);
                        }
                    }
                }
            }
        }
예제 #14
0
        public override void Invoke(AMFContext context)
        {
            MessageOutput messageOutput = context.MessageOutput;

            for (int i = 0; i < context.AMFMessage.BodyCount; i++)
            {
                ResponseBody body2;
                AMFBody      bodyAt = context.AMFMessage.GetBodyAt(i);
                if (!bodyAt.IsEmptyTarget)
                {
                    continue;
                }
                object content = bodyAt.Content;
                if (content is IList)
                {
                    content = (content as IList)[0];
                }
                IMessage message = content as IMessage;
                if (message == null)
                {
                    continue;
                }
                if (FluorineContext.Current.Client == null)
                {
                    FluorineContext.Current.SetCurrentClient(this._endpoint.GetMessageBroker().ClientRegistry.GetClient(message));
                }
                if (message.clientId == null)
                {
                    message.clientId = Guid.NewGuid().ToString("D");
                }
                if (messageOutput.GetResponse(bodyAt) != null)
                {
                    continue;
                }
                try
                {
                    if (context.AMFMessage.BodyCount > 1)
                    {
                        CommandMessage message2 = message as CommandMessage;
                        if ((message2 != null) && (message2.operation == 2))
                        {
                            message2.SetHeader(CommandMessage.FluorineSuppressPollWaitHeader, null);
                        }
                    }
                    IMessage message3 = this._endpoint.ServiceMessage(message);
                    if (message3 is ErrorMessage)
                    {
                        ErrorMessage message4 = message3 as ErrorMessage;
                        body2 = new ErrorResponseBody(bodyAt, message, message3 as ErrorMessage);
                        if (!(message4.faultCode == "Client.Authentication"))
                        {
                            goto Label_0291;
                        }
                        messageOutput.AddBody(body2);
                        for (int j = i + 1; j < context.AMFMessage.BodyCount; j++)
                        {
                            bodyAt = context.AMFMessage.GetBodyAt(j);
                            if (bodyAt.IsEmptyTarget)
                            {
                                content = bodyAt.Content;
                                if (content is IList)
                                {
                                    content = (content as IList)[0];
                                }
                                message = content as IMessage;
                                if (message != null)
                                {
                                    body2 = new ErrorResponseBody(bodyAt, message, new SecurityException(message4.faultString));
                                    messageOutput.AddBody(body2);
                                }
                            }
                        }
                        break;
                    }
                    body2 = new ResponseBody(bodyAt, message3);
                }
                catch (Exception exception)
                {
                    if ((log != null) && log.get_IsErrorEnabled())
                    {
                        log.Error(exception.Message, exception);
                    }
                    body2 = new ErrorResponseBody(bodyAt, message, exception);
                }
Label_0291:
                messageOutput.AddBody(body2);
            }
        }
        public override void Invoke(AMFContext context)
        {
            MessageOutput messageOutput = context.MessageOutput;

            for (int i = 0; i < context.AMFMessage.BodyCount; i++)
            {
                AMFBody      amfBody      = context.AMFMessage.GetBodyAt(i);
                ResponseBody responseBody = null;
                //Check for Flex2 messages and skip
                if (amfBody.IsEmptyTarget)
                {
                    continue;
                }

                if (amfBody.IsDebug)
                {
                    continue;
                }
                if (amfBody.IsDescribeService)
                {
                    responseBody = new ResponseBody();
                    responseBody.IgnoreResults = amfBody.IgnoreResults;
                    responseBody.Target        = amfBody.Response + AMFBody.OnResult;
                    responseBody.Response      = null;
                    DescribeService describeService = new DescribeService(amfBody);
                    responseBody.Content = describeService.GetDescription();
                    messageOutput.AddBody(responseBody);
                    continue;
                }

                //Check if response exists.
                responseBody = messageOutput.GetResponse(amfBody);
                if (responseBody != null)
                {
                    continue;
                }

                try
                {
                    MessageBroker   messageBroker   = _endpoint.GetMessageBroker();
                    RemotingService remotingService = messageBroker.GetService(RemotingService.RemotingServiceId) as RemotingService;
                    if (remotingService == null)
                    {
                        string serviceNotFound = __Res.GetString(__Res.Service_NotFound, RemotingService.RemotingServiceId);
                        responseBody = new ErrorResponseBody(amfBody, new FluorineException(serviceNotFound));
                        messageOutput.AddBody(responseBody);
                        if (log.IsErrorEnabled)
                        {
                            log.Error(serviceNotFound);
                        }
                        continue;
                    }
                    Destination destination = null;
                    if (destination == null)
                    {
                        destination = remotingService.GetDestinationWithSource(amfBody.TypeName);
                    }
                    if (destination == null)
                    {
                        destination = remotingService.DefaultDestination;
                    }
                    //At this moment we got a destination with the exact source or we have a default destination with the "*" source.
                    if (destination == null)
                    {
                        string destinationNotFound = __Res.GetString(__Res.Destination_NotFound, amfBody.TypeName);
                        responseBody = new ErrorResponseBody(amfBody, new FluorineException(destinationNotFound));
                        messageOutput.AddBody(responseBody);
                        if (log.IsErrorEnabled)
                        {
                            log.Error(destinationNotFound);
                        }
                        continue;
                    }

                    try
                    {
                        remotingService.CheckSecurity(destination);
                    }
                    catch (UnauthorizedAccessException exception)
                    {
                        responseBody = new ErrorResponseBody(amfBody, exception);
                        if (log.IsDebugEnabled)
                        {
                            log.Debug(exception.Message);
                        }
                        continue;
                    }

                    //Cache check
                    string source        = amfBody.TypeName + "." + amfBody.Method;
                    IList  parameterList = amfBody.GetParameterList();
                    string key           = FluorineFx.Configuration.CacheMap.GenerateCacheKey(source, parameterList);
                    if (FluorineConfiguration.Instance.CacheMap.ContainsValue(key))
                    {
                        object result = FluorineFx.Configuration.FluorineConfiguration.Instance.CacheMap.Get(key);
                        if (result != null)
                        {
                            if (log != null && log.IsDebugEnabled)
                            {
                                log.Debug(__Res.GetString(__Res.Cache_HitKey, source, key));
                            }
                            responseBody = new ResponseBody(amfBody, result);
                            messageOutput.AddBody(responseBody);
                            continue;
                        }
                    }

                    object          instance;
                    FactoryInstance factoryInstance = destination.GetFactoryInstance();
                    lock (factoryInstance)
                    {
                        factoryInstance.Source = amfBody.TypeName;
                        if (FluorineContext.Current.ActivationMode != null)//query string can override the activation mode
                        {
                            factoryInstance.Scope = FluorineContext.Current.ActivationMode;
                        }
                        instance = factoryInstance.Lookup();
                    }
                    if (instance != null)
                    {
                        try
                        {
                            bool isAccessible = TypeHelper.GetTypeIsAccessible(instance.GetType());
                            if (!isAccessible)
                            {
                                string msg = __Res.GetString(__Res.Type_InitError, amfBody.TypeName);
                                if (log.IsErrorEnabled)
                                {
                                    log.Error(msg);
                                }
                                responseBody = new ErrorResponseBody(amfBody, new FluorineException(msg));
                                messageOutput.AddBody(responseBody);
                                continue;
                            }

                            MethodInfo mi = null;
                            if (!amfBody.IsRecordsetDelivery)
                            {
                                mi = MethodHandler.GetMethod(instance.GetType(), amfBody.Method, parameterList);
                            }
                            else
                            {
                                //will receive recordsetid only (ignore)
                                mi = instance.GetType().GetMethod(amfBody.Method);
                            }
                            if (mi != null)
                            {
                                object[] roleAttributes = mi.GetCustomAttributes(typeof(RoleAttribute), true);
                                if (roleAttributes != null && roleAttributes.Length == 1)
                                {
                                    RoleAttribute roleAttribute = roleAttributes[0] as RoleAttribute;
                                    string[]      roles         = roleAttribute.Roles.Split(',');

                                    bool authorized = messageBroker.LoginManager.DoAuthorization(roles);
                                    if (!authorized)
                                    {
                                        throw new UnauthorizedAccessException(__Res.GetString(__Res.Security_AccessNotAllowed));
                                    }
                                }

                                #region Invocation handling
                                PageSizeAttribute pageSizeAttribute  = null;
                                MethodInfo        miCounter          = null;
                                object[]          pageSizeAttributes = mi.GetCustomAttributes(typeof(PageSizeAttribute), true);
                                if (pageSizeAttributes != null && pageSizeAttributes.Length == 1)
                                {
                                    pageSizeAttribute = pageSizeAttributes[0] as PageSizeAttribute;
                                    miCounter         = instance.GetType().GetMethod(amfBody.Method + "Count");
                                    if (miCounter != null && miCounter.ReturnType != typeof(System.Int32))
                                    {
                                        miCounter = null; //check signature
                                    }
                                }
                                ParameterInfo[] parameterInfos = mi.GetParameters();
                                //Try to handle missing/optional parameters.
                                object[] args = new object[parameterInfos.Length];
                                if (!amfBody.IsRecordsetDelivery)
                                {
                                    if (args.Length != parameterList.Count)
                                    {
                                        string msg = __Res.GetString(__Res.Arg_Mismatch, parameterList.Count, mi.Name, args.Length);
                                        if (log != null && log.IsErrorEnabled)
                                        {
                                            log.Error(msg);
                                        }
                                        responseBody = new ErrorResponseBody(amfBody, new ArgumentException(msg));
                                        messageOutput.AddBody(responseBody);
                                        continue;
                                    }
                                    parameterList.CopyTo(args, 0);
                                    if (pageSizeAttribute != null)
                                    {
                                        PagingContext pagingContext = new PagingContext(pageSizeAttribute.Offset, pageSizeAttribute.Limit);
                                        PagingContext.SetPagingContext(pagingContext);
                                    }
                                }
                                else
                                {
                                    if (amfBody.Target.EndsWith(".release"))
                                    {
                                        responseBody = new ResponseBody(amfBody, null);
                                        messageOutput.AddBody(responseBody);
                                        continue;
                                    }
                                    string recordsetId = parameterList[0] as string;
                                    string recordetDeliveryParameters = amfBody.GetRecordsetArgs();
                                    byte[] buffer = System.Convert.FromBase64String(recordetDeliveryParameters);
                                    recordetDeliveryParameters = System.Text.Encoding.UTF8.GetString(buffer);
                                    if (recordetDeliveryParameters != null && recordetDeliveryParameters != string.Empty)
                                    {
                                        string[] stringParameters = recordetDeliveryParameters.Split(new char[] { ',' });
                                        for (int j = 0; j < stringParameters.Length; j++)
                                        {
                                            if (stringParameters[j] == string.Empty)
                                            {
                                                args[j] = null;
                                            }
                                            else
                                            {
                                                args[j] = stringParameters[j];
                                            }
                                        }
                                        //TypeHelper.NarrowValues(argsStore, parameterInfos);
                                    }
                                    PagingContext pagingContext = new PagingContext(System.Convert.ToInt32(parameterList[1]), System.Convert.ToInt32(parameterList[2]));
                                    PagingContext.SetPagingContext(pagingContext);
                                }

                                TypeHelper.NarrowValues(args, parameterInfos);

                                try
                                {
                                    InvocationHandler invocationHandler = new InvocationHandler(mi);
                                    object            result            = invocationHandler.Invoke(instance, args);

                                    if (FluorineConfiguration.Instance.CacheMap != null && FluorineConfiguration.Instance.CacheMap.ContainsCacheDescriptor(source))
                                    {
                                        //The result should be cached
                                        CacheableObject cacheableObject = new CacheableObject(source, key, result);
                                        FluorineConfiguration.Instance.CacheMap.Add(cacheableObject.Source, cacheableObject.CacheKey, cacheableObject);
                                        result = cacheableObject;
                                    }
                                    responseBody = new ResponseBody(amfBody, result);

                                    if (pageSizeAttribute != null)
                                    {
                                        int    totalCount  = 0;
                                        string recordsetId = null;

                                        IList  list = amfBody.GetParameterList();
                                        string recordetDeliveryParameters = null;
                                        if (!amfBody.IsRecordsetDelivery)
                                        {
                                            //fist call paging
                                            object[] argsStore = new object[list.Count];
                                            list.CopyTo(argsStore, 0);
                                            recordsetId = System.Guid.NewGuid().ToString();
                                            if (miCounter != null)
                                            {
                                                //object[] counterArgs = new object[0];
                                                totalCount = (int)miCounter.Invoke(instance, args);
                                            }
                                            string[] stringParameters = new string[argsStore.Length];
                                            for (int j = 0; j < argsStore.Length; j++)
                                            {
                                                if (argsStore[j] != null)
                                                {
                                                    stringParameters[j] = argsStore[j].ToString();
                                                }
                                                else
                                                {
                                                    stringParameters[j] = string.Empty;
                                                }
                                            }
                                            recordetDeliveryParameters = string.Join(",", stringParameters);
                                            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(recordetDeliveryParameters);
                                            recordetDeliveryParameters = System.Convert.ToBase64String(buffer);
                                        }
                                        else
                                        {
                                            recordsetId = amfBody.GetParameterList()[0] as string;
                                        }
                                        if (result is DataTable)
                                        {
                                            DataTable dataTable = result as DataTable;
                                            dataTable.ExtendedProperties["TotalCount"]  = totalCount;
                                            dataTable.ExtendedProperties["Service"]     = recordetDeliveryParameters + "/" + amfBody.Target;
                                            dataTable.ExtendedProperties["RecordsetId"] = recordsetId;
                                            if (amfBody.IsRecordsetDelivery)
                                            {
                                                dataTable.ExtendedProperties["Cursor"]      = Convert.ToInt32(list[list.Count - 2]);
                                                dataTable.ExtendedProperties["DynamicPage"] = true;
                                            }
                                        }
                                    }
                                }
                                catch (UnauthorizedAccessException exception)
                                {
                                    responseBody = new ErrorResponseBody(amfBody, exception);
                                    if (log.IsDebugEnabled)
                                    {
                                        log.Debug(exception.Message);
                                    }
                                }
                                catch (Exception exception)
                                {
                                    if (exception is TargetInvocationException && exception.InnerException != null)
                                    {
                                        responseBody = new ErrorResponseBody(amfBody, exception.InnerException);
                                    }
                                    else
                                    {
                                        responseBody = new ErrorResponseBody(amfBody, exception);
                                    }
                                    if (log.IsDebugEnabled)
                                    {
                                        log.Debug(__Res.GetString(__Res.Invocation_Failed, mi.Name, exception.Message));
                                    }
                                }
                                #endregion Invocation handling
                            }
                            else
                            {
                                responseBody = new ErrorResponseBody(amfBody, new MissingMethodException(amfBody.TypeName, amfBody.Method));
                            }
                        }
                        finally
                        {
                            factoryInstance.OnOperationComplete(instance);
                        }
                    }
                    else
                    {
                        responseBody = new ErrorResponseBody(amfBody, new TypeInitializationException(amfBody.TypeName, null));
                    }
                }
                catch (Exception exception)
                {
                    if (log != null && log.IsErrorEnabled)
                    {
                        log.Error(exception.Message + String.Format(" (Type: {0}, Method: {1})", amfBody.TypeName, amfBody.Method), exception);
                    }
                    responseBody = new ErrorResponseBody(amfBody, exception);
                }
                messageOutput.AddBody(responseBody);
            }
        }
예제 #16
0
 protected override void HandleMessage(Dictionary <string, string> message)
 {
     MessageOutput.HandleMessage(message);
 }
예제 #17
0
        /// <summary>
        /// Метод получает диалог, либо создает новый.
        /// </summary>
        /// <param name="dialogId">Id диалога, для которого нужно подтянуть сообщения.</param>
        /// <param name="account">Логин текущего пользователя.</param>
        /// <param name="isWriteBtn">Флаг кнопки "Написать".</param>
        /// <param name="executorId">Id исполнителя, на ставку которого нажали.</param>
        /// <returns>Список сообщений диалога.</returns>
        public async Task <GetResultMessageOutput> GetDialogAsync(long?dialogId, string account, string executorId, bool isWriteBtn = false)
        {
            try
            {
                GetResultMessageOutput messagesList = new GetResultMessageOutput();

                // Если dialogId не передан и не передан флаг кнопки, значит нужно открыть пустой чат.
                if (dialogId == null && !isWriteBtn)
                {
                    messagesList.DialogState = DialogStateEnum.None.ToString();

                    return(messagesList);
                }

                // Найдет Id текущего пользователя.
                string userId = await _userService.GetUserIdByLogin(account);

                // Если передан флаг кнопки "Ответить", значит нужно поискать существующий диалог с исполнителем или создать новый.
                if (isWriteBtn)
                {
                    // Есть ли роль заказчика.
                    UserOutput user = await _userService.GetUserInitialsByIdAsync(userId);

                    // Пытается найти существующий диалог заказчика с исполнителем.
                    if (user.UserRole.Equals(UserRole.CUSTOMER) && !string.IsNullOrEmpty(executorId))
                    {
                        // Ищет Id диалога с текущим заказчиком и исполнителем, на ставку которого нажали. Затем сравнит их DialogId, если он совпадает, значит заказчик с исполнителем общаются.
                        // Выберет DialogId заказчика.
                        long customerDialogId = await _postgre.DialogMembers
                                                .Where(d => d.Id
                                                       .Equals(userId))
                                                .Select(res => res.DialogId)
                                                .FirstOrDefaultAsync();

                        // Выберет DialogId исполнителя.
                        long executorDialogId = await _postgre.DialogMembers
                                                .Where(d => d.Id
                                                       .Equals(executorId))
                                                .Select(res => res.DialogId)
                                                .FirstOrDefaultAsync();

                        // Сравнит DialogId заказчика и исполнителя. Если они равны, значит заказчик и исполнитель общаются в одном чате и возьмет DialogId этого чата.
                        if (customerDialogId != executorDialogId)
                        {
                            // Создаст новый диалог.
                            await _postgre.MainInfoDialogs.AddAsync(new MainInfoDialogEntity()
                            {
                                DialogName = string.Empty,
                                Created    = DateTime.Now
                            });

                            await _postgre.SaveChangesAsync();

                            // Выберет DialogId созданного диалога.
                            long newDialogId = await _postgre.MainInfoDialogs
                                               .OrderBy(d => d.DialogId)
                                               .Select(d => d.DialogId)
                                               .LastOrDefaultAsync();

                            // Добавит заказчика и исполнителя к новому диалогу.
                            await _postgre.DialogMembers.AddRangeAsync(
                                new DialogMemberEntity()
                            {
                                DialogId = newDialogId,
                                Id       = userId,
                                Joined   = DateTime.Now
                            },
                                new DialogMemberEntity()
                            {
                                DialogId = newDialogId,
                                Id       = executorId,
                                Joined   = DateTime.Now
                            });

                            await _postgre.SaveChangesAsync();

                            messagesList.DialogState = DialogStateEnum.Open.ToString();

                            return(messagesList);
                        }

                        dialogId = executorDialogId;
                    }
                }

                // Проверит существование диалога.
                bool isDialog = await _postgre.MainInfoDialogs
                                .Where(d => d.DialogId == dialogId)
                                .FirstOrDefaultAsync() != null;

                if (!isDialog)
                {
                    throw new NotFoundDialogIdException(dialogId);
                }

                // Получит сообщения диалога.
                var messages = await(_postgre.DialogMessages
                                     .Where(d => d.DialogId == dialogId)
                                     .OrderBy(m => m.Created)
                                     .Select(res => new
                {
                    dialogId    = res.DialogId,
                    message     = res.Message,
                    created     = string.Format("{0:f}", res.Created),
                    userId      = res.UserId,
                    isMyMessage = res.IsMyMessage
                })
                                     .ToListAsync());

                // Если у диалога нет сообщений, значит вернуть пустой диалог, который будет открыт.
                if (!messages.Any())
                {
                    messagesList.DialogState = DialogStateEnum.Empty.ToString();

                    return(messagesList);
                }

                // Приведет к типу MessageOutput.
                foreach (object message in messages)
                {
                    string        jsonString    = JsonSerializer.Serialize(message);
                    MessageOutput messageOutput = JsonSerializer.Deserialize <MessageOutput>(jsonString);

                    // Проставит флаг принадлежности сообщения.
                    messageOutput.IsMyMessage = messageOutput.UserId.Equals(userId);

                    // Затирает Id пользователя, чтобы фронт его не видел.
                    messageOutput.UserId = null;
                    messagesList.Messages.Add(messageOutput);
                }
                messagesList.DialogState = DialogStateEnum.Open.ToString();

                // Находит Id участников диалога по DialogId.
                IEnumerable <string> membersIds = await GetDialogMembers(dialogId);

                if (membersIds == null)
                {
                    throw new NotDialogMembersException(dialogId);
                }

                string     id        = membersIds.FirstOrDefault(i => !i.Equals(userId));
                UserOutput otherUser = await _userService.GetUserInitialsByIdAsync(id);

                // Запишет имя и фамилию пользователя, диалог с которым открыт.
                if (!string.IsNullOrEmpty(otherUser.FirstName) && !string.IsNullOrEmpty(otherUser.LastName))
                {
                    messagesList.FirstName = otherUser.FirstName;
                    messagesList.LastName  = CommonMethodsService.SubstringLastName(otherUser.LastName);
                }

                // Если не заполнено имя и фамилия, значит записать логин.
                else
                {
                    messagesList.UserName = otherUser.UserName;
                }

                return(messagesList);
            }

            catch (Exception ex)
            {
                Logger logger = new Logger(_db, ex.GetType().FullName, ex.Message, ex.StackTrace);
                await logger.LogCritical();

                throw new Exception(ex.Message);
            }
        }
예제 #18
0
        public override void Invoke(AMFContext context)
        {
            MessageOutput messageOutput = context.MessageOutput;

            for (int i = 0; i < context.AMFMessage.BodyCount; i++)
            {
                AMFBody amfBody = context.AMFMessage.GetBodyAt(i);

                if (!amfBody.IsEmptyTarget)
                {
                    continue;
                }

                object content = amfBody.Content;
                if (content is IList)
                {
                    content = (content as IList)[0];
                }
                IMessage message = content as IMessage;

                //Check for Flex2 messages and handle
                if (message != null)
                {
                    if (Context.AMFContext.Current.Client == null)
                    {
                        Context.AMFContext.Current.SetCurrentClient(_endpoint.GetMessageBroker().ClientRegistry.GetClient(message));
                    }

                    if (message.clientId == null)
                    {
                        message.clientId = Guid.NewGuid().ToString("D");
                    }

                    //Check if response exists.
                    ResponseBody responseBody = messageOutput.GetResponse(amfBody);
                    if (responseBody != null)
                    {
                        continue;
                    }

                    try
                    {
                        if (context.AMFMessage.BodyCount > 1)
                        {
                            CommandMessage commandMessage = message as CommandMessage;
                            //Suppress poll wait if there are more messages to process
                            if (commandMessage != null && commandMessage.operation == CommandMessage.PollOperation)
                            {
                                commandMessage.SetHeader(CommandMessage.AMFSuppressPollWaitHeader, null);
                            }
                        }
                        IMessage resultMessage = _endpoint.ServiceMessage(message);
                        if (resultMessage is ErrorMessage)
                        {
                            ErrorMessage errorMessage = resultMessage as ErrorMessage;
                            responseBody = new ErrorResponseBody(amfBody, message, resultMessage as ErrorMessage);
                            if (errorMessage.faultCode == ErrorMessage.ClientAuthenticationError)
                            {
                                messageOutput.AddBody(responseBody);
                                for (int j = i + 1; j < context.AMFMessage.BodyCount; j++)
                                {
                                    amfBody = context.AMFMessage.GetBodyAt(j);

                                    if (!amfBody.IsEmptyTarget)
                                    {
                                        continue;
                                    }

                                    content = amfBody.Content;
                                    if (content is IList)
                                    {
                                        content = (content as IList)[0];
                                    }
                                    message = content as IMessage;

                                    //Check for Flex2 messages and handle
                                    if (message != null)
                                    {
                                        responseBody = new ErrorResponseBody(amfBody, message, new SecurityException(errorMessage.faultString));
                                        messageOutput.AddBody(responseBody);
                                    }
                                }
                                //Leave further processing
                                return;
                            }
                        }
                        else
                        {
                            responseBody = new ResponseBody(amfBody, resultMessage);
                        }
                    }
                    catch (Exception exception)
                    {
                        responseBody = new ErrorResponseBody(amfBody, message, exception);
                    }
                    messageOutput.AddBody(responseBody);
                }
            }
        }
예제 #19
0
        /// <summary>
        /// Метод пишет сообщение.
        /// </summary>
        /// <param name="account">Логин пользователя.</param>
        /// <param name="message">Сообщение.</param>
        /// <param name="dialogId">Id диалога.</param>
        /// <returns>Список сообщений.</returns>
        public async Task <GetResultMessageOutput> SendAsync(string message, string account, long dialogId)
        {
            try
            {
                GetResultMessageOutput messagesList = new GetResultMessageOutput();

                // Если сообщения не передано, то ничего не делать.
                if (string.IsNullOrEmpty(message))
                {
                    return(null);
                }

                // Найдет Id пользователя.
                string userId = await _userService.GetUserIdByLogin(account);

                // Проверит существование диалога.
                bool isDialog = await _postgre.MainInfoDialogs
                                .Where(d => d.DialogId == dialogId)
                                .FirstOrDefaultAsync() != null;

                if (!isDialog)
                {
                    throw new NotFoundDialogIdException(dialogId);
                }

                // Запишет сообщение в диалог.
                await _postgre.DialogMessages.AddAsync(new DialogMessageEntity()
                {
                    Message     = message,
                    DialogId    = dialogId,
                    Created     = DateTime.Now,
                    UserId      = userId,
                    IsMyMessage = true
                });

                await _postgre.SaveChangesAsync();

                // Получит сообщения диалога.
                var messages = await(_postgre.DialogMessages
                                     .Where(d => d.DialogId == dialogId)
                                     .OrderBy(m => m.Created)
                                     .Select(res => new
                {
                    dialogId    = res.DialogId,
                    message     = res.Message,
                    created     = string.Format("{0:f}", res.Created),
                    userId      = res.UserId,
                    isMyMessage = res.IsMyMessage
                })
                                     .ToListAsync());

                // Приведет к типу MessageOutput.
                foreach (object messageText in messages)
                {
                    string        jsonString    = JsonSerializer.Serialize(messageText);
                    MessageOutput messageOutput = JsonSerializer.Deserialize <MessageOutput>(jsonString);

                    // Проставит флаг принадлежности сообщения.
                    messageOutput.IsMyMessage = messageOutput.UserId.Equals(userId);

                    // Затирает Id пользователя, чтобы фронт не видел.
                    messageOutput.UserId = null;

                    messagesList.Messages.Add(messageOutput);
                }
                messagesList.DialogState = DialogStateEnum.Open.ToString();

                return(messagesList);
            }

            catch (Exception ex)
            {
                Logger logger = new Logger(_db, ex.GetType().FullName, ex.Message, ex.StackTrace);
                await logger.LogCritical();

                throw new Exception(ex.Message);
            }
        }
예제 #20
0
        public override Task Invoke(AMFContext context)
        {
            MessageOutput messageOutput = context.MessageOutput;

            for (int i = 0; i < context.AMFMessage.BodyCount; i++)
            {
                AMFBody      amfBody      = context.AMFMessage.GetBodyAt(i);
                ResponseBody responseBody = null;
                //Check for Flex2 messages and skip
                if (amfBody.IsEmptyTarget)
                {
                    continue;
                }

                //Check if response exists.
                responseBody = messageOutput.GetResponse(amfBody);
                if (responseBody != null)
                {
                    continue;
                }

                try
                {
                    MessageBroker   messageBroker   = _endpoint.GetMessageBroker();
                    RemotingService remotingService = messageBroker.GetService(RemotingService.RemotingServiceId) as RemotingService;
                    if (remotingService == null)
                    {
                        string serviceNotFound = __Res.GetString(__Res.Service_NotFound, RemotingService.RemotingServiceId);
                        responseBody = new ErrorResponseBody(amfBody, new AMFException(serviceNotFound));
                        messageOutput.AddBody(responseBody);
                        continue;
                    }
                    Destination destination = null;
                    if (destination == null)
                    {
                        destination = remotingService.GetDestinationWithSource(amfBody.TypeName);
                    }
                    if (destination == null)
                    {
                        destination = remotingService.DefaultDestination;
                    }
                    //At this moment we got a destination with the exact source or we have a default destination with the "*" source.
                    if (destination == null)
                    {
                        string destinationNotFound = __Res.GetString(__Res.Destination_NotFound, amfBody.TypeName);
                        responseBody = new ErrorResponseBody(amfBody, new AMFException(destinationNotFound));
                        messageOutput.AddBody(responseBody);
                        continue;
                    }

                    //Cache check
                    string source        = amfBody.TypeName + "." + amfBody.Method;
                    IList  parameterList = amfBody.GetParameterList();

                    FactoryInstance factoryInstance = destination.GetFactoryInstance();
                    factoryInstance.Source = amfBody.TypeName;
                    object instance = factoryInstance.Lookup();

                    if (instance != null)
                    {
                        bool isAccessible = TypeHelper.GetTypeIsAccessible(instance.GetType());
                        if (!isAccessible)
                        {
                            string msg = __Res.GetString(__Res.Type_InitError, amfBody.TypeName);
                            responseBody = new ErrorResponseBody(amfBody, new AMFException(msg));
                            messageOutput.AddBody(responseBody);
                            continue;
                        }

                        MethodInfo mi = null;
                        if (!amfBody.IsRecordsetDelivery)
                        {
                            mi = MethodHandler.GetMethod(instance.GetType(), amfBody.Method, amfBody.GetParameterList());
                        }
                        else
                        {
                            //will receive recordsetid only (ignore)
                            mi = instance.GetType().GetMethod(amfBody.Method);
                        }
                        if (mi != null)
                        {
                            #region Invocation handling
                            ParameterInfo[] parameterInfos = mi.GetParameters();
                            //Try to handle missing/optional parameters.
                            object[] args = new object[parameterInfos.Length];
                            if (!amfBody.IsRecordsetDelivery)
                            {
                                if (args.Length != parameterList.Count)
                                {
                                    string msg = __Res.GetString(__Res.Arg_Mismatch, parameterList.Count, mi.Name, args.Length);
                                    responseBody = new ErrorResponseBody(amfBody, new ArgumentException(msg));
                                    messageOutput.AddBody(responseBody);
                                    continue;
                                }
                                parameterList.CopyTo(args, 0);
                            }
                            else
                            {
                                if (amfBody.Target.EndsWith(".release"))
                                {
                                    responseBody = new ResponseBody(amfBody, null);
                                    messageOutput.AddBody(responseBody);
                                    continue;
                                }
                                string recordsetId = parameterList[0] as string;
                                string recordetDeliveryParameters = amfBody.GetRecordsetArgs();
                                byte[] buffer = System.Convert.FromBase64String(recordetDeliveryParameters);
                                recordetDeliveryParameters = System.Text.Encoding.UTF8.GetString(buffer);
                                if (recordetDeliveryParameters != null && recordetDeliveryParameters != string.Empty)
                                {
                                    string[] stringParameters = recordetDeliveryParameters.Split(new char[] { ',' });
                                    for (int j = 0; j < stringParameters.Length; j++)
                                    {
                                        if (stringParameters[j] == string.Empty)
                                        {
                                            args[j] = null;
                                        }
                                        else
                                        {
                                            args[j] = stringParameters[j];
                                        }
                                    }
                                    //TypeHelper.NarrowValues(argsStore, parameterInfos);
                                }
                            }

                            TypeHelper.NarrowValues(args, parameterInfos);

                            try
                            {
                                InvocationHandler invocationHandler = new InvocationHandler(mi);
                                object            result            = invocationHandler.Invoke(instance, args);

                                responseBody = new ResponseBody(amfBody, result);
                            }
                            catch (UnauthorizedAccessException exception)
                            {
                                responseBody = new ErrorResponseBody(amfBody, exception);
                            }
                            catch (Exception exception)
                            {
                                if (exception is TargetInvocationException && exception.InnerException != null)
                                {
                                    responseBody = new ErrorResponseBody(amfBody, exception.InnerException);
                                }
                                else
                                {
                                    responseBody = new ErrorResponseBody(amfBody, exception);
                                }
                            }
                            #endregion Invocation handling
                        }
                        else
                        {
                            responseBody = new ErrorResponseBody(amfBody, new MissingMethodException(amfBody.TypeName, amfBody.Method));
                        }
                    }
                    else
                    {
                        responseBody = new ErrorResponseBody(amfBody, new TypeInitializationException(amfBody.TypeName, null));
                    }
                }
                catch (Exception exception)
                {
                    responseBody = new ErrorResponseBody(amfBody, exception);
                }
                messageOutput.AddBody(responseBody);
            }

            return(Task.FromResult <object>(null));
        }
        public async Task StartShutdownAsync()
        {
            if (ShutdownStarted)
            {
                return;
            }

            try
            {
                MessageOutput.Clear();

                ShutdownType = 1;
                Application.Current.Dispatcher.Invoke(() => this.Cursor = System.Windows.Input.Cursors.Wait);
                Application.Current.Dispatcher.Invoke(() => this.CancelShutdownButton.Cursor = System.Windows.Input.Cursors.Arrow);

                var app = new ServerApp(true)
                {
                    CheckForOnlinePlayers = this.CheckForOnlinePlayers,
                    SendMessages          = this.SendShutdownMessages,
                    BackupWorldFile       = this.BackupWorldFile,
                    ShutdownInterval      = this.ShutdownInterval,
                    ShutdownReason        = this.ShutdownReason,
                    OutputLogs            = false,
                    SendAlerts            = true,
                    ServerProcess         = RestartServer ? ServerProcessType.Restart : ServerProcessType.Shutdown,
                    ProgressCallback      = (p, m, n) => { TaskUtils.RunOnUIThreadAsync(() => { this.AddMessage(m, n); }).DoNotWait(); },
                };

                // if restarting the serverm, then check and update the public IP address
                if (RestartServer && Config.Default.ManagePublicIPAutomatically)
                {
                    await App.DiscoverMachinePublicIPAsync(false);
                }

                var profile       = ServerProfileSnapshot.Create(Server.Profile);
                var restartServer = RestartServer;
                var updateServer  = UpdateServer;

                _shutdownCancellationSource = new CancellationTokenSource();

                var exitCode = await Task.Run(() => app.PerformProfileShutdown(profile, restartServer, updateServer, false, _shutdownCancellationSource.Token));

                if (exitCode != ServerApp.EXITCODE_NORMALEXIT && exitCode != ServerApp.EXITCODE_CANCELLED)
                {
                    throw new ApplicationException($"An error occured during the shutdown process - ExitCode: {exitCode}");
                }

                if (restartServer)
                {
                    profile.Update(Server.Profile);
                    Server.Profile.SaveProfile();
                }

                ShutdownType = 0;
                // if restarting or updating the server after the shutdown, delay the form closing
                if (restartServer || updateServer)
                {
                    await Task.Delay(5000);
                }

                if (CloseShutdownWindowWhenFinished)
                {
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, _globalizer.GetResourceString("ServerSettings_ShutdownServer_FailedTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
                ShutdownType = 0;
            }
            finally
            {
                _shutdownCancellationSource = null;
                Application.Current.Dispatcher.Invoke(() => this.Cursor = null);
                Application.Current.Dispatcher.Invoke(() => this.CancelShutdownButton.Cursor = null);
            }
        }
        private async void StartListening()
        {
            LogOutput.Trigger("Starting to listen for input.");
            Listening = true;
            while (Listening)
            {
                try
                {
                    // Based on the protocol we've defined, the first uint is the size of the message. [UInt (4)] + [Message (1*n)] - The UInt describes the length of the message.
                    uint readLength = await reader.LoadAsync(sizeof(uint));

                    // Check if the size of the data is expected (otherwise the remote has already terminated the connection).
                    if (!Listening)
                    {
                        break;
                    }
                    if (readLength < sizeof(uint))
                    {
                        Listening = false;
                        Disconnect();
                        LogOutput.Trigger("The connection has been terminated.");
                        break;
                    }

                    uint messageLength = reader.RReadUint();                      //

                    LogOutput.Trigger("messageLength: " + messageLength.ToString());

                    // Load the rest of the message since you already know the length of the data expected.
                    readLength = await reader.LoadAsync(messageLength);

                    // Check if the size of the data is expected (otherwise the remote has already terminated the connection).
                    if (!Listening)
                    {
                        break;
                    }
                    if (readLength < messageLength)
                    {
                        Listening = false;
                        Disconnect();
                        LogOutput.Trigger("The connection has been terminated.");
                        break;
                    }

                    string message = reader.ReadString(messageLength);
                    MessageOutput.Trigger("Received message: " + message);
                    if (DO_RESPONSE)
                    {
                        SendMessage("abcdefghij");
                    }
                }
                catch (Exception e)
                {
                    // If this is an unknown status it means that the error is fatal and retry will likely fail.
                    if (SocketError.GetStatus(e.HResult) == SocketErrorStatus.Unknown)
                    {
                        Listening = false;
                        Disconnect();
                        LogOutput.Trigger("Fatal unknown error occurred.");
                        break;
                    }
                }
            }
            LogOutput.Trigger("Stopped to listen for input.");
        }
예제 #23
0
        public override void Invoke(AMFContext context)
        {
            MessageOutput messageOutput = context.MessageOutput;

            for (int i = 0; i < context.AMFMessage.BodyCount; i++)
            {
                AMFBody amfBody = context.AMFMessage.GetBodyAt(i);
                //Check for Flex2 messages
                if (amfBody.IsEmptyTarget)
                {
                    object content = amfBody.Content;
                    if (content is IList)
                    {
                        content = (content as IList)[0];
                    }
                    IMessage message = content as IMessage;
                    if (message != null)
                    {
                        Client      client  = null;
                        HttpSession session = null;
                        if (FluorineContext.Current.Client == null)
                        {
                            IClientRegistry clientRegistry = _endpoint.GetMessageBroker().ClientRegistry;
                            string          clientId       = message.GetFlexClientId();
                            if (!clientRegistry.HasClient(clientId))
                            {
                                lock (clientRegistry.SyncRoot)
                                {
                                    if (!clientRegistry.HasClient(clientId))
                                    {
                                        client = _endpoint.GetMessageBroker().ClientRegistry.GetClient(clientId) as Client;
                                    }
                                }
                            }
                            if (client == null)
                            {
                                client = _endpoint.GetMessageBroker().ClientRegistry.GetClient(clientId) as Client;
                            }
                            FluorineContext.Current.SetClient(client);
                        }
                        session = _endpoint.GetMessageBroker().SessionManager.GetHttpSession(HttpContext.Current);
                        FluorineContext.Current.SetSession(session);
                        //Context initialized, notify listeners.
                        if (session != null && session.IsNew)
                        {
                            session.NotifyCreated();
                        }
                        if (client != null)
                        {
                            if (session != null)
                            {
                                client.RegisterSession(session);
                            }
                            if (client.IsNew)
                            {
                                client.Renew(_endpoint.ClientLeaseTime);
                                client.NotifyCreated();
                            }
                        }

                        /*
                         * RemotingConnection remotingConnection = null;
                         * foreach (IConnection connection in client.Connections)
                         * {
                         *  if (connection is RemotingConnection)
                         *  {
                         *      remotingConnection = connection as RemotingConnection;
                         *      break;
                         *  }
                         * }
                         * if (remotingConnection == null)
                         * {
                         *  remotingConnection = new RemotingConnection(_endpoint, null, client.Id, null);
                         *  remotingConnection.Initialize(client, session);
                         * }
                         * FluorineContext.Current.SetConnection(remotingConnection);
                         */
                    }
                }
                else
                {
                    //Flash remoting
                    AMFHeader amfHeader = context.AMFMessage.GetHeader(AMFHeader.AMFDSIdHeader);
                    string    amfDSId   = null;
                    if (amfHeader == null)
                    {
                        amfDSId = Guid.NewGuid().ToString("D");
                        ASObject asoObjectDSId = new ASObject();
                        asoObjectDSId["name"]           = AMFHeader.AMFDSIdHeader;
                        asoObjectDSId["mustUnderstand"] = false;
                        asoObjectDSId["data"]           = amfDSId;//set
                        AMFHeader headerDSId = new AMFHeader(AMFHeader.RequestPersistentHeader, true, asoObjectDSId);
                        context.MessageOutput.AddHeader(headerDSId);
                    }
                    else
                    {
                        amfDSId = amfHeader.Content as string;
                    }

                    Client      client  = null;
                    HttpSession session = null;
                    if (FluorineContext.Current.Client == null)
                    {
                        IClientRegistry clientRegistry = _endpoint.GetMessageBroker().ClientRegistry;
                        string          clientId       = amfDSId;
                        if (!clientRegistry.HasClient(clientId))
                        {
                            lock (clientRegistry.SyncRoot)
                            {
                                if (!clientRegistry.HasClient(clientId))
                                {
                                    client = _endpoint.GetMessageBroker().ClientRegistry.GetClient(clientId) as Client;
                                }
                            }
                        }
                        if (client == null)
                        {
                            client = _endpoint.GetMessageBroker().ClientRegistry.GetClient(clientId) as Client;
                        }
                    }
                    FluorineContext.Current.SetClient(client);
                    session = _endpoint.GetMessageBroker().SessionManager.GetHttpSession(HttpContext.Current);
                    FluorineContext.Current.SetSession(session);
                    //Context initialized, notify listeners.
                    if (session != null && session.IsNew)
                    {
                        session.NotifyCreated();
                    }
                    if (client != null)
                    {
                        if (session != null)
                        {
                            client.RegisterSession(session);
                        }
                        if (client.IsNew)
                        {
                            client.Renew(_endpoint.ClientLeaseTime);
                            client.NotifyCreated();
                        }
                    }
                }
            }
        }
예제 #24
0
        protected override void InitializeSecurity()
        {
            Dictionary <string, string> message;
            var dhg = new DiffieHellmanGenerator();

            // Stage 1: Await key request
            message = WaitForKey("request");
            if (message == null)
            {
                MessageOutput.Log("Invalid request from client; expected keys");
                return;
            }

            // Stage 2: Send keys
            var publicKeys = primesReader.GetRandomKeystore();
            var secretB    = dhg.GenerateSecret();
            var transportB = dhg.GenerateTransport(secretB, publicKeys);

            Send(publicKeys.GetJson());

            // Stage 3: Send b, await a
            message = WaitForKey("a");
            Send(new Dictionary <string, string>
            {
                { "b", transportB.ToString() }
            });
            if (message == null)
            {
                MessageOutput.Log("Invalid response from client; expected a");
                return;
            }

            // Stage 4: Calculate shared secret
            var transportA = BigInteger.Parse(message["a"]);

            SharedSecret = dhg.GenerateSharedSecret(secretB, transportA, publicKeys);

            // Stage 5: Await encryption
            message = WaitForJson();
            if (message == null)
            {
                return;
            }

            if (message.ContainsKey("encryption"))
            {
                SetEncryption(message["encryption"]);
                MessageOutput.Log("Connection summary:\n" +
                                  $"\tp: {publicKeys.P}\n" +
                                  $"\tg: {publicKeys.G}\n" +
                                  $"\tsecret: {secretB}\n" +
                                  $"\ttransport: {transportB}\n" +
                                  $"\treceived transport: {transportA}\n" +
                                  $"\tshared secret: {SharedSecret}\n" +
                                  $"\tencryption: {message["encryption"]}");
            }
            else
            {
                // Client skipped encryption step; assume none and handle the message.
                SetEncryption("none");
                MessageOutput.Log("Connection summary:\n" +
                                  $"\tp: {publicKeys.P}\n" +
                                  $"\tg: {publicKeys.G}\n" +
                                  $"\tsecret: {secretB}\n" +
                                  $"\ttransport: {transportB}\n" +
                                  $"\treceived transport: {transportA}\n" +
                                  $"\tshared secret: {SharedSecret}\n" +
                                  $"\tencryption: none");
                message["msg"] = Encoding.UTF8.GetString(Convert.FromBase64String(message["msg"]));
                MessageOutput.HandleMessage(message);
            }
        }