Ejemplo n.º 1
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 = UtilsString.RegExMatchMulti(scutilOut.Replace(" ", ""), "nameserver\\[[0-9]+\\]:([0-9:\\.]+)");
                foreach (List <string> match in result)
                {
                    foreach (string field in match)
                    {
                        list.Add(field);
                    }
                }
            }

            // Method3 - Compatibility
            if (FileExists("/etc/resolv.conf"))
            {
                string o = FileContentsReadText("/etc/resolv.conf");
                foreach (string line in o.Split('\n'))
                {
                    if (line.Trim().StartsWith("#"))
                    {
                        continue;
                    }
                    if (line.Trim().StartsWith("nameserver"))
                    {
                        string field = line.Substring(11).Trim();
                        list.Add(field);
                    }
                }
            }

            return(list);
        }
Ejemplo n.º 2
0
        public UsuariosSectores(UsuariosSectores usec, List <Sroles> RolesAEditar)
        {
            this.id        = usec.id;
            this.idSector  = usec.idSector;
            this.idUsuario = usec.idUsuario;
            UtilsString Auxiliar = new UtilsString();

            this.roles = Auxiliar.TraducirRolesAString(RolesAEditar);
        }
Ejemplo n.º 3
0
        public void VerificarVM()
        {
            string           rolSeleccionado = "ROLE_USUARIOS_ADMINISTRADOR";
            UtilsString      Utils           = new UtilsString();
            UsSecRepository  UsSec           = new UsSecRepository();
            UsuariosSectores UsuarioSec      = UsSec.BuscarUsuarioSector(2011);
            ViewModel        vm = new ViewModel(UsuarioSec, rolSeleccionado);

            Assert.IsNotNull(vm);
        }
Ejemplo n.º 4
0
        public ViewMuestra(UsuariosSectores usec, List <Roles> RolesTotales)
        {
            this.id            = usec.id;
            this.nombreSector  = usec.nombreSector;
            this.nombreUsuario = usec.nombreUsuario;
            UtilsString   Auxiliar     = new UtilsString();
            List <string> lista_string = Auxiliar.ConvertirDeListaDeRolesAListaNombreRoles(RolesTotales);

            this.nombreRoles = Auxiliar.ParsearPropiedadRoles(usec, lista_string);
        }
Ejemplo n.º 5
0
 public ActionResult EditarUsuarioSector(List <ViewModel> lista_VMUsSec, string rolElegido)
 {
     if (rolElegido != null)
     {
         UtilsString utils = new UtilsString();
         utils.ModificarDatosRolSegunChequeos(lista_VMUsSec, rolElegido);
         return(RedirectToAction("Index", "UsuariosSectores"));
     }
     return(RedirectToAction("ObtenerRoles", "Rol"));
 }
Ejemplo n.º 6
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 = UtilsString.RegExMatchOne(getInfo, "^IPv6: (.*?)$").Trim();

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

                                break;
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 7
0
        public ViewModel(UsuariosSectores usec, string rolSeleccionado)
        {
            UtilsString Utils = new UtilsString();

            this.Id        = usec.id;
            this.nombreSec = usec.nombreSector;
            this.nombreUsu = usec.nombreUsuario;
            this.dni       = usec.dni;
            this.roles     = usec.roles;
            this.Chked     = Utils.VerificarRolEnUsuarioSector(usec, rolSeleccionado);
        }
        public void GetShortestWordsTest()
        {
            var text = "ББ ВВВ ГГГГ, А ДДДД  ДД. Е ЖЖ ЗЗЗ";
            var word = UtilsString.GetShortestWord(text);

            Assert.That(word, Is.EqualTo("А"));

            text = "";
            word = UtilsString.GetShortestWord(text);
            Assert.That(word, Is.EqualTo(""));
        }
        public void GetLongestWordsTest()
        {
            var text        = "ББ ВВВ ГГГГ, А ДДДД  ДД. Е  ЛЛЛЛ ЖЖ ЗЗЗ";
            var expectedArr = new[] { "ГГГГ", "ДДДД", "ЛЛЛЛ" };
            var wordsArr    = UtilsString.GetLongestWords(text);

            Assert.That(wordsArr, Is.EqualTo(expectedArr));

            text     = "";
            wordsArr = UtilsString.GetLongestWords(text);
            Assert.That(wordsArr, Is.Empty);
        }
Ejemplo n.º 10
0
        public override void OnNormalizeVersion()
        {
            if (Version == "")
            {
                return;
            }

            string ver  = UtilsString.ExtractBetween(Version, "OpenVPN ", " ");
            string libs = UtilsString.ExtractBetween(Version, "library versions:", "\n").Trim();

            Version = ver + " - " + libs;
        }
Ejemplo n.º 11
0
        public void ParsearPropiedadRolesNulo()
        {
            UtilsString      Utils        = new UtilsString();
            UsSecRepository  UsSec        = new UsSecRepository();
            UsuariosSectores UsuarioSec   = UsSec.BuscarUsuarioSector(2011);
            List <Roles>     Lista_Roles  = UsSec.ListarTodosRoles();
            List <string>    Lista_string = Utils.ConvertirDeListaDeRolesAListaNombreRoles(Lista_Roles);
            List <Sroles>    Lista_SRoles = new List <Sroles>();

            Lista_SRoles = Utils.ParsearPropiedadRoles(UsuarioSec, Lista_string);
            //string StringResultante = Utils.TraducirRolesAString(Lista_SRoles);
            Assert.IsNotNull(Lista_SRoles);
        }
Ejemplo n.º 12
0
        public ActionResult ObtenerRoles()
        {
            UtilsString   utils           = new UtilsString();
            List <Roles>  listadoDeRoles  = UsSecRepo.ListarTodosRoles();
            List <Sroles> listadoDeSRoles = new List <Sroles>();

            foreach (Roles rol in listadoDeRoles)
            {
                Sroles rolSel = new Sroles(rol, false);
                listadoDeSRoles.Add(rolSel);
            }

            return(View(listadoDeSRoles));
        }
Ejemplo n.º 13
0
    // Export pages text file for proofreading
    public static void CreatePagesTextFile(string fileName, string[] keys)
    {
        // header
        string       exportFileName = "JsonKeys/" + fileName + " " + Localizer.LanguageCode + ".txt";
        StreamWriter streamWriter   = File.CreateText(exportFileName);

        streamWriter.WriteLine(fileName);
        streamWriter.WriteLine("");

        // body
        int page = 1;

        foreach (string key in keys)
        {
            string export = Localizer.Value(key);
            export = UtilsString.CorrectForQuotes(export);
            export = UtilsString.CorrectForTabs(export);
            export = UtilsString.CorrectBreaks(export);                 // correct for <br> tags
            export = UtilsString.RemoveMarkup(export, "b");             // remove <b> bold
            export = UtilsString.RemoveMarkup(export, "i");             // remove <i> italic
            export = UtilsString.RemoveMarkup(export, "color");         // remove <color> tags
            export = UtilsString.RemoveMarkup(export, "line-height");   // remove line change tags
            export = UtilsString.RemoveMarkup(export, "align");         // remove font related tags
            export = UtilsString.RemoveMarkup(export, "font");
            export = UtilsString.RemoveMarkup(export, "size");
            export = UtilsString.RemoveMarkup(export, "voffset");


            // check for single quote
            if (UtilsString.CheckForQuote(export, false))
            {
                Logger.Warning("Found \' in key:" + key);
            }

            // streamWriter.WriteLine("Page " + page++);
            streamWriter.WriteLine(export);
            streamWriter.WriteLine("");
        }

        // footer
        streamWriter.WriteLine("");
        streamWriter.WriteLine("Chess Origins");
        streamWriter.WriteLine("© Copyright 2022");
        streamWriter.WriteLine("Lowke Media Pty Ltd");
        streamWriter.WriteLine("All Rights Reserved");
        streamWriter.Close();

        Logger.Print(">>> Exported file:" + exportFileName);
    }
Ejemplo n.º 14
0
        public void VerificarVMGuardarDatos()
        {
            string                  rolSeleccionado = "ROLE_USUARIOS_ADMINISTRADOR";
            List <ViewModel>        lista           = new List <ViewModel>();
            UtilsString             Utils           = new UtilsString();
            UsSecRepository         UsSec           = new UsSecRepository();
            UsuariosSectores        UsuarioSec      = UsSec.BuscarUsuarioSector(2011);
            ViewModel               vm  = new ViewModel(UsuarioSec, rolSeleccionado);
            List <UsuariosSectores> aux = UsSec.ListarTodosUsuariosSectores("39", "juan", null);

            foreach (var item in aux)
            {
                ViewModel vModel = new ViewModel(item, rolSeleccionado);
                lista.Add(vModel);
            }
            Utils.ModificarDatosRolSegunChequeos(lista, rolSeleccionado);
            Assert.IsNull(lista);
        }
Ejemplo n.º 15
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);
        }
Ejemplo n.º 16
0
        public override IpAddresses ResolveDNS(string host)
        {
            // Base method with Dns.GetHostEntry have cache issue, for example on Fedora. OS X it's based on Mono.
            // Also, base methods with Dns.GetHostEntry sometime don't fetch AAAA IPv6 addresses.

            IpAddresses result = new IpAddresses();

            string hostPath = LocateExecutable("host");

            if (hostPath != "")
            {
                // Note: CNAME record are automatically followed.
                SystemShell s = new SystemShell();
                s.Path = "/usr/bin/host";
                s.Arguments.Add("-W 5");
                s.Arguments.Add(SystemShell.EscapeHost(host));
                s.NoDebugLog = true;
                if (s.Run())
                {
                    string hostout = s.Output;
                    foreach (string line in hostout.Split('\n'))
                    {
                        string ipv4 = UtilsString.RegExMatchOne(line, "^.*? has address (.*?)$");
                        if (ipv4 != "")
                        {
                            result.Add(ipv4.Trim());
                        }

                        string ipv6 = UtilsString.RegExMatchOne(line, "^.*? has IPv6 address (.*?)$");
                        if (ipv6 != "")
                        {
                            result.Add(ipv6.Trim());
                        }
                    }
                }
            }

            return(result);
        }
        public void GroupTextByCharsTest()
        {
            var text         = "ПППОООГГГООООДДДААА";
            var expectedText = "ПОГОДА";
            var actualText   = UtilsString.GroupTextByChars(text);

            Assert.That(expectedText, Is.EqualTo(actualText));

            text         = "Ххххоооорррооошшшиий деееннннь";
            expectedText = "хороший день";
            actualText   = UtilsString.GroupTextByChars(text);
            Assert.That(expectedText, Is.EqualTo(actualText));

            text         = "     ";
            expectedText = " ";
            actualText   = UtilsString.GroupTextByChars(text);
            Assert.That(expectedText, Is.EqualTo(actualText));

            text         = "";
            expectedText = "";
            actualText   = UtilsString.GroupTextByChars(text);
            Assert.That(expectedText, Is.EqualTo(actualText));
        }
Ejemplo n.º 18
0
 public override void OnNormalizeVersion()
 {
     Version = UtilsString.RegExMatchOne(Version, "^curl\\s(.*?)\\s");
 }
Ejemplo n.º 19
0
 public string ValToDesc(Int64 v)
 {
     return(UtilsString.FormatBytes(v, true, true));
 }
 public void RestorePolicy()
 {
     SystemShell.ShellCmd("netsh advfirewall set " + UtilsString.StringSafe(id) + " firewallpolicy " + Inbound + "," + Outbound);
 }
Ejemplo n.º 21
0
        protected void LogIn(object sender, EventArgs e)
        {
            if (IsValid)
            {
                // Validate the user password
                var manager       = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
                var signinManager = Context.GetOwinContext().GetUserManager <ApplicationSignInManager>();
                var result        = signinManager.PasswordSignIn(textUsername.Value, textPassword.Value, false, shouldLockout: false);

                switch (result)
                {
                case SignInStatus.Success:

                    var finduserid = manager.FindByName(textUsername.Value).Id;

                    var isadmin = manager.IsInRole(finduserid, "Admin");

                    var currentUser = manager.FindById(finduserid);

                    int currentSupplierID = currentUser.supplierId;


                    currentUser.WebStatus = "Logged In";

                    manager.Update(currentUser);

                    //set the supplier as live
                    BL.SetSupplierWebstatus(currentSupplierID, 2);

                    if (isadmin)
                    {
                        Response.Redirect("~/pages/admin/supplieredit.aspx");
                    }
                    else
                    {
                        // check for first login
                        var empty = UtilsString.IsEmpty(currentUser.firstLogin.Trim().ToUpper());

                        if (!empty)
                        {
                            if (currentUser.firstLogin.Trim().ToUpper() == "Y")
                            {
                                Response.Redirect("~/account/managepassword.aspx");
                            }
                            else
                            {
                                Response.Redirect("~/pages/userland.aspx");
                            }
                        }
                    }


                    break;

                case SignInStatus.LockedOut:
                    Response.Redirect("/Account/Lockout");
                    break;

                case SignInStatus.Failure:
                default:
                    dvMessage.InnerText = "Invalid Username and/or Password";
                    dvMessage.Visible   = true;
                    break;
                }
            }
        }
 public void StateOff()
 {
     SystemShell.ShellCmd("netsh advfirewall set " + UtilsString.StringSafe(id) + " state off");
 }
 public void NotifyOff()
 {
     //Registry.SetValue(GetNotificationRegPath(), "DisableNotifications", 1, RegistryValueKind.DWord);
     //Platform.Instance.ShellCmd("netsh firewall set notifications mode=disable profile=" + GetOldFirewallProfileName());
     SystemShell.ShellCmd("netsh advfirewall set " + UtilsString.StringSafe(id) + " settings inboundusernotification disable");
 }
Ejemplo n.º 24
0
        public override void DrawRect(CGRect dirtyRect)
        {
            var context = NSGraphicsContext.CurrentContext.GraphicsPort;

            // Engine.Instance.Stats.Charts.Hit (RandomGenerator.GetInt (1024, 1024 * 1024), RandomGenerator.GetInt (1024, 1024 * 1024)); // Debugging

            context.SetFillColor(m_colorBackground);
            context.FillRect(dirtyRect);

            NSColor.Gray.Set();
            NSBezierPath.StrokeRect(Bounds);


            nfloat DX = this.Bounds.Size.Width;
            nfloat DY = this.Bounds.Size.Height;

            m_chartDX     = DX;
            m_chartDY     = DY - m_legendDY;
            m_chartStartX = 0;
            m_chartStartY = m_chartDY;


            float maxY = m_chart.GetMax();

            if (maxY <= 0)
            {
                maxY = 4096;
            }
            else if (maxY > 1000000000000)
            {
                maxY = 1000000000000;
            }

            CGPoint lastPointDown = new CGPoint(-1, -1);
            CGPoint lastPointUp   = new CGPoint(-1, -1);

            nfloat stepX = (m_chartDX - 0) / m_chart.Resolution;

            // Grid lines
            for (int g = 0; g < m_chart.Grid; g++)
            {
                nfloat x = ((m_chartDX - 0) / m_chart.Grid) * g;
                DrawLine(context, m_colorGrid, m_chartStartX + x, 0, m_chartStartX + x, m_chartStartY);
            }

            // Axis line
            DrawLine(context, m_colorAxis, 0, m_chartStartY, m_chartDX, m_chartStartY);

            // Legend

            /*
             * {
             *      string legend = "";
             *      legend += Messages.ChartRange + ": " + Utils.FormatSeconds(m_chart.Resolution * m_chart.TimeStep);
             *      legend += "   ";
             *      legend += Messages.ChartGrid + ": " + Utils.FormatSeconds(m_chart.Resolution / m_chart.Grid * m_chart.TimeStep);
             *      legend += "   ";
             *      legend += Messages.ChartStep + ": " + Utils.FormatSeconds(m_chart.TimeStep);
             *
             *      Point mp = Cursor.Position;
             *      mp = PointToClient(mp);
             *      if ((mp.X > 0) && (mp.Y < chartDX) && (mp.Y > chartDY) && (mp.Y < DY))
             *              legend += " - " + Messages.ChartClickToChangeResolution;
             *
             *      e.Graphics.DrawString(legend, FontLabel, BrushLegendText, ChartRectangle(0, chartStartY, chartDX, m_legendDY), formatTopCenter);
             * }
             */


            // Graph
            for (int i = 0; i < m_chart.Resolution; i++)
            {
                int p = i + m_chart.Pos + 1;
                if (p >= m_chart.Resolution)
                {
                    p -= m_chart.Resolution;
                }

                nfloat downY = ((m_chart.Download[p]) * (m_chartDY - m_marginTopY)) / maxY;
                nfloat upY   = ((m_chart.Upload[p]) * (m_chartDY - m_marginTopY)) / maxY;

                CGPoint pointDown = ChartPoint(m_chartStartX + stepX * i, m_chartStartY - downY);
                CGPoint pointUp   = ChartPoint(m_chartStartX + stepX * i, m_chartStartY - upY);

                //e.Graphics.DrawLine(Pens.Green, new Point(0,0), point);

                if (lastPointDown.X != -1)
                {
                    DrawLine(context, m_colorDownloadGraph, lastPointDown, pointDown);
                    DrawLine(context, m_colorUploadGraph, lastPointUp, pointUp);
                }

                lastPointDown = pointDown;
                lastPointUp   = pointUp;
            }

            // Download line
            nfloat downCurY = 0;
            {
                long v = m_chart.GetLastDownload();
                downCurY = ((v) * (m_chartDY - m_marginTopY)) / maxY;
                DrawLine(context, m_colorDownloadLine, 0, m_chartStartY - downCurY, m_chartDX, m_chartStartY - downCurY);
                DrawStringOutline(context, Messages.ChartDownload + ": " + ValToDesc(v), m_colorDownloadText, ChartRectangle(0, 0, m_chartDX - 10, m_chartStartY - downCurY), 8);
            }

            // Upload line
            {
                long   v   = m_chart.GetLastUpload();
                nfloat y   = ((v) * (m_chartDY - m_marginTopY)) / maxY;
                nfloat dly = 0;
                if (Math.Abs(downCurY - y) < 10)
                {
                    dly = 15;                                              // Download and upload overwrap, distance it.
                }
                DrawLine(context, m_colorUploadLine, 0, m_chartStartY - y, m_chartDX, m_chartStartY - y);
                DrawStringOutline(context, Messages.ChartUpload + ": " + ValToDesc(v), m_colorUploadText, ChartRectangle(0, 0, m_chartDX - 10, m_chartStartY - y - dly), 8);
            }

            // Mouse lines
            {
                CGPoint mp = Window.MouseLocationOutsideOfEventStream;
                mp.X -= this.Frame.Left;
                mp.Y -= this.Frame.Top;
                //mp = ParentWindow.ConvertPointToView (mp, this);

                mp = Invert(mp);

                //mp = Window.ConvertScreenToBase (mp);

                if ((mp.X > 0) && (mp.Y < m_chartDX) && (mp.Y > 0) && (mp.Y < m_chartDY))
                {
                    DrawLine(context, m_colorMouse, 0, mp.Y, m_chartDX, mp.Y);
                    DrawLine(context, m_colorMouse, mp.X, 0, mp.X, m_chartDY);

                    nfloat i = (m_chartDX - (mp.X - m_chartStartX)) / stepX;

                    int t = Conversions.ToInt32(i * m_chart.TimeStep);

                    //float y = mp.Y * maxY / (chartDY - m_marginTopY);
                    nfloat y = (m_chartStartY - (mp.Y - m_marginTopY)) * maxY / m_chartDY;

                    String label = ValToDesc(Conversions.ToInt64(y)) + ", " + UtilsString.FormatSeconds(t) + " ago";

                    int formatAlign = 6;

                    CGRect rect = new CGRect();
                    if (DX - mp.X > DX / 2)
                    //if (mp.X < DX - 200)
                    {
                        if (DY - mp.Y > DY / 2)
                        //if (mp.Y < 20)
                        {
                            formatAlign = 0;
                            rect.X      = mp.X + 5;
                            rect.Y      = mp.Y + 5;
                            rect.Width  = DX;
                            rect.Height = DX;
                        }
                        else
                        {
                            formatAlign = 6;
                            rect.X      = mp.X + 5;
                            rect.Y      = 0;
                            rect.Width  = DX;
                            rect.Height = mp.Y - 5;
                        }
                    }
                    else
                    {
                        if (DY - mp.Y > DY / 2)
                        //if (mp.Y < 40)
                        {
                            formatAlign = 2;
                            rect.X      = 0;
                            rect.Y      = mp.Y;
                            rect.Width  = mp.X - 5;
                            rect.Height = DY;
                        }
                        else
                        {
                            formatAlign = 8;
                            rect.X      = 0;
                            rect.Y      = 0;
                            rect.Width  = mp.X - 5;
                            rect.Height = mp.Y - 5;
                        }
                    }

                    DrawStringOutline(context, label, m_colorMouse, rect, formatAlign);
                }
            }
        }
Ejemplo n.º 25
0
        // This is the only method about exchange data between this software and AirVPN infrastructure.
        // We don't use SSL. Useless layer in our case, and we need to fetch hostname and direct IP that don't permit common-name match.

        // 'S' is the AES 256 bit one-time session key, crypted with a RSA 4096 public-key.
        // 'D' is the data from the client to our server, crypted with the AES.
        // The server answer is XML decrypted with the same AES session.
        public static XmlDocument FetchUrl(string authPublicKey, string url, Dictionary <string, string> parameters)
        {
            // AES
            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.KeySize = 256;
                rijAlg.GenerateKey();
                rijAlg.GenerateIV();

                // Generate S

                // Bug workaround: Xamarin 6.1.2 macOS throw an 'Default constructor not found for type System.Diagnostics.FilterElement' error.
                // in 'new System.Xml.Serialization.XmlSerializer', so i avoid that.

                /*
                 * StringReader sr = new System.IO.StringReader(authPublicKey);
                 * System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
                 * RSAParameters publicKey = (RSAParameters)xs.Deserialize(sr);
                 */
                RSAParameters publicKey        = new RSAParameters();
                XmlDocument   docAuthPublicKey = new XmlDocument();
                docAuthPublicKey.LoadXml(authPublicKey);
                publicKey.Modulus  = Convert.FromBase64String(docAuthPublicKey.DocumentElement["Modulus"].InnerText);
                publicKey.Exponent = Convert.FromBase64String(docAuthPublicKey.DocumentElement["Exponent"].InnerText);

                Dictionary <string, byte[]> assocParamS = new Dictionary <string, byte[]>();
                assocParamS["key"] = rijAlg.Key;
                assocParamS["iv"]  = rijAlg.IV;

                byte[] bytesParamS = null;
                using (RSACryptoServiceProvider csp = new RSACryptoServiceProvider())
                {
                    csp.ImportParameters(publicKey);
                    bytesParamS = csp.Encrypt(UtilsCore.AssocToUtf8Bytes(assocParamS), false);
                }

                // Generate D

                byte[] aesDataIn   = UtilsCore.AssocToUtf8Bytes(parameters);
                byte[] bytesParamD = null;

                {
                    MemoryStream aesCryptStream  = null;
                    CryptoStream aesCryptStream2 = null;

                    try
                    {
                        aesCryptStream = new MemoryStream();
                        using (ICryptoTransform aesEncryptor = rijAlg.CreateEncryptor())
                        {
                            aesCryptStream2 = new CryptoStream(aesCryptStream, aesEncryptor, CryptoStreamMode.Write);
                            aesCryptStream2.Write(aesDataIn, 0, aesDataIn.Length);
                            aesCryptStream2.FlushFinalBlock();

                            bytesParamD = aesCryptStream.ToArray();
                        }
                    }
                    finally
                    {
                        if (aesCryptStream2 != null)
                        {
                            aesCryptStream2.Dispose();
                        }
                        else if (aesCryptStream != null)
                        {
                            aesCryptStream.Dispose();
                        }
                    }
                }

                // HTTP Fetch
                HttpRequest request = new HttpRequest();
                request.Url             = url;
                request.Parameters["s"] = UtilsString.Base64Encode(bytesParamS);
                request.Parameters["d"] = UtilsString.Base64Encode(bytesParamD);

                HttpResponse response = Engine.Instance.FetchUrl(request);

                try
                {
                    byte[] fetchResponse      = response.BufferData;
                    byte[] fetchResponsePlain = null;

                    MemoryStream aesDecryptStream  = null;
                    CryptoStream aesDecryptStream2 = null;

                    // Decrypt answer

                    try
                    {
                        aesDecryptStream = new MemoryStream();
                        using (ICryptoTransform aesDecryptor = rijAlg.CreateDecryptor())
                        {
                            aesDecryptStream2 = new CryptoStream(aesDecryptStream, aesDecryptor, CryptoStreamMode.Write);
                            aesDecryptStream2.Write(fetchResponse, 0, fetchResponse.Length);
                            aesDecryptStream2.FlushFinalBlock();

                            fetchResponsePlain = aesDecryptStream.ToArray();
                        }
                    }
                    finally
                    {
                        if (aesDecryptStream2 != null)
                        {
                            aesDecryptStream2.Dispose();
                        }
                        else if (aesDecryptStream != null)
                        {
                            aesDecryptStream.Dispose();
                        }
                    }

                    string finalData = System.Text.Encoding.UTF8.GetString(fetchResponsePlain);

                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(finalData);
                    return(doc);
                }
                catch (Exception ex)
                {
                    string message = "";
                    if (response.GetHeader("location") != "")
                    {
                        message = MessagesFormatter.Format(Messages.ManifestFailedUnexpected302, response.GetHeader("location"));
                    }
                    else
                    {
                        message = ex.Message + " - " + response.GetLineReport();
                    }
                    throw new Exception(message);
                }
            }
        }
Ejemplo n.º 26
0
    // Export localization string file with all variables removed from the key
    private static void CreateKeysFile(string fileName, string[] keys, bool variablesInKeys = false)
    {
        // header
        string       exportFileName = "JsonKeys/" + fileName + " " + Localizer.LanguageCode + ".json";
        StreamWriter streamWriter   = File.CreateText(exportFileName);

        streamWriter.WriteLine("{");
        streamWriter.WriteLine("    \"keys\": [");
        bool isFirst = true;

        // body
        foreach (string key in keys)
        {
            LocalizerValue value = Localizer.LocalizerValue(key);
            if (value == null)
            {
                continue;
            }

            if (!isFirst)
            {
                streamWriter.WriteLine("        },");
            }
            isFirst = false;

            string justKey = Localizer.JustKey(key);
            streamWriter.WriteLine("        {");
            streamWriter.WriteLine("            \"key\": \"" + justKey + "\",");
            if (!string.IsNullOrEmpty(value.context))
            {
                streamWriter.WriteLine("            \"context\": \"" + value.context + "\",");
            }
            if (!string.IsNullOrEmpty(value.citation))
            {
                streamWriter.WriteLine("            \"citation\": \"" + value.citation + "\",");
            }
            if (!string.IsNullOrEmpty(value.note))
            {
                streamWriter.WriteLine("            \"note\": \"" + value.note + "\",");
            }
            string[] variables = variablesInKeys ? null : value.Variables;
            string   export    = Localizer.Value(key, variables);
            if (string.IsNullOrEmpty(export))
            {
                Logger.Warning("key:" + key + " is empty value.");
            }
            export = UtilsString.CorrectForQuotes(export);
            export = UtilsString.CorrectForTabs(export);

            // check for single quote
            if (UtilsString.CheckForQuote(export, false))
            {
                Logger.Warning("Found \' in key:" + key);
            }

            streamWriter.WriteLine("            \"original\": \"" + export + "\",");
            streamWriter.WriteLine("            \"value\": \"" + export + "\"");
        }

        // footer
        streamWriter.WriteLine("        }");
        streamWriter.WriteLine("    ]");
        streamWriter.WriteLine("}");
        streamWriter.Close();

        Logger.Print(">>> Exported file:" + exportFileName);
    }
Ejemplo n.º 27
0
        public override void OnJsonRouteList(Json jRoutesList)
        {
            base.OnJsonRouteList(jRoutesList);

            string netstatPath = LocateExecutable("netstat");

            if (netstatPath != "")
            {
                string result = SystemShell.Shell1(netstatPath, "-rnl");

                string[] lines = result.Split('\n');
                foreach (string line in lines)
                {
                    if (line == "Routing tables")
                    {
                        continue;
                    }
                    if (line == "Internet:")
                    {
                        continue;
                    }
                    if (line == "Internet6:")
                    {
                        continue;
                    }

                    string[] fields = UtilsString.StringCleanSpace(line).Split(' ');

                    if ((fields.Length > 0) && (fields[0].ToLowerInvariant().Trim() == "destination"))
                    {
                        continue;
                    }

                    if (fields.Length >= 7)
                    {
                        Json      jRoute  = new Json();
                        IpAddress address = new IpAddress();
                        if (fields[0].ToLowerInvariant().Trim() == "default")
                        {
                            IpAddress gateway = new IpAddress(fields[1]);
                            if (gateway.Valid == false)
                            {
                                continue;
                            }
                            if (gateway.IsV4)
                            {
                                address = IpAddress.DefaultIPv4;
                            }
                            else if (gateway.IsV6)
                            {
                                address = IpAddress.DefaultIPv6;
                            }
                        }
                        else
                        {
                            address.Parse(fields[0]);
                        }
                        if (address.Valid == false)
                        {
                            continue;
                        }
                        jRoute["address"].Value   = address.ToCIDR();
                        jRoute["gateway"].Value   = fields[1];
                        jRoute["flags"].Value     = fields[2];
                        jRoute["refs"].Value      = fields[3];
                        jRoute["use"].Value       = fields[4];
                        jRoute["mtu"].Value       = fields[5];
                        jRoute["interface"].Value = fields[6];
                        if (fields.Length > 7)
                        {
                            jRoute["expire"].Value = fields[7];
                        }
                        jRoutesList.Append(jRoute);
                    }
                }
            }
        }
Ejemplo n.º 28
0
        protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        {
            //base.OnPaint(e);
            Form.Skin.GraphicsCommon(e.Graphics);

            try
            {
                int DX = this.ClientRectangle.Width;
                int DY = this.ClientRectangle.Height;

                //e.Graphics.FillRectangle(BrushBackground, this.ClientRectangle);
                Form.DrawImage(e.Graphics, GuiUtils.GetResourceImage("tab_l_bg"), new Rectangle(0, 0, ClientSize.Width, ClientSize.Height));

                m_chartDX     = this.ClientRectangle.Width;
                m_chartDY     = this.ClientRectangle.Height - m_legendDY;
                m_chartStartX = 0;
                m_chartStartY = m_chartDY;


                float maxY = m_chart.GetMax();
                if (maxY <= 0)
                {
                    maxY = 4096;
                }
                else if (maxY > 1000000000000)
                {
                    maxY = 1000000000000;
                }

                Point lastPointDown = new Point(-1, -1);
                Point lastPointUp   = new Point(-1, -1);

                float stepX = (m_chartDX - 0) / m_chart.Resolution;

                // Grid lines
                for (int g = 0; g < m_chart.Grid; g++)
                {
                    float x = ((m_chartDX - 0) / m_chart.Grid) * g;
                    e.Graphics.DrawLine(m_penGrid, m_chartStartX + x, 0, m_chartStartX + x, m_chartStartY);
                }

                // Axis line
                e.Graphics.DrawLine(Pens.Gray, 0, m_chartStartY, m_chartDX, m_chartStartY);

                // Legend

                /*
                 * {
                 *      string legend = "";
                 *      legend += Messages.ChartRange + ": " + Utils.FormatSeconds(m_chart.Resolution * m_chart.TimeStep);
                 *      legend += "   ";
                 *      legend += Messages.ChartGrid + ": " + Utils.FormatSeconds(m_chart.Resolution / m_chart.Grid * m_chart.TimeStep);
                 *      legend += "   ";
                 *      legend += Messages.ChartStep + ": " + Utils.FormatSeconds(m_chart.TimeStep);
                 *
                 *      Point mp = Cursor.Position;
                 *      mp = PointToClient(mp);
                 *      if ((mp.X > 0) && (mp.Y < chartDX) && (mp.Y > chartDY) && (mp.Y < DY))
                 *              legend += " - " + Messages.ChartClickToChangeResolution;
                 *
                 *      e.Graphics.DrawString(legend, FontLabel, BrushLegendText, ChartRectangle(0, chartStartY, chartDX, m_legendDY), formatTopCenter);
                 * }
                 */

                // Graph
                for (int i = 0; i < m_chart.Resolution; i++)
                {
                    int p = i + m_chart.Pos + 1;
                    if (p >= m_chart.Resolution)
                    {
                        p -= m_chart.Resolution;
                    }

                    float downY = ((m_chart.Download[p]) * (m_chartDY - m_marginTopY)) / maxY;
                    float upY   = ((m_chart.Upload[p]) * (m_chartDY - m_marginTopY)) / maxY;

                    Point pointDown = ChartPoint(m_chartStartX + stepX * i, m_chartStartY - downY);
                    Point pointUp   = ChartPoint(m_chartStartX + stepX * i, m_chartStartY - upY);

                    //e.Graphics.DrawLine(Pens.Green, new Point(0,0), point);

                    if (lastPointDown.X != -1)
                    {
                        e.Graphics.DrawLine(m_penDownloadGraph, lastPointDown, pointDown);
                        e.Graphics.DrawLine(m_penUploadGraph, lastPointUp, pointUp);
                    }

                    lastPointDown = pointDown;
                    lastPointUp   = pointUp;
                }

                // Download line
                float downCurY = 0;
                {
                    long v = m_chart.GetLastDownload();
                    downCurY = ((v) * (m_chartDY - m_marginTopY)) / maxY;
                    e.Graphics.DrawLine(m_penDownloadLine, 0, m_chartStartY - downCurY, m_chartDX, m_chartStartY - downCurY);
                    Form.DrawStringOutline(e.Graphics, Messages.ChartDownload + ": " + ValToDesc(v), FontLabel, m_brushDownloadText, ChartRectangle(0, 0, m_chartDX, m_chartStartY - downCurY), formatBottomRight);
                }

                // Upload line
                {
                    long  v   = m_chart.GetLastUpload();
                    float y   = ((v) * (m_chartDY - m_marginTopY)) / maxY;
                    float dly = 0;
                    if (Math.Abs(downCurY - y) < 10)
                    {
                        dly = 15;                                                  // Download and upload overwrap, distance it.
                    }
                    e.Graphics.DrawLine(m_penUploadLine, 0, m_chartStartY - y, m_chartDX, m_chartStartY - y);
                    Form.DrawStringOutline(e.Graphics, Messages.ChartUpload + ": " + ValToDesc(v), FontLabel, m_brushUploadText, ChartRectangle(0, 0, m_chartDX, m_chartStartY - y - dly), formatBottomRight);
                }

                // Mouse lines
                {
                    Point mp = Cursor.Position;
                    mp = PointToClient(mp);

                    if ((mp.X > 0) && (mp.Y < m_chartDX) && (mp.Y > 0) && (mp.Y < m_chartDY))
                    {
                        e.Graphics.DrawLine(m_penMouse, 0, mp.Y, m_chartDX, mp.Y);
                        e.Graphics.DrawLine(m_penMouse, mp.X, 0, mp.X, m_chartDY);

                        float i = (m_chartDX - (mp.X - m_chartStartX)) / stepX;

                        int t = Conversions.ToInt32(i * m_chart.TimeStep);

                        //float y = mp.Y * maxY / (chartDY - m_marginTopY);
                        float y = (m_chartStartY - (mp.Y - m_marginTopY)) * maxY / m_chartDY;

                        String label = ValToDesc(Conversions.ToInt64(y)) + ", " + UtilsString.FormatSeconds(t) + " ago";

                        StringFormat formatAlign = formatBottomLeft;
                        Rectangle    rect        = new Rectangle();
                        //if(DX - mp.X > DX / 2)
                        if (mp.X < DX - 150)
                        {
                            //if (DY - mp.Y > DY / 2)
                            if (mp.Y < 20)
                            {
                                formatAlign = formatTopLeft;
                                rect.X      = mp.X + 20;
                                rect.Y      = mp.Y + 5;
                                rect.Width  = DX;
                                rect.Height = DX;
                            }
                            else
                            {
                                formatAlign = formatBottomLeft;
                                rect.X      = mp.X + 20;
                                rect.Y      = 0;
                                rect.Width  = DX;
                                rect.Height = mp.Y - 5;
                            }
                        }
                        else
                        {
                            //if (DY - mp.Y > DY / 2)
                            if (mp.Y < 20)
                            {
                                formatAlign = formatTopRight;
                                rect.X      = 0;
                                rect.Y      = mp.Y;
                                rect.Width  = mp.X - 20;
                                rect.Height = DY;
                            }
                            else
                            {
                                formatAlign = formatBottomRight;
                                rect.X      = 0;
                                rect.Y      = 0;
                                rect.Width  = mp.X - 20;
                                rect.Height = mp.Y - 5;
                            }
                        }

                        Form.DrawStringOutline(e.Graphics, label, FontLabel, m_brushMouse, rect, formatAlign);
                    }
                }
            }
            catch
            {
            }
        }
Ejemplo n.º 29
0
        public string ValToDesc(Int64 v)
        {
            string r = UtilsString.FormatBytes(v, true, true);

            return(r);
        }
Ejemplo n.º 30
0
        public void RefreshUi(Engine.RefreshUiMode mode)
        {
            try
            {
                if ((mode == Engine.RefreshUiMode.MainMessage) || (mode == Engine.RefreshUiMode.Full))
                {
                    if (Engine.CurrentServer != null)
                    {
                        ImgTopFlag.Image = NSImage.ImageNamed("flag_" + Engine.CurrentServer.CountryCode.ToLowerInvariant() + ".png");
                    }
                    else
                    {
                        ImgTopFlag.Image = NSImage.ImageNamed("notconnected.png");
                    }

                    LblWaiting1.StringValue = Engine.WaitMessage;

                    if (Engine.IsWaiting())
                    {
                        ImgProgress.StartAnimation(this);
                        ImgTopPanel.Image        = NSImage.ImageNamed("topbar_osx_yellow.png");
                        MnuTrayStatus.Image      = NSImage.ImageNamed("status_yellow_16.png");
                        LblTopStatus.StringValue = Engine.WaitMessage;

                        TabOverview.SelectAt(1);

                        CmdCancel.Hidden       = (Engine.IsWaitingCancelAllowed() == false);
                        CmdCancel.Enabled      = (Engine.IsWaitingCancelPending() == false);
                        MnuTrayConnect.Enabled = CmdCancel.Enabled;
                    }
                    else if (Engine.IsConnected())
                    {
                        ImgProgress.StopAnimation(this);
                        ImgTopPanel.Image        = NSImage.ImageNamed("topbar_osx_green.png");
                        MnuTrayStatus.Image      = NSImage.ImageNamed("status_green_16.png");
                        LblTopStatus.StringValue = MessagesFormatter.Format(MessagesUi.TopBarConnected, Engine.CurrentServer.DisplayName);

                        TabOverview.SelectAt(2);

                        LblConnectedServerName.StringValue = Engine.CurrentServer.DisplayName;
                        LblConnectedLocation.StringValue   = Engine.CurrentServer.GetLocationForList();
                        TxtConnectedExitIp.StringValue     = Engine.ConnectionActive.ExitIPs.ToString();
                        ImgConnectedCountry.Image          = NSImage.ImageNamed("flag_" + Engine.CurrentServer.CountryCode.ToLowerInvariant() + ".png");
                    }
                    else
                    {
                        ImgProgress.StopAnimation(this);
                        ImgTopPanel.Image   = NSImage.ImageNamed("topbar_osx_red.png");
                        MnuTrayStatus.Image = NSImage.ImageNamed("status_red_16.png");
                        if (Engine.Instance.NetworkLockManager.IsActive())
                        {
                            LblTopStatus.StringValue = MessagesUi.TopBarNotConnectedLocked;
                        }
                        else
                        {
                            LblTopStatus.StringValue = MessagesUi.TopBarNotConnectedExposed;
                        }

                        TabOverview.SelectAt(0);
                    }

                    EnabledUI();
                }

                if ((mode == Engine.RefreshUiMode.Log) || (mode == Engine.RefreshUiMode.Full))
                {
                    lock (Engine.LogsPending)
                    {
                        while (Engine.LogsPending.Count > 0)
                        {
                            LogEntry l = Engine.LogsPending[0];
                            Engine.LogsPending.RemoveAt(0);

                            Log(l);
                        }
                    }
                    LblWaiting2.StringValue = Engine.Logs.GetLogDetailTitle();
                }

                if ((mode == Engine.RefreshUiMode.Stats) || (mode == Engine.RefreshUiMode.Full))
                {
                    if (Engine.IsConnected())
                    {
                        TxtConnectedSince.StringValue = Engine.Stats.GetValue("VpnStart");

                        TxtConnectedDownload.StringValue = UtilsString.FormatBytes(Engine.ConnectionActive.BytesLastDownloadStep, true, false);
                        TxtConnectedUpload.StringValue   = UtilsString.FormatBytes(Engine.ConnectionActive.BytesLastUploadStep, true, false);
                    }
                }

                if ((mode == Engine.RefreshUiMode.Full))
                {
                    if (TableServersController != null)
                    {
                        TableServersController.RefreshUI();
                    }
                    if (TableAreasController != null)
                    {
                        TableAreasController.RefreshUI();
                    }
                }
            }
            catch (Exception)
            {
                // TOFIX: macOS sometime throw an useless exception in closing phase
            }
        }