Example #1
0
        public MJpegWrapper()
        {
            if (Environment.UserInteractive)
            {
                Logger.logType = LoggingMode.Console | LoggingMode.File;
            }
            string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;

            Globals.Initialize(exePath);
            PrivateAccessor.SetStaticFieldValue(typeof(Globals), "errorFilePath", Globals.WritableDirectoryBase + "MJpegCameraErrors.txt");

            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            System.Net.ServicePointManager.Expect100Continue      = false;
            System.Net.ServicePointManager.DefaultConnectionLimit = 640;

            cfg = new ProxyConfig();
            if (File.Exists(CameraProxyGlobals.ConfigFilePath))
            {
                cfg.Load(CameraProxyGlobals.ConfigFilePath);
            }
            else
            {
                if (cfg.users.Count == 0)
                {
                    cfg.users.Add(new User("admin", "admin", 100));
                }
                cfg.Save(CameraProxyGlobals.ConfigFilePath);
            }
            SimpleHttpLogger.RegisterLogger(Logger.httpLogger);
            bool killed = false;

            try
            {
                foreach (var process in Process.GetProcessesByName("live555ProxyServer"))
                {
                    try
                    {
                        process.Kill();
                        killed = true;
                    }
                    catch (Exception ex)
                    {
                        Logger.Debug(ex, "Trying to kill existing live555ProxyServer process");
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Debug(ex, "Trying to iterate through existing live555ProxyServer processes");
            }
            if (killed)
            {
                Thread.Sleep(500);
            }
        }
Example #2
0
 private static void ioSchedulerLoop()
 {
     try
     {
         Stopwatch       watch          = new Stopwatch();
         EventWaitHandle ewh            = new EventWaitHandle(false, EventResetMode.ManualReset);
         int             lastIntervalMs = BurstIntervalMs;
         while (true)
         {
             try
             {
                 watch.Restart();
                 foreach (ThrottlingRuleSet ruleSet in ruleSets)
                 {
                     ruleSet.DoScheduledOperations(lastIntervalMs);
                 }
                 lastIntervalMs = BurstIntervalMs;
                 int timeToWait = lastIntervalMs - (int)watch.ElapsedMilliseconds;
                 if (timeToWait > 0)
                 {
                     ewh.WaitOne(timeToWait);
                 }
             }
             catch (ThreadAbortException ex)
             {
                 throw ex;
             }
             catch (Exception ex)
             {
                 SimpleHttpLogger.Log(ex);
             }
         }
     }
     catch (ThreadAbortException)
     {
         foreach (ThrottlingRuleSet ruleSet in ruleSets)
         {
             ruleSet.ReleaseAllWaitingThreads();
         }
     }
 }
Example #3
0
        public TimelapseWrapper(bool isAspNet)
        {
            if (!isAspNet)
            {
                Logger.logType = Environment.UserInteractive ? (LoggingMode.Console | LoggingMode.File) : LoggingMode.File;
                TimelapseGlobals.Initialize(System.Reflection.Assembly.GetEntryAssembly().Location);
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            }

            System.Net.ServicePointManager.Expect100Continue = false;
            if (!isAspNet)
            {
                System.Net.ServicePointManager.DefaultConnectionLimit = 640;
            }

            cfg = new TimelapseConfig();
            if (File.Exists(Globals.ConfigFilePath))
            {
                cfg.Load(Globals.ConfigFilePath);
            }
            else
            {
                if (cfg.users.Count == 0)
                {
                    cfg.users.Add(new User("admin", "admin", 100));
                }
                cfg.Save(Globals.ConfigFilePath);
            }
            SimpleHttpLogger.RegisterLogger(Logger.httpLogger);

            // The ASP.NET implementation does not currently support request throttling, though output throttling should be more-or-less possible easily.
            GlobalThrottledStream.ThrottlingManager.Initialize(3);
            GlobalThrottledStream.ThrottlingManager.SetBytesPerSecond(0, cfg.options.uploadBytesPerSecond);
            GlobalThrottledStream.ThrottlingManager.SetBytesPerSecond(1, cfg.options.downloadBytesPerSecond);
            GlobalThrottledStream.ThrottlingManager.SetBytesPerSecond(2, -1);
            GlobalThrottledStream.ThrottlingManager.BurstIntervalMs = cfg.options.throttlingGranularity;
        }
Example #4
0
        /// <summary>
        /// <para>Call this from your Main() function, and it takes care of all initialization for a Windows Service app with the following features:</para>
        /// <list type="bullet">
        /// <item>Logs separated by month in <see cref="Globals.WritableDirectoryBase"/> + "Logs/"</item>
        /// <item><see cref="Environment.CurrentDirectory"/> set to <see cref="Globals.WritableDirectoryBase"/></item>
        /// <item>Unhandled exceptions logged.</item>
        /// <item>(Windows Only) Service Manager GUI with "Open Data Folder" button which opens <see cref="Globals.WritableDirectoryBase"/> in Explorer.</item>
        /// <item>(Windows Only) A temporary instance of the service is automatically started if the debugger is attached.</item>
        /// <item>If the service has a public static field named "settings" which inherits from SerializableObjectBase, that field will be instantiated if necessary, loaded, then saved if the settings file does not exist.</item>
        /// </list>
        /// <para>Notice that some assumptions are made about the architecture of the application.</para>
        /// <para>When running on linux, this class simply starts the service.</para>
        /// <para>You may initialize <see cref="Globals"/> with custom values, if desired, before calling this method.</para>
        /// </summary>
        /// <typeparam name="ServiceType">Type of Service class.</typeparam>
        /// <param name="options">Optional options for service initialization.</param>
        public static void WindowsService <ServiceType>(WindowsServiceInitOptions options = null) where ServiceType : ServiceBase, new()
        {
            if (options == null)
            {
                options = new WindowsServiceInitOptions();
            }
            Directory.CreateDirectory(Globals.WritableDirectoryBase);
            Directory.CreateDirectory(Globals.WritableDirectoryBase + "Logs/");
            Globals.OverrideErrorFilePath(() => Globals.WritableDirectoryBase + "Logs/" + Globals.AssemblyName + "_" + DateTime.Now.Year + "_" + DateTime.Now.Month.ToString().PadLeft(2, '0') + ".txt");
            Environment.CurrentDirectory = Globals.WritableDirectoryBase;

            Logger.CatchAll();
            SimpleHttpLogger.RegisterLogger(Logger.httpLogger, false);

            ServiceType myService = new ServiceType();

            // Initialize the settings object, if the service has a public static field named "settings" that inherits from SerializableObjectBase.
            FieldInfo settingsField            = myService.GetType().GetField("settings", BindingFlags.Static | BindingFlags.Public);
            SerializableObjectBase settingsObj = null;

            if (settingsField != null && settingsField.FieldType.IsSubclassOf(typeof(SerializableObjectBase)))
            {
                settingsObj = (SerializableObjectBase)settingsField.GetValue(null);
                if (settingsObj == null)
                {
                    settingsObj = (SerializableObjectBase)Activator.CreateInstance(settingsField.FieldType);
                    settingsField.SetValue(null, settingsObj);
                }
                settingsObj.Load();
                settingsObj.SaveIfNoExist();
            }

            if (Platform.IsUnix() || Platform.IsRunningOnMono())
            {
                LinuxWindowsService(myService, options, settingsObj);
                return;
            }
            string serviceName = !string.IsNullOrWhiteSpace(options.ServiceName) ? options.ServiceName : myService.ServiceName;

            if (Environment.UserInteractive)
            {
                string Title = serviceName + " " + Globals.AssemblyVersion + " Service Manager";

                List <ButtonDefinition> additionalButtons = new List <ButtonDefinition>();
                if (options.ServiceManagerButtons_OpenDataFolder)
                {
                    additionalButtons.Add(new ButtonDefinition("Open Data Folder", btnOpenDataFolder_Click));
                }
                if (options.ServiceManagerButtons_UpdateSettingsFile && settingsObj != null)
                {
                    additionalButtons.Add(new ButtonDefinition("Update Settings File", (sender, ignored) =>
                    {
                        settingsObj.Save();
                        Process.Start(settingsObj.GetType().Name + ".cfg");
                    }));
                }
                if (options.ServiceManagerButtons != null)
                {
                    foreach (ButtonDefinition btn in options.ServiceManagerButtons)
                    {
                        additionalButtons.Add(btn);
                    }
                }

                bool didStart = false;
                if (Debugger.IsAttached || options.RunForDebugging)
                {
                    PrivateAccessor.CallMethod <ServiceType>(myService, "OnStart", new object[] { new string[0] });
                    didStart = true;
                }

                try
                {
                    System.Windows.Forms.Application.Run(new ServiceManager(Title, serviceName, additionalButtons.ToArray()));
                }
                finally
                {
                    if (didStart)
                    {
                        PrivateAccessor.CallMethod <ServiceType>(myService, "OnStop");
                    }
                }
            }
            else
            {
                ServiceBase.Run(myService);
            }
        }
Example #5
0
 static WebServer()
 {
     settings.Load(SettingsPath);
     settings.SaveIfNoExist(SettingsPath);
     SimpleHttpLogger.RegisterLogger(Logger.httpLogger, false);
 }
Example #6
0
        public ErrorTrackerSvc()
        {
            Settings.data.Load();

            Logger.CatchAll((sender, e) =>
            {
                Emailer.SendError(null, sender, e);
            });

            Settings.data.SaveIfNoExist();

            if (Settings.data.CountUsers() == 0)
            {
                User defaultAdmin = new User("admin", "admin", null, true)
                {
                    Permanent = true
                };
                Settings.data.TryAddUser(defaultAdmin);
                defaultAdmin.InitializeUserId();
                Settings.data.Save();
            }
            if (string.IsNullOrWhiteSpace(Settings.data.systemName))
            {
                Settings.data.systemName = "Error Tracker";
                Settings.data.Save();
            }
            if (string.IsNullOrWhiteSpace(Settings.data.privateSigningKey))
            {
                Settings.data.privateSigningKey = new SignatureFactory().ExportPrivateKey();
                Settings.data.Save();
            }
            if (string.IsNullOrWhiteSpace(Settings.data.vapidPrivateKey) ||
                string.IsNullOrWhiteSpace(Settings.data.vapidPublicKey))
            {
                WebPush.VapidDetails vapidKeys = WebPush.VapidHelper.GenerateVapidKeys();
                Settings.data.vapidPrivateKey = vapidKeys.PrivateKey;
                Settings.data.vapidPublicKey  = vapidKeys.PublicKey;
                foreach (User u in Settings.data.GetAllUsers())
                {
                    u.ClearAllPushNotificationSubscriptions();
                }
                Settings.data.Save();
            }
            BPUtil.PasswordReset.StatelessPasswordResetBase.Initialize(Settings.data.privateSigningKey);

            // Initialize User IDs.
            bool setAny = false;

            foreach (User user in Settings.data.GetAllUsers())
            {
                if (user.InitializeUserId())
                {
                    setAny = true;
                }
            }
            if (setAny)
            {
                Settings.data.Save();
            }

            InitializeComponent();

            SvcName = this.ServiceName;

            ICertificateSelector certSelector = null;

            if (!string.IsNullOrWhiteSpace(Settings.data.certificatePath) && File.Exists(Settings.data.certificatePath))
            {
                X509Certificate2 cert;
                if (!string.IsNullOrWhiteSpace(Settings.data.certificatePassword))
                {
                    cert = new X509Certificate2(Settings.data.certificatePath, Settings.data.certificatePassword);
                }
                else
                {
                    cert = new X509Certificate2(Settings.data.certificatePath);
                }
                certSelector = SimpleCertificateSelector.FromCertificate(cert);
            }
            SimpleHttpLogger.RegisterLogger(Logger.httpLogger);
            srv = new WebServer(Settings.data.port_http, Settings.data.port_https, certSelector, IPAddress.Any);

            thrMaintainProjects              = new Thread(maintainProjects);
            thrMaintainProjects.Name         = "Maintain Projects";
            thrMaintainProjects.IsBackground = false;
        }
Example #7
0
        private void WebSocketRead()
        {
            WebSocketCloseFrame closeFrame = null;

            try
            {
                WebSocketFrameHeader fragmentStart = null;
                List <byte[]>        fragments     = new List <byte[]>();
                ulong totalLength = 0;
                while (true)
                {
                    WebSocketFrameHeader head = new WebSocketFrameHeader(tcpStream);

                    if (head.opcode == WebSocketOpcode.Close)
                    {
                        closeFrame = new WebSocketCloseFrame(head, tcpStream);
                        Send(WebSocketCloseCode.Normal);
                        //SimpleHttpLogger.LogVerbose("WebSocket connection closed with code: "
                        //	+ (ushort)closeFrame.CloseCode
                        //	+ " (" + closeFrame.CloseCode + ")"
                        //	 + (!string.IsNullOrEmpty(closeFrame.Message) ? " -- \"" + closeFrame.Message + "\"" : ""));
                        return;
                    }
                    else if (head.opcode == WebSocketOpcode.Ping)
                    {
                        WebSocketPingFrame pingFrame = new WebSocketPingFrame(head, tcpStream);
                        SendFrame(WebSocketOpcode.Pong, pingFrame.Data);
                        continue;
                    }
                    else if (head.opcode == WebSocketOpcode.Pong)
                    {
                        WebSocketPongFrame pingFrame = new WebSocketPongFrame(head, tcpStream);
                        continue;
                    }
                    else if (head.opcode == WebSocketOpcode.Continuation || head.opcode == WebSocketOpcode.Text || head.opcode == WebSocketOpcode.Binary)
                    {
                        // The WebSocket protocol supports payload fragmentation, which is the
                        // reason for much of the complexity to follow.
                        // (The primary purpose of fragmentation is to allow sending a message
                        // that is of unknown size when the message is started without having to
                        // buffer that message.)

                        // Validate Payload Length
                        totalLength += head.payloadLength;
                        if (totalLength > (ulong)MAX_PAYLOAD_BYTES)
                        {
                            throw new WebSocketException(WebSocketCloseCode.MessageTooBig);
                        }

                        // Keep track of the frame that started each set of fragments
                        if (fragmentStart == null)
                        {
                            if (head.opcode == WebSocketOpcode.Continuation)
                            {
                                throw new WebSocketException(WebSocketCloseCode.ProtocolError, "Continuation frame did not follow a Text or Binary frame.");
                            }
                            fragmentStart = head;
                        }

                        // Read the Frame's Payload
                        fragments.Add(ByteUtil.ReadNBytes(tcpStream, (int)head.payloadLength));

                        if (head.fin)
                        {
                            // This ends a set of 1 or more fragments.

                            // Assemble the final payload.
                            byte[] payload;
                            if (fragments.Count == 1)
                            {
                                payload = fragments[0];
                            }
                            else
                            {
                                // We must assemble a fragmented payload.
                                payload = new byte[(int)totalLength];
                                int soFar = 0;
                                for (int i = 0; i < fragments.Count; i++)
                                {
                                    byte[] part = fragments[i];
                                    fragments[i] = null;
                                    Array.Copy(part, 0, payload, soFar, part.Length);
                                    soFar += part.Length;
                                }
                            }

                            // Call onMessageReceived callback
                            try
                            {
                                if (fragmentStart.opcode == WebSocketOpcode.Text)
                                {
                                    onMessageReceived(new WebSocketTextFrame(fragmentStart, payload));
                                }
                                else
                                {
                                    onMessageReceived(new WebSocketBinaryFrame(fragmentStart, payload));
                                }
                            }
                            catch (ThreadAbortException) { }
                            catch (Exception ex)
                            {
                                if (!HttpProcessor.IsOrdinaryDisconnectException(ex))
                                {
                                    SimpleHttpLogger.Log(ex);
                                }
                            }

                            // Reset fragmentation state
                            fragmentStart = null;
                            fragments.Clear();
                            totalLength = 0;
                        }
                    }
                }
            }
            catch (ThreadAbortException)
            {
                if (closeFrame == null)
                {
                    closeFrame           = new WebSocketCloseFrame();
                    closeFrame.CloseCode = WebSocketCloseCode.Normal;
                }
                Try.Swallow(() =>
                {
                    tcpClient.SendTimeout = Math.Min(tcpClient.SendTimeout, 1000);
                    Send(closeFrame.CloseCode);
                });
            }
            catch (Exception ex)
            {
                bool isDisconnect = HttpProcessor.IsOrdinaryDisconnectException(ex);
                if (!isDisconnect)
                {
                    SimpleHttpLogger.LogVerbose(ex);
                }

                if (closeFrame == null)
                {
                    closeFrame           = new WebSocketCloseFrame();
                    closeFrame.CloseCode = isDisconnect ? WebSocketCloseCode.ConnectionLost : WebSocketCloseCode.InternalError;
                }
                Try.Swallow(() => { Send(closeFrame.CloseCode); });
            }
            finally
            {
                try
                {
                    if (closeFrame == null)
                    {
                        // This should not happen, but it is possible that further development could leave a code path where closeFrame did not get set.
                        closeFrame           = new WebSocketCloseFrame();
                        closeFrame.CloseCode = WebSocketCloseCode.InternalError;
                    }
                    onClose(closeFrame);
                }
                catch (ThreadAbortException) { }
                catch (Exception) { }
            }
        }