Ejemplo n.º 1
0
        public MQTT_Handling(ConsoleOutputLogger Logger)
        {
            // create client instance
            client              = new MqttClient(IPAddress.Parse(MQTTBindingConfiguration.MQTTBindingConfigFile.mqtt_broker_host), MQTTBindingConfiguration.MQTTBindingConfigFile.mqtt_broker_port, false, null, null, MqttSslProtocols.None);
            clientId            = Guid.NewGuid().ToString();
            ConsoleOutputLogger = Logger;
            // connect
            try
            {
                client.Connect(clientId);

                if (client.IsConnected)
                {
                    ConsoleOutputLogger.WriteLine("MQTT Binding: Successfully connected!");
                }
                else
                {
                    ConsoleOutputLogger.WriteLine("MQTT Binding: Connection Problem - could not connect!");
                }
            }
            catch (Exception e)
            {
                ConsoleOutputLogger.WriteLine("MQTT Binding Exception - " + e.Message);
            }
        }
Ejemplo n.º 2
0
        public void Run()
        {
            ConsoleOutputLogger.WriteLine("MQTT Binding Thread started");

            while (!Shutdown)
            {
                Thread.Sleep(100);
            }
        }
Ejemplo n.º 3
0
        public void process()
        {
            // we can't use a StreamReader for input, because it buffers up extra data on us inside it's
            // "processed" view of the world, and we want the data raw after the headers
            inputStream = new BufferedStream(socket.GetStream());

            // we probably shouldn't be using a streamwriter for all output from handlers either
            outputStream = new StreamWriter(new BufferedStream(socket.GetStream()));
            try {
                parseRequest();
                readHeaders();
                if (http_method.Equals("GET"))
                {
                    handleGETRequest();
                }
                else if (http_method.Equals("POST"))
                {
                    handlePOSTRequest();
                }
            } catch (Exception e) {
                ConsoleOutputLogger.WriteLine("Exception: " + e.ToString());
                writeFailure();
            }
            outputStream.Flush();
            // bs.Flush(); // flush any remaining output
            inputStream = null; outputStream = null;             // bs = null;
            socket.Close();
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Create a new server socket, set up all the endpoints, bind the socket and then listen
        /// </summary>
        public void listen()
        {
            // Wait for VCRScheduler...
            //ConsoleOutputLogger.WriteLine("HTTP Server is waiting for VCRScheduler...");
            //while (!internal_vcr_scheduler_set)
            //{
            //    Thread.Sleep(10);
            //}
            Socket     listener  = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress  ipaddress = IPAddress.Parse(HTTPServer_ListeningIP);
            IPEndPoint endpoint  = new IPEndPoint(ipaddress, HTTPServer_Port);

            try
            {
                // Create a new server socket, set up all the endpoints, bind the socket and then listen
                listener.Bind(endpoint);
                listener.Blocking = true;
                listener.Listen(-1);
                ConsoleOutputLogger.WriteLineToScreenOnly("[HTTP] Administrationsoberfläche unter http://" + HTTPServer_ListeningIP + ":" + HTTPServer_Port + " erreichbar.");
                while (true)
                {
                    try
                    {
                        // Accept a new connection from the net, blocking till one comes in
                        Socket s = listener.Accept();

                        // Create a new processor for this request
                        HttpProcessor processor = new HttpProcessor(s, HTTPServer_DocumentRoot, Storage, LatitudeStorage, XS1_Configuration, ConsoleOutputLogger, ELVMAXMonitoringThread, AuthorizationEnabled, Username, Password, AuthDisabledForAdressesThatStartWith);

                        // Dispatch that processor in its own thread
                        Thread thread = new Thread(new ThreadStart(processor.process));
                        thread.Start();
                        Thread.Sleep(10);
                        //processor.process();
                    }
                    catch (NullReferenceException)
                    {
                        // Don't even ask me why they throw this exception when this happens
                        ConsoleOutputLogger.WriteLine("[FEHLER@HTTP] Kann nicht auf TCP-Port " + HTTPServer_Port + " verbinden - wird vermutlich schon benutzt.");
                    }
                }
            }
            catch (Exception e)
            {
                ConsoleOutputLogger.WriteLine("[FEHLER@HTTP] " + e.Message);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Create a new server socket, set up all the endpoints, bind the socket and then listen
        /// </summary>
        public void listen()
        {
            Socket     listener  = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress  ipaddress = IPAddress.Parse(HTTPServer_ListeningIP);
            IPEndPoint endpoint  = new IPEndPoint(ipaddress, HTTPServer_Port);

            try
            {
                // Create a new server socket, set up all the endpoints, bind the socket and then listen
                listener.Bind(endpoint);
                listener.Blocking = true;
                listener.Listen(-1);
                ConsoleOutputLogger.WriteLineToScreenOnly("[HTTP] Administrationsoberfläche unter http://" + HTTPServer_ListeningIP + ":" + HTTPServer_Port + " erreichbar.");
                while (true)
                {
                    try
                    {
                        // Accept a new connection from the net, blocking till one comes in
                        Socket s = listener.Accept();

                        // Create a new processor for this request
                        HttpProcessor processor = new HttpProcessor(s, HTTPServer_DocumentRoot, ConsoleOutputLogger, ThumbCache);


                        // Dispatch that processor in its own thread
                        Thread thread = new Thread(new ThreadStart(processor.process));
                        thread.Start();
                        //Thread.Sleep(10);
                        //processor.process();
                    }
                    catch (NullReferenceException)
                    {
                        // Don't even ask me why they throw this exception when this happens
                        ConsoleOutputLogger.WriteLine("[FEHLER@HTTP] Kann nicht auf TCP-Port " + HTTPServer_Port + " verbinden - wird vermutlich schon benutzt.");
                    }
                }
            }
            catch (Exception e)
            {
                ConsoleOutputLogger.WriteLine("[FEHLER@HTTP] " + e.Message);
            }
        }
Ejemplo n.º 6
0
        public MQTT_Handling(ConsoleOutputLogger Logger)
        {
            // create client instance 
            client = new MqttClient(IPAddress.Parse(MQTTBindingConfiguration.MQTTBindingConfigFile.mqtt_broker_host),MQTTBindingConfiguration.MQTTBindingConfigFile.mqtt_broker_port,false,null,null,MqttSslProtocols.None);
            clientId = Guid.NewGuid().ToString();
            ConsoleOutputLogger = Logger;
            // connect
            try
            {
                client.Connect(clientId);

                if (client.IsConnected)
                    ConsoleOutputLogger.WriteLine("MQTT Binding: Successfully connected!");
                else
                    ConsoleOutputLogger.WriteLine("MQTT Binding: Connection Problem - could not connect!");
            }
            catch(Exception e)
            {
                ConsoleOutputLogger.WriteLine("MQTT Binding Exception - " + e.Message);
            }
            
        }
Ejemplo n.º 7
0
        /// <summary>
        /// We need to make sure that the url that we are trying to treat as a file
        /// lies below the document root of the http server so that people can't grab
        /// random files off your computer while this is running.
        /// </summary>
        public void writeURL()
        {
            try
            {
                // set this to true when implementing and reaching a new method
                bool method_found = false;

                // first check if the request is actually authenticated
                IPEndPoint AC_endpoint = (IPEndPoint)s.RemoteEndPoint;
                ConsoleOutputLogger.WriteLine(AC_endpoint.Address.ToString() + " GET " + original_url);

                querystring = "";
                url         = original_url;

                if (url.ToUpper().StartsWith("/PICS/"))
                {
                    List <FileInfo> Jpegs = FileManager.EnumerateAllJPGs(GalleryServer.Properties.Settings.Default.PicturesPath);
                    Dictionary <String, List <FileInfo> > sortedByDays = FileManager.SortAllJpegsByDay(Jpegs);

                    // let's find out if we're going to go deeper...

                    if (url.ToUpper().EndsWith("/PICS/"))
                    {
                        #region this is the first level /pics/
                        // the first level just get's you the days of which pics are available...
                        Dictionary <String, String> OutputObj = new Dictionary <string, string>();
                        foreach (String Date in sortedByDays.Keys)
                        {
                            OutputObj.Add(Date, "/pics/" + Date.ToLower());
                        }
                        string Output = JsonConvert.SerializeObject(OutputObj, Formatting.Indented);

                        int left = new UTF8Encoding().GetByteCount(Output);
                        //writeSuccess(left, "application/json");
                        writeSuccess(left, "text/html");
                        byte[] buffer = new UTF8Encoding().GetBytes(Output);
                        ns.Write(buffer, 0, left);
                        ns.Flush();
                        return;

                        #endregion
                    }
                    else
                    {
                        #region Here we go into deeper levels, first level will be day
                        url = url.Remove(0, 6);
                        Dictionary <String, String> OutputObj = new Dictionary <string, string>();

                        foreach (String Day in sortedByDays.Keys)
                        {
                            if (url.ToUpper().EndsWith(Day.ToUpper()))
                            {
                                // we've found the day, output all jpgs here...
                                foreach (FileInfo _file in sortedByDays[Day])
                                {
                                    OutputObj.Add(_file.Name + _file.LastWriteTime.Ticks, "/picture/" + _file.Name + _file.LastWriteTime.Ticks);
                                }
                            }
                        }
                        string Output = JsonConvert.SerializeObject(OutputObj, Formatting.Indented);

                        int left = new UTF8Encoding().GetByteCount(Output);
                        //writeSuccess(left, "application/json");
                        writeSuccess(left, "text/html");
                        byte[] buffer = new UTF8Encoding().GetBytes(Output);
                        ns.Write(buffer, 0, left);
                        ns.Flush();
                        return;

                        #endregion
                    }
                }
                else
                if (url.ToUpper().StartsWith("/PICTURE/"))
                {
                    List <FileInfo> Jpegs = FileManager.EnumerateAllJPGs(GalleryServer.Properties.Settings.Default.PicturesPath);
                    // remove the /picture thingie...
                    url = url.Remove(0, 9);

                    foreach (FileInfo jpg in Jpegs)
                    {
                        if (url.ToUpper().StartsWith(jpg.Name + jpg.LastWriteTime.Ticks))
                        {
                            // we've found the picture, now we determine if we want the picture or the thumbnail...
                            if (url.ToUpper().EndsWith("/THUMBNAIL"))
                            {
                                // it's the thumbnail...
                                byte[] ThumbnailData = ThumbCache.RetrieveThumbnail(jpg);
                                Stream stream        = new MemoryStream(ThumbnailData);
                                long   left          = ThumbnailData.Length;
                                long   bytesSent     = 0;
                                writeSuccess(left, "image/jpeg");

                                BufferedStream bs = new BufferedStream(stream);

                                // for performance reasons...
                                int read;
                                while (left > 0 && (read = bs.Read(bytes, 0, (int)Math.Min(left, bytes.Length))) != 0)
                                {
                                    ns.Write(bytes, 0, read);
                                    bytesSent = bytesSent + read;
                                    left     -= read;
                                }
                                ns.Flush();
                                bs.Close();
                                stream.Close();
                                return;
                            }
                            else
                            {
                                #region throw the original file out...
                                FileStream     fs        = null;
                                BufferedStream bs        = null;
                                long           bytesSent = 0;
                                // Open the file for binary transfer
                                fs = new FileStream(jpg.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                                long left = jpg.Length;
                                writeSuccess(left, "image/jpeg");
                                bs = new BufferedStream(fs);

                                // for performance reasons...
                                int read;
                                while (left > 0 && (read = bs.Read(bytes, 0, (int)Math.Min(left, bytes.Length))) != 0)
                                {
                                    ns.Write(bytes, 0, read);
                                    bytesSent = bytesSent + read;
                                    left     -= read;
                                }
                                ns.Flush();
                                bs.Close();
                                fs.Close();
                                return;

                                #endregion
                            }
                        }
                    }
                }
                else
                {
                    #region File request (everything else...)

                    #region default page
                    if (url == "/")
                    {
                        url = "/index.html";
                    }
                    #endregion

                    // check if we have some querystring parameters
                    if (url.Contains("?"))
                    {
                        // yes, remove everything after the ? from the url but save it to querystring
                        querystring = url.Substring(url.IndexOf('?') + 1);
                        url         = url.Remove(url.IndexOf('?'));
                    }

                    // Replace the forward slashes with back-slashes to make a file name
                    string filename = url.Replace('/', Path.DirectorySeparatorChar);                     //you have different path separators in unix and windows
                    try
                    {
                        // Construct a filename from the doc root and the filename
                        FileInfo file = new FileInfo(docRootFile + filename);
                        // Make sure they aren't trying in funny business by checking that the
                        // resulting canonical name of the file has the doc root as a subset.
                        filename = file.FullName;
                        if (!filename.StartsWith(docRootFile.FullName))
                        {
                            writeForbidden();
                        }
                        else
                        {
                            FileStream     fs        = null;
                            BufferedStream bs        = null;
                            long           bytesSent = 0;
                            bool           resumed   = false;

                            try
                            {
                                if (filename.EndsWith(".log"))
                                {
                                    // now give the user a 403 and break...
                                    writeForbidden();
                                    ns.Flush();
                                }
                                else
                                if (filename.EndsWith(".html") | (filename.EndsWith(".htm")))
                                {
                                    //
                                    String Output = File.ReadAllText(filename);

                                    int left = new UTF8Encoding().GetByteCount(Output);
                                    writeSuccess(left, "text/html");
                                    byte[] buffer = new UTF8Encoding().GetBytes(Output);
                                    ns.Write(buffer, 0, left);
                                    ns.Flush();
                                }
                                else
                                {
                                    // Open the file for binary transfer
                                    fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                                    long left = file.Length;
                                    bool isThisARecordingRecording = false;

                                    #region different mime-type-handling
                                    switch (getFileExtension(filename))
                                    {
                                    case ".css":
                                        writeSuccess(left, "text/css");
                                        break;

                                    case ".gif":
                                        writeSuccess(left, "image/gif");
                                        break;

                                    case ".png":
                                        writeSuccess(left, "image/png");
                                        break;

                                    case ".jpg":
                                        writeSuccess(left, "image/jpeg");
                                        break;

                                    case ".jpeg":
                                        writeSuccess(left, "image/jpeg");
                                        break;

                                    case ".ico":
                                        writeSuccess(left, "image/ico");
                                        break;

                                    default:
                                        // Write the content length and the success header to the stream; it's binary...so treat it as binary
                                        writeSuccess(left, "application/octet-stream");
                                        break;
                                    }
                                    #endregion

                                    // Copy the contents of the file to the stream, ensure that we never write
                                    // more than the content length we specified.  Just in case the file somehow
                                    // changes out from under us, although I don't know if that is possible.
                                    bs   = new BufferedStream(fs);
                                    left = file.Length;

                                    // for performance reasons...
                                    int read;
                                    while (left > 0 && (read = bs.Read(bytes, 0, (int)Math.Min(left, bytes.Length))) != 0)
                                    {
                                        ns.Write(bytes, 0, read);
                                        bytesSent = bytesSent + read;
                                        left     -= read;
                                    }
                                    ns.Flush();
                                    bs.Close();
                                    fs.Close();
                                }
                            }
                            catch (Exception e)
                            {
                                ConsoleOutputLogger.WriteLineToScreenOnly("[FEHLER@HTTP] " + e.Message);
                                try
                                {
                                    writeFailure();
                                }
                                catch (Exception)
                                {
                                    ConsoleOutputLogger.WriteLineToScreenOnly("[FEHLER@HTTP] connection lost to client");
                                }
                                if (bs != null)
                                {
                                    bs.Close();
                                }
                                if (bs != null)
                                {
                                    fs.Close();
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        ConsoleOutputLogger.WriteLineToScreenOnly("[FEHLER@HTTP] " + e.Message);
                        writeFailure();
                    }
                    #endregion
                }
            }
            catch (Exception e)
            {
                ConsoleOutputLogger.WriteLineToScreenOnly("[FEHLER@HTTP] " + e.Message + " ## " + e.StackTrace);
                writeFailure();
            }
        }