Exemple #1
0
        public void Run()
        {
            Int64 now = UtilsCore.UnixTimeStampMs();

            m_timeLastStart = now;
            OnRun();
            m_timeLastEnd = now;

            if (m_thread != null)
            {
                m_thread = null;
            }
        }
Exemple #2
0
        // Note: If cache is expired, but new query don't return IPs, old cache it's returned.
        public static IpAddresses ResolveDNS(string host, bool nocache)
        {
            if (nocache)
            {
                return(Platform.Instance.ResolveDNS(host));
            }
            else
            {
                DnsManagerEntry entry = null;
                lock (m_cache)
                {
                    if (m_cache.ContainsKey(host))
                    {
                        entry = m_cache[host];
                    }
                    else
                    {
                        entry = new DnsManagerEntry();
                    }
                }
                Int64 now   = UtilsCore.UnixTimeStamp();
                Int64 delay = now - entry.TimeStamp;
                Int64 ttl   = 3600;
                if ((Engine.Instance != null) && (Engine.Instance.Storage != null))
                {
                    ttl = Engine.Instance.Storage.GetInt("dns.cache.ttl");
                }
                if (delay >= ttl)
                {
                    IpAddresses result = Platform.Instance.ResolveDNS(host);
                    if (result.Count != 0)
                    {
                        entry.Response  = result;
                        entry.TimeStamp = now;
                        lock (m_cache)
                        {
                            m_cache[host] = entry;
                        }
                    }
                }

                return(entry.Response);
            }
        }
Exemple #3
0
        public string Refresh()
        {
            m_lastRefreshTry = UtilsCore.UnixTimeStamp();

            Engine.Instance.Logs.Log(LogType.Verbose, Messages.ManifestUpdate);

            string globalResult = "";

            // TOOPTIMIZE: Stop at first error
            foreach (Provider provider in Providers)
            {
                if (provider.Enabled)
                {
                    string result = provider.Refresh();
                    if (result != "")
                    {
                        if (Engine.Instance.ConnectionActive == null)                         // Note: only if not connected, otherwise misunderstanding.
                        {
                            if (Engine.Instance.Storage.GetBool("ui.skip.provider.manifest.failed") == false)
                            {
                                Engine.Instance.OnProviderManifestFailed(provider);
                            }
                        }

                        if (globalResult != "")
                        {
                            globalResult += "; ";
                        }
                        globalResult += result;
                    }
                }
            }

            Engine.Instance.PostManifestUpdate();

            if (globalResult == "")
            {
                Engine.Instance.Logs.Log(LogType.Verbose, Messages.ManifestDone);

                m_lastRefreshDone = UtilsCore.UnixTimeStamp();
            }

            return(globalResult);
        }
Exemple #4
0
        public bool NeedUpdate(bool recommended)
        {
            Int64 refreshInterval = Engine.Instance.Storage.GetInt("advanced.manifest.refresh");

            if (refreshInterval == 0)
            {
                return(false);
            }

            if (refreshInterval < 0)
            {
                refreshInterval = 10;                 // Default
            }
            if (m_lastRefreshTry + 60 * refreshInterval < UtilsCore.UnixTimeStamp())
            {
                return(true);
            }

            return(false);
        }
Exemple #5
0
        public void DoRefresh(bool force)
        {
            bool postRefreshRecompute = force;

            foreach (Provider provider in Providers)
            {
                if (provider.Enabled)
                {
                    if ((force) || (provider.GetNeedRefresh()))
                    {
                        postRefreshRecompute = true;
                        string result = provider.OnRefresh();
                        if (result != "")
                        {
                            if (Engine.Instance.ConnectionActive == null)                             // Note: only if not connected, otherwise misunderstanding.
                            {
                                if (Engine.Instance.Storage.GetBool("ui.skip.provider.manifest.failed") == false)
                                {
                                    Engine.Instance.OnProviderManifestFailed(provider);
                                }
                            }
                        }
                    }
                }
            }

            if (postRefreshRecompute)
            {
                Engine.Instance.PostManifestUpdate();
            }

            m_lastRefreshDone = UtilsCore.UnixTimeStamp();

            if (InvalidateWithNextRefresh)
            {
                InvalidateWithNextRefresh = false;
                Engine.Instance.InvalidateConnections();
            }
        }
Exemple #6
0
        public static string FormatTime(Int64 unix)
        {
            if (unix == 0)
            {
                return("-");
            }

            string o   = "";
            Int64  now = UtilsCore.UnixTimeStamp();

            if (unix == now)
            {
                o = GetText("TimeJustNow");
            }
            else if (unix < now)
            {
                o = FormatSeconds(now - unix) + " " + GetText("TimeAgo");
            }
            else
            {
                o = FormatSeconds(unix - now) + " " + GetText("TimeRemain");
            }
            return(o);
        }
Exemple #7
0
        public void CheckRun()
        {
            if (m_cancelRequested)
            {
                return;
            }

            Int64 now = UtilsCore.UnixTimeStampMs();

            if (m_thread != null)
            {
                // Already running
            }
            else if ((m_timeLastStart != 0) && (m_timeLastEnd < m_timeLastStart))
            {
                // Already running
            }
            else if (now - m_timeLastEnd < m_timeEvery)
            {
                // Not need
            }
            else
            {
                //Engine.Instance.Logs.LogVerbose("Run job " + this.GetType().FullName);
                if (GetSync())
                {
                    Run();
                }
                else
                {
                    m_thread          = new System.Threading.Thread(this.Run);
                    m_thread.Priority = GetPriority();
                    m_thread.Start();
                }
            }
        }
Exemple #8
0
        public void LogDebug(string message)
        {
            long ts = UtilsCore.UnixTimeStampMs();

            LogVerbose(ts.ToString() + ":" + message);
        }
Exemple #9
0
 public virtual string OnRefresh()
 {
     m_lastTryRefresh = UtilsCore.UnixTimeStamp();
     return("");
 }
Exemple #10
0
 public virtual string HashSHA256(string str)
 {
     return(UtilsCore.HashSHA256(ID + "-" + str));
 }
        private static bool AllowPath(string path)
        {
            string sha256 = "";
            string signId = "";

            if (Platform.Instance.FileExists(path) == false)
            {
                return(false);
            }

            List <string> trustedPaths = Platform.Instance.GetTrustedPaths();

            foreach (string trustedPath in trustedPaths)
            {
                if (path.StartsWith(trustedPath, StringComparison.InvariantCulture))
                {
                    return(true);
                }
            }

            // Avoid if possible any shell before the storage init.
            if (Engine.Instance.Storage == null)
            {
                return(false);
            }

            Json rulesCustom = Engine.Instance.Storage.GetJson("external.rules");

            for (int r = 0; r < 2; r++)
            {
                Json rules = null;
                if (r == 0)
                {
                    if (Engine.Instance.Storage.GetBool("external.rules.recommended"))
                    {
                        rules = Engine.Instance.Manifest["external-rules-recommended"].Value as Json;
                    }
                    else
                    {
                        continue;
                    }
                }
                else if (r == 1)
                {
                    rules = rulesCustom;
                }

                foreach (Json rule in rules.GetArray())
                {
                    string type = rule["type"].Value as string;
                    if (type == "all")
                    {
                        return(true);
                    }
                    if (type == "sign")
                    {
                        if (signId == "")
                        {
                            signId = Platform.Instance.FileGetSignedId(path);
                        }

                        if (rule["id"].Value as string == signId)
                        {
                            return(true);
                        }
                    }

                    if (type == "sha256")
                    {
                        if (sha256 == "")
                        {
                            sha256 = UtilsCore.HashSHA256File(path);
                        }

                        if (rule["hash"].Value as string == sha256)
                        {
                            return(true);
                        }
                    }
                    if (type == "path")
                    {
                        if (rule["path"].Value as string == path)
                        {
                            return(true);
                        }
                    }
                }
            }

            // Ensure compute, Report and result
            if (signId == "")
            {
                signId = Platform.Instance.FileGetSignedId(path);
            }
            if (sha256 == "")
            {
                sha256 = UtilsCore.HashSHA256File(path);
            }

            Json askToUi = new Json();

            askToUi["sha256"].Value  = sha256;
            askToUi["sign-id"].Value = signId;
            askToUi["path"].Value    = path;

            // Propose to add rule to UI
            Json replyUi = Engine.Instance.OnAskShellExternalPermission(askToUi);

            if (replyUi.HasKey("allow"))
            {
                if (Convert.ToBoolean(replyUi["allow"].Value) == false)
                {
                    return(false);
                }
            }

            if (replyUi.HasKey("type"))
            {
                replyUi.RemoveKey("allow");
                rulesCustom.Append(replyUi);
                Engine.Instance.Storage.SetJson("external.rules", rulesCustom);

                return(AllowPath(path));
            }

            if (replyUi.HasKey("allow"))
            {
                if (Convert.ToBoolean(replyUi["allow"].Value) == true)
                {
                    return(true);
                }
            }

            //Engine.Instance.Storage.SetJson("external.rules", rules);

            return(false);
        }
Exemple #12
0
 public bool VersionAboveOrEqual(string v)
 {
     return(UtilsCore.CompareVersions(Version, v) >= 0);
 }
Exemple #13
0
 public bool VersionUnder(string v)
 {
     return(UtilsCore.CompareVersions(Version, v) == -1);
 }
Exemple #14
0
        public static IpAddresses GetGuardIps(bool force)
        {
            // This is called a lots of time.
            Int64 now = UtilsCore.UnixTimeStamp();

            if ((force == false) && ((now - m_lastGuardTime < 60)))
            {
                return(m_lastGuardIps);
            }

            IpAddresses ips = new IpAddresses();

            try
            {
                string controlHost = Engine.Instance.Storage.Get("proxy.host").ToLowerInvariant().Trim();

                if ((controlHost != "127.0.0.1") && (controlHost.ToLowerInvariant() != "localhost"))
                {
                    // Guard IPS are used to avoid routing loop, that occur only if the Tor host is the same machine when OpenVPN run.
                    return(ips);
                }

                List <string> ipsMessages = new List <string>();

                using (TcpClient s = new TcpClient())
                {
                    Connect(s);

                    Write(s, "getinfo circuit-status\n");
                    Flush(s);
                    string circuits = Read(s);

                    string[] circuitsLines = circuits.Split('\n');
                    foreach (string circuit in circuitsLines)
                    {
                        string id = circuit.ToLowerInvariant().RegExMatchOne("\\d+\\sbuilt\\s\\$([0-9a-f]+)");

                        if (id != "")
                        {
                            Write(s, "getinfo ns/id/" + id.ToUpperInvariant() + "\n");
                            string nodeInfo = Read(s);

                            string[] nodeLines = nodeInfo.Split('\n');
                            foreach (string line in nodeLines)
                            {
                                string ip = line.RegExMatchOne("r\\s.+?\\s.+?\\s.+?\\s.+?\\s.+?\\s(.+?)\\s");

                                if ((IpAddress.IsIP(ip)) && (!ips.Contains(ip)))
                                {
                                    ips.Add(ip);
                                    ipsMessages.Add(ip + " (circuit)");
                                }
                            }
                        }
                    }

                    Write(s, "getconf bridge\n");
                    Flush(s);
                    string bridges = Read(s);

                    if (bridges.IndexOf("meek") == -1)                     //Panic if we have meek enabled, don't yet know what to do :-(
                    {
                        string[] bridgeLines = bridges.Split('\n');
                        foreach (string bridge in bridgeLines)
                        {
                            List <string> matches = bridge.ToLowerInvariant().RegExMatchSingle("250.bridge=(.+?)\\s([0-9a-f\\.\\:]+?):\\d+\\s");
                            if ((matches != null) && (matches.Count == 2))
                            {
                                string bridgeType = matches[0];
                                string ip         = matches[1];

                                if ((IpAddress.IsIP(ip)) && (!ips.Contains(ip)))
                                {
                                    ips.Add(matches[1]);
                                    ipsMessages.Add(matches[1] + " (" + bridgeType + ")");
                                }
                            }
                        }
                    }
                    else
                    {
                        Engine.Instance.Logs.Log(LogType.Warning, LanguageManager.GetText("TorControlMeekUnsupported"));
                    }

                    if (ips.Count == 0)
                    {
                        Engine.Instance.Logs.Log(LogType.Warning, LanguageManager.GetText("TorControlNoIps"));
                        //throw new Exception(Messages.TorControlNoIps);
                    }
                    else
                    {
                        string list = String.Join("; ", ipsMessages.ToArray());
                        Engine.Instance.Logs.Log(LogType.Verbose, LanguageManager.GetText("TorControlGuardIps", list));
                    }
                }
            }
            catch (Exception e)
            {
                //throw new Exception(LanguageManager.GetText("TorControlException, e.Message));
                Engine.Instance.Logs.Log(LogType.Warning, LanguageManager.GetText("TorControlException", e.Message));
            }

            m_lastGuardIps  = ips;
            m_lastGuardTime = now;

            return(ips);
        }
Exemple #15
0
        public void Start()
        {
            m_command = new ElevatedProcess.Command();

            if (Platform.Instance.NeedExecuteOutsideAppPath(ExePath))
            {
                string tempPathToDelete = UtilsCore.GetTempPath() + "/openvpn-" + RandomGenerator.GetHash();
                if (Platform.Instance.FileExists(tempPathToDelete))
                {
                    Platform.Instance.FileDelete(tempPathToDelete);
                }
                System.IO.File.Copy(ExePath, tempPathToDelete);

                ExePath = tempPathToDelete;

                DeleteAfterStart = true;
            }

            m_command.Parameters["command"]     = "process_openvpn";
            m_command.Parameters["path"]        = ExePath;
            m_command.Parameters["airbuild"]    = (AirBuild ? "y":"n");
            m_command.Parameters["gui-version"] = Constants.Name + Constants.VersionDesc;
            m_command.Parameters["config"]      = ConfigPath;

            m_command.ExceptionEvent += delegate(ElevatedProcess.Command cmd, string message)
            {
                StdErr.Write("Error: " + message);
            };

            m_command.ReceiveEvent += delegate(ElevatedProcess.Command cmd, string data)
            {
                string feedbackType = data.Substring(0, 6);
                string feedbackData = data.Substring(7);

                if (feedbackType == "stdout")
                {
                    StdOut.Write(feedbackData);
                }
                else if (feedbackType == "stderr")
                {
                    StdErr.Write(feedbackData);
                }
                else if (feedbackType == "procid")
                {
                    m_pid = Conversions.ToInt32(feedbackData);
                    if (DeleteAfterStart)
                    {
                        Platform.Instance.FileDelete(ExePath);
                    }
                }
                else if (feedbackType == "return")
                {
                }
            };

            m_command.CompleteEvent += delegate(ElevatedProcess.Command cmd)
            {
                StdOut.Stop();
                StdErr.Stop();
                if (EndEvent != null)
                {
                    EndEvent();
                }
            };
            m_command.DoASync();
        }