public List <HostEntry> ReadHostEntries()
        {
            List <HostEntry> hostEntries = new List <HostEntry>();

            using (StreamReader sr = new StreamReader(HostLocation))
            {
                string line;

                while ((line = sr.ReadLine()) != null)
                {
                    // Check if line is relevant
                    line = line.TrimAll();
                    if (string.IsNullOrWhiteSpace(line) || line.StartsWith("#"))
                    {
                        continue;
                    }

                    // Extract the entries
                    string[] lineParts = line.Split(' ');
                    string   other     = lineParts.JoinFrom(2, " ");

                    var hostEntry = new HostEntry(lineParts[0], lineParts[1], other);
                    hostEntries.Add(hostEntry);
                }
            }

            return(hostEntries);
        }
Esempio n. 2
0
        public void Save_AppliesDeletionReorderingDisabling()
        {
            StringResource resource = new StringResource(Resources.ComplexHostsFile_Before);

            HostsFile file = new HostsFile(resource);

            var entry1 = file.Entries.Where(c => c.Hostname == "host1.localhost").First();
            var entry2 = file.Entries.Where(c => c.Hostname == "host2.localhost").First();
            var entry3 = file.Entries.Where(c => c.Hostname == "host3.localhost").First();
            var entry4 = file.Entries.Where(c => c.Hostname == "host4.localhost").First();
            var entry5 = file.Entries.Where(c => c.Hostname == "host5.localhost").First();
            var entry6 = new HostEntry("host6.localhost", "127.0.0.1", "comment 6");

            entry1.Enabled = false;
            entry2.Enabled = true;
            entry3.Enabled = false;

            entry3.SwapLine(entry5); // swap two with a deleted in between
            entry6.SwapLine(entry2); // new swapped with existing

            file.DeleteEntry(entry4);
            file.AddEntry(entry6);

            file.Save();

            string actualOutput = resource.ToString();

            Assert.AreEqual(Resources.ComplexHostsFile_Expected, actualOutput);
        }
Esempio n. 3
0
        // hosts file manipulation methods

        // reloads the hosts file, must be called under lock(_localLock)
        private static void InternalRefresh()
        {
            List <HostEntry> entries = new List <HostEntry>();

            try
            {
                s_activeReader = new StreamReader(new FileStream(s_hostsFilePath, FileMode.Open));

                string line;
                while ((line = s_activeReader.ReadLine()) != null)
                {
                    HostEntry nextEntry = TryParseLine(line);
                    if (nextEntry != null)
                    {
                        entries.Add(nextEntry);
                    }
                }
            }
            finally
            {
                if (s_activeReader != null)
                {
                    s_activeReader.Dispose();
                    s_activeReader = null;
                }
            }

            s_entriesCache = entries;
        }
        public void ToString_IsCorrect()
        {
            var str = "127.0.0.1 google.com";
            var he  = HostEntry.FromString(str);

            Assert.AreEqual(str, he.ToString());
        }
Esempio n. 5
0
        private bool NameMatch(HostEntry entry, string name)
        {
            ValidateNonNull(entry, "entry");
            ValidateName(name);

            return(string.Equals(entry.Name, name, StringComparison.OrdinalIgnoreCase));
        }
Esempio n. 6
0
        protected override void ProcessRecord()
        {
            ValidateAddress(Address);

            var newEntry = new HostEntry(Name, Address, Comment)
            {
                Enabled = Enabled
            };

            if (ShouldProcess(newEntry.ToShortString(), "Add host entry"))
            {
                if (!Force && HostEntryExists(HostsFile.Entries, newEntry.Name))
                {
                    if (!ShouldContinue(String.Format("The host entry '{0}' already exists and the Force paremeter was not specified. If you continue, a duplicate host entry will be created", Name),
                                        "Confirm", ref yesToAll, ref noToAll))
                    {
                        return;
                    }
                }

                HostsFile.AddEntry(newEntry);

                WriteObject(newEntry);
            }
        }
Esempio n. 7
0
 public bool Matches(HostEntry host)
 {
     return
         ((Domain.Length == 0 || host.Name.ToLower().Contains(Domain.ToLower())) &&
          (IPAddress.Length == 0 || host.IP.ToLower().Contains(IPAddress.ToLower())) &&
          (Description.Length == 0 || host.Description.ToLower().Contains(Description.ToLower())));
 }
Esempio n. 8
0
        public void Equals_SameValues_ReturnsTrue()
        {
            HostEntry entryA = new HostEntry(5, null, "    ", false, "hostname", "address", "comment");
            HostEntry entryB = new HostEntry(5, null, "    ", false, "hostname", "address", "comment");

            Assert.IsTrue(entryA.Equals(entryB));
        }
Esempio n. 9
0
        protected override void ProcessRecord()
        {
            ValidateAddress(Address);

            var newEntry = new HostEntry(Name, Address, Comment)
            {
                Enabled = Enabled
            };

            if (ShouldProcess(newEntry.ToShortString(), "Add host entry"))
            {
                if (!Force && HostEntryExists(HostsFile.Entries, newEntry.Name))
                {
                    if (!ShouldContinue(String.Format("The host entry '{0}' already exists and the Force paremeter was not specified. If you continue, a duplicate host entry will be created", Name),
                        "Confirm", ref yesToAll, ref noToAll))
                    {
                        return;
                    }
                }

                HostsFile.AddEntry(newEntry);

                WriteObject(newEntry);
            }
        }
        private void AddTask()
        {
            string defaultAddress = addresses[0];

            using (var form = new EditHostEntryForm(view.ServiceProvider, addresses))
            {
                form.Text = Resources.AddHostEntryDialogTitle;

                HostEntry selectedEntry = view.SelectedEntries.Select(c => c.HostEntry).FirstOrDefault();

                form.EditableFields = HostEntryField.All;
                form.HostEntry      = new HostEntry("", defaultAddress, null);

                DialogResult result = view.ShowDialog(form);

                if (result == DialogResult.OK)
                {
                    this.module.ServiceProxy.AddEntries(new List <HostEntry>()
                    {
                        form.HostEntry
                    });
                    this.UpdateData();
                }
            }
        }
Esempio n. 11
0
        public PropertyBag EditEntries(PropertyBag bag)
        {
            return(CatchCommonExceptions(() =>
            {
                EditEntriesRequest request = new EditEntriesRequest(bag);

                HostsFile hostsFile = GetHostsFile();

                IEnumerable <HostEntry> hostEntries = hostsFile.Entries;

                for (int i = 0; i < request.ChangedEntries.Count; i++)
                {
                    HostEntry originalEntry = request.OriginalEntries[i];
                    HostEntry changedEntry = request.ChangedEntries[i];

                    HostEntry hostEntry = FindHostEntry(originalEntry, hostEntries);

                    hostEntry.Address = changedEntry.Address;
                    hostEntry.Hostname = changedEntry.Hostname;
                    hostEntry.Comment = changedEntry.Comment;
                    hostEntry.Enabled = changedEntry.Enabled;
                }

                hostsFile.Save();

                return new EditEntriesResponse().ToPropertyBag();
            }));
        }
        public void failure_should_double_retry()
        {
            var he = new HostEntry("a")
            {
                RetryDelayMax     = TimeSpan.FromSeconds(300),
                RetryDelayInitial = TimeSpan.FromSeconds(30)
            };

            he.MarkFailed();
            he.Dead.Should().BeTrue();
            he.RetryCount.Should().Be(0);

            he.NextRetry.Should().BeCloseTo(DateTime.Now.AddSeconds(30), precision: 3000);

            he.RetryFailed();

            he.RetryCount.Should().Be(1);
            he.NextRetry.Should().BeCloseTo(DateTime.Now.AddSeconds(30 * 2), precision: 3000);

            he.RetryFailed();

            he.RetryCount.Should().Be(2);
            he.NextRetry.Should().BeCloseTo(DateTime.Now.AddSeconds(30 * 2 * 2), precision: 3000);

            //run it past the maximum
            Enumerable.Range(1, 30 * 12)
            .ForEach(i => he.RetryFailed());

            he.RetryFailed();

            he.NextRetry.Should().BeCloseTo(DateTime.Now + he.RetryDelayMax, precision: 1000);
        }
Esempio n. 13
0
        public void IsDirty_AnyProprtyChanged_ReturnsTrue(string propertyName, object newValue)
        {
            HostEntry entry = new HostEntry(5, "original-line", " ", false, "hostname", "address", "comment");

            entry.GetType().GetProperty(propertyName).SetValue(entry, newValue, null);

            Assert.IsTrue(entry.IsDirty);
        }
        public void Parsing_NoUrl_IsSuccessful()
        {
            var he = HostEntry.FromString("nothing  google.com	");

            Assert.IsTrue(he.HasValue);
            Assert.AreEqual(null, he.Value.Ip);
            Assert.AreEqual("google.com", he.Value.Url);
        }
        public void Parsing_CorrectHostEntry_IsSuccessful()
        {
            var he = HostEntry.FromString("127.0.0.1  google.com	");

            Assert.IsTrue(he.HasValue);
            Assert.AreEqual(IPAddress.Parse("127.0.0.1"), he.Value.Ip);
            Assert.AreEqual("google.com", he.Value.Url);
        }
Esempio n. 16
0
 public HostLine(HostLineKind kind, HostEntry? entry_ = null, string comment_ = null, HostLineError? error_ = null, string line_ = null)
 {
     Kind = kind;
     Entry_ = entry_;
     Comment_ = comment_;
     Error_ = error_;
     Line = line_ ?? mkLine(Entry_, Comment_);
 }
Esempio n. 17
0
        public void ToString_IsNotDirty_HasOriginalString_ReturnsOriginalString()
        {
            HostEntry entry = new HostEntry(5, "original-line", " ", false, "hostname", "address", "comment");

            string actualValue = entry.ToString();

            Assert.AreEqual("original-line", actualValue);
        }
 internal static void ContructAddMessage(this HostEntry hostEntry, IMessageBuilder builder)
 {
     builder
     .WriteLine("Added Host Entry")
     .IncreaseIndent()
     .WriteLine("Host Name: {0}", hostEntry.HostName)
     .WriteLine("IP: {0}", hostEntry.IpAddress);
 }
 private HostEntry GetEnabledAlternateHostEntry(HostEntry entry)
 {
     return(hostEntryModels
            .Where(x => x.HostEntry.Enabled &&
                   x.HostEntry.Hostname == entry.Hostname)
            .Select(x => x.HostEntry)
            .FirstOrDefault() ?? entry);
 }
Esempio n. 20
0
        public void Equals_DifferentProperty_ReturnsFalse(string propertyName, object newValue)
        {
            HostEntry entryA = new HostEntry(5, null, "    ", false, "hostname", "address", "comment");
            HostEntry entryB = new HostEntry(5, null, "    ", false, "hostname", "address", "comment");

            entryB.GetType().GetProperty(propertyName).SetValue(entryB, newValue, null);

            Assert.IsFalse(entryA.Equals(entryB));
        }
Esempio n. 21
0
 private IEnumerable <string> GetAlternateAddresses(HostEntry entry)
 {
     return(entryModels
            .Where(x => x.HostEntry.Hostname == entry.Hostname &&
                   !x.HostEntry.Enabled)
            .Select(x => x.HostEntry.Address)
            .Distinct()
            .ToList());
 }
Esempio n. 22
0
        public void ToString_IsNotDirty_DoesNotHaveOriginalString_FormatsValues()
        {
            HostEntry entry = new HostEntry(5, null, "    ", false, "hostname", "address", "comment");

            string expectedValue = "# address    hostname # comment";
            string actualValue   = entry.ToString();

            Assert.AreEqual(expectedValue, actualValue);
        }
Esempio n. 23
0
        public void AddEntry_HostnameIsIgnored_ThrowsArgumentError()
        {
            StringResource resource = new StringResource();

            HostsFile file = new HostsFile(resource);

            HostEntry entry = new HostEntry("localhost", "1.0.0.0", null);

            file.AddEntry(entry);
        }
Esempio n. 24
0
        public void DeleteEntry_DoesNotExist_DoesNotThrowException()
        {
            StringResource resource = new StringResource();

            HostsFile file = new HostsFile(resource);

            HostEntry entry = new HostEntry("host.localhost", "1.0.0.0", null);

            file.DeleteEntry(entry);
        }
Esempio n. 25
0
        public void IsDirty_LineSwapped_SwapsNewStatus()
        {
            HostEntry entryA = new HostEntry(-1, "original-line", " ", false, "hostname", "address", "comment");
            HostEntry entryB = new HostEntry(10, "original-line", " ", false, "hostname", "address", "comment");

            entryA.SwapLine(entryB);

            Assert.IsFalse(entryA.IsNew);
            Assert.IsTrue(entryB.IsNew);
        }
Esempio n. 26
0
        public void IsDirty_LineSwapped_ReturnsTrue()
        {
            HostEntry entryA = new HostEntry(5, "original-line", " ", false, "hostname", "address", "comment");
            HostEntry entryB = new HostEntry(10, "original-line", " ", false, "hostname", "address", "comment");

            entryA.SwapLine(entryB);

            Assert.IsTrue(entryA.IsDirty);
            Assert.IsTrue(entryB.IsDirty);
        }
Esempio n. 27
0
        public void InternalConstructor_AssignsProperties()
        {
            HostEntry entry = new HostEntry(5, "original-line", " ", false, "hostname", "address", "comment");

            Assert.AreEqual("hostname", entry.Hostname);
            Assert.AreEqual("address", entry.Address);
            Assert.AreEqual("comment", entry.Comment);
            Assert.AreEqual(5, entry.Line);
            Assert.AreEqual(false, entry.Enabled);
        }
Esempio n. 28
0
        public void IsDirty_LineSwapped_SwapsLineNumbers()
        {
            HostEntry entryA = new HostEntry(5, "original-line", " ", false, "hostname", "address", "comment");
            HostEntry entryB = new HostEntry(10, "original-line", " ", false, "hostname", "address", "comment");

            entryA.SwapLine(entryB);

            Assert.AreEqual(10, entryA.Line);
            Assert.AreEqual(5, entryB.Line);
        }
Esempio n. 29
0
        public void IsDirty_ValuesNotChanged_ReturnsFalse()
        {
            HostEntry entry = new HostEntry(5, "original-line", " ", false, "hostname", "address", "comment");

            entry.Enabled  = false;
            entry.Hostname = "hostname";
            entry.Address  = "address";
            entry.Comment  = "comment";

            Assert.IsFalse(entry.IsDirty);
        }
Esempio n. 30
0
        public void ToString_IsDirty_FormatsValues()
        {
            HostEntry entry = new HostEntry(5, "original-line", "    ", false, "hostname", "address", "comment");

            entry.Hostname = "hostname2";

            string expectedValue = "# address    hostname2 # comment";
            string actualValue   = entry.ToString();

            Assert.AreEqual(expectedValue, actualValue);
        }
Esempio n. 31
0
        public void Constructor_AssignsProperties()
        {
            string s = typeof(HostEntryFixture).Assembly.FullName;

            HostEntry entry = new HostEntry("hostname", "address", "comment");

            Assert.AreEqual("hostname", entry.Hostname);
            Assert.AreEqual("address", entry.Address);
            Assert.AreEqual("comment", entry.Comment);
            Assert.AreEqual(-1, entry.Line);
            Assert.AreEqual(true, entry.Enabled);
        }
Esempio n. 32
0
        private void tResolveDNSEntry(string entry)
        {
            var resolvedEntry = new HostEntry()
            {
                HostName  = "Host Not Found",
                IPAddress = entry
            };
            BackgroundWorker worker = new BackgroundWorker()
            {
                WorkerReportsProgress = true
            };

            worker.DoWork += (sender, e) =>
            {
                try
                {
                    var dnsEntry = Dns.GetHostEntry(entry);
                    uDebugLogAdd("Attempted DNS entry lookup");
                    if (dnsEntry != null)
                    {
                        uDebugLogAdd("DNS entry wasn't null");
                        if (!string.IsNullOrWhiteSpace(dnsEntry.HostName))
                        {
                            resolvedEntry.HostName  = dnsEntry.HostName;
                            resolvedEntry.IPAddress = dnsEntry.AddressList[0].ToString();
                            uDebugLogAdd($"DNS entry hostname isn't empty, resolved to: {resolvedEntry.HostName}");
                        }
                    }
                    worker.ReportProgress(1);
                    resolvedEntries++;
                }
                catch (SocketException se)
                {
                    uDebugLogAdd($"DNS lookup error: {se.Message}");
                    resolvedEntry.HostName = se.Message;
                    worker.ReportProgress(1);
                    resolvedEntries++;
                }
                catch (Exception ex)
                {
                    LogException(ex);
                }
            };
            worker.ProgressChanged += (sender2, e2) =>
            {
                if (e2.ProgressPercentage == 1)
                {
                    uDebugLogAdd($"Worker progress is {e2.ProgressPercentage}, adding ResolvedEntry | IP({resolvedEntry.IPAddress}) | HN({resolvedEntry.HostName})");
                    lbNetNSLookup.Items.Add(resolvedEntry);
                }
            };
            worker.RunWorkerAsync();
        }
        public HostEntryControl(HostEntry hostEntry)
            : this()
        {
            if (hostEntry == null)
                throw new ArgumentNullException(nameof(hostEntry));

            //this.Description = hostEntry.Description;
            //this.IPAddress = hostEntry.IPAddress;
            //this.Active = hostEntry.Enabled;
            //this.Destination = hostEntry.Destination;
            this.SelectedItem = hostEntry;
        }
Esempio n. 34
0
        public void AddEntry(HostEntry entry)
        {
            if (entry == null)
            {
                throw new ArgumentNullException("entry");
            }

            if (HostEntry.IsIgnoredHostname(entry.Name))
            {
                throw new ArgumentException("The following hostnames cannot be configured: " + String.Join(", ", HostEntry.IgnoredHostnames));
            }

            if (!entries.Contains(entry))
            {
                entries.Add(entry);
            }
        }
Esempio n. 35
0
        static string mkLine(HostEntry? entry_, string comment_)
        {
            var sb = new StringBuilder();
            if (entry_ != null)
            {
                sb.Append(entry_.Value.IP);
                sb.Append(' ');
                sb.Append(entry_.Value.Host);
            }

            if (comment_ != null)
                sb.Append(comment_);

            return sb.ToString();
        }
Esempio n. 36
0
 internal static extern unsafe int GetNextIPAddress(HostEntry* entry, void** addressListHandle, IPAddress* endPoint);
Esempio n. 37
0
 internal static unsafe extern int GetHostEntriesForName(string address, HostEntry** entry);
Esempio n. 38
0
 internal static extern unsafe int GetHostByName(string address, HostEntry* entry);
Esempio n. 39
0
 internal static extern unsafe void FreeHostEntry(HostEntry* entry);
Esempio n. 40
0
        public void DeleteEntry(HostEntry entry)
        {
            if (entry == null)
            {
                throw new ArgumentNullException("entry");
            }

            if (entries.Contains(entry))
            {
                if (!(entry.IsNew || deletedLines.Contains(entry.Line)))
                {
                    deletedLines.Add(entry.Line);
                }

                entries.Remove(entry);
            }
        }
Esempio n. 41
0
 public static HostLine FromEntry(HostEntry entry, string comment_ = null)
 {
     return new HostLine(HostLineKind.HostEntry, entry_: entry, comment_: comment_);
 }
Esempio n. 42
0
 internal static unsafe extern void FreeHostEntriesForName(HostEntry* entry);
Esempio n. 43
0
 internal static extern unsafe int GetHostByAddress(IPAddress* address, HostEntry* entry);