Пример #1
0
        /// <summary>
        /// Sends a command to the broker service to initiate the captive portal detection.
        /// </summary>
        public void DetectCaptivePortal()
        {
            var ipcDetectCaptivePortalMsg = new IPCMessage(IPCCommand.IpcDetectCaptivePortal);

            ipcDetectCaptivePortalMsg.AddAttribute("ip", Manager.Settings.Network.CaptivePortalDetectionIp);
            brokerIPC.WriteToPipe(ipcDetectCaptivePortalMsg, promptRestartBrokerServiceOnFail: false);
        }
Пример #2
0
        /// <summary>
        /// Writes a message to the instantiated Windows pipe.
        /// </summary>
        /// <param name="message">IPC message to write.</param>
        /// <returns>True on success.</returns>
        public bool WriteToPipe(IPCMessage message)
        {
            try
            {
                var buffer      = Encoding.UTF8.GetBytes(message.ToString());
                var writeResult = Kernel32.WriteFile(this.writePipe, buffer, (uint)buffer.Length, out uint bytesWritten, IntPtr.Zero);
                if (!writeResult)
                {
                    var lastWindowsError = Marshal.GetLastWin32Error();
                    if (lastWindowsError == ErrorBrokenPipe)
                    {
                        ErrorHandling.ErrorHandler.Handle("Could not write to pipe, got ERROR_BROKEN_PIPE from Windows", ErrorHandling.LogLevel.Debug);
                        this.StopListenerThread();
                    }

                    return(false);
                }
            }
            catch (Exception e)
            {
                ErrorHandling.ErrorHandler.Handle(e, ErrorHandling.LogLevel.Error);
                return(false);
            }

            return(true);
        }
Пример #3
0
 protected override void ProcessCodedUIMessage(ref IPCMessage request)
 {
     if (request.Type == IPCMessage.MessageTypes.GetPropertyValue)
     {
         if (request.Message == "ItemsCount")
         {
             request.Data = (object)this.Items.Count;
             return;
         }
         if (request.Message == "SelectedIndex")
         {
             request.Data = (object)this.SelectedIndex;
             return;
         }
         if (request.Message == "IsMultipleSelection")
         {
             request.Data = (object)(bool)(this.SelectionMode == SelectionMode.MultiSimple ? 1 : (this.SelectionMode == SelectionMode.MultiExtended ? 1 : 0));
             return;
         }
         if (request.Message == "DataSource")
         {
             if (this.DataSource != null)
             {
                 request.Data = (object)this.DataSource.ToString();
                 return;
             }
             request.Data = (object)"(none)";
             return;
         }
     }
     base.ProcessCodedUIMessage(ref request);
 }
Пример #4
0
        /// <summary>
        /// Writes a message to a named pipe.
        /// </summary>
        /// <param name="pipe">Named pipe instance to write to.</param>
        /// <param name="message">IPCMessage to send.</param>
        public static void WriteToPipe(NamedPipeClientStream pipe, IPCMessage message)
        {
            var bytes = Encoding.UTF8.GetBytes(message.ToString());

            pipe.Write(bytes, 0, bytes.Length);
            pipe.Flush();
        }
Пример #5
0
        protected IPCPacket(IPCMessage message)
        {
            writeStream = new BinaryWriter(new MemoryStream());

            Message = message;

            writeStream.Write((byte)message);
        }
Пример #6
0
        protected IPCPacket(IPCMessage message)
        {
            writeStream = new BinaryWriter(new MemoryStream());

            Message = message;

            writeStream.Write((byte)message);
        }
Пример #7
0
        private void OnMessageSended(IPCMessage message)
        {
            Action <IPCAccessor, IPCMessage> messageSent = this.MessageSent;

            if (messageSent != null)
            {
                messageSent(this, message);
            }
        }
Пример #8
0
        private void OnMessageReceived(IPCMessage message)
        {
            Action <IPCAccessor, IPCMessage> messageReceived = this.MessageReceived;

            if (messageReceived != null)
            {
                messageReceived(this, message);
            }
        }
Пример #9
0
        protected override void ProcessAnswer(IIPCRequest request, IPCMessage answer)
        {
            if (request.TimedOut)
            {
                logger.Warn("Message {0} already timed out, message ignored", request.RequestMessage.GetType());
                return;
            }

            request.ProcessMessage(answer);
        }
Пример #10
0
 public override void Send(IPCMessage message)
 {
     if (Connected)
     {
         SocketAsyncEventArgs socketAsyncEventArgs = new SocketAsyncEventArgs();
         byte[] array = IPCMessageSerializer.Instance.SerializeWithLength(message);
         socketAsyncEventArgs.SetBuffer(array, 0, array.Length);
         Socket.SendAsync(socketAsyncEventArgs);
     }
 }
Пример #11
0
 protected override void ProcessCodedUIMessage(ref IPCMessage request)
 {
     if (request.Type == IPCMessage.MessageTypes.GetPropertyValue && request.Message == "Lines")
     {
         request.Data = (object)this.Rows.Count;
     }
     else
     {
         base.ProcessCodedUIMessage(ref request);
     }
 }
Пример #12
0
 protected override void ProcessRequest(IPCMessage request)
 {
     try
     {
         m_operations.HandleMessage(request);
     }
     catch (Exception ex)
     {
         SendError(ex, request);
     }
 }
Пример #13
0
        protected override bool HandleGenericMessage(IPCMessage msg)
        {
            switch (msg.Type)
            {
            case tysos.Messages.Message.MESSAGE_NET_REGISTER_DEVICE:
                RegisterDevice(msg.Message as string);
                return(true);

            default:
                return(false);
            }
        }
Пример #14
0
        public void HandleMessage(IPCMessage message)
        {
            Action <object, IPCMessage> handler;

            if (!m_handlers.TryGetValue(message.GetType(), out handler))
            {
                logger.Error("Received message {0} but no method handle it !", message.GetType());
                return;
            }

            handler(this, message);
        }
Пример #15
0
        private void OnStartMessage(int sender, IPCMessage msg)
        {
            StartMessage startMsg = (StartMessage)msg;

            Chat.WriteLine("OnStartMessage");
            ActiveGlobalSettings = new GlobalSettings
            {
                Sector = startMsg.Sector
            };
            Leader = new Identity(IdentityType.SimpleChar, sender);
            Start();
        }
Пример #16
0
        public override void Send(IPCMessage message)
        {
            if (this.IsReacheable)
            {
                SocketAsyncEventArgs socketAsyncEventArgs = new SocketAsyncEventArgs();
                socketAsyncEventArgs.Completed += new System.EventHandler <SocketAsyncEventArgs>(this.OnSendCompleted);
                byte[] array = Singleton <IPCMessageSerializer> .Instance.SerializeWithLength(message);

                socketAsyncEventArgs.SetBuffer(array, 0, array.Length);
                this.Socket.SendAsync(socketAsyncEventArgs);
            }
        }
Пример #17
0
        public void HandleMessage(IPCMessage message)
        {
            Action <object, IPCMessage> action;

            if (!m_handlers.TryGetValue(message.GetType(), out action))
            {
                IPCOperations.logger.Error <Type>("Received message {0} but no method handle it !", message.GetType());
            }
            else
            {
                action(this, message);
            }
        }
Пример #18
0
        private void OnStartMessage(int sender, IPCMessage msg)
        {
            StartMessage startMsg = (StartMessage)msg;

            Chat.WriteLine("OnStartMessage");
            ActiveGlobalSettings = new GlobalSettings
            {
                MissionDifficulty = startMsg.MissionDifficulty,
                MissionFaction    = startMsg.MissionFaction
            };
            Leader = new Identity(IdentityType.SimpleChar, sender);
            Start();
        }
Пример #19
0
 protected override void ProcessCodedUIMessage(ref IPCMessage request)
 {
     if (request.Type == IPCMessage.MessageTypes.GetPropertyValue)
     {
         bool flag = request.ControlType == "DropDownButton";
         if (request.Data != null)
         {
             flag = flag | request.Data.ToString().ToLower().Contains("splitbutton") | request.Data.ToString().ToLower().Contains("dropdownbutton");
         }
         if (request.Message == "ItemsCount" && flag)
         {
             if (request.Data != null && !string.IsNullOrEmpty(request.Data.ToString()))
             {
                 string str = request.Data.ToString();
                 foreach (RadItem radItem in (RadItemCollection)this.Items)
                 {
                     if (radItem.Name == str && radItem is RadDropDownButtonElement)
                     {
                         request.Data = (object)(radItem as RadDropDownButtonElement).Items.Count;
                         return;
                     }
                 }
             }
             request.Data = (object)0;
             return;
         }
         if (request.Message == "HasChildNodes" && flag)
         {
             if (request.Data != null && !string.IsNullOrEmpty(request.Data.ToString()))
             {
                 string str = request.Data.ToString();
                 foreach (RadItem radItem in (RadItemCollection)this.Items)
                 {
                     if (radItem.Name == str && radItem is RadDropDownButtonElement)
                     {
                         request.Data = (object)((radItem as RadDropDownButtonElement).Items.Count > 0);
                         return;
                     }
                 }
             }
             request.Data = (object)0;
             return;
         }
         if (request.Message == "ItemsCount")
         {
             request.Data = (object)this.Items.Count;
             return;
         }
     }
     base.ProcessCodedUIMessage(ref request);
 }
Пример #20
0
 protected override void ProcessRequest(IPCMessage message)
 {
     if (m_operations == null)
     {
         if (!(message is HandshakeMessage))
         {
             SendError(string.Format("The first received packet should be a HandshakeMessage not {0}", message.GetType()));
             Disconnect();
         }
         else
         {
             HandshakeMessage handshakeMessage = message as HandshakeMessage;
             WorldServer      server;
             try
             {
                 server = WorldServerManager.Instance.RequestConnection(this, handshakeMessage.World);
             }
             catch (Exception exception)
             {
                 SendError(exception);
                 Disconnect();
                 return;
             }
             Server       = server;
             m_operations = new IPCOperations(this);
             Send(new CommonOKMessage
             {
                 RequestGuid = message.RequestGuid
             });
         }
     }
     else
     {
         if (message.RequestGuid != Guid.Empty)
         {
             m_currentRequest = message;
         }
         else
         {
             m_currentRequest = null;
         }
         try
         {
             m_operations.HandleMessage(message);
         }
         catch (Exception exception)
         {
             SendError(exception);
         }
     }
 }
Пример #21
0
        /// <summary>
        /// Sends a disconnect command to the Broker.
        /// </summary>
        /// <returns>True if successfully sent disconnection command.</returns>
        public bool Disconnect()
        {
            var disconnectMessage = new IPCMessage(IPCCommand.IpcDisconnect);

            var writeToPipeResult = brokerIPC.WriteToPipe(disconnectMessage);

            if (writeToPipeResult)
            {
                uptimeStart = DateTime.MinValue;
                SetDisconnecting();
            }

            return(writeToPipeResult);
        }
Пример #22
0
        /// <summary>
        /// Switches the VPN server to a different endpoint.
        /// </summary>
        /// <param name="endpoint">Endpoint (VPN server) IP address.</param>
        /// <param name="publicKey">Public key of remote VPN server.</param>
        /// <returns>True if successfully sent the switch command.</returns>
        public bool SwitchServer(string endpoint, string publicKey)
        {
            NamedPipeClientStream tunnelPipe = null;

            try
            {
                using (tunnelPipe = ConnectWGTunnelNamedPipe())
                {
                    if (tunnelPipe == null)
                    {
                        return(false);
                    }

                    var serverSwitchRequest = new IPCMessage(IPCCommand.WgSet);
                    serverSwitchRequest.AddAttribute("replace_peers", "true");
                    serverSwitchRequest.AddAttribute("public_key", BitConverter.ToString(Convert.FromBase64String(publicKey)).Replace("-", string.Empty).ToLower());
                    serverSwitchRequest.AddAttribute("endpoint", endpoint);

                    var allowedIPs = ProductConstants.AllowedIPs.Split(',').Select(ip => ip.Trim()).ToList();
                    allowedIPs.ForEach(ip => serverSwitchRequest.AddAttribute("allowed_ip", ip));

                    IPC.WriteToPipe(tunnelPipe, serverSwitchRequest);

                    var response = IPC.ReadFromPipe(tunnelPipe);
                    var errno    = response["errno"].FirstOrDefault();
                    if (errno == null || errno != "0")
                    {
                        throw new Exception("Set request UAPI error " + errno);
                    }

                    // Update IP info.
                    Manager.IPInfoUpdater.ForceUpdate();
                }
            }
            catch (Exception e)
            {
                ErrorHandling.ErrorHandler.Handle(e, ErrorHandling.LogLevel.Error);
                return(false);
            }
            finally
            {
                if (tunnelPipe != null && tunnelPipe.IsConnected)
                {
                    tunnelPipe.Close();
                }
            }

            return(true);
        }
Пример #23
0
 protected override void ProcessRequest(IPCMessage request)
 {
     if (request is IPCErrorMessage)
     {
         this.HandleError(request as IPCErrorMessage);
     }
     if (request is DisconnectClientMessage)
     {
         this.HandleMessage(request as DisconnectClientMessage);
     }
     if (this.m_additionalsHandlers.ContainsKey(request.GetType()))
     {
         this.m_additionalsHandlers[request.GetType()](request);
     }
 }
Пример #24
0
        public override void MessageLoop()
        {
            t = Syscalls.SchedulerFunctions.GetCurrentThread();
            Syscalls.SchedulerFunctions.GetCurrentThread().owning_process.MessageServer = this;

            if (InitServer() == false)
            {
                System.Diagnostics.Debugger.Log(0, null, "InitServer failed");
                return;
            }

            while (s != State.Idle)
            {
                ;
            }
            System.Diagnostics.Debugger.Log(0, null, "entering message loop");

            while (true)
            {
                IPCMessage msg = null;
                do
                {
                    msg = Syscalls.IPCFunctions.ReadMessage();

                    if (msg != null)
                    {
                        HandleMessage(msg);
                    }
                } while (msg != null);

                BackgroundProc();

                /* Block on either new messages or having a non-empty command queue */
                Syscalls.SchedulerFunctions.Block(new DelegateEvent(
                                                      delegate()
                {
                    if (t.owning_process.MessagePending == true)
                    {
                        return(true);
                    }
                    if (cmds.Count != 0)
                    {
                        return(true);
                    }
                    return(false);
                }));
            }
        }
Пример #25
0
        protected override void ProcessAnswer(IIPCRequest request, IPCMessage answer)
        {
            if (request.TimedOut)
            {
                logger.Warn("Message {0} already timed out, message ignored", request.RequestMessage.GetType());
                return;
            }

            if (request.TimeoutTimer != null)
            {
                request.TimeoutTimer.Stop();
                TaskPool.RemoveTimer(request.TimeoutTimer);
            }

            request.ProcessMessage(answer);
        }
Пример #26
0
        protected override bool HandleGenericMessage(IPCMessage msg)
        {
            switch (msg.Type)
            {
            case tysos.Messages.Message.MESSAGE_GUI_REGISTER_DISPLAY:
                RegisterDisplay(msg.Message as string);
                return(true);

            case tysos.Messages.Message.MESSAGE_GUI_REGISTER_INPUT:
                RegisterInput(msg.Message as string);
                return(true);

            default:
                return(false);
            }
        }
Пример #27
0
        /// <summary>
        /// Saves a config file to the users' AppData folder and sends a connect command to the Broker.
        /// </summary>
        /// <returns>True if successfully sent connection command.</returns>
        public bool Connect()
        {
            var configFilePath = ProductConstants.FirefoxPrivateNetworkConfFile;
            var connectMessage = new IPCMessage(IPCCommand.IpcConnect);

            connectMessage.AddAttribute("config", configFilePath);

            var writeToPipeResult = brokerIPC.WriteToPipe(connectMessage);

            if (writeToPipeResult)
            {
                uptimeStart = DateTime.MinValue;
                SetConnecting();
            }

            return(writeToPipeResult);
        }
Пример #28
0
 protected override void ProcessCodedUIMessage(ref IPCMessage request)
 {
     if (request.Type == IPCMessage.MessageTypes.GetPropertyValue)
     {
         if (request.Message == "ItemsCount")
         {
             request.Data = (object)this.Items.Count;
             return;
         }
         if (request.Message == "HasChildNodes")
         {
             request.Data = (object)(this.Items.Count > 0);
             return;
         }
     }
     base.ProcessCodedUIMessage(ref request);
 }
Пример #29
0
        static void DemoSendNormalMessages()
        {
            PrintTitle("Demo: Sending 10 Normal Messages");
            InterprocessCommunication comA = new InterprocessCommunication();
            InterprocessCommunication comB = new InterprocessCommunication();

            Console.Write("\r\n  Initializing IPC on 'CommunicationA'");
            if (!comA.Initialize("CommunicationA"))
            {
                Console.Write("\r\n  IPC on 'CommunicationA' failed.\r\n  Last Error: {0}", comA.LastError);
                return;
            }
            Console.Write("\r\n  Successfully initialized IPC on 'CommunicationA'");

            Console.Write("\r\n  Initializing IPC on 'CommunicationB'");
            if (!comB.Initialize("CommunicationB"))
            {
                Console.Write("\r\n  IPC on 'CommunicationB' failed.\r\n  Last Error: {0}", comB.LastError);
                return;
            }
            Console.Write("\r\n  Successfully initialized IPC on 'CommunicationB'");

            Console.Write("\r\n\r\n  Sending 5 messages from 'CommunicationA' to 'CommunicationB' and vice versa");
            for (int i = 0; i < 5; i++)
            {
                comA.PostMessage("CommunicationB", "Command", "Message #" + (i + 1));
                comB.PostMessage("CommunicationA", "Command", "Message #" + (i + 1));
            }

            IPCMessage msg;

            for (int i = 0; i < 5; i++)
            {
                msg = IPCMessage.FromString(comA.GetMessage());
                msg.Print();
                msg = IPCMessage.FromString(comB.GetMessage());
                msg.Print();
            }

            Console.Write("\r\n\r\n  Closing 'CommunicationA' ... "); comA.Dispose(); Console.Write("Closed");
            Console.Write("\r\n  Closing 'CommunicationB' ... "); comB.Dispose(); Console.Write("Closed");
            Console.Write("\r\n\r\n  Sending 10 normal messages demonstration successfully finished.");
            PrintTerminatingTitle();
        }
Пример #30
0
 protected override void ProcessCodedUIMessage(ref IPCMessage request)
 {
     base.ProcessCodedUIMessage(ref request);
     if (this.ButtonElement == null || request == null)
     {
         return;
     }
     if (this.ButtonElement.IsInValidState(true) && request.Type == IPCMessage.MessageTypes.ExecuteMethod && request.Message == "ButtonClick")
     {
         this.ButtonElement.CallDoClick(EventArgs.Empty);
     }
     else
     {
         if (request.Type != IPCMessage.MessageTypes.GetPropertyValue || !(request.Message == "IsPressed"))
         {
             return;
         }
         request.Data = (object)this.ButtonElement.IsPressed;
     }
 }
Пример #31
0
        public override void Send(IPCMessage message)
        {
            if (!IsReacheable)
            {
                return;
            }

            var args = new SocketAsyncEventArgs();

            args.Completed += OnSendCompleted;
            var stream = new MemoryStream();

            IPCMessageSerializer.Instance.SerializeWithLength(message, stream);

            // serialize stuff
            var data = stream.ToArray();

            args.SetBuffer(data, 0, data.Length);
            Socket.SendAsync(args);
        }
 public IPCMessageAttribute(IPCMessage message)
 {
     Message = message;
 }
Пример #33
0
        ////////////////////////////////////////////////////////
        //
        // Listen to Incoming Messages from Service Manager
        //
        ////////////////////////////////////////////////////////
        void ServiceManager_OnServiceManagerEvent(IPCMessage ipcMessage)
        {
            // Debug
            //Console.WriteLine("ServiceManager_OnServiceManagerEvent...\r\n");

            //What type of message - ASR or Headtracker

            if (ipcMessage.MessageType == MessageType.ASR)
            {
                if (ipcMessage.MessageSubType == MessageSubType.Asr_GrammarRecognized)
                {
                    //Last ASR Message
                    this.Invoke(new EventHandler(ASRCommandSpoken), new object[] { ipcMessage.PayloadAsString });
                }
            }

            //Head-tracker Events?
            if (ipcMessage.MessageType == MessageType.Headtracker)
            {
                if (ipcMessage.MessageSubType == MessageSubType.Headtracker_Moved)
                {
                    //Movement is deltaX and deltaY, stored in user1 and user2 parameters of message
                    int deltaX = ipcMessage.User1;
                    int deltaY = ipcMessage.User2;
                }
            }
        }
Пример #34
0
 public EmptyPacket(IPCMessage ipcMessage) : base(ipcMessage)
 {
 }