Esempio n. 1
0
        private static void send(Message message)
        {
            Message response = null;
            try
            {
                Console.WriteLine();
                Console.WriteLine("==========");
                Console.WriteLine();
                Console.WriteLine("request: ");
                Console.WriteLine(message);
                response = client.SendMessage(message, true);
            }
            catch (WebCommunicator.Exceptions.CommunicationException exception)
            {
                Console.WriteLine("Communication Error: " + exception.Message);
            }

            if (response == null)
                return;

            Console.WriteLine();
            Console.WriteLine("Response:");
            Console.WriteLine(response.ToString());

            if (response.Values.ContainsKey("Return"))
            {
                Console.WriteLine("Server responded with the following message:");
                Console.WriteLine(response.Values["Return"]);
            }
        }
Esempio n. 2
0
        protected override void Execute_WebHookCommand(WebhookCommandContext context)
        {
            var interpreter = context.Interpreter;
            var originalCommand = context.OriginalCommand;
            var innerCommands = originalCommand.InnerCommands;

            var webHookEngines = context.WebhookEngines;

            var computerName = context.ReadParameter("ComputerName").Value;

            var outMessage = new Message();

            //Dictionary<string, string> values = new Dictionary<string, string>();
            outMessage.Values.Add("Action", "SendScript");
            outMessage.Values.Add("TargetComputerName", computerName);
            outMessage.Values.Add("ScriptText", innerCommands.OriginalText);

            foreach (var webHookEngine in webHookEngines.Values)
            {
                if (webHookEngine.ComputerName.Equals(computerName))
                {
                    //TODO: improve?
                    interpreter.WriteEvent("hey, that's me!");
                    webHookEngine.AddCommands(innerCommands);
                }
                else
                {
                    webHookEngine.SendMessage(outMessage);
                }
            }
        }
Esempio n. 3
0
 private static void AddDevicesToResponse(Message response, IEnumerable<IDeviceState> devices)
 {
     foreach (var device in devices)
     {
         response.Payload.Add(device.ToXElement());
     }
 }
Esempio n. 4
0
 static void TestDreamingnestMessage(Message message)
 {
     TestMessage
         (
         message: message,
         address: "http://" + host + "/communicator/",
         accessKey: "4241084ebc474b35",
         encryptionKey: "916fa93f32134cf2"
         );
 }
Esempio n. 5
0
        internal static Message SendMessage(RoomieCommandContext context, Message outMessage)
        {
            //TODO: that's not too conclusive.
            if (!WebHookPresent(context))
            {
                throw new RoomieRuntimeException("WebHook not present.");
            }

            Message response = WebHookCommands.Common.SendMessage(context.DataStore, outMessage);

            return response;
        }
Esempio n. 6
0
        private Message buildRequest(INetwork network)
        {
            var message = new Message();
            message.Values.Add("Action", "SyncHomeAutomationNetwork");
            message.Values.Add("NetworkAddress", network.Name);

            foreach (var device in network.Devices)
            {
                message.Payload.Add(device.ToXElement());
            }

            return message;
        }
Esempio n. 7
0
        public override void ProcessMessage(ComputerRecord callingComputer, Message request, Message response)
        {
            //validate input
            if (!request.Values.ContainsKey("HomeID"))
            {
                response.ErrorMessage = "Home ID not set";
                return;
            }
            if (!request.Values.ContainsKey("NodeID"))
            {
                response.ErrorMessage = "Node ID not set";
                return;
            }
            if (!request.Values.ContainsKey("DeviceName"))
            {
                response.ErrorMessage = "Device Name not set.";
                return;
            }
            if (!request.Values.ContainsKey("DeviceType"))
            {
                response.ErrorMessage = "Device Type not set.";
                return;
            }

            //read input
            uint homeId;
            byte nodeId;
            string deviceName;
            ZWaveDeviceType deviceType;
            try
            {
                homeId = Convert.ToUInt32(request.Values["HomeID"]);
                nodeId = Convert.ToByte(request.Values["NodeID"]);
                deviceName = request.Values["DeviceName"];
                deviceType = ZWaveDeviceType.GetTypeFromString(request.Values["DeviceType"]);
            }
            catch
            {
                response.ErrorMessage = "Error parsing input.";
                return;
            }

            ComputerRecord computer = callingComputer;
            UserEntry user = callingComputer.User;
            ZWaveNetworkRecord networkRecord = ZWaveManager.GetNetwork(user, homeId);

            ZWaveManager.RegisterZWaveDevice(networkRecord, nodeId, deviceName, deviceType);

            response.Values.Add("Response", "Device added. HomeID=" + homeId + ", NodeID=" + nodeId + ", Name=\"" + deviceName + "\" Type=\"" + deviceType + "\"");
        }
Esempio n. 8
0
        public static Message SendMessage(DataStore dataStore, Message outMessage)
        {
            var engines = GetWebhookEngines(dataStore);

            if (engines.Count == 0)
                throw new RoomieRuntimeException("No WebHook engines present.");

            if (engines.Count > 1)
                throw new RoomieRuntimeException("Multiple WebHook engines not yet supported.");

            WebHookEngine engine = null;

            //TODO: I know, I know... this is awful.
            foreach (WebHookEngine firstEngine in engines.Values)
                engine = firstEngine;

            return engine.SendMessage(outMessage);
        }
Esempio n. 9
0
        //TODO: work with multiple engines
        protected override void Execute_Definition(RoomieCommandContext context)
        {
            var engine = context.Engine;
            var interpreter = context.Interpreter;
            var scope = context.Scope;
            var originalXml = context.OriginalXml;

            var webhookEngines = Common.GetWebHookEngines(engine);

            var outMessage = new Message();

            foreach (string variableName in scope.Names)
                outMessage.Values.Add(variableName, scope.GetValue(variableName));

            foreach (XmlNode node in originalXml.ChildNodes)
                outMessage.Payload.Add(node);

            Common.SendMessage(engine, outMessage);
        }
Esempio n. 10
0
        public override void ProcessMessage(ComputerRecord callingComputer, Message request, Message response)
        {
            //validate input
            if (!request.Values.ContainsKey("HomeID"))
            {
                response.ErrorMessage = "Home ID not set";
                return;
            }
            if (!request.Values.ContainsKey("NodeID"))
            {
                response.ErrorMessage = "Node ID not set";
                return;
            }

            //read input
            uint? homeId;
            byte nodeId;
            try
            {
                homeId = Convert.ToUInt32(request.Values["HomeID"]);
                nodeId = Convert.ToByte(request.Values["NodeID"]);
            }
            catch
            {
                response.ErrorMessage = "Error parsing input.";
                return;
            }

            UserEntry userRecord = callingComputer.User;
            ZWaveNetworkRecord networkRecord = ZWaveManager.GetNetwork(userRecord, homeId);

            ZWaveDeviceRecord record = ZWaveManager.GetDevice(networkRecord, nodeId);

            if(record == null)
            {
                response.ErrorMessage = "Could not find device to delete";
                return;
            }

            record.DeleteRecord();

            response.Values.Add("Response", "Device with HomeID=" + homeId + "and NodeID= " + nodeId + " deleted.");
        }
Esempio n. 11
0
        static void TestMessage(Message message, string address, string accessKey, string encryptionKey = null)
        {
            WriteDivider();
            Console.WriteLine(message);
            WriteDivider();

            var client = new CommunicatorClient
            (
                url: address,
                accessKey: accessKey,
                encryptionKey: encryptionKey
            );

            Console.WriteLine("Sending message...");

            var response = client.SendMessage(message, encryptionKey != null, 1);

            Console.WriteLine(response.ToString());

            WriteDivider();
        }
Esempio n. 12
0
        static void Main(string[] args)
        {
            byte[] lul = Encoding.UTF8.GetBytes("<");

            Console.WriteLine("I am the client!");

            WebCommunicator.StreamUtilities.RunCryptoSanityCheck();
            Console.WriteLine("\tpassed crypto sanity check.");

            byte[] key = StreamUtilities.StringToByteArray("0123456789abcdef");
            client = new CommunicatorClient("http://localhost:1337", "user_1_key", key);

            Message message1 = new Message();
            message1.Values.Add("Action", "Time?");
            send(message1);

            Message message2 = new Message();
            message2.Values.Add("Action", "Write");
            message2.Values.Add("Text", "Hello from over the network!");
            send(message2);

            Console.ReadKey();
        }
Esempio n. 13
0
        public override void ProcessMessage(ComputerRecord callingComputer, Message request, Message response)
        {
            if (!request.Values.ContainsKey("To"))
            {
                response.ErrorMessage = "To not set.";
                return;
            }
            if (!request.Values.ContainsKey("Subject"))
            {
                response.ErrorMessage = "Subject not set.";
                return;
            }
            if (!request.Values.ContainsKey("Body"))
            {
                response.ErrorMessage = "Body not set.";
                return;
            }

            string to = request.Values["To"];
            string subject = request.Values["Subject"];
            string body = request.Values["Body"];

            bool sent;

            try
            {
                sent = Roomie.WebService.Common.MailerBot.SendMessage(to, subject, body);
                if (sent)
                    response.Values.Add("Response", "mail sent.");
                else
                    response.ErrorMessage = "unknown error sending message to " + to;
            }
            catch(System.Security.SecurityException)
            {
                response.ErrorMessage = "Server denied from sending mail.";
            }
        }
Esempio n. 14
0
        public Message SendMessage(Message outMessage, bool encryptMessage, int tries)
        {
            Message response = null;

            while (tries != 0)
            {
                try
                {
                    response = sendMessage(outMessage, encryptMessage);
                    if (!String.IsNullOrEmpty(response.CommunicationErrorMessage))
                        throw new Exceptions.CommunicationException(response.CommunicationErrorMessage);
                    return response;
                }
                catch (Exceptions.CommunicationException exception)
                {
                    tries--;
                    if (tries == 0)
                        throw exception;
                    response = null;
                }
            }

            return response;
        }
Esempio n. 15
0
        private void Run()
        {
            running = true;
            print("Webhook reading tasks...");

            foreach (RoomieCommand command in roomieController.CommandLibrary)
            {
                if (command.Name.Equals("WebHookConnectTasks"))
                {
                    AddCommand(command.BlankCommandCall());
                }
            }

            //create an outgoing message to request tasks.  This message object will be reused for every transmission.
            Message outMessage = new Message();
            outMessage.Values.Add("Action", "GetTasks");

            while (true)
            {
                try
                {
                    Message response = SendMessage(outMessage);

                    //TODO: use LINQ?
                    foreach (var payloadNode in response.Payload)
                    {
                        if (payloadNode.Name.LocalName.Equals("Script"))
                        {
                            if (payloadNode.Attribute("Text") == null)
                            {
                                throw new RoomieRuntimeException("'Text' attribute not specified for WebHook script response.");
                            }

                            var commands = ScriptCommandList.FromText(payloadNode.Attribute("Text").Value);
                            AddCommands(commands);
                        }
                        else
                        {
                            throw new RoomieRuntimeException("Received unexpected data while gettings tasks.  Node named \"" + payloadNode.Name.LocalName + "\"");
                        }

                    }
                }
                catch (RoomieRuntimeException exception)
                {
                    print(exception.Message);
                    print("sleeping for 10 seconds because of error...");
                    System.Threading.Thread.Sleep(new TimeSpan(0, 0, 10));
                }
            }
        }
Esempio n. 16
0
        public static Message CreatePing()
        {
            var result = new Message();
            result.ReplaceControlValue(ControlActionControlValueName, PingActionControlValueName);

            return result;
        }
Esempio n. 17
0
        private static IEnumerable<IDeviceState> ProcessSentDevices(Message request, Message response, User user,  Network network, IRoomieDatabaseContext database)
        {
            var sentDevices = request.Payload.Select(x => x.ToDeviceState());
            sentDevices = sentDevices.Select(x => x.NewWithNetwork(network));

            return sentDevices;
        }
Esempio n. 18
0
        public override void ProcessMessage(WebHookContext context, Message request, Message response)
        {
            if (!request.Values.ContainsKey("HomeID"))
            {
                response.ErrorMessage = "Home ID not set.";
                return;
            }

            //read input
            uint homeId;
            try
            {
                homeId = Convert.ToUInt32(request.Values["HomeID"]);
            }
            catch
            {
                response.ErrorMessage = "Error parsing input. (1283)";
                return;
            }

            var database = context.Database;
            var computer = context.Computer;
            var user = context.User;

            var network = (from n in database.HomeAutomationNetwork
                           where
                           //n.HomeId == homeId &&
                              n.Owner.Id == user.Id
                           select n).First();

                //          database.ZWaveNetworks
                //.FirstOrDefault(n => n.HomeId == homeId && n.Owner.Id == user.Id);

            if (network == null)
            {
                response.ErrorMessage = "ZWave network with Home ID " + homeId + " not found.";
                return;
            }

            network.AttatchedComputer = computer;
            network.UpdatePing();

            StringBuilder builder = new StringBuilder();
            builder.Append("<DeviceList>");

            foreach (var device in network.Devices)
            {
                builder.Append("<Device Address=\"");
                builder.Append(device.Address);
                builder.Append("\" DeviceName=\"");
                builder.Append(device.Name);
                builder.Append("\" DeviceType=\"");
                builder.Append(device.Type);
                builder.Append("\" />");
            }

            try
            {
                builder.Append("</DeviceList>");
                response.Payload.Add(XmlUtilities.StringToXml(builder.ToString()));
            }
            catch (XmlException)
            {
                response.ErrorMessage = "Error building response XML. (8472)";
                return;
            }

            try
            {
                response.Values.Add("Response", network.Devices.Count + " devices sent");
            }
            catch
            {
                response.ErrorMessage = "Server error: exception parsing XML. (error code 19382)";
            }
        }
Esempio n. 19
0
        //private string timestampPrefix()
        //{
        //    return DateTime.Now.ToString("yyyyMMddHHmmssFFFFFFF");
        //}
        private Message sendMessage(Message request, bool encryptMessage)
        {
            lock (request)
            {
                //TODO: learn how to use compile flags
                //request.ToFile(timestampPrefix() + "_request.xml");

                //calibrate
                if (nextCalibrate == null || nextCalibrate < DateTime.Now)
                {
                    request.ReplaceControlValue(Message.LibraryVersionControlValueName, InternalLibraryVersion.GetLibraryVersion().ToString());

                    nextCalibrate = DateTime.Now.Add(calibrateFrequency);
                }

                System.Net.WebClient webClient = new System.Net.WebClient();

                if (accessKey != null)
                    webClient.QueryString[Message.AccessKeyHeaderName] = accessKey;

                //set encryption is using...
                Aes aes = null;
                if (encryptionKey != null)
                {
                    try
                    {
                        aes = StreamUtilities.GetAesCryptoTransform(encryptionKey, null);
                    }
                    catch (CryptographicException exception)
                    {
                        throw new Exceptions.CommunicationException("Encryption exception.  Is the encryption key the right length?", exception);
                    }
                }

                //message is all ready to go.
                MemoryStream outgoingStream = new MemoryStream();
                Common.WriteMessageStream(outgoingStream, request, sessionKey, aes, encryptMessage);

                //TODO: fix these last-minute converstions to/from arrays
                byte[] responseBytes;
                try
                {
                    responseBytes = webClient.UploadData(url, outgoingStream.ToArray());
                }
                catch (System.Net.WebException exception)
                {
                    throw new Exceptions.CommunicationException(exception.Message);
                }
                MemoryStream responseStream = StreamUtilities.ToMemoryStream(responseBytes);

                Message response = responseStream.ToMessage(aes);

                //update sessionKey
                if (response.controlValues.ContainsKey(Message.NewSessionKeyControlValueName))
                    sessionKey = response.controlValues[Message.NewSessionKeyControlValueName];

                //response.ToFile(timestampPrefix() + "_response.xml");
                return response;
            }
        }
Esempio n. 20
0
 public Message SendMessage(Message request, bool encryptMessage)
 {
     return SendMessage(request, encryptMessage, defaultTries);
 }
Esempio n. 21
0
        public static void WriteMessageStream(MemoryStream outStream, Message outMessage, string sessionKey, Aes aes, bool encrypt)
        {
            outMessage.ReplaceControlValue(Message.TimestampControlValueName, DateTime.Now.ToUniversalTime().ToString());
            outMessage.ReplaceControlValue(Message.SessionKeyControlValueName, sessionKey);
            if (encrypt)
            {
                aes.GenerateIV();

                StreamUtilities.WriteStringToMemoryStream(outStream, aes.IV.Length + "!");
                outStream.Write(aes.IV, 0, aes.IV.Length);
                StreamUtilities.RunCryptoTransform(outMessage.Serialize(), aes.CreateEncryptor(), outStream, true);
            }
            else
            {
                outMessage.Serialize(outStream);
            }
        }
Esempio n. 22
0
        public static Message ToMessage(this MemoryStream inStream, Aes aes = null)
        {
            if (inStream.Length == 0)
                throw new Exceptions.CommunicationException("read stream blank!");

            MemoryStream plainStream;

            inStream.Seek(0, SeekOrigin.Begin);

            //TODO: clean this up
            string beforeGreaterThan = StreamUtilities.ReadUntilChar(inStream, '<', 5, true);
            string beforeExclaimation = StreamUtilities.ReadUntilChar(inStream, '!', 5, true);

            bool streamEncrypted;
            if (beforeGreaterThan != null && beforeExclaimation == null)
                streamEncrypted = false;
            else if (beforeGreaterThan == null && beforeExclaimation != null)
                streamEncrypted = true;
            else if (beforeGreaterThan.Length < beforeExclaimation.Length)
                streamEncrypted = false;
            else
                streamEncrypted = true;

            if (streamEncrypted)
            {

                if (aes == null)
                    throw new Exceptions.CommunicationException("oops!  Got an encrypted response, but don't know the key.");

                string numBytesForIvString = StreamUtilities.ReadUntilChar(inStream, '!', 10, false);

                //int bleh = StreamUtilities.PeekByte(inStream);
                //string test2 = StreamUtilities.MemoryStreamToString(inStream);

                int numBytesForIv;
                try
                {
                    numBytesForIv = Convert.ToInt32(numBytesForIvString);
                }
                catch
                {
                    throw new Exceptions.CommunicationException("Error parsing the number of bytes for the Initialization Vector");
                }

                byte[] iv = new byte[numBytesForIv];
                int numRead = inStream.Read(iv, 0, numBytesForIv);

                if (numRead != numBytesForIv)
                    throw new Exceptions.CommunicationException("Error reading the initialization vector.");

                aes.IV = iv;

                try
                {
                    plainStream = StreamUtilities.RunCryptoTransform(inStream, aes.CreateDecryptor(), false);

                    plainStream.Seek(0, SeekOrigin.Begin);
                    //string beforeGreaterThan2 = StreamUtilities.ReadUntilChar(inStream, 'x', 50, true);
                    //string test3 = StreamUtilities.MemoryStreamToString(plainStream);
                    //inStream.Seek(0, SeekOrigin.Begin);
                }
                catch (CryptographicException exception)
                {
                    throw new Exceptions.CommunicationException("Error decrypting response.", exception);
                }
            }
            else
            {
                plainStream = inStream;
            }

            Message result = new Message(plainStream);

            if (result.controlValues.Count == 0 && result.Values.Count == 0 && result.Payload.Count == 0)
                throw new Exceptions.CommunicationException("Blank response.");

            if (!String.IsNullOrEmpty(result.CommunicationErrorMessage))
                throw new Exceptions.CommunicationException(result.CommunicationErrorMessage);

            return result;
        }