Esempio n. 1
0
        public override bool OnIpV6Restore()
        {
            foreach (IpV6ModeEntry entry in m_listIpV6Mode)
            {
                if (entry.Mode == "Off")
                {
                    ShellCmd("networksetup -setv6off \"" + SystemShell.EscapeInsideQuote(entry.Interface) + "\"");
                }
                else if (entry.Mode == "Automatic")
                {
                    ShellCmd("networksetup -setv6automatic \"" + SystemShell.EscapeInsideQuote(entry.Interface) + "\"");
                }
                else if (entry.Mode == "LinkLocal")
                {
                    ShellCmd("networksetup -setv6LinkLocal \"" + SystemShell.EscapeInsideQuote(entry.Interface) + "\"");
                }
                else if (entry.Mode == "Manual")
                {
                    ShellCmd("networksetup -setv6manual \"" + SystemShell.EscapeInsideQuote(entry.Interface) + "\" " + entry.Address + " " + entry.PrefixLength + " " + entry.Router);                     // IJTF2 // TOCHECK
                }

                Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.NetworkAdapterIpV6Restored, entry.Interface));
            }

            m_listIpV6Mode.Clear();

            Recovery.Save();

            base.OnIpV6Restore();

            return(true);
        }
Esempio n. 2
0
        public override bool OnDnsSwitchDo(IpAddresses dns)
        {
            string mode = Engine.Instance.Storage.GetLower("dns.mode");

            if (mode == "auto")
            {
                string[] interfaces = GetInterfaces();
                foreach (string i in interfaces)
                {
                    string i2 = i.Trim();

                    string currentStr = SystemShell.Shell("/usr/sbin/networksetup", new string[] { "-getdnsservers", SystemShell.EscapeInsideQuote(i2) });

                    // v2
                    IpAddresses current = new IpAddresses();
                    foreach (string line in currentStr.Split('\n'))
                    {
                        string ip = line.Trim();
                        if (IpAddress.IsIP(ip))
                        {
                            current.Add(ip);
                        }
                    }

                    if (dns.Equals(current) == false)
                    {
                        DnsSwitchEntry e = new DnsSwitchEntry();
                        e.Name = i2;
                        e.Dns  = current.Addresses;
                        m_listDnsSwitch.Add(e);

                        SystemShell s = new SystemShell();
                        s.Path = LocateExecutable("networksetup");
                        s.Arguments.Add("-setdnsservers");
                        s.Arguments.Add(SystemShell.EscapeInsideQuote(i2));
                        if (dns.IPs.Count == 0)
                        {
                            s.Arguments.Add("empty");
                        }
                        else
                        {
                            foreach (IpAddress ip in dns.IPs)
                            {
                                s.Arguments.Add(ip.Address);
                            }
                        }
                        s.Run();

                        Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.NetworkAdapterDnsDone, i2, ((current.Count == 0) ? "Automatic" : current.Addresses), dns.Addresses));
                    }
                }

                Recovery.Save();
            }

            base.OnDnsSwitchDo(dns);

            return(true);
        }
Esempio n. 3
0
        public override bool OnDnsSwitchDo(string dns)
        {
            string mode = Engine.Instance.Storage.GetLower("dns.mode");

            if (mode == "auto")
            {
                string[] interfaces = GetInterfaces();
                foreach (string i in interfaces)
                {
                    string i2 = i.Trim();

                    string current = ShellCmd("networksetup -getdnsservers \"" + SystemShell.EscapeInsideQuote(i2) + "\"");

                    // v2
                    List <string> ips = new List <string>();
                    foreach (string line in current.Split('\n'))
                    {
                        string ip = line.Trim();
                        if (IpAddress.IsIP(ip))
                        {
                            ips.Add(ip);
                        }
                    }

                    if (ips.Count != 0)
                    {
                        current = String.Join(",", ips.ToArray());
                    }
                    else
                    {
                        current = "";
                    }
                    if (current != dns)
                    {
                        // Switch
                        Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.NetworkAdapterDnsDone, i2, ((current == "") ? "Automatic" : current), dns));

                        DnsSwitchEntry e = new DnsSwitchEntry();
                        e.Name = i2;
                        e.Dns  = current;
                        m_listDnsSwitch.Add(e);

                        string dns2 = dns.Replace(",", "\" \"");
                        ShellCmd("networksetup -setdnsservers \"" + SystemShell.EscapeInsideQuote(i2) + "\" \"" + dns2 + "\""); // IJTF2 eh?
                    }
                }

                Recovery.Save();
            }

            base.OnDnsSwitchDo(dns);

            return(true);
        }
Esempio n. 4
0
        public override bool OsCredentialSystemDelete(string name)
        {
            string      secretToolPath = LocateExecutable("secret-tool");
            SystemShell shell          = new SystemShell();

            shell.Path = secretToolPath;
            shell.Arguments.Add("clear");
            shell.Arguments.Add("'Eddie Profile'");
            shell.Arguments.Add("'" + SystemShell.EscapeInsideQuote(name) + "'");
            shell.Run();
            int exitCode = shell.ExitCode;

            return(exitCode == 0);
        }
Esempio n. 5
0
        public override bool OsCredentialSystemWrite(string name, string password)
        {
            string      secretToolPath = LocateExecutable("secret-tool");
            SystemShell shell          = new SystemShell();

            shell.Path = secretToolPath;
            shell.Arguments.Add("store");
            shell.Arguments.Add("--label='Eddie, saved password for " + SystemShell.EscapeInsideQuote(name) + " profile'");
            shell.Arguments.Add("'Eddie Profile'");
            shell.Arguments.Add("'" + SystemShell.EscapeInsideQuote(name) + "'");
            shell.AutoWriteStdin = password + "\n";
            shell.Run();
            int exitCode = shell.ExitCode;

            return(exitCode == 0);
        }
Esempio n. 6
0
        public override bool OnDnsSwitchRestore()
        {
            foreach (DnsSwitchEntry e in m_listDnsSwitch)
            {
                /*
                 * string v = e.Dns;
                 * if (v == "")
                 *      v = "empty";
                 * v = v.Replace(",", "\" \"");
                 *
                 * SystemShell.Shell("/usr/sbin/networksetup", new string[] { "-setdnsservers", SystemShell.EscapeInsideQuote(e.Name), v });
                 */
                IpAddresses dns = new IpAddresses();
                dns.Add(e.Dns);

                SystemShell s = new SystemShell();
                s.Path = LocateExecutable("networksetup");
                s.Arguments.Add("-setdnsservers");
                s.Arguments.Add(SystemShell.EscapeInsideQuote(e.Name));
                if (dns.Count == 0)
                {
                    s.Arguments.Add("empty");
                }
                else
                {
                    foreach (IpAddress ip in dns.IPs)
                    {
                        s.Arguments.Add(ip.Address);
                    }
                }
                s.Run();

                Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.NetworkAdapterDnsRestored, e.Name, ((e.Dns == "") ? "Automatic" : e.Dns)));
            }

            m_listDnsSwitch.Clear();

            Recovery.Save();

            base.OnDnsSwitchRestore();

            return(true);
        }
Esempio n. 7
0
        public override bool OnIpV6Do()
        {
            if (Engine.Instance.Storage.GetLower("ipv6.mode") == "disable")
            {
                string[] interfaces = GetInterfaces();
                foreach (string i in interfaces)
                {
                    string getInfo = ShellCmd("networksetup -getinfo \"" + SystemShell.EscapeInsideQuote(i) + "\"");

                    string mode    = Utils.RegExMatchOne(getInfo, "^IPv6: (.*?)$");
                    string address = Utils.RegExMatchOne(getInfo, "^IPv6 IP address: (.*?)$");

                    if ((mode == "") && (address != ""))
                    {
                        mode = "LinkLocal";
                    }

                    if (mode != "Off")
                    {
                        Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.NetworkAdapterIpV6Disabled, i));

                        IpV6ModeEntry entry = new IpV6ModeEntry();
                        entry.Interface = i;
                        entry.Mode      = mode;
                        entry.Address   = address;
                        if (mode == "Manual")
                        {
                            entry.Router       = Utils.RegExMatchOne(getInfo, "^IPv6 IP Router: (.*?)$");
                            entry.PrefixLength = Utils.RegExMatchOne(getInfo, "^IPv6 Prefix Length: (.*?)$");
                        }
                        m_listIpV6Mode.Add(entry);

                        ShellCmd("networksetup -setv6off \"" + SystemShell.EscapeInsideQuote(i) + "\"");
                    }
                }

                Recovery.Save();
            }

            base.OnIpV6Do();

            return(true);
        }
Esempio n. 8
0
        public override string OsCredentialSystemRead(string name)
        {
            string      secretToolPath = LocateExecutable("secret-tool");
            SystemShell shell          = new SystemShell();

            shell.Path = secretToolPath;
            shell.Arguments.Add("lookup");
            shell.Arguments.Add("'Eddie Profile'");
            shell.Arguments.Add("'" + SystemShell.EscapeInsideQuote(name) + "'");
            shell.Run();
            int exitCode = shell.ExitCode;

            if (exitCode == 0)
            {
                return(shell.Output);
            }
            else
            {
                return("");
            }
        }
Esempio n. 9
0
        public override bool OnIpV6Restore()
        {
            foreach (IpV6ModeEntry entry in m_listIpV6Mode)
            {
                if (entry.Mode == "Off")
                {
                    SystemShell.Shell("/usr/sbin/networksetup", new string[] { "-setv6off", SystemShell.EscapeInsideQuote(entry.Interface) });
                }
                else if (entry.Mode == "Automatic")
                {
                    SystemShell.Shell("/usr/sbin/networksetup", new string[] { "-setv6automatic", SystemShell.EscapeInsideQuote(entry.Interface) });
                }
                else if (entry.Mode == "LinkLocal")
                {
                    SystemShell.Shell("/usr/sbin/networksetup", new string[] { "-setv6LinkLocal", SystemShell.EscapeInsideQuote(entry.Interface) });
                }
                else if (entry.Mode == "Manual")
                {
                    SystemShell.Shell("/usr/sbin/networksetup", new string[] { "-setv6manual", SystemShell.EscapeInsideQuote(entry.Interface), entry.Address, entry.PrefixLength, entry.Router });
                }

                Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.NetworkAdapterIpV6Restored, entry.Interface));
            }

            m_listIpV6Mode.Clear();

            Recovery.Save();

            base.OnIpV6Restore();

            return(true);
        }
Esempio n. 10
0
        public override IpAddresses DetectDNS()
        {
            IpAddresses list = new IpAddresses();

            string networksetupPath = LocateExecutable("networksetup");

            if (networksetupPath != "")
            {
                string[] interfaces = GetInterfaces();
                foreach (string i in interfaces)
                {
                    string i2 = i.Trim();

                    string current = SystemShell.Shell(networksetupPath, new string[] { "-getdnsservers", SystemShell.EscapeInsideQuote(i2) });

                    list.Add(current);
                }
            }

            return(list);
        }
Esempio n. 11
0
        public override IpAddresses DetectDNS()
        {
            IpAddresses list = new IpAddresses();

            // Method1: Don't return DHCP DNS
            string networksetupPath = LocateExecutable("networksetup");

            if (networksetupPath != "")
            {
                string[] interfaces = GetInterfaces();
                foreach (string i in interfaces)
                {
                    string i2 = i.Trim();

                    string current = SystemShell.Shell(networksetupPath, new string[] { "-getdnsservers", SystemShell.EscapeInsideQuote(i2) });

                    foreach (string line in current.Split('\n'))
                    {
                        string field = line.Trim();
                        list.Add(field);
                    }
                }
            }

            // Method2 - More info about DHCP DNS
            string scutilPath = LocateExecutable("scutil");

            if (scutilPath != "")
            {
                string scutilOut             = SystemShell.Shell1(scutilPath, "--dns");
                List <List <string> > result = scutilOut.Replace(" ", "").RegExMatchMulti("nameserver\\[[0-9]+\\]:([0-9:\\.]+)");
                foreach (List <string> match in result)
                {
                    foreach (string field in match)
                    {
                        list.Add(field);
                    }
                }
            }

            // Method3 - Compatibility
            try
            {
                if (FileExists("/etc/resolv.conf"))
                {
                    string o = FileContentsReadText("/etc/resolv.conf");
                    foreach (string line in o.Split('\n'))
                    {
                        if (line.Trim().StartsWith("#", StringComparison.InvariantCulture))
                        {
                            continue;
                        }
                        if (line.Trim().StartsWith("nameserver", StringComparison.InvariantCulture))
                        {
                            string field = line.Substring(11).Trim();
                            list.Add(field);
                        }
                    }
                }
            }
            catch
            {
                // Can be unreadable (root 600), ignore
            }

            return(list);
        }
Esempio n. 12
0
        public override void OnJsonNetworkInfo(Json jNetworkInfo)
        {
            // Step1: Set IPv6 support to true by default.
            // From base virtual, always 'false'. Missing Mono implementation?
            // After for interfaces listed by 'networksetup -listallhardwareports' we detect specific support.
            foreach (Json jNetworkInterface in jNetworkInfo["interfaces"].Json.GetArray())
            {
                jNetworkInterface["support_ipv6"].Value = true;
            }

            // Step2: Query 'networksetup -listallhardwareports' to obtain a more accurate device friendly names.
            string networksetupPath = LocateExecutable("networksetup");

            if (networksetupPath != "")
            {
                string nsOutput = SystemShell.Shell1(networksetupPath, "-listallhardwareports");
                string lastName = "";
                foreach (string line in nsOutput.Split('\n'))
                {
                    if (line.StartsWith("Hardware Port: ", StringComparison.InvariantCulture))
                    {
                        lastName = line.Substring(15).Trim();
                    }
                    if (line.StartsWith("Device:", StringComparison.InvariantCulture))
                    {
                        string deviceId = line.Substring(7).Trim();
                        foreach (Json jNetworkInterface in jNetworkInfo["interfaces"].Json.GetArray())
                        {
                            if (jNetworkInterface["id"].Value as string == deviceId)
                            {
                                // Set friendly name
                                jNetworkInterface["friendly"].Value = lastName;

                                // Detect IPv6 support
                                string getInfo = SystemShell.Shell(LocateExecutable("networksetup"), new string[] { "-getinfo", SystemShell.EscapeInsideQuote(lastName) });

                                string mode = getInfo.RegExMatchOne("^IPv6: (.*?)$").Trim();

                                if (mode == "Off")
                                {
                                    jNetworkInterface["support_ipv6"].Value = false;
                                }
                                else
                                {
                                    jNetworkInterface["support_ipv6"].Value = true;
                                }

                                break;
                            }
                        }
                    }
                }
            }
        }
Esempio n. 13
0
        public override void OnReceive(Json data)
        {
            base.OnReceive(data);

            string cmd = data["command"].Value as string;

            if (cmd == "ui.notification")
            {
                if (Eddie.Core.Platform.Instance.CanShellAsNormalUser())
                {
                    string pathNotifySend = Core.Platform.Instance.LocateExecutable("notify-send");
                    if (pathNotifySend != "")
                    {
                        SystemShell s = new SystemShell();
                        s.Path = pathNotifySend;
                        s.Arguments.Add("--urgency=low");
                        s.Arguments.Add("--expire-time=2000");
                        if (data["level"].Value as string == "infoimportant")
                        {
                            s.Arguments.Add("--icon=dialog-information");
                        }
                        else if (data["level"].Value as string == "warning")
                        {
                            s.Arguments.Add("--icon=dialog-warning");
                        }
                        else if (data["level"].Value as string == "error")
                        {
                            s.Arguments.Add("--icon=dialog-error");
                        }
                        else
                        {
                            s.Arguments.Add("--icon=dialog-information");
                        }
                        s.Arguments.Add("\"" + SystemShell.EscapeInsideQuote(Constants.Name) + "\"");
                        string message = SystemShell.EscapeInsideQuote(data["message"].Value as string);
                        message = message.Trim('-');                         // Hack, bad notify-send args parse of quoted string
                        s.Arguments.Add("\"" + message + "\"");
                        s.RunAsNormalUser = true;
                        s.WaitEnd         = false;
                        s.Run();
                    }
                }
            }
            else if (cmd == "ui.color")
            {
                string color = data["color"].Value as string;
                if (Tray != null)
                {
                    if (color == "green")
                    {
                        Tray.SendCommand("tray.active:true");
                        Tray.SendCommand("menu.status.icon:stock:gtk-yes");
                        Tray.SendCommand("menu.connect.text:" + Messages.CommandDisconnect);
                    }
                    else
                    {
                        Tray.SendCommand("tray.active:false");
                        if (color == "yellow")
                        {
                            Tray.SendCommand("menu.status.icon:stock:gtk-media-play");
                            Tray.SendCommand("menu.connect.text:" + Messages.CommandCancel);
                        }
                        else
                        {
                            Tray.SendCommand("menu.status.icon:stock:gtk-no");
                            Tray.SendCommand("menu.connect.text:" + Messages.CommandConnect);
                        }
                    }
                }
            }
            else if (cmd == "ui.status")
            {
                string full = data["full"].Value as string;
                if (Tray != null)
                {
                    Tray.SendCommand("menu.status.text:> " + full);
                }
            }
        }
Esempio n. 14
0
        public override bool OnIPv6Block()
        {
            string[] interfaces = GetInterfaces();
            foreach (string i in interfaces)
            {
                string getInfo = SystemShell.Shell("/usr/sbin/networksetup", new string[] { "-getinfo", SystemShell.EscapeInsideQuote(i) });

                string mode    = UtilsString.RegExMatchOne(getInfo, "^IPv6: (.*?)$");
                string address = UtilsString.RegExMatchOne(getInfo, "^IPv6 IP address: (.*?)$");

                if ((mode == "") && (address != ""))
                {
                    mode = "LinkLocal";
                }

                if (mode != "Off")
                {
                    IpV6ModeEntry entry = new IpV6ModeEntry();
                    entry.Interface = i;
                    entry.Mode      = mode;
                    entry.Address   = address;
                    if (mode == "Manual")
                    {
                        entry.Router       = UtilsString.RegExMatchOne(getInfo, "^IPv6 IP Router: (.*?)$");
                        entry.PrefixLength = UtilsString.RegExMatchOne(getInfo, "^IPv6 Prefix Length: (.*?)$");
                    }
                    m_listIpV6Mode.Add(entry);

                    SystemShell.Shell("/usr/sbin/networksetup", new string[] { "-setv6off", SystemShell.EscapeInsideQuote(i) });

                    Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.OsMacNetworkAdapterIPv6Disabled, i));
                }
            }

            Recovery.Save();

            base.OnIPv6Block();

            return(true);
        }
Esempio n. 15
0
        public byte[] FetchUrlEx(string url, System.Collections.Specialized.NameValueCollection parameters, string title, bool forceBypassProxy, string resolve)
        {
            if (Available() == false)
            {
                throw new Exception(Messages.ToolsCurlRequired);
            }

            if (Utils.CompareVersions(Version, minVersionRequired) == -1)
            {
                throw new Exception(GetRequiredVersionMessage());
            }

            ProgramScope programScope = new ProgramScope(this.GetPath(), "curl");

            // Don't use proxy if connected to the VPN, or in special cases (checking) during connection.
            bool bypassProxy = forceBypassProxy;

            if (bypassProxy == false)
            {
                bypassProxy = Engine.Instance.IsConnected();
            }

            string dataParameters = "";

            if (parameters != null)
            {
                foreach (string k in parameters.Keys)
                {
                    if (dataParameters != "")
                    {
                        dataParameters += "&";
                    }
                    dataParameters += SystemShell.EscapeAlphaNumeric(k) + "=" + Uri.EscapeUriString(parameters[k]);
                }
            }

            string args = "";

            if (bypassProxy == false)
            {
                string proxyMode     = Engine.Instance.Storage.Get("proxy.mode").ToLowerInvariant();
                string proxyHost     = Engine.Instance.Storage.Get("proxy.host");
                int    proxyPort     = Engine.Instance.Storage.GetInt("proxy.port");
                string proxyAuth     = Engine.Instance.Storage.Get("proxy.auth").ToLowerInvariant();
                string proxyLogin    = Engine.Instance.Storage.Get("proxy.login");
                string proxyPassword = Engine.Instance.Storage.Get("proxy.password");

                if (proxyMode == "detect")
                {
                    throw new Exception(Messages.ProxyDetectDeprecated);
                }

                if (proxyMode == "tor")
                {
                    proxyMode     = "socks";
                    proxyAuth     = "none";
                    proxyLogin    = "";
                    proxyPassword = "";
                }

                if (proxyMode == "http")
                {
                    args += " --proxy http://" + SystemShell.EscapeHost(proxyHost) + ":" + proxyPort.ToString();
                }
                else if (proxyMode == "socks")
                {
                    // curl support different types of proxy. OpenVPN not, only socks5. So, it's useless to support other kind of proxy here.
                    args += " --proxy socks5://" + SystemShell.EscapeHost(proxyHost) + ":" + proxyPort.ToString();
                }

                if ((proxyMode != "none") && (proxyAuth != "none"))
                {
                    if (proxyAuth == "basic")
                    {
                        args += " --proxy-basic";
                    }
                    else if (proxyAuth == "ntlm")
                    {
                        args += " --proxy-ntlm";
                    }

                    if (SystemShell.EscapeInsideQuoteAcceptable(proxyLogin) == false)
                    {
                        throw new Exception(MessagesFormatter.Format(Messages.UnacceptableCharacters, "Proxy Login"));
                    }

                    if (SystemShell.EscapeInsideQuoteAcceptable(proxyPassword) == false)
                    {
                        throw new Exception(MessagesFormatter.Format(Messages.UnacceptableCharacters, "Proxy Password"));
                    }

                    if ((proxyLogin != "") && (proxyPassword != ""))
                    {
                        args += " --proxy-user \"" + SystemShell.EscapeInsideQuote(proxyLogin) + "\":\"" + SystemShell.EscapeInsideQuote(proxyPassword) + "\"";
                    }
                }
            }

            args += " \"" + SystemShell.EscapeUrl(url) + "\"";
            args += " -sS"; // -s Silent mode, -S with errors
            args += " --max-time " + Engine.Instance.Storage.GetInt("tools.curl.max-time").ToString();

            Tool cacertTool = Software.GetTool("cacert.pem");

            if (cacertTool.Available())
            {
                args += " --cacert \"" + SystemShell.EscapePath(cacertTool.Path) + "\"";
            }

            if (resolve != "")
            {
                args += " --resolve " + resolve;
            }

            if (dataParameters != "")
            {
                args += " --data \"" + dataParameters + "\"";
            }

            string error = "";

            byte[] output   = default(byte[]);
            int    exitcode = -1;

            try
            {
                /*
                 * if ((Engine.Instance != null) && (Engine.Instance.Storage != null) && (Engine.Instance.Storage.GetBool("log.level.debug")))
                 * {
                 *  string message = "curl " + this.GetPath() + " " + args;
                 *  message = Utils.RegExReplace(message, "[a-zA-Z0-9+/]{30,}=", "{base64-omissis}");
                 *  Engine.Instance.Logs.Log(LogType.Verbose, message);
                 * }
                 */

                Process p = new Process();

                p.StartInfo.FileName         = SystemShell.EscapePath(this.GetPath());
                p.StartInfo.Arguments        = args;
                p.StartInfo.WorkingDirectory = "";

                p.StartInfo.CreateNoWindow         = true;
                p.StartInfo.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden;
                p.StartInfo.UseShellExecute        = false;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError  = true;

                p.Start();

                using (var memoryStream = new System.IO.MemoryStream())
                {
                    //p.StandardOutput.BaseStream.CopyTo(memstream); // .Net 4 only
                    Utils.CopyStream(p.StandardOutput.BaseStream, memoryStream);
                    output = memoryStream.ToArray();
                }

                error = p.StandardError.ReadToEnd();

                p.WaitForExit();

                exitcode = p.ExitCode;
            }
            catch (Exception e)
            {
                error  = e.Message;
                output = default(byte[]);
            }

            programScope.End();

            if (error != "")
            {
                throw new Exception(error.Trim());
            }

            return(output);
        }
Esempio n. 16
0
        public HttpResponse Fetch(HttpRequest request)
        {
            HttpResponse response = new HttpResponse();

            ExceptionIfRequired();

            ProgramScope programScope = new ProgramScope(this.GetPath(), "curl");

            // Don't use proxy if connected to the VPN, or in special cases (checking) during connection.
            bool bypassProxy = request.BypassProxy;

            if (bypassProxy == false)
            {
                bypassProxy = Engine.Instance.IsConnected();
            }

            string dataParameters = "";

            if (request.Parameters.Count > 0)
            {
                foreach (string k in request.Parameters.Keys)
                {
                    if (dataParameters != "")
                    {
                        dataParameters += "&";
                    }
                    dataParameters += SystemShell.EscapeAlphaNumeric(k) + "=" + Uri.EscapeUriString(request.Parameters[k]);
                }
            }

            string args = "";

            if (bypassProxy == false)
            {
                string proxyMode     = Engine.Instance.Storage.GetLower("proxy.mode");
                string proxyWhen     = Engine.Instance.Storage.GetLower("proxy.when");
                string proxyHost     = Engine.Instance.Storage.Get("proxy.host");
                int    proxyPort     = Engine.Instance.Storage.GetInt("proxy.port");
                string proxyAuth     = Engine.Instance.Storage.Get("proxy.auth").ToLowerInvariant();
                string proxyLogin    = Engine.Instance.Storage.Get("proxy.login");
                string proxyPassword = Engine.Instance.Storage.Get("proxy.password");

                if ((proxyWhen == "none") || (proxyWhen == "openvpn"))
                {
                    proxyMode = "none";
                }

                if (proxyMode == "detect")
                {
                    throw new Exception(Messages.ProxyDetectDeprecated);
                }

                if (proxyMode == "tor")
                {
                    proxyMode     = "socks";
                    proxyAuth     = "none";
                    proxyLogin    = "";
                    proxyPassword = "";
                }

                if (proxyMode == "http")
                {
                    args += " --proxy http://" + SystemShell.EscapeHost(proxyHost) + ":" + proxyPort.ToString();
                }
                else if (proxyMode == "socks")
                {
                    // curl support different types of proxy. OpenVPN not, only socks5. So, it's useless to support other kind of proxy here.
                    args += " --proxy socks5://" + SystemShell.EscapeHost(proxyHost) + ":" + proxyPort.ToString();
                }

                if ((proxyMode != "none") && (proxyAuth != "none"))
                {
                    if (proxyAuth == "basic")
                    {
                        args += " --proxy-basic";
                    }
                    else if (proxyAuth == "ntlm")
                    {
                        args += " --proxy-ntlm";
                    }

                    if (SystemShell.EscapeInsideQuoteAcceptable(proxyLogin) == false)
                    {
                        throw new Exception(MessagesFormatter.Format(Messages.UnacceptableCharacters, "Proxy Login"));
                    }

                    if (SystemShell.EscapeInsideQuoteAcceptable(proxyPassword) == false)
                    {
                        throw new Exception(MessagesFormatter.Format(Messages.UnacceptableCharacters, "Proxy Password"));
                    }

                    if ((proxyLogin != "") && (proxyPassword != ""))
                    {
                        args += " --proxy-user \"" + SystemShell.EscapeInsideQuote(proxyLogin) + "\":\"" + SystemShell.EscapeInsideQuote(proxyPassword) + "\"";
                    }
                }
            }

            args += " \"" + SystemShell.EscapeUrl(request.Url) + "\"";
            args += " -sS";             // -s Silent mode, -S with errors
            args += " --max-time " + Engine.Instance.Storage.GetInt("tools.curl.max-time").ToString();

            string pathCacert = Engine.Instance.LocateResource("cacert.pem");

            if (pathCacert != "")
            {
                args += " --cacert \"" + SystemShell.EscapePath(pathCacert) + "\"";
            }

            if (request.ForceResolve != "")
            {
                args += " --resolve " + request.ForceResolve;
            }

            if (dataParameters != "")
            {
                args += " --data \"" + dataParameters + "\"";
            }

            if (request.IpLayer == "4")
            {
                args += " -4";
            }
            if (request.IpLayer == "6")
            {
                args += " -6";
            }

            args += " -i";

            string error = "";

            try
            {
                using (Process p = new Process())
                {
                    p.StartInfo.FileName         = SystemShell.EscapePath(this.GetPath());
                    p.StartInfo.Arguments        = args;
                    p.StartInfo.WorkingDirectory = "";

                    p.StartInfo.CreateNoWindow         = true;
                    p.StartInfo.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden;
                    p.StartInfo.UseShellExecute        = false;
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.RedirectStandardError  = true;

                    p.Start();

                    {
                        using (System.IO.MemoryStream Stream = new System.IO.MemoryStream())
                        {
                            using (System.IO.MemoryStream StreamHeader = new System.IO.MemoryStream())
                            {
                                using (System.IO.MemoryStream StreamBody = new System.IO.MemoryStream())
                                {
                                    byte[] buffer = new byte[4096];
                                    int    read;
                                    while ((read = p.StandardOutput.BaseStream.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        Stream.Write(buffer, 0, read);
                                    }

                                    if (Stream.Length >= 4)
                                    {
                                        byte[] buffer2 = Stream.ToArray();
                                        int    i       = 0;
                                        for (; i < Stream.Length - 4; i++)
                                        {
                                            if ((buffer2[i] == 13) && (buffer2[i + 1] == 10) && (buffer2[i + 2] == 13) && (buffer2[i + 3] == 10))
                                            {
                                                StreamHeader.Write(buffer2, 0, i);
                                                StreamBody.Write(buffer2, i + 4, (int)Stream.Length - i - 4);
                                                break;
                                            }
                                        }

                                        if (StreamHeader.Length == 0)
                                        {
                                            StreamHeader.Write(buffer2, 0, (int)Stream.Length);
                                        }
                                    }
                                    else
                                    {
                                        StreamHeader.Write(Stream.ToArray(), 0, (int)Stream.Length);
                                    }

                                    response.BufferHeader = StreamHeader.ToArray();
                                    response.BufferData   = StreamBody.ToArray();
                                }
                            }

                            string   headers      = System.Text.Encoding.ASCII.GetString(response.BufferHeader);
                            string[] headersLines = headers.Split('\n');
                            for (int l = 0; l < headersLines.Length; l++)
                            {
                                string line = headersLines[l];
                                if (l == 0)
                                {
                                    response.StatusLine = line;
                                }
                                int posSep = line.IndexOf(":");
                                if (posSep != -1)
                                {
                                    string k = line.Substring(0, posSep);
                                    string v = line.Substring(posSep + 1);
                                    response.Headers.Add(new KeyValuePair <string, string>(k.ToLowerInvariant().Trim(), v.Trim()));
                                }
                            }
                        }
                    }

                    error = p.StandardError.ReadToEnd();

                    p.WaitForExit();

                    response.ExitCode = p.ExitCode;
                }
            }
            catch (Exception e)
            {
                error = e.Message;
            }

            programScope.End();

            if (error != "")
            {
                throw new Exception(error.Trim());
            }

            return(response);
        }
Esempio n. 17
0
        public override void OnReceive(Json data)
        {
            string cmd = data["command"].Value as string;

            if (cmd == "engine.shutdown")
            {
                if (Tray != null)
                {
                    Tray.CancelRequested = true;
                    Tray.SendCommand("action.exit");

                    // Tray.Join(); // sometime don't exit...
                    if (Tray.Join(2000) == false)
                    {
                        Tray.Abort();
                    }

                    Tray = null;
                }
            }
            else if (cmd == "engine.ui")
            {
                if (Eddie.Core.Engine.Instance.Storage.GetBool("gui.tray_show"))
                {
                    Tray = new Tray();
                    for (int t = 0; t < 3000; t += 100)
                    {
                        if (Tray.IsStarted())
                        {
                            break;
                        }
                        System.Threading.Thread.Sleep(100);
                    }
                }
            }
            else if (cmd == "ui.notification")
            {
                string pathNotifySend = Core.Platform.Instance.LocateExecutable("notify-send");
                if (pathNotifySend != "")
                {
                    SystemShell s = new SystemShell();
                    s.Path = pathNotifySend;
                    s.Arguments.Add("--urgency=low");
                    //s.Arguments.Add("--expire-time=2000");
                    if (data["level"].Value as string == "infoimportant")
                    {
                        s.Arguments.Add("--icon=dialog-information");
                    }
                    else if (data["level"].Value as string == "warning")
                    {
                        s.Arguments.Add("--icon=dialog-warning");
                    }
                    else if (data["level"].Value as string == "error")
                    {
                        s.Arguments.Add("--icon=dialog-error");
                    }
                    else if (data["level"].Value as string == "fatal")
                    {
                        s.Arguments.Add("--icon=dialog-error");
                    }
                    else
                    {
                        s.Arguments.Add("--icon=dialog-information");
                    }
                    s.Arguments.Add("\"" + SystemShell.EscapeInsideQuote(Constants.Name) + "\"");
                    string message = SystemShell.EscapeInsideQuote(data["message"].Value as string);
                    message = message.Trim('-');                     // Hack, bad notify-send args parse of quoted string
                    s.Arguments.Add("\"" + message + "\"");
                    s.WaitEnd = false;
                    s.Run();
                }
            }
            else if (cmd == "ui.main-status")
            {
                string appIcon       = data["app_icon"].Value as string;
                string appColor      = data["app_color"].Value as string;
                string actionIcon    = data["action_icon"].Value as string;
                string actionCommand = data["action_command"].Value as string;
                string actionText    = data["action_text"].Value as string;
                if (Tray != null)
                {
                    if (appColor == "green")
                    {
                        Tray.SendCommand("tray.active:true");
                    }
                    else
                    {
                        Tray.SendCommand("tray.active:false");
                    }

                    if (appColor == "green")
                    {
                        Tray.SendCommand("menu.status.icon:stock:gtk-yes");
                        Tray.SendCommand("menu.connect.text:" + LanguageManager.GetText("CommandDisconnect"));
                    }
                    else if (appColor == "yellow")
                    {
                        Tray.SendCommand("menu.status.icon:stock:gtk-media-play");
                    }
                    else
                    {
                        Tray.SendCommand("menu.status.icon:stock:gtk-no");
                    }

                    Tray.SendCommand("menu.connect.text:" + actionText);
                    Tray.SendCommand("menu.connect.enable:" + ((actionCommand != "") ? "true":"false"));
                }
            }
            else if (cmd == "ui.status")
            {
                string full = data["full"].Value as string;
                if (Tray != null)
                {
                    Tray.SendCommand("menu.status.text:> " + full);
                }
            }

            base.OnReceive(data);
        }