Example #1
0
        /// <summary>
        /// Constructor to initialize threads.
        /// </summary>
        public TwitchService(IConfiguration configuration)
        {
            Threads = new List <ServiceThread>();

            Username = configuration.GetSection("Credentials:Username").Value;
            string Password = configuration.GetSection("Credentials:Password").Value;

            // initializing client
            this.TCPClient = new TcpClient(TWITCH_HOST, TWITCH_PORT);
            this.Reader    = new StreamReader(TCPClient.GetStream());
            this.Writer    = new StreamWriter(TCPClient.GetStream());

            // logs in
            Task.Run(async() => await Writer.WriteLineAndFlushAsync(
                         "PASS " + Password + Environment.NewLine +
                         "NICK " + Username + Environment.NewLine +
                         "USER " + Username + " 8 * :" + Username
                         )).Wait();
            // Adds membership state event (NAMES, JOIN, PART, or MODE) functionality.
            //By default we do not send this data to clients without this capability.
            //await st.Writer.WriteLineAndFlushAsync(
            //     "CAP REQ :twitch.tv/membership"
            // );

            // Enables USERSTATE, GLOBALUSERSTATE, ROOMSTATE, HOSTTARGET, NOTICE and CLEARCHAT raw commands.
            Task.Run(async() => await Writer.WriteLineAndFlushAsync(
                         "CAP REQ :twitch.tv/commands"
                         )).Wait();

            // Adds IRC v3 message tags to PRIVMSG, USERSTATE, NOTICE and GLOBALUSERSTATE (if enabled with commands CAP)
            Task.Run(async() => await Writer.WriteLineAndFlushAsync(
                         "CAP REQ :twitch.tv/tags"
                         )).Wait();
        }
Example #2
0
        public void DownloadToClient(String server, string remotefilename, string localfilename)
        {
            try
            {
                TCPClient tcpc = new TCPClient();
                Byte[]    read = new Byte[1024];

                OptionsLoader ol   = new OptionsLoader();
                int           port = 0;
                if (ol.Port > 0)
                {
                    port = ol.Port;
                }
                else
                {
                    // The default in case nothing else is set
                    port = 8081;
                }


                // Try to connect to the server
                IPAddress  adr = new IPAddress(server);
                IPEndPoint ep  = new IPEndPoint(adr, port);
                if (tcpc.Connect(ep) == -1)
                {
                    throw new Exception("Unable to connect to " + server + " on port " + port);
                }

                // Get the stream
                Stream s = tcpc.GetStream();
                Byte[] b = Encoding.ASCII.GetBytes(remotefilename.ToCharArray());
                s.Write(b, 0, b.Length);
                int          bytes;
                FileStream   fs = new FileStream(localfilename, FileMode.OpenOrCreate);
                BinaryWriter w  = new BinaryWriter(fs);

                // Read the stream and convert it to ASII
                while ((bytes = s.Read(read, 0, read.Length)) != 0)
                {
                    w.Write(read, 0, bytes);
                    read = new Byte[1024];
                }

                tcpc.Close();
                w.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }
        /// <summary>
        /// Connects the control room application to the PLC software through a TCPConnection
        /// that is established over ethernet.
        /// </summary>
        /// <returns> Returns a bool indicating whether or not the connection established successfully. </returns>
        private bool ConnectToPLC()
        {
            // This is one of 3 connect methods that must be used to connect the client
            // instance with the endpoint (IP address and port number) listed.
            TCPClient.Connect(ConnectionEndpoint);

            // This gets the stream that the client is connected to above.
            // Stream is how we will write our data back and forth between
            // the PLC.
            Stream = TCPClient.GetStream();

            logger.Info($"Established TCP connection at ({ConnectionEndpoint.Address}, {ConnectionEndpoint.Port}).");
            return(TCPClient.Client.Connected);
        }
Example #4
0
 public async Task Connect(string Server, int Port)
 {
     try
     {
         TCPClient.Connect(Server, Port);
         SSLStream = new SslStream(TCPClient.GetStream(), false,
                                   (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) =>
         {
             return(true);
         })
         {
             ReadTimeout = 50000, WriteTimeout = 50000
         };
         await SSLStream.AuthenticateAsClientAsync(Server);
     }
     catch
     {
     }
 }
        /// <summary>
        /// Writes a message to the network stream that is connecting this application
        /// to the application running the PLC hardware.
        /// </summary>
        /// <param name="message"> A string that represents the state of the object. </param>
        public void WriteMessage(string message)
        {
            // Convert the message passed in into a byte[] array.
            Data = System.Text.Encoding.ASCII.GetBytes(message);

            // If the connection to the PLC is successful, get the NetworkStream
            // that is being used and write to it.
            if (ConnectToPLC())
            {
                try {
                    Stream = TCPClient.GetStream();

                    Stream.Write(Data, 0, Data.Length);

                    logger.Info("Sent message to PLC over TCP.");
                } catch (SocketException e) {
                    Console.WriteLine($"Encountered a socket exception.");
                    logger.Error($"There was an issue with the socket: {e.Message}.");
                }
            }
        }
Example #6
0
        //Check For the MODE Passive or Port
        private NetworkStream Mode(bool PassiveMode, ref TCPClient client, ref Socket clientSocket, string strIP, int Port)
        {
            Thread        oThread = Thread.CurrentThread;
            NetworkStream nw      = null;

            lock (oThread)
            {
                if (PassiveMode)
                {
                    //Socket is Opened
                    if (clientSocket != null)
                    {
                        nw = new NetworkStream(clientSocket, FileAccess.ReadWrite);
                    }
                }
                else
                {
                    //Client Need to be Connected
                    client = new TCPClient(strIP, Port);
                    nw     = client.GetStream();
                }
            }
            return(nw);
        }
Example #7
0
        public override void Start()
        {
            try
            {
                // Setting up the variables for listener
                ListenPort = int.Parse(Program.configuration["LISTENPORT"]);

                // Setting the service status
                Status = true;

                // Get a new session link.

                while (Status)
                {
                    // Listener is configuring
                    TCPService = new TcpListener(IPAddress.Any, ListenPort);

                    // Start listening for client requests.
                    TCPService.Start();

                    Console.Error.WriteLine("Waiting for linking... ");

                    // Perform a blocking call to accept requests.
                    TCPClient = TCPService.AcceptTcpClient();

                    Console.Error.WriteLine("The implant is being linked.");
                    LinkStatus = true;

                    Console.Error.WriteLine("Stopping the service as the implant is being linked.");
                    // Stopping the listener as the implant is being linked.
                    TCPService.Stop();

                    // Read stream as string and process
                    while (LinkStatus)
                    {
                        // Get a stream object for reading and writing
                        NetworkStream stream = TCPClient.GetStream();

                        // Creating StreamString class for string based communications
                        TCPClientStream = new StreamString(stream);

                        //Instruction received from the TCP client...
                        string instruction = TCPClientStream.ReadString();
                        instruction = Common.Decrypt(instruction);

                        //Instruction is processing...
                        Instructions.Instruct(instruction);
                    }
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("TCP Service Exception on Receive: " + e);
                Status     = false;
                LinkStatus = false;
            }
            finally
            {
                Stop();
            }
        }
Example #8
0
        public void DownloadToClient(String server, string remotefilename, string localfilename)
        {
            try
            {
                TCPClient tcpc = new TCPClient();
                Byte[] read = new Byte[1024];

                OptionsLoader ol = new OptionsLoader();
                int port = 0;
                if (ol.Port > 0)
                {
                    port = ol.Port;
                }
                else
                {
                    // The default in case nothing else is set
                    port = 8081;
                }

                // Try to connect to the server
                IPAddress adr = new IPAddress(server);
                IPEndPoint ep = new IPEndPoint(adr, port);
                if (tcpc.Connect(ep) == -1)
                {
                    throw new Exception("Unable to connect to " + server + " on port " + port);
                }

                // Get the stream
                Stream s = tcpc.GetStream();
                Byte[] b = Encoding.ASCII.GetBytes(remotefilename.ToCharArray());
                s.Write( b, 0,  b.Length );
                int bytes;
                FileStream fs = new FileStream(localfilename, FileMode.OpenOrCreate);
                BinaryWriter w = new BinaryWriter(fs);

                // Read the stream and convert it to ASII
                while( (bytes = s.Read(read, 0, read.Length)) != 0)
                {
                    w.Write(read, 0, bytes);
                    read = new Byte[1024];
                }

                tcpc.Close();
                w.Close();
                fs.Close();
            }
            catch(Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }
Example #9
0
        public override void Start()
        {
            try
            {
                // Setting up the variables for listener
                ListenPort = int.Parse(Program.configuration["LISTENPORT"]);

                // Setting the service status
                Status = true;

                // Get a new session link.

                while (Status)
                {
                    // Listener is configuring
                    TCPService = new TcpListener(IPAddress.Any, ListenPort);

                    // Start listening for client requests.
                    TCPService.Start();

                    Console.Error.WriteLine("Waiting for linking... ");

                    // Perform a blocking call to accept requests.
                    TCPClient = TCPService.AcceptTcpClient();

                    Console.Error.WriteLine("The implant is being linked.");
                    LinkStatus = true;

                    Console.Error.WriteLine("Stopping the service as the implant is being linked.");
                    // Stopping the listener as the implant is being linked.
                    TCPService.Stop();

                    // Read stream as string and process
                    while (LinkStatus)
                    {
                        // Get a stream object for reading and writing
                        NetworkStream stream = TCPClient.GetStream();

                        // Creating StreamString class for string based communications
                        TCPClientStream = new StreamString(stream);

                        //Instruction received from the TCP client...
                        string instruction = TCPClientStream.ReadString();
                        instruction = Common.Decrypt(instruction);

                        // If scenario is requested call scenario, otherwise run instructions
                        if (instruction.StartsWith("scenario"))
                        {
                            if (Regex.Split(instruction, " ").Length < 3)
                            {
                                // Set the socket as the Console output
                                Program.consoleIO = Console.Out;
                                Console.SetOut(new SocketWriter());
                                // Raise the error
                                Console.WriteLine("Usage: scenario file filepath");
                            }
                            else
                            {
                                // scenario instruction format:
                                // scenario file BASE64STRING
                                string scenario_b64 = Regex.Split(instruction, " ")[2];
                                // send the Base64 encoded scenario to run
                                PetaqImplant.Scenario.Run(scenario_b64);
                            }
                        }
                        else
                        {
                            // run the instruction received
                            PetaqImplant.Instructions.Instruct(instruction, new SocketWriter());
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("TCP Service Exception on Receive: " + e);
                Status     = false;
                LinkStatus = false;
            }
            finally
            {
                Stop();
            }
        }